CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
refactor: 基于共享 app-server 重构活动采集与历史同步
Bob1443582ce8a2
diff --git a/AGENTS.md b/AGENTS.mdindex 1758141..ba7af3d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -107,17 +107,17 @@ CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用,使用 Swift 6,### 启动与并发边界-- Hook 事件模式必须先于 UI 和长期服务初始化,处理完成后立即退出,失败不能阻断 Codex-- Hook 处理必须限制读取量和执行时间,并发写入必须加锁+- 共享 app-server 采集由独立 actor 拥有连接和解析状态,不在主 actor 执行阻塞 I/O+- 采集消息和读取时间必须有界,共享数据写入必须加锁- 普通模式由 App 的统一入口装配长期服务- 工程默认采用 `MainActor` 隔离,共享可变状态放入 actor,跨 actor 值类型按需声明 `nonisolated`,禁止在主 actor 执行阻塞 I/O- 类型命名使用 `UpperCamelCase`,成员命名使用 `lowerCamelCase`### 数据链路与权限边界-- 保持 app-server 额度与用量、Hook 历史聚合、实时任务三条数据链路独立-- 账户主链路、Hook 启用与校验必须分别检查当前 app-server 的实际版本是否满足各自最低要求-- 修改 Hook 配置时必须保留用户和其他应用已有的 handler+- 保持 app-server 额度与用量、活动历史聚合、实时任务三条数据链路独立+- 账户主链路、活动连接启用与校验必须分别检查当前 app-server 的实际版本是否满足各自最低要求+- 活动连接只订阅已加载线程,不创建用户轮次、不回答审批、不修改 Codex 配置或管理共享 daemon 生命周期- helper 只能执行固定的睡眠控制和自动重置唤醒计划,不得增加网络、任意命令执行或额外文件访问- 新增网络访问、日志数据或 CloudKit 字段前先核对隐私边界- 开启自动重置或防睡眠前必须取得用户确认,打开 helper 授权系统设置必须由用户显式操作触发@@ -128,8 +128,8 @@ CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用,使用 Swift 6,- helper 只接受有限时间戳,维护单一的系统唤醒计划;目标变化、功能关闭、App 退出、对应连接断开或 helper 启动时必须收敛并清理计划- 修改唤醒事件的归属或类型时,必须考虑旧版本遗留事件的清理兼容性- 异常会话保护跟随防睡眠开关,只判定非匿名运行中任务,等待批准任务不参与判定-- Hook 初始化、系统睡眠、唤醒恢复或数据源不可用期间暂停异常会话判定,数据恢复后执行无通知对账-- 主动排空 Hook 读取是屏障,每个调用方必须等待一轮在本次请求之后开始的读取;唤醒后只有该轮读取成功,才能执行生命周期对账并恢复保护判定+- 活动连接初始化、系统睡眠、唤醒恢复或数据源不可用期间暂停异常会话判定,数据恢复后执行无通知对账+- 主动排空活动读取是屏障,每个调用方必须等待一轮在本次请求之后开始的读取;唤醒后只有该轮读取成功,才能执行生命周期对账并恢复保护判定- reader 更换时丢弃旧结果,数据源不可用或任务取消时不得使用旧快照继续判定### 数据语义与兼容性@@ -137,13 +137,13 @@ CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用,使用 Swift 6,- 缺少会话标识的任务按匿名任务处理,保留在实时快照和 UI 中,不发布任务通知或触觉反馈,不参与防睡眠和异常会话保护,不生成持久化保护标识- 异常会话保护记录只保存哈希任务标识和必要时间戳,保留时间必须有界;Debug 与 Release 共用的数据必须跨进程加锁,修改存储格式或身份计算属于兼容性问题- 聚合算法、输出字段、字段含义或去重规则变化,需要重新计算历史数据时,必须递增聚合 schema,从保留期内的原始事件完整重建,不新增字段级历史迁移-- Hook 计数字段缺失表示历史来源不可用,不能解释为明确的零值+- 活动计数字段缺失表示历史来源不可用,不能解释为明确的零值## 测试规范`CodexBarTests` 使用 Swift Testing,无 App 宿主,直接编译 `CodexBar/` 与 `Shared/` 源码。测试 target 独有的 `CODEXBAR_TESTING` 条件只移除 `@main`,不启动 App、Codex、CloudKit 或 helper。文件测试使用独立临时目录,偏好测试使用独立 `UserDefaults` suite,禁止读写真实用户数据。仓库没有覆盖率门槛。-每次代码改动至少应完成构建和单元测试,运行 `swiftformat` 和 `swiftlint` 两项检查,并手动验证受影响流程。菜单、窗口焦点、Hook、同步、通知和防睡眠改动必须说明手动验证场景。Debug 与 Release 使用不同 App 和 helper bundle ID,排查时不要混用。+每次代码改动至少应完成构建和单元测试,运行 `swiftformat` 和 `swiftlint` 两项检查,并手动验证受影响流程。菜单、窗口焦点、活动采集、同步、通知和防睡眠改动必须说明手动验证场景。Debug 与 Release 使用不同 App 和 helper bundle ID,排查时不要混用。## Git 规范@@ -174,4 +174,4 @@ Tag 名 `v{MARKETING_VERSION}` 里的版本号从 `Config/Version.xcconfig` 读- 处理窗口、菜单、快捷键、App 激活或事件监听时,特别注意 `LSUIElement` 应用特有的焦点行为- 不做辅助功能(Accessibility)适配,不新增辅助功能标签、特征或操作- 注释保持克制,只解释非显然的生命周期、焦点、actor 或系统 API 约束;现有注释多为解释为什么的类型,沿用同样风格-- 改动涉及菜单面板、窗口焦点、Hook、同步、通知、自动重置唤醒或防睡眠时,构建通过之外还要说明应手动覆盖的交互场景;helper 相关改动额外要验证 App 包内 helper 与 plist 位置、签名、首次系统授权、运行/等待切换、唤醒计划替换与清理和异常退出后的恢复+- 改动涉及菜单面板、窗口焦点、活动采集、同步、通知、自动重置唤醒或防睡眠时,构建通过之外还要说明应手动覆盖的交互场景;helper 相关改动额外要验证 App 包内 helper 与 plist 位置、签名、首次系统授权、运行/等待切换、唤醒计划替换与清理和异常退出后的恢复diff --git a/CodexBar/App/CodexBarApp.swift b/CodexBar/App/CodexBarApp.swiftindex 4240e38..78ee43b 100644--- a/CodexBar/App/CodexBarApp.swift+++ b/CodexBar/App/CodexBarApp.swift@@ -6,15 +6,11 @@ import SwiftUI#if !CODEXBAR_TESTING@main#endif-/// 应用入口; Hook 子进程模式会在初始化阶段记录事件并退出+/// 应用入口struct CodexBarApp: App {@NSApplicationDelegateAdaptor(CodexBarAppDelegate.self) private var appDelegateinit() {- if WorkflowHookEventRecorder.handleIfRequested() {- exit(EXIT_SUCCESS)- }-// 缩短系统工具提示首次出现的延迟 (毫秒)UserDefaults.standard.set(500, forKey: "NSInitialToolTipDelay")}diff --git a/CodexBar/Controllers/ActivityCenterPanelController.swift b/CodexBar/Controllers/ActivityPanelController.swiftsimilarity index 89%rename from CodexBar/Controllers/ActivityCenterPanelController.swiftrename to CodexBar/Controllers/ActivityPanelController.swiftindex d83884d..dad8e7c 100644--- a/CodexBar/Controllers/ActivityCenterPanelController.swift+++ b/CodexBar/Controllers/ActivityPanelController.swift@@ -4,17 +4,17 @@ import SwiftUI/// 点击活动卡片后展开的并发任务中心, 复用菜单侧边抽屉定位和动画@MainActor-final class ActivityCenterPanelController {- private let activityMonitor: CodexActivityMonitor- private let presentationState: CodexActivityCenterPresentationState+final class ActivityPanelController {+ private let activityMonitor: ActivityMonitor+ private let presentationState: ActivityCenterPresentationStateprivate let mainPanelSettings: MainPanelSettings- private let contentHost = SidePanelContentHost<CodexActivityCenterView>(- initialSize: CodexActivityCenterView.initialPanelSize,+ private let contentHost = SidePanelContentHost<ActivityCenterView>(+ initialSize: ActivityCenterView.initialPanelSize,ignoresMouseEvents: false,sizingOptions: [],- cornerRadius: CodexActivityCenterView.panelCornerRadius+ cornerRadius: ActivityCenterView.panelCornerRadius)- private var currentContext: CodexActivityCenterPanelContext?+ private var currentContext: ActivityCenterPanelContext?private weak var menuSurfaceWindow: NSWindow?private weak var menuContentView: NSView?private var cancellables = Set<AnyCancellable>()@@ -28,8 +28,8 @@ final class ActivityCenterPanelController {)init(- activityMonitor: CodexActivityMonitor,- presentationState: CodexActivityCenterPresentationState,+ activityMonitor: ActivityMonitor,+ presentationState: ActivityCenterPresentationState,mainPanelSettings: MainPanelSettings) {self.activityMonitor = activityMonitor@@ -56,7 +56,7 @@ final class ActivityCenterPanelController {}func toggle(- context: CodexActivityCenterPanelContext,+ context: ActivityCenterPanelContext,relativeTo menuSurfaceWindow: NSWindow?,contentView: NSView?) {@@ -85,7 +85,7 @@ final class ActivityCenterPanelController {}private func schedulePresentation(- context: CodexActivityCenterPanelContext,+ context: ActivityCenterPanelContext,relativeTo menuSurfaceWindow: NSWindow?,contentView: NSView?) {@@ -121,7 +121,7 @@ final class ActivityCenterPanelController {}private func show(- context: CodexActivityCenterPanelContext,+ context: ActivityCenterPanelContext,relativeTo menuSurfaceWindow: NSWindow?,contentView: NSView?) {@@ -155,10 +155,10 @@ final class ActivityCenterPanelController {}private func panelLayout(- context: CodexActivityCenterPanelContext,+ context: ActivityCenterPanelContext,menuSurfaceWindow: NSWindow,contentView: NSView?,- snapshot: CodexActivitySnapshot,+ snapshot: ActivitySnapshot,allowsCachedAnchor: Bool = true) -> (size: CGSize, position: SidePanelPosition) {let menuSurfaceFrame = SidePanelSupport.contentScreenFrame(@@ -178,7 +178,7 @@ final class ActivityCenterPanelController {let menuMaximumHeight = alignmentScreenFrame.map {$0.maxY - menuSurfaceFrame.minY} ?? screenMaximumHeight- let panelSize = CodexActivityCenterView.panelSize(+ let panelSize = ActivityCenterView.panelSize(maximumHeight: min(screenMaximumHeight, menuMaximumHeight),snapshot: snapshot)@@ -194,7 +194,7 @@ final class ActivityCenterPanelController {return (panelSize, position)}- private func updateVisibleLayout(for snapshot: CodexActivitySnapshot) {+ private func updateVisibleLayout(for snapshot: ActivitySnapshot) {guard let panel = contentHost.panel,panel.isVisible,let currentContext,@@ -251,7 +251,7 @@ final class ActivityCenterPanelController {private func updateContent(panelSize: CGSize) {contentHost.updateContent(- CodexActivityCenterView(+ ActivityCenterView(activityMonitor: activityMonitor,presentationState: presentationState,mainPanelSettings: mainPanelSettingsdiff --git a/CodexBar/Controllers/CodexBarAppDelegate.swift b/CodexBar/Controllers/CodexBarAppDelegate.swiftindex 71fc99a..6451bfb 100644--- a/CodexBar/Controllers/CodexBarAppDelegate.swift+++ b/CodexBar/Controllers/CodexBarAppDelegate.swift@@ -5,23 +5,19 @@ import os@MainActorfinal class CodexBarAppDelegate: NSObject, NSApplicationDelegate {private let codexStatusService = CodexStatusService()- lazy var proxySettings = CodexProxySettings(service: codexStatusService)lazy var viewModel = CodexStatusViewModel(service: codexStatusService)- let workflowViewModel = WorkflowViewModel()- lazy var advancedModeSettings = AdvancedModeSettings(codexStatusService: codexStatusService)- lazy var codexCLINotificationSettings = CodexCLINotificationSettings(+ let historyViewModel = HistoryViewModel()+ lazy var tuiNotificationSettings = TUINotificationSettings(codexStatusService: codexStatusService)- let activityProtectionSettings = ActivityProtectionSettings()- lazy var activityMonitor = CodexActivityMonitor(- advancedModeSettings: advancedModeSettings,- activityProtectionSettings: activityProtectionSettings+ let protectionSettings = ProtectionSettings()+ lazy var activityMonitor = ActivityMonitor(+ protectionSettings: protectionSettings)lazy var keepAliveController = KeepAliveController(- activityMonitor: activityMonitor,- advancedModeSettings: advancedModeSettings+ activityMonitor: activityMonitor)- let syncSettings = WorkflowSyncSettings()+ let syncSettings = SyncSettings()let globalHotKeySettings = GlobalHotKeySettings()let menuBarQuotaSettings = MenuBarQuotaSettings()let mainPanelSettings = MainPanelSettings()@@ -32,7 +28,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {private var statusItemController: StatusItemController?private var taskGlowController: TaskGlowController?- private var notificationService: CodexNotificationService?+ private var notificationService: NotificationService?private var autoResetController: AutoResetController?private var terminationPreparationTask: Task<Void, Never>?private var hasPreparedForTermination = false@@ -40,13 +36,11 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {// MARK: - App 生命周期func applicationDidFinishLaunching(_: Notification) {- // Hook 子进程模式绝不会走到这里, 干净退出标志因此不会被它改写AppProcessDiagnostics.install()let controller = StatusItemController(viewModel: viewModel,- workflowViewModel: workflowViewModel,- advancedModeSettings: advancedModeSettings,- codexCLINotificationSettings: codexCLINotificationSettings,+ historyViewModel: historyViewModel,+ tuiNotificationSettings: tuiNotificationSettings,activityMonitor: activityMonitor,syncSettings: syncSettings,globalHotKeySettings: globalHotKeySettings,@@ -56,13 +50,12 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {notificationSettings: notificationSettings,autoResetSettings: autoResetSettings,keepAliveController: keepAliveController,- appUpdater: appUpdater,- proxySettings: proxySettings+ appUpdater: appUpdater)controller.install()statusItemController = controller- let notificationService = CodexNotificationService(+ let notificationService = NotificationService(settings: notificationSettings,statusViewModel: viewModel,activityMonitor: activityMonitor@@ -88,16 +81,15 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {keepAliveController.onKeepAliveLimitTriggered = { [weak notificationService] duration inawait notificationService?.notifyKeepAliveLimitReached(durationText: duration.title) ?? false}- activityMonitor.onInactivityProtectionTriggered = { [weak notificationService] notice in- await notificationService?.notifyActivityProtection(notice) ?? false+ activityMonitor.onProtectionTriggered = { [weak notificationService] notice in+ await notificationService?.notifyProtection(notice) ?? false}- activityMonitor.onInactivityProtectionInvalidated = { [weak notificationService] taskID, attemptID in- notificationService?.invalidateActivityProtectionNotification(taskID: taskID, attemptID: attemptID)+ activityMonitor.onProtectionInvalidated = { [weak notificationService] taskID, attemptID in+ notificationService?.invalidateProtectionNotification(taskID: taskID, attemptID: attemptID)}let taskGlowController = TaskGlowController(settings: taskGlowSettings,- activityMonitor: activityMonitor,- advancedModeSettings: advancedModeSettings+ activityMonitor: activityMonitor)taskGlowController.start()self.taskGlowController = taskGlowController@@ -135,6 +127,11 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {guard !Task.isCancelled else {return}+ if success {+ do { try await AppServerLogStore.shared.finish() } catch {+ AppLog.app.error("退出前请求日志写入失败")+ }+ }terminationPreparationTask = nilhasPreparedForTermination = successNSApplication.shared.reply(toApplicationShouldTerminate: success)@@ -149,13 +146,12 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {let state = LogFields.joined("version=\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "-")","build=\(Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "-")",- "advancedMode=\(advancedModeSettings.isEnabled ? 1 : 0)","keepAlive=\(keepAliveController.isEnabled ? 1 : 0)","keepAliveLimit=\(keepAliveController.maximumDuration.loggedHours)","keepAliveBattery=\(keepAliveController.lowBatteryThreshold.rawValue)","keepAliveWaiting=\(keepAliveController.keepsAwakeWhileWaiting ? 1 : 0)","keepAliveDisplay=\(keepAliveController.keepsDisplayAwake ? 1 : 0)",- "activityProtectionMinutes=\(activityProtectionSettings.inactivityDuration.loggedMinutes)",+ "protectionMinutes=\(protectionSettings.inactivityDuration.loggedMinutes)","sync=\(syncSettings.isEnabled ? 1 : 0)","notification=\(notificationSettings.isEnabled ? 1 : 0)","autoReset=\(autoResetSettings.isEnabled ? 1 : 0)",diff --git a/CodexBar/Controllers/HeatmapDetailPanelController.swift b/CodexBar/Controllers/HeatmapPanelController.swiftsimilarity index 95%rename from CodexBar/Controllers/HeatmapDetailPanelController.swiftrename to CodexBar/Controllers/HeatmapPanelController.swiftindex e9ac6e7..4eef041 100644--- a/CodexBar/Controllers/HeatmapDetailPanelController.swift+++ b/CodexBar/Controllers/HeatmapPanelController.swift@@ -4,12 +4,12 @@ import SwiftUI/// 热力图 hover 详情控制器, 负责左右贴边定位和抽屉式切换动画@MainActor-final class HeatmapDetailPanelController {- private let contentHost = SidePanelContentHost<UsageHeatmapDayDetailView>(- initialSize: UsageHeatmapDayDetailView.panelSize(showsWorkflow: true),+final class HeatmapPanelController {+ private let contentHost = SidePanelContentHost<HeatmapDetailView>(+ initialSize: HeatmapDetailView.panelSize(showsActivity: true),ignoresMouseEvents: true,sizingOptions: [.preferredContentSize],- cornerRadius: UsageHeatmapDayDetailView.panelCornerRadius+ cornerRadius: HeatmapDetailView.panelCornerRadius)private lazy var drawerAnimator = SidePanelDrawerAnimator(contentViewProvider: { [weak self] in@@ -112,7 +112,7 @@ final class HeatmapDetailPanelController {attach(panel, to: menuSurfaceWindow)}- let panelSize = UsageHeatmapDayDetailView.panelSize(showsWorkflow: context.showsWorkflow)+ let panelSize = HeatmapDetailView.panelSize(showsActivity: context.showsActivity)let position = panelPosition(for: panelSize,relativeTo: menuSurfaceWindow,@@ -290,8 +290,8 @@ final class HeatmapDetailPanelController {private func updateContent(_ context: UsageHeatmapHoverContext) {contentHost.updateContent(- UsageHeatmapDayDetailView(context: context),- size: UsageHeatmapDayDetailView.panelSize(showsWorkflow: context.showsWorkflow)+ HeatmapDetailView(context: context),+ size: HeatmapDetailView.panelSize(showsActivity: context.showsActivity))}diff --git a/CodexBar/Controllers/LogWindowController.swift b/CodexBar/Controllers/LogWindowController.swiftindex 8a3bb90..1ce43ac 100644--- a/CodexBar/Controllers/LogWindowController.swift+++ b/CodexBar/Controllers/LogWindowController.swift@@ -1,19 +1,25 @@import AppKitimport SwiftUI-/// 日志窗口控制器, 使用全局 RequestLogStore 保持关闭后日志不丢失+/// 日志窗口控制器, 日志持续写入本地, 仅在窗口打开时读取显示内容@MainActorfinal class LogWindowController: HostingWindowController {- private let store: RequestLogStore+ private var closeObserver: (any NSObjectProtocol)?+ private let store: AppServerLogViewModelinit(- store: RequestLogStore = .shared,+ store: AppServerLogViewModel = .shared,screenProvider: @escaping () -> NSScreen?) {self.store = storesuper.init(screenProvider: screenProvider)}+ override func open() {+ super.open()+ store.start()+ }+override func makeWindow() -> NSWindow {let hostingController = NSHostingController(rootView: LogView(store: store))@@ -22,6 +28,9 @@ final class LogWindowController: HostingWindowController {window.styleMask = [.titled, .closable, .miniaturizable, .resizable]window.contentMinSize = Metrics.minimumContentSizewindow.setContentSize(Metrics.defaultContentSize)+ closeObserver = NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification, object: window, queue: .main) { [weak self] _ in+ MainActor.assumeIsolated { self?.store.stop() }+ }return window}diff --git a/CodexBar/Controllers/SettingsOptionsPanelController.swift b/CodexBar/Controllers/OptionsPanelController.swiftsimilarity index 99%rename from CodexBar/Controllers/SettingsOptionsPanelController.swiftrename to CodexBar/Controllers/OptionsPanelController.swiftindex d8f7249..24a15cf 100644--- a/CodexBar/Controllers/SettingsOptionsPanelController.swift+++ b/CodexBar/Controllers/OptionsPanelController.swift@@ -46,7 +46,7 @@ private struct SidePanelEntryRebuildHost<Content: View>: View {/// 各子面板只差内容视图与高度变化来源, 窗口组关闭规则由 SettingsWindowController 统一维护/// 与重置次数面板不同: 内容是交互控件, 用常驻 hosting controller + ObservableObject 驱动更新, 不替换 rootView@MainActor-final class SettingsOptionsPanelController {+final class OptionsPanelController {private let animationKey: Stringprivate let initialPanelSize: CGSize/// 展开前的准备动作, 例如刷新只在这个面板里露面的设置项diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftindex 1bded39..5ff7fe9 100644--- a/CodexBar/Controllers/SettingsWindowController.swift+++ b/CodexBar/Controllers/SettingsWindowController.swift@@ -6,27 +6,25 @@ import SwiftUI@MainActorfinal class SettingsWindowController: HostingWindowController {private let viewModel: CodexStatusViewModel- private let proxySettings: CodexProxySettingsprivate let appUpdater: AppUpdater- private let advancedModeSettings: AdvancedModeSettings- private let codexCLINotificationSettings: CodexCLINotificationSettings- private let syncSettings: WorkflowSyncSettings+ private let tuiNotificationSettings: TUINotificationSettings+ private let syncSettings: SyncSettingsprivate let globalHotKeySettings: GlobalHotKeySettingsprivate let menuBarQuotaSettings: MenuBarQuotaSettingsprivate let mainPanelSettings: MainPanelSettingsprivate let taskGlowSettings: TaskGlowSettingsprivate let notificationSettings: NotificationSettingsprivate let autoResetSettings: AutoResetSettings- private let activityProtectionSettings: ActivityProtectionSettings+ private let protectionSettings: ProtectionSettingsprivate let keepAliveController: KeepAliveControllerprivate let onSyncChanged: (Bool) -> Void- private let onRebuildWorkflowData: WorkflowSyncScheduler.RebuildHandler+ private let onRebuildHistoryData: SyncScheduler.RebuildHandlerprivate let mainPanelUndoManager = UndoManager()private let animationState = SettingsWindowAnimationState()private var windowFocusObserver: AnyCancellable?private var windowVisibilityObserver: AnyCancellable?/// 只在真的要展开时构造: hosting controller 与动态面板订阅会常驻到 App 结束, 而用户可能一次子面板都没开过- private var optionsPanelControllers: [SettingsOptionsPanel: SettingsOptionsPanelController] = [:]+ private var optionsPanelControllers: [SettingsOptionsPanel: OptionsPanelController] = [:]private var optionsDismissEventMonitor: Any?private var optionsDismissFocusObserver: AnyCancellable?private var optionsDismissedByClick: (panel: SettingsOptionsPanel, event: NSEvent)?@@ -36,27 +34,23 @@ final class SettingsWindowController: HostingWindowController {init(viewModel: CodexStatusViewModel,appUpdater: AppUpdater,- proxySettings: CodexProxySettings,- advancedModeSettings: AdvancedModeSettings,- codexCLINotificationSettings: CodexCLINotificationSettings,- syncSettings: WorkflowSyncSettings,+ tuiNotificationSettings: TUINotificationSettings,+ syncSettings: SyncSettings,globalHotKeySettings: GlobalHotKeySettings,menuBarQuotaSettings: MenuBarQuotaSettings,mainPanelSettings: MainPanelSettings,taskGlowSettings: TaskGlowSettings,notificationSettings: NotificationSettings,autoResetSettings: AutoResetSettings,- activityProtectionSettings: ActivityProtectionSettings,+ protectionSettings: ProtectionSettings,keepAliveController: KeepAliveController,screenProvider: @escaping () -> NSScreen?,onSyncChanged: @escaping (Bool) -> Void,- onRebuildWorkflowData: @escaping WorkflowSyncScheduler.RebuildHandler+ onRebuildHistoryData: @escaping SyncScheduler.RebuildHandler) {self.viewModel = viewModelself.appUpdater = appUpdater- self.proxySettings = proxySettings- self.advancedModeSettings = advancedModeSettings- self.codexCLINotificationSettings = codexCLINotificationSettings+ self.tuiNotificationSettings = tuiNotificationSettingsself.syncSettings = syncSettingsself.globalHotKeySettings = globalHotKeySettingsself.menuBarQuotaSettings = menuBarQuotaSettings@@ -64,10 +58,10 @@ final class SettingsWindowController: HostingWindowController {self.taskGlowSettings = taskGlowSettingsself.notificationSettings = notificationSettingsself.autoResetSettings = autoResetSettings- self.activityProtectionSettings = activityProtectionSettings+ self.protectionSettings = protectionSettingsself.keepAliveController = keepAliveControllerself.onSyncChanged = onSyncChanged- self.onRebuildWorkflowData = onRebuildWorkflowData+ self.onRebuildHistoryData = onRebuildHistoryDatasuper.init(screenProvider: screenProvider)}@@ -84,8 +78,6 @@ final class SettingsWindowController: HostingWindowController {override func makeWindow() -> NSWindow {let hostingController = NSHostingController(rootView: AppSettingsView(- proxySettings: proxySettings,- advancedModeSettings: advancedModeSettings,syncSettings: syncSettings,globalHotKeySettings: globalHotKeySettings,menuBarQuotaSettings: menuBarQuotaSettings,@@ -95,7 +87,7 @@ final class SettingsWindowController: HostingWindowController {autoResetSettings: autoResetSettings,keepAliveController: keepAliveController,onSyncChanged: onSyncChanged,- onRebuildWorkflowData: onRebuildWorkflowData,+ onRebuildHistoryData: onRebuildHistoryData,onOptionsAction: { [weak self] action inself?.handleOptionsAction(action)},@@ -157,20 +149,19 @@ final class SettingsWindowController: HostingWindowController {private func refreshSettingsState() {notificationSettings.refreshAuthorizationStatus()- advancedModeSettings.reconcileConfiguration()- codexCLINotificationSettings.refresh()+ tuiNotificationSettings.refresh()syncSettings.refresh()menuBarQuotaSettings.refresh()mainPanelSettings.refresh()taskGlowSettings.refresh()autoResetSettings.refresh()- activityProtectionSettings.refresh()+ protectionSettings.refresh()keepAliveController.refresh()}private func optionsPanelController(_ panel: SettingsOptionsPanel- ) -> SettingsOptionsPanelController {+ ) -> OptionsPanelController {if let existing = existingOptionsPanelController(panel) {return existing}@@ -183,18 +174,18 @@ final class SettingsWindowController: HostingWindowController {/// 没建过就说明它不可能开着, 收起动作不必为此把它构造出来private func existingOptionsPanelController(_ panel: SettingsOptionsPanel- ) -> SettingsOptionsPanelController? {+ ) -> OptionsPanelController? {optionsPanelControllers[panel]}private func makeOptionsPanelController(_ panel: SettingsOptionsPanel- ) -> SettingsOptionsPanelController {+ ) -> OptionsPanelController {switch panel {case .mainPanel:makeMainPanelOptionsPanelController()case .taskGlow:- SettingsOptionsPanelController(+ OptionsPanelController(animationKey: "CodexBar.taskGlowOptionsDrawerTransform",initialPanelSize: TaskGlowOptionsView.initialPanelSize,willHide: { [taskGlowSettings] in taskGlowSettings.endColorPreview() },@@ -203,17 +194,16 @@ final class SettingsWindowController: HostingWindowController {})case .notification:- SettingsOptionsPanelController(+ OptionsPanelController(animationKey: "CodexBar.notificationOptionsDrawerTransform",initialPanelSize: NotificationOptionsView.initialPanelSize,- willShow: { [codexCLINotificationSettings] in- codexCLINotificationSettings.refresh()+ willShow: { [tuiNotificationSettings] in+ tuiNotificationSettings.refresh()},- contentProvider: { [notificationSettings, advancedModeSettings, codexCLINotificationSettings, autoResetSettings, keepAliveController] in+ contentProvider: { [notificationSettings, tuiNotificationSettings, autoResetSettings, keepAliveController] inNotificationOptionsView(notificationSettings: notificationSettings,- advancedModeSettings: advancedModeSettings,- codexCLINotificationSettings: codexCLINotificationSettings,+ tuiNotificationSettings: tuiNotificationSettings,autoResetSettings: autoResetSettings,keepAliveController: keepAliveController)@@ -222,7 +212,6 @@ final class SettingsWindowController: HostingWindowController {// 防睡眠只订阅相关派生值, 避免每次任务起停都触发面板高度重算contentChanges: Publishers.MergeMany([notificationSettings.objectWillChange.eraseToAnyPublisher(),- advancedModeSettings.objectWillChange.eraseToAnyPublisher(),autoResetSettings.$isEnabled.map { _ in () }.eraseToAnyPublisher(),@@ -235,7 +224,7 @@ final class SettingsWindowController: HostingWindowController {]).eraseToAnyPublisher())case .autoReset:- SettingsOptionsPanelController(+ OptionsPanelController(animationKey: "CodexBar.autoResetOptionsDrawerTransform",initialPanelSize: AutoResetOptionsView.initialPanelSize,contentProvider: { [autoResetSettings] in@@ -243,13 +232,13 @@ final class SettingsWindowController: HostingWindowController {})case .keepAlive:- SettingsOptionsPanelController(+ OptionsPanelController(animationKey: "CodexBar.keepAliveOptionsDrawerTransform",initialPanelSize: KeepAliveOptionsView.initialPanelSize,- contentProvider: { [keepAliveController, activityProtectionSettings] in+ contentProvider: { [keepAliveController, protectionSettings] inKeepAliveOptionsView(keepAliveController: keepAliveController,- activityProtectionSettings: activityProtectionSettings+ protectionSettings: protectionSettings)},// 面板里只有 hasBattery 会增删行, 其余各行的取值不改高度@@ -260,17 +249,16 @@ final class SettingsWindowController: HostingWindowController {}}- private func makeMainPanelOptionsPanelController() -> SettingsOptionsPanelController {- SettingsOptionsPanelController(+ private func makeMainPanelOptionsPanelController() -> OptionsPanelController {+ OptionsPanelController(animationKey: "CodexBar.mainPanelOptionsDrawerTransform",initialPanelSize: MainPanelOptionsView.initialPanelSize,willShow: { [mainPanelSettings] inmainPanelSettings.refresh()},- contentProvider: { [mainPanelSettings, advancedModeSettings, mainPanelUndoManager] in+ contentProvider: { [mainPanelSettings, mainPanelUndoManager] inMainPanelOptionsView(settings: mainPanelSettings,- advancedModeSettings: advancedModeSettings,undoManager: mainPanelUndoManager)}diff --git a/CodexBar/Controllers/SidePanelPresenter.swift b/CodexBar/Controllers/SidePanelPresenter.swiftnew file mode 100644index 0000000..94fab56--- /dev/null+++ b/CodexBar/Controllers/SidePanelPresenter.swift@@ -0,0 +1,311 @@+import AppKit+import SwiftUI++// MARK: - 抽屉动效++@MainActor+final class SidePanelDrawerAnimator {+ private let contentViewProvider: @MainActor () -> NSView?+ private let animationKey: String+ private let overscan: CGFloat++ init(+ contentViewProvider: @escaping @MainActor () -> NSView?,+ animationKey: String,+ overscan: CGFloat+ ) {+ self.contentViewProvider = contentViewProvider+ self.animationKey = animationKey+ self.overscan = overscan+ }++ func hiddenTranslation(for side: UsageHeatmapDetailSide, panelWidth: CGFloat) -> CGFloat {+ let distance = panelWidth + overscan+ switch side {+ case .left:+ return distance+ case .right:+ return -distance+ }+ }++ func setTranslation(_ translationX: CGFloat) {+ guard let layer = contentViewProvider()?.layer else {+ return+ }++ CATransaction.begin()+ CATransaction.setDisableActions(true)+ layer.removeAnimation(forKey: animationKey)+ layer.transform = CATransform3DMakeTranslation(translationX, 0, 0)+ CATransaction.commit()+ }++ func animateTranslation(+ from fromTranslationX: CGFloat? = nil,+ to translationX: CGFloat,+ duration: TimeInterval,+ timing: CAMediaTimingFunctionName,+ completion: (() -> Void)? = nil+ ) {+ guard let layer = contentViewProvider()?.layer else {+ completion?()+ return+ }++ let targetTransform = CATransform3DMakeTranslation(translationX, 0, 0)+ CATransaction.begin()+ CATransaction.setCompletionBlock(completion)++ let animation = CABasicAnimation(keyPath: "transform")+ animation.fromValue = fromTranslationX.map { CATransform3DMakeTranslation($0, 0, 0) }+ ?? layer.presentation()?.transform+ ?? layer.transform+ animation.toValue = targetTransform+ animation.duration = duration+ animation.timingFunction = CAMediaTimingFunction(name: timing)+ layer.add(animation, forKey: animationKey)+ layer.transform = targetTransform++ CATransaction.commit()+ }++ func animateEntryAfterInitialLayout(+ from hiddenTranslationX: CGFloat,+ panel: NSPanel,+ duration: TimeInterval,+ isCurrent: @escaping @MainActor () -> Bool,+ completion: @escaping @MainActor () -> Void+ ) {+ panel.contentView?.layoutSubtreeIfNeeded()+ panel.displayIfNeeded()+ CATransaction.flush()++ Task { @MainActor [weak self, weak panel] in+ await Task.yield()+ // 过期请求的隐藏和清理由调用方的 generation 流程负责+ guard let self,+ let panel,+ panel.isVisible,+ isCurrent() else {+ return+ }++ setTranslation(hiddenTranslationX)+ panel.contentView?.layoutSubtreeIfNeeded()+ panel.displayIfNeeded()+ CATransaction.flush()+ panel.alphaValue = 1+ animateTranslation(+ from: hiddenTranslationX,+ to: 0,+ duration: duration,+ timing: .easeOut+ ) {+ Task { @MainActor in+ guard isCurrent() else {+ return+ }++ completion()+ }+ }+ }+ }++ func resetVisualState(for panel: NSPanel) {+ setTranslation(0)+ panel.alphaValue = 1+ }+}++// MARK: - 展开与收起++/// 抽屉面板共用的显隐状态机, 用于重置次数 设置子选项和任务中心+/// 负责 generation 竞态防护 入退场动画和 child window 挂载与卸载+/// 热力图详情面板带切边与延迟隐藏 状态机不同 因此不走这里+@MainActor+final class SidePanelDrawerPresenter {+ private let makesKey: Bool+ private let usesUntranslatedInitialLayout: Bool+ private let drawerAnimator: SidePanelDrawerAnimator+ private weak var panel: NSPanel?+ private var visibilityGeneration = 0+ private var isExitAnimationRunning = false+ private var currentSide = UsageHeatmapDetailSide.right+ private weak var parentWindow: NSWindow?++ init(+ animationKey: String,+ makesKey: Bool = false,+ usesUntranslatedInitialLayout: Bool = false,+ contentViewProvider: @escaping @MainActor () -> NSView?+ ) {+ self.makesKey = makesKey+ self.usesUntranslatedInitialLayout = usesUntranslatedInitialLayout+ drawerAnimator = SidePanelDrawerAnimator(+ contentViewProvider: contentViewProvider,+ animationKey: animationKey,+ overscan: SidePanelSupport.Metrics.drawerOverscan+ )+ }++ var isVisible: Bool {+ panel?.isVisible == true+ }++ /// 内容更新由调用方在 present 之前完成+ func present(+ _ panel: NSPanel,+ at position: SidePanelPosition,+ relativeTo parentWindow: NSWindow,+ completion: @escaping @MainActor () -> Void = {}+ ) {+ self.panel = panel+ visibilityGeneration += 1+ isExitAnimationRunning = false+ panel.setFrame(position.frame, display: true)+ currentSide = position.side++ let generation = visibilityGeneration+ let hidden = drawerAnimator.hiddenTranslation(for: currentSide, panelWidth: panel.frame.width)+ drawerAnimator.setTranslation(usesUntranslatedInitialLayout ? 0 : hidden)+ panel.alphaValue = 0+ self.parentWindow = parentWindow+ SidePanelSupport.attach(panel, to: parentWindow)+ panel.order(.above, relativeTo: parentWindow.windowNumber)+ if makesKey {+ panel.makeKey()+ }+ drawerAnimator.animateEntryAfterInitialLayout(+ from: hidden,+ panel: panel,+ duration: SidePanelSupport.Metrics.drawerEnterDuration,+ isCurrent: { [weak self] in+ self?.visibilityGeneration == generation+ },+ completion: { [weak self] in+ guard let self else {+ return+ }++ drawerAnimator.setTranslation(0)+ completion()+ }+ )+ }++ func hide(immediate: Bool = false) {+ guard let panel else {+ return+ }++ // 不可见的子窗口仍可能挂在父窗口上, 收尾不能只依据 isVisible+ if immediate || !panel.isVisible {+ visibilityGeneration += 1+ drawerAnimator.resetVisualState(for: panel)+ isExitAnimationRunning = false+ orderOut(panel)+ return+ }++ guard !isExitAnimationRunning else {+ return+ }++ visibilityGeneration += 1+ let generation = visibilityGeneration+ let side = currentSide+ isExitAnimationRunning = true+ let hidden = drawerAnimator.hiddenTranslation(for: side, panelWidth: panel.frame.width)+ drawerAnimator.animateTranslation(+ to: hidden,+ duration: SidePanelSupport.Metrics.drawerExitDuration,+ timing: .easeIn+ ) { [weak self] in+ Task { @MainActor [weak self] in+ guard let self,+ generation == visibilityGeneration else {+ return+ }++ orderOut(panel)+ drawerAnimator.setTranslation(0)+ isExitAnimationRunning = false+ }+ }+ }++ private func orderOut(_ panel: NSPanel) {+ SidePanelSupport.orderOut(panel, menuSurfaceWindow: parentWindow)+ }+}++// MARK: - 内容宿主++/// 侧边面板的内容宿主: 懒建 panel + hostingController, 统一"替换 rootView → configureLayers → setContentSize"的更新序列+/// ⚠️ 每次更新都整树替换 rootView 是刻意行为 (见 CLAUDE.md 热力图详情面板的说明), 不要改成常驻状态推送+@MainActor+final class SidePanelContentHost<Root: View> {+ private(set) var panel: NSPanel?+ private var hostingController: NSHostingController<Root>?+ private let initialSize: CGSize+ private let ignoresMouseEvents: Bool+ private let sizingOptions: NSHostingSizingOptions+ private let cornerRadius: CGFloat++ init(+ initialSize: CGSize,+ ignoresMouseEvents: Bool,+ sizingOptions: NSHostingSizingOptions,+ cornerRadius: CGFloat+ ) {+ self.initialSize = initialSize+ self.ignoresMouseEvents = ignoresMouseEvents+ self.sizingOptions = sizingOptions+ self.cornerRadius = cornerRadius+ }++ var contentView: NSView? {+ hostingController?.view+ }++ func containsScreenPoint(_ screenPoint: NSPoint) -> Bool {+ guard let panel, panel.isVisible else {+ return false+ }++ return panel.frame.contains(screenPoint)+ }++ func ensurePanel() -> NSPanel {+ if let panel {+ return panel+ }++ let panel = SidePanelSupport.makePanel(+ initialSize: initialSize,+ ignoresMouseEvents: ignoresMouseEvents+ )+ self.panel = panel+ return panel+ }++ func updateContent(_ rootView: Root, size: CGSize) {+ if let hostingController {+ hostingController.rootView = rootView+ } else {+ let hostingController = NSHostingController(rootView: rootView)+ hostingController.sizingOptions = sizingOptions+ panel?.contentViewController = hostingController+ self.hostingController = hostingController+ }++ SidePanelSupport.configureLayers(+ hostingView: hostingController?.view,+ contentView: panel?.contentView,+ cornerRadius: cornerRadius+ )+ panel?.setContentSize(size)+ }+}diff --git a/CodexBar/Controllers/SidePanelSupport.swift b/CodexBar/Controllers/SidePanelSupport.swiftindex 8f9df37..d27286e 100644--- a/CodexBar/Controllers/SidePanelSupport.swift+++ b/CodexBar/Controllers/SidePanelSupport.swift@@ -52,315 +52,6 @@ final class KeyableBorderlessPanel: NSPanel {}}-// MARK: - 抽屉动效--@MainActor-final class SidePanelDrawerAnimator {- private let contentViewProvider: @MainActor () -> NSView?- private let animationKey: String- private let overscan: CGFloat-- init(- contentViewProvider: @escaping @MainActor () -> NSView?,- animationKey: String,- overscan: CGFloat- ) {- self.contentViewProvider = contentViewProvider- self.animationKey = animationKey- self.overscan = overscan- }-- func hiddenTranslation(for side: UsageHeatmapDetailSide, panelWidth: CGFloat) -> CGFloat {- let distance = panelWidth + overscan- switch side {- case .left:- return distance- case .right:- return -distance- }- }-- func setTranslation(_ translationX: CGFloat) {- guard let layer = contentViewProvider()?.layer else {- return- }-- CATransaction.begin()- CATransaction.setDisableActions(true)- layer.removeAnimation(forKey: animationKey)- layer.transform = CATransform3DMakeTranslation(translationX, 0, 0)- CATransaction.commit()- }-- func animateTranslation(- from fromTranslationX: CGFloat? = nil,- to translationX: CGFloat,- duration: TimeInterval,- timing: CAMediaTimingFunctionName,- completion: (() -> Void)? = nil- ) {- guard let layer = contentViewProvider()?.layer else {- completion?()- return- }-- let targetTransform = CATransform3DMakeTranslation(translationX, 0, 0)- CATransaction.begin()- CATransaction.setCompletionBlock(completion)-- let animation = CABasicAnimation(keyPath: "transform")- animation.fromValue = fromTranslationX.map { CATransform3DMakeTranslation($0, 0, 0) }- ?? layer.presentation()?.transform- ?? layer.transform- animation.toValue = targetTransform- animation.duration = duration- animation.timingFunction = CAMediaTimingFunction(name: timing)- layer.add(animation, forKey: animationKey)- layer.transform = targetTransform-- CATransaction.commit()- }-- func animateEntryAfterInitialLayout(- from hiddenTranslationX: CGFloat,- panel: NSPanel,- duration: TimeInterval,- isCurrent: @escaping @MainActor () -> Bool,- completion: @escaping @MainActor () -> Void- ) {- panel.contentView?.layoutSubtreeIfNeeded()- panel.displayIfNeeded()- CATransaction.flush()-- Task { @MainActor [weak self, weak panel] in- await Task.yield()- // 过期请求的隐藏和清理由调用方的 generation 流程负责- guard let self,- let panel,- panel.isVisible,- isCurrent() else {- return- }-- setTranslation(hiddenTranslationX)- panel.contentView?.layoutSubtreeIfNeeded()- panel.displayIfNeeded()- CATransaction.flush()- panel.alphaValue = 1- animateTranslation(- from: hiddenTranslationX,- to: 0,- duration: duration,- timing: .easeOut- ) {- Task { @MainActor in- guard isCurrent() else {- return- }-- completion()- }- }- }- }-- func resetVisualState(for panel: NSPanel) {- setTranslation(0)- panel.alphaValue = 1- }-}--// MARK: - 展开与收起--/// 抽屉面板共用的显隐状态机, 用于重置次数 设置子选项和任务中心-/// 负责 generation 竞态防护 入退场动画和 child window 挂载与卸载-/// 热力图详情面板带切边与延迟隐藏 状态机不同 因此不走这里-@MainActor-final class SidePanelDrawerPresenter {- private let makesKey: Bool- private let usesUntranslatedInitialLayout: Bool- private let drawerAnimator: SidePanelDrawerAnimator- private weak var panel: NSPanel?- private var visibilityGeneration = 0- private var isExitAnimationRunning = false- private var currentSide = UsageHeatmapDetailSide.right- private weak var parentWindow: NSWindow?-- init(- animationKey: String,- makesKey: Bool = false,- usesUntranslatedInitialLayout: Bool = false,- contentViewProvider: @escaping @MainActor () -> NSView?- ) {- self.makesKey = makesKey- self.usesUntranslatedInitialLayout = usesUntranslatedInitialLayout- drawerAnimator = SidePanelDrawerAnimator(- contentViewProvider: contentViewProvider,- animationKey: animationKey,- overscan: SidePanelSupport.Metrics.drawerOverscan- )- }-- var isVisible: Bool {- panel?.isVisible == true- }-- /// 内容更新由调用方在 present 之前完成- func present(- _ panel: NSPanel,- at position: SidePanelPosition,- relativeTo parentWindow: NSWindow,- completion: @escaping @MainActor () -> Void = {}- ) {- self.panel = panel- visibilityGeneration += 1- isExitAnimationRunning = false- panel.setFrame(position.frame, display: true)- currentSide = position.side-- let generation = visibilityGeneration- let hidden = drawerAnimator.hiddenTranslation(for: currentSide, panelWidth: panel.frame.width)- drawerAnimator.setTranslation(usesUntranslatedInitialLayout ? 0 : hidden)- panel.alphaValue = 0- self.parentWindow = parentWindow- SidePanelSupport.attach(panel, to: parentWindow)- panel.order(.above, relativeTo: parentWindow.windowNumber)- if makesKey {- panel.makeKey()- }- drawerAnimator.animateEntryAfterInitialLayout(- from: hidden,- panel: panel,- duration: SidePanelSupport.Metrics.drawerEnterDuration,- isCurrent: { [weak self] in- self?.visibilityGeneration == generation- },- completion: { [weak self] in- guard let self else {- return- }-- drawerAnimator.setTranslation(0)- completion()- }- )- }-- func hide(immediate: Bool = false) {- guard let panel else {- return- }-- // 不可见的子窗口仍可能挂在父窗口上, 收尾不能只依据 isVisible- if immediate || !panel.isVisible {- visibilityGeneration += 1- drawerAnimator.resetVisualState(for: panel)- isExitAnimationRunning = false- orderOut(panel)- return- }-- guard !isExitAnimationRunning else {- return- }-- visibilityGeneration += 1- let generation = visibilityGeneration- let side = currentSide- isExitAnimationRunning = true- let hidden = drawerAnimator.hiddenTranslation(for: side, panelWidth: panel.frame.width)- drawerAnimator.animateTranslation(- to: hidden,- duration: SidePanelSupport.Metrics.drawerExitDuration,- timing: .easeIn- ) { [weak self] in- Task { @MainActor [weak self] in- guard let self,- generation == visibilityGeneration else {- return- }-- orderOut(panel)- drawerAnimator.setTranslation(0)- isExitAnimationRunning = false- }- }- }-- private func orderOut(_ panel: NSPanel) {- SidePanelSupport.orderOut(panel, menuSurfaceWindow: parentWindow)- }-}--// MARK: - 内容宿主--/// 侧边面板的内容宿主: 懒建 panel + hostingController, 统一"替换 rootView → configureLayers → setContentSize"的更新序列-/// ⚠️ 每次更新都整树替换 rootView 是刻意行为 (见 CLAUDE.md 热力图详情面板的说明), 不要改成常驻状态推送-@MainActor-final class SidePanelContentHost<Root: View> {- private(set) var panel: NSPanel?- private var hostingController: NSHostingController<Root>?- private let initialSize: CGSize- private let ignoresMouseEvents: Bool- private let sizingOptions: NSHostingSizingOptions- private let cornerRadius: CGFloat-- init(- initialSize: CGSize,- ignoresMouseEvents: Bool,- sizingOptions: NSHostingSizingOptions,- cornerRadius: CGFloat- ) {- self.initialSize = initialSize- self.ignoresMouseEvents = ignoresMouseEvents- self.sizingOptions = sizingOptions- self.cornerRadius = cornerRadius- }-- var contentView: NSView? {- hostingController?.view- }-- func containsScreenPoint(_ screenPoint: NSPoint) -> Bool {- guard let panel, panel.isVisible else {- return false- }-- return panel.frame.contains(screenPoint)- }-- func ensurePanel() -> NSPanel {- if let panel {- return panel- }-- let panel = SidePanelSupport.makePanel(- initialSize: initialSize,- ignoresMouseEvents: ignoresMouseEvents- )- self.panel = panel- return panel- }-- func updateContent(_ rootView: Root, size: CGSize) {- if let hostingController {- hostingController.rootView = rootView- } else {- let hostingController = NSHostingController(rootView: rootView)- hostingController.sizingOptions = sizingOptions- panel?.contentViewController = hostingController- self.hostingController = hostingController- }-- SidePanelSupport.configureLayers(- hostingView: hostingController?.view,- contentView: panel?.contentView,- cornerRadius: cornerRadius- )- panel?.setContentSize(size)- }-}-// MARK: - 面板工厂与定位@MainActordiff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex 5c2d84a..ca13b03 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -7,11 +7,10 @@ import SwiftUI@MainActorfinal class StatusItemController: NSObject, NSMenuDelegate {private let viewModel: CodexStatusViewModel- private let workflowViewModel: WorkflowViewModel- private let advancedModeSettings: AdvancedModeSettings- private let codexCLINotificationSettings: CodexCLINotificationSettings- private let activityMonitor: CodexActivityMonitor- private let syncSettings: WorkflowSyncSettings+ private let historyViewModel: HistoryViewModel+ private let tuiNotificationSettings: TUINotificationSettings+ private let activityMonitor: ActivityMonitor+ private let syncSettings: SyncSettingsprivate let globalHotKeySettings: GlobalHotKeySettingsprivate let menuBarQuotaSettings: MenuBarQuotaSettingsprivate let mainPanelSettings: MainPanelSettings@@ -19,17 +18,16 @@ final class StatusItemController: NSObject, NSMenuDelegate {private let notificationSettings: NotificationSettingsprivate let autoResetSettings: AutoResetSettingsprivate let keepAliveController: KeepAliveController- private let proxySettings: CodexProxySettingsprivate let appUpdater: AppUpdaterprivate let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)private let popover = NSPopover()private let menuSurfaceVisibility = MenuSurfaceVisibilityState()private let popoverAnimationState = MenuSurfaceAnimationState()private let fallbackPanelAnimationState = MenuSurfaceAnimationState()- private let activityCenterPresentationState = CodexActivityCenterPresentationState()- private let heatmapDetailPanelController = HeatmapDetailPanelController()+ private let activityCenterPresentationState = ActivityCenterPresentationState()+ private let heatmapDetailPanelController = HeatmapPanelController()private let resetCreditsPanelController = ResetCreditsPanelController()- private lazy var activityCenterPanelController = ActivityCenterPanelController(+ private lazy var activityCenterPanelController = ActivityPanelController(activityMonitor: activityMonitor,presentationState: activityCenterPresentationState,mainPanelSettings: mainPanelSettings@@ -46,9 +44,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {private lazy var settingsWindowController = SettingsWindowController(viewModel: viewModel,appUpdater: appUpdater,- proxySettings: proxySettings,- advancedModeSettings: advancedModeSettings,- codexCLINotificationSettings: codexCLINotificationSettings,+ tuiNotificationSettings: tuiNotificationSettings,syncSettings: syncSettings,globalHotKeySettings: globalHotKeySettings,menuBarQuotaSettings: menuBarQuotaSettings,@@ -56,29 +52,29 @@ final class StatusItemController: NSObject, NSMenuDelegate {taskGlowSettings: taskGlowSettings,notificationSettings: notificationSettings,autoResetSettings: autoResetSettings,- activityProtectionSettings: activityMonitor.activityProtectionSettings,+ protectionSettings: activityMonitor.protectionSettings,keepAliveController: keepAliveController) { [weak self] inself?.statusItem.button?.window?.screen} onSyncChanged: { [weak self] _ in// setEnabled 在回调之前已经写回属性, 现场求值就是新结论- self?.workflowSyncScheduler.requestSync(trigger: .settings)- } onRebuildWorkflowData: { [weak self] dateKeys, completion in+ self?.syncScheduler.requestSync(trigger: .settings)+ } onRebuildHistoryData: { [weak self] dateKeys, completion inguard let self else {completion(.failure(CancellationError()))return}- workflowSyncScheduler.requestRebuild(for: dateKeys, completion: completion)+ syncScheduler.requestRebuild(for: dateKeys, completion: completion)}private lazy var logWindowController = LogWindowController { [weak self] inself?.statusItem.button?.window?.screen}- private lazy var workflowSyncScheduler = WorkflowSyncScheduler(- viewModel: workflowViewModel,+ private lazy var syncScheduler = SyncScheduler(+ viewModel: historyViewModel,syncActivation: { [weak self] in- self?.workflowSyncActivation ?? .syncOff+ self?.syncActivation ?? .syncOff})@@ -118,11 +114,10 @@ final class StatusItemController: NSObject, NSMenuDelegate {init(viewModel: CodexStatusViewModel,- workflowViewModel: WorkflowViewModel,- advancedModeSettings: AdvancedModeSettings,- codexCLINotificationSettings: CodexCLINotificationSettings,- activityMonitor: CodexActivityMonitor,- syncSettings: WorkflowSyncSettings,+ historyViewModel: HistoryViewModel,+ tuiNotificationSettings: TUINotificationSettings,+ activityMonitor: ActivityMonitor,+ syncSettings: SyncSettings,globalHotKeySettings: GlobalHotKeySettings,menuBarQuotaSettings: MenuBarQuotaSettings,mainPanelSettings: MainPanelSettings,@@ -130,13 +125,11 @@ final class StatusItemController: NSObject, NSMenuDelegate {notificationSettings: NotificationSettings,autoResetSettings: AutoResetSettings,keepAliveController: KeepAliveController,- appUpdater: AppUpdater,- proxySettings: CodexProxySettings+ appUpdater: AppUpdater) {self.viewModel = viewModel- self.workflowViewModel = workflowViewModel- self.advancedModeSettings = advancedModeSettings- self.codexCLINotificationSettings = codexCLINotificationSettings+ self.historyViewModel = historyViewModel+ self.tuiNotificationSettings = tuiNotificationSettingsself.activityMonitor = activityMonitorself.syncSettings = syncSettingsself.globalHotKeySettings = globalHotKeySettings@@ -147,122 +140,9 @@ final class StatusItemController: NSObject, NSMenuDelegate {self.autoResetSettings = autoResetSettingsself.keepAliveController = keepAliveControllerself.appUpdater = appUpdater- self.proxySettings = proxySettingssuper.init()}- private struct StatusIconState: Equatable {- let usesErrorImage: Bool- let ordinaryUsageAllowed: Bool?- let progress: StatusIconProgress?- let activity: CodexActivitySnapshot-- func symbolName(at now: Date) -> String {- if usesErrorImage {- return "person.slash.fill"- }- switch activity.statusItemActivity(at: now) {- case .waiting: return "person.badge.key.fill"- case .running: return "person.badge.clock.fill"- case .completed: return "person.badge.shield.checkmark.fill"- case .terminated: return "person.badge.shield.exclamationmark.fill"- case .idle: return "person.fill"- }- }-- var hasLiveDuration: Bool {- activity.hasActiveTasks- }-- func toolTip(at now: Date) -> String? {- var lines: [String] = []- if usesErrorImage {- lines.append(String(localized: "codex-status.account.unavailable"))- }-- if let activityText = activityToolTip(at: now) {- lines.append(activityText)- }- if activity.activeCount > 1 {- lines.append(- String(localized: "status-item.activity-summary", defaultValue: "\(activity.waitingCount, specifier: "%lld")\(activity.runningCount, specifier: "%lld")")- )- }- if let progress {- lines.append(progress.toolTip)- }- return lines.isEmpty ? nil : lines.joined(separator: "\n")- }-- private func activityToolTip(at now: Date) -> String? {- switch activity.statusItemActivity(at: now) {- case let .waiting(task):- var text = String(localized: "activity.status.codex-waiting-for-approval")- if let projectName = task.projectName {- text += " • \(projectName)"- }- if let toolName = task.toolName {- text += " • \(toolName)"- }- text += " • \(CodexActivityDisplayFormat.waitingDurationFragment(since: task.stateChangedAt, now: now))"- return text- case let .running(task):- var text = String(localized: "activity.status.codex-running")- if let projectName = task.projectName {- text += " • \(projectName)"- }- if task.showsPreciseDuration, let startedAt = task.startedAt {- text += " • \(CodexActivityDisplayFormat.runningDurationFragment(since: startedAt, now: now))"- }- return text- case let .completed(completion):- var text = String(localized: "activity.status.codex-just-completed")- if let projectName = completion.projectName {- text += " • \(projectName)"- }- if let duration = completion.duration {- text += " • \(CodexActivityDisplayFormat.elapsedDurationFragment(for: duration))"- }- return text- case let .terminated(termination):- var text = String(localized: "activity.status.codex-stopped")- if let projectName = termination.projectName {- text += " • \(projectName)"- }- if let duration = termination.duration {- text += " • \(CodexActivityDisplayFormat.elapsedDurationFragment(for: duration))"- }- return text- case .idle:- return nil- }- }- }-- private struct StatusIconProgress: Equatable {- let label: String- let percent: Int- let isStale: Bool-- var toolTip: String {- let percentText = CodexPercentageFormat.string(from: percent)- return String(localized: "quota.status.remaining", defaultValue: "\(label)\(percentText)")- }-- init?(snapshot: CodexQuotaSnapshot?, selection: MenuBarQuotaSelection) {- guard let targetKind = selection.windowKind,- let snapshot,- let window = snapshot.codexLimit?.window(ofKind: targetKind),- window.hasData else {- return nil- }-- label = window.label- percent = window.remainingPercent- isStale = snapshot.isRateLimitsStale- }- }-// MARK: - 装配与对外入口func install() {@@ -271,9 +151,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {observeGlobalHotKeySettings()// 订阅时 CombineLatest 会同步发出当前值, 初始图标由订阅路径统一渲染observeViewModel()- observeWorkflowSyncState()- advancedModeSettings.reconcileConfiguration()- observeMainPanelAdvancedModeState()+ observeSyncState()viewModel.startAutoRefresh()}@@ -284,7 +162,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {statusIconHostingView?.removeFromSuperview()statusIconHostingView = nilstatusToolTipTask?.cancel()- workflowSyncScheduler.cancel()+ syncScheduler.cancel()setAuxiliaryWindowKeyFocus(true)globalHotKeyController.uninstall()cancellables.removeAll()@@ -353,8 +231,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {) -> NSHostingController<AnyView> {let rootView = CodexStatusMenuView(viewModel: viewModel,- workflowViewModel: workflowViewModel,- advancedModeSettings: advancedModeSettings,+ historyViewModel: historyViewModel,mainPanelSettings: mainPanelSettings,activityMonitor: activityMonitor,syncSettings: syncSettings,@@ -400,14 +277,9 @@ final class StatusItemController: NSObject, NSMenuDelegate {.map(\.hasTaskCenterContent).removeDuplicates()- let isTaskCenterVisible = Publishers.CombineLatest(- advancedModeSettings.$isEnabled,- mainPanelSettings.$layout- )- .map { isAdvancedModeEnabled, layout in- isAdvancedModeEnabled && layout.isVisible(.activity)- }- .removeDuplicates()+ let isTaskCenterVisible = mainPanelSettings.$layout+ .map { $0.isVisible(.activity) }+ .removeDuplicates()Publishers.CombineLatest4(menuSurfaceVisibility.$isVisible,@@ -450,7 +322,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {guard let self else {return}- refreshWorkflowIfAdvancedModeEnabled(performMaintenance: true)+ refreshHistory(performMaintenance: true)}.store(in: &cancellables)@@ -481,27 +353,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {.store(in: &cancellables)}- private func observeWorkflowSyncState() {- advancedModeSettings.$isEnabled- .removeDuplicates()- .sink { [weak self] isEnabled in- guard let self else {- return- }-- if isEnabled {- // 回调跑在 willSet, advancedModeSettings.isEnabled 此刻还是旧值, 只能用参数- workflowSyncScheduler.requestSync(- trigger: .advancedModeEnabled,- activation: syncSettings.activation(isAdvancedModeEnabled: true)- )- } else {- workflowSyncScheduler.clearPendingMaintenance()- activityCenterPanelController.hide(immediate: true)- }- }- .store(in: &cancellables)-+ private func observeSyncState() {syncSettings.$syncAvailability.removeDuplicates().sink { [weak self] availability in@@ -510,15 +362,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {.store(in: &cancellables)}- private func observeMainPanelAdvancedModeState() {- advancedModeSettings.$isEnabled- .removeDuplicates()- .sink { [weak self] isEnabled in- self?.mainPanelSettings.updateAdvancedModeEnabled(isEnabled)- }- .store(in: &cancellables)- }-private func observeGlobalHotKeySettings() {globalHotKeySettings.$shortcut.removeDuplicates()@@ -591,7 +434,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {)}- /// 终态提示按墙上时间到期, 即使没有后续 Hook 事件也会恢复普通图标+ /// 终态提示按墙上时间到期, 即使没有后续活动事件也会恢复普通图标private func scheduleStatusIconExpiration() {statusIconExpirationTask?.cancel()statusIconExpirationTask = nil@@ -763,7 +606,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {guard let self, isActiveMenuSurfaceVisible else { return }menuSurfaceState = .shown// 展开完成后再刷新共享状态, 避免主面板与设置窗口在淡入期间一起重算- refreshWorkflowIfAdvancedModeEnabled(performMaintenance: false)+ refreshHistory(performMaintenance: false)viewModel.refreshIfNeeded(trigger: .panelOpen)}}@@ -1000,22 +843,15 @@ final class StatusItemController: NSObject, NSMenuDelegate {// MARK: - 刷新与同步- private func refreshWorkflowIfAdvancedModeEnabled(performMaintenance: Bool) {- // 进阶模式与额度使用同一刷新节奏, 配置和信任状态损坏后都能自动收敛- advancedModeSettings.reconcileConfiguration()- guard advancedModeSettings.isEnabled else {- workflowSyncScheduler.clearPendingMaintenance()- return- }-+ private func refreshHistory(performMaintenance: Bool) {if performMaintenance {// 统计维护挂在额度刷新完成事件上, 触发来源继承那一次刷新- workflowSyncScheduler.requestMaintenance(+ syncScheduler.requestMaintenance(allowsSync: true,trigger: viewModel.lastRefreshTrigger)} else {- workflowViewModel.refreshIfNeeded()+ historyViewModel.refreshIfNeeded()}}@@ -1023,17 +859,16 @@ final class StatusItemController: NSObject, NSMenuDelegate {/// 从 $syncAvailability 的订阅进来时 syncSettings.isSyncAvailable 还是旧值, 只有回调参数是新的/// 不在这里判断该不该跳过: requestSync 的 guard 已经统一处理并记下 reason=private func handleSyncChanged(isSyncAvailable: Bool) {- workflowSyncScheduler.requestSync(+ syncScheduler.requestSync(trigger: .settings,activation: syncSettings.activation(- isAdvancedModeEnabled: advancedModeSettings.isEnabled,isSyncAvailable: isSyncAvailable))}- private var workflowSyncActivation: WorkflowSyncActivation {- syncSettings.activation(isAdvancedModeEnabled: advancedModeSettings.isEnabled)+ private var syncActivation: SyncActivation {+ syncSettings.activation()}// MARK: - 侧边面板@@ -1073,7 +908,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {)}- private func toggleActivityCenterPanel(_ context: CodexActivityCenterPanelContext) {+ private func toggleActivityCenterPanel(_ context: ActivityCenterPanelContext) {guard isActiveMenuSurfaceVisible,let menuSurfaceContentView = activeMenuSurfaceContentView,let menuSurfaceWindow = activeMenuSurfaceWindow else {@@ -1178,6 +1013,6 @@ private protocol MenuSideDetailPanel: AnyObject {func containsScreenPoint(_ screenPoint: NSPoint) -> Bool}-extension HeatmapDetailPanelController: MenuSideDetailPanel {}+extension HeatmapPanelController: MenuSideDetailPanel {}extension ResetCreditsPanelController: MenuSideDetailPanel {}-extension ActivityCenterPanelController: MenuSideDetailPanel {}+extension ActivityPanelController: MenuSideDetailPanel {}diff --git a/CodexBar/Controllers/TaskGlowController.swift b/CodexBar/Controllers/TaskGlowController.swiftindex c4b592c..291de66 100644--- a/CodexBar/Controllers/TaskGlowController.swift+++ b/CodexBar/Controllers/TaskGlowController.swift@@ -6,8 +6,7 @@ import QuartzCore@MainActorfinal class TaskGlowController {private let settings: TaskGlowSettings- private let activityMonitor: CodexActivityMonitor- private let advancedModeSettings: AdvancedModeSettings+ private let activityMonitor: ActivityMonitorprivate var appearance: TaskGlowAppearanceprivate var cancellables = Set<AnyCancellable>()private var panels: [TaskGlowPanel] = []@@ -25,12 +24,10 @@ final class TaskGlowController {init(settings: TaskGlowSettings,- activityMonitor: CodexActivityMonitor,- advancedModeSettings: AdvancedModeSettings+ activityMonitor: ActivityMonitor) {self.settings = settingsself.activityMonitor = activityMonitor- self.advancedModeSettings = advancedModeSettingsappearance = settings.appearancemotionClock.setAnimationSpeed(appearance.animationSpeed)}@@ -42,20 +39,16 @@ final class TaskGlowController {func start() {guard cancellables.isEmpty else { return }- Publishers.CombineLatest3(- settings.$isEnabled,- advancedModeSettings.$isEnabled,- advancedModeSettings.$isVerified- )- .sink { [weak self] enabled, advancedModeEnabled, advancedModeVerified in- guard let self else { return }- if !enabled || !advancedModeEnabled || !advancedModeVerified {- cancelPreview()+ settings.$isEnabled+ .sink { [weak self] enabled in+ guard let self else { return }+ if !enabled {+ cancelPreview()+ }+ isEnabled = enabled+ consume(ActivityPresentationUpdate(snapshot: activityMonitor.snapshot, terminalEvents: []))}- isEnabled = enabled && advancedModeEnabled && advancedModeVerified- consume(CodexActivityPresentationUpdate(snapshot: activityMonitor.snapshot, terminalEvents: []))- }- .store(in: &cancellables)+ .store(in: &cancellables)settings.previewRequests.sink { [weak self] in self?.handlePreviewRequest($0) }@@ -123,7 +116,7 @@ final class TaskGlowController {}return}- guard isEnabled, advancedModeSettings.isOperable,+ guard isEnabled,!isSystemSleeping, !isDisplaySleeping, isSessionActive else { return }let role: TaskGlowColorRoleswitch request {@@ -167,7 +160,7 @@ final class TaskGlowController {presentation.resume(now: Date())}- private func consume(_ update: CodexActivityPresentationUpdate) {+ private func consume(_ update: ActivityPresentationUpdate) {presentation.update(snapshot: update.snapshot,terminalEvents: update.terminalEvents,@@ -283,561 +276,3 @@ final class TaskGlowController {panels.removeAll()}}--/// 所有屏幕共享同一运动周期, 新窗口直接加入当前进度-private final class TaskGlowMotionClock {- private static let standardCycleDuration = TaskGlowAnimationTiming.cycleDuration- private(set) var cycleDuration = standardCycleDuration- private var isRunning = false- private var startedAt: CFTimeInterval?-- func setAnimationSpeed(_ speed: TaskGlowAnimationSpeed) {- let duration = Self.standardCycleDuration * speed.durationMultiplier- guard duration != cycleDuration else { return }- // 改速时保留当前周期进度, 各屏幕仍共享同一出发时间- if let startedAt {- let now = CACurrentMediaTime()- self.startedAt = now - (now - startedAt) / cycleDuration * duration- }- cycleDuration = duration- }-- func setRunning(_ running: Bool) {- guard isRunning != running else { return }- isRunning = running- startedAt = nil- }-- func restart(at time: CFTimeInterval) {- isRunning = true- startedAt = time- }-- func startTime() -> CFTimeInterval {- if let startedAt {- return startedAt- }- let time = CACurrentMediaTime()- startedAt = time- return time- }-}--private final class TaskGlowPanel: NSPanel {- let indicatorView: TaskGlowView-- override var canBecomeKey: Bool {- false- }-- override var canBecomeMain: Bool {- false- }-- init(screen: NSScreen, motionClock: TaskGlowMotionClock) {- let geometry = TaskGlowGeometry(screenFrame: screen.frame)- indicatorView = TaskGlowView(geometry: geometry, scale: screen.backingScaleFactor, motionClock: motionClock)- super.init(contentRect: geometry.frame, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)- isReleasedWhenClosed = false- isOpaque = false- backgroundColor = .clear- hasShadow = false- ignoresMouseEvents = true- hidesOnDeactivate = false- isFloatingPanel = true- // iTerm2 等 App 的顶部窗口使用 statusBar + 1, 光带必须在其上方才能露出菜单栏顶边- level = NSWindow.Level(rawValue: NSWindow.Level.statusBar.rawValue + 2)- // 非激活面板跨 Space 和全屏显示, 不加入窗口循环或抢走当前 App 的焦点- collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .ignoresCycle, .stationary]- animationBehavior = .none- contentView = indicatorView- }-}--/// 移动路径贯穿屏幕, 中心部分由屏幕刘海自然遮挡-private struct TaskGlowGeometry {- let frame: NSRect- let path: CGPath-- init(screenFrame: NSRect) {- let height: CGFloat = 12- frame = NSRect(x: screenFrame.minX, y: screenFrame.maxY - height, width: screenFrame.width, height: height)- let path = CGMutablePath()- path.move(to: CGPoint(x: 0, y: height - 1.5))- path.addLine(to: CGPoint(x: screenFrame.width, y: height - 1.5))- self.path = path- }-}--private final class TaskGlowView: NSView {- private let trackLayer = CAShapeLayer()- private let lightLayer = CALayer()- private var lightSegments: [CAShapeLayer] = []- static let visibilityDuration = 0.24- private static let segmentsPerSide = 32- private static let stationaryColorAlpha: CGFloat = 0.9- private let convergencePoint = 0.5- private let motionClock: TaskGlowMotionClock- private var presentationState: TaskGlowState?- private var terminalPresentation: TaskGlowTerminalPresentation?- private var contentState: TaskGlowState?- private var transitionTask: Task<Void, Never>?- private var repeatsMotion = true- private var playback: TaskGlowPlayback?- private var glowAppearance = TaskGlowAppearance()-- init(- geometry: TaskGlowGeometry,- scale: CGFloat,- motionClock: TaskGlowMotionClock- ) {- self.motionClock = motionClock- super.init(frame: NSRect(origin: .zero, size: geometry.frame.size))- wantsLayer = true- layer?.opacity = 0- trackLayer.frame = bounds- trackLayer.path = geometry.path- trackLayer.fillColor = nil- trackLayer.lineWidth = 3- trackLayer.contentsScale = scale- trackLayer.shadowRadius = 4- trackLayer.shadowOffset = .zero- lightLayer.frame = bounds- lightLayer.shadowOpacity = 0.8- lightLayer.shadowRadius = 4- lightLayer.shadowOffset = .zero- layer?.addSublayer(trackLayer)- layer?.addSublayer(lightLayer)- // 嵌套描边让渐变沿弧长移动, 重叠区域避免相邻短线的抗锯齿接缝- for _ in 0 ..< Self.segmentsPerSide * 2 {- let segment = CAShapeLayer()- segment.frame = bounds- segment.path = geometry.path- segment.fillColor = nil- segment.lineWidth = 3- segment.contentsScale = scale- lightLayer.addSublayer(segment)- lightSegments.append(segment)- }- setAccessibilityElement(false)- }-- @available(*, unavailable)- required init?(coder _: NSCoder) {- fatalError("init(coder:) has not been implemented")- }-- private var hasArtwork: Bool {- contentState != nil && (layer?.presentation()?.opacity ?? layer?.opacity ?? 0) > 0.001- }-- var interruptionDelay: TimeInterval {- guard hasArtwork else { return 0 }- let distance: CGFloat = if !trackLayer.isHidden {- 0.5- } else {- lightSegments.map { segment in- let current = segment.presentation() ?? segment- return max(abs(current.strokeStart - convergencePoint), abs(current.strokeEnd - convergencePoint))- }.max() ?? 0- }- return max(0.001, Double(distance) * TaskGlowAnimationTiming.edgeTraversalDuration) + TaskGlowAnimationTiming.transitionGap- }-- func update(- state: TaskGlowState,- appearance glowAppearance: TaskGlowAppearance,- terminalPresentation: TaskGlowTerminalPresentation? = nil,- repeatsMotion: Bool = true,- playback: TaskGlowPlayback? = nil- ) {- let previousAppearance = applyAppearance(glowAppearance, state: state)- let changesPlayback = self.playback?.id != playback?.id- self.playback = playback- if !changesPlayback, presentationState == state, self.terminalPresentation == terminalPresentation, self.repeatsMotion == repeatsMotion {- refreshStableAppearance(state, previous: previousAppearance)- return- }- let continuesRunning = !changesPlayback && presentationState == .running && state == .running- let continuesTerminal = !changesPlayback && presentationState == state && self.terminalPresentation != nil && terminalPresentation != nil- // 同色提示延长时保留尚未完成的展开, 收尾会读取最新的淡出期限- if continuesTerminal, transitionTask != nil {- self.terminalPresentation = terminalPresentation- return- }- let terminalOpacity = continuesTerminal ? (trackLayer.presentation() ?? trackLayer).opacity : nil- let hasArtwork = hasArtwork- presentationState = state- self.terminalPresentation = terminalPresentation- self.repeatsMotion = repeatsMotion- transitionTask?.cancel()- transitionTask = nil- freezeArtwork()- if state != .hidden {- contentState = state- animateVisibility(to: Float(glowAppearance.brightness))- }-- if continuesRunning {- showStable(.running)- return- }-- if let terminalOpacity {- showStable(state, initialTerminalOpacity: terminalOpacity)- return- }-- if let terminalPresentation,- Date().timeIntervalSince(terminalPresentation.startedAt) >= terminalPresentation.entranceDuration {- showStable(state)- return- }-- transitionTask = Task { @MainActor [weak self] in- guard let self, !Task.isCancelled else { return }- do {- try await transition(to: state, hasArtwork: hasArtwork, playback: changesPlayback ? playback : nil)- transitionTask = nil- } catch {- return- }- }- }-- private func transition(to state: TaskGlowState, hasArtwork: Bool, playback: TaskGlowPlayback?) async throws {- if hasArtwork {- let duration = animateExtent(expanded: false)- // 预览切换共享收回期限, 避免不同屏幕分别开始计时- let wait = playback.map { max(0, $0.mediaStart - CACurrentMediaTime()) } ?? duration- try await Task.sleep(for: .seconds(wait))- try Task.checkCancellation()- }- if state == .hidden {- contentState = nil- animateVisibility(to: 0)- try await Task.sleep(for: .seconds(Self.visibilityDuration))- try Task.checkCancellation()- return- }- let delay = playback.map { max(0, $0.mediaStart - CACurrentMediaTime()) }- ?? (hasArtwork ? TaskGlowAnimationTiming.transitionGap : 0)- try await Task.sleep(for: .seconds(delay))- try Task.checkCancellation()- if state == .running {- showStable(.running)- fadeInMovingLight()- } else {- setCollapsedColor(state.color(in: glowAppearance))- let duration = animateExtent(expanded: true)- try await Task.sleep(for: .seconds(duration))- try Task.checkCancellation()- showStable(state)- }- }-- private func applyAppearance(_ appearance: TaskGlowAppearance, state: TaskGlowState) -> TaskGlowAppearance {- let previous = glowAppearance- glowAppearance = appearance- if previous.brightness != appearance.brightness, state != .hidden {- animateVisibility(to: Float(appearance.brightness))- }- return previous- }-- private func refreshStableAppearance(_ state: TaskGlowState, previous: TaskGlowAppearance) {- guard state != .hidden, transitionTask == nil,- previous.colors != glowAppearance.colors || previous.animationSpeed != glowAppearance.animationSpeed else { return }- showStable(state)- }-- /// 面板等待实际收回和淡出结束, 不用独立计时器提前移除仍可见的光带- func waitForDismissal() async -> Bool {- await transitionTask?.value- return !Task.isCancelled && presentationState == .hidden && transitionTask == nil- }-- func stopAnimating() {- transitionTask?.cancel()- transitionTask = nil- stopArtworkAnimations()- layer?.removeAllAnimations()- }-- private struct SegmentAppearance {- let start: CGFloat- let end: CGFloat- let color: CGColor?- }-- /// 先冻结合成器当前帧, 再移除动画, 防止中途改目标时跳到上一段的终点- private func freezeArtwork() {- let usesTrack = !trackLayer.isHidden- let track = trackLayer.presentation() ?? trackLayer- let light = lightLayer.presentation() ?? lightLayer- let opacity = usesTrack ? track.opacity : light.opacity- let appearances = lightSegments.enumerated().map { index, segment -> SegmentAppearance in- if usesTrack {- return SegmentAppearance(- start: index < Self.segmentsPerSide ? 0 : convergencePoint,- end: index < Self.segmentsPerSide ? convergencePoint : 1,- color: distributedColor(track.strokeColor)- )- }- let current = segment.presentation() ?? segment- return SegmentAppearance(start: current.strokeStart, end: current.strokeEnd, color: current.strokeColor)- }- let shadowColor = usesTrack ? track.shadowColor : light.shadowColor- CATransaction.begin()- CATransaction.setDisableActions(true)- stopArtworkAnimations()- trackLayer.isHidden = true- lightLayer.isHidden = false- lightLayer.opacity = opacity- lightLayer.shadowColor = shadowColor- for (segment, appearance) in zip(lightSegments, appearances) {- segment.strokeStart = appearance.start- segment.strokeEnd = appearance.end- segment.strokeColor = appearance.color- }- CATransaction.commit()- }-- private func showStable(_ state: TaskGlowState, initialTerminalOpacity: Float? = nil) {- CATransaction.begin()- CATransaction.setDisableActions(true)- stopArtworkAnimations()- trackLayer.strokeStart = 0- trackLayer.strokeEnd = 1- trackLayer.strokeColor = state.color(in: glowAppearance).withAlphaComponent(Self.stationaryColorAlpha).cgColor- trackLayer.shadowColor = state.color(in: glowAppearance).cgColor- trackLayer.shadowOpacity = 0.8- trackLayer.opacity = 1- trackLayer.isHidden = state == .running- lightLayer.isHidden = state != .running- lightLayer.opacity = 1- lightLayer.shadowColor = state.color(in: glowAppearance).cgColor- if state == .running {- configureMovingLight()- } else if state == .waiting {- let animation = CAKeyframeAnimation(keyPath: "opacity")- animation.values = [1, 0, 0, 1]- animation.keyTimes = [0, 0.45, 0.55, 1]- animation.duration = 1.5 * glowAppearance.animationSpeed.durationMultiplier- if !repeatsMotion, let playback {- animation.beginTime = trackLayer.convertTime(playback.mediaStart + TaskGlowAnimationTiming.expansionDuration, from: nil)- }- animation.repeatCount = repeatsMotion ? .infinity : 2- animation.timingFunctions = [- CAMediaTimingFunction(name: .easeInEaseOut),- CAMediaTimingFunction(name: .linear),- CAMediaTimingFunction(name: .easeInEaseOut)- ]- trackLayer.add(animation, forKey: "breathe")- } else if let terminalPresentation {- animateTerminalFade(terminalPresentation, initialOpacity: initialTerminalOpacity)- }- CATransaction.commit()- }-- private func animateTerminalFade(_ presentation: TaskGlowTerminalPresentation, initialOpacity: Float?) {- trackLayer.opacity = 0- let elapsed = max(0, Date().timeIntervalSince(presentation.startedAt))- guard presentation.duration > elapsed else { return }- let animation = CAKeyframeAnimation(keyPath: "opacity")- if presentation.holdDuration > 0 {- var values: [Float] = [initialOpacity ?? 1]- var times: [NSNumber] = [0]- var timingFunctions: [CAMediaTimingFunction] = []- if let initialOpacity, initialOpacity < 1 {- let recovery = min(Self.visibilityDuration, presentation.holdDuration / 2)- values.append(1)- times.append(NSNumber(value: recovery / presentation.duration))- timingFunctions.append(CAMediaTimingFunction(name: .easeInEaseOut))- }- animation.values = values + [1, 0]- animation.keyTimes = times + [NSNumber(value: presentation.holdDuration / presentation.duration), 1]- animation.timingFunctions = timingFunctions + [- CAMediaTimingFunction(name: .linear),- CAMediaTimingFunction(name: .easeInEaseOut)- ]- } else {- animation.values = [initialOpacity ?? 1, 0]- animation.keyTimes = [0, 1]- animation.timingFunctions = [CAMediaTimingFunction(name: .easeInEaseOut)]- }- animation.duration = presentation.duration- animation.beginTime = trackLayer.convertTime(CACurrentMediaTime(), from: nil) - elapsed- trackLayer.add(animation, forKey: "terminalFade")- }-- private func configureMovingLight() {- let span = min(0.336, max(0.096, 300 / bounds.width))- let startTime = motionClock.startTime()- var previousIntensity = 0.0- for (index, segment) in lightSegments.enumerated() {- let depth = index % Self.segmentsPerSide- if depth == 0 {- previousIntensity = 0- }- let position = (Double(depth) + 0.5) / Double(Self.segmentsPerSide)- let intensity = pow(sin(position * .pi / 2), 2)- let color = glowAppearance.color(for: .running)- let tint = color.blended(withFraction: pow(intensity, 8) * 0.8, of: .white) ?? color- segment.strokeColor = tint.withAlphaComponent((intensity - previousIntensity) / (1 - previousIntensity)).cgColor- previousIntensity = intensity- let tailLength = span * (1 - Double(depth) / Double(Self.segmentsPerSide))- let isLeft = index < Self.segmentsPerSide- segment.strokeStart = convergencePoint- segment.strokeEnd = convergencePoint- animateEmission(segment, tailLength: tailLength, span: span, isLeft: isLeft, startTime: startTime)- }- }-- private func animateExtent(expanded: Bool) -> TimeInterval {- let targets = lightSegments.indices.map { index in- (- start: expanded && index < Self.segmentsPerSide ? 0.0 : convergencePoint,- end: expanded && index >= Self.segmentsPerSide ? 1.0 : convergencePoint- )- }- let distance = zip(lightSegments, targets).map { segment, target in- max(abs(segment.strokeStart - target.start), abs(segment.strokeEnd - target.end))- }.max() ?? 0- let duration = max(0.001, Double(distance) * TaskGlowAnimationTiming.edgeTraversalDuration)- CATransaction.begin()- CATransaction.setDisableActions(true)- for (segment, target) in zip(lightSegments, targets) {- animateValue(segment, keyPath: "strokeStart", from: segment.strokeStart, to: target.start, duration: duration)- animateValue(segment, keyPath: "strokeEnd", from: segment.strokeEnd, to: target.end, duration: duration)- segment.strokeStart = target.start- segment.strokeEnd = target.end- }- CATransaction.commit()- return duration- }-- private func setCollapsedColor(_ color: NSColor) {- CATransaction.begin()- CATransaction.setDisableActions(true)- stopArtworkAnimations()- lightLayer.opacity = 1- lightLayer.shadowColor = color.cgColor- for segment in lightSegments {- segment.strokeStart = convergencePoint- segment.strokeEnd = convergencePoint- segment.strokeColor = distributedColor(color.withAlphaComponent(Self.stationaryColorAlpha).cgColor)- }- CATransaction.commit()- }-- private func distributedColor(_ color: CGColor?) -> CGColor? {- guard let color, let base = NSColor(cgColor: color) else { return color }- let alpha = 1 - pow(1 - base.alphaComponent, 1 / Double(Self.segmentsPerSide))- return base.withAlphaComponent(alpha).cgColor- }-- private func animateVisibility(to opacity: Float) {- guard let layer else { return }- let current = layer.presentation()?.opacity ?? layer.opacity- CATransaction.begin()- CATransaction.setDisableActions(true)- layer.removeAnimation(forKey: "visibility")- layer.opacity = opacity- animateValue(layer, keyPath: "opacity", from: current, to: opacity, duration: Self.visibilityDuration, key: "visibility")- CATransaction.commit()- }-- private func fadeInMovingLight() {- animateValue(lightLayer, keyPath: "opacity", from: Float(0), to: Float(1), duration: 0.18)- }-- private func animateValue(_ layer: CALayer, keyPath: String, from: Any?, to: Any?, duration: TimeInterval, key: String? = nil) {- let animation = CABasicAnimation(keyPath: keyPath)- animation.fromValue = from- animation.toValue = to- animation.duration = duration- animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)- layer.add(animation, forKey: key ?? keyPath)- }-- private func stopArtworkAnimations() {- trackLayer.removeAllAnimations()- lightLayer.removeAllAnimations()- for segment in lightSegments {- segment.removeAllAnimations()- }- }-- /// 各屏幕共享出发和掉头时刻, 回程拖尾完全收进中心后才开始下一轮- private func animateEmission(_ segment: CAShapeLayer, tailLength: Double, span: Double, isLeft: Bool, startTime: CFTimeInterval) {- let multiplier = glowAppearance.animationSpeed.durationMultiplier- let halfCrossing = TaskGlowAnimationTiming.travelDuration / 2 * multiplier- let offscreen = TaskGlowAnimationTiming.offscreenDuration * multiplier- let outwardDuration = halfCrossing + offscreen- let inwardDuration = halfCrossing + offscreen + TaskGlowAnimationTiming.centerRetractionDuration * multiplier- let outward = emissionAnimation(- waypoints: [(0, convergencePoint), (halfCrossing, 1), (outwardDuration, 1 + span)],- tailLength: tailLength, isLeft: isLeft- )- let inward = emissionAnimation(- waypoints: [- (0, 1 + span), (offscreen, 1),- (offscreen + halfCrossing, convergencePoint), (inwardDuration, convergencePoint - span)- ],- tailLength: tailLength, isLeft: isLeft- )- inward.beginTime = outwardDuration- // 每个单程独立缓入缓出, 保证两端掉头都平滑- let travel = CAAnimationGroup()- travel.animations = [outward, inward]- travel.duration = motionClock.cycleDuration- travel.beginTime = segment.convertTime(startTime, from: nil)- travel.repeatCount = repeatsMotion ? .infinity : 0- segment.add(travel, forKey: "emission")- }-- /// 在描边进入和离开屏幕的拐点插入关键帧, 屏幕外掉头时同时翻转拖尾方向- private func emissionAnimation(- waypoints: [(time: Double, head: Double)],- tailLength: Double,- isLeft: Bool- ) -> CAAnimationGroup {- let duration = waypoints.last!.time- var times: [Double] = []- var starts: [Double] = []- var ends: [Double] = []- for (from, to) in zip(waypoints, waypoints.dropFirst()) {- let distance = to.head - from.head- let tailOffset = distance > 0 ? -tailLength : tailLength- let crossings = [convergencePoint, 1].flatMap { boundary in- [0, tailOffset].map { (boundary - from.head - $0) / distance }- }- let progress = Array(Set([0.0, 1.0] + crossings.filter { $0 > 0 && $0 < 1 })).sorted()- for fraction in progress {- let time = from.time + (to.time - from.time) * fraction- if times.last == time {- continue- }- let head = from.head + distance * fraction- let tail = head + tailOffset- let start = min(1, max(convergencePoint, min(head, tail)))- let end = min(1, max(convergencePoint, max(head, tail)))- times.append(time)- starts.append(isLeft ? 1 - end : start)- ends.append(isLeft ? 1 - start : end)- }- }- let startAnimation = CAKeyframeAnimation(keyPath: "strokeStart")- startAnimation.keyTimes = times.map { NSNumber(value: $0 / duration) }- startAnimation.values = starts- let endAnimation = CAKeyframeAnimation(keyPath: "strokeEnd")- endAnimation.keyTimes = startAnimation.keyTimes- endAnimation.values = ends- let animation = CAAnimationGroup()- animation.animations = [startAnimation, endAnimation]- animation.duration = duration- animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)- return animation- }-}diff --git a/CodexBar/Models/ActivityAggregate.swift b/CodexBar/Models/ActivityAggregate.swiftnew file mode 100644index 0000000..920fa25--- /dev/null+++ b/CodexBar/Models/ActivityAggregate.swift@@ -0,0 +1,408 @@+import Foundation++// MARK: - 每日事件聚合++/// ID 保留期限只决定最终存储形态, 不能影响聚合结果+nonisolated enum ActivityIdentifiers {+ case retained+ case compacted+}++/// 从原始事件生成每日聚合的纯内存累加器+/// 全量和增量路径都收集 ID, 只有 finalize 时才按保留策略决定是否落盘+nonisolated struct ActivityAccumulator {+ private var aggregate: ActivityAggregate+ private var sessionIDs: Set<String> = []+ private var turnIDs: Set<String> = []++ init(+ rebuilding date: String,+ generationID: String?,+ generationStartedEmpty: Bool,+ eventCountAvailability: ActivityCountAvailability+ ) {+ aggregate = ActivityAggregate(+ date: date,+ generationID: generationID,+ generationStartedEmpty: generationStartedEmpty,+ eventCountAvailability: eventCountAvailability+ )+ }++ init(+ appending aggregate: ActivityAggregate,+ generationID: String?,+ generationStartedEmpty: Bool+ ) {+ var aggregate = aggregate+ aggregate.generationID = generationID+ aggregate.generationStartedEmpty = generationStartedEmpty+ self.aggregate = aggregate+ sessionIDs = Set(aggregate.sessionIDs ?? [])+ turnIDs = Set(aggregate.turnIDs ?? [])+ }++ mutating func record(_ event: ActivityRecord) {+ // origin 只控制实时活动过滤, 历史统计按全部业务事件事实保持原口径+ Self.increment(&aggregate.eventCount)++ switch event.eventKind {+ case .sessionStarted: Self.increment(&aggregate.sessionStartedCount)+ case .sessionEnded: Self.increment(&aggregate.sessionEndedCount)+ case .turnStarted: Self.increment(&aggregate.turnStartedCount)+ case .turnCompleted: Self.increment(&aggregate.turnCompletedCount)+ case .turnAborted: Self.increment(&aggregate.turnAbortedCount)+ case .toolStarted: Self.increment(&aggregate.toolStartedCount)+ case .toolCompleted: Self.increment(&aggregate.toolCompletedCount)+ case .approvalRequested: Self.increment(&aggregate.approvalRequestedCount)+ case .compactionStarted: Self.increment(&aggregate.compactionStartedCount)+ case .compactionCompleted: Self.increment(&aggregate.compactionCompletedCount)+ case .subagentStarted: Self.increment(&aggregate.subagentStartedCount)+ case .subagentEnded: Self.increment(&aggregate.subagentEndedCount)+ case .none: break+ }++ // 终态事件不单独构成对应的当日活跃轮次+ if event.eventKind != .sessionEnded, let sessionID = event.sessionID {+ sessionIDs.insert(sessionID)+ }+ if event.eventKind != .turnCompleted, event.eventKind != .turnAborted, let turnID = event.turnID {+ turnIDs.insert(turnID)+ }++ if let projectDisplayName = event.projectDisplayName {+ aggregate.projectCounts[projectDisplayName, default: 0] += 1+ }+ if let model = event.model {+ aggregate.modelCounts[model, default: 0] += 1+ }+ }++ func finalized(identifierStorage: ActivityIdentifiers) -> ActivityAggregate {+ var aggregate = aggregate+ switch identifierStorage {+ case .retained:+ aggregate.sessionCount = nil+ aggregate.turnCount = nil+ aggregate.sessionIDs = Self.normalizedIdentifiers(sessionIDs)+ aggregate.turnIDs = Self.normalizedIdentifiers(turnIDs)+ case .compacted:+ aggregate.sessionCount = sessionIDs.count+ aggregate.turnCount = turnIDs.count+ aggregate.sessionIDs = nil+ aggregate.turnIDs = nil+ }+ return aggregate+ }++ private static func increment(_ count: inout Int?) {+ count = (count ?? 0) + 1+ }++ private static func normalizedIdentifiers(_ identifiers: Set<String>) -> [String] {+ identifiers.sorted()+ }+}++/// 全量重放时保留每个活动计数字段原有的可用性+nonisolated struct ActivityCountAvailability {+ static let all = ActivityCountAvailability(+ includesEventCount: true,+ events: Set(ActivityEventKind.allCases)+ )++ static let legacy = ActivityCountAvailability(+ includesEventCount: true,+ events: Set(ActivityEventKind.allCases.filter { $0 != .turnAborted })+ )++ private let includesEventCount: Bool+ private let events: Set<ActivityEventKind>++ init(aggregate: ActivityAggregate) {+ includesEventCount = aggregate.eventCount != nil+ events = Set(ActivityEventKind.allCases.filter { aggregate.eventCount(for: $0) != nil })+ }++ private init(includesEventCount: Bool, events: Set<ActivityEventKind>) {+ self.includesEventCount = includesEventCount+ self.events = events+ }++ var initialEventCount: Int? {+ includesEventCount ? 0 : nil+ }++ func initialCount(for event: ActivityEventKind) -> Int? {+ events.contains(event) ? 0 : nil+ }+}++/// Aggregates/activity.jsonl 中的持久化聚合行, 同时兼容保留 ID 和只保留计数两种形态+nonisolated struct ActivityAggregate: Codable, Equatable {+ let date: String+ var generationID: String?+ var generationStartedEmpty: Bool+ var eventCount: Int?+ var sessionStartedCount: Int?+ var sessionEndedCount: Int?+ var turnStartedCount: Int?+ var turnCompletedCount: Int?+ var turnAbortedCount: Int?+ var toolStartedCount: Int?+ var toolCompletedCount: Int?+ var approvalRequestedCount: Int?+ var compactionStartedCount: Int?+ var compactionCompletedCount: Int?+ var subagentStartedCount: Int?+ var subagentEndedCount: Int?+ var sessionCount: Int?+ var turnCount: Int?+ var projectCounts: [String: Int]+ var modelCounts: [String: Int]+ var sessionIDs: [String]?+ var turnIDs: [String]?++ /// 增量路径只有在完整 ID 集合仍然存在时才能继续安全去重+ var supportsIncrementalAggregation: Bool {+ sessionCount == nil && turnCount == nil+ }++ init(+ date: String,+ generationID: String? = nil,+ generationStartedEmpty: Bool = false,+ eventCountAvailability: ActivityCountAvailability = .all+ ) {+ self.date = date+ self.generationID = generationID+ self.generationStartedEmpty = generationStartedEmpty+ eventCount = eventCountAvailability.initialEventCount+ sessionStartedCount = eventCountAvailability.initialCount(for: .sessionStarted)+ sessionEndedCount = eventCountAvailability.initialCount(for: .sessionEnded)+ turnStartedCount = eventCountAvailability.initialCount(for: .turnStarted)+ turnCompletedCount = eventCountAvailability.initialCount(for: .turnCompleted)+ turnAbortedCount = eventCountAvailability.initialCount(for: .turnAborted)+ toolStartedCount = eventCountAvailability.initialCount(for: .toolStarted)+ toolCompletedCount = eventCountAvailability.initialCount(for: .toolCompleted)+ approvalRequestedCount = eventCountAvailability.initialCount(for: .approvalRequested)+ compactionStartedCount = eventCountAvailability.initialCount(for: .compactionStarted)+ compactionCompletedCount = eventCountAvailability.initialCount(for: .compactionCompleted)+ subagentStartedCount = eventCountAvailability.initialCount(for: .subagentStarted)+ subagentEndedCount = eventCountAvailability.initialCount(for: .subagentEnded)+ sessionCount = nil+ turnCount = nil+ projectCounts = [:]+ modelCounts = [:]+ sessionIDs = []+ turnIDs = []+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ date = try container.decode(String.self, forKey: .date)+ generationID = try container.decodeIfPresent(String.self, forKey: .generationID)+ generationStartedEmpty = try container.decodeIfPresent(Bool.self, forKey: .generationStartedEmpty) ?? false+ eventCount = try container.decodeIfPresent(Int.self, forKey: .eventCount)+ sessionStartedCount = try container.decodeIfPresent(Int.self, forKey: .sessionStartedCount)+ sessionEndedCount = try container.decodeIfPresent(Int.self, forKey: .sessionEndedCount)+ turnStartedCount = try container.decodeIfPresent(Int.self, forKey: .turnStartedCount)+ turnCompletedCount = try container.decodeIfPresent(Int.self, forKey: .turnCompletedCount)+ turnAbortedCount = try container.decodeIfPresent(Int.self, forKey: .turnAbortedCount)+ toolStartedCount = try container.decodeIfPresent(Int.self, forKey: .toolStartedCount)+ toolCompletedCount = try container.decodeIfPresent(Int.self, forKey: .toolCompletedCount)+ approvalRequestedCount = try container.decodeIfPresent(Int.self, forKey: .approvalRequestedCount)+ compactionStartedCount = try container.decodeIfPresent(Int.self, forKey: .compactionStartedCount)+ compactionCompletedCount = try container.decodeIfPresent(Int.self, forKey: .compactionCompletedCount)+ subagentStartedCount = try container.decodeIfPresent(Int.self, forKey: .subagentStartedCount)+ subagentEndedCount = try container.decodeIfPresent(Int.self, forKey: .subagentEndedCount)+ sessionCount = try container.decodeIfPresent(Int.self, forKey: .sessionCount)+ turnCount = try container.decodeIfPresent(Int.self, forKey: .turnCount)+ projectCounts = try container.decodeIfPresent([String: Int].self, forKey: .projectCounts) ?? [:]+ modelCounts = try container.decodeIfPresent([String: Int].self, forKey: .modelCounts) ?? [:]+ sessionIDs = try container.decodeIfPresent([String].self, forKey: .sessionIDs)+ turnIDs = try container.decodeIfPresent([String].self, forKey: .turnIDs)+ }++ mutating func normalizeIdentifierStorage(retainsIdentifiers: Bool) {+ guard !retainsIdentifiers else {+ sessionIDs = Self.normalizedIdentifiers(sessionIDs)+ turnIDs = Self.normalizedIdentifiers(turnIDs)+ return+ }++ sessionCount = CountResolution.preferredCount(+ compactedCount: sessionCount,+ identifiers: sessionIDs+ ) ?? sessionStartedCount+ turnCount = CountResolution.preferredCount(+ compactedCount: turnCount,+ identifiers: turnIDs+ ) ?? turnCompletedCount+ sessionIDs = nil+ turnIDs = nil+ }++ var metrics: ActivityMetrics {+ syncedAggregate.metrics+ }++ static func normalized(+ aggregates: [ActivityAggregate],+ today: Date = Date(),+ calendar: Calendar = .current+ ) -> [ActivityAggregate] {+ let retentionCutoffDate = HistoryStorage.retentionCutoffDate(today: today, calendar: calendar)+ let identifierCutoffDate = HistoryStorage.identifierRetentionCutoffDate(today: today, calendar: calendar)++ return aggregates.compactMap { aggregate in+ guard let date = Self.date(from: aggregate.date), date >= retentionCutoffDate else {+ return nil+ }++ var mutableAggregate = aggregate+ mutableAggregate.normalizeIdentifierStorage(+ retainsIdentifiers: date >= identifierCutoffDate+ )+ return mutableAggregate+ }+ .sorted { $0.date < $1.date }+ }++ static func encodeJSONLines(_ aggregates: [ActivityAggregate]) throws -> Data {+ try aggregates.reduce(into: Data()) { result, aggregate in+ try result.append(aggregate.jsonLineData())+ }+ }++ func jsonLineData() throws -> Data {+ var fields = try [+ OrderedJSON.field(CodingKeys.date.rawValue, date),+ OrderedJSON.field(CodingKeys.generationID.rawValue, generationID),+ OrderedJSON.field(CodingKeys.generationStartedEmpty.rawValue, generationStartedEmpty)+ ]+ try fields.append(contentsOf: OrderedJSON.presentCountFields(eventCountFields))+ try fields.append(contentsOf: [+ OrderedJSON.field(CodingKeys.sessionCount.rawValue, sessionCount),+ OrderedJSON.field(CodingKeys.turnCount.rawValue, turnCount),+ OrderedJSON.field(CodingKeys.projectCounts.rawValue, projectCounts),+ OrderedJSON.field(CodingKeys.modelCounts.rawValue, modelCounts),+ OrderedJSON.field(CodingKeys.sessionIDs.rawValue, sessionIDs),+ OrderedJSON.field(CodingKeys.turnIDs.rawValue, turnIDs)+ ])++ return OrderedJSON.lineData(fields)+ }++ var eventCountAvailability: ActivityCountAvailability {+ ActivityCountAvailability(aggregate: self)+ }++ func eventCount(for event: ActivityEventKind) -> Int? {+ switch event {+ case .sessionStarted: sessionStartedCount+ case .sessionEnded: sessionEndedCount+ case .turnStarted: turnStartedCount+ case .turnCompleted: turnCompletedCount+ case .turnAborted: turnAbortedCount+ case .toolStarted: toolStartedCount+ case .toolCompleted: toolCompletedCount+ case .approvalRequested: approvalRequestedCount+ case .compactionStarted: compactionStartedCount+ case .compactionCompleted: compactionCompletedCount+ case .subagentStarted: subagentStartedCount+ case .subagentEnded: subagentEndedCount+ }+ }++ var syncedAggregate: SyncedActivity {+ SyncedActivity(+ date: date,+ generationID: generationID,+ eventCount: eventCount,+ sessionStartedCount: sessionStartedCount,+ sessionEndedCount: sessionEndedCount,+ turnStartedCount: turnStartedCount,+ turnCompletedCount: turnCompletedCount,+ turnAbortedCount: turnAbortedCount,+ toolStartedCount: toolStartedCount,+ toolCompletedCount: toolCompletedCount,+ approvalRequestedCount: approvalRequestedCount,+ compactionStartedCount: compactionStartedCount,+ compactionCompletedCount: compactionCompletedCount,+ subagentStartedCount: subagentStartedCount,+ subagentEndedCount: subagentEndedCount,+ sessionCount: syncedSessionCount,+ turnCount: syncedTurnCount,+ projectCounts: projectCounts,+ modelCounts: modelCounts+ )+ }++ private var syncedSessionCount: Int? {+ CountResolution.preferredCount(+ compactedCount: sessionCount,+ identifiers: sessionIDs+ )+ }++ private var syncedTurnCount: Int? {+ CountResolution.preferredCount(+ compactedCount: turnCount,+ identifiers: turnIDs+ )+ }++ private var eventCountFields: [(String, Int?)] {+ [+ (CodingKeys.eventCount.rawValue, eventCount),+ (CodingKeys.sessionStartedCount.rawValue, sessionStartedCount),+ (CodingKeys.sessionEndedCount.rawValue, sessionEndedCount),+ (CodingKeys.turnStartedCount.rawValue, turnStartedCount),+ (CodingKeys.turnCompletedCount.rawValue, turnCompletedCount),+ (CodingKeys.turnAbortedCount.rawValue, turnAbortedCount),+ (CodingKeys.toolStartedCount.rawValue, toolStartedCount),+ (CodingKeys.toolCompletedCount.rawValue, toolCompletedCount),+ (CodingKeys.approvalRequestedCount.rawValue, approvalRequestedCount),+ (CodingKeys.compactionStartedCount.rawValue, compactionStartedCount),+ (CodingKeys.compactionCompletedCount.rawValue, compactionCompletedCount),+ (CodingKeys.subagentStartedCount.rawValue, subagentStartedCount),+ (CodingKeys.subagentEndedCount.rawValue, subagentEndedCount)+ ]+ }++ private static func normalizedIdentifiers(_ identifiers: [String]?) -> [String]? {+ identifiers.map { Set($0).sorted() }+ }++ private static func date(from string: String) -> Date? {+ CodexDateFormat.dayDate(from: string)+ }++ private enum CodingKeys: String, CodingKey {+ case date+ case generationID+ case generationStartedEmpty+ case eventCount+ case sessionStartedCount+ case sessionEndedCount+ case turnStartedCount+ case turnCompletedCount+ case turnAbortedCount+ case toolStartedCount+ case toolCompletedCount+ case approvalRequestedCount+ case compactionStartedCount+ case compactionCompletedCount+ case subagentStartedCount+ case subagentEndedCount+ case sessionCount+ case turnCount+ case projectCounts+ case modelCounts+ case sessionIDs+ case turnIDs+ }+}++// 同步用的每日聚合行, 保留 Aggregates/activity.jsonl 中的计数, 不包含 sessionIds 和 turnIdsdiff --git a/CodexBar/Models/ActivityEventKind.swift b/CodexBar/Models/ActivityEventKind.swiftnew file mode 100644index 0000000..afad453--- /dev/null+++ b/CodexBar/Models/ActivityEventKind.swift@@ -0,0 +1,28 @@+import Foundation++/// app-server 事件映射到业务统计的生命周期阶段, 持久化直接使用枚举名称+nonisolated enum ActivityEventKind: String, CaseIterable, Hashable {+ case sessionStarted+ case sessionEnded+ case turnStarted+ case toolStarted+ case toolCompleted+ case approvalRequested+ case compactionStarted+ case compactionCompleted+ case turnCompleted+ case turnAborted+ case subagentStarted+ case subagentEnded++ init?(eventName: String) {+ self.init(rawValue: eventName)+ }+}++/// 审批路由的文件值直接使用成员名称, 协议解码在 app-server 边界完成+nonisolated enum ApprovalReviewer: String, Codable, CaseIterable {+ case user+ case autoReview+ case guardianSubagent+}diff --git a/CodexBar/Models/CodexActivityModels.swift b/CodexBar/Models/ActivityModels.swiftsimilarity index 79%rename from CodexBar/Models/CodexActivityModels.swiftrename to CodexBar/Models/ActivityModels.swiftindex e3c9e5e..79d7d01 100644--- a/CodexBar/Models/CodexActivityModels.swift+++ b/CodexBar/Models/ActivityModels.swift@@ -2,12 +2,12 @@ import Foundation/// 实时活动管道的共享保留窗口/// tail reader 的 bootstrap 回放范围与任务中心的历史保留期是同一个不变量, 必须相等-nonisolated enum CodexActivityRetention {+nonisolated enum ActivityRetention {static let window: TimeInterval = 24 * 60 * 60}-/// 活跃任务最近收到的 Hook 事件, 供活动卡片展示当前执行阶段-nonisolated enum CodexActivityEvent: Equatable {+/// 活跃任务最近收到的 活动事件, 供活动卡片展示当前执行阶段+nonisolated enum ActivityPhase: Equatable {case promptSubmittedcase toolStartedcase toolFinished@@ -20,16 +20,16 @@ nonisolated enum CodexActivityEvent: Equatable {}/// bootstrap 后需要向更早日期定向查找 Prompt 起点的精确任务引用-nonisolated struct CodexActivityPromptReference: Hashable {+nonisolated struct ActivityPromptReference: Hashable {let sessionID: Stringlet turnID: String}/// 正在运行或等待批准的任务摘要, 不对 UI 暴露原始会话 ID-nonisolated struct CodexActivityTaskSnapshot: Equatable, Identifiable {+nonisolated struct ActivityTaskSnapshot: Equatable, Identifiable {let id: UUIDlet isAnonymous: Bool- let latestEvent: CodexActivityEvent+ let latestEvent: ActivityPhaselet projectName: String?let modelName: String?let effort: String?@@ -37,13 +37,18 @@ nonisolated struct CodexActivityTaskSnapshot: Equatable, Identifiable {let startedAt: Date?let stateChangedAt: Datelet showsPreciseDuration: Bool- /// nil 表示 Hook 字段不足, 无法可靠统计; 0 表示已确认当前没有活跃子 Agent+ /// nil 表示 活动字段不足, 无法可靠统计; 0 表示已确认当前没有活跃子 Agentlet activeSubagentCount: Int?- var tokenUsage: CodexTokenUsage?+ var tokenUsage: TokenUsage?+ var itemType: String?++ var toolDisplayName: String? {+ toolName ?? itemType+ }}/// 最近确认结束的任务; 完成只表示一轮任务结束, 不代表执行成功-nonisolated struct CodexActivityCompletion: Equatable, Identifiable {+nonisolated struct ActivityCompletion: Equatable, Identifiable {let id: UUIDlet isAnonymous: Boollet projectName: String?@@ -51,18 +56,18 @@ nonisolated struct CodexActivityCompletion: Equatable, Identifiable {let effort: String?let completedAt: Datelet duration: TimeInterval?- var tokenUsage: CodexTokenUsage?+ var tokenUsage: TokenUsage?}/// 本轮确认的终态和快照一起发布, 历史恢复只发布快照-nonisolated struct CodexActivityPresentationUpdate {- let snapshot: CodexActivitySnapshot- let terminalEvents: [CodexActivityTerminalEvent]+nonisolated struct ActivityPresentationUpdate {+ let snapshot: ActivitySnapshot+ let terminalEvents: [ActivityTerminalEvent]}-nonisolated enum CodexActivityTerminalEvent: Equatable {- case completed(CodexActivityCompletion)- case terminated(CodexActivityTermination)+nonisolated enum ActivityTerminalEvent: Equatable {+ case completed(ActivityCompletion)+ case terminated(ActivityTermination)var id: UUID {switch self {@@ -80,7 +85,7 @@ nonisolated enum CodexActivityTerminalEvent: Equatable {}/// 最近确认终止的任务; 中断和其他终止都不会触发完成提醒-nonisolated struct CodexActivityTermination: Equatable, Identifiable {+nonisolated struct ActivityTermination: Equatable, Identifiable {let id: UUIDlet isAnonymous: Boollet projectName: String?@@ -88,53 +93,53 @@ nonisolated struct CodexActivityTermination: Equatable, Identifiable {let effort: String?let terminatedAt: Datelet duration: TimeInterval?- var tokenUsage: CodexTokenUsage?+ var tokenUsage: TokenUsage?}/// 实时越过静默阈值时交给通知服务的最小信息, 不包含原始 session 或 turn ID-nonisolated struct CodexActivityProtectionNotice: Equatable, Sendable {+nonisolated struct ProtectionNotice: Equatable, Sendable {let taskID: UUIDlet attemptID: UUIDlet projectName: String?let inactivityDurationText: String}-/// UI 只消费该快照, 不直接读取或解释 Hook 事件-nonisolated struct CodexActivitySnapshot: Equatable {- let waitingTasks: [CodexActivityTaskSnapshot]- let runningTasks: [CodexActivityTaskSnapshot]- let recentCompletions: [CodexActivityCompletion]- let recentTerminations: [CodexActivityTermination]+/// UI 只消费该快照, 不直接读取或解释 活动事件+nonisolated struct ActivitySnapshot: Equatable {+ let waitingTasks: [ActivityTaskSnapshot]+ let runningTasks: [ActivityTaskSnapshot]+ let recentCompletions: [ActivityCompletion]+ let recentTerminations: [ActivityTermination]- static let empty = CodexActivitySnapshot(+ static let empty = ActivitySnapshot(waitingTasks: [],runningTasks: [],recentCompletions: [],recentTerminations: [])- var primaryWaitingTask: CodexActivityTaskSnapshot? {+ var primaryWaitingTask: ActivityTaskSnapshot? {waitingTasks.first}- var primaryRunningTask: CodexActivityTaskSnapshot? {+ var primaryRunningTask: ActivityTaskSnapshot? {runningTasks.first}- var mostRecentCompletion: CodexActivityCompletion? {+ var mostRecentCompletion: ActivityCompletion? {recentCompletions.first}- var mostRecentTermination: CodexActivityTermination? {+ var mostRecentTermination: ActivityTermination? {recentTerminations.first}- var latestTerminalEvent: CodexActivityTerminalEvent? {+ var latestTerminalEvent: ActivityTerminalEvent? {if let termination = mostRecentTermination,mostRecentCompletion.map({ termination.terminatedAt >= $0.completedAt }) ?? true {return .terminated(termination)}- return mostRecentCompletion.map(CodexActivityTerminalEvent.completed)+ return mostRecentCompletion.map(ActivityTerminalEvent.completed)}var waitingCount: Int {@@ -197,13 +202,13 @@ nonisolated struct CodexActivitySnapshot: Equatable {/// 快照归一后的主活动状态nonisolated enum CodexPrimaryActivity: Equatable {- case waiting(CodexActivityTaskSnapshot)- case running(CodexActivityTaskSnapshot)- case completed(CodexActivityCompletion)- case terminated(CodexActivityTermination)+ case waiting(ActivityTaskSnapshot)+ case running(ActivityTaskSnapshot)+ case completed(ActivityCompletion)+ case terminated(ActivityTermination)case idle- var tokenUsage: CodexTokenUsage? {+ var tokenUsage: TokenUsage? {switch self {case let .completed(completion): completion.tokenUsagecase let .terminated(termination): termination.tokenUsage@@ -213,10 +218,10 @@ nonisolated enum CodexPrimaryActivity: Equatable {}}-/// 只有 live Hook 或 session 生命周期会发布 transition, bootstrap 永远不会触发历史通知-nonisolated enum CodexActivityTransition: Equatable {- case waitingApproval(CodexActivityTaskSnapshot)- case completed(CodexActivityCompletion)+/// 只有 live 事件 或 session 生命周期会发布 transition, bootstrap 永远不会触发历史通知+nonisolated enum ActivityTransition: Equatable {+ case waitingApproval(ActivityTaskSnapshot)+ case completed(ActivityCompletion)var isAnonymous: Bool {switch self {@@ -255,21 +260,21 @@ nonisolated enum CodexDurationFormat {}}-nonisolated enum CodexActivityDisplayFormat {+nonisolated enum ActivityDisplayFormat {static func modelMetadata(modelName: String?, effort: String?) -> String? {let components = [modelName, effort].compactMap(normalizedText)return components.isEmpty ? nil : components.joined(separator: " • ")}- static func eventText(for task: CodexActivityTaskSnapshot) -> String {+ static func eventText(for task: ActivityTaskSnapshot) -> String {switch task.latestEvent {case .promptSubmitted:String(localized: "activity.event.thinking")case .toolStarted:- task.toolName.map { String(localized: "activity.event.using-named-tool", defaultValue: "\($0)") }+ task.toolDisplayName.map { String(localized: "activity.event.using-named-tool", defaultValue: "\($0)") }?? String(localized: "activity.event.using-tool")case .toolFinished:- task.toolName.map { String(localized: "activity.event.finished-using-tool", defaultValue: "\($0)") }+ task.toolDisplayName.map { String(localized: "activity.event.finished-using-tool", defaultValue: "\($0)") }?? String(localized: "activity.event.tool-completed")case .compactionStarted:String(localized: "activity.event.compacting-context")@@ -312,17 +317,17 @@ nonisolated enum CodexActivityDisplayFormat {/// 活动卡片和任务中心共用同一份文案片段static func waitingDetailComponents(- for task: CodexActivityTaskSnapshot,+ for task: ActivityTaskSnapshot,now: Date) -> [String] {[- task.toolName ?? String(localized: "activity.event.waiting-next-action"),+ task.toolDisplayName ?? String(localized: "activity.event.waiting-next-action"),waitingDurationFragment(since: task.stateChangedAt, now: now)]}static func runningDetailComponents(- for task: CodexActivityTaskSnapshot,+ for task: ActivityTaskSnapshot,now: Date) -> [String] {let duration = if task.showsPreciseDuration, let startedAt = task.startedAt {diff --git a/CodexBar/Models/ActivityRecord.swift b/CodexBar/Models/ActivityRecord.swiftnew file mode 100644index 0000000..668ceab--- /dev/null+++ b/CodexBar/Models/ActivityRecord.swift@@ -0,0 +1,168 @@+import Foundation++// MARK: - 归一化活动事件++/// 事件来源的本地归一化分类, 不保留原始 source 内容+nonisolated enum ActivityOrigin: String, Codable, Sendable {+ case main+ case autoReview+ case auxiliary+ case unknown++ init(from decoder: Decoder) throws {+ let container = try decoder.singleValueContainer()+ let rawValue = try? container.decode(String.self)+ self = rawValue.flatMap(Self.init(rawValue:)) ?? .unknown+ }+}++/// app-server 的最小统计事件, 在边界归一化来源与可选元数据+nonisolated struct ActivityRecord: Codable, Equatable {+ let id: String?+ let timestamp: Date+ let name: String+ let origin: ActivityOrigin+ let cwd: String?+ let tool: String?+ let model: String?+ let effort: String?+ let approvalReviewer: ApprovalReviewer?+ let sessionID: String?+ let turnID: String?+ let agentID: String?+ var source: AppServerEventSource?++ init(+ timestamp: Date,+ name: String,+ origin: ActivityOrigin,+ cwd: String?,+ tool: String?,+ model: String?,+ effort: String?,+ approvalReviewer: ApprovalReviewer?,+ sessionID: String?,+ turnID: String?,+ agentID: String?,+ id: String? = nil+ ) {+ self.id = id+ self.timestamp = timestamp+ self.name = name+ self.origin = Self.resolvedOrigin(origin, model: model)+ self.cwd = cwd+ self.tool = tool+ self.model = model+ self.effort = effort+ self.approvalReviewer = approvalReviewer+ self.sessionID = sessionID+ self.turnID = turnID+ self.agentID = agentID+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ let timestamp = try container.decode(Date.self, forKey: .timestamp)+ let phase = try container.decode(String.self, forKey: .name)+ guard let event = ActivityEventKind(rawValue: phase) else {+ throw DecodingError.dataCorruptedError(forKey: .name, in: container, debugDescription: "Unknown activity phase")+ }+ let name = event.rawValue+ source = try container.decodeIfPresent(AppServerEventSource.self, forKey: .source)++ id = try container.decodeIfPresent(String.self, forKey: .id)+ let decodedOrigin = (try? container.decode(ActivityOrigin.self, forKey: .origin)) ?? .unknown+ let decodedModel = Self.string(from: container, key: .model)++ self.timestamp = timestamp+ self.name = name+ origin = Self.resolvedOrigin(decodedOrigin, model: decodedModel)+ cwd = Self.string(from: container, key: .cwd)+ tool = Self.string(from: container, key: .tool)+ model = decodedModel+ effort = Self.string(from: container, key: .effort)+ approvalReviewer = try? container.decode(+ ApprovalReviewer.self,+ forKey: .approvalReviewer+ )+ sessionID = Self.string(from: container, key: .sessionID)+ turnID = Self.string(from: container, key: .turnID)+ agentID = Self.string(from: container, key: .agentID)+ }++ var eventKind: ActivityEventKind? {+ ActivityEventKind(eventName: name)+ }++ var projectDisplayName: String? {+ guard let cwd, !cwd.isEmpty else {+ return nil+ }++ let url = URL(fileURLWithPath: cwd).standardizedFileURL+ let lastComponent = url.lastPathComponent+ return lastComponent.isEmpty ? cwd : lastComponent+ }++ private static func string(+ from container: KeyedDecodingContainer<CodingKeys>,+ key: CodingKeys+ ) -> String? {+ guard let value = try? container.decode(String.self, forKey: key) else {+ return nil+ }++ let trimmedValue = value.trimmingCharacters(in: .whitespacesAndNewlines)+ return trimmedValue.isEmpty ? nil : trimmedValue+ }++ /// 来源元数据缺失时, 专用审核模型只作为未知来源的保守后备+ private static func resolvedOrigin(+ _ origin: ActivityOrigin,+ model: String?+ ) -> ActivityOrigin {+ guard origin == .unknown,+ model == autoReviewModelName else {+ return origin+ }+ return .autoReview+ }++ func encode(to encoder: Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encodeIfPresent(id, forKey: .id)+ try container.encode(timestamp, forKey: .timestamp)+ guard let eventKind else {+ throw EncodingError.invalidValue(name, .init(codingPath: encoder.codingPath, debugDescription: "Unknown activity phase"))+ }+ try container.encode(eventKind.rawValue, forKey: .name)+ try container.encode(origin, forKey: .origin)+ try container.encodeIfPresent(cwd, forKey: .cwd)+ try container.encodeIfPresent(tool, forKey: .tool)+ try container.encodeIfPresent(model, forKey: .model)+ try container.encodeIfPresent(effort, forKey: .effort)+ try container.encodeIfPresent(approvalReviewer, forKey: .approvalReviewer)+ try container.encodeIfPresent(sessionID, forKey: .sessionID)+ try container.encodeIfPresent(turnID, forKey: .turnID)+ try container.encodeIfPresent(agentID, forKey: .agentID)+ try container.encodeIfPresent(source, forKey: .source)+ }++ private enum CodingKeys: String, CodingKey {+ case id+ case timestamp+ case name+ case origin+ case cwd+ case tool+ case model+ case effort+ case approvalReviewer+ case sessionID+ case turnID+ case agentID+ case source+ }++ private static let autoReviewModelName = "codex-auto-review"+}diff --git a/CodexBar/Models/ActivitySyncRecord.swift b/CodexBar/Models/ActivitySyncRecord.swiftnew file mode 100644index 0000000..a5dac4c--- /dev/null+++ b/CodexBar/Models/ActivitySyncRecord.swift@@ -0,0 +1,200 @@+import Foundation++nonisolated struct SyncedActivity: Codable, Equatable {+ let date: String+ var generationID: String?+ var eventCount: Int?+ var sessionStartedCount: Int?+ var sessionEndedCount: Int?+ var turnStartedCount: Int?+ var turnCompletedCount: Int?+ var turnAbortedCount: Int?+ var toolStartedCount: Int?+ var toolCompletedCount: Int?+ var approvalRequestedCount: Int?+ var compactionStartedCount: Int?+ var compactionCompletedCount: Int?+ var subagentStartedCount: Int?+ var subagentEndedCount: Int?+ var sessionCount: Int?+ var turnCount: Int?+ var projectCounts: [String: Int]+ var modelCounts: [String: Int]++ var metrics: ActivityMetrics {+ ActivityMetrics(+ startDate: date,+ sessionCount: CountResolution.resolvedCount(+ compactedCount: sessionCount,+ fallback: sessionStartedCount ?? 0+ ),+ turnCount: CountResolution.resolvedCount(+ compactedCount: turnCount,+ fallback: turnCompletedCount ?? 0+ ),+ toolStartedCount: toolStartedCount ?? 0,+ toolCompletedCount: toolCompletedCount ?? 0,+ approvalRequestedCount: approvalRequestedCount ?? 0,+ compactionStartedCount: compactionStartedCount ?? 0,+ compactionCompletedCount: compactionCompletedCount ?? 0,+ subagentStartedCount: subagentStartedCount ?? 0,+ subagentEndedCount: subagentEndedCount ?? 0,+ modelCounts: modelCounts,+ turnAbortedCount: turnAbortedCount+ )+ }++ func jsonLineData() throws -> Data {+ var fields = try [+ OrderedJSON.field(CodingKeys.date.rawValue, date),+ OrderedJSON.field(CodingKeys.generationID.rawValue, generationID)+ ]+ try fields.append(contentsOf: OrderedJSON.presentCountFields(eventCountFields))+ try fields.append(contentsOf: [+ OrderedJSON.field(CodingKeys.sessionCount.rawValue, sessionCount),+ OrderedJSON.field(CodingKeys.turnCount.rawValue, turnCount),+ OrderedJSON.field(CodingKeys.projectCounts.rawValue, projectCounts),+ OrderedJSON.field(CodingKeys.modelCounts.rawValue, modelCounts)+ ])++ return OrderedJSON.lineData(fields)+ }++ private var eventCountFields: [(String, Int?)] {+ [+ (CodingKeys.eventCount.rawValue, eventCount),+ (CodingKeys.sessionStartedCount.rawValue, sessionStartedCount),+ (CodingKeys.sessionEndedCount.rawValue, sessionEndedCount),+ (CodingKeys.turnStartedCount.rawValue, turnStartedCount),+ (CodingKeys.turnCompletedCount.rawValue, turnCompletedCount),+ (CodingKeys.turnAbortedCount.rawValue, turnAbortedCount),+ (CodingKeys.toolStartedCount.rawValue, toolStartedCount),+ (CodingKeys.toolCompletedCount.rawValue, toolCompletedCount),+ (CodingKeys.approvalRequestedCount.rawValue, approvalRequestedCount),+ (CodingKeys.compactionStartedCount.rawValue, compactionStartedCount),+ (CodingKeys.compactionCompletedCount.rawValue, compactionCompletedCount),+ (CodingKeys.subagentStartedCount.rawValue, subagentStartedCount),+ (CodingKeys.subagentEndedCount.rawValue, subagentEndedCount)+ ]+ }++ func requiredGenerationID() throws -> String {+ guard let generationID, !generationID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ throw ActivitySyncError.missingGeneration(date)+ }+ return generationID+ }++ func matchesRemoteSource(_ remote: SyncedActivity) -> Bool {+ generationID != nil && generationID == remote.generationID+ }++ private enum CodingKeys: String, CodingKey {+ case date+ case generationID+ case eventCount+ case sessionStartedCount+ case sessionEndedCount+ case turnStartedCount+ case turnCompletedCount+ case turnAbortedCount+ case toolStartedCount+ case toolCompletedCount+ case approvalRequestedCount+ case compactionStartedCount+ case compactionCompletedCount+ case subagentStartedCount+ case subagentEndedCount+ case sessionCount+ case turnCount+ case projectCounts+ case modelCounts+ }+}++extension SyncedActivity {+ nonisolated init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ date = try container.decode(String.self, forKey: .date)+ generationID = try container.decodeIfPresent(String.self, forKey: .generationID)+ eventCount = try container.decodeIfPresent(Int.self, forKey: .eventCount)+ sessionStartedCount = try container.decodeIfPresent(Int.self, forKey: .sessionStartedCount)+ sessionEndedCount = try container.decodeIfPresent(Int.self, forKey: .sessionEndedCount)+ turnStartedCount = try container.decodeIfPresent(Int.self, forKey: .turnStartedCount)+ turnCompletedCount = try container.decodeIfPresent(Int.self, forKey: .turnCompletedCount)+ turnAbortedCount = try container.decodeIfPresent(Int.self, forKey: .turnAbortedCount)+ toolStartedCount = try container.decodeIfPresent(Int.self, forKey: .toolStartedCount)+ toolCompletedCount = try container.decodeIfPresent(Int.self, forKey: .toolCompletedCount)+ approvalRequestedCount = try container.decodeIfPresent(Int.self, forKey: .approvalRequestedCount)+ compactionStartedCount = try container.decodeIfPresent(Int.self, forKey: .compactionStartedCount)+ compactionCompletedCount = try container.decodeIfPresent(Int.self, forKey: .compactionCompletedCount)+ subagentStartedCount = try container.decodeIfPresent(Int.self, forKey: .subagentStartedCount)+ subagentEndedCount = try container.decodeIfPresent(Int.self, forKey: .subagentEndedCount)+ sessionCount = try container.decodeIfPresent(Int.self, forKey: .sessionCount)+ turnCount = try container.decodeIfPresent(Int.self, forKey: .turnCount)+ projectCounts = try container.decodeIfPresent([String: Int].self, forKey: .projectCounts) ?? [:]+ modelCounts = try container.decodeIfPresent([String: Int].self, forKey: .modelCounts) ?? [:]+ }+}++nonisolated struct ActivitySyncRecord: Codable, Equatable, Identifiable {+ let deviceID: String+ let daily: SyncedActivity+ var updatedAt: Date?+ let recordName: String++ var id: String {+ recordName+ }++ var date: String {+ daily.date+ }++ init(deviceID: String, daily: SyncedActivity, updatedAt: Date? = nil, recordName: String) throws {+ let generation = try daily.requiredGenerationID()+ guard recordName == Self.recordName(deviceID: deviceID, date: daily.date, generation: generation) else {+ throw ActivitySyncError.invalidRecordIdentity+ }+ self.deviceID = deviceID+ self.daily = daily+ self.updatedAt = updatedAt+ self.recordName = recordName+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ do {+ try self.init(+ deviceID: container.decode(String.self, forKey: .deviceID),+ daily: container.decode(SyncedActivity.self, forKey: .daily),+ updatedAt: container.decodeIfPresent(Date.self, forKey: .updatedAt),+ recordName: container.decode(String.self, forKey: .recordName)+ )+ } catch let error as ActivitySyncError {+ throw DecodingError.dataCorrupted(.init(+ codingPath: decoder.codingPath,+ debugDescription: "Invalid activity record identity",+ underlyingError: error+ ))+ }+ }++ static func recordName(deviceID: String, date: String, generation: String) -> String {+ "\(deviceID)_\(date)_\(generation)"+ }+}++nonisolated enum ActivitySyncError: LocalizedError {+ case missingGeneration(String)+ case invalidRecordIdentity++ var errorDescription: String? {+ switch self {+ case let .missingGeneration(date):+ String(localized: "sync.error.activity-generation", defaultValue: "Activity history for \(date) has no valid generation and cannot be synchronized")+ case .invalidRecordIdentity:+ String(localized: "sync.error.activity-identity", defaultValue: "The activity record identity does not match its device, date and generation")+ }+ }+}diff --git a/CodexBar/Models/AppServerEventRecord.swift b/CodexBar/Models/AppServerEventRecord.swiftnew file mode 100644index 0000000..4d940a4--- /dev/null+++ b/CodexBar/Models/AppServerEventRecord.swift@@ -0,0 +1,145 @@+import Foundation++/// 白名单协议元数据, 原始线程身份与业务统计归属分开保存+nonisolated struct AppServerEventSource: Codable, Equatable {+ let method: String+ let threadID: String+ var turnID: String?+ var parentThreadID: String?+ var rootThreadID: String?+ var rootTurnID: String?+ var itemID: String?+ var itemType: String?+ var itemStatus: String?+ var agentThreadID: String?+ var itemKind: String?+ var requestID: String?+ var reviewID: String?+ var turnStatus: String?+ var turnStartedAt: Date?+ var turnCompletedAt: Date?+ var durationMs: Double?+}++/// 统一日志的版本与类型边界, Token 快照不会作为活动进入计数+nonisolated struct AppServerEventRecord: Codable, Equatable {+ enum Kind: String, Codable { case activity, tokenSnapshot, tokenObservation }++ static let currentVersion = 2+ let version: Int+ let kind: Kind+ let recordedAt: Date+ let source: AppServerEventSource?+ private let activityPayload: ActivityRecord?+ let token: TokenTurn?+ let observation: TokenObservation?++ var deduplicationID: String? {+ if let id = activityPayload?.id {+ return "activity:" + id+ }+ if let observation {+ return "token:\(observation.turn.id):\(observation.streamID):\(observation.sequence)"+ }+ return nil+ }++ var activity: ActivityRecord? {+ guard var activity = activityPayload else { return nil }+ activity.source = source+ return activity+ }++ init(activity: ActivityRecord, recordedAt: Date = Date()) {+ version = Self.currentVersion+ kind = .activity+ self.recordedAt = recordedAt+ source = activity.source+ var payload = activity+ payload.source = nil+ activityPayload = payload+ token = nil+ observation = nil+ }++ init(token: TokenTurn, source: AppServerEventSource? = nil, recordedAt: Date) {+ version = Self.currentVersion+ kind = .tokenSnapshot+ self.recordedAt = recordedAt+ self.source = source+ activityPayload = nil+ self.token = token+ observation = nil+ }++ init(observation: TokenObservation, recordedAt: Date) {+ version = Self.currentVersion+ kind = .tokenObservation+ self.recordedAt = recordedAt+ source = nil+ activityPayload = nil+ token = nil+ self.observation = observation+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ version = try container.decode(Int.self, forKey: .version)+ guard version == Self.currentVersion else {+ throw DecodingError.dataCorruptedError(forKey: .version, in: container, debugDescription: "Unsupported event version")+ }+ kind = try container.decode(Kind.self, forKey: .kind)+ recordedAt = try container.decode(Date.self, forKey: .recordedAt)+ source = try container.decodeIfPresent(AppServerEventSource.self, forKey: .source)+ observation = try container.decodeIfPresent(TokenObservation.self, forKey: .observation)+ switch kind {+ case .activity:+ activityPayload = try container.decode(ActivityRecord.self, forKey: .activityPayload)+ token = nil+ guard !container.contains(.token), observation == nil else {+ throw DecodingError.dataCorruptedError(forKey: .token, in: container, debugDescription: "Activity cannot contain tokens")+ }+ case .tokenObservation:+ activityPayload = nil+ token = nil+ guard observation != nil, !container.contains(.token), !container.contains(.activityPayload) else {+ throw DecodingError.dataCorruptedError(forKey: .observation, in: container, debugDescription: "Missing observation")+ }+ case .tokenSnapshot:+ token = try container.decode(TokenTurn.self, forKey: .token)+ activityPayload = nil+ guard !container.contains(.activityPayload), observation == nil, token?.usage?.isValid != false else {+ throw DecodingError.dataCorruptedError(forKey: .token, in: container, debugDescription: "Invalid token snapshot")+ }+ }+ }++ func jsonLineData() throws -> Data {+ try Self.encoder.encode(self) + Data([JSONLines.newlineByte])+ }++ static func decode(from data: Data) throws -> Self {+ try decode(Self.self, from: data)+ }++ static func decode<Value: Decodable>(_ type: Value.Type, from data: Data) throws -> Value {+ try decoder.decode(type, from: data)+ }++ static func encode(_ value: some Encodable) throws -> Data {+ try encoder.encode(value)+ }++ private static let encoder = JSONLines.stableEncoder+ private static let decoder = JSONLines.decoder++ private enum CodingKeys: String, CodingKey {+ case version+ case kind+ case recordedAt+ case source+ case activityPayload+ case token+ case observation+ }+}diff --git a/CodexBar/Models/AppServerLogEntry.swift b/CodexBar/Models/AppServerLogEntry.swiftnew file mode 100644index 0000000..59d993f--- /dev/null+++ b/CodexBar/Models/AppServerLogEntry.swift@@ -0,0 +1,105 @@+import Foundation++/// JSON-RPC 交互日志: 带 id 的请求先记录为进行+/// 响应或错误到达后回填到同一条+/// 无需配对的消息单独记录, request 和 detail 分别保留发送与接收内容+nonisolated struct AppServerLogEntry: Identifiable, Equatable, Codable, Sendable {+ enum Source: String, Codable, Sendable {+ case request+ case sent+ case received+ case connection+ case local+ }++ enum Status: String, Codable, Sendable {+ case pending+ case success+ case failure+ case information+ }++ var position: Int64 = 0+ let id: UUID+ var connection: String?+ let requestedAt: Date+ var respondedAt: Date?+ let source: Source+ var status: Status+ let method: String?+ var request: String?+ var detail: String?+ var requestOriginalBytes: Int?+ var detailOriginalBytes: Int?++ func bounded(to limit: Int) -> Self {+ var result = self+ if let request, request.utf8.count > limit {+ result.requestOriginalBytes = requestOriginalBytes ?? request.utf8.count+ result.request = Self.truncated(request, limit: limit)+ }+ if let detail, detail.utf8.count > limit {+ result.detailOriginalBytes = detailOriginalBytes ?? detail.utf8.count+ result.detail = Self.truncated(detail, limit: limit)+ }+ return result+ }++ static func truncated(_ text: String, limit: Int) -> String {+ guard text.utf8.count > limit else { return text }+ let marker = "\n[Truncated, original: \(text.utf8.count) bytes]"+ var prefix = Array(text.utf8.prefix(max(0, limit - marker.utf8.count)))+ while String(bytes: prefix, encoding: .utf8) == nil {+ prefix.removeLast()+ }+ return (String(bytes: prefix, encoding: .utf8) ?? "") + marker+ }++ var isReceived: Bool {+ source == .received+ }++ var isConnectionEvent: Bool {+ source == .connection+ }++ static let summaryPreviewLength = 160+ static let expandedInlinePreviewLength = 260++ static func preview(_ text: String, limit: Int) -> String {+ guard limit > 0,+ let endIndex = text.index(text.startIndex, offsetBy: limit, limitedBy: text.endIndex),+ endIndex < text.endIndex else {+ return text+ }++ return String(text[..<endIndex]) + "..."+ }++ static func singleLinePreview(_ text: String, limit: Int) -> String {+ let text = displayJSON(text) ?? text+ let firstLine = text.components(separatedBy: .newlines).first ?? ""+ let normalizedText = firstLine+ .components(separatedBy: .whitespaces)+ .filter { !$0.isEmpty }+ .joined(separator: " ")+ let displayText = preview(normalizedText, limit: limit)++ guard firstLine != text, !displayText.hasSuffix("...") else {+ return displayText+ }++ return displayText + "..."+ }++ /// 展示时统一 JSON 格式, 已保存的原文仍用于复制与持久化+ private static func displayJSON(_ text: String) -> String? {+ guard let object = try? JSONSerialization.jsonObject(with: Data(text.utf8), options: .fragmentsAllowed),+ let data = try? JSONSerialization.data(withJSONObject: object, options: [.fragmentsAllowed, .sortedKeys, .withoutEscapingSlashes]) else {+ return nil+ }+ return String(data: data, encoding: .utf8)+ }+}++// 窗口只加载已浏览的历史, 新增记录和响应更新按数据库 revision 增量合并diff --git a/CodexBar/Models/CodexDateFormat.swift b/CodexBar/Models/CodexDateFormat.swiftindex abc286b..2d01ad4 100644--- a/CodexBar/Models/CodexDateFormat.swift+++ b/CodexBar/Models/CodexDateFormat.swift@@ -44,7 +44,7 @@ nonisolated enum CodexDateFormat {return date}- /// yyyy-MM-dd HH:mm:ss.SSS, Hook 原始事件写入本机时间字符串+ /// yyyy-MM-dd HH:mm:ss.SSS, 归一化活动事件写入本机时间字符串static func localTimestampString(from date: Date) -> String {localTimestampFormatter.string(from: date)}diff --git a/CodexBar/Models/CodexHookEvent.swift b/CodexBar/Models/CodexHookEvent.swiftdeleted file mode 100644index 1000785..0000000--- a/CodexBar/Models/CodexHookEvent.swift+++ /dev/null@@ -1,51 +0,0 @@-import Foundation--/// Codex Hook 事件名的统一枚举, 负责在 hooks.json 与 app-server 命名间转换-nonisolated enum CodexHookEvent: String, CaseIterable, Hashable {- case sessionStart = "SessionStart"- case sessionEnd = "SessionEnd"- case userPromptSubmit = "UserPromptSubmit"- case preToolUse = "PreToolUse"- case postToolUse = "PostToolUse"- case permissionRequest = "PermissionRequest"- case preCompact = "PreCompact"- case postCompact = "PostCompact"- case stop = "Stop"- case interrupt = "Interrupt"- case subagentStart = "SubagentStart"- case subagentStop = "SubagentStop"-- init?(eventName: String) {- let normalizedName = Self.normalizedName(eventName)- guard let event = Self.allCases.first(where: { $0.normalizedName == normalizedName }) else {- return nil- }- self = event- }-- var configName: String {- rawValue- }-- var appServerName: String {- rawValue.prefix(1).lowercased() + rawValue.dropFirst()- }-- private var normalizedName: String {- Self.normalizedName(rawValue)- }-- private static func normalizedName(_ eventName: String) -> String {- eventName- .replacingOccurrences(of: "_", with: "")- .replacingOccurrences(of: "-", with: "")- .lowercased()- }-}--/// Codex turn 的审批路由; 只有 user 表示 PermissionRequest 会停在用户 UI-nonisolated enum CodexApprovalReviewer: String, Codable {- case user- case autoReview = "auto_review"- case guardianSubagent = "guardian_subagent"-}diff --git a/CodexBar/Models/CodexProxyConfiguration.swift b/CodexBar/Models/CodexProxyConfiguration.swiftdeleted file mode 100644index 3b190f8..0000000--- a/CodexBar/Models/CodexProxyConfiguration.swift+++ /dev/null@@ -1,152 +0,0 @@-import Darwin-import Foundation--nonisolated struct CodexProxyConfiguration: Codable, Equatable, Sendable {- enum Transport: String, Codable, CaseIterable, Sendable {- case http- case https- }-- enum InputField: Hashable {- case host- case port- case username- }-- enum ValidationKind {- case required- case format- }-- struct ValidationIssue: Equatable {- let field: InputField- let kind: ValidationKind-- var title: String {- switch (field, kind) {- case (.host, .required): String(localized: "proxy.validation.host.required")- case (.port, .required): String(localized: "proxy.validation.port.required")- case (.username, .required): String(localized: "proxy.validation.username.required")- case (.host, .format): String(localized: "proxy.validation.host.invalid")- case (.port, .format): String(localized: "proxy.validation.port.invalid")- case (.username, .format): String(localized: "proxy.validation.username.invalid")- }- }- }-- var isEnabled = false- var transport = Transport.http- var host = ""- var port = ""- var usesAuthentication = false- var username = ""-- var validationIssues: [ValidationIssue] {- var issues: [ValidationIssue] = []- if host.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- issues.append(ValidationIssue(field: .host, kind: .required))- }- if port.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- issues.append(ValidationIssue(field: .port, kind: .required))- }- if usesAuthentication, username.isEmpty {- issues.append(ValidationIssue(field: .username, kind: .required))- }- guard issues.isEmpty else { return issues }- if (try? normalizedHost()) == nil {- issues.append(ValidationIssue(field: .host, kind: .format))- }- if validPort == nil {- issues.append(ValidationIssue(field: .port, kind: .format))- }- if !isUsernameValid {- issues.append(ValidationIssue(field: .username, kind: .format))- }- return issues- }-- func validated() throws -> Self {- if let issue = validationIssues.first {- throw issue.field == .username ? CodexProxyError.missingUsername : CodexProxyError.invalidAddress- }- var result = self- result.host = try normalizedHost()- guard let portNumber = validPort else { throw CodexProxyError.invalidAddress }- result.port = String(portNumber)- return result- }-- private var validPort: Int? {- guard let number = Int(port.trimmingCharacters(in: .whitespacesAndNewlines)),- (1 ... 65535).contains(number) else { return nil }- return number- }-- private var isUsernameValid: Bool {- !usesAuthentication || (!username.isEmpty && !username.contains(":")- && !username.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }))- }-- private func normalizedHost() throws -> String {- var host = host.trimmingCharacters(in: .whitespacesAndNewlines)- guard !host.isEmpty,- !host.contains(where: \.isWhitespace),- !host.contains(where: { "/?#@\\%".contains($0) }) else {- throw CodexProxyError.invalidAddress- }- if host.contains(":") || host.contains("[") {- let address = host.hasPrefix("[") && host.hasSuffix("]")- ? String(host.dropFirst().dropLast()) : host- var bytes = in6_addr()- guard inet_pton(AF_INET6, address, &bytes) == 1 else { throw CodexProxyError.invalidAddress }- host = "[\(address)]"- } else {- let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: ".-"))- guard host.unicodeScalars.allSatisfy({ allowed.contains($0) }) else {- throw CodexProxyError.invalidAddress- }- }- guard let components = URLComponents(string: "\(transport.rawValue)://\(host):1"),- components.host != nil, components.port == 1,- components.user == nil, components.password == nil,- components.path.isEmpty, components.url != nil else {- throw CodexProxyError.invalidAddress- }- return host- }-- func environment(overriding base: [String: String], password: String) throws -> [String: String] {- guard isEnabled else { return base }- let configuration = try validated()- var components = URLComponents(string: "\(transport.rawValue)://\(configuration.host):\(configuration.port)")!- if usesAuthentication {- let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~"))- components.percentEncodedUser = username.addingPercentEncoding(withAllowedCharacters: allowed)- components.percentEncodedPassword = password.addingPercentEncoding(withAllowedCharacters: allowed)- }- guard let address = components.url?.absoluteString else { throw CodexProxyError.invalidAddress }- var environment = base- // 协议专用变量优先于系统设置, 清理继承的旁路和 WebSocket 变量以保持单一出口- for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "WS_PROXY", "WSS_PROXY"] {- environment[key] = address- environment[key.lowercased()] = address- }- environment["NO_PROXY"] = "localhost,127.0.0.1,::1"- environment["no_proxy"] = environment["NO_PROXY"]- return environment- }-}--nonisolated enum CodexProxyError: LocalizedError {- case invalidAddress- case missingUsername- case invalidStoredConfiguration-- var errorDescription: String? {- switch self {- case .invalidAddress: String(localized: "proxy.error.invalid-endpoint")- case .missingUsername: String(localized: "proxy.error.invalid-username")- case .invalidStoredConfiguration: String(localized: "proxy.error.configuration-unreadable")- }- }-}diff --git a/CodexBar/Models/CodexStatusError.swift b/CodexBar/Models/CodexStatusError.swiftindex dcb88a9..df5ba50 100644--- a/CodexBar/Models/CodexStatusError.swift+++ b/CodexBar/Models/CodexStatusError.swift@@ -2,31 +2,25 @@ import Foundation/// UI 和日志共用的 app-server 错误分类, 保留可重试/需重连判断nonisolated enum CodexStatusError: LocalizedError {- case executableNotFound- case sourceUnavailable(CodexCLIExecutableSource)case serverTimeoutcase serverConnectionClosedcase invalidServerResponsecase invalidResponsePayload- case serverError(String)+ case serverError(AppServerRPCError)case unsupportedMethodcase unsupportedVersion(minimum: String)case notLoggedInvar errorDescription: String? {switch self {- case .executableNotFound:- String(localized: "codex-status.cli.error.executable-not-found")- case let .sourceUnavailable(source):- "\(source.displayName): \(String(localized: "codex-cli.source.status.unavailable"))"case .serverTimeout:String(localized: "codex-status.app-server.error.server-timeout")case .serverConnectionClosed:String(localized: "codex-status.app-server.error.connection-closed")case .invalidServerResponse, .invalidResponsePayload:String(localized: "codex-status.app-server.error.invalid-response")- case let .serverError(message):- message+ case let .serverError(error):+ error.messagecase .unsupportedMethod:String(localized: "codex-status.app-server.error.unsupported-method")case let .unsupportedVersion(minimum):@@ -52,7 +46,7 @@ nonisolated enum CodexStatusError: LocalizedError {case .unsupportedMethod:truedefault:- serverErrorMessageContains("Invalid request: unknown variant")+ serverErrorCode == -32601 || serverErrorMessageContains("Invalid request: unknown variant")}}@@ -61,7 +55,13 @@ nonisolated enum CodexStatusError: LocalizedError {return false}- return !isAuthenticationRequired && !isUnsupportedMethod+ return !isAuthenticationRequired && !isUnsupportedMethod && !isProtocolOrParameterFailure+ }++ /// 服务端也用 -32600 表示线程历史不可用, 仅匹配当前线程的已知错误+ func isMissingRollout(for threadID: String) -> Bool {+ guard case let .serverError(error) = self else { return false }+ return error.code == -32600 && error.message == "no rollout found for thread id \(threadID)"}/// 参数或协议形状不正确时继续用同一请求重试不会恢复@@ -70,7 +70,7 @@ nonisolated enum CodexStatusError: LocalizedError {case .invalidResponsePayload, .unsupportedMethod, .unsupportedVersion:truecase .serverError:- serverErrorMessageContains("invalid params")+ [-32700, -32600, -32602].contains(serverErrorCode ?? 0) || serverErrorMessageContains("invalid params")|| serverErrorMessageContains("invalid request")|| serverErrorMessageContains("missing field")|| serverErrorMessageContains("unknown field")@@ -90,11 +90,16 @@ nonisolated enum CodexStatusError: LocalizedError {}}+ private var serverErrorCode: Int? {+ guard case let .serverError(error) = self else { return nil }+ return error.code+ }+private func serverErrorMessageContains(_ keyword: String) -> Bool {- guard case let .serverError(message) = self else {+ guard case let .serverError(error) = self else {return false}- return message.range(of: keyword, options: .caseInsensitive) != nil+ return error.message.range(of: keyword, options: .caseInsensitive) != nil}}diff --git a/CodexBar/Models/CodexTokenHistory.swift b/CodexBar/Models/CodexTokenHistory.swiftdeleted file mode 100644index f47242f..0000000--- a/CodexBar/Models/CodexTokenHistory.swift+++ /dev/null@@ -1,157 +0,0 @@-import CryptoKit-import Foundation--/// 一条线程轮次的累计快照, 身份只保存哈希, 不保存对话正文或原始 ID-nonisolated struct CodexTokenTurn: Codable, Equatable, Identifiable {- let id: String- var rootID: String- var startedAt: Date?- var updatedAt: Date- var usage: CodexTokenUsage?- var rebuiltAt: Date?-- static func identifier(thread: String, turn: String) -> String {- // 哈希身份域是固定输入, 不随存储 schema 变化, 避免同一轮次生成多个身份- let data = (try? JSONEncoder().encode(["token-turn-v1", thread, turn])) ?? Data()- return hexString(SHA256.hash(data: data))- }-- static func hexString(_ bytes: some Sequence<UInt8>) -> String {- let digits = Array("0123456789abcdef".utf8)- var result: [UInt8] = []- result.reserveCapacity(bytes.underestimatedCount * 2)- for byte in bytes {- result.append(digits[Int(byte >> 4)])- result.append(digits[Int(byte & 0x0F)])- }- return String(bytes: result, encoding: .utf8) ?? ""- }-- func merging(_ other: Self) -> Self {- precondition(id == other.id)- // 显式重建允许修正为更小的用量, 旧缓存不能再以累计值较大为由恢复错误结果- if rebuiltAt != other.rebuiltAt {- return (rebuiltAt ?? .distantPast) > (other.rebuiltAt ?? .distantPast) ? self : other- }- var result = self- if rootID == id {- result.rootID = other.rootID- }- if let date = other.startedAt {- result.startedAt = min(startedAt ?? date, date)- }- result.updatedAt = max(updatedAt, other.updatedAt)- if let candidate = other.usage, candidate.isValid {- if let current = usage {- // 同一累计快照的副本和较短扫描都不能重复累加或覆盖更完整的数据- if Self.usageOrder(candidate).lexicographicallyPrecedes(Self.usageOrder(current)) == false {- result.usage = candidate- }- } else {- result.usage = candidate- }- }- return result- }-- static func merged(_ records: [Self]) -> [String: Self] {- records.reduce(into: [:]) { result, record in- result[record.id] = result[record.id]?.merging(record) ?? record- }- }-- static func dailyUsage(_ records: [Self], now: Date = Date()) -> [String: CodexTokenUsage] {- let byID = merged(records)- let cutoff = WorkflowStorage.retentionCutoffDate(today: now)- var result: [String: CodexTokenUsage] = [:]- var invalidDates: Set<String> = []- for record in byID.values {- guard let usage = record.usage, usage.isValid,- let start = byID[record.rootID]?.startedAt, start >= cutoff, start <= now else { continue }- let date = CodexDateFormat.dayString(from: start)- if let current = result[date] {- if let sum = current.adding(usage) {- result[date] = sum- } else {- invalidDates.insert(date)- }- } else {- result[date] = usage- }- }- for date in invalidDates {- result.removeValue(forKey: date)- }- return result- }-- func pseudonymized(salt: Data) -> Self {- let key = SymmetricKey(data: salt)- return pseudonymized { value in- Self.hexString(HMAC<SHA256>.authenticationCode(for: Data(value.utf8), using: key))- }- }-- static func pseudonymized(_ records: [Self], salt: Data) -> [Self] {- let key = SymmetricKey(data: salt)- var identities: [String: String] = [:]- return records.map { record in- record.pseudonymized { value in- if let cached = identities[value] {- return cached- }- let hashed = hexString(HMAC<SHA256>.authenticationCode(for: Data(value.utf8), using: key))- identities[value] = hashed- return hashed- }- }- }-- private func pseudonymized(hash: (String) -> String) -> Self {- let exportedID = hash(id)- return Self(- id: exportedID, rootID: rootID == id ? exportedID : hash(rootID),- startedAt: startedAt, updatedAt: updatedAt, usage: usage, rebuiltAt: rebuiltAt- )- }-- static func syncable(_ records: [Self]) -> [Self] {- let rootIDs = Set(records.filter { $0.usage != nil }.map(\.rootID))- return records.filter { $0.usage != nil || $0.rebuiltAt != nil || rootIDs.contains($0.id) }- }-- private static func usageOrder(_ usage: CodexTokenUsage) -> [Int64] {- [- usage.totalTokens,- usage.inputTokens,- usage.outputTokens,- usage.cachedInputTokens,- usage.cacheWriteInputTokens,- usage.reasoningOutputTokens- ]- }-}--/// 云端身份只通过账户 salt 与本地已发现的轮次匹配, 不导入其他设备的轮次-nonisolated struct CodexTokenHistoryBaseline {- let salt: Data- private let turns: [String: CodexTokenTurn]- private let latestRebuiltAt: Date?-- init(salt: Data, turns: [String: CodexTokenTurn]) {- self.salt = salt- self.turns = turns.filter { $0.value.rebuiltAt != nil }- latestRebuiltAt = self.turns.values.compactMap(\.rebuiltAt).max()- }-- func replacement(for local: CodexTokenTurn) -> CodexTokenTurn? {- guard let latestRebuiltAt, latestRebuiltAt > (local.rebuiltAt ?? .distantPast) else { return nil }- let exported = local.pseudonymized(salt: salt)- guard let remote = turns[exported.id], let rebuiltAt = remote.rebuiltAt,- rebuiltAt > (local.rebuiltAt ?? .distantPast), remote.rootID == exported.rootID else { return nil }- return CodexTokenTurn(- id: local.id, rootID: local.rootID, startedAt: remote.startedAt ?? local.startedAt,- updatedAt: remote.updatedAt, usage: remote.usage, rebuiltAt: rebuiltAt- )- }-}diff --git a/CodexBar/Models/CodexWorkflowModels.swift b/CodexBar/Models/CodexWorkflowModels.swiftdeleted file mode 100644index e2225ff..0000000--- a/CodexBar/Models/CodexWorkflowModels.swift+++ /dev/null@@ -1,1008 +0,0 @@-import Foundation--/// 写入 JSONL 时固定字段顺序, 便于人工排查和 diff-private nonisolated enum WorkflowJSON {- static func lineData(_ fields: [String]) -> Data {- let json = "{\(fields.joined(separator: ","))}"- return Data(json.utf8) + Data([0x0A])- }-- static func field(_ name: String, _ value: (some Encodable)?) throws -> String {- try "\"\(name)\":\(Self.value(value))"- }-- static func value(_ value: (some Encodable)?) throws -> String {- guard let value else {- return "null"- }-- return try Self.value(value)- }-- static func value(_ value: some Encodable) throws -> String {- let data = try JSONLines.stableEncoder.encode(value)- guard let text = String(bytes: data, encoding: .utf8) else {- throw EncodingError.invalidValue(- value,- .init(codingPath: [], debugDescription: "Encoded workflow JSON was not UTF-8")- )- }- return text- }-- static func presentCountFields(_ values: [(String, Int?)]) throws -> [String] {- try values.compactMap { name, value in- guard let value else {- return nil- }- return try field(name, value)- }- }-}--private nonisolated enum WorkflowCountResolution {- static func preferredCount(- compactedCount: Int?,- identifiers: [String]? = nil- ) -> Int? {- if let compactedCount, compactedCount > 0 {- return compactedCount- }-- if let identifiers {- return Set(identifiers).count- }-- return compactedCount == 0 ? 0 : nil- }-- static func resolvedCount(- compactedCount: Int?,- identifiers: [String]? = nil,- fallback: Int- ) -> Int {- preferredCount(compactedCount: compactedCount, identifiers: identifiers) ?? fallback- }-}--// MARK: - Hook 原始事件--/// Hook 事件来源的本地归一化分类, 不保留 rollout 中的原始 source 内容-nonisolated enum WorkflowEventOrigin: String, Codable, Sendable {- case main- case autoReview- case auxiliary- case unknown-- init(from decoder: Decoder) throws {- let container = try decoder.singleValueContainer()- let rawValue = try? container.decode(String.self)- self = rawValue.flatMap(Self.init(rawValue:)) ?? .unknown- }-}--/// hooks 进程落盘和读取的最小事件模型, 在边界归一化来源并对历史字段缺失保持宽容-nonisolated struct WorkflowHookEvent: Decodable, Equatable {- let timestamp: Date- let name: String- let origin: WorkflowEventOrigin- let directoryPath: String?- let toolName: String?- let modelName: String?- let effort: String?- let permissionMode: String?- let approvalReviewer: CodexApprovalReviewer?- let sessionID: String?- let turnID: String?- let agentID: String?-- init(- timestamp: Date,- name: String,- origin: WorkflowEventOrigin,- directoryPath: String?,- toolName: String?,- modelName: String?,- effort: String?,- permissionMode: String?,- approvalReviewer: CodexApprovalReviewer?,- sessionID: String?,- turnID: String?,- agentID: String?- ) {- self.timestamp = timestamp- self.name = name- self.origin = Self.resolvedOrigin(origin, modelName: modelName)- self.directoryPath = directoryPath- self.toolName = toolName- self.modelName = modelName- self.effort = effort- self.permissionMode = permissionMode- self.approvalReviewer = approvalReviewer- self.sessionID = sessionID- self.turnID = turnID- self.agentID = agentID- }-- init(from decoder: Decoder) throws {- let container = try decoder.container(keyedBy: CodingKeys.self)- guard let timestampString = Self.string(from: container, key: .timestamp),- let timestamp = Self.date(from: timestampString) else {- throw DecodingError.dataCorrupted(- .init(codingPath: decoder.codingPath, debugDescription: "Missing or invalid hook event timestamp")- )- }- guard let name = Self.string(from: container, key: .event) else {- throw DecodingError.dataCorrupted(- .init(codingPath: decoder.codingPath, debugDescription: "Missing hook event name")- )- }-- let decodedOrigin = (try? container.decode(WorkflowEventOrigin.self, forKey: .origin)) ?? .unknown- let decodedModelName = Self.string(from: container, key: .modelName)-- self.timestamp = timestamp- self.name = name- origin = Self.resolvedOrigin(decodedOrigin, modelName: decodedModelName)- directoryPath = Self.string(from: container, key: .cwd)- toolName = Self.string(from: container, key: .toolName)- modelName = decodedModelName- effort = Self.string(from: container, key: .effort)- permissionMode = Self.string(from: container, key: .permissionMode)- approvalReviewer = try? container.decode(- CodexApprovalReviewer.self,- forKey: .approvalReviewer- )- sessionID = Self.string(from: container, key: .sessionID)- turnID = Self.string(from: container, key: .turnID)- agentID = Self.string(from: container, key: .agentID)- }-- var hookEvent: CodexHookEvent? {- CodexHookEvent(eventName: name)- }-- var projectDisplayName: String? {- guard let directoryPath, !directoryPath.isEmpty else {- return nil- }-- let url = URL(fileURLWithPath: directoryPath).standardizedFileURL- let lastComponent = url.lastPathComponent- return lastComponent.isEmpty ? directoryPath : lastComponent- }-- private static func string(- from container: KeyedDecodingContainer<CodingKeys>,- key: CodingKeys- ) -> String? {- guard let value = try? container.decode(String.self, forKey: key) else {- return nil- }-- let trimmedValue = value.trimmingCharacters(in: .whitespacesAndNewlines)- return trimmedValue.isEmpty ? nil : trimmedValue- }-- private static func date(from string: String) -> Date? {- CodexDateFormat.localTimestampDate(from: string)- }-- /// Ephemeral Guardian 没有 rollout path, canonical model 是来源判定的可靠后备- private static func resolvedOrigin(- _ origin: WorkflowEventOrigin,- modelName: String?- ) -> WorkflowEventOrigin {- guard origin == .unknown,- modelName == autoReviewModelName else {- return origin- }- return .autoReview- }-- func jsonLineData() throws -> Data {- let fields = try [- WorkflowJSON.field("timestamp", CodexDateFormat.localTimestampString(from: timestamp)),- WorkflowJSON.field("event", name),- WorkflowJSON.field("origin", origin),- WorkflowJSON.field("model", modelName),- WorkflowJSON.field("effort", effort),- WorkflowJSON.field("permission", permissionMode),- WorkflowJSON.field("approval", approvalReviewer),- WorkflowJSON.field("session", sessionID),- WorkflowJSON.field("turn", turnID),- WorkflowJSON.field("agent", agentID),- WorkflowJSON.field("tool", toolName),- WorkflowJSON.field("cwd", directoryPath)- ]-- return WorkflowJSON.lineData(fields)- }-- private enum CodingKeys: String, CodingKey {- case timestamp- case event- case origin- case cwd- case toolName = "tool"- case modelName = "model"- case effort- case permissionMode = "permission"- case approvalReviewer = "approval"- case sessionID = "session"- case turnID = "turn"- case agentID = "agent"- }-- private static let autoReviewModelName = "codex-auto-review"-}--// MARK: - 每日聚合指标--/// 热力图详情面板直接消费的每日统计-nonisolated struct WorkflowDailyMetrics: Equatable {- let startDate: String- let sessionCount: Int- let turnCount: Int- let toolCallCount: Int- let permissionRequestCount: Int- let contextCompactionCount: Int- let subagentCount: Int- let modelCounts: [String: Int]- let interruptCount: Int?-- var mostUsedModel: String? {- modelCounts- .filter { $0.value > 0 }- .sorted { lhs, rhs in- lhs.value == rhs.value ? lhs.key < rhs.key : lhs.value > rhs.value- }- .first?.key- }-- init(- startDate: String,- sessionCount: Int,- turnCount: Int,- toolCallCount: Int,- permissionRequestCount: Int,- contextCompactionCount: Int,- subagentCount: Int,- modelCounts: [String: Int] = [:],- interruptCount: Int? = nil- ) {- self.startDate = startDate- self.sessionCount = sessionCount- self.turnCount = turnCount- self.toolCallCount = toolCallCount- self.permissionRequestCount = permissionRequestCount- self.contextCompactionCount = contextCompactionCount- self.subagentCount = subagentCount- self.modelCounts = modelCounts- self.interruptCount = interruptCount- }-- static func empty(startDate: String) -> WorkflowDailyMetrics {- WorkflowDailyMetrics(- startDate: startDate,- sessionCount: 0,- turnCount: 0,- toolCallCount: 0,- permissionRequestCount: 0,- contextCompactionCount: 0,- subagentCount: 0- )- }-- init(- startDate: String,- sessionCount: Int,- turnCount: Int,- preToolUseCount: Int,- postToolUseCount: Int,- permissionRequestCount: Int,- preCompactCount: Int,- postCompactCount: Int,- subagentStartCount: Int,- subagentStopCount: Int,- modelCounts: [String: Int],- interruptCount: Int? = nil- ) {- self.startDate = startDate- self.sessionCount = sessionCount- self.turnCount = turnCount- toolCallCount = max(preToolUseCount, postToolUseCount)- self.permissionRequestCount = permissionRequestCount- contextCompactionCount = max(preCompactCount, postCompactCount)- subagentCount = max(subagentStartCount, subagentStopCount)- self.modelCounts = modelCounts- self.interruptCount = interruptCount- }-- func adding(_ other: WorkflowDailyMetrics) -> WorkflowDailyMetrics {- WorkflowDailyMetrics(- startDate: startDate,- sessionCount: sessionCount + other.sessionCount,- turnCount: turnCount + other.turnCount,- toolCallCount: toolCallCount + other.toolCallCount,- permissionRequestCount: permissionRequestCount + other.permissionRequestCount,- contextCompactionCount: contextCompactionCount + other.contextCompactionCount,- subagentCount: subagentCount + other.subagentCount,- modelCounts: Self.mergedCounts(modelCounts, other.modelCounts),- interruptCount: interruptCount.flatMap { lhs in other.interruptCount.map { lhs + $0 } }- )- }-- private static func mergedCounts(- _ lhs: [String: Int],- _ rhs: [String: Int]- ) -> [String: Int] {- rhs.reduce(into: lhs) { result, item in- result[item.key, default: 0] += item.value- }- }-}--// MARK: - 面板快照--/// WorkflowService 发布给 UI 的近端快照-nonisolated struct WorkflowSnapshot: Equatable {- let dailyMetrics: [WorkflowDailyMetrics]- var tokenUsageByDate: [String: CodexTokenUsage] = [:]-- static let empty = WorkflowSnapshot(dailyMetrics: [])-- init(dailyMetrics: [WorkflowDailyMetrics]) {- self.dailyMetrics = dailyMetrics- }-- /// 同 generation 只采用一份数据; 确认独立的新 generation 与历史贡献累加- init(- localAggregates: [WorkflowDailyAggregate],- syncedRecords: [WorkflowSyncedDailyRecord],- currentDeviceID: String?- ) {- var metricsByDate = [String: WorkflowDailyMetrics]()-- let localByDate = Dictionary(uniqueKeysWithValues: localAggregates.map { ($0.date, $0) })- let currentDeviceRecords = syncedRecords.filter { $0.deviceID == currentDeviceID }- let otherDeviceRecords = syncedRecords.filter { $0.deviceID != currentDeviceID }-- Self.merge(otherDeviceRecords, into: &metricsByDate)-- let remoteByDate = Dictionary(grouping: currentDeviceRecords, by: \.date)- let currentDeviceDates = Set(localByDate.keys).union(remoteByDate.keys)- for date in currentDeviceDates {- Self.mergeCurrentDeviceDate(- local: localByDate[date],- remoteRecords: remoteByDate[date] ?? [],- into: &metricsByDate- )- }-- dailyMetrics = metricsByDate.values.sorted { $0.startDate < $1.startDate }- }-- private static func mergeCurrentDeviceDate(- local: WorkflowDailyAggregate?,- remoteRecords: [WorkflowSyncedDailyRecord],- into metricsByDate: inout [String: WorkflowDailyMetrics]- ) {- guard let local else {- merge(remoteRecords, into: &metricsByDate)- return- }-- let matchingIndex = remoteRecords.firstIndex {- local.syncedAggregate.matchesRemoteSource($0.daily)- }-- guard remoteRecords.isEmpty || local.sourceIsFresh || matchingIndex != nil else {- merge(remoteRecords, into: &metricsByDate)- return- }-- for (index, record) in remoteRecords.enumerated() where index != matchingIndex {- merge(record.daily.metrics, into: &metricsByDate)- }-- if let matchingIndex,- (remoteRecords[matchingIndex].daily.eventCount ?? 0) > (local.eventCount ?? 0) {- merge(remoteRecords[matchingIndex].daily.metrics, into: &metricsByDate)- } else {- merge(local.metrics, into: &metricsByDate)- }- }-- private static func merge(- _ records: [WorkflowSyncedDailyRecord],- into metricsByDate: inout [String: WorkflowDailyMetrics]- ) {- for record in records {- merge(record.daily.metrics, into: &metricsByDate)- }- }-- private static func merge(- _ metrics: WorkflowDailyMetrics,- into metricsByDate: inout [String: WorkflowDailyMetrics]- ) {- if let existing = metricsByDate[metrics.startDate] {- metricsByDate[metrics.startDate] = existing.adding(metrics)- } else {- metricsByDate[metrics.startDate] = metrics- }- }-}--// MARK: - 每日事件聚合--/// ID 保留期限只决定最终存储形态, 不能影响聚合结果-nonisolated enum WorkflowIdentifierStorage {- case retained- case compacted-}--/// 从原始事件生成每日聚合的纯内存累加器-/// 全量和增量路径都收集 ID, 只有 finalize 时才按保留策略决定是否落盘-nonisolated struct WorkflowDailyAccumulator {- private var aggregate: WorkflowDailyAggregate- private var sessionIDs: Set<String> = []- private var turnIDs: Set<String> = []-- init(- rebuilding date: String,- sourceGeneration: String?,- sourceIsFresh: Bool,- hookCountAvailability: WorkflowHookCountAvailability- ) {- aggregate = WorkflowDailyAggregate(- date: date,- sourceGeneration: sourceGeneration,- sourceIsFresh: sourceIsFresh,- hookCountAvailability: hookCountAvailability- )- }-- init(- appending aggregate: WorkflowDailyAggregate,- sourceGeneration: String?,- sourceIsFresh: Bool- ) {- var aggregate = aggregate- aggregate.sourceGeneration = sourceGeneration- aggregate.sourceIsFresh = sourceIsFresh- self.aggregate = aggregate- sessionIDs = Set(aggregate.sessionIDs ?? [])- turnIDs = Set(aggregate.turnIDs ?? [])- }-- mutating func record(_ event: WorkflowHookEvent) {- // origin 只控制实时活动过滤, 历史统计按全部 Hook 事实保持原口径- Self.increment(&aggregate.eventCount)-- switch event.hookEvent {- case .sessionStart: Self.increment(&aggregate.sessionStartCount)- case .sessionEnd: Self.increment(&aggregate.sessionEndCount)- case .userPromptSubmit: Self.increment(&aggregate.userPromptSubmitCount)- case .stop: Self.increment(&aggregate.stopCount)- case .interrupt: Self.increment(&aggregate.interruptCount)- case .preToolUse: Self.increment(&aggregate.preToolUseCount)- case .postToolUse: Self.increment(&aggregate.postToolUseCount)- case .permissionRequest: Self.increment(&aggregate.permissionRequestCount)- case .preCompact: Self.increment(&aggregate.preCompactCount)- case .postCompact: Self.increment(&aggregate.postCompactCount)- case .subagentStart: Self.increment(&aggregate.subagentStartCount)- case .subagentStop: Self.increment(&aggregate.subagentStopCount)- case .none: break- }-- // 终态事件不单独构成对应的当日活跃轮次- if event.hookEvent != .sessionEnd, let sessionID = event.sessionID {- sessionIDs.insert(sessionID)- }- if event.hookEvent != .stop, event.hookEvent != .interrupt, let turnID = event.turnID {- turnIDs.insert(turnID)- }-- if let projectDisplayName = event.projectDisplayName {- aggregate.projectCounts[projectDisplayName, default: 0] += 1- }- if let modelName = event.modelName {- aggregate.modelCounts[modelName, default: 0] += 1- }- }-- func finalized(identifierStorage: WorkflowIdentifierStorage) -> WorkflowDailyAggregate {- var aggregate = aggregate- switch identifierStorage {- case .retained:- aggregate.sessionCount = nil- aggregate.turnCount = nil- aggregate.sessionIDs = Self.normalizedIdentifiers(sessionIDs)- aggregate.turnIDs = Self.normalizedIdentifiers(turnIDs)- case .compacted:- aggregate.sessionCount = sessionIDs.count- aggregate.turnCount = turnIDs.count- aggregate.sessionIDs = nil- aggregate.turnIDs = nil- }- return aggregate- }-- private static func increment(_ count: inout Int?) {- count = (count ?? 0) + 1- }-- private static func normalizedIdentifiers(_ identifiers: Set<String>) -> [String] {- identifiers.sorted()- }-}--/// 全量重放时保留每个 Hook 计数字段原有的可用性-nonisolated struct WorkflowHookCountAvailability {- static let all = WorkflowHookCountAvailability(- includesEventCount: true,- events: Set(CodexHookEvent.allCases)- )-- static let legacy = WorkflowHookCountAvailability(- includesEventCount: true,- events: Set(CodexHookEvent.allCases.filter { $0 != .interrupt })- )-- private let includesEventCount: Bool- private let events: Set<CodexHookEvent>-- init(aggregate: WorkflowDailyAggregate) {- includesEventCount = aggregate.eventCount != nil- events = Set(CodexHookEvent.allCases.filter { aggregate.hookCount(for: $0) != nil })- }-- private init(includesEventCount: Bool, events: Set<CodexHookEvent>) {- self.includesEventCount = includesEventCount- self.events = events- }-- var initialEventCount: Int? {- includesEventCount ? 0 : nil- }-- func initialCount(for event: CodexHookEvent) -> Int? {- events.contains(event) ? 0 : nil- }-}--/// daily.jsonl 中的持久化聚合行, 同时兼容保留 ID 和只保留计数两种形态-nonisolated struct WorkflowDailyAggregate: Codable, Equatable {- let date: String- var sourceGeneration: String?- var sourceIsFresh: Bool- var eventCount: Int?- var sessionStartCount: Int?- var sessionEndCount: Int?- var userPromptSubmitCount: Int?- var stopCount: Int?- var interruptCount: Int?- var preToolUseCount: Int?- var postToolUseCount: Int?- var permissionRequestCount: Int?- var preCompactCount: Int?- var postCompactCount: Int?- var subagentStartCount: Int?- var subagentStopCount: Int?- var sessionCount: Int?- var turnCount: Int?- var projectCounts: [String: Int]- var modelCounts: [String: Int]- var sessionIDs: [String]?- var turnIDs: [String]?-- /// 增量路径只有在完整 ID 集合仍然存在时才能继续安全去重- var supportsIncrementalAggregation: Bool {- sessionCount == nil && turnCount == nil- }-- init(- date: String,- sourceGeneration: String? = nil,- sourceIsFresh: Bool = false,- hookCountAvailability: WorkflowHookCountAvailability = .all- ) {- self.date = date- self.sourceGeneration = sourceGeneration- self.sourceIsFresh = sourceIsFresh- eventCount = hookCountAvailability.initialEventCount- sessionStartCount = hookCountAvailability.initialCount(for: .sessionStart)- sessionEndCount = hookCountAvailability.initialCount(for: .sessionEnd)- userPromptSubmitCount = hookCountAvailability.initialCount(for: .userPromptSubmit)- stopCount = hookCountAvailability.initialCount(for: .stop)- interruptCount = hookCountAvailability.initialCount(for: .interrupt)- preToolUseCount = hookCountAvailability.initialCount(for: .preToolUse)- postToolUseCount = hookCountAvailability.initialCount(for: .postToolUse)- permissionRequestCount = hookCountAvailability.initialCount(for: .permissionRequest)- preCompactCount = hookCountAvailability.initialCount(for: .preCompact)- postCompactCount = hookCountAvailability.initialCount(for: .postCompact)- subagentStartCount = hookCountAvailability.initialCount(for: .subagentStart)- subagentStopCount = hookCountAvailability.initialCount(for: .subagentStop)- sessionCount = nil- turnCount = nil- projectCounts = [:]- modelCounts = [:]- sessionIDs = []- turnIDs = []- }-- init(from decoder: Decoder) throws {- let container = try decoder.container(keyedBy: CodingKeys.self)- date = try container.decode(String.self, forKey: .date)- sourceGeneration = try container.decodeIfPresent(String.self, forKey: .sourceGeneration)- sourceIsFresh = try container.decodeIfPresent(Bool.self, forKey: .sourceIsFresh) ?? false- eventCount = try container.decodeIfPresent(Int.self, forKey: .eventCount)- sessionStartCount = try container.decodeIfPresent(Int.self, forKey: .sessionStartCount)- sessionEndCount = try container.decodeIfPresent(Int.self, forKey: .sessionEndCount)- userPromptSubmitCount = try container.decodeIfPresent(Int.self, forKey: .userPromptSubmitCount)- stopCount = try container.decodeIfPresent(Int.self, forKey: .stopCount)- interruptCount = try container.decodeIfPresent(Int.self, forKey: .interruptCount)- preToolUseCount = try container.decodeIfPresent(Int.self, forKey: .preToolUseCount)- postToolUseCount = try container.decodeIfPresent(Int.self, forKey: .postToolUseCount)- permissionRequestCount = try container.decodeIfPresent(Int.self, forKey: .permissionRequestCount)- preCompactCount = try container.decodeIfPresent(Int.self, forKey: .preCompactCount)- postCompactCount = try container.decodeIfPresent(Int.self, forKey: .postCompactCount)- subagentStartCount = try container.decodeIfPresent(Int.self, forKey: .subagentStartCount)- subagentStopCount = try container.decodeIfPresent(Int.self, forKey: .subagentStopCount)- sessionCount = try container.decodeIfPresent(Int.self, forKey: .sessionCount)- turnCount = try container.decodeIfPresent(Int.self, forKey: .turnCount)- projectCounts = try container.decodeIfPresent([String: Int].self, forKey: .projectCounts) ?? [:]- modelCounts = try container.decodeIfPresent([String: Int].self, forKey: .modelCounts) ?? [:]- sessionIDs = try container.decodeIfPresent([String].self, forKey: .sessionIDs)- turnIDs = try container.decodeIfPresent([String].self, forKey: .turnIDs)- }-- mutating func normalizeIdentifierStorage(retainsIdentifiers: Bool) {- guard !retainsIdentifiers else {- sessionIDs = Self.normalizedIdentifiers(sessionIDs)- turnIDs = Self.normalizedIdentifiers(turnIDs)- return- }-- sessionCount = WorkflowCountResolution.preferredCount(- compactedCount: sessionCount,- identifiers: sessionIDs- ) ?? sessionStartCount- turnCount = WorkflowCountResolution.preferredCount(- compactedCount: turnCount,- identifiers: turnIDs- ) ?? stopCount- sessionIDs = nil- turnIDs = nil- }-- var metrics: WorkflowDailyMetrics {- syncedAggregate.metrics- }-- static func normalized(- aggregates: [WorkflowDailyAggregate],- today: Date = Date(),- calendar: Calendar = .current- ) -> [WorkflowDailyAggregate] {- let retentionCutoffDate = WorkflowStorage.retentionCutoffDate(today: today, calendar: calendar)- let identifierCutoffDate = WorkflowStorage.identifierRetentionCutoffDate(today: today, calendar: calendar)-- return aggregates.compactMap { aggregate in- guard let date = Self.date(from: aggregate.date), date >= retentionCutoffDate else {- return nil- }-- var mutableAggregate = aggregate- mutableAggregate.normalizeIdentifierStorage(- retainsIdentifiers: date >= identifierCutoffDate- )- return mutableAggregate- }- .sorted { $0.date < $1.date }- }-- static func encodeJSONLines(_ aggregates: [WorkflowDailyAggregate]) throws -> Data {- try aggregates.reduce(into: Data()) { result, aggregate in- try result.append(aggregate.jsonLineData())- }- }-- func jsonLineData() throws -> Data {- var fields = try [- WorkflowJSON.field("date", date),- WorkflowJSON.field("sourceGeneration", sourceGeneration),- WorkflowJSON.field("sourceIsFresh", sourceIsFresh)- ]- try fields.append(contentsOf: WorkflowJSON.presentCountFields(hookCountFields))- try fields.append(contentsOf: [- WorkflowJSON.field("sessionCount", sessionCount),- WorkflowJSON.field("turnCount", turnCount),- WorkflowJSON.field("projectCounts", projectCounts),- WorkflowJSON.field("modelCounts", modelCounts),- WorkflowJSON.field("sessionIds", sessionIDs),- WorkflowJSON.field("turnIds", turnIDs)- ])-- return WorkflowJSON.lineData(fields)- }-- var hookCountAvailability: WorkflowHookCountAvailability {- WorkflowHookCountAvailability(aggregate: self)- }-- func hookCount(for event: CodexHookEvent) -> Int? {- switch event {- case .sessionStart: sessionStartCount- case .sessionEnd: sessionEndCount- case .userPromptSubmit: userPromptSubmitCount- case .stop: stopCount- case .interrupt: interruptCount- case .preToolUse: preToolUseCount- case .postToolUse: postToolUseCount- case .permissionRequest: permissionRequestCount- case .preCompact: preCompactCount- case .postCompact: postCompactCount- case .subagentStart: subagentStartCount- case .subagentStop: subagentStopCount- }- }-- var syncedAggregate: WorkflowSyncedDailyAggregate {- WorkflowSyncedDailyAggregate(- date: date,- sourceGeneration: sourceGeneration,- eventCount: eventCount,- sessionStartCount: sessionStartCount,- sessionEndCount: sessionEndCount,- userPromptSubmitCount: userPromptSubmitCount,- stopCount: stopCount,- interruptCount: interruptCount,- preToolUseCount: preToolUseCount,- postToolUseCount: postToolUseCount,- permissionRequestCount: permissionRequestCount,- preCompactCount: preCompactCount,- postCompactCount: postCompactCount,- subagentStartCount: subagentStartCount,- subagentStopCount: subagentStopCount,- sessionCount: syncedSessionCount,- turnCount: syncedTurnCount,- projectCounts: projectCounts,- modelCounts: modelCounts- )- }-- private var syncedSessionCount: Int? {- WorkflowCountResolution.preferredCount(- compactedCount: sessionCount,- identifiers: sessionIDs- )- }-- private var syncedTurnCount: Int? {- WorkflowCountResolution.preferredCount(- compactedCount: turnCount,- identifiers: turnIDs- )- }-- private var hookCountFields: [(String, Int?)] {- [- ("eventCount", eventCount),- ("sessionStartCount", sessionStartCount),- ("sessionEndCount", sessionEndCount),- ("userPromptSubmitCount", userPromptSubmitCount),- ("stopCount", stopCount),- ("interruptCount", interruptCount),- ("preToolUseCount", preToolUseCount),- ("postToolUseCount", postToolUseCount),- ("permissionRequestCount", permissionRequestCount),- ("preCompactCount", preCompactCount),- ("postCompactCount", postCompactCount),- ("subagentStartCount", subagentStartCount),- ("subagentStopCount", subagentStopCount)- ]- }-- private static func normalizedIdentifiers(_ identifiers: [String]?) -> [String]? {- identifiers.map { Set($0).sorted() }- }-- private static func date(from string: String) -> Date? {- CodexDateFormat.dayDate(from: string)- }-- private enum CodingKeys: String, CodingKey {- case date- case sourceGeneration- case sourceIsFresh- case eventCount- case sessionStartCount- case sessionEndCount- case userPromptSubmitCount- case stopCount- case interruptCount- case preToolUseCount- case postToolUseCount- case permissionRequestCount- case preCompactCount- case postCompactCount- case subagentStartCount- case subagentStopCount- case sessionCount- case turnCount- case projectCounts- case modelCounts- case sessionIDs = "sessionIds"- case turnIDs = "turnIds"- }-}--/// 同步用的每日聚合行, 保留 daily.jsonl 中的计数, 不包含 sessionIds 和 turnIds-nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable {- let date: String- var sourceGeneration: String?- var eventCount: Int?- var sessionStartCount: Int?- var sessionEndCount: Int?- var userPromptSubmitCount: Int?- var stopCount: Int?- var interruptCount: Int?- var preToolUseCount: Int?- var postToolUseCount: Int?- var permissionRequestCount: Int?- var preCompactCount: Int?- var postCompactCount: Int?- var subagentStartCount: Int?- var subagentStopCount: Int?- var sessionCount: Int?- var turnCount: Int?- var projectCounts: [String: Int]- var modelCounts: [String: Int]-- var metrics: WorkflowDailyMetrics {- WorkflowDailyMetrics(- startDate: date,- sessionCount: WorkflowCountResolution.resolvedCount(- compactedCount: sessionCount,- fallback: sessionStartCount ?? 0- ),- turnCount: WorkflowCountResolution.resolvedCount(- compactedCount: turnCount,- fallback: stopCount ?? 0- ),- preToolUseCount: preToolUseCount ?? 0,- postToolUseCount: postToolUseCount ?? 0,- permissionRequestCount: permissionRequestCount ?? 0,- preCompactCount: preCompactCount ?? 0,- postCompactCount: postCompactCount ?? 0,- subagentStartCount: subagentStartCount ?? 0,- subagentStopCount: subagentStopCount ?? 0,- modelCounts: modelCounts,- interruptCount: interruptCount- )- }-- func jsonLineData() throws -> Data {- var fields = try [- WorkflowJSON.field("date", date),- WorkflowJSON.field("sourceGeneration", sourceGeneration)- ]- try fields.append(contentsOf: WorkflowJSON.presentCountFields(hookCountFields))- try fields.append(contentsOf: [- WorkflowJSON.field("sessionCount", sessionCount),- WorkflowJSON.field("turnCount", turnCount),- WorkflowJSON.field("projectCounts", projectCounts),- WorkflowJSON.field("modelCounts", modelCounts)- ])-- return WorkflowJSON.lineData(fields)- }-- private var hookCountFields: [(String, Int?)] {- [- ("eventCount", eventCount),- ("sessionStartCount", sessionStartCount),- ("sessionEndCount", sessionEndCount),- ("userPromptSubmitCount", userPromptSubmitCount),- ("stopCount", stopCount),- ("interruptCount", interruptCount),- ("preToolUseCount", preToolUseCount),- ("postToolUseCount", postToolUseCount),- ("permissionRequestCount", permissionRequestCount),- ("preCompactCount", preCompactCount),- ("postCompactCount", postCompactCount),- ("subagentStartCount", subagentStartCount),- ("subagentStopCount", subagentStopCount)- ]- }-- func hasSameContent(as other: WorkflowSyncedDailyAggregate) -> Bool {- var lhs = self- var rhs = other- lhs.sourceGeneration = nil- rhs.sourceGeneration = nil- return lhs == rhs- }-- func matchesRemoteSource(_ remote: WorkflowSyncedDailyAggregate) -> Bool {- if let sourceGeneration,- remote.sourceGeneration == sourceGeneration {- return true- }- return remote.sourceGeneration == nil && hasSameContent(as: remote)- }-- private enum CodingKeys: String, CodingKey {- case date- case sourceGeneration- case eventCount- case sessionStartCount- case sessionEndCount- case userPromptSubmitCount- case stopCount- case interruptCount- case preToolUseCount- case postToolUseCount- case permissionRequestCount- case preCompactCount- case postCompactCount- case subagentStartCount- case subagentStopCount- case sessionCount- case turnCount- case projectCounts- case modelCounts- }-}--extension WorkflowSyncedDailyAggregate {- nonisolated init(from decoder: Decoder) throws {- let container = try decoder.container(keyedBy: CodingKeys.self)- date = try container.decode(String.self, forKey: .date)- sourceGeneration = try container.decodeIfPresent(String.self, forKey: .sourceGeneration)- eventCount = try container.decodeIfPresent(Int.self, forKey: .eventCount)- sessionStartCount = try container.decodeIfPresent(Int.self, forKey: .sessionStartCount)- sessionEndCount = try container.decodeIfPresent(Int.self, forKey: .sessionEndCount)- userPromptSubmitCount = try container.decodeIfPresent(Int.self, forKey: .userPromptSubmitCount)- stopCount = try container.decodeIfPresent(Int.self, forKey: .stopCount)- interruptCount = try container.decodeIfPresent(Int.self, forKey: .interruptCount)- preToolUseCount = try container.decodeIfPresent(Int.self, forKey: .preToolUseCount)- postToolUseCount = try container.decodeIfPresent(Int.self, forKey: .postToolUseCount)- permissionRequestCount = try container.decodeIfPresent(Int.self, forKey: .permissionRequestCount)- preCompactCount = try container.decodeIfPresent(Int.self, forKey: .preCompactCount)- postCompactCount = try container.decodeIfPresent(Int.self, forKey: .postCompactCount)- subagentStartCount = try container.decodeIfPresent(Int.self, forKey: .subagentStartCount)- subagentStopCount = try container.decodeIfPresent(Int.self, forKey: .subagentStopCount)- sessionCount = try container.decodeIfPresent(Int.self, forKey: .sessionCount)- turnCount = try container.decodeIfPresent(Int.self, forKey: .turnCount)- projectCounts = try container.decodeIfPresent([String: Int].self, forKey: .projectCounts) ?? [:]- modelCounts = try container.decodeIfPresent([String: Int].self, forKey: .modelCounts) ?? [:]- }-}--nonisolated struct WorkflowSyncedDailyRecord: Codable, Equatable, Identifiable {- let deviceID: String- let daily: WorkflowSyncedDailyAggregate- var updatedAt: Date?- var recordName: String?-- private enum CodingKeys: String, CodingKey {- case deviceID = "deviceId"- case daily, updatedAt, recordName- }-- var id: String {- recordName ?? Self.legacyRecordName(deviceID: deviceID, date: daily.date)- }-- var date: String {- daily.date- }-- static func legacyRecordName(deviceID: String, date: String) -> String {- "\(deviceID)_\(date)"- }-}diff --git a/CodexBar/Models/HistorySnapshot.swift b/CodexBar/Models/HistorySnapshot.swiftnew file mode 100644index 0000000..1d2eb5f--- /dev/null+++ b/CodexBar/Models/HistorySnapshot.swift@@ -0,0 +1,199 @@+import Foundation++// MARK: - 每日聚合指标++/// 热力图详情面板直接消费的每日统计+nonisolated struct ActivityMetrics: Equatable {+ let startDate: String+ let sessionCount: Int+ let turnCount: Int+ let toolCallCount: Int+ let approvalRequestedCount: Int+ let contextCompactionCount: Int+ let subagentCount: Int+ let modelCounts: [String: Int]+ let turnAbortedCount: Int?++ var mostUsedModel: String? {+ modelCounts+ .filter { $0.value > 0 }+ .sorted { lhs, rhs in+ lhs.value == rhs.value ? lhs.key < rhs.key : lhs.value > rhs.value+ }+ .first?.key+ }++ init(+ startDate: String,+ sessionCount: Int,+ turnCount: Int,+ toolCallCount: Int,+ approvalRequestedCount: Int,+ contextCompactionCount: Int,+ subagentCount: Int,+ modelCounts: [String: Int] = [:],+ turnAbortedCount: Int? = nil+ ) {+ self.startDate = startDate+ self.sessionCount = sessionCount+ self.turnCount = turnCount+ self.toolCallCount = toolCallCount+ self.approvalRequestedCount = approvalRequestedCount+ self.contextCompactionCount = contextCompactionCount+ self.subagentCount = subagentCount+ self.modelCounts = modelCounts+ self.turnAbortedCount = turnAbortedCount+ }++ static func empty(startDate: String) -> ActivityMetrics {+ ActivityMetrics(+ startDate: startDate,+ sessionCount: 0,+ turnCount: 0,+ toolCallCount: 0,+ approvalRequestedCount: 0,+ contextCompactionCount: 0,+ subagentCount: 0+ )+ }++ init(+ startDate: String,+ sessionCount: Int,+ turnCount: Int,+ toolStartedCount: Int,+ toolCompletedCount: Int,+ approvalRequestedCount: Int,+ compactionStartedCount: Int,+ compactionCompletedCount: Int,+ subagentStartedCount: Int,+ subagentEndedCount: Int,+ modelCounts: [String: Int],+ turnAbortedCount: Int? = nil+ ) {+ self.startDate = startDate+ self.sessionCount = sessionCount+ self.turnCount = turnCount+ toolCallCount = max(toolStartedCount, toolCompletedCount)+ self.approvalRequestedCount = approvalRequestedCount+ contextCompactionCount = max(compactionStartedCount, compactionCompletedCount)+ subagentCount = max(subagentStartedCount, subagentEndedCount)+ self.modelCounts = modelCounts+ self.turnAbortedCount = turnAbortedCount+ }++ func adding(_ other: ActivityMetrics) -> ActivityMetrics {+ ActivityMetrics(+ startDate: startDate,+ sessionCount: sessionCount + other.sessionCount,+ turnCount: turnCount + other.turnCount,+ toolCallCount: toolCallCount + other.toolCallCount,+ approvalRequestedCount: approvalRequestedCount + other.approvalRequestedCount,+ contextCompactionCount: contextCompactionCount + other.contextCompactionCount,+ subagentCount: subagentCount + other.subagentCount,+ modelCounts: Self.mergedCounts(modelCounts, other.modelCounts),+ turnAbortedCount: turnAbortedCount.flatMap { lhs in other.turnAbortedCount.map { lhs + $0 } }+ )+ }++ private static func mergedCounts(+ _ lhs: [String: Int],+ _ rhs: [String: Int]+ ) -> [String: Int] {+ rhs.reduce(into: lhs) { result, item in+ result[item.key, default: 0] += item.value+ }+ }+}++// MARK: - 面板快照++/// HistoryService 发布给 UI 的近端快照+nonisolated struct HistorySnapshot: Equatable {+ let dailyMetrics: [ActivityMetrics]+ var tokenUsageByDate: [String: TokenUsage] = [:]++ static let empty = HistorySnapshot(dailyMetrics: [])++ init(dailyMetrics: [ActivityMetrics]) {+ self.dailyMetrics = dailyMetrics+ }++ /// 同 generation 只采用一份数据; 确认独立的新 generation 与历史贡献累加+ init(+ localAggregates: [ActivityAggregate],+ syncedRecords: [ActivitySyncRecord],+ currentDeviceID: String?+ ) {+ var metricsByDate = [String: ActivityMetrics]()++ let localByDate = Dictionary(uniqueKeysWithValues: localAggregates.map { ($0.date, $0) })+ let currentDeviceRecords = syncedRecords.filter { $0.deviceID == currentDeviceID }+ let otherDeviceRecords = syncedRecords.filter { $0.deviceID != currentDeviceID }++ Self.merge(otherDeviceRecords, into: &metricsByDate)++ let remoteByDate = Dictionary(grouping: currentDeviceRecords, by: \.date)+ let currentDeviceDates = Set(localByDate.keys).union(remoteByDate.keys)+ for date in currentDeviceDates {+ Self.mergeCurrentDeviceDate(+ local: localByDate[date],+ remoteRecords: remoteByDate[date] ?? [],+ into: &metricsByDate+ )+ }++ dailyMetrics = metricsByDate.values.sorted { $0.startDate < $1.startDate }+ }++ private static func mergeCurrentDeviceDate(+ local: ActivityAggregate?,+ remoteRecords: [ActivitySyncRecord],+ into metricsByDate: inout [String: ActivityMetrics]+ ) {+ guard let local else {+ merge(remoteRecords, into: &metricsByDate)+ return+ }++ let matchingIndex = remoteRecords.firstIndex {+ local.syncedAggregate.matchesRemoteSource($0.daily)+ }++ guard remoteRecords.isEmpty || local.generationStartedEmpty || matchingIndex != nil else {+ merge(remoteRecords, into: &metricsByDate)+ return+ }++ for (index, record) in remoteRecords.enumerated() where index != matchingIndex {+ merge(record.daily.metrics, into: &metricsByDate)+ }++ if let matchingIndex,+ (remoteRecords[matchingIndex].daily.eventCount ?? 0) > (local.eventCount ?? 0) {+ merge(remoteRecords[matchingIndex].daily.metrics, into: &metricsByDate)+ } else {+ merge(local.metrics, into: &metricsByDate)+ }+ }++ private static func merge(+ _ records: [ActivitySyncRecord],+ into metricsByDate: inout [String: ActivityMetrics]+ ) {+ for record in records {+ merge(record.daily.metrics, into: &metricsByDate)+ }+ }++ private static func merge(+ _ metrics: ActivityMetrics,+ into metricsByDate: inout [String: ActivityMetrics]+ ) {+ if let existing = metricsByDate[metrics.startDate] {+ metricsByDate[metrics.startDate] = existing.adding(metrics)+ } else {+ metricsByDate[metrics.startDate] = metrics+ }+ }+}diff --git a/CodexBar/Models/StatusIconState.swift b/CodexBar/Models/StatusIconState.swiftnew file mode 100644index 0000000..04db63e--- /dev/null+++ b/CodexBar/Models/StatusIconState.swift@@ -0,0 +1,113 @@+import Foundation++struct StatusIconState: Equatable {+ let usesErrorImage: Bool+ let ordinaryUsageAllowed: Bool?+ let progress: StatusIconProgress?+ let activity: ActivitySnapshot++ func symbolName(at now: Date) -> String {+ if usesErrorImage {+ return "person.slash.fill"+ }+ switch activity.statusItemActivity(at: now) {+ case .waiting: return "person.badge.key.fill"+ case .running: return "person.badge.clock.fill"+ case .completed: return "person.badge.shield.checkmark.fill"+ case .terminated: return "person.badge.shield.exclamationmark.fill"+ case .idle: return "person.fill"+ }+ }++ var hasLiveDuration: Bool {+ activity.hasActiveTasks+ }++ func toolTip(at now: Date) -> String? {+ var lines: [String] = []+ if usesErrorImage {+ lines.append(String(localized: "codex-status.account.unavailable"))+ }++ if let activityText = activityToolTip(at: now) {+ lines.append(activityText)+ }+ if activity.activeCount > 1 {+ lines.append(+ String(localized: "status-item.activity-summary", defaultValue: "\(activity.waitingCount, specifier: "%lld")\(activity.runningCount, specifier: "%lld")")+ )+ }+ if let progress {+ lines.append(progress.toolTip)+ }+ return lines.isEmpty ? nil : lines.joined(separator: "\n")+ }++ private func activityToolTip(at now: Date) -> String? {+ switch activity.statusItemActivity(at: now) {+ case let .waiting(task):+ var text = String(localized: "activity.status.codex-waiting-for-approval")+ if let projectName = task.projectName {+ text += " • \(projectName)"+ }+ if let toolName = task.toolDisplayName {+ text += " • \(toolName)"+ }+ text += " • \(ActivityDisplayFormat.waitingDurationFragment(since: task.stateChangedAt, now: now))"+ return text+ case let .running(task):+ var text = String(localized: "activity.status.codex-running")+ if let projectName = task.projectName {+ text += " • \(projectName)"+ }+ if task.showsPreciseDuration, let startedAt = task.startedAt {+ text += " • \(ActivityDisplayFormat.runningDurationFragment(since: startedAt, now: now))"+ }+ return text+ case let .completed(completion):+ var text = String(localized: "activity.status.codex-just-completed")+ if let projectName = completion.projectName {+ text += " • \(projectName)"+ }+ if let duration = completion.duration {+ text += " • \(ActivityDisplayFormat.elapsedDurationFragment(for: duration))"+ }+ return text+ case let .terminated(termination):+ var text = String(localized: "activity.status.codex-stopped")+ if let projectName = termination.projectName {+ text += " • \(projectName)"+ }+ if let duration = termination.duration {+ text += " • \(ActivityDisplayFormat.elapsedDurationFragment(for: duration))"+ }+ return text+ case .idle:+ return nil+ }+ }+}++struct StatusIconProgress: Equatable {+ let label: String+ let percent: Int+ let isStale: Bool++ var toolTip: String {+ let percentText = CodexPercentageFormat.string(from: percent)+ return String(localized: "quota.status.remaining", defaultValue: "\(label)\(percentText)")+ }++ init?(snapshot: CodexQuotaSnapshot?, selection: MenuBarQuotaSelection) {+ guard let targetKind = selection.windowKind,+ let snapshot,+ let window = snapshot.codexLimit?.window(ofKind: targetKind),+ window.hasData else {+ return nil+ }++ label = window.label+ percent = window.remainingPercent+ isStale = snapshot.isRateLimitsStale+ }+}diff --git a/CodexBar/Models/TaskGlowPresentationState.swift b/CodexBar/Models/TaskGlowPresentationState.swiftindex 2007a16..1f51031 100644--- a/CodexBar/Models/TaskGlowPresentationState.swift+++ b/CodexBar/Models/TaskGlowPresentationState.swift@@ -1,7 +1,7 @@import AppKitimport QuartzCore-private extension CodexActivityTerminalEvent {+private extension ActivityTerminalEvent {var glowState: TaskGlowState {switch self {case .completed: .completed@@ -12,9 +12,9 @@ private extension CodexActivityTerminalEvent {/// 短提示只消费开启后新增的结束记录, 到期后按最新快照恢复等待或运行状态struct TaskGlowPresentationState {- private var snapshot = CodexActivitySnapshot.empty+ private var snapshot = ActivitySnapshot.emptyprivate var enabledAt: Date?- private var briefEvent: CodexActivityTerminalEvent?+ private var briefEvent: ActivityTerminalEvent?private var briefExpiration: Date?private var suspendedAt: Date?private var resumesAt: Date?@@ -49,8 +49,8 @@ struct TaskGlowPresentationState {}mutating func update(- snapshot: CodexActivitySnapshot,- terminalEvents: [CodexActivityTerminalEvent],+ snapshot: ActivitySnapshot,+ terminalEvents: [ActivityTerminalEvent],isEnabled: Bool,acceptsBriefEvents: Bool,now: Date@@ -119,7 +119,7 @@ struct TaskGlowPresentationState {terminal = nil}- private mutating func show(_ event: CodexActivityTerminalEvent, until expiration: Date, fadeDuration: TimeInterval, now: Date) {+ private mutating func show(_ event: ActivityTerminalEvent, until expiration: Date, fadeDuration: TimeInterval, now: Date) {terminal = TaskGlowTerminalPresentation(eventID: event.id,startedAt: terminal.flatMap { $0.eventID == event.id ? $0.startedAt : nil } ?? now,diff --git a/CodexBar/Models/TokenHistory.swift b/CodexBar/Models/TokenHistory.swiftnew file mode 100644index 0000000..3cc9cfe--- /dev/null+++ b/CodexBar/Models/TokenHistory.swift@@ -0,0 +1,328 @@+import CryptoKit+import Foundation++/// 一条线程轮次的累计快照, 身份只保存哈希, 不保存对话正文或原始 ID+nonisolated struct TokenTurn: Codable, Equatable, Identifiable {+ let id: String+ var rootID: String+ var startedAt: Date?+ var updatedAt: Date+ var usage: TokenUsage?+ var rebuiltAt: Date?+ var generationID: String+ var ancestorIDs: Set<String>+ var checkpoint: [String: TokenObservationCheckpoint]+ var hasConflict: Bool++ init(+ id: String,+ rootID: String,+ startedAt: Date? = nil,+ updatedAt: Date,+ usage: TokenUsage? = nil,+ rebuiltAt: Date? = nil,+ generationID: String = "initial",+ ancestorIDs: Set<String> = [],+ checkpoint: [String: TokenObservationCheckpoint] = [:],+ hasConflict: Bool = false+ ) {+ self.id = id+ self.rootID = rootID+ self.startedAt = startedAt.map(JSONLines.storageDate)+ self.updatedAt = JSONLines.storageDate(updatedAt)+ self.usage = usage+ self.rebuiltAt = rebuiltAt.map(JSONLines.storageDate)+ self.generationID = generationID+ self.ancestorIDs = ancestorIDs+ self.checkpoint = checkpoint+ self.hasConflict = hasConflict+ }++ private enum CodingKeys: String, CodingKey {+ case id, rootID, startedAt, updatedAt, usage, rebuiltAt+ case generationID, ancestorIDs, checkpoint, hasConflict+ }++ func encode(to encoder: Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(id, forKey: .id)+ try container.encode(rootID, forKey: .rootID)+ try container.encodeIfPresent(startedAt, forKey: .startedAt)+ try container.encode(updatedAt, forKey: .updatedAt)+ try container.encodeIfPresent(usage, forKey: .usage)+ try container.encodeIfPresent(rebuiltAt, forKey: .rebuiltAt)+ try container.encode(generationID, forKey: .generationID)+ try container.encode(ancestorIDs.sorted(), forKey: .ancestorIDs)+ try container.encode(checkpoint, forKey: .checkpoint)+ try container.encode(hasConflict, forKey: .hasConflict)+ }++ static func identifier(thread: String, turn: String) -> String {+ // 哈希身份域是固定输入, 不随存储 version 变化, 避免同一轮次生成多个身份+ let data = (try? JSONEncoder().encode(["token-turn-v1", thread, turn])) ?? Data()+ return hexString(SHA256.hash(data: data))+ }++ static func hexString(_ bytes: some Sequence<UInt8>) -> String {+ let digits = Array("0123456789abcdef".utf8)+ var result: [UInt8] = []+ result.reserveCapacity(bytes.underestimatedCount * 2)+ for byte in bytes {+ result.append(digits[Int(byte >> 4)])+ result.append(digits[Int(byte & 0x0F)])+ }+ return String(bytes: result, encoding: .utf8) ?? ""+ }++ func merging(_ other: Self) -> Self {+ precondition(id == other.id)+ if generationID != other.generationID {+ if ancestorIDs.contains(other.generationID) {+ return incorporatingUncoveredObservations(from: other)+ }+ if other.ancestorIDs.contains(generationID) {+ return other.incorporatingUncoveredObservations(from: self)+ }+ return conflicting(with: other)+ }+ if hasConflict || other.hasConflict {+ return conflicting(with: other)+ }+ if !checkpoint.isEmpty || !other.checkpoint.isEmpty {+ let coversOther = covers(other.checkpoint)+ let otherCovers = other.covers(checkpoint)+ if coversOther && !otherCovers {+ return self+ }+ if otherCovers && !coversOther {+ return other+ }+ if !coversOther || usage != other.usage {+ return conflicting(with: other)+ }+ }+ var result = self+ if rootID == id {+ result.rootID = other.rootID+ }+ if let date = other.startedAt {+ result.startedAt = min(startedAt ?? date, date)+ }+ result.updatedAt = max(updatedAt, other.updatedAt)+ if let candidate = other.usage, candidate.isValid {+ if let current = usage {+ // 同一累计快照的副本和较短扫描都不能重复累加或覆盖更完整的数据+ if Self.usageOrder(candidate).lexicographicallyPrecedes(Self.usageOrder(current)) == false {+ result.usage = candidate+ }+ } else {+ result.usage = candidate+ }+ }+ return result+ }++ func covers(_ boundary: [String: TokenObservationCheckpoint]) -> Bool {+ boundary.allSatisfy { id, value in+ guard let current = checkpoint[id], current.sequence >= value.sequence else { return false }+ return current.sequence != value.sequence || current.usage == value.usage+ }+ }++ mutating func startNewGeneration(at date: Date) {+ ancestorIDs.insert(generationID)+ generationID = UUID().uuidString.lowercased()+ rebuiltAt = JSONLines.storageDate(date)+ }++ private func incorporatingUncoveredObservations(from old: Self) -> Self {+ var result = self+ guard !hasConflict else { return conflicting(with: old) }+ for (stream, incoming) in old.checkpoint {+ guard let covered = checkpoint[stream] else { return conflicting(with: old) }+ if incoming.sequence == covered.sequence, incoming.usage != covered.usage {+ return conflicting(with: old)+ }+ guard incoming.sequence > covered.sequence else { continue }+ guard let delta = incoming.usage.subtracting(covered.usage),+ let usage = result.usage?.adding(delta), usage.isValid else { return conflicting(with: old) }+ result.usage = usage+ result.checkpoint[stream] = incoming+ result.updatedAt = max(result.updatedAt, old.updatedAt)+ }+ return result+ }++ private func conflicting(with other: Self) -> Self {+ var result = self+ // 冲突保留可恢复的边界, 不把任意分支的用量当成权威结果+ let generations = ancestorIDs.union(other.ancestorIDs)+ .union([generationID, other.generationID])+ if generationID != other.generationID {+ if ancestorIDs.contains(other.generationID) {+ result.generationID = generationID+ } else if other.ancestorIDs.contains(generationID) {+ result.generationID = other.generationID+ } else {+ let origins = generations.filter { !$0.hasPrefix("conflict-") }.sorted()+ result.generationID = "conflict-" + Self.hexString(SHA256.hash(data: Data(origins.joined(separator: ":").utf8)))+ }+ }+ result.ancestorIDs = generations.subtracting([result.generationID])+ result.hasConflict = true+ result.usage = nil+ result.rebuiltAt = [rebuiltAt, other.rebuiltAt].compactMap(\.self).max()+ result.updatedAt = max(updatedAt, other.updatedAt)+ result.startedAt = [startedAt, other.startedAt].compactMap(\.self).min()+ for (stream, incoming) in other.checkpoint {+ let current = result.checkpoint[stream]+ if incoming.sequence > (current?.sequence ?? 0)+ || (incoming.sequence == current?.sequence && Self.usageOrder(current?.usage ?? .zero).lexicographicallyPrecedes(Self.usageOrder(incoming.usage))) {+ result.checkpoint[stream] = incoming+ }+ }+ return result+ }++ static func merged(_ records: [Self]) -> [String: Self] {+ records.reduce(into: [:]) { result, record in+ result[record.id] = result[record.id]?.merging(record) ?? record+ }+ }++ static func dailyUsage(_ records: [Self], now: Date = Date()) -> [String: TokenUsage] {+ let byID = merged(records)+ let cutoff = HistoryStorage.retentionCutoffDate(today: now)+ var result: [String: TokenUsage] = [:]+ var invalidDates: Set<String> = []+ for record in byID.values {+ if record.hasConflict, let start = byID[record.rootID]?.startedAt {+ invalidDates.insert(CodexDateFormat.dayString(from: start))+ }+ guard let usage = record.usage, usage.isValid,+ let start = byID[record.rootID]?.startedAt, start >= cutoff, start <= now else { continue }+ let date = CodexDateFormat.dayString(from: start)+ if let current = result[date] {+ if let sum = current.adding(usage) {+ result[date] = sum+ } else {+ invalidDates.insert(date)+ }+ } else {+ result[date] = usage+ }+ }+ for date in invalidDates {+ result.removeValue(forKey: date)+ }+ return result+ }++ func pseudonymized(salt: Data) -> Self {+ let key = SymmetricKey(data: salt)+ return pseudonymized { value in+ Self.hexString(HMAC<SHA256>.authenticationCode(for: Data(value.utf8), using: key))+ }+ }++ static func pseudonymized(_ records: [Self], salt: Data) -> [Self] {+ let key = SymmetricKey(data: salt)+ var identities: [String: String] = [:]+ return records.map { record in+ record.pseudonymized { value in+ if let cached = identities[value] {+ return cached+ }+ let hashed = hexString(HMAC<SHA256>.authenticationCode(for: Data(value.utf8), using: key))+ identities[value] = hashed+ return hashed+ }+ }+ }++ private func pseudonymized(hash: (String) -> String) -> Self {+ let exportedID = hash(id)+ return Self(+ id: exportedID, rootID: rootID == id ? exportedID : hash(rootID),+ startedAt: startedAt, updatedAt: updatedAt, usage: usage, rebuiltAt: rebuiltAt,+ generationID: generationID, ancestorIDs: ancestorIDs,+ checkpoint: checkpoint, hasConflict: hasConflict+ )+ }++ static func syncable(_ records: [Self]) -> [Self] {+ let rootIDs = Set(records.filter { $0.usage != nil }.map(\.rootID))+ return records.filter { $0.usage != nil || $0.generationID != "initial" || $0.hasConflict || rootIDs.contains($0.id) }+ }++ private static func usageOrder(_ usage: TokenUsage) -> [Int64] {+ [+ usage.totalTokens,+ usage.inputTokens,+ usage.outputTokens,+ usage.cachedInputTokens,+ usage.cacheWriteInputTokens,+ usage.reasoningOutputTokens+ ]+ }+}++/// 云端身份只通过账户 salt 与本地已发现的轮次匹配, 不导入其他设备的轮次+nonisolated struct TokenHistoryBaseline {+ let salt: Data+ private let turns: [String: TokenTurn]+ init(salt: Data, turns: [String: TokenTurn]) {+ self.salt = salt+ self.turns = turns+ }++ func replacement(for local: TokenTurn) -> TokenTurn? {+ let exported = local.pseudonymized(salt: salt)+ guard var remote = turns[exported.id], remote.rootID == exported.rootID else { return nil }+ remote = exported.merging(remote)+ guard remote != exported else { return nil }+ return TokenTurn(+ id: local.id, rootID: local.rootID, startedAt: remote.startedAt ?? local.startedAt,+ updatedAt: remote.updatedAt, usage: remote.usage, rebuiltAt: remote.rebuiltAt,+ generationID: remote.generationID, ancestorIDs: remote.ancestorIDs,+ checkpoint: remote.checkpoint, hasConflict: remote.hasConflict+ )+ }+}++nonisolated struct TokenObservationCheckpoint: Codable, Equatable {+ var sequence: Int64+ var usage: TokenUsage+}++/// streamID 是每次采集连续区间生成的随机身份, 不包含设备或原始线程信息+nonisolated struct TokenObservation: Codable, Equatable {+ let turn: TokenTurn+ let rootStartedAt: Date?+ let streamID: String+ let sequence: Int64+ let previous: TokenUsage+ let current: TokenUsage++ func applying(to existing: TokenTurn?) throws -> TokenTurn {+ var result = existing ?? turn+ let boundary = result.checkpoint[streamID]+ if let boundary, boundary.sequence >= sequence {+ return result+ }+ guard sequence == (boundary?.sequence ?? 0) + 1,+ let delta = current.subtracting(previous),+ let observed = (boundary?.usage ?? .zero).adding(delta), observed.isValid else {+ throw TokenCacheError.incompleteJournal+ }+ if !result.hasConflict {+ guard let usage = (result.usage ?? .zero).adding(delta), usage.isValid else {+ throw TokenCacheError.incompleteJournal+ }+ result.usage = usage+ }+ result.checkpoint[streamID] = TokenObservationCheckpoint(sequence: sequence, usage: observed)+ result.updatedAt = max(result.updatedAt, turn.updatedAt)+ return result+ }+}diff --git a/CodexBar/Models/CodexTokenUsage.swift b/CodexBar/Models/TokenUsage.swiftsimilarity index 58%rename from CodexBar/Models/CodexTokenUsage.swiftrename to CodexBar/Models/TokenUsage.swiftindex 14caf27..6eeb719 100644--- a/CodexBar/Models/CodexTokenUsage.swift+++ b/CodexBar/Models/TokenUsage.swift@@ -1,6 +1,6 @@import Foundation-nonisolated struct CodexTokenUsage: Codable, Equatable {+nonisolated struct TokenUsage: Codable, Equatable {let inputTokens: Int64let cachedInputTokens: Int64let cacheWriteInputTokens: Int64@@ -32,39 +32,21 @@ nonisolated struct CodexTokenUsage: Codable, Equatable {)}- private var values: [Int64] {- [inputTokens, cachedInputTokens, cacheWriteInputTokens, outputTokens, reasoningOutputTokens, totalTokens]- }+ static let zero = Self(inputTokens: 0, cachedInputTokens: 0, cacheWriteInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0, totalTokens: 0)- private enum CodingKeys: String, CodingKey {- case inputTokens = "input_tokens"- case cachedInputTokens = "cached_input_tokens"- case cacheWriteInputTokens = "cache_write_input_tokens"- case outputTokens = "output_tokens"- case reasoningOutputTokens = "reasoning_output_tokens"- case totalTokens = "total_tokens"+ func subtracting(_ other: Self) -> Self? {+ guard isValid, other.isValid else { return nil }+ let differences = zip(values, other.values).map { $0.subtractingReportingOverflow($1) }+ guard !differences.contains(where: { $0.overflow || $0.partialValue < 0 }) else { return nil }+ let result = Self(+ inputTokens: differences[0].partialValue, cachedInputTokens: differences[1].partialValue,+ cacheWriteInputTokens: differences[2].partialValue, outputTokens: differences[3].partialValue,+ reasoningOutputTokens: differences[4].partialValue, totalTokens: differences[5].partialValue+ )+ return result.isValid ? result : nil}-}-/// 终态读取可能从文件尾部开始, 使用明确归属的轮次累计值避免漏算前面的响应-nonisolated struct CodexRolloutTokenUsageRecord: Decodable {- let payload: CodexRolloutTokenUsagePayload-}--nonisolated struct CodexRolloutTokenUsagePayload: Decodable {- let threadID: String- let sessionID: String- let turnID: String- let rootTurnID: String- let responseID: String- let turnTokenUsage: CodexTokenUsage-- private enum CodingKeys: String, CodingKey {- case threadID = "thread_id"- case sessionID = "session_id"- case turnID = "turn_id"- case rootTurnID = "root_turn_id"- case responseID = "response_id"- case turnTokenUsage = "turn_token_usage"+ private var values: [Int64] {+ [inputTokens, cachedInputTokens, cacheWriteInputTokens, outputTokens, reasoningOutputTokens, totalTokens]}}diff --git a/CodexBar/Models/UsageHeatmapDay.swift b/CodexBar/Models/UsageHeatmapDay.swiftindex b062f1a..b081342 100644--- a/CodexBar/Models/UsageHeatmapDay.swift+++ b/CodexBar/Models/UsageHeatmapDay.swift@@ -14,12 +14,12 @@ nonisolated enum UsageHeatmapTokenState: Equatable {}}-/// 热力图单元格模型, 合并 app-server token 数据和本地 Hook 工作流统计+/// 热力图单元格模型, 合并 app-server token 数据和本地 活动统计nonisolated struct UsageHeatmapDay: Equatable, Identifiable {let startDate: Stringlet tokenState: UsageHeatmapTokenState- let workflow: WorkflowDailyMetrics- var tokenUsage: CodexTokenUsage?+ let history: ActivityMetrics+ var tokenUsage: TokenUsage?var id: String {startDate@@ -35,17 +35,16 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {static func grid(usage: CodexUsageSnapshot?,- workflow: WorkflowSnapshot,- showsWorkflow: Bool,+ history: HistorySnapshot,+ showsActivity: Bool,columnCount: Int,today: Date) -> [UsageHeatmapDay?] {let todayTokenCount = usage?.tokenCount(on: today)let hasDailyUsageBuckets = usage?.hasDailyUsageBuckets == true- // 进阶模式开启时当天工作流统计可见- // 进阶模式关闭时只在 token bucket 已返回时展示今天- let endingDaysAgo = showsWorkflow || todayTokenCount != nil ? 0 : 1- let workflowByDate = workflow.dailyMetrics.reduce(into: [String: WorkflowDailyMetrics]()) { result, metrics in+ // 活动统计可见时包含今天, 仅展示 Token 时等待当天 bucket 返回+ let endingDaysAgo = showsActivity || todayTokenCount != nil ? 0 : 1+ let historyByDate = history.dailyMetrics.reduce(into: [String: ActivityMetrics]()) { result, metrics inresult[metrics.startDate] = metrics}let todayString = CodexDateFormat.dayString(from: today)@@ -73,8 +72,8 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {return UsageHeatmapDay(startDate: startDate,tokenState: tokenState,- workflow: workflowByDate[startDate] ?? .empty(startDate: startDate),- tokenUsage: workflow.tokenUsageByDate[startDate]+ history: historyByDate[startDate] ?? .empty(startDate: startDate),+ tokenUsage: history.tokenUsageByDate[startDate])}}diff --git a/CodexBar/Resources/CodexBar.entitlements b/CodexBar/Resources/CodexBar.entitlementsindex bd04f32..2d32a1d 100644--- a/CodexBar/Resources/CodexBar.entitlements+++ b/CodexBar/Resources/CodexBar.entitlements@@ -4,11 +4,11 @@<dict><key>com.apple.developer.icloud-container-identifiers</key><array>- <string>iCloud.app.zabrian.codexbar</string>+ <string>iCloud.app.zabrian.codexbar.data</string></array><key>com.apple.developer.icloud-services</key><array><string>CloudKit</string></array></dict>-</plist>+</plist>\ No newline at end of filediff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstringsindex 8fd9865..6355e38 100644--- a/CodexBar/Resources/Localizable.xcstrings+++ b/CodexBar/Resources/Localizable.xcstrings@@ -145,70 +145,6 @@}}},- "activity-protection.caption" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Hide inactive tasks and exclude them from keep-awake"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "任务长时间没有进展时隐藏并停止参与防睡眠"- }- }- }- },- "activity-protection.duration.hours" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "%lld hr"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "%lld 小时"- }- }- }- },- "activity-protection.duration.thirty-minutes" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "30 min"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "30 分钟"- }- }- }- },- "activity-protection.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Stalled Task Protection"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "异常会话保护"- }- }- }- },"activity.anonymous.keep-awake-exclusion" : {"localizations" : {"en" : {@@ -705,1538 +641,1586 @@}}},- "advanced-mode.codex.version.unavailable" : {+ "app.action.quit" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not determine the Codex version. Advanced Mode requires Codex %@ or later"+ "value" : "Quit CodexBar"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "无法确认 Codex 版本, 进阶模式需要 Codex %@ 或更高版本"+ "value" : "退出 CodexBar"}}}},- "advanced-mode.codex.version.unsupported" : {+ "app.command.settings" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enabling Advanced Mode requires Codex %@ or later"+ "value" : "Settings…"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "启用进阶模式需要 Codex %@ 或更高版本"+ "value" : "设置…"}}}},- "advanced-mode.hook.error.config-read-failed" : {+ "app.menu.log" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not read the Codex Hook configuration"+ "value" : "Log"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "读取 Codex Hook 配置失败"+ "value" : "日志"}}}},- "advanced-mode.hook.error.configuration-failed" : {+ "app.menu.settings" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not configure Codex Hook"+ "value" : "Settings"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "设置 Codex Hook 失败"+ "value" : "设置"}}}},- "advanced-mode.hook.error.invalid-config-format" : {+ "auto-reset.confirmation.message" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Invalid hooks.json format"+ "value" : "When enabled, CodexBar automatically uses a manual reset credit at the configured time before it expires and may briefly wake your Mac."}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "hooks.json 格式错误"+ "value" : "开启后, CodexBar 在手动重置临近过期时, 按设置的临期时间提前自动使用重置; 并可能短暂唤醒 Mac"}}}},- "advanced-mode.hook.error.trust-cleanup-unavailable" : {+ "auto-reset.confirmation.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Advanced Mode is off. Could not clear Hook trust"+ "value" : "Enable Automatic Reset?"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "进阶模式已关闭, 无法清理 Hook 信任状态"+ "value" : "开启自动重置?"}}}},- "advanced-mode.hook.error.verification-failed" : {+ "auto-reset.error.wake-schedule-failed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not verify Codex Hook: %@"+ "value" : "Could not schedule a wake event for Automatic Reset"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "无法验证 Codex Hook: %@"+ "value" : "设置自动重置唤醒计划失败"}}}},- "advanced-mode.hook.result.empty" : {+ "auto-reset.lead-time.fifteen-minutes" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex returned no Hook validation results"+ "value" : "15 Minutes"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 未返回 Hook 校验结果"+ "value" : "15 分钟"}}}},- "advanced-mode.hook.result.error" : {+ "auto-reset.lead-time.four-hours" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex reported Hook validation errors"+ "value" : "4 Hours"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 返回 Hook 校验错误"+ "value" : "4 小时"}}}},- "advanced-mode.hook.result.warning" : {+ "auto-reset.lead-time.one-hour" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex reported Hook validation warnings"+ "value" : "1 Hour"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 返回 Hook 校验警告"+ "value" : "1 小时"}}}},- "advanced-mode.hook.status.disabled" : {+ "auto-reset.lead-time.six-hours" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Hook is disabled"+ "value" : "6 Hours"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Hook 已被禁用"+ "value" : "6 小时"}}}},- "advanced-mode.hook.status.disabled-by-codex" : {+ "auto-reset.lead-time.thirty-minutes" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex Hook is disabled in Codex settings"+ "value" : "30 Minutes"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 配置已禁用 Hook"+ "value" : "30 分钟"}}}},- "advanced-mode.hook.status.inactive" : {+ "auto-reset.lead-time.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Hook is not working"+ "value" : "Time Before Expiration"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Hook 未生效"+ "value" : "临期时间"}}}},- "advanced-mode.hook.status.incomplete" : {+ "auto-reset.lead-time.two-hours" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Hook is incomplete"+ "value" : "2 Hours"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Hook 配置不完整"+ "value" : "2 小时"}}}},- "advanced-mode.hook.status.unexpected-source" : {+ "banked-reset.available-count" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Unexpected CodexBar Hook source"+ "value" : "%lld left"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Hook 意外来源"+ "value" : "可用: %lld"}}}},- "advanced-mode.hook.status.untrusted" : {+ "banked-reset.count" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Hook is not trusted"+ "value" : "Banked Resets: %lld"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Hook 未被信任"+ "value" : "留存重置: %lld"}}}},- "advanced-mode.name" : {+ "banked-reset.expiration.label" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Advanced Mode"+ "value" : "Expires"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "进阶模式"+ "value" : "过期时间"}}}},- "app.action.quit" : {+ "banked-reset.expiration.unknown" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Quit CodexBar"+ "value" : "Expiration time unknown"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "退出 CodexBar"+ "value" : "未知过期时间"}}}},- "app.command.settings" : {+ "codex-status.account.error.not-logged-in" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Settings…"+ "value" : "Codex is not signed in"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "设置…"+ "value" : "Codex 未登录"}}}},- "app.menu.log" : {+ "codex-status.account.not-signed-in" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Log"+ "value" : "Not signed in"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "日志"+ "value" : "未登录"}}}},- "app.menu.settings" : {+ "codex-status.account.unavailable" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Settings"+ "value" : "Codex account unavailable"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "设置"+ "value" : "Codex 账号异常"}}}},- "auto-reset.confirmation.message" : {+ "codex-status.app-server.error.connection-closed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "When enabled, CodexBar automatically uses a manual reset credit at the configured time before it expires and may briefly wake your Mac."+ "value" : "The Codex app-server connection closed"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "开启后, CodexBar 在手动重置临近过期时, 按设置的临期时间提前自动使用重置; 并可能短暂唤醒 Mac"+ "value" : "Codex app-server 连接已经断开"}}}},- "auto-reset.confirmation.title" : {+ "codex-status.app-server.error.invalid-response" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enable Automatic Reset?"+ "value" : "Could not parse the Codex app-server response"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "开启自动重置?"+ "value" : "Codex app-server 响应无法解析"}}}},- "auto-reset.error.wake-schedule-failed" : {+ "codex-status.app-server.error.server-timeout" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not schedule a wake event for Automatic Reset"+ "value" : "Timed out waiting for a Codex app-server response"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "设置自动重置唤醒计划失败"+ "value" : "Codex app-server 等待响应超时"}}}},- "auto-reset.lead-time.fifteen-minutes" : {+ "codex-status.app-server.error.unsupported-method" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "15 Minutes"+ "value" : "The Codex app-server does not support this method"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "15 分钟"+ "value" : "Codex app-server 不支持该接口"}}}},- "auto-reset.lead-time.four-hours" : {+ "codex-status.daemon.error.unavailable" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "4 Hours"+ "value" : "The shared Codex service is unavailable. Start a Codex session with the background service enabled, then reconnect."}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "4 小时"+ "value" : "Codex 共享服务不可用, 请启动已启用后台服务的 Codex 会话后重新连接"}}}},- "auto-reset.lead-time.one-hour" : {+ "codex-tui-notifications.error.read-failed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "1 Hour"+ "value" : "Could not read Codex TUI notification settings"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "1 小时"+ "value" : "读取 Codex TUI 通知设置失败"}}}},- "auto-reset.lead-time.six-hours" : {+ "codex-tui-notifications.error.state-mismatch" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "6 Hours"+ "value" : "Codex TUI notification status does not match the setting"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "6 小时"+ "value" : "Codex TUI 通知状态与设置不一致"}}}},- "auto-reset.lead-time.thirty-minutes" : {+ "codex-tui-notifications.error.write-failed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "30 Minutes"+ "value" : "Could not update Codex TUI notification settings"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "30 分钟"+ "value" : "写入 Codex TUI 通知设置失败"}}}},- "auto-reset.lead-time.title" : {+ "codex-version.requirement" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Time Before Expiration"+ "value" : "Codex %@ or later is required"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "临期时间"+ "value" : "需要 Codex %@ 或更高版本"}}}},- "auto-reset.lead-time.two-hours" : {+ "codex.source.error.not-found" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "2 Hours"+ "value" : "%@ not found"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "2 小时"+ "value" : "未找到 %@"}}}},- "banked-reset.available-count" : {+ "codex.version.launch-failed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "%lld left"+ "value" : "Failed to launch"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "可用: %lld"+ "value" : "启动失败"}}}},- "banked-reset.count" : {+ "codex.version.newer-installed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Banked Resets: %lld"+ "value" : "Installed: %@"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "留存重置: %lld"+ "value" : "已安装 %@"}}}},- "banked-reset.expiration.label" : {+ "codex.version.parse-failed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Expires"+ "value" : "Version not recognized"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "过期时间"+ "value" : "版本未知"}}}},- "banked-reset.expiration.unknown" : {+ "codex.version.read-failed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Expiration time unknown"+ "value" : "Failed to read version"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "未知过期时间"+ "value" : "读取失败"}}}},- "codex-cli.source.action.select" : {+ "codex.version.read-timeout" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Select Source"+ "value" : "Version check timed out"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "选择来源"+ "value" : "读取超时"}}}},- "codex-cli.source.automatic" : {+ "codex.version.unknown" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Automatic"+ "value" : "Unknown version"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "自动选择"+ "value" : "未知版本"}}}},- "codex-cli.source.error.not-found" : {+ "common.action.cancel" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "%@ not found"+ "value" : "Cancel"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "未找到 %@"+ "value" : "取消"}}}},- "codex-cli.source.status.in-use" : {+ "common.action.clear" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "In Use"+ "value" : "Clear"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "当前使用"+ "value" : "清空"}}}},- "codex-cli.source.status.unavailable" : {+ "common.action.click-to-copy" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Unavailable"+ "value" : "Click to Copy"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "不可用"+ "value" : "点击复制"}}}},- "codex-cli.version.launch-failed" : {+ "common.action.close" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Failed to launch"+ "value" : "Close"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "启动失败"+ "value" : "关闭"}}}},- "codex-cli.version.newer-installed" : {+ "common.action.copy" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Installed: %@"+ "value" : "Copy"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "已安装 %@"+ "value" : "复制"}}}},- "codex-cli.version.parse-failed" : {+ "common.action.enable" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Version not recognized"+ "value" : "Enable"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "版本未知"+ "value" : "开启"}}}},- "codex-cli.version.read-failed" : {+ "common.action.open-system-settings" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Failed to read version"+ "value" : "Open System Settings"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "读取失败"+ "value" : "打开系统设置"}}}},- "codex-cli.version.read-timeout" : {+ "common.action.preview" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Version check timed out"+ "value" : "Preview"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "读取超时"+ "value" : "预览"}}}},- "codex-cli.version.unknown" : {+ "common.action.quit" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Unknown version"+ "value" : "Quit"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "未知版本"+ "value" : "退出"}}}},- "codex-status.account.error.not-logged-in" : {+ "common.action.restore-default" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex is not signed in"+ "value" : "Restore Default"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 未登录"+ "value" : "恢复默认"}}}},- "codex-status.account.not-signed-in" : {+ "common.codex" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Not signed in"+ "value" : "Codex"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "未登录"+ "value" : "Codex"}}}},- "codex-status.account.unavailable" : {+ "common.empty.no-data" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex account unavailable"+ "value" : "No data"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 账号异常"+ "value" : "暂无数据"}}}},- "codex-status.app-server.error.connection-closed" : {+ "common.status.available" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "The Codex app-server connection closed"+ "value" : "Available"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex app-server 连接已经断开"+ "value" : "可用"}}}},- "codex-status.app-server.error.invalid-response" : {+ "common.status.completed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not parse the Codex app-server response"+ "value" : "Completed"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex app-server 响应无法解析"+ "value" : "完成"}}}},- "codex-status.app-server.error.server-timeout" : {+ "common.status.copied" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Timed out waiting for a Codex app-server response"+ "value" : "Copied"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex app-server 等待响应超时"+ "value" : "已复制"}}}},- "codex-status.app-server.error.unsupported-method" : {+ "common.status.not-set" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "The Codex app-server does not support this method"+ "value" : "Not set"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex app-server 不支持该接口"+ "value" : "未设置"}}}},- "codex-status.cli.error.executable-not-found" : {+ "date-picker.next-month" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not find the Codex CLI or app"+ "value" : "Next Month"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "找不到 Codex CLI 或 Codex App"+ "value" : "下个月"}}}},- "codex-tui-notifications.error.read-failed" : {+ "date-picker.previous-month" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not read Codex TUI notification settings"+ "value" : "Previous Month"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "读取 Codex TUI 通知设置失败"+ "value" : "上个月"}}}},- "codex-tui-notifications.error.state-mismatch" : {+ "date-picker.select-end" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex TUI notification status does not match the setting"+ "value" : "Select an end date"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex TUI 通知状态与设置不一致"+ "value" : "选择结束日期"}}}},- "codex-tui-notifications.error.write-failed" : {+ "date-picker.select-range" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not update Codex TUI notification settings"+ "value" : "Select Date Range"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "写入 Codex TUI 通知设置失败"+ "value" : "选择日期范围"}}}},- "codex-version.requirement" : {+ "date-picker.select-start" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex %@ or later is required"+ "value" : "Select a start date"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "需要 Codex %@ 或更高版本"+ "value" : "选择开始日期"}}}},- "common.action.cancel" : {+ "date-range.closed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Cancel"+ "value" : "%1$@ – %2$@"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "取消"+ "value" : "%1$@ ~ %2$@"}}}},- "common.action.clear" : {+ "date-range.open-ended" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Clear"+ "value" : "%@ –"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "清空"+ "value" : "%@ ~"}}}},- "common.action.click-to-copy" : {+ "duration.days-compact" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Click to Copy"+ "value" : "%lldd"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "点击复制"+ "value" : "%lld天"}}}},- "common.action.close" : {+ "duration.minutes" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Close"+ "value" : "%lld min"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "关闭"+ "value" : "%lld 分钟"}}}},- "common.action.copy" : {+ "duration.seconds" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Copy"+ "value" : "%lld sec"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "复制"+ "value" : "%lld 秒"}}}},- "common.action.enable" : {+ "helper.error.assets-invalid" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enable"+ "value" : "Helper validation failed. Reinstall CodexBar"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "开启"+ "value" : "CodexBar Helper 组件或配置异常, 请重新安装 CodexBar"}}}},- "common.action.open-system-settings" : {+ "helper.error.assets-missing" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Open System Settings"+ "value" : "Helper incomplete. Reinstall CodexBar"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "打开系统设置"+ "value" : "CodexBar Helper 组件或配置丢失, 请重新安装 CodexBar"}}}},- "common.action.preview" : {+ "helper.error.connection-failed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Preview"+ "value" : "Could not connect to the service"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "预览"+ "value" : "连接服务失败"}}}},- "common.action.quit" : {+ "helper.error.connection-interrupted" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Quit"+ "value" : "The service connection was interrupted"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "退出"+ "value" : "服务连接中断"}}}},- "common.action.restore-default" : {+ "helper.error.invalid-interface" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Restore Default"+ "value" : "Invalid service interface"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "恢复默认"+ "value" : "服务接口无效"}}}},- "common.codex" : {+ "helper.error.no-response" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex"+ "value" : "The service is not responding"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex"+ "value" : "服务无响应"}}}},- "common.empty.no-data" : {+ "helper.error.registration-failed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "No data"+ "value" : "Could not register the service"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "暂无数据"+ "value" : "注册服务失败"}}}},- "common.status.available" : {+ "helper.error.update-failed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Available"+ "value" : "Could not update the service"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "可用"+ "value" : "更新服务失败"}}}},- "common.status.completed" : {+ "helper.status.authorization-required" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Completed"+ "value" : "Allow CodexBar to run in the background"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "完成"+ "value" : "需要授权允许 CodexBar 后台运行"}}}},- "common.status.copied" : {+ "helper.status.install-and-authorize" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Copied"+ "value" : "Install CodexBar Helper and allow background activity"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "已复制"+ "value" : "需要安装并授权 CodexBar Helper 后台运行"}}}},- "common.status.not-set" : {+ "helper.status.installed-needs-authorization" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Not set"+ "value" : "CodexBar Helper installed. Allow background activity"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "未设置"+ "value" : "已安装 CodexBar Helper 但需要授权允许后台运行"}}}},- "date-picker.next-month" : {+ "helper.status.not-registered" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Next Month"+ "value" : "CodexBarHelper is not registered"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "下个月"+ "value" : "CodexBarHelper 尚未注册"}}}},- "date-picker.previous-month" : {+ "history.metric.approvals" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Previous Month"+ "value" : "Approvals"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "上个月"+ "value" : "权限请求"}}}},- "date-picker.select-end" : {+ "history.metric.compactions" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Select an end date"+ "value" : "Compactions"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "选择结束日期"+ "value" : "上下文压缩"}}}},- "date-picker.select-range" : {+ "history.metric.sessions" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Select Date Range"+ "value" : "Sessions"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "选择日期范围"+ "value" : "会话总数"}}}},- "date-picker.select-start" : {+ "history.metric.subagents" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Select a start date"+ "value" : "Subagents"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "选择开始日期"+ "value" : "子智能体"}}}},- "date-range.closed" : {+ "history.metric.tool-calls" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "%1$@ – %2$@"+ "value" : "Tool Calls"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "%1$@ ~ %2$@"+ "value" : "工具调用"}}}},- "date-range.open-ended" : {+ "history.metric.turns" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "%@ –"+ "value" : "Turns"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "%@ ~"+ "value" : "对话轮次"}}}},- "duration.days-compact" : {+ "history.rebuild.action" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "%lldd"+ "value" : "Rebuild"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "%lld天"+ "value" : "重建"}}}},- "duration.minutes" : {+ "history.rebuild.confirmation.message" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "%lld min"+ "value" : "Recalculate activity data and session data for %@ from locally collected app-server events and Token records.\nAfter syncing, local data will be replaced and cloud data updated"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "%lld 分钟"+ "value" : "将从本机采集的 app-server 事件和 Token 记录 重新统计 %@ 的活动数据和会话数据\n同步后将替换本机数据并更新云端数据"}}}},- "duration.seconds" : {+ "history.rebuild.confirmation.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "%lld sec"+ "value" : "Rebuild selected dates (%lld)?"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "%lld 秒"+ "value" : "批量重建 %lld 天的数据?"}}}},- "helper.error.assets-invalid" : {+ "history.rebuild.error.source-changed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Helper validation failed. Reinstall CodexBar"+ "value" : "Local data changed; try again"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Helper 组件或配置异常, 请重新安装 CodexBar"+ "value" : "本地数据发生变化, 请重试"}}}},- "helper.error.assets-missing" : {+ "history.rebuild.error.source-unavailable" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Helper incomplete. Reinstall CodexBar"+ "value" : "No local data is available to rebuild"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Helper 组件或配置丢失, 请重新安装 CodexBar"+ "value" : "没有可重建的本地数据"}}}},- "helper.error.connection-failed" : {+ "history.rebuild.error.token-history-already-running" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not connect to the service"+ "value" : "Session data is already being rebuilt"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "连接服务失败"+ "value" : "会话数据正在重建中"}}}},- "helper.error.connection-interrupted" : {+ "history.rebuild.result.completed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "The service connection was interrupted"+ "value" : "Rebuild Complete"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "服务连接中断"+ "value" : "重建完成"}}}},- "helper.error.invalid-interface" : {+ "history.rebuild.result.failed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Invalid service interface"+ "value" : "Rebuild Failed"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "服务接口无效"+ "value" : "重建失败"}}}},- "helper.error.no-response" : {+ "history.rebuild.summary.additional-dates" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "The service is not responding"+ "value" : ", etc"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "服务无响应"+ "value" : " 等"}}}},- "helper.error.registration-failed" : {+ "history.rebuild.summary.cloud-replacement-pending" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not register the service"+ "value" : "; cloud data will be replaced when sync becomes available"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "注册服务失败"+ "value" : "; 云端替换将在同步可用后继续"}}}},- "helper.error.update-failed" : {+ "history.rebuild.summary.completed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not update the service"+ "value" : "Days rebuilt: %1$lld; events: %2$lld"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "更新服务失败"+ "value" : "已重建 %1$lld 天, 包含活动事件 %2$lld 条"}}}},- "helper.status.authorization-required" : {+ "history.rebuild.summary.incomplete-dates" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Allow CodexBar to run in the background"+ "value" : "; dates not rebuilt (%1$lld): %2$@"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "需要授权允许 CodexBar 后台运行"+ "value" : "; %1$lld 天未完成 (%2$@)"}}}},- "helper.status.install-and-authorize" : {+ "history.rebuild.summary.retry-later" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Install CodexBar Helper and allow background activity"+ "value" : ", will retry automatically"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "需要安装并授权 CodexBar Helper 后台运行"+ "value" : ", 稍后会自动重试"}}}},- "helper.status.installed-needs-authorization" : {+ "history.rebuild.summary.skipped-invalid-events" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Helper installed. Allow background activity"+ "value" : "; skipped %lld invalid events"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "已安装 CodexBar Helper 但需要授权允许后台运行"+ "value" : ", 跳过 %lld 条无效数据"}}}},- "helper.status.not-registered" : {+ "history.rebuild.summary.sync-replacement-marking-failed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBarHelper is not registered"+ "value" : "; could not replace cloud data, please try again later"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBarHelper 尚未注册"+ "value" : "; 云端替换未能完成, 请稍后重新尝试"+ }+ }+ }+ },+ "history.rebuild.summary.token-history-incomplete" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "; session data rebuild incomplete, please retry"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "; 会话数据重建未完成, 请重试"+ }+ }+ }+ },+ "history.rebuild.summary.token-record-count" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "; %lld session data records"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "; 会话数据 %lld 条"+ }+ }+ }+ },+ "history.rebuild.title" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Rebuild Data"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "重建数据"}}}@@ -2673,6 +2657,22 @@}}},+ "log.action.latest" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Latest"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "最新日志"+ }+ }+ }+ },"log.action.preview-full" : {"localizations" : {"en" : {@@ -2817,6 +2817,38 @@}}},+ "log.connection.account" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Account"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "账户"+ }+ }+ }+ },+ "log.connection.activity" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Activity"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "活动"+ }+ }+ }+ },"log.empty.no-entries" : {"localizations" : {"en" : {@@ -2833,6 +2865,22 @@}}},+ "log.label.connection-event" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Connection"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "连接"+ }+ }+ }+ },"log.label.error" : {"localizations" : {"en" : {@@ -2849,6 +2897,54 @@}}},+ "log.label.local" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Local"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "本地"+ }+ }+ }+ },+ "log.label.received" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Received"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "接收"+ }+ }+ }+ },+ "log.label.sent" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Sent"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "发送"+ }+ }+ }+ },"log.payload.details" : {"localizations" : {"en" : {@@ -2865,6 +2961,22 @@}}},+ "log.payload.received" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Received Content"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "接收内容"+ }+ }+ }+ },"log.payload.request" : {"localizations" : {"en" : {@@ -2897,146 +3009,146 @@}}},- "log.status.in-progress" : {+ "log.persistence.error.read" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "In Progress"+ "value" : "Could not read the saved logs"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "进行中"+ "value" : "无法读取已保存的日志"}}}},- "log.status.waiting-response" : {+ "log.persistence.error.write" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Waiting for response"+ "value" : "Could not save the logs"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "等待响应"+ "value" : "无法保存日志"}}}},- "log.window.title" : {+ "log.persistence.interrupted" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Log"+ "value" : "The previous run ended before a response was received"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar 日志"+ "value" : "上次运行结束时尚未收到响应"}}}},- "menu-bar-quota.selection.off" : {+ "log.status.in-progress" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Off"+ "value" : "In Progress"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "关闭"+ "value" : "进行中"}}}},- "menu-bar-quota.selection.primary" : {+ "log.status.waiting-response" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Primary"+ "value" : "Waiting for response"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "主额度"+ "value" : "等待响应"}}}},- "menu-bar-quota.selection.secondary" : {+ "log.window.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Secondary"+ "value" : "CodexBar Log"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "次额度"+ "value" : "CodexBar 日志"}}}},- "notification.activity-protection.body.codex" : {+ "menu-bar-quota.selection.off" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "No progress on the Codex task for %@; hidden and excluded from keep-awake"+ "value" : "Off"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 任务已静默 %@, 已隐藏并停止参与防睡眠"+ "value" : "关闭"}}}},- "notification.activity-protection.body.project" : {+ "menu-bar-quota.selection.primary" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "No progress in \"%1$@\" for %2$@; hidden and excluded from keep-awake"+ "value" : "Primary"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "%1$@ 已静默 %2$@, 已隐藏并停止参与防睡眠"+ "value" : "主额度"}}}},- "notification.activity-protection.title" : {+ "menu-bar-quota.selection.secondary" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex Task Stalled"+ "value" : "Secondary"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 任务长时间无进展"+ "value" : "次额度"}}}@@ -3249,2690 +3361,2020 @@}}},- "notification.quota-reset.body" : {+ "notification.protection.body.codex" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "%1$@ %2$@"+ "value" : "No progress on the Codex task for %@; hidden and excluded from keep-awake"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "%1$@ %2$@"+ "value" : "Codex 任务已静默 %@, 已隐藏并停止参与防睡眠"}}}},- "notification.quota-reset.title" : {+ "notification.protection.body.project" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Quota Reset"+ "value" : "No progress in \"%1$@\" for %2$@; hidden and excluded from keep-awake"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "额度已重置"+ "value" : "%1$@ 已静默 %2$@, 已隐藏并停止参与防睡眠"}}}},- "notification.sound.default" : {+ "notification.protection.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Default"+ "value" : "Codex Task Stalled"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "默认"+ "value" : "Codex 任务长时间无进展"}}}},- "notification.sound.silent" : {+ "notification.quota-reset.body" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "None"+ "value" : "%1$@ %2$@"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "静音"+ "value" : "%1$@ %2$@"}}}},- "notification.task-completed.body.codex" : {+ "notification.quota-reset.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex task completed • %@"+ "value" : "Quota Reset"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 任务完成, %@"+ "value" : "额度已重置"}}}},- "notification.task-completed.body.project" : {+ "notification.sound.default" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Task completed in \"%1$@\" • %2$@"+ "value" : "Default"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "「%1$@」任务完成, %2$@"+ "value" : "默认"}}}},- "notification.task-completed.title" : {+ "notification.sound.silent" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex Task Completed"+ "value" : "None"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 任务完成"+ "value" : "静音"}}}},- "notification.task-waiting.body.codex" : {+ "notification.task-completed.body.codex" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex is waiting for approval to continue"+ "value" : "Codex task completed • %@"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 正在等待批准下一步操作"+ "value" : "Codex 任务完成, %@"}}}},- "notification.task-waiting.body.codex-tool" : {+ "notification.task-completed.body.project" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex is waiting for approval to use %@"+ "value" : "Task completed in \"%1$@\" • %2$@"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 正在等待批准使用 %@"+ "value" : "「%1$@」任务完成, %2$@"}}}},- "notification.task-waiting.body.project" : {+ "notification.task-completed.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "A task in \"%@\" is waiting for action approval"+ "value" : "Codex Task Completed"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "「%@」正在等待批准操作"+ "value" : "Codex 任务完成"}}}},- "notification.task-waiting.body.project-tool" : {+ "notification.task-waiting.body.codex" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "A task in \"%1$@\" is waiting for approval to use %2$@"+ "value" : "Codex is waiting for approval to continue"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "「%1$@」正在等待批准 %2$@ 操作"+ "value" : "Codex 正在等待批准下一步操作"}}}},- "notification.task-waiting.title" : {+ "notification.task-waiting.body.codex-tool" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex Is Waiting for Approval"+ "value" : "Codex is waiting for approval to use %@"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 等待批准"+ "value" : "Codex 正在等待批准使用 %@"}}}},- "proxy.action.cancel-test" : {+ "notification.task-waiting.body.project" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Cancel Test"+ "value" : "A task in \"%@\" is waiting for action approval"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "取消测试"+ "value" : "「%@」正在等待批准操作"}}}},- "proxy.action.clear-configuration" : {+ "notification.task-waiting.body.project-tool" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Delete Configuration"+ "value" : "A task in \"%1$@\" is waiting for approval to use %2$@"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "删除配置"+ "value" : "「%1$@」正在等待批准 %2$@ 操作"}}}},- "proxy.action.save" : {+ "notification.task-waiting.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Save"+ "value" : "Codex Is Waiting for Approval"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "保存"+ "value" : "Codex 等待批准"}}}},- "proxy.action.test-connection" : {+ "protection.caption" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Test Connection"+ "value" : "Hide inactive tasks and exclude them from keep-awake"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "测试连接"+ "value" : "任务长时间没有进展时隐藏并停止参与防睡眠"}}}},- "proxy.authentication" : {+ "protection.duration.hours" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Authentication"+ "value" : "%lld hr"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "身份验证"+ "value" : "%lld 小时"}}}},- "proxy.configuration.title" : {+ "protection.duration.thirty-minutes" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Proxy Configuration"+ "value" : "30 min"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "代理配置"+ "value" : "30 分钟"}}}},- "proxy.enabled" : {+ "protection.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enable proxy"+ "value" : "Stalled Task Protection"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "启用代理"+ "value" : "异常会话保护"}}}},- "proxy.error.configuration-unreadable" : {+ "quota.credits.value" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Proxy error: unable to read configuration"+ "value" : "Credits: %@"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "代理配置错误: 无法读取配置"+ "value" : "积分: %@"}}}},- "proxy.error.invalid-endpoint" : {+ "quota.status.remaining" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Proxy error: invalid server"+ "value" : "%1$@: %2$@ remaining"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "代理配置错误: 服务器无效"+ "value" : "%1$@ 剩余 %2$@"}}}},- "proxy.error.invalid-username" : {+ "quota.value.unlimited" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Proxy error: invalid username"+ "value" : "Unlimited"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "代理配置错误: 用户名无效"+ "value" : "无限"}}}},- "proxy.feedback.clear-failed" : {+ "quota.window.fallback" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not clear proxy configuration"+ "value" : "Quota"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "清除代理配置失败"+ "value" : "额度"}}}},- "proxy.feedback.load-failed" : {+ "settings.about.github-project" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Load failed"+ "value" : "GitHub Project"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "读取失败"+ "value" : "GitHub 项目"}}}},- "proxy.feedback.save-failed" : {+ "settings.about.helper.authorized" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Save failed"+ "value" : "Authorized"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "保存失败"+ "value" : "已授权"}}}},- "proxy.password" : {+ "settings.about.helper.not-installed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Password"+ "value" : "Not Installed"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "密码"+ "value" : "未安装"}}}},- "proxy.server" : {+ "settings.about.helper.requires-approval" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Proxy server"+ "value" : "Not Authorized"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "代理服务器"+ "value" : "未授权"}}}},- "proxy.test.codex-login-required" : {+ "settings.about.helper.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Sign in to Codex"+ "value" : "CodexBar Helper"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "请登录 Codex"+ "value" : "CodexBar Helper"}}}},- "proxy.test.codex-unavailable" : {+ "settings.about.helper.unavailable" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex unavailable"+ "value" : "Unavailable"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 不可用"+ "value" : "不可用"}}}},- "proxy.test.connected" : {+ "settings.about.version" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Connected"+ "value" : "CodexBar Version"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "连接成功"+ "value" : "CodexBar 版本"}}}},- "proxy.test.connection-failed" : {+ "settings.auto-reset.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Connection failed"+ "value" : "Automatic Reset"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "连接失败"+ "value" : "自动重置"}}}},- "proxy.test.proxy-authentication-failed" : {+ "settings.codex.connection.action.reconnect" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Authentication failed"+ "value" : "Reconnect"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "身份验证失败"+ "value" : "重新建立连接"}}}},- "proxy.test.timed-out" : {+ "settings.codex.connection.status.reconnecting" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Timed out"+ "value" : "Reconnecting"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "连接超时"+ "value" : "正在重新连接"}}}},- "proxy.title" : {+ "settings.codex.daemon.disconnected" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Network Proxy"+ "value" : "Not Connected"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "网络代理"+ "value" : "未连接"}}}},- "proxy.username" : {+ "settings.codex.daemon.in-use" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Username"+ "value" : "In Use"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "用户名"+ "value" : "当前使用"}}}},- "proxy.validation.host.invalid" : {+ "settings.codex.daemon.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Invalid host"+ "value" : "Codex Daemon"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "主机错误"+ "value" : "Codex Daemon"}}}},- "proxy.validation.host.required" : {+ "settings.codex.version.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enter server"+ "value" : "Codex Versions"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "请输入服务器地址"+ "value" : "Codex 版本"}}}},- "proxy.validation.port.invalid" : {+ "settings.data-update.interval.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Port 1–65535"+ "value" : "Data Update Interval"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "端口范围 1~65535"+ "value" : "数据更新间隔"}}}},- "proxy.validation.port.required" : {+ "settings.general.automatic-update-checks" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enter port"+ "value" : "Automatically Check for Updates"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "请输入端口"+ "value" : "自动检查更新"}}}},- "proxy.validation.username.invalid" : {+ "settings.general.launch-at-login" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Invalid username"+ "value" : "Launch at Login"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "用户名格式有误"+ "value" : "开机自动启动"}}}},- "proxy.validation.username.required" : {+ "settings.general.launch-at-login-failed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enter username"+ "value" : "Could not update Launch at Login"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "请输入用户名"+ "value" : "设置开机启动失败"}}}},- "quota.credits.value" : {+ "settings.hotkey.action.clear" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Credits: %@"+ "value" : "Clear App Shortcut"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "积分: %@"+ "value" : "清除 App 快捷键"}}}},- "quota.status.remaining" : {+ "settings.hotkey.prompt" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "%1$@: %2$@ remaining"+ "value" : "Press a Shortcut"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "%1$@ 剩余 %2$@"+ "value" : "请设置快捷键"}}}},- "quota.value.unlimited" : {+ "settings.hotkey.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Unlimited"+ "value" : "App Shortcut"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "无限"+ "value" : "App 快捷键"}}}},- "quota.window.fallback" : {+ "settings.keep-alive.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Quota"+ "value" : "Prevent System Sleep"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "额度"+ "value" : "防止系统睡眠"}}}},- "settings.about.github-project" : {+ "settings.main-panel.animations" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "GitHub Project"+ "value" : "Animation Effects"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "GitHub 项目"+ "value" : "动画效果"}}}},- "settings.about.helper.authorized" : {+ "settings.main-panel.layout.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Authorized"+ "value" : "Main Panel Layout"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "已授权"+ "value" : "主面板布局"}}}},- "settings.about.helper.not-installed" : {+ "settings.main-panel.section.account" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Not Installed"+ "value" : "Account"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "未安装"+ "value" : "账户"}}}},- "settings.about.helper.requires-approval" : {+ "settings.main-panel.section.activity" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Not Authorized"+ "value" : "Tasks"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "未授权"+ "value" : "任务"}}}},- "settings.about.helper.title" : {+ "settings.main-panel.section.quota" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Helper"+ "value" : "Quota"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Helper"+ "value" : "额度"}}}},- "settings.about.helper.unavailable" : {+ "settings.main-panel.section.status" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Unavailable"+ "value" : "Status"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "不可用"+ "value" : "状态"}}}},- "settings.about.version" : {+ "settings.main-panel.section.usage" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Version"+ "value" : "Usage"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar 版本"+ "value" : "用量"}}}},- "settings.auto-reset.title" : {+ "settings.menu-bar-quota.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Automatic Reset"+ "value" : "Menu Bar Quota Indicator"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "自动重置"+ "value" : "菜单栏额度指示"}}}},- "settings.codex.connection.action.reconnect" : {+ "settings.menu-bar-quota.window" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Reconnect"+ "value" : "Quota Window"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "重新建立连接"+ "value" : "额度窗口"}}}},- "settings.codex.connection.status.reconnecting" : {+ "settings.notifications.auto-reset.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Reconnecting"+ "value" : "Automatic Reset Notifications"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "正在重新连接"+ "value" : "自动重置通知"}}}},- "settings.codex.version.title" : {+ "settings.notifications.banked-reset-expiry.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Codex Versions"+ "value" : "Reset Expiration"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "Codex 版本"+ "value" : "重置临期通知"}}}},- "settings.data-update.interval.title" : {+ "settings.notifications.codex-tui.caption" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Data Update Interval"+ "value" : "Separate from CodexBar notifications"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "数据更新间隔"+ "value" : "Codex TUI 通知, 独立于 CodexBar 通知"}}}},- "settings.general.automatic-update-checks" : {+ "settings.notifications.codex-tui.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Automatically Check for Updates"+ "value" : "Codex TUI Notifications"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "自动检查更新"+ "value" : "Codex TUI 通知"}}}},- "settings.general.launch-at-login" : {+ "settings.notifications.keep-alive-limit.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Launch at Login"+ "value" : "Keep-Awake Limit"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "开机自动启动"+ "value" : "防睡眠上限通知"}}}},- "settings.general.launch-at-login-failed" : {+ "settings.notifications.low-battery.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not update Launch at Login"+ "value" : "Low Battery Alert"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "设置开机启动失败"+ "value" : "低电量保护通知"}}}},- "settings.hotkey.action.clear" : {+ "settings.notifications.low-quota.threshold" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Clear App Shortcut"+ "value" : "Low Quota Threshold"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "清除 App 快捷键"+ "value" : "低额度阈值"}}}},- "settings.hotkey.prompt" : {+ "settings.notifications.low-quota.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Press a Shortcut"+ "value" : "Low Quota"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "请设置快捷键"+ "value" : "额度预警通知"}}}},- "settings.hotkey.title" : {+ "settings.notifications.quota-reset.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "App Shortcut"+ "value" : "Quota Reset"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "App 快捷键"+ "value" : "额度重置通知"}}}},- "settings.keep-alive.title" : {+ "settings.notifications.sound.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Prevent System Sleep"+ "value" : "Sound"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "防止系统睡眠"+ "value" : "通知音效"}}}},- "settings.main-panel.animations" : {+ "settings.notifications.system.permission-disabled" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Animation Effects"+ "value" : "Notification permission has not been granted"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "动画效果"+ "value" : "系统通知权限未开启"}}}},- "settings.main-panel.layout.title" : {+ "settings.notifications.system.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Main Panel Layout"+ "value" : "System Notifications"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "主面板布局"+ "value" : "系统通知"}}}},- "settings.main-panel.section.account" : {+ "settings.notifications.task-completion.minimum-duration" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Account"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "账户"- }- }- }- },- "settings.main-panel.section.activity" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Tasks"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "任务"- }- }- }- },- "settings.main-panel.section.quota" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Quota"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "额度"- }- }- }- },- "settings.main-panel.section.status" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Status"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "状态"- }- }- }- },- "settings.main-panel.section.usage" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Usage"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "用量"- }- }- }- },- "settings.menu-bar-quota.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Menu Bar Quota Indicator"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "菜单栏额度指示"- }- }- }- },- "settings.menu-bar-quota.window" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Quota Window"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "额度窗口"- }- }- }- },- "settings.notifications.auto-reset.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Automatic Reset Notifications"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "自动重置通知"- }- }- }- },- "settings.notifications.banked-reset-expiry.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Reset Expiration"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "重置临期通知"- }- }- }- },- "settings.notifications.codex-tui.caption" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Separate from CodexBar notifications"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "Codex TUI 通知, 独立于 CodexBar 通知"- }- }- }- },- "settings.notifications.codex-tui.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Codex TUI Notifications"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "Codex TUI 通知"- }- }- }- },- "settings.notifications.keep-alive-limit.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Keep-Awake Limit"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "防睡眠上限通知"- }- }- }- },- "settings.notifications.low-battery.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Low Battery Alert"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "低电量保护通知"- }- }- }- },- "settings.notifications.low-quota.threshold" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Low Quota Threshold"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "低额度阈值"- }- }- }- },- "settings.notifications.low-quota.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Low Quota"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "额度预警通知"- }- }- }- },- "settings.notifications.quota-reset.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Quota Reset"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "额度重置通知"- }- }- }- },- "settings.notifications.sound.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Sound"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "通知音效"- }- }- }- },- "settings.notifications.system.permission-disabled" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Notification permission has not been granted"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "系统通知权限未开启"- }- }- }- },- "settings.notifications.system.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "System Notifications"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "系统通知"- }- }- }- },- "settings.notifications.task-completion.minimum-duration" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Task Duration"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "任务时长"- }- }- }- },- "settings.notifications.task-completion.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Task Completion"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "任务完成通知"- }- }- }- },- "settings.notifications.task-haptics.caption" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Trackpad haptics when tasks finish or await approval"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "任务完成或等待批准时触发触摸板震动"- }- }- }- },- "settings.notifications.task-haptics.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Task Haptics"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "任务触觉反馈"- }- }- }- },- "settings.notifications.task-waiting.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Approval Requests"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "任务等待通知"- }- }- }- },- "settings.sync.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Sync Across Devices"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "跨设备同步"- }- }- }- },- "settings.tab.about" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "About"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "关于"- }- }- }- },- "settings.tab.advanced" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Advanced"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "高级"- }- }- }- },- "settings.tab.general" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "General"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "通用"- }- }- }- },- "settings.task-glow.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Glow Effect"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "流光效果"- }- }- }- },- "settings.window.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "CodexBar Settings"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "CodexBar 设置"- }- }- }- },- "status-item.activity-summary" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Waiting: %1$lld • Running: %2$lld"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "等待 %1$lld • 运行 %2$lld"- }- }- }- },- "sync.error.retry-later" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Sync failed; try again later"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "同步失败, 请稍后重试"- }- }- }- },- "sync.icloud.error.account-unavailable" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "iCloud account unavailable"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "iCloud 账户不可用"- }- }- }- },- "sync.icloud.error.network-unavailable" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Network unavailable"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "网络不可用"- }- }- }- },- "sync.icloud.error.service-unavailable" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Service temporarily unavailable"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "服务暂时不可用"- }- }- }- },- "sync.status.disabled" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Sync is off"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "同步未开启"- }- }- }- },- "sync.status.last-sync" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Last Sync"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "最近同步"- }- }- }- },- "sync.status.last-sync-time" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Last sync: %@"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "最近同步: %@"- }- }- }- },- "sync.status.no-history" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "No sync history"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "暂无同步记录"- }- }- }- },- "sync.status.syncing" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Syncing"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "正在同步"- }- }- }- },- "sync.status.unavailable" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Sync unavailable"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "同步不可用"- }- }- }- },- "task-glow.brightness.title" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Brightness"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "亮度"- }- }- }- },- "task-glow.color.completed" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Completed"+ "value" : "Task Duration"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "已完成"+ "value" : "任务时长"}}}},- "task-glow.color.preview-help" : {+ "settings.notifications.task-completion.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Double-click to preview effect"+ "value" : "Task Completion"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "双击预览效果"+ "value" : "任务完成通知"}}}},- "task-glow.color.running" : {+ "settings.notifications.task-haptics.caption" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Running"+ "value" : "Trackpad haptics when tasks finish or await approval"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "运行中"+ "value" : "任务完成或等待批准时触发触摸板震动"}}}},- "task-glow.color.terminated" : {+ "settings.notifications.task-haptics.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Stopped"+ "value" : "Task Haptics"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "已终止"+ "value" : "任务触觉反馈"}}}},- "task-glow.color.waiting" : {+ "settings.notifications.task-waiting.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Waiting for Approval"+ "value" : "Approval Requests"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "等待批准"+ "value" : "任务等待通知"}}}},- "task-glow.duration.title" : {+ "settings.sync.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "End Duration"+ "value" : "Sync Across Devices"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "结束时长"+ "value" : "跨设备同步"}}}},- "task-glow.speed.fast" : {+ "settings.tab.about" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Faster"+ "value" : "About"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "较快"+ "value" : "关于"}}}},- "task-glow.speed.slow" : {+ "settings.tab.advanced" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Slower"+ "value" : "Advanced"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "较慢"+ "value" : "高级"}}}},- "task-glow.speed.standard" : {+ "settings.tab.general" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Standard"+ "value" : "General"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "标准"+ "value" : "通用"}}}},- "task-glow.speed.title" : {+ "settings.task-glow.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Animation Speed"+ "value" : "Glow Effect"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "动画速度"+ "value" : "流光效果"}}}},- "updater.action.check" : {+ "settings.window.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Check for Updates"+ "value" : "CodexBar Settings"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "检查更新"+ "value" : "CodexBar 设置"}}}},- "updater.action.install" : {+ "status-item.activity-summary" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Update Now"+ "value" : "Waiting: %1$lld • Running: %2$lld"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "立即更新"+ "value" : "等待 %1$lld • 运行 %2$lld"}}}},- "updater.status.check-failed" : {+ "sync.error.activity-generation" : {+ "extractionState" : "manual","localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Could not check for updates"+ "value" : "Activity history for %@ has no valid generation and cannot be synchronized"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "检查更新失败"+ "value" : "%@ 的活动历史缺少有效代次, 无法同步"}}}},- "updater.status.checking" : {+ "sync.error.activity-identity" : {+ "extractionState" : "manual","localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Checking for updates"+ "value" : "The activity record identity does not match its device, date and generation"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "正在检查更新"+ "value" : "活动同步记录身份与设备 日期 代次不一致"}}}},- "updater.status.missing-configuration" : {+ "sync.error.retry-later" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Update source is not configured"+ "value" : "Sync failed; try again later"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "未配置更新源"+ "value" : "同步失败, 请稍后重试"}}}},- "updater.status.up-to-date" : {+ "sync.icloud.error.account-unavailable" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar is up to date"+ "value" : "iCloud account unavailable"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "没有可用更新"+ "value" : "iCloud 账户不可用"}}}},- "updater.status.update-available" : {+ "sync.icloud.error.network-unavailable" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Version v%@ is available"+ "value" : "Network unavailable"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "发现新版本: v%@"+ "value" : "网络不可用"}}}},- "usage.heatmap.activity-metrics" : {+ "sync.icloud.error.service-unavailable" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Activity data"+ "value" : "Service temporarily unavailable"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "活动数据"+ "value" : "服务暂时不可用"}}}},- "usage.heatmap.no-data" : {+ "sync.status.disabled" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "No daily usage data"+ "value" : "Sync is off"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "暂无日用量数据"+ "value" : "同步未开启"}}}},- "usage.heatmap.past-weeks" : {+ "sync.status.last-sync" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Past %lld Weeks"+ "value" : "Last Sync"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "近 %lld 周"+ "value" : "最近同步"}}}},- "usage.heatmap.token-metrics" : {+ "sync.status.last-sync-time" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Session data"+ "value" : "Last sync: %@"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "会话数据"+ "value" : "最近同步: %@"}}}},- "usage.heatmap.top-model" : {+ "sync.status.no-history" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Top Model"+ "value" : "No sync history"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "最热模型"+ "value" : "暂无同步记录"}}}},- "usage.status.last-updated" : {+ "sync.status.syncing" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Updated"+ "value" : "Syncing"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "数据更新时间"+ "value" : "正在同步"}}}},- "usage.summary.current-streak" : {+ "sync.status.unavailable" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Current Streak"+ "value" : "Sync unavailable"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "当前连胜"+ "value" : "同步不可用"}}}},- "usage.summary.lifetime-tokens" : {+ "task-glow.brightness.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Lifetime Tokens"+ "value" : "Brightness"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "全时累计"+ "value" : "亮度"}}}},- "usage.summary.longest-chat" : {+ "task-glow.color.completed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Longest Task"+ "value" : "Completed"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "最长任务"+ "value" : "已完成"}}}},- "usage.summary.longest-streak" : {+ "task-glow.color.preview-help" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Longest Streak"+ "value" : "Double-click to preview effect"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "最长连胜"+ "value" : "双击预览效果"}}}},- "usage.summary.peak-tokens" : {+ "task-glow.color.running" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Peak Tokens"+ "value" : "Running"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "单日峰值"+ "value" : "运行中"}}}},- "usage.tokens.cache-hit-rate" : {+ "task-glow.color.terminated" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Cache-H"+ "value" : "Stopped"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "缓存命中率"+ "value" : "已终止"}}}},- "usage.tokens.cache-write-input" : {+ "task-glow.color.waiting" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Cache-W"+ "value" : "Waiting for Approval"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "缓存写入"+ "value" : "等待批准"}}}},- "usage.tokens.cached-input" : {+ "task-glow.duration.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Cached"+ "value" : "End Duration"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "缓存命中"+ "value" : "结束时长"}}}},- "usage.tokens.input" : {+ "task-glow.speed.fast" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Input"+ "value" : "Faster"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "输入总计"+ "value" : "较快"}}}},- "usage.tokens.output" : {+ "task-glow.speed.slow" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Output"+ "value" : "Slower"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "输出总计"+ "value" : "较慢"}}}},- "usage.tokens.reasoning-output" : {+ "task-glow.speed.standard" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Reasoning"+ "value" : "Standard"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "推理输出"+ "value" : "标准"}}}},- "usage.tokens.total" : {+ "task-glow.speed.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Total"+ "value" : "Animation Speed"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "总计"+ "value" : "动画速度"}}}},- "workflow.metric.approvals" : {+ "updater.action.check" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Approvals"+ "value" : "Check for Updates"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "权限请求"+ "value" : "检查更新"}}}},- "workflow.metric.compactions" : {+ "updater.action.install" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Compactions"+ "value" : "Update Now"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "上下文压缩"+ "value" : "立即更新"}}}},- "workflow.metric.sessions" : {+ "updater.status.check-failed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Sessions"+ "value" : "Could not check for updates"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "会话总数"+ "value" : "检查更新失败"}}}},- "workflow.metric.subagents" : {+ "updater.status.checking" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Subagents"+ "value" : "Checking for updates"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "子智能体"+ "value" : "正在检查更新"}}}},- "workflow.metric.tool-calls" : {+ "updater.status.missing-configuration" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Tool Calls"+ "value" : "Update source is not configured"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "工具调用"+ "value" : "未配置更新源"}}}},- "workflow.metric.turns" : {+ "updater.status.up-to-date" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Turns"+ "value" : "CodexBar is up to date"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "对话轮次"+ "value" : "没有可用更新"}}}},- "workflow.rebuild.action" : {+ "updater.status.update-available" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Rebuild"+ "value" : "Version v%@ is available"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "重建"+ "value" : "发现新版本: v%@"}}}},- "workflow.rebuild.confirmation.message" : {+ "usage.heatmap.activity-metrics" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Recalculate activity data and session data for %@ from local Hook events and rollouts.\nAfter syncing, local data will be replaced and cloud data updated"+ "value" : "Activity data"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "将从本机 Hook 事件和 rollout 重新统计 %@ 的活动数据和会话数据\n同步后将替换本机数据并更新云端数据"+ "value" : "活动数据"}}}},- "workflow.rebuild.confirmation.title" : {+ "usage.heatmap.no-data" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Rebuild selected dates (%lld)?"+ "value" : "No daily usage data"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "批量重建 %lld 天的数据?"+ "value" : "暂无日用量数据"}}}},- "workflow.rebuild.error.source-changed" : {+ "usage.heatmap.past-weeks" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Local data changed; try again"+ "value" : "Past %lld Weeks"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "本地数据发生变化, 请重试"+ "value" : "近 %lld 周"}}}},- "workflow.rebuild.error.source-unavailable" : {+ "usage.heatmap.token-metrics" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "No local data is available to rebuild"+ "value" : "Session data"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "没有可重建的本地数据"+ "value" : "会话数据"}}}},- "workflow.rebuild.error.token-history-already-running" : {+ "usage.heatmap.top-model" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Session data is already being rebuilt"+ "value" : "Top Model"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "会话数据正在重建中"+ "value" : "最热模型"}}}},- "workflow.rebuild.result.completed" : {+ "usage.status.last-updated" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Rebuild Complete"+ "value" : "Updated"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "重建完成"+ "value" : "数据更新时间"}}}},- "workflow.rebuild.result.failed" : {+ "usage.summary.current-streak" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Rebuild Failed"+ "value" : "Current Streak"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "重建失败"+ "value" : "当前连胜"}}}},- "workflow.rebuild.summary.additional-dates" : {+ "usage.summary.lifetime-tokens" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : ", etc"+ "value" : "Lifetime Tokens"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : " 等"+ "value" : "全时累计"}}}},- "workflow.rebuild.summary.cloud-replacement-pending" : {+ "usage.summary.longest-chat" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "; cloud data will be replaced when sync becomes available"+ "value" : "Longest Task"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "; 云端替换将在同步可用后继续"+ "value" : "最长任务"}}}},- "workflow.rebuild.summary.completed" : {+ "usage.summary.longest-streak" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Days rebuilt: %1$lld; events: %2$lld"+ "value" : "Longest Streak"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "已重建 %1$lld 天, 包含 Hook 数据 %2$lld 条"+ "value" : "最长连胜"}}}},- "workflow.rebuild.summary.incomplete-dates" : {+ "usage.summary.peak-tokens" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "; dates not rebuilt (%1$lld): %2$@"+ "value" : "Peak Tokens"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "; %1$lld 天未完成 (%2$@)"+ "value" : "单日峰值"}}}},- "workflow.rebuild.summary.retry-after-advanced-mode-enabled" : {+ "usage.tokens.cache-hit-rate" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : ", will retry automatically after Advanced Mode is enabled"+ "value" : "Cache-H"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : ", 开启进阶模式后会自动重试"+ "value" : "缓存命中率"}}}},- "workflow.rebuild.summary.retry-later" : {+ "usage.tokens.cache-write-input" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : ", will retry automatically"+ "value" : "Cache-W"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : ", 稍后会自动重试"+ "value" : "缓存写入"}}}},- "workflow.rebuild.summary.skipped-invalid-events" : {+ "usage.tokens.cached-input" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "; skipped %lld invalid events"+ "value" : "Cached"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : ", 跳过 %lld 条无效数据"+ "value" : "缓存命中"}}}},- "workflow.rebuild.summary.sync-replacement-marking-failed" : {+ "usage.tokens.input" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "; could not replace cloud data, please try again later"+ "value" : "Input"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "; 云端替换未能完成, 请稍后重新尝试"+ "value" : "输入总计"}}}},- "workflow.rebuild.summary.token-history-incomplete" : {+ "usage.tokens.output" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "; session data rebuild incomplete, please retry"+ "value" : "Output"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "; 会话数据重建未完成, 请重试"+ "value" : "输出总计"}}}},- "workflow.rebuild.summary.token-record-count" : {+ "usage.tokens.reasoning-output" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "; %lld session data records"+ "value" : "Reasoning"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "; 会话数据 %lld 条"+ "value" : "推理输出"}}}},- "workflow.rebuild.title" : {+ "usage.tokens.total" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Rebuild Data"+ "value" : "Total"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "重建数据"+ "value" : "总计"}}}diff --git a/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift b/CodexBar/Services/Activity/ActivityMonitor+Completion.swiftsimilarity index 77%rename from CodexBar/Services/Workflow/CodexActivityTerminalResolution.swiftrename to CodexBar/Services/Activity/ActivityMonitor+Completion.swiftindex 08ca273..1b615ee 100644--- a/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift+++ b/CodexBar/Services/Activity/ActivityMonitor+Completion.swift@@ -2,18 +2,18 @@ import Combineimport Foundationimport os-extension CodexActivityMonitor {+extension ActivityMonitor {/// Interrupt 只结束匹配的 turn, 不清空同 session 的新任务- func interruptTask(from event: WorkflowHookEvent, source: CodexActivityEventSource) {- let eventKey = CodexActivityTaskKey(event: event)+ func interruptTask(from event: ActivityRecord, source: ActivityEventSource) {+ let eventKey = ActivityTaskKey(event: event)if recentEndedDate(for: eventKey) != nil {discardStaleTerminalTask(for: eventKey)return}let match = matchingTerminalTask(for: event, allowsAnonymousFallback: event.sessionID == nil)- let key: CodexActivityTaskKey- let task: CodexActivityTask?+ let key: ActivityTaskKey+ let task: ActivityTask?switch match {case let .active(matchedKey):key = matchedKey@@ -28,7 +28,7 @@ extension CodexActivityMonitor {key = eventKeytask = nil}- guard task.map({ event.timestamp >= $0.lastMainHookEventAt }) ?? true else {+ guard task.map({ event.timestamp >= $0.lastMainEventAt }) ?? true else {return}if recentEndedDate(for: key) != nil {@@ -38,14 +38,14 @@ extension CodexActivityMonitor {tasks.removeValue(forKey: key)pendingTerminalTasks.removeValue(forKey: key)- clearActivityProtection(for: key, taskID: task?.displayID, reason: .terminal)+ clearProtection(for: key, taskID: task?.displayID, reason: .terminal)let termination = storeTermination(for: key,projectName: event.projectDisplayName ?? task?.projectName,- modelName: event.modelName ?? task?.modelName,+ modelName: event.model ?? task?.modelName,effort: event.effort ?? task?.effort,terminatedAt: event.timestamp,- duration: task?.preciseDuration(until: event.timestamp),+ duration: event.source == nil || event.source?.turnCompletedAt != nil ? task?.preciseDuration(until: event.timestamp) : nil,task: task)recordTerminalPresentationEvent(.terminated(termination))@@ -55,16 +55,16 @@ extension CodexActivityMonitor {}recordEndedTask(eventKey, at: event.timestamp)if source == .live {- AppLog.activity.notice("任务已终止: source=interruptHook")+ AppLog.activity.notice("任务已终止: source=turnInterrupted")}}// MARK: - 终态判定与记录- /// PermissionRequest 表示进入审批流程; 只有 rollout 明确把审批路由给 user 时才是 UI 等待+ /// PermissionRequest 表示进入审批流程; 只有 服务端明确把审批路由给 user 时才是 UI 等待func resolvePendingApprovalIfPossible(- for task: inout CodexActivityTask,- into transitions: inout [CodexActivityTransition]+ for task: inout ActivityTask,+ into transitions: inout [ActivityTransition]) -> Bool {let wasWaiting = task.state == .waitingApprovalguard task.resolvePendingApprovals() else { return false }@@ -77,17 +77,17 @@ extension CodexActivityMonitor {return true}- /// rollout 终态归类的唯一入口; 活动任务和等待终态确认任务只有 abort 兜底时间不同+ /// app-server 终态归类的唯一入口; 活动任务和等待终态确认任务只有 abort 兜底时间不同/// 终止记录供任务中心和流光展示, 不发布通知 transitionfunc resolveTerminal(- _ terminal: CodexSessionTaskTerminalState,- task: CodexActivityTask,- key: CodexActivityTaskKey,+ _ terminal: SessionTerminalState,+ task: ActivityTask,+ key: ActivityTaskKey,abortFallback: Date,publishesEvents: Bool = true,- into transitions: inout [CodexActivityTransition]+ into transitions: inout [ActivityTransition]) {- clearActivityProtection(+ clearProtection(for: key,taskID: task.displayID,reason: .terminal@@ -111,6 +111,7 @@ extension CodexActivityMonitor {task,key: key,completedAt: completedAt,+ observedAt: abortFallback,reportedDuration: duration)guard publishesEvents else { return }@@ -125,8 +126,8 @@ extension CodexActivityMonitor {}static func backfilledStartedAt(- for task: CodexActivityTask,- state: CodexSessionTaskLifecycleState+ for task: ActivityTask,+ state: SessionLifecycleState) -> Date? {guard task.startedAt == nil,let startedAt = state.startedAt,@@ -137,8 +138,8 @@ extension CodexActivityMonitor {}static func mergeLifecycleBackfill(- from state: CodexSessionTaskLifecycleState,- into task: inout CodexActivityTask+ from state: SessionLifecycleState,+ into task: inout ActivityTask) -> Bool {var didChange = falseif let startedAt = backfilledStartedAt(for: task, state: state) {@@ -152,21 +153,22 @@ extension CodexActivityMonitor {}private func storeResolvedCompletion(- _ task: CodexActivityTask,- key: CodexActivityTaskKey,- completedAt: Date,+ _ task: ActivityTask,+ key: ActivityTaskKey,+ completedAt: Date?,+ observedAt: Date,reportedDuration: TimeInterval?- ) -> CodexActivityCompletion {- // rollout 时间戳是整秒, 避免因为同一秒内的 Hook 毫秒时间戳而把完成时间记在最后活动之前- let recordedCompletedAt = max(completedAt, task.lastActivityAt)- let completion = CodexActivityCompletion(+ ) -> ActivityCompletion {+ // 轮次时间戳可能是整秒, 避免将完成时间记在同秒的最后活动之前+ let recordedCompletedAt = max(completedAt ?? observedAt, task.lastActivityAt)+ let completion = ActivityCompletion(id: UUID(),isAnonymous: key.isAnonymous,projectName: task.projectName,modelName: task.modelName,effort: task.effort,completedAt: recordedCompletedAt,- duration: reportedDuration ?? task.preciseDuration(until: recordedCompletedAt)+ duration: reportedDuration ?? completedAt.flatMap { task.preciseDuration(until: $0) })completions.append(completion)terminalTaskKeyByID[completion.id] = key@@ -179,10 +181,10 @@ extension CodexActivityMonitor {}private func storeTermination(- _ task: CodexActivityTask,+ _ task: ActivityTask,at terminatedAt: Date,includesDuration: Bool- ) -> CodexActivityTermination {+ ) -> ActivityTermination {storeTermination(for: task.key,projectName: task.projectName,@@ -195,15 +197,15 @@ extension CodexActivityMonitor {}private func storeTermination(- for key: CodexActivityTaskKey,+ for key: ActivityTaskKey,projectName: String?,modelName: String?,effort: String?,terminatedAt: Date,duration: TimeInterval?,- task: CodexActivityTask? = nil- ) -> CodexActivityTermination {- let termination = CodexActivityTermination(+ task: ActivityTask? = nil+ ) -> ActivityTermination {+ let termination = ActivityTermination(id: UUID(),isAnonymous: key.isAnonymous,projectName: projectName,@@ -218,7 +220,7 @@ extension CodexActivityMonitor {return termination}- func recordTerminalPresentationEvent(_ event: CodexActivityTerminalEvent) {+ func recordTerminalPresentationEvent(_ event: ActivityTerminalEvent) {guard canPublishActivityTransitions, Date().timeIntervalSince(event.endedAt) <= 10,event.endedAt >= terminalPresentationNotBefore else {return@@ -233,7 +235,7 @@ extension CodexActivityMonitor {}func recentEndedDate(- for key: CodexActivityTaskKey,+ for key: ActivityTaskKey,now: Date = Date()) -> Date? {guard let date = recentlyEndedTaskAt[key] else {@@ -249,21 +251,21 @@ extension CodexActivityMonitor {return date}- func recordEndedTask(_ key: CodexActivityTaskKey, at date: Date) {+ func recordEndedTask(_ key: ActivityTaskKey, at date: Date) {recentlyEndedTaskAt[key] = max(recentlyEndedTaskAt[key] ?? .distantPast, date)if let sessionID = key.sessionID {- let sessionKey = CodexActivityTaskKey.session(sessionID)+ let sessionKey = ActivityTaskKey.session(sessionID)recentlyEndedTaskAt[sessionKey] = max(recentlyEndedTaskAt[sessionKey] ?? .distantPast, date)}}func clearCollectedActivityState() {resetTerminalPresentationEvents()- cancelAllActivityProtectionAttempts()+ cancelAllProtectionAttempts()let taskIDs = Set(tasks.values.map(\.displayID)).union(pendingTerminalTasks.values.map(\.task.displayID))for taskID in taskIDs {- invalidateActivityProtectionNotification(for: taskID)+ invalidateProtectionNotification(for: taskID)}tasks.removeAll()pendingTerminalTasks.removeAll()@@ -285,7 +287,7 @@ extension CodexActivityMonitor {guard let pending = pendingTerminalTasks.removeValue(forKey: key) else {continue}- clearActivityProtection(+ clearProtection(for: key,taskID: pending.task.displayID,reason: .terminal@@ -293,16 +295,16 @@ extension CodexActivityMonitor {}}- func publishWaitingApprovalTransitions(_ taskKeys: [CodexActivityTaskKey]) {+ func publishWaitingApprovalTransitions(_ taskKeys: [ActivityTaskKey]) {for transition in waitingApprovalTransitions(taskKeys) {transitionSubject.send(transition)}}- func waitingApprovalTransitions(_ taskKeys: [CodexActivityTaskKey]) -> [CodexActivityTransition] {+ func waitingApprovalTransitions(_ taskKeys: [ActivityTaskKey]) -> [ActivityTransition] {guard canPublishActivityTransitions else { return [] }- var transitions: [CodexActivityTransition] = []- var lastWaitingIndexByKey: [CodexActivityTaskKey: Int] = [:]+ var transitions: [ActivityTransition] = []+ var lastWaitingIndexByKey: [ActivityTaskKey: Int] = [:]for (index, key) in taskKeys.enumerated() {lastWaitingIndexByKey[key] = index}diff --git a/CodexBar/Services/Workflow/CodexActivityOriginFiltering.swift b/CodexBar/Services/Activity/ActivityMonitor+Origins.swiftsimilarity index 78%rename from CodexBar/Services/Workflow/CodexActivityOriginFiltering.swiftrename to CodexBar/Services/Activity/ActivityMonitor+Origins.swiftindex 492b1df..7038d56 100644--- a/CodexBar/Services/Workflow/CodexActivityOriginFiltering.swift+++ b/CodexBar/Services/Activity/ActivityMonitor+Origins.swift@@ -1,23 +1,25 @@import Foundationimport os-extension CodexActivityMonitor {+extension ActivityMonitor {/// 仅为实时链路归一化事件副本, 来源过滤和执行身份使用同一判断- func activityEvent(from event: WorkflowHookEvent, source: CodexActivityEventSource) -> WorkflowHookEvent? {+ func activityEvent(from event: ActivityRecord, source: ActivityEventSource) -> ActivityRecord? {guard let origin = activityOrigin(for: event, source: source) else { return nil }guard origin != event.origin else { return event }- return WorkflowHookEvent(+ var resolved = ActivityRecord(timestamp: event.timestamp, name: event.name, origin: origin,- directoryPath: event.directoryPath, toolName: event.toolName, modelName: event.modelName,- effort: event.effort, permissionMode: event.permissionMode, approvalReviewer: event.approvalReviewer,- sessionID: event.sessionID, turnID: event.turnID, agentID: event.agentID+ cwd: event.cwd, tool: event.tool, model: event.model,+ effort: event.effort, approvalReviewer: event.approvalReviewer,+ sessionID: event.sessionID, turnID: event.turnID, agentID: event.agentID, id: event.id)+ resolved.source = event.source+ return resolved}private func activityOrigin(- for event: WorkflowHookEvent,- source: CodexActivityEventSource- ) -> WorkflowEventOrigin? {+ for event: ActivityRecord,+ source: ActivityEventSource+ ) -> ActivityOrigin? {let exactKey = Self.exactTurnKey(for: event)switch event.origin {case .autoReview:@@ -56,8 +58,8 @@ extension CodexActivityMonitor {}private func rememberActivityOrigin(- _ origin: WorkflowEventOrigin,- for key: CodexActivityTaskKey,+ _ origin: ActivityOrigin,+ for key: ActivityTaskKey,at timestamp: Date) {activityTaskOrigins[key] = (@@ -66,7 +68,7 @@ extension CodexActivityMonitor {)}- private static func exactTurnKey(for event: WorkflowHookEvent) -> CodexActivityTaskKey? {+ private static func exactTurnKey(for event: ActivityRecord) -> ActivityTaskKey? {guard let sessionID = event.sessionID,let turnID = event.turnID else {return nil@@ -74,7 +76,7 @@ extension CodexActivityMonitor {return .turn(session: sessionID, turn: turnID)}- private func discardExcludedActivity(for key: CodexActivityTaskKey) {+ private func discardExcludedActivity(for key: ActivityTaskKey) {var taskIDs = Set<UUID>()if let task = tasks.removeValue(forKey: key) {taskIDs.insert(task.displayID)@@ -84,10 +86,10 @@ extension CodexActivityMonitor {}if taskIDs.isEmpty {- clearActivityProtection(for: key, taskID: nil, reason: .terminal)+ clearProtection(for: key, taskID: nil, reason: .terminal)} else {for taskID in taskIDs {- clearActivityProtection(for: key, taskID: taskID, reason: .terminal)+ clearProtection(for: key, taskID: taskID, reason: .terminal)}}@@ -98,13 +100,13 @@ extension CodexActivityMonitor {removeTerminalMemory(for: key)}- private func removeTerminalMemory(for key: CodexActivityTaskKey) {+ private func removeTerminalMemory(for key: ActivityTaskKey) {guard let removedAt = recentlyEndedTaskAt.removeValue(forKey: key),let sessionID = key.sessionID else {return}- let sessionKey = CodexActivityTaskKey.session(sessionID)+ let sessionKey = ActivityTaskKey.session(sessionID)guard recentlyEndedTaskAt[sessionKey] == removedAt else {return}diff --git a/CodexBar/Services/Workflow/CodexActivityProtection.swift b/CodexBar/Services/Activity/ActivityMonitor+Protection.swiftsimilarity index 56%rename from CodexBar/Services/Workflow/CodexActivityProtection.swiftrename to CodexBar/Services/Activity/ActivityMonitor+Protection.swiftindex 5eebc8b..f7e3004 100644--- a/CodexBar/Services/Workflow/CodexActivityProtection.swift+++ b/CodexBar/Services/Activity/ActivityMonitor+Protection.swift@@ -1,25 +1,25 @@import Foundationimport os-extension CodexActivityMonitor {+extension ActivityMonitor {// MARK: - 异常任务保护- private var canEvaluateActivityProtection: Bool {+ private var canEvaluateProtection: Bool {isStarted- && isActivityProtectionEnabled- && tailReader != nil+ && isProtectionEnabled+ && activityReader != nil&& !isBootstrapping- && !isActivityProtectionRecoveryInProgress+ && !isProtectionRecoveryInProgress&& isActivitySourceHealthy}- func setActivityProtectionEnabled(_ enabled: Bool) {- guard enabled != isActivityProtectionEnabled else {+ func setProtectionEnabled(_ enabled: Bool) {+ guard enabled != isProtectionEnabled else {return}- isActivityProtectionEnabled = enabled+ isProtectionEnabled = enabledcancelInactivityCheck()- cancelAllActivityProtectionAttempts()+ cancelAllProtectionAttempts()guard isStarted else {return@@ -31,57 +31,57 @@ extension CodexActivityMonitor {refreshSnapshot(now: now)return}- reconcileActivityProtection(now: now, sendsNotification: false)+ reconcileProtection(now: now, sendsNotification: false)}- func handleActivityProtectionTimingChange() {- cancelAllActivityProtectionAttempts()- reconcileActivityProtection(now: Date(), sendsNotification: false)+ func handleProtectionTimingChange() {+ cancelAllProtectionAttempts()+ reconcileProtection(now: Date(), sendsNotification: false)}@discardableResult- func beginActivityProtectionRecovery() -> UInt64 {- activityProtectionRecoveryGeneration &+= 1- isActivityProtectionRecoveryInProgress = true+ func beginProtectionRecovery() -> UInt64 {+ protectionRecoveryGeneration &+= 1+ isProtectionRecoveryInProgress = truesessionTransitionNotBefore = nilresetTerminalPresentationEvents()cancelInactivityCheck()- cancelAllActivityProtectionAttempts()- return activityProtectionRecoveryGeneration+ cancelAllProtectionAttempts()+ return protectionRecoveryGeneration}- func finishActivityProtectionRecovery(generation: UInt64) {- guard generation == activityProtectionRecoveryGeneration else {+ func finishProtectionRecovery(generation: UInt64) {+ guard generation == protectionRecoveryGeneration else {return}resetTerminalPresentationEvents()- isActivityProtectionRecoveryInProgress = false+ isProtectionRecoveryInProgress = falsesessionTransitionNotBefore = Date()- reconcileActivityProtection(now: Date(), sendsNotification: false)+ reconcileProtection(now: Date(), sendsNotification: false)}- func resetActivityProtectionRecovery() {- activityProtectionRecoveryGeneration &+= 1- isActivityProtectionRecoveryInProgress = false- cancelAllActivityProtectionAttempts()+ func resetProtectionRecovery() {+ protectionRecoveryGeneration &+= 1+ isProtectionRecoveryInProgress = false+ cancelAllProtectionAttempts()}- func applyPersistedActivityProtection(now: Date) {- removeExpiredActivityProtectionRecords(now: now)+ func applyPersistedProtection(now: Date) {+ removeExpiredProtectionRecords(now: now)- guard canEvaluateActivityProtection else {+ guard canEvaluateProtection else {return}for (key, var task) in tasks {guard task.hasFreshLifecycle(at: now),- let identifier = key.activityProtectionIdentifier,- let record = activityProtectionRecords[identifier] else {+ let identifier = key.protectionIdentifier,+ let record = protectionRecords[identifier] else {continue}if task.state == .waitingApproval || task.lastProgressAt > record.lastProgressAt {- clearActivityProtection(+ clearProtection(for: key,taskID: task.displayID,reason: .progress@@ -95,11 +95,11 @@ extension CodexActivityMonitor {}}- func reconcileActivityProtection(+ func reconcileProtection(now: Date,sendsNotification: Bool) {- guard canEvaluateActivityProtection else {+ guard canEvaluateProtection else {cancelInactivityCheck()refreshSnapshot(now: now)return@@ -110,11 +110,11 @@ extension CodexActivityMonitor {return}- let threshold = activityProtectionSettings.inactivityDuration.timeInterval- let restorableKeys = tasks.compactMap { key, task -> CodexActivityTaskKey? in+ let threshold = protectionSettings.inactivityDuration.timeInterval+ let restorableKeys = tasks.compactMap { key, task -> ActivityTaskKey? inguard !key.isAnonymous,task.state == .suppressed,- task.activityProtectionReferenceAt.addingTimeInterval(threshold) > now else {+ task.protectionReferenceAt.addingTimeInterval(threshold) > now else {return nil}return key@@ -123,10 +123,10 @@ extension CodexActivityMonitor {restoreActivityTaskForCurrentThreshold(key, restoredAt: now)}- let overdueKeys = tasks.compactMap { key, task -> CodexActivityTaskKey? in+ let overdueKeys = tasks.compactMap { key, task -> ActivityTaskKey? inguard !key.isAnonymous,task.state == .running,- let deadline = task.activityProtectionDeadline(at: now, inactivityDuration: threshold),+ let deadline = task.protectionDeadline(at: now, inactivityDuration: threshold),deadline <= now else {return nil}@@ -139,19 +139,19 @@ extension CodexActivityMonitor {}func scheduleNextInactivityCheck(now: Date) {- guard canEvaluateActivityProtection else {+ guard canEvaluateProtection else {cancelInactivityCheck()return}- let threshold = activityProtectionSettings.inactivityDuration.timeInterval+ let threshold = protectionSettings.inactivityDuration.timeIntervallet nextDeadline = tasks.compactMap { key, task -> Date? inguard !key.isAnonymous,task.state == .running,- activityProtectionAttempts[key] == nil else {+ protectionAttempts[key] == nil else {return nil}- return task.activityProtectionDeadline(at: now, inactivityDuration: threshold)+ return task.protectionDeadline(at: now, inactivityDuration: threshold)}.min()guard let nextDeadline else {@@ -173,7 +173,7 @@ extension CodexActivityMonitor {}inactivityCheckTask = nilinactivityCheckDeadline = nil- reconcileActivityProtection(now: Date(), sendsNotification: true)+ reconcileProtection(now: Date(), sendsNotification: true)}}@@ -184,81 +184,81 @@ extension CodexActivityMonitor {}func beginDueInactivityChecks(now: Date) {- guard canEvaluateActivityProtection else {+ guard canEvaluateProtection else {refreshSnapshot(now: now)return}- let threshold = activityProtectionSettings.inactivityDuration.timeInterval- let candidates = tasks.compactMap { key, task -> ActivityProtectionCandidate? in+ let threshold = protectionSettings.inactivityDuration.timeInterval+ let candidates = tasks.compactMap { key, task -> ProtectionCandidate? inguard !key.isAnonymous,task.state == .running,- activityProtectionAttempts[key] == nil,- let deadline = task.activityProtectionDeadline(at: now, inactivityDuration: threshold),+ protectionAttempts[key] == nil,+ let deadline = task.protectionDeadline(at: now, inactivityDuration: threshold),deadline <= now else {return nil}- return ActivityProtectionCandidate(+ return ProtectionCandidate(key: key,taskID: task.displayID,projectName: task.projectName,lastProgressAt: task.lastProgressAt,progressGeneration: task.progressGeneration,- inactivityDuration: activityProtectionSettings.inactivityDuration+ inactivityDuration: protectionSettings.inactivityDuration)}for candidate in candidates {- beginActivityProtectionAttempt(candidate)+ beginProtectionAttempt(candidate)}refreshSnapshot(now: now)}- func beginActivityProtectionAttempt(_ candidate: ActivityProtectionCandidate) {- guard isActivityProtectionCandidateRelevant(candidate, now: Date()) else {+ func beginProtectionAttempt(_ candidate: ProtectionCandidate) {+ guard isProtectionCandidateRelevant(candidate, now: Date()) else {return}- invalidateActivityProtectionNotification(for: candidate.taskID)+ invalidateProtectionNotification(for: candidate.taskID)let attemptID = UUID()let markedAt = Date()- persistActivityProtectionRecord(+ persistProtectionRecord(for: candidate.key,lastProgressAt: candidate.lastProgressAt,markedAt: markedAt)let timeoutTask = Task { @MainActor [weak self] in- try? await Task.sleep(for: Self.activityProtectionNotificationSubmissionGrace)+ try? await Task.sleep(for: Self.protectionNotificationSubmissionGrace)guard let self, !Task.isCancelled else {return}- finishActivityProtectionAttempt(+ finishProtectionAttempt(candidate.key,attemptID: attemptID,taskID: candidate.taskID,notificationWasSubmitted: false)}- activityProtectionAttempts[candidate.key] = ActivityProtectionAttempt(+ protectionAttempts[candidate.key] = ProtectionAttempt(id: attemptID,candidate: candidate,markedAt: markedAt,timeoutTask: timeoutTask)- activityProtectionNoticeAttemptIDs[candidate.taskID] = attemptID+ protectionNoticeAttemptIDs[candidate.taskID] = attemptID- let notice = CodexActivityProtectionNotice(+ let notice = ProtectionNotice(taskID: candidate.taskID,attemptID: attemptID,projectName: candidate.projectName,inactivityDurationText: candidate.inactivityDuration.title)- let notificationHandler = onInactivityProtectionTriggered+ let notificationHandler = onProtectionTriggeredTask { @MainActor [weak self] inlet notificationWasSubmitted = await notificationHandler?(notice) ?? false- self?.finishActivityProtectionAttempt(+ self?.finishProtectionAttempt(candidate.key,attemptID: attemptID,taskID: candidate.taskID,@@ -267,30 +267,30 @@ extension CodexActivityMonitor {}}- func finishActivityProtectionAttempt(- _ key: CodexActivityTaskKey,+ func finishProtectionAttempt(+ _ key: ActivityTaskKey,attemptID: UUID,taskID: UUID,notificationWasSubmitted: Bool) {- guard let attempt = activityProtectionAttempts[key],+ guard let attempt = protectionAttempts[key],attempt.id == attemptID else {if notificationWasSubmitted {- onInactivityProtectionInvalidated?(taskID, attemptID)+ onProtectionInvalidated?(taskID, attemptID)}return}- guard isActivityProtectionCandidateRelevant(attempt.candidate, now: Date()) else {- cancelActivityProtectionAttempt(for: key, matching: attemptID)+ guard isProtectionCandidateRelevant(attempt.candidate, now: Date()) else {+ cancelProtectionAttempt(for: key, matching: attemptID)refreshSnapshot(now: Date())return}attempt.timeoutTask.cancel()- activityProtectionAttempts.removeValue(forKey: key)+ protectionAttempts.removeValue(forKey: key)if !notificationWasSubmitted {- invalidateActivityProtectionNotification(+ invalidateProtectionNotification(for: attempt.candidate.taskID,matching: attemptID)@@ -309,17 +309,17 @@ extension CodexActivityMonitor {}func suppressActivityTaskSilently(- _ key: CodexActivityTaskKey,+ _ key: ActivityTaskKey,markedAt: Date) {- cancelActivityProtectionAttempt(for: key)+ cancelProtectionAttempt(for: key)guard !key.isAnonymous,var task = tasks[key],task.state == .running else {return}- persistActivityProtectionRecord(+ persistProtectionRecord(for: key,lastProgressAt: task.lastProgressAt,markedAt: markedAt@@ -331,14 +331,14 @@ extension CodexActivityMonitor {}func suppressBackfilledActivityTaskIfOverdue(- _ key: CodexActivityTaskKey,+ _ key: ActivityTaskKey,now: Date) {guard !key.isAnonymous,- canEvaluateActivityProtection,+ canEvaluateProtection,let task = tasks[key],task.state == .running,- let deadline = task.activityProtectionDeadline(at: now, inactivityDuration: activityProtectionSettings.inactivityDuration.timeInterval),+ let deadline = task.protectionDeadline(at: now, inactivityDuration: protectionSettings.inactivityDuration.timeInterval),deadline <= now else {return}@@ -346,7 +346,7 @@ extension CodexActivityMonitor {}func restoreActivityTaskForCurrentThreshold(- _ key: CodexActivityTaskKey,+ _ key: ActivityTaskKey,restoredAt: Date) {guard var task = tasks[key], task.state == .suppressed else {@@ -356,7 +356,7 @@ extension CodexActivityMonitor {task.state = .runningtask.stateChangedAt = restoredAttasks[key] = task- clearActivityProtection(+ clearProtection(for: key,taskID: task.displayID,reason: .thresholdChange@@ -375,10 +375,10 @@ extension CodexActivityMonitor {task.state = .runningtask.stateChangedAt = restoredAttasks[key] = task- invalidateActivityProtectionNotification(for: task.displayID)+ invalidateProtectionNotification(for: task.displayID)}- for (taskID, attemptID) in Array(activityProtectionNoticeAttemptIDs) {- invalidateActivityProtectionNotification(for: taskID, matching: attemptID)+ for (taskID, attemptID) in Array(protectionNoticeAttemptIDs) {+ invalidateProtectionNotification(for: taskID, matching: attemptID)}if !suppressedKeys.isEmpty {AppLog.activity.notice(@@ -387,13 +387,13 @@ extension CodexActivityMonitor {}}- func isActivityProtectionCandidateRelevant(- _ candidate: ActivityProtectionCandidate,+ func isProtectionCandidateRelevant(+ _ candidate: ProtectionCandidate,now: Date) -> Bool {guard !candidate.key.isAnonymous,- canEvaluateActivityProtection,- activityProtectionSettings.inactivityDuration == candidate.inactivityDuration,+ canEvaluateProtection,+ protectionSettings.inactivityDuration == candidate.inactivityDuration,let task = tasks[candidate.key],task.displayID == candidate.taskID,task.state == .running,@@ -401,50 +401,50 @@ extension CodexActivityMonitor {task.progressGeneration == candidate.progressGeneration else {return false}- return task.activityProtectionDeadline(at: now, inactivityDuration: candidate.inactivityDuration.timeInterval)+ return task.protectionDeadline(at: now, inactivityDuration: candidate.inactivityDuration.timeInterval).map { $0 <= now } == true}- func isInactivityProtectionNoticeRelevant(+ func isProtectionNoticeRelevant(taskID: UUID,attemptID: UUID) -> Bool {- guard activityProtectionNoticeAttemptIDs[taskID] == attemptID,- let attempt = activityProtectionAttempts.values.first(where: {+ guard protectionNoticeAttemptIDs[taskID] == attemptID,+ let attempt = protectionAttempts.values.first(where: {$0.id == attemptID && $0.candidate.taskID == taskID}) else {return false}- return isActivityProtectionCandidateRelevant(attempt.candidate, now: Date())+ return isProtectionCandidateRelevant(attempt.candidate, now: Date())}- func shouldRestoreActivityProtection(- for key: CodexActivityTaskKey,+ func shouldRestoreProtection(+ for key: ActivityTaskKey,progressAt: Date) -> Bool {- guard let identifier = key.activityProtectionIdentifier,- let record = activityProtectionRecords[identifier] else {+ guard let identifier = key.protectionIdentifier,+ let record = protectionRecords[identifier] else {return true}return progressAt > record.lastProgressAt}- func clearActivityProtection(- for key: CodexActivityTaskKey,+ func clearProtection(+ for key: ActivityTaskKey,taskID: UUID?,- reason: ActivityProtectionClearReason+ reason: ProtectionClearReason) {- cancelActivityProtectionAttempt(for: key)- if let identifier = key.activityProtectionIdentifier,- let record = activityProtectionRecords.removeValue(forKey: identifier) {+ cancelProtectionAttempt(for: key)+ if let identifier = key.protectionIdentifier,+ let record = protectionRecords.removeValue(forKey: identifier) {let matchingMarkedAt: Date? = switch reason {case .progress, .thresholdChange: record.markedAtcase .terminal, .retention: nil}- enqueueActivityProtectionPersistence(+ enqueueProtectionPersistence(removals: [- ActivityProtectionRemoval(+ ProtectionRemoval(taskIdentifier: identifier,matchingMarkedAt: matchingMarkedAt)@@ -452,67 +452,67 @@ extension CodexActivityMonitor {)}if let taskID {- invalidateActivityProtectionNotification(for: taskID)+ invalidateProtectionNotification(for: taskID)}}- func invalidateActivityProtectionNotification(for taskID: UUID) {- guard let attemptID = activityProtectionNoticeAttemptIDs[taskID] else {+ func invalidateProtectionNotification(for taskID: UUID) {+ guard let attemptID = protectionNoticeAttemptIDs[taskID] else {return}- invalidateActivityProtectionNotification(for: taskID, matching: attemptID)+ invalidateProtectionNotification(for: taskID, matching: attemptID)}- func invalidateActivityProtectionNotification(+ func invalidateProtectionNotification(for taskID: UUID,matching attemptID: UUID) {- guard activityProtectionNoticeAttemptIDs[taskID] == attemptID else {+ guard protectionNoticeAttemptIDs[taskID] == attemptID else {return}- activityProtectionNoticeAttemptIDs.removeValue(forKey: taskID)- onInactivityProtectionInvalidated?(taskID, attemptID)+ protectionNoticeAttemptIDs.removeValue(forKey: taskID)+ onProtectionInvalidated?(taskID, attemptID)}- func cancelActivityProtectionAttempt(- for key: CodexActivityTaskKey,+ func cancelProtectionAttempt(+ for key: ActivityTaskKey,matching attemptID: UUID? = nil) {- guard let attempt = activityProtectionAttempts[key],+ guard let attempt = protectionAttempts[key],attemptID == nil || attempt.id == attemptID else {return}attempt.timeoutTask.cancel()- activityProtectionAttempts.removeValue(forKey: key)+ protectionAttempts.removeValue(forKey: key)- if let identifier = key.activityProtectionIdentifier,- let record = activityProtectionRecords[identifier],+ if let identifier = key.protectionIdentifier,+ let record = protectionRecords[identifier],record.markedAt == attempt.markedAt {- activityProtectionRecords.removeValue(forKey: identifier)- enqueueActivityProtectionPersistence(+ protectionRecords.removeValue(forKey: identifier)+ enqueueProtectionPersistence(removals: [- ActivityProtectionRemoval(+ ProtectionRemoval(taskIdentifier: identifier,matchingMarkedAt: attempt.markedAt)])}- invalidateActivityProtectionNotification(+ invalidateProtectionNotification(for: attempt.candidate.taskID,matching: attempt.id)}- func cancelAllActivityProtectionAttempts() {- for key in Array(activityProtectionAttempts.keys) {- cancelActivityProtectionAttempt(for: key)+ func cancelAllProtectionAttempts() {+ for key in Array(protectionAttempts.keys) {+ cancelProtectionAttempt(for: key)}}- func removeExpiredActivityProtectionRecords(now: Date) {- let expiredIdentifiers = activityProtectionRecords.compactMap { identifier, record in+ func removeExpiredProtectionRecords(now: Date) {+ let expiredIdentifiers = protectionRecords.compactMap { identifier, record inrecord.expiresAt <= now ? identifier : nil}guard !expiredIdentifiers.isEmpty else {@@ -520,39 +520,39 @@ extension CodexActivityMonitor {}for identifier in expiredIdentifiers {- activityProtectionRecords.removeValue(forKey: identifier)+ protectionRecords.removeValue(forKey: identifier)}- enqueueActivityProtectionPersistence(+ enqueueProtectionPersistence(removals: expiredIdentifiers.map {- ActivityProtectionRemoval(taskIdentifier: $0)+ ProtectionRemoval(taskIdentifier: $0)})}- func persistActivityProtectionRecord(- for key: CodexActivityTaskKey,+ func persistProtectionRecord(+ for key: ActivityTaskKey,lastProgressAt: Date,markedAt: Date) {- guard let taskIdentifier = key.activityProtectionIdentifier else {+ guard let taskIdentifier = key.protectionIdentifier else {return}- let record = ActivityProtectionRecord(+ let record = ProtectionRecord(taskIdentifier: taskIdentifier,lastProgressAt: lastProgressAt,markedAt: markedAt,expiresAt: lastProgressAt.addingTimeInterval(Self.activityRetention))- activityProtectionRecords[record.taskIdentifier] = record- enqueueActivityProtectionPersistence(upserts: [record])+ protectionRecords[record.taskIdentifier] = record+ enqueueProtectionPersistence(upserts: [record])}- func enqueueActivityProtectionPersistence(- upserts: [ActivityProtectionRecord] = [],- removals: [ActivityProtectionRemoval] = []+ func enqueueProtectionPersistence(+ upserts: [ProtectionRecord] = [],+ removals: [ProtectionRemoval] = []) {- let previousTask = activityProtectionPersistenceTask- let stateStore = activityProtectionStateStore+ let previousTask = protectionPersistenceTask+ let stateStore = protectionStorelet task = Task { @MainActor inawait previousTask?.valuedo {@@ -566,6 +566,6 @@ extension CodexActivityMonitor {)}}- activityProtectionPersistenceTask = task+ protectionPersistenceTask = task}}diff --git a/CodexBar/Services/Workflow/CodexActivitySubagentTracking.swift b/CodexBar/Services/Activity/ActivityMonitor+Subagents.swiftsimilarity index 60%rename from CodexBar/Services/Workflow/CodexActivitySubagentTracking.swiftrename to CodexBar/Services/Activity/ActivityMonitor+Subagents.swiftindex 8654c7c..565d186 100644--- a/CodexBar/Services/Workflow/CodexActivitySubagentTracking.swift+++ b/CodexBar/Services/Activity/ActivityMonitor+Subagents.swift@@ -1,90 +1,97 @@import Foundation-struct CodexPendingSubagentEvent {- let event: WorkflowHookEvent- let source: CodexActivityEventSource+struct PendingSubagentEvent {+ let event: ActivityRecord+ let source: ActivityEventSource}-extension CodexActivityMonitor {- /// 生命周期和工具 Hook 都携带子轮次, 已结束或未确认的归属不回退到当前根任务+extension ActivityMonitor {+ /// 生命周期和工具事件 都携带子轮次, 已结束或未确认的归属不回退到当前根任务func matchingSubagentParentTaskKey(- for event: WorkflowHookEvent- ) -> CodexActivityTaskKey? {+ for event: ActivityRecord+ ) -> ActivityTaskKey? {guard let reference = subagentReference(for: event),let rootKey = subagentTurnLinks[reference], rootKey.sessionID == event.sessionID else { return nil }return tasks.first(where: { $0.value.resolvedTurnKey == rootKey })?.key}- func subagentReference(for event: WorkflowHookEvent) -> CodexActivityTurnReference? {+ func subagentReference(for event: ActivityRecord) -> ActivityTurnReference? {guard let agentID = event.agentID, let turnID = event.turnID else { return nil }- // 引用的相等性只由线程和轮次决定, 时间只用于文件定位- return CodexActivityTurnReference(threadID: agentID, turnID: turnID, startedAt: event.timestamp)+ // 引用的相等性只由线程和轮次决定, 时间用于保留窗口+ return ActivityTurnReference(threadID: agentID, turnID: turnID, startedAt: event.timestamp)}- func deferUnassociatedSubagentEvent(_ event: WorkflowHookEvent, source: CodexActivityEventSource) -> Bool {+ func deferUnassociatedSubagentEvent(_ event: ActivityRecord, source: ActivityEventSource) -> Bool {guard let reference = subagentReference(for: event), subagentTurnLinks[reference] == nil else { return false }guard event.sessionID != nil else { return true }if !pendingSubagentEvents.contains(where: { $0.event == event }) {- pendingSubagentEvents.append(CodexPendingSubagentEvent(event: event, source: source))+ pendingSubagentEvents.append(PendingSubagentEvent(event: event, source: source))}return true}- func subagentLifecycleReferences() -> [CodexActivityTurnReference] {- let cutoff = Date().addingTimeInterval(-CodexActivityRetention.window)+ func subagentLifecycleReferences() -> [ActivityTurnReference] {+ let cutoff = Date().addingTimeInterval(-ActivityRetention.window)pendingSubagentEvents.removeAll { $0.event.timestamp <= cutoff }- // 结束后的关联也保留一个回放窗口, 用于拒绝旧 Agent 的迟到生命周期 Hook+ // 结束后的关联也保留一个回放窗口, 用于拒绝旧 Agent 的迟到生命周期事件subagentTurnLinks = subagentTurnLinks.filter { $0.key.startedAt > cutoff }var references = pendingSubagentEvents.compactMap { subagentReference(for: $0.event) }for task in tasks.values {for (owner, execution) in task.executions where !execution.isTerminal {guard let agentID = owner.agentID, let turnID = owner.turnID else { continue }- references.append(CodexActivityTurnReference(threadID: agentID, turnID: turnID, startedAt: execution.lastHookEventAt))+ references.append(ActivityTurnReference(threadID: agentID, turnID: turnID, startedAt: execution.lastEventAt))}}return Array(Set(references))}func applySubagentLifecycle(- _ state: CodexSessionTaskLifecycleState,+ _ state: SessionLifecycleState,terminalOnly: Bool,- into transitions: inout [CodexActivityTransition]+ into transitions: inout [ActivityTransition]) -> Bool {guard state.readStatus == .complete,state.recordedThreadID == state.requestedThreadID,let rootTurnID = state.rootTurnID,let parentThreadID = state.parentThreadID, parentThreadID != state.requestedThreadID else { return false }- let reference = CodexActivityTurnReference(threadID: state.requestedThreadID, turnID: state.turnID, startedAt: state.startedAt ?? Date())- let hookSessions = Set(pendingSubagentEvents.compactMap { pending -> String? in+ let reference = ActivityTurnReference(threadID: state.requestedThreadID, turnID: state.turnID, startedAt: state.startedAt ?? Date())+ let eventSessions = Set(pendingSubagentEvents.compactMap { pending -> String? insubagentReference(for: pending.event) == reference ? pending.event.sessionID : nil})let rootSessionID = state.rootSessionID ?? subagentTurnLinks[reference]?.sessionID- ?? (hookSessions.count == 1 ? hookSessions.first : nil)+ ?? (eventSessions.count == 1 ? eventSessions.first : nil)guard let rootSessionID, rootSessionID != state.requestedThreadID,- hookSessions.isEmpty || hookSessions == [rootSessionID] else { return false }- let rootKey = CodexActivityTaskKey.turn(session: rootSessionID, turn: rootTurnID)+ eventSessions.isEmpty || eventSessions == [rootSessionID] else { return false }+ let rootKey = ActivityTaskKey.turn(session: rootSessionID, turn: rootTurnID)guard subagentTurnLinks[reference].map({ $0 == rootKey }) ?? true else { return false }subagentTurnLinks[reference] = rootKeyguard !terminalOnly || state.terminal != nil,let key = tasks.first(where: { $0.value.resolvedTurnKey == rootKey })?.key,var task = tasks[key] else { return false }- let owner = CodexActivityExecutionKey(agentID: state.requestedThreadID, turnID: state.turnID)+ let owner = ActivityExecutionKey(agentID: state.requestedThreadID, turnID: state.turnID)let wasWaiting = task.state == .waitingApprovaltask.mergeExecutionLifecycle(state, owner: owner)+ let wasRunning = task.subagentsByID[state.requestedThreadID]?.isRunning+ let isRunning = state.terminal == nil+ if wasRunning != isRunning {+ let observedAt = state.lastProgressAt ?? state.startedAt ?? Date()+ task.recordSubagentActivity(agentID: state.requestedThreadID, isStarting: isRunning, at: observedAt)+ task.latestEvent = isRunning ? .subagentStarted : .subagentFinished+ }_ = resolvePendingApprovalIfPossible(for: &task, into: &transitions)if !terminalOnly {_ = mergeLifecycleProgress(from: state, key: key, into: &task)}tasks[key] = taskif !terminalOnly, wasWaiting != (task.state == .waitingApproval) {- clearActivityProtection(for: key, taskID: task.displayID, reason: .progress)+ clearProtection(for: key, taskID: task.displayID, reason: .progress)}return true}- func replayAssociatedSubagentEvents(into transitions: inout [CodexActivityTransition]) -> Bool {- var remaining: [CodexPendingSubagentEvent] = []- var ready: [CodexPendingSubagentEvent] = []+ func replayAssociatedSubagentEvents(into transitions: inout [ActivityTransition]) -> Bool {+ var remaining: [PendingSubagentEvent] = []+ var ready: [PendingSubagentEvent] = []for pending in pendingSubagentEvents {if let reference = subagentReference(for: pending.event), subagentTurnLinks[reference] != nil {ready.append(pending)@@ -93,7 +100,7 @@ extension CodexActivityMonitor {}}pendingSubagentEvents = remaining- var waitingKeys: [CodexActivityTaskKey] = []+ var waitingKeys: [ActivityTaskKey] = []for pending in ready {guard let reference = subagentReference(for: pending.event),subagentTurnLinks[reference]?.sessionID == pending.event.sessionID else { continue }diff --git a/CodexBar/Services/Workflow/CodexActivityTokenUsage.swift b/CodexBar/Services/Activity/ActivityMonitor+Tokens.swiftsimilarity index 74%rename from CodexBar/Services/Workflow/CodexActivityTokenUsage.swiftrename to CodexBar/Services/Activity/ActivityMonitor+Tokens.swiftindex 410b7a6..73905b7 100644--- a/CodexBar/Services/Workflow/CodexActivityTokenUsage.swift+++ b/CodexBar/Services/Activity/ActivityMonitor+Tokens.swift@@ -1,16 +1,16 @@import Foundation-struct CodexTaskTokenUsageRequest {- let root: CodexActivityTurnReference+struct TaskTokenRequest {+ let root: ActivityTurnReferencelet expectedAgentIDs: Set<String>- var references: Set<CodexActivityTurnReference>+ var references: Set<ActivityTurnReference>let deadline: Datevar nextReadAt = Date.distantPast- func usage(from states: [CodexSessionTaskLifecycleState], requiresFinalUsage: Bool = true) -> CodexTokenUsage? {+ func usage(from states: [SessionLifecycleState], requiresFinalUsage: Bool = true) -> TokenUsage? {let agentIDs = Set(references.filter { $0 != root }.map(\.threadID))guard !requiresFinalUsage || expectedAgentIDs.isSubset(of: agentIDs) else { return nil }- var total: CodexTokenUsage?+ var total: TokenUsage?for reference in references {guard let state = states.first(where: { $0.requestedThreadID == reference.threadID && $0.turnID == reference.turnID }),state.readStatus == .complete, state.recordedThreadID == reference.threadID,@@ -34,37 +34,37 @@ struct CodexTaskTokenUsageRequest {}}-extension CodexActivityMonitor {+extension ActivityMonitor {func registerTerminalTokenUsage(- id: UUID, key: CodexActivityTaskKey, task: CodexActivityTask?, endedAt: Date, now: Date = Date()+ id: UUID, key: ActivityTaskKey, task: ActivityTask?, endedAt: Date, now: Date = Date()) {guard let session = key.sessionID, let turn = task?.associatedTurnID ?? key.turnID else { return }// 缺少子 Agent 身份时不能把主线程小计展示为整项任务总量guard task?.executions.keys.contains(where: \.isUnattributed) != true else { return }- let root = CodexActivityTurnReference(threadID: session, turnID: turn, startedAt: task?.startedAt ?? endedAt)+ let root = ActivityTurnReference(threadID: session, turnID: turn, startedAt: task?.startedAt ?? endedAt)terminalTokenUsageRequests[id] = tokenUsageRequest(root: root, task: task, deadline: now.addingTimeInterval(30))}private func tokenUsageRequest(- root: CodexActivityTurnReference, task: CodexActivityTask?, deadline: Date- ) -> CodexTaskTokenUsageRequest {+ root: ActivityTurnReference, task: ActivityTask?, deadline: Date+ ) -> TaskTokenRequest {var references: Set = [root]- let rootKey = CodexActivityTaskKey.turn(session: root.threadID, turn: root.turnID)+ let rootKey = ActivityTaskKey.turn(session: root.threadID, turn: root.turnID)references.formUnion(subagentTurnLinks.filter { $0.value == rootKey }.map(\.key))if let task {for owner in task.executions.keys {guard let agent = owner.agentID, let turn = owner.turnID else { continue }- references.insert(CodexActivityTurnReference(threadID: agent, turnID: turn, startedAt: root.startedAt))+ references.insert(ActivityTurnReference(threadID: agent, turnID: turn, startedAt: root.startedAt))}}- return CodexTaskTokenUsageRequest(+ return TaskTokenRequest(root: root, expectedAgentIDs: Set(task?.subagentsByID.keys.map(\.self) ?? []),references: references, deadline: deadline)}- func activeTokenUsageReferences() -> [CodexActivityTurnReference] {- var references: Set<CodexActivityTurnReference> = []+ func activeTokenUsageReferences() -> [ActivityTurnReference] {+ var references: Set<ActivityTurnReference> = []for task in tasks.values {guard let root = task.turnReference else { continue }references.formUnion(tokenUsageRequest(root: root, task: task, deadline: .distantFuture).references)@@ -73,7 +73,7 @@ extension CodexActivityMonitor {}@discardableResult- func applyActiveTokenUsage(_ states: [CodexSessionTaskLifecycleState]) -> Bool {+ func applyActiveTokenUsage(_ states: [SessionLifecycleState]) -> Bool {var changed = falsefor (key, var task) in tasks {guard let root = task.turnReference else { continue }@@ -88,14 +88,14 @@ extension CodexActivityMonitor {return changed}- /// 结束后有界重读, Interrupt Hook 可能先于最后一条用量落盘- func prepareTerminalTokenUsageReadBatch(now: Date) -> [CodexActivityTurnReference] {+ /// 结束后有界重读, 轮次终态可能先于最后一条用量更新+ func prepareTerminalTokenUsageReadBatch(now: Date) -> [ActivityTurnReference] {terminalTokenUsageRequests = terminalTokenUsageRequests.filter { $0.value.deadline > now }let due = terminalTokenUsageRequests.filter { $0.value.nextReadAt <= now }.sorted { $0.value.nextReadAt < $1.value.nextReadAt }.prefix(16)- var references: Set<CodexActivityTurnReference> = []+ var references: Set<ActivityTurnReference> = []for (id, var request) in due {- let rootKey = CodexActivityTaskKey.turn(session: request.root.threadID, turn: request.root.turnID)+ let rootKey = ActivityTaskKey.turn(session: request.root.threadID, turn: request.root.turnID)request.references.formUnion(subagentTurnLinks.filter { $0.value == rootKey }.map(\.key))request.nextReadAt = now.addingTimeInterval(2)terminalTokenUsageRequests[id] = request@@ -109,11 +109,11 @@ extension CodexActivityMonitor {}@discardableResult- func applyTerminalTokenUsage(_ states: [CodexSessionTaskLifecycleState]) -> Bool {+ func applyTerminalTokenUsage(_ states: [SessionLifecycleState]) -> Bool {var changed = falsefor (id, var request) in terminalTokenUsageRequests {guard states.contains(where: { $0.requestedThreadID == request.root.threadID && $0.turnID == request.root.turnID }) else { continue }- let rootKey = CodexActivityTaskKey.turn(session: request.root.threadID, turn: request.root.turnID)+ let rootKey = ActivityTaskKey.turn(session: request.root.threadID, turn: request.root.turnID)request.references.formUnion(subagentTurnLinks.filter { $0.value == rootKey }.map(\.key))terminalTokenUsageRequests[id] = request// 仅汇总已确认属于本轮的线程, 临时读取不完整时保留上次结果diff --git a/CodexBar/Services/Workflow/CodexActivityMonitor.swift b/CodexBar/Services/Activity/ActivityMonitor.swiftsimilarity index 68%rename from CodexBar/Services/Workflow/CodexActivityMonitor.swiftrename to CodexBar/Services/Activity/ActivityMonitor.swiftindex 90ae150..1b23653 100644--- a/CodexBar/Services/Workflow/CodexActivityMonitor.swift+++ b/CodexBar/Services/Activity/ActivityMonitor.swift@@ -3,43 +3,43 @@ import Combineimport Foundationimport os-/// 从本机 Hook JSONL 维护进程内实时任务状态, 是菜单栏; 活动卡片; 通知和触觉反馈的唯一任务状态来源+/// 从共享 app-server 维护实时任务状态, 是菜单栏, 活动卡片, 通知和触觉反馈的任务来源@MainActor-final class CodexActivityMonitor: ObservableObject {- @Published private(set) var snapshot = CodexActivitySnapshot.empty+final class ActivityMonitor: ObservableObject {+ @Published private(set) var snapshot = ActivitySnapshot.empty- var transitionPublisher: AnyPublisher<CodexActivityTransition, Never> {+ var transitionPublisher: AnyPublisher<ActivityTransition, Never> {transitionSubject.eraseToAnyPublisher()}- var presentationPublisher: AnyPublisher<CodexActivityPresentationUpdate, Never> {+ var presentationPublisher: AnyPublisher<ActivityPresentationUpdate, Never> {presentationSubject.eraseToAnyPublisher()}- var onInactivityProtectionTriggered: ((CodexActivityProtectionNotice) async -> Bool)?- var onInactivityProtectionInvalidated: ((UUID, UUID) -> Void)?+ var onProtectionTriggered: ((ProtectionNotice) async -> Bool)?+ var onProtectionInvalidated: ((UUID, UUID) -> Void)?- private let advancedModeSettings: AdvancedModeSettings- let activityProtectionSettings: ActivityProtectionSettings- let activityProtectionStateStore: ActivityProtectionStateStore- private let sessionLifecycleReader = CodexSessionLifecycleReader()- let transitionSubject = PassthroughSubject<CodexActivityTransition, Never>()- private let presentationSubject = PassthroughSubject<CodexActivityPresentationUpdate, Never>()- var pendingTerminalPresentationEvents: [CodexActivityTerminalEvent] = []+ let protectionSettings: ProtectionSettings+ let protectionStore: ProtectionStore+ private let activityDirectoryURL: URL+ private var lifecycleCache = SessionLifecycleCache()+ let transitionSubject = PassthroughSubject<ActivityTransition, Never>()+ private let presentationSubject = PassthroughSubject<ActivityPresentationUpdate, Never>()+ var pendingTerminalPresentationEvents: [ActivityTerminalEvent] = []var terminalPresentationNotBefore = Date()- var tasks: [CodexActivityTaskKey: CodexActivityTask] = [:]- var subagentTurnLinks: [CodexActivityTurnReference: CodexActivityTaskKey] = [:]- var pendingSubagentEvents: [CodexPendingSubagentEvent] = []- var pendingTerminalTasks: [CodexActivityTaskKey: PendingTerminalTask] = [:]- var completions: [CodexActivityCompletion] = []- var terminations: [CodexActivityTermination] = []- var recentlyEndedTaskAt: [CodexActivityTaskKey: Date] = [:]- var terminalTaskKeyByID: [UUID: CodexActivityTaskKey] = [:]- var terminalTokenUsageRequests: [UUID: CodexTaskTokenUsageRequest] = [:]- var activityTaskOrigins: [CodexActivityTaskKey: (origin: WorkflowEventOrigin, observedAt: Date)] = [:]- var tailReader: HookEventTailReader?- private var tailReaderControlTask: Task<Void, Never>?- private var tailReaderGeneration: UInt64 = 0+ var tasks: [ActivityTaskKey: ActivityTask] = [:]+ var subagentTurnLinks: [ActivityTurnReference: ActivityTaskKey] = [:]+ var pendingSubagentEvents: [PendingSubagentEvent] = []+ var pendingTerminalTasks: [ActivityTaskKey: PendingTerminalTask] = [:]+ var completions: [ActivityCompletion] = []+ var terminations: [ActivityTermination] = []+ var recentlyEndedTaskAt: [ActivityTaskKey: Date] = [:]+ var terminalTaskKeyByID: [UUID: ActivityTaskKey] = [:]+ var terminalTokenUsageRequests: [UUID: TaskTokenRequest] = [:]+ var activityTaskOrigins: [ActivityTaskKey: (origin: ActivityOrigin, observedAt: Date)] = [:]+ var activityReader: AppServerActivityReader?+ private var activityReaderControlTask: Task<Void, Never>?+ private var activityReaderGeneration: UInt64 = 0private var recoveryTask: Task<Void, Never>?private var recoveryTaskID: UUID?private var isSystemSleeping = false@@ -49,21 +49,21 @@ final class CodexActivityMonitor: ObservableObject {private var cleanupDeadline: Date?var inactivityCheckTask: Task<Void, Never>?var inactivityCheckDeadline: Date?- var activityProtectionAttempts: [CodexActivityTaskKey: ActivityProtectionAttempt] = [:]- var activityProtectionNoticeAttemptIDs: [UUID: UUID] = [:]- var activityProtectionRecords: [String: ActivityProtectionRecord] = [:]- private var activityProtectionStateLoadTask: Task<Void, Never>?- var activityProtectionPersistenceTask: Task<Void, Never>?- private var isActivityProtectionStateLoaded = false- var isActivityProtectionEnabled = false+ var protectionAttempts: [ActivityTaskKey: ProtectionAttempt] = [:]+ var protectionNoticeAttemptIDs: [UUID: UUID] = [:]+ var protectionRecords: [String: ProtectionRecord] = [:]+ private var protectionStateLoadTask: Task<Void, Never>?+ var protectionPersistenceTask: Task<Void, Never>?+ private var isProtectionStateLoaded = false+ var isProtectionEnabled = falsevar isActivitySourceHealthy = false- var isActivityProtectionRecoveryInProgress = false- var activityProtectionRecoveryGeneration: UInt64 = 0- private var requestedMonitoringEnabled = false+ private var unavailableTurns = Set<ActivityTaskKey>()+ var isProtectionRecoveryInProgress = false+ var protectionRecoveryGeneration: UInt64 = 0private var cancellables = Set<AnyCancellable>()var isStarted = falsevar isBootstrapping = false- /// 历史回放跨多个批次到达, 事件数累加到 bootstrapEnd 才一次记完+ /// 初始快照跨多个批次到达, 事件数累加到 bootstrapEnd 才一次记完/// reader 每次重试都会重新发一遍 bootstrapStart, 所以事件数跟着重置, 但耗时要累计private var bootstrapEventCount = 0private var bootstrapDuration = LogDuration()@@ -71,13 +71,13 @@ final class CodexActivityMonitor: ObservableObject {var sessionTransitionNotBefore: Date?init(- advancedModeSettings: AdvancedModeSettings,- activityProtectionSettings: ActivityProtectionSettings,- activityProtectionStateStore: ActivityProtectionStateStore = ActivityProtectionStateStore()+ protectionSettings: ProtectionSettings,+ protectionStore: ProtectionStore = ProtectionStore(),+ activityDirectoryURL: URL = HistoryStorage.directoryURL()) {- self.advancedModeSettings = advancedModeSettings- self.activityProtectionSettings = activityProtectionSettings- self.activityProtectionStateStore = activityProtectionStateStore+ self.protectionSettings = protectionSettings+ self.protectionStore = protectionStore+ self.activityDirectoryURL = activityDirectoryURL}func start() {@@ -86,22 +86,15 @@ final class CodexActivityMonitor: ObservableObject {}isStarted = true- loadActivityProtectionState()+ loadProtectionState()+ startReaderIfReady()- Publishers.CombineLatest(advancedModeSettings.$isEnabled, advancedModeSettings.$isVerified)- .map { $0 && $1 }- .removeDuplicates()- .sink { [weak self] isOperable in- self?.requestMonitoringEnabled(isOperable)- }- .store(in: &cancellables)-- activityProtectionSettings.$inactivityDuration+ protectionSettings.$inactivityDuration.dropFirst()// @Published 在 willSet 发值, 切回主队列后再按已经提交的新阈值重算.receive(on: DispatchQueue.main).sink { [weak self] _ in- self?.handleActivityProtectionTimingChange()+ self?.handleProtectionTimingChange()}.store(in: &cancellables)@@ -114,7 +107,7 @@ final class CodexActivityMonitor: ObservableObject {}isSystemSleeping = truerecoveryTask?.cancel()- beginActivityProtectionRecovery()+ beginProtectionRecovery()AppLog.activity.notice("异常任务判定已暂停: reason=systemSleep")}.store(in: &cancellables)@@ -138,7 +131,7 @@ final class CodexActivityMonitor: ObservableObject {.publisher(for: .NSSystemClockDidChange).receive(on: DispatchQueue.main).sink { [weak self] _ in- self?.handleActivityProtectionTimingChange()+ self?.handleProtectionTimingChange()}.store(in: &cancellables)}@@ -149,69 +142,56 @@ final class CodexActivityMonitor: ObservableObject {}isStarted = falsecancellables.removeAll()- activityProtectionStateLoadTask?.cancel()- activityProtectionStateLoadTask = nil+ protectionStateLoadTask?.cancel()+ protectionStateLoadTask = nilstopReaderAndClearState()}- private func loadActivityProtectionState() {- guard !isActivityProtectionStateLoaded,- activityProtectionStateLoadTask == nil else {+ private func loadProtectionState() {+ guard !isProtectionStateLoaded,+ protectionStateLoadTask == nil else {return}- activityProtectionStateLoadTask = Task { @MainActor [weak self] in+ protectionStateLoadTask = Task { @MainActor [weak self] inguard let self else {return}- let records = await activityProtectionStateStore.load()+ let records = await protectionStore.load()guard isStarted, !Task.isCancelled else {return}- activityProtectionRecords = records- isActivityProtectionStateLoaded = true- activityProtectionStateLoadTask = nil- setMonitoringEnabled(requestedMonitoringEnabled)+ protectionRecords = records+ isProtectionStateLoaded = true+ protectionStateLoadTask = nil+ startReaderIfReady()}}- private func requestMonitoringEnabled(_ isEnabled: Bool) {- requestedMonitoringEnabled = isEnabled- guard isActivityProtectionStateLoaded else {- return- }- setMonitoringEnabled(isEnabled)- }-- private func setMonitoringEnabled(_ isOperable: Bool) {- guard isOperable else {- AppLog.activity.notice("任务监控已停止: reason=hookInoperable")- stopReaderAndClearState()- return- }-- guard tailReader == nil else {- return- }-- AppLog.activity.notice("任务监控已启动: reason=hookOperable")-- tailReaderGeneration &+= 1- let generation = tailReaderGeneration- let reader = HookEventTailReader(+ private func startReaderIfReady() {+ guard isStarted, isProtectionStateLoaded, activityReader == nil else { return }+ AppLog.activity.notice("任务监控已启动: reason=appLaunch")++ activityReaderGeneration &+= 1+ let generation = activityReaderGeneration+ lifecycleCache = SessionLifecycleCache()+ let reader = AppServerActivityReader(+ lifecycleCache: lifecycleCache,+ tokenHistory: TokenHistoryStore(directoryURL: activityDirectoryURL),+ recorder: ActivityRecorder(directoryURL: activityDirectoryURL),onBatch: { [weak self] batch in- guard let self, tailReaderGeneration == generation else {+ guard let self, activityReaderGeneration == generation else {return}consume(batch)})- tailReader = reader- tailReaderControlTask = Task { @MainActor [weak self] in+ activityReader = reader+ activityReaderControlTask = Task { @MainActor [weak self] inawait reader.start()guard let self,- tailReaderGeneration == generation,- tailReader != nil else {+ activityReaderGeneration == generation,+ activityReader != nil else {return}startSessionLifecyclePolling(generation: generation)@@ -219,14 +199,14 @@ final class CodexActivityMonitor: ObservableObject {}private func stopReaderAndClearState() {- tailReaderGeneration &+= 1+ activityReaderGeneration &+= 1recoveryTask?.cancel()recoveryTask = nil- resetActivityProtectionRecovery()- tailReaderControlTask?.cancel()- tailReaderControlTask = nil- let reader = tailReader- tailReader = nil+ resetProtectionRecovery()+ activityReaderControlTask?.cancel()+ activityReaderControlTask = nil+ let reader = activityReader+ activityReader = nilif let reader {Task {await reader.stop()@@ -257,7 +237,7 @@ final class CodexActivityMonitor: ObservableObject {guard let self else {return}- if isActivityProtectionRecoveryInProgress {+ if isProtectionRecoveryInProgress {if !isSystemSleeping, recoveryTask == nil {requestActivityRecovery()}@@ -269,37 +249,34 @@ final class CodexActivityMonitor: ObservableObject {}}- private func refreshSessionLifecycleNow(resetsResolutionFallbacks: Bool = false) {- guard tailReader != nil else {+ private func refreshSessionLifecycleNow() {+ guard activityReader != nil else {return}- let generation = tailReaderGeneration+ let generation = activityReaderGenerationTask { @MainActor [weak self] inguard let self,- tailReaderGeneration == generation else {+ activityReaderGeneration == generation else {return}- if resetsResolutionFallbacks {- await sessionLifecycleReader.resetResolutionFallbacks()- }guard !Task.isCancelled,- tailReaderGeneration == generation else {+ activityReaderGeneration == generation else {return}await reconcileSessionLifecycles(generation: generation)}}- /// 把一条 rollout 生命周期状态合进当前任务, 返回是否改动过状态+ /// 把一条 app-server 生命周期状态合进当前任务, 返回是否改动过状态/// 待确认终态的任务与在跑的任务走两条分支, 前者已经从 tasks 里挪走private func applyLifecycleState(- _ state: CodexSessionTaskLifecycleState,+ _ state: SessionLifecycleState,terminalOnly: Bool = false,- into transitions: inout [CodexActivityTransition]+ into transitions: inout [ActivityTransition]) -> Bool {guard !terminalOnly || (state.readStatus == .complete && state.terminal != nil) else { return false }- let exact = CodexActivityTaskKey.turn(session: state.requestedThreadID, turn: state.turnID)+ let exact = ActivityTaskKey.turn(session: state.requestedThreadID, turn: state.turnID)let key = tasks.first(where: { $0.value.resolvedTurnKey == exact })?.key?? pendingTerminalTasks.first(where: { $0.value.task.resolvedTurnKey == exact })?.key ?? exactif var pending = pendingTerminalTasks[key] {@@ -320,7 +297,7 @@ final class CodexActivityMonitor: ObservableObject {terminal,task: pending.task,key: key,- abortFallback: pending.supersededAt,+ abortFallback: state.terminalObservedAt ?? state.contextObservedAt ?? pending.supersededAt,publishesEvents: !state.isHistoricalTerminal,into: &transitions)@@ -335,9 +312,9 @@ final class CodexActivityMonitor: ObservableObject {if !terminalOnly {let now = Date()task.recordLifecycleRead(state, at: now)- if task.activityProtectionDeadline(at: now, inactivityDuration: activityProtectionSettings.inactivityDuration.timeInterval)+ if task.protectionDeadline(at: now, inactivityDuration: protectionSettings.inactivityDuration.timeInterval).map({ $0 <= now }) != true {- cancelActivityProtectionAttempt(for: key)+ cancelProtectionAttempt(for: key)}}_ = Self.mergeLifecycleBackfill(from: state, into: &task)@@ -353,14 +330,14 @@ final class CodexActivityMonitor: ObservableObject {terminal,task: task,key: key,- abortFallback: Date(),+ abortFallback: state.terminalObservedAt ?? state.contextObservedAt ?? Date(),publishesEvents: !state.isHistoricalTerminal,into: &transitions)return true}- task.mergeExecutionLifecycle(state, owner: CodexActivityExecutionKey(agentID: nil, turnID: state.turnID))+ task.mergeExecutionLifecycle(state, owner: ActivityExecutionKey(agentID: nil, turnID: state.turnID))let wasSuppressedBeforeApproval = task.state == .suppressedif resolvePendingApprovalIfPossible(@@ -368,7 +345,7 @@ final class CodexActivityMonitor: ObservableObject {into: &transitions) {if wasSuppressedBeforeApproval, task.state == .waitingApproval {- clearActivityProtection(+ clearProtection(for: key,taskID: task.displayID,reason: .progress@@ -384,9 +361,9 @@ final class CodexActivityMonitor: ObservableObject {}func mergeLifecycleProgress(- from state: CodexSessionTaskLifecycleState,- key: CodexActivityTaskKey,- into task: inout CodexActivityTask+ from state: SessionLifecycleState,+ key: ActivityTaskKey,+ into task: inout ActivityTask) -> Bool {guard state.readStatus == .complete,let lastProgressAt = state.lastProgressAt,@@ -396,12 +373,12 @@ final class CodexActivityMonitor: ObservableObject {let wasSuppressed = task.state == .suppressedtask.recordProgress(at: lastProgressAt)- if shouldRestoreActivityProtection(for: key, progressAt: lastProgressAt) {+ if shouldRestoreProtection(for: key, progressAt: lastProgressAt) {if wasSuppressed {task.state = .runningtask.stateChangedAt = lastProgressAt}- clearActivityProtection(+ clearProtection(for: key,taskID: task.displayID,reason: .progress@@ -412,10 +389,10 @@ final class CodexActivityMonitor: ObservableObject {/// 恢复只由读取屏障后的调用推进, 普通 poll 不能绕过恢复代次private func requestActivityRecovery() {- guard !isSystemSleeping, let reader = tailReader, !isBootstrapping else { return }+ guard !isSystemSleeping, let reader = activityReader, !isBootstrapping else { return }recoveryTask?.cancel()- let recoveryGeneration = beginActivityProtectionRecovery()- let generation = tailReaderGeneration+ let recoveryGeneration = beginProtectionRecovery()+ let generation = activityReaderGenerationlet taskID = UUID()recoveryTaskID = taskIDrecoveryTask = Task { @MainActor [weak self] in@@ -427,25 +404,24 @@ final class CodexActivityMonitor: ObservableObject {recoveryTaskID = nil}}- guard !Task.isCancelled, generation == tailReaderGeneration,- recoveryGeneration == activityProtectionRecoveryGeneration else { return }+ guard !Task.isCancelled, generation == activityReaderGeneration,+ recoveryGeneration == protectionRecoveryGeneration else { return }if case .sourceUnavailable = result {- // Hook 缺口只阻止完整恢复, 独立读取成功的明确终态仍可静默收敛+ // 连接缺口只阻止完整恢复, 独立读取成功的明确终态仍可静默收敛_ = await reconcileSessionLifecycles(generation: generation, terminalOnly: true)return}guard case .completed = result, isActivitySourceHealthy, !isBootstrapping else { return }- await sessionLifecycleReader.resetResolutionFallbacks()guard !Task.isCancelled, !isSystemSleeping,- recoveryGeneration == activityProtectionRecoveryGeneration else { return }+ recoveryGeneration == protectionRecoveryGeneration else { return }let didReconcile = await reconcileSessionLifecycles(generation: generation, recovering: true)- guard didReconcile, !Task.isCancelled, generation == tailReaderGeneration,- recoveryGeneration == activityProtectionRecoveryGeneration else { return }- finishActivityProtectionRecovery(generation: recoveryGeneration)+ guard didReconcile, !Task.isCancelled, generation == activityReaderGeneration,+ recoveryGeneration == protectionRecoveryGeneration else { return }+ finishProtectionRecovery(generation: recoveryGeneration)}}- private func lifecycleReferences(now: Date, includeAll: Bool) -> [CodexActivityTurnReference] {+ private func lifecycleReferences(now: Date, includeAll: Bool) -> [ActivityTurnReference] {var references = activeTokenUsageReferences()references.append(contentsOf: subagentLifecycleReferences())references.append(contentsOf: prepareTerminalTokenUsageReadBatch(now: now))@@ -467,23 +443,26 @@ final class CodexActivityMonitor: ObservableObject {recovering: Bool = false,terminalOnly: Bool = false) async -> Bool {- guard generation == tailReaderGeneration, tailReader != nil, !isBootstrapping,+ guard generation == activityReaderGeneration, activityReader != nil, !isBootstrapping,terminalOnly || isActivitySourceHealthy, !isSystemSleeping,- recovering || terminalOnly || !isActivityProtectionRecoveryInProgress,+ recovering || terminalOnly || !isProtectionRecoveryInProgress,!isReconcilingLifecycles else { return false }isReconcilingLifecycles = truedefer { isReconcilingLifecycles = false }let bootstrapGeneration = bootstrapCompletionGeneration- let recoveryGeneration = activityProtectionRecoveryGeneration+ let recoveryGeneration = protectionRecoveryGenerationlet references = lifecycleReferences(now: Date(), includeAll: recovering)- let states = await sessionLifecycleReader.lifecycleStates(for: references)- guard !Task.isCancelled, generation == tailReaderGeneration,+ let states = await lifecycleCache.lifecycleStates(for: references)+ guard !Task.isCancelled, generation == activityReaderGeneration,bootstrapGeneration == bootstrapCompletionGeneration,- recoveryGeneration == activityProtectionRecoveryGeneration,- tailReader != nil, !isBootstrapping, terminalOnly || isActivitySourceHealthy,+ recoveryGeneration == protectionRecoveryGeneration,+ activityReader != nil, !isBootstrapping, terminalOnly || isActivitySourceHealthy,!isSystemSleeping else { return false }- var didChange = false- var transitions: [CodexActivityTransition] = []+ let unavailable = Set(states.filter { $0.readStatus != .complete }.map { ActivityTaskKey.turn(session: $0.requestedThreadID, turn: $0.turnID) })+ let availabilityChanged = unavailableTurns != unavailable+ unavailableTurns = unavailable+ var didChange = availabilityChanged+ var transitions: [ActivityTransition] = []for state in states {didChange = applySubagentLifecycle(state, terminalOnly: terminalOnly, into: &transitions) || didChangedidChange = applyLifecycleState(state, terminalOnly: terminalOnly, into: &transitions) || didChange@@ -511,17 +490,19 @@ final class CodexActivityMonitor: ObservableObject {}var canPublishActivityTransitions: Bool {- !isBootstrapping && !isActivityProtectionRecoveryInProgress && isActivitySourceHealthy+ !isBootstrapping && !isProtectionRecoveryInProgress && isActivitySourceHealthy}- // MARK: - Hook 事件消费+ // MARK: - 活动事件消费- private func consume(_ batch: HookEventBatch) {+ private func consume(_ batch: ActivityEventBatch) {switch batch {+ case .lifecycleChanged:+ refreshSessionLifecycleNow()case .bootstrapStart:recoveryTask?.cancel()recoveryTask = nil- // 重试会重放整段历史, 计时从第一次开始算才是用户等到的总时长+ // 重试会重新查询初始快照, 计时从第一次开始算才是用户等到的总时长if !isBootstrapping {bootstrapDuration = LogDuration()}@@ -537,21 +518,18 @@ final class CodexActivityMonitor: ObservableObject {for event in events {_ = apply(event, source: .bootstrap)}- case let .bootstrapEnd(degraded, attempts):- isActivitySourceHealthy = !degraded+ case .bootstrapEnd:+ isActivitySourceHealthy = truesessionTransitionNotBefore = Date()let completionGeneration = bootstrapCompletionGenerationTask { @MainActor [weak self] inawait self?.finishBootstrap(- degraded: degraded,- attempts: attempts,completionGeneration: completionGeneration)}case let .live(events):- let pendingKeysBefore = Set(pendingTerminalTasks.keys)let activeCountBefore = snapshot.activeCount- var waitingTaskKeys: [CodexActivityTaskKey] = []+ var waitingTaskKeys: [ActivityTaskKey] = []for event in events {if let key = apply(event, source: .live) {waitingTaskKeys.append(key)@@ -572,95 +550,70 @@ final class CodexActivityMonitor: ObservableObject {}publishWaitingApprovalTransitions(waitingTaskKeys)if !pendingTerminalTasks.isEmpty {- // 只有刚进入终态确认窗口的任务需要重置解析缓存重试定位 rollout- // 窗口期内的后续批次只做即时查询, 避免反复递归扫描 sessions- let hasNewPendingTasks = !Set(pendingTerminalTasks.keys)- .subtracting(pendingKeysBefore).isEmpty- refreshSessionLifecycleNow(resetsResolutionFallbacks: hasNewPendingTasks)- } else if events.contains(where: { $0.hookEvent == .stop }) {+ // 新进入终态确认窗口的任务立即查询, 不等待下次周期对账+ refreshSessionLifecycleNow()+ } else if events.contains(where: { $0.eventKind == .turnCompleted }) {refreshSessionLifecycleNow()}- case let .sourceHealthChanged(isHealthy):- guard isHealthy != isActivitySourceHealthy else {+ case .sourceUnavailable:+ guard isActivitySourceHealthy else {return}- isActivitySourceHealthy = isHealthy+ isActivitySourceHealthy = falseresetTerminalPresentationEvents()- if isHealthy {- if !isBootstrapping {- requestActivityRecovery()- }- } else {- beginActivityProtectionRecovery()- cancelInactivityCheck()- cancelAllActivityProtectionAttempts()- AppLog.activity.error(- "异常任务判定已暂停: reason=hookSourceUnavailable"- )- }+ beginProtectionRecovery()+ snapshot = .empty+ cancelInactivityCheck()+ cancelAllProtectionAttempts()+ AppLog.activity.error(+ "异常任务判定已暂停: reason=activitySourceUnavailable"+ )}}private func finishBootstrap(- degraded: Bool,- attempts: Int,completionGeneration: UInt64) async {- let recoveryGeneration = activityProtectionRecoveryGeneration- if !degraded {- let references = tasks.values.compactMap(\.turnReference)- + pendingTerminalTasks.values.compactMap(\.task.turnReference)- if !references.isEmpty {- let states = await sessionLifecycleReader.lifecycleStates(for: references)- guard !Task.isCancelled, completionGeneration == bootstrapCompletionGeneration,- tailReader != nil else {- return- }- var ignoredTransitions: [CodexActivityTransition] = []- if recoveryGeneration == activityProtectionRecoveryGeneration, isActivitySourceHealthy, !isSystemSleeping {- for state in states {- _ = applyLifecycleState(state, into: &ignoredTransitions)- }+ let recoveryGeneration = protectionRecoveryGeneration+ let references = tasks.values.compactMap(\.turnReference)+ + pendingTerminalTasks.values.compactMap(\.task.turnReference)+ if !references.isEmpty {+ let states = await lifecycleCache.lifecycleStates(for: references)+ guard !Task.isCancelled, completionGeneration == bootstrapCompletionGeneration,+ activityReader != nil else {+ return+ }+ var ignoredTransitions: [ActivityTransition] = []+ if recoveryGeneration == protectionRecoveryGeneration, isActivitySourceHealthy, !isSystemSleeping {+ for state in states {+ _ = applyLifecycleState(state, into: &ignoredTransitions)}}}guard completionGeneration == bootstrapCompletionGeneration,- tailReader != nil else {+ activityReader != nil else {return}resetTerminalPresentationEvents()isBootstrapping = falseif isActivitySourceHealthy, !isSystemSleeping {- if recoveryGeneration == activityProtectionRecoveryGeneration {- finishActivityProtectionRecovery(generation: recoveryGeneration)+ if recoveryGeneration == protectionRecoveryGeneration {+ finishProtectionRecovery(generation: recoveryGeneration)} else {requestActivityRecovery()}}let now = Date()- applyPersistedActivityProtection(now: now)- reconcileActivityProtection(now: now, sendsNotification: false)+ applyPersistedProtection(now: now)+ reconcileProtection(now: now, sendsNotification: false)backfillPromptStartTimesFromHistory()let activeCount = snapshot.activeCountlet eventCount = bootstrapEventCountlet elapsed = bootstrapDuration.elapsed- guard !degraded else {- let details = LogFields.joined(- "attempts=\(attempts)",- "events=\(eventCount)",- "activeTasks=\(activeCount)",- "elapsed=\(elapsed)",- "reason=incompleteHistory",- "action=pauseProtection"- )- AppLog.activity.notice("历史回放已降级: \(details, privacy: .public)")- return- }-let details = LogFields.joined(- "attempts=\(attempts)",+ "attempts=1","events=\(eventCount)","activeTasks=\(activeCount)","elapsed=\(elapsed)"@@ -671,15 +624,15 @@ final class CodexActivityMonitor: ObservableObject {/// bootstrap 只覆盖 24 小时窗口; 窗口内恢复出的无起点任务向更早日期回查 Prompt 起点private func backfillPromptStartTimesFromHistory() {let references = tasks.values.compactMap(\.promptReference)- guard !references.isEmpty, let reader = tailReader else {+ guard !references.isEmpty, let reader = activityReader else {return}- let generation = tailReaderGeneration+ let generation = activityReaderGenerationTask { @MainActor [weak self] inlet startTimes = await reader.findPromptStartTimes(for: references)guard let self,- tailReaderGeneration == generation,+ activityReaderGeneration == generation,!isBootstrapping,!startTimes.isEmpty else {return@@ -688,10 +641,10 @@ final class CodexActivityMonitor: ObservableObject {}}- private func backfillStartTimes(_ startTimes: [CodexActivityPromptReference: Date]) {+ private func backfillStartTimes(_ startTimes: [ActivityPromptReference: Date]) {var didChange = falsefor (reference, startedAt) in startTimes {- let key = CodexActivityTaskKey.turn(session: reference.sessionID, turn: reference.turnID)+ let key = ActivityTaskKey.turn(session: reference.sessionID, turn: reference.turnID)guard var task = tasks[key],task.startedAt == nil,startedAt <= task.lastActivityAt else {@@ -707,9 +660,9 @@ final class CodexActivityMonitor: ObservableObject {}func apply(- _ event: WorkflowHookEvent,- source: CodexActivityEventSource- ) -> CodexActivityTaskKey? {+ _ event: ActivityRecord,+ source: ActivityEventSource+ ) -> ActivityTaskKey? {guard let event = activityEvent(from: event, source: source) else {return nil}@@ -718,59 +671,59 @@ final class CodexActivityMonitor: ObservableObject {return nil}let isTopLevelEvent = event.agentID == nil- switch event.hookEvent {- case .userPromptSubmit:+ switch event.eventKind {+ case .turnStarted:guard isTopLevelEvent else { return nil }startTask(from: event, source: source)- case .preToolUse:+ case .toolStarted:resumeTask(from: event,latestEvent: .toolStarted,allowsRecovery: isTopLevelEvent,source: source)- case .postToolUse:+ case .toolCompleted:resumeTask(from: event,latestEvent: .toolFinished,allowsRecovery: isTopLevelEvent,source: source)- case .preCompact:+ case .compactionStarted:resumeTask(from: event,latestEvent: .compactionStarted,allowsRecovery: isTopLevelEvent,source: source)- case .postCompact:+ case .compactionCompleted:resumeTask(from: event,latestEvent: .compactionFinished,allowsRecovery: isTopLevelEvent,source: source)- case .subagentStart:+ case .subagentStarted:// 子智能体只更新所属顶层任务, 不自行创建一条并发任务updateSubagentActivity(from: event, isStarting: true, source: source)- case .subagentStop:+ case .subagentEnded:updateSubagentActivity(from: event, isStarting: false, source: source)- case .permissionRequest:+ case .approvalRequested:return waitForApproval(from: event, source: source)- case .stop:+ case .turnCompleted:guard isTopLevelEvent else {return nil}observeStop(from: event, source: source)- case .interrupt:+ case .turnAborted:guard isTopLevelEvent else {return nil}interruptTask(from: event, source: source)- case .sessionEnd:+ case .sessionEnded:guard isTopLevelEvent else { return nil }terminateSession(from: event)- case .sessionStart, .none:+ case .sessionStarted, .none:break}return nil@@ -779,10 +732,10 @@ final class CodexActivityMonitor: ObservableObject {// MARK: - 任务状态转换private func startTask(- from event: WorkflowHookEvent,- source: CodexActivityEventSource+ from event: ActivityRecord,+ source: ActivityEventSource) {- let key = CodexActivityTaskKey(event: event)+ let key = ActivityTaskKey(event: event)guard !updateAliasedPrompt(from: event, key: key) else { return }preserveSupersededSessionTask(from: event, key: key)if let pending = pendingTerminalTasks[key] {@@ -805,7 +758,7 @@ final class CodexActivityMonitor: ObservableObject {return}}- if let existing = tasks[key], event.timestamp < existing.lastMainHookEventAt {+ if let existing = tasks[key], event.timestamp < existing.lastMainEventAt {return}@@ -813,7 +766,7 @@ final class CodexActivityMonitor: ObservableObject {// 同一 session 的 turn 按顺序执行. 新 prompt 让旧 turn 立即退出活动列表// 但保留短暂终态确认窗口, 避免把迟到的正常完成误记为终止guard !tasks.values.contains(where: {- $0.key.sessionID == sessionID && $0.lastMainHookEventAt > event.timestamp+ $0.key.sessionID == sessionID && $0.lastMainEventAt > event.timestamp}) else {return}@@ -821,7 +774,7 @@ final class CodexActivityMonitor: ObservableObject {$0.key != key && $0.key.sessionID == sessionID}for task in supersededTasks {- clearActivityProtection(for: task.key, taskID: task.displayID, reason: .terminal)+ clearProtection(for: task.key, taskID: task.displayID, reason: .terminal)pendingTerminalTasks[task.key] = PendingTerminalTask(task: task,supersededAt: event.timestamp,@@ -834,7 +787,7 @@ final class CodexActivityMonitor: ObservableObject {}if source == .live {- clearActivityProtection(+ clearProtection(for: key,taskID: displayID,reason: .progress@@ -851,7 +804,7 @@ final class CodexActivityMonitor: ObservableObject {return}- var task = CodexActivityTask(+ var task = ActivityTask(displayID: displayID,key: key,event: event,@@ -865,12 +818,12 @@ final class CodexActivityMonitor: ObservableObject {}private func resumeTask(- from event: WorkflowHookEvent,- latestEvent: CodexActivityEvent,+ from event: ActivityRecord,+ latestEvent: ActivityPhase,allowsRecovery: Bool,- source: CodexActivityEventSource+ source: ActivityEventSource) {- let eventKey = CodexActivityTaskKey(event: event)+ let eventKey = ActivityTaskKey(event: event)let matchedKey = event.agentID == nil? matchingActiveTaskKey(for: event): matchingSubagentParentTaskKey(for: event)@@ -887,10 +840,10 @@ final class CodexActivityMonitor: ObservableObject {let wasSuppressed = task.state == .suppressedtask.resumeExecution(from: event, latestEvent: latestEvent)task.mergeMetadata(from: event)- task.recordHookEvent(at: event.timestamp)+ task.recordEvent(at: event.timestamp)tasks[key] = taskif wasSuppressed || source == .live {- clearActivityProtection(+ clearProtection(for: key,taskID: task.displayID,reason: .progress@@ -906,7 +859,7 @@ final class CodexActivityMonitor: ObservableObject {return}- let recoveredTask = CodexActivityTask(+ let recoveredTask = ActivityTask(displayID: UUID(),key: eventKey,event: event,@@ -917,7 +870,7 @@ final class CodexActivityMonitor: ObservableObject {)tasks[eventKey] = recoveredTaskif source == .live {- clearActivityProtection(+ clearProtection(for: eventKey,taskID: recoveredTask.displayID,reason: .progress@@ -926,9 +879,9 @@ final class CodexActivityMonitor: ObservableObject {}private func updateSubagentActivity(- from event: WorkflowHookEvent,+ from event: ActivityRecord,isStarting: Bool,- source: CodexActivityEventSource+ source: ActivityEventSource) {guard let key = matchingSubagentParentTaskKey(for: event),recentEndedDate(for: key) == nil,@@ -953,19 +906,19 @@ final class CodexActivityMonitor: ObservableObject {let wasSuppressed = task.state == .suppressedtask.resumeExecution(from: event, latestEvent: isStarting ? .subagentStarted : .subagentFinished)task.mergeMetadata(from: event)- task.recordHookEvent(at: event.timestamp)+ task.recordEvent(at: event.timestamp)if wasSuppressed || source == .live {- clearActivityProtection(for: key, taskID: task.displayID, reason: .progress)+ clearProtection(for: key, taskID: task.displayID, reason: .progress)}}tasks[key] = task}private func waitForApproval(- from event: WorkflowHookEvent,- source: CodexActivityEventSource- ) -> CodexActivityTaskKey? {- let eventKey = CodexActivityTaskKey(event: event)+ from event: ActivityRecord,+ source: ActivityEventSource+ ) -> ActivityTaskKey? {+ let eventKey = ActivityTaskKey(event: event)let matchedKey = event.agentID == nil? matchingActiveTaskKey(for: event): matchingSubagentParentTaskKey(for: event)@@ -982,12 +935,13 @@ final class CodexActivityMonitor: ObservableObject {let wasSuppressed = task.state == .suppressedtask.mergeMetadata(from: event)// 权限事件描述当前请求; 缺失工具名时不能沿用上一条工具事件- task.toolName = event.toolName- task.recordHookEvent(at: event.timestamp)+ task.toolName = event.tool+ task.itemType = event.source?.itemType+ task.recordEvent(at: event.timestamp)let enteredWaiting = task.recordApprovalRequest(from: event)tasks[key] = taskif wasSuppressed || source == .live {- clearActivityProtection(+ clearProtection(for: key,taskID: task.displayID,reason: .progress@@ -1003,7 +957,7 @@ final class CodexActivityMonitor: ObservableObject {return nil}- var task = CodexActivityTask(+ var task = ActivityTask(displayID: UUID(),key: eventKey,event: event,@@ -1015,7 +969,7 @@ final class CodexActivityMonitor: ObservableObject {let enteredWaiting = task.recordApprovalRequest(from: event)tasks[eventKey] = taskif source == .live {- clearActivityProtection(+ clearProtection(for: eventKey,taskID: task.displayID,reason: .progress@@ -1024,9 +978,9 @@ final class CodexActivityMonitor: ObservableObject {return enteredWaiting ? eventKey : nil}- /// Stop handler 仍可要求同一 turn 继续执行, 完成只由 rollout terminal 确认- private func observeStop(from event: WorkflowHookEvent, source: CodexActivityEventSource) {- let eventKey = CodexActivityTaskKey(event: event)+ /// 结束提示与生命周期分开处理, 完成分类由服务端轮次终态确认+ private func observeStop(from event: ActivityRecord, source: ActivityEventSource) {+ let eventKey = ActivityTaskKey(event: event)guard recentEndedDate(for: eventKey) == nil else {discardStaleTerminalTask(for: eventKey)return@@ -1038,12 +992,12 @@ final class CodexActivityMonitor: ObservableObject {AppLog.activity.error("任务终态已延后: reason=ambiguousStop")case let .pending(key):guard var pending = pendingTerminalTasks[key],- event.timestamp >= pending.task.lastMainHookEventAt else {+ event.timestamp >= pending.task.lastMainEventAt else {return}// 新 turn 或 SessionEnd 已确定旧任务退出活动列表, Stop 不恢复它或重置 gracepending.task.mergeMetadata(from: event)- pending.task.recordHookEvent(at: event.timestamp)+ pending.task.recordEvent(at: event.timestamp)pendingTerminalTasks[key] = pendingcase .active, .none:resumeTask(@@ -1055,16 +1009,16 @@ final class CodexActivityMonitor: ObservableObject {}}- func discardStaleTerminalTask(for key: CodexActivityTaskKey) {+ func discardStaleTerminalTask(for key: ActivityTaskKey) {if let task = tasks.removeValue(forKey: key) {- clearActivityProtection(+ clearProtection(for: key,taskID: task.displayID,reason: .terminal)}if let pending = pendingTerminalTasks.removeValue(forKey: key) {- clearActivityProtection(+ clearProtection(for: key,taskID: pending.task.displayID,reason: .terminal@@ -1073,15 +1027,15 @@ final class CodexActivityMonitor: ObservableObject {}/// SessionEnd 没有 turn_id, 以 session 为边界把活跃任务移入终态确认窗口- /// 任务立即退出活跃列表, 后续继续从 rollout 确认完成或终止分类- private func terminateSession(from event: WorkflowHookEvent) {+ /// 任务立即退出活跃列表, 后续继续从 app-server 确认完成或终止分类+ private func terminateSession(from event: ActivityRecord) {guard let sessionID = event.sessionID else {return}let deadline = Date().addingTimeInterval(Self.supersededTerminalGracePeriod)let matchingPendingTasks = pendingTerminalTasks.filter { key, pending in- key.sessionID == sessionID && pending.task.lastMainHookEventAt <= event.timestamp+ key.sessionID == sessionID && pending.task.lastMainEventAt <= event.timestamp}for (key, pending) in matchingPendingTasks {pendingTerminalTasks[key] = PendingTerminalTask(@@ -1092,11 +1046,11 @@ final class CodexActivityMonitor: ObservableObject {}let matchingActiveTasks = tasks.filter { key, task in- key.sessionID == sessionID && task.lastMainHookEventAt <= event.timestamp+ key.sessionID == sessionID && task.lastMainEventAt <= event.timestamp}for (key, task) in matchingActiveTasks {tasks.removeValue(forKey: key)- clearActivityProtection(for: key, taskID: task.displayID, reason: .terminal)+ clearProtection(for: key, taskID: task.displayID, reason: .terminal)pendingTerminalTasks[key] = PendingTerminalTask(task: task,supersededAt: event.timestamp,@@ -1106,8 +1060,8 @@ final class CodexActivityMonitor: ObservableObject {}/// 精确 turn 失败后只接受同 session 唯一活动任务, 有待确认旧 turn 时不猜测- private func matchingActiveTaskKey(for event: WorkflowHookEvent) -> CodexActivityTaskKey? {- let exactKey = CodexActivityTaskKey(event: event)+ private func matchingActiveTaskKey(for event: ActivityRecord) -> ActivityTaskKey? {+ let exactKey = ActivityTaskKey(event: event)if let key = tasks.first(where: { $0.value.resolvedTurnKey == exactKey })?.key {return key}@@ -1131,17 +1085,17 @@ final class CodexActivityMonitor: ObservableObject {return candidates[0].key}- let anonymousKey = CodexActivityTaskKey.anonymous(- project: CodexActivityTaskKey.projectIdentifier(event.projectDisplayName)+ let anonymousKey = ActivityTaskKey.anonymous(+ project: ActivityTaskKey.projectIdentifier(event.projectDisplayName))return tasks[anonymousKey] == nil ? nil : anonymousKey}func matchingTerminalTask(- for event: WorkflowHookEvent,+ for event: ActivityRecord,allowsAnonymousFallback: Bool = true- ) -> CodexTerminalTaskMatch {- let exactKey = CodexActivityTaskKey(event: event)+ ) -> TerminalTaskMatch {+ let exactKey = ActivityTaskKey(event: event)if let key = pendingTerminalTasks.first(where: { $0.value.task.resolvedTurnKey == exactKey })?.key {return .pending(key)}@@ -1159,7 +1113,7 @@ final class CodexActivityMonitor: ObservableObject {if let sessionID = event.sessionID {let pendingCandidates = pendingTerminalTasks.filter {$0.value.task.key.sessionID == sessionID- && $0.value.task.lastMainHookEventAt <= event.timestamp+ && $0.value.task.lastMainEventAt <= event.timestamp&& (event.turnID == nil || $0.value.task.associatedTurnID == nil)}if pendingCandidates.count == 1, let key = pendingCandidates.keys.first {@@ -1171,7 +1125,7 @@ final class CodexActivityMonitor: ObservableObject {let activeCandidates = tasks.values.filter {$0.key.sessionID == sessionID- && $0.lastMainHookEventAt <= event.timestamp+ && $0.lastMainEventAt <= event.timestamp&& (event.turnID == nil || $0.associatedTurnID == nil)}if activeCandidates.count == 1 {@@ -1185,8 +1139,8 @@ final class CodexActivityMonitor: ObservableObject {guard allowsAnonymousFallback else {return .none}- let anonymousKey = CodexActivityTaskKey.anonymous(- project: CodexActivityTaskKey.projectIdentifier(event.projectDisplayName)+ let anonymousKey = ActivityTaskKey.anonymous(+ project: ActivityTaskKey.projectIdentifier(event.projectDisplayName))if tasks[anonymousKey] != nil {return .active(anonymousKey)@@ -1201,13 +1155,14 @@ final class CodexActivityMonitor: ObservableObject {func refreshSnapshot(now: Date) {pruneExpiredState(now: now)+ guard isActivitySourceHealthy || !isStarted else { return }let waitingTasks = sortedTasks(in: .waitingApproval)let runningTasks = sortedTasks(in: .running)let recentCompletions = completions.sorted(by: Self.recentFirst(\.completedAt, \.id))let recentTerminations = terminations.sorted(by: Self.recentFirst(\.terminatedAt, \.id))- let newSnapshot = CodexActivitySnapshot(+ let newSnapshot = ActivitySnapshot(waitingTasks: waitingTasks.map(\.snapshot),runningTasks: runningTasks.map(\.snapshot),recentCompletions: recentCompletions,@@ -1220,16 +1175,16 @@ final class CodexActivityMonitor: ObservableObject {snapshot = newSnapshot}if didChange || !events.isEmpty {- presentationSubject.send(CodexActivityPresentationUpdate(snapshot: newSnapshot, terminalEvents: events))+ presentationSubject.send(ActivityPresentationUpdate(snapshot: newSnapshot, terminalEvents: events))}scheduleNextCleanup(now: now)scheduleNextInactivityCheck(now: now)}- private func sortedTasks(in state: CodexActivityTaskState) -> [CodexActivityTask] {+ private func sortedTasks(in state: ActivityTaskState) -> [ActivityTask] {tasks.values- .filter { $0.state == state }+ .filter { $0.state == state && !unavailableTurns.contains($0.resolvedTurnKey ?? $0.key) }.sorted(by: Self.recentFirst(\.lastActivityAt, \.displayID))}@@ -1252,7 +1207,7 @@ final class CodexActivityMonitor: ObservableObject {let activityCutoff = now.addingTimeInterval(-Self.activityRetention)let expiredTasks = tasks.filter { $0.value.lastActivityAt <= activityCutoff }for (key, task) in expiredTasks {- clearActivityProtection(+ clearProtection(for: key,taskID: task.displayID,reason: .retention@@ -1260,7 +1215,7 @@ final class CodexActivityMonitor: ObservableObject {}tasks = tasks.filter { $0.value.lastActivityAt > activityCutoff }- removeExpiredActivityProtectionRecords(now: now)+ removeExpiredProtectionRecords(now: now)let historyCutoff = now.addingTimeInterval(-Self.recentHistoryRetention)completions.removeAll { $0.completedAt <= historyCutoff }@@ -1297,7 +1252,7 @@ final class CodexActivityMonitor: ObservableObject {deadlines.append(contentsOf: activityTaskOrigins.values.map {$0.observedAt.addingTimeInterval(Self.activityRetention)})- deadlines.append(contentsOf: activityProtectionRecords.values.map(\.expiresAt))+ deadlines.append(contentsOf: protectionRecords.values.map(\.expiresAt))guard let nextDeadline = deadlines.filter({ $0 > now }).min() else {cleanupTask?.cancel()@@ -1324,27 +1279,27 @@ final class CodexActivityMonitor: ObservableObject {private static let recentHistoryRetention: TimeInterval = 10 * 60static let endedTaskRetention: TimeInterval = 24 * 60 * 60- static let activityRetention = CodexActivityRetention.window- static let activityProtectionNotificationSubmissionGrace: Duration = .seconds(3)+ static let activityRetention = ActivityRetention.window+ static let protectionNotificationSubmissionGrace: Duration = .seconds(3)private static let supersededTerminalGracePeriod: TimeInterval = 5private static let sessionLifecyclePollInterval: TimeInterval = 1}-private extension CodexActivityMonitor {- func resumePromptInSameTurn(from event: WorkflowHookEvent, existing: CodexActivityTask?) -> Bool {+private extension ActivityMonitor {+ func resumePromptInSameTurn(from event: ActivityRecord, existing: ActivityTask?) -> Bool {guard var task = existing, let turnID = event.turnID, task.associatedTurnID == turnID else { return false }task.resumeExecution(from: event, latestEvent: .promptSubmitted)task.mergeMetadata(from: event)- task.recordHookEvent(at: event.timestamp)+ task.recordEvent(at: event.timestamp)task.startedAt = task.startedAt ?? event.timestamptasks[task.key] = taskreturn true}- func preserveSupersededSessionTask(from event: WorkflowHookEvent, key: CodexActivityTaskKey) {+ func preserveSupersededSessionTask(from event: ActivityRecord, key: ActivityTaskKey) {if let existing = tasks[key], key.isSessionOnly,let resolved = existing.resolvedTurnKey,- event.timestamp > (existing.startedAt ?? existing.lastHookEventAt) {+ event.timestamp > (existing.startedAt ?? existing.lastEventAt) {pendingTerminalTasks[resolved] = PendingTerminalTask(task: existing,supersededAt: event.timestamp,@@ -1353,15 +1308,15 @@ private extension CodexActivityMonitor {}}- func updateAliasedPrompt(from event: WorkflowHookEvent, key: CodexActivityTaskKey) -> Bool {+ func updateAliasedPrompt(from event: ActivityRecord, key: ActivityTaskKey) -> Bool {guard let existing = tasks.values.first(where: { $0.resolvedTurnKey == key && $0.key != key }) else {return false}- guard event.timestamp >= existing.lastMainHookEventAt else { return true }+ guard event.timestamp >= existing.lastMainEventAt else { return true }var task = existingtask.mergeMetadata(from: event)task.recordExecutionEvent(event)- task.recordHookEvent(at: event.timestamp)+ task.recordEvent(at: event.timestamp)tasks[existing.key] = taskreturn true}diff --git a/CodexBar/Services/Workflow/CodexActivityTask.swift b/CodexBar/Services/Activity/ActivityTask.swiftsimilarity index 70%rename from CodexBar/Services/Workflow/CodexActivityTask.swiftrename to CodexBar/Services/Activity/ActivityTask.swiftindex 74f23cf..ce1c1ab 100644--- a/CodexBar/Services/Workflow/CodexActivityTask.swift+++ b/CodexBar/Services/Activity/ActivityTask.swift@@ -1,12 +1,12 @@import CryptoKitimport Foundation-enum CodexActivityTaskKey: Hashable {+enum ActivityTaskKey: Hashable {case turn(session: String, turn: String)case session(String)case anonymous(project: String)- init(event: WorkflowHookEvent) {+ init(event: ActivityRecord) {if let sessionID = event.sessionID, let turnID = event.turnID {self = .turn(session: sessionID, turn: turnID)} else if let sessionID = event.sessionID {@@ -44,7 +44,7 @@ enum CodexActivityTaskKey: Hashable {return false}- var activityProtectionIdentifier: String? {+ var protectionIdentifier: String? {let value: Stringswitch self {case let .turn(session, turn):@@ -54,6 +54,7 @@ enum CodexActivityTaskKey: Hashable {case .anonymous:return nil}+ // 哈希域固定不随代码命名变化, 避免同一任务生成不同的保护标识let data = Data("CodexBar.ActivityProtection.v1\u{0}\(value)".utf8)return SHA256.hash(data: data).map {String(format: "%02x", $0)@@ -65,86 +66,85 @@ enum CodexActivityTaskKey: Hashable {}}-enum CodexActivityEventSource {+enum ActivityEventSource {case bootstrapcase live}-enum CodexTerminalTaskMatch {- case active(CodexActivityTaskKey)- case pending(CodexActivityTaskKey)+enum TerminalTaskMatch {+ case active(ActivityTaskKey)+ case pending(ActivityTaskKey)case ambiguouscase none}-enum ActivityProtectionClearReason {+enum ProtectionClearReason {case progresscase thresholdChangecase terminalcase retention}-struct ActivityProtectionCandidate {- let key: CodexActivityTaskKey+struct ProtectionCandidate {+ let key: ActivityTaskKeylet taskID: UUIDlet projectName: String?let lastProgressAt: Datelet progressGeneration: UInt64- let inactivityDuration: ActivityProtectionSettings.InactivityDuration+ let inactivityDuration: ProtectionSettings.InactivityDuration}-struct ActivityProtectionAttempt {+struct ProtectionAttempt {let id: UUID- let candidate: ActivityProtectionCandidate+ let candidate: ProtectionCandidatelet markedAt: Datelet timeoutTask: Task<Void, Never>}-enum CodexActivityTaskState: Equatable {+enum ActivityTaskState: Equatable {case runningcase waitingApprovalcase suppressed}struct PendingTerminalTask {- var task: CodexActivityTask+ var task: ActivityTasklet supersededAt: Datelet deadline: Datevar nextPollAt: Date = .distantPastvar expiresAt: Date {- supersededAt.addingTimeInterval(CodexActivityRetention.window)+ supersededAt.addingTimeInterval(ActivityRetention.window)}}-struct CodexActivityTask {+struct ActivityTask {let displayID: UUID- let key: CodexActivityTaskKey+ let key: ActivityTaskKeyvar associatedTurnID: String?var lifecycleCoverageCheckedAt: Date?- var incompleteTailCheckedAt: Date?- var incompleteTailUnchangedSince: Date?- var state: CodexActivityTaskState- var latestEvent: CodexActivityEvent+ var state: ActivityTaskState+ var latestEvent: ActivityPhasevar projectName: String?var modelName: String?var effort: String?var toolName: String?+ var itemType: String?var startedAt: Date?var stateChangedAt: Date- var lastHookEventAt: Date+ var lastEventAt: Datevar lastProgressAt: Datevar progressGeneration: UInt64- var executions: [CodexActivityExecutionKey: CodexActivityExecution] = [:]- var subagentsByID: [String: CodexSubagentObservation]+ var executions: [ActivityExecutionKey: ActivityExecution] = [:]+ var subagentsByID: [String: SubagentObservation]var isSubagentCountReliable: Bool- var tokenUsage: CodexTokenUsage?+ var tokenUsage: TokenUsage?init(displayID: UUID,- key: CodexActivityTaskKey,- event: WorkflowHookEvent,- state: CodexActivityTaskState,- latestEvent: CodexActivityEvent,+ key: ActivityTaskKey,+ event: ActivityRecord,+ state: ActivityTaskState,+ latestEvent: ActivityPhase,startedAt: Date?,progressGeneration: UInt64) {@@ -154,12 +154,13 @@ struct CodexActivityTask {self.state = stateself.latestEvent = latestEventprojectName = event.projectDisplayName- modelName = event.modelName+ modelName = event.modeleffort = Self.normalizedEffort(event.effort)- toolName = event.toolName+ toolName = event.tool+ itemType = event.source?.itemTypeself.startedAt = startedAtstateChangedAt = event.timestamp- lastHookEventAt = event.timestamp+ lastEventAt = event.timestamplastProgressAt = event.timestampself.progressGeneration = progressGenerationsubagentsByID = [:]@@ -179,8 +180,8 @@ struct CodexActivityTask {return end.timeIntervalSince(startedAt)}- var snapshot: CodexActivityTaskSnapshot {- CodexActivityTaskSnapshot(+ var snapshot: ActivityTaskSnapshot {+ ActivityTaskSnapshot(id: displayID,isAnonymous: key.isAnonymous,latestEvent: displayedApproval == nil ? latestEvent : .approvalRequested,@@ -192,30 +193,31 @@ struct CodexActivityTask {stateChangedAt: stateChangedAt,showsPreciseDuration: showsPreciseDuration,activeSubagentCount: activeSubagentCount,- tokenUsage: tokenUsage+ tokenUsage: tokenUsage,+ itemType: displayedApproval.map(\.itemType) ?? itemType)}- var turnReference: CodexActivityTurnReference? {+ var turnReference: ActivityTurnReference? {guard let sessionID = key.sessionID, let turnID = associatedTurnID else {return nil}- return CodexActivityTurnReference(+ return ActivityTurnReference(threadID: sessionID,turnID: turnID,startedAt: startedAt ?? lastActivityAt)}- var promptReference: CodexActivityPromptReference? {+ var promptReference: ActivityPromptReference? {guard startedAt == nil,let sessionID = key.sessionID, let turnID = associatedTurnID else {return nil}- return CodexActivityPromptReference(sessionID: sessionID, turnID: turnID)+ return ActivityPromptReference(sessionID: sessionID, turnID: turnID)}- var resolvedTurnKey: CodexActivityTaskKey? {+ var resolvedTurnKey: ActivityTaskKey? {guard let session = key.sessionID, let turn = associatedTurnID else { return nil }return .turn(session: session, turn: turn)}@@ -228,40 +230,40 @@ struct CodexActivityTask {lifecycleCoverageCheckedAt.map { now.timeIntervalSince($0) < 5 } == true}- mutating func recordLifecycleRead(_ state: CodexSessionTaskLifecycleState, at now: Date) {+ mutating func recordLifecycleRead(_ state: SessionLifecycleState, at now: Date) {lifecycleCoverageCheckedAt = state.readStatus == .complete && state.hasContext ? now : nil- incompleteTailUnchangedSince = state.readStatus == .incomplete && state.hasContext ? state.incompleteTailUnchangedSince : nil- incompleteTailCheckedAt = incompleteTailUnchangedSince == nil ? nil : now}/// 阈值调整与隐藏共用计时起点, 恢复不要求读取结果仍在有效期内- var activityProtectionReferenceAt: Date {- max(lastProgressAt, incompleteTailUnchangedSince ?? lastProgressAt)+ var protectionReferenceAt: Date {+ lastProgressAt}- /// 隐藏还要求新鲜的读取依据, 半行观察不作为完整覆盖或任务进展- func activityProtectionDeadline(at now: Date, inactivityDuration: TimeInterval) -> Date? {- if hasFreshLifecycle(at: now) {- return activityProtectionReferenceAt.addingTimeInterval(inactivityDuration)- }- guard let incompleteTailCheckedAt, now.timeIntervalSince(incompleteTailCheckedAt) < 5,- incompleteTailUnchangedSince != nil else { return nil }- return activityProtectionReferenceAt.addingTimeInterval(inactivityDuration)+ /// 隐藏还要求共享服务提供的新鲜生命周期覆盖+ func protectionDeadline(at now: Date, inactivityDuration: TimeInterval) -> Date? {+ guard hasFreshLifecycle(at: now) else { return nil }+ return protectionReferenceAt.addingTimeInterval(inactivityDuration)}- mutating func mergeMetadata(from event: WorkflowHookEvent) {+ mutating func mergeMetadata(from event: ActivityRecord) {if associatedTurnID == nil, !key.isAnonymous, event.agentID == nil {associatedTurnID = event.turnID}projectName = event.projectDisplayName ?? projectName- modelName = event.modelName ?? modelName+ modelName = event.model ?? modelName_ = mergeEffort(event.effort)- toolName = event.toolName ?? toolName+ switch event.eventKind {+ case .toolStarted, .toolCompleted, .approvalRequested:+ toolName = event.tool+ itemType = event.source?.itemType+ default:+ break+ }}- /// Hook 顺序独立于 rollout 进展, 避免用量记录使稍早的状态事件失效- mutating func recordHookEvent(at timestamp: Date) {- lastHookEventAt = max(lastHookEventAt, timestamp)+ /// 业务事件顺序独立于执行进展, 避免用量记录使稍早的状态事件失效+ mutating func recordEvent(at timestamp: Date) {+ lastEventAt = max(lastEventAt, timestamp)recordProgress(at: timestamp)}@@ -304,7 +306,7 @@ struct CodexActivityTask {if !isStarting, previous == nil {isSubagentCountReliable = false}- subagentsByID[agentID] = CodexSubagentObservation(+ subagentsByID[agentID] = SubagentObservation(isRunning: isStarting && !hasEnded,timestamp: timestamp)@@ -329,8 +331,8 @@ struct CodexActivityTask {return value.isEmpty ? nil : value}- var displayedApproval: CodexActivityApproval? {- executions.values.compactMap { execution -> CodexActivityApproval? in+ var displayedApproval: ActivityApproval? {+ executions.values.compactMap { execution -> ActivityApproval? inguard case let .waiting(approval)? = execution.approval else { return nil }return approval}.min {@@ -341,33 +343,33 @@ struct CodexActivityTask {}}- func executionKey(for event: WorkflowHookEvent) -> CodexActivityExecutionKey {- CodexActivityExecutionKey(+ func executionKey(for event: ActivityRecord) -> ActivityExecutionKey {+ ActivityExecutionKey(agentID: event.agentID,turnID: event.turnID,isUnattributed: event.agentID == nil && event.origin != .main)}- var lastMainHookEventAt: Date {+ var lastMainEventAt: Date {executions.filter { $0.key.agentID == nil && !$0.key.isUnattributed }- .values.map(\.lastHookEventAt).max() ?? startedAt ?? .distantPast+ .values.map(\.lastEventAt).max() ?? startedAt ?? .distantPast}- func acceptsExecutionEvent(_ event: WorkflowHookEvent) -> Bool {+ func acceptsExecutionEvent(_ event: ActivityRecord) -> Bool {let execution = executions[executionKey(for: event)]- return execution?.isTerminal != true && event.timestamp >= (execution?.lastHookEventAt ?? .distantPast)+ return execution?.isTerminal != true && event.timestamp >= (execution?.lastEventAt ?? .distantPast)}- mutating func recordExecutionEvent(_ event: WorkflowHookEvent) {+ mutating func recordExecutionEvent(_ event: ActivityRecord) {let owner = executionKey(for: event)- var execution = executions[owner] ?? CodexActivityExecution()- execution.lastHookEventAt = max(execution.lastHookEventAt, event.timestamp)+ var execution = executions[owner] ?? ActivityExecution()+ execution.lastEventAt = max(execution.lastEventAt, event.timestamp)execution.mergeReviewer(event.approvalReviewer, at: event.timestamp)executions[owner] = execution}- mutating func resumeExecution(from event: WorkflowHookEvent, latestEvent: CodexActivityEvent) {+ mutating func resumeExecution(from event: ActivityRecord, latestEvent: ActivityPhase) {recordExecutionEvent(event)let owner = executionKey(for: event)if owner.isReliable, var execution = executions[owner] {@@ -380,7 +382,7 @@ struct CodexActivityTask {}/// 审批路由未知时只保存候选, 后续上下文只能确认同一执行归属- mutating func recordApprovalRequest(from event: WorkflowHookEvent) -> Bool {+ mutating func recordApprovalRequest(from event: ActivityRecord) -> Bool {let wasWaiting = state == .waitingApprovallet owner = executionKey(for: event)guard event.timestamp > (executions[owner]?.lastApprovalRequestedAt ?? .distantPast),@@ -388,8 +390,9 @@ struct CodexActivityTask {recordExecutionEvent(event)executions[owner]?.lastApprovalRequestedAt = event.timestampif executions[owner]?.approval == nil {- executions[owner]?.approval = .pending(CodexActivityApproval(- requestedAt: event.timestamp, toolName: event.toolName, sequence: progressGeneration+ executions[owner]?.approval = .pending(ActivityApproval(+ requestedAt: event.timestamp, toolName: event.tool, sequence: progressGeneration,+ itemType: event.source?.itemType))}_ = resolvePendingApprovals()@@ -413,27 +416,40 @@ struct CodexActivityTask {}mutating func mergeApprovalContext(- reviewer: CodexApprovalReviewer?, observedAt: Date?, owner: CodexActivityExecutionKey+ reviewer: ApprovalReviewer?, observedAt: Date?, owner: ActivityExecutionKey) {guard let observedAt else { return }- var execution = executions[owner] ?? CodexActivityExecution()+ var execution = executions[owner] ?? ActivityExecution()execution.mergeReviewer(reviewer, at: observedAt)executions[owner] = execution}- mutating func mergeExecutionLifecycle(_ lifecycle: CodexSessionTaskLifecycleState, owner: CodexActivityExecutionKey) {+ mutating func mergeExecutionLifecycle(_ lifecycle: SessionLifecycleState, owner: ActivityExecutionKey) {guard lifecycle.readStatus == .complete else { return }if lifecycle.terminal != nil {finishExecution(owner, at: lifecycle.lastProgressAt ?? lastProgressAt)} else {mergeApprovalContext(reviewer: lifecycle.approvalReviewer, observedAt: lifecycle.contextObservedAt, owner: owner)mergeExecutionProgress(at: lifecycle.lastExecutionProgressAt, owner: owner)+ if let waiting = lifecycle.isWaitingApproval, let changedAt = lifecycle.approvalChangedAt {+ var execution = executions[owner] ?? ActivityExecution()+ if waiting {+ let approval = execution.approval?.request ?? ActivityApproval(+ requestedAt: changedAt, toolName: nil, sequence: progressGeneration+ )+ execution.approval = .waiting(approval)+ } else {+ execution.approval = nil+ }+ executions[owner] = execution+ refreshApprovalState(at: changedAt)+ }}}- mutating func mergeExecutionProgress(at timestamp: Date?, owner: CodexActivityExecutionKey) {+ mutating func mergeExecutionProgress(at timestamp: Date?, owner: ActivityExecutionKey) {guard owner.isReliable, let timestamp else { return }- var execution = executions[owner] ?? CodexActivityExecution()+ var execution = executions[owner] ?? ActivityExecution()execution.lastExecutionProgressAt = max(execution.lastExecutionProgressAt ?? .distantPast, timestamp)if let approval = execution.approval, timestamp > approval.request.requestedAt {execution.approval = nil@@ -442,8 +458,8 @@ struct CodexActivityTask {refreshApprovalState(at: timestamp)}- mutating func finishExecution(_ owner: CodexActivityExecutionKey, at timestamp: Date) {- var execution = executions[owner] ?? CodexActivityExecution()+ mutating func finishExecution(_ owner: ActivityExecutionKey, at timestamp: Date) {+ var execution = executions[owner] ?? ActivityExecution()execution.approval = nilexecution.isTerminal = trueexecutions[owner] = execution@@ -465,7 +481,7 @@ struct CodexActivityTask {}}-struct CodexActivityExecutionKey: Hashable {+struct ActivityExecutionKey: Hashable {let agentID: String?let turnID: String?var isUnattributed = false@@ -475,40 +491,41 @@ struct CodexActivityExecutionKey: Hashable {}}-struct CodexActivityApproval {+struct ActivityApproval {let requestedAt: Datelet toolName: String?let sequence: UInt64+ var itemType: String?}-enum CodexActivityApprovalState {- case pending(CodexActivityApproval)- case waiting(CodexActivityApproval)+enum ActivityApprovalState {+ case pending(ActivityApproval)+ case waiting(ActivityApproval)- var request: CodexActivityApproval {+ var request: ActivityApproval {switch self {case let .pending(request), let .waiting(request): request}}}-struct CodexActivityExecution {- var lastHookEventAt: Date = .distantPast- var approvalReviewer: CodexApprovalReviewer?+struct ActivityExecution {+ var lastEventAt: Date = .distantPast+ var approvalReviewer: ApprovalReviewer?var approvalContextObservedAt: Date?var lastExecutionProgressAt: Date?var lastApprovalRequestedAt: Date?- var approval: CodexActivityApprovalState?+ var approval: ActivityApprovalState?var isTerminal = false- mutating func mergeReviewer(_ reviewer: CodexApprovalReviewer?, at timestamp: Date) {+ mutating func mergeReviewer(_ reviewer: ApprovalReviewer?, at timestamp: Date) {guard let reviewer, timestamp >= (approvalContextObservedAt ?? .distantPast) else { return }approvalReviewer = reviewerapprovalContextObservedAt = timestamp}}-struct CodexSubagentObservation {+struct SubagentObservation {let isRunning: Boollet timestamp: Date}diff --git a/CodexBar/Services/Activity/AppServerActivityModels.swift b/CodexBar/Services/Activity/AppServerActivityModels.swiftnew file mode 100644index 0000000..5fe251f--- /dev/null+++ b/CodexBar/Services/Activity/AppServerActivityModels.swift@@ -0,0 +1,255 @@+import Foundation++nonisolated struct ActivityThread: Decodable {+ let id: String+ var cwd: String?+ var model: String?+ var reasoningEffort: String?+ var status: ActivityThreadStatus?+ var source: ActivityThreadSource?+ var parentThreadId: String?+ var createdAt: Double?++ var origin: ActivityOrigin {+ source?.origin ?? .unknown+ }++ var parentID: String? {+ parentThreadId ?? source?.parentID+ }+}++nonisolated struct ActivityThreadStatus: Decodable {+ let type: String+ var activeFlags: [String]?+ var isWaiting: Bool {+ activeFlags?.contains("waitingOnApproval") == true+ }+}++nonisolated struct ActivityThreadSource: Decodable {+ let origin: ActivityOrigin+ let parentID: String?++ init(from decoder: Decoder) throws {+ let value = try ActivityJSONValue(from: decoder)+ if let name = value.string {+ origin = ["cli", "vscode", "exec", "appServer"].contains(name) ? .main : .unknown+ parentID = nil+ } else if let subagent = value["subAgent"] ?? value["subagent"] {+ let other = subagent["other"]?.string+ origin = other == "guardian" ? .autoReview : .auxiliary+ parentID = (subagent["thread_spawn"] ?? subagent["threadSpawn"])?["parent_thread_id"]?.string+ } else {+ origin = value["custom"] == nil ? .unknown : .main+ parentID = nil+ }+ }+}++/// 只在协议边界使用, 不将任意 JSON 正文写入日志或持久化+indirect nonisolated enum ActivityJSONValue: Decodable {+ case object([String: ActivityJSONValue])+ case array([ActivityJSONValue])+ case string(String)+ case number(Double)+ case bool(Bool)+ case null++ init(from decoder: Decoder) throws {+ let container = try decoder.singleValueContainer()+ if container.decodeNil() {+ self = .null+ } else if let value = try? container.decode(String.self) {+ self = .string(value)+ } else if let value = try? container.decode(Bool.self) {+ self = .bool(value)+ } else if let value = try? container.decode(Double.self) {+ self = .number(value)+ } else if let value = try? container.decode([String: Self].self) {+ self = .object(value)+ } else {+ self = try .array(container.decode([Self].self))+ }+ }++ subscript(_ key: String) -> Self? {+ if case let .object(object) = self {+ return object[key]+ }+ return nil+ }++ var string: String? {+ if case let .string(value) = self {+ return value+ }+ return nil+ }++ var number: Double? {+ if case let .number(value) = self {+ return value+ }+ return nil+ }++ var identifier: String? {+ if let string {+ return string+ }+ if let number {+ return String(number)+ }+ return nil+ }+}++nonisolated struct ActivityTurn: Decodable {+ let id: String+ let status: String+ var startedAt: Double?+ var completedAt: Double?+ var durationMs: Double?+}++nonisolated struct ActivityItem: Decodable {+ struct CommandAction: Decodable {+ let type: String+ }++ let id: String+ let type: String+ var status: String?+ var tool: String?+ var agentThreadId: String?+ var kind: String?+ var commandActions: [CommandAction]?++ var toolDisplayName: String? {+ guard type == "commandExecution" else { return tool }+ var seen: Set<String> = []+ let types = (commandActions ?? []).map(\.type).filter {+ !$0.isEmpty && $0 != "unknown" && seen.insert($0).inserted+ }+ return types.isEmpty ? nil : types.joined(separator: "/")+ }++ /// 调用类型决定是否计数, 具体工具名缺失不影响分类+ var isToolCall: Bool {+ Self.isToolType(type)+ }++ static func isToolType(_ type: String) -> Bool {+ switch type {+ case "commandExecution", "fileChange", "webSearch", "imageView", "imageGeneration", "sleep",+ "mcpToolCall", "dynamicToolCall", "collabAgentToolCall": true+ default: false+ }+ }+}++nonisolated struct ActivityTokenBreakdown: Decodable {+ let inputTokens: Int64+ let cachedInputTokens: Int64+ var cacheWriteInputTokens: Int64?+ let outputTokens: Int64+ let reasoningOutputTokens: Int64+ let totalTokens: Int64++ var usage: TokenUsage {+ TokenUsage(+ inputTokens: inputTokens, cachedInputTokens: cachedInputTokens, cacheWriteInputTokens: cacheWriteInputTokens ?? 0,+ outputTokens: outputTokens, reasoningOutputTokens: reasoningOutputTokens, totalTokens: totalTokens+ )+ }+}++nonisolated struct ActivityTokenUpdate: Decodable {+ let total: ActivityTokenBreakdown+ let last: ActivityTokenBreakdown+}++nonisolated struct ActivityNotification: Decodable {+ enum Category {+ case state+ case progress+ case ignored+ }++ /// 方法名称相似不代表协议含义相同, 采集和日志共用完整名称分类+ static func category(for method: String) -> Category {+ switch method {+ case "thread/started", "thread/status/changed", "thread/settings/updated", "thread/tokenUsage/updated",+ "turn/started", "turn/completed", "item/started", "item/completed", "item/autoApprovalReview/started",+ "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "item/permissions/requestApproval", "serverRequest/resolved":+ .state+ case "item/agentMessage/delta", "item/plan/delta", "item/reasoning/textDelta", "item/reasoning/summaryTextDelta",+ "item/commandExecution/outputDelta", "item/fileChange/outputDelta":+ .progress+ default:+ .ignored+ }+ }++ let id: ActivityJSONValue?+ let method: String+ let params: Params++ struct Params: Decodable {+ var threadId: String?+ var turnId: String?+ var itemId: String?+ var requestId: ActivityJSONValue?+ var targetItemId: String?+ var reviewId: String?+ var thread: ActivityThread?+ var turn: ActivityTurn?+ var item: ActivityItem?+ var status: ActivityThreadStatus?+ var threadSettings: Settings?+ var startedAtMs: Double?+ var completedAtMs: Double?+ var tokenUsage: ActivityTokenUpdate?+ }++ struct Settings: Decodable {+ var model: String?+ var effort: String?+ var cwd: String?+ var approvalsReviewer: ActivityApprovalReviewer?+ }+}++nonisolated struct ActivityThreadRead: Decodable { let thread: ActivityThread }+nonisolated struct ActivityLoadedPage: Decodable { let data: [String]+ var nextCursor: String?+}++nonisolated struct ActivityTurnsPage: Decodable { let data: [ActivityTurn]+ var nextCursor: String?+}++nonisolated struct ActivityThreadResume: Decodable {+ let thread: ActivityThread+ var model: String?+ var reasoningEffort: String?+ var approvalsReviewer: ActivityApprovalReviewer?+}++/// Codex 协议使用 snake_case, 本地持久化使用业务枚举本身的名称+nonisolated struct ActivityApprovalReviewer: Decodable {+ let value: ApprovalReviewer++ init(from decoder: Decoder) throws {+ let container = try decoder.singleValueContainer()+ let raw = try container.decode(String.self)+ switch raw {+ case "user": value = .user+ case "auto_review": value = .autoReview+ case "guardian_subagent": value = .guardianSubagent+ default:+ throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unknown approval reviewer")+ }+ }+}diff --git a/CodexBar/Services/Activity/AppServerActivityReader.swift b/CodexBar/Services/Activity/AppServerActivityReader.swiftnew file mode 100644index 0000000..06e132a--- /dev/null+++ b/CodexBar/Services/Activity/AppServerActivityReader.swift@@ -0,0 +1,560 @@+import Foundation+import os++nonisolated enum ActivityEventBatch {+ case bootstrapStart+ case bootstrapEvents([ActivityRecord])+ case bootstrapEnd+ case live([ActivityRecord])+ case sourceUnavailable+ case lifecycleChanged+}++nonisolated enum ActivityEventDrainResult: Sendable {+ case completed+ case sourceUnavailable+ case cancelled+}++/// actor 独占连接与解析状态, UI 仅消费归一化事件和有覆盖时限的生命周期快照+actor AppServerActivityReader {+ nonisolated static var defaultSocketURL: URL {+ CodexPaths.codexHomeDirectory().appendingPathComponent("app-server-control/app-server-control.sock")+ }++ private let lifecycleCache: SessionLifecycleCache+ private let onBatch: @MainActor @Sendable (ActivityEventBatch) -> Void+ private let socketURL: URL+ private let tokenHistory: TokenHistoryStore+ private let recorder: ActivityRecorder+ private var session: AppServerSession?+ private var reducer = AppServerActivityReducer()+ private var subscribed = Set<String>()+ private var loop: Task<Void, Never>?+ private var generation = 0+ private var connectedAt = Date.distantFuture+ private var reconciledAt = Date.distantPast+ private var persistedTokens: [TokenTurn] = []+ private var lastTokenRefresh = Date.distantPast+ private var isRunning = false+ private var isStopping = false+ private var stopWaiters: [CheckedContinuation<Void, Never>] = []+ private var stateChanged = false+ private var lastPublished = Date.distantPast+ private var isTokenWriter = false+ private var drainWaiters: [CheckedContinuation<ActivityEventDrainResult, Never>] = []+ private var pendingEvents: [ActivityRecord] = []+ private var pendingPublication: [ActivityRecord] = []+ private var pendingObservations: [TokenObservation] = []+ private var deferredNotifications: [ActivityNotification] = []+ private var verifiedThreads: [String: Date] = [:]+ private var checkedThreads: [String: Date] = [:]+ private var revisions: [String: Int] = [:]+ private var preparingThread: String?+ private var invalidThreads = Set<String>()+ private var storageRetryAfter = Date.distantPast+ private var storageFailed = false+ private var storagePaused = false+ private let maximumPendingEvents: Int+ private let maximumPendingBytes: Int++ init(+ lifecycleCache: SessionLifecycleCache,+ socketURL: URL = AppServerActivityReader.defaultSocketURL,+ tokenHistory: TokenHistoryStore = TokenHistoryStore(),+ recorder: ActivityRecorder = ActivityRecorder(),+ maximumPendingEvents: Int = 4096,+ maximumPendingBytes: Int = 8 * 1024 * 1024,+ onBatch: @escaping @MainActor @Sendable (ActivityEventBatch) -> Void+ ) {+ self.lifecycleCache = lifecycleCache+ self.socketURL = socketURL+ self.tokenHistory = tokenHistory+ self.recorder = recorder+ self.maximumPendingEvents = maximumPendingEvents+ self.maximumPendingBytes = maximumPendingBytes+ self.onBatch = onBatch+ }++ func start() {+ guard !isRunning, !isStopping else { return }+ isRunning = true+ generation += 1+ let current = generation+ loop = Task { [weak self] in await self?.run(generation: current) }+ }++ func stop() async {+ if isStopping {+ await withCheckedContinuation { stopWaiters.append($0) }+ return+ }+ isStopping = true+ defer {+ isStopping = false+ let waiters = stopWaiters+ stopWaiters.removeAll()+ for waiter in waiters {+ waiter.resume()+ }+ }+ isRunning = false+ generation += 1+ let previous = loop+ previous?.cancel()+ loop = nil+ session?.close()+ session = nil+ subscribed.removeAll()+ await previous?.value+ try? await persistPending()+ completeDrains(.cancelled)+ isTokenWriter = false+ await tokenHistory.releaseRecordingLease()+ await lifecycleCache.invalidate()+ }++ /// 每次调用执行本次请求之后的查询, 不复用正在进行的旧快照+ func drainNow() async -> ActivityEventDrainResult {+ guard isRunning, !Task.isCancelled else { return .cancelled }+ guard session != nil else { return .sourceUnavailable }+ return await withCheckedContinuation { drainWaiters.append($0) }+ }++ func findPromptStartTimes(for references: [ActivityPromptReference]) -> [ActivityPromptReference: Date] {+ var result: [ActivityPromptReference: Date] = [:]+ for reference in references {+ let key = ActivityTurnReference(threadID: reference.sessionID, turnID: reference.turnID, startedAt: Date())+ if let start = reducer.states[key]?.startedAt {+ result[reference] = start+ }+ }+ return result+ }++ private func run(generation current: Int) async {+ while isRunning, generation == current, !Task.isCancelled {+ do {+ if storagePaused {+ guard await retryStorage() else {+ try await Task.sleep(for: .milliseconds(100))+ continue+ }+ storagePaused = false+ }+ if session == nil {+ try await connect(generation: current)+ }+ try await acquireTokenWriter(generation: current)+ try await consumeAvailable(generation: current)+ if !drainWaiters.isEmpty || Date().timeIntervalSince(reconciledAt) >= 2 {+ let waiters = drainWaiters+ drainWaiters.removeAll()+ do {+ try await reconcile(bootstrap: false, forced: !waiters.isEmpty, generation: current)+ try await consumeAvailable(generation: current)+ let result: ActivityEventDrainResult = isRunning && generation == current && !Task.isCancelled ? .completed : .cancelled+ for waiter in waiters {+ waiter.resume(returning: result)+ }+ } catch {+ for waiter in waiters {+ waiter.resume(returning: .sourceUnavailable)+ }+ throw error+ }+ }+ try await Task.sleep(for: .milliseconds(100))+ } catch is CancellationError {+ completeDrains(.cancelled)+ return+ } catch {+ await recover(from: error, generation: current)+ try? await Task.sleep(for: .seconds(3))+ }+ }+ }++ private func connect(generation current: Int) async throws {+ // 存储未准备好时不创建连接, 避免本地故障触发重复初始化+ isTokenWriter = try await tokenHistory.acquireRecordingLease()+ try await persistPending()+ persistedTokens = try await tokenHistory.refresh()+ try checkGeneration(current)+ await onBatch(.bootstrapStart)+ try checkGeneration(current)+ let connection = try AppServerSession(socketURL: socketURL)+ do {+ try connection.initialize()+ } catch {+ connection.close()+ throw error+ }+ session = connection+ connectedAt = Date()+ reducer.reconnect()+ reducer.restoreTokenTurns(persistedTokens)+ try await reconcile(bootstrap: true, forced: true, generation: current)+ try checkGeneration(current)+ await onBatch(.bootstrapEnd)+ }++ private func acquireTokenWriter(generation current: Int) async throws {+ guard !isTokenWriter, Date() >= storageRetryAfter else { return }+ do {+ if try await tokenHistory.acquireRecordingLease() {+ try await persistPending()+ persistedTokens = try await tokenHistory.refresh()+ try checkGeneration(current)+ reducer.restoreTokenTurns(persistedTokens)+ isTokenWriter = true+ }+ } catch is CancellationError {+ throw CancellationError()+ } catch {+ recordStorageFailure(error)+ }+ }++ private func recover(from error: Error, generation current: Int) async {+ guard generation == current, isRunning else { return }+ let method = error is StorageBacklogFull || session == nil && !(error is CodexStatusError) ? "activity/storage" : "activity/connection"+ AppServerLogStore.shared.recordFailure(method: method, message: error.localizedDescription, connection: "activity")+ // 后续协议错误不能丢掉前面已取得的有效结果, 存储失败时保留队列供下一轮重试+ try? await flushPending(generation: current)+ guard generation == current, isRunning else { return }+ await disconnected()+ }++ private func completeDrains(_ result: ActivityEventDrainResult) {+ let pending = drainWaiters+ drainWaiters.removeAll()+ for waiter in pending {+ waiter.resume(returning: result)+ }+ }++ private func disconnected() async {+ completeDrains(.sourceUnavailable)+ session?.close()+ session = nil+ subscribed.removeAll()+ deferredNotifications.removeAll()+ verifiedThreads.removeAll()+ invalidThreads.removeAll()+ checkedThreads.removeAll()+ isTokenWriter = false+ await tokenHistory.releaseRecordingLease()+ await lifecycleCache.invalidate()+ await onBatch(.sourceUnavailable)+ }++ private func reconcile(bootstrap: Bool, forced: Bool, generation current: Int) async throws {+ var loaded = Set<String>()+ var cursor: String?+ repeat {+ var params: [String: Any] = ["limit": 100]+ if let cursor {+ params["cursor"] = cursor+ }+ let page: ActivityLoadedPage = try await request("thread/loaded/list", params: params, generation: current)+ loaded.formUnion(page.data)+ cursor = page.nextCursor+ } while cursor != nil && loaded.count < 10000+ let knownActive = Set(reducer.states.keys.filter {+ reducer.states[$0]?.terminal == nil && reducer.threads[$0.threadID]?.status?.type != "notLoaded"+ }.map(\.threadID))+ let now = Date()+ let candidates = loaded.union(knownActive).filter { id in+ let interval: TimeInterval = invalidThreads.contains(id) || knownActive.contains(id) || reducer.threads[id]?.status?.type == "active" ? 5 : 60+ return forced || now.timeIntervalSince(checkedThreads[id] ?? .distantPast) >= interval+ }.sorted { (checkedThreads[$0] ?? .distantPast, $0) < (checkedThreads[$1] ?? .distantPast, $1) }+ let deadline = ContinuousClock.now.advanced(by: .seconds(1))+ for id in candidates {+ try checkGeneration(current)+ try await reconcileThread(id, loaded: loaded, bootstrap: bootstrap, generation: current)+ // 日常对账分轮执行, 强制排空则等待本轮完整覆盖+ if !forced, ContinuousClock.now >= deadline {+ break+ }+ }+ subscribed.formIntersection(loaded)+ let retained = loaded.union(knownActive)+ checkedThreads = checkedThreads.filter { retained.contains($0.key) }+ revisions = revisions.filter { retained.contains($0.key) }+ verifiedThreads = verifiedThreads.filter { retained.contains($0.key) }+ invalidThreads.formIntersection(retained)+ reconciledAt = Date()+ await lifecycleCache.replace(reducer.states, verifiedThreads: verifiedThreads)+ try checkGeneration(current)+ if !bootstrap {+ await onBatch(.lifecycleChanged)+ }+ }++ private func reconcileThread(_ id: String, loaded: Set<String>, bootstrap: Bool, generation current: Int) async throws {+ let started = Date()+ let revision = revisions[id, default: 0]+ let newSubscription = !subscribed.contains(id)+ if newSubscription {+ preparingThread = id+ }+ defer { preparingThread = nil }+ do {+ let read: ActivityThreadRead = try await request("thread/read", params: ["threadId": id, "includeTurns": false], generation: current)+ var thread = read.thread+ var reviewer: ApprovalReviewer?+ if loaded.contains(id), newSubscription, thread.status?.type != "notLoaded" {+ let joined: ActivityThreadResume = try await request(+ "thread/resume", params: ["threadId": id, "excludeTurns": true], generation: current+ )+ thread = joined.thread+ thread.model = joined.model ?? thread.model+ thread.reasoningEffort = joined.reasoningEffort ?? thread.reasoningEffort+ reviewer = joined.approvalsReviewer?.value+ subscribed.insert(id)+ }+ if newSubscription {+ reducer.threads[id] = thread+ }+ let turns: ActivityTurnsPage = try await request(+ "thread/turns/list", params: ["threadId": id, "limit": 10, "itemsView": "summary"], generation: current+ )+ if newSubscription, turns.data.count <= 1, turns.data.allSatisfy({ $0.status == "inProgress" }),+ let created = thread.createdAt, created >= connectedAt.timeIntervalSince1970 {+ reducer.markNewThread(id)+ }+ // 查询期间收到的新状态优先, 不用旧响应倒退实时状态+ if revision == revisions[id, default: 0] {+ let events = reducer.reconcile(thread: thread, turns: turns.data, reviewer: reviewer, now: Date(), bootstrap: bootstrap || newSubscription)+ if !events.isEmpty {+ await onBatch(.bootstrapEvents(events))+ }+ }+ if !invalidThreads.contains(id) || revision == revisions[id, default: 0] {+ invalidThreads.remove(id)+ verifiedThreads[id] = started+ }+ preparingThread = nil+ consumeDeferred(for: id)+ if invalidThreads.contains(id) {+ reducer.invalidateThread(id)+ }+ try await flushPending(generation: current)+ } catch CodexStatusError.invalidResponsePayload {+ consumeDeferred(for: id)+ invalidateThread(id, method: "activity/thread", resetTokenBaseline: false)+ } catch let error as CodexStatusError where error.isMissingRollout(for: id)+ || (!error.isTransportFailure && !error.isProtocolOrParameterFailure) {+ reducer.invalidateThread(id)+ verifiedThreads[id] = nil+ subscribed.remove(id)+ consumeDeferred(for: id)+ } catch {+ consumeDeferred(for: id)+ throw error+ }+ checkedThreads[id] = started+ }++ private func consumeDeferred(for id: String) {+ guard reducer.threads[id] != nil else { return }+ let pending = deferredNotifications.filter { ($0.params.threadId ?? $0.params.thread?.id) == id }+ deferredNotifications.removeAll { ($0.params.threadId ?? $0.params.thread?.id) == id }+ for notification in pending {+ consume(notification)+ }+ }++ private func request<Response: Decodable>(_ method: String, params: [String: Any], generation current: Int) async throws -> Response {+ try checkGeneration(current)+ guard let connection = session else { throw CodexStatusError.serverConnectionClosed }+ let pending = try connection.beginRequest(method, params: params)+ var received = false+ do {+ while true {+ try checkGeneration(current)+ switch try connection.poll(pending) {+ case .waiting:+ try await Task.sleep(for: .milliseconds(10))+ case let .event(data):+ try consume(data)+ try await flushPending(generation: current, force: false)+ await Task.yield()+ case let .response(data):+ received = true+ return try AppServerRPC.decode(data, as: Response.self)+ }+ }+ } catch {+ if !received {+ connection.fail(pending, error: error)+ }+ throw error+ }+ }++ private func checkGeneration(_ current: Int) throws {+ try Task.checkCancellation()+ guard generation == current, isRunning else { throw CancellationError() }+ }++ private func consume(_ data: Data) throws {+ let method = try JSONDecoder().decode(MethodEnvelope.self, from: data).method+ guard ActivityNotification.category(for: method) != .ignored else { return }+ let notification: ActivityNotification+ do {+ notification = try JSONDecoder().decode(ActivityNotification.self, from: data)+ } catch is DecodingError {+ guard let envelope = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let params = envelope["params"] as? [String: Any],+ let threadID = params["threadId"] as? String ?? (params["thread"] as? [String: Any])?["id"] as? String,+ !threadID.isEmpty else { throw CodexStatusError.invalidServerResponse }+ // 用量或轮次边界缺失时不能把跨轮次消耗归到下一条通知+ invalidateThread(threadID, method: method, resetTokenBaseline: ["thread/tokenUsage/updated", "turn/started", "turn/completed"].contains(method))+ return+ }+ let id = notification.params.threadId ?? notification.params.thread?.id+ if let id, preparingThread == id || (reducer.threads[id] == nil && notification.params.thread == nil) {+ guard deferredNotifications.count < 4096 else { throw CodexStatusError.invalidServerResponse }+ deferredNotifications.append(notification)+ return+ }+ consume(notification)+ }++ private func consume(_ notification: ActivityNotification) {+ stateChanged = true+ if let id = notification.params.threadId ?? notification.params.thread?.id,+ ActivityNotification.category(for: notification.method) == .state {+ revisions[id, default: 0] += 1+ }+ let events = reducer.consume(notification, now: Date())+ pendingEvents += events+ pendingPublication += events+ if let id = notification.params.threadId ?? notification.params.thread?.id, invalidThreads.contains(id) {+ reducer.invalidateThread(id)+ }+ let observations = reducer.takeTokenObservations()+ if isTokenWriter {+ pendingObservations += observations+ }+ }++ private func consumeAvailable(generation current: Int) async throws {+ try await flushPending(generation: current)+ let deadline = ContinuousClock.now.advanced(by: .milliseconds(50))+ for _ in 0 ..< 256 {+ try checkGeneration(current)+ guard let data = try session?.nextEvent() else { break }+ try consume(data)+ try await flushPending(generation: current, force: false)+ if ContinuousClock.now >= deadline {+ break+ }+ }+ try await flushPending(generation: current)+ }++ private func persistPending() async throws {+ while let event = pendingEvents.first {+ try await recorder.record(event: event)+ pendingEvents.removeFirst()+ }+ if isTokenWriter, !pendingObservations.isEmpty || Date().timeIntervalSince(lastTokenRefresh) >= 1 {+ let batch = pendingObservations+ let committed = try await tokenHistory.recordObservations(batch)+ pendingObservations.removeFirst(batch.count)+ persistedTokens = committed+ reducer.acceptTokenTurns(committed)+ lastTokenRefresh = Date()+ }+ }++ private func flushPending(generation current: Int, force: Bool = true) async throws {+ try checkGeneration(current)+ guard stateChanged || !pendingEvents.isEmpty || !pendingObservations.isEmpty || !pendingPublication.isEmpty else { return }+ if !force, pendingEvents.isEmpty, pendingObservations.isEmpty, Date().timeIntervalSince(lastPublished) < 0.1 {+ return+ }+ _ = await retryStorage()+ try checkGeneration(current)+ await lifecycleCache.replace(reducer.states, verifiedThreads: verifiedThreads)+ try checkGeneration(current)+ stateChanged = false+ lastPublished = Date()+ let events = pendingPublication+ pendingPublication.removeAll()+ let visible = events.filter { event in+ guard [.subagentStarted, .subagentEnded].contains(event.eventKind),+ let agent = event.agentID, let turn = event.turnID else { return true }+ return reducer.states[ActivityTurnReference(threadID: agent, turnID: turn, startedAt: event.timestamp)] != nil+ }+ if !visible.isEmpty {+ await onBatch(.live(visible))+ }+ await onBatch(.lifecycleChanged)+ if storageFailed, try pendingStorageExceedsLimit() {+ storagePaused = true+ throw StorageBacklogFull()+ }+ }++ private func invalidateThread(_ id: String, method: String, resetTokenBaseline: Bool) {+ let firstFailure = invalidThreads.insert(id).inserted+ verifiedThreads[id] = nil+ revisions[id, default: 0] += 1+ stateChanged = true+ reducer.invalidateThread(id)+ if resetTokenBaseline {+ reducer.invalidateTokenBaseline(id)+ }+ if firstFailure {+ AppServerLogStore.shared.recordFailure(method: method, message: "Invalid payload for thread \(id)", connection: "activity")+ }+ }++ private func retryStorage() async -> Bool {+ guard Date() >= storageRetryAfter else { return false }+ do {+ try await persistPending()+ storageFailed = false+ storageRetryAfter = .distantPast+ return true+ } catch {+ recordStorageFailure(error)+ return false+ }+ }++ private func recordStorageFailure(_ error: Error) {+ if !storageFailed {+ AppServerLogStore.shared.recordFailure(method: "activity/storage", message: error.localizedDescription, connection: "activity")+ }+ storageFailed = true+ storageRetryAfter = Date().addingTimeInterval(1)+ }++ private func pendingStorageExceedsLimit() throws -> Bool {+ if pendingEvents.count + pendingObservations.count >= maximumPendingEvents {+ return true+ }+ var bytes = 0+ for event in pendingEvents {+ bytes += try AppServerEventRecord(activity: event).jsonLineData().count+ if bytes >= maximumPendingBytes {+ return true+ }+ }+ bytes += try JSONLines.stableEncoder.encode(pendingObservations).count+ return bytes >= maximumPendingBytes+ }++ private struct StorageBacklogFull: LocalizedError {+ var errorDescription: String? {+ "Activity persistence buffer is full; collection is paused until pending data is saved"+ }+ }++ private struct MethodEnvelope: Decodable { let method: String }+}diff --git a/CodexBar/Services/Activity/AppServerActivityReducer.swift b/CodexBar/Services/Activity/AppServerActivityReducer.swiftnew file mode 100644index 0000000..18172f0--- /dev/null+++ b/CodexBar/Services/Activity/AppServerActivityReducer.swift@@ -0,0 +1,442 @@+import Foundation++/// 将协议事件映射为既有业务阶段, 快照对账与实时统计分别处理+nonisolated struct AppServerActivityReducer {+ var threads: [String: ActivityThread] = [:]+ var states: [ActivityTurnReference: SessionLifecycleState] = [:]+ private var childRoots: [String: (session: String, turn: String)] = [:]+ private var threadTotals: [String: TokenUsage] = [:]+ private var tokenStreamID = UUID().uuidString.lowercased()+ private var tokenSequences: [String: Int64] = [:]+ private(set) var tokenObservations: [TokenObservation] = []+ private var seenEvents: [String: Date] = [:]+ private var approvals: [String: ActivityTurnReference] = [:]+ private var waitingSince: [String: Date] = [:]+ private var toolItems: [String: (item: ActivityItem, at: Date)] = [:]+ private var observingSince = Date.distantPast+ private(set) var tokenTurns: [TokenTurn] = []++ mutating func reconnect(now: Date = Date()) {+ // 断线期间的累计变化没有完整轮次归属, 重新建立基线, 不归入重连后的轮次+ threadTotals.removeAll()+ tokenStreamID = UUID().uuidString.lowercased()+ tokenSequences.removeAll()+ approvals.removeAll()+ waitingSince.removeAll()+ observingSince = now+ }++ mutating func invalidateThread(_ id: String) {+ threads[id]?.status = ActivityThreadStatus(type: "notLoaded")+ for key in states.keys where key.threadID == id && states[key]?.terminal == nil {+ states[key]?.readStatus = .unavailable+ }+ }++ mutating func invalidateTokenBaseline(_ id: String) {+ threadTotals.removeValue(forKey: id)+ }++ mutating func markNewThread(_ id: String) {+ if threadTotals[id] == nil {+ threadTotals[id] = .zero+ }+ }++ mutating func takeTokenObservations() -> [TokenObservation] {+ defer { tokenObservations.removeAll(keepingCapacity: true) }+ return tokenObservations+ }++ mutating func acceptTokenTurns(_ turns: [TokenTurn]) {+ tokenTurns = turns+ let records = Dictionary(uniqueKeysWithValues: turns.map { ($0.id, $0) })+ for key in states.keys {+ states[key]?.tokenUsage = records[TokenTurn.identifier(thread: key.threadID, turn: key.turnID)]?.usage+ }+ }++ mutating func restoreTokenTurns(_ turns: [TokenTurn]) {+ tokenTurns = turns+ threadTotals.removeAll()+ let records = Dictionary(uniqueKeysWithValues: turns.map { ($0.id, $0) })+ for key in states.keys {+ states[key]?.tokenUsage = records[TokenTurn.identifier(thread: key.threadID, turn: key.turnID)]?.usage+ }+ }++ mutating func reconcile(thread: ActivityThread, turns: [ActivityTurn], reviewer: ApprovalReviewer?, now: Date, bootstrap: Bool = false) -> [ActivityRecord] {+ var thread = thread+ // thread/read 不返回完整配置, 保留 resume 和 settings 通知提供的模型上下文+ thread.model = thread.model ?? threads[thread.id]?.model+ thread.reasoningEffort = thread.reasoningEffort ?? threads[thread.id]?.reasoningEffort+ threads[thread.id] = thread+ var events: [ActivityRecord] = []+ for turn in turns {+ let reference = reference(thread.id, turn.id, at: turn.startedAt.map(Date.init(timeIntervalSince1970:)) ?? now)+ let existed = states[reference] != nil+ updateTurn(turn, threadID: thread.id, reviewer: reviewer, now: now, historical: true)+ if !existed || bootstrap, turn.status == "inProgress", thread.status?.type == "active" {+ events.append(event(.turnStarted, threadID: thread.id, turnID: turn.id, at: reference.startedAt))+ }+ }+ updateWaiting(threadID: thread.id, status: thread.status, now: now)+ resolveRoots()+ return events+ }++ mutating func consume(_ notification: ActivityNotification, now: Date) -> [ActivityRecord] {+ let category = ActivityNotification.category(for: notification.method)+ guard category != .ignored else { return [] }+ let params = notification.params+ guard let threadID = params.threadId ?? params.thread?.id else { return [] }+ let wasKnown = threads[threadID] != nil+ if let thread = params.thread {+ threads[threadID] = thread+ }+ guard threads[threadID] != nil else { return [] }+ let date = (params.completedAtMs ?? params.startedAtMs).map { Date(timeIntervalSince1970: $0 / 1000) } ?? now+ let turnID = params.turnId ?? params.turn?.id ?? activeReference(threadID)?.turnID+ var events: [ActivityRecord] = []+ switch notification.method {+ case "thread/started":+ if !wasKnown, let created = params.thread?.createdAt, created >= floor(observingSince.timeIntervalSince1970) {+ markNewThread(threadID)+ }+ case "thread/settings/updated":+ updateSettings(params.threadSettings, threadID: threadID, now: now)+ case "thread/status/changed":+ threads[threadID]?.status = params.status+ updateWaiting(threadID: threadID, status: params.status, now: now)+ case "turn/started", "turn/completed":+ guard let turn = params.turn, ["inProgress", "completed", "failed", "interrupted"].contains(turn.status) else { break }+ events.append(turnEvent(turn, threadID: threadID, now: now))+ case "item/started", "item/completed":+ if let turnID, let item = params.item {+ events += itemEvents(item, method: notification.method, threadID: threadID, turnID: turnID, at: date)+ }+ case "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "item/permissions/requestApproval":+ guard let turnID else { break }+ let reference = reference(threadID, turnID, at: date)+ if let id = notification.id?.identifier {+ approvals[id] = reference+ }+ events.append(event(+ .approvalRequested,+ threadID: threadID,+ turnID: turnID,+ at: date,+ item: approvalItem(params.itemId, threadID: threadID, turnID: turnID, method: notification.method),+ identity: params.itemId ?? notification.id?.identifier,+ reviewer: .user+ ))+ states[reference]?.isWaitingApproval = true+ states[reference]?.approvalChangedAt = waitingSince[threadID] ?? date+ case "item/autoApprovalReview/started":+ guard let turnID else { break }+ events.append(event(+ .approvalRequested,+ threadID: threadID,+ turnID: turnID,+ at: date,+ identity: params.targetItemId ?? params.reviewId,+ reviewer: .autoReview+ ))+ case "serverRequest/resolved":+ if let id = params.requestId?.identifier, let reference = approvals.removeValue(forKey: id),+ !approvals.values.contains(reference) {+ states[reference]?.isWaitingApproval = false+ states[reference]?.approvalChangedAt = now+ }+ case "thread/tokenUsage/updated":+ if let turnID, let usage = params.tokenUsage {+ updateUsage(threadID: threadID, turnID: turnID, update: usage, now: now)+ }+ default:+ if category == .progress, let turnID {+ progress(threadID, turnID, at: now)+ }+ }+ resolveRoots()+ prune(now: now)+ return finish(events, notification: notification, threadID: threadID, turnID: turnID, now: now)+ }++ private mutating func finish(+ _ events: [ActivityRecord], notification: ActivityNotification,+ threadID: String, turnID: String?, now: Date+ ) -> [ActivityRecord] {+ let source = source(notification, threadID: threadID, turnID: turnID)+ return events.map { value in+ var value = value+ value.source = source+ return value+ }.filter { value in+ guard let id = value.id else { return false }+ guard seenEvents[id] == nil else { return false }+ seenEvents[id] = now+ return true+ }+ }++ private func source(_ notification: ActivityNotification, threadID: String, turnID: String?) -> AppServerEventSource {+ let params = notification.params+ let state = turnID.flatMap { states[reference(threadID, $0, at: .distantPast)] }+ let item = params.item ?? turnID.flatMap {+ approvalItem(params.itemId, threadID: threadID, turnID: $0, method: notification.method)+ }+ return AppServerEventSource(+ method: notification.method, threadID: threadID, turnID: turnID,+ parentThreadID: threads[threadID]?.parentID,+ rootThreadID: state?.rootSessionID, rootTurnID: state?.rootTurnID,+ itemID: params.item?.id ?? params.itemId ?? params.targetItemId,+ itemType: item?.type, itemStatus: params.item?.status,+ agentThreadID: params.item?.agentThreadId, itemKind: params.item?.kind,+ requestID: notification.id?.identifier ?? params.requestId?.identifier,+ reviewID: params.reviewId, turnStatus: params.turn?.status,+ turnStartedAt: params.turn?.startedAt.map(Date.init(timeIntervalSince1970:)),+ turnCompletedAt: params.turn?.completedAt.map(Date.init(timeIntervalSince1970:)),+ durationMs: params.turn?.durationMs+ )+ }++ private mutating func turnEvent(_ turn: ActivityTurn, threadID: String, now: Date) -> ActivityRecord {+ updateTurn(turn, threadID: threadID, reviewer: nil, now: now, historical: false)+ if turn.status != "inProgress", threadTotals[threadID] == .zero {+ // 未观察到本轮用量就已结束, 零基线不能把漏掉的消耗算到下一轮+ threadTotals.removeValue(forKey: threadID)+ }+ let phase: ActivityEventKind = turn.status == "inProgress" ? .turnStarted : turn.status == "completed" ? .turnCompleted : .turnAborted+ let timestamp = (turn.status == "inProgress" ? turn.startedAt : turn.completedAt).map(Date.init(timeIntervalSince1970:)) ?? now+ return event(phase, threadID: threadID, turnID: turn.id, at: timestamp)+ }++ private mutating func prune(now: Date) {+ let retainedDate = HistoryStorage.retentionCutoffDate(today: now)+ let retainedRoots = Set(tokenTurns.filter { $0.updatedAt >= retainedDate }.map(\.rootID))+ tokenTurns = tokenTurns.filter { $0.updatedAt >= retainedDate || retainedRoots.contains($0.id) }+ let cutoff = now.addingTimeInterval(-ActivityRetention.window)+ seenEvents = seenEvents.filter { $0.value > cutoff }+ toolItems = toolItems.filter { $0.value.at > cutoff }+ states = states.filter { $0.value.terminal == nil || ($0.value.lastProgressAt ?? .distantPast) > cutoff }+ }++ private mutating func updateSettings(_ settings: ActivityNotification.Settings?, threadID: String, now: Date) {+ if let settings, var thread = threads[threadID] {+ thread.model = settings.model ?? thread.model+ thread.reasoningEffort = settings.effort+ thread.cwd = settings.cwd ?? thread.cwd+ threads[threadID] = thread+ for key in states.keys where key.threadID == threadID && states[key]?.terminal == nil {+ states[key]?.effort = settings.effort+ if let reviewer = settings.approvalsReviewer?.value {+ states[key]?.approvalReviewer = reviewer+ }+ states[key]?.contextObservedAt = now+ }+ }+ }++ private mutating func itemEvents(_ item: ActivityItem, method: String, threadID: String, turnID: String, at date: Date) -> [ActivityRecord] {+ var events: [ActivityRecord] = []+ progress(threadID, turnID, at: date)+ let starting = method == "item/started"+ if item.isToolCall {+ toolItems["\(threadID):\(turnID):\(item.id)"] = (item, date)+ events.append(event(starting ? .toolStarted : .toolCompleted, threadID: threadID, turnID: turnID, at: date, item: item))+ } else if item.type == "contextCompaction" {+ events.append(event(starting ? .compactionStarted : .compactionCompleted, threadID: threadID, turnID: turnID, at: date, item: item))+ } else if !starting, item.type == "subAgentActivity", ["started", "completed", "interrupted"].contains(item.kind ?? "") {+ // interacted 只是活动, 不代表创建或结束子 Agent+ events.append(event(+ item.kind == "started" ? .subagentStarted : .subagentEnded,+ threadID: threadID,+ turnID: turnID,+ at: date,+ item: item+ ))+ }+ return events+ }++ private func approvalItem(_ id: String?, threadID: String, turnID: String, method: String) -> ActivityItem? {+ guard let id else { return nil }+ if let known = toolItems["\(threadID):\(turnID):\(id)"] {+ return known.item+ }+ if method == "item/commandExecution/requestApproval" {+ return ActivityItem(id: id, type: "commandExecution")+ }+ if method == "item/fileChange/requestApproval" {+ return ActivityItem(id: id, type: "fileChange")+ }+ return nil+ }++ private mutating func updateTurn(_ turn: ActivityTurn, threadID: String, reviewer: ApprovalReviewer?, now: Date, historical: Bool) {+ let start = turn.startedAt.map(Date.init(timeIntervalSince1970:))+ let reference = reference(threadID, turn.id, at: start ?? now)+ let previous = states[reference]+ let terminal: SessionTerminalState?+ let isTerminal = ["completed", "failed", "interrupted"].contains(turn.status)+ let isLoaded = ["active", "idle"].contains(threads[threadID]?.status?.type ?? "")+ if isTerminal, turn.completedAt != nil || !historical || isLoaded {+ let date = turn.completedAt.map(Date.init(timeIntervalSince1970:))+ if turn.status == "completed" {+ var reportedAt = date+ var duration = turn.durationMs.map { $0 / 1000 }+ if case let .completed(previousAt, previousDuration) = previous?.terminal {+ reportedAt = reportedAt ?? previousAt+ duration = duration ?? previousDuration+ }+ terminal = .completed(at: reportedAt, duration: duration)+ } else if case let .aborted(previousAt) = previous?.terminal {+ terminal = .aborted(at: date ?? previousAt)+ } else {+ terminal = .aborted(at: date)+ }+ } else {+ terminal = previous?.terminal+ }+ var state = SessionLifecycleState(+ requestedThreadID: threadID, turnID: turn.id, startedAt: start,+ approvalReviewer: reviewer ?? previous?.approvalReviewer,+ effort: threads[threadID]?.reasoningEffort, lastProgressAt: previous?.lastProgressAt ?? start,+ terminal: terminal, readStatus: terminal == nil && (!isLoaded || turn.status != "inProgress") ? .unavailable : .complete,+ hasContext: true, contextObservedAt: now, rootTurnID: previous?.rootTurnID,+ recordedThreadID: threadID, rootSessionID: previous?.rootSessionID,+ parentThreadID: threads[threadID]?.parentID,+ lastExecutionProgressAt: previous?.lastExecutionProgressAt,+ tokenUsage: previous?.tokenUsage ?? tokenTurns.first(where: { $0.id == TokenTurn.identifier(thread: threadID, turn: turn.id) })?.usage,+ isHistoricalTerminal: previous?.terminal == nil ? historical : previous?.isHistoricalTerminal ?? historical,+ isWaitingApproval: previous?.isWaitingApproval, approvalChangedAt: previous?.approvalChangedAt+ )+ if terminal != nil {+ state.terminalObservedAt = previous?.terminalObservedAt ?? now+ state.lastProgressAt = turn.completedAt.map(Date.init(timeIntervalSince1970:)) ?? state.terminalObservedAt+ }+ states[reference] = state+ }++ private mutating func updateWaiting(threadID: String, status: ActivityThreadStatus?, now: Date) {+ guard let status, status.type == "active" || status.type == "idle" else { return }+ if status.isWaiting, waitingSince[threadID] == nil {+ waitingSince[threadID] = now+ }+ for key in states.keys where key.threadID == threadID && states[key]?.terminal == nil {+ if states[key]?.isWaitingApproval != status.isWaiting {+ states[key]?.approvalChangedAt = waitingSince[threadID] ?? now+ }+ states[key]?.isWaitingApproval = status.isWaiting+ }+ if !status.isWaiting {+ waitingSince.removeValue(forKey: threadID)+ }+ }++ private mutating func progress(_ threadID: String, _ turnID: String, at date: Date) {+ let key = reference(threadID, turnID, at: date)+ let lastProgress = states[key]?.lastProgressAt ?? .distantPast+ states[key]?.lastProgressAt = max(lastProgress, date)+ // 输出增量是执行进展, 但等待中的其他并发请求仍由服务端状态裁决+ states[key]?.lastExecutionProgressAt = date+ }++ private mutating func resolveRoots() {+ for _ in 0 ..< 16 {+ var changed = false+ for key in states.keys {+ guard var state = states[key], state.rootTurnID == nil else { continue }+ if let parent = threads[key.threadID]?.parentID {+ if let root = childRoots[key.threadID] {+ state.rootTurnID = root.turn+ state.rootSessionID = root.session+ states[key] = state+ changed = true+ continue+ }+ guard let start = threads[key.threadID]?.createdAt.map(Date.init(timeIntervalSince1970:)) ?? state.startedAt,+ let ancestor = states.values.filter({+ $0.requestedThreadID == parent && ($0.startedAt ?? .distantFuture) <= start+ }).max(by: { ($0.startedAt ?? .distantPast) < ($1.startedAt ?? .distantPast) }),+ let rootTurn = ancestor.rootTurnID, let rootSession = ancestor.rootSessionID else { continue }+ state.rootTurnID = rootTurn+ state.rootSessionID = rootSession+ childRoots[key.threadID] = (rootSession, rootTurn)+ } else if threads[key.threadID]?.origin == .main || threads[key.threadID]?.origin == .autoReview {+ state.rootTurnID = key.turnID+ state.rootSessionID = key.threadID+ } else {+ continue+ }+ states[key] = state+ changed = true+ }+ if !changed {+ break+ }+ }+ }++ private func reference(_ threadID: String, _ turnID: String, at date: Date) -> ActivityTurnReference {+ ActivityTurnReference(threadID: threadID, turnID: turnID, startedAt: date)+ }++ private func activeReference(_ threadID: String) -> ActivityTurnReference? {+ states.keys.filter { $0.threadID == threadID && states[$0]?.terminal == nil }.max { $0.startedAt < $1.startedAt }+ }++ private func event(+ _ phase: ActivityEventKind, threadID: String, turnID: String, at date: Date,+ item: ActivityItem? = nil, identity: String? = nil, reviewer: ApprovalReviewer? = nil+ ) -> ActivityRecord {+ let thread = threads[threadID]+ let state = states[reference(threadID, turnID, at: date)]+ let isChild = thread?.parentID != nil+ let agentID = item?.agentThreadId ?? (isChild ? threadID : nil)+ let eventTurn = item?.agentThreadId.flatMap { activeReference($0)?.turnID } ?? turnID+ return ActivityRecord(+ timestamp: date, name: phase.rawValue, origin: thread?.origin ?? .unknown,+ cwd: thread?.cwd, tool: item?.toolDisplayName, model: thread?.model,+ effort: thread?.reasoningEffort, approvalReviewer: reviewer ?? state?.approvalReviewer,+ sessionID: isChild ? state?.rootSessionID : threadID, turnID: eventTurn, agentID: agentID,+ id: [threadID, turnID, item?.id ?? identity ?? "turn", phase.rawValue].joined(separator: ":")+ )+ }++ private mutating func updateUsage(threadID: String, turnID: String, update: ActivityTokenUpdate, now: Date) {+ let total = update.total.usage+ guard total.isValid else { return }+ defer { threadTotals[threadID] = total }+ guard let previous = threadTotals[threadID], let delta = total.subtracting(previous), delta != .zero else { return }+ let key = reference(threadID, turnID, at: now)+ guard let state = states[key], let rootSession = state.rootSessionID, let rootTurn = state.rootTurnID else { return }+ let id = TokenTurn.identifier(thread: threadID, turn: turnID)+ let existing = tokenTurns.first { $0.id == id }+ let sequence = (tokenSequences[id] ?? 0) + 1+ tokenSequences[id] = sequence+ let rootKey = reference(rootSession, rootTurn, at: now)+ let metadata = TokenTurn(+ id: id,+ rootID: TokenTurn.identifier(thread: rootSession, turn: rootTurn),+ startedAt: state.startedAt,+ updatedAt: now+ )+ let observation = TokenObservation(+ turn: metadata,+ rootStartedAt: states[rootKey]?.startedAt,+ streamID: tokenStreamID,+ sequence: sequence,+ previous: previous,+ current: total+ )+ tokenObservations.append(observation)+ guard let record = try? observation.applying(to: existing) else { return }+ states[key]?.tokenUsage = record.usage+ tokenTurns.removeAll { $0.id == id }+ tokenTurns.append(record)+ if record.rootID != id, !tokenTurns.contains(where: { $0.id == record.rootID }), let root = states[rootKey] {+ tokenTurns.append(TokenTurn(id: record.rootID, rootID: record.rootID, startedAt: root.startedAt, updatedAt: now, usage: nil))+ }+ }+}diff --git a/CodexBar/Services/Workflow/ActivityProtectionStateStore.swift b/CodexBar/Services/Activity/ProtectionStore.swiftsimilarity index 75%rename from CodexBar/Services/Workflow/ActivityProtectionStateStore.swiftrename to CodexBar/Services/Activity/ProtectionStore.swiftindex 6f87b17..abe2fe1 100644--- a/CodexBar/Services/Workflow/ActivityProtectionStateStore.swift+++ b/CodexBar/Services/Activity/ProtectionStore.swift@@ -2,14 +2,14 @@ import Darwinimport Foundationimport os-nonisolated struct ActivityProtectionRecord: Codable, Equatable, Sendable {+nonisolated struct ProtectionRecord: Codable, Equatable, Sendable {let taskIdentifier: Stringlet lastProgressAt: Datelet markedAt: Datelet expiresAt: Date}-nonisolated struct ActivityProtectionRemoval: Sendable {+nonisolated struct ProtectionRemoval: Sendable {let taskIdentifier: Stringlet matchingMarkedAt: Date?@@ -19,8 +19,8 @@ nonisolated struct ActivityProtectionRemoval: Sendable {}}-/// 异常任务标记的本地存储, actor 隔离进程内访问, flock 保护 Debug 和 Release 共用文件-actor ActivityProtectionStateStore {+/// 异常任务标记的本地存储, actor 隔离进程内访问, flock 保护同一构建的多进程访问+actor ProtectionStore {private let directoryURL: URLprivate let stateURL: URLprivate let lockURL: URL@@ -28,20 +28,13 @@ actor ActivityProtectionStateStore {init(directoryURL: URL? = nil, fileManager: FileManager = .default) {self.fileManager = fileManager- let applicationSupportURL = fileManager.urls(- for: .applicationSupportDirectory,- in: .userDomainMask- ).first ?? URL(fileURLWithPath: NSHomeDirectory())- .appendingPathComponent("Library", isDirectory: true)- .appendingPathComponent("Application Support", isDirectory: true)- self.directoryURL = directoryURL ?? applicationSupportURL- .appendingPathComponent("CodexBar", isDirectory: true)- .appendingPathComponent("ActivityProtection", isDirectory: true)+ self.directoryURL = directoryURL ?? AppStorage.directoryURL(fileManager: fileManager)+ .appendingPathComponent("Protection", isDirectory: true)stateURL = self.directoryURL.appendingPathComponent("state.json", isDirectory: false)lockURL = self.directoryURL.appendingPathComponent("state.lock", isDirectory: false)}- func load(now: Date = Date()) -> [String: ActivityProtectionRecord] {+ func load(now: Date = Date()) -> [String: ProtectionRecord] {do {return try withExclusiveLock {var records = loadRecordsWithoutLock()@@ -61,8 +54,8 @@ actor ActivityProtectionStateStore {}func apply(- upserts: [ActivityProtectionRecord] = [],- removals: [ActivityProtectionRemoval] = [],+ upserts: [ProtectionRecord] = [],+ removals: [ProtectionRemoval] = [],now: Date = Date()) throws {try withExclusiveLock {@@ -130,13 +123,13 @@ actor ActivityProtectionStateStore {private static let lockTimeout: TimeInterval = 2private static let lockRetryMicroseconds: useconds_t = 50000- private func loadRecordsWithoutLock() -> [String: ActivityProtectionRecord] {+ private func loadRecordsWithoutLock() -> [String: ProtectionRecord] {guard fileManager.fileExists(atPath: stateURL.path) else {return [:]}guard let data = try? Data(contentsOf: stateURL), !data.isEmpty,- let state = try? JSONDecoder().decode(ActivityProtectionState.self, from: data),- state.schemaVersion == ActivityProtectionState.currentSchemaVersion else {+ let state = try? JSONDecoder().decode(ProtectionState.self, from: data),+ state.version == ProtectionState.currentVersion else {AppLog.activity.error("异常任务状态已忽略: reason=invalidState")return [:]}@@ -150,10 +143,10 @@ actor ActivityProtectionStateStore {}private func saveRecordsWithoutLock(- _ records: [String: ActivityProtectionRecord]+ _ records: [String: ProtectionRecord]) throws {- let state = ActivityProtectionState(- schemaVersion: ActivityProtectionState.currentSchemaVersion,+ let state = ProtectionState(+ version: ProtectionState.currentVersion,records: records.values.sorted {$0.taskIdentifier < $1.taskIdentifier}@@ -166,9 +159,9 @@ actor ActivityProtectionStateStore {}}-private nonisolated struct ActivityProtectionState: Codable {- static let currentSchemaVersion = 1+private nonisolated struct ProtectionState: Codable {+ static let currentVersion = 1- let schemaVersion: Int- let records: [ActivityProtectionRecord]+ let version: Int+ let records: [ProtectionRecord]}diff --git a/CodexBar/Services/Activity/SessionLifecycleCache.swift b/CodexBar/Services/Activity/SessionLifecycleCache.swiftnew file mode 100644index 0000000..766c9c4--- /dev/null+++ b/CodexBar/Services/Activity/SessionLifecycleCache.swift@@ -0,0 +1,105 @@+import Foundation++nonisolated struct ActivityTurnReference: Hashable {+ let threadID: String+ let turnID: String+ let startedAt: Date+ var isTerminalUsageOnly = false++ static func == (lhs: Self, rhs: Self) -> Bool {+ lhs.threadID == rhs.threadID && lhs.turnID == rhs.turnID+ }++ func hash(into hasher: inout Hasher) {+ hasher.combine(threadID)+ hasher.combine(turnID)+ }+}++/// 运行状态按线程验证有效期, 已确认终态不随连接或刷新期限失效+actor SessionLifecycleCache {+ private var states: [ActivityTurnReference: SessionLifecycleState] = [:]+ private var verifiedThreads: [String: Date] = [:]++ func replace(_ states: [ActivityTurnReference: SessionLifecycleState], verifiedThreads: [String: Date]) {+ self.states = states+ self.verifiedThreads = verifiedThreads+ }++ func invalidate() {+ verifiedThreads.removeAll()+ }++ func lifecycleStates(for references: [ActivityTurnReference], now: Date = Date()) -> [SessionLifecycleState] {+ let requested = Set(references)+ let childReferences = states.keys.filter { reference in+ guard let state = states[reference], state.parentThreadID != nil,+ let root = state.rootSessionID, let turn = state.rootTurnID else { return false }+ return requested.contains(ActivityTurnReference(threadID: root, turnID: turn, startedAt: now))+ }+ var result = Array(requested.union(childReferences)).map { reference in+ var state = states[reference] ?? SessionLifecycleState(+ requestedThreadID: reference.threadID, turnID: reference.turnID, startedAt: nil,+ approvalReviewer: nil, effort: nil, lastProgressAt: nil, terminal: nil, readStatus: .notFound+ )+ let verified = verifiedThreads[reference.threadID] ?? .distantPast+ // 已确认终态是事实, 不依赖运行状态的刷新期限+ if state.terminal == nil, now.timeIntervalSince(verified) > 15 {+ state.readStatus = .unavailable+ }+ return state+ }+ var changed = true+ while changed {+ changed = false+ for child in result where child.terminal == nil && child.readStatus != .complete {+ guard let root = child.rootSessionID, let turn = child.rootTurnID else { continue }+ for index in result.indices {+ let parent = result[index]+ let isRoot = parent.requestedThreadID == root && parent.turnID == turn+ let isAncestor = parent.requestedThreadID == child.parentThreadID+ && parent.rootSessionID == root && parent.rootTurnID == turn+ if isRoot || isAncestor, parent.terminal == nil, parent.readStatus == .complete {+ result[index].readStatus = .unavailable+ changed = true+ }+ }+ }+ }+ return result+ }+}++nonisolated struct SessionLifecycleState {+ let requestedThreadID: String+ let turnID: String+ let startedAt: Date?+ var approvalReviewer: ApprovalReviewer?+ var effort: String?+ var lastProgressAt: Date?+ let terminal: SessionTerminalState?+ var readStatus: SessionReadStatus = .complete+ var hasContext = false+ var contextObservedAt: Date?+ var rootTurnID: String?+ var recordedThreadID: String?+ var rootSessionID: String?+ var parentThreadID: String?+ var lastExecutionProgressAt: Date?+ var tokenUsage: TokenUsage?+ var isHistoricalTerminal = false+ var isWaitingApproval: Bool?+ var approvalChangedAt: Date?+ var terminalObservedAt: Date?+}++nonisolated enum SessionReadStatus {+ case complete+ case unavailable+ case notFound+}++nonisolated enum SessionTerminalState {+ case completed(at: Date?, duration: TimeInterval?)+ case aborted(at: Date?)+}diff --git a/CodexBar/Services/AppServer/AccountSession.swift b/CodexBar/Services/AppServer/AccountSession.swiftnew file mode 100644index 0000000..c195682--- /dev/null+++ b/CodexBar/Services/AppServer/AccountSession.swift@@ -0,0 +1,140 @@+import Foundation+import os++/// 账户连接负责业务解码与重试, 传输和请求日志复用共享 WebSocket+final nonisolated class AccountSession {+ private typealias EncodedMessage = (data: Data, text: String)+ private let transport: AppServerSession+ private let timeout: TimeInterval+ private let logStorage: AppServerLogStore?+ private var nextID = 1+ private var unsupportedMethods: Set<String> = []++ var isOpen: Bool {+ transport.isOpen+ }++ init(socketURL: URL, timeout: TimeInterval = 20, logStorage: AppServerLogStore? = .shared) throws {+ transport = try AppServerSession(socketURL: socketURL, retainsNotifications: false, logStorage: logStorage, connectionName: "account")+ self.timeout = timeout+ self.logStorage = logStorage+ }++ func initializeAccount() throws -> (version: String, account: AccountReadResponse) {+ let result = try request(+ "initialize",+ params: ["clientInfo": [+ "name": "codex_bar",+ "title": "Codex Bar",+ "version": Self.clientVersion()+ ], "capabilities": ["experimentalApi": true]],+ as: InitializeResult.self+ )+ let version = Self.serverVersion(fromUserAgent: result.userAgent)+ let minimum = CodexMinimumVersion.global+ // 版本未知不能作为明确的低版本结论+ guard let version, let isSupported = CodexVersionReader.isVersion(version, atLeast: minimum) else {+ throw CodexStatusError.invalidServerResponse+ }+ guard isSupported else {+ let error = CodexStatusError.unsupportedVersion(minimum: minimum)+ if let logStorage {+ let details = LogFields.joined("current=\(version)", "minimum=\(minimum)")+ AppLog.codex.notice("Codex 版本不支持: \(details, privacy: .public)")+ logStorage.recordFailure(message: error.localizedDescription)+ }+ throw error+ }+ try notify("initialized")+ let account = try request("account/read", params: ["refreshToken": false], as: AccountReadResponse.self)+ guard account.account != nil else { throw CodexStatusError.notLoggedIn }+ return (version, account)+ }++ private static func clientVersion() -> String {+ guard let version = Bundle.main.shortVersionString, !version.isEmpty else { return "1.0.0" }+ return version+ }++ /// userAgent 首个 token 中 "/" 之后的部分才是实际运行版本+ private static func serverVersion(fromUserAgent userAgent: String?) -> String? {+ guard let firstToken = userAgent?.split(separator: " ").first,+ let slashIndex = firstToken.firstIndex(of: "/") else { return nil }+ let version = firstToken[firstToken.index(after: slashIndex)...]+ return version.isEmpty ? nil : String(version)+ }++ func close() {+ transport.close()+ }++ func notify(_ method: String, params: [String: Any]? = nil) throws {+ let encoded = try encodeMessage(method: method, id: nil, params: params)++ try transport.notify(encoded.data)+ }++ func request<Response: Decodable>(+ _ method: String,+ params: [String: Any]? = nil,+ as type: Response.Type+ ) throws -> Response {+ guard !unsupportedMethods.contains(method) else {+ throw CodexStatusError.unsupportedMethod+ }++ // app-server 偶发业务错误可重试一次; 传输错误由上层重建连接+ do {+ return try performRequestRememberingUnsupported(method, params: params, as: type)+ } catch let error as CodexStatusError where error.isRetriableServerError && AppServerRPC.permitsRetry(method) {+ return try performRequestRememberingUnsupported(method, params: params, as: type)+ }+ }++ private func performRequestRememberingUnsupported<Response: Decodable>(+ _ method: String,+ params: [String: Any]? = nil,+ as type: Response.Type+ ) throws -> Response {+ do {+ return try performRequest(method, params: params, as: type)+ } catch let error as CodexStatusError {+ if error.isUnsupportedMethod {+ unsupportedMethods.insert(method)+ }+ throw error+ }+ }++ private func performRequest<Response: Decodable>(+ _ method: String,+ params: [String: Any]? = nil,+ as type: Response.Type+ ) throws -> Response {+ let id = nextID+ nextID += 1+ let encoded = try encodeMessage(method: method, id: id, params: params)+ do {+ let data = try transport.exchange(encoded.data, id: id, timeout: timeout)+ return try decodeResponse(data, as: type)+ } catch {+ if let failure = error as? CodexStatusError, failure.isTransportFailure {+ close()+ }+ throw error+ }+ }++ private func encodeMessage(method: String, id: Int?, params: [String: Any]?) throws -> EncodedMessage {+ let data = try AppServerRPC.encode(method: method, id: id, params: params)+ return (data, String(bytes: data, encoding: .utf8) ?? "")+ }++ private func decodeResponse<Response: Decodable>(_ data: Data, as type: Response.Type) throws -> Response {+ try AppServerRPC.decode(data, as: type)+ }+}++private nonisolated struct InitializeResult: Decodable {+ let userAgent: String?+}diff --git a/CodexBar/Services/AppServer/AppServerConfig.swift b/CodexBar/Services/AppServer/AppServerConfig.swiftnew file mode 100644index 0000000..8a6974b--- /dev/null+++ b/CodexBar/Services/AppServer/AppServerConfig.swift@@ -0,0 +1,72 @@+import Foundation++/// config/read 的最小响应模型, 只解出 TUI 通知相关状态+nonisolated struct ConfigReadResponse: Decodable {+ let config: AppServerConfig++ var areTUINotificationsEnabled: Bool {+ config.tui?.notifications?.isEnabled ?? true+ }+}++/// Codex 用户配置根节点, 字段保持 optional 以兼容不同 Codex 版本+nonisolated struct AppServerConfig: Decodable {+ let tui: AppServerTUI?+}++/// tui.notifications 支持布尔值或事件名数组; 空数组等价于不发送通知+nonisolated struct AppServerTUI: Decodable {+ let notifications: AppServerTUINotifications?+}++nonisolated enum AppServerTUINotifications: Decodable {+ case boolean(Bool)+ case events([String])++ var isEnabled: Bool {+ switch self {+ case let .boolean(isEnabled):+ isEnabled+ case let .events(events):+ !events.isEmpty+ }+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.singleValueContainer()+ if let isEnabled = try? container.decode(Bool.self) {+ self = .boolean(isEnabled)+ return+ }++ self = try .events(container.decode([String].self))+ }+}++/// config/batchWrite 的单条编辑, 直接转成 app-server 期望的 JSON 对象+nonisolated struct ConfigBatchEdit: Sendable {+ let keyPath: String+ let mergeStrategy: String++ private let value: Bool++ init(+ keyPath: String,+ value: Bool,+ mergeStrategy: String+ ) {+ self.keyPath = keyPath+ self.value = value+ self.mergeStrategy = mergeStrategy+ }++ var appServerObject: [String: Any] {+ [+ "keyPath": keyPath,+ "value": value,+ "mergeStrategy": mergeStrategy+ ]+ }+}++nonisolated struct ConfigWriteResponse: Decodable {}diff --git a/CodexBar/Services/AppServer/AppServerLogStore.swift b/CodexBar/Services/AppServer/AppServerLogStore.swiftnew file mode 100644index 0000000..b11ab89--- /dev/null+++ b/CodexBar/Services/AppServer/AppServerLogStore.swift@@ -0,0 +1,476 @@+import Foundation+import os+import SQLite3++nonisolated struct AppServerLogPage: Sendable {+ let entries: [AppServerLogEntry]+ let revision: Int64+ let generation: Int64+ let total: Int+ let hasMore: Bool+}++/// SQLite 连接和全部可变状态仅在 queue 上访问, 请求线程只提交有序写入+final nonisolated class AppServerLogStore: @unchecked Sendable {+ #if CODEXBAR_TESTING+ static let shared = AppServerLogStore(directoryURL: FileManager.default.temporaryDirectory.appendingPathComponent("CodexBarTestLogs-\(UUID().uuidString)"))+ #else+ static let shared = AppServerLogStore(directoryURL: defaultDirectory)+ #endif++ static var defaultDirectory: URL {+ AppStorage.directoryURL().appendingPathComponent("Logs", isDirectory: true)+ }++ #if DEBUG+ static let databaseName = "logs-debug.sqlite"+ #else+ static let databaseName = "logs.sqlite"+ #endif++ struct Limits: Sendable {+ var entries = 10000+ var bytes = 50 * 1024 * 1024+ var bodyBytes = 64 * 1024+ var pageEntries = 1000+ }++ private let limits: Limits+ private var storedBytes = 0+ private var storedCount = 0+ private var needsCheckpoint = false+ private let admissionLock = NSLock()+ private var queuedBytes = 0+ private var droppedEntries = 0+ private let directoryURL: URL+ private let queue = DispatchQueue(label: "CodexBar.request-log", qos: .utility)+ private var database: OpaquePointer?+ private var writeError: String?+ private var isFinished = false+ private static let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)++ init(directoryURL: URL, limits: Limits = Limits()) {+ self.limits = limits+ self.directoryURL = directoryURL+ }++ deinit {+ if let database {+ sqlite3_close(database)+ }+ }++ func beginRequest(method: String, payload: String, connection: String? = nil, source: AppServerLogEntry.Source = .request) -> UUID {+ let entry = AppServerLogEntry(id: UUID(), connection: connection, requestedAt: Date(), source: source, status: .pending, method: method, request: payload)+ append(entry)+ return entry.id+ }++ func finishRequest(_ id: UUID, response: String) {+ complete(id, status: .success, detail: response)+ }++ func failRequest(_ id: UUID, message: String) {+ complete(id, status: .failure, detail: message)+ }++ func recordSent(method: String, payload: String, connection: String? = nil, error: String? = nil) {+ let now = Date()+ append(AppServerLogEntry(+ id: UUID(),+ connection: connection,+ requestedAt: now,+ respondedAt: now,+ source: .sent,+ status: error == nil ? .success : .failure,+ method: method,+ request: payload,+ detail: error+ ))+ }++ func recordFailure(+ method: String? = nil,+ message: String,+ connection: String? = nil,+ source: AppServerLogEntry.Source = .local+ ) {+ append(AppServerLogEntry(+ id: UUID(),+ connection: connection,+ requestedAt: Date(),+ source: source,+ status: .failure,+ method: method,+ request: nil,+ detail: message+ ))+ }++ func recordReceived(method: String, payload: String, connection: String) {+ let now = Date()+ append(AppServerLogEntry(+ id: UUID(),+ connection: connection,+ requestedAt: now,+ respondedAt: now,+ source: .received,+ status: .information,+ method: method,+ request: nil,+ detail: payload+ ))+ }++ @discardableResult+ func recordConnection(method: String, detail: String, connection: String, status: AppServerLogEntry.Status) -> UUID {+ let entry = AppServerLogEntry(+ id: UUID(),+ connection: connection,+ requestedAt: Date(),+ source: .connection,+ status: status,+ method: method,+ request: nil,+ detail: detail+ )+ append(entry)+ return entry.id+ }++ func page(before position: Int64? = nil, limit: Int = 100) async throws -> AppServerLogPage {+ try await perform { storage in+ let limit = min(max(1, limit), storage.limits.pageEntries)+ let stats = try storage.stats()+ let entries = try storage.read(+ "SELECT position, payload, id FROM entries WHERE position < ? ORDER BY position DESC LIMIT ?",+ values: [position ?? Int64.max, Int64(max(1, limit) + 1)]+ )+ return AppServerLogPage(+ entries: Array(entries.prefix(max(1, limit))), revision: stats.revision,+ generation: stats.generation, total: stats.total, hasMore: entries.count > max(1, limit)+ )+ }+ }++ func changes(since revision: Int64) async throws -> AppServerLogPage {+ try await perform { storage in+ let stats = try storage.stats()+ let entries = stats.revision == revision ? [] : try storage.read(+ "SELECT position, payload, id FROM entries WHERE revision > ? ORDER BY position DESC LIMIT ?", values: [revision, Int64(storage.limits.pageEntries + 1)]+ )+ return AppServerLogPage(+ entries: Array(entries.prefix(storage.limits.pageEntries)),+ revision: stats.revision,+ generation: stats.generation,+ total: stats.total,+ hasMore: entries.count > storage.limits.pageEntries+ )+ }+ }++ func clear() async throws {+ try await perform { storage in+ try storage.transaction {+ try storage.execute("DELETE FROM entries")+ try storage.execute("UPDATE metadata SET revision = revision + 1, generation = generation + 1, total = 0")+ }+ storage.storedBytes = 0+ storage.storedCount = 0+ storage.writeError = nil+ try storage.execute("PRAGMA wal_checkpoint(TRUNCATE)")+ }+ }++ /// 正常退出时排空已提交写入, 之后到达的网络回调不再追加日志+ func finish() async throws {+ try await perform { storage in+ storage.isFinished = true+ try storage.execute("PRAGMA wal_checkpoint(TRUNCATE)")+ }+ }++ private func append(_ entry: AppServerLogEntry) {+ let entry = entry.bounded(to: limits.bodyBytes)+ enqueue(cost: (entry.request?.utf8.count ?? 0) + (entry.detail?.utf8.count ?? 0)+ + (entry.method?.utf8.count ?? 0) + (entry.connection?.utf8.count ?? 0) + 1024) { storage in+ try storage.transaction { try storage.save(entry, inserting: true) }+ }+ }++ private func complete(_ id: UUID, status: AppServerLogEntry.Status, detail: String) {+ let completed = Date()+ let originalBytes = detail.utf8.count+ let detail = AppServerLogEntry.truncated(detail, limit: limits.bodyBytes)+ enqueue(cost: detail.utf8.count + 1024) { storage in+ try storage.transaction {+ let statement = try storage.prepare("SELECT position, payload, id FROM entries WHERE id = ?")+ defer { sqlite3_finalize(statement) }+ try storage.bind(id.uuidString, to: statement, at: 1)+ guard try storage.step(statement) == SQLITE_ROW else { return }+ guard var entry = storage.decode(statement, skipCorrupt: true) else { return }+ entry.status = status+ entry.detail = detail+ entry.detailOriginalBytes = originalBytes > storage.limits.bodyBytes ? originalBytes : nil+ entry.respondedAt = completed+ try storage.save(entry, inserting: false)+ }+ }+ }++ private func enqueue(cost: Int, _ operation: @escaping @Sendable (AppServerLogStore) throws -> Void) {+ admissionLock.lock()+ guard queuedBytes + cost <= limits.bytes else {+ droppedEntries += 1+ admissionLock.unlock()+ return+ }+ queuedBytes += cost+ admissionLock.unlock()+ queue.async { [self] in+ defer {+ admissionLock.lock()+ queuedBytes -= cost+ admissionLock.unlock()+ }+ guard !isFinished else { return }+ do {+ try open()+ try operation(self)+ if needsCheckpoint {+ try execute("PRAGMA wal_checkpoint(TRUNCATE)")+ try execute("PRAGMA incremental_vacuum(256)")+ needsCheckpoint = false+ }+ writeError = nil+ } catch {+ writeError = String(localized: "log.persistence.error.write")+ // 不把包含请求正文的数据库错误写入系统日志+ AppLog.app.error("请求日志写入失败")+ }+ }+ }++ private func perform<Value: Sendable>(_ operation: @escaping @Sendable (AppServerLogStore) throws -> Value) async throws -> Value {+ try await withCheckedThrowingContinuation { continuation in+ queue.async { [self] in+ do {+ try open()+ admissionLock.lock()+ let dropped = droppedEntries+ droppedEntries = 0+ admissionLock.unlock()+ if dropped > 0, !isFinished {+ let entry = AppServerLogEntry(+ id: UUID(),+ requestedAt: Date(),+ source: .local, status: .failure,+ method: "log/backpressure",+ request: nil,+ detail: "Skipped \(dropped) log entries because the write buffer was full"+ )+ try transaction { try save(entry, inserting: true) }+ }+ let result = try operation(self)+ if let writeError {+ throw StorageError(message: writeError)+ }+ continuation.resume(returning: result)+ } catch {+ continuation.resume(throwing: error)+ }+ }+ }+ }++ private func open() throws {+ guard database == nil else { return }+ try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])+ var opened: OpaquePointer?+ let path = directoryURL.appendingPathComponent(Self.databaseName).path+ guard sqlite3_open_v2(path, &opened, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX, nil) == SQLITE_OK else {+ if let opened {+ sqlite3_close(opened)+ }+ throw StorageError(message: String(localized: "log.persistence.error.read"))+ }+ database = opened+ do {+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path)+ sqlite3_busy_timeout(database, 3000)+ if try scalar("PRAGMA auto_vacuum") != 2 {+ try execute("PRAGMA auto_vacuum = INCREMENTAL")+ try execute("VACUUM")+ }+ try execute("PRAGMA journal_mode = WAL")+ try execute("PRAGMA journal_size_limit = 4194304")+ try execute("PRAGMA wal_autocheckpoint = 256")+ try execute("PRAGMA synchronous = NORMAL")+ try execute("PRAGMA secure_delete = ON")+ try execute("CREATE TABLE IF NOT EXISTS metadata (revision INTEGER NOT NULL, generation INTEGER NOT NULL, total INTEGER NOT NULL)")+ try execute("INSERT INTO metadata SELECT 0, 0, 0 WHERE NOT EXISTS (SELECT 1 FROM metadata)")+ try execute("""+ CREATE TABLE IF NOT EXISTS entries (+ position INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE,+ revision INTEGER NOT NULL, state TEXT NOT NULL, payload BLOB NOT NULL+ )+ """)+ try execute("CREATE INDEX IF NOT EXISTS entries_revision ON entries(revision)")+ try execute("CREATE INDEX IF NOT EXISTS entries_state ON entries(state)")+ storedCount = try scalar("SELECT COUNT(*) FROM entries")+ storedBytes = try scalar("SELECT COALESCE(SUM(length(payload)), 0) FROM entries")+ try transaction { try pruneIfNeeded() }+ // 上次进程退出时未完成的请求不能永久显示为等待响应+ let interrupted = try read("SELECT position, payload, id FROM entries WHERE state = 'pending'", values: [], skipCorrupt: true)+ try transaction {+ for var entry in interrupted {+ entry.status = .failure+ entry.detail = String(localized: "log.persistence.interrupted")+ try save(entry, inserting: false)+ }+ }+ } catch {+ sqlite3_close(database)+ database = nil+ throw error+ }+ }++ private func save(_ entry: AppServerLogEntry, inserting: Bool) throws {+ let previousBytes = inserting ? 0 : try scalar("SELECT COALESCE(length(payload), 0) FROM entries WHERE id = '\(entry.id.uuidString)'")+ guard inserting || previousBytes > 0 else { return }+ try execute("UPDATE metadata SET revision = revision + 1\(inserting ? ", total = total + 1" : "")")+ let sql = inserting+ ? "INSERT INTO entries (id, state, payload, revision) VALUES (?, ?, ?, (SELECT revision FROM metadata))"+ : "UPDATE entries SET state = ?2, payload = ?3, revision = (SELECT revision FROM metadata) WHERE id = ?1"+ let statement = try prepare(sql)+ defer { sqlite3_finalize(statement) }+ try bind(entry.id.uuidString, to: statement, at: 1)+ try bind(entry.status.rawValue, to: statement, at: 2)+ let data = try JSONEncoder().encode(entry.bounded(to: limits.bodyBytes))+ let bound = data.withUnsafeBytes { sqlite3_bind_blob(statement, 3, $0.baseAddress, Int32($0.count), Self.transient) }+ guard bound == SQLITE_OK else { throw failure() }+ _ = try step(statement)+ storedBytes += data.count - previousBytes+ storedCount += inserting ? 1 : 0+ try pruneIfNeeded()+ }++ private func pruneIfNeeded() throws {+ guard storedCount > limits.entries || storedBytes > limits.bytes else { return }+ let count = max(1, limits.entries * 9 / 10)+ let bytes = max(1, limits.bytes * 9 / 10)+ try execute("""+ DELETE FROM entries WHERE position IN (+ SELECT position FROM (+ SELECT position, ROW_NUMBER() OVER (ORDER BY position DESC) AS n,+ SUM(length(payload)) OVER (ORDER BY position DESC) AS bytes FROM entries+ ) WHERE n > \(count) OR bytes > \(bytes)+ )+ """)+ storedCount = try scalar("SELECT COUNT(*) FROM entries")+ storedBytes = try scalar("SELECT COALESCE(SUM(length(payload)), 0) FROM entries")+ try execute("UPDATE metadata SET total = \(storedCount), revision = revision + 1, generation = generation + 1")+ needsCheckpoint = true+ }++ private func scalar(_ sql: String) throws -> Int {+ let statement = try prepare(sql)+ defer { sqlite3_finalize(statement) }+ guard try step(statement) == SQLITE_ROW else { return 0 }+ return Int(sqlite3_column_int64(statement, 0))+ }++ private struct Statistics {+ let revision: Int64+ let generation: Int64+ let total: Int+ }++ private func stats() throws -> Statistics {+ let statement = try prepare("SELECT revision, generation, total FROM metadata")+ defer { sqlite3_finalize(statement) }+ guard try step(statement) == SQLITE_ROW else { throw failure() }+ return Statistics(revision: sqlite3_column_int64(statement, 0), generation: sqlite3_column_int64(statement, 1), total: Int(sqlite3_column_int64(statement, 2)))+ }++ private func read(_ sql: String, values: [Int64], skipCorrupt: Bool = false) throws -> [AppServerLogEntry] {+ let statement = try prepare(sql)+ defer { sqlite3_finalize(statement) }+ for (index, value) in values.enumerated() {+ guard sqlite3_bind_int64(statement, Int32(index + 1), value) == SQLITE_OK else { throw failure() }+ }+ var entries: [AppServerLogEntry] = []+ while try step(statement) == SQLITE_ROW {+ if let entry = decode(statement, skipCorrupt: skipCorrupt) {+ entries.append(entry)+ }+ }+ return entries+ }++ private func decode(_ statement: OpaquePointer, skipCorrupt: Bool = false) -> AppServerLogEntry? {+ let position = sqlite3_column_int64(statement, 0)+ let data = sqlite3_column_blob(statement, 1).map {+ Data(bytes: $0, count: Int(sqlite3_column_bytes(statement, 1)))+ } ?? Data()+ let storedID = sqlite3_column_text(statement, 2).flatMap { UUID(uuidString: String(cString: $0)) }+ if var entry = try? JSONDecoder().decode(AppServerLogEntry.self, from: data), entry.id == storedID {+ entry.position = position+ return entry+ }+ guard !skipCorrupt else { return nil }+ // 占位记录沿用数据库身份和位置, 原始字节不被恢复流程覆盖+ var identity = (UInt64(0), UInt64(bitPattern: position).bigEndian)+ let id = storedID ?? withUnsafeBytes(of: &identity) { UUID(uuid: $0.load(as: uuid_t.self)) }+ return AppServerLogEntry(+ position: position, id: id, requestedAt: .distantPast, source: .local, status: .failure,+ method: "log/corrupt", request: nil,+ detail: String(localized: "log.persistence.error.read") + "\n" + (String(data: data, encoding: .utf8) ?? data.base64EncodedString())+ )+ }++ private func transaction(_ operation: () throws -> Void) throws {+ try execute("BEGIN IMMEDIATE")+ do {+ try operation()+ try execute("COMMIT")+ } catch {+ try? execute("ROLLBACK")+ storedCount = (try? scalar("SELECT COUNT(*) FROM entries")) ?? storedCount+ storedBytes = (try? scalar("SELECT COALESCE(SUM(length(payload)), 0) FROM entries")) ?? storedBytes+ throw error+ }+ }++ private func prepare(_ sql: String) throws -> OpaquePointer {+ var statement: OpaquePointer?+ guard sqlite3_prepare_v2(database, sql, -1, &statement, nil) == SQLITE_OK, let statement else { throw failure() }+ return statement+ }++ private func execute(_ sql: String) throws {+ guard sqlite3_exec(database, sql, nil, nil, nil) == SQLITE_OK else { throw failure() }+ }++ private func bind(_ text: String, to statement: OpaquePointer, at index: Int32) throws {+ guard sqlite3_bind_text(statement, index, text, -1, Self.transient) == SQLITE_OK else { throw failure() }+ }++ private func step(_ statement: OpaquePointer) throws -> Int32 {+ let status = sqlite3_step(statement)+ guard status == SQLITE_ROW || status == SQLITE_DONE else { throw failure() }+ return status+ }++ private func failure() -> StorageError {+ StorageError(message: String(localized: "log.persistence.error.read"))+ }++ private struct StorageError: LocalizedError {+ let message: String+ var errorDescription: String? {+ message+ }+ }+}diff --git a/CodexBar/Services/AppServer/AppServerLogViewModel.swift b/CodexBar/Services/AppServer/AppServerLogViewModel.swiftnew file mode 100644index 0000000..9da967d--- /dev/null+++ b/CodexBar/Services/AppServer/AppServerLogViewModel.swift@@ -0,0 +1,183 @@+import Combine+import Foundation++@MainActor+final class AppServerLogViewModel: ObservableObject {+ static let shared = AppServerLogViewModel()++ @Published private(set) var entries: [AppServerLogEntry] = []+ @Published private(set) var totalCount = 0+ @Published private(set) var hasMore = false+ @Published private(set) var isLoading = false+ @Published private(set) var errorMessage: String?++ private let storage: AppServerLogStore+ private let pageSize: Int+ private let maximumEntries: Int+ @Published private(set) var browsingHistory = false+ private var revision: Int64 = 0+ private var generation: Int64 = 0+ private var isLoaded = false+ private var isReading = false+ private var observation: Task<Void, Never>?+ private var observationGeneration = 0++ init(storage: AppServerLogStore = .shared, pageSize: Int = 100, maximumEntries: Int = 1000) {+ self.storage = storage+ self.pageSize = min(pageSize, maximumEntries)+ self.maximumEntries = maximumEntries+ }++ func start() {+ guard observation == nil else { return }+ observationGeneration += 1+ observation = Task { [weak self] in+ while !Task.isCancelled {+ guard let self else { return }+ await refresh()+ try? await Task.sleep(for: .milliseconds(250))+ }+ }+ }++ func stop() {+ observationGeneration += 1+ observation?.cancel()+ observation = nil+ entries = []+ totalCount = 0+ hasMore = false+ isLoaded = false+ isReading = false+ isLoading = false+ }++ func refresh() async {+ guard !isReading else { return }+ let current = observationGeneration+ isReading = true+ isLoading = !isLoaded+ defer {+ if current == observationGeneration {+ isReading = false+ isLoading = false+ }+ }+ do {+ if !isLoaded {+ try await loadFirst(current: current)+ } else {+ let changes = try await storage.changes(since: revision)+ guard current == observationGeneration else { return }+ if changes.generation != generation || changes.hasMore {+ try await loadFirst(current: current)+ } else {+ if !changes.entries.isEmpty {+ let newest = entries.first?.position ?? 0+ var byID = Dictionary(uniqueKeysWithValues: entries.map { ($0.id, $0) })+ for entry in changes.entries where byID[entry.id] != nil || (!browsingHistory && entry.position > newest) {+ byID[entry.id] = entry+ }+ entries = Array(byID.values.sorted { $0.position > $1.position }.prefix(maximumEntries))+ }+ revision = changes.revision+ totalCount = changes.total+ let oldest = try await storage.page(before: entries.last?.position, limit: 1)+ guard current == observationGeneration else { return }+ hasMore = !oldest.entries.isEmpty+ }+ }+ errorMessage = nil+ } catch {+ if current == observationGeneration {+ errorMessage = error.localizedDescription+ }+ }+ }++ func loadMore() async {+ let waitingGeneration = observationGeneration+ while isReading {+ do { try await Task.sleep(for: .milliseconds(25)) } catch { return }+ guard waitingGeneration == observationGeneration else { return }+ }+ guard !Task.isCancelled, hasMore, let cursor = entries.last?.position else { return }+ let current = observationGeneration+ isReading = true+ isLoading = true+ defer {+ if current == observationGeneration {+ isReading = false+ isLoading = false+ }+ }+ do {+ let page = try await storage.page(before: cursor, limit: pageSize)+ guard current == observationGeneration else { return }+ if page.generation != generation {+ try await loadFirst(current: current)+ } else {+ let existing = Set(entries.map(\.id))+ entries.append(contentsOf: page.entries.filter { !existing.contains($0.id) })+ if entries.count > maximumEntries {+ entries.removeFirst(entries.count - maximumEntries)+ browsingHistory = true+ }+ hasMore = page.hasMore+ totalCount = page.total+ }+ errorMessage = nil+ } catch {+ if current == observationGeneration {+ errorMessage = error.localizedDescription+ }+ }+ }++ func showLatest() async {+ guard !isReading else { return }+ isLoaded = false+ await refresh()+ }++ func clear() async {+ let waitingGeneration = observationGeneration+ while isReading {+ do { try await Task.sleep(for: .milliseconds(25)) } catch { return }+ guard waitingGeneration == observationGeneration else { return }+ }+ guard !Task.isCancelled else { return }+ let current = observationGeneration+ isReading = true+ isLoading = true+ defer {+ if current == observationGeneration {+ isReading = false+ isLoading = false+ }+ }+ do {+ try await storage.clear()+ try await loadFirst(current: current)+ if current == observationGeneration {+ errorMessage = nil+ }+ } catch {+ if current == observationGeneration {+ errorMessage = error.localizedDescription+ }+ }+ }++ private func loadFirst(current: Int) async throws {+ let page = try await storage.page(limit: pageSize)+ guard current == observationGeneration else { return }+ entries = page.entries+ browsingHistory = false+ revision = page.revision+ generation = page.generation+ totalCount = page.total+ hasMore = page.hasMore+ isLoaded = true+ }+}diff --git a/CodexBar/Services/AppServer/AppServerRPC.swift b/CodexBar/Services/AppServer/AppServerRPC.swiftnew file mode 100644index 0000000..a235fce--- /dev/null+++ b/CodexBar/Services/AppServer/AppServerRPC.swift@@ -0,0 +1,53 @@+import CoreFoundation+import Foundation++nonisolated struct AppServerRPCError: Error {+ let code: Int?+ let message: String+ let data: Data?+}++/// 账户与活动连接使用相同的信封和载荷错误边界+nonisolated enum AppServerRPC {+ static func encode(method: String, id: Int?, params: [String: Any]?) throws -> Data {+ var object: [String: Any] = ["method": method]+ if let id {+ object["id"] = id+ }+ if let params {+ object["params"] = params+ }+ return try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes])+ }++ static func decode<Response: Decodable>(_ data: Data, as _: Response.Type) throws -> Response {+ guard let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],+ (object["error"] != nil) != (object["result"] != nil) else {+ throw CodexStatusError.invalidServerResponse+ }+ if let error = object["error"] {+ guard let error = error as? [String: Any], let message = error["message"] as? String else {+ throw CodexStatusError.invalidServerResponse+ }+ if let code = error["code"] {+ guard let number = code as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), code is Int else {+ throw CodexStatusError.invalidServerResponse+ }+ }+ let detail = try error["data"].map {+ try JSONSerialization.data(withJSONObject: $0, options: [.fragmentsAllowed, .sortedKeys, .withoutEscapingSlashes])+ }+ throw CodexStatusError.serverError(AppServerRPCError(code: error["code"] as? Int, message: message, data: detail))+ }+ do {+ let payload = try JSONSerialization.data(withJSONObject: object["result"]!, options: [.fragmentsAllowed])+ return try JSONDecoder().decode(Response.self, from: payload)+ } catch {+ throw CodexStatusError.invalidResponsePayload+ }+ }++ static func permitsRetry(_ method: String) -> Bool {+ ["account/read", "account/rateLimits/read", "config/read", "model/list", "configRequirements/read"].contains(method)+ }+}diff --git a/CodexBar/Services/AppServer/AppServerSession.swift b/CodexBar/Services/AppServer/AppServerSession.swiftnew file mode 100644index 0000000..ca26bc0--- /dev/null+++ b/CodexBar/Services/AppServer/AppServerSession.swift@@ -0,0 +1,417 @@+import CryptoKit+import Darwin+import Foundation++/// 每条连接由所属 actor 独占, 通过 Unix WebSocket 访问共享服务, 不拥有 daemon 生命周期+final nonisolated class AppServerSession {+ private var descriptor: Int32 = -1+ private var nextID = 0+ private var notifications: [Data] = []+ private let logStorage: AppServerLogStore?+ private let socketPath: String+ private let connectionName: String+ private let retainsNotifications: Bool+ var isOpen: Bool {+ descriptor >= 0+ }++ private static let maximumMessageSize = 16 * 1024 * 1024++ init(socketURL: URL, retainsNotifications: Bool = true, logStorage: AppServerLogStore? = .shared, connectionName: String = "activity") throws {+ socketPath = socketURL.path+ self.logStorage = logStorage+ self.connectionName = connectionName+ self.retainsNotifications = retainsNotifications+ let connectionLogID = logStorage?.recordConnection(method: "connection/open", detail: socketPath, connection: connectionName, status: .pending)+ do {+ descriptor = socket(AF_UNIX, SOCK_STREAM, 0)+ guard descriptor >= 0 else { throw CodexStatusError.serverConnectionClosed }+ var address = sockaddr_un()+ address.sun_family = sa_family_t(AF_UNIX)+ let path = Array(socketURL.path.utf8CString)+ guard path.count <= MemoryLayout.size(ofValue: address.sun_path) else {+ throw CodexStatusError.serverConnectionClosed+ }+ withUnsafeMutableBytes(of: &address.sun_path) { destination in+ path.withUnsafeBytes { destination.copyBytes(from: $0) }+ }+ let result = withUnsafePointer(to: &address) {+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ Darwin.connect(descriptor, $0, socklen_t(MemoryLayout<sockaddr_un>.size))+ }+ }+ guard result == 0 else { throw CodexStatusError.serverConnectionClosed }+ var enabled: Int32 = 1+ _ = setsockopt(descriptor, SOL_SOCKET, SO_NOSIGPIPE, &enabled, socklen_t(MemoryLayout<Int32>.size))+ _ = fcntl(descriptor, F_SETFL, O_NONBLOCK)+ try handshake()+ if let connectionLogID {+ logStorage?.finishRequest(connectionLogID, response: socketPath)+ }+ } catch {+ if let connectionLogID {+ logStorage?.failRequest(connectionLogID, message: error.localizedDescription)+ }+ close()+ throw error+ }+ }++ deinit { close() }++ func close() {+ guard descriptor >= 0 else { return }+ Darwin.close(descriptor)+ descriptor = -1+ logStorage?.recordConnection(method: "connection/closed", detail: socketPath, connection: connectionName, status: .information)+ }++ func initialize() throws {+ let result: Initialization = try request("initialize", params: [+ "clientInfo": ["name": "codex_bar_activity", "version": Bundle.main.shortVersionString ?? "1.0.0"],+ "capabilities": ["experimentalApi": true]+ ])+ let version = result.userAgent.split(separator: " ").first?.split(separator: "/").last.map(String.init)+ guard let version,+ CodexVersionReader.isVersion(version, atLeast: CodexMinimumVersion.activity) == true else {+ throw CodexStatusError.unsupportedVersion(minimum: CodexMinimumVersion.activity)+ }+ try send(["method": "initialized"])+ }++ func request<Response: Decodable>(_ method: String, params: [String: Any] = [:]) throws -> Response {+ nextID += 1+ let id = nextID+ let payload = try AppServerRPC.encode(method: method, id: id, params: params)+ return try AppServerRPC.decode(exchange(payload, id: id, timeout: 10), as: Response.self)+ }++ struct PendingRequest {+ let id: Int+ let logID: UUID?+ let deadline: ContinuousClock.Instant+ }++ enum RequestPoll {+ case waiting+ case event(Data)+ case response(Data)+ }++ /// 活动连接分步等响应, 由所属 actor 在等待期间消费推送和处理取消+ func beginRequest(_ method: String, params: [String: Any]) throws -> PendingRequest {+ nextID += 1+ let payload = try AppServerRPC.encode(method: method, id: nextID, params: params)+ let request = PendingRequest(+ id: nextID,+ logID: logStorage?.beginRequest(method: method, payload: String(bytes: payload, encoding: .utf8) ?? "", connection: connectionName),+ deadline: ContinuousClock.now.advanced(by: .seconds(10))+ )+ do { try sendFrame(payload, opcode: 1) } catch {+ fail(request, error: error)+ throw error+ }+ return request+ }++ func poll(_ request: PendingRequest) throws -> RequestPoll {+ try Task.checkCancellation()+ guard ContinuousClock.now < request.deadline else { throw CodexStatusError.serverTimeout }+ guard let data = try receive(before: Date().addingTimeInterval(0.02), matchingResponseID: request.id) else { return .waiting }+ guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {+ throw CodexStatusError.invalidServerResponse+ }+ if object["id"] as? Int == request.id, object["result"] != nil || object["error"] != nil {+ if let logID = request.logID {+ let response = (String(bytes: data, encoding: .utf8) ?? "")+ if object["error"] != nil {+ logStorage?.failRequest(logID, message: response)+ } else {+ logStorage?.finishRequest(logID, response: response)+ }+ }+ return .response(data)+ }+ return .event(data)+ }++ func fail(_ request: PendingRequest, error: Error) {+ if let logID = request.logID {+ logStorage?.failRequest(logID, message: error.localizedDescription)+ }+ }++ /// 账户和活动连接共用帧协议与请求日志, 业务解码由调用方负责+ func exchange(_ payload: Data, id: Int, timeout: TimeInterval) throws -> Data {+ let request = try JSONSerialization.jsonObject(with: payload) as? [String: Any]+ let method = request?["method"] as? String ?? "unknown"+ let text = String(data: payload, encoding: .utf8) ?? ""+ let token = logStorage?.beginRequest(method: method, payload: text, connection: connectionName)+ do {+ let data = try receiveResponse(payload, id: id, timeout: timeout)+ if let token {+ let response = String(data: data, encoding: .utf8) ?? ""+ let object = try JSONSerialization.jsonObject(with: data) as? [String: Any]+ if object?["error"] != nil {+ logStorage?.failRequest(token, message: response)+ } else {+ logStorage?.finishRequest(token, response: response)+ }+ }+ return data+ } catch {+ if let token {+ logStorage?.failRequest(token, message: error.localizedDescription)+ }+ throw error+ }+ }++ private func receiveResponse(_ payload: Data, id: Int, timeout: TimeInterval) throws -> Data {+ try sendFrame(payload, opcode: 1)+ let deadline = Date().addingTimeInterval(timeout)+ while Date() < deadline {+ guard let data = try receive(before: deadline, matchingResponseID: id),+ let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { continue }+ if object["id"] as? Int == id, object["result"] != nil || object["error"] != nil {+ return data+ }+ // 审批请求只作为观察事件, 绝不在旁观连接中回答+ if retainsNotifications {+ guard notifications.count < 4096 else { throw CodexStatusError.serverConnectionClosed }+ notifications.append(data)+ }+ }+ throw CodexStatusError.serverTimeout+ }++ func notify(_ payload: Data) throws {+ let object = try JSONSerialization.jsonObject(with: payload) as? [String: Any]+ let method = object?["method"] as? String ?? "unknown"+ let text = String(data: payload, encoding: .utf8) ?? ""+ do {+ try sendFrame(payload, opcode: 1)+ logStorage?.recordSent(method: method, payload: text, connection: connectionName)+ } catch {+ logStorage?.recordSent(method: method, payload: text, connection: connectionName, error: error.localizedDescription)+ throw error+ }+ }++ func nextEvent() throws -> Data? {+ if !notifications.isEmpty {+ return notifications.removeFirst()+ }+ do {+ return try receive(before: Date().addingTimeInterval(0.05))+ } catch {+ logStorage?.recordFailure(method: "connection/receive", message: error.localizedDescription, connection: connectionName, source: .connection)+ throw error+ }+ }++ private func handshake() throws {+ let key = Data((0 ..< 16).map { _ in UInt8.random(in: .min ... .max) }).base64EncodedString()+ let text = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: \(key)\r\nSec-WebSocket-Version: 13\r\n\r\n"+ let deadline = Date().addingTimeInterval(5)+ let token = logStorage?.beginRequest(method: "websocket/handshake", payload: text, connection: connectionName, source: .connection)+ var header = Data()+ do {+ try write(Data(text.utf8), before: deadline)+ while !header.suffix(4).elementsEqual([13, 10, 13, 10]), header.count < 16384 {+ try header.append(read(1, before: deadline))+ }+ guard let response = String(data: header, encoding: .utf8) else { throw CodexStatusError.invalidServerResponse }+ let expected = Data(Insecure.SHA1.hash(data: Data((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").utf8))).base64EncodedString()+ guard response.hasPrefix("HTTP/1.1 101 "), response.contains(expected) else {+ throw CodexStatusError.invalidServerResponse+ }+ if let token {+ logStorage?.finishRequest(token, response: response)+ }+ } catch {+ if let token {+ let received = String(data: header, encoding: .utf8) ?? header.base64EncodedString()+ logStorage?.failRequest(token, message: received.isEmpty ? error.localizedDescription : received + "\n" + error.localizedDescription)+ }+ throw error+ }+ }++ private func send(_ object: [String: Any]) throws {+ try notify(JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes]))+ }++ private func sendFrame(_ payload: Data, opcode: UInt8) throws {+ let mask = (0 ..< 4).map { _ in UInt8.random(in: .min ... .max) }+ var frame = Data([0x80 | opcode])+ if payload.count < 126 {+ frame.append(0x80 | UInt8(payload.count))+ } else if payload.count <= Int(UInt16.max) {+ frame.append(0xFE)+ frame.append(contentsOf: [UInt8(payload.count >> 8), UInt8(payload.count & 255)])+ } else {+ frame.append(0xFF)+ frame.append(contentsOf: (0 ..< 8).reversed().map { UInt8((UInt64(payload.count) >> ($0 * 8)) & 255) })+ }+ frame.append(contentsOf: mask)+ frame.append(contentsOf: payload.enumerated().map { $0.element ^ mask[$0.offset % 4] })+ do {+ try write(frame, before: Date().addingTimeInterval(5))+ if opcode != 1 {+ logStorage?.recordSent(method: controlMethod(opcode), payload: framePayload(payload), connection: connectionName)+ }+ } catch {+ if opcode != 1 {+ logStorage?.recordSent(+ method: controlMethod(opcode),+ payload: framePayload(payload),+ connection: connectionName,+ error: error.localizedDescription+ )+ }+ throw error+ }+ }++ private func receive(before deadline: Date, matchingResponseID: Int? = nil) throws -> Data? {+ guard try ready(Int16(POLLIN), before: deadline) else { return nil }+ let frameDeadline = Date().addingTimeInterval(10)+ var message = Data()+ var fragmented = false+ while true {+ let header = try [UInt8](read(2, before: frameDeadline))+ let opcode = header[0] & 15+ var length = UInt64(header[1] & 127)+ if length == 126 || length == 127 {+ length = try read(length == 126 ? 2 : 8, before: frameDeadline).reduce(UInt64(0)) { ($0 << 8) | UInt64($1) }+ }+ guard length <= Self.maximumMessageSize, message.count + Int(length) <= Self.maximumMessageSize,+ header[1] & 128 == 0 else { throw CodexStatusError.invalidServerResponse }+ let payload = try read(Int(length), before: frameDeadline)+ if opcode >= 8 {+ logStorage?.recordReceived(method: controlMethod(opcode), payload: framePayload(payload), connection: connectionName)+ }+ if opcode == 8 {+ throw CodexStatusError.serverConnectionClosed+ }+ if opcode == 9 {+ guard header[0] & 128 != 0, length <= 125 else { throw CodexStatusError.invalidServerResponse }+ try sendFrame(payload, opcode: 10)+ if !fragmented, try !ready(Int16(POLLIN), before: deadline) {+ return nil+ }+ continue+ }+ if opcode == 10 {+ guard header[0] & 128 != 0, length <= 125 else { throw CodexStatusError.invalidServerResponse }+ if !fragmented, try !ready(Int16(POLLIN), before: deadline) {+ return nil+ }+ continue+ }+ guard header[0] & 0x70 == 0, opcode == (fragmented ? 0 : 1) else { throw CodexStatusError.invalidServerResponse }+ message.append(payload)+ if header[0] & 128 != 0 {+ recordIncoming(message, matchingResponseID: matchingResponseID)+ return message+ }+ fragmented = true+ }+ }++ /// 在完整消息首次读取时记录, 队列取出和业务消费不重复写日志+ private func recordIncoming(_ data: Data, matchingResponseID: Int?) {+ guard let logStorage else { return }+ let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]+ if let matchingResponseID, object?["id"] as? Int == matchingResponseID,+ object?["result"] != nil || object?["error"] != nil {+ return+ }+ guard Self.shouldRecordIncoming(object) else { return }+ let method = object?["method"] as? String ?? "app-server/message"+ logStorage.recordReceived(method: method, payload: framePayload(data), connection: connectionName)+ }++ /// 推送只记录业务使用的状态事件, 错误和异常协议消息保留以便排查+ /// 此判断不参与消息路由, 被过滤的消息仍交给业务消费+ private static func shouldRecordIncoming(_ object: [String: Any]?) -> Bool {+ guard let object, let method = object["method"] as? String else { return true }+ if method == "error" || method == "warning" {+ return true+ }+ guard ActivityNotification.category(for: method) == .state else { return false }+ switch method {+ case "item/started", "item/completed":+ guard let params = object["params"] as? [String: Any],+ let item = params["item"] as? [String: Any], let type = item["type"] as? String else { return true }+ return ActivityItem.isToolType(type) || type == "contextCompaction" || type == "subAgentActivity"+ default:+ return true+ }+ }++ private func controlMethod(_ opcode: UInt8) -> String {+ switch opcode {+ case 8: "websocket/close"+ case 9: "websocket/ping"+ case 10: "websocket/pong"+ default: "websocket/opcode/\(opcode)"+ }+ }++ private func framePayload(_ data: Data) -> String {+ String(data: data, encoding: .utf8) ?? "base64:" + data.base64EncodedString()+ }++ private func ready(_ events: Int16, before deadline: Date) throws -> Bool {+ guard descriptor >= 0 else { throw CodexStatusError.serverConnectionClosed }+ var descriptor = pollfd(fd: descriptor, events: events, revents: 0)+ while Date() < deadline {+ try Task.checkCancellation()+ let result = Darwin.poll(&descriptor, 1, Int32(max(1, min(100, deadline.timeIntervalSinceNow * 1000))))+ if result < 0, errno == EINTR {+ continue+ }+ guard result >= 0 else { throw CodexStatusError.serverConnectionClosed }+ if result == 0 {+ continue+ }+ if descriptor.revents & events != 0 {+ return true+ }+ throw CodexStatusError.serverConnectionClosed+ }+ return false+ }++ private func read(_ count: Int, before deadline: Date) throws -> Data {+ var result = Data()+ var buffer = [UInt8](repeating: 0, count: min(count, 65536))+ while result.count < count {+ guard try ready(Int16(POLLIN), before: deadline) else { throw CodexStatusError.serverTimeout }+ let size = recv(descriptor, &buffer, min(buffer.count, count - result.count), 0)+ if size < 0, errno == EINTR || errno == EAGAIN {+ continue+ }+ guard size > 0 else { throw CodexStatusError.serverConnectionClosed }+ result.append(contentsOf: buffer.prefix(size))+ }+ return result+ }++ private func write(_ data: Data, before deadline: Date) throws {+ var offset = 0+ while offset < data.count {+ guard try ready(Int16(POLLOUT), before: deadline) else { throw CodexStatusError.serverTimeout }+ let size = data.withUnsafeBytes { Darwin.send(descriptor, $0.baseAddress!.advanced(by: offset), data.count - offset, 0) }+ if size < 0, errno == EINTR || errno == EAGAIN {+ continue+ }+ guard size > 0 else { throw CodexStatusError.serverConnectionClosed }+ offset += size+ }+ }++ private struct Initialization: Decodable { let userAgent: String }+}diff --git a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift b/CodexBar/Services/Codex/CodexPaths.swiftsimilarity index 65%rename from CodexBar/Services/CodexCLI/CodexCLIResolver.swiftrename to CodexBar/Services/Codex/CodexPaths.swiftindex 3798b3d..aea13e0 100644--- a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift+++ b/CodexBar/Services/Codex/CodexPaths.swift@@ -1,8 +1,8 @@import Darwinimport Foundation-/// 可用于启动 app-server 的安装来源-nonisolated enum CodexCLIExecutableSource: String, Equatable {+/// 用于展示已安装版本的来源+nonisolated enum CodexExecutableSource: String, Equatable {case globalcase bundled@@ -14,106 +14,31 @@ nonisolated enum CodexCLIExecutableSource: String, Equatable {}}-/// 自动沿用 CLI 优先的解析规则, 手动选择只使用指定来源-nonisolated enum CodexCLISourceSelection: String, CaseIterable, Identifiable {- case automatic- case global- case bundled-- var id: Self {- self- }-- var source: CodexCLIExecutableSource? {- switch self {- case .automatic: nil- case .global: .global- case .bundled: .bundled- }- }-- var title: String {- source?.displayName ?? String(localized: "codex-cli.source.automatic")- }-- static func load(from defaults: UserDefaults) -> Self {- defaults.string(forKey: defaultsKey).flatMap(Self.init(rawValue:)) ?? .automatic- }-- func save(to defaults: UserDefaults) {- defaults.set(rawValue, forKey: Self.defaultsKey)- }-- private static let defaultsKey = "CodexCLI.sourceSelection"-}--/// 启动 app-server 所需的可执行文件和固定 stdio 参数-nonisolated struct AppServerCommand: Equatable {- let source: CodexCLIExecutableSource- let executablePath: String- let arguments = ["app-server", "--listen", "stdio://"]-}--/// 当前已连接 app-server 的来源信息, 设置页用它标记`当前使用`-nonisolated struct CodexCLIConnectionInfo: Equatable {- let source: CodexCLIExecutableSource- let executablePath: String+/// 当前共享 app-server 的握手信息, 不将安装路径误作服务运行来源+nonisolated struct CodexServerConnectionInfo: Equatable {+ let socketPath: String/// 来自 initialize 握手, 代表当前 app-server 进程真实运行的版本let version: String?let openedAt: Date}-/// 一次 PATH 扫描得到的安装结果, 供启动和版本检测复用-nonisolated struct CodexCLIInstallations: Equatable {+/// 一次 PATH 扫描得到的安装结果, 供版本检测使用+nonisolated struct CodexInstallations: Equatable {let globalPath: String?let bundledPath: String?-- // 与启动优先级一致: 全局优先, 回退内置- var activeSource: CodexCLIExecutableSource? {- if globalPath != nil {- return .global- }- if bundledPath != nil {- return .bundled- }- return nil- }-- func path(for source: CodexCLIExecutableSource) -> String? {- switch source {- case .global: globalPath- case .bundled: bundledPath- }- }}/// 解析真实用户环境下的 Codex 可执行文件, 避免使用 Xcode/container 的 HOME-nonisolated enum CodexCLIResolver {+nonisolated enum CodexPaths {static let bundledResourceURL = URL(fileURLWithPath: "/Applications/ChatGPT.app/Contents/Resources", isDirectory: true)- static let environment = appServerEnvironment()+ static let environment = resolvedEnvironment()private struct PackageManifest: Decodable {let entrypoint: String}- /// 从已解析的安装信息派生命令, 避免重复扫描 PATH- static func command(- from installations: CodexCLIInstallations,- source: CodexCLIExecutableSource? = nil- ) throws -> AppServerCommand {- if let source, installations.path(for: source) == nil {- throw CodexStatusError.sourceUnavailable(source)- }- guard let source = source ?? installations.activeSource,- let path = installations.path(for: source) else {- throw CodexStatusError.executableNotFound- }-- return AppServerCommand(source: source, executablePath: path)- }-/// Codex 配置目录: 优先 CODEX_HOME, 回退真实用户 HOME 下的 .codex- /// hooks.json 等配置文件统一从这里解析+ /// 共享服务 socket 位置统一从这里解析static func codexHomeDirectory(environment: [String: String] = environment) -> URL {if let codexHome = nonEmptyEnvironmentValue("CODEX_HOME", in: environment) {return URL(fileURLWithPath: codexHome, isDirectory: true)@@ -135,7 +60,7 @@ nonisolated enum CodexCLIResolver {static func resolveInstallations(environment: [String: String] = environment,bundledResourceURL: URL = bundledResourceURL- ) -> CodexCLIInstallations {+ ) -> CodexInstallations {let bundledExecutablePaths = [packageExecutablePath(in: bundledResourceURL),bundledResourceURL.appendingPathComponent("codex").path@@ -149,7 +74,7 @@ nonisolated enum CodexCLIResolver {FileManager.default.isExecutableFile(atPath: $0)} ?? (cliIsBundled ? cliPath : nil)- return CodexCLIInstallations(+ return CodexInstallations(globalPath: cliIsBundled ? nil : cliPath,bundledPath: bundledPath)@@ -166,7 +91,7 @@ nonisolated enum CodexCLIResolver {return packageDirectory.appendingPathComponent(manifest.entrypoint).path}- private static func appServerEnvironment() -> [String: String] {+ private static func resolvedEnvironment() -> [String: String] {var environment = ProcessInfo.processInfo.environmentlet homeDirectory = realUserHomeDirectory()let path = environment["PATH"] ?? ""@@ -230,7 +155,7 @@ nonisolated enum CodexCLIResolver {canonicalPath(lhs) == canonicalPath(rhs)}- /// "两个路径是否指向同一文件"的统一口径, Hook 配置匹配也复用它+ /// "两个路径是否指向同一文件"的统一口径static func canonicalPath(_ path: String, expandingTilde: Bool = false) -> String {let expandedPath = expandingTilde ? (path as NSString).expandingTildeInPath : pathreturn URL(fileURLWithPath: expandedPath)diff --git a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift b/CodexBar/Services/Codex/CodexVersionService.swiftsimilarity index 74%rename from CodexBar/Services/CodexCLI/CodexCLIVersionService.swiftrename to CodexBar/Services/Codex/CodexVersionService.swiftindex 5653f86..7208cb7 100644--- a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift+++ b/CodexBar/Services/Codex/CodexVersionService.swift@@ -3,32 +3,32 @@ import Foundationimport os/// 设置页版本区域的完整快照-nonisolated struct CodexCLIVersionSnapshot: Equatable {- let global: CodexCLIVersionItem- let bundled: CodexCLIVersionItem+nonisolated struct CodexVersionSnapshot: Equatable {+ let global: CodexVersionItem+ let bundled: CodexVersionItemlet refreshedAt: Date/// 让首次 refresh 不受节流限制- static let empty = CodexCLIVersionSnapshot(- global: CodexCLIVersionItem(source: .global),- bundled: CodexCLIVersionItem(source: .bundled),+ static let empty = CodexVersionSnapshot(+ global: CodexVersionItem(source: .global),+ bundled: CodexVersionItem(source: .bundled),refreshedAt: .distantPast)}/// 单个安装源的磁盘检测结果-nonisolated struct CodexCLIVersionItem: Equatable, Identifiable {- let source: CodexCLIExecutableSource+nonisolated struct CodexVersionItem: Equatable, Identifiable {+ let source: CodexExecutableSourcelet path: String?let version: String?let errorMessage: String?- var id: CodexCLIExecutableSource {+ var id: CodexExecutableSource {source}init(- source: CodexCLIExecutableSource,+ source: CodexExecutableSource,path: String? = nil,version: String? = nil,errorMessage: String? = nil@@ -42,49 +42,30 @@ nonisolated struct CodexCLIVersionItem: Equatable, Identifiable {var displayVersion: String {if path == nil {return String(- localized: "codex-cli.source.error.not-found",+ localized: "codex.source.error.not-found",defaultValue: "\(source.displayName)")}- return version ?? errorMessage ?? String(localized: "codex-cli.version.unknown")+ return version ?? errorMessage ?? String(localized: "codex.version.unknown")}}-/// 合并磁盘检测版本和当前 app-server 握手版本-nonisolated struct CodexCLIVersionDisplay: Equatable {- let source: CodexCLIExecutableSource- let isCurrent: Bool+/// 安装版本只描述磁盘文件, 不推断共享服务的运行来源+nonisolated struct CodexVersionDisplay: Equatable {let displayVersion: Stringlet hasVersion: Boollet path: String?- /// 当前会话尚未重连到新安装版本时显示的新版本号- let newerInstalledVersion: String?-- init(item: CodexCLIVersionItem, connection: CodexCLIConnectionInfo?) {- let isCurrent = connection?.source == item.source- // 当前来源优先显示正在运行的版本, 避免后台升级后误报已生效- let runningVersion = isCurrent ? connection?.version : nil- let version = runningVersion ?? item.version-- source = item.source- self.isCurrent = isCurrent- hasVersion = version != nil- displayVersion = version ?? item.displayVersion- path = (isCurrent ? connection?.executablePath : nil) ?? item.path-- if let runningVersion,- let installed = item.version,- CodexCLIVersionReader.isVersion(installed, newerThan: runningVersion) == true {- newerInstalledVersion = installed- } else {- newerInstalledVersion = nil- }++ init(item: CodexVersionItem) {+ displayVersion = item.displayVersion+ hasVersion = item.version != nil+ path = item.path}}/// 并发检测 Codex CLI 与 Codex App 内置 CLI 的磁盘版本-actor CodexCLIVersionService {+actor CodexVersionService {private let timeout: TimeIntervalprivate static let pipeDrainTimeout: TimeInterval = 0.25private static let maxPipeOutputBytes = 64 * 1024@@ -93,13 +74,13 @@ actor CodexCLIVersionService {self.timeout = timeout}- func fetchSnapshot() async -> CodexCLIVersionSnapshot {+ func fetchSnapshot() async -> CodexVersionSnapshot {await Self.fetchSnapshot(timeout: timeout)}- private static func fetchSnapshot(timeout: TimeInterval) async -> CodexCLIVersionSnapshot {- let environment = CodexCLIResolver.environment- let installations = CodexCLIResolver.resolveInstallations(environment: environment)+ private static func fetchSnapshot(timeout: TimeInterval) async -> CodexVersionSnapshot {+ let environment = CodexPaths.environment+ let installations = CodexPaths.resolveInstallations(environment: environment)// 两个安装源互不依赖, 并发检测避免两个超时串行叠加async let global = probeVersion(@@ -116,7 +97,7 @@ actor CodexCLIVersionService {)let (globalItem, bundledItem) = await (global, bundled)- return CodexCLIVersionSnapshot(+ return CodexVersionSnapshot(global: globalItem,bundled: bundledItem,refreshedAt: Date()@@ -124,13 +105,13 @@ actor CodexCLIVersionService {}private static func probeVersion(- source: CodexCLIExecutableSource,+ source: CodexExecutableSource,path: String?,environment: [String: String],timeout: TimeInterval- ) async -> CodexCLIVersionItem {+ ) async -> CodexVersionItem {guard let path else {- return CodexCLIVersionItem(source: source)+ return CodexVersionItem(source: source)}let deadline = Date().addingTimeInterval(timeout)@@ -200,9 +181,9 @@ actor CodexCLIVersionService {return failedVersionItem(source: source, path: path, failure: .parse)}- let displayVersion = CodexCLIVersionReader.displayVersion(from: version)+ let displayVersion = CodexVersionReader.displayVersion(from: version)logVersionDetectionCompleted(source: source, version: displayVersion)- return CodexCLIVersionItem(+ return CodexVersionItem(source: source,path: path,version: displayVersion@@ -210,7 +191,7 @@ actor CodexCLIVersionService {}private static func logVersionDetectionFailure(- source: CodexCLIExecutableSource,+ source: CodexExecutableSource,stage: String,exitCode: Int32? = nil,detail: String? = nil@@ -226,18 +207,18 @@ actor CodexCLIVersionService {fields.append("detail=\(detail)")}let details = LogFields.joined(fields)- AppLog.codexCLI.error("版本检测失败: \(details, privacy: .public)")+ AppLog.codex.error("版本检测失败: \(details, privacy: .public)")}private static func logVersionDetectionCompleted(- source: CodexCLIExecutableSource,+ source: CodexExecutableSource,version: String) {let details = LogFields.joined("source=\(source.rawValue)","version=\(version)")- AppLog.codexCLI.notice("版本检测完成: \(details, privacy: .public)")+ AppLog.codex.notice("版本检测完成: \(details, privacy: .public)")}private static func terminateTimedOutProbe(@@ -254,11 +235,11 @@ actor CodexCLIVersionService {}private static func failedVersionItem(- source: CodexCLIExecutableSource,+ source: CodexExecutableSource,path: String,failure: VersionProbeFailure- ) -> CodexCLIVersionItem {- CodexCLIVersionItem(source: source, path: path, errorMessage: failure.message)+ ) -> CodexVersionItem {+ CodexVersionItem(source: source, path: path, errorMessage: failure.message)}private static func stopCollectors(outputCollector: PipeReadBuffer, errorCollector: PipeReadBuffer) {@@ -288,13 +269,13 @@ actor CodexCLIVersionService {var message: String {switch self {case .launch:- String(localized: "codex-cli.version.launch-failed")+ String(localized: "codex.version.launch-failed")case .timeout:- String(localized: "codex-cli.version.read-timeout")+ String(localized: "codex.version.read-timeout")case .read:- String(localized: "codex-cli.version.read-failed")+ String(localized: "codex.version.read-failed")case .parse:- String(localized: "codex-cli.version.parse-failed")+ String(localized: "codex.version.parse-failed")}}}@@ -360,13 +341,13 @@ private final nonisolated class ProcessExitWaiter: Sendable {}/// CodexBar 各能力依赖的 app-server 最低版本-nonisolated enum CodexCLIMinimumVersion {- static let global = "0.145.0"- static let advancedMode = "0.153.0"+nonisolated enum CodexMinimumVersion {+ static let global = "0.160.0"+ static let activity = "0.160.0"}/// 从 ` codex --version` 的输出中提取用户可读版本号-nonisolated enum CodexCLIVersionReader {+nonisolated enum CodexVersionReader {static func displayVersion(from output: String) -> String {output.split(whereSeparator: \.isWhitespace)@@ -399,7 +380,7 @@ nonisolated enum CodexCLIVersionReader {let prerelease: [PrereleaseIdentifier]?init?(_ rawValue: String) {- let displayVersion = CodexCLIVersionReader.displayVersion(from: rawValue)+ let displayVersion = CodexVersionReader.displayVersion(from: rawValue)let versionWithoutBuild = displayVersion.split(separator: "+",maxSplits: 1,@@ -484,37 +465,4 @@ nonisolated enum CodexCLIVersionReader {}}-/// 设置页持有的版本检测状态, 负责节流和丢弃过期刷新结果-@MainActor-final class CodexCLIVersionViewModel: ObservableObject {- @Published private(set) var snapshot = CodexCLIVersionSnapshot.empty- @Published private(set) var isRefreshing = false-- /// onAppear 和 didBecomeActive 常连发- /// 版本检测需要节流以避免频繁启动子进程- private static let refreshThrottle: TimeInterval = 60-- private let service: CodexCLIVersionService- private let refreshCoordinator = RefreshTaskCoordinator()-- init(service: CodexCLIVersionService = CodexCLIVersionService()) {- self.service = service- }-- deinit {- refreshCoordinator.cancel()- }-- func refresh(force: Bool = false) {- guard !isRefreshing,- force || Date().timeIntervalSince(snapshot.refreshedAt) > Self.refreshThrottle else {- return- }-- refreshCoordinator.run(- setRefreshing: { [weak self] in self?.isRefreshing = $0 },- operation: { [service = self.service] in await service.fetchSnapshot() },- commit: { [weak self] snapshot in self?.snapshot = snapshot }- )- }-}+// 设置页持有的版本检测状态, 负责节流和丢弃过期刷新结果diff --git a/CodexBar/Services/Codex/CodexVersionViewModel.swift b/CodexBar/Services/Codex/CodexVersionViewModel.swiftnew file mode 100644index 0000000..d4a0c70--- /dev/null+++ b/CodexBar/Services/Codex/CodexVersionViewModel.swift@@ -0,0 +1,36 @@+import Combine+import Foundation++@MainActor+final class CodexVersionViewModel: ObservableObject {+ @Published private(set) var snapshot = CodexVersionSnapshot.empty+ @Published private(set) var isRefreshing = false++ /// onAppear 和 didBecomeActive 常连发+ /// 版本检测需要节流以避免频繁启动子进程+ private static let refreshThrottle: TimeInterval = 60++ private let service: CodexVersionService+ private let refreshCoordinator = RefreshTaskCoordinator()++ init(service: CodexVersionService = CodexVersionService()) {+ self.service = service+ }++ deinit {+ refreshCoordinator.cancel()+ }++ func refresh(force: Bool = false) {+ guard !isRefreshing,+ force || Date().timeIntervalSince(snapshot.refreshedAt) > Self.refreshThrottle else {+ return+ }++ refreshCoordinator.run(+ setRefreshing: { [weak self] in self?.isRefreshing = $0 },+ operation: { [service = self.service] in await service.fetchSnapshot() },+ commit: { [weak self] snapshot in self?.snapshot = snapshot }+ )+ }+}diff --git a/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift b/CodexBar/Services/Codex/PipeReadBuffer.swiftsimilarity index 51%rename from CodexBar/Services/CodexStatus/AppServerPipeReaders.swiftrename to CodexBar/Services/Codex/PipeReadBuffer.swiftindex 5e86a8e..a018b29 100644--- a/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift+++ b/CodexBar/Services/Codex/PipeReadBuffer.swift@@ -1,63 +1,24 @@import Foundation-/// app-server stdout 行读取器, 只向会话层暴露完整非空行-final nonisolated class JSONLineReader {- private let buffer: PipeReadBuffer-- init(fileHandle: FileHandle) {- buffer = PipeReadBuffer(fileHandle: fileHandle, parsesLines: true)- }-- func nextLine(timeout: TimeInterval) -> String? {- buffer.nextLine(timeout: timeout)- }-- func stop() {- buffer.stop()- }-- var isClosed: Bool {- buffer.hasNoMoreLines- }-}--/// stderr 只需要及时 drain, 避免子进程因管道填满而阻塞-final nonisolated class PipeDrain {- private let buffer: PipeReadBuffer-- init(fileHandle: FileHandle) {- buffer = PipeReadBuffer(fileHandle: fileHandle)- }-- func stop() {- buffer.stop()- }-}-/// 底层 pipe 读取桥接了 FileHandle, DispatchSourceRead 和 semaphore/// 这些非 Sendable 类型/// 对外 Sendable 边界只保留在这里/// 可变状态全部经由 lock 保护, 读事件固定在 readQueue 上执行final nonisolated class PipeReadBuffer: @unchecked Sendable {private let lock = NSLock()- private let lineSemaphore = DispatchSemaphore(value: 0)private let closedSemaphore = DispatchSemaphore(value: 0)private let fileHandle: FileHandleprivate let readQueue: DispatchQueueprivate let readQueueKey = DispatchSpecificKey<Void>()private let readSource: DispatchSourceReadprivate let maxBytes: Int- private let parsesLines: Boolprivate var collectedData = Data()- private var lineBuffer = Data()- private var lines: [String] = []private var closed = falseprivate var readSourceCancelled = false- init(fileHandle: FileHandle, maxBytes: Int = 0, parsesLines: Bool = false) {+ init(fileHandle: FileHandle, maxBytes: Int) {self.fileHandle = fileHandleself.maxBytes = max(maxBytes, 0)- self.parsesLines = parsesLinesreadQueue = DispatchQueue(label: "CodexBar.pipe-read", qos: .userInitiated)readSource = DispatchSource.makeReadSource(fileDescriptor: fileHandle.fileDescriptor,@@ -71,23 +32,6 @@ final nonisolated class PipeReadBuffer: @unchecked Sendable {readSource.resume()}- func nextLine(timeout: TimeInterval) -> String? {- if let line = popLine() {- return line- }-- if hasNoMoreLines {- return nil- }-- let result = lineSemaphore.wait(timeout: .now() + max(0, timeout))- guard result == .success else {- return nil- }-- return popLine()- }-private func readAvailableData() {let data = fileHandle.availableDataguard !data.isEmpty else {@@ -104,18 +48,6 @@ final nonisolated class PipeReadBuffer: @unchecked Sendable {if maxBytes > 0, collectedData.count < maxBytes {collectedData.append(data.prefix(maxBytes - collectedData.count))}-- guard parsesLines else {- return- }-- lineBuffer.append(data)-- while let newlineRange = lineBuffer.firstRange(of: Data([0x0A])) {- let lineData = lineBuffer[..<newlineRange.lowerBound]- lineBuffer.removeSubrange(...newlineRange.lowerBound)- appendLineIfPresent(lineData, signal: true)- }}}@@ -135,24 +67,14 @@ final nonisolated class PipeReadBuffer: @unchecked Sendable {try? fileHandle.close()let snapshot = withLock {- appendRemainingLineIfNeeded()closed = truereturn collectedData}closedSemaphore.signal()- lineSemaphore.signal()return snapshot}- func stop() {- _ = stopAndRead()- }-- var hasNoMoreLines: Bool {- withLock { closed && lines.isEmpty }- }-private func cancelReadSourceIfNeeded() {let shouldCancel = withLock {guard !readSourceCancelled else {@@ -178,43 +100,9 @@ final nonisolated class PipeReadBuffer: @unchecked Sendable {private func markClosed() {withLock {- appendRemainingLineIfNeeded()closed = true}closedSemaphore.signal()- lineSemaphore.signal()- }-- private func appendRemainingLineIfNeeded() {- guard parsesLines, !lineBuffer.isEmpty else {- return- }-- appendLineIfPresent(lineBuffer, signal: false)- lineBuffer.removeAll()- }-- private func appendLineIfPresent(_ data: Data, signal: Bool) {- guard let line = String(bytes: data, encoding: .utf8)?- .trimmingCharacters(in: .whitespacesAndNewlines),- !line.isEmpty else {- return- }-- lines.append(line)- if signal {- lineSemaphore.signal()- }- }-- private func popLine() -> String? {- withLock {- guard !lines.isEmpty else {- return nil- }-- return lines.removeFirst()- }}private func withLock<T>(_ work: () -> T) -> T {diff --git a/CodexBar/Services/CodexStatus/AppServerSession.swift b/CodexBar/Services/CodexStatus/AppServerSession.swiftdeleted file mode 100644index 40a0716..0000000--- a/CodexBar/Services/CodexStatus/AppServerSession.swift+++ /dev/null@@ -1,399 +0,0 @@-import Foundation-import os--/// 对 app-server stdio JSON-RPC 的薄封装-/// 负责日志记录, 超时和 unsupported 方法缓存-final nonisolated class AppServerSession {- let process: Process-- private typealias EncodedMessage = (data: Data, text: String)- private typealias ResponseLine = (text: String, data: Data)-- private static let writeFailureMessage = String(localized: "log.app-server.error.write-connection-closed")- private static let responseConnectionClosedMessage = String(localized: "log.app-server.error.response-connection-closed")- private static let responseTimeoutMessage = String(localized: "log.app-server.error.response-timeout")- private static let closeGracefulTimeout: TimeInterval = 1.0- private static let closeKillTimeout: TimeInterval = 0.5-- private let input: Pipe- private let lineReader: JSONLineReader- private let errorReader: PipeDrain- private let timeout: TimeInterval- private let deadline: Date?- private let logStorage: RequestLogStorage?- private var nextID = 1- private var unsupportedMethods: Set<String> = []-- private init(- process: Process,- input: Pipe,- lineReader: JSONLineReader,- errorReader: PipeDrain,- timeout: TimeInterval,- deadline: Date?- ) {- self.process = process- self.input = input- self.lineReader = lineReader- self.errorReader = errorReader- self.timeout = timeout- self.deadline = deadline- logStorage = deadline == nil ? .shared : nil- }-- static func launch(- command: AppServerCommand,- environment: [String: String],- timeout: TimeInterval,- deadline: Date? = nil,- usesCustomProxy: Bool = false- ) throws -> AppServerSession {- let process = Process()- process.executableURL = URL(fileURLWithPath: command.executablePath)- // 只覆盖本次子进程, 避免系统优先策略盖过用户在 App 中指定的代理- process.arguments = command.arguments + (usesCustomProxy ? ["-c", "features.respect_system_proxy=false"] : [])- process.environment = environment- let input = Pipe()- let output = Pipe()- let error = Pipe()- process.standardInput = input- process.standardOutput = output- process.standardError = error- let reader = JSONLineReader(fileHandle: output.fileHandleForReading)- let errorReader = PipeDrain(fileHandle: error.fileHandleForReading)- do {- try process.run()- } catch {- reader.stop()- errorReader.stop()- throw error- }- return AppServerSession(- process: process,- input: input,- lineReader: reader,- errorReader: errorReader,- timeout: timeout,- deadline: deadline- )- }-- static func redactingProxyCredentials(_ text: String) -> String {- func redact(_ value: Any) -> Any {- switch value {- case let string as String:- string.replacingOccurrences(- of: #"(?i)(https?://)[^\s/"@]+@"#,- with: "$1<redacted>@",- options: .regularExpression- )- case let object as [String: Any]: object.mapValues(redact)- case let array as [Any]: array.map(redact)- default: value- }- }-- // 先解码 JSON 转义, 才能匹配 URL 中的用户名和密码并替换为 <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) {- return result- }- return redact(text) as? String ?? text- }-- func initializeAccount() throws -> (version: String, account: AccountReadResponse) {- let result = try request(- "initialize",- params: ["clientInfo": [- "name": "codex_bar",- "title": "Codex Bar",- "version": Self.clientVersion()- ]],- as: InitializeResult.self- )- let version = Self.serverVersion(fromUserAgent: result.userAgent)- let minimum = CodexCLIMinimumVersion.global- // 版本未知不能作为明确的低版本结论, 否则 Hook 对账会误删现有配置- guard let version, let isSupported = CodexCLIVersionReader.isVersion(version, atLeast: minimum) else {- throw CodexStatusError.invalidServerResponse- }- guard isSupported else {- let error = CodexStatusError.unsupportedVersion(minimum: minimum)- if let logStorage {- let details = LogFields.joined("current=\(version)", "minimum=\(minimum)")- AppLog.codexCLI.notice("Codex 版本不支持: \(details, privacy: .public)")- logStorage.recordFailure(message: error.localizedDescription)- }- throw error- }- try notify("initialized")- let account = try request("account/read", params: ["refreshToken": false], as: AccountReadResponse.self)- guard account.account != nil else { throw CodexStatusError.notLoggedIn }- return (version, account)- }-- private static func clientVersion() -> String {- guard let version = Bundle.main.shortVersionString, !version.isEmpty else { return "1.0.0" }- return version- }-- /// userAgent 首个 token 中 "/" 之后的部分才是实际运行版本- private static func serverVersion(fromUserAgent userAgent: String?) -> String? {- guard let firstToken = userAgent?.split(separator: " ").first,- let slashIndex = firstToken.firstIndex(of: "/") else { return nil }- let version = firstToken[firstToken.index(after: slashIndex)...]- return version.isEmpty ? nil : String(version)- }-- func close() {- lineReader.stop()- errorReader.stop()- try? input.fileHandleForWriting.close()-- if process.isRunning {- switch ProcessTermination.terminate(- process,- gracefulTimeout: Self.closeGracefulTimeout,- killTimeout: Self.closeKillTimeout- ) {- case .alreadyExited, .terminated:- break- case .killed:- logStorage?.recordFailure(- message: String(localized: "log.app-server.error.exit-timeout-killed")- )- case .stillRunning:- logStorage?.recordFailure(- message: String(localized: "log.app-server.error.exit-timeout-running")- )- }- }- }-- func notify(_ method: String, params: [String: Any]? = nil) throws {- let encoded = try encodeMessage(method: method, id: nil, params: params)-- try writeEncoded(encoded) {- logStorage?.recordFailure(method: method, message: Self.writeFailureMessage)- }- logStorage?.recordRequestWithEmptyResponse(method: method, payload: encoded.text)- }-- func request<Response: Decodable>(- _ method: String,- params: [String: Any]? = nil,- as type: Response.Type- ) throws -> Response {- guard !unsupportedMethods.contains(method) else {- throw CodexStatusError.unsupportedMethod- }-- // app-server 偶发业务错误可重试一次; 传输错误由上层重建连接- do {- return try performRequestRememberingUnsupported(method, params: params, as: type)- } catch let error as CodexStatusError where deadline == nil && error.isRetriableServerError {- return try performRequestRememberingUnsupported(method, params: params, as: type)- }- }-- private func performRequestRememberingUnsupported<Response: Decodable>(- _ method: String,- params: [String: Any]? = nil,- as type: Response.Type- ) throws -> Response {- do {- return try performRequest(method, params: params, as: type)- } catch let error as CodexStatusError {- if error.isUnsupportedMethod {- unsupportedMethods.insert(method)- }- throw error- }- }-- private func performRequest<Response: Decodable>(- _ method: String,- params: [String: Any]? = nil,- as type: Response.Type- ) throws -> Response {- let id = nextID- nextID += 1- let encoded = try encodeMessage(method: method, id: id, params: params)- let token = logStorage?.beginRequest(method: method, payload: encoded.text) ?? UUID()-- try writeEncoded(encoded) {- logStorage?.failRequest(token, message: Self.writeFailureMessage)- }-- return try waitForResponse(id: id, token: token, decode: type)- }-- private func encodeMessage(method: String, id: Int?, params: [String: Any]?) throws -> EncodedMessage {- try encode(message(method: method, id: id, params: params))- }-- private func message(method: String, id: Int?, params: [String: Any]?) -> [String: Any] {- var object: [String: Any] = ["method": method]- if let id {- object["id"] = id- }- if let params {- object["params"] = params- }- return object- }-- private func encode(_ object: [String: Any]) throws -> EncodedMessage {- let data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes])- guard let text = String(bytes: data, encoding: .utf8) else {- throw EncodingError.invalidValue(- object,- .init(codingPath: [], debugDescription: "Encoded app-server JSON was not UTF-8")- )- }- return (data, text)- }-- private func writeEncoded(_ encoded: EncodedMessage, onFailure: () -> Void) throws {- do {- try writeData(encoded.data)- } catch {- onFailure()- throw CodexStatusError.serverConnectionClosed- }- }-- private func writeData(_ data: Data) throws {- var payload = data- payload.append(0x0A)- try input.fileHandleForWriting.write(contentsOf: payload)- }-- private func waitForResponse<Response: Decodable>(- id: Int,- token: UUID,- decode type: Response.Type- ) throws -> Response {- let deadline = min(deadline ?? .distantFuture, Date().addingTimeInterval(timeout))- let decoder = JSONDecoder()-- // stdout 可能混有无关日志行, 只消费 id 匹配的 JSON-RPC 响应- while Date() < deadline {- if self.deadline != nil {- try Task.checkCancellation()- }- guard let line = try nextResponseLine(- matching: id,- before: deadline,- token: token,- decoder: decoder- ) else {- continue- }-- let result = try decodeResponse(line, as: type, token: token, decoder: decoder)- logStorage?.finishRequest(token, response: Self.redactingProxyCredentials(line.text))- return result- }-- try failRequest(token, message: Self.responseTimeoutMessage, error: .serverTimeout)- }-- private func nextResponseLine(- matching id: Int,- before deadline: Date,- token: UUID,- decoder: JSONDecoder- ) throws -> ResponseLine? {- let remaining = max(0, deadline.timeIntervalSinceNow)- let wait = self.deadline == nil ? remaining : min(0.1, remaining)- guard let text = lineReader.nextLine(timeout: wait) else {- if lineReader.isClosed {- try failRequest(token, message: Self.responseConnectionClosedMessage, error: .serverConnectionClosed)- }-- return nil- }-- guard let data = text.data(using: .utf8),- let idEnvelope = try? decoder.decode(RPCIDEnvelope.self, from: data),- idEnvelope.id == id else {- return nil- }-- return (text, data)- }-- private func decodeResponse<Response: Decodable>(- _ line: ResponseLine,- as _: Response.Type,- token: UUID,- decoder: JSONDecoder- ) throws -> Response {- let envelope: RPCResponseEnvelope<Response>- do {- envelope = try decoder.decode(RPCResponseEnvelope<Response>.self, from: line.data)- } catch is RPCResponsePayloadDecodingError {- try failRequest(token, message: line.text, error: .invalidResponsePayload)- } catch {- try failRequest(token, message: line.text, error: .invalidServerResponse)- }-- if let error = envelope.error {- try failRequest(token, message: line.text, error: .serverError(Self.redactingProxyCredentials(error.message)))- }- if let result = envelope.result {- return result- }-- try failRequest(token, message: line.text, error: .invalidServerResponse)- }-- private func failRequest(_ token: UUID, message: String, error: CodexStatusError) throws -> Never {- logStorage?.failRequest(token, message: Self.redactingProxyCredentials(message))- throw error- }-}--private nonisolated struct InitializeResult: Decodable {- let userAgent: String?-}--/// 先轻量读取 id, 避免把其他请求或日志行误当成本次响应-private nonisolated struct RPCIDEnvelope: Decodable {- let id: Int?-}--/// error 与 result 合并在同一个信封里一次解码-/// result 形状不匹配时单独分类, 响应行已消费不会破坏会话边界-private nonisolated struct RPCResponseEnvelope<Response: Decodable>: Decodable {- let error: RPCError?- let result: Response?-- private enum CodingKeys: String, CodingKey {- case error- case result- }-- init(from decoder: Decoder) throws {- let container = try decoder.container(keyedBy: CodingKeys.self)- error = try container.decodeIfPresent(RPCError.self, forKey: .error)- guard error == nil else {- result = nil- return- }-- do {- result = try container.decodeIfPresent(Response.self, forKey: .result)- } catch {- throw RPCResponsePayloadDecodingError()- }- }-}--private nonisolated struct RPCResponsePayloadDecodingError: Error {}--private nonisolated struct RPCError: Decodable {- let message: String-}diff --git a/CodexBar/Services/CodexStatus/AutoResetController.swift b/CodexBar/Services/CodexStatus/AutoResetController.swiftindex b4f6075..314e397 100644--- a/CodexBar/Services/CodexStatus/AutoResetController.swift+++ b/CodexBar/Services/CodexStatus/AutoResetController.swift@@ -48,7 +48,7 @@ final class AutoResetController {private let settings: AutoResetSettingsprivate let statusViewModel: CodexStatusViewModelprivate let service: CodexStatusService- private let notificationService: CodexNotificationService+ private let notificationService: NotificationServiceprivate let keepAliveController: KeepAliveControllerprivate let wakeActivity = SystemSleepService(sleepAssertionName: "CodexBar - Automatic Reset"@@ -73,7 +73,7 @@ final class AutoResetController {settings: AutoResetSettings,statusViewModel: CodexStatusViewModel,service: CodexStatusService,- notificationService: CodexNotificationService,+ notificationService: NotificationService,keepAliveController: KeepAliveController) {self.settings = settingsdiff --git a/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift b/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swiftdeleted file mode 100644index 862e023..0000000--- a/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift+++ /dev/null@@ -1,165 +0,0 @@-import Foundation--/// config/read 的最小响应模型, 只解出 Hook 与 TUI 通知相关状态-nonisolated struct CodexConfigReadResponse: Decodable {- let config: CodexAppServerConfig-- var hooksGloballyDisabled: Bool {- (config.features?.hooks ?? config.features?.codexHooks) == false- }-- var hookTrustState: [String: String] {- config.hooks?.state?.compactMapValues(\.trustedHash) ?? [:]- }-- var areTUINotificationsEnabled: Bool {- config.tui?.notifications?.isEnabled ?? true- }-}--/// Codex 用户配置根节点, 字段保持 optional 以兼容不同 Codex 版本-nonisolated struct CodexAppServerConfig: Decodable {- let features: CodexAppServerFeatures?- let hooks: CodexAppServerHooks?- let tui: CodexAppServerTUI?-}--/// Codex 新旧配置名可能同时存在, 读取时按 hooks 优先回退 codex_hooks-nonisolated struct CodexAppServerFeatures: Decodable {- let hooks: Bool?- let codexHooks: Bool?-- private enum CodingKeys: String, CodingKey {- case hooks- case codexHooks = "codex_hooks"- }-}--/// hooks.state 里保存 hook key 到 trusted_hash 的映射-nonisolated struct CodexAppServerHooks: Decodable {- let state: [String: CodexHookTrustState]?-}--nonisolated struct CodexHookTrustState: Decodable {- let trustedHash: String?-- private enum CodingKeys: String, CodingKey {- case trustedHash = "trusted_hash"- }-}--/// tui.notifications 支持布尔值或事件名数组; 空数组等价于不发送通知-nonisolated struct CodexAppServerTUI: Decodable {- let notifications: CodexAppServerTUINotifications?-}--nonisolated enum CodexAppServerTUINotifications: Decodable {- case boolean(Bool)- case events([String])-- var isEnabled: Bool {- switch self {- case let .boolean(isEnabled):- isEnabled- case let .events(events):- !events.isEmpty- }- }-- init(from decoder: Decoder) throws {- let container = try decoder.singleValueContainer()- if let isEnabled = try? container.decode(Bool.self) {- self = .boolean(isEnabled)- return- }-- self = try .events(container.decode([String].self))- }-}--/// config/batchWrite 的单条编辑, 直接转成 app-server 期望的 JSON 对象-nonisolated struct CodexConfigBatchEdit: Sendable {- let keyPath: String- let mergeStrategy: String-- private let value: Value-- init(- keyPath: String,- value: Bool,- mergeStrategy: String- ) {- self.init(keyPath: keyPath, value: .bool(value), mergeStrategy: mergeStrategy)- }-- init(- keyPath: String,- value: [String: [String: String]],- mergeStrategy: String- ) {- self.init(keyPath: keyPath, value: .stringMap(value), mergeStrategy: mergeStrategy)- }-- private init(- keyPath: String,- value: Value,- mergeStrategy: String- ) {- self.keyPath = keyPath- self.value = value- self.mergeStrategy = mergeStrategy- }-- var appServerObject: [String: Any] {- [- "keyPath": keyPath,- "value": value.appServerValue,- "mergeStrategy": mergeStrategy- ]- }-- private enum Value: Sendable {- case bool(Bool)- case stringMap([String: [String: String]])-- var appServerValue: Any {- switch self {- case let .bool(value):- value- case let .stringMap(value):- value- }- }- }-}--nonisolated struct CodexConfigWriteResponse: Decodable {}--/// hooks/list 的响应列表按 cwd 分组-nonisolated struct CodexHooksListResponse: Decodable {- let data: [CodexHooksListEntry]-}--/// 单个 cwd 下 Codex 解析出的 Hook 状态-nonisolated struct CodexHooksListEntry: Decodable {- let cwd: String- let hooks: [CodexHookMetadata]- let warnings: [String]- let errors: [CodexHookErrorInfo]-}--/// hooks/list 返回的单个 Hook 元数据, key/currentHash 用于自动写入信任状态-nonisolated struct CodexHookMetadata: Decodable {- let eventName: String- let command: String?- let enabled: Bool- let sourcePath: String- let trustStatus: String- let key: String?- let currentHash: String?-}--nonisolated struct CodexHookErrorInfo: Decodable {- let path: String- let message: String-}diff --git a/CodexBar/Services/CodexStatus/CodexProxyConnectionTester.swift b/CodexBar/Services/CodexStatus/CodexProxyConnectionTester.swiftdeleted file mode 100644index a50ee55..0000000--- a/CodexBar/Services/CodexStatus/CodexProxyConnectionTester.swift+++ /dev/null@@ -1,25 +0,0 @@-import Foundation--/// 独立于正式连接的探测, 所有请求共享截止时间且不写入额度交互日志-nonisolated enum CodexProxyConnectionTester {- static func test(- configuration: CodexProxyConfiguration,- password: String,- source: CodexCLISourceSelection- ) throws {- try Task.checkCancellation()- let deadline = Date().addingTimeInterval(8)- var configuration = configuration- configuration.isEnabled = true- let environment = try configuration.environment(overriding: CodexCLIResolver.environment, password: password)- let command = try CodexCLIResolver.command(- from: CodexCLIResolver.resolveInstallations(),- source: source.source- )- let session = try AppServerSession.launch(command: command, environment: environment, timeout: 8, deadline: deadline, usesCustomProxy: true)- defer { session.close() }- _ = try session.initializeAccount()- _ = try session.request("account/rateLimits/read", as: AccountRateLimitsResponse.self)- try Task.checkCancellation()- }-}diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swiftindex 7e8efbd..f34eb1b 100644--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift@@ -135,56 +135,14 @@ private nonisolated extension ReadResult {}}-/// 维持一条 codex app-server stdio 会话, 复用失败后按需重建+/// 独立持有账户连接, 与活动监听连接同一个共享服务actor CodexStatusService {- private static let requestTimeout: TimeInterval = 20- // 定期回收连接, 让后台升级后的 codex 二进制有机会生效- private static let connectionMaxAge: TimeInterval = 1 * 60 * 60- private static let environment = CodexCLIResolver.environment-private var connection: AppServerConnection?private var supplementalDataCache = SupplementalDataCache()- private var lastResolvedSource: CodexCLIExecutableSource?- private let defaults: UserDefaults- private var sourceSelection: CodexCLISourceSelection-- /// app-server 退出后继续写管道会触发 SIGPIPE- /// 忽略信号, 让 write 抛错后走重建- private static let ignoreBrokenPipeSignal: Void = {- signal(SIGPIPE, SIG_IGN)- }()-- init(defaults: UserDefaults = .standard) {- self.defaults = defaults- sourceSelection = CodexCLISourceSelection.load(from: defaults)- _ = Self.ignoreBrokenPipeSignal- }-- func applyProxy(_ configuration: CodexProxyConfiguration?, password: String) throws {- try CodexProxyStore.save(configuration, password: password, to: defaults)- // actor 内提交设置并回收旧进程, 后续所有业务入口统一按新配置建立连接- teardownConnection()- supplementalDataCache = SupplementalDataCache()- }+ private let socketURL: URL- private func openConfiguredConnection(command: AppServerCommand) throws -> ConnectionResolution {- let stored = try CodexProxyStore.load(from: defaults)- let configuration = stored?.configuration- let usesCustomProxy = configuration?.isEnabled == true- let environment: [String: String] = if let configuration, usesCustomProxy {- try configuration.environment(- overriding: Self.environment,- password: stored?.password ?? ""- )- } else {- Self.environment- }- return Self.openConnection(- command: command,- environment: environment,- timeout: Self.requestTimeout,- usesCustomProxy: usesCustomProxy- )+ init(socketURL: URL = AppServerActivityReader.defaultSocketURL) {+ self.socketURL = socketURL}// MARK: - 对外入口@@ -195,79 +153,43 @@ actor CodexStatusService {return CodexFetchResult(outcome: outcome, trace: trace)}- func currentConnectionInfo() async -> CodexCLIConnectionInfo? {- guard let connection, connection.session.process.isRunning else {+ func currentConnectionInfo() async -> CodexServerConnectionInfo? {+ guard let connection, connection.session.isOpen else {return nil}- return connection.commandInfo- }-- func currentSourceSelection() -> CodexCLISourceSelection {- sourceSelection+ return connection.connectionInfo}/// 需要以实际运行版本做能力检查时建立或复用连接- func readyConnectionInfo() throws -> CodexCLIConnectionInfo {- try readyConnection().commandInfo+ func readyConnectionInfo() throws -> CodexServerConnectionInfo {+ try readyConnection().connectionInfo}- /// 重连先关闭旧会话, 新连接失败时保持断开- func reconnect(- selection: CodexCLISourceSelection? = nil,- minimumVersion: String- ) throws -> CodexCLIConnectionInfo {+ /// 只重建当前客户端连接, 不重启共享服务+ func reconnect(minimumVersion: String) throws -> CodexServerConnectionInfo {teardownConnection()supplementalDataCache = SupplementalDataCache()- let requestedSelection = selection ?? sourceSelection- let command = try CodexCLIResolver.command(- from: CodexCLIResolver.resolveInstallations(environment: Self.environment),- source: requestedSelection.source- )- let resolution = try openConfiguredConnection(command: command)- switch resolution {- case let .ready(candidate, _):- guard let version = candidate.commandInfo.version,- CodexCLIVersionReader.isVersion(version, atLeast: minimumVersion) == true else {- candidate.close()- throw CodexStatusError.unsupportedVersion(minimum: minimumVersion)- }-- connection = candidate- sourceSelection = requestedSelection- sourceSelection.save(to: defaults)- lastResolvedSource = command.source- AppLog.codexCLI.notice("Codex 连接已切换: source=\(command.source.rawValue, privacy: .public)")- return candidate.commandInfo- case .notLoggedIn:- throw CodexStatusError.notLoggedIn- case let .unsupportedVersion(minimum):- throw CodexStatusError.unsupportedVersion(minimum: minimum)- case .initializationFailed:- throw CodexStatusError.serverConnectionClosed+ let candidate = try readyConnection()+ guard let version = candidate.connectionInfo.version,+ CodexVersionReader.isVersion(version, atLeast: minimumVersion) == true else {+ teardownConnection()+ throw CodexStatusError.unsupportedVersion(minimum: minimumVersion)}+ return candidate.connectionInfo}- func readCodexConfig() async throws -> CodexConfigReadResponse {+ func readCodexConfig() async throws -> ConfigReadResponse {let connection = try readyConnection()return try connection.session.request("config/read",params: ["includeLayers": false],- as: CodexConfigReadResponse.self- )- }-- func listCodexHooks(cwds: [String]) async throws -> CodexHooksListResponse {- let connection = try readyConnection()- return try connection.session.request(- "hooks/list",- params: ["cwds": cwds],- as: CodexHooksListResponse.self+ as: ConfigReadResponse.self)}/// 设置写入统一走批量接口, 让 Codex 负责刷新用户配置- func writeCodexConfigBatch(edits: [CodexConfigBatchEdit]) async throws -> CodexConfigWriteResponse {+ func writeCodexConfigBatch(edits: [ConfigBatchEdit]) async throws -> ConfigWriteResponse {let connection = try readyConnection()return try connection.session.request("config/batchWrite",@@ -275,7 +197,7 @@ actor CodexStatusService {"edits": edits.map(\.appServerObject),"reloadUserConfig": true],- as: CodexConfigWriteResponse.self+ as: ConfigWriteResponse.self)}@@ -326,7 +248,7 @@ actor CodexStatusService {}/// 复用连接出现传输故障时只重建重试一次- /// 避免故障状态下反复拉起进程+ /// 避免故障状态下反复建立连接private func resolveOutcome(allowRebuild: Bool,trace: inout CodexFetchTrace@@ -384,7 +306,7 @@ actor CodexStatusService {}/// 自动重置链路在传输故障后重建一次连接- /// 每次逻辑操作最多刷新一次认证, 不在业务错误上创建新进程+ /// 每次逻辑操作最多刷新一次认证, 不在业务错误上重建连接private func withAutoResetConnection<Value>(_ operation: (AppServerConnection) throws -> Value) throws -> Value {@@ -430,63 +352,13 @@ actor CodexStatusService {}private func ensureConnection() -> ConnectionResolution {- if let connection, connection.session.process.isRunning,- Date().timeIntervalSince(connection.openedAt) < Self.connectionMaxAge {+ if let connection, connection.session.isOpen {return .ready(connection: connection, reused: true)}-- // 只记失效这个事实: 下面还可能解析不到 codex 或者开不起来- // 收尾由额度刷新那条的 conn=new 承载, 不必在这里再记一条- if let connection {- let reason = connection.session.process.isRunning ? "expired" : "processExited"- AppLog.app.notice("codex 连接已失效: reason=\(reason, privacy: .public)")- }teardownConnection()-- let command: AppServerCommand- do {- command = try CodexCLIResolver.command(- from: CodexCLIResolver.resolveInstallations(environment: Self.environment),- source: sourceSelection.source- )- } catch {- let details = LogFields.joined(- "stage=resolveCLI",- "detail=\(error.localizedDescription)"- )- AppLog.app.error("codex 连接失败: \(details, privacy: .public)")- RequestLogStorage.shared.recordFailure(message: error.localizedDescription)- return .initializationFailed(message: error.localizedDescription)- }-- // 可执行文件路径含用户名, 只记来源分类- // 每次新建连接都重新解析, 换了来源才值得记一条- if lastResolvedSource != command.source {- lastResolvedSource = command.source- AppLog.codexCLI.notice(- "codex 路径已解析: source=\(command.source.rawValue, privacy: .public)"- )- }-- let resolution: ConnectionResolution- do {- resolution = try openConfiguredConnection(command: command)- } catch let error as CodexProxyError {- AppLog.settings.error("\(error.localizedDescription, privacy: .public)")- return .initializationFailed(message: error.localizedDescription)- } catch {- RequestLogStorage.shared.recordFailure(message: error.localizedDescription)- return .initializationFailed(message: error.localizedDescription)- }- switch resolution {- case let .ready(newConnection, _):+ let resolution = Self.openConnection(socketURL: socketURL)+ if case let .ready(newConnection, _) = resolution {connection = newConnection- case .unsupportedVersion:- AppLog.app.error("codex 连接失败: stage=version")- case .initializationFailed:- AppLog.app.error("codex 连接失败: stage=open")- case .notLoggedIn:- break}return resolution}@@ -730,49 +602,26 @@ actor CodexStatusService {}}- /// 初始化失败与未登录在这里分流; 两者都不复用本次新建的进程- private static func openConnection(- command: AppServerCommand,- environment: [String: String],- timeout: TimeInterval,- usesCustomProxy: Bool- ) -> ConnectionResolution {- let session: AppServerSession+ /// 初始化失败与未登录在这里分流; 两者都关闭本次新建的连接+ private static func openConnection(socketURL: URL) -> ConnectionResolution {do {- session = try AppServerSession.launch(- command: command,- environment: environment,- timeout: timeout,- usesCustomProxy: usesCustomProxy- )+ let session = try AccountSession(socketURL: socketURL)+ return initializeConnection(session: session, socketURL: socketURL, openedAt: Date())} catch {- RequestLogStorage.shared.recordFailure(- message: String(- localized: "log.app-server.error.launch-failed",- defaultValue: "\(error.localizedDescription)"- )- )- return .initializationFailed(message: CodexStatusError.serverConnectionClosed.localizedDescription)+ AppServerLogStore.shared.recordFailure(message: error.localizedDescription)+ return .initializationFailed(message: String(localized: "codex-status.daemon.error.unavailable"))}- let openedAt = Date()-- return initializeConnection(- session: session,- command: command,- openedAt: openedAt- )}private static func initializeConnection(- session: AppServerSession,- command: AppServerCommand,+ session: AccountSession,+ socketURL: URL,openedAt: Date) -> ConnectionResolution {do {let initialized = try session.initializeAccount()- let commandInfo = CodexCLIConnectionInfo(- source: command.source,- executablePath: command.executablePath,+ let connectionInfo = CodexServerConnectionInfo(+ socketPath: socketURL.path,version: initialized.version,openedAt: openedAt)@@ -781,7 +630,7 @@ actor CodexStatusService {connection: AppServerConnection(session: session,accountResponse: initialized.account,- commandInfo: commandInfo+ connectionInfo: connectionInfo),reused: false)@@ -793,7 +642,7 @@ actor CodexStatusService {return .unsupportedVersion(minimum: minimum)} catch {// app-server 链路的细节按既有分工进日志窗口, 不重复写系统日志- RequestLogStorage.shared.recordFailure(+ AppServerLogStore.shared.recordFailure(message: String(localized: "log.app-server.error.initialization-failed",defaultValue: "\(error.localizedDescription)"@@ -805,25 +654,25 @@ actor CodexStatusService {}}-/// 持有 stdio 会话及初始化阶段读取到的账号/版本信息+/// 持有共享服务客户端连接及账户和运行版本信息private final nonisolated class AppServerConnection {- let session: AppServerSession- let commandInfo: CodexCLIConnectionInfo+ let session: AccountSession+ let connectionInfo: CodexServerConnectionInfovar accountResponse: AccountReadResponseprivate var isClosed = falsevar openedAt: Date {- commandInfo.openedAt+ connectionInfo.openedAt}init(- session: AppServerSession,+ session: AccountSession,accountResponse: AccountReadResponse,- commandInfo: CodexCLIConnectionInfo+ connectionInfo: CodexServerConnectionInfo) {self.session = sessionself.accountResponse = accountResponse- self.commandInfo = commandInfo+ self.connectionInfo = connectionInfo}deinit {diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swiftindex 29270e2..7c2a05a 100644--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift@@ -48,20 +48,15 @@ final class CodexStatusViewModel: ObservableObject {@Published private(set) var snapshot: CodexQuotaSnapshot?@Published private(set) var isRefreshing = false@Published private(set) var loadState: CodexLoadState = .loading- @Published private(set) var codexConnectionInfo: CodexCLIConnectionInfo?+ @Published private(set) var codexConnectionInfo: CodexServerConnectionInfo?@Published private(set) var connectionErrorMessage: String?- @Published private(set) var unavailableConnectionSource: CodexCLIExecutableSource?- @Published private(set) var codexSourceSelection = CodexCLISourceSelection.automatic- @Published private(set) var pendingCodexSourceSelection: CodexCLISourceSelection?@Published private(set) var autoRefreshCountdownStartedAt: Date?@Published private(set) var dataUpdateInterval: DataUpdateInterval/// 统计维护挂在额度刷新完成事件上, 由它继承本次刷新的触发来源private(set) var lastRefreshTrigger: LogTrigger = .launch- var isReconnecting: Bool {- pendingCodexSourceSelection != nil- }+ @Published private(set) var isReconnecting = falsevar autoRefreshInterval: TimeInterval {dataUpdateInterval.duration@@ -151,8 +146,7 @@ final class CodexStatusViewModel: ObservableObject {operation: { [service = self.service] inawait (fetch: service.fetchOutcome(),- connectionInfo: service.currentConnectionInfo(),- selection: service.currentSourceSelection()+ connectionInfo: service.currentConnectionInfo())},commit: { [weak self] result in@@ -183,9 +177,7 @@ final class CodexStatusViewModel: ObservableObject {elapsed: duration.elapsed)codexConnectionInfo = result.connectionInfo- codexSourceSelection = result.selectionconnectionErrorMessage = result.fetch.outcome.connectionErrorMessage- unavailableConnectionSource = nilautoRefreshCountdownStartedAt = Date()})@@ -281,33 +273,27 @@ final class CodexStatusViewModel: ObservableObject {let generation = connectionInfoGenerationTask {let info = await service.currentConnectionInfo()- let selection = await service.currentSourceSelection()guard generation == connectionInfoGeneration, !isReconnecting else {return}codexConnectionInfo = info- codexSourceSelection = selection}}- func reconnectCodex(- selection: CodexCLISourceSelection? = nil,- requiresAdvancedMode: Bool- ) async -> Bool {+ func reconnectCodex() async -> Bool {guard !isRefreshing, !isReconnecting else {return false}- pendingCodexSourceSelection = selection ?? codexSourceSelection+ isReconnecting = truecodexConnectionInfo = nilsnapshot = nilloadState = .loadingconnectionErrorMessage = nil- unavailableConnectionSource = nilconnectionInfoGeneration &+= 1var didReconnect = falsedefer {- pendingCodexSourceSelection = nil+ isReconnecting = falselet trigger = pendingForcedRefreshTriggerpendingForcedRefreshTrigger = nilif didReconnect || trigger != nil {@@ -317,10 +303,8 @@ final class CodexStatusViewModel: ObservableObject {do {codexConnectionInfo = try await service.reconnect(- selection: selection,- minimumVersion: requiresAdvancedMode ? CodexCLIMinimumVersion.advancedMode : CodexCLIMinimumVersion.global+ minimumVersion: CodexMinimumVersion.activity)- codexSourceSelection = await service.currentSourceSelection()didReconnect = truereturn true} catch {@@ -329,14 +313,7 @@ final class CodexStatusViewModel: ObservableObject {case let CodexStatusError.unsupportedVersion(minimum): .unsupportedVersion(minimum: minimum)default: .initializationFailed}- if case let CodexStatusError.sourceUnavailable(source) = error {- unavailableConnectionSource = source- } else {- connectionErrorMessage = error.localizedDescription- }- if let error = error as? CodexProxyError {- AppLog.settings.error("\(error.localizedDescription, privacy: .public)")- }+ connectionErrorMessage = error.localizedDescriptionreturn false}}diff --git a/CodexBar/Services/CodexStatus/RequestLog.swift b/CodexBar/Services/CodexStatus/RequestLog.swiftdeleted file mode 100644index 172c33b..0000000--- a/CodexBar/Services/CodexStatus/RequestLog.swift+++ /dev/null@@ -1,213 +0,0 @@-import Combine-import Foundation-import os--/// JSON-RPC 交互日志: 带 id 的请求先记录为进行-/// 响应或错误到达后回填到同一条-/// `initialized` 这类无 id 请求没有响应可等, 单独记录为空响应-nonisolated struct RequestLogEntry: Identifiable, Equatable {- enum Kind {- case pending- case response- case failure- case emptyResponse- }-- let id: UUID- let requestedAt: Date- var respondedAt: Date?- var kind: Kind- let method: String?- let request: String?- var detail: String?-- static let summaryPreviewLength = 160- static let expandedInlinePreviewLength = 260-- static func preview(_ text: String, limit: Int) -> String {- guard limit > 0,- let endIndex = text.index(text.startIndex, offsetBy: limit, limitedBy: text.endIndex),- endIndex < text.endIndex else {- return text- }-- return String(text[..<endIndex]) + "..."- }-- static func singleLinePreview(_ text: String, limit: Int) -> String {- let firstLine = text.components(separatedBy: .newlines).first ?? ""- let normalizedText = firstLine- .components(separatedBy: .whitespaces)- .filter { !$0.isEmpty }- .joined(separator: " ")- let displayText = preview(normalizedText, limit: limit)-- guard firstLine != text, !displayText.hasSuffix("...") else {- return displayText- }-- return displayText + "..."- }-}--/// 常驻日志存储, 允许后台请求路径同步写入并立即拿到请求 token-final nonisolated class RequestLogStorage: Sendable {- static let shared = RequestLogStorage()-- /// 环形上限避免长时间运行后日志无限增长- private static let capacity = 500-- /// 最新在前, 既方便渲染也让刚发出的请求更快被回填- private let storage = OSAllocatedUnfairLock(initialState: [RequestLogEntry]())-- var entries: [RequestLogEntry] {- storage.withLock { $0 }- }-- private init() {}-- /// payload 由 AppServerSession 用相同的稳定序列化选项生成, 无需再做一轮归一化- func beginRequest(method: String, payload: String) -> UUID {- let id = UUID()- append(- RequestLogEntry(- id: id,- requestedAt: Date(),- respondedAt: nil,- kind: .pending,- method: method,- request: payload,- detail: nil- )- )- return id- }-- func finishRequest(_ id: UUID, response: String) {- update(id) { entry in- entry.kind = .response- entry.detail = Self.normalized(response)- entry.respondedAt = Date()- }- }-- func failRequest(_ id: UUID, message: String) {- update(id) { entry in- entry.kind = .failure- entry.detail = Self.normalized(message)- entry.respondedAt = Date()- }- }-- func recordRequestWithEmptyResponse(method: String, payload: String) {- append(- RequestLogEntry(- id: UUID(),- requestedAt: Date(),- respondedAt: nil,- kind: .emptyResponse,- method: method,- request: payload,- detail: ""- )- )- }-- func recordFailure(method: String? = nil, message: String) {- append(- RequestLogEntry(- id: UUID(),- requestedAt: Date(),- respondedAt: nil,- kind: .failure,- method: method,- request: nil,- detail: Self.normalized(message)- )- )- }-- func clear() {- storage.withLock {- $0.removeAll()- }-- notifyChange()- }-- private func append(_ entry: RequestLogEntry) {- storage.withLock {- $0.insert(entry, at: 0)- if $0.count > Self.capacity {- $0.removeLast($0.count - Self.capacity)- }- }-- notifyChange()- }-- private func update(_ id: UUID, _ mutate: @Sendable (inout RequestLogEntry) -> Void) {- let didUpdate = storage.withLock {- guard let index = $0.firstIndex(where: { $0.id == id }) else {- return false- }- mutate(&$0[index])- return true- }-- guard didUpdate else {- return- }-- notifyChange()- }-- private func notifyChange() {- Task { @MainActor in- RequestLogStore.shared.reloadFromStorage()- }- }-- /// 合法 JSON 重新序列化为稳定, 未转义斜杠的日志文本- /// 非 JSON 错误消息保持原样- private static func normalized(_ text: String) -> String {- jsonNormalized(text) ?? text- }-- private static func jsonNormalized(_ text: String) -> String? {- guard let data = text.data(using: .utf8),- let object = try? JSONSerialization.jsonObject(with: data),- JSONSerialization.isValidJSONObject(object),- let output = try? JSONSerialization.data(- withJSONObject: object,- options: [.sortedKeys, .withoutEscapingSlashes]- ) else {- return nil- }-- return String(bytes: output, encoding: .utf8)- }-}--/// SwiftUI 观察层只负责在主线程发布 storage 快照-@MainActor-final class RequestLogStore: ObservableObject {- static let shared = RequestLogStore()-- @Published private(set) var entries: [RequestLogEntry]-- private let storage: RequestLogStorage-- init(storage: RequestLogStorage = .shared) {- self.storage = storage- entries = storage.entries- }-- func clear() {- storage.clear()- }-- fileprivate func reloadFromStorage() {- entries = storage.entries- }-}diff --git a/CodexBar/Services/History/ActivityRecorder.swift b/CodexBar/Services/History/ActivityRecorder.swiftnew file mode 100644index 0000000..3725aec--- /dev/null+++ b/CodexBar/Services/History/ActivityRecorder.swift@@ -0,0 +1,20 @@+import Foundation++/// 采集器只写已观察到的活动, 初始快照不进入历史+actor ActivityRecorder {+ private let directoryURL: URL+ private var journal = AppServerEventJournal()++ init(directoryURL: URL = HistoryStorage.directoryURL()) {+ self.directoryURL = directoryURL+ }++ func record(event: ActivityRecord) throws {+ guard event.id != nil else { return }+ try HistoryStorage.withExclusiveLock(in: directoryURL) {+ try journal.append(AppServerEventRecord(activity: event), in: directoryURL)+ }+ }+}++// 调用方持有 events.lock, 活动与 Token 共用追加和维护状态事务diff --git a/CodexBar/Services/History/AppServerEventJournal.swift b/CodexBar/Services/History/AppServerEventJournal.swiftnew file mode 100644index 0000000..14f8ce8--- /dev/null+++ b/CodexBar/Services/History/AppServerEventJournal.swift@@ -0,0 +1,151 @@+import Foundation++nonisolated struct AppServerEventJournal {+ private var identities: [String: Set<String>] = [:]+ private var sizes: [String: UInt64] = [:]+ private var inodes: [String: UInt64] = [:]++ mutating func append(_ entry: AppServerEventRecord, in directoryURL: URL) throws {+ let dateKey = HistoryStorage.dateKey(for: entry.activity?.timestamp ?? entry.recordedAt)+ let eventsDirectory = directoryURL.appendingPathComponent("Events")+ let eventLogURL = HistoryStorage.eventLogURL(for: dateKey, in: eventsDirectory)+ let maintenanceURL = HistoryStorage.maintenanceURL(in: directoryURL)+ var maintenanceState = try JSONFileStorage.load(HistoryMaintenanceState.self, from: maintenanceURL) ?? HistoryMaintenanceState()+ let existingStat = HistoryStorage.fileStat(at: eventLogURL)+ var stateChanged = false+ if entry.deduplicationID != nil, sizes[dateKey] != existingStat?.size || inodes[dateKey] != existingStat?.identifier {+ let offset = sizes[dateKey].flatMap { size in+ inodes[dateKey] == existingStat?.identifier && size < (existingStat?.size ?? 0) ? size : nil+ } ?? 0+ var previous = offset > 0 ? identities[dateKey] ?? [] : []+ if existingStat != nil {+ try Self.read(at: eventLogURL, from: offset) { entry in+ if let id = entry.deduplicationID {+ previous.insert(id)+ }+ }+ }+ identities[dateKey] = previous+ }+ if let identity = entry.deduplicationID, identities[dateKey]?.contains(identity) == true {+ if maintenanceState.markPending(dateKey) {+ try JSONFileStorage.save(maintenanceState, to: maintenanceURL)+ }+ return+ }++ if let existingStat {+ let day = maintenanceState.days[dateKey]+ let identifierChanged = day?.fileIdentifier != nil+ && day?.fileIdentifier != existingStat.identifier+ let fileShrank = day.map { existingStat.size < $0.offset } ?? false++ if identifierChanged || fileShrank {+ maintenanceState.startNewGeneration(+ for: dateKey,+ startedEmpty: existingStat.size == 0,+ fileIdentifier: existingStat.identifier+ )+ stateChanged = true+ } else {+ stateChanged = maintenanceState.ensureGenerationID(+ for: dateKey,+ fileIdentifier: existingStat.identifier+ )+ }+ } else {+ maintenanceState.startNewGeneration(+ for: dateKey,+ startedEmpty: true,+ fileIdentifier: nil+ )+ stateChanged = true+ }++ try append(entry.jsonLineData(), to: eventLogURL)+ if let identity = entry.deduplicationID {+ identities[dateKey, default: []].insert(identity)+ }+ sizes[dateKey] = entry.deduplicationID != nil ? HistoryStorage.fileSize(at: eventLogURL) : nil+ inodes[dateKey] = HistoryStorage.fileStat(at: eventLogURL)?.identifier+ let oldest = HistoryStorage.dateKey(for: Date().addingTimeInterval(-2 * 86400))+ identities = identities.filter { $0.key >= oldest }+ sizes = sizes.filter { $0.key >= oldest }+ inodes = inodes.filter { $0.key >= oldest }++ if var day = maintenanceState.days[dateKey],+ day.fileIdentifier == nil,+ let identifier = HistoryStorage.fileStat(at: eventLogURL)?.identifier {+ day.fileIdentifier = identifier+ maintenanceState.days[dateKey] = day+ stateChanged = true+ }++ // 稳态下当天早已 pending, 跳过无变化的全量重写以缩短持锁时间+ if maintenanceState.markPending(dateKey) || stateChanged {+ try JSONFileStorage.save(maintenanceState, to: maintenanceURL)+ }+ }++ /// 分块扫描并限制单行大小, 截断或损坏的行不影响其他完整记录+ static func read(at url: URL, from offset: UInt64 = 0, onInvalidLine: (() -> Void)? = nil, consume: (AppServerEventRecord) throws -> Void) throws {+ let handle = try FileHandle(forReadingFrom: url)+ defer { try? handle.close() }+ try handle.seek(toOffset: offset)+ var buffer = Data()+ var droppingLine = false+ let maximumLineSize = 1024 * 1024+ while let chunk = try handle.read(upToCount: 64 * 1024), !chunk.isEmpty {+ buffer.append(chunk)+ while let newline = buffer.firstIndex(of: JSONLines.newlineByte) {+ let line = Data(buffer[..<newline])+ if !droppingLine, line.count <= maximumLineSize, let entry = try? AppServerEventRecord.decode(from: line) {+ try consume(entry)+ } else if !droppingLine, !line.isEmpty {+ onInvalidLine?()+ }+ droppingLine = false+ buffer.removeSubrange(...newline)+ }+ if buffer.count > maximumLineSize || droppingLine {+ if !droppingLine {+ onInvalidLine?()+ }+ buffer.removeAll(keepingCapacity: true)+ droppingLine = true+ }+ }+ if !droppingLine, let entry = try? AppServerEventRecord.decode(from: buffer) {+ try consume(entry)+ } else if !droppingLine, !buffer.isEmpty {+ onInvalidLine?()+ }+ }++ private func append(_ data: Data, to url: URL) throws {+ try FileManager.default.createDirectory(+ at: url.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )++ if !FileManager.default.fileExists(atPath: url.path) {+ FileManager.default.createFile(atPath: url.path, contents: nil, attributes: [.posixPermissions: 0o600])+ }++ let fileHandle = try FileHandle(forUpdating: url)+ defer {+ try? fileHandle.close()+ }++ let length = try fileHandle.seekToEnd()+ if length > 0 {+ try fileHandle.seek(toOffset: length - 1)+ let last = try fileHandle.read(upToCount: 1)+ try fileHandle.seekToEnd()+ if last != Data([0x0A]) {+ try fileHandle.write(contentsOf: Data([0x0A]))+ }+ }+ try fileHandle.write(contentsOf: data)+ }+}diff --git a/CodexBar/Services/History/HistoryMaintenance.swift b/CodexBar/Services/History/HistoryMaintenance.swiftnew file mode 100644index 0000000..fbcb825--- /dev/null+++ b/CodexBar/Services/History/HistoryMaintenance.swift@@ -0,0 +1,202 @@+import Foundation++/// State/aggregation.json 的全局状态, pending 表示可增量, dirty 表示需全量重建+nonisolated struct HistoryMaintenanceState: Codable, Equatable {+ private enum CodingKeys: String, CodingKey {+ case version+ case pending+ case dirty+ case days+ }++ /// 原始事件到每日聚合的算法版本, 变化时统一从原始 JSONL 重建+ static let currentVersion = 2++ var version: Int+ var pending: [String]+ var dirty: [String]+ var days: [String: HistoryDayMaintenanceState]++ init(+ version: Int = Self.currentVersion,+ pending: [String] = [],+ dirty: [String] = [],+ days: [String: HistoryDayMaintenanceState] = [:]+ ) {+ self.version = version+ self.pending = Self.normalizedDates(pending)+ self.dirty = Self.normalizedDates(dirty)+ self.days = days+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ // 缺少版本只能说明来源更旧, 不能乐观视为当前算法+ version = try container.decodeIfPresent(Int.self, forKey: .version) ?? 0+ pending = try Self.normalizedDates(container.decodeIfPresent([String].self, forKey: .pending) ?? [])+ dirty = try Self.normalizedDates(container.decodeIfPresent([String].self, forKey: .dirty) ?? [])+ days = try container.decodeIfPresent([String: HistoryDayMaintenanceState].self, forKey: .days) ?? [:]+ }++ /// 返回状态是否有实际变化, 便于调用方跳过无谓的落盘+ @discardableResult+ mutating func markPending(_ dateKey: String) -> Bool {+ let newPending = Self.inserting(dateKey, into: pending)+ let changed = newPending != pending || days[dateKey] == nil+ pending = newPending+ ensureDayState(for: dateKey)+ return changed+ }++ @discardableResult+ mutating func markDirty(_ dateKey: String) -> Bool {+ markDirty(contentsOf: [dateKey])+ }++ /// 批量标脏一次性归一化, 避免逐个插入的重复排序与校验+ @discardableResult+ mutating func markDirty(contentsOf dateKeys: [String]) -> Bool {+ guard !dateKeys.isEmpty else {+ return false+ }++ let newDirty = Self.normalizedDates(dirty + dateKeys)+ var changed = newDirty != dirty+ dirty = newDirty++ for dateKey in dateKeys where days[dateKey] == nil {+ days[dateKey] = HistoryDayMaintenanceState()+ changed = true+ }++ return changed+ }++ mutating func removePending(_ dateKey: String) {+ pending.removeAll { $0 == dateKey }+ }++ mutating func removeDirty(_ dateKey: String) {+ dirty.removeAll { $0 == dateKey }+ }++ mutating func remove(_ dateKey: String) {+ removePending(dateKey)+ removeDirty(dateKey)+ days.removeValue(forKey: dateKey)+ }++ @discardableResult+ mutating func ensureGenerationID(+ for dateKey: String,+ fileIdentifier: UInt64?+ ) -> Bool {+ var day = days[dateKey] ?? HistoryDayMaintenanceState()+ var changed = false++ if day.generationID == nil {+ day.generationID = Self.makeGenerationID()+ day.generationStartedEmpty = false+ changed = true+ }+ if day.fileIdentifier == nil, let fileIdentifier {+ day.fileIdentifier = fileIdentifier+ changed = true+ }++ days[dateKey] = day+ return changed+ }++ mutating func startNewGeneration(+ for dateKey: String,+ startedEmpty: Bool,+ fileIdentifier: UInt64?+ ) {+ days[dateKey] = HistoryDayMaintenanceState(+ generationID: Self.makeGenerationID(),+ generationStartedEmpty: startedEmpty,+ fileIdentifier: fileIdentifier+ )+ markDirty(dateKey)+ }++ mutating func normalize() -> Bool {+ let previousPending = pending+ let previousDirty = dirty+ let previousDays = days++ pending = Self.normalizedDates(pending)+ dirty = Self.normalizedDates(dirty)+ days = days.filter { HistoryStorage.isValidDateKey($0.key) }++ return previousPending != pending || previousDirty != dirty || previousDays != days+ }++ private mutating func ensureDayState(for dateKey: String) {+ if days[dateKey] == nil {+ days[dateKey] = HistoryDayMaintenanceState()+ }+ }++ private static func inserting(_ dateKey: String, into dates: [String]) -> [String] {+ normalizedDates(dates + [dateKey])+ }++ private static func normalizedDates(_ dates: [String]) -> [String] {+ Set(dates.filter(HistoryStorage.isValidDateKey)).sorted()+ }++ private static func makeGenerationID() -> String {+ UUID().uuidString.lowercased()+ }+}++nonisolated struct HistoryDayMaintenanceState: Codable, Equatable {+ private enum CodingKeys: String, CodingKey {+ case offset+ case size+ case corrupt+ case generationID+ case generationStartedEmpty+ case fileIdentifier+ case boundaryHash+ }++ var offset: UInt64+ var size: UInt64+ var corrupt: Int+ var generationID: String?+ var generationStartedEmpty: Bool+ var fileIdentifier: UInt64?+ var boundaryHash: String?++ init(+ offset: UInt64 = 0,+ size: UInt64 = 0,+ corrupt: Int = 0,+ generationID: String? = nil,+ generationStartedEmpty: Bool = false,+ fileIdentifier: UInt64? = nil,+ boundaryHash: String? = nil+ ) {+ self.offset = offset+ self.size = size+ self.corrupt = corrupt+ self.generationID = generationID+ self.generationStartedEmpty = generationStartedEmpty+ self.fileIdentifier = fileIdentifier+ self.boundaryHash = boundaryHash+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ offset = try container.decodeIfPresent(UInt64.self, forKey: .offset) ?? 0+ size = try container.decodeIfPresent(UInt64.self, forKey: .size) ?? 0+ corrupt = try container.decodeIfPresent(Int.self, forKey: .corrupt) ?? 0+ generationID = try container.decodeIfPresent(String.self, forKey: .generationID)+ generationStartedEmpty = try container.decodeIfPresent(Bool.self, forKey: .generationStartedEmpty) ?? false+ fileIdentifier = try container.decodeIfPresent(UInt64.self, forKey: .fileIdentifier)+ boundaryHash = try container.decodeIfPresent(String.self, forKey: .boundaryHash)+ }+}diff --git a/CodexBar/Services/History/HistoryService.swift b/CodexBar/Services/History/HistoryService.swiftnew file mode 100644index 0000000..b976c49--- /dev/null+++ b/CodexBar/Services/History/HistoryService.swift@@ -0,0 +1,1056 @@+import Combine+import CryptoKit+import Darwin+import Foundation+import os++/// 汇总失败时定位到哪一步, 只用于日志+private nonisolated enum MaintenanceStage: String {+ case prepare+ case write+ case prune+}++/// 一轮汇总的计数, 成功路径压进 SyncScheduler 的收尾那一条日志, 不为每天单独记一行+/// dates 从各处理结果的计数求和得出, 不额外保存+nonisolated struct HistoryMaintenanceCounts {+ var events = 0+ var written = 0+ var skipped = 0+ var failed = 0+ var pruned = 0+ var dateRange = "-"+ /// 这条之前连续空转了多少轮, 用来确认静默期是没事干而不是没跑+ var idle = 0++ var dates: Int {+ written + skipped + failed+ }++ /// 这一轮有没有真的改变过状态+ var hasWork: Bool {+ dates > 0 || pruned > 0+ }+}++/// 从 归一化活动事件维护每日聚合, 对外只发布 UI 需要的统计快照+actor HistoryService {+ private let directoryURL: URL+ private let eventsDirectoryURL: URL+ private let dailyLogURL: URL+ private let syncService: SyncService+ private let tokenHistory: TokenHistoryStore+ /// 上次归一化时 Aggregates/activity.jsonl 的 stat 与当天日期键+ private var lastNormalizedDailyLog: HistoryDailyLogStamp?+ /// 上一条维护日志之后连续空转的轮数, 记出去就清零+ private var idleMaintenanceRounds = 0+ private var verifiedBoundaries: [String: HistoryBoundaryVerification] = [:]+ private static let eventReadChunkSize = 64 * 1024++ init(+ directoryURL: URL = HistoryStorage.directoryURL(),+ syncService: SyncService? = nil,+ tokenHistory: TokenHistoryStore? = nil+ ) {+ self.directoryURL = directoryURL+ eventsDirectoryURL = HistoryStorage.eventsDirectoryURL(in: directoryURL)+ dailyLogURL = HistoryStorage.dailyURL(in: directoryURL)+ self.syncService = syncService ?? SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: directoryURL))+ self.tokenHistory = tokenHistory ?? TokenHistoryStore(directoryURL: directoryURL)+ }++ // MARK: - 快照读取++ func loadSnapshot(+ synchronize: Bool = false,+ trigger: LogTrigger = .auto+ ) async -> HistorySnapshot {+ await makeSnapshot(+ localAggregates: loadDailyAggregates() ?? [],+ synchronize: synchronize,+ trigger: trigger+ )+ }++ /// 先跑一轮维护再取快照+ /// counts 为 nil 表示这一轮空转, 由调用方决定记不记日志+ func loadSnapshotWithMaintenance(+ synchronize: Bool,+ trigger: LogTrigger+ ) async -> (snapshot: HistorySnapshot, counts: HistoryMaintenanceCounts?) {+ let counts = performMaintenanceIfNeeded()+ let snapshot = await loadSnapshot(synchronize: synchronize, trigger: trigger)+ return (snapshot, counts)+ }++ private func makeSnapshot(+ localAggregates: [ActivityAggregate],+ synchronize: Bool,+ trigger: LogTrigger,+ localTokenTurns: [TokenTurn]? = nil+ ) async -> HistorySnapshot {+ // 只有 Token 的日志日期需要维护游标, 但不能生成一次活动统计贡献+ let localAggregates = localAggregates.filter { $0.eventCount != 0 }+ let tokenTurns: [TokenTurn]+ if let localTokenTurns {+ tokenTurns = localTokenTurns+ } else {+ do {+ let baseline = await syncService.tokenRecoveryBaselineIfEnabled()+ tokenTurns = try await tokenHistory.refresh(baseline: baseline)+ } catch {+ let error = error as NSError+ AppLog.history.error("Token 历史读取失败: domain=\(error.domain, privacy: .public) code=\(error.code)")+ tokenTurns = []+ }+ }+ let syncSnapshot: SyncSnapshot = if synchronize {+ await syncService.synchronizeIfEnabled(localAggregates: localAggregates, localTokenTurns: tokenTurns, trigger: trigger)+ } else {+ await syncService.snapshotFromCacheIfEnabled(localTokenTurns: tokenTurns)+ }+ var snapshot = HistorySnapshot(+ localAggregates: localAggregates,+ syncedRecords: syncSnapshot.records,+ currentDeviceID: syncSnapshot.currentDeviceID+ )+ snapshot.tokenUsageByDate = syncSnapshot.tokenUsageByDate ?? TokenTurn.dailyUsage(tokenTurns)+ return snapshot+ }++ /// 以指定日期范围内的本机原始事件为权威来源重建, 并安排替换当前设备的同日云端贡献+ func rebuildData(+ for dateKeys: [String],+ synchronize: Bool+ ) async throws -> HistoryDataRebuildOutcome {+ let duration = LogDuration()+ let normalizedDateKeys = Set(dateKeys).sorted()+ guard !normalizedDateKeys.isEmpty else {+ throw HistoryDataRebuildError.sourceUnavailable+ }++ // 单日失败不中止整批: 失败的日期已被 rebuildLocalData 标脏, 常规维护会自动重建+ // 中止会让「前几天已改写, 后几天没碰」这个事实完全不被上报+ var rebuildResults = [HistoryMaintenanceResult]()+ var failedDateKeys = [String]()+ var firstFailure: Error?+ let eventDateKeysWithData = normalizedDateKeys.filter { HistoryStorage.fileSize(at: eventLogURL(for: $0)) > 0 }+ for dateKey in eventDateKeysWithData {+ do {+ try rebuildResults.append(rebuildLocalData(for: dateKey))+ } catch {+ // 整批成功时这个原因不会往上抛, 摘要只带得走日期+ let details = LogFields.joined(+ "stage=date",+ "date=\(dateKey)",+ "detail=\(error.localizedDescription)"+ )+ AppLog.history.error("数据重建失败: \(details, privacy: .public)")+ failedDateKeys.append(dateKey)+ if firstFailure == nil {+ firstFailure = error+ }+ }+ }++ var tokenResult = TokenRebuildResult.empty+ var didFailTokenRebuild = false+ do {+ tokenResult = try await tokenHistory.rebuild(for: normalizedDateKeys)+ } catch {+ didFailTokenRebuild = true+ firstFailure = firstFailure ?? error+ let error = error as NSError+ AppLog.history.error("Token 重建失败: domain=\(error.domain, privacy: .public) code=\(error.code)")+ }++ // 成功与失败的日期都要登记: 失败的日期稍后会被自动重建并推进 generationID,+ // 届时会上传到新的 record ID, 不清理旧记录会在云端留下同日重复的贡献+ // 全部失败时同样要登记, 它们一样已被标脏+ var didFailReplacementMarking = false+ do {+ try await syncService.markReplacementNeeded(for: eventDateKeysWithData)+ } catch {+ let details = LogFields.joined(+ "stage=replacementMarking",+ "dates=\(normalizedDateKeys.count)",+ "detail=\(error.localizedDescription)"+ )+ AppLog.history.error("数据重建失败: \(details, privacy: .public)")+ didFailReplacementMarking = true+ }++ // 一天都没成功才算整体失败, 并保留首个真实原因而非笼统报「数据发生变化」+ guard !rebuildResults.isEmpty || !tokenResult.dateKeys.isEmpty else {+ throw firstFailure ?? HistoryDataRebuildError.sourceUnavailable+ }++ // 重建只由设置页的用户操作发起+ let localTurns = await (try? tokenHistory.currentTurns()) ?? []+ let snapshot = await makeSnapshot(+ localAggregates: loadDailyAggregates() ?? [],+ synchronize: synchronize,+ trigger: .manual,+ localTokenTurns: localTurns+ )+ let tokenSyncPending = await syncService.hasPendingTokenUpdates(local: localTurns)+ let summary = await HistoryDataRebuildSummary(+ rebuiltDateCount: Set(rebuildResults.map(\.dateKey)).union(tokenResult.dateKeys).count,+ eventCount: rebuildResults.reduce(0) { $0 + ($1.aggregate.eventCount ?? 0) },+ corruptLineCount: rebuildResults.reduce(0) { $0 + $1.corrupt },+ isSyncReplacementPending: syncService.hasPendingReplacement(for: eventDateKeysWithData) || tokenSyncPending,+ failedDateKeys: failedDateKeys,+ didFailSyncReplacementMarking: didFailReplacementMarking,+ tokenTurnCount: tokenResult.turnCount,+ didFailTokenRebuild: didFailTokenRebuild+ )+ let elapsed = duration.elapsed+ let details = LogFields.joined(+ "dates=\(summary.rebuiltDateCount)",+ "events=\(summary.eventCount)",+ "tokenTurns=\(summary.tokenTurnCount)",+ "corruptLines=\(summary.corruptLineCount)",+ "failedDates=\(failedDateKeys.count)",+ "elapsed=\(elapsed)"+ )+ AppLog.history.notice("数据重建完成: \(details, privacy: .public)")+ return HistoryDataRebuildOutcome(snapshot: snapshot, summary: summary)+ }++ private func loadDailyAggregates() -> [ActivityAggregate]? {+ guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {+ return nil+ }++ let aggregates: [ActivityAggregate] = JSONLines.decode(from: data)+ guard !aggregates.isEmpty else {+ return nil+ }++ return ActivityAggregate.normalized(aggregates: aggregates)+ }++ // MARK: - 重建与维护调度++ private func rebuildLocalData(for dateKey: String) throws -> HistoryMaintenanceResult {+ var aggregates = loadDailyAggregates() ?? []+ let eventCountAvailability = aggregates+ .first(where: { $0.date == dateKey })?+ .eventCountAvailability ?? .legacy+ let task = try prepareRebuildTask(+ for: dateKey,+ eventCountAvailability: eventCountAvailability+ )++ do {+ let result = try buildDailyAggregate(for: task)+ guard try commit(result, aggregates: &aggregates),+ rebuildWasCommitted(result) else {+ throw HistoryDataRebuildError.sourceChanged+ }+ return result+ } catch {+ markDirty(dateKey)+ throw error+ }+ }++ private func prepareRebuildTask(+ for dateKey: String,+ eventCountAvailability: ActivityCountAvailability+ ) throws -> HistoryMaintenanceTask {+ let retentionCutoffKey = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate())+ guard HistoryStorage.isValidDateKey(dateKey), dateKey >= retentionCutoffKey else {+ throw HistoryDataRebuildError.sourceUnavailable+ }++ return try HistoryStorage.withExclusiveLock(in: directoryURL) {+ guard let stat = HistoryStorage.fileStat(at: eventLogURL(for: dateKey)),+ stat.size > 0 else {+ throw HistoryDataRebuildError.sourceUnavailable+ }++ var state = HistoryStorage.loadMaintenanceState(in: directoryURL)+ state.ensureGenerationID(for: dateKey, fileIdentifier: stat.identifier)+ state.markDirty(dateKey)+ try HistoryStorage.saveMaintenanceState(state, in: directoryURL)+ guard let day = state.days[dateKey] else { throw HistoryDataRebuildError.sourceUnavailable }+ var task = dirtyTask(for: dateKey, day: day, size: stat.size, eventCountAvailability: eventCountAvailability)+ task.generationID = UUID().uuidString.lowercased()+ task.generationStartedEmpty = false+ return task+ }+ }++ private func rebuildWasCommitted(_ result: HistoryMaintenanceResult) -> Bool {+ let dailyGeneration = loadDailyAggregates()?+ .first(where: { $0.date == result.dateKey })?+ .generationID+ guard dailyGeneration == result.aggregate.generationID else {+ return false+ }++ return (try? HistoryStorage.withExclusiveLock(in: directoryURL) {+ guard let day = HistoryStorage.loadMaintenanceState(in: directoryURL).days[result.dateKey] else {+ return false+ }+ return day.generationID == result.aggregate.generationID+ && day.offset == result.size+ }) ?? false+ }++ /// 空转的一轮返回 nil+ /// 维护跟随额度刷新执行, 只记录有实际工作的轮次, 避免空闲时持续产生重复日志+ /// 收尾日志由 SyncScheduler 统一记, 这里只负责判断有没有值得记的东西+ private func performMaintenanceIfNeeded() -> HistoryMaintenanceCounts? {+ let duration = LogDuration()+ var counts = HistoryMaintenanceCounts()+ var stage = MaintenanceStage.prepare+ do {+ let tasks = try prepareMaintenanceTasks()+ stage = .write+ let didCommitDailyLog = perform(tasks, counts: &counts)+ // 成功提交前已整体归一化, 没有完整提交时再做一次稳态检查+ if !didCommitDailyLog {+ try normalizeDailyAggregatesIfNeeded()+ }+ stage = .prune+ counts.pruned = try pruneExpiredEventFiles()+ } catch {+ let elapsed = duration.elapsed+ let details = LogFields.joined(+ "stage=\(stage.rawValue)",+ "elapsed=\(elapsed)",+ "detail=\(error.localizedDescription)"+ )+ AppLog.history.error("事件汇总失败: \(details, privacy: .public)")+ idleMaintenanceRounds = 0+ return nil+ }++ guard counts.hasWork else {+ idleMaintenanceRounds += 1+ return nil+ }++ counts.idle = idleMaintenanceRounds+ idleMaintenanceRounds = 0+ return counts+ }++ /// 返回是否至少完整提交一个聚合与维护状态+ /// 批次内共享同一份内存聚合, 避免每个任务重新读盘+ private func perform(+ _ tasks: [HistoryMaintenanceTask],+ counts: inout HistoryMaintenanceCounts+ ) -> Bool {+ // 任务是 dirty 与 pending 两段拼接, 只在各自半边有序, 取首尾会得到反向区间+ let dateKeys = tasks.map(\.dateKey)+ guard let oldestDateKey = dateKeys.min(),+ let newestDateKey = dateKeys.max() else {+ return false+ }++ counts.dateRange = oldestDateKey == newestDateKey+ ? oldestDateKey+ : oldestDateKey + ".." + newestDateKey++ var aggregates = loadDailyAggregates() ?? []+ var didCommit = false+ for task in tasks {+ do {+ let result = try buildDailyAggregate(for: task)+ if try commit(result, aggregates: &aggregates) {+ didCommit = true+ counts.written += 1+ // 记本轮新摄入的量; 累加 eventCount 会变成当日总数, 事件停写也看不出来+ // dirty 任务没有 base, 差值即整天重算的量, 与"这轮处理了多少"仍然一致+ counts.events += (result.aggregate.eventCount ?? 0) - task.baseEventCount+ } else {+ counts.skipped += 1+ }+ } catch {+ counts.failed += 1+ let details = LogFields.joined(+ "stage=daily",+ "date=\(task.dateKey)",+ "detail=\(error.localizedDescription)",+ "action=markDirty"+ )+ AppLog.history.error("事件汇总失败: \(details, privacy: .public)")+ markDirty(task.dateKey)+ }+ }++ return didCommit+ }++ private func prepareMaintenanceTasks() throws -> [HistoryMaintenanceTask] {+ let eventDateKeys = eventDateKeys()+ let dailyDecodeResult = loadDailyAggregatesWithFailures()++ return try HistoryStorage.withExclusiveLock(in: directoryURL) {+ var state = HistoryStorage.loadMaintenanceState(in: directoryURL)+ var changedState = state.normalize()+ let dailyByDate = dailyDecodeResult.values.reduce(into: [String: ActivityAggregate]()) { result, aggregate in+ result[aggregate.date] = aggregate+ }++ let changedByRebuild = markRebuildDates(+ eventDateKeys: eventDateKeys,+ dailyDecodeResult: dailyDecodeResult,+ dailyByDate: dailyByDate,+ state: &state+ )+ let changedByReconcile = reconcileEventFiles(eventDateKeys: eventDateKeys, state: &state)+ changedState = changedState || changedByRebuild || changedByReconcile++ let tasks = makeMaintenanceTasks(+ state: &state,+ dailyByDate: dailyByDate,+ changedState: &changedState+ )++ if changedState {+ try HistoryStorage.saveMaintenanceState(state, in: directoryURL)+ }++ return tasks+ }+ }++ private func markRebuildDates(+ eventDateKeys: [String],+ dailyDecodeResult: JSONLinesDecodeResult<ActivityAggregate>,+ dailyByDate: [String: ActivityAggregate],+ state: inout HistoryMaintenanceState+ ) -> Bool {+ var changed = false++ if state.version != HistoryMaintenanceState.currentVersion {+ changed = state.markDirty(contentsOf: eventDateKeys) || changed+ state.version = HistoryMaintenanceState.currentVersion+ changed = true+ }++ if dailyDecodeResult.failedLineCount > 0 || (dailyDecodeResult.values.isEmpty && !eventDateKeys.isEmpty) {+ changed = state.markDirty(contentsOf: eventDateKeys) || changed+ }++ changed = state.markDirty(contentsOf: eventDateKeys.filter { dailyByDate[$0] == nil }) || changed+ changed = state.markDirty(contentsOf: state.pending.filter { dailyByDate[$0] == nil }) || changed++ return changed+ }++ private func reconcileEventFiles(+ eventDateKeys: [String],+ state: inout HistoryMaintenanceState+ ) -> Bool {+ verifiedBoundaries = verifiedBoundaries.filter { state.days[$0.key] != nil }+ var changed = state.markDirty(contentsOf: eventDateKeys.filter { state.days[$0] == nil })++ for dateKey in eventDateKeys {+ guard let stat = HistoryStorage.fileStat(at: eventLogURL(for: dateKey)) else {+ continue+ }++ changed = state.ensureGenerationID(+ for: dateKey,+ fileIdentifier: stat.identifier+ ) || changed+ guard let day = state.days[dateKey] else {+ continue+ }++ let identifierChanged = day.fileIdentifier != nil+ && day.fileIdentifier != stat.identifier+ let boundaryChanged = hasBoundaryChanged(dateKey: dateKey, day: day, stat: stat)++ if identifierChanged || stat.size < day.offset || boundaryChanged {+ state.startNewGeneration(+ for: dateKey,+ startedEmpty: stat.size == 0,+ fileIdentifier: stat.identifier+ )+ changed = true+ } else if day.offset != day.size {+ state.markDirty(dateKey)+ changed = true+ } else if stat.size > day.offset,+ !state.pending.contains(dateKey),+ !state.dirty.contains(dateKey) {+ state.markPending(dateKey)+ changed = true+ }+ }++ return changed+ }++ /// boundaryHash 覆盖 offset 之前的边界片段, 追加只写在 offset 之后+ /// 文件未修改时复用已有哈希, 减少持锁时间和采集器的等待+ private func hasBoundaryChanged(+ dateKey: String,+ day: HistoryDayMaintenanceState,+ stat: HistoryFileStat+ ) -> Bool {+ guard let recordedHash = day.boundaryHash else {+ return false+ }++ // 只有完整 stat 可以跳过校验, 毫秒精度不能区分同毫秒内的改写+ if let verified = verifiedBoundaries[dateKey],+ verified.offset == day.offset, verified.digest == recordedHash, verified.stat == stat {+ return false+ }++ guard (try? eventLogBoundaryHash(for: dateKey, endingAt: day.offset)) == recordedHash else {+ verifiedBoundaries.removeValue(forKey: dateKey)+ return true+ }++ verifiedBoundaries[dateKey] = HistoryBoundaryVerification(offset: day.offset, digest: recordedHash, stat: stat)+ return false+ }++ private func makeMaintenanceTasks(+ state: inout HistoryMaintenanceState,+ dailyByDate: [String: ActivityAggregate],+ changedState: inout Bool+ ) -> [HistoryMaintenanceTask] {+ let dirty = Set(state.dirty)+ var tasks: [HistoryMaintenanceTask] = state.dirty.compactMap { dateKey in+ guard let day = state.days[dateKey] else {+ return nil+ }+ return dirtyTask(+ for: dateKey,+ day: day,+ eventCountAvailability: dailyByDate[dateKey]?+ .eventCountAvailability ?? .legacy+ )+ }++ for dateKey in state.pending where !dirty.contains(dateKey) {+ let day = state.days[dateKey] ?? HistoryDayMaintenanceState()+ let size = eventLogSize(for: dateKey)+ guard size > day.offset else {+ state.removePending(dateKey)+ changedState = true+ continue+ }++ let existingAggregate = dailyByDate[dateKey]+ guard let baseAggregate = existingAggregate,+ baseAggregate.generationID == day.generationID else {+ state.markDirty(dateKey)+ changedState = true+ tasks.append(dirtyTask(+ for: dateKey,+ day: day,+ size: size,+ eventCountAvailability: existingAggregate?+ .eventCountAvailability ?? .legacy+ ))+ continue+ }++ // ID 已压缩的聚合无法判断追加事件是否属于已有 session 或 turn+ // 任何不能证明与全量结果等价的增量任务都降级为完整重建+ guard retainsIdentifiers(for: dateKey),+ baseAggregate.supportsIncrementalAggregation else {+ state.markDirty(dateKey)+ changedState = true+ tasks.append(dirtyTask(+ for: dateKey,+ day: day,+ size: size,+ eventCountAvailability: baseAggregate.eventCountAvailability+ ))+ continue+ }++ tasks.append(+ pendingTask(+ for: dateKey,+ day: day,+ size: size,+ baseAggregate: baseAggregate+ )+ )+ }++ return tasks+ }++ private func dirtyTask(+ for dateKey: String,+ day: HistoryDayMaintenanceState,+ size: UInt64? = nil,+ eventCountAvailability: ActivityCountAvailability = .legacy+ ) -> HistoryMaintenanceTask {+ let stat = HistoryStorage.fileStat(at: eventLogURL(for: dateKey))+ return HistoryMaintenanceTask(+ dateKey: dateKey,+ startOffset: 0,+ size: size ?? stat?.size ?? 0,+ mode: .rebuild(eventCountAvailability),+ existingCorrupt: 0,+ expectedGenerationID: day.generationID,+ generationID: day.generationID,+ generationStartedEmpty: day.generationStartedEmpty,+ fileIdentifier: stat?.identifier+ )+ }++ private func pendingTask(+ for dateKey: String,+ day: HistoryDayMaintenanceState,+ size: UInt64,+ baseAggregate: ActivityAggregate+ ) -> HistoryMaintenanceTask {+ HistoryMaintenanceTask(+ dateKey: dateKey,+ startOffset: day.offset,+ size: size,+ mode: .append(baseAggregate),+ existingCorrupt: day.corrupt,+ expectedGenerationID: day.generationID,+ generationID: day.generationID,+ generationStartedEmpty: day.generationStartedEmpty,+ fileIdentifier: day.fileIdentifier+ )+ }++ // MARK: - 事件文件读取与聚合++ private func eventLogURL(for dateKey: String) -> URL {+ HistoryStorage.eventLogURL(for: dateKey, in: eventsDirectoryURL)+ }++ private func eventLogSize(for dateKey: String) -> UInt64 {+ HistoryStorage.fileSize(at: eventLogURL(for: dateKey))+ }++ private func eventLogBoundaryHash(+ for dateKey: String,+ endingAt offset: UInt64+ ) throws -> String? {+ guard offset > 0 else {+ return nil+ }++ let length = min(offset, 4 * 1024)+ let handle = try FileHandle(forReadingFrom: eventLogURL(for: dateKey))+ defer {+ try? handle.close()+ }++ try handle.seek(toOffset: offset - length)+ guard let data = try handle.read(upToCount: Int(length)),+ data.count == Int(length) else {+ throw CocoaError(.fileReadUnknown)+ }++ return SHA256.hash(data: data)+ .map { String(format: "%02x", $0) }+ .joined()+ }++ private func loadDailyAggregatesWithFailures() -> JSONLinesDecodeResult<ActivityAggregate> {+ guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {+ return JSONLinesDecodeResult(values: [], failedLineCount: 0)+ }++ return JSONLines.decodeWithFailures(from: data)+ }++ private func eventDateKeys() -> [String] {+ HistoryStorage.eventLogDateKeys(in: eventsDirectoryURL)+ }++ private func buildDailyAggregate(+ for task: HistoryMaintenanceTask+ ) throws -> HistoryMaintenanceResult {+ var accumulator = switch task.mode {+ case let .rebuild(eventCountAvailability):+ ActivityAccumulator(+ rebuilding: task.dateKey,+ generationID: task.generationID,+ generationStartedEmpty: task.generationStartedEmpty,+ eventCountAvailability: eventCountAvailability+ )+ case let .append(baseAggregate):+ ActivityAccumulator(+ appending: baseAggregate,+ generationID: task.generationID,+ generationStartedEmpty: task.generationStartedEmpty+ )+ }+ var corrupt = task.existingCorrupt++ corrupt += try readEvents(+ at: eventLogURL(for: task.dateKey),+ from: task.startOffset,+ upTo: task.size+ ) { event in+ accumulator.record(event)+ }++ let identifierStorage: ActivityIdentifiers = retainsIdentifiers(for: task.dateKey)+ ? .retained+ : .compacted+ let aggregate = accumulator.finalized(identifierStorage: identifierStorage)+ return try HistoryMaintenanceResult(+ dateKey: task.dateKey,+ aggregate: aggregate,+ expectedGenerationID: task.expectedGenerationID,+ size: task.size,+ corrupt: corrupt,+ fileIdentifier: task.fileIdentifier,+ boundaryHash: eventLogBoundaryHash(for: task.dateKey, endingAt: task.size)+ )+ }++ private func readEvents(+ at url: URL,+ from startOffset: UInt64,+ upTo size: UInt64,+ record: (ActivityRecord) -> Void+ ) throws -> Int {+ guard size > startOffset else {+ return 0+ }++ let fileHandle = try FileHandle(forReadingFrom: url)+ defer {+ try? fileHandle.close()+ }++ try fileHandle.seek(toOffset: startOffset)++ var remainingBytes = size - startOffset+ var buffer = Data()+ var corrupt = 0++ // 分块读取防止大日志一次性进内存, 但仍按完整 JSONL 行解码+ while remainingBytes > 0 {+ let readSize = min(Int(remainingBytes), Self.eventReadChunkSize)+ guard let chunk = try fileHandle.read(upToCount: readSize), !chunk.isEmpty else {+ break+ }++ remainingBytes -= UInt64(chunk.count)+ buffer.append(chunk)++ while let newlineIndex = buffer.firstIndex(of: JSONLines.newlineByte) {+ let lineData = buffer[..<newlineIndex]+ corrupt += Self.decode(lineData, record: record)+ buffer.removeSubrange(...newlineIndex)+ }+ }++ if !buffer.isEmpty {+ corrupt += Self.decode(buffer, record: record)+ }++ return corrupt+ }++ nonisolated static func decode(+ _ lineData: Data.SubSequence,+ record: (ActivityRecord) -> Void+ ) -> Int {+ guard let line = String(bytes: lineData, encoding: .utf8)?+ .trimmingCharacters(in: .whitespacesAndNewlines) else {+ return 1+ }++ guard !line.isEmpty else {+ return 0+ }++ guard let data = line.data(using: .utf8),+ let entry = try? AppServerEventRecord.decode(from: data) else {+ return 1+ }++ if let event = entry.activity {+ record(event)+ }+ return 0+ }++ // MARK: - 落盘与状态提交++ /// 返回聚合与维护状态是否都基于同一份事件源完成提交+ private func commit(+ _ result: HistoryMaintenanceResult,+ aggregates: inout [ActivityAggregate]+ ) throws -> Bool {+ try HistoryStorage.withExclusiveLock(in: directoryURL) {+ var state = HistoryStorage.loadMaintenanceState(in: directoryURL)+ guard let currentSize = try validatedEventLogSize(for: result, state: &state) else { return false }+ // 两个文件提交前先标脏, 中途退出会从事件重建, 不沿旧偏移重复追加+ state.markDirty(result.dateKey)+ try HistoryStorage.saveMaintenanceState(state, in: directoryURL)+ aggregates = loadDailyAggregates() ?? []+ try writeDailyAggregate(result.aggregate, into: &aggregates)+ state.days[result.dateKey] = HistoryDayMaintenanceState(+ offset: result.size, size: result.size, corrupt: result.corrupt,+ generationID: result.aggregate.generationID,+ generationStartedEmpty: result.aggregate.generationStartedEmpty,+ fileIdentifier: result.fileIdentifier, boundaryHash: result.boundaryHash+ )+ state.removeDirty(result.dateKey)+ if currentSize == result.size {+ state.removePending(result.dateKey)+ } else {+ state.markPending(result.dateKey)+ }+ try HistoryStorage.saveMaintenanceState(state, in: directoryURL)+ return true+ }+ }++ /// 锁内确认读取期间仍是同一份追加源; 断代时换 generation 并等待重建+ private func validatedEventLogSize(+ for result: HistoryMaintenanceResult,+ state: inout HistoryMaintenanceState+ ) throws -> UInt64? {+ guard state.days[result.dateKey]?.generationID == result.expectedGenerationID else {+ return nil+ }++ let stat = HistoryStorage.fileStat(at: eventLogURL(for: result.dateKey))+ let identifierMatches = result.fileIdentifier == nil+ || result.fileIdentifier == stat?.identifier+ let boundaryMatches = (try? eventLogBoundaryHash(+ for: result.dateKey,+ endingAt: result.size+ )) == result.boundaryHash++ guard let stat,+ stat.size >= result.size,+ identifierMatches,+ boundaryMatches else {+ state.startNewGeneration(+ for: result.dateKey,+ startedEmpty: stat?.size == 0,+ fileIdentifier: stat?.identifier+ )+ try HistoryStorage.saveMaintenanceState(state, in: directoryURL)+ return nil+ }++ return stat.size+ }++ private func writeDailyAggregate(+ _ aggregate: ActivityAggregate,+ into aggregates: inout [ActivityAggregate]+ ) throws {+ try FileManager.default.createDirectory(+ at: dailyLogURL.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )++ upsert(aggregate, into: &aggregates)+ aggregates = ActivityAggregate.normalized(aggregates: aggregates)+ let data = try ActivityAggregate.encodeJSONLines(aggregates)+ try data.write(to: dailyLogURL, options: .atomic)+ }++ private func normalizeDailyAggregatesIfNeeded() throws {+ guard let stat = HistoryStorage.fileStat(at: dailyLogURL), stat.size > 0 else {+ return+ }++ // 稳态下文件与日期都没变, 跳过全量解码与重编码比对+ let dayKey = HistoryStorage.dateKey(for: Date())+ if lastNormalizedDailyLog == HistoryDailyLogStamp(size: stat.size, identifier: stat.identifier, dayKey: dayKey) {+ return+ }++ guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {+ return+ }++ let decodeResult = JSONLines.decodeWithFailures(ActivityAggregate.self, from: data)+ guard decodeResult.failedLineCount == 0 else {+ return+ }++ let normalizedAggregates = ActivityAggregate.normalized(aggregates: decodeResult.values)+ let normalizedData = try ActivityAggregate.encodeJSONLines(normalizedAggregates)+ if normalizedData != data {+ try FileManager.default.createDirectory(+ at: dailyLogURL.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )+ try normalizedData.write(to: dailyLogURL, options: .atomic)+ }++ if let latestStat = HistoryStorage.fileStat(at: dailyLogURL) {+ lastNormalizedDailyLog = HistoryDailyLogStamp(+ size: latestStat.size,+ identifier: latestStat.identifier,+ dayKey: dayKey+ )+ }+ }++ private func upsert(_ aggregate: ActivityAggregate, into aggregates: inout [ActivityAggregate]) {+ if let index = aggregates.firstIndex(where: { $0.date == aggregate.date }) {+ aggregates[index] = aggregate+ } else {+ aggregates.append(aggregate)+ }+ }++ private func markDirty(_ dateKey: String) {+ do {+ try HistoryStorage.withExclusiveLock(in: directoryURL) {+ var state = HistoryStorage.loadMaintenanceState(in: directoryURL)+ state.markDirty(dateKey)+ try HistoryStorage.saveMaintenanceState(state, in: directoryURL)+ }+ } catch {+ // 标记丢了下一轮就不会重建这天, 数据会静默缺一块+ let details = LogFields.joined(+ "stage=markDirty",+ "date=\(dateKey)",+ "detail=\(error.localizedDescription)"+ )+ AppLog.history.error("事件汇总失败: \(details, privacy: .public)")+ }+ }++ // MARK: - 保留期清理++ @discardableResult+ private func pruneExpiredEventFiles() throws -> Int {+ let cutoffDate = HistoryStorage.retentionCutoffDate()+ let expiredDateKeys = eventDateKeys().filter { dateKey in+ guard let date = CodexDateFormat.dayDate(from: dateKey) else {+ return false+ }++ return date < cutoffDate+ }++ guard !expiredDateKeys.isEmpty else {+ return 0+ }++ try HistoryStorage.withExclusiveLock(in: directoryURL) {+ var state = HistoryStorage.loadMaintenanceState(in: directoryURL)+ for dateKey in expiredDateKeys {+ try? FileManager.default.removeItem(at: eventLogURL(for: dateKey))+ state.remove(dateKey)+ }++ try HistoryStorage.saveMaintenanceState(state, in: directoryURL)+ }+ // 保留期到点会真的删掉原始事件文件, 数据对不上时要能查到哪些日期被清掉了+ let details = LogFields.joined(+ "dates=\(expiredDateKeys.count)",+ "oldest=\(expiredDateKeys.first ?? "-")"+ )+ AppLog.history.notice("过期事件已清理: \(details, privacy: .public)")+ return expiredDateKeys.count+ }++ private func retainsIdentifiers(for dateKey: String) -> Bool {+ guard let date = CodexDateFormat.dayDate(from: dateKey) else {+ return true+ }++ return date >= HistoryStorage.identifierRetentionCutoffDate()+ }+}++/// 完整精度的校验结果只在当前进程复用+private nonisolated struct HistoryBoundaryVerification {+ let offset: UInt64+ let digest: String+ let stat: HistoryFileStat+}++/// Aggregates/activity.jsonl 某一时刻的 stat 快照与当天日期键, 用于跳过稳态下的重复归一化+private nonisolated struct HistoryDailyLogStamp: Equatable {+ let size: UInt64+ let identifier: UInt64?+ let dayKey: String+}++/// 全量重建与安全增量使用不同初始状态, 避免用 nil 隐含任务语义+private nonisolated enum HistoryMaintenanceMode {+ case rebuild(ActivityCountAvailability)+ case append(ActivityAggregate)+}++// 单次维护任务: 从 startOffset 读到 size, 可基于已有聚合继续追加+private nonisolated struct HistoryMaintenanceTask {+ let dateKey: String+ let startOffset: UInt64+ let size: UInt64+ let mode: HistoryMaintenanceMode+ let existingCorrupt: Int+ let expectedGenerationID: String?+ var generationID: String?+ var generationStartedEmpty: Bool+ let fileIdentifier: UInt64?++ var baseEventCount: Int {+ switch mode {+ case .rebuild:+ 0+ case let .append(aggregate):+ aggregate.eventCount ?? 0+ }+ }+}++/// 维护任务的提交结果, corrupt 统计保留给后续诊断+private nonisolated struct HistoryMaintenanceResult {+ let dateKey: String+ let aggregate: ActivityAggregate+ let expectedGenerationID: String?+ let size: UInt64+ let corrupt: Int+ let fileIdentifier: UInt64?+ let boundaryHash: String?+}++nonisolated struct HistoryDataRebuildSummary: Equatable, Sendable {+ let rebuiltDateCount: Int+ let eventCount: Int+ let corruptLineCount: Int+ let isSyncReplacementPending: Bool+ /// 未完成的日期, 已标脏并会由常规维护自动重建+ let failedDateKeys: [String]+ let didFailSyncReplacementMarking: Bool+ let tokenTurnCount: Int+ let didFailTokenRebuild: Bool+}++nonisolated struct HistoryDataRebuildOutcome {+ let snapshot: HistorySnapshot+ let summary: HistoryDataRebuildSummary+}++private nonisolated enum HistoryDataRebuildError: LocalizedError {+ case sourceUnavailable+ case sourceChanged++ var errorDescription: String? {+ switch self {+ case .sourceUnavailable:+ String(localized: "history.rebuild.error.source-unavailable")+ case .sourceChanged:+ String(localized: "history.rebuild.error.source-changed")+ }+ }+}diff --git a/CodexBar/Services/History/HistoryStorage.swift b/CodexBar/Services/History/HistoryStorage.swiftnew file mode 100644index 0000000..dd5d4c9--- /dev/null+++ b/CodexBar/Services/History/HistoryStorage.swift@@ -0,0 +1,180 @@+import CryptoKit+import Darwin+import Foundation+import os++/// 活动统计文件路径, 保留期和跨进程 flock 都集中在这里+nonisolated enum HistoryStorage {+ private static let retentionDayCount = 210+ private static let identifierRetentionDayCount = 3++ // MARK: - 存储路径++ static func eventsDirectoryURL(in root: URL = directoryURL()) -> URL {+ root+ .appendingPathComponent("Events", isDirectory: true)+ }++ static func eventLogURL(for dateKey: String, in directoryURL: URL = eventsDirectoryURL()) -> URL {+ directoryURL.appendingPathComponent("\(dateKey).jsonl", isDirectory: false)+ }++ static func dailyURL(in root: URL = directoryURL()) -> URL {+ root.appendingPathComponent("Aggregates/activity.jsonl", isDirectory: false)+ }++ static func lockURL(in root: URL = directoryURL()) -> URL {+ root.appendingPathComponent("Locks/events.lock", isDirectory: false)+ }++ static func maintenanceURL(in root: URL = directoryURL()) -> URL {+ root.appendingPathComponent("State/aggregation.json", isDirectory: false)+ }++ static func syncDirectoryURL(in root: URL = directoryURL()) -> URL {+ root.appendingPathComponent("Sync", isDirectory: true)+ }++ static func directoryURL() -> URL {+ AppStorage.directoryURL()+ }++ static func withExclusiveLock<T>(+ in root: URL = directoryURL(),+ _ work: () throws -> T+ ) throws -> T {+ try FileManager.default.createDirectory(+ at: lockURL(in: root).deletingLastPathComponent(),+ withIntermediateDirectories: true+ )++ // 创建与打开必须是同一次调用: 分开做时两个进程可能各自创建,+ // 后创建的会 unlink 掉前者正在锁的 inode, 于是双方都以为自己独占+ let fileDescriptor = open(lockURL(in: root).path, O_RDWR | O_CREAT, 0o600)+ guard fileDescriptor >= 0 else {+ throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)+ }+ defer {+ close(fileDescriptor)+ }++ // 采集与维护使用独立服务实例, 文件事务必须共享同一把锁+ guard flock(fileDescriptor, LOCK_EX) == 0 else {+ throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)+ }++ defer {+ flock(fileDescriptor, LOCK_UN)+ }++ return try work()+ }++ static func loadMaintenanceState(in root: URL = directoryURL()) -> HistoryMaintenanceState {+ let url = maintenanceURL(in: root)+ guard let data = try? Data(contentsOf: url), !data.isEmpty,+ let state = try? JSONLines.decoder.decode(HistoryMaintenanceState.self, from: data) else {+ return HistoryMaintenanceState()+ }++ return state+ }++ static func saveMaintenanceState(_ state: HistoryMaintenanceState, in root: URL = directoryURL()) throws {+ let url = maintenanceURL(in: root)+ try FileManager.default.createDirectory(+ at: url.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )++ let data = try JSONLines.stableEncoder.encode(state)+ try data.write(to: url, options: .atomic)+ }++ static func fileSize(at url: URL) -> UInt64 {+ fileStat(at: url)?.size ?? 0+ }++ /// 单次 stat 同时返回大小与 inode 标识, 文件缺失或不可读时为 nil+ /// 维护流程需要批量读取文件状态, 直接使用 stat(2) 避免逐个构造属性字典+ /// 内存保留纳秒精度用于检测改写, 落盘时间统一使用整数毫秒+ /// 沿用 attributesOfItem 的语义跟随符号链接, 因此用 stat 而非 lstat+ static func fileStat(at url: URL) -> HistoryFileStat? {+ var info = Darwin.stat()+ guard stat(url.path, &info) == 0 else {+ return nil+ }++ return HistoryFileStat(+ size: UInt64(clamping: info.st_size),+ identifier: UInt64(info.st_ino),+ modifiedAtNanoseconds: Int64(info.st_mtimespec.tv_sec) * 1000000000+ + Int64(info.st_mtimespec.tv_nsec)+ )+ }++ /// 枚举目录中文件名为合法日期键的 .jsonl 事件日志, 返回升序日期键+ static func eventLogDateKeys(in directoryURL: URL = eventsDirectoryURL()) -> [String] {+ guard let contents = try? FileManager.default.contentsOfDirectory(+ at: directoryURL,+ includingPropertiesForKeys: nil,+ options: [.skipsHiddenFiles]+ ) else {+ return []+ }++ return contents+ .filter { $0.pathExtension == "jsonl" }+ .map { $0.deletingPathExtension().lastPathComponent }+ .filter { isValidDateKey($0) }+ .sorted()+ }++ /// 返回保留窗口内且本机原始事件文件非空的日期, 供设置页标记和筛选实际重建项+ static func rebuildableEventDateKeys(+ in directoryURL: URL = eventsDirectoryURL()+ ) -> [String] {+ let cutoffKey = dateKey(for: retentionCutoffDate())+ return eventLogDateKeys(in: directoryURL)+ .filter { dateKey in+ dateKey >= cutoffKey+ && fileSize(at: eventLogURL(for: dateKey, in: directoryURL)) > 0+ }+ .sorted(by: >)+ }++ static func retentionCutoffDate(today: Date = Date(), calendar: Calendar = .current) -> Date {+ cutoffDate(dayCount: retentionDayCount, today: today, calendar: calendar)+ }++ static func identifierRetentionCutoffDate(today: Date = Date(), calendar: Calendar = .current) -> Date {+ cutoffDate(dayCount: identifierRetentionDayCount, today: today, calendar: calendar)+ }++ private static func cutoffDate(dayCount: Int, today: Date, calendar: Calendar) -> Date {+ let todayStart = calendar.startOfDay(for: today)+ return calendar.date(+ byAdding: .day,+ value: -(dayCount - 1),+ to: todayStart+ ) ?? todayStart+ }++ static func dateKey(for date: Date) -> String {+ CodexDateFormat.dayString(from: date)+ }++ static func isValidDateKey(_ dateKey: String) -> Bool {+ CodexDateFormat.dayDate(from: dateKey) != nil+ }+}++nonisolated struct HistoryFileStat: Equatable {+ let size: UInt64+ let identifier: UInt64+ let modifiedAtNanoseconds: Int64++ var modificationTime: Int64 {+ modifiedAtNanoseconds / 1000000+ }+}diff --git a/CodexBar/Services/History/HistoryViewModel.swift b/CodexBar/Services/History/HistoryViewModel.swiftnew file mode 100644index 0000000..fdbc2af--- /dev/null+++ b/CodexBar/Services/History/HistoryViewModel.swift@@ -0,0 +1,90 @@+import Combine+import Foundation++/// UI 层的工作流状态, 节流普通刷新, 维护刷新由上层调度器合并+@MainActor+final class HistoryViewModel: ObservableObject {+ @Published private(set) var snapshot = HistorySnapshot.empty++ private static let minimumRefreshInterval: TimeInterval = 5++ private let service: HistoryService+ private var isRefreshing = false+ private let refreshCoordinator = RefreshTaskCoordinator()+ private var lastRefreshedAt: Date?++ init(service: HistoryService = HistoryService()) {+ self.service = service+ }++ deinit {+ refreshCoordinator.cancel()+ }++ func refreshIfNeeded() {+ guard Date().timeIntervalSince(lastRefreshedAt ?? .distantPast) > Self.minimumRefreshInterval else {+ return+ }++ refresh()+ }++ func refresh() {+ if isRefreshing {+ return+ }++ refreshCoordinator.run(+ setRefreshing: { [weak self] in self?.isRefreshing = $0 },+ operation: { [service = self.service] in await service.loadSnapshot() },+ commit: { [weak self] snapshot in+ self?.snapshot = snapshot+ self?.lastRefreshedAt = Date()+ }+ )+ }++ /// 由 SyncScheduler 串行调度, 无需自行判断并发, 只执行一次明确的维护刷新+ /// 返回这一轮的维护计数, 空转为 nil; 收尾日志由调用方按它决定记不记+ func refreshMaintenance(+ synchronize: Bool,+ trigger: LogTrigger+ ) async -> HistoryMaintenanceCounts? {+ refreshCoordinator.cancel()+ isRefreshing = true+ defer {+ isRefreshing = false+ }++ let result = await service.loadSnapshotWithMaintenance(+ synchronize: synchronize,+ trigger: trigger+ )++ guard !Task.isCancelled else { return result.counts }+ snapshot = result.snapshot+ lastRefreshedAt = Date()+ return result.counts+ }++ func rebuildData(+ for dateKeys: [String],+ synchronize: Bool+ ) async throws -> HistoryDataRebuildSummary {+ refreshCoordinator.cancel()+ isRefreshing = true+ defer {+ isRefreshing = false+ }++ let outcome = try await service.rebuildData(+ for: dateKeys,+ synchronize: synchronize+ )+ if !Task.isCancelled {+ snapshot = outcome.snapshot+ lastRefreshedAt = Date()+ }+ return outcome.summary+ }+}diff --git a/CodexBar/Services/History/TokenHistoryStore.swift b/CodexBar/Services/History/TokenHistoryStore.swiftnew file mode 100644index 0000000..40ca6e5--- /dev/null+++ b/CodexBar/Services/History/TokenHistoryStore.swift@@ -0,0 +1,303 @@+import CryptoKit+import Darwin+import Foundation+import os++/// 仅保存订阅期间取得的轮次累计快照, 不扫描 Codex 会话文件+actor TokenHistoryStore {+ private let directoryURL: URL+ private var recordingLease: Int32?+ private var journal = AppServerEventJournal()+ private var journalFiles: [String: TokenJournalCheckpoint] = [:]+ private var scannedFiles: [String: HistoryFileStat] = [:]++ init(directoryURL: URL = HistoryStorage.directoryURL()) {+ self.directoryURL = directoryURL+ }++ deinit {+ if let recordingLease {+ JSONFileStorage.releaseLock(recordingLease)+ }+ }++ /// 同机多个 App 可以旁观, 但只有一个采集器累计 Token, 避免不同基线覆盖彼此+ func acquireRecordingLease() throws -> Bool {+ if recordingLease != nil {+ return true+ }+ recordingLease = try JSONFileStorage.acquireLock(in: directoryURL.appendingPathComponent("Locks"), name: "tokens.lock", nonblocking: true)+ return recordingLease != nil+ }++ func releaseRecordingLease() {+ if let recordingLease {+ JSONFileStorage.releaseLock(recordingLease)+ }+ recordingLease = nil+ }++ func record(_ turns: [TokenTurn], sources: [String: AppServerEventSource] = [:], now: Date = Date()) throws {+ guard !turns.isEmpty else { return }+ try HistoryStorage.withExclusiveLock(in: directoryURL) {+ var records = try load(now: now)+ var changed: [TokenTurn] = []+ for turn in turns {+ let merged = records[turn.id]?.merging(turn) ?? turn+ if records[turn.id] != merged {+ changed.append(merged)+ }+ records[turn.id] = merged+ }+ // 日志先于快照提交, 意外退出后可以从已采集的数据重建+ let roots = Set(changed.map(\.rootID))+ try saveObservedTurns(changed + roots.compactMap { records[$0] }, sources: sources, now: now)+ records = retained(records, now: now)+ try save(records)+ }+ }++ func recordObservations(_ observations: [TokenObservation], now: Date = Date()) throws -> [TokenTurn] {+ try HistoryStorage.withExclusiveLock(in: directoryURL) {+ var records = try load(now: now)+ for observation in observations {+ let existing = records[observation.turn.id]+ let updated = try observation.applying(to: existing)+ // 原始观测先落盘, 快照失败后按同一检查点重放, 重试不会重复累计+ try journal.append(AppServerEventRecord(observation: observation, recordedAt: now), in: directoryURL)+ records[updated.id] = updated+ Self.ensureRoot(for: observation, in: &records)+ }+ try save(records)+ return Array(records.values)+ }+ }++ private static func ensureRoot(for observation: TokenObservation, in records: inout [String: TokenTurn]) {+ let turn = observation.turn+ if turn.rootID != turn.id, records[turn.rootID] == nil {+ records[turn.rootID] = TokenTurn(+ id: turn.rootID,+ rootID: turn.rootID,+ startedAt: observation.rootStartedAt,+ updatedAt: turn.updatedAt+ )+ }+ }++ func refresh(now: Date = Date(), baseline: TokenHistoryBaseline? = nil) throws -> [TokenTurn] {+ try HistoryStorage.withExclusiveLock(in: directoryURL) {+ var records = try load(now: now)+ var replacements: [TokenTurn] = []+ if let baseline {+ for (id, turn) in records {+ if let replacement = baseline.replacement(for: turn) {+ records[id] = replacement+ if replacement != turn {+ replacements.append(replacement)+ }+ }+ }+ }+ let roots = Set(replacements.map(\.rootID))+ try saveObservedTurns(replacements + roots.compactMap { records[$0] }, now: now)+ records = retained(records, now: now)+ try save(records)+ return Array(records.values)+ }+ }++ func currentTurns(now: Date = Date()) throws -> [TokenTurn] {+ try HistoryStorage.withExclusiveLock(in: directoryURL) { try Array(load(now: now).values) }+ }++ func rebuildableDateKeys(now: Date = Date()) throws -> [String] {+ try Array(TokenTurn.dailyUsage(currentTurns(now: now), now: now).keys).sorted()+ }++ func rebuild(for dateKeys: [String], now: Date = Date()) throws -> TokenRebuildResult {+ try HistoryStorage.withExclusiveLock(in: directoryURL) {+ let recorded = try journalTurns(now: now)+ let dates = Set(dateKeys)+ var ledger = try load(now: now)+ var count = 0+ var rebuiltDates = Set<String>()+ var rebuiltTurns: [TokenTurn] = []+ for var turn in recorded.values {+ guard let rootStart = recorded[turn.rootID]?.startedAt else { continue }+ let date = CodexDateFormat.dayString(from: rootStart)+ guard dates.contains(date) else { continue }+ let previous = ledger[turn.id]+ guard turn.covers(previous?.checkpoint ?? [:]) else { throw TokenCacheError.incompleteJournal }+ turn.generationID = previous?.generationID ?? turn.generationID+ turn.ancestorIDs = previous?.ancestorIDs ?? []+ turn.startNewGeneration(at: now)+ ledger[turn.id] = turn+ rebuiltTurns.append(turn)+ rebuiltDates.insert(date)+ count += 1+ }+ try saveObservedTurns(rebuiltTurns, now: now)+ try save(ledger)+ return TokenRebuildResult(dateKeys: rebuiltDates.sorted(), turnCount: count)+ }+ }++ private func saveObservedTurns(_ records: [TokenTurn], sources: [String: AppServerEventSource] = [:], now: Date) throws {+ for record in TokenTurn.merged(records).values.sorted(by: { $0.id < $1.id }) {+ try journal.append(AppServerEventRecord(token: record, source: sources[record.id], recordedAt: now), in: directoryURL)+ }+ }++ private func journalTurns(now: Date) throws -> [String: TokenTurn] {+ let directory = HistoryStorage.eventsDirectoryURL(in: directoryURL)+ let cutoff = CodexDateFormat.dayString(from: HistoryStorage.retentionCutoffDate(today: now))+ var result: [String: TokenTurn] = [:]+ for date in HistoryStorage.eventLogDateKeys(in: directory) where date >= cutoff {+ let url = HistoryStorage.eventLogURL(for: date, in: directory)+ var invalid = false+ try AppServerEventJournal.read(at: url, onInvalidLine: { invalid = true }, consume: { entry in+ if let observation = entry.observation {+ result[observation.turn.id] = try observation.applying(to: result[observation.turn.id])+ Self.ensureRoot(for: observation, in: &result)+ }+ })+ if invalid {+ throw TokenCacheError.incompleteJournal+ }+ }+ return result+ }++ private var ledgerURL: URL {+ directoryURL.appendingPathComponent("Aggregates/tokens.json")+ }++ private func load(now: Date) throws -> [String: TokenTurn] {+ let cache: TokenAggregateCache?+ do {+ let data = try Data(contentsOf: ledgerURL)+ // 版本先于完整解码检查, 不把其他版本的数据当成损坏缓存覆盖+ struct Version: Decodable { let version: Int }+ let version = try JSONDecoder().decode(Version.self, from: data).version+ guard version == TokenAggregateCache.currentVersion else { throw TokenCacheError.unsupportedVersion(version) }+ cache = try AppServerEventRecord.decode(TokenAggregateCache.self, from: data)+ } catch let error as CocoaError where error.code == .fileReadNoSuchFile {+ cache = nil+ } catch is DecodingError {+ AppLog.history.error("Token 缓存损坏, 从原始事件恢复")+ cache = nil+ }+ if cache == nil {+ journalFiles.removeAll()+ scannedFiles.removeAll()+ }+ var records = cache?.turns ?? [:]+ journalFiles = cache?.files ?? [:]+ let directory = HistoryStorage.eventsDirectoryURL(in: directoryURL)+ let cutoff = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate(today: now))+ let dates = HistoryStorage.eventLogDateKeys(in: directory).filter { $0 >= cutoff }+ journalFiles = journalFiles.filter { dates.contains($0.key) }+ scannedFiles = scannedFiles.filter { dates.contains($0.key) }+ for date in dates {+ let url = HistoryStorage.eventLogURL(for: date, in: directory)+ guard let stat = HistoryStorage.fileStat(at: url) else { continue }+ let previous = journalFiles[date]+ if previous?.size == stat.size, previous?.identifier == stat.identifier,+ previous?.modificationTime == stat.modificationTime, scannedFiles[date] == stat {+ continue+ }+ let offset = previous.flatMap { $0.identifier == stat.identifier && $0.size < stat.size ? $0.size : nil } ?? 0+ var invalid = false+ try AppServerEventJournal.read(at: url, from: offset, onInvalidLine: { invalid = true }, consume: { entry in+ if let observation = entry.observation {+ records[observation.turn.id] = try observation.applying(to: records[observation.turn.id])+ Self.ensureRoot(for: observation, in: &records)+ } else if let turn = entry.token {+ records[turn.id] = records[turn.id]?.merging(turn) ?? turn+ }+ })+ if invalid, cache == nil {+ throw TokenCacheError.incompleteJournal+ }+ journalFiles[date] = TokenJournalCheckpoint(size: stat.size, identifier: stat.identifier, modificationTime: stat.modificationTime)+ scannedFiles[date] = stat+ }+ return retained(records, now: now)+ }++ private func save(_ records: [String: TokenTurn]) throws {+ // 日志与缓存共用时间编码, 避免 epoch 换算精度差异影响重建标记比较+ let data = try AppServerEventRecord.encode(TokenAggregateCache(turns: records, files: journalFiles))+ guard (try? Data(contentsOf: ledgerURL)) != data else { return }+ try FileManager.default.createDirectory(at: ledgerURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ try data.write(to: ledgerURL, options: .atomic)+ }++ private func retained(_ records: [String: TokenTurn], now: Date) -> [String: TokenTurn] {+ let cutoff = HistoryStorage.retentionCutoffDate(today: now)+ let roots = Set(records.values.filter { $0.updatedAt >= cutoff }.map(\.rootID))+ return records.filter { $0.value.updatedAt >= cutoff || roots.contains($0.key) }+ }+}++private nonisolated struct TokenAggregateCache: Codable {+ static let currentVersion = 2+ var version = Self.currentVersion+ var turns: [String: TokenTurn]+ var files: [String: TokenJournalCheckpoint]+}++private nonisolated struct TokenJournalCheckpoint: Codable {+ let size: UInt64+ let identifier: UInt64+ let modificationTime: Int64+}++nonisolated struct TokenRebuildResult {+ let dateKeys: [String]+ let turnCount: Int+ static let empty = Self(dateKeys: [], turnCount: 0)+}++nonisolated struct TokenFileCache<Value: Codable & Equatable> {+ let url: URL+ private var data: Data?+ private var value: Value?++ init(url: URL) {+ self.url = url+ }++ mutating func load(validate: (Data) throws -> Void = { _ in }) throws -> Value? {+ guard FileManager.default.fileExists(atPath: url.path) else {+ data = nil+ value = nil+ return nil+ }+ let current = try Data(contentsOf: url)+ if current == data {+ return value+ }+ try validate(current)+ let decoded = try JSONLines.decoder.decode(Value.self, from: current)+ data = current+ value = decoded+ return decoded+ }++ mutating func save(_ updated: Value) throws {+ let current = try? Data(contentsOf: url)+ if let current, current == data, updated == value {+ return+ }+ let encoded = try JSONLines.stableEncoder.encode(updated)+ if current != encoded {+ try encoded.write(to: url, options: .atomic)+ }+ data = encoded+ value = updated+ }+}++nonisolated enum TokenCacheError: Error { case unsupportedVersion(Int), incompleteJournal }diff --git a/CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift b/CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swiftindex ffc8195..f19ee1d 100644--- a/CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift+++ b/CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift@@ -33,7 +33,7 @@ final class AutoResetWakeScheduler {var onErrorMessageChanged: ((String?) -> Void)?- private let runtimeStatusMonitor = HelperRuntimeStatusMonitor()+ private let runtimeStatusMonitor = HelperStatusMonitor()private var isRequested = falseprivate var isHelperReady = falseprivate var desiredWakeDate: Date?@@ -204,7 +204,7 @@ final class AutoResetWakeScheduler {}private func cancelOwnedSchedule(reason: String) async -> Bool {- for delay in KeepAliveHelperConfiguration.wakeCancellationRetryDelays {+ for delay in HelperConfiguration.wakeCancellationRetryDelays {if delay > .zero {try? await Task.sleep(for: delay)}@@ -215,7 +215,7 @@ final class AutoResetWakeScheduler {let result = await runtimeStatusMonitor.setAutoResetWakeSchedule(connection: connection ?? makeConnection(),unixTimestamp: 0,- timeout: KeepAliveHelperConfiguration.requestTimeout+ timeout: HelperConfiguration.requestTimeout)guard !Task.isCancelled else {return false@@ -270,7 +270,7 @@ final class AutoResetWakeScheduler {let result = await runtimeStatusMonitor.setAutoResetWakeSchedule(connection: connection ?? makeConnection(),unixTimestamp: requestedDate?.timeIntervalSince1970 ?? 0,- timeout: KeepAliveHelperConfiguration.requestTimeout+ timeout: HelperConfiguration.requestTimeout)guard !Task.isCancelled, isHelperReady else {return@@ -304,11 +304,11 @@ final class AutoResetWakeScheduler {appliedSchedule = .unknownerrorMessage = KeepAliveLocalizedMessage.autoResetWakeScheduleFailed- guard retryIndex < KeepAliveHelperConfiguration.wakeScheduleRetryDelays.count else {+ guard retryIndex < HelperConfiguration.wakeScheduleRetryDelays.count else {return}- let delay = KeepAliveHelperConfiguration.wakeScheduleRetryDelays[retryIndex]+ let delay = HelperConfiguration.wakeScheduleRetryDelays[retryIndex]retryIndex += 1try? await Task.sleep(for: delay)}diff --git a/CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swift b/CodexBar/Services/KeepAlive/HelperConfiguration.swiftsimilarity index 98%rename from CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swiftrename to CodexBar/Services/KeepAlive/HelperConfiguration.swiftindex 32e0e8a..306325c 100644--- a/CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swift+++ b/CodexBar/Services/KeepAlive/HelperConfiguration.swift@@ -5,7 +5,7 @@ import Securityimport ServiceManagement@MainActor-enum KeepAliveHelperConfiguration {+enum HelperConfiguration {static let registrationRetryDelays: [Duration] = [.milliseconds(500),.seconds(1),@@ -243,7 +243,7 @@ final class HelperPackageValidation: ObservableObject {let machServiceName = CodexBarHelperIPC.machServiceNametask = Task { [weak self] inlet worker = Task.detached(priority: .utility) {- KeepAliveHelperConfiguration.validatePackage(appURL: appURL, machServiceName: machServiceName)+ HelperConfiguration.validatePackage(appURL: appURL, machServiceName: machServiceName)}let result = await worker.valueguard let self, !Task.isCancelled else { return }diff --git a/CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift b/CodexBar/Services/KeepAlive/HelperStatusMonitor.swiftsimilarity index 99%rename from CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swiftrename to CodexBar/Services/KeepAlive/HelperStatusMonitor.swiftindex fca8755..e305fe5 100644--- a/CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift+++ b/CodexBar/Services/KeepAlive/HelperStatusMonitor.swift@@ -24,7 +24,7 @@ struct HelperRuntimeStatus {}@MainActor-final class HelperRuntimeStatusMonitor {+final class HelperStatusMonitor {enum WakeScheduleResult {case successcase helperFailure(Int32)diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swiftindex ccab818..4b86d7a 100644--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift@@ -87,8 +87,7 @@ final class KeepAliveController: ObservableObject {isEnabled && isPreventingSleep}- private let activityMonitor: CodexActivityMonitor- private let advancedModeSettings: AdvancedModeSettings+ private let activityMonitor: ActivityMonitorprivate let defaults: UserDefaultsprivate let systemSleepService = SystemSleepService()private let powerSourceMonitor = PowerSourceMonitor()@@ -112,7 +111,7 @@ final class KeepAliveController: ObservableObject {private var pendingRequestCompletion: ((Bool) -> Void)?private var retryTask: Task<Void, Never>?private var requestTimeoutTask: Task<Void, Never>?- private let helperRuntimeStatusMonitor = HelperRuntimeStatusMonitor()+ private let helperStatusMonitor = HelperStatusMonitor()private var retryAttempt = 0private var helperRegistrationTask: Task<Void, Never>?private let helperPackageValidation = HelperPackageValidation()@@ -133,22 +132,16 @@ final class KeepAliveController: ObservableObject {private var isStarted = falseprivate var isPreparingForTermination = falseprivate var lastLoggedSleepConditions: SleepConditions?- /// advancedModeSettings.isOperable 的最新值, 由订阅维护- /// 不直接读那个属性: 订阅回调跑在 willSet, 那时它还是改动前的值- private var isAdvancedModeEnabled: Bool// MARK: - 生命周期init(- activityMonitor: CodexActivityMonitor,- advancedModeSettings: AdvancedModeSettings,+ activityMonitor: ActivityMonitor,defaults: UserDefaults = .standard) {self.activityMonitor = activityMonitor- self.advancedModeSettings = advancedModeSettingsself.defaults = defaultsdurationLimiter = KeepAliveDurationLimiter(defaults: defaults)- isAdvancedModeEnabled = advancedModeSettings.isOperableisEnabled = defaults.bool(forKey: Self.enabledKey)// 默认关闭: 老版本升上来的用户不该多出一条中断任务的路径lowBatteryThreshold = (defaults.object(forKey: Self.lowBatteryThresholdKey) as? Int)@@ -157,7 +150,7 @@ final class KeepAliveController: ObservableObject {keepsAwakeWhileWaiting = defaults.bool(forKey: Self.keepsAwakeWhileWaitingKey)// 默认关闭: 它会让人离开后机器一直停在解锁状态, 这个取舍只能由用户自己做keepsDisplayAwake = defaults.bool(forKey: Self.keepsDisplayAwakeKey)- activityMonitor.setActivityProtectionEnabled(isEnabled)+ activityMonitor.setProtectionEnabled(isEnabled)autoResetWakeScheduler.onErrorMessageChanged = { [weak self] message inself?.autoResetWakeScheduleErrorMessage = message}@@ -172,21 +165,6 @@ final class KeepAliveController: ObservableObject {.sink { [weak self] in self?.objectWillChange.send() }.store(in: &cancellables)- // 进阶模式是本功能的依赖, 不是用户意图- // 只重新求值当前该不该防止系统睡眠, 绝不改写用户保存的开关- // 看 isOperable 那两个输入而不是只看 isEnabled: Codex 那边全局关掉 hooks- // 或者不信任我们的 handler 时事件送不过来, 任务恒为空, 防睡眠也就不该显示成可用- // @Published 在 willSet 就发信号, 此刻回读 advancedModeSettings.isOperable 会拿到- // 正在变的那一项的旧值; CombineLatest 的两个参数都是各自的新值, 所以只认闭包参数- Publishers.CombineLatest(advancedModeSettings.$isEnabled, advancedModeSettings.$isVerified)- .map { $0 && $1 }- .removeDuplicates()- .sink { [weak self] isOperable in- self?.isAdvancedModeEnabled = isOperable- self?.reconcileSleepState(trigger: .advancedModeChanged)- }- .store(in: &cancellables)-activityMonitor.$snapshot.sink { [weak self] snapshot inself?.handleActivitySnapshot(snapshot)@@ -298,10 +276,6 @@ final class KeepAliveController: ObservableObject {// MARK: - 设置入口func setEnabled(_ enabled: Bool) {- // 与 sleepBlockReason 读同一份镜像, 类内只保留一个进阶模式状态的真相来源- guard !enabled || isAdvancedModeEnabled else {- return- }guard enabled != isEnabled else {return}@@ -309,7 +283,7 @@ final class KeepAliveController: ObservableObject {AppLog.keepAlive.notice("KeepAlive 开关变更: enabled=\(enabled ? 1 : 0)")isEnabled = enableddefaults.set(enabled, forKey: Self.enabledKey)- activityMonitor.setActivityProtectionEnabled(enabled)+ activityMonitor.setProtectionEnabled(enabled)registrationErrorMessage = niloperationErrorMessage = nil@@ -503,7 +477,7 @@ final class KeepAliveController: ObservableObject {hasNotifiedLowBattery = false}- private func handleActivitySnapshot(_ snapshot: CodexActivitySnapshot) {+ private func handleActivitySnapshot(_ snapshot: ActivitySnapshot) {let runningTaskIDs = keepAliveTaskIDs(in: snapshot.runningTasks)let currentWaitingTaskIDs = keepAliveTaskIDs(in: snapshot.waitingTasks)let activeTaskIDs = runningTaskIDs.union(currentWaitingTaskIDs)@@ -525,7 +499,7 @@ final class KeepAliveController: ObservableObject {reconcileSleepState(trigger: .taskChanged)}- private func keepAliveTaskIDs(in tasks: [CodexActivityTaskSnapshot]) -> Set<UUID> {+ private func keepAliveTaskIDs(in tasks: [ActivityTaskSnapshot]) -> Set<UUID> {Set(tasks.lazy.filter { !$0.isAnonymous }.map(\.id))}@@ -549,15 +523,15 @@ final class KeepAliveController: ObservableObject {return}- let service = KeepAliveHelperConfiguration.service+ let service = HelperConfiguration.servicerefreshHelperStatus()switch helperStatus {case .enabled, .requiresApproval:- if KeepAliveHelperConfiguration.registrationNeedsRefresh(defaults: defaults) {+ if HelperConfiguration.registrationNeedsRefresh(defaults: defaults) {refreshRegisteredHelper()} else if helperStatus == .enabled,- let updateIdentifier = KeepAliveHelperConfiguration.pendingUpdateIdentifier(+ let updateIdentifier = HelperConfiguration.pendingUpdateIdentifier(defaults: defaults) {completePendingHelperUpdate(updateIdentifier)@@ -566,7 +540,7 @@ final class KeepAliveController: ObservableObject {}returncase .notRegistered, .notFound:- guard KeepAliveHelperConfiguration.assetsArePresent else {+ guard HelperConfiguration.assetsArePresent else {helperPackageValidation.reportMissingAssets()return}@@ -586,9 +560,9 @@ final class KeepAliveController: ObservableObject {}refreshHelperStatus()- KeepAliveHelperConfiguration.recordRegistration(defaults: defaults, status: helperStatus)+ HelperConfiguration.recordRegistration(defaults: defaults, status: helperStatus)if helperStatus == .enabled,- let updateIdentifier = KeepAliveHelperConfiguration.pendingUpdateIdentifier(+ let updateIdentifier = HelperConfiguration.pendingUpdateIdentifier(defaults: defaults) {completePendingHelperUpdate(updateIdentifier)@@ -599,13 +573,13 @@ final class KeepAliveController: ObservableObject {private func refreshRegisteredHelper() {let requiresSleepReset = helperStatus == .enabledguard helperRegistrationTask == nil,- KeepAliveHelperConfiguration.assetsArePresent else {+ HelperConfiguration.assetsArePresent else {return}guard autoResetWakeScheduler.beginHelperInterruptionPreparation() else {return}- guard let updateIdentifier = KeepAliveHelperConfiguration.beginUpdate(+ guard let updateIdentifier = HelperConfiguration.beginUpdate(defaults: defaults,requiresSleepReset: requiresSleepReset) else {@@ -621,7 +595,7 @@ final class KeepAliveController: ObservableObject {registrationErrorMessage = niloperationErrorMessage = nil- let service = KeepAliveHelperConfiguration.service+ let service = HelperConfiguration.servicehelperRegistrationTask = Task { @MainActor [weak self] inguard let self else {return@@ -648,7 +622,7 @@ final class KeepAliveController: ObservableObject {var helperWasUpdated = falseif updateError == nil,helperStatus.isRegisteredOrAwaitingApproval {- KeepAliveHelperConfiguration.recordRegistration(+ HelperConfiguration.recordRegistration(defaults: defaults,status: helperStatus)@@ -693,7 +667,7 @@ final class KeepAliveController: ObservableObject {private func refreshHelperStatus() {let previousStatus = helperStatus- assign(HelperStatus(KeepAliveHelperConfiguration.service.status), to: \.helperStatus)+ assign(HelperStatus(HelperConfiguration.service.status), to: \.helperStatus)// 每次 App 激活都会跑, 只记真正的迁移, 否则日志会被无变化的求值淹没// 取局部量再插值: Logger 的插值是 autoclosure, 直接写属性会被要求显式 self, 与 --self remove 冲突let currentStatus = helperStatus@@ -780,10 +754,10 @@ final class KeepAliveController: ObservableObject {publishNotificationDependencies()}- /// 通知选项是否可用取决于用户开关, 进阶模式, 电量和时长上限+ /// 通知选项是否可用取决于用户开关, 电量和时长上限/// 各输入的更新路径统一调用此方法, 避免各自维护判定规则private func publishNotificationDependencies() {- let isKeepAliveUsable = isEnabled && isAdvancedModeEnabled+ let isKeepAliveUsable = isEnabledassign(isKeepAliveUsable && hasBattery && lowBatteryThreshold != .off,to: \.isLowBatteryProtectionEnabled@@ -798,7 +772,7 @@ final class KeepAliveController: ObservableObject {/// 因任务, 电量或时长暂停防睡眠时, 仍允许修改设置private static func allowsOptions(_ blockReason: SleepBlockReason?) -> Bool {switch blockReason {- case .notStarted, .userOff, .advancedModeDisabled, .helperUnavailable, .terminating:+ case .notStarted, .userOff, .helperUnavailable, .terminating:falsecase nil, .noTasks, .helperRefreshing, .lowBattery, .limitReached:true@@ -813,7 +787,6 @@ final class KeepAliveController: ObservableObject {let conditions = SleepConditions(blockReason: blockReason,enabled: isEnabled,- advancedMode: isAdvancedModeEnabled,tasks: hasKeepAliveTasks,helper: helperStatus,refreshing: isRefreshingHelper,@@ -833,7 +806,6 @@ final class KeepAliveController: ObservableObject {"trigger=\(triggerName)","want=\(blockReason == nil ? 1 : 0)","enabled=\(conditions.enabled ? 1 : 0)",- "advancedMode=\(conditions.advancedMode ? 1 : 0)","tasks=\(conditions.tasks ? 1 : 0)","helper=\(helperName)","refreshing=\(conditions.refreshing ? 1 : 0)",@@ -873,7 +845,7 @@ final class KeepAliveController: ObservableObject {}}- helperRuntimeStatusMonitor.cancelRequest()+ helperStatusMonitor.cancelRequest()completePendingRequest(success: false)let connection = connection ?? makeConnection()appliedSleepPreventionRequested = requested@@ -1091,13 +1063,13 @@ final class KeepAliveController: ObservableObject {}private func fetchHelperRuntimeStatus() async -> HelperRuntimeStatus? {- guard !requestInFlight, !helperRuntimeStatusMonitor.isRequestInFlight else {+ guard !requestInFlight, !helperStatusMonitor.isRequestInFlight else {return nil}let connection = connection ?? makeConnection()- return await helperRuntimeStatusMonitor.fetch(+ return await helperStatusMonitor.fetch(connection: connection,- timeout: KeepAliveHelperConfiguration.requestTimeout,+ timeout: HelperConfiguration.requestTimeout,onConnectionFailure: { [weak self] error inself?.handleConnectionFailure(error)},@@ -1108,14 +1080,14 @@ final class KeepAliveController: ObservableObject {}private func resetSleepAfterHelperUpdate(_ updateIdentifier: String) async -> Bool {- guard !requestInFlight, !helperRuntimeStatusMonitor.isRequestInFlight else {+ guard !requestInFlight, !helperStatusMonitor.isRequestInFlight else {return false}let connection = connection ?? makeConnection()- return await helperRuntimeStatusMonitor.resetSleepAfterUpdate(+ return await helperStatusMonitor.resetSleepAfterUpdate(connection: connection,updateIdentifier: updateIdentifier,- timeout: KeepAliveHelperConfiguration.requestTimeout,+ timeout: HelperConfiguration.requestTimeout,onConnectionFailure: { [weak self] error inself?.handleConnectionFailure(error)},@@ -1210,14 +1182,14 @@ final class KeepAliveController: ObservableObject {private func scheduleRequestTimeout(for requested: Bool, generation: UInt64) {requestTimeoutTask?.cancel()requestTimeoutTask = Task { @MainActor [weak self] in- try? await Task.sleep(for: KeepAliveHelperConfiguration.requestTimeout)+ try? await Task.sleep(for: HelperConfiguration.requestTimeout)// 认状态而不是认取消位: 每条取消路径都同时推进了 generation 或清了 in-flight,// 认状态就不必依赖将来每个新路径都记得 cancelguard let self, generation == requestGeneration, requestInFlight else {return}- let timeout = LogDuration.seconds(KeepAliveHelperConfiguration.requestTimeout)+ let timeout = LogDuration.seconds(HelperConfiguration.requestTimeout)let details = LogFields.joined("op=\(requested ? "acquire" : "release")","generation=\(generation)",@@ -1236,7 +1208,7 @@ final class KeepAliveController: ObservableObject {private func invalidateConnection() {cancelRequestTimeout()cancelExternalObservation()- helperRuntimeStatusMonitor.cancelRequest()+ helperStatusMonitor.cancelRequest()requestGeneration &+= 1let connection = connectionself.connection = nil@@ -1277,8 +1249,8 @@ final class KeepAliveController: ObservableObject {cancelExternalObservation()return}- helperRuntimeStatusMonitor.startObservation(- interval: KeepAliveHelperConfiguration.externalObservationInterval+ helperStatusMonitor.startObservation(+ interval: HelperConfiguration.externalObservationInterval) { [weak self] inguard let self,sleepPreventionSource == .external,@@ -1320,7 +1292,7 @@ final class KeepAliveController: ObservableObject {}private func cancelExternalObservation() {- helperRuntimeStatusMonitor.cancelObservation()+ helperStatusMonitor.cancelObservation()}// MARK: - 屏幕常亮@@ -1381,15 +1353,15 @@ final class KeepAliveController: ObservableObject {// 每次重试都会重建特权连接并以 root 拉起 pmset// 限制重试次数, 避免 helper 持续失败时反复拉起特权进程- guard retryAttempt < KeepAliveHelperConfiguration.sleepToggleRetryDelays.count else {+ guard retryAttempt < HelperConfiguration.sleepToggleRetryDelays.count else {AppLog.keepAlive.error(- "KeepAlive 切换重试已放弃: attempts=\(KeepAliveHelperConfiguration.sleepToggleRetryDelays.count)"+ "KeepAlive 切换重试已放弃: attempts=\(HelperConfiguration.sleepToggleRetryDelays.count)")operationErrorMessage = KeepAliveLocalizedMessage.retryLimitReachedreturn}- let delay = KeepAliveHelperConfiguration.sleepToggleRetryDelays[retryAttempt]+ let delay = HelperConfiguration.sleepToggleRetryDelays[retryAttempt]retryAttempt += 1let attempt = retryAttemptlet wait = LogDuration.seconds(delay)@@ -1444,10 +1416,7 @@ final class KeepAliveController: ObservableObject {if !isEnabled {return .userOff}- if !isAdvancedModeEnabled {- return .advancedModeDisabled- }- // 先检查依赖, 避免进阶模式恢复任务前以 noTasks 提前放出未授权 Helper 的设置入口+ // 先检查依赖, 避免任务恢复前以 noTasks 提前放出未授权 Helper 的设置入口if helperStatus != .enabled {return .helperUnavailable}@@ -1487,7 +1456,7 @@ extension KeepAliveController {try await service.unregister()mayHaveHelperLease = falsetry Task.checkCancellation()- try await KeepAliveHelperConfiguration.registerRefreshedHelper(service)+ try await HelperConfiguration.registerRefreshedHelper(service)}func setAutoResetRequested(_ requested: Bool) {@@ -1513,10 +1482,10 @@ extension KeepAliveController {private var isHelperReadyForAutoResetWake: Bool {guard helperStatus == .enabled,!isRefreshingHelper,- !KeepAliveHelperConfiguration.registrationNeedsRefresh(defaults: defaults) else {+ !HelperConfiguration.registrationNeedsRefresh(defaults: defaults) else {return false}- return KeepAliveHelperConfiguration.pendingUpdateIdentifier(defaults: defaults) == nil+ return HelperConfiguration.pendingUpdateIdentifier(defaults: defaults) == nil}private func reconcileAutoResetWakeSchedule() {@@ -1560,7 +1529,7 @@ private extension KeepAliveController {}func completeHelperUpdate(_ updateIdentifier: String) async -> Bool {- for delay in KeepAliveHelperConfiguration.updateCompletionRetryDelays {+ for delay in HelperConfiguration.updateCompletionRetryDelays {if delay > .zero {try? await Task.sleep(for: delay)}@@ -1573,7 +1542,7 @@ private extension KeepAliveController {continue}if await resetSleepAfterHelperUpdate(updateIdentifier) {- KeepAliveHelperConfiguration.completeUpdate(+ HelperConfiguration.completeUpdate(updateIdentifier,defaults: defaults)diff --git a/CodexBar/Services/KeepAlive/KeepAliveModels.swift b/CodexBar/Services/KeepAlive/KeepAliveModels.swiftindex 844e52c..7793173 100644--- a/CodexBar/Services/KeepAlive/KeepAliveModels.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveModels.swift@@ -116,7 +116,6 @@ extension KeepAliveController {enum SleepBlockReason: String {case notStartedcase userOff- case advancedModeDisabledcase noTaskscase helperUnavailablecase helperRefreshing@@ -131,7 +130,6 @@ extension KeepAliveController {struct SleepConditions: Equatable {let blockReason: SleepBlockReason?let enabled: Bool- let advancedMode: Boollet tasks: Boollet helper: HelperStatuslet refreshing: Booldiff --git a/CodexBar/Services/Notifications/NotificationContent.swift b/CodexBar/Services/Notifications/NotificationContent.swiftnew file mode 100644index 0000000..18d1ca9--- /dev/null+++ b/CodexBar/Services/Notifications/NotificationContent.swift@@ -0,0 +1,183 @@+import Foundation++nonisolated struct NotificationContent: Equatable {+ /// 只用于日志分类, 由各静态工厂带出, 保证与实际内容不会错位+ let kind: String+ let title: String+ let body: String++ static func lowQuota(+ limitTitle: String,+ windowLabel: String,+ thresholdPercent: Int+ ) -> NotificationContent {+ let thresholdText = CodexPercentageFormat.string(from: thresholdPercent)+ return NotificationContent(+ kind: "lowQuota",+ title: String(localized: "notification.low-quota.title"),+ body: String(+ localized: "notification.low-quota.body",+ defaultValue: "\(limitTitle)\(windowLabel)\(thresholdText)"+ )+ )+ }++ static func quotaReset(+ limitTitle: String,+ windowLabel: String+ ) -> NotificationContent {+ NotificationContent(+ kind: "quotaReset",+ title: String(localized: "notification.quota-reset.title"),+ body: String(+ localized: "notification.quota-reset.body",+ defaultValue: "\(limitTitle)\(windowLabel)"+ )+ )+ }++ static func autoResetSucceeded(remainingCount: Int?) -> NotificationContent {+ let body = if let remainingCount {+ String(+ localized: "notification.auto-reset.body.count",+ defaultValue: "\(remainingCount)"+ )+ } else {+ ""+ }++ return NotificationContent(+ kind: "autoResetSucceeded",+ title: String(localized: "notification.auto-reset.title"),+ body: body+ )+ }++ static func autoResetFailed(+ reason: AutoResetFailureNotice+ ) -> NotificationContent {+ let body = switch reason {+ case .expired:+ String(localized: "notification.auto-reset-failed.body.expired")+ case .authentication:+ String(localized: "notification.auto-reset-failed.body.authentication")+ case .permanent:+ String(localized: "notification.auto-reset-failed.body.permanent")+ }++ return NotificationContent(+ kind: "autoResetFailed",+ title: String(localized: "notification.auto-reset-failed.title"),+ body: body+ )+ }++ static func taskCompleted(project: String?, duration: TimeInterval) -> NotificationContent {+ let durationText = ActivityDisplayFormat.elapsedDurationFragment(for: duration)+ let body = if let project {+ String(+ localized: "notification.task-completed.body.project",+ defaultValue: "\(project)\(durationText)"+ )+ } else {+ String(+ localized: "notification.task-completed.body.codex",+ defaultValue: "\(durationText)"+ )+ }++ return NotificationContent(+ kind: "taskCompleted",+ title: String(localized: "notification.task-completed.title"),+ body: body+ )+ }++ static func taskWaiting(project: String?, toolName: String?) -> NotificationContent {+ let body = switch (project, toolName) {+ case let (project?, toolName?):+ String(+ localized: "notification.task-waiting.body.project-tool",+ defaultValue: "\(project)\(toolName)"+ )+ case let (project?, nil):+ String(+ localized: "notification.task-waiting.body.project",+ defaultValue: "\(project)"+ )+ case let (nil, toolName?):+ String(+ localized: "notification.task-waiting.body.codex-tool",+ defaultValue: "\(toolName)"+ )+ case (nil, nil):+ String(localized: "notification.task-waiting.body.codex")+ }++ return NotificationContent(+ kind: "taskWaiting",+ title: String(localized: "notification.task-waiting.title"),+ body: body+ )+ }++ static func protection(+ project: String?,+ inactivityDurationText: String+ ) -> NotificationContent {+ let body = if let project {+ String(+ localized: "notification.protection.body.project",+ defaultValue: "\(project)\(inactivityDurationText)"+ )+ } else {+ String(+ localized: "notification.protection.body.codex",+ defaultValue: "\(inactivityDurationText)"+ )+ }++ return NotificationContent(+ kind: "protection",+ title: String(localized: "notification.protection.title"),+ body: body+ )+ }++ static func creditExpiry(count: Int, expirationDate: Date) -> NotificationContent {+ let expirationText = CodexDateFormat.localDisplayString(from: expirationDate)+ return NotificationContent(+ kind: "creditExpiry",+ title: String(localized: "notification.banked-reset-expiry.title"),+ body: String(+ localized: "notification.banked-reset-expiry.body",+ defaultValue: "\(count)\(expirationText)"+ )+ )+ }++ static func lowBattery(percent: Int) -> NotificationContent {+ let percentText = CodexPercentageFormat.string(from: percent)+ return NotificationContent(+ kind: "lowBattery",+ title: String(localized: "notification.keep-alive-ended.title"),+ body: String(+ localized: "notification.keep-alive-ended.low-battery",+ defaultValue: "\(percentText)"+ )+ )+ }++ static func keepAliveLimit(durationText: String) -> NotificationContent {+ NotificationContent(+ kind: "keepAliveLimit",+ title: String(localized: "notification.keep-alive-ended.title"),+ body: String(+ localized: "notification.keep-alive-ended.duration-limit",+ defaultValue: "\(durationText)"+ )+ )+ }+}++// MARK: - UNUserNotificationCenterDelegatediff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/NotificationService.swiftsimilarity index 79%rename from CodexBar/Services/Notifications/CodexNotificationService.swiftrename to CodexBar/Services/Notifications/NotificationService.swiftindex bd9b2d0..98911ba 100644--- a/CodexBar/Services/Notifications/CodexNotificationService.swift+++ b/CodexBar/Services/Notifications/NotificationService.swift@@ -12,10 +12,10 @@ nonisolated enum AutoResetFailureNotice: String, Sendable {/// 集中式提醒服务: 订阅额度与实时活动, 负责触觉反馈; 阈值判定; 去重; 重置识别与本地通知发送@MainActor-final class CodexNotificationService: NSObject {+final class NotificationService: NSObject {private let settings: NotificationSettingsprivate let statusViewModel: CodexStatusViewModel- private let activityMonitor: CodexActivityMonitor+ private let activityMonitor: ActivityMonitorprivate let defaults: UserDefaultsprivate nonisolated let openMenuSurface: @MainActor @Sendable () -> Void@@ -54,7 +54,7 @@ final class CodexNotificationService: NSObject {init(settings: NotificationSettings,statusViewModel: CodexStatusViewModel,- activityMonitor: CodexActivityMonitor,+ activityMonitor: ActivityMonitor,defaults: UserDefaults = .standard,openMenuSurface: @escaping @MainActor @Sendable () -> Void) {@@ -116,9 +116,9 @@ final class CodexNotificationService: NSObject {.store(in: &cancellables)}- // MARK: - Hook 任务提醒+ // MARK: - 任务提醒- private func handleActivityTransition(_ transition: CodexActivityTransition) {+ private func handleActivityTransition(_ transition: ActivityTransition) {guard !transition.isAnonymous else {return}@@ -137,7 +137,7 @@ final class CodexNotificationService: NSObject {let identifier = Self.taskWaitingNotificationIdentifier(for: taskID)taskWaitingNotificationIdentifiers.insert(identifier)send(- .taskWaiting(project: task.projectName, toolName: task.toolName),+ .taskWaiting(project: task.projectName, toolName: task.toolDisplayName),sound: settings.taskWaitingSound,identifier: identifier,isStillRelevant: { [weak self] in@@ -176,7 +176,7 @@ final class CodexNotificationService: NSObject {return isStillWaiting}- private func reconcileTaskWaitingNotifications(with snapshot: CodexActivitySnapshot) {+ private func reconcileTaskWaitingNotifications(with snapshot: ActivitySnapshot) {let activeIdentifiers = Set(snapshot.waitingTasks.map {Self.taskWaitingNotificationIdentifier(for: $0.id)})@@ -216,24 +216,24 @@ final class CodexNotificationService: NSObject {// MARK: - 异常任务保护- func notifyActivityProtection(_ notice: CodexActivityProtectionNotice) async -> Bool {+ func notifyProtection(_ notice: ProtectionNotice) async -> Bool {guard settings.canDeliver else {return false}- let identifier = Self.activityProtectionNotificationIdentifier(+ let identifier = Self.protectionNotificationIdentifier(taskID: notice.taskID,attemptID: notice.attemptID)let deliveryTask = send(- .activityProtection(+ .protection(project: notice.projectName,inactivityDurationText: notice.inactivityDurationText),sound: .systemDefault,identifier: identifier,isStillRelevant: { [weak self] in- self?.activityMonitor.isInactivityProtectionNoticeRelevant(+ self?.activityMonitor.isProtectionNoticeRelevant(taskID: notice.taskID,attemptID: notice.attemptID) ?? false@@ -243,8 +243,8 @@ final class CodexNotificationService: NSObject {return await deliveryTask?.value ?? false}- func invalidateActivityProtectionNotification(taskID: UUID, attemptID: UUID) {- let identifier = Self.activityProtectionNotificationIdentifier(+ func invalidateProtectionNotification(taskID: UUID, attemptID: UUID) {+ let identifier = Self.protectionNotificationIdentifier(taskID: taskID,attemptID: attemptID)@@ -598,13 +598,13 @@ final class CodexNotificationService: NSObject {/// - Returns: 提交任务, 调用方可 await 其 value 获取提交结果@discardableResultprivate func send(- _ notification: CodexNotificationContent,+ _ notification: NotificationContent,sound: NotificationSoundOption,identifier: String = UUID().uuidString,dedupKey: String? = nil,isStillRelevant: (() -> Bool)? = nil,onSubmissionFailure: (() -> Void)? = nil,- retryCount: Int = CodexNotificationService.notificationSubmissionRetryCount+ retryCount: Int = NotificationService.notificationSubmissionRetryCount) -> Task<Bool, Never>? {let kind = notification.kindif let dedupKey {@@ -715,11 +715,11 @@ final class CodexNotificationService: NSObject {"taskWaiting|\(taskID.uuidString)"}- private nonisolated static func activityProtectionNotificationIdentifier(+ private nonisolated static func protectionNotificationIdentifier(taskID: UUID,attemptID: UUID) -> String {- "activityProtection|\(taskID.uuidString)|\(attemptID.uuidString)"+ "protection|\(taskID.uuidString)|\(attemptID.uuidString)"}private nonisolated static func quotaWindowStateKey(@@ -772,189 +772,7 @@ final class CodexNotificationService: NSObject {}}-nonisolated struct CodexNotificationContent: Equatable {- /// 只用于日志分类, 由各静态工厂带出, 保证与实际内容不会错位- let kind: String- let title: String- let body: String-- static func lowQuota(- limitTitle: String,- windowLabel: String,- thresholdPercent: Int- ) -> CodexNotificationContent {- let thresholdText = CodexPercentageFormat.string(from: thresholdPercent)- return CodexNotificationContent(- kind: "lowQuota",- title: String(localized: "notification.low-quota.title"),- body: String(- localized: "notification.low-quota.body",- defaultValue: "\(limitTitle)\(windowLabel)\(thresholdText)"- )- )- }-- static func quotaReset(- limitTitle: String,- windowLabel: String- ) -> CodexNotificationContent {- CodexNotificationContent(- kind: "quotaReset",- title: String(localized: "notification.quota-reset.title"),- body: String(- localized: "notification.quota-reset.body",- defaultValue: "\(limitTitle)\(windowLabel)"- )- )- }-- static func autoResetSucceeded(remainingCount: Int?) -> CodexNotificationContent {- let body = if let remainingCount {- String(- localized: "notification.auto-reset.body.count",- defaultValue: "\(remainingCount)"- )- } else {- ""- }-- return CodexNotificationContent(- kind: "autoResetSucceeded",- title: String(localized: "notification.auto-reset.title"),- body: body- )- }-- static func autoResetFailed(- reason: AutoResetFailureNotice- ) -> CodexNotificationContent {- let body = switch reason {- case .expired:- String(localized: "notification.auto-reset-failed.body.expired")- case .authentication:- String(localized: "notification.auto-reset-failed.body.authentication")- case .permanent:- String(localized: "notification.auto-reset-failed.body.permanent")- }-- return CodexNotificationContent(- kind: "autoResetFailed",- title: String(localized: "notification.auto-reset-failed.title"),- body: body- )- }-- static func taskCompleted(project: String?, duration: TimeInterval) -> CodexNotificationContent {- let durationText = CodexActivityDisplayFormat.elapsedDurationFragment(for: duration)- let body = if let project {- String(- localized: "notification.task-completed.body.project",- defaultValue: "\(project)\(durationText)"- )- } else {- String(- localized: "notification.task-completed.body.codex",- defaultValue: "\(durationText)"- )- }-- return CodexNotificationContent(- kind: "taskCompleted",- title: String(localized: "notification.task-completed.title"),- body: body- )- }-- static func taskWaiting(project: String?, toolName: String?) -> CodexNotificationContent {- let body = switch (project, toolName) {- case let (project?, toolName?):- String(- localized: "notification.task-waiting.body.project-tool",- defaultValue: "\(project)\(toolName)"- )- case let (project?, nil):- String(- localized: "notification.task-waiting.body.project",- defaultValue: "\(project)"- )- case let (nil, toolName?):- String(- localized: "notification.task-waiting.body.codex-tool",- defaultValue: "\(toolName)"- )- case (nil, nil):- String(localized: "notification.task-waiting.body.codex")- }-- return CodexNotificationContent(- kind: "taskWaiting",- title: String(localized: "notification.task-waiting.title"),- body: body- )- }-- static func activityProtection(- project: String?,- inactivityDurationText: String- ) -> CodexNotificationContent {- let body = if let project {- String(- localized: "notification.activity-protection.body.project",- defaultValue: "\(project)\(inactivityDurationText)"- )- } else {- String(- localized: "notification.activity-protection.body.codex",- defaultValue: "\(inactivityDurationText)"- )- }-- return CodexNotificationContent(- kind: "activityProtection",- title: String(localized: "notification.activity-protection.title"),- body: body- )- }-- static func creditExpiry(count: Int, expirationDate: Date) -> CodexNotificationContent {- let expirationText = CodexDateFormat.localDisplayString(from: expirationDate)- return CodexNotificationContent(- kind: "creditExpiry",- title: String(localized: "notification.banked-reset-expiry.title"),- body: String(- localized: "notification.banked-reset-expiry.body",- defaultValue: "\(count)\(expirationText)"- )- )- }-- static func lowBattery(percent: Int) -> CodexNotificationContent {- let percentText = CodexPercentageFormat.string(from: percent)- return CodexNotificationContent(- kind: "lowBattery",- title: String(localized: "notification.keep-alive-ended.title"),- body: String(- localized: "notification.keep-alive-ended.low-battery",- defaultValue: "\(percentText)"- )- )- }-- static func keepAliveLimit(durationText: String) -> CodexNotificationContent {- CodexNotificationContent(- kind: "keepAliveLimit",- title: String(localized: "notification.keep-alive-ended.title"),- body: String(- localized: "notification.keep-alive-ended.duration-limit",- defaultValue: "\(durationText)"- )- )- }-}--// MARK: - UNUserNotificationCenterDelegate--extension CodexNotificationService: UNUserNotificationCenterDelegate {+extension NotificationService: UNUserNotificationCenterDelegate {/// 菜单栏常驻应用处于前台时也要展示横幅并播放声音nonisolated func userNotificationCenter(_: UNUserNotificationCenter,diff --git a/CodexBar/Services/Settings/AdvancedModeSettings.swift b/CodexBar/Services/Settings/AdvancedModeSettings.swiftdeleted file mode 100644index 42773d8..0000000--- a/CodexBar/Services/Settings/AdvancedModeSettings.swift+++ /dev/null@@ -1,1119 +0,0 @@-import Combine-import Foundation-import os--/// 进阶模式开关状态机, 同时管理 hooks.json 和 Codex 信任状态-@MainActor-final class AdvancedModeSettings: ObservableObject {- /// 当前进程中的进阶模式开启状态, 首次从现有配置恢复- /// 开启后配置缺失视为需要自愈, 只有显式关闭或明确的低版本会置为 false- @Published private(set) var isEnabled = false- @Published private(set) var isUpdating = false- /// 最近一次校验的明确结论: Codex 会不会真的执行 CodexBar 的 Hook- /// 乐观默认: 启动对账开始前没有反证, 不能提前把依赖进阶模式的功能关掉- /// 只由明确结论写入两个方向, RPC 失败或被取消时保留上次的值:- /// 连不上 app-server 不说明 Hook 坏了, 那时置灰会把好用的功能关掉- @Published private(set) var isVerified = true-- /// Hook 链路真的通不通: 当前进程中开启, 且最近一次校验没有明确失败- /// 依赖进阶模式的下游 (防睡眠, 任务类通知) 一律看这个- /// Codex 那边全局关掉 hooks 或者不信任我们的 handler 时 isEnabled 照样是 true- var isOperable: Bool {- isEnabled && isVerified- }-- /// 读取 hooks.json 失败, 由 refreshInstallationState() 独立维护- @Published private var readErrorMessage: String?- /// 开关操作与 Hook 校验的结果, 只能由下一次操作或校验覆盖- /// 与读取类错误分开存储: 每轮对账都会读取配置, 不能抹掉校验告警- @Published private var operationErrorMessage: String?-- var errorMessage: String? {- operationErrorMessage ?? readErrorMessage- }-- private let hooksURL: URL- private let fileManager: FileManager- private let codexStatusService: CodexStatusService- private let updateCoordinator = RefreshTaskCoordinator()- /// refreshInstallationState() 上次读到的安装结论, 首次读取前为 nil- /// 不能用 isEnabled 代替: 开启后它会刻意不跟随外部配置丢失- private var lastKnownInstalled: Bool?-- init(- hooksURL: URL = AdvancedModeSettings.defaultHooksURL(),- fileManager: FileManager = .default,- codexStatusService: CodexStatusService- ) {- self.hooksURL = hooksURL- self.fileManager = fileManager- self.codexStatusService = codexStatusService- }-- // MARK: - 对外入口-- private func refreshInstallationState() {- do {- let config = try readConfigIfPresent()- let installed = Self.containsAnyManagedHook(- in: config,- executablePath: currentExecutablePath- )- if installed, !isEnabled {- isEnabled = true- }- let isComplete = Self.containsAllManagedHooks(- in: config,- executablePath: currentExecutablePath- )- // 每次开面板都会读一遍, 无条件记会刷屏- // 只在结论变了才记, 外部改动 ~/.codex/hooks.json 就是从这条看出来的- // 首次读取没有可比的上次值; 拿 isEnabled 的初始 false 去比, 会让装了 Hook 的用户每次启动误报一条- if let lastKnownInstalled, lastKnownInstalled != installed {- AppLog.hooks.notice("Hook 配置变化: installed=\(installed ? 1 : 0)")- }- lastKnownInstalled = installed- if isEnabled, !isComplete {- assignVerified(false, reason: .configurationDamaged)- }- if readErrorMessage != nil {- readErrorMessage = nil- }- } catch {- // 只有 I/O 失败和 JSON 格式错误会走到这里, 它们对「Hook 装没装」不提供信息- // 文件不存在或配置里没有 CodexBar 都由 readConfigIfPresent 正常返回- // 因此保留上次已知值, 不能把读取失败当成用户关闭了进阶模式- let details = LogFields.joined(- "detail=\(error.localizedDescription)",- "action=keepLastKnown"- )- AppLog.hooks.error("Hook 读取失败: \(details, privacy: .public)")- readErrorMessage = String(localized: "advanced-mode.hook.error.config-read-failed")- }- }-- func setEnabled(_ enabled: Bool) {- AppLog.hooks.notice("进阶模式开关变更: enabled=\(enabled ? 1 : 0)")- runLatestUpdate(showProgress: true) { settings, generation in- await settings.applyEnabled(enabled, generation: generation)- }- }-- func reconcileConfiguration() {- refreshInstallationState()- guard isEnabled, !isUpdating else {- return- }-- runLatestUpdate(showProgress: false) { settings, generation in- await settings.reconcileConfiguration(generation: generation)- }- }-- // MARK: - 更新流程与并发控制-- private func applyEnabled(_ enabled: Bool, generation: Int) async {- do {- if enabled {- try await ensureAdvancedModeVersionSupported()- try ensureCurrentUpdate(generation)- try await ensureCodexHooksGloballyEnabled()- try ensureCurrentUpdate(generation)- try writeManagedHookConfig(enabled: true)- try ensureCurrentUpdate(generation)- isEnabled = true- await verifyInstalledHooksWithAppServer(generation: generation)- } else {- try await disableAdvancedMode(generation: generation)- }- } catch is CancellationError {- return- } catch {- handleApplyError(error, generation: generation)- }- }-- /// 与手动关闭共用同一事务, 自动关闭也不会遗留另一套清理语义- private func disableAdvancedMode(generation: Int, cleanupTrust: Bool = true) async throws {- // 关闭前先通过 hooks/list 拿到 key- // hooks.json 删除后 app-server 就无法再反查这些 key- let cleanupPlan: ManagedHookTrustCleanupPlan? = if cleanupTrust {- try await hookTrustCleanupPlan(generation: generation)- } else {- nil- }- try ensureCurrentUpdate(generation)- try writeManagedHookConfig(enabled: false)- try ensureCurrentUpdate(generation)- isEnabled = false- operationErrorMessage = nil- guard let cleanupPlan else {- return- }- await cleanupCodexHookTrust(- removing: cleanupPlan.keys,- discoveryError: cleanupPlan.discoveryError,- generation: generation- )- }-- private func reconcileConfiguration(generation: Int) async {- do {- try await ensureAdvancedModeVersionSupported()- try ensureCurrentUpdate(generation)- } catch is CancellationError {- return- } catch CodexStatusError.unsupportedVersion(minimum: _) {- // 低于全局门槛的连接已关闭, 无法通过 app-server 查询或删除信任项- await disableUnsupportedAdvancedMode(- error: .unsupportedCodexVersion(minimum: CodexCLIMinimumVersion.advancedMode),- generation: generation,- cleanupTrust: false- )- return- } catch let error as AdvancedModeError {- guard case .unsupportedCodexVersion = error else {- handleVerificationError(error, generation: generation)- return- }-- await disableUnsupportedAdvancedMode(error: error, generation: generation)- return- } catch {- handleVerificationError(error, generation: generation)- return- }-- do {- // 全局开关关闭时不写用户文件, 等 Codex 恢复后再补齐- let globallyDisabled = try await readGlobalHookDisabled()- try ensureCurrentUpdate(generation)- guard !globallyDisabled else {- assignVerified(false, reason: .globallyDisabled)- operationErrorMessage = AdvancedModeError.hooksGloballyDisabled.localizedDescription- return- }-- try reconcileManagedHookConfig()- try ensureCurrentUpdate(generation)-- try await validateInstalledHooksWithAppServer()- try ensureCurrentUpdate(generation)- assignVerified(true, reason: .verified)- if operationErrorMessage != nil {- operationErrorMessage = nil- }- } catch is CancellationError {- return- } catch {- handleVerificationError(error, generation: generation)- }- }-- private func disableUnsupportedAdvancedMode(- error: AdvancedModeError,- generation: Int,- cleanupTrust: Bool = true- ) async {- do {- try ensureCurrentUpdate(generation)- assignVerified(false, reason: .unsupportedVersion)- try await disableAdvancedMode(generation: generation, cleanupTrust: cleanupTrust)- try ensureCurrentUpdate(generation)- if operationErrorMessage == nil {- operationErrorMessage = error.localizedDescription- }- AppLog.hooks.notice("进阶模式已自动关闭: reason=unsupportedVersion")- } catch is CancellationError {- return- } catch {- handleApplyError(error, generation: generation)- }- }-- private func verifyInstalledHooksWithAppServer(generation: Int) async {- do {- try await ensureAdvancedModeVersionSupported()- try ensureCurrentUpdate(generation)-- // 全局开关排在 hooks/list 之前: 它一关, 列表里必然找不到我们的 handler,- // 那时报"已不完整"会把用户引去翻本来就完好的 hooks.json- let globallyDisabled = try await readGlobalHookDisabled()- try ensureCurrentUpdate(generation)- guard !globallyDisabled else {- assignVerified(false, reason: .globallyDisabled)- operationErrorMessage = AdvancedModeError.hooksGloballyDisabled.localizedDescription- return- }-- try await validateInstalledHooksWithAppServer()- try ensureCurrentUpdate(generation)- assignVerified(true, reason: .verified)- operationErrorMessage = nil- } catch is CancellationError {- return- } catch {- handleVerificationError(error, generation: generation)- }- }-- private func handleVerificationError(_ error: Error, generation: Int) {- guard updateCoordinator.canCommit(generation) else {- return- }-- if let error = error as? AdvancedModeError {- // AdvancedModeError 是明确结论: Codex 答复了, 只是答复说这条链路不通- assignVerified(false, reason: .validationFailed)- operationErrorMessage = error.localizedDescription- } else {- // 这一支是"验不了"而不是"确认不通", isVerified 保留上次的值- operationErrorMessage = String(- localized: "advanced-mode.hook.error.verification-failed",- defaultValue: "\(error.localizedDescription)"- )- }- }-- /// @Published 在 willSet 无条件发信号, 而每次 App 激活都会跑一次校验- /// 同值赋值会让设置页与两个子面板反复空转, 所以走这里- /// reason 是排查依据: 用户只会说"防睡眠灰了", 那时得能从日志看出是全局禁用还是校验没过- /// "验不了"那一支不调这里, 结论保持不变也就不该记一条变化- private func assignVerified(_ verified: Bool, reason: AdvancedModeVerificationReason) {- guard isVerified != verified else {- return- }-- let details = LogFields.joined(- "verified=\(verified ? 1 : 0)",- "reason=\(reason.rawValue)"- )- AppLog.hooks.notice("Hook 链路校验结论变化: \(details, privacy: .public)")- isVerified = verified- }-- private func runLatestUpdate(- showProgress: Bool,- _ operation: @escaping @MainActor @Sendable (AdvancedModeSettings, Int) async -> Void- ) {- if showProgress {- isUpdating = true- operationErrorMessage = nil- }-- updateCoordinator.start { [weak self] generation in- guard let self else {- return- }-- await operation(self, generation)- updateCoordinator.finish(generation) {- if showProgress {- isUpdating = false- }- }- }- }-- private func ensureCurrentUpdate(_ generation: Int) throws {- try Task.checkCancellation()-- guard updateCoordinator.canCommit(generation) else {- throw CancellationError()- }- }-- private func handleApplyError(_ error: Error, generation: Int) {- guard updateCoordinator.canCommit(generation) else {- return- }-- if let advancedModeError = error as? AdvancedModeError,- advancedModeError.isPreflightFailure {- // 前置检查拦下是预期内的拒绝, 配置一个字没动, 不是故障- AppLog.hooks.notice(- "进阶模式前置检查未通过: detail=\(advancedModeError.localizedDescription, privacy: .public)"- )- isEnabled = false- operationErrorMessage = advancedModeError.localizedDescription- } else {- AppLog.hooks.error(- "Hook 写入失败: detail=\(error.localizedDescription, privacy: .public)"- )- refreshInstallationState()- operationErrorMessage = String(localized: "advanced-mode.hook.error.configuration-failed")- }- }-}--private extension AdvancedModeSettings {- typealias JSONObject = [String: Any]- typealias JSONArray = [Any]-- static let hooksKey = "hooks"- static let hookTypeKey = "type"- static let hookCommandKey = "command"- static let hookTimeoutKey = "timeout"- static let hookCommandType = "command"- static let configMergeStrategyReplace = "replace"- static let configMergeStrategyUpsert = "upsert"- static let hookTrustStateKeyPath = "hooks.state"- static let trustedHashKey = "trusted_hash"-- struct ManagedHookTrustEntry {- let key: String- let trustedHash: String- }-- /// discoveryError 会在 Hook 已关闭后展示, 说明仅信任状态清理未完成- struct ManagedHookTrustCleanupPlan {- let keys: Set<String>- let discoveryError: Error?- }-- /// Hook 链路校验结论的变化理由, 只用于日志的 reason= 取值- enum AdvancedModeVerificationReason: String {- case configurationDamaged- case globallyDisabled- case unsupportedVersion- case validationFailed- case verified- }-- enum AdvancedModeError: LocalizedError {- case invalidFormat- case configurationFailed- case hooksGloballyDisabled- case codexVersionUnavailable(minimum: String)- case unsupportedCodexVersion(minimum: String)- case hookValidationFailed(String)-- var errorDescription: String? {- switch self {- case .invalidFormat:- String(localized: "advanced-mode.hook.error.invalid-config-format")- case .configurationFailed:- String(localized: "advanced-mode.hook.error.configuration-failed")- case .hooksGloballyDisabled:- String(localized: "advanced-mode.hook.status.disabled-by-codex")- case let .codexVersionUnavailable(minimum):- String(- localized: "advanced-mode.codex.version.unavailable",- defaultValue: "\(minimum)"- )- case let .unsupportedCodexVersion(minimum):- String(- localized: "advanced-mode.codex.version.unsupported",- defaultValue: "\(minimum)"- )- case let .hookValidationFailed(message):- message- }- }-- var isPreflightFailure: Bool {- switch self {- case .hooksGloballyDisabled, .codexVersionUnavailable, .unsupportedCodexVersion:- true- case .invalidFormat, .configurationFailed, .hookValidationFailed:- false- }- }- }-- nonisolated static func defaultHooksURL() -> URL {- CodexCLIResolver.codexHomeDirectory()- .appendingPathComponent("hooks.json")- }-- var currentExecutablePath: String {- Bundle.main.executableURL?.path- ?? CommandLine.arguments.first- ?? "/Applications/CodexBar.app/Contents/MacOS/CodexBar"- }-- var hooksListWorkingDirectory: String {- fileManager.homeDirectoryForCurrentUser.path- }-- /// Codex 的 config.toml 里 features.hooks 是不是关着- /// 开关流程与校验流程共用这一处读取, 两边对"全局禁用"的判断不会分叉- func readGlobalHookDisabled() async throws -> Bool {- try await codexStatusService.readCodexConfig().hooksGloballyDisabled- }-- func ensureCodexHooksGloballyEnabled() async throws {- if try await readGlobalHookDisabled() {- throw AdvancedModeError.hooksGloballyDisabled- }- }-- /// 检查实际用于 hooks/list 的 app-server 握手版本- /// 不能只看磁盘版本, 否则升级后尚未重连的旧进程会被误判为可用- func ensureAdvancedModeVersionSupported() async throws {- let minimumVersion = CodexCLIMinimumVersion.advancedMode- let connectionInfo = try await codexStatusService.readyConnectionInfo()- guard let currentVersion = connectionInfo.version,- let isSupported = CodexCLIVersionReader.isVersion(- currentVersion,- atLeast: minimumVersion- ) else {- throw AdvancedModeError.codexVersionUnavailable(minimum: minimumVersion)- }-- guard isSupported else {- let details = LogFields.joined(- "current=\(currentVersion)",- "minimum=\(minimumVersion)"- )- AppLog.hooks.notice("Hook 版本不支持: \(details, privacy: .public)")- throw AdvancedModeError.unsupportedCodexVersion(minimum: minimumVersion)- }- }-- func validateInstalledHooksWithAppServer() async throws {- var response = try await codexStatusService.listCodexHooks(cwds: [hooksListWorkingDirectory])- // 只信任 command/sourcePath/event 都匹配当前 CodexBar 的 Hook- let entries = Self.hookTrustEntriesNeedingUpdate(- from: response,- executablePath: currentExecutablePath,- hooksURL: hooksURL- )- if !entries.isEmpty {- do {- try await trustManagedHooks(entries)- } catch {- AppLog.hooks.error(- "Hook 信任自愈失败: detail=\(error.localizedDescription, privacy: .public)"- )- throw AdvancedModeError.hookValidationFailed(- String(localized: "advanced-mode.hook.status.untrusted")- )- }- AppLog.hooks.notice("Hook 信任状态已自愈: keys=\(entries.count)")- response = try await codexStatusService.listCodexHooks(cwds: [hooksListWorkingDirectory])- }-- if let message = Self.validationMessage(- from: response,- executablePath: currentExecutablePath,- hooksURL: hooksURL- ) {- throw AdvancedModeError.hookValidationFailed(message)- }- }-- func hookTrustCleanupPlan(generation: Int) async throws -> ManagedHookTrustCleanupPlan {- do {- let keys = try await managedHookTrustKeysFromAppServer()- try ensureCurrentUpdate(generation)- return .init(keys: keys, discoveryError: nil)- } catch is CancellationError {- throw CancellationError()- } catch {- return .init(keys: [], discoveryError: error)- }- }-- // MARK: - hooks.json 读写-- func writeManagedHookConfig(enabled: Bool) throws {- var config = try readConfigIfPresent()- try Self.removeManagedHooks(- from: &config,- executablePath: currentExecutablePath- )-- if enabled {- _ = try Self.reconcileManagedHooks(- in: &config,- executablePath: currentExecutablePath- )- }-- try write(config)- // 改的是用户自己的 ~/.codex/hooks.json, 每次写入都要留痕- AppLog.hooks.notice("Hook 配置已写入: enabled=\(enabled ? 1 : 0)")- }-- func reconcileManagedHookConfig() throws {- var config = try readConfigIfPresent()- let repairedEvents = try Self.reconcileManagedHooks(- in: &config,- executablePath: currentExecutablePath- )- guard !repairedEvents.isEmpty else {- return- }-- do {- try write(config)- } catch {- AppLog.hooks.error(- "Hook 补齐写入失败: detail=\(error.localizedDescription, privacy: .public)"- )- throw AdvancedModeError.configurationFailed- }- let events = repairedEvents.map(\.rawValue).joined(separator: ",")- let details = LogFields.joined(- "count=\(repairedEvents.count)",- "events=\(events)"- )- AppLog.hooks.notice("Hook 配置已自愈: \(details, privacy: .public)")- }-- func managedHookTrustKeysFromAppServer() async throws -> Set<String> {- let response = try await codexStatusService.listCodexHooks(cwds: [hooksListWorkingDirectory])- return Self.managedHookTrustKeys(- from: response,- executablePath: currentExecutablePath,- hooksURL: hooksURL- )- }-- // MARK: - Hook 信任状态-- func cleanupCodexHookTrust(- removing keys: Set<String>,- discoveryError: Error?,- generation: Int- ) async {- do {- try ensureCurrentUpdate(generation)- if !keys.isEmpty {- try await removeManagedHookTrust(keys)- try ensureCurrentUpdate(generation)- AppLog.hooks.notice("Hook 信任状态已清理: keys=\(keys.count)")- }-- if let discoveryError {- let details = LogFields.joined(- "stage=discovery",- "detail=\(discoveryError.localizedDescription)"- )- AppLog.hooks.error("无法清理 Hook 信任状态: \(details, privacy: .public)")- operationErrorMessage = String(localized: "advanced-mode.hook.error.trust-cleanup-unavailable")- } else {- operationErrorMessage = nil- }- } catch is CancellationError {- return- } catch {- guard updateCoordinator.canCommit(generation) else {- return- }-- let details = LogFields.joined(- "stage=remove",- "detail=\(error.localizedDescription)"- )- AppLog.hooks.error("无法清理 Hook 信任状态: \(details, privacy: .public)")- operationErrorMessage = String(localized: "advanced-mode.hook.error.trust-cleanup-unavailable")- }- }-- func trustManagedHooks(_ entries: [ManagedHookTrustEntry]) async throws {- guard !entries.isEmpty else {- return- }-- try await writeHookTrustState(- Self.hookTrustStateValue(from: entries),- mergeStrategy: Self.configMergeStrategyUpsert- )- }-- func removeManagedHookTrust(_ keys: Set<String>) async throws {- guard !keys.isEmpty else {- return- }-- let response = try await codexStatusService.readCodexConfig()- var state = response.hookTrustState- // 先读出现有 state 再 replace, 只删除 CodexBar key, 保留用户自己的信任项- for key in keys {- state.removeValue(forKey: key)- }-- try await writeHookTrustState(- Self.hookTrustStateValue(from: state),- mergeStrategy: Self.configMergeStrategyReplace- )- }-- func writeHookTrustState(- _ value: [String: [String: String]],- mergeStrategy: String- ) async throws {- _ = try await codexStatusService.writeCodexConfigBatch(- edits: [- .init(- keyPath: Self.hookTrustStateKeyPath,- value: value,- mergeStrategy: mergeStrategy- )- ]- )- }-- func readConfigIfPresent() throws -> JSONObject {- guard fileManager.fileExists(atPath: hooksURL.path) else {- return [:]- }-- return try readConfig()- }-- func readConfig() throws -> JSONObject {- let data = try Data(contentsOf: hooksURL)- guard !data.isEmpty else {- return [:]- }-- let object: Any- do {- object = try JSONSerialization.jsonObject(with: data)- } catch {- throw AdvancedModeError.invalidFormat- }-- guard let config = object as? JSONObject else {- throw AdvancedModeError.invalidFormat- }-- return config- }-- func write(_ config: JSONObject) throws {- try fileManager.createDirectory(- at: hooksURL.deletingLastPathComponent(),- withIntermediateDirectories: true- )-- let data = try JSONSerialization.data(- withJSONObject: config,- options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]- )- try data.write(to: hooksURL, options: .atomic)- }-- static func containsAnyManagedHook(in config: JSONObject, executablePath: String) -> Bool {- guard let hooks = config[hooksKey] as? JSONObject else {- return false- }-- return CodexHookEvent.allCases.contains { event in- guard let groups = hooks[event.configName] as? JSONArray else {- return false- }-- return groups.contains {- groupContainsCodexBarHandler($0, executablePath: executablePath)- }- }- }-- static func containsAllManagedHooks(in config: JSONObject, executablePath: String) -> Bool {- guard let hooks = config[hooksKey] as? JSONObject else {- return false- }-- return CodexHookEvent.allCases.allSatisfy { event in- guard let groups = hooks[event.configName] as? JSONArray else {- return false- }-- return isCanonicalCodexBarEvent(- groups,- event: event,- executablePath: executablePath- )- }- }-- static func reconcileManagedHooks(- in config: inout JSONObject,- executablePath: String- ) throws -> [CodexHookEvent] {- var hooks = try hooksObject(from: config)- var repairedEvents: [CodexHookEvent] = []-- // 每个事件只保留一个标准独立 group, 不和用户已有 group 混写- for event in CodexHookEvent.allCases {- var groups = try eventGroups(named: event.configName, from: hooks)- guard !isCanonicalCodexBarEvent(- groups,- event: event,- executablePath: executablePath- ) else {- continue- }-- groups = groups.compactMap {- groupRemovingCodexBarHandlers(- from: $0,- executablePath: executablePath- )- }- groups.append([- hooksKey: [managedHookHandler(for: event, executablePath: executablePath)]- ])- hooks[event.configName] = groups- repairedEvents.append(event)- }-- config[hooksKey] = hooks- return repairedEvents- }-- static func removeManagedHooks(- from config: inout JSONObject,- executablePath: String- ) throws {- guard config[hooksKey] != nil else {- return- }-- var hooks = try hooksObject(from: config)-- // 仅移除 command 同时匹配当前可执行路径与 --hook-event 的 handler- // 结构异常的同级条目一律跳过: 只负责移除自己的 handler, 不校验整个文件- // 在这里抛错会让开关既关不掉又被 refresh() 翻回打开, 用户无法从 UI 脱困- for (event, value) in hooks {- guard let groups = value as? JSONArray else {- continue- }-- let filteredGroups = groups.compactMap {- groupRemovingCodexBarHandlers(- from: $0,- executablePath: executablePath- )- }-- if filteredGroups.isEmpty {- hooks.removeValue(forKey: event)- } else {- hooks[event] = filteredGroups- }- }-- config[hooksKey] = hooks- }-- static func validationMessage(- from response: CodexHooksListResponse,- executablePath: String,- hooksURL: URL- ) -> String? {- guard !response.data.isEmpty else {- return String(localized: "advanced-mode.hook.result.empty")- }-- let entries = response.data- let hooks = entries.flatMap(\.hooks)- let warnings = entries.flatMap(\.warnings)- let errors = entries.flatMap(\.errors)- let expectedSourcePath = normalizedPath(hooksURL.path)- var hasMissingEvent = false- var hasDisabledHook = false- var hasUnexpectedSource = false- var hasUntrustedHook = false-- for event in CodexHookEvent.allCases {- guard let hook = matchingHook(- for: event,- in: hooks,- executablePath: executablePath,- expectedSourcePath: expectedSourcePath- ) else {- hasMissingEvent = true- continue- }-- hasDisabledHook = hasDisabledHook || !hook.enabled- hasUnexpectedSource = hasUnexpectedSource || normalizedPath(hook.sourcePath) != expectedSourcePath- hasUntrustedHook = hasUntrustedHook || hookNeedsTrustUpdate(hook)- }-- if !errors.isEmpty {- return String(localized: "advanced-mode.hook.result.error")- }- if hasDisabledHook {- return String(localized: "advanced-mode.hook.status.disabled")- }- if hasUntrustedHook {- return String(localized: "advanced-mode.hook.status.untrusted")- }- if hasMissingEvent {- return String(localized: "advanced-mode.hook.status.incomplete")- }- if hasUnexpectedSource {- return String(localized: "advanced-mode.hook.status.unexpected-source")- }- if !warnings.isEmpty {- return String(localized: "advanced-mode.hook.result.warning")- }-- return nil- }-- static func hookTrustEntriesNeedingUpdate(- from response: CodexHooksListResponse,- executablePath: String,- hooksURL: URL- ) -> [ManagedHookTrustEntry] {- let hooks = response.data.flatMap(\.hooks)- let expectedSourcePath = normalizedPath(hooksURL.path)- var entries: [ManagedHookTrustEntry] = []- var seenKeys = Set<String>()-- for event in CodexHookEvent.allCases {- guard let hook = matchingHook(- for: event,- in: hooks,- executablePath: executablePath,- expectedSourcePath: expectedSourcePath- ),- isManagedHook(- hook,- executablePath: executablePath,- expectedSourcePath: expectedSourcePath- ),- hookNeedsTrustUpdate(hook),- let key = hook.key,- let trustedHash = hook.currentHash,- !key.isEmpty,- !trustedHash.isEmpty,- seenKeys.insert(key).inserted else {- continue- }-- entries.append(.init(key: key, trustedHash: trustedHash))- }-- return entries- }-- static func managedHookTrustKeys(- from response: CodexHooksListResponse,- executablePath: String,- hooksURL: URL- ) -> Set<String> {- let expectedSourcePath = normalizedPath(hooksURL.path)- return Set(- response.data- .flatMap(\.hooks)- .compactMap { hook in- guard isManagedHook(- hook,- executablePath: executablePath,- expectedSourcePath: expectedSourcePath- ),- let key = hook.key,- !key.isEmpty else {- return nil- }-- return key- }- )- }-- static func matchingHook(- for event: CodexHookEvent,- in hooks: [CodexHookMetadata],- executablePath: String,- expectedSourcePath: String- ) -> CodexHookMetadata? {- let matchingHooks = hooks.filter {- ($0.command.map { isCodexBarCommand($0, executablePath: executablePath) } ?? false)- && $0.eventName == event.appServerName- }- return matchingHooks.first { normalizedPath($0.sourcePath) == expectedSourcePath }- ?? matchingHooks.first- }-- static func isManagedHook(- _ hook: CodexHookMetadata,- executablePath: String,- expectedSourcePath: String- ) -> Bool {- guard let command = hook.command else {- return false- }-- // 自动信任/清理必须同时匹配命令和 sourcePath, 防止误碰用户 Hook- return isCodexBarCommand(command, executablePath: executablePath)- && normalizedPath(hook.sourcePath) == expectedSourcePath- }-- static func hookNeedsTrustUpdate(_ hook: CodexHookMetadata) -> Bool {- switch hook.trustStatus.lowercased() {- case "untrusted", "modified":- true- default:- false- }- }-- static func hookTrustStateValue(from state: [String: String]) -> [String: [String: String]] {- state.mapValues { [trustedHashKey: $0] }- }-- static func hookTrustStateValue(from entries: [ManagedHookTrustEntry]) -> [String: [String: String]] {- entries.reduce(into: [:]) { value, entry in- value[entry.key] = [trustedHashKey: entry.trustedHash]- }- }-- static func hooksObject(from config: JSONObject) throws -> JSONObject {- guard let value = config[hooksKey] else {- return [:]- }-- guard let hooks = value as? JSONObject else {- throw AdvancedModeError.invalidFormat- }-- return hooks- }-- static func eventGroups(named event: String, from hooks: JSONObject) throws -> JSONArray {- guard let value = hooks[event] else {- return []- }-- guard let groups = value as? JSONArray else {- throw AdvancedModeError.invalidFormat- }-- return groups- }-- static func groupContainsCodexBarHandler(- _ group: Any,- executablePath: String- ) -> Bool {- handlers(from: group)?.contains {- isCurrentCodexBarHandler($0, executablePath: executablePath)- } ?? false- }-- static func isCanonicalCodexBarEvent(- _ groups: JSONArray,- event: CodexHookEvent,- executablePath: String- ) -> Bool {- let managedHandlerCount = groups.reduce(into: 0) { count, group in- count += handlers(from: group)?.count(where: {- isCurrentCodexBarHandler($0, executablePath: executablePath)- }) ?? 0- }- guard managedHandlerCount == 1 else {- return false- }-- return groups.contains {- isCanonicalCodexBarGroup(- $0,- event: event,- executablePath: executablePath- )- }- }-- static func isCanonicalCodexBarGroup(- _ group: Any,- event: CodexHookEvent,- executablePath: String- ) -> Bool {- guard let group = group as? JSONObject,- group.count == 1,- let handlers = handlers(from: group),- handlers.count == 1,- let handler = handlers.first as? JSONObject,- handler.count == 3,- handler[hookTypeKey] as? String == hookCommandType,- handler[hookCommandKey] as? String == hookCommand(executablePath: executablePath),- let timeout = handler[hookTimeoutKey] as? NSNumber else {- return false- }-- return timeout.doubleValue == Double(- WorkflowHookEventRecorder.hookTimeoutSeconds(for: event)- )- }-- static func groupRemovingCodexBarHandlers(- from group: Any,- executablePath: String- ) -> Any? {- guard var groupObject = group as? JSONObject,- let handlers = handlers(from: group) else {- return group- }-- let filteredHandlers = handlers.filter {- !isCurrentCodexBarHandler($0, executablePath: executablePath)- }- guard !filteredHandlers.isEmpty else {- return nil- }-- groupObject[hooksKey] = filteredHandlers- return groupObject- }-- static func handlers(from group: Any) -> JSONArray? {- guard let group = group as? JSONObject else {- return nil- }-- return group[hooksKey] as? JSONArray- }-- /// 管理项身份只由当前可执行路径和 --hook-event 确定- /// type 本身可能损坏, 不能用它决定是否允许自愈或清理- static func isCurrentCodexBarHandler(- _ handler: Any,- executablePath: String- ) -> Bool {- guard let handler = handler as? JSONObject,- let command = handler[hookCommandKey] as? String else {- return false- }-- return isCodexBarCommand(command, executablePath: executablePath)- }-- static func managedHookHandler(- for event: CodexHookEvent,- executablePath: String- ) -> JSONObject {- [- hookTypeKey: hookCommandType,- hookCommandKey: hookCommand(executablePath: executablePath),- hookTimeoutKey: WorkflowHookEventRecorder.hookTimeoutSeconds(for: event)- ]- }-- static func hookCommand(executablePath: String) -> String {- "\(shellQuoted(executablePath)) \(WorkflowHookEventRecorder.hookArgument)"- }-- static func isCodexBarCommand(_ command: String, executablePath: String) -> Bool {- // 使用 shell quoted 路径匹配当前 app, 再要求带有 Hook 子进程参数- command.contains(shellQuoted(executablePath))- && command.split(whereSeparator: \.isWhitespace)- .contains(Substring(WorkflowHookEventRecorder.hookArgument))- }-- static func shellQuoted(_ value: String) -> String {- "'\(value.replacingOccurrences(of: "'", with: "'\\''"))'"- }-- static func normalizedPath(_ path: String) -> String {- CodexCLIResolver.canonicalPath(path, expandingTilde: true)- }-}diff --git a/CodexBar/Services/Settings/CodexProxySettings.swift b/CodexBar/Services/Settings/CodexProxySettings.swiftdeleted file mode 100644index 8349f22..0000000--- a/CodexBar/Services/Settings/CodexProxySettings.swift+++ /dev/null@@ -1,223 +0,0 @@-import Combine-import Foundation--@MainActor-final class CodexProxySettings: ObservableObject {- enum TestResult: Equatable {- case success- case validation(CodexProxyConfiguration.ValidationIssue)- case authenticationRequired- case loginRequired- case timeout- case codexUnavailable- case failed- case loadFailed- case saveFailed- case clearFailed-- var title: String {- switch self {- case .success: String(localized: "proxy.test.connected")- case let .validation(issue): issue.title- case .authenticationRequired: String(localized: "proxy.test.proxy-authentication-failed")- case .loginRequired: String(localized: "proxy.test.codex-login-required")- case .timeout: String(localized: "proxy.test.timed-out")- case .codexUnavailable: String(localized: "proxy.test.codex-unavailable")- case .failed: String(localized: "proxy.test.connection-failed")- case .loadFailed: String(localized: "proxy.feedback.load-failed")- case .saveFailed: String(localized: "proxy.feedback.save-failed")- case .clearFailed: String(localized: "proxy.feedback.clear-failed")- }- }-- static func failure(for error: Error) -> Self {- guard let error = error as? CodexStatusError else { return .failed }- if error.isAuthenticationRequired {- return .loginRequired- }- switch error {- case .serverTimeout:- return .timeout- case .executableNotFound, .sourceUnavailable, .unsupportedVersion, .unsupportedMethod:- return .codexUnavailable- case let .serverError(message):- let message = message.lowercased()- if message.contains("proxy authentication required") {- return .authenticationRequired- }- if message.contains("401 unauthorized") {- return .loginRequired- }- if message.contains("timed out") || message.contains("timeout") {- return .timeout- }- return .failed- default:- return .failed- }- }- }-- @Published private(set) var configuration: CodexProxyConfiguration?- @Published private(set) var hasStoredConfiguration: Bool- @Published var draft = CodexProxyConfiguration()- @Published var password = ""- @Published private(set) var isSaving = false- @Published private(set) var testResult: TestResult?- @Published private(set) var showsValidationErrors = false-- private let service: CodexStatusService- private let defaults: UserDefaults- @Published private var testTask: Task<Void, Never>?-- var isTesting: Bool {- testTask != nil- }-- init(service: CodexStatusService, defaults: UserDefaults = .standard) {- self.service = service- self.defaults = defaults- hasStoredConfiguration = CodexProxyStore.containsConfiguration(in: defaults)- configuration = try? CodexProxyStore.load(from: defaults)?.configuration- }-- var invalidFields: Set<CodexProxyConfiguration.InputField> {- Set(validationIssues.map(\.field))- }-- var validationIssues: [CodexProxyConfiguration.ValidationIssue] {- showsValidationErrors ? draft.validationIssues : []- }-- var feedback: TestResult? {- if let issue = validationIssues.first {- return .validation(issue)- }- return testResult- }-- func loadDraft(showValidationErrors: Bool = false) {- showsValidationErrors = showValidationErrors- cancelTest()- password = ""- hasStoredConfiguration = CodexProxyStore.containsConfiguration(in: defaults)- do {- let stored = try CodexProxyStore.load(from: defaults)- configuration = stored?.configuration- draft = configuration ?? CodexProxyConfiguration()- password = stored?.password ?? ""- } catch {- configuration = nil- draft = CodexProxyConfiguration()- testResult = .loadFailed- }- }-- func draftChanged() {- cancelTest()- }-- func closeDraft() {- showsValidationErrors = false- cancelTest()- password = ""- }-- func cancelTest() {- testTask?.cancel()- testTask = nil- testResult = nil- }-- func testConnection(source: CodexCLISourceSelection) {- cancelTest()- showsValidationErrors = true- guard validationIssues.isEmpty else { return }- let configuration = draft- let password = password- testTask = Task { [weak self] in- guard !Task.isCancelled else { return }- let worker = Task.detached {- try CodexProxyConnectionTester.test(configuration: configuration, password: password, source: source)- }- do {- try await withTaskCancellationHandler {- try await worker.value- } onCancel: {- worker.cancel()- }- guard let self, !Task.isCancelled else { return }- testResult = .success- } catch {- guard let self, !Task.isCancelled else { return }- testResult = TestResult.failure(for: error)- }- guard let self, !Task.isCancelled else { return }- testTask = nil- }- }-- func setEnabled(_ enabled: Bool, onCompletion: @escaping (Bool) -> Void) {- guard !isSaving else { return }- showsValidationErrors = false- do {- guard let stored = try CodexProxyStore.load(from: defaults) else {- onCompletion(false)- return- }- var configuration = stored.configuration- if enabled, !configuration.validationIssues.isEmpty {- loadDraft(showValidationErrors: true)- onCompletion(false)- return- }- configuration.isEnabled = enabled- // 在创建异步任务前提交显示状态并锁定开关, 连续点击不会重复排队- isSaving = true- self.configuration = configuration- Task {- let succeeded: Bool- do {- try await service.applyProxy(configuration, password: stored.password)- hasStoredConfiguration = true- draft.isEnabled = enabled- succeeded = true- } catch {- self.configuration = stored.configuration- succeeded = false- }- isSaving = false- onCompletion(succeeded)- }- } catch {- onCompletion(false)- }- }-- func save(clear: Bool = false) async -> Bool {- guard !isSaving else { return false }- cancelTest()- if !clear {- showsValidationErrors = true- guard validationIssues.isEmpty else { return false }- } else {- showsValidationErrors = false- }- isSaving = true- defer { isSaving = false }- do {- let configuration = clear ? nil : try draft.validated()- try await service.applyProxy(configuration, password: password)- self.configuration = configuration- hasStoredConfiguration = configuration != nil- if clear {- draft = CodexProxyConfiguration()- password = ""- }- return true- } catch {- testResult = clear ? .clearFailed : .saveFailed- return false- }- }-}diff --git a/CodexBar/Services/Settings/CodexProxyStore.swift b/CodexBar/Services/Settings/CodexProxyStore.swiftdeleted file mode 100644index 0130d33..0000000--- a/CodexBar/Services/Settings/CodexProxyStore.swift+++ /dev/null@@ -1,41 +0,0 @@-import Foundation--/// 代理配置和密码作为一条本机偏好保存, 不参与云同步-nonisolated enum CodexProxyStore {- private static let configurationKey = "CodexProxy.configuration"-- struct StoredConfiguration: Codable {- let configuration: CodexProxyConfiguration- let password: String- }-- static func containsConfiguration(in defaults: UserDefaults) -> Bool {- defaults.object(forKey: configurationKey) != nil- }-- static func save(_ configuration: CodexProxyConfiguration?, password: String, to defaults: UserDefaults) throws {- guard let configuration else {- defaults.removeObject(forKey: configurationKey)- return- }- // 停用时保留原始字段, 无效配置也必须能够关闭- let stored = try StoredConfiguration(- configuration: configuration.isEnabled ? configuration.validated() : configuration,- password: configuration.usesAuthentication ? password : ""- )- try defaults.set(JSONEncoder().encode(stored), forKey: configurationKey)- }-- static func load(from defaults: UserDefaults) throws -> StoredConfiguration? {- guard containsConfiguration(in: defaults) else { return nil }- guard let data = defaults.data(forKey: configurationKey),- let stored = try? JSONDecoder().decode(StoredConfiguration.self, from: data) else {- throw CodexProxyError.invalidStoredConfiguration- }- // 读取时保留原始输入, 让设置窗口能够回填并修正无效配置- return StoredConfiguration(- configuration: stored.configuration,- password: stored.configuration.usesAuthentication ? stored.password : ""- )- }-}diff --git a/CodexBar/Services/Settings/MainPanelSettings.swift b/CodexBar/Services/Settings/MainPanelSettings.swiftindex 941dd11..e007490 100644--- a/CodexBar/Services/Settings/MainPanelSettings.swift+++ b/CodexBar/Services/Settings/MainPanelSettings.swift@@ -45,20 +45,6 @@ nonisolated struct MainPanelLayout: Equatable, Sendable {func isVisible(_ section: MainPanelSection) -> Bool {!hiddenSections.contains(section)}-- func disablingActivitySection() -> MainPanelLayout {- var hiddenSections = hiddenSections- hiddenSections.insert(.activity)-- if orderedSections.allSatisfy(hiddenSections.contains) {- hiddenSections.remove(.account)- }-- return MainPanelLayout(- orderedSections: orderedSections,- hiddenSections: hiddenSections- )- }}/// 主面板区域布局与动画效果偏好@@ -68,7 +54,6 @@ final class MainPanelSettings: ObservableObject {@Published private(set) var areAnimationsEnabled: Boolprivate let defaults: UserDefaults- private var isAdvancedModeEnabled: Bool?init(defaults: UserDefaults = .standard) {self.defaults = defaults@@ -82,40 +67,7 @@ final class MainPanelSettings: ObservableObject {areAnimationsEnabled = loadedAnimationsEnabled}- let loadedLayout = Self.loadLayout(from: defaults)- guard isAdvancedModeEnabled == false else {- publish(loadedLayout)- return- }-- let updatedLayout = loadedLayout.disablingActivitySection()- if updatedLayout == loadedLayout {- publish(updatedLayout)- } else {- saveAndPublish(updatedLayout)- }- }-- func updateAdvancedModeEnabled(_ isEnabled: Bool) {- let wasEnabled = isAdvancedModeEnabled- isAdvancedModeEnabled = isEnabled- let updatedLayout: MainPanelLayout- if isEnabled {- // 首次恢复进阶模式状态时保留布局, 只有关闭到开启的转换才自动显示任务- guard wasEnabled == false else { return }- updatedLayout = MainPanelLayout(- orderedSections: layout.orderedSections,- hiddenSections: layout.hiddenSections.subtracting([.activity])- )- } else {- updatedLayout = layout.disablingActivitySection()- }- guard updatedLayout != layout else {- return- }-- AppLog.settings.notice("进阶模式开关已同步主面板任务中心")- saveAndPublish(updatedLayout)+ publish(Self.loadLayout(from: defaults))}func setAnimationsEnabled(_ enabled: Bool) {@@ -133,9 +85,6 @@ final class MainPanelSettings: ObservableObject {isVisible: Bool,undoManager: UndoManager) {- guard section != .activity || !isVisible || isAdvancedModeEnabled == true else {- return- }guard layout.isVisible(section) != isVisible else {return}@@ -184,9 +133,7 @@ final class MainPanelSettings: ObservableObject {_ requestedLayout: MainPanelLayout,undoManager: UndoManager) {- let updatedLayout = isAdvancedModeEnabled == false- ? requestedLayout.disablingActivitySection()- : requestedLayout+ let updatedLayout = requestedLayoutguard updatedLayout != layout else {return}diff --git a/CodexBar/Services/Settings/NotificationSettings.swift b/CodexBar/Services/Settings/NotificationSettings.swiftindex 7ae7871..ddc692e 100644--- a/CodexBar/Services/Settings/NotificationSettings.swift+++ b/CodexBar/Services/Settings/NotificationSettings.swift@@ -5,7 +5,7 @@ import osimport UserNotifications/// 管理通知偏好和系统授权状态-/// 具体的通知发送与触觉反馈由 CodexNotificationService 处理+/// 具体的通知发送与触觉反馈由 NotificationService 处理@MainActorfinal class NotificationSettings: ObservableObject {@Published private(set) var isEnabled: Booldiff --git a/CodexBar/Services/Settings/ActivityProtectionSettings.swift b/CodexBar/Services/Settings/ProtectionSettings.swiftsimilarity index 79%rename from CodexBar/Services/Settings/ActivityProtectionSettings.swiftrename to CodexBar/Services/Settings/ProtectionSettings.swiftindex 75bb277..548114c 100644--- a/CodexBar/Services/Settings/ActivityProtectionSettings.swift+++ b/CodexBar/Services/Settings/ProtectionSettings.swift@@ -4,7 +4,7 @@ import os/// 异常任务保护跟随防睡眠开关, 此处只管理静默阈值@MainActor-final class ActivityProtectionSettings: ObservableObject {+final class ProtectionSettings: ObservableObject {@Published private(set) var inactivityDuration: InactivityDurationprivate let defaults: UserDefaults@@ -35,14 +35,16 @@ final class ActivityProtectionSettings: ObservableObject {}private static func storedDuration(in defaults: UserDefaults) -> InactivityDuration {- (defaults.object(forKey: inactivityDurationKey) as? Int)+ let value = defaults.object(forKey: inactivityDurationKey)+ ?? defaults.object(forKey: "KeepAlive.abnormalTaskInactivitySeconds")+ return (value as? Int).flatMap(InactivityDuration.init(rawValue:)) ?? .oneHour}- private static let inactivityDurationKey = "KeepAlive.abnormalTaskInactivitySeconds"+ private static let inactivityDurationKey = "Protection.inactivityDuration"}-extension ActivityProtectionSettings {+extension ProtectionSettings {enum InactivityDuration: Int, CaseIterable, Identifiable {case thirtyMinutes = 1800case oneHour = 3600@@ -63,12 +65,12 @@ extension ActivityProtectionSettings {var title: String {if self == .thirtyMinutes {- return String(localized: "activity-protection.duration.thirty-minutes")+ return String(localized: "protection.duration.thirty-minutes")}let hours = rawValue / 3600return String(- localized: "activity-protection.duration.hours",+ localized: "protection.duration.hours",defaultValue: "\(hours)")}diff --git a/CodexBar/Services/Settings/WorkflowSyncSettings.swift b/CodexBar/Services/Settings/SyncSettings.swiftsimilarity index 69%rename from CodexBar/Services/Settings/WorkflowSyncSettings.swiftrename to CodexBar/Services/Settings/SyncSettings.swiftindex 89be294..29b7dd2 100644--- a/CodexBar/Services/Settings/WorkflowSyncSettings.swift+++ b/CodexBar/Services/Settings/SyncSettings.swift@@ -3,14 +3,14 @@ import Combineimport Foundationimport os-/// 设置页的工作流同步状态+/// 设置页的跨设备同步状态@MainActor-final class WorkflowSyncSettings: ObservableObject {+final class SyncSettings: ObservableObject {@Published private(set) var isEnabled: Bool@Published private(set) var isSyncing = false@Published private(set) var syncFailureMessage: String?@Published private(set) var lastUploadAt: Date?- @Published private(set) var syncAvailability = WorkflowSyncAvailability.unknown+ @Published private(set) var syncAvailability = SyncAvailability.unknownprivate let defaults: UserDefaultsprivate var cancellables = Set<AnyCancellable>()@@ -60,32 +60,14 @@ final class WorkflowSyncSettings: ObservableObject {syncFailureMessage != nil}- /// "同步是否实际生效"的唯一判定: 进阶模式已启用且同步开关打开且 iCloud 可用- /// 按顺序返回第一个不满足的项, 日志的 reason= 直接取它的 rawValue- func activation(isAdvancedModeEnabled: Bool) -> WorkflowSyncActivation {- activation(isAdvancedModeEnabled: isAdvancedModeEnabled, isSyncAvailable: isSyncAvailable)- }-- /// 两项依赖都可以由调用方指定- /// @Published 的订阅回调跑在 willSet, 那时属性还是旧值, 只有回调参数是新值- func activation(- isAdvancedModeEnabled: Bool,- isSyncAvailable: Bool- ) -> WorkflowSyncActivation {- if !isAdvancedModeEnabled {- return .advancedModeOff- }- if !isEnabled {- return .syncOff- }- if !isSyncAvailable {- return .unavailable- }+ func activation(isSyncAvailable: Bool? = nil) -> SyncActivation {+ guard isEnabled else { return .syncOff }+ guard isSyncAvailable ?? self.isSyncAvailable else { return .unavailable }return .active}- func isEffectivelyActive(isAdvancedModeEnabled: Bool) -> Bool {- activation(isAdvancedModeEnabled: isAdvancedModeEnabled).isActive+ var isEffectivelyActive: Bool {+ activation().isActive}var unavailableMessage: String? {@@ -100,11 +82,15 @@ final class WorkflowSyncSettings: ObservableObject {}nonisolated static func isEnabled(defaults: UserDefaults = .standard) -> Bool {- defaults.bool(forKey: enabledKey)+ // 新键优先, 旧设置只作为首次改名后的读取来源+ if defaults.object(forKey: enabledKey) != nil {+ return defaults.bool(forKey: enabledKey)+ }+ return defaults.bool(forKey: "WorkflowSync.isEnabled")}private func observeSyncNotifications() {- NotificationCenter.default.publisher(for: .workflowSyncDidStart)+ NotificationCenter.default.publisher(for: .syncDidStart).sink { [weak self] _ inTask { @MainActor inself?.handleSyncDidStart()@@ -112,7 +98,7 @@ final class WorkflowSyncSettings: ObservableObject {}.store(in: &cancellables)- NotificationCenter.default.publisher(for: .workflowSyncDidFinish)+ NotificationCenter.default.publisher(for: .syncDidFinish).sink { [weak self] notification inTask { @MainActor inguard let self else {@@ -144,8 +130,8 @@ final class WorkflowSyncSettings: ObservableObject {}private func handleSyncDidFinish(_ notification: Notification) {- let didSucceed = notification.userInfo?[WorkflowSyncNotificationKey.didSucceed] as? Bool ?? true- let failureMessage = notification.userInfo?[WorkflowSyncNotificationKey.failureMessage] as? String+ let didSucceed = notification.userInfo?[SyncNotificationKey.didSucceed] as? Bool ?? true+ let failureMessage = notification.userInfo?[SyncNotificationKey.failureMessage] as? StringisSyncing = falseif didSucceed {@@ -156,7 +142,7 @@ final class WorkflowSyncSettings: ObservableObject {lastUploadAt = Self.loadLastUploadAt()}- private func applyAvailabilityResult(_ result: WorkflowSyncAvailabilityResult) {+ private func applyAvailabilityResult(_ result: SyncAvailabilityResult) {syncAvailability = result.availabilityguard result.availability.isUnavailable else {return@@ -177,15 +163,15 @@ final class WorkflowSyncSettings: ObservableObject {private func applySyncFailure(_ message: String?) {syncFailureMessage = isEnabled- ? message ?? WorkflowSyncFailureReason.retryLater.message+ ? message ?? SyncFailureReason.retryLater.message: nil}- private nonisolated static func querySyncAvailability() async -> WorkflowSyncAvailabilityResult {+ private nonisolated static func querySyncAvailability() async -> SyncAvailabilityResult {await withCheckedContinuation { continuation in- WorkflowSyncCloudKit.makeContainer().accountStatus { status, error in+ SyncCloudKit.makeContainer().accountStatus { status, error incontinuation.resume(- returning: WorkflowSyncFailureReason.availabilityResult(+ returning: SyncFailureReason.availabilityResult(status: status,error: error)@@ -195,16 +181,15 @@ final class WorkflowSyncSettings: ObservableObject {}private nonisolated static func loadLastUploadAt() -> Date? {- WorkflowSyncService.loadLastUploadAt()+ SyncService.loadLastUploadAt()}- private nonisolated static let enabledKey = "WorkflowSync.isEnabled"+ private nonisolated static let enabledKey = "Sync.isEnabled"}/// 同步没生效时缺的是哪一项, 同时充当日志里的 reason= 取值-nonisolated enum WorkflowSyncActivation: String {+nonisolated enum SyncActivation: String {case active- case advancedModeOffcase syncOffcase unavailable@@ -213,7 +198,7 @@ nonisolated enum WorkflowSyncActivation: String {}}-nonisolated enum WorkflowSyncAvailability: Equatable {+nonisolated enum SyncAvailability: Equatable {case unknowncase availablecase unavailable@@ -227,19 +212,19 @@ nonisolated enum WorkflowSyncAvailability: Equatable {}}-nonisolated struct WorkflowSyncAvailabilityResult {- let availability: WorkflowSyncAvailability- let failureReason: WorkflowSyncFailureReason?+nonisolated struct SyncAvailabilityResult {+ let availability: SyncAvailability+ let failureReason: SyncFailureReason?- static let available = WorkflowSyncAvailabilityResult(+ static let available = SyncAvailabilityResult(availability: .available,failureReason: nil)static func unavailable(- _ failureReason: WorkflowSyncFailureReason- ) -> WorkflowSyncAvailabilityResult {- WorkflowSyncAvailabilityResult(+ _ failureReason: SyncFailureReason+ ) -> SyncAvailabilityResult {+ SyncAvailabilityResult(availability: .unavailable,failureReason: failureReason)@@ -247,16 +232,16 @@ nonisolated struct WorkflowSyncAvailabilityResult {}extension Notification.Name {- nonisolated static let workflowSyncDidStart = Notification.Name("CodexBar.workflowSyncDidStart")- nonisolated static let workflowSyncDidFinish = Notification.Name("CodexBar.workflowSyncDidFinish")+ nonisolated static let syncDidStart = Notification.Name("CodexBar.syncDidStart")+ nonisolated static let syncDidFinish = Notification.Name("CodexBar.syncDidFinish")}-nonisolated enum WorkflowSyncNotificationKey {+nonisolated enum SyncNotificationKey {static let didSucceed = "didSucceed"static let failureMessage = "failureMessage"}-nonisolated enum WorkflowSyncFailureReason: String {+nonisolated enum SyncFailureReason: String {case networkUnavailablecase accountUnavailablecase serviceUnavailable@@ -276,8 +261,8 @@ nonisolated enum WorkflowSyncFailureReason: String {}}-nonisolated extension WorkflowSyncFailureReason {- static func classify(_ error: Error) -> WorkflowSyncFailureReason {+nonisolated extension SyncFailureReason {+ static func classify(_ error: Error) -> SyncFailureReason {guard let error = error as? CKError else {return .retryLater}@@ -297,7 +282,7 @@ nonisolated extension WorkflowSyncFailureReason {static func availabilityResult(status: CKAccountStatus,error: Error?- ) -> WorkflowSyncAvailabilityResult {+ ) -> SyncAvailabilityResult {if let error {return .unavailable(classify(error))}diff --git a/CodexBar/Services/Settings/CodexCLINotificationSettings.swift b/CodexBar/Services/Settings/TUINotificationSettings.swiftsimilarity index 96%rename from CodexBar/Services/Settings/CodexCLINotificationSettings.swiftrename to CodexBar/Services/Settings/TUINotificationSettings.swiftindex c0c6277..59dbc7c 100644--- a/CodexBar/Services/Settings/CodexCLINotificationSettings.swift+++ b/CodexBar/Services/Settings/TUINotificationSettings.swift@@ -4,7 +4,7 @@ import os/// Codex TUI 通知设置, 通过 app-server 读写用户级 config.toml@MainActor-final class CodexCLINotificationSettings: ObservableObject {+final class TUINotificationSettings: ObservableObject {@Published private(set) var isEnabled = true@Published private(set) var isUpdating = false@Published private(set) var errorMessage: String?@@ -78,7 +78,7 @@ final class CodexCLINotificationSettings: ObservableObject {private func runLatestUpdate(operation: ConfigOperation,- body: @escaping @MainActor @Sendable (CodexCLINotificationSettings, Int) async throws -> Bool+ body: @escaping @MainActor @Sendable (TUINotificationSettings, Int) async throws -> Bool) {isUpdating = trueerrorMessage = nildiff --git a/CodexBar/Services/Support/AppLog.swift b/CodexBar/Services/Support/AppLog.swiftindex ad84cc8..6c55d14 100644--- a/CodexBar/Services/Support/AppLog.swift+++ b/CodexBar/Services/Support/AppLog.swift@@ -8,18 +8,16 @@ nonisolated enum AppLog {/// App 生命周期, Sparkle 更新, 额度刷新结果与重置次数查询static let app = Logger(subsystem: subsystem, category: "app")static let keepAlive = Logger(subsystem: subsystem, category: "keepalive")- /// 本地 Hook 事件聚合与维护- static let workflow = Logger(subsystem: subsystem, category: "workflow")+ /// 本地 活动事件聚合与维护+ static let history = Logger(subsystem: subsystem, category: "history")/// CloudKit 同步static let sync = Logger(subsystem: subsystem, category: "sync")- /// 改写用户 ~/.codex 下的 Hook 配置与信任状态- static let hooks = Logger(subsystem: subsystem, category: "hooks")/// 实时任务监控, 只记低频的生命周期节点, 逐事件与逐快照的路径一律不记static let activity = Logger(subsystem: subsystem, category: "activity")/// 开机启动, 全局快捷键, Codex 自身通知配置这类用户设置static let settings = Logger(subsystem: subsystem, category: "settings")/// codex 可执行文件检测与版本读取- static let codexCLI = Logger(subsystem: subsystem, category: "codexcli")+ static let codex = Logger(subsystem: subsystem, category: "codex")/// 本地通知static let notification = Logger(subsystem: subsystem, category: "notification")@@ -46,9 +44,6 @@ nonisolated enum LogTrigger: String {case wakecase settingscase retry- /// 进阶模式开关转为开启后补跑同步- case advancedModeEnabled- case advancedModeChangedcase taskChangedcase helperRegisteredcase terminationdiff --git a/CodexBar/Services/Support/AppStorage.swift b/CodexBar/Services/Support/AppStorage.swiftnew file mode 100644index 0000000..f277f3d--- /dev/null+++ b/CodexBar/Services/Support/AppStorage.swift@@ -0,0 +1,17 @@+import Foundation++nonisolated enum AppStorage {+ #if DEBUG+ static let directoryName = "CodexBar Debug"+ #else+ static let directoryName = "CodexBar"+ #endif++ static func directoryURL(fileManager: FileManager = .default) -> URL {+ let applicationSupport = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+ ?? URL(fileURLWithPath: NSHomeDirectory())+ .appendingPathComponent("Library", isDirectory: true)+ .appendingPathComponent("Application Support", isDirectory: true)+ return applicationSupport.appendingPathComponent(directoryName, isDirectory: true)+ }+}diff --git a/CodexBar/Services/Support/CountResolution.swift b/CodexBar/Services/Support/CountResolution.swiftnew file mode 100644index 0000000..b357ba4--- /dev/null+++ b/CodexBar/Services/Support/CountResolution.swift@@ -0,0 +1,26 @@+import Foundation++nonisolated enum CountResolution {+ static func preferredCount(+ compactedCount: Int?,+ identifiers: [String]? = nil+ ) -> Int? {+ if let compactedCount, compactedCount > 0 {+ return compactedCount+ }++ if let identifiers {+ return Set(identifiers).count+ }++ return compactedCount == 0 ? 0 : nil+ }++ static func resolvedCount(+ compactedCount: Int?,+ identifiers: [String]? = nil,+ fallback: Int+ ) -> Int {+ preferredCount(compactedCount: compactedCount, identifiers: identifiers) ?? fallback+ }+}diff --git a/CodexBar/Services/Support/JSONFileStorage.swift b/CodexBar/Services/Support/JSONFileStorage.swiftnew file mode 100644index 0000000..ed27739--- /dev/null+++ b/CodexBar/Services/Support/JSONFileStorage.swift@@ -0,0 +1,44 @@+import Darwin+import Foundation++nonisolated enum JSONFileStorage {+ static func withLock<T>(in directory: URL, _ operation: () throws -> T) throws -> T {+ guard let descriptor = try acquireLock(in: directory) else { throw POSIXError(.EIO) }+ defer { releaseLock(descriptor) }+ return try operation()+ }++ static func acquireLock(in directory: URL, name: String = "store.lock", nonblocking: Bool = false) throws -> Int32? {+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ let descriptor = open(directory.appendingPathComponent(name).path, O_RDWR | O_CREAT, 0o600)+ guard descriptor >= 0 else { throw POSIXError(.EIO) }+ guard flock(descriptor, LOCK_EX | (nonblocking ? LOCK_NB : 0)) == 0 else {+ let code = errno+ close(descriptor)+ if nonblocking, code == EWOULDBLOCK {+ return nil+ }+ throw POSIXError(POSIXErrorCode(rawValue: code) ?? .EIO)+ }+ return descriptor+ }++ static func releaseLock(_ descriptor: Int32) {+ flock(descriptor, LOCK_UN)+ close(descriptor)+ }++ static func load<T: Decodable>(_: T.Type, from url: URL) throws -> T? {+ guard FileManager.default.fileExists(atPath: url.path) else { return nil }+ return try JSONLines.decoder.decode(T.self, from: Data(contentsOf: url))+ }++ static func save(_ value: some Encodable, to url: URL) throws {+ let data = try JSONLines.stableEncoder.encode(value)+ guard (try? Data(contentsOf: url)) != data else { return }+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try data.write(to: url, options: .atomic)+ }+}++// 调用方持有文件锁, 每次核对磁盘字节后复用解码结果, 不依赖 mtime 判断跨进程修改diff --git a/CodexBar/Services/Workflow/JSONLines.swift b/CodexBar/Services/Support/JSONLines.swiftsimilarity index 73%rename from CodexBar/Services/Workflow/JSONLines.swiftrename to CodexBar/Services/Support/JSONLines.swiftindex a34a04d..9b22c97 100644--- a/CodexBar/Services/Workflow/JSONLines.swift+++ b/CodexBar/Services/Support/JSONLines.swift@@ -16,9 +16,31 @@ nonisolated enum JSONLines {static let stableEncoder: JSONEncoder = {let encoder = JSONEncoder()encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]+ encoder.dateEncodingStrategy = .custom { date, encoder in+ let milliseconds = (date.timeIntervalSince1970 * 1000).rounded(.down)+ guard let timestamp = Int64(exactly: milliseconds) else {+ throw EncodingError.invalidValue(date, .init(codingPath: encoder.codingPath, debugDescription: "Invalid millisecond timestamp"))+ }+ var container = encoder.singleValueContainer()+ try container.encode(timestamp)+ }return encoder}()+ static let decoder: JSONDecoder = {+ let decoder = JSONDecoder()+ decoder.dateDecodingStrategy = .custom { decoder in+ let timestamp = try decoder.singleValueContainer().decode(Int64.self)+ return Date(timeIntervalSince1970: Double(timestamp) / 1000)+ }+ return decoder+ }()++ /// 内存快照与落盘精度一致, 避免重建标记在重新读取后被误判为更旧+ static func storageDate(_ date: Date) -> Date {+ Date(timeIntervalSince1970: (date.timeIntervalSince1970 * 1000).rounded(.down) / 1000)+ }+/// 从文件中部 seek 读取时首行必然残缺: 丢弃首个换行(含)之前的内容/// 找不到换行时原样返回, 交给按行解码当坏行跳过static func droppingLeadingPartialLine(_ data: Data) -> Data {@@ -39,7 +61,6 @@ nonisolated enum JSONLines {_: T.Type = T.self,from data: Data) -> JSONLinesDecodeResult<T> {- let decoder = JSONDecoder()var values = [T]()var failedLineCount = 0diff --git a/CodexBar/Services/Support/OrderedJSON.swift b/CodexBar/Services/Support/OrderedJSON.swiftnew file mode 100644index 0000000..51d2688--- /dev/null+++ b/CodexBar/Services/Support/OrderedJSON.swift@@ -0,0 +1,41 @@+import Foundation++/// 写入 JSONL 时固定字段顺序, 便于人工排查和 diff+nonisolated enum OrderedJSON {+ static func lineData(_ fields: [String]) -> Data {+ let json = "{\(fields.joined(separator: ","))}"+ return Data(json.utf8) + Data([0x0A])+ }++ static func field(_ name: String, _ value: (some Encodable)?) throws -> String {+ try "\"\(name)\":\(Self.value(value))"+ }++ static func value(_ value: (some Encodable)?) throws -> String {+ guard let value else {+ return "null"+ }++ return try Self.value(value)+ }++ static func value(_ value: some Encodable) throws -> String {+ let data = try JSONLines.stableEncoder.encode(value)+ guard let text = String(bytes: data, encoding: .utf8) else {+ throw EncodingError.invalidValue(+ value,+ .init(codingPath: [], debugDescription: "Encoded history JSON was not UTF-8")+ )+ }+ return text+ }++ static func presentCountFields(_ values: [(String, Int?)]) throws -> [String] {+ try values.compactMap { name, value in+ guard let value else {+ return nil+ }+ return try field(name, value)+ }+ }+}diff --git a/CodexBar/Services/Sync/ActivityRecordCodec.swift b/CodexBar/Services/Sync/ActivityRecordCodec.swiftnew file mode 100644index 0000000..585c495--- /dev/null+++ b/CodexBar/Services/Sync/ActivityRecordCodec.swift@@ -0,0 +1,128 @@+import CloudKit+import Foundation++// MARK: - CloudKit 记录编解码++nonisolated enum ActivityRecordCodec {+ static let version = 1++ enum RecordTypes {+ static let metadata = "Metadata"+ static let activity = "Activity"+ }++ enum FieldKeys {+ static let salt = "salt"+ static let version = "version"+ static let deviceID = "deviceID"+ static let date = "date"+ static let generationID = "generationID"+ static let eventCount = "eventCount"+ static let sessionStartedCount = "sessionStartedCount"+ static let sessionEndedCount = "sessionEndedCount"+ static let turnStartedCount = "turnStartedCount"+ static let turnCompletedCount = "turnCompletedCount"+ static let turnAbortedCount = "turnAbortedCount"+ static let toolStartedCount = "toolStartedCount"+ static let toolCompletedCount = "toolCompletedCount"+ static let approvalRequestedCount = "approvalRequestedCount"+ static let compactionStartedCount = "compactionStartedCount"+ static let compactionCompletedCount = "compactionCompletedCount"+ static let subagentStartedCount = "subagentStartedCount"+ static let subagentEndedCount = "subagentEndedCount"+ static let sessionCount = "sessionCount"+ static let turnCount = "turnCount"+ static let projectCounts = "projectCounts"+ static let modelCounts = "modelCounts"+ static let updatedAt = "updatedAt"+ }++ static func apply(+ _ aggregate: SyncedActivity,+ deviceID: String,+ to record: CKRecord+ ) {+ record[FieldKeys.version] = version as CKRecordValue+ record[FieldKeys.deviceID] = deviceID as CKRecordValue+ record[FieldKeys.date] = aggregate.date as CKRecordValue+ record[FieldKeys.generationID] = aggregate.generationID as CKRecordValue?+ record[FieldKeys.eventCount] = aggregate.eventCount as CKRecordValue?+ record[FieldKeys.sessionStartedCount] = aggregate.sessionStartedCount as CKRecordValue?+ record[FieldKeys.sessionEndedCount] = aggregate.sessionEndedCount as CKRecordValue?+ record[FieldKeys.turnStartedCount] = aggregate.turnStartedCount as CKRecordValue?+ record[FieldKeys.turnCompletedCount] = aggregate.turnCompletedCount as CKRecordValue?+ record[FieldKeys.turnAbortedCount] = aggregate.turnAbortedCount as CKRecordValue?+ record[FieldKeys.toolStartedCount] = aggregate.toolStartedCount as CKRecordValue?+ record[FieldKeys.toolCompletedCount] = aggregate.toolCompletedCount as CKRecordValue?+ record[FieldKeys.approvalRequestedCount] = aggregate.approvalRequestedCount as CKRecordValue?+ record[FieldKeys.compactionStartedCount] = aggregate.compactionStartedCount as CKRecordValue?+ record[FieldKeys.compactionCompletedCount] = aggregate.compactionCompletedCount as CKRecordValue?+ record[FieldKeys.subagentStartedCount] = aggregate.subagentStartedCount as CKRecordValue?+ record[FieldKeys.subagentEndedCount] = aggregate.subagentEndedCount as CKRecordValue?+ record[FieldKeys.sessionCount] = aggregate.sessionCount as CKRecordValue?+ record[FieldKeys.turnCount] = aggregate.turnCount as CKRecordValue?+ record[FieldKeys.projectCounts] = countsData(aggregate.projectCounts) as CKRecordValue+ record[FieldKeys.modelCounts] = countsData(aggregate.modelCounts) as CKRecordValue+ record[FieldKeys.updatedAt] = Date() as CKRecordValue+ }++ static func remoteDailyRecord(from record: CKRecord) throws -> ActivitySyncRecord? {+ guard record.recordType == RecordTypes.activity,+ let deviceID = record[FieldKeys.deviceID] as? String,+ let date = record[FieldKeys.date] as? String,+ HistoryStorage.isValidDateKey(date) else {+ return nil+ }++ let aggregate = SyncedActivity(+ date: date,+ generationID: record[FieldKeys.generationID] as? String,+ eventCount: optionalIntValue(record[FieldKeys.eventCount]),+ sessionStartedCount: optionalIntValue(record[FieldKeys.sessionStartedCount]),+ sessionEndedCount: optionalIntValue(record[FieldKeys.sessionEndedCount]),+ turnStartedCount: optionalIntValue(record[FieldKeys.turnStartedCount]),+ turnCompletedCount: optionalIntValue(record[FieldKeys.turnCompletedCount]),+ turnAbortedCount: optionalIntValue(record[FieldKeys.turnAbortedCount]),+ toolStartedCount: optionalIntValue(record[FieldKeys.toolStartedCount]),+ toolCompletedCount: optionalIntValue(record[FieldKeys.toolCompletedCount]),+ approvalRequestedCount: optionalIntValue(record[FieldKeys.approvalRequestedCount]),+ compactionStartedCount: optionalIntValue(record[FieldKeys.compactionStartedCount]),+ compactionCompletedCount: optionalIntValue(record[FieldKeys.compactionCompletedCount]),+ subagentStartedCount: optionalIntValue(record[FieldKeys.subagentStartedCount]),+ subagentEndedCount: optionalIntValue(record[FieldKeys.subagentEndedCount]),+ sessionCount: optionalIntValue(record[FieldKeys.sessionCount]),+ turnCount: optionalIntValue(record[FieldKeys.turnCount]),+ projectCounts: counts(from: record[FieldKeys.projectCounts]),+ modelCounts: counts(from: record[FieldKeys.modelCounts])+ )++ return try ActivitySyncRecord(+ deviceID: deviceID,+ daily: aggregate,+ updatedAt: record[FieldKeys.updatedAt] as? Date ?? record.modificationDate,+ recordName: record.recordID.recordName+ )+ }++ static func optionalIntValue(_ value: CKRecordValue?) -> Int? {+ if let number = value as? NSNumber {+ return number.intValue+ }+ if let value = value as? Int {+ return value+ }+ return nil+ }++ static func counts(from value: CKRecordValue?) -> [String: Int] {+ guard let data = value as? Data,+ let counts = try? JSONDecoder().decode([String: Int].self, from: data) else {+ return [:]+ }+ return counts+ }++ static func countsData(_ counts: [String: Int]) -> Data {+ (try? JSONLines.stableEncoder.encode(counts)) ?? Data("{}".utf8)+ }+}diff --git a/CodexBar/Services/Sync/ActivitySyncStore.swift b/CodexBar/Services/Sync/ActivitySyncStore.swiftnew file mode 100644index 0000000..0b28198--- /dev/null+++ b/CodexBar/Services/Sync/ActivitySyncStore.swift@@ -0,0 +1,151 @@+import CloudKit+import Foundation++nonisolated struct ActivitySyncStore {+ let directoryURL: URL++ private var cacheDirectoryURL: URL {+ directoryURL.appendingPathComponent("Activity", isDirectory: true)+ }++ private var cacheURL: URL {+ cacheDirectoryURL.appendingPathComponent("cache.json", isDirectory: false)+ }++ func load() throws -> ActivitySyncCache {+ try JSONFileStorage.withLock(in: cacheDirectoryURL) { try read() }+ }++ func loadState() -> SyncState {+ (try? load().state) ?? SyncState()+ }++ func saveState(_ state: SyncState) throws {+ try update { $0.state = state }+ }++ func loadCachedRecords() -> [ActivitySyncRecord] {+ (try? load().records) ?? []+ }++ func saveCachedRecords(_ records: [ActivitySyncRecord], state: SyncState) throws {+ try update {+ $0.records = Self.sorted(records)+ $0.state = state+ }+ }++ /// 数据和对应游标必须一起提交, 不能让新游标指向尚未保存的数据+ func saveFetchedRecords(_ records: [ActivitySyncRecord], cursor: CKServerChangeToken?) throws {+ let data = try cursor.map { try NSKeyedArchiver.archivedData(withRootObject: $0, requiringSecureCoding: true) }+ try update {+ $0.records = Self.sorted(records)+ $0.cursor = data+ }+ }++ func removeCursorIfPresent() throws {+ try update { $0.cursor = nil }+ }++ func reset(state: SyncState) throws {+ try update { $0 = ActivitySyncCache(state: state) }+ }++ private func read() throws -> ActivitySyncCache {+ let cache: ActivitySyncCache+ do {+ guard let data = try readData() else { return ActivitySyncCache() }+ let header = try JSONLines.decoder.decode(ActivitySyncCacheHeader.self, from: data)+ guard header.version == ActivitySyncCache.currentVersion else { throw SyncRecovery.Failure.unsupportedCacheVersion }+ cache = try JSONLines.decoder.decode(ActivitySyncCache.self, from: data)+ } catch is DecodingError {+ // 损坏时整体失效, 不保留脱离缓存数据的游标或上传摘要+ return ActivitySyncCache()+ }+ guard cache.state.containerIdentifier == SyncCloudKit.containerIdentifier else { return ActivitySyncCache() }+ return cache+ }++ private func readData() throws -> Data? {+ do {+ return try Data(contentsOf: cacheURL)+ } catch let error as CocoaError where error.code == .fileReadNoSuchFile {+ return nil+ }+ }++ private func update(_ body: (inout ActivitySyncCache) throws -> Void) throws {+ try JSONFileStorage.withLock(in: cacheDirectoryURL) {+ var cache = try read()+ try body(&cache)+ try JSONFileStorage.save(cache, to: cacheURL)+ }+ }++ private static func sorted(_ records: [ActivitySyncRecord]) -> [ActivitySyncRecord] {+ records.sorted { ($0.deviceID, $0.date, $0.id) < ($1.deviceID, $1.date, $1.id) }+ }+}++private nonisolated struct ActivitySyncCacheHeader: Decodable { let version: Int }++nonisolated struct ActivitySyncCache: Codable, Equatable {+ static let currentVersion = 1+ var version = currentVersion+ var state = SyncState()+ var records: [ActivitySyncRecord] = []+ var cursor: Data?+}++nonisolated struct SyncState: Codable, Equatable {+ var containerIdentifier: String?+ var deviceID: String?+ var hashByDate: [String: String]+ var replacementDates: [String]+ var lastUploadAt: Date?+ var lastPrunedDate: String?++ init(+ containerIdentifier: String? = SyncCloudKit.containerIdentifier,+ deviceID: String? = nil,+ hashByDate: [String: String] = [:],+ replacementDates: [String] = [],+ lastUploadAt: Date? = nil,+ lastPrunedDate: String? = nil+ ) {+ self.containerIdentifier = containerIdentifier+ self.deviceID = deviceID+ self.hashByDate = hashByDate+ self.replacementDates = replacementDates+ self.lastUploadAt = lastUploadAt+ self.lastPrunedDate = lastPrunedDate+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)++ containerIdentifier = try container.decodeIfPresent(String.self, forKey: .containerIdentifier)+ deviceID = try container.decodeIfPresent(String.self, forKey: .deviceID)+ hashByDate = try container.decodeIfPresent([String: String].self, forKey: .hashByDate)+ ?? [:]+ let decodedReplacementDates = try container.decodeIfPresent(+ [String].self,+ forKey: .replacementDates+ ) ?? []+ replacementDates = Set(+ decodedReplacementDates.filter(HistoryStorage.isValidDateKey)+ ).sorted()+ lastUploadAt = try container.decodeIfPresent(Date.self, forKey: .lastUploadAt)+ lastPrunedDate = try container.decodeIfPresent(String.self, forKey: .lastPrunedDate)+ }++ private enum CodingKeys: String, CodingKey {+ case containerIdentifier+ case deviceID+ case hashByDate+ case replacementDates+ case lastUploadAt+ case lastPrunedDate+ }+}diff --git a/CodexBar/Services/Sync/SyncCancellation.swift b/CodexBar/Services/Sync/SyncCancellation.swiftnew file mode 100644index 0000000..ba63e35--- /dev/null+++ b/CodexBar/Services/Sync/SyncCancellation.swift@@ -0,0 +1,9 @@+import Foundation++nonisolated enum SyncCancellation {+ /// Task 的取消标记不会随开关重新启用而复活+ static func check(isEnabled: () -> Bool) throws {+ try Task.checkCancellation()+ guard isEnabled() else { throw CancellationError() }+ }+}diff --git a/CodexBar/Services/Sync/SyncDatabase.swift b/CodexBar/Services/Sync/SyncDatabase.swiftnew file mode 100644index 0000000..5a89814--- /dev/null+++ b/CodexBar/Services/Sync/SyncDatabase.swift@@ -0,0 +1,35 @@+import CloudKit++/// 仅封装同步实际使用的操作, 测试可以注入局部失败而不连接 iCloud+nonisolated protocol SyncDatabase: Sendable {+ typealias Records = [CKRecord.ID: Result<CKRecord, Error>]+ typealias Modification = (saveResults: Records, deleteResults: [CKRecord.ID: Result<Void, Error>])+ typealias QueryPage = (matchResults: [(CKRecord.ID, Result<CKRecord, Error>)], queryCursor: CKQueryOperation.Cursor?)+ typealias ZoneModification = (saveResults: [CKRecordZone.ID: Result<CKRecordZone, Error>], deleteResults: [CKRecordZone.ID: Result<Void, Error>])++ func records(for ids: [CKRecord.ID], desiredKeys: [CKRecord.FieldKey]?) async throws -> Records+ func modifyRecords(saving records: [CKRecord], deleting ids: [CKRecord.ID], savePolicy: CKModifyRecordsOperation.RecordSavePolicy, atomically: Bool) async throws -> Modification+ func records(matching query: CKQuery, inZoneWith zone: CKRecordZone.ID?, desiredKeys: [CKRecord.FieldKey]?, resultsLimit: Int) async throws -> QueryPage+ func records(continuingMatchFrom cursor: CKQueryOperation.Cursor, desiredKeys: [CKRecord.FieldKey]?, resultsLimit: Int) async throws -> QueryPage+ func recordZone(for id: CKRecordZone.ID) async throws -> CKRecordZone+ func modifyRecordZones(saving zones: [CKRecordZone], deleting ids: [CKRecordZone.ID]) async throws -> ZoneModification+ func fetchChanges(inZoneWith zone: CKRecordZone.ID, since token: CKServerChangeToken?, resultsLimit: Int) async throws -> SyncChanges+}++nonisolated struct SyncChanges: Sendable {+ let records: SyncDatabase.Records+ let deletions: [(id: CKRecord.ID, type: String)]+ let token: CKServerChangeToken?+ let moreComing: Bool+}++extension CKDatabase: SyncDatabase {+ nonisolated func fetchChanges(inZoneWith zone: CKRecordZone.ID, since token: CKServerChangeToken?, resultsLimit: Int) async throws -> SyncChanges {+ let changes = try await recordZoneChanges(inZoneWith: zone, since: token, desiredKeys: nil, resultsLimit: resultsLimit)+ return SyncChanges(+ records: changes.modificationResultsByID.mapValues { $0.map(\.record) },+ deletions: changes.deletions.map { ($0.recordID, $0.recordType) },+ token: changes.changeToken, moreComing: changes.moreComing+ )+ }+}diff --git a/CodexBar/Services/Sync/SyncRecovery.swift b/CodexBar/Services/Sync/SyncRecovery.swiftnew file mode 100644index 0000000..305c951--- /dev/null+++ b/CodexBar/Services/Sync/SyncRecovery.swift@@ -0,0 +1,94 @@+import CloudKit+import Foundation++/// 只有已确认的局部错误允许继续, 未识别的云端错误保持停止当前轮次+nonisolated enum SyncRecovery {+ enum Failure: Error {+ case invalidCursor+ case unsupportedCacheVersion+ case missingRecordResult+ }++ static func decodeCursor(_ data: Data) throws -> CKServerChangeToken {+ do {+ guard let token = try NSKeyedUnarchiver.unarchivedObject(ofClass: CKServerChangeToken.self, from: data) else {+ throw Failure.invalidCursor+ }+ return token+ } catch {+ throw Failure.invalidCursor+ }+ }++ static func isInvalidCursor(_ error: Error) -> Bool {+ if case Failure.invalidCursor = error {+ return true+ }+ return (error as? CKError)?.code == .changeTokenExpired+ }++ static func isMissingZone(_ error: Error, zoneID: CKRecordZone.ID, queryingZone: Bool = false) -> Bool {+ isMissingZone(error, zoneID: zoneID, queryingZone: queryingZone, depth: 0)+ }++ private static func isMissingZone(_ error: Error, zoneID: CKRecordZone.ID, queryingZone: Bool, depth: Int) -> Bool {+ guard depth < 8, let error = error as? CKError else { return false }+ switch error.code {+ case .zoneNotFound, .userDeletedZone:+ return true+ case .unknownItem:+ // 查询单条记录时的 unknownItem 不能说明整个 zone 已不存在+ return queryingZone+ case .partialFailure:+ return (error.partialErrorsByItemID ?? [:]).contains { key, failure in+ if let id = key as? CKRecordZone.ID, id == zoneID {+ return isMissingZone(failure, zoneID: zoneID, queryingZone: queryingZone, depth: depth + 1)+ }+ if let id = key as? CKRecord.ID, id.zoneID == zoneID {+ return isMissingZone(failure, zoneID: zoneID, queryingZone: false, depth: depth + 1)+ }+ return false+ }+ default:+ return false+ }+ }++ static func isRecordFailure(_ error: Error) -> Bool {+ guard let error = error as? CKError else { return false }+ return [.serverRecordChanged, .constraintViolation, .unknownItem, .assetFileNotFound, .assetFileModified, .invalidArguments].contains(error.code)+ }++ static func stopsOtherSync(_ error: Error) -> Bool {+ if error is CancellationError {+ return true+ }+ guard let error = error as? CKError else { return false }+ return !isRecordFailure(error) && error.code != .changeTokenExpired+ }+}++nonisolated struct SyncFailures {+ private(set) var first: Error?+ private(set) var stopping: Error?++ mutating func record(_ error: Error) {+ first = first ?? error+ if !SyncRecovery.isRecordFailure(error) {+ stopping = stopping ?? error+ }+ }++ func checkStopping() throws {+ if let stopping {+ throw stopping+ }+ }++ func check() throws {+ try checkStopping()+ if let first {+ throw first+ }+ }+}diff --git a/CodexBar/Services/Workflow/WorkflowSyncScheduler.swift b/CodexBar/Services/Sync/SyncScheduler.swiftsimilarity index 77%rename from CodexBar/Services/Workflow/WorkflowSyncScheduler.swiftrename to CodexBar/Services/Sync/SyncScheduler.swiftindex 94bd066..a060c9f 100644--- a/CodexBar/Services/Workflow/WorkflowSyncScheduler.swift+++ b/CodexBar/Services/Sync/SyncScheduler.swift@@ -3,15 +3,18 @@ import os/// 合并工作流维护刷新中的同步请求, 避免频繁开关产生重复同步@MainActor-final class WorkflowSyncScheduler {- typealias RebuildCompletion = (Result<WorkflowDataRebuildSummary, Error>) -> Void+final class SyncScheduler {+ typealias RebuildCompletion = (Result<HistoryDataRebuildSummary, Error>) -> Voidtypealias RebuildHandler = ([String], @escaping RebuildCompletion) -> Voidprivate static let syncCooldown: TimeInterval = 8- private let viewModel: WorkflowViewModel- private let syncActivation: () -> WorkflowSyncActivation+ private let maintenance: (Bool, LogTrigger) async -> HistoryMaintenanceCounts?+ private let rebuild: ([String], Bool) async throws -> HistoryDataRebuildSummary+ private let syncActivation: () -> SyncActivationprivate var isRunning = false+ private var runningTask: Task<Void, Never>?+ private var runningSynchronizes = falseprivate var pendingRebuild: RebuildRequest?private var cooldownTask: Task<Void, Never>?private var lastSyncFinishedAt: Date?@@ -20,15 +23,26 @@ final class WorkflowSyncScheduler {private var pendingSyncTrigger: LogTrigger?private var pendingMaintenanceTrigger: LogTrigger?+ convenience init(viewModel: HistoryViewModel, syncActivation: @escaping () -> SyncActivation) {+ self.init(+ syncActivation: syncActivation,+ maintenance: { await viewModel.refreshMaintenance(synchronize: $0, trigger: $1) },+ rebuild: { try await viewModel.rebuildData(for: $0, synchronize: $1) }+ )+ }+init(- viewModel: WorkflowViewModel,- syncActivation: @escaping () -> WorkflowSyncActivation+ syncActivation: @escaping () -> SyncActivation,+ maintenance: @escaping (Bool, LogTrigger) async -> HistoryMaintenanceCounts?,+ rebuild: @escaping ([String], Bool) async throws -> HistoryDataRebuildSummary) {- self.viewModel = viewModelself.syncActivation = syncActivation+ self.maintenance = maintenance+ self.rebuild = rebuild}deinit {+ runningTask?.cancel()cooldownTask?.cancel()}@@ -44,7 +58,7 @@ final class WorkflowSyncScheduler {/// activation 传 nil 时现场求值/// 从 @Published 的订阅里调用必须显式传入: 那时属性还是旧值, 现场求值会得到刚被改掉的那个结论- func requestSync(trigger: LogTrigger, activation overrideActivation: WorkflowSyncActivation? = nil) {+ func requestSync(trigger: LogTrigger, activation overrideActivation: SyncActivation? = nil) {let activation = overrideActivation ?? syncActivation()guard activation.isActive else {let details = LogFields.joined(@@ -71,6 +85,9 @@ final class WorkflowSyncScheduler {}func clearPendingSync() {+ if runningSynchronizes {+ runningTask?.cancel()+ }pendingSyncTrigger = nilcancelCooldownTask()drain()@@ -83,6 +100,7 @@ final class WorkflowSyncScheduler {}func cancel() {+ runningTask?.cancel()clearPendingMaintenance()pendingRebuild?.completion(.failure(CancellationError()))pendingRebuild = nil@@ -133,15 +151,13 @@ final class WorkflowSyncScheduler {cancelCooldownTask()}- Task { @MainActor [weak self] in+ runningSynchronizes = synchronize+ runningTask = Task { @MainActor [weak self] inguard let self else {return}- let counts = await viewModel.refreshMaintenance(- synchronize: synchronize,- trigger: trigger- )+ let counts = await maintenance(synchronize, trigger)finishMaintenance(synchronize: synchronize,trigger: trigger,@@ -155,7 +171,7 @@ final class WorkflowSyncScheduler {synchronize: Bool,trigger: LogTrigger,duration: LogDuration,- counts: WorkflowMaintenanceCounts?+ counts: HistoryMaintenanceCounts?) {logMaintenanceOutcome(synchronize: synchronize,@@ -164,8 +180,10 @@ final class WorkflowSyncScheduler {counts: counts)isRunning = false+ runningTask = nil+ runningSynchronizes = false- if synchronize {+ if synchronize, !Task.isCancelled {lastSyncFinishedAt = Date()}@@ -182,18 +200,16 @@ final class WorkflowSyncScheduler {pendingRebuild = nillet synchronize = syncActivation().isActive- Task(priority: .utility) { @MainActor [weak self] in+ runningSynchronizes = synchronize+ runningTask = Task(priority: .utility) { @MainActor [weak self] inguard let self else {return}- let result: Result<WorkflowDataRebuildSummary, Error>+ let result: Result<HistoryDataRebuildSummary, Error>do {result = try await .success(- viewModel.rebuildData(- for: request.dateKeys,- synchronize: synchronize- )+ rebuild(request.dateKeys, synchronize))} catch {let details = LogFields.joined(@@ -201,12 +217,14 @@ final class WorkflowSyncScheduler {"dates=\(request.dateKeys.count)","detail=\(error.localizedDescription)")- AppLog.workflow.error("数据重建失败: \(details, privacy: .public)")+ AppLog.history.error("数据重建失败: \(details, privacy: .public)")result = .failure(error)}isRunning = false- if synchronize {+ runningTask = nil+ runningSynchronizes = false+ if synchronize, !Task.isCancelled {lastSyncFinishedAt = Date()}request.completion(result)@@ -215,12 +233,12 @@ final class WorkflowSyncScheduler {}/// 空转轮次不记录日志, 避免周期刷新产生重复信息- /// 同步自身的起止由 WorkflowSyncService 记, 这里只承载维护结果, 不给 sync 开后门+ /// 同步自身的起止由 SyncService 记, 这里只承载维护结果, 不给 sync 开后门private func logMaintenanceOutcome(synchronize: Bool,trigger: LogTrigger,duration: LogDuration,- counts: WorkflowMaintenanceCounts?+ counts: HistoryMaintenanceCounts?) {guard let counts else {return@@ -243,7 +261,7 @@ final class WorkflowSyncScheduler {"pruned=\(counts.pruned)","elapsed=\(elapsed)")- AppLog.workflow.notice("统计刷新完成: \(details, privacy: .public)")+ AppLog.history.notice("统计刷新完成: \(details, privacy: .public)")}private func remainingSyncCooldown() -> TimeInterval {diff --git a/CodexBar/Services/Sync/SyncService.swift b/CodexBar/Services/Sync/SyncService.swiftnew file mode 100644index 0000000..fb365ce--- /dev/null+++ b/CodexBar/Services/Sync/SyncService.swift@@ -0,0 +1,1160 @@+import CloudKit+import CryptoKit+import Foundation+import IOKit+import os+import Security++nonisolated enum SyncCloudKit {+ static let containerIdentifier = "iCloud.app.zabrian.codexbar.data"++ static let zoneName = "CodexBarAppZone"++ static func makeContainer() -> CKContainer {+ CKContainer(identifier: containerIdentifier)+ }+}++/// 同步失败时定位到哪一步, 只用于日志+private nonisolated enum SyncStage: String {+ case zone+ case device+ case fetch+ case upload+ case tokens+ case prune+}++/// 将本机 daily.jsonl 中不含 sessionIds 和 turnIds 的聚合行同步到 CloudKit private database+actor SyncService {+ private let container: CKContainer?+ private let suppliedDatabase: (any SyncDatabase)?+ private lazy var database: any SyncDatabase = suppliedDatabase ?? (container ?? SyncCloudKit.makeContainer()).privateCloudDatabase+ private let fileManager: FileManager+ private let directoryURL: URL+ private let isEnabled: @Sendable () -> Bool+ private lazy var tokenSync = TokenSync(+ database: database, directoryURL: directoryURL.appendingPathComponent("Tokens"), isEnabled: isEnabled+ )++ // zone 存在性跨轮缓存, 共享故障后重新确认+ // salt 只在单轮内复用, 每轮确认同名 zone 是否已经被其他设备重建+ private var isSyncZoneConfirmed = false+ private var cachedAccountSalt: Data?++ init(+ container: CKContainer? = nil,+ database: (any SyncDatabase)? = nil,+ fileManager: FileManager = .default,+ directoryURL: URL = HistoryStorage.syncDirectoryURL(),+ isEnabled: @escaping @Sendable () -> Bool = { SyncSettings.isEnabled() }+ ) {+ self.container = container+ suppliedDatabase = database+ self.fileManager = fileManager+ self.directoryURL = directoryURL+ self.isEnabled = isEnabled+ }++ // MARK: - 同步入口++ func snapshotFromCacheIfEnabled(localTokenTurns: [TokenTurn] = []) async -> SyncSnapshot {+ guard isEnabled() else {+ return .disabled+ }++ let state = activityStore.loadState()+ return await snapshot(from: state, localTokenTurns: localTokenTurns)+ }++ /// 显式重建后, 将所选日期标记为当前设备云端贡献的权威替换来源+ func markReplacementNeeded(for dates: [String]) throws {+ let validDates = Set(dates.filter(HistoryStorage.isValidDateKey))+ guard !validDates.isEmpty else {+ return+ }++ var state = activityStore.loadState()+ state.replacementDates = Set(state.replacementDates)+ .union(validDates)+ .sorted()+ for date in validDates {+ state.hashByDate.removeValue(forKey: date)+ }+ try activityStore.saveState(state)+ }++ func hasPendingReplacement(for dates: [String]) -> Bool {+ !Set(activityStore.loadState().replacementDates).isDisjoint(with: dates)+ }++ func tokenRecoveryBaselineIfEnabled() async -> TokenHistoryBaseline? {+ guard isEnabled() else { return nil }+ return await tokenSync.recoveryBaseline(accountScopedDeviceID: activityStore.loadState().deviceID)+ }++ func hasPendingTokenUpdates(local: [TokenTurn]) async -> Bool {+ await tokenSync.hasPendingUpdates(local: local, accountScopedDeviceID: activityStore.loadState().deviceID)+ }++ func synchronizeIfEnabled(+ localAggregates: [ActivityAggregate],+ localTokenTurns: [TokenTurn] = [],+ trigger: LogTrigger+ ) async -> SyncSnapshot {+ guard isEnabled(), !Task.isCancelled else {+ logSyncSkipped(trigger: trigger)+ return .disabled+ }++ AppLog.sync.notice("同步开始: trigger=\(trigger.rawValue, privacy: .public)")+ let duration = LogDuration()+ var stage = SyncStage.zone+ var didSucceed = false+ var failureMessage: String?+ Self.postSyncNotification(.syncDidStart)+ defer {+ Self.postSyncNotification(+ .syncDidFinish,+ didSucceed: didSucceed,+ failureMessage: failureMessage+ )+ }++ var state = activityStore.loadState()++ // 显式开启同步允许恢复缺失的 zone, 同一轮最多重新执行一次+ cachedAccountSalt = nil+ for attempt in 0 ..< 2 {+ do {+ try SyncCancellation.check(isEnabled: isEnabled)+ failureMessage = try await synchronizeOnce(+ localAggregates: localAggregates, localTokenTurns: localTokenTurns,+ state: &state, stage: &stage, trigger: trigger, duration: duration+ )+ didSucceed = failureMessage == nil+ break+ } catch {+ var failure = error+ if SyncRecovery.stopsOtherSync(error) {+ invalidateAccountScopedCaches()+ }+ if SyncRecovery.isMissingZone(error, zoneID: syncZoneID), !Task.isCancelled, isEnabled() {+ do {+ try await resetSyncState(state: &state)+ if attempt == 0 {+ AppLog.sync.notice("云端 zone 已失效, 重置同步状态后重试")+ stage = .zone+ continue+ }+ } catch {+ failure = error+ }+ }+ if !(failure is CancellationError), !Task.isCancelled, isEnabled() {+ let reason = SyncFailureReason.classify(failure)+ logSyncFailed(trigger: trigger, stage: stage, elapsed: duration.elapsed, reason: reason, detail: failure.localizedDescription)+ failureMessage = reason.message+ }+ try? activityStore.saveState(state)+ break+ }+ }++ guard !Task.isCancelled, isEnabled() else { return .disabled }+ let latestState = activityStore.loadState()+ return await snapshot(from: latestState, localTokenTurns: localTokenTurns)+ }++ private func synchronizeOnce(+ localAggregates: [ActivityAggregate], localTokenTurns: [TokenTurn],+ state: inout SyncState, stage: inout SyncStage, trigger: LogTrigger, duration: LogDuration+ ) async throws -> String? {+ try await ensureSyncZoneExists(state: &state)+ stage = .device+ let deviceID = try await resolveCurrentDeviceID()+ try await resetStateIfDeviceChanged(deviceID, state: &state)++ var localByDate: [String: LocalSyncAggregate] = [:]+ var confirmedDates = Set<String>()+ var activityFailure: Error?+ do {+ stage = .upload+ localByDate = try Self.syncedAggregatesByDate(localAggregates)+ confirmedDates = try await synchronizeActivity(localByDate: localByDate, deviceID: deviceID, state: &state, stage: &stage)+ } catch {+ if SyncRecovery.stopsOtherSync(error) {+ throw error+ }+ activityFailure = error+ logSyncFailed(+ trigger: trigger,+ stage: stage,+ elapsed: duration.elapsed,+ reason: SyncFailureReason.classify(error),+ detail: error.localizedDescription+ )+ }+ stage = .tokens+ try await tokenSync.synchronize(+ local: localTokenTurns, accountScopedDeviceID: deviceID, salt: accountSalt(), zoneID: syncZoneID+ )+ if let activityFailure {+ try SyncCancellation.check(isEnabled: isEnabled)+ try activityStore.saveState(state)+ return (activityFailure as? ActivitySyncError)?.errorDescription ?? SyncFailureReason.classify(activityFailure).message+ }+ stage = .prune+ let deletedCount = try await pruneCurrentDeviceRecordsIfNeeded(deviceID: deviceID, state: &state)+ try activityStore.saveState(state)+ // confirmed 是本地与远端已对齐的日期数, 含哈希未变而无需上传的那些+ // 它小于 local 就说明这一轮还有日期没落到云上+ let elapsed = duration.elapsed+ logSyncCompleted(+ trigger: trigger,+ localCount: localByDate.count,+ confirmedCount: confirmedDates.count,+ deletedCount: deletedCount,+ elapsed: elapsed+ )+ return nil+ }++ private func synchronizeActivity(+ localByDate: [String: LocalSyncAggregate], deviceID: String,+ state: inout SyncState, stage: inout SyncStage+ ) async throws -> Set<String> {+ stage = .fetch+ try await refreshCacheBeforeUpload(localByDate: localByDate, deviceID: deviceID, state: &state)+ stage = .upload+ let dates = try await uploadChangedAggregates(localByDate: localByDate, remoteRecords: activityStore.loadCachedRecords(), state: &state)+ try finalizeUpload(confirmedDates: dates, state: &state)+ stage = .fetch+ try await refreshCacheFromRemote()+ return dates+ }++ private func logSyncSkipped(trigger: LogTrigger) {+ let details = LogFields.joined(+ "trigger=\(trigger.rawValue)",+ "reason=syncOff"+ )+ AppLog.sync.notice("同步已跳过: \(details, privacy: .public)")+ }++ private func logSyncCompleted(+ trigger: LogTrigger,+ localCount: Int,+ confirmedCount: Int,+ deletedCount: Int,+ elapsed: String+ ) {+ let details = LogFields.joined(+ "trigger=\(trigger.rawValue)",+ "local=\(localCount)",+ "confirmed=\(confirmedCount)",+ "deleted=\(deletedCount)",+ "elapsed=\(elapsed)"+ )+ AppLog.sync.notice("同步完成: \(details, privacy: .public)")+ }++ private func logSyncFailed(+ trigger: LogTrigger,+ stage: SyncStage,+ elapsed: String,+ reason: SyncFailureReason,+ detail: String+ ) {+ let details = LogFields.joined(+ "trigger=\(trigger.rawValue)",+ "stage=\(stage.rawValue)",+ "elapsed=\(elapsed)",+ "reason=\(reason.rawValue)",+ "detail=\(detail)"+ )+ AppLog.sync.error("同步失败: \(details, privacy: .public)")+ }++ private func refreshCacheBeforeUpload(+ localByDate: [String: LocalSyncAggregate],+ deviceID: String,+ state: inout SyncState+ ) async throws {+ guard !state.replacementDates.isEmpty else {+ try await refreshCacheFromRemote()+ return+ }++ // 替换前全量拉取, 避免增量缓存遗漏同设备同日期的旧 generation+ try await rebuildCacheFromRemote()+ try await preparePendingReplacements(+ localByDate: localByDate,+ deviceID: deviceID,+ state: &state+ )+ }++ private func finalizeUpload(+ confirmedDates: Set<String>,+ state: inout SyncState+ ) throws {+ let completedReplacementDates = Set(state.replacementDates).intersection(confirmedDates)+ if !completedReplacementDates.isEmpty {+ state.replacementDates.removeAll { completedReplacementDates.contains($0) }+ try activityStore.saveState(state)+ }+ }++ private func resetStateIfDeviceChanged(+ _ deviceID: String,+ state: inout SyncState+ ) async throws {+ guard state.deviceID != deviceID else {+ return+ }++ try await resetSyncState(state: &state)+ state.deviceID = deviceID+ try activityStore.saveState(state)+ }++ private func resetSyncState(state: inout SyncState) async throws {+ try SyncCancellation.check(isEnabled: isEnabled)+ // 先持久化未绑定状态, 中途失败或退出后仍会重新清理, 不把旧缓存当作已恢复+ state = SyncState(replacementDates: state.replacementDates)+ try activityStore.reset(state: state)+ try await tokenSync.resetCache()+ try SyncCancellation.check(isEnabled: isEnabled)+ }++ private static func syncedAggregatesByDate(+ _ aggregates: [ActivityAggregate]+ ) throws -> [String: LocalSyncAggregate] {+ try aggregates.reduce(into: [String: LocalSyncAggregate]()) { result, aggregate in+ _ = try aggregate.syncedAggregate.requiredGenerationID()+ result[aggregate.date] = LocalSyncAggregate(+ aggregate: aggregate.syncedAggregate,+ generationStartedEmpty: aggregate.generationStartedEmpty+ )+ }+ }++ private func snapshot(from state: SyncState, localTokenTurns: [TokenTurn]) async -> SyncSnapshot {+ guard let deviceID = state.deviceID else {+ return .disabled+ }++ let replacementDates = Set(state.replacementDates)+ let records = Self.filteredRetained(records: activityStore.loadCachedRecords()).filter { record in+ record.deviceID != deviceID || !replacementDates.contains(record.date)+ }++ return await SyncSnapshot(+ records: records,+ currentDeviceID: deviceID,+ tokenUsageByDate: tokenSync.snapshot(local: localTokenTurns, accountScopedDeviceID: deviceID)+ )+ }+}++private extension SyncService {+ struct LocalSyncAggregate {+ let aggregate: SyncedActivity+ let generationStartedEmpty: Bool+ }++ struct PendingUpload {+ let date: String+ let aggregate: SyncedActivity+ let generationStartedEmpty: Bool+ let hash: String+ }++ struct PendingRecord {+ let upload: PendingUpload+ let recordID: CKRecord.ID+ }++ struct RecordToSave {+ let upload: PendingUpload+ let record: CKRecord+ }++ struct UploadBatchResult {+ var confirmed: [ConfirmedHash] = []+ var failures = SyncFailures()+ }++ struct ConfirmedHash {+ let date: String+ let hash: String+ let didUpload: Bool+ }++ enum Metrics {+ static let syncVersion = ActivityRecordCodec.version+ static let saltByteCount = 32+ static let recordFetchLimit = 200+ static let queryFetchLimit = 200+ static let uploadBatchSize = 25+ static let uploadTimeBudget: TimeInterval = 20+ }++ typealias RecordTypes = ActivityRecordCodec.RecordTypes+ typealias FieldKeys = ActivityRecordCodec.FieldKeys++ static let accountSaltRecordName = "accountSalt"++ var syncZoneID: CKRecordZone.ID {+ CKRecordZone.ID(zoneName: SyncCloudKit.zoneName, ownerName: CKCurrentUserDefaultName)+ }++ var accountSaltRecordID: CKRecord.ID {+ CKRecord.ID(recordName: Self.accountSaltRecordName, zoneID: syncZoneID)+ }++ private var activityStore: ActivitySyncStore {+ ActivitySyncStore(directoryURL: directoryURL)+ }++ // MARK: - 上传++ func uploadChangedAggregates(+ localByDate: [String: LocalSyncAggregate],+ remoteRecords: [ActivitySyncRecord],+ state: inout SyncState+ ) async throws -> Set<String> {+ guard let deviceID = state.deviceID else {+ return []+ }++ // 每个日期的 hash 是一次 JSON 编码加 SHA256, 本轮只算一次+ // 既用来判定"和上次一样不必上传", 也直接填进待上传项+ let localHashByDate = try localByDate.mapValues { try hash(for: $0.aggregate) }++ var confirmedDates = Set<String>()+ for (date, hash) in localHashByDate where state.hashByDate[date] == hash {+ confirmedDates.insert(date)+ }++ let pendingUploads = makePendingUploads(+ localByDate: localByDate,+ localHashByDate: localHashByDate,+ state: state+ )+ guard !pendingUploads.isEmpty else {+ return confirmedDates+ }++ let deadline = Date().addingTimeInterval(Metrics.uploadTimeBudget)+ var failures = SyncFailures()++ for batchStart in stride(from: 0, to: pendingUploads.count, by: Metrics.uploadBatchSize) {+ try SyncCancellation.check(isEnabled: isEnabled)+ guard Date() < deadline else {+ break+ }++ let batchEnd = min(batchStart + Metrics.uploadBatchSize, pendingUploads.count)+ let batch = Array(pendingUploads[batchStart ..< batchEnd])+ let result = try await processUploadBatch(batch, deviceID: deviceID, remoteRecords: remoteRecords)+ try applyConfirmedHashes(result.confirmed, to: &state)+ confirmedDates.formUnion(result.confirmed.map(\.date))+ try result.failures.checkStopping()+ if let error = result.failures.first {+ failures.record(error)+ }+ }+ try failures.check()++ return confirmedDates+ }++ func preparePendingReplacements(+ localByDate: [String: LocalSyncAggregate],+ deviceID: String,+ state: inout SyncState+ ) async throws {+ let replacementDates = Set(state.replacementDates).intersection(localByDate.keys)+ guard !replacementDates.isEmpty else {+ return+ }++ let cachedRecords = activityStore.loadCachedRecords()+ let recordsToReplace = cachedRecords.filter {+ $0.deviceID == deviceID && replacementDates.contains($0.date)+ }+ var recordIDs = Set(recordsToReplace.map {+ CKRecord.ID(recordName: $0.id, zoneID: syncZoneID)+ })++ for date in replacementDates {+ guard let local = localByDate[date] else { continue }+ try recordIDs.insert(recordID(deviceID: deviceID, date: date, generation: local.aggregate.requiredGenerationID()))+ }++ try await deleteRecords(Array(recordIDs))++ for date in replacementDates {+ state.hashByDate.removeValue(forKey: date)+ }+ try activityStore.saveCachedRecords(cachedRecords.filter {+ $0.deviceID != deviceID || !replacementDates.contains($0.date)+ }, state: state)+ }++ func deleteRecords(_ recordIDs: [CKRecord.ID]) async throws {+ for batchStart in stride(from: 0, to: recordIDs.count, by: Metrics.uploadBatchSize) {+ let batchEnd = min(batchStart + Metrics.uploadBatchSize, recordIDs.count)+ let batch = Array(recordIDs[batchStart ..< batchEnd])+ try SyncCancellation.check(isEnabled: isEnabled)+ let result = try await database.modifyRecords(+ saving: [],+ deleting: batch,+ savePolicy: .changedKeys,+ atomically: false+ )++ for recordID in batch {+ switch result.deleteResults[recordID] {+ case .success:+ continue+ case let .failure(error as CKError) where error.code == .unknownItem:+ continue+ case let .failure(error):+ throw error+ case nil:+ throw SyncError.missingRecordResult+ }+ }+ }+ }++ func applyConfirmedHashes(+ _ confirmedBatch: [ConfirmedHash],+ to state: inout SyncState+ ) throws {+ guard !confirmedBatch.isEmpty else {+ return+ }++ for confirmation in confirmedBatch {+ state.hashByDate[confirmation.date] = confirmation.hash+ }++ if confirmedBatch.contains(where: \.didUpload) {+ state.lastUploadAt = Date()+ }+ try activityStore.saveState(state)+ }++ /// hash 由调用方一次算好传进来, 这里只做筛选+ func makePendingUploads(+ localByDate: [String: LocalSyncAggregate],+ localHashByDate: [String: String],+ state: SyncState+ ) -> [PendingUpload] {+ localByDate.compactMap { date, local in+ guard let hash = localHashByDate[date],+ state.hashByDate[date] != hash else {+ return nil+ }++ return PendingUpload(+ date: date,+ aggregate: local.aggregate,+ generationStartedEmpty: local.generationStartedEmpty,+ hash: hash+ )+ }+ .sorted { $0.date < $1.date }+ }++ /// 单条待上传记录落到哪个 CKRecord 上, 或者本轮不需要上传+ private enum UploadTarget {+ case skip+ case save(CKRecord)+ }++ /// 远端已有更完整的同源聚合, 或者同日已有记录且本地不是新鲜来源时都不覆盖+ private func resolveUploadTarget(+ _ pendingRecord: PendingRecord,+ deviceID: String,+ remoteRecords: [ActivitySyncRecord],+ existingRecords: [CKRecord.ID: Result<CKRecord, any Error>]+ ) throws -> UploadTarget {+ let existing = try Self.fetchedRecord(from: existingRecords[pendingRecord.recordID])+ if let existing {+ guard let remote = try ActivityRecordCodec.remoteDailyRecord(from: existing) else {+ throw ActivitySyncError.invalidRecordIdentity+ }+ if (remote.daily.eventCount ?? 0) > (pendingRecord.upload.aggregate.eventCount ?? 0) {+ return .skip+ }+ return .save(existing)+ }++ let hasRemoteHistory = remoteRecords.contains {+ $0.deviceID == deviceID && $0.date == pendingRecord.upload.date+ }+ if !hasRemoteHistory || pendingRecord.upload.generationStartedEmpty {+ return .save(CKRecord(recordType: RecordTypes.activity, recordID: pendingRecord.recordID))+ }++ return .skip+ }++ func processUploadBatch(+ _ pendingUploads: [PendingUpload],+ deviceID: String,+ remoteRecords: [ActivitySyncRecord]+ ) async throws -> UploadBatchResult {+ let pendingRecords = try pendingUploads.map { upload in+ try PendingRecord(+ upload: upload,+ recordID: recordID(deviceID: deviceID, date: upload.date, generation: upload.aggregate.requiredGenerationID())+ )+ }+ let recordIDs = pendingRecords.map(\.recordID)+ try SyncCancellation.check(isEnabled: isEnabled)+ let existingRecords = try await database.records(for: recordIDs, desiredKeys: nil)+ var outcome = UploadBatchResult()+ var recordsToSave = [RecordToSave]()++ for pendingRecord in pendingRecords {+ do {+ switch try resolveUploadTarget(+ pendingRecord,+ deviceID: deviceID,+ remoteRecords: remoteRecords,+ existingRecords: existingRecords+ ) {+ case .skip:+ outcome.confirmed.append(+ ConfirmedHash(+ date: pendingRecord.upload.date,+ hash: pendingRecord.upload.hash,+ didUpload: false+ )+ )+ case let .save(record):+ ActivityRecordCodec.apply(pendingRecord.upload.aggregate, deviceID: deviceID, to: record)+ recordsToSave.append(+ RecordToSave(upload: pendingRecord.upload, record: record)+ )+ }+ } catch {+ outcome.failures.record(error)+ if outcome.failures.stopping != nil {+ return outcome+ }+ }+ }++ guard !recordsToSave.isEmpty else {+ return outcome+ }++ let records = recordsToSave.map(\.record)++ try SyncCancellation.check(isEnabled: isEnabled)+ let result = try await database.modifyRecords(+ saving: records,+ deleting: [],+ savePolicy: .changedKeys,+ atomically: false+ )++ for pendingRecord in recordsToSave {+ switch result.saveResults[pendingRecord.record.recordID] {+ case .success:+ outcome.confirmed.append(+ ConfirmedHash(+ date: pendingRecord.upload.date,+ hash: pendingRecord.upload.hash,+ didUpload: true+ )+ )+ case let .failure(error):+ outcome.failures.record(error)+ case nil:+ outcome.failures.record(SyncRecovery.Failure.missingRecordResult)+ }+ }++ return outcome+ }++ // MARK: - 拉取与缓存++ func refreshCacheFromRemote() async throws {+ do {+ let cache = try activityStore.load()+ guard let token = try cache.cursor.map(SyncRecovery.decodeCursor) else {+ try await rebuildCacheFromRemote()+ return+ }+ try await applyZoneChangesToCache(+ since: token,+ cachedRecords: cache.records+ )+ } catch where SyncRecovery.isInvalidCursor(error) {+ try SyncCancellation.check(isEnabled: isEnabled)+ // 增量拉取退化成全量重建, 代价高得多, 反复出现说明游标或缓存有问题+ let details = LogFields.joined(+ "detail=\(error.localizedDescription)",+ "action=fullRebuild"+ )+ AppLog.sync.notice("增量拉取已降级: \(details, privacy: .public)")+ try await rebuildCacheFromRemote()+ }+ }++ func applyZoneChangesToCache(+ since initialToken: CKServerChangeToken?,+ cachedRecords: [ActivitySyncRecord]+ ) async throws {+ var cacheByID = Self.recordsByID(records: cachedRecords)+ var token: CKServerChangeToken? = initialToken+ var moreComing = true++ while moreComing {+ try SyncCancellation.check(isEnabled: isEnabled)+ let result = try await database.fetchChanges(+ inZoneWith: syncZoneID,+ since: token,+ resultsLimit: Metrics.recordFetchLimit+ )++ try mergeChangedRecords(+ result.records.values,+ into: &cacheByID+ )+ removeDeletedRecords(result.deletions, from: &cacheByID)++ token = result.token+ moreComing = result.moreComing+ }++ try activityStore.saveFetchedRecords(+ Self.filteredRetained(records: Array(cacheByID.values)), cursor: token+ )+ }++ func rebuildCacheFromRemote() async throws {+ try activityStore.removeCursorIfPresent()+ let syncedRecords = try await fetchAllRemoteDailyRecords()+ let retainedRecords = Self.filteredRetained(records: syncedRecords)+ try activityStore.saveFetchedRecords(retainedRecords, cursor: nil)+ try await establishCursorBaseline(cachedRecords: retainedRecords)+ }++ func fetchAllRemoteDailyRecords() async throws -> [ActivitySyncRecord] {+ let query = CKQuery(+ recordType: RecordTypes.activity,+ predicate: NSPredicate(format: "TRUEPREDICATE")+ )+ query.sortDescriptors = [+ NSSortDescriptor(key: FieldKeys.deviceID, ascending: true),+ NSSortDescriptor(key: FieldKeys.date, ascending: true)+ ]++ let matches = try await fetchAllRecordMatches(matching: query)+ return try Self.remoteDailyRecords(from: matches)+ }++ func fetchCurrentDeviceRecordIDsToPrune(+ deviceID: String,+ cutoffKey: String+ ) async throws -> [CKRecord.ID] {+ let query = CKQuery(+ recordType: RecordTypes.activity,+ predicate: NSPredicate(+ format: "%K == %@",+ FieldKeys.deviceID,+ deviceID+ )+ )++ let currentDeviceMatches = try await fetchAllRecordMatches(+ matching: query,+ desiredKeys: [FieldKeys.date]+ )+ return try currentDeviceMatches.compactMap { recordID, result in+ let record = try result.get()+ guard let date = record[FieldKeys.date] as? String,+ HistoryStorage.isValidDateKey(date) else {+ // 无法进入保留窗口比较的当前设备记录是异常数据, 一并清理+ return recordID+ }++ return date < cutoffKey ? recordID : nil+ }+ }++ func fetchAllRecordMatches(+ matching query: CKQuery,+ desiredKeys: [String]? = nil+ ) async throws -> [(CKRecord.ID, Result<CKRecord, Error>)] {+ try SyncCancellation.check(isEnabled: isEnabled)+ let firstPage = try await database.records(+ matching: query,+ inZoneWith: syncZoneID,+ desiredKeys: desiredKeys,+ resultsLimit: Metrics.queryFetchLimit+ )+ var matches = firstPage.matchResults+ var cursor = firstPage.queryCursor++ while let currentCursor = cursor {+ try SyncCancellation.check(isEnabled: isEnabled)+ let page = try await database.records(+ continuingMatchFrom: currentCursor,+ desiredKeys: desiredKeys,+ resultsLimit: Metrics.queryFetchLimit+ )+ matches.append(contentsOf: page.matchResults)+ cursor = page.queryCursor+ }++ return matches+ }++ func establishCursorBaseline(cachedRecords: [ActivitySyncRecord]) async throws {+ do {+ try await applyZoneChangesToCache(+ since: nil,+ cachedRecords: cachedRecords+ )+ } catch {+ // zone 已被删除时必须恢复整条同步链路, 不能仅丢弃游标后继续上传+ if error is ActivitySyncError || SyncRecovery.isMissingZone(error, zoneID: syncZoneID) {+ throw error+ }+ guard !Task.isCancelled else { return }+ // 丢掉游标, 下次同步会从头拉一遍+ let details = LogFields.joined(+ "detail=\(error.localizedDescription)",+ "action=dropCursor"+ )+ AppLog.sync.notice("游标基线已降级: \(details, privacy: .public)")+ try? activityStore.removeCursorIfPresent()+ }+ }++ func mergeChangedRecords(+ _ modificationResults: Dictionary<CKRecord.ID, Result<CKRecord, Error>>.Values,+ into cacheByID: inout [String: ActivitySyncRecord]+ ) throws {+ for modificationResult in modificationResults {+ let modification = try modificationResult.get()+ guard let record = try ActivityRecordCodec.remoteDailyRecord(from: modification) else {+ continue+ }++ cacheByID[record.id] = record+ }+ }++ func removeDeletedRecords(+ _ deletions: [(id: CKRecord.ID, type: String)],+ from cacheByID: inout [String: ActivitySyncRecord]+ ) {+ for deletion in deletions where deletion.type == RecordTypes.activity {+ guard let cacheID = cacheID(fromRecordName: deletion.id.recordName) else {+ continue+ }+ cacheByID.removeValue(forKey: cacheID)+ }+ }++ @discardableResult+ func pruneCurrentDeviceRecordsIfNeeded(+ deviceID: String,+ state: inout SyncState+ ) async throws -> Int {+ let today = HistoryStorage.dateKey(for: Date())+ guard state.lastPrunedDate != today else {+ return 0+ }++ let cutoffKey = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate())+ let expiredDates = Set(state.hashByDate.keys.filter { $0 < cutoffKey })+ state.replacementDates.removeAll { $0 < cutoffKey }+ let recordIDs = try await Set(+ fetchCurrentDeviceRecordIDsToPrune(+ deviceID: deviceID,+ cutoffKey: cutoffKey+ )+ )++ if !recordIDs.isEmpty {+ try await deleteRecords(+ recordIDs.sorted { $0.recordName < $1.recordName }+ )+ }++ for date in expiredDates {+ state.hashByDate.removeValue(forKey: date)+ }+ state.lastPrunedDate = today+ return recordIDs.count+ }++ // MARK: - 账号与设备标识++ func resolveCurrentDeviceID() async throws -> String {+ let salt = try await accountSalt()+ let uuid = try Self.ioPlatformUUID()+ let mac = HMAC<SHA256>.authenticationCode(+ for: Data(uuid.utf8),+ using: SymmetricKey(data: salt)+ )+ return Self.hexString(Data(mac))+ }++ func accountSalt() async throws -> Data {+ if let cachedAccountSalt {+ return cachedAccountSalt+ }++ let recordID = accountSaltRecordID+ let salt: Data = if let fetched = try await fetchAccountSalt(recordID) {+ fetched+ } else {+ try await createAccountSalt(recordID)+ }++ cachedAccountSalt = salt+ return salt+ }++ func fetchAccountSalt(_ recordID: CKRecord.ID) async throws -> Data? {+ try SyncCancellation.check(isEnabled: isEnabled)+ let result = try await database.records(for: [recordID], desiredKeys: nil)+ guard let record = try Self.fetchedRecord(from: result[recordID]) else {+ return nil+ }+ guard let salt = record[FieldKeys.salt] as? Data,+ salt.count == Metrics.saltByteCount else {+ throw SyncError.missingAccountSalt+ }+ return salt+ }++ func createAccountSalt(_ recordID: CKRecord.ID) async throws -> Data {+ let salt = try Self.randomSalt()+ let record = CKRecord(recordType: RecordTypes.metadata, recordID: recordID)+ record[FieldKeys.salt] = salt as CKRecordValue+ record[FieldKeys.version] = Metrics.syncVersion as CKRecordValue++ do {+ try SyncCancellation.check(isEnabled: isEnabled)+ let saveResult = try await database.modifyRecords(+ saving: [record],+ deleting: [],+ savePolicy: .ifServerRecordUnchanged,+ atomically: true+ )+ switch saveResult.saveResults[recordID] {+ case .success:+ return salt+ case let .failure(error):+ throw error+ case nil:+ throw SyncError.missingRecordResult+ }+ } catch let error as CKError where error.code == .serverRecordChanged || error.code == .constraintViolation {+ if let salt = try await fetchAccountSalt(recordID) {+ return salt+ }+ }++ throw SyncError.missingAccountSalt+ }++ // MARK: - 记录与 zone 维护++ func ensureSyncZoneExists(state: inout SyncState) async throws {+ guard !isSyncZoneConfirmed else {+ return+ }++ if try await syncZoneExists() == false {+ invalidateAccountScopedCaches()+ try await resetSyncState(state: &state)+ let zone = CKRecordZone(zoneID: syncZoneID)+ try SyncCancellation.check(isEnabled: isEnabled)+ let result = try await database.modifyRecordZones(saving: [zone], deleting: [])++ switch result.saveResults[syncZoneID] {+ case .success:+ break+ case let .failure(error):+ throw error+ case nil:+ throw SyncError.missingRecordResult+ }+ }++ try SyncCancellation.check(isEnabled: isEnabled)+ isSyncZoneConfirmed = true+ }++ func invalidateAccountScopedCaches() {+ isSyncZoneConfirmed = false+ cachedAccountSalt = nil+ }++ func syncZoneExists() async throws -> Bool {+ do {+ try SyncCancellation.check(isEnabled: isEnabled)+ _ = try await database.recordZone(for: syncZoneID)+ return true+ } catch where SyncRecovery.isMissingZone(error, zoneID: syncZoneID, queryingZone: true) {+ return false+ }+ }++ func recordID(deviceID: String, date: String, generation: String) -> CKRecord.ID {+ CKRecord.ID(+ recordName: ActivitySyncRecord.recordName(deviceID: deviceID, date: date, generation: generation),+ zoneID: syncZoneID+ )+ }++ func cacheID(fromRecordName recordName: String) -> String? {+ recordName.isEmpty ? nil : recordName+ }++ func hash(for aggregate: SyncedActivity) throws -> String {+ let digest = try SHA256.hash(data: aggregate.jsonLineData())+ return Self.hexString(Data(digest))+ }++ nonisolated static func postSyncNotification(+ _ name: Notification.Name,+ didSucceed: Bool? = nil,+ failureMessage: String? = nil+ ) {+ Task { @MainActor in+ var userInfo = [String: Any]()+ if let didSucceed {+ userInfo[SyncNotificationKey.didSucceed] = didSucceed+ }+ if let failureMessage {+ userInfo[SyncNotificationKey.failureMessage] = failureMessage+ }++ NotificationCenter.default.post(+ name: name,+ object: nil,+ userInfo: userInfo.isEmpty ? nil : userInfo+ )+ }+ }+}++extension SyncService {+ /// 设置页读取最近上传时间, 与内部 loadState 使用同一 version 校验口径+ nonisolated static func loadLastUploadAt() -> Date? {+ ActivitySyncStore(directoryURL: HistoryStorage.syncDirectoryURL()).loadState().lastUploadAt+ }+}++private extension SyncService {+ static func remoteDailyRecords(+ from matchResults: [(CKRecord.ID, Result<CKRecord, Error>)]+ ) throws -> [ActivitySyncRecord] {+ try matchResults.compactMap { _, result in+ try ActivityRecordCodec.remoteDailyRecord(from: result.get())+ }+ }++ static func fetchedRecord(+ from result: Result<CKRecord, Error>?+ ) throws -> CKRecord? {+ switch result {+ case let .success(record):+ return record+ case let .failure(error as CKError) where error.code == .unknownItem:+ return nil+ case let .failure(error):+ throw error+ case nil:+ throw SyncError.missingRecordResult+ }+ }++ static func filteredRetained(+ records: [ActivitySyncRecord]+ ) -> [ActivitySyncRecord] {+ let cutoffKey = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate())+ return records.filter { $0.date >= cutoffKey }+ }++ static func recordsByID(+ records: [ActivitySyncRecord]+ ) -> [String: ActivitySyncRecord] {+ filteredRetained(records: records)+ .reduce(into: [String: ActivitySyncRecord]()) { result, record in+ result[record.id] = record+ }+ }++ static func randomSalt() throws -> Data {+ var bytes = [UInt8](repeating: 0, count: Metrics.saltByteCount)+ let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)+ guard status == errSecSuccess else {+ throw SyncError.randomSaltFailed+ }+ return Data(bytes)+ }++ static func ioPlatformUUID() throws -> String {+ let service = IOServiceGetMatchingService(+ kIOMainPortDefault,+ IOServiceMatching("IOPlatformExpertDevice")+ )+ guard service != 0 else {+ throw SyncError.missingIOPlatformUUID+ }+ defer {+ IOObjectRelease(service)+ }++ guard let value = IORegistryEntryCreateCFProperty(+ service,+ "IOPlatformUUID" as CFString,+ kCFAllocatorDefault,+ 0+ )?.takeRetainedValue() as? String,+ !value.isEmpty else {+ throw SyncError.missingIOPlatformUUID+ }++ return value+ }++ static func hexString(_ data: Data) -> String {+ data.map { String(format: "%02x", $0) }.joined()+ }+}++/// records 包含所有设备的日聚合, 不含 sessionIds 和 turnIds+/// currentDeviceId 用于展示时替换本机云端副本, 避免重复计数+nonisolated struct SyncSnapshot: Equatable {+ let records: [ActivitySyncRecord]+ let currentDeviceID: String?+ var tokenUsageByDate: [String: TokenUsage]?++ static let disabled = SyncSnapshot(records: [], currentDeviceID: nil)+}++private nonisolated enum SyncError: Error {+ case missingAccountSalt+ case missingIOPlatformUUID+ case missingRecordResult+ case randomSaltFailed+}diff --git a/CodexBar/Services/Sync/TokenSync.swift b/CodexBar/Services/Sync/TokenSync.swiftnew file mode 100644index 0000000..89c4e3b--- /dev/null+++ b/CodexBar/Services/Sync/TokenSync.swift@@ -0,0 +1,273 @@+import CloudKit+import Foundation++/// 每个线程轮次一个云端累计记录, 多设备通过条件写入收敛到同一份用量+actor TokenSync {+ private let database: any SyncDatabase+ private let directoryURL: URL+ private let isEnabled: @Sendable () -> Bool+ private var fileCache: TokenFileCache<TokenSyncCache>+ static let recordType = "Tokens"+ private static let currentVersion = 2++ init(database: any SyncDatabase, directoryURL: URL, isEnabled: @escaping @Sendable () -> Bool = { SyncSettings.isEnabled() }) {+ self.database = database+ self.directoryURL = directoryURL+ self.isEnabled = isEnabled+ fileCache = TokenFileCache(url: directoryURL.appendingPathComponent("cache.json"))+ }++ func recoveryBaseline(accountScopedDeviceID: String?) -> TokenHistoryBaseline? {+ guard let accountScopedDeviceID, let cache = try? load(), cache.accountScopedDeviceID == accountScopedDeviceID else { return nil }+ return TokenHistoryBaseline(salt: cache.salt, turns: cache.turns)+ }++ func snapshot(local: [TokenTurn], accountScopedDeviceID: String?) -> [String: TokenUsage] {+ guard let cache = try? load(), cache.accountScopedDeviceID == accountScopedDeviceID else {+ return TokenTurn.dailyUsage(local)+ }+ return TokenTurn.dailyUsage(TokenTurn.pseudonymized(local, salt: cache.salt) + Array(cache.turns.values))+ }++ func hasPendingUpdates(local: [TokenTurn], accountScopedDeviceID: String?) -> Bool {+ let records = TokenTurn.syncable(local)+ guard let cache = try? load(), cache.accountScopedDeviceID == accountScopedDeviceID else { return !records.isEmpty }+ return records.contains { turn in+ let candidate = turn.pseudonymized(salt: cache.salt)+ guard let remote = cache.turns[candidate.id] else { return true }+ return remote.merging(candidate) != remote+ }+ }++ func resetCache() throws {+ try SyncCancellation.check(isEnabled: isEnabled)+ guard let lock = try JSONFileStorage.acquireLock(in: directoryURL, name: "sync.lock", nonblocking: true) else {+ throw POSIXError(.EWOULDBLOCK)+ }+ defer { JSONFileStorage.releaseLock(lock) }+ try JSONFileStorage.withLock(in: directoryURL) {+ if FileManager.default.fileExists(atPath: fileCache.url.path) {+ try FileManager.default.removeItem(at: fileCache.url)+ }+ fileCache = TokenFileCache(url: fileCache.url)+ }+ }++ func synchronize(local: [TokenTurn], accountScopedDeviceID: String, salt: Data, zoneID: CKRecordZone.ID) async throws {+ try SyncCancellation.check(isEnabled: isEnabled)+ // 整轮同步共用非阻塞锁, 防止另一个进程用较早的快照覆盖游标, 界面读取不等待网络+ guard let lock = try JSONFileStorage.acquireLock(in: directoryURL, name: "sync.lock", nonblocking: true) else { return }+ defer { JSONFileStorage.releaseLock(lock) }+ var cache: TokenSyncCache+ do {+ cache = try load() ?? TokenSyncCache(accountScopedDeviceID: accountScopedDeviceID, salt: salt)+ } catch is DecodingError {+ cache = TokenSyncCache(accountScopedDeviceID: accountScopedDeviceID, salt: salt)+ }+ if cache.accountScopedDeviceID != accountScopedDeviceID || cache.salt != salt {+ cache = TokenSyncCache(accountScopedDeviceID: accountScopedDeviceID, salt: salt)+ }+ do {+ try await fetch(into: &cache, zoneID: zoneID)+ } catch where SyncRecovery.isInvalidCursor(error) {+ var rebuilt = TokenSyncCache(accountScopedDeviceID: accountScopedDeviceID, salt: salt)+ try await fetch(into: &rebuilt, zoneID: zoneID)+ cache = rebuilt+ }+ // 先落盘拉取结果, 上传失败时也能展示已经读取的其他设备贡献+ try save(cache)+ try await upload(local: local, cache: &cache, zoneID: zoneID)+ try await prune(cache: &cache, zoneID: zoneID)+ try save(cache)+ }++ private func fetch(into cache: inout TokenSyncCache, zoneID: CKRecordZone.ID) async throws {+ var token = try cache.cursor.map(SyncRecovery.decodeCursor)+ var turns = token == nil ? [:] : cache.turns+ var more = true+ while more {+ try Task.checkCancellation()+ try SyncCancellation.check(isEnabled: isEnabled)+ let result = try await database.fetchChanges(inZoneWith: zoneID, since: token, resultsLimit: 200)+ for modification in result.records.values {+ if let turn = try Self.turn(from: modification.get()) {+ turns[turn.id] = turn+ }+ }+ for deletion in result.deletions where deletion.type == Self.recordType {+ turns.removeValue(forKey: deletion.id.recordName)+ }+ token = result.token+ more = result.moreComing+ }+ cache.turns = turns+ cache.cursor = try token.map { try NSKeyedArchiver.archivedData(withRootObject: $0, requiringSecureCoding: true) }+ }++ private func upload(local: [TokenTurn], cache: inout TokenSyncCache, zoneID: CKRecordZone.ID) async throws {+ let pending = TokenTurn.pseudonymized(TokenTurn.syncable(local), salt: cache.salt)+ .filter { candidate in+ guard let remote = cache.turns[candidate.id] else { return true }+ return remote.merging(candidate) != remote+ }+ .sorted { $0.updatedAt > $1.updatedAt }+ let deadline = Date().addingTimeInterval(20)+ var failures = SyncFailures()+ for offset in stride(from: 0, to: pending.count, by: 25) {+ try Task.checkCancellation()+ guard Date() < deadline else { break }+ let batch = Array(pending[offset ..< min(offset + 25, pending.count)])+ let ids = batch.map { Self.recordID($0.id, zoneID: zoneID) }+ try SyncCancellation.check(isEnabled: isEnabled)+ let existing = try await database.records(for: ids, desiredKeys: nil)+ var saving: [CKRecord] = []+ for candidate in batch {+ let id = Self.recordID(candidate.id, zoneID: zoneID)+ let record: CKRecord+ do {+ record = try fetchedRecord(existing[id]) ?? CKRecord(recordType: Self.recordType, recordID: id)+ } catch {+ failures.record(error)+ if failures.stopping != nil {+ break+ }+ continue+ }+ let remote = Self.turn(from: record)+ let merged = remote?.merging(candidate) ?? candidate+ if remote == merged {+ cache.turns[merged.id] = merged+ continue+ }+ Self.apply(merged, to: record)+ saving.append(record)+ }+ try save(cache)+ try failures.checkStopping()+ if saving.isEmpty {+ continue+ }+ try SyncCancellation.check(isEnabled: isEnabled)+ let result = try await database.modifyRecords(saving: saving, deleting: [], savePolicy: .ifServerRecordUnchanged, atomically: false)+ for record in saving {+ switch result.saveResults[record.recordID] {+ case let .success(saved):+ if let turn = Self.turn(from: saved) {+ cache.turns[turn.id] = turn+ }+ case let .failure(error): failures.record(error)+ case nil: failures.record(TokenSyncError.missingRecordResult)+ }+ }+ try save(cache)+ // 冲突不会使用覆盖写入, 下一轮重新获取服务端累计值后合并+ try failures.checkStopping()+ }+ try failures.check()+ }++ private func fetchedRecord(_ result: Result<CKRecord, any Error>?) throws -> CKRecord? {+ switch result {+ case let .success(record): record+ case let .failure(error as CKError) where error.code == .unknownItem: nil+ case let .failure(error): throw error+ case nil: throw TokenSyncError.missingRecordResult+ }+ }++ private func prune(cache: inout TokenSyncCache, zoneID: CKRecordZone.ID) async throws {+ let cutoff = HistoryStorage.retentionCutoffDate()+ let requiredRoots = Set(cache.turns.values.filter { $0.updatedAt >= cutoff }.map(\.rootID))+ let expired = cache.turns.values.filter {+ $0.updatedAt < cutoff && !requiredRoots.contains($0.id)+ }.prefix(200)+ let ids = expired.map { Self.recordID($0.id, zoneID: zoneID) }+ guard !ids.isEmpty else { return }+ try SyncCancellation.check(isEnabled: isEnabled)+ let result = try await database.modifyRecords(saving: [], deleting: ids, savePolicy: .ifServerRecordUnchanged, atomically: false)+ for id in ids {+ guard let deletion = result.deleteResults[id] else { throw TokenSyncError.missingRecordResult }+ do { try deletion.get() } catch let error as CKError where error.code == .unknownItem {}+ cache.turns.removeValue(forKey: id.recordName)+ }+ }++ private func load() throws -> TokenSyncCache? {+ try JSONFileStorage.withLock(in: directoryURL) {+ try fileCache.load { data in+ let header = try JSONLines.decoder.decode(TokenSyncCacheHeader.self, from: data)+ guard header.version == TokenSyncCache.currentVersion else { throw SyncRecovery.Failure.unsupportedCacheVersion }+ }+ }+ }++ private func save(_ cache: TokenSyncCache) throws {+ try JSONFileStorage.withLock(in: directoryURL) {+ try fileCache.save(cache)+ }+ }++ static func recordID(_ id: String, zoneID: CKRecordZone.ID) -> CKRecord.ID {+ CKRecord.ID(recordName: id, zoneID: zoneID)+ }++ static func apply(_ turn: TokenTurn, to record: CKRecord) {+ record["version"] = currentVersion as CKRecordValue+ record["rootID"] = turn.rootID as CKRecordValue+ record["startedAt"] = turn.startedAt as CKRecordValue?+ record["updatedAt"] = turn.updatedAt as CKRecordValue+ record["rebuiltAt"] = turn.rebuiltAt as CKRecordValue?+ record["generationID"] = turn.generationID as CKRecordValue+ record["ancestorIDs"] = turn.ancestorIDs.sorted() as CKRecordValue+ record["checkpoint"] = try? JSONLines.stableEncoder.encode(turn.checkpoint) as CKRecordValue+ record["hasConflict"] = (turn.hasConflict ? 1 : 0) as CKRecordValue+ record["usage"] = turn.usage.flatMap { try? JSONLines.stableEncoder.encode($0) } as CKRecordValue?+ }++ static func turn(from record: CKRecord) -> TokenTurn? {+ guard record.recordType == recordType, (record["version"] as? NSNumber)?.intValue == currentVersion,+ let rootID = record["rootID"] as? String,+ let updatedAt = record["updatedAt"] as? Date,+ let generationID = record["generationID"] as? String,+ let ancestors = record["ancestorIDs"] as? [String],+ let checkpointData = record["checkpoint"] as? Data,+ let checkpoint = try? JSONDecoder().decode([String: TokenObservationCheckpoint].self, from: checkpointData),+ checkpoint.values.allSatisfy({ $0.sequence > 0 && $0.usage.isValid }),+ let hasConflict = record["hasConflict"] as? NSNumber else { return nil }+ let id = record.recordID.recordName+ guard isHash(id), isHash(rootID) else { return nil }+ var usage: TokenUsage?+ if let value = record["usage"] {+ guard let data = value as? Data, let decoded = try? JSONDecoder().decode(TokenUsage.self, from: data), decoded.isValid else { return nil }+ usage = decoded+ }+ if let rebuiltAt = record["rebuiltAt"], !(rebuiltAt is Date) {+ return nil+ }+ return TokenTurn(+ id: id, rootID: rootID, startedAt: record["startedAt"] as? Date, updatedAt: updatedAt,+ usage: usage, rebuiltAt: record["rebuiltAt"] as? Date,+ generationID: generationID, ancestorIDs: Set(ancestors),+ checkpoint: checkpoint, hasConflict: hasConflict.boolValue+ )+ }++ private static func isHash(_ text: String) -> Bool {+ text.count == 64 && text.utf8.allSatisfy { (48 ... 57).contains($0) || (97 ... 102).contains($0) }+ }+}++private nonisolated struct TokenSyncCacheHeader: Decodable { let version: Int }++private nonisolated struct TokenSyncCache: Codable, Equatable {+ static let currentVersion = 2+ var version = currentVersion+ let accountScopedDeviceID: String+ let salt: Data+ var turns: [String: TokenTurn] = [:]+ var cursor: Data?+}++private nonisolated enum TokenSyncError: Error {+ case missingRecordResult+}diff --git a/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift b/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swiftdeleted file mode 100644index f30ac96..0000000--- a/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift+++ /dev/null@@ -1,869 +0,0 @@-import Foundation--/// 活跃轮次的线程定位信息, 用于关联 rollout 生命周期事件-nonisolated struct CodexActivityTurnReference: Hashable {- let threadID: String- let turnID: String- let startedAt: Date- var isTerminalUsageOnly = false-- static func == (lhs: Self, rhs: Self) -> Bool {- lhs.threadID == rhs.threadID && lhs.turnID == rhs.turnID- }-- func hash(into hasher: inout Hasher) {- hasher.combine(threadID)- hasher.combine(turnID)- }-}--/// 文件读取结果包含覆盖状态, 缓存事实不能替代本轮读取成功-actor CodexSessionLifecycleReader {- private let sessionsRootURL: URL- private let archivedSessionsRootURL: URL- private let fileManager: FileManager- private var roundRobinOffset = 0- private var cursorsByThread: [String: SessionFileCursor] = [:]- private var lastResolutionAttemptByThread: [String: Date] = [:]- private var lastRecursiveAttemptByThread: [String: Date] = [:]-- init(codexHomeURL: URL = CodexCLIResolver.codexHomeDirectory(), fileManager: FileManager = .default) {- sessionsRootURL = codexHomeURL.appendingPathComponent("sessions", isDirectory: true)- archivedSessionsRootURL = codexHomeURL.appendingPathComponent("archived_sessions", isDirectory: true)- self.fileManager = fileManager- }-- func lifecycleStates(for references: [CodexActivityTurnReference], now: Date = Date()) -> [CodexSessionTaskLifecycleState] {- let grouped = Dictionary(grouping: references, by: \.threadID)- let cutoff = now.addingTimeInterval(-CodexActivityRetention.window)- cursorsByThread = cursorsByThread.filter { $0.value.lastReadAt > cutoff }- lastResolutionAttemptByThread = lastResolutionAttemptByThread.filter { $0.value > cutoff }- lastRecursiveAttemptByThread = lastRecursiveAttemptByThread.filter { $0.value > cutoff }- var budget = Self.readByteLimit- var states: [CodexSessionTaskLifecycleState] = []- let threadIDs = grouped.keys.sorted()- let start = threadIDs.isEmpty ? 0 : roundRobinOffset % threadIDs.count- let ordered = Array(threadIDs.dropFirst(start)) + Array(threadIDs.prefix(start))- roundRobinOffset = threadIDs.isEmpty ? 0 : (start + 1) % threadIDs.count- for threadID in ordered {- guard !Task.isCancelled else { return [] }- guard let threadReferences = grouped[threadID],- let latest = threadReferences.max(by: { $0.startedAt < $1.startedAt }) else { continue }- var status = CodexSessionReadStatus.notFound- if var cursor = cursor(for: latest) {- let needsHistory = threadReferences.contains { cursor.historyReadLimit(for: $0) > 0 }- let tailLimit = needsHistory ? Self.readByteLimit / 2 : Self.readByteLimit- status = scan(into: &cursor, limit: min(tailLimit, budget), now: now)- budget -= min(budget, cursor.lastReadByteCount)- if cursor.metadata?.id != threadID {- status = .unavailable- }- cursor.prepareSupplementalHistory(for: threadReferences, now: now)- let historyLimit = threadReferences.map { cursor.historyReadLimit(for: $0) }.max() ?? 0- if status != .unavailable, budget > 0, historyLimit > 0 {- if !backfillHistory(into: &cursor, limit: historyLimit, budget: &budget) {- status = .unavailable- }- }- guard !Task.isCancelled else { return [] }- cursor.lastReadAt = now- let referencedTurns = Set(threadReferences.map(\.turnID))- cursor.lifecycleByTurnID = cursor.lifecycleByTurnID.filter {- referencedTurns.contains($0.key) || ($0.value.lastProgressAt ?? .distantPast) > cutoff- || (cursor.supplementalHistoryByTurn[$0.key]?.lastRequestedAt ?? .distantPast) > cutoff- }- cursor.supplementalHistoryByTurn = cursor.supplementalHistoryByTurn.filter {- $0.value.lastRequestedAt > cutoff- }- cursorsByThread[threadID] = cursor- }- let cursor = cursorsByThread[threadID]- for reference in threadReferences {- let known = cursor?.lifecycleByTurnID[reference.turnID]- let hasReadGap = known?.hasReadGap ?? (cursor?.hasDecodeFailures == true)- let hasHistoryGap = cursor?.hasHistoryGap(for: reference.turnID) == true- let turnStatus: CodexSessionReadStatus = if status == .unavailable || status == .notFound {- status- } else if known?.terminal != nil {- // 明确终态不依赖文件尾部另一条记录是否已写完- .complete- } else {- hasReadGap || hasHistoryGap ? .incomplete : status- }- states.append(CodexSessionTaskLifecycleState(- requestedThreadID: threadID, turnID: reference.turnID, startedAt: known?.startedAt,- approvalReviewer: known?.approvalReviewer, effort: known?.effort,- lastProgressAt: known?.lastProgressAt, terminal: turnStatus == .complete ? known?.terminal : nil,- readStatus: turnStatus, hasContext: known?.hasContext == true,- contextObservedAt: known?.contextObservedAt,- rootTurnID: known?.rootTurnID,- recordedThreadID: cursor?.metadata?.id,- rootSessionID: cursor?.metadata?.sessionID,- parentThreadID: cursor?.metadata?.parentThreadID,- lastExecutionProgressAt: known?.lastExecutionProgressAt,- incompleteTailUnchangedSince: status == .incomplete && !hasReadGap && !hasHistoryGap && known?.hasContext == true && known?.terminal == nil- ? cursor?.incompleteTailUnchangedSince : nil,- tokenUsage: turnStatus == .complete && status == .complete ? known?.tokenUsage : nil,- isHistoricalTerminal: known?.isHistoricalTerminal == true- ))- }- }- return states- }-- func resetResolutionFallbacks() {- lastResolutionAttemptByThread.removeAll()- lastRecursiveAttemptByThread.removeAll()- }-- private func cursor(for reference: CodexActivityTurnReference) -> SessionFileCursor? {- if let cursor = cursorsByThread[reference.threadID],- matchingFile(in: cursor.url.deletingLastPathComponent(), threadID: reference.threadID) == cursor.url {- return cursor- }- if cursorsByThread.removeValue(forKey: reference.threadID) != nil {- lastResolutionAttemptByThread.removeValue(forKey: reference.threadID)- lastRecursiveAttemptByThread.removeValue(forKey: reference.threadID)- }- let now = Date()- if let last = lastResolutionAttemptByThread[reference.threadID], now.timeIntervalSince(last) < 10 {- return nil- }- lastResolutionAttemptByThread[reference.threadID] = now- for directory in [sessionDirectory(for: reference.startedAt), sessionDirectory(for: now), archivedSessionsRootURL] {- if let url = matchingFile(in: directory, threadID: reference.threadID) {- let cursor = initialCursor(for: url)- if cursor.metadata?.id == reference.threadID {- return cursor- }- }- }- if let last = lastRecursiveAttemptByThread[reference.threadID], now.timeIntervalSince(last) < 60 {- return nil- }- lastRecursiveAttemptByThread[reference.threadID] = now- guard let enumerator = fileManager.enumerator(- at: sessionsRootURL, includingPropertiesForKeys: [.isRegularFileKey],- options: [.skipsHiddenFiles, .skipsPackageDescendants]- ) else { return nil }- let matches = enumerator.compactMap { $0 as? URL }.filter { Self.matchesFile($0, threadID: reference.threadID) }- guard matches.count == 1, let url = matches.first else { return nil }- let cursor = initialCursor(for: url)- return cursor.metadata?.id == reference.threadID ? cursor : nil- }-- private func matchingFile(in directory: URL, threadID: String) -> URL? {- let matches = (try? fileManager.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]))?- .filter { Self.matchesFile($0, threadID: threadID) } ?? []- return matches.count == 1 ? matches.first : nil- }-- private static func matchesFile(_ url: URL, threadID: String) -> Bool {- let name = url.lastPathComponent- guard name.hasPrefix("rollout-"), name.hasSuffix(".jsonl") else { return false }- let stem = String(name.dropLast(6))- if stem.hasSuffix("-\(threadID)") {- return true- }- guard let separator = stem.lastIndex(of: "_"), UUID(uuidString: String(stem[stem.index(after: separator)...])) != nil else { return false }- return stem[..<separator].hasSuffix("-\(threadID)")- }-- private func sessionDirectory(for date: Date) -> URL {- let components = CodexDateFormat.localGregorianCalendar.dateComponents([.year, .month, .day], from: date)- return sessionsRootURL.appendingPathComponent(String(format: "%04d/%02d/%02d", components.year ?? 0, components.month ?? 0, components.day ?? 0))- }-- private func initialCursor(for url: URL) -> SessionFileCursor {- let stat = WorkflowStorage.fileStat(at: url)- let size = stat?.size ?? 0- let offset = size > Self.bootstrapByteLimit ? size - Self.bootstrapByteLimit : 0- return SessionFileCursor(- url: url, fileIdentifier: stat?.identifier, offset: offset,- isDiscardingLine: offset > 0,- metadata: WorkflowRolloutMetadataReader.metadata(transcriptPath: url.path),- history: offset > 0 ? SessionHistoryCursor(offset: size, contextLookupOffset: offset) : nil,- initialContextOffset: offset > 0 ? offset : nil,- bootstrapEnd: offset > 0 ? size : nil- )- }-- private func backfillHistory(into cursor: inout SessionFileCursor, limit: Int, budget: inout Int) -> Bool {- guard var history = cursor.history, history.offset > 0 else { return true }- guard let before = WorkflowStorage.fileStat(at: cursor.url),- before.identifier == cursor.fileIdentifier, before.size >= cursor.offset,- let handle = try? FileHandle(forReadingFrom: cursor.url) else { return false }- defer { try? handle.close() }- let count = min(limit, budget, Int(history.offset))- let start = history.offset - UInt64(count)- guard (try? handle.seek(toOffset: start)) != nil,- let data = try? handle.read(upToCount: count) else { return false }- budget -= data.count- // 短读或后置检查失败前实际读到的字节也计入补查预算- cursor.totalHistoryBytesRead += UInt64(data.count)- guard data.count == count else { return false }- history.offset = start- history.consume(data, file: cursor, maximumBufferedLineByteCount: Self.maximumBufferedLineByteCount)- guard let after = WorkflowStorage.fileStat(at: cursor.url),- after.identifier == before.identifier, after.size >= before.size else { return false }- for (turnID, earlier) in history.lifecycleByTurnID {- var latest = cursor.lifecycleByTurnID[turnID] ?? SessionTurnLifecycle()- if latest.terminal == nil, earlier.terminal != nil {- latest.isHistoricalTerminal = true- }- latest.mergeEarlier(earlier)- cursor.lifecycleByTurnID[turnID] = latest- }- cursor.restoreInitialContext(from: history)- // 已合并的事实留在主游标, 回读只保留跨块半行和待定位的进展- history.lifecycleByTurnID.removeAll(keepingCapacity: true)- cursor.history = history- return true- }-- private func scan(into cursor: inout SessionFileCursor, limit: Int, now: Date = Date()) -> CodexSessionReadStatus {- cursor.lastReadByteCount = 0- var previousTailUnchangedSince = cursor.incompleteTailUnchangedSince- cursor.incompleteTailUnchangedSince = nil- guard let stat = WorkflowStorage.fileStat(at: cursor.url) else { return .unavailable }- if stat.size < cursor.offset || (cursor.fileIdentifier != nil && cursor.fileIdentifier != stat.identifier) {- cursor = initialCursor(for: cursor.url)- previousTailUnchangedSince = nil- }- let end = stat.size- guard let handle = try? FileHandle(forReadingFrom: cursor.url) else { return .unavailable }- defer { try? handle.close() }- if end > cursor.offset {- guard limit > 0 else { return .incomplete }- guard (try? handle.seek(toOffset: cursor.offset)) != nil,- let data = try? handle.read(upToCount: min(limit, Int(end - cursor.offset))), !data.isEmpty else { return .unavailable }- cursor.lastReadByteCount = data.count- cursor.offset += UInt64(data.count)- cursor.fileIdentifier = stat.identifier- cursor.consume(data, maximumBufferedLineByteCount: Self.maximumBufferedLineByteCount)- }- guard let after = WorkflowStorage.fileStat(at: cursor.url), after.identifier == stat.identifier,- after.size >= end else { return .unavailable }- // 只有实际文件末尾的有界半行可以计时, 积压和跳过的大行不能作为静默依据- if cursor.offset == after.size, cursor.hasPartialLine, !cursor.isDiscardingLine {- cursor.incompleteTailUnchangedSince = cursor.lastReadByteCount > 0 ? now : previousTailUnchangedSince ?? now- }- return cursor.offset == end && !cursor.hasPartialLine ? .complete : .incomplete- }-- private static let bootstrapByteLimit: UInt64 = 512 * 1024- private static let readByteLimit = 8 * 1024 * 1024- private static let maximumBufferedLineByteCount = 16 * 1024 * 1024-}--private nonisolated struct SessionSupplementalHistoryRead {- let initialHistoryBytesRead: UInt64- var lastRequestedAt: Date-}--private nonisolated struct SessionFileCursor {- let url: URL- var fileIdentifier: UInt64?- var offset: UInt64- var isDiscardingLine: Bool- var metadata: WorkflowRolloutMetadataPayload?- var currentTurnID: String?- var hasTurnBoundary = false- var lifecycleByTurnID: [String: SessionTurnLifecycle] = [:]- var supplementalHistoryByTurn: [String: SessionSupplementalHistoryRead] = [:]- var totalHistoryBytesRead: UInt64 = 0- var partialLineData = Data()- var history: SessionHistoryCursor?- var initialContextOffset: UInt64?- private var pendingInitialProgress = SessionTurnLifecycle()- private var initialProgressBeforeTerminal: [String: SessionTurnLifecycle] = [:]- var bootstrapEnd: UInt64?- private(set) var lastReadGapOffset: UInt64?- var lastReadAt = Date()- var lastReadByteCount = 0- var incompleteTailUnchangedSince: Date?-- var hasDecodeFailures: Bool {- lastReadGapOffset != nil- }-- var hasPartialLine: Bool {- isDiscardingLine || !partialLineData.isEmpty- }-- private var hasPendingInitialProgress: Bool {- initialContextOffset != nil && pendingInitialProgress.lastProgressAt != nil- }-- func hasHistoryGap(for turnID: String) -> Bool {- let hasStart = lifecycleByTurnID[turnID]?.startedAt != nil- return (hasPendingInitialProgress && !hasStart)- || history.map { $0.requiresLeadingLineRecovery || ($0.offset > 0 && (!hasStart || hasPendingInitialProgress)) } == true- }-- func historyReadLimit(for reference: CodexActivityTurnReference) -> Int {- guard history.map({ $0.offset > 0 }) == true else { return 0 }- let known = lifecycleByTurnID[reference.turnID]- if known?.terminal == nil, !reference.isTerminalUsageOnly {- let needsHistory = hasPendingInitialProgress || history?.requiresLeadingLineRecovery == true- || known?.startedAt == nil || known?.hasContext != true- || known?.effort == nil || known?.approvalReviewer == nil- return needsHistory ? Int.max : 0- }- guard known?.terminal == nil || known?.rootTurnID == nil || known?.hasTokenUsageRecord != true else { return 0 }- let initialBytes = supplementalHistoryByTurn[reference.turnID]?.initialHistoryBytesRead ?? totalHistoryBytesRead- let consumedBytes = min(UInt64(Self.supplementalHistoryByteLimit), totalHistoryBytesRead - initialBytes)- return Self.supplementalHistoryByteLimit - Int(consumedBytes)- }-- mutating func prepareSupplementalHistory(for references: [CodexActivityTurnReference], now: Date) {- let initial = SessionSupplementalHistoryRead(initialHistoryBytesRead: totalHistoryBytesRead, lastRequestedAt: now)- for reference in references where reference.isTerminalUsageOnly || lifecycleByTurnID[reference.turnID]?.terminal != nil {- supplementalHistoryByTurn[reference.turnID, default: initial].lastRequestedAt = now- }- }-- private static let supplementalHistoryByteLimit = 32 * 1024 * 1024-- mutating func restoreInitialContext(from history: SessionHistoryCursor) {- guard initialContextOffset != nil, history.hasInitialTurnBoundary, !history.initialContextHasReadGap else { return }- if let turnID = history.initialTurnID {- var state = lifecycleByTurnID[turnID] ?? SessionTurnLifecycle()- state.mergeEarlier(initialProgressBeforeTerminal[turnID] ?? pendingInitialProgress)- lifecycleByTurnID[turnID] = state- }- pendingInitialProgress = SessionTurnLifecycle()- initialContextOffset = nil- // 尾部可能已进入下一轮, 补查只给启动片段补归属, 不回退当前轮次- if !hasTurnBoundary {- currentTurnID = history.initialTurnID.flatMap { initialProgressBeforeTerminal[$0] == nil ? $0 : nil }- hasTurnBoundary = true- }- initialProgressBeforeTerminal.removeAll()- }-- /// 读取预算可以在一行中间结束, 游标仍需推进并在下一轮继续拼接- /// 超过缓冲上限后只扫描到换行, 避免异常大行阻塞后续终态- mutating func consume(_ data: Data, maximumBufferedLineByteCount: Int) {- var fragmentStart = data.startIndex- while let newline = data[fragmentStart...].firstIndex(of: JSONLines.newlineByte) {- if isDiscardingLine, let bootstrapEnd {- let lineEnd = offset - UInt64(data.count) + UInt64(newline + 1)- self.bootstrapEnd = nil- // 启动时跨过的半行后来才写完, 重新定位这一行以免正反两路都跳过它- if lineEnd > bootstrapEnd {- history = SessionHistoryCursor(- offset: lineEnd, contextLookupOffset: initialContextOffset, requiresLeadingLineRecovery: true- )- }- }- consumeLineFragment(- data[fragmentStart ..< newline],- completesLine: true,- endingAt: offset - UInt64(data.count) + UInt64(newline + 1),- maximumBufferedLineByteCount: maximumBufferedLineByteCount- )- fragmentStart = data.index(after: newline)- }- if fragmentStart < data.endIndex {- consumeLineFragment(- data[fragmentStart...],- completesLine: false,- endingAt: offset,- maximumBufferedLineByteCount: maximumBufferedLineByteCount- )- }- }-- private mutating func consumeLineFragment(- _ fragment: Data.SubSequence,- completesLine: Bool,- endingAt: UInt64,- maximumBufferedLineByteCount: Int- ) {- if isDiscardingLine {- if completesLine {- isDiscardingLine = false- }- return- }-- guard fragment.count <= maximumBufferedLineByteCount - partialLineData.count else {- partialLineData.removeAll(keepingCapacity: false)- markReadGap(at: endingAt)- isDiscardingLine = !completesLine- return- }-- partialLineData.append(contentsOf: fragment)- guard completesLine else { return }- let keepsCapacity = partialLineData.count <= Self.retainedLineCapacityByteLimit- defer { partialLineData.removeAll(keepingCapacity: keepsCapacity) }-- applyCompleteLine(partialLineData, endingAt: endingAt)- }-- @discardableResult- mutating func applyCompleteLine(_ data: Data, endingAt: UInt64) -> CodexRolloutLineEnvelope? {- guard !JSONLines.isBlankLine(data) else { return nil }- let decoder = JSONDecoder()- guard let envelope = try? decoder.decode(CodexRolloutLineEnvelope.self, from: data) else {- markReadGap(at: endingAt)- return nil- }- apply(envelope)- if envelope.type == "token_usage_record", let turnID = envelope.payload?.turnID {- // 用量字段损坏不能影响生命周期解码, 也不能沿用上一条累计值- var state = lifecycleByTurnID[turnID] ?? SessionTurnLifecycle()- state.tokenUsage = nil- state.hasTokenUsageRecord = true- if let record = try? decoder.decode(CodexRolloutTokenUsageRecord.self, from: data).payload,- record.threadID == metadata?.id,- record.sessionID == (metadata?.sessionID ?? metadata?.id),- !record.responseID.isEmpty, !record.rootTurnID.isEmpty,- !turnID.isEmpty, record.turnTokenUsage.isValid {- state.tokenUsage = record.turnTokenUsage- state.rootTurnID = record.rootTurnID- }- lifecycleByTurnID[turnID] = state- }- return envelope- }-- private static let retainedLineCapacityByteLimit = 512 * 1024-- /// 损坏可能遮住 turn 边界, 只保留已明确结束的事实, 后续新 turn 独立建立覆盖- mutating func markReadGap(at offset: UInt64) {- lastReadGapOffset = offset- currentTurnID = nil- hasTurnBoundary = true- pendingInitialProgress = SessionTurnLifecycle()- initialProgressBeforeTerminal.removeAll()- for turnID in lifecycleByTurnID.keys {- lifecycleByTurnID[turnID]?.tokenUsage = nil- lifecycleByTurnID[turnID]?.hasTokenUsageRecord = true- if lifecycleByTurnID[turnID]?.terminal == nil {- lifecycleByTurnID[turnID]?.hasReadGap = true- }- }- }-- mutating func apply(_ envelope: CodexRolloutLineEnvelope) {- if envelope.endsTurnContext, !hasTurnBoundary, initialContextOffset != nil,- let turnID = envelope.payload?.turnID, !turnID.isEmpty, initialProgressBeforeTerminal[turnID] == nil {- // 起始归属尚未恢复, 先保留各轮次结束前的进展, 不让迟到终态截断其他轮次- initialProgressBeforeTerminal[turnID] = pendingInitialProgress- }- if envelope.startsTurnContext {- hasTurnBoundary = true- currentTurnID = envelope.payload?.turnID.flatMap { $0.isEmpty ? nil : $0 }- if let turnID = currentTurnID, let rootTurnID = envelope.payload?.rootTurnID, !rootTurnID.isEmpty {- var state = lifecycleByTurnID[turnID] ?? SessionTurnLifecycle()- state.rootTurnID = rootTurnID- lifecycleByTurnID[turnID] = state- }- }- if let event = envelope.progressEvent(currentTurnID: currentTurnID) {- apply(event)- } else if !hasTurnBoundary, initialContextOffset != nil, let progress = envelope.unassignedProgress {- // 只暂存启动片段的进展时间, 首个轮次边界之后按新上下文正常处理- pendingInitialProgress.apply(progress)- }- if let event = envelope.lifecycleEvent {- apply(event)- }- if envelope.type == "turn_context", let turnID = currentTurnID {- var state = lifecycleByTurnID[turnID] ?? SessionTurnLifecycle()- state.hasContext = true- lifecycleByTurnID[turnID] = state- }- if envelope.endsTurnContext, envelope.payload?.turnID == currentTurnID {- currentTurnID = nil- }- }-- mutating func apply(_ event: SessionLifecycleEvent) {- var state = lifecycleByTurnID[event.turnID] ?? SessionTurnLifecycle()- state.apply(event.change)- lifecycleByTurnID[event.turnID] = state- }-}--/// 从启动时的文件末尾向前读, 每个完整行只在回读链路中解析一次-private nonisolated struct SessionHistoryCursor {- var offset: UInt64- var contextLookupOffset: UInt64?- var requiresLeadingLineRecovery = false- private var hasSkippedTail = false- var lifecycleByTurnID: [String: SessionTurnLifecycle] = [:]- private var partialLineData = Data()- // 第一段可能是尚未落盘完整的尾行, 由正向游标继续跟踪- private var isDiscardingLine = true- private var hasDecodeFailures = false- private var pendingProgress = SessionTurnLifecycle()- private var progressAfterTerminals: [(turnID: String, progress: SessionTurnLifecycle)] = []- private var initialEndedTurnIDs: Set<String> = []- private(set) var hasInitialTurnBoundary = false- private(set) var initialTurnID: String?- private(set) var initialContextHasReadGap = false-- mutating func consume(_ data: Data, file: SessionFileCursor, maximumBufferedLineByteCount: Int) {- var end = data.endIndex- while let newline = data[..<end].lastIndex(of: JSONLines.newlineByte) {- prepend(data[(newline + 1) ..< end], maximumBufferedLineByteCount: maximumBufferedLineByteCount)- finishLine(file: file, lineStart: offset + UInt64(newline + 1))- end = newline- }- prepend(data[..<end], maximumBufferedLineByteCount: maximumBufferedLineByteCount)- if offset == 0 {- finishLine(file: file, lineStart: 0)- }- }-- private mutating func prepend(_ fragment: Data.SubSequence, maximumBufferedLineByteCount: Int) {- guard !isDiscardingLine else { return }- guard fragment.count <= maximumBufferedLineByteCount - partialLineData.count else {- partialLineData.removeAll(keepingCapacity: false)- isDiscardingLine = true- hasDecodeFailures = true- pendingProgress = SessionTurnLifecycle()- progressAfterTerminals.removeAll()- return- }- partialLineData = Data(fragment) + partialLineData- }-- private mutating func finishLine(file: SessionFileCursor, lineStart: UInt64) {- if hasSkippedTail {- requiresLeadingLineRecovery = false- }- hasSkippedTail = true- defer {- partialLineData.removeAll(keepingCapacity: false)- isDiscardingLine = false- }- guard !isDiscardingLine, !partialLineData.isEmpty else { return }- var earlier = SessionFileCursor(- url: file.url, fileIdentifier: file.fileIdentifier, offset: 0,- isDiscardingLine: false, metadata: file.metadata- )- let envelope = earlier.applyCompleteLine(partialLineData, endingAt: lineStart + UInt64(partialLineData.count))- if earlier.hasDecodeFailures {- hasDecodeFailures = true- pendingProgress = SessionTurnLifecycle()- progressAfterTerminals.removeAll()- }- if let envelope {- if !hasInitialTurnBoundary, let contextLookupOffset, lineStart <= contextLookupOffset {- if envelope.endsTurnContext, let turnID = envelope.payload?.turnID, !turnID.isEmpty {- initialEndedTurnIDs.insert(turnID)- }- if envelope.startsTurnContext {- hasInitialTurnBoundary = true- initialContextHasReadGap = hasDecodeFailures- initialTurnID = envelope.payload?.turnID.flatMap { $0.isEmpty || initialEndedTurnIDs.contains($0) ? nil : $0 }- initialEndedTurnIDs.removeAll()- }- }- if envelope.endsTurnContext, let turnID = envelope.payload?.turnID, !turnID.isEmpty {- progressAfterTerminals.append((turnID, pendingProgress))- pendingProgress = SessionTurnLifecycle()- }- if envelope.startsTurnContext {- if let turnID = envelope.payload?.turnID, !turnID.isEmpty {- var state = earlier.lifecycleByTurnID[turnID] ?? SessionTurnLifecycle()- state.mergeEarlier(pendingProgress)- // 反向读到开始边界后才确定归属, 只排除该轮次自身结束后的进展- for segment in progressAfterTerminals.reversed() {- guard segment.turnID != turnID else { break }- state.mergeEarlier(segment.progress)- }- earlier.lifecycleByTurnID[turnID] = state- }- pendingProgress = SessionTurnLifecycle()- progressAfterTerminals.removeAll()- }- // 没有显式轮次的进展, 遇到更早的上下文边界后才能确定归属- if let progress = envelope.unassignedProgress {- pendingProgress.apply(progress)- }- }- for (turnID, var state) in earlier.lifecycleByTurnID {- // 正向新增的坏行可能不在历史快照中, 按位置保留跨过该缺口的轮次状态- if hasDecodeFailures || file.lastReadGapOffset.map({ lineStart < $0 }) == true {- state.hasReadGap = true- state.tokenUsage = nil- state.hasTokenUsageRecord = true- }- var latest = lifecycleByTurnID[turnID] ?? SessionTurnLifecycle()- latest.mergeEarlier(state)- lifecycleByTurnID[turnID] = latest- }- }-}--// MARK: - rollout 行解码--/// Codex rollout JSONL 单行的共享解码模型-/// Hook 子进程 (WorkflowTurnContextReader) 与 lifecycle reader 共用同一份 schema-nonisolated struct CodexRolloutLineEnvelope: Decodable {- let timestamp: String?- let type: String- let payload: CodexRolloutLinePayload?-}--nonisolated struct CodexRolloutLinePayload: Decodable {- let type: String?- let turnID: String?- let rootTurnID: String?- let messageMetadata: CodexRolloutMessageMetadata?- let role: String?- let startedAt: Double?- let completedAt: Double?- let durationMilliseconds: Double?- let approvalReviewer: CodexApprovalReviewer?- let effort: String?-- var normalizedEffort: String? {- guard let effort else {- return nil- }- let value = effort.trimmingCharacters(in: .whitespacesAndNewlines)- return value.isEmpty ? nil : value- }-- private enum CodingKeys: String, CodingKey {- case type, role- case turnID = "turn_id"- case rootTurnID = "root_turn_id"- case messageMetadata = "internal_chat_message_metadata_passthrough"- case startedAt = "started_at"- case completedAt = "completed_at"- case durationMilliseconds = "duration_ms"- case approvalReviewer = "approvals_reviewer"- case effort- }-}--nonisolated struct CodexRolloutMessageMetadata: Decodable {- let turnID: String?-- private enum CodingKeys: String, CodingKey {- case turnID = "turn_id"- }-}--private nonisolated extension CodexRolloutLineEnvelope {- var startsTurnContext: Bool {- type == "turn_context" || (type == "event_msg" && ["task_started", "turn_started"].contains(payload?.type ?? ""))- }-- var endsTurnContext: Bool {- type == "event_msg" && ["task_complete", "turn_complete", "turn_aborted"].contains(payload?.type ?? "")- }-- func progressEvent(currentTurnID: String?) -> SessionLifecycleEvent? {- guard let turnID = explicitProgressTurnID ?? currentTurnID, !turnID.isEmpty,- let change = progressChange else { return nil }- return SessionLifecycleEvent(turnID: turnID, change: change)- }-- var unassignedProgress: SessionLifecycleChange? {- explicitProgressTurnID == nil ? progressChange : nil- }-- private var explicitProgressTurnID: String? {- type == "response_item" ? payload?.messageMetadata?.turnID : payload?.turnID- }-- private var progressChange: SessionLifecycleChange? {- let progressTypes: Set = [- "token_count", "item_completed", "agent_message", "agent_reasoning",- "task_started", "turn_started", "task_complete", "turn_complete", "turn_aborted"- ]- guard type == "response_item" || type == "token_usage_record"- || (type == "event_msg" && payload?.type.map(progressTypes.contains) == true) else {- return nil- }- let eventDate = timestamp.flatMap(CodexDateFormat.iso8601Date)- ?? payload?.completedAt.flatMap(Self.date)- ?? payload?.startedAt.flatMap(Self.date)- guard let eventDate else {- return nil- }-- let isExecutionProgress = if type == "response_item" {- payload?.role == "assistant" || ["function_call_output", "custom_tool_call_output", "tool_search_output"].contains(payload?.type ?? "")- } else {- type == "event_msg" && ["agent_message", "agent_reasoning"].contains(payload?.type ?? "")- }- return .progress(at: eventDate, resumesApproval: isExecutionProgress)- }-- var lifecycleEvent: SessionLifecycleEvent? {- guard let payload,- let turnID = payload.turnID,- !turnID.isEmpty else {- return nil- }-- if type == "turn_context" {- let effort = payload.normalizedEffort- guard payload.approvalReviewer != nil || effort != nil else {- return nil- }- return SessionLifecycleEvent(- turnID: turnID,- change: .context(- approvalReviewer: payload.approvalReviewer,- effort: effort,- observedAt: timestamp.flatMap(CodexDateFormat.iso8601Date)- )- )- }-- guard type == "event_msg" else {- return nil- }-- switch payload.type {- case "task_started", "turn_started":- guard let startedAt = payload.startedAt.flatMap(Self.date) else {- return nil- }- return SessionLifecycleEvent(turnID: turnID, change: .started(at: startedAt))- case "task_complete", "turn_complete":- guard let completedAt = payload.completedAt.flatMap(Self.date) ?? timestamp.flatMap(CodexDateFormat.iso8601Date) else {- return nil- }- let duration = payload.durationMilliseconds.flatMap { milliseconds in- milliseconds.isFinite && milliseconds >= 0 ? milliseconds / 1000 : nil- }- return SessionLifecycleEvent(turnID: turnID, change: .completed(at: completedAt, duration: duration))- case "turn_aborted":- return SessionLifecycleEvent(- turnID: turnID,- change: .aborted(at: timestamp.flatMap(CodexDateFormat.iso8601Date))- )- default:- return nil- }- }-- private static func date(from seconds: Double) -> Date? {- guard seconds.isFinite, seconds > 0 else {- return nil- }- return Date(timeIntervalSince1970: seconds)- }-}--private nonisolated struct SessionLifecycleEvent {- let turnID: String- let change: SessionLifecycleChange-}--private nonisolated enum SessionLifecycleChange {- case progress(at: Date, resumesApproval: Bool)- case started(at: Date)- case context(approvalReviewer: CodexApprovalReviewer?, effort: String?, observedAt: Date?)- case completed(at: Date, duration: TimeInterval?)- case aborted(at: Date?)-}--private nonisolated struct SessionTurnLifecycle {- var tokenUsage: CodexTokenUsage?- var hasTokenUsageRecord = false- var isHistoricalTerminal = false- var rootTurnID: String?- var hasReadGap = false- var contextObservedAt: Date?- var hasContext = false- var startedAt: Date?- var approvalReviewer: CodexApprovalReviewer?- var effort: String?- var lastProgressAt: Date?- var lastExecutionProgressAt: Date?- var terminal: CodexSessionTaskTerminalState?-- mutating func mergeEarlier(_ earlier: Self) {- hasReadGap = hasReadGap || earlier.hasReadGap- hasContext = hasContext || earlier.hasContext- if let start = earlier.startedAt {- startedAt = min(startedAt ?? start, start)- }- approvalReviewer = approvalReviewer ?? earlier.approvalReviewer- effort = effort ?? earlier.effort- contextObservedAt = contextObservedAt ?? earlier.contextObservedAt- rootTurnID = rootTurnID ?? earlier.rootTurnID- terminal = terminal ?? earlier.terminal- if let progress = earlier.lastProgressAt {- lastProgressAt = max(lastProgressAt ?? progress, progress)- }- if let progress = earlier.lastExecutionProgressAt {- lastExecutionProgressAt = max(lastExecutionProgressAt ?? progress, progress)- }- if !hasTokenUsageRecord {- tokenUsage = earlier.tokenUsage- hasTokenUsageRecord = earlier.hasTokenUsageRecord- }- }-- mutating func apply(_ change: SessionLifecycleChange) {- switch change {- case let .progress(at, resumesApproval):- lastProgressAt = max(lastProgressAt ?? .distantPast, at)- if resumesApproval {- lastExecutionProgressAt = max(lastExecutionProgressAt ?? .distantPast, at)- }- case let .started(at):- if let currentStartedAt = startedAt {- startedAt = min(currentStartedAt, at)- } else {- startedAt = at- }- case let .context(reviewer, reasoningEffort, observedAt):- hasContext = true- contextObservedAt = observedAt ?? contextObservedAt- approvalReviewer = reviewer ?? approvalReviewer- effort = reasoningEffort ?? effort- case let .completed(at, duration):- terminal = .completed(at: at, duration: duration)- case let .aborted(at):- terminal = .aborted(at: at)- }- }-}--nonisolated struct CodexSessionTaskLifecycleState {- let requestedThreadID: String- let turnID: String- let startedAt: Date?- let approvalReviewer: CodexApprovalReviewer?- let effort: String?- let lastProgressAt: Date?- let terminal: CodexSessionTaskTerminalState?- var readStatus: CodexSessionReadStatus = .complete- var hasContext = false- var contextObservedAt: Date?- var rootTurnID: String?- var recordedThreadID: String?- var rootSessionID: String?- var parentThreadID: String?- var lastExecutionProgressAt: Date?- var incompleteTailUnchangedSince: Date?- var tokenUsage: CodexTokenUsage?- var isHistoricalTerminal = false-}--nonisolated enum CodexSessionReadStatus {- case complete- case incomplete- case unavailable- case notFound-}--nonisolated enum CodexSessionTaskTerminalState {- case completed(at: Date, duration: TimeInterval?)- case aborted(at: Date?)-}diff --git a/CodexBar/Services/Workflow/CodexTokenHistoryStore.swift b/CodexBar/Services/Workflow/CodexTokenHistoryStore.swiftdeleted file mode 100644index 71ac25c..0000000--- a/CodexBar/Services/Workflow/CodexTokenHistoryStore.swift+++ /dev/null@@ -1,596 +0,0 @@-import CryptoKit-import Darwin-import Foundation-import os--/// 历史采集独立于实时任务, 全量补读后按文件游标增量消费-actor CodexTokenHistoryStore {- private let codexHomeURL: URL- private let directoryURL: URL- private let byteBudget: Int- private let reportProgress: @Sendable (CodexTokenReplayProgress) -> Void- private var lastReportedProgress: CodexTokenReplayProgress?-- init(- codexHomeURL: URL = CodexCLIResolver.codexHomeDirectory(),- directoryURL: URL = WorkflowStorage.directoryURL().appendingPathComponent("Tokens"),- byteBudget: Int = 64 * 1024 * 1024,- reportProgress: @escaping @Sendable (CodexTokenReplayProgress) -> Void = { $0.writeLog() }- ) {- self.codexHomeURL = codexHomeURL- self.directoryURL = directoryURL- self.byteBudget = byteBudget- self.reportProgress = reportProgress- }-- func refresh(now: Date = Date(), baseline: CodexTokenHistoryBaseline? = nil) throws -> [CodexTokenTurn] {- let duration = LogDuration()- return try CodexTokenFileStorage.withLock(in: directoryURL) {- let url = directoryURL.appendingPathComponent("ledger.json")- var ledger = try CodexTokenFileStorage.load(TokenHistoryLedger.self, from: url) ?? TokenHistoryLedger()- guard ledger.schema == TokenHistoryLedger.currentSchema else { throw CocoaError(.fileReadCorruptFile) }- var restored = false- for turn in ledger.turns.values {- guard let replacement = baseline?.replacement(for: turn) else { continue }- ledger.restore(replacement)- restored = true- }- // 已扫描的累计值可能混有重建前的旧记录, 重新按记录时间消费而不是给旧值换上新标记- if restored {- ledger.files.removeAll()- }- let cutoff = WorkflowStorage.retentionCutoffDate(today: now)- let files = rolloutFiles(since: cutoff).map { (url: $0, key: fileKey($0)) }- var remaining = byteBudget- // 每轮先处理上次尚未扫描的文件, 防止大型活跃文件让历史补读饥饿- let ordered = files.map { file in- (- file: file,- lastReadAt: ledger.files[file.key]?.lastReadAt ?? .distantPast,- modifiedAt: (try? file.url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? .distantPast- )- }.sorted { lhs, rhs in- if lhs.lastReadAt != rhs.lastReadAt {- return lhs.lastReadAt < rhs.lastReadAt- }- // 同批未读文件优先补近期数据, 不依赖文件系统枚举顺序- if lhs.modifiedAt != rhs.modifiedAt {- return lhs.modifiedAt > rhs.modifiedAt- }- return lhs.file.url.path < rhs.file.url.path- }.map(\.file)- var results: [String: TokenHistoryScanResult] = [:]- for file in ordered where remaining > 0 {- try Task.checkCancellation()- results[file.key] = try scan(file.url, key: file.key, ledger: &ledger, remaining: &remaining, now: now, baseline: baseline)- }- let roots = Set(ledger.turns.values.filter { $0.updatedAt >= cutoff }.map(\.rootID))- ledger.turns = ledger.turns.filter { $0.value.updatedAt >= cutoff || roots.contains($0.key) }- ledger.recoveryCutoffs = ledger.recoveryCutoffs?.filter { ledger.turns[$0.key] != nil }- let fileKeys = Set(files.map(\.key))- ledger.files = ledger.files.filter { fileKeys.contains($0.key) }- try CodexTokenFileStorage.save(ledger, to: url)- let progress = replayProgress(files: files, ledger: ledger, results: results, batchBytes: byteBudget - remaining, duration: duration)- publishProgress(progress, restored: restored)- return Array(ledger.turns.values)- }- }-- private func replayProgress(- files: [(url: URL, key: String)], ledger: TokenHistoryLedger, results: [String: TokenHistoryScanResult], batchBytes: Int, duration: LogDuration- ) -> CodexTokenReplayProgress {- var progress = CodexTokenReplayProgress(totalFiles: files.count, batchBytes: batchBytes, elapsed: duration.elapsed)- for (url, key) in files {- guard let stat = WorkflowStorage.fileStat(at: url) else {- progress.unavailableFiles += 1- continue- }- progress.totalBytes += stat.size- let cursor = ledger.files[key]- let hasValidCursor = cursor?.inode == stat.identifier && (cursor?.offset ?? 0) <= stat.size- let offset = hasValidCursor ? cursor?.offset ?? 0 : 0- progress.processedBytes += offset- if results[key] == .unavailable {- progress.unavailableFiles += 1- } else if results[key] == .waitingForLine || cursor?.droppingLongLine == true && offset == stat.size {- progress.waitingFiles += 1- } else if hasValidCursor, offset == stat.size {- progress.completedFiles += 1- }- }- return progress- }-- private func publishProgress(_ progress: CodexTokenReplayProgress, restored: Bool) {- guard progress.totalFiles > 0 || lastReportedProgress != nil else { return }- if let previous = lastReportedProgress, !restored {- // 追平后的普通追加不重复记录完成, 停在同一个半行或不可读文件时也不刷屏- guard !(previous.isComplete && progress.isComplete), !progress.hasSamePosition(as: previous) else { return }- }- lastReportedProgress = progress- reportProgress(progress)- }-- private func rolloutFiles(since cutoff: Date) -> [URL] {- var result: [URL] = []- for name in ["sessions", "archived_sessions"] {- let root = codexHomeURL.appendingPathComponent(name)- guard let enumerator = FileManager.default.enumerator(- at: root, includingPropertiesForKeys: [.isRegularFileKey, .contentModificationDateKey], options: [.skipsHiddenFiles]- ) else { continue }- for case let url as URL in enumerator where url.pathExtension == "jsonl" && url.lastPathComponent.hasPrefix("rollout-") {- guard let values = try? url.resourceValues(forKeys: [.isRegularFileKey, .contentModificationDateKey]),- values.isRegularFile == true, (values.contentModificationDate ?? .distantPast) >= cutoff else { continue }- result.append(url)- }- }- return result- }-- @discardableResult- private func scan(- _ url: URL, key: String? = nil, ledger: inout TokenHistoryLedger, remaining: inout Int, now: Date,- snapshot: WorkflowFileStat? = nil, baseline: CodexTokenHistoryBaseline? = nil- ) throws -> TokenHistoryScanResult {- guard let source = try openSource(url, snapshot: snapshot) else { return .unavailable }- let handle = source.handle- defer { try? handle.close() }- let size = snapshot?.size ?? source.stat.size- let inode = source.stat.identifier- let key = key ?? fileKey(url)- var cursor = ledger.files[key] ?? TokenHistoryCursor(inode: inode)- if cursor.inode != inode || cursor.offset > size {- cursor = TokenHistoryCursor(inode: inode)- }- if let hash = cursor.boundaryHash, try boundaryHash(handle, at: cursor.offset) != hash {- if snapshot != nil {- throw CodexTokenRebuildError.sourceChanged- }- cursor = TokenHistoryCursor(inode: inode)- }- cursor.lastReadAt = now- guard cursor.offset < size else {- ledger.files[key] = cursor- return TokenHistoryScanResult(reachedEnd: true, hasPartialLine: cursor.droppingLongLine)- }- try handle.seek(toOffset: cursor.offset)- var line = Data()- var dropping = cursor.droppingLongLine- reading: while cursor.offset < size, remaining > 0 || !line.isEmpty {- try Task.checkCancellation()- let count = remaining > 0 ? min(64 * 1024, remaining) : 64 * 1024- let data = try handle.read(upToCount: min(count, Int(clamping: size - cursor.offset))) ?? Data()- if data.isEmpty {- if snapshot != nil {- throw CodexTokenRebuildError.sourceChanged- }- break- }- remaining -= data.count- var offset = data.startIndex- while offset < data.endIndex {- let newline = data[offset...].firstIndex(of: JSONLines.newlineByte)- let end = newline ?? data.endIndex- let fragment = data[offset ..< end]- cursor.offset += UInt64(fragment.count + (newline == nil ? 0 : 1))- if !dropping {- if line.count + fragment.count > 1024 * 1024 {- line.removeAll(keepingCapacity: false)- dropping = true- } else {- line.append(contentsOf: fragment)- }- }- if newline != nil {- if !dropping {- consume(line, thread: source.thread, session: source.session, ledger: &ledger, baseline: baseline)- }- line.removeAll(keepingCapacity: true)- dropping = false- cursor.committedOffset = cursor.offset- if remaining <= 0 {- break reading- }- offset = end + 1- } else {- break- }- }- }- // 半行不提交, 超长正文则跨轮继续跳过, 不将正文写入缓存- let reachedEnd = cursor.offset >= size- cursor.droppingLongLine = dropping- if !dropping {- cursor.offset = cursor.committedOffset- }- cursor.boundaryHash = try boundaryHash(handle, at: cursor.offset)- ledger.files[key] = cursor- return TokenHistoryScanResult(reachedEnd: reachedEnd, hasPartialLine: dropping || cursor.offset < size)- }-- private func openSource(- _ url: URL, snapshot: WorkflowFileStat?- ) throws -> TokenHistoryReadSource? {- guard let stat = WorkflowStorage.fileStat(at: url) else {- if snapshot != nil {- throw CocoaError(.fileReadNoSuchFile)- }- return nil- }- if let snapshot, snapshot.identifier != stat.identifier || stat.size < snapshot.size {- throw CodexTokenRebuildError.sourceChanged- }- guard let metadata = WorkflowRolloutMetadataReader.metadata(transcriptPath: url.path), let thread = metadata.id,- let handle = try? FileHandle(forReadingFrom: url) else {- if snapshot != nil {- throw CocoaError(.fileReadCorruptFile)- }- return nil- }- return TokenHistoryReadSource(stat: stat, thread: thread, session: metadata.sessionID ?? thread, handle: handle)- }-- private func boundaryHash(_ handle: FileHandle, at offset: UInt64) throws -> String {- let count = min(offset, 512)- try handle.seek(toOffset: offset - count)- let data = try handle.read(upToCount: Int(count)) ?? Data()- return CodexTokenTurn.hexString(SHA256.hash(data: data))- }-- private func consume(- _ line: Data, thread: String, session: String, ledger: inout TokenHistoryLedger,- baseline: CodexTokenHistoryBaseline?- ) {- guard let envelope = try? JSONDecoder().decode(TokenHistoryLine.self, from: line) else { return }- if envelope.type == "token_usage_record" {- guard let payload = try? JSONDecoder().decode(CodexRolloutTokenUsageRecord.self, from: line).payload,- payload.threadID == thread, payload.sessionID == session,- !payload.turnID.isEmpty, !payload.rootTurnID.isEmpty, !payload.responseID.isEmpty,- payload.turnTokenUsage.isValid, let timestamp = envelope.date else { return }- let id = CodexTokenTurn.identifier(thread: thread, turn: payload.turnID)- var value = CodexTokenTurn(- id: id, rootID: CodexTokenTurn.identifier(thread: session, turn: payload.rootTurnID),- startedAt: ledger.turns[id]?.startedAt, updatedAt: timestamp,- usage: payload.turnTokenUsage, rebuiltAt: ledger.turns[id]?.rebuiltAt- )- if let replacement = baseline?.replacement(for: value) {- ledger.restore(replacement)- value.rebuiltAt = replacement.rebuiltAt- }- // 恢复后重放旧文件和归档副本时, 不能恢复云端已经修正的旧累计值- guard timestamp > (ledger.recoveryCutoffs?[id] ?? .distantPast) else { return }- ledger.turns[id] = ledger.turns[id]?.merging(value) ?? value- } else if envelope.type == "event_msg", ["task_started", "turn_started"].contains(envelope.payload?.type ?? ""),- let turn = envelope.payload?.turnID, !turn.isEmpty,- let timestamp = envelope.payload?.startedAt.flatMap(TokenHistoryLine.eventDate) ?? envelope.date {- let id = CodexTokenTurn.identifier(thread: thread, turn: turn)- let value = CodexTokenTurn(- id: id, rootID: id, startedAt: timestamp, updatedAt: timestamp, usage: nil, rebuiltAt: ledger.turns[id]?.rebuiltAt- )- if let replacement = baseline?.replacement(for: value) {- ledger.restore(replacement)- } else {- ledger.turns[id] = ledger.turns[id]?.merging(value) ?? value- }- }- }-- private func fileKey(_ url: URL) -> String {- CodexTokenTurn.hexString(SHA256.hash(data: Data(url.path.utf8)))- }-}--extension CodexTokenHistoryStore {- func currentTurns() throws -> [CodexTokenTurn] {- try CodexTokenFileStorage.withLock(in: directoryURL) {- try Array(loadLedger().turns.values)- }- }-- func rebuildableDateKeys(now: Date = Date()) throws -> [String] {- try CodexTokenFileStorage.withLock(in: directoryURL) {- let ledger = try loadLedger()- let cutoff = WorkflowStorage.retentionCutoffDate(today: now)- return Set(ledger.turns.values.compactMap { turn -> String? in- guard let start = ledger.turns[turn.rootID]?.startedAt, start >= cutoff, start <= now else { return nil }- return CodexDateFormat.dayString(from: start)- }).sorted()- }- }-- /// 只在完整扫描成功后提交, 扫描期间不持有共享账本锁, 旧统计仍可读取- func rebuild(for dateKeys: [String], now: Date = Date()) async throws -> CodexTokenRebuildResult {- guard let lock = try CodexTokenFileStorage.acquireLock(in: directoryURL, name: "rebuild.lock", nonblocking: true) else {- throw CodexTokenRebuildError.alreadyRunning- }- defer { CodexTokenFileStorage.releaseLock(lock) }- let dates = Set(dateKeys.filter {- WorkflowStorage.isValidDateKey($0) && $0 >= WorkflowStorage.dateKey(for: WorkflowStorage.retentionCutoffDate(today: now))- && $0 <= WorkflowStorage.dateKey(for: now)- })- guard !dates.isEmpty else { return .empty }- let files = try rolloutFiles(since: WorkflowStorage.retentionCutoffDate(today: now)).map { url in- guard let stat = WorkflowStorage.fileStat(at: url) else { throw CocoaError(.fileReadNoSuchFile) }- return (url, stat)- }- var rebuilt = TokenHistoryLedger()- for (url, stat) in files {- var finished = false- while !finished {- try Task.checkCancellation()- var remaining = max(1, byteBudget)- finished = try scan(url, ledger: &rebuilt, remaining: &remaining, now: now, snapshot: stat) != .pending- await Task.yield()- }- }- return try commitRebuild(rebuilt, dates: dates, startedAt: now)- }-- private func loadLedger() throws -> TokenHistoryLedger {- let ledger = try CodexTokenFileStorage.load(TokenHistoryLedger.self, from: directoryURL.appendingPathComponent("ledger.json"))- ?? TokenHistoryLedger()- guard ledger.schema == TokenHistoryLedger.currentSchema else { throw CocoaError(.fileReadCorruptFile) }- return ledger- }-- private func commitRebuild(_ rebuilt: TokenHistoryLedger, dates: Set<String>, startedAt: Date) throws -> CodexTokenRebuildResult {- try CodexTokenFileStorage.withLock(in: directoryURL) {- try Task.checkCancellation()- var ledger = try loadLedger()- let requiredRoots = Set(rebuilt.turns.values.filter { $0.usage != nil }.map(\.rootID))- var rebuiltDates: Set<String> = []- var turnCount = 0- for var turn in rebuilt.turns.values {- let previous = ledger.turns[turn.id]- if turn.usage == nil, let previous {- turn.rootID = previous.rootID- }- guard let start = rebuilt.turns[turn.rootID]?.startedAt ?? ledger.turns[turn.rootID]?.startedAt,- dates.contains(CodexDateFormat.dayString(from: start)) else { continue }- turn.startedAt = turn.startedAt ?? previous?.startedAt- // 读取开始之后新产生的累计用量保留, 不用重建的文件快照覆盖活跃任务的新进展- if var previous, previous.updatedAt > startedAt {- previous.rebuiltAt = nil- turn = turn.merging(previous)- }- if turn.usage != nil || previous?.usage != nil || requiredRoots.contains(turn.id) {- turn.rebuiltAt = max(startedAt, previous?.rebuiltAt?.addingTimeInterval(0.001) ?? startedAt)- }- ledger.turns[turn.id] = turn- ledger.recoveryCutoffs?.removeValue(forKey: turn.id)- rebuiltDates.insert(CodexDateFormat.dayString(from: start))- if turn.usage != nil {- turnCount += 1- }- }- try CodexTokenFileStorage.save(ledger, to: directoryURL.appendingPathComponent("ledger.json"))- return CodexTokenRebuildResult(dateKeys: rebuiltDates, turnCount: turnCount)- }- }-}--nonisolated struct CodexTokenRebuildResult {- let dateKeys: Set<String>- let turnCount: Int- static let empty = Self(dateKeys: [], turnCount: 0)-}--private nonisolated enum CodexTokenRebuildError: LocalizedError {- case sourceChanged- case alreadyRunning-- var errorDescription: String? {- switch self {- case .sourceChanged: String(localized: "workflow.rebuild.error.source-changed")- case .alreadyRunning: String(localized: "workflow.rebuild.error.token-history-already-running")- }- }-}--private nonisolated enum TokenHistoryScanResult {- case pending- case waitingForLine- case complete- case unavailable-- init(reachedEnd: Bool, hasPartialLine: Bool) {- if !reachedEnd {- self = .pending- } else {- self = hasPartialLine ? .waitingForLine : .complete- }- }-}--/// 只记录扫描工作量, 不携带路径 轮次身份或 token 用量-nonisolated struct CodexTokenReplayProgress {- let totalFiles: Int- let batchBytes: Int- let elapsed: String- var completedFiles = 0- var unavailableFiles = 0- var waitingFiles = 0- var totalBytes: UInt64 = 0- var processedBytes: UInt64 = 0-- var isComplete: Bool {- completedFiles == totalFiles- }-- var remainingBytes: UInt64 {- totalBytes - min(processedBytes, totalBytes)- }-- func hasSamePosition(as other: Self) -> Bool {- totalFiles == other.totalFiles && completedFiles == other.completedFiles- && unavailableFiles == other.unavailableFiles && waitingFiles == other.waitingFiles- && totalBytes == other.totalBytes && processedBytes == other.processedBytes- }-- func writeLog() {- let fraction = totalBytes == 0 ? 0 : Double(processedBytes) / Double(totalBytes)- let percent = isComplete ? 100 : min(99.9, fraction * 100)- let details = LogFields.joined(- "files=\(completedFiles)/\(totalFiles)",- "progress=\(String(format: "%.1f%%", percent))",- "processed=\(Self.formattedBytes(processedBytes))/\(Self.formattedBytes(totalBytes))",- "remaining=\(Self.formattedBytes(remainingBytes))",- "read=\(Self.formattedBytes(UInt64(max(0, batchBytes))))",- "waiting=\(waitingFiles)",- "unavailable=\(unavailableFiles)",- "elapsed=\(elapsed)"- )- if isComplete {- AppLog.workflow.notice("Rollout 回放完成: \(details, privacy: .public)")- } else {- AppLog.workflow.notice("Rollout 回放进度: \(details, privacy: .public)")- }- }-- private static func formattedBytes(_ bytes: UInt64) -> String {- if bytes < 1024 {- return "\(bytes)B"- }- if bytes < 1024 * 1024 {- return String(format: "%.2fKiB", Double(bytes) / 1024)- }- return String(format: "%.2fMiB", Double(bytes) / (1024 * 1024))- }-}--private nonisolated struct TokenHistoryReadSource {- let stat: WorkflowFileStat- let thread: String- let session: String- let handle: FileHandle-}--private nonisolated struct TokenHistoryLedger: Codable {- static let currentSchema = 1- var schema = currentSchema- var turns: [String: CodexTokenTurn] = [:]- var files: [String: TokenHistoryCursor] = [:]- var recoveryCutoffs: [String: Date]?-- mutating func restore(_ turn: CodexTokenTurn) {- turns[turn.id] = turn- if recoveryCutoffs == nil {- recoveryCutoffs = [:]- }- recoveryCutoffs?[turn.id] = turn.rebuiltAt- }-}--private nonisolated struct TokenHistoryCursor: Codable {- let inode: UInt64- var offset: UInt64 = 0- var committedOffset: UInt64 = 0- var droppingLongLine = false- var lastReadAt = Date.distantPast- var boundaryHash: String?-}--private nonisolated struct TokenHistoryLine: Decodable {- let type: String- let timestamp: String?- let payload: TokenHistoryEvent?- var date: Date? {- timestamp.flatMap(CodexDateFormat.iso8601Date)- }-- static func eventDate(_ value: Double) -> Date? {- guard value.isFinite, value > 0 else { return nil }- return Date(timeIntervalSince1970: value > 100000000000 ? value / 1000 : value)- }-}--private nonisolated struct TokenHistoryEvent: Decodable {- let type: String?- let turnID: String?- let startedAt: Double?- enum CodingKeys: String, CodingKey {- case type- case turnID = "turn_id"- case startedAt = "started_at"- }-}--/// 独立文件锁避免 Debug 与 Release 互相覆盖, 不占用 Hook recorder 的锁-nonisolated enum CodexTokenFileStorage {- static func withLock<T>(in directory: URL, _ operation: () throws -> T) throws -> T {- guard let descriptor = try acquireLock(in: directory) else { throw POSIXError(.EIO) }- defer { releaseLock(descriptor) }- return try operation()- }-- static func acquireLock(in directory: URL, name: String = "store.lock", nonblocking: Bool = false) throws -> Int32? {- try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let descriptor = open(directory.appendingPathComponent(name).path, O_RDWR | O_CREAT, 0o600)- guard descriptor >= 0 else { throw POSIXError(.EIO) }- guard flock(descriptor, LOCK_EX | (nonblocking ? LOCK_NB : 0)) == 0 else {- let code = errno- close(descriptor)- if nonblocking, code == EWOULDBLOCK {- return nil- }- throw POSIXError(POSIXErrorCode(rawValue: code) ?? .EIO)- }- return descriptor- }-- static func releaseLock(_ descriptor: Int32) {- flock(descriptor, LOCK_UN)- close(descriptor)- }-- static func load<T: Decodable>(_: T.Type, from url: URL) throws -> T? {- guard FileManager.default.fileExists(atPath: url.path) else { return nil }- return try JSONDecoder().decode(T.self, from: Data(contentsOf: url))- }-- static func save(_ value: some Encodable, to url: URL) throws {- let data = try JSONLines.stableEncoder.encode(value)- guard (try? Data(contentsOf: url)) != data else { return }- try data.write(to: url, options: .atomic)- }-}--/// 调用方持有文件锁, 每次核对磁盘字节后复用解码结果, 不依赖 mtime 判断跨进程修改-nonisolated struct CodexTokenFileCache<Value: Codable & Equatable> {- let url: URL- private var data: Data?- private var value: Value?-- init(url: URL) {- self.url = url- }-- mutating func load() throws -> Value? {- guard FileManager.default.fileExists(atPath: url.path) else {- data = nil- value = nil- return nil- }- let current = try Data(contentsOf: url)- if current == data {- return value- }- let decoded = try JSONDecoder().decode(Value.self, from: current)- data = current- value = decoded- return decoded- }-- mutating func save(_ updated: Value) throws {- let current = try? Data(contentsOf: url)- if let current, current == data, updated == value {- return- }- let encoded = try JSONLines.stableEncoder.encode(updated)- if current != encoded {- try encoded.write(to: url, options: .atomic)- }- data = encoded- value = updated- }-}diff --git a/CodexBar/Services/Workflow/CodexTokenHistorySync.swift b/CodexBar/Services/Workflow/CodexTokenHistorySync.swiftdeleted file mode 100644index 2c12fb0..0000000--- a/CodexBar/Services/Workflow/CodexTokenHistorySync.swift+++ /dev/null@@ -1,229 +0,0 @@-import CloudKit-import Foundation--/// 每个线程轮次一个云端累计记录, 多设备通过条件写入收敛到同一份用量-actor CodexTokenHistorySync {- private let database: CKDatabase- private let directoryURL: URL- private var fileCache: CodexTokenFileCache<TokenSyncCache>- static let recordType = "CodexBarTokenTurn"- private static let currentSchema = 1-- init(database: CKDatabase, directoryURL: URL) {- self.database = database- self.directoryURL = directoryURL- fileCache = CodexTokenFileCache(url: directoryURL.appendingPathComponent("cache.json"))- }-- func recoveryBaseline(accountScopedDeviceID: String?) -> CodexTokenHistoryBaseline? {- guard let accountScopedDeviceID, let cache = try? load(), cache.accountScopedDeviceID == accountScopedDeviceID else { return nil }- return CodexTokenHistoryBaseline(salt: cache.salt, turns: cache.turns)- }-- func snapshot(local: [CodexTokenTurn], accountScopedDeviceID: String?) -> [String: CodexTokenUsage] {- guard let cache = try? load(), cache.accountScopedDeviceID == accountScopedDeviceID else {- return CodexTokenTurn.dailyUsage(local)- }- return CodexTokenTurn.dailyUsage(CodexTokenTurn.pseudonymized(local, salt: cache.salt) + Array(cache.turns.values))- }-- func hasPendingUpdates(local: [CodexTokenTurn], accountScopedDeviceID: String?) -> Bool {- let records = CodexTokenTurn.syncable(local)- guard let cache = try? load(), cache.accountScopedDeviceID == accountScopedDeviceID else { return !records.isEmpty }- return records.contains { turn in- let candidate = turn.pseudonymized(salt: cache.salt)- guard let remote = cache.turns[candidate.id] else { return true }- return remote.merging(candidate) != remote- }- }-- func synchronize(local: [CodexTokenTurn], accountScopedDeviceID: String, salt: Data, zoneID: CKRecordZone.ID) async throws {- // 整轮同步共用非阻塞锁, 防止另一个进程用较早的快照覆盖游标, 界面读取不等待网络- guard let lock = try CodexTokenFileStorage.acquireLock(in: directoryURL, name: "sync.lock", nonblocking: true) else { return }- defer { CodexTokenFileStorage.releaseLock(lock) }- var cache = try load() ?? TokenSyncCache(accountScopedDeviceID: accountScopedDeviceID, salt: salt)- if cache.accountScopedDeviceID != accountScopedDeviceID || cache.salt != salt {- cache = TokenSyncCache(accountScopedDeviceID: accountScopedDeviceID, salt: salt)- }- do {- try await fetch(into: &cache, zoneID: zoneID)- } catch let error as CKError where error.code == .changeTokenExpired {- cache.cursor = nil- cache.turns = [:]- try await fetch(into: &cache, zoneID: zoneID)- }- // 先落盘拉取结果, 上传失败时也能展示已经读取的其他设备贡献- try save(cache)- try await upload(local: local, cache: &cache, zoneID: zoneID)- try await prune(cache: &cache, zoneID: zoneID)- try save(cache)- }-- private func fetch(into cache: inout TokenSyncCache, zoneID: CKRecordZone.ID) async throws {- var token = try cache.cursor.flatMap {- try NSKeyedUnarchiver.unarchivedObject(ofClass: CKServerChangeToken.self, from: $0)- }- var more = true- while more {- try Task.checkCancellation()- let result = try await database.recordZoneChanges(inZoneWith: zoneID, since: token, desiredKeys: nil, resultsLimit: 200)- for modification in result.modificationResultsByID.values {- if let turn = try Self.turn(from: modification.get().record) {- cache.turns[turn.id] = turn- }- }- for deletion in result.deletions where deletion.recordType == Self.recordType {- cache.turns.removeValue(forKey: deletion.recordID.recordName)- }- token = result.changeToken- more = result.moreComing- }- cache.cursor = try token.map { try NSKeyedArchiver.archivedData(withRootObject: $0, requiringSecureCoding: true) }- }-- private func upload(local: [CodexTokenTurn], cache: inout TokenSyncCache, zoneID: CKRecordZone.ID) async throws {- let pending = CodexTokenTurn.pseudonymized(CodexTokenTurn.syncable(local), salt: cache.salt)- .filter { candidate in- guard let remote = cache.turns[candidate.id] else { return true }- return remote.merging(candidate) != remote- }- .sorted { $0.updatedAt > $1.updatedAt }- let deadline = Date().addingTimeInterval(20)- for offset in stride(from: 0, to: pending.count, by: 25) {- try Task.checkCancellation()- guard Date() < deadline else { break }- let batch = Array(pending[offset ..< min(offset + 25, pending.count)])- let ids = batch.map { Self.recordID($0.id, zoneID: zoneID) }- let existing = try await database.records(for: ids)- var saving: [CKRecord] = []- for candidate in batch {- let id = Self.recordID(candidate.id, zoneID: zoneID)- let record = try fetchedRecord(existing[id])- ?? CKRecord(recordType: Self.recordType, recordID: id)- let remote = Self.turn(from: record)- let merged = remote?.merging(candidate) ?? candidate- if remote == merged {- cache.turns[merged.id] = merged- continue- }- Self.apply(merged, to: record)- saving.append(record)- }- if saving.isEmpty {- continue- }- let result = try await database.modifyRecords(saving: saving, deleting: [], savePolicy: .ifServerRecordUnchanged, atomically: false)- var failure: (any Error)?- for record in saving {- switch result.saveResults[record.recordID] {- case let .success(saved):- if let turn = Self.turn(from: saved) {- cache.turns[turn.id] = turn- }- case let .failure(error): failure = error- case nil: failure = TokenHistorySyncError.missingRecordResult- }- }- try save(cache)- // 冲突不会使用覆盖写入, 下一轮重新获取服务端累计值后合并- if let failure {- throw failure- }- }- }-- private func fetchedRecord(_ result: Result<CKRecord, any Error>?) throws -> CKRecord? {- switch result {- case let .success(record): record- case let .failure(error as CKError) where error.code == .unknownItem: nil- case let .failure(error): throw error- case nil: throw TokenHistorySyncError.missingRecordResult- }- }-- private func prune(cache: inout TokenSyncCache, zoneID: CKRecordZone.ID) async throws {- let cutoff = WorkflowStorage.retentionCutoffDate()- let requiredRoots = Set(cache.turns.values.filter { $0.updatedAt >= cutoff }.map(\.rootID))- let expired = cache.turns.values.filter {- $0.updatedAt < cutoff && !requiredRoots.contains($0.id)- }.prefix(200)- let ids = expired.map { Self.recordID($0.id, zoneID: zoneID) }- guard !ids.isEmpty else { return }- let result = try await database.modifyRecords(saving: [], deleting: ids, atomically: false)- for id in ids {- guard let deletion = result.deleteResults[id] else { throw TokenHistorySyncError.missingRecordResult }- do { try deletion.get() } catch let error as CKError where error.code == .unknownItem {}- cache.turns.removeValue(forKey: id.recordName)- }- }-- private func load() throws -> TokenSyncCache? {- try CodexTokenFileStorage.withLock(in: directoryURL) {- let cache = try fileCache.load()- guard cache == nil || cache?.schema == TokenSyncCache.currentSchema else { throw CocoaError(.fileReadCorruptFile) }- return cache- }- }-- private func save(_ cache: TokenSyncCache) throws {- try CodexTokenFileStorage.withLock(in: directoryURL) {- try fileCache.save(cache)- }- }-- static func recordID(_ id: String, zoneID: CKRecordZone.ID) -> CKRecord.ID {- CKRecord.ID(recordName: id, zoneID: zoneID)- }-- static func apply(_ turn: CodexTokenTurn, to record: CKRecord) {- record["schemaVersion"] = currentSchema as CKRecordValue- record["rootID"] = turn.rootID as CKRecordValue- record["startedAt"] = turn.startedAt as CKRecordValue?- record["observedAt"] = turn.updatedAt as CKRecordValue- record["rebuiltAt"] = turn.rebuiltAt as CKRecordValue?- record["usage"] = turn.usage.flatMap { try? JSONLines.stableEncoder.encode($0) } as CKRecordValue?- }-- static func turn(from record: CKRecord) -> CodexTokenTurn? {- guard record.recordType == recordType, (record["schemaVersion"] as? NSNumber)?.intValue == currentSchema,- let rootID = record["rootID"] as? String,- let updatedAt = record["observedAt"] as? Date else { return nil }- let id = record.recordID.recordName- guard isHash(id), isHash(rootID) else { return nil }- var usage: CodexTokenUsage?- if let value = record["usage"] {- guard let data = value as? Data, let decoded = try? JSONDecoder().decode(CodexTokenUsage.self, from: data), decoded.isValid else { return nil }- usage = decoded- }- if let rebuiltAt = record["rebuiltAt"], !(rebuiltAt is Date) {- return nil- }- return CodexTokenTurn(- id: id, rootID: rootID, startedAt: record["startedAt"] as? Date, updatedAt: updatedAt,- usage: usage, rebuiltAt: record["rebuiltAt"] as? Date- )- }-- private static func isHash(_ text: String) -> Bool {- text.count == 64 && text.utf8.allSatisfy { (48 ... 57).contains($0) || (97 ... 102).contains($0) }- }-}--private nonisolated struct TokenSyncCache: Codable, Equatable {- static let currentSchema = 1- var schema = currentSchema- let accountScopedDeviceID: String- let salt: Data- var turns: [String: CodexTokenTurn] = [:]- var cursor: Data?-- private enum CodingKeys: String, CodingKey {- case schema- case accountScopedDeviceID = "accountID"- case salt, turns, cursor- }-}--private nonisolated enum TokenHistorySyncError: Error {- case missingRecordResult-}diff --git a/CodexBar/Services/Workflow/HookEventTailReader.swift b/CodexBar/Services/Workflow/HookEventTailReader.swiftdeleted file mode 100644index 39a76fa..0000000--- a/CodexBar/Services/Workflow/HookEventTailReader.swift+++ /dev/null@@ -1,533 +0,0 @@-import Darwin-import Foundation--nonisolated enum HookEventBatch {- case bootstrapStart- case bootstrapEvents([WorkflowHookEvent])- /// degraded 表示历史覆盖不完整, 不得据此判断任务静默- case bootstrapEnd(degraded: Bool, attempts: Int)- case live([WorkflowHookEvent])- case sourceHealthChanged(Bool)-}--nonisolated enum HookEventDrainResult: Sendable {- case completed- case sourceUnavailable- case cancelled-}--/// 在独立 actor 中按完整 JSONL 行读取 HookEvents/events-/// bootstrap 覆盖滚动 24 小时并作为单次事务发送, live 随后按窗口内各日期文件 offset 增量读取-actor HookEventTailReader {- private let onBatch: @MainActor @Sendable (HookEventBatch) -> Void- private var pollTask: Task<Void, Never>?- private var readProcessingTask: Task<Void, Never>?- private var isRunning = false- // actor 会在 await 期间重入; 所有外部读取请求通过这两个标记合并为单一读取流程- private var isProcessingReads = false- private var hasPendingDrain = false- private var fileCursors: [String: HookFileCursor] = [:]- private let eventsDirectoryURL: URL- private let now: @Sendable () -> Date- private var bootstrapRetryAt: Date?- private var lastReportedSourceHealth: Bool?- private var requestedDrainGeneration: UInt64 = 0- private var drainWaiters: [UInt64: CheckedContinuation<HookEventDrainResult, Never>] = [:]-- init(- eventsDirectoryURL: URL = WorkflowStorage.eventsDirectoryURL(),- now: @escaping @Sendable () -> Date = Date.init,- onBatch: @escaping @MainActor @Sendable (HookEventBatch) -> Void- ) {- self.eventsDirectoryURL = eventsDirectoryURL- self.now = now- self.onBatch = onBatch- }-- func start() async {- guard !isRunning, !isProcessingReads else {- return- }- isRunning = true- isProcessingReads = true- defer {- isProcessingReads = false- }-- await bootstrapRecentActivity()- await drainPendingRequests()- guard isRunning, !Task.isCancelled else {- return- }-- pollTask = Task { [weak self] in- while !Task.isCancelled {- try? await Task.sleep(for: .seconds(Self.pollInterval))- guard !Task.isCancelled else {- return- }- _ = await self?.drainNow()- }- }- }-- func stop() {- isRunning = false- hasPendingDrain = false- pollTask?.cancel()- pollTask = nil- readProcessingTask?.cancel()- readProcessingTask = nil- completeAllDrainWaiters(with: .cancelled)- }-- /// 每个调用方等待一轮在本次请求之后开始的读取, 已经在途的旧读取不能提前满足该请求- func drainNow() async -> HookEventDrainResult {- guard isRunning, !Task.isCancelled else {- return .cancelled- }-- requestedDrainGeneration &+= 1- let generation = requestedDrainGeneration- hasPendingDrain = true-- return await withTaskCancellationHandler {- await withCheckedContinuation { continuation in- drainWaiters[generation] = continuation- startPendingReadIfNeeded()- }- } onCancel: {- Task {- await self.cancelDrainWaiter(generation)- }- }- }-- private func startPendingReadIfNeeded() {- guard isRunning, !isProcessingReads else {- return- }- isProcessingReads = true- readProcessingTask = Task { [weak self] in- await self?.processPendingReads()- }- }-- private func processPendingReads() async {- await drainPendingRequests()- isProcessingReads = false- readProcessingTask = nil-- // 最后一轮完成后没有 await 空窗, 正常不会遗漏请求; 这里仍保留自愈以约束未来改动- if isRunning, hasPendingDrain {- startPendingReadIfNeeded()- }- }-- private func drainPendingRequests() async {- while isRunning, hasPendingDrain, !Task.isCancelled {- hasPendingDrain = false- let generation = requestedDrainGeneration- let result = await drainNewLines()- completeDrainWaiters(through: generation, with: result)- }-- if !isRunning || Task.isCancelled {- completeAllDrainWaiters(with: .cancelled)- }- }-- private func completeDrainWaiters(- through generation: UInt64,- with result: HookEventDrainResult- ) {- let completedGenerations = drainWaiters.keys.filter { $0 <= generation }- for completedGeneration in completedGenerations {- drainWaiters.removeValue(forKey: completedGeneration)?.resume(returning: result)- }- }-- private func completeAllDrainWaiters(with result: HookEventDrainResult) {- let waiters = Array(drainWaiters.values)- drainWaiters.removeAll()- for waiter in waiters {- waiter.resume(returning: result)- }- }-- private func cancelDrainWaiter(_ generation: UInt64) {- drainWaiters.removeValue(forKey: generation)?.resume(returning: .cancelled)- }-- private func eventLogURL(for dateKey: String) -> URL {- WorkflowStorage.eventLogURL(for: dateKey, in: eventsDirectoryURL)- }-- // MARK: - bootstrap-- private func bootstrapRecentActivity() async {- for attempt in 0 ..< Self.bootstrapAttemptLimit {- guard isRunning, !Task.isCancelled else {- return- }- if let result = await bootstrapAttempt(now: now()) {- bootstrapRetryAt = nil- fileCursors = result.cursors- let healthy = result.cursors.values.allSatisfy { !$0.isDegraded }- await onBatch(.bootstrapEnd(degraded: !healthy, attempts: attempt + 1))- await reportSourceHealth(healthy)- return- }- }-- // 连续读取失败时清空恢复态并跳过当前已有字节, 避免稍后误当 live 发送历史通知- // 代价是丢掉最多 24 小时的任务状态, 所以要让下游知道这一轮是降级而不是真的没有历史- let current = now()- bootstrapRetryAt = current.addingTimeInterval(Self.bootstrapRetryInterval)- fileCursors = Dictionary(uniqueKeysWithValues: Self.dateKeys(- from: current.addingTimeInterval(-Self.activityRetention), through: current- ).map { dateKey in- let stat = WorkflowStorage.fileStat(at: eventLogURL(for: dateKey))- return (dateKey, HookFileCursor(offset: stat?.size ?? 0, identifier: stat?.identifier, isDegraded: true))- })- await onBatch(.bootstrapStart)- await onBatch(.bootstrapEnd(degraded: true, attempts: Self.bootstrapAttemptLimit))- await reportSourceHealth(false)- }-- private func bootstrapAttempt(now: Date) async -> BootstrapResult? {- guard (try? FileManager.default.contentsOfDirectory(atPath: eventsDirectoryURL.path)) != nil else { return nil }- let cutoff = now.addingTimeInterval(-Self.activityRetention)- let dateKeys = Self.dateKeys(from: cutoff, through: now)- let bootstrapDateKey = WorkflowStorage.dateKey(for: now)- guard let boundaries = try? dateKeys.map({ dateKey in- let url = eventLogURL(for: dateKey)- let stat = try readableStat(at: url)- return HookFileBoundary(- dateKey: dateKey,- url: url,- size: stat?.size ?? 0,- fileIdentifier: stat?.identifier- )- }) else { return nil }-- await onBatch(.bootstrapStart)-- var cursors: [String: HookFileCursor] = [:]- for boundary in boundaries {- guard isRunning, !Task.isCancelled else {- return nil- }-- let streamResult = await streamEvents(- at: boundary.url,- from: 0,- through: boundary.size,- cutoff: cutoff,- makeBatch: HookEventBatch.bootstrapEvents- )- guard streamResult.didReachUpperBound else {- return nil- }- cursors[boundary.dateKey] = HookFileCursor(- offset: streamResult.completeOffset,- identifier: boundary.fileIdentifier,- isDegraded: streamResult.hasDecodeFailures- )- }-- guard boundariesAreStable(boundaries, activeDateKey: bootstrapDateKey),- WorkflowStorage.dateKey(for: self.now()) == bootstrapDateKey else {- return nil- }-- return BootstrapResult(cursors: cursors)- }-- // MARK: - 增量 tail-- private func drainNewLines() async -> HookEventDrainResult {- guard isRunning, !Task.isCancelled else {- return .cancelled- }-- guard (try? FileManager.default.contentsOfDirectory(atPath: eventsDirectoryURL.path)) != nil else {- await reportSourceHealth(false)- return .sourceUnavailable- }- let current = now()- if let bootstrapRetryAt {- guard current >= bootstrapRetryAt else { return .sourceUnavailable }- await bootstrapRecentActivity()- guard isRunning, !Task.isCancelled else { return .cancelled }- return lastReportedSourceHealth == true ? .completed : .sourceUnavailable- }- let dates = Self.dateKeys(from: current.addingTimeInterval(-Self.activityRetention), through: current)- fileCursors = fileCursors.filter { dates.contains($0.key) }- var healthy = true- for dateKey in dates {- let url = eventLogURL(for: dateKey)- let stat: WorkflowFileStat?- do {- stat = try readableStat(at: url)- } catch {- await reportSourceHealth(false)- return .sourceUnavailable- }- var cursor = fileCursors[dateKey] ?? HookFileCursor()- if (cursor.identifier != nil && stat?.identifier != cursor.identifier)- || (stat?.size ?? 0) < cursor.offset {- await bootstrapRecentActivity()- return lastReportedSourceHealth == true ? .completed : .sourceUnavailable- }- let size = stat?.size ?? 0- let result = await streamEvents(- at: url, from: cursor.offset, through: size,- cutoff: current.addingTimeInterval(-Self.activityRetention), makeBatch: HookEventBatch.live- )- guard isRunning, !Task.isCancelled else { return .cancelled }- cursor.offset = result.completeOffset- cursor.identifier = stat?.identifier- cursor.isDegraded = cursor.isDegraded || result.hasDecodeFailures- fileCursors[dateKey] = cursor- healthy = healthy && result.didReachUpperBound && !cursor.isDegraded- }- await reportSourceHealth(healthy)- return healthy ? .completed : .sourceUnavailable- }-- private func readableStat(at url: URL) throws -> WorkflowFileStat? {- guard let stat = WorkflowStorage.fileStat(at: url) else {- let code = errno- if code == ENOENT {- return nil- }- throw POSIXError(POSIXErrorCode(rawValue: code) ?? .EIO)- }- let handle = try FileHandle(forReadingFrom: url)- try handle.close()- return stat- }-- private func reportSourceHealth(_ isHealthy: Bool) async {- guard isHealthy != lastReportedSourceHealth else {- return- }- lastReportedSourceHealth = isHealthy- await onBatch(.sourceHealthChanged(isHealthy))- }-- /// 返回已处理完整行的绝对 offset 和是否读完固定上界; 后续失败时保留此前进度- private func streamEvents(- at url: URL,- from startOffset: UInt64,- through upperBound: UInt64,- cutoff: Date?,- makeBatch: ([WorkflowHookEvent]) -> HookEventBatch- ) async -> HookEventStreamResult {- guard upperBound > startOffset else {- return .completed(at: startOffset)- }- guard let handle = try? FileHandle(forReadingFrom: url) else {- return .interrupted(at: startOffset)- }- defer {- try? handle.close()- }-- guard (try? handle.seek(toOffset: startOffset)) != nil else {- return .interrupted(at: startOffset)- }-- var readOffset = startOffset- var completeOffset = startOffset- var pending = Data()- var hasDecodeFailures = false-- while readOffset < upperBound {- guard isRunning, !Task.isCancelled else {- return HookEventStreamResult(completeOffset: completeOffset, didReachUpperBound: false, hasDecodeFailures: hasDecodeFailures)- }-- let requestedCount = Int(min(- UInt64(Self.readChunkByteCount),- upperBound - readOffset- ))- guard let chunk = try? handle.read(upToCount: requestedCount),- !chunk.isEmpty else {- return HookEventStreamResult(completeOffset: completeOffset, didReachUpperBound: false, hasDecodeFailures: hasDecodeFailures)- }-- readOffset += UInt64(chunk.count)- pending.append(chunk)-- guard let lastNewlineIndex = pending.lastIndex(of: JSONLines.newlineByte) else {- await Task.yield()- continue- }-- let remainderStart = pending.index(after: lastNewlineIndex)- let completeData = Data(pending[...lastNewlineIndex])- pending = remainderStart < pending.endIndex- ? Data(pending[remainderStart...])- : Data()- completeOffset = readOffset - UInt64(pending.count)-- let decoded = JSONLines.decodeWithFailures(WorkflowHookEvent.self, from: completeData)- if decoded.failedLineCount > 0 {- hasDecodeFailures = true- await reportSourceHealth(false)- }- var events = decoded.values- if let cutoff {- events.removeAll { $0.timestamp < cutoff }- }- if !events.isEmpty {- await onBatch(makeBatch(events))- }- await Task.yield()- }-- return HookEventStreamResult(- completeOffset: completeOffset,- didReachUpperBound: completeOffset == upperBound,- hasDecodeFailures: hasDecodeFailures- )- }-- /// 从 24 小时窗口之前的事件文件中定向查找 Prompt 起点, 供 bootstrap 后回填恢复任务的开始时间- func findPromptStartTimes(- for references: [CodexActivityPromptReference]- ) -> [CodexActivityPromptReference: Date] {- let cutoff = now().addingTimeInterval(-Self.activityRetention)- var unresolvedKeys = Set(references)- var startTimes: [CodexActivityPromptReference: Date] = [:]- var remainingBytes = Self.promptSearchByteLimit-- for url in eventLogURLs(onOrBefore: cutoff) {- guard !unresolvedKeys.isEmpty, remainingBytes > 0 else {- break- }-- let size = WorkflowStorage.fileSize(at: url)- let readCount = min(size, remainingBytes)- guard readCount > 0,- let handle = try? FileHandle(forReadingFrom: url) else {- continue- }- defer {- try? handle.close()- }-- let readOffset = size - readCount- guard (try? handle.seek(toOffset: readOffset)) != nil,- let data = try? handle.read(upToCount: Int(readCount)),- !data.isEmpty else {- remainingBytes -= readCount- continue- }- remainingBytes -= UInt64(data.count)-- let completeData = readOffset > 0 ? JSONLines.droppingLeadingPartialLine(data) : data-- for event in JSONLines.decode(WorkflowHookEvent.self, from: completeData)- where event.hookEvent == .userPromptSubmit && event.timestamp < cutoff {- guard let sessionID = event.sessionID, let turnID = event.turnID else {- continue- }- let key = CodexActivityPromptReference(sessionID: sessionID, turnID: turnID)- guard unresolvedKeys.remove(key) != nil else {- continue- }- startTimes[key] = event.timestamp- }- }-- return startTimes- }-- private func eventLogURLs(onOrBefore cutoff: Date) -> [URL] {- let cutoffDateKey = WorkflowStorage.dateKey(for: cutoff)- return WorkflowStorage.eventLogDateKeys(in: eventsDirectoryURL)- .filter { $0 <= cutoffDateKey }- .sorted(by: >)- .map { eventLogURL(for: $0) }- }-- private func boundariesAreStable(- _ boundaries: [HookFileBoundary],- activeDateKey: String- ) -> Bool {- for boundary in boundaries {- let stat = WorkflowStorage.fileStat(at: boundary.url)- guard stat?.identifier == boundary.fileIdentifier else {- return false- }- let currentSize = stat?.size ?? 0- if boundary.dateKey == activeDateKey {- guard currentSize >= boundary.size else {- return false- }- } else if currentSize != boundary.size {- return false- }- }- return true- }-- private static func dateKeys(from start: Date, through end: Date) -> [String] {- // 产出的日期键要和 WorkflowStorage.dateKey 对齐, 必须固定公历- let calendar = CodexDateFormat.localGregorianCalendar- var date = calendar.startOfDay(for: start)- let endDate = calendar.startOfDay(for: end)- var keys: [String] = []-- while date <= endDate {- keys.append(WorkflowStorage.dateKey(for: date))- guard let nextDate = calendar.date(byAdding: .day, value: 1, to: date),- nextDate > date else {- break- }- date = nextDate- }- return keys- }-- private static let pollInterval: TimeInterval = 2- private static let activityRetention = CodexActivityRetention.window- private static let readChunkByteCount = 512 * 1024- private static let promptSearchByteLimit: UInt64 = 8 * 1024 * 1024- private static let bootstrapAttemptLimit = 3- private static let bootstrapRetryInterval: TimeInterval = 10-}--private nonisolated struct HookFileBoundary {- let dateKey: String- let url: URL- let size: UInt64- let fileIdentifier: UInt64?-}--private nonisolated struct HookFileCursor {- var offset: UInt64 = 0- var identifier: UInt64?- var isDegraded = false-}--private nonisolated struct BootstrapResult {- let cursors: [String: HookFileCursor]-}--private nonisolated struct HookEventStreamResult {- let completeOffset: UInt64- let didReachUpperBound: Bool- var hasDecodeFailures = false-- static func completed(at offset: UInt64) -> Self {- Self(completeOffset: offset, didReachUpperBound: true)- }-- static func interrupted(at offset: UInt64) -> Self {- Self(completeOffset: offset, didReachUpperBound: false)- }-}diff --git a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swiftdeleted file mode 100644index 90c324b..0000000--- a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift+++ /dev/null@@ -1,499 +0,0 @@-import Darwin-import Foundation--/// Hook 子进程入口: 读取 stdin payload, 写入本地 JSONL, 然后立即退出-nonisolated enum WorkflowHookEventRecorder {- static let hookArgument = "--hook-event"-- /// SessionEnd 和 Interrupt 在 Codex 中最多允许 3 秒, 其他事件沿用 5 秒- /// 超时定义在这里而不是 AdvancedModeSettings: 写配置与下面的等锁预算必须同源- private static let defaultHookTimeoutSeconds = 5- private static let terminalHookTimeoutSeconds = 3-- static func hookTimeoutSeconds(for event: CodexHookEvent) -> Int {- switch event {- case .sessionEnd, .interrupt: terminalHookTimeoutSeconds- default: defaultHookTimeoutSeconds- }- }-- static func handleIfRequested() -> Bool {- guard CommandLine.arguments.contains(hookArgument) else {- return false- }-- let payload = stdinPayload()-- guard let eventName = payload.string(for: "hook_event_name") else {- // 显式 Hook 模式下吞掉无效输入- // 避免 Hook 子进程继续启动完整菜单栏 App-- return true- }-- try? record(payload: payload, eventName: eventName)- return true- }-- private static func record(payload: WorkflowHookPayload, eventName: String) throws {- let hookEvent = CodexHookEvent(eventName: eventName)- let timestamp = payload.date(for: "timestamp") ?? Date()- let cwd = payload.string(for: "cwd") ?? FileManager.default.currentDirectoryPath- let tool = payload.string(for: "tool_name")- let model = payload.string(for: "model")- let permission = payload.string(for: "permission_mode")- let sessionID = payload.string(for: "session_id")- let turnID = payload.string(for: "turn_id")- let agentID = payload.string(for: "agent_id")- let transcriptPath = payload.string(for: "transcript_path")- let sourcePath = hookEvent == .subagentStop- ? payload.string(for: "agent_transcript_path") : transcriptPath- let origin = WorkflowRolloutMetadataReader.origin(transcriptPath: sourcePath)- let turnContext = readTurnContext(- transcriptPath: transcriptPath,- hookEvent: hookEvent,- turnID: turnID- )- let event = WorkflowHookEvent(- timestamp: timestamp,- name: eventName,- origin: origin,- directoryPath: cwd,- toolName: tool,- modelName: model,- effort: turnContext?.effort,- permissionMode: permission,- approvalReviewer: turnContext?.approvalReviewer,- sessionID: sessionID,- turnID: turnID,- agentID: agentID- )-- try recordWorkflowTransaction(- event: event,- lockWaitLimitSeconds: lockWaitLimitSeconds(for: hookEvent)- )- }-- private static func readTurnContext(- transcriptPath: String?,- hookEvent: CodexHookEvent?,- turnID: String?- ) -> WorkflowTurnContext? {- guard let hookEvent,- hookEvent == .userPromptSubmit || hookEvent == .permissionRequest,- let turnID,- let transcriptPath else {- return nil- }- return WorkflowTurnContextReader.context(- transcriptPath: transcriptPath,- turnID: turnID- )- }-- /// 为事件写入预留时间, 避免等待锁耗尽超时预算后被 Codex 中途终止- private static func lockWaitLimitSeconds(for event: CodexHookEvent?) -> TimeInterval {- let timeout = event.map(hookTimeoutSeconds(for:)) ?? defaultHookTimeoutSeconds- return max(0, Double(timeout) - 2)- }-- private static func recordWorkflowTransaction(- event: WorkflowHookEvent,- lockWaitLimitSeconds: TimeInterval- ) throws {- try WorkflowStorage.withExclusiveLock(waitLimitSeconds: lockWaitLimitSeconds) {- let dateKey = WorkflowStorage.dateKey(for: event.timestamp)- let eventLogURL = WorkflowStorage.eventLogURL(for: dateKey)- var maintenanceState = WorkflowStorage.loadMaintenanceState()- let existingStat = WorkflowStorage.fileStat(at: eventLogURL)- var stateChanged = false-- if let existingStat {- let day = maintenanceState.days[dateKey]- let identifierChanged = day?.fileIdentifier != nil- && day?.fileIdentifier != existingStat.identifier- let fileShrank = day.map { existingStat.size < $0.offset } ?? false-- if identifierChanged || fileShrank {- maintenanceState.startNewSourceGeneration(- for: dateKey,- isFresh: existingStat.size == 0,- fileIdentifier: existingStat.identifier- )- stateChanged = true- } else {- stateChanged = maintenanceState.ensureSourceGeneration(- for: dateKey,- fileIdentifier: existingStat.identifier- )- }- } else {- maintenanceState.startNewSourceGeneration(- for: dateKey,- isFresh: true,- fileIdentifier: nil- )- stateChanged = true- }-- try append(event.jsonLineData(), to: eventLogURL)-- if var day = maintenanceState.days[dateKey],- day.fileIdentifier == nil,- let identifier = WorkflowStorage.fileStat(at: eventLogURL)?.identifier {- day.fileIdentifier = identifier- maintenanceState.days[dateKey] = day- stateChanged = true- }-- // 稳态下当天早已 pending, 跳过无变化的全量重写以缩短持锁时间- if maintenanceState.markPending(dateKey) || stateChanged {- try WorkflowStorage.saveMaintenanceState(maintenanceState)- }- }- }-- private static func append(_ data: Data, to url: URL) throws {- try FileManager.default.createDirectory(- at: url.deletingLastPathComponent(),- withIntermediateDirectories: true- )-- if !FileManager.default.fileExists(atPath: url.path) {- FileManager.default.createFile(atPath: url.path, contents: nil)- }-- let fileHandle = try FileHandle(forWritingTo: url)- defer {- try? fileHandle.close()- }-- try fileHandle.seekToEnd()- try fileHandle.write(contentsOf: data)- }-- private static func stdinPayload() -> WorkflowHookPayload {- guard isatty(STDIN_FILENO) == 0 else {- return WorkflowHookPayload(values: [:])- }-- let data = FileHandle.standardInput.readDataToEndOfFile()- guard !data.isEmpty else {- return WorkflowHookPayload(values: [:])- }-- guard let object = try? JSONSerialization.jsonObject(with: data),- let values = object as? [String: Any] else {- return WorkflowHookPayload(values: [:])- }-- return WorkflowHookPayload(values: values)- }-}--/// Codex 把来源写在大型指令字段之前, 在固定预算内读取已完成的元数据字段-nonisolated enum WorkflowRolloutMetadataReader {- static func origin(transcriptPath: String?) -> WorkflowEventOrigin {- metadata(transcriptPath: transcriptPath)?.source?.origin ?? .unknown- }-- static func metadata(transcriptPath: String?) -> WorkflowRolloutMetadataPayload? {- guard let transcriptPath else {- return nil- }-- let url = URL(fileURLWithPath: transcriptPath)- guard let handle = try? FileHandle(forReadingFrom: url) else {- return nil- }- defer {- try? handle.close()- }-- var data = Data()- while data.count < firstLineByteLimit {- let readCount = min(readChunkByteCount, firstLineByteLimit - data.count)- guard let chunk = try? handle.read(upToCount: readCount),- !chunk.isEmpty else {- return nil- }- data.append(chunk)-- if let newlineIndex = data.firstIndex(of: JSONLines.newlineByte) {- return decodedMetadata(from: Data(data[..<newlineIndex]))- }-- if let prefix = metadataPrefix(from: data),- let metadata = decodedMetadata(from: prefix), metadata.source != nil {- return metadata- }- }- return nil- }-- private static func decodedMetadata(from data: Data) -> WorkflowRolloutMetadataPayload? {- guard let envelope = try? JSONDecoder().decode(WorkflowRolloutMetadataEnvelope.self, from: data),- envelope.type == "session_meta" else {- return nil- }- return envelope.payload- }-- /// 只在外层或 payload 的完整字段边界补齐对象, 字符串和嵌套值交给 JSONDecoder 验证- private static func metadataPrefix(from data: Data) -> Data? {- var containers: [UInt8] = []- var isInString = false- var isEscaped = false- var prefixEnd: Int?- var closingBraces = 0-- for (index, byte) in data.enumerated() {- if isInString {- if isEscaped {- isEscaped = false- } else if byte == 0x5C {- isEscaped = true- } else if byte == 0x22 {- isInString = false- }- continue- }-- switch byte {- case 0x22:- isInString = true- case 0x7B, 0x5B:- guard containers.count < 64 else { return nil }- containers.append(byte)- case 0x7D, 0x5D:- let opening: UInt8 = byte == 0x7D ? 0x7B : 0x5B- guard containers.popLast() == opening else { return nil }- if containers.isEmpty {- return data- }- if containers == [0x7B] {- prefixEnd = index + 1- closingBraces = 1- }- case 0x2C:- if containers == [0x7B] || containers == [0x7B, 0x7B] {- prefixEnd = index- closingBraces = containers.count- }- default:- break- }- }-- guard let prefixEnd else { return nil }- return Data(data.prefix(prefixEnd)) + Data(repeating: 0x7D, count: closingBraces)- }-- private static let readChunkByteCount = 32 * 1024- private static let firstLineByteLimit = 256 * 1024-}--private nonisolated struct WorkflowRolloutMetadataEnvelope: Decodable {- let type: String- let payload: WorkflowRolloutMetadataPayload?-}--nonisolated struct WorkflowRolloutMetadataPayload: Decodable {- let id: String?- let sessionID: String?- private let explicitParentThreadID: String?- var parentThreadID: String? {- explicitParentThreadID ?? source?.parentThreadID- }-- let source: WorkflowRolloutSource?-- private enum CodingKeys: String, CodingKey {- case id, source- case sessionID = "session_id"- case explicitParentThreadID = "parent_thread_id"- }-}--nonisolated struct WorkflowRolloutSource: Decodable {- let origin: WorkflowEventOrigin- var parentThreadID: String?-- init(from decoder: Decoder) throws {- if let name = try? decoder.singleValueContainer().decode(String.self) {- origin = Self.knownMainSourceNames.contains(name) ? .main : .unknown- return- }-- guard let container = try? decoder.container(keyedBy: WorkflowRolloutSourceKey.self) else {- origin = .unknown- return- }- if let subagentKey = container.allKeys.first(where: { $0.stringValue == "subagent" }) {- let subagent = try? container.decode(WorkflowRolloutSubagentSource.self, forKey: subagentKey)- origin = subagent?.origin ?? .unknown- parentThreadID = subagent?.parentThreadID- return- }- if let customKey = container.allKeys.first(where: { $0.stringValue == "custom" }),- let customSource = try? container.decode(String.self, forKey: customKey),- !customSource.isEmpty {- origin = .main- return- }- origin = .unknown- }-- private static let knownMainSourceNames: Set<String> = [- "cli",- "exec",- "mcp",- "vscode"- ]-}--private nonisolated struct WorkflowRolloutSubagentSource: Decodable {- let origin: WorkflowEventOrigin- var parentThreadID: String?-- init(from decoder: Decoder) throws {- if let name = try? decoder.singleValueContainer().decode(String.self) {- origin = name.isEmpty ? .unknown : .auxiliary- return- }-- guard let container = try? decoder.container(keyedBy: WorkflowRolloutSourceKey.self),- !container.allKeys.isEmpty else {- origin = .unknown- return- }- if let spawnKey = container.allKeys.first(where: { $0.stringValue == "thread_spawn" }),- let spawn = try? container.nestedContainer(keyedBy: WorkflowRolloutSourceKey.self, forKey: spawnKey),- let parentKey = spawn.allKeys.first(where: { $0.stringValue == "parent_thread_id" }) {- parentThreadID = try? spawn.decode(String.self, forKey: parentKey)- }- if let otherKey = container.allKeys.first(where: { $0.stringValue == "other" }) {- guard let name = try? container.decode(String.self, forKey: otherKey),- !name.isEmpty else {- origin = .unknown- return- }- origin = name == "guardian" ? .autoReview : .auxiliary- return- }- origin = .auxiliary- }-}--private nonisolated struct WorkflowRolloutSourceKey: CodingKey {- let stringValue: String- let intValue: Int? = nil-- init?(stringValue: String) {- self.stringValue = stringValue- }-- init?(intValue _: Int) {- nil- }-}--/// Hook payload 不直接提供 reviewer 和 effort; 从当前 rollout 尾部只提取匹配 turn 的上下文-private nonisolated enum WorkflowTurnContextReader {- static func context(- transcriptPath: String,- turnID: String- ) -> WorkflowTurnContext? {- let url = URL(fileURLWithPath: transcriptPath)- let size = WorkflowStorage.fileSize(at: url)- guard size > 0,- let handle = try? FileHandle(forReadingFrom: url) else {- return nil- }- defer {- try? handle.close()- }-- let offset = size > searchByteLimit ? size - searchByteLimit : 0- guard (try? handle.seek(toOffset: offset)) != nil,- let data = try? handle.read(upToCount: Int(size - offset)),- !data.isEmpty else {- return nil- }-- let completeData = offset > 0 ? JSONLines.droppingLeadingPartialLine(data) : data-- for envelope in JSONLines.decode(CodexRolloutLineEnvelope.self, from: completeData)- .reversed() {- guard envelope.type == "turn_context",- let payload = envelope.payload,- payload.turnID == turnID else {- continue- }- return WorkflowTurnContext(- approvalReviewer: payload.approvalReviewer,- effort: payload.normalizedEffort- )- }- return nil- }-- private static let searchByteLimit: UInt64 = 8 * 1024 * 1024-}--private nonisolated struct WorkflowTurnContext {- let approvalReviewer: CodexApprovalReviewer?- let effort: String?-}--/// Codex Hook payload 字段存在版本差异, 这里集中做宽松类型归一化-private nonisolated struct WorkflowHookPayload {- let values: [String: Any]-- func string(for key: String) -> String? {- Self.normalizedString(values[key])- }-- func date(for key: String) -> Date? {- Self.normalizedDate(values[key])- }-- private static func normalizedString(_ value: Any?) -> String? {- switch value {- case let string as String:- let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)- return trimmedString.isEmpty ? nil : trimmedString- case let number as NSNumber:- return number.stringValue- default:- return nil- }- }-- private static func normalizedDate(_ value: Any?) -> Date? {- switch value {- case let string as String:- return date(from: string)- case let number as NSNumber:- let rawValue = number.doubleValue- let seconds = rawValue > 10000000000 ? rawValue / 1000 : rawValue- return Date(timeIntervalSince1970: seconds)- default:- return nil- }- }-- private static func date(from string: String) -> Date? {- let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)- guard !trimmedString.isEmpty else {- return nil- }-- if let date = CodexDateFormat.iso8601Date(from: trimmedString) {- return date- }-- return CodexDateFormat.localTimestampDate(from: trimmedString)- }-}diff --git a/CodexBar/Services/Workflow/WorkflowService.swift b/CodexBar/Services/Workflow/WorkflowService.swiftdeleted file mode 100644index 315e417..0000000--- a/CodexBar/Services/Workflow/WorkflowService.swift+++ /dev/null@@ -1,1584 +0,0 @@-import Combine-import CryptoKit-import Darwin-import Foundation-import os--/// 汇总失败时定位到哪一步, 只用于日志-private nonisolated enum MaintenanceStage: String {- case prepare- case write- case prune-}--/// 一轮汇总的计数, 成功路径压进 WorkflowSyncScheduler 的收尾那一条日志, 不为每天单独记一行-/// dates 从各处理结果的计数求和得出, 不额外保存-nonisolated struct WorkflowMaintenanceCounts {- var events = 0- var written = 0- var skipped = 0- var failed = 0- var pruned = 0- var dateRange = "-"- /// 这条之前连续空转了多少轮, 用来确认静默期是没事干而不是没跑- var idle = 0-- var dates: Int {- written + skipped + failed- }-- /// 这一轮有没有真的改变过状态- var hasWork: Bool {- dates > 0 || pruned > 0- }-}--/// 从 Hook 原始事件维护每日聚合, 对外只发布 UI 需要的统计快照-actor WorkflowService {- private let eventsDirectoryURL: URL- private let dailyLogURL: URL- private let syncService: WorkflowSyncService- private let tokenHistory: CodexTokenHistoryStore- /// 上次归一化时 daily.jsonl 的 stat 与当天日期键- private var lastNormalizedDailyLog: WorkflowDailyLogStamp?- /// 上一条维护日志之后连续空转的轮数, 记出去就清零- private var idleMaintenanceRounds = 0- private static let eventReadChunkSize = 64 * 1024-- init(- eventsDirectoryURL: URL = WorkflowStorage.eventsDirectoryURL(),- dailyLogURL: URL = WorkflowStorage.dailyURL(),- syncService: WorkflowSyncService = WorkflowSyncService(),- tokenHistory: CodexTokenHistoryStore = CodexTokenHistoryStore()- ) {- self.eventsDirectoryURL = eventsDirectoryURL- self.dailyLogURL = dailyLogURL- self.syncService = syncService- self.tokenHistory = tokenHistory- }-- // MARK: - 快照读取-- func loadSnapshot(- synchronize: Bool = false,- trigger: LogTrigger = .auto- ) async -> WorkflowSnapshot {- await makeSnapshot(- localAggregates: loadDailyAggregates() ?? [],- synchronize: synchronize,- trigger: trigger- )- }-- /// 先跑一轮维护再取快照- /// counts 为 nil 表示这一轮空转, 由调用方决定记不记日志- func loadSnapshotWithMaintenance(- synchronize: Bool,- trigger: LogTrigger- ) async -> (snapshot: WorkflowSnapshot, counts: WorkflowMaintenanceCounts?) {- let counts = performMaintenanceIfNeeded()- let snapshot = await loadSnapshot(synchronize: synchronize, trigger: trigger)- return (snapshot, counts)- }-- private func makeSnapshot(- localAggregates: [WorkflowDailyAggregate],- synchronize: Bool,- trigger: LogTrigger,- localTokenTurns: [CodexTokenTurn]? = nil- ) async -> WorkflowSnapshot {- let tokenTurns: [CodexTokenTurn]- if let localTokenTurns {- tokenTurns = localTokenTurns- } else {- do {- let baseline = await syncService.tokenRecoveryBaselineIfEnabled()- tokenTurns = try await tokenHistory.refresh(baseline: baseline)- } catch {- let error = error as NSError- AppLog.workflow.error("Token 历史读取失败: domain=\(error.domain, privacy: .public) code=\(error.code)")- tokenTurns = []- }- }- let syncSnapshot: WorkflowSyncSnapshot = if synchronize {- await syncService.synchronizeIfEnabled(localAggregates: localAggregates, localTokenTurns: tokenTurns, trigger: trigger)- } else {- await syncService.snapshotFromCacheIfEnabled(localTokenTurns: tokenTurns)- }- var snapshot = WorkflowSnapshot(- localAggregates: localAggregates,- syncedRecords: syncSnapshot.records,- currentDeviceID: syncSnapshot.currentDeviceID- )- snapshot.tokenUsageByDate = syncSnapshot.tokenUsageByDate ?? CodexTokenTurn.dailyUsage(tokenTurns)- return snapshot- }-- /// 以指定日期范围内的本机原始事件为权威来源重建, 并安排替换当前设备的同日云端贡献- fileprivate func rebuildData(- for dateKeys: [String],- synchronize: Bool- ) async throws -> WorkflowDataRebuildOutcome {- let duration = LogDuration()- let normalizedDateKeys = Set(dateKeys).sorted()- guard !normalizedDateKeys.isEmpty else {- throw WorkflowDataRebuildError.sourceUnavailable- }-- // 单日失败不中止整批: 失败的日期已被 rebuildLocalData 标脏, 常规维护会自动重建- // 中止会让「前几天已改写, 后几天没碰」这个事实完全不被上报- var rebuildResults = [WorkflowMaintenanceResult]()- var failedDateKeys = [String]()- var firstFailure: Error?- let hookDateKeys = normalizedDateKeys.filter { WorkflowStorage.fileSize(at: eventLogURL(for: $0)) > 0 }- for dateKey in hookDateKeys {- do {- try rebuildResults.append(rebuildLocalData(for: dateKey))- } catch {- // 整批成功时这个原因不会往上抛, 摘要只带得走日期- let details = LogFields.joined(- "stage=date",- "date=\(dateKey)",- "detail=\(error.localizedDescription)"- )- AppLog.workflow.error("数据重建失败: \(details, privacy: .public)")- failedDateKeys.append(dateKey)- if firstFailure == nil {- firstFailure = error- }- }- }-- var tokenResult = CodexTokenRebuildResult.empty- var didFailTokenRebuild = false- do {- tokenResult = try await tokenHistory.rebuild(for: normalizedDateKeys)- } catch {- didFailTokenRebuild = true- firstFailure = firstFailure ?? error- let error = error as NSError- AppLog.workflow.error("Token 重建失败: domain=\(error.domain, privacy: .public) code=\(error.code)")- }-- // 成功与失败的日期都要登记: 失败的日期稍后会被自动重建并推进 sourceGeneration,- // 届时会上传到新的 record ID, 不清理旧记录会在云端留下同日重复的贡献- // 全部失败时同样要登记, 它们一样已被标脏- var didFailReplacementMarking = false- do {- try await syncService.markReplacementNeeded(for: hookDateKeys)- } catch {- let details = LogFields.joined(- "stage=replacementMarking",- "dates=\(normalizedDateKeys.count)",- "detail=\(error.localizedDescription)"- )- AppLog.workflow.error("数据重建失败: \(details, privacy: .public)")- didFailReplacementMarking = true- }-- // 一天都没成功才算整体失败, 并保留首个真实原因而非笼统报「数据发生变化」- guard !rebuildResults.isEmpty || !tokenResult.dateKeys.isEmpty else {- throw firstFailure ?? WorkflowDataRebuildError.sourceUnavailable- }-- // 重建只由设置页的用户操作发起- let localTurns = await (try? tokenHistory.currentTurns()) ?? []- let snapshot = await makeSnapshot(- localAggregates: loadDailyAggregates() ?? [],- synchronize: synchronize,- trigger: .manual,- localTokenTurns: localTurns- )- let tokenSyncPending = await syncService.hasPendingTokenUpdates(local: localTurns)- let summary = await WorkflowDataRebuildSummary(- rebuiltDateCount: Set(rebuildResults.map(\.dateKey)).union(tokenResult.dateKeys).count,- eventCount: rebuildResults.reduce(0) { $0 + ($1.aggregate.eventCount ?? 0) },- corruptLineCount: rebuildResults.reduce(0) { $0 + $1.corrupt },- isSyncReplacementPending: syncService.hasPendingReplacement(for: hookDateKeys) || tokenSyncPending,- failedDateKeys: failedDateKeys,- didFailSyncReplacementMarking: didFailReplacementMarking,- tokenTurnCount: tokenResult.turnCount,- didFailTokenRebuild: didFailTokenRebuild- )- let elapsed = duration.elapsed- let details = LogFields.joined(- "dates=\(summary.rebuiltDateCount)",- "events=\(summary.eventCount)",- "tokenTurns=\(summary.tokenTurnCount)",- "corruptLines=\(summary.corruptLineCount)",- "failedDates=\(failedDateKeys.count)",- "elapsed=\(elapsed)"- )- AppLog.workflow.notice("数据重建完成: \(details, privacy: .public)")- return WorkflowDataRebuildOutcome(snapshot: snapshot, summary: summary)- }-- private func loadDailyAggregates() -> [WorkflowDailyAggregate]? {- guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {- return nil- }-- let aggregates: [WorkflowDailyAggregate] = JSONLines.decode(from: data)- guard !aggregates.isEmpty else {- return nil- }-- return WorkflowDailyAggregate.normalized(aggregates: aggregates)- }-- // MARK: - 重建与维护调度-- private func rebuildLocalData(for dateKey: String) throws -> WorkflowMaintenanceResult {- var aggregates = loadDailyAggregates() ?? []- let hookCountAvailability = aggregates- .first(where: { $0.date == dateKey })?- .hookCountAvailability ?? .legacy- let task = try prepareRebuildTask(- for: dateKey,- hookCountAvailability: hookCountAvailability- )-- do {- let result = try buildDailyAggregate(for: task)- guard try commit(result, aggregates: &aggregates),- rebuildWasCommitted(result) else {- throw WorkflowDataRebuildError.sourceChanged- }- return result- } catch {- markDirty(dateKey)- throw error- }- }-- private func prepareRebuildTask(- for dateKey: String,- hookCountAvailability: WorkflowHookCountAvailability- ) throws -> WorkflowMaintenanceTask {- let retentionCutoffKey = WorkflowStorage.dateKey(for: WorkflowStorage.retentionCutoffDate())- guard WorkflowStorage.isValidDateKey(dateKey), dateKey >= retentionCutoffKey else {- throw WorkflowDataRebuildError.sourceUnavailable- }-- return try WorkflowStorage.withExclusiveLock {- guard let stat = WorkflowStorage.fileStat(at: eventLogURL(for: dateKey)),- stat.size > 0 else {- throw WorkflowDataRebuildError.sourceUnavailable- }-- var state = WorkflowStorage.loadMaintenanceState()- state.startNewSourceGeneration(- for: dateKey,- isFresh: false,- fileIdentifier: stat.identifier- )- try WorkflowStorage.saveMaintenanceState(state)-- guard let day = state.days[dateKey] else {- throw WorkflowDataRebuildError.sourceUnavailable- }- return dirtyTask(- for: dateKey,- day: day,- size: stat.size,- hookCountAvailability: hookCountAvailability- )- }- }-- private func rebuildWasCommitted(_ result: WorkflowMaintenanceResult) -> Bool {- let dailyGeneration = loadDailyAggregates()?- .first(where: { $0.date == result.dateKey })?- .sourceGeneration- guard dailyGeneration == result.aggregate.sourceGeneration else {- return false- }-- return (try? WorkflowStorage.withExclusiveLock {- guard let day = WorkflowStorage.loadMaintenanceState().days[result.dateKey] else {- return false- }- return day.sourceGeneration == result.aggregate.sourceGeneration- && day.offset == result.size- }) ?? false- }-- /// 空转的一轮返回 nil- /// 维护跟随额度刷新执行, 只记录有实际工作的轮次, 避免空闲时持续产生重复日志- /// 收尾日志由 WorkflowSyncScheduler 统一记, 这里只负责判断有没有值得记的东西- private func performMaintenanceIfNeeded() -> WorkflowMaintenanceCounts? {- let duration = LogDuration()- var counts = WorkflowMaintenanceCounts()- var stage = MaintenanceStage.prepare- do {- let tasks = try prepareMaintenanceTasks()- stage = .write- let didCommitDailyLog = perform(tasks, counts: &counts)- // 成功提交前已整体归一化, 没有完整提交时再做一次稳态检查- if !didCommitDailyLog {- try normalizeDailyAggregatesIfNeeded()- }- stage = .prune- counts.pruned = try pruneExpiredEventFiles()- } catch {- let elapsed = duration.elapsed- let details = LogFields.joined(- "stage=\(stage.rawValue)",- "elapsed=\(elapsed)",- "detail=\(error.localizedDescription)"- )- AppLog.workflow.error("事件汇总失败: \(details, privacy: .public)")- idleMaintenanceRounds = 0- return nil- }-- guard counts.hasWork else {- idleMaintenanceRounds += 1- return nil- }-- counts.idle = idleMaintenanceRounds- idleMaintenanceRounds = 0- return counts- }-- /// 返回是否至少完整提交一个聚合与维护状态- /// 批次内共享同一份内存聚合, 避免每个任务重新读盘- private func perform(- _ tasks: [WorkflowMaintenanceTask],- counts: inout WorkflowMaintenanceCounts- ) -> Bool {- // 任务是 dirty 与 pending 两段拼接, 只在各自半边有序, 取首尾会得到反向区间- let dateKeys = tasks.map(\.dateKey)- guard let oldestDateKey = dateKeys.min(),- let newestDateKey = dateKeys.max() else {- return false- }-- counts.dateRange = oldestDateKey == newestDateKey- ? oldestDateKey- : oldestDateKey + ".." + newestDateKey-- var aggregates = loadDailyAggregates() ?? []- var didCommit = false- for task in tasks {- do {- let result = try buildDailyAggregate(for: task)- if try commit(result, aggregates: &aggregates) {- didCommit = true- counts.written += 1- // 记本轮新摄入的量; 累加 eventCount 会变成当日总数, Hook 停写也看不出来- // dirty 任务没有 base, 差值即整天重算的量, 与"这轮处理了多少"仍然一致- counts.events += (result.aggregate.eventCount ?? 0) - task.baseEventCount- } else {- counts.skipped += 1- }- } catch {- counts.failed += 1- let details = LogFields.joined(- "stage=daily",- "date=\(task.dateKey)",- "detail=\(error.localizedDescription)",- "action=markDirty"- )- AppLog.workflow.error("事件汇总失败: \(details, privacy: .public)")- markDirty(task.dateKey)- }- }-- return didCommit- }-- private func prepareMaintenanceTasks() throws -> [WorkflowMaintenanceTask] {- let eventDateKeys = eventDateKeys()- let dailyDecodeResult = loadDailyAggregatesWithFailures()-- return try WorkflowStorage.withExclusiveLock {- var state = WorkflowStorage.loadMaintenanceState()- var changedState = state.normalize()- let dailyByDate = dailyDecodeResult.values.reduce(into: [String: WorkflowDailyAggregate]()) { result, aggregate in- result[aggregate.date] = aggregate- }-- let changedByRebuild = markRebuildDates(- eventDateKeys: eventDateKeys,- dailyDecodeResult: dailyDecodeResult,- dailyByDate: dailyByDate,- state: &state- )- let changedByReconcile = reconcileEventFiles(eventDateKeys: eventDateKeys, state: &state)- changedState = changedState || changedByRebuild || changedByReconcile-- let tasks = makeMaintenanceTasks(- state: &state,- dailyByDate: dailyByDate,- changedState: &changedState- )-- if changedState {- try WorkflowStorage.saveMaintenanceState(state)- }-- return tasks- }- }-- private func markRebuildDates(- eventDateKeys: [String],- dailyDecodeResult: JSONLinesDecodeResult<WorkflowDailyAggregate>,- dailyByDate: [String: WorkflowDailyAggregate],- state: inout WorkflowMaintenanceState- ) -> Bool {- var changed = false-- if state.schema != WorkflowMaintenanceState.currentAggregationSchema {- changed = state.markDirty(contentsOf: eventDateKeys) || changed- state.schema = WorkflowMaintenanceState.currentAggregationSchema- changed = true- }-- if dailyDecodeResult.failedLineCount > 0 || (dailyDecodeResult.values.isEmpty && !eventDateKeys.isEmpty) {- changed = state.markDirty(contentsOf: eventDateKeys) || changed- }-- changed = state.markDirty(contentsOf: eventDateKeys.filter { dailyByDate[$0] == nil }) || changed- changed = state.markDirty(contentsOf: state.pending.filter { dailyByDate[$0] == nil }) || changed-- return changed- }-- private func reconcileEventFiles(- eventDateKeys: [String],- state: inout WorkflowMaintenanceState- ) -> Bool {- var changed = state.markDirty(contentsOf: eventDateKeys.filter { state.days[$0] == nil })-- for dateKey in eventDateKeys {- guard let stat = WorkflowStorage.fileStat(at: eventLogURL(for: dateKey)) else {- continue- }-- changed = state.ensureSourceGeneration(- for: dateKey,- fileIdentifier: stat.identifier- ) || changed- guard let day = state.days[dateKey] else {- continue- }-- let identifierChanged = day.fileIdentifier != nil- && day.fileIdentifier != stat.identifier- let boundary = boundaryStatus(dateKey: dateKey, day: day, stat: stat)- if let verifiedAt = boundary.verifiedAtNanoseconds {- changed = state.recordBoundaryVerification(- for: dateKey,- at: verifiedAt- ) || changed- }-- if identifierChanged || stat.size < day.offset || boundary.isChanged {- state.startNewSourceGeneration(- for: dateKey,- isFresh: stat.size == 0,- fileIdentifier: stat.identifier- )- changed = true- } else if day.offset != day.size {- state.markDirty(dateKey)- changed = true- } else if stat.size > day.offset,- !state.pending.contains(dateKey),- !state.dirty.contains(dateKey) {- state.markPending(dateKey)- changed = true- }- }-- return changed- }-- /// boundaryHash 覆盖 offset 之前的边界片段, 追加只写在 offset 之后- /// 文件未修改时复用已有哈希, 减少持锁时间和 Hook 子进程的等待- ///- /// - Returns: 边界是否变化, 以及确认边界未变时的文件修改时间. 无需记录时, 时间为 nil- private func boundaryStatus(- dateKey: String,- day: WorkflowDayMaintenanceState,- stat: WorkflowFileStat- ) -> (isChanged: Bool, verifiedAtNanoseconds: Int64?) {- guard let recordedHash = day.boundaryHash else {- return (false, nil)- }-- // mtime 是主判据: 任何写入都会推进它, identifier 与 size 作为附加保险- if day.boundaryVerifiedAtNanoseconds == stat.modifiedAtNanoseconds,- day.fileIdentifier == stat.identifier,- day.size == stat.size {- return (false, nil)- }-- guard (try? eventLogBoundaryHash(for: dateKey, endingAt: day.offset)) == recordedHash else {- return (true, nil)- }-- // 记下本次校验时的 mtime, 文件保持不动的话下一轮即可跳过- return (false, stat.modifiedAtNanoseconds)- }-- private func makeMaintenanceTasks(- state: inout WorkflowMaintenanceState,- dailyByDate: [String: WorkflowDailyAggregate],- changedState: inout Bool- ) -> [WorkflowMaintenanceTask] {- let dirty = Set(state.dirty)- var tasks: [WorkflowMaintenanceTask] = state.dirty.compactMap { dateKey in- guard let day = state.days[dateKey] else {- return nil- }- return dirtyTask(- for: dateKey,- day: day,- hookCountAvailability: dailyByDate[dateKey]?- .hookCountAvailability ?? .legacy- )- }-- for dateKey in state.pending where !dirty.contains(dateKey) {- let day = state.days[dateKey] ?? WorkflowDayMaintenanceState()- let size = eventLogSize(for: dateKey)- guard size > day.offset else {- state.removePending(dateKey)- changedState = true- continue- }-- let existingAggregate = dailyByDate[dateKey]- guard let baseAggregate = existingAggregate,- baseAggregate.sourceGeneration == day.sourceGeneration else {- state.markDirty(dateKey)- changedState = true- tasks.append(dirtyTask(- for: dateKey,- day: day,- size: size,- hookCountAvailability: existingAggregate?- .hookCountAvailability ?? .legacy- ))- continue- }-- // ID 已压缩的聚合无法判断追加事件是否属于已有 session 或 turn- // 任何不能证明与全量结果等价的增量任务都降级为完整重建- guard retainsIdentifiers(for: dateKey),- baseAggregate.supportsIncrementalAggregation else {- state.markDirty(dateKey)- changedState = true- tasks.append(dirtyTask(- for: dateKey,- day: day,- size: size,- hookCountAvailability: baseAggregate.hookCountAvailability- ))- continue- }-- tasks.append(- pendingTask(- for: dateKey,- day: day,- size: size,- baseAggregate: baseAggregate- )- )- }-- return tasks- }-- private func dirtyTask(- for dateKey: String,- day: WorkflowDayMaintenanceState,- size: UInt64? = nil,- hookCountAvailability: WorkflowHookCountAvailability = .legacy- ) -> WorkflowMaintenanceTask {- let stat = WorkflowStorage.fileStat(at: eventLogURL(for: dateKey))- return WorkflowMaintenanceTask(- dateKey: dateKey,- startOffset: 0,- size: size ?? stat?.size ?? 0,- mode: .rebuild(hookCountAvailability),- existingCorrupt: 0,- sourceGeneration: day.sourceGeneration,- sourceIsFresh: day.sourceIsFresh,- fileIdentifier: stat?.identifier- )- }-- private func pendingTask(- for dateKey: String,- day: WorkflowDayMaintenanceState,- size: UInt64,- baseAggregate: WorkflowDailyAggregate- ) -> WorkflowMaintenanceTask {- WorkflowMaintenanceTask(- dateKey: dateKey,- startOffset: day.offset,- size: size,- mode: .append(baseAggregate),- existingCorrupt: day.corrupt,- sourceGeneration: day.sourceGeneration,- sourceIsFresh: day.sourceIsFresh,- fileIdentifier: day.fileIdentifier- )- }-- // MARK: - 事件文件读取与聚合-- private func eventLogURL(for dateKey: String) -> URL {- WorkflowStorage.eventLogURL(for: dateKey, in: eventsDirectoryURL)- }-- private func eventLogSize(for dateKey: String) -> UInt64 {- WorkflowStorage.fileSize(at: eventLogURL(for: dateKey))- }-- private func eventLogBoundaryHash(- for dateKey: String,- endingAt offset: UInt64- ) throws -> String? {- guard offset > 0 else {- return nil- }-- let length = min(offset, 4 * 1024)- let handle = try FileHandle(forReadingFrom: eventLogURL(for: dateKey))- defer {- try? handle.close()- }-- try handle.seek(toOffset: offset - length)- guard let data = try handle.read(upToCount: Int(length)),- data.count == Int(length) else {- throw CocoaError(.fileReadUnknown)- }-- return SHA256.hash(data: data)- .map { String(format: "%02x", $0) }- .joined()- }-- private func loadDailyAggregatesWithFailures() -> JSONLinesDecodeResult<WorkflowDailyAggregate> {- guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {- return JSONLinesDecodeResult(values: [], failedLineCount: 0)- }-- return JSONLines.decodeWithFailures(from: data)- }-- private func eventDateKeys() -> [String] {- WorkflowStorage.eventLogDateKeys(in: eventsDirectoryURL)- }-- private func buildDailyAggregate(- for task: WorkflowMaintenanceTask- ) throws -> WorkflowMaintenanceResult {- var accumulator = switch task.mode {- case let .rebuild(hookCountAvailability):- WorkflowDailyAccumulator(- rebuilding: task.dateKey,- sourceGeneration: task.sourceGeneration,- sourceIsFresh: task.sourceIsFresh,- hookCountAvailability: hookCountAvailability- )- case let .append(baseAggregate):- WorkflowDailyAccumulator(- appending: baseAggregate,- sourceGeneration: task.sourceGeneration,- sourceIsFresh: task.sourceIsFresh- )- }- var corrupt = task.existingCorrupt-- corrupt += try readEvents(- at: eventLogURL(for: task.dateKey),- from: task.startOffset,- upTo: task.size- ) { event in- accumulator.record(event)- }-- let identifierStorage: WorkflowIdentifierStorage = retainsIdentifiers(for: task.dateKey)- ? .retained- : .compacted- let aggregate = accumulator.finalized(identifierStorage: identifierStorage)- return try WorkflowMaintenanceResult(- dateKey: task.dateKey,- aggregate: aggregate,- size: task.size,- corrupt: corrupt,- fileIdentifier: task.fileIdentifier,- boundaryHash: eventLogBoundaryHash(for: task.dateKey, endingAt: task.size)- )- }-- private func readEvents(- at url: URL,- from startOffset: UInt64,- upTo size: UInt64,- record: (WorkflowHookEvent) -> Void- ) throws -> Int {- guard size > startOffset else {- return 0- }-- let fileHandle = try FileHandle(forReadingFrom: url)- defer {- try? fileHandle.close()- }-- try fileHandle.seek(toOffset: startOffset)-- let decoder = JSONDecoder()- var remainingBytes = size - startOffset- var buffer = Data()- var corrupt = 0-- // 分块读取防止大日志一次性进内存, 但仍按完整 JSONL 行解码- while remainingBytes > 0 {- let readSize = min(Int(remainingBytes), Self.eventReadChunkSize)- guard let chunk = try fileHandle.read(upToCount: readSize), !chunk.isEmpty else {- break- }-- remainingBytes -= UInt64(chunk.count)- buffer.append(chunk)-- while let newlineIndex = buffer.firstIndex(of: JSONLines.newlineByte) {- let lineData = buffer[..<newlineIndex]- corrupt += decode(lineData, using: decoder, record: record)- buffer.removeSubrange(...newlineIndex)- }- }-- if !buffer.isEmpty {- corrupt += decode(buffer, using: decoder, record: record)- }-- return corrupt- }-- private func decode(- _ lineData: Data.SubSequence,- using decoder: JSONDecoder,- record: (WorkflowHookEvent) -> Void- ) -> Int {- guard let line = String(bytes: lineData, encoding: .utf8)?- .trimmingCharacters(in: .whitespacesAndNewlines) else {- return 1- }-- guard !line.isEmpty else {- return 0- }-- guard let data = line.data(using: .utf8),- let event = try? decoder.decode(WorkflowHookEvent.self, from: data) else {- return 1- }-- record(event)- return 0- }-- // MARK: - 落盘与状态提交-- /// 返回聚合与维护状态是否都基于同一份事件源完成提交- private func commit(- _ result: WorkflowMaintenanceResult,- aggregates: inout [WorkflowDailyAggregate]- ) throws -> Bool {- guard try eventLogSourceIsValid(for: result) else {- return false- }-- // daily.jsonl 和 maintenance.json 分开写- // 每次提交前后都检查事件文件是否被并发追加- try writeDailyAggregate(result.aggregate, into: &aggregates)- return try commitMaintenanceState(result)- }-- private func eventLogSourceIsValid(for result: WorkflowMaintenanceResult) throws -> Bool {- try WorkflowStorage.withExclusiveLock {- var state = WorkflowStorage.loadMaintenanceState()- return try validatedEventLogSize(for: result, state: &state) != nil- }- }-- /// 锁内确认读取期间仍是同一份追加源; 断代时换 generation 并等待重建- private func validatedEventLogSize(- for result: WorkflowMaintenanceResult,- state: inout WorkflowMaintenanceState- ) throws -> UInt64? {- guard state.days[result.dateKey]?.sourceGeneration == result.aggregate.sourceGeneration else {- return nil- }-- let stat = WorkflowStorage.fileStat(at: eventLogURL(for: result.dateKey))- let identifierMatches = result.fileIdentifier == nil- || result.fileIdentifier == stat?.identifier- let boundaryMatches = (try? eventLogBoundaryHash(- for: result.dateKey,- endingAt: result.size- )) == result.boundaryHash-- guard let stat,- stat.size >= result.size,- identifierMatches,- boundaryMatches else {- state.startNewSourceGeneration(- for: result.dateKey,- isFresh: stat?.size == 0,- fileIdentifier: stat?.identifier- )- try WorkflowStorage.saveMaintenanceState(state)- return nil- }-- return stat.size- }-- private func writeDailyAggregate(- _ aggregate: WorkflowDailyAggregate,- into aggregates: inout [WorkflowDailyAggregate]- ) throws {- try FileManager.default.createDirectory(- at: dailyLogURL.deletingLastPathComponent(),- withIntermediateDirectories: true- )-- upsert(aggregate, into: &aggregates)- aggregates = WorkflowDailyAggregate.normalized(aggregates: aggregates)- let data = try WorkflowDailyAggregate.encodeJSONLines(aggregates)- try data.write(to: dailyLogURL, options: .atomic)- }-- private func normalizeDailyAggregatesIfNeeded() throws {- guard let stat = WorkflowStorage.fileStat(at: dailyLogURL), stat.size > 0 else {- return- }-- // 稳态下文件与日期都没变, 跳过全量解码与重编码比对- let dayKey = WorkflowStorage.dateKey(for: Date())- if lastNormalizedDailyLog == WorkflowDailyLogStamp(size: stat.size, identifier: stat.identifier, dayKey: dayKey) {- return- }-- guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {- return- }-- let decodeResult = JSONLines.decodeWithFailures(WorkflowDailyAggregate.self, from: data)- guard decodeResult.failedLineCount == 0 else {- return- }-- let normalizedAggregates = WorkflowDailyAggregate.normalized(aggregates: decodeResult.values)- let normalizedData = try WorkflowDailyAggregate.encodeJSONLines(normalizedAggregates)- if normalizedData != data {- try FileManager.default.createDirectory(- at: dailyLogURL.deletingLastPathComponent(),- withIntermediateDirectories: true- )- try normalizedData.write(to: dailyLogURL, options: .atomic)- }-- if let latestStat = WorkflowStorage.fileStat(at: dailyLogURL) {- lastNormalizedDailyLog = WorkflowDailyLogStamp(- size: latestStat.size,- identifier: latestStat.identifier,- dayKey: dayKey- )- }- }-- /// 返回第二次源校验后是否真正推进了维护状态- private func commitMaintenanceState(_ result: WorkflowMaintenanceResult) throws -> Bool {- try WorkflowStorage.withExclusiveLock {- var state = WorkflowStorage.loadMaintenanceState()-- guard let currentSize = try validatedEventLogSize(for: result, state: &state) else {- return false- }-- state.days[result.dateKey] = WorkflowDayMaintenanceState(- offset: result.size,- size: result.size,- corrupt: result.corrupt,- sourceGeneration: result.aggregate.sourceGeneration,- sourceIsFresh: result.aggregate.sourceIsFresh,- fileIdentifier: result.fileIdentifier,- boundaryHash: result.boundaryHash- )- state.removeDirty(result.dateKey)-- if currentSize == result.size {- state.removePending(result.dateKey)- } else {- state.markPending(result.dateKey)- }-- try WorkflowStorage.saveMaintenanceState(state)- return true- }- }-- private func upsert(_ aggregate: WorkflowDailyAggregate, into aggregates: inout [WorkflowDailyAggregate]) {- if let index = aggregates.firstIndex(where: { $0.date == aggregate.date }) {- aggregates[index] = aggregate- } else {- aggregates.append(aggregate)- }- }-- private func markDirty(_ dateKey: String) {- do {- try WorkflowStorage.withExclusiveLock {- var state = WorkflowStorage.loadMaintenanceState()- state.markDirty(dateKey)- try WorkflowStorage.saveMaintenanceState(state)- }- } catch {- // 标记丢了下一轮就不会重建这天, 数据会静默缺一块- let details = LogFields.joined(- "stage=markDirty",- "date=\(dateKey)",- "detail=\(error.localizedDescription)"- )- AppLog.workflow.error("事件汇总失败: \(details, privacy: .public)")- }- }-- // MARK: - 保留期清理-- @discardableResult- private func pruneExpiredEventFiles() throws -> Int {- let cutoffDate = WorkflowStorage.retentionCutoffDate()- let expiredDateKeys = eventDateKeys().filter { dateKey in- guard let date = CodexDateFormat.dayDate(from: dateKey) else {- return false- }-- return date < cutoffDate- }-- guard !expiredDateKeys.isEmpty else {- return 0- }-- try WorkflowStorage.withExclusiveLock {- var state = WorkflowStorage.loadMaintenanceState()- for dateKey in expiredDateKeys {- try? FileManager.default.removeItem(at: eventLogURL(for: dateKey))- state.remove(dateKey)- }-- try WorkflowStorage.saveMaintenanceState(state)- }- // 保留期到点会真的删掉原始事件文件, 数据对不上时要能查到哪些日期被清掉了- let details = LogFields.joined(- "dates=\(expiredDateKeys.count)",- "oldest=\(expiredDateKeys.first ?? "-")"- )- AppLog.workflow.notice("过期事件已清理: \(details, privacy: .public)")- return expiredDateKeys.count- }-- private func retainsIdentifiers(for dateKey: String) -> Bool {- guard let date = CodexDateFormat.dayDate(from: dateKey) else {- return true- }-- return date >= WorkflowStorage.identifierRetentionCutoffDate()- }-}--/// Hook 统计文件路径, 保留期和跨进程 flock 都集中在这里-nonisolated enum WorkflowStorage {- private static let retentionDayCount = 210- private static let identifierRetentionDayCount = 3-- // MARK: - 存储路径-- static func eventsDirectoryURL() -> URL {- directoryURL()- .appendingPathComponent("events", isDirectory: true)- }-- static func eventLogURL(for dateKey: String, in directoryURL: URL = eventsDirectoryURL()) -> URL {- directoryURL.appendingPathComponent("\(dateKey).jsonl", isDirectory: false)- }-- static func dailyURL() -> URL {- directoryURL()- .appendingPathComponent("daily.jsonl", isDirectory: false)- }-- static func lockURL() -> URL {- directoryURL()- .appendingPathComponent("stats.lock", isDirectory: false)- }-- static func maintenanceURL() -> URL {- directoryURL()- .appendingPathComponent("maintenance.json", isDirectory: false)- }-- static func syncDirectoryURL() -> URL {- directoryURL()- .appendingPathComponent("Sync", isDirectory: true)- }-- static func directoryURL() -> URL {- let applicationSupportURL = FileManager.default.urls(- for: .applicationSupportDirectory,- in: .userDomainMask- ).first ?? URL(fileURLWithPath: NSHomeDirectory())- .appendingPathComponent("Library", isDirectory: true)- .appendingPathComponent("Application Support", isDirectory: true)-- return applicationSupportURL- .appendingPathComponent("CodexBar", isDirectory: true)- .appendingPathComponent("HookEvents", isDirectory: true)- }-- /// waitLimitSeconds 为 nil 时无限等待, 供不在 Codex 关键路径上的主 App 使用- static func withExclusiveLock<T>(- waitLimitSeconds: Double? = nil,- _ work: () throws -> T- ) throws -> T {- try FileManager.default.createDirectory(- at: directoryURL(),- withIntermediateDirectories: true- )-- // 创建与打开必须是同一次调用: 分开做时两个进程可能各自创建,- // 后创建的会 unlink 掉前者正在锁的 inode, 于是双方都以为自己独占- let fileDescriptor = open(lockURL().path, O_RDWR | O_CREAT, 0o644)- guard fileDescriptor >= 0 else {- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)- }- defer {- close(fileDescriptor)- }-- // Hook 子进程和主 App 可能同时写统计文件, 必须使用进程级排他锁- try acquireExclusiveLock(fileDescriptor, waitLimitSeconds: waitLimitSeconds)-- defer {- flock(fileDescriptor, LOCK_UN)- }-- return try work()- }-- /// 有等待上限时改用非阻塞重试: Hook 子进程不能无限期占着 Codex 的一轮- private static func acquireExclusiveLock(- _ fileDescriptor: Int32,- waitLimitSeconds: Double?- ) throws {- guard let waitLimitSeconds else {- guard flock(fileDescriptor, LOCK_EX) == 0 else {- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)- }- return- }-- let clock = ContinuousClock()- let deadline = clock.now.advanced(by: .seconds(waitLimitSeconds))- var retryInterval = lockMinimumRetryIntervalMicroseconds- while flock(fileDescriptor, LOCK_EX | LOCK_NB) != 0 {- let lockErrno = errno- guard lockErrno == EWOULDBLOCK else {- throw POSIXError(POSIXErrorCode(rawValue: lockErrno) ?? .EIO)- }- guard clock.now < deadline else {- throw POSIXError(.ETIMEDOUT)- }- usleep(retryInterval)- retryInterval = min(retryInterval * 2, lockMaximumRetryIntervalMicroseconds)- }- }-- /// 锁轮询从短间隔开始逐步退避, 兼顾短期争用的响应速度和持续争用时的开销- private static let lockMinimumRetryIntervalMicroseconds: UInt32 = 1000- private static let lockMaximumRetryIntervalMicroseconds: UInt32 = 20000-- static func loadMaintenanceState() -> WorkflowMaintenanceState {- let url = maintenanceURL()- guard let data = try? Data(contentsOf: url), !data.isEmpty,- let state = try? JSONDecoder().decode(WorkflowMaintenanceState.self, from: data) else {- return WorkflowMaintenanceState()- }-- return state- }-- static func saveMaintenanceState(_ state: WorkflowMaintenanceState) throws {- try FileManager.default.createDirectory(- at: directoryURL(),- withIntermediateDirectories: true- )-- let data = try JSONLines.stableEncoder.encode(state)- try data.write(to: maintenanceURL(), options: .atomic)- }-- static func fileSize(at url: URL) -> UInt64 {- fileStat(at: url)?.size ?? 0- }-- /// 单次 stat 同时返回大小与 inode 标识, 文件缺失或不可读时为 nil- /// 维护流程需要批量读取文件状态, 直接使用 stat(2) 避免逐个构造属性字典- /// mtime 记整数纳秒: 落盘状态用 JSON 编码, Date 会退化成浮点而无法精确比较- /// 沿用 attributesOfItem 的语义跟随符号链接, 因此用 stat 而非 lstat- static func fileStat(at url: URL) -> WorkflowFileStat? {- var info = Darwin.stat()- guard stat(url.path, &info) == 0 else {- return nil- }-- return WorkflowFileStat(- size: UInt64(clamping: info.st_size),- identifier: UInt64(info.st_ino),- modifiedAtNanoseconds: Int64(info.st_mtimespec.tv_sec) * 1000000000- + Int64(info.st_mtimespec.tv_nsec)- )- }-- /// 枚举目录中文件名为合法日期键的 .jsonl 事件日志, 返回升序日期键- static func eventLogDateKeys(in directoryURL: URL = eventsDirectoryURL()) -> [String] {- guard let contents = try? FileManager.default.contentsOfDirectory(- at: directoryURL,- includingPropertiesForKeys: nil,- options: [.skipsHiddenFiles]- ) else {- return []- }-- return contents- .filter { $0.pathExtension == "jsonl" }- .map { $0.deletingPathExtension().lastPathComponent }- .filter { isValidDateKey($0) }- .sorted()- }-- /// 返回保留窗口内且本机原始事件文件非空的日期, 供设置页标记和筛选实际重建项- static func rebuildableEventDateKeys(- in directoryURL: URL = eventsDirectoryURL()- ) -> [String] {- let cutoffKey = dateKey(for: retentionCutoffDate())- return eventLogDateKeys(in: directoryURL)- .filter { dateKey in- dateKey >= cutoffKey- && fileSize(at: eventLogURL(for: dateKey, in: directoryURL)) > 0- }- .sorted(by: >)- }-- static func retentionCutoffDate(today: Date = Date(), calendar: Calendar = .current) -> Date {- cutoffDate(dayCount: retentionDayCount, today: today, calendar: calendar)- }-- static func identifierRetentionCutoffDate(today: Date = Date(), calendar: Calendar = .current) -> Date {- cutoffDate(dayCount: identifierRetentionDayCount, today: today, calendar: calendar)- }-- private static func cutoffDate(dayCount: Int, today: Date, calendar: Calendar) -> Date {- let todayStart = calendar.startOfDay(for: today)- return calendar.date(- byAdding: .day,- value: -(dayCount - 1),- to: todayStart- ) ?? todayStart- }-- static func dateKey(for date: Date) -> String {- CodexDateFormat.dayString(from: date)- }-- static func isValidDateKey(_ dateKey: String) -> Bool {- CodexDateFormat.dayDate(from: dateKey) != nil- }-}--/// 记录单日事件文件已处理到的 offset, 支持后续增量维护-/// 维护流程使用的文件状态字段-nonisolated struct WorkflowFileStat {- let size: UInt64- let identifier: UInt64- let modifiedAtNanoseconds: Int64-}--nonisolated struct WorkflowDayMaintenanceState: Codable, Equatable {- var offset: UInt64- var size: UInt64- var corrupt: Int- var sourceGeneration: String?- var sourceIsFresh: Bool- var fileIdentifier: UInt64?- var boundaryHash: String?- /// 上次校验 boundaryHash 时文件的 mtime; 未变即可跳过重算- var boundaryVerifiedAtNanoseconds: Int64?-- init(- offset: UInt64 = 0,- size: UInt64 = 0,- corrupt: Int = 0,- sourceGeneration: String? = nil,- sourceIsFresh: Bool = false,- fileIdentifier: UInt64? = nil,- boundaryHash: String? = nil,- boundaryVerifiedAtNanoseconds: Int64? = nil- ) {- self.offset = offset- self.size = size- self.corrupt = corrupt- self.sourceGeneration = sourceGeneration- self.sourceIsFresh = sourceIsFresh- self.fileIdentifier = fileIdentifier- self.boundaryHash = boundaryHash- self.boundaryVerifiedAtNanoseconds = boundaryVerifiedAtNanoseconds- }-- init(from decoder: Decoder) throws {- let container = try decoder.container(keyedBy: CodingKeys.self)- offset = try container.decodeIfPresent(UInt64.self, forKey: .offset) ?? 0- size = try container.decodeIfPresent(UInt64.self, forKey: .size) ?? 0- corrupt = try container.decodeIfPresent(Int.self, forKey: .corrupt) ?? 0- sourceGeneration = try container.decodeIfPresent(String.self, forKey: .sourceGeneration)- sourceIsFresh = try container.decodeIfPresent(Bool.self, forKey: .sourceIsFresh) ?? false- fileIdentifier = try container.decodeIfPresent(UInt64.self, forKey: .fileIdentifier)- boundaryHash = try container.decodeIfPresent(String.self, forKey: .boundaryHash)- boundaryVerifiedAtNanoseconds = try container.decodeIfPresent(- Int64.self,- forKey: .boundaryVerifiedAtNanoseconds- )- }-}--/// maintenance.json 的全局状态, pending 表示可增量, dirty 表示需全量重建-nonisolated struct WorkflowMaintenanceState: Codable, Equatable {- /// 原始事件到每日聚合的算法版本, 变化时统一从原始 JSONL 重建- static let currentAggregationSchema = 9-- var schema: Int- var pending: [String]- var dirty: [String]- var days: [String: WorkflowDayMaintenanceState]-- init(- schema: Int = Self.currentAggregationSchema,- pending: [String] = [],- dirty: [String] = [],- days: [String: WorkflowDayMaintenanceState] = [:]- ) {- self.schema = schema- self.pending = Self.normalizedDates(pending)- self.dirty = Self.normalizedDates(dirty)- self.days = days- }-- init(from decoder: Decoder) throws {- let container = try decoder.container(keyedBy: CodingKeys.self)- // 缺少版本只能说明来源更旧, 不能乐观视为当前算法- schema = try container.decodeIfPresent(Int.self, forKey: .schema) ?? 0- pending = try Self.normalizedDates(container.decodeIfPresent([String].self, forKey: .pending) ?? [])- dirty = try Self.normalizedDates(container.decodeIfPresent([String].self, forKey: .dirty) ?? [])- days = try container.decodeIfPresent([String: WorkflowDayMaintenanceState].self, forKey: .days) ?? [:]- }-- /// 返回状态是否有实际变化, 便于调用方跳过无谓的落盘- @discardableResult- mutating func markPending(_ dateKey: String) -> Bool {- let newPending = Self.inserting(dateKey, into: pending)- let changed = newPending != pending || days[dateKey] == nil- pending = newPending- ensureDayState(for: dateKey)- return changed- }-- @discardableResult- mutating func markDirty(_ dateKey: String) -> Bool {- markDirty(contentsOf: [dateKey])- }-- /// 批量标脏一次性归一化, 避免逐个插入的重复排序与校验- @discardableResult- mutating func markDirty(contentsOf dateKeys: [String]) -> Bool {- guard !dateKeys.isEmpty else {- return false- }-- let newDirty = Self.normalizedDates(dirty + dateKeys)- var changed = newDirty != dirty- dirty = newDirty-- for dateKey in dateKeys where days[dateKey] == nil {- days[dateKey] = WorkflowDayMaintenanceState()- changed = true- }-- return changed- }-- mutating func removePending(_ dateKey: String) {- pending.removeAll { $0 == dateKey }- }-- mutating func removeDirty(_ dateKey: String) {- dirty.removeAll { $0 == dateKey }- }-- mutating func remove(_ dateKey: String) {- removePending(dateKey)- removeDirty(dateKey)- days.removeValue(forKey: dateKey)- }-- @discardableResult- mutating func ensureSourceGeneration(- for dateKey: String,- fileIdentifier: UInt64?- ) -> Bool {- var day = days[dateKey] ?? WorkflowDayMaintenanceState()- var changed = false-- if day.sourceGeneration == nil {- day.sourceGeneration = Self.newSourceGeneration()- day.sourceIsFresh = false- changed = true- }- if day.fileIdentifier == nil, let fileIdentifier {- day.fileIdentifier = fileIdentifier- changed = true- }-- days[dateKey] = day- return changed- }-- /// 记下 boundaryHash 重算通过时文件的 mtime, 供下一轮跳过重算- @discardableResult- mutating func recordBoundaryVerification(for dateKey: String, at nanoseconds: Int64) -> Bool {- guard var day = days[dateKey], day.boundaryVerifiedAtNanoseconds != nanoseconds else {- return false- }-- day.boundaryVerifiedAtNanoseconds = nanoseconds- days[dateKey] = day- return true- }-- mutating func startNewSourceGeneration(- for dateKey: String,- isFresh: Bool,- fileIdentifier: UInt64?- ) {- days[dateKey] = WorkflowDayMaintenanceState(- sourceGeneration: Self.newSourceGeneration(),- sourceIsFresh: isFresh,- fileIdentifier: fileIdentifier- )- markDirty(dateKey)- }-- mutating func normalize() -> Bool {- let previousPending = pending- let previousDirty = dirty- let previousDays = days-- pending = Self.normalizedDates(pending)- dirty = Self.normalizedDates(dirty)- days = days.filter { WorkflowStorage.isValidDateKey($0.key) }-- return previousPending != pending || previousDirty != dirty || previousDays != days- }-- private mutating func ensureDayState(for dateKey: String) {- if days[dateKey] == nil {- days[dateKey] = WorkflowDayMaintenanceState()- }- }-- private static func inserting(_ dateKey: String, into dates: [String]) -> [String] {- normalizedDates(dates + [dateKey])- }-- private static func normalizedDates(_ dates: [String]) -> [String] {- Set(dates.filter(WorkflowStorage.isValidDateKey)).sorted()- }-- private static func newSourceGeneration() -> String {- UUID().uuidString.lowercased()- }-}--/// daily.jsonl 某一时刻的 stat 快照与当天日期键, 用于跳过稳态下的重复归一化-private nonisolated struct WorkflowDailyLogStamp: Equatable {- let size: UInt64- let identifier: UInt64?- let dayKey: String-}--/// 全量重建与安全增量使用不同初始状态, 避免用 nil 隐含任务语义-private nonisolated enum WorkflowMaintenanceMode {- case rebuild(WorkflowHookCountAvailability)- case append(WorkflowDailyAggregate)-}--// 单次维护任务: 从 startOffset 读到 size, 可基于已有聚合继续追加-private nonisolated struct WorkflowMaintenanceTask {- let dateKey: String- let startOffset: UInt64- let size: UInt64- let mode: WorkflowMaintenanceMode- let existingCorrupt: Int- let sourceGeneration: String?- let sourceIsFresh: Bool- let fileIdentifier: UInt64?-- var baseEventCount: Int {- switch mode {- case .rebuild:- 0- case let .append(aggregate):- aggregate.eventCount ?? 0- }- }-}--/// 维护任务的提交结果, corrupt 统计保留给后续诊断-private nonisolated struct WorkflowMaintenanceResult {- let dateKey: String- let aggregate: WorkflowDailyAggregate- let size: UInt64- let corrupt: Int- let fileIdentifier: UInt64?- let boundaryHash: String?-}--nonisolated struct WorkflowDataRebuildSummary: Equatable, Sendable {- let rebuiltDateCount: Int- let eventCount: Int- let corruptLineCount: Int- let isSyncReplacementPending: Bool- /// 未完成的日期, 已标脏并会由常规维护自动重建- let failedDateKeys: [String]- let didFailSyncReplacementMarking: Bool- let tokenTurnCount: Int- let didFailTokenRebuild: Bool-}--private nonisolated struct WorkflowDataRebuildOutcome {- let snapshot: WorkflowSnapshot- let summary: WorkflowDataRebuildSummary-}--private nonisolated enum WorkflowDataRebuildError: LocalizedError {- case sourceUnavailable- case sourceChanged-- var errorDescription: String? {- switch self {- case .sourceUnavailable:- String(localized: "workflow.rebuild.error.source-unavailable")- case .sourceChanged:- String(localized: "workflow.rebuild.error.source-changed")- }- }-}--/// UI 层的工作流状态, 节流普通刷新, 维护刷新由上层调度器合并-@MainActor-final class WorkflowViewModel: ObservableObject {- @Published private(set) var snapshot = WorkflowSnapshot.empty-- private static let minimumRefreshInterval: TimeInterval = 5-- private let service: WorkflowService- private var isRefreshing = false- private let refreshCoordinator = RefreshTaskCoordinator()- private var lastRefreshedAt: Date?-- init(service: WorkflowService = WorkflowService()) {- self.service = service- }-- deinit {- refreshCoordinator.cancel()- }-- func refreshIfNeeded() {- guard Date().timeIntervalSince(lastRefreshedAt ?? .distantPast) > Self.minimumRefreshInterval else {- return- }-- refresh()- }-- func refresh() {- if isRefreshing {- return- }-- refreshCoordinator.run(- setRefreshing: { [weak self] in self?.isRefreshing = $0 },- operation: { [service = self.service] in await service.loadSnapshot() },- commit: { [weak self] snapshot in- self?.snapshot = snapshot- self?.lastRefreshedAt = Date()- }- )- }-- /// 由 WorkflowSyncScheduler 串行调度, 无需自行判断并发, 只执行一次明确的维护刷新- /// 返回这一轮的维护计数, 空转为 nil; 收尾日志由调用方按它决定记不记- func refreshMaintenance(- synchronize: Bool,- trigger: LogTrigger- ) async -> WorkflowMaintenanceCounts? {- refreshCoordinator.cancel()- isRefreshing = true- defer {- isRefreshing = false- }-- let result = await service.loadSnapshotWithMaintenance(- synchronize: synchronize,- trigger: trigger- )-- snapshot = result.snapshot- lastRefreshedAt = Date()- return result.counts- }-- func rebuildData(- for dateKeys: [String],- synchronize: Bool- ) async throws -> WorkflowDataRebuildSummary {- refreshCoordinator.cancel()- isRefreshing = true- defer {- isRefreshing = false- }-- let outcome = try await service.rebuildData(- for: dateKeys,- synchronize: synchronize- )- snapshot = outcome.snapshot- lastRefreshedAt = Date()- return outcome.summary- }-}diff --git a/CodexBar/Services/Workflow/WorkflowSyncService.swift b/CodexBar/Services/Workflow/WorkflowSyncService.swiftdeleted file mode 100644index 7ccc969..0000000--- a/CodexBar/Services/Workflow/WorkflowSyncService.swift+++ /dev/null@@ -1,1451 +0,0 @@-import CloudKit-import CryptoKit-import Foundation-import IOKit-import os-import Security--nonisolated enum WorkflowSyncCloudKit {- private static let containerIdentifier = "iCloud.app.zabrian.codexbar"-- static func makeContainer() -> CKContainer {- CKContainer(identifier: containerIdentifier)- }-}--/// 同步失败时定位到哪一步, 只用于日志-private nonisolated enum WorkflowSyncStage: String {- case zone- case device- case fetch- case upload- case tokens- case prune-}--/// 将本机 daily.jsonl 中不含 sessionIds 和 turnIds 的聚合行同步到 CloudKit private database-actor WorkflowSyncService {- private let database: CKDatabase- private let fileManager: FileManager- private let directoryURL: URL- private let tokenHistorySync: CodexTokenHistorySync-- // zone 存在性和 account salt 首次确认后跨轮缓存, 避免每轮同步都重复请求- // 任一轮同步失败时作废: iCloud 账号切换必然伴随请求报错, 下一轮会重新确认- private var isSyncZoneConfirmed = false- private var cachedAccountSalt: Data?-- init(- container: CKContainer = WorkflowSyncCloudKit.makeContainer(),- fileManager: FileManager = .default,- directoryURL: URL = WorkflowStorage.syncDirectoryURL()- ) {- database = container.privateCloudDatabase- self.fileManager = fileManager- self.directoryURL = directoryURL- tokenHistorySync = CodexTokenHistorySync(- database: container.privateCloudDatabase,- directoryURL: directoryURL.appendingPathComponent("Tokens")- )- }-- // MARK: - 同步入口-- func snapshotFromCacheIfEnabled(localTokenTurns: [CodexTokenTurn] = []) async -> WorkflowSyncSnapshot {- guard WorkflowSyncSettings.isEnabled() else {- return .disabled- }-- let state = loadState()- return await snapshot(from: state, localTokenTurns: localTokenTurns)- }-- /// 显式重建后, 将所选日期标记为当前设备云端贡献的权威替换来源- func markReplacementNeeded(for dates: [String]) throws {- let validDates = Set(dates.filter(WorkflowStorage.isValidDateKey))- guard !validDates.isEmpty else {- return- }-- var state = loadState()- state.replacementDates = Set(state.replacementDates)- .union(validDates)- .sorted()- for date in validDates {- state.hashByDate.removeValue(forKey: date)- }- try saveState(state)- }-- func hasPendingReplacement(for dates: [String]) -> Bool {- !Set(loadState().replacementDates).isDisjoint(with: dates)- }-- func tokenRecoveryBaselineIfEnabled() async -> CodexTokenHistoryBaseline? {- guard WorkflowSyncSettings.isEnabled() else { return nil }- return await tokenHistorySync.recoveryBaseline(accountScopedDeviceID: loadState().deviceID)- }-- func hasPendingTokenUpdates(local: [CodexTokenTurn]) async -> Bool {- await tokenHistorySync.hasPendingUpdates(local: local, accountScopedDeviceID: loadState().deviceID)- }-- func synchronizeIfEnabled(- localAggregates: [WorkflowDailyAggregate],- localTokenTurns: [CodexTokenTurn] = [],- trigger: LogTrigger- ) async -> WorkflowSyncSnapshot {- guard WorkflowSyncSettings.isEnabled() else {- logSyncSkipped(trigger: trigger)- return .disabled- }-- AppLog.sync.notice("同步开始: trigger=\(trigger.rawValue, privacy: .public)")- let duration = LogDuration()- var stage = WorkflowSyncStage.zone- var didSucceed = false- var failureMessage: String?- Self.postSyncNotification(.workflowSyncDidStart)- defer {- Self.postSyncNotification(- .workflowSyncDidFinish,- didSucceed: didSucceed,- failureMessage: failureMessage- )- }-- var state = loadState()-- do {- try await ensureSyncZoneExists()- stage = .device- let deviceID = try await resolveCurrentDeviceID()- try resetStateIfDeviceChanged(deviceID, state: &state)- try await migrateStateIfNeeded(&state)-- stage = .fetch- let localByDate = Self.syncedAggregatesByDate(localAggregates)- try await refreshCacheBeforeUpload(- localByDate: localByDate,- deviceID: deviceID,- state: &state- )-- stage = .upload- let confirmedDates = try await uploadChangedAggregates(- localByDate: localByDate,- remoteRecords: loadCachedRecords(),- state: &state- )- try finalizeUpload(- confirmedDates: confirmedDates,- state: &state- )-- try await refreshCacheFromRemote()- stage = .tokens- try await tokenHistorySync.synchronize(- local: localTokenTurns, accountScopedDeviceID: deviceID, salt: accountSalt(), zoneID: syncZoneID- )- stage = .prune- let deletedCount = try await pruneCurrentDeviceRecordsIfNeeded(- deviceID: deviceID,- state: &state- )- try saveState(state)- didSucceed = true- // confirmed 是本地与远端已对齐的日期数, 含哈希未变而无需上传的那些- // 它小于 local 就说明这一轮还有日期没落到云上- let elapsed = duration.elapsed- logSyncCompleted(- trigger: trigger,- localCount: localByDate.count,- confirmedCount: confirmedDates.count,- deletedCount: deletedCount,- elapsed: elapsed- )- } catch {- let reason = WorkflowSyncFailureReason.classify(error)- let elapsed = duration.elapsed- logSyncFailed(- trigger: trigger,- stage: stage,- elapsed: elapsed,- reason: reason,- detail: error.localizedDescription- )- invalidateAccountScopedCaches()- failureMessage = reason.message- try? saveState(state)- }-- let latestState = loadState()- return await snapshot(from: latestState, localTokenTurns: localTokenTurns)- }-- private func logSyncSkipped(trigger: LogTrigger) {- let details = LogFields.joined(- "trigger=\(trigger.rawValue)",- "reason=syncOff"- )- AppLog.sync.notice("同步已跳过: \(details, privacy: .public)")- }-- private func logSyncCompleted(- trigger: LogTrigger,- localCount: Int,- confirmedCount: Int,- deletedCount: Int,- elapsed: String- ) {- let details = LogFields.joined(- "trigger=\(trigger.rawValue)",- "local=\(localCount)",- "confirmed=\(confirmedCount)",- "deleted=\(deletedCount)",- "elapsed=\(elapsed)"- )- AppLog.sync.notice("同步完成: \(details, privacy: .public)")- }-- private func logSyncFailed(- trigger: LogTrigger,- stage: WorkflowSyncStage,- elapsed: String,- reason: WorkflowSyncFailureReason,- detail: String- ) {- let details = LogFields.joined(- "trigger=\(trigger.rawValue)",- "stage=\(stage.rawValue)",- "elapsed=\(elapsed)",- "reason=\(reason.rawValue)",- "detail=\(detail)"- )- AppLog.sync.error("同步失败: \(details, privacy: .public)")- }-- private func refreshCacheBeforeUpload(- localByDate: [String: LocalSyncAggregate],- deviceID: String,- state: inout WorkflowSyncState- ) async throws {- guard !state.replacementDates.isEmpty else {- try await refreshCacheFromRemote()- return- }-- // 替换前全量拉取, 避免增量缓存遗漏同设备同日期的旧 generation- try await rebuildCacheFromRemote()- try await preparePendingReplacements(- localByDate: localByDate,- deviceID: deviceID,- state: &state- )- }-- private func finalizeUpload(- confirmedDates: Set<String>,- state: inout WorkflowSyncState- ) throws {- let completedReplacementDates = Set(state.replacementDates).intersection(confirmedDates)- if !completedReplacementDates.isEmpty {- state.replacementDates.removeAll { completedReplacementDates.contains($0) }- try saveState(state)- }- }-- private func resetStateIfDeviceChanged(- _ deviceID: String,- state: inout WorkflowSyncState- ) throws {- guard state.deviceID != deviceID else {- return- }-- try removeCursorIfPresent()- try saveCachedRecords([])-- let resetState = WorkflowSyncState(- deviceID: deviceID,- replacementDates: state.replacementDates- )- try saveState(resetState)- state = resetState- }-- private static func syncedAggregatesByDate(- _ aggregates: [WorkflowDailyAggregate]- ) -> [String: LocalSyncAggregate] {- aggregates.reduce(into: [String: LocalSyncAggregate]()) { result, aggregate in- result[aggregate.date] = LocalSyncAggregate(- aggregate: aggregate.syncedAggregate,- sourceIsFresh: aggregate.sourceIsFresh- )- }- }-- private func snapshot(from state: WorkflowSyncState, localTokenTurns: [CodexTokenTurn]) async -> WorkflowSyncSnapshot {- guard let deviceID = state.deviceID else {- return .disabled- }-- let replacementDates = Set(state.replacementDates)- let records = Self.filteredRetained(records: loadCachedRecords()).filter { record in- record.deviceID != deviceID || !replacementDates.contains(record.date)- }-- return await WorkflowSyncSnapshot(- records: records,- currentDeviceID: deviceID,- tokenUsageByDate: tokenHistorySync.snapshot(local: localTokenTurns, accountScopedDeviceID: deviceID)- )- }-}--private extension WorkflowSyncService {- struct LocalSyncAggregate {- let aggregate: WorkflowSyncedDailyAggregate- let sourceIsFresh: Bool- }-- struct PendingUpload {- let date: String- let aggregate: WorkflowSyncedDailyAggregate- let sourceIsFresh: Bool- let hash: String- }-- struct PendingRecord {- let upload: PendingUpload- let legacyRecordID: CKRecord.ID- let generationRecordID: CKRecord.ID?- }-- struct RecordToSave {- let upload: PendingUpload- let record: CKRecord- }-- struct ConfirmedHash {- let date: String- let hash: String- let didUpload: Bool- }-- enum Metrics {- static let syncSchemaVersion = 6- static let syncZoneName = "CodexBarZone"- static let saltByteCount = 32- static let recordFetchLimit = 200- static let queryFetchLimit = 200- static let uploadBatchSize = 25- static let uploadTimeBudget: TimeInterval = 20- }-- enum RecordTypes {- static let metadata = "CodexBarSyncMetadata"- static let dailyAggregate = "CodexBarDailyAggregate"- }-- enum FieldKeys {- static let salt = "salt"- static let schemaVersion = "schemaVersion"- static let deviceID = "deviceId"- static let date = "date"- static let sourceGeneration = "sourceGeneration"- static let eventCount = "eventCount"- static let sessionStartCount = "sessionStartCount"- static let sessionEndCount = "sessionEndCount"- static let userPromptSubmitCount = "userPromptSubmitCount"- static let stopCount = "stopCount"- static let interruptCount = "interruptCount"- static let preToolUseCount = "preToolUseCount"- static let postToolUseCount = "postToolUseCount"- static let permissionRequestCount = "permissionRequestCount"- static let preCompactCount = "preCompactCount"- static let postCompactCount = "postCompactCount"- static let subagentStartCount = "subagentStartCount"- static let subagentStopCount = "subagentStopCount"- static let sessionCount = "sessionCount"- static let turnCount = "turnCount"- static let projectCounts = "projectCounts"- static let modelCounts = "modelCounts"- static let updatedAt = "updatedAt"- }-- static let accountSaltRecordName = "accountSalt"-- var syncZoneID: CKRecordZone.ID {- CKRecordZone.ID(zoneName: Metrics.syncZoneName, ownerName: CKCurrentUserDefaultName)- }-- var accountSaltRecordID: CKRecord.ID {- CKRecord.ID(recordName: Self.accountSaltRecordName, zoneID: syncZoneID)- }-- nonisolated static func stateURL(in directoryURL: URL) -> URL {- directoryURL.appendingPathComponent("state.json", isDirectory: false)- }-- var stateURL: URL {- Self.stateURL(in: directoryURL)- }-- var cacheURL: URL {- directoryURL.appendingPathComponent("cache.jsonl", isDirectory: false)- }-- var cursorURL: URL {- directoryURL.appendingPathComponent("cursor.data", isDirectory: false)- }-- // MARK: - 上传-- func uploadChangedAggregates(- localByDate: [String: LocalSyncAggregate],- remoteRecords: [WorkflowSyncedDailyRecord],- state: inout WorkflowSyncState- ) async throws -> Set<String> {- guard let deviceID = state.deviceID else {- return []- }-- // 每个日期的 hash 是一次 JSON 编码加 SHA256, 本轮只算一次- // 既用来判定"和上次一样不必上传", 也直接填进待上传项- let localHashByDate = try localByDate.mapValues { try hash(for: $0.aggregate) }-- var confirmedDates = Set<String>()- for (date, hash) in localHashByDate where state.hashByDate[date] == hash {- confirmedDates.insert(date)- }-- let pendingUploads = makePendingUploads(- localByDate: localByDate,- localHashByDate: localHashByDate,- state: state- )- guard !pendingUploads.isEmpty else {- return confirmedDates- }-- let deadline = Date().addingTimeInterval(Metrics.uploadTimeBudget)-- for batchStart in stride(from: 0, to: pendingUploads.count, by: Metrics.uploadBatchSize) {- guard !Task.isCancelled, Date() < deadline else {- break- }-- let batchEnd = min(batchStart + Metrics.uploadBatchSize, pendingUploads.count)- let batch = Array(pendingUploads[batchStart ..< batchEnd])- let confirmedBatch: [ConfirmedHash]- do {- confirmedBatch = try await processUploadBatch(- batch,- deviceID: deviceID,- remoteRecords: remoteRecords- )- } catch {- try markPendingForRetry(batch, state: &state)- throw error- }-- try applyConfirmedHashes(confirmedBatch, to: &state)- confirmedDates.formUnion(confirmedBatch.map(\.date))- }-- return confirmedDates- }-- func markPendingForRetry(- _ pendingUploads: [PendingUpload],- state: inout WorkflowSyncState- ) throws {- for upload in pendingUploads {- state.hashByDate.removeValue(forKey: upload.date)- }- try saveState(state)- }-- func preparePendingReplacements(- localByDate: [String: LocalSyncAggregate],- deviceID: String,- state: inout WorkflowSyncState- ) async throws {- let replacementDates = Set(state.replacementDates).intersection(localByDate.keys)- guard !replacementDates.isEmpty else {- return- }-- let cachedRecords = loadCachedRecords()- let recordsToReplace = cachedRecords.filter {- $0.deviceID == deviceID && replacementDates.contains($0.date)- }- var recordIDs = Set(recordsToReplace.map {- CKRecord.ID(recordName: $0.id, zoneID: syncZoneID)- })-- for date in replacementDates {- recordIDs.insert(recordID(deviceID: deviceID, date: date))- if let generation = localByDate[date]?.aggregate.sourceGeneration {- recordIDs.insert(recordID(deviceID: deviceID, date: date, generation: generation))- }- }-- try await deleteRecords(Array(recordIDs))-- try saveCachedRecords(cachedRecords.filter {- $0.deviceID != deviceID || !replacementDates.contains($0.date)- })- for date in replacementDates {- state.hashByDate.removeValue(forKey: date)- }- try saveState(state)- }-- func deleteRecords(_ recordIDs: [CKRecord.ID]) async throws {- for batchStart in stride(from: 0, to: recordIDs.count, by: Metrics.uploadBatchSize) {- let batchEnd = min(batchStart + Metrics.uploadBatchSize, recordIDs.count)- let batch = Array(recordIDs[batchStart ..< batchEnd])- let result = try await database.modifyRecords(- saving: [],- deleting: batch,- savePolicy: .changedKeys,- atomically: false- )-- for recordID in batch {- switch result.deleteResults[recordID] {- case .success:- continue- case let .failure(error as CKError) where error.code == .unknownItem:- continue- case let .failure(error):- throw error- case nil:- throw WorkflowSyncError.missingRecordResult- }- }- }- }-- func applyConfirmedHashes(- _ confirmedBatch: [ConfirmedHash],- to state: inout WorkflowSyncState- ) throws {- guard !confirmedBatch.isEmpty else {- return- }-- for confirmation in confirmedBatch {- state.hashByDate[confirmation.date] = confirmation.hash- }-- if confirmedBatch.contains(where: \.didUpload) {- state.lastUploadAt = Date()- }- try saveState(state)- }-- /// hash 由调用方一次算好传进来, 这里只做筛选- func makePendingUploads(- localByDate: [String: LocalSyncAggregate],- localHashByDate: [String: String],- state: WorkflowSyncState- ) -> [PendingUpload] {- localByDate.compactMap { date, local in- guard let hash = localHashByDate[date],- state.hashByDate[date] != hash else {- return nil- }-- return PendingUpload(- date: date,- aggregate: local.aggregate,- sourceIsFresh: local.sourceIsFresh,- hash: hash- )- }- .sorted { $0.date < $1.date }- }-- /// 单条待上传记录落到哪个 CKRecord 上, 或者本轮不需要上传- private enum UploadTarget {- case skip- case save(CKRecord)- }-- /// 远端已有更完整的同源聚合, 或者同日已有记录且本地不是新鲜来源时都不覆盖- private func resolveUploadTarget(- _ pendingRecord: PendingRecord,- deviceID: String,- remoteRecords: [WorkflowSyncedDailyRecord],- existingRecords: [CKRecord.ID: Result<CKRecord, any Error>]- ) throws -> UploadTarget {- let legacyRecord = try Self.fetchedRecord(- from: existingRecords[pendingRecord.legacyRecordID]- )- let generationRecord: CKRecord? = if let recordID = pendingRecord.generationRecordID {- try Self.fetchedRecord(from: existingRecords[recordID])- } else {- nil- }- let fetchedRecords = [legacyRecord, generationRecord].compactMap(\.self)- let matchingRecord = fetchedRecords.first { record in- guard let remote = Self.remoteDailyRecord(from: record) else {- return false- }- return pendingRecord.upload.aggregate.matchesRemoteSource(remote.daily)- }-- if let matchingRecord,- let remoteAggregate = Self.remoteDailyRecord(from: matchingRecord)?.daily,- (remoteAggregate.eventCount ?? 0) > (pendingRecord.upload.aggregate.eventCount ?? 0),- pendingRecord.upload.aggregate.sourceGeneration != nil {- return .skip- }-- if let matchingRecord {- return .save(matchingRecord)- }-- // 上面两个分支都用不到它; 放在早退之后, 命中缓存的那些 pending 就不必扫一遍全量远端记录- var knownRemoteRecords = remoteRecords.filter {- $0.deviceID == deviceID && $0.date == pendingRecord.upload.date- }- for record in fetchedRecords.compactMap({ Self.remoteDailyRecord(from: $0) })- where !knownRemoteRecords.contains(where: { $0.id == record.id }) {- knownRemoteRecords.append(record)- }-- if knownRemoteRecords.isEmpty {- return .save(CKRecord(- recordType: RecordTypes.dailyAggregate,- recordID: pendingRecord.generationRecordID ?? pendingRecord.legacyRecordID- ))- }-- if pendingRecord.upload.sourceIsFresh,- let generationRecordID = pendingRecord.generationRecordID,- generationRecord == nil {- return .save(CKRecord(- recordType: RecordTypes.dailyAggregate,- recordID: generationRecordID- ))- }-- return .skip- }-- func processUploadBatch(- _ pendingUploads: [PendingUpload],- deviceID: String,- remoteRecords: [WorkflowSyncedDailyRecord]- ) async throws -> [ConfirmedHash] {- let pendingRecords: [PendingRecord] = pendingUploads.map { upload in- PendingRecord(- upload: upload,- legacyRecordID: recordID(deviceID: deviceID, date: upload.date),- generationRecordID: upload.aggregate.sourceGeneration.map { generation in- recordID(deviceID: deviceID, date: upload.date, generation: generation)- }- )- }- let recordIDs = Array(Set(pendingRecords.flatMap { pendingRecord in- [pendingRecord.legacyRecordID, pendingRecord.generationRecordID].compactMap(\.self)- }))- let existingRecords = try await database.records(for: recordIDs)- var confirmedHashes = [ConfirmedHash]()- var recordsToSave = [RecordToSave]()-- for pendingRecord in pendingRecords {- switch try resolveUploadTarget(- pendingRecord,- deviceID: deviceID,- remoteRecords: remoteRecords,- existingRecords: existingRecords- ) {- case .skip:- confirmedHashes.append(- ConfirmedHash(- date: pendingRecord.upload.date,- hash: pendingRecord.upload.hash,- didUpload: false- )- )- case let .save(record):- apply(pendingRecord.upload.aggregate, deviceID: deviceID, to: record)- recordsToSave.append(- RecordToSave(upload: pendingRecord.upload, record: record)- )- }- }-- guard !recordsToSave.isEmpty else {- return confirmedHashes- }-- let records = recordsToSave.map(\.record)-- let result = try await database.modifyRecords(- saving: records,- deleting: [],- savePolicy: .changedKeys,- atomically: false- )-- for pendingRecord in recordsToSave {- switch result.saveResults[pendingRecord.record.recordID] {- case .success:- confirmedHashes.append(- ConfirmedHash(- date: pendingRecord.upload.date,- hash: pendingRecord.upload.hash,- didUpload: true- )- )- case let .failure(error):- throw error- case nil:- throw WorkflowSyncError.missingRecordResult- }- }-- return confirmedHashes- }-- // MARK: - 拉取与缓存-- func refreshCacheFromRemote() async throws {- guard let token = try loadCursor() else {- try await rebuildCacheFromRemote()- return- }-- do {- try await applyZoneChangesToCache(- since: token,- cachedRecords: loadCachedRecords()- )- } catch {- // 增量拉取退化成全量重建, 代价高得多, 反复出现说明游标或缓存有问题- let details = LogFields.joined(- "detail=\(error.localizedDescription)",- "action=fullRebuild"- )- AppLog.sync.notice("增量拉取已降级: \(details, privacy: .public)")- try await rebuildCacheFromRemote()- }- }-- func applyZoneChangesToCache(- since initialToken: CKServerChangeToken?,- cachedRecords: [WorkflowSyncedDailyRecord]- ) async throws {- var cacheByID = Self.recordsByID(records: cachedRecords)- var token: CKServerChangeToken? = initialToken- var moreComing = true-- while moreComing {- let result = try await database.recordZoneChanges(- inZoneWith: syncZoneID,- since: token,- desiredKeys: nil,- resultsLimit: Metrics.recordFetchLimit- )-- try mergeChangedRecords(- result.modificationResultsByID.values,- into: &cacheByID- )- removeDeletedRecords(result.deletions, from: &cacheByID)-- token = result.changeToken- moreComing = result.moreComing- }-- try saveCachedRecords(- Self.filteredRetained(records: Array(cacheByID.values))- )- if let token {- try saveCursor(token)- }- }-- func rebuildCacheFromRemote() async throws {- try removeCursorIfPresent()- let syncedRecords = try await fetchAllRemoteDailyRecords()- let retainedRecords = Self.filteredRetained(records: syncedRecords)- try saveCachedRecords(retainedRecords)- await establishCursorBaseline(cachedRecords: retainedRecords)- }-- func fetchAllRemoteDailyRecords() async throws -> [WorkflowSyncedDailyRecord] {- let query = CKQuery(- recordType: RecordTypes.dailyAggregate,- predicate: NSPredicate(format: "TRUEPREDICATE")- )- query.sortDescriptors = [- NSSortDescriptor(key: FieldKeys.deviceID, ascending: true),- NSSortDescriptor(key: FieldKeys.date, ascending: true)- ]-- let matches = try await fetchAllRecordMatches(matching: query)- return try Self.remoteDailyRecords(from: matches)- }-- func fetchCurrentDeviceRecordIDsToPrune(- deviceID: String,- cutoffKey: String- ) async throws -> [CKRecord.ID] {- let query = CKQuery(- recordType: RecordTypes.dailyAggregate,- predicate: NSPredicate(- format: "%K == %@",- FieldKeys.deviceID,- deviceID- )- )-- let currentDeviceMatches = try await fetchAllRecordMatches(- matching: query,- desiredKeys: [FieldKeys.date]- )- return try currentDeviceMatches.compactMap { recordID, result in- let record = try result.get()- guard let date = record[FieldKeys.date] as? String,- WorkflowStorage.isValidDateKey(date) else {- // 无法进入保留窗口比较的当前设备记录是异常数据, 一并清理- return recordID- }-- return date < cutoffKey ? recordID : nil- }- }-- func fetchAllRecordMatches(- matching query: CKQuery,- desiredKeys: [String]? = nil- ) async throws -> [(CKRecord.ID, Result<CKRecord, Error>)] {- let firstPage = try await database.records(- matching: query,- inZoneWith: syncZoneID,- desiredKeys: desiredKeys,- resultsLimit: Metrics.queryFetchLimit- )- var matches = firstPage.matchResults- var cursor = firstPage.queryCursor-- while let currentCursor = cursor {- let page = try await database.records(- continuingMatchFrom: currentCursor,- desiredKeys: desiredKeys,- resultsLimit: Metrics.queryFetchLimit- )- matches.append(contentsOf: page.matchResults)- cursor = page.queryCursor- }-- return matches- }-- func establishCursorBaseline(cachedRecords: [WorkflowSyncedDailyRecord]) async {- do {- try await applyZoneChangesToCache(- since: nil,- cachedRecords: cachedRecords- )- } catch {- // 丢掉游标, 下次同步会从头拉一遍- let details = LogFields.joined(- "detail=\(error.localizedDescription)",- "action=dropCursor"- )- AppLog.sync.notice("游标基线已降级: \(details, privacy: .public)")- try? fileManager.removeItem(at: cursorURL)- }- }-- func mergeChangedRecords(- _ modificationResults: Dictionary<CKRecord.ID, Result<CKDatabase.RecordZoneChange.Modification, Error>>.Values,- into cacheByID: inout [String: WorkflowSyncedDailyRecord]- ) throws {- for modificationResult in modificationResults {- let modification = try modificationResult.get()- guard let record = Self.remoteDailyRecord(from: modification.record) else {- continue- }-- cacheByID[record.id] = record- }- }-- func removeDeletedRecords(- _ deletions: [CKDatabase.RecordZoneChange.Deletion],- from cacheByID: inout [String: WorkflowSyncedDailyRecord]- ) {- for deletion in deletions where deletion.recordType == RecordTypes.dailyAggregate {- guard let cacheID = cacheID(fromRecordName: deletion.recordID.recordName) else {- continue- }- cacheByID.removeValue(forKey: cacheID)- }- }-- @discardableResult- func pruneCurrentDeviceRecordsIfNeeded(- deviceID: String,- state: inout WorkflowSyncState- ) async throws -> Int {- let today = WorkflowStorage.dateKey(for: Date())- guard state.lastPrunedDate != today else {- return 0- }-- let cutoffKey = WorkflowStorage.dateKey(for: WorkflowStorage.retentionCutoffDate())- let expiredDates = Set(state.hashByDate.keys.filter { $0 < cutoffKey })- state.replacementDates.removeAll { $0 < cutoffKey }- var recordIDs = try await Set(- fetchCurrentDeviceRecordIDsToPrune(- deviceID: deviceID,- cutoffKey: cutoffKey- )- )- for date in expiredDates {- recordIDs.insert(- CKRecord.ID(- recordName: WorkflowSyncedDailyRecord.legacyRecordName(- deviceID: deviceID,- date: date- ),- zoneID: syncZoneID- )- )- }-- if !recordIDs.isEmpty {- try await deleteRecords(- recordIDs.sorted { $0.recordName < $1.recordName }- )- }-- for date in expiredDates {- state.hashByDate.removeValue(forKey: date)- }- state.lastPrunedDate = today- return recordIDs.count- }-- // MARK: - 账号与设备标识-- func resolveCurrentDeviceID() async throws -> String {- let salt = try await accountSalt()- let uuid = try Self.ioPlatformUUID()- let mac = HMAC<SHA256>.authenticationCode(- for: Data(uuid.utf8),- using: SymmetricKey(data: salt)- )- return Self.hexString(Data(mac))- }-- func accountSalt() async throws -> Data {- if let cachedAccountSalt {- return cachedAccountSalt- }-- let recordID = accountSaltRecordID- let salt: Data = if let fetched = try await fetchAccountSalt(recordID) {- fetched- } else {- try await createAccountSalt(recordID)- }-- cachedAccountSalt = salt- return salt- }-- func fetchAccountSalt(_ recordID: CKRecord.ID) async throws -> Data? {- let result = try await database.records(for: [recordID])- guard let record = try Self.fetchedRecord(from: result[recordID]) else {- return nil- }- guard let salt = record[FieldKeys.salt] as? Data,- salt.count == Metrics.saltByteCount else {- throw WorkflowSyncError.missingAccountSalt- }- return salt- }-- func createAccountSalt(_ recordID: CKRecord.ID) async throws -> Data {- let salt = try Self.randomSalt()- let record = CKRecord(recordType: RecordTypes.metadata, recordID: recordID)- record[FieldKeys.salt] = salt as CKRecordValue- record[FieldKeys.schemaVersion] = Metrics.syncSchemaVersion as CKRecordValue-- do {- let saveResult = try await database.modifyRecords(- saving: [record],- deleting: [],- savePolicy: .ifServerRecordUnchanged,- atomically: true- )- switch saveResult.saveResults[recordID] {- case .success:- return salt- case let .failure(error):- throw error- case nil:- throw WorkflowSyncError.missingRecordResult- }- } catch let error as CKError where error.code == .serverRecordChanged || error.code == .constraintViolation {- if let salt = try await fetchAccountSalt(recordID) {- return salt- }- }-- throw WorkflowSyncError.missingAccountSalt- }-- // MARK: - 记录与 zone 维护-- func ensureSyncZoneExists() async throws {- guard !isSyncZoneConfirmed else {- return- }-- if try await syncZoneExists() == false {- let zone = CKRecordZone(zoneID: syncZoneID)- let result = try await database.modifyRecordZones(saving: [zone], deleting: [])-- switch result.saveResults[syncZoneID] {- case .success:- break- case let .failure(error):- throw error- case nil:- throw WorkflowSyncError.missingRecordResult- }- }-- isSyncZoneConfirmed = true- }-- func invalidateAccountScopedCaches() {- isSyncZoneConfirmed = false- cachedAccountSalt = nil- }-- func syncZoneExists() async throws -> Bool {- do {- _ = try await database.recordZone(for: syncZoneID)- return true- } catch let error as CKError where error.code == .zoneNotFound || error.code == .unknownItem {- return false- }- }-- func apply(- _ aggregate: WorkflowSyncedDailyAggregate,- deviceID: String,- to record: CKRecord- ) {- record[FieldKeys.schemaVersion] = Metrics.syncSchemaVersion as CKRecordValue- record[FieldKeys.deviceID] = deviceID as CKRecordValue- record[FieldKeys.date] = aggregate.date as CKRecordValue- record[FieldKeys.sourceGeneration] = aggregate.sourceGeneration as CKRecordValue?- record[FieldKeys.eventCount] = aggregate.eventCount as CKRecordValue?- record[FieldKeys.sessionStartCount] = aggregate.sessionStartCount as CKRecordValue?- record[FieldKeys.sessionEndCount] = aggregate.sessionEndCount as CKRecordValue?- record[FieldKeys.userPromptSubmitCount] = aggregate.userPromptSubmitCount as CKRecordValue?- record[FieldKeys.stopCount] = aggregate.stopCount as CKRecordValue?- record[FieldKeys.interruptCount] = aggregate.interruptCount as CKRecordValue?- record[FieldKeys.preToolUseCount] = aggregate.preToolUseCount as CKRecordValue?- record[FieldKeys.postToolUseCount] = aggregate.postToolUseCount as CKRecordValue?- record[FieldKeys.permissionRequestCount] = aggregate.permissionRequestCount as CKRecordValue?- record[FieldKeys.preCompactCount] = aggregate.preCompactCount as CKRecordValue?- record[FieldKeys.postCompactCount] = aggregate.postCompactCount as CKRecordValue?- record[FieldKeys.subagentStartCount] = aggregate.subagentStartCount as CKRecordValue?- record[FieldKeys.subagentStopCount] = aggregate.subagentStopCount as CKRecordValue?- record[FieldKeys.sessionCount] = aggregate.sessionCount as CKRecordValue?- record[FieldKeys.turnCount] = aggregate.turnCount as CKRecordValue?- record[FieldKeys.projectCounts] = Self.countsData(aggregate.projectCounts) as CKRecordValue- record[FieldKeys.modelCounts] = Self.countsData(aggregate.modelCounts) as CKRecordValue- record[FieldKeys.updatedAt] = Date() as CKRecordValue- }-- func recordID(deviceID: String, date: String) -> CKRecord.ID {- recordID(deviceID: deviceID, date: date, generation: nil)- }-- func recordID(- deviceID: String,- date: String,- generation: String?- ) -> CKRecord.ID {- CKRecord.ID(- recordName: recordName(deviceID: deviceID, date: date, generation: generation),- zoneID: syncZoneID- )- }-- func recordName(- deviceID: String,- date: String,- generation: String?- ) -> String {- let legacyName = WorkflowSyncedDailyRecord.legacyRecordName(- deviceID: deviceID,- date: date- )- return generation.map { "\(legacyName)_\($0)" } ?? legacyName- }-- func cacheID(fromRecordName recordName: String) -> String? {- recordName.isEmpty ? nil : recordName- }-- func hash(for aggregate: WorkflowSyncedDailyAggregate) throws -> String {- let digest = try SHA256.hash(data: aggregate.jsonLineData())- return Self.hexString(Data(digest))- }-- nonisolated static func postSyncNotification(- _ name: Notification.Name,- didSucceed: Bool? = nil,- failureMessage: String? = nil- ) {- Task { @MainActor in- var userInfo = [String: Any]()- if let didSucceed {- userInfo[WorkflowSyncNotificationKey.didSucceed] = didSucceed- }- if let failureMessage {- userInfo[WorkflowSyncNotificationKey.failureMessage] = failureMessage- }-- NotificationCenter.default.post(- name: name,- object: nil,- userInfo: userInfo.isEmpty ? nil : userInfo- )- }- }-}--extension WorkflowSyncService {- /// 设置页读取最近上传时间, 与内部 loadState 使用同一 schema 校验口径- nonisolated static func loadLastUploadAt() -> Date? {- loadState(at: stateURL(in: WorkflowStorage.syncDirectoryURL())).lastUploadAt- }-}--private extension WorkflowSyncService {- func loadState() -> WorkflowSyncState {- Self.loadState(at: stateURL)- }-- func migrateStateIfNeeded(_ state: inout WorkflowSyncState) async throws {- guard state.schema == WorkflowSyncState.previousSchema else {- return- }-- try await rebuildCacheFromRemote()-- var migratedState = state- migratedState.schema = WorkflowSyncState.currentSchema- try saveState(migratedState)- state = migratedState- }-- nonisolated static func loadState(at url: URL) -> WorkflowSyncState {- guard let data = try? Data(contentsOf: url), !data.isEmpty,- let state = try? JSONDecoder().decode(WorkflowSyncState.self, from: data) else {- return WorkflowSyncState()- }- guard WorkflowSyncState.supports(state.schema) else {- return WorkflowSyncState()- }- return state- }-- func saveState(_ state: WorkflowSyncState) throws {- try ensureSyncDirectoryExists()- let data = try JSONLines.stableEncoder.encode(state)- try data.write(to: stateURL, options: .atomic)- }-- func loadCachedRecords() -> [WorkflowSyncedDailyRecord] {- guard let data = try? Data(contentsOf: cacheURL), !data.isEmpty else {- return []- }-- return JSONLines.decode(from: data)- }-- func saveCachedRecords(_ records: [WorkflowSyncedDailyRecord]) throws {- try ensureSyncDirectoryExists()-- let encoder = JSONLines.stableEncoder- let data = try records- .sorted { lhs, rhs in- if lhs.deviceID == rhs.deviceID {- if lhs.date == rhs.date {- return lhs.id < rhs.id- }- return lhs.date < rhs.date- }- return lhs.deviceID < rhs.deviceID- }- .reduce(into: Data()) { result, record in- try result.append(encoder.encode(record))- result.append(0x0A)- }- try data.write(to: cacheURL, options: .atomic)- }-- func loadCursor() throws -> CKServerChangeToken? {- guard let data = try? Data(contentsOf: cursorURL), !data.isEmpty else {- return nil- }-- return try NSKeyedUnarchiver.unarchivedObject(- ofClass: CKServerChangeToken.self,- from: data- )- }-- func saveCursor(_ token: CKServerChangeToken) throws {- try ensureSyncDirectoryExists()- let data = try NSKeyedArchiver.archivedData(- withRootObject: token,- requiringSecureCoding: true- )- try data.write(to: cursorURL, options: .atomic)- }-- func removeCursorIfPresent() throws {- guard fileManager.fileExists(atPath: cursorURL.path) else {- return- }- try fileManager.removeItem(at: cursorURL)- }-- func ensureSyncDirectoryExists() throws {- try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)- }-}--private extension WorkflowSyncService {- static func remoteDailyRecords(- from matchResults: [(CKRecord.ID, Result<CKRecord, Error>)]- ) throws -> [WorkflowSyncedDailyRecord] {- try matchResults.compactMap { _, result in- try remoteDailyRecord(from: result.get())- }- }-- static func remoteDailyRecord(from record: CKRecord) -> WorkflowSyncedDailyRecord? {- guard record.recordType == RecordTypes.dailyAggregate,- let deviceID = record[FieldKeys.deviceID] as? String,- let date = record[FieldKeys.date] as? String,- WorkflowStorage.isValidDateKey(date) else {- return nil- }-- let aggregate = WorkflowSyncedDailyAggregate(- date: date,- sourceGeneration: record[FieldKeys.sourceGeneration] as? String,- eventCount: optionalIntValue(record[FieldKeys.eventCount]),- sessionStartCount: optionalIntValue(record[FieldKeys.sessionStartCount]),- sessionEndCount: optionalIntValue(record[FieldKeys.sessionEndCount]),- userPromptSubmitCount: optionalIntValue(record[FieldKeys.userPromptSubmitCount]),- stopCount: optionalIntValue(record[FieldKeys.stopCount]),- interruptCount: optionalIntValue(record[FieldKeys.interruptCount]),- preToolUseCount: optionalIntValue(record[FieldKeys.preToolUseCount]),- postToolUseCount: optionalIntValue(record[FieldKeys.postToolUseCount]),- permissionRequestCount: optionalIntValue(record[FieldKeys.permissionRequestCount]),- preCompactCount: optionalIntValue(record[FieldKeys.preCompactCount]),- postCompactCount: optionalIntValue(record[FieldKeys.postCompactCount]),- subagentStartCount: optionalIntValue(record[FieldKeys.subagentStartCount]),- subagentStopCount: optionalIntValue(record[FieldKeys.subagentStopCount]),- sessionCount: optionalIntValue(record[FieldKeys.sessionCount]),- turnCount: optionalIntValue(record[FieldKeys.turnCount]),- projectCounts: counts(from: record[FieldKeys.projectCounts]),- modelCounts: counts(from: record[FieldKeys.modelCounts])- )-- return WorkflowSyncedDailyRecord(- deviceID: deviceID,- daily: aggregate,- updatedAt: record[FieldKeys.updatedAt] as? Date ?? record.modificationDate,- recordName: record.recordID.recordName- )- }-- static func fetchedRecord(- from result: Result<CKRecord, Error>?- ) throws -> CKRecord? {- switch result {- case let .success(record):- return record- case let .failure(error as CKError) where error.code == .unknownItem:- return nil- case let .failure(error):- throw error- case nil:- throw WorkflowSyncError.missingRecordResult- }- }-- static func filteredRetained(- records: [WorkflowSyncedDailyRecord]- ) -> [WorkflowSyncedDailyRecord] {- let cutoffKey = WorkflowStorage.dateKey(for: WorkflowStorage.retentionCutoffDate())- return records.filter { $0.date >= cutoffKey }- }-- static func recordsByID(- records: [WorkflowSyncedDailyRecord]- ) -> [String: WorkflowSyncedDailyRecord] {- filteredRetained(records: records)- .reduce(into: [String: WorkflowSyncedDailyRecord]()) { result, record in- result[record.id] = record- }- }-- static func optionalIntValue(_ value: CKRecordValue?) -> Int? {- if let number = value as? NSNumber {- return number.intValue- }- if let value = value as? Int {- return value- }- return nil- }-- static func counts(from value: CKRecordValue?) -> [String: Int] {- guard let data = value as? Data,- let counts = try? JSONDecoder().decode([String: Int].self, from: data) else {- return [:]- }- return counts- }-- static func countsData(_ counts: [String: Int]) -> Data {- (try? JSONLines.stableEncoder.encode(counts)) ?? Data("{}".utf8)- }-- static func randomSalt() throws -> Data {- var bytes = [UInt8](repeating: 0, count: Metrics.saltByteCount)- let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)- guard status == errSecSuccess else {- throw WorkflowSyncError.randomSaltFailed- }- return Data(bytes)- }-- static func ioPlatformUUID() throws -> String {- let service = IOServiceGetMatchingService(- kIOMainPortDefault,- IOServiceMatching("IOPlatformExpertDevice")- )- guard service != 0 else {- throw WorkflowSyncError.missingIOPlatformUUID- }- defer {- IOObjectRelease(service)- }-- guard let value = IORegistryEntryCreateCFProperty(- service,- "IOPlatformUUID" as CFString,- kCFAllocatorDefault,- 0- )?.takeRetainedValue() as? String,- !value.isEmpty else {- throw WorkflowSyncError.missingIOPlatformUUID- }-- return value- }-- static func hexString(_ data: Data) -> String {- data.map { String(format: "%02x", $0) }.joined()- }-}--/// records 包含所有设备的日聚合, 不含 sessionIds 和 turnIds-/// currentDeviceId 用于展示时替换本机云端副本, 避免重复计数-nonisolated struct WorkflowSyncSnapshot: Equatable {- let records: [WorkflowSyncedDailyRecord]- let currentDeviceID: String?- var tokenUsageByDate: [String: CodexTokenUsage]?-- static let disabled = WorkflowSyncSnapshot(records: [], currentDeviceID: nil)-}--private nonisolated struct WorkflowSyncState: Codable, Equatable {- static let currentSchema = 4- static let previousSchema = 3-- static func supports(_ schema: Int) -> Bool {- schema == currentSchema || schema == previousSchema- }-- var schema: Int- var deviceID: String?- var hashByDate: [String: String]- var replacementDates: [String]- var lastUploadAt: Date?- var lastPrunedDate: String?-- init(- schema: Int = Self.currentSchema,- deviceID: String? = nil,- hashByDate: [String: String] = [:],- replacementDates: [String] = [],- lastUploadAt: Date? = nil,- lastPrunedDate: String? = nil- ) {- self.schema = schema- self.deviceID = deviceID- self.hashByDate = hashByDate- self.replacementDates = replacementDates- self.lastUploadAt = lastUploadAt- self.lastPrunedDate = lastPrunedDate- }-- init(from decoder: Decoder) throws {- let container = try decoder.container(keyedBy: CodingKeys.self)-- schema = try container.decodeIfPresent(Int.self, forKey: .schema) ?? Self.currentSchema- deviceID = try container.decodeIfPresent(String.self, forKey: .deviceID)- hashByDate = try container.decodeIfPresent([String: String].self, forKey: .hashByDate)- ?? [:]- let decodedReplacementDates = try container.decodeIfPresent(- [String].self,- forKey: .replacementDates- ) ?? []- replacementDates = Set(- decodedReplacementDates.filter(WorkflowStorage.isValidDateKey)- ).sorted()- lastUploadAt = try container.decodeIfPresent(Date.self, forKey: .lastUploadAt)- lastPrunedDate = try container.decodeIfPresent(String.self, forKey: .lastPrunedDate)- }-- private enum CodingKeys: String, CodingKey {- case schema- case deviceID = "deviceId"- case hashByDate- case replacementDates- case lastUploadAt- case lastPrunedDate- }-}--private nonisolated enum WorkflowSyncError: Error {- case missingAccountSalt- case missingIOPlatformUUID- case missingRecordResult- case randomSaltFailed-}diff --git a/CodexBar/Views/Log/LogPreview.swift b/CodexBar/Views/Log/LogPreview.swiftnew file mode 100644index 0000000..9f3858d--- /dev/null+++ b/CodexBar/Views/Log/LogPreview.swift@@ -0,0 +1,196 @@+import AppKit+import SwiftUI++// MARK: - JSON 预览与高亮++/// 日志预览文本, JSON 时会带基础语法高亮+struct LogCodePreview {+ let attributedText: NSAttributedString+ let language: String?+}++/// 将 JSON 格式化并做轻量 token 高亮, 非 JSON 保持纯文本+enum LogCodePreviewFormatter {+ private static let font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)+ private static var baseAttributes: [NSAttributedString.Key: Any] {+ [+ .font: font,+ .foregroundColor: NSColor.labelColor+ ]+ }++ private static let jsonReadingOptions: JSONSerialization.ReadingOptions = [.fragmentsAllowed]+ private static let jsonWritingOptions: JSONSerialization.WritingOptions = [+ .fragmentsAllowed,+ .prettyPrinted,+ .sortedKeys,+ .withoutEscapingSlashes+ ]+ private static let tokenRegex = try? NSRegularExpression(+ pattern: #""(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b|\b(?:true|false|null)\b|[{}\[\]:,]"#+ )++ static func preview(for text: String) -> LogCodePreview {+ if let formattedJSON = formattedJSON(text) {+ return LogCodePreview(+ attributedText: highlightedJSON(formattedJSON),+ language: "JSON"+ )+ }++ return LogCodePreview(+ attributedText: attributedPlainText(text),+ language: nil+ )+ }++ private static func formattedJSON(_ text: String) -> String? {+ guard let data = text.data(using: .utf8),+ let object = try? JSONSerialization.jsonObject(with: data, options: jsonReadingOptions),+ let output = try? JSONSerialization.data(+ withJSONObject: object,+ options: jsonWritingOptions+ ) else {+ return nil+ }++ return String(bytes: output, encoding: .utf8)+ }++ private static func attributedPlainText(_ text: String) -> NSAttributedString {+ NSAttributedString(+ string: text,+ attributes: baseAttributes+ )+ }++ private static func highlightedJSON(_ text: String) -> NSAttributedString {+ let attributedText = NSMutableAttributedString(+ string: text,+ attributes: baseAttributes+ )++ guard let tokenRegex else {+ return attributedText+ }++ let nsText = text as NSString+ let fullRange = NSRange(location: 0, length: nsText.length)+ tokenRegex.enumerateMatches(in: text, range: fullRange) { match, _, _ in+ guard let range = match?.range else {+ return+ }++ let token = nsText.substring(with: range)+ attributedText.addAttribute(+ .foregroundColor,+ value: color(for: token, in: nsText, range: range),+ range: range+ )+ }++ return attributedText+ }++ private static func color(for token: String, in text: NSString, range: NSRange) -> NSColor {+ if token.hasPrefix("\"") {+ return isJSONKey(in: text, after: range) ? .systemBlue : .systemGreen+ }++ if token == "true" || token == "false" {+ return .systemOrange+ }++ if token == "null" {+ return .secondaryLabelColor+ }++ if token.first?.isNumber == true || token.hasPrefix("-") {+ return .systemPurple+ }++ return .tertiaryLabelColor+ }++ private static func isJSONKey(in text: NSString, after range: NSRange) -> Bool {+ var cursor = range.location + range.length+ while cursor < text.length {+ guard let scalar = UnicodeScalar(Int(text.character(at: cursor))),+ CharacterSet.whitespacesAndNewlines.contains(scalar) else {+ break+ }+ cursor += 1+ }++ guard cursor < text.length else {+ return false+ }++ return text.character(at: cursor) == 58+ }+}++/// AppKit 文本视图承载完整日志, 支持横向滚动+struct LogCodePreviewView: NSViewRepresentable {+ let attributedText: NSAttributedString++ func makeNSView(context _: Context) -> NSScrollView {+ let scrollView = NSScrollView()+ scrollView.hasVerticalScroller = true+ scrollView.hasHorizontalScroller = true+ scrollView.autohidesScrollers = false+ scrollView.drawsBackground = true+ scrollView.backgroundColor = .textBackgroundColor++ let textView = NSTextView()+ textView.isEditable = false+ textView.isSelectable = true+ textView.isRichText = true+ textView.drawsBackground = true+ textView.backgroundColor = .textBackgroundColor+ textView.textContainerInset = NSSize(width: 12, height: 12)+ textView.minSize = NSSize(width: 0, height: scrollView.contentSize.height)+ textView.maxSize = NSSize(+ width: CGFloat.greatestFiniteMagnitude,+ height: CGFloat.greatestFiniteMagnitude+ )+ textView.isVerticallyResizable = true+ textView.isHorizontallyResizable = true+ textView.autoresizingMask = []+ textView.textContainer?.containerSize = NSSize(+ width: CGFloat.greatestFiniteMagnitude,+ height: CGFloat.greatestFiniteMagnitude+ )+ textView.textContainer?.widthTracksTextView = false++ scrollView.documentView = textView+ return scrollView+ }++ func updateNSView(_ scrollView: NSScrollView, context _: Context) {+ guard let textView = scrollView.documentView as? NSTextView else {+ return+ }++ textView.textStorage?.setAttributedString(attributedText)+ updateDocumentSize(for: textView, in: scrollView)+ }++ private func updateDocumentSize(for textView: NSTextView, in scrollView: NSScrollView) {+ guard let layoutManager = textView.layoutManager,+ let textContainer = textView.textContainer else {+ return+ }++ layoutManager.ensureLayout(for: textContainer)+ let usedRect = layoutManager.usedRect(for: textContainer)+ let inset = textView.textContainerInset+ let minimumSize = scrollView.contentSize+ let fittedSize = NSSize(+ width: max(ceil(usedRect.maxX + inset.width * 2), minimumSize.width),+ height: max(ceil(usedRect.maxY + inset.height * 2), minimumSize.height)+ )++ textView.setFrameSize(fittedSize)+ }+}diff --git a/CodexBar/Views/Log/LogView.swift b/CodexBar/Views/Log/LogView.swiftindex 965dfa9..0e287d5 100644--- a/CodexBar/Views/Log/LogView.swift+++ b/CodexBar/Views/Log/LogView.swift@@ -3,16 +3,25 @@ import SwiftUI/// app-server 交互日志窗口根视图struct LogView: View {- @ObservedObject var store: RequestLogStore+ @ObservedObject var store: AppServerLogViewModelvar body: some View {// 每轮渲染只取一次发布快照复用let entries = store.entriesVStack(spacing: 0) {- header(entries: entries)+ headerDivider()- if entries.isEmpty {+ if let error = store.errorMessage {+ Text(error)+ .font(.caption)+ .foregroundStyle(.red)+ .padding(8)+ }++ if entries.isEmpty, store.isLoading {+ ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)+ } else if entries.isEmpty {emptyState} else {logList(entries: entries)@@ -21,7 +30,7 @@ struct LogView: View {.frame(minWidth: 640, minHeight: 480)}- private func header(entries: [RequestLogEntry]) -> some View {+ private var header: some View {HStack(spacing: 10) {Image(systemName: "doc.text.magnifyingglass").foregroundStyle(.tint)@@ -29,7 +38,7 @@ struct LogView: View {Text("log.app-server.window.title").font(.headline)- Text(verbatim: "\(entries.count)")+ Text(verbatim: "\(store.totalCount)").font(.caption.monospacedDigit()).foregroundStyle(.secondary).padding(.horizontal, 7)@@ -38,13 +47,19 @@ struct LogView: View {Spacer()+ if store.browsingHistory {+ Button("log.action.latest") { Task { await store.showLatest() } }+ .controlSize(.small)+ .disabled(store.isLoading)+ }+Button {- store.clear()+ Task { await store.clear() }} label: {Label("common.action.clear", systemImage: "trash")}.controlSize(.small)- .disabled(entries.isEmpty)+ .disabled(store.totalCount == 0 || store.isLoading)}.padding(.horizontal, 16).padding(.vertical, 10)@@ -62,13 +77,19 @@ struct LogView: View {.frame(maxWidth: .infinity, maxHeight: .infinity)}- private func logList(entries: [RequestLogEntry]) -> some View {+ private func logList(entries: [AppServerLogEntry]) -> some View {ScrollView {LazyVStack(alignment: .leading, spacing: 0) {ForEach(entries) { entry inLogRow(entry: entry)Divider()}+ if store.hasMore {+ ProgressView()+ .frame(maxWidth: .infinity)+ .padding()+ .task(id: entries.last?.id) { await store.loadMore() }+ }}}.background(Color(nsColor: .textBackgroundColor))@@ -79,7 +100,7 @@ struct LogView: View {/// 单条日志行, 摘要行可展开查看请求和响应预览private struct LogRow: View {- let entry: RequestLogEntry+ let entry: AppServerLogEntry@State private var isExpanded = false@State private var fullTextItem: FullLogTextItem?@@ -110,9 +131,9 @@ private struct LogRow: View {caption: detailCaption,time: entry.respondedAt,text: detail,- color: entry.kind == .failure ? .red : .primary+ color: entry.status == .failure ? .red : .primary)- } else if entry.kind == .pending {+ } else if entry.status == .pending {Text("log.status.waiting-response").font(.caption.monospaced()).foregroundStyle(.secondary)@@ -142,14 +163,14 @@ private struct LogRow: View {.font(.caption.monospaced()).foregroundStyle(.secondary)- Text(entry.kind.label)+ Text(entry.source.label).font(.caption2.weight(.semibold))- .foregroundStyle(entry.kind.tint)+ .foregroundStyle(entry.status.tint).padding(.horizontal, 6).padding(.vertical, 1).background(RoundedRectangle(cornerRadius: 4, style: .continuous)- .fill(entry.kind.tint.opacity(0.14))+ .fill(entry.status.tint.opacity(0.14)))if let method = entry.method {@@ -159,7 +180,7 @@ private struct LogRow: View {} else if let detail = entry.detail {// 无方法名的记录 (信息/进程级错误) 直接预览正文// 避免标签后留空- Text(RequestLogEntry.singleLinePreview(detail, limit: RequestLogEntry.summaryPreviewLength))+ Text(AppServerLogEntry.singleLinePreview(detail, limit: AppServerLogEntry.summaryPreviewLength)).font(.caption).foregroundStyle(.secondary).lineLimit(1)@@ -179,9 +200,9 @@ private struct LogRow: View {) -> some View {let caption = String(localized: caption)let hasText = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty- let displayText = RequestLogEntry.singleLinePreview(+ let displayText = AppServerLogEntry.singleLinePreview(text,- limit: RequestLogEntry.expandedInlinePreviewLength+ limit: AppServerLogEntry.expandedInlinePreviewLength)return VStack(alignment: .leading, spacing: 2) {@@ -228,20 +249,22 @@ private struct LogRow: View {}private var detailCaption: LocalizedStringResource {- switch entry.kind {- case .response, .emptyResponse:- "log.payload.response"- case .failure:- "log.label.error"- default:- "log.payload.details"+ if entry.isConnectionEvent {+ return "log.payload.details"+ }+ if entry.isReceived {+ return "log.payload.received"}+ if entry.status == .failure {+ return "log.label.error"+ }+ return entry.source == .request ? "log.payload.response" : "log.payload.details"}private static let timeFormatter: DateFormatter = {let formatter = DateFormatter()formatter.locale = Locale(identifier: "en_US_POSIX")- formatter.dateFormat = "HH:mm:ss.SSS"+ formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"return formatter}()}@@ -330,224 +353,25 @@ private struct FullLogTextView: View {}}-// MARK: - JSON 预览与高亮--/// 日志预览文本, JSON 时会带基础语法高亮-private struct LogCodePreview {- let attributedText: NSAttributedString- let language: String?-}--/// 将 JSON 格式化并做轻量 token 高亮, 非 JSON 保持纯文本-private enum LogCodePreviewFormatter {- private static let font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)- private static var baseAttributes: [NSAttributedString.Key: Any] {- [- .font: font,- .foregroundColor: NSColor.labelColor- ]- }-- private static let jsonReadingOptions: JSONSerialization.ReadingOptions = [.fragmentsAllowed]- private static let jsonWritingOptions: JSONSerialization.WritingOptions = [- .fragmentsAllowed,- .prettyPrinted,- .sortedKeys,- .withoutEscapingSlashes- ]- private static let tokenRegex = try? NSRegularExpression(- pattern: #""(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b|\b(?:true|false|null)\b|[{}\[\]:,]"#- )-- static func preview(for text: String) -> LogCodePreview {- if let formattedJSON = formattedJSON(text) {- return LogCodePreview(- attributedText: highlightedJSON(formattedJSON),- language: "JSON"- )- }-- return LogCodePreview(- attributedText: attributedPlainText(text),- language: nil- )- }-- private static func formattedJSON(_ text: String) -> String? {- guard let data = text.data(using: .utf8),- let object = try? JSONSerialization.jsonObject(with: data, options: jsonReadingOptions),- let output = try? JSONSerialization.data(- withJSONObject: object,- options: jsonWritingOptions- ) else {- return nil- }-- return String(bytes: output, encoding: .utf8)- }-- private static func attributedPlainText(_ text: String) -> NSAttributedString {- NSAttributedString(- string: text,- attributes: baseAttributes- )- }-- private static func highlightedJSON(_ text: String) -> NSAttributedString {- let attributedText = NSMutableAttributedString(- string: text,- attributes: baseAttributes- )-- guard let tokenRegex else {- return attributedText- }-- let nsText = text as NSString- let fullRange = NSRange(location: 0, length: nsText.length)- tokenRegex.enumerateMatches(in: text, range: fullRange) { match, _, _ in- guard let range = match?.range else {- return- }-- let token = nsText.substring(with: range)- attributedText.addAttribute(- .foregroundColor,- value: color(for: token, in: nsText, range: range),- range: range- )- }-- return attributedText- }-- private static func color(for token: String, in text: NSString, range: NSRange) -> NSColor {- if token.hasPrefix("\"") {- return isJSONKey(in: text, after: range) ? .systemBlue : .systemGreen- }-- if token == "true" || token == "false" {- return .systemOrange- }-- if token == "null" {- return .secondaryLabelColor- }-- if token.first?.isNumber == true || token.hasPrefix("-") {- return .systemPurple- }-- return .tertiaryLabelColor- }-- private static func isJSONKey(in text: NSString, after range: NSRange) -> Bool {- var cursor = range.location + range.length- while cursor < text.length {- guard let scalar = UnicodeScalar(Int(text.character(at: cursor))),- CharacterSet.whitespacesAndNewlines.contains(scalar) else {- break- }- cursor += 1- }-- guard cursor < text.length else {- return false- }-- return text.character(at: cursor) == 58- }-}--/// AppKit 文本视图承载完整日志, 支持横向滚动-private struct LogCodePreviewView: NSViewRepresentable {- let attributedText: NSAttributedString-- func makeNSView(context _: Context) -> NSScrollView {- let scrollView = NSScrollView()- scrollView.hasVerticalScroller = true- scrollView.hasHorizontalScroller = true- scrollView.autohidesScrollers = false- scrollView.drawsBackground = true- scrollView.backgroundColor = .textBackgroundColor-- let textView = NSTextView()- textView.isEditable = false- textView.isSelectable = true- textView.isRichText = true- textView.drawsBackground = true- textView.backgroundColor = .textBackgroundColor- textView.textContainerInset = NSSize(width: 12, height: 12)- textView.minSize = NSSize(width: 0, height: scrollView.contentSize.height)- textView.maxSize = NSSize(- width: CGFloat.greatestFiniteMagnitude,- height: CGFloat.greatestFiniteMagnitude- )- textView.isVerticallyResizable = true- textView.isHorizontallyResizable = true- textView.autoresizingMask = []- textView.textContainer?.containerSize = NSSize(- width: CGFloat.greatestFiniteMagnitude,- height: CGFloat.greatestFiniteMagnitude- )- textView.textContainer?.widthTracksTextView = false-- scrollView.documentView = textView- return scrollView- }-- func updateNSView(_ scrollView: NSScrollView, context _: Context) {- guard let textView = scrollView.documentView as? NSTextView else {- return- }-- textView.textStorage?.setAttributedString(attributedText)- updateDocumentSize(for: textView, in: scrollView)- }-- private func updateDocumentSize(for textView: NSTextView, in scrollView: NSScrollView) {- guard let layoutManager = textView.layoutManager,- let textContainer = textView.textContainer else {- return- }-- layoutManager.ensureLayout(for: textContainer)- let usedRect = layoutManager.usedRect(for: textContainer)- let inset = textView.textContainerInset- let minimumSize = scrollView.contentSize- let fittedSize = NSSize(- width: max(ceil(usedRect.maxX + inset.width * 2), minimumSize.width),- height: max(ceil(usedRect.maxY + inset.height * 2), minimumSize.height)- )-- textView.setFrameSize(fittedSize)- }-}--private extension RequestLogEntry.Kind {+private extension AppServerLogEntry.Source {var label: LocalizedStringResource {switch self {- case .pending:- "log.status.in-progress"- case .response:- "common.status.completed"- case .failure:- "log.label.error"- case .emptyResponse:- "log.payload.request"+ case .request: "log.payload.request"+ case .sent: "log.label.sent"+ case .received: "log.label.received"+ case .connection: "log.label.connection-event"+ case .local: "log.label.local"}}+}+private extension AppServerLogEntry.Status {var tint: Color {switch self {- case .pending:- .orange- case .response:- .green- case .failure:- .red- case .emptyResponse:- .blue+ case .pending: .orange+ case .success: .green+ case .failure: .red+ case .information: .blue}}}diff --git a/CodexBar/Views/Menu/CodexActivityCard.swift b/CodexBar/Views/Menu/ActivityCard.swiftsimilarity index 92%rename from CodexBar/Views/Menu/CodexActivityCard.swiftrename to CodexBar/Views/Menu/ActivityCard.swiftindex 413ee2f..31e280f 100644--- a/CodexBar/Views/Menu/CodexActivityCard.swift+++ b/CodexBar/Views/Menu/ActivityCard.swift@@ -2,9 +2,9 @@ import SwiftUI/// 实时任务摘要, 使用主面板共享的时间/// 活动和防睡眠状态由卡片自行观察, 避免刷新整个菜单树-struct CodexActivityCard: View {- @ObservedObject var activityMonitor: CodexActivityMonitor- @ObservedObject var presentationState: CodexActivityCenterPresentationState+struct ActivityCard: View {+ @ObservedObject var activityMonitor: ActivityMonitor+ @ObservedObject var presentationState: ActivityCenterPresentationState@ObservedObject var keepAliveController: KeepAliveControllerlet showsUnavailableState: Boollet onTaskCenterTap: (ScreenFrameProvider) -> Void@@ -12,7 +12,7 @@ struct CodexActivityCard: View {@State private var frameProvider = ScreenFrameProvider()@State private var isHovered = false- private var snapshot: CodexActivitySnapshot {+ private var snapshot: ActivitySnapshot {showsUnavailableState ? .empty : activityMonitor.snapshot}@@ -110,7 +110,7 @@ struct CodexActivityCard: View {.truncationMode(.middle)if let detail = content.detail {- CodexActivityStatusText(+ ActivityStatusText(text: detail,tint: content.tint,effect: statusTextEffect@@ -121,7 +121,7 @@ struct CodexActivityCard: View {Spacer(minLength: 0)if content.isAnonymous {- CodexActivityAnonymousIcon()+ ActivityAnonymousIcon().transition(.opacity)}@@ -160,7 +160,7 @@ struct CodexActivityCard: View {.animation(.codexStatus, value: content.otherTaskCount)}- private func tokenUsageMetrics(_ usage: CodexTokenUsage) -> some View {+ private func tokenUsageMetrics(_ usage: TokenUsage) -> some View {HStack(alignment: .top, spacing: 0) {tokenMetric("usage.tokens.total", tokens: usage.totalTokens)tokenMetric("usage.tokens.input", tokens: usage.inputTokens)@@ -206,7 +206,7 @@ struct CodexActivityCard: View {symbolName: "hand.raised.fill",tint: .orange,fallback: "activity.status.codex-waiting-for-approval",- detailComponents: CodexActivityDisplayFormat.waitingDetailComponents(+ detailComponents: ActivityDisplayFormat.waitingDetailComponents(for: task,now: now)@@ -217,15 +217,15 @@ struct CodexActivityCard: View {symbolName: "bolt.fill",tint: .blue,fallback: "common.codex",- detailComponents: CodexActivityDisplayFormat.runningDetailComponents(+ detailComponents: ActivityDisplayFormat.runningDetailComponents(for: task,now: now))case let .completed(completion):- let details = CodexActivityDisplayFormat.historyDetailComponents(+ let details = ActivityDisplayFormat.historyDetailComponents(duration: completion.duration,- relativeText: CodexActivityDisplayFormat.completionRelativeText(completion.completedAt, now: now)+ relativeText: ActivityDisplayFormat.completionRelativeText(completion.completedAt, now: now))return ActivityCardContent(symbolName: "checkmark.circle.fill",@@ -242,9 +242,9 @@ struct CodexActivityCard: View {tokenUsage: completion.tokenUsage)case let .terminated(termination):- let details = CodexActivityDisplayFormat.historyDetailComponents(+ let details = ActivityDisplayFormat.historyDetailComponents(duration: termination.duration,- relativeText: CodexActivityDisplayFormat.terminationRelativeText(termination.terminatedAt, now: now)+ relativeText: ActivityDisplayFormat.terminationRelativeText(termination.terminatedAt, now: now))return ActivityCardContent(symbolName: "xmark.circle.fill",@@ -275,7 +275,7 @@ struct CodexActivityCard: View {}private func activeContent(- for task: CodexActivityTaskSnapshot,+ for task: ActivityTaskSnapshot,symbolName: String,tint: Color,fallback: LocalizedStringResource,@@ -305,7 +305,7 @@ struct CodexActivityCard: View {fallback: LocalizedStringResource) -> String {[- CodexActivityDisplayFormat.modelMetadata(+ ActivityDisplayFormat.modelMetadata(modelName: modelName,effort: effort),@@ -317,7 +317,7 @@ struct CodexActivityCard: View {private func activeDetailComponents(_ components: [String],- task: CodexActivityTaskSnapshot+ task: ActivityTaskSnapshot) -> [String] {guard let count = task.activeSubagentCount, count > 0 else {return components@@ -331,7 +331,7 @@ struct CodexActivityCard: View {max(0, snapshot.activeCount - 1)}- private var statusTextEffect: CodexActivityStatusText.Effect {+ private var statusTextEffect: ActivityStatusText.Effect {guard allowsAnimations else { return .none }switch snapshot.primaryActivity {case .running: return .shimmer@@ -408,10 +408,10 @@ private struct ActivityCardContent {let detail: String?let otherTaskCount: Intlet isAnonymous: Bool- var tokenUsage: CodexTokenUsage?+ var tokenUsage: TokenUsage?}-struct CodexActivityAnonymousIcon: View {+struct ActivityAnonymousIcon: View {var body: some View {Image(systemName: "person.crop.circle.dashed")// 虚线圆形 symbol 留白较多, 适当放大以接近相邻状态图标的视觉面积diff --git a/CodexBar/Views/Menu/CodexActivityCenterView.swift b/CodexBar/Views/Menu/ActivityCenterView.swiftsimilarity index 90%rename from CodexBar/Views/Menu/CodexActivityCenterView.swiftrename to CodexBar/Views/Menu/ActivityCenterView.swiftindex c9fed8c..1c9a8c6 100644--- a/CodexBar/Views/Menu/CodexActivityCenterView.swift+++ b/CodexBar/Views/Menu/ActivityCenterView.swift@@ -3,7 +3,7 @@ import SwiftUI/// 活动卡片与任务中心共享的显隐和逐秒时间状态@MainActor-final class CodexActivityCenterPresentationState: ObservableObject {+final class ActivityCenterPresentationState: ObservableObject {@Published var isPresented = false@Published private(set) var timelineDate = Date()private var timelineTask: Task<Void, Never>?@@ -36,7 +36,7 @@ final class CodexActivityCenterPresentationState: ObservableObject {/// 点击活动卡片时传给 AppKit 控制器的定位信息@MainActor-struct CodexActivityCenterPanelContext {+struct ActivityCenterPanelContext {let anchorProvider: ScreenFrameProviderlet preferredSide: UsageHeatmapDetailSide}@@ -44,9 +44,9 @@ struct CodexActivityCenterPanelContext {// MARK: - 任务中心面板/// 并发任务中心, 实时展示全部等待; 运行; 最近完成和最近终止任务-struct CodexActivityCenterView: View {- @ObservedObject var activityMonitor: CodexActivityMonitor- @ObservedObject var presentationState: CodexActivityCenterPresentationState+struct ActivityCenterView: View {+ @ObservedObject var activityMonitor: ActivityMonitor+ @ObservedObject var presentationState: ActivityCenterPresentationState@ObservedObject var mainPanelSettings: MainPanelSettingsvar body: some View {@@ -70,7 +70,7 @@ struct CodexActivityCenterView: View {static func panelSize(maximumHeight: CGFloat,- snapshot: CodexActivitySnapshot+ snapshot: ActivitySnapshot) -> CGSize {let visibleSectionCounts = [snapshot.waitingTasks.count,@@ -185,7 +185,7 @@ struct CodexActivityCenterView: View {title: LocalizedStringResource,symbolName: String,tint: Color,- tasks: [CodexActivityTaskSnapshot],+ tasks: [ActivityTaskSnapshot],now: Date,isWaiting: Bool) -> some View {@@ -246,7 +246,7 @@ struct CodexActivityCenterView: View {}private func taskRow(- _ task: CodexActivityTaskSnapshot,+ _ task: ActivityTaskSnapshot,symbolName: String,tint: Color,now: Date,@@ -264,7 +264,7 @@ struct CodexActivityCenterView: View {)}- private func completionRow(_ completion: CodexActivityCompletion, now: Date) -> some View {+ private func completionRow(_ completion: ActivityCompletion, now: Date) -> some View {row(symbolName: "checkmark.circle.fill",tint: .green,@@ -274,7 +274,7 @@ struct CodexActivityCenterView: View {isAnonymous: completion.isAnonymous,detail: historyDetail(duration: completion.duration,- relativeText: CodexActivityDisplayFormat.completionRelativeText(+ relativeText: ActivityDisplayFormat.completionRelativeText(completion.completedAt,now: now)@@ -283,7 +283,7 @@ struct CodexActivityCenterView: View {)}- private func terminationRow(_ termination: CodexActivityTermination, now: Date) -> some View {+ private func terminationRow(_ termination: ActivityTermination, now: Date) -> some View {row(symbolName: "xmark.circle.fill",tint: .red,@@ -293,7 +293,7 @@ struct CodexActivityCenterView: View {isAnonymous: termination.isAnonymous,detail: historyDetail(duration: termination.duration,- relativeText: CodexActivityDisplayFormat.terminationRelativeText(+ relativeText: ActivityDisplayFormat.terminationRelativeText(termination.terminatedAt,now: now)@@ -310,12 +310,12 @@ struct CodexActivityCenterView: View {effort: String?,isAnonymous: Bool,detail: String,- tokenUsage: CodexTokenUsage? = nil,- effect: CodexActivityStatusText.Effect = .none+ tokenUsage: TokenUsage? = nil,+ effect: ActivityStatusText.Effect = .none) -> some View {HStack(alignment: .top, spacing: 9) {if isAnonymous {- CodexActivityAnonymousIcon()+ ActivityAnonymousIcon().frame(width: Metrics.symbolWidth, height: Metrics.titleLineHeight)} else {Image(systemName: symbolName)@@ -332,7 +332,7 @@ struct CodexActivityCenterView: View {)HStack(spacing: 6) {- CodexActivityStatusText(+ ActivityStatusText(text: detail,tint: tint,effect: presentationState.isPresented@@ -341,7 +341,7 @@ struct CodexActivityCenterView: View {)if let tokenUsage {Spacer(minLength: 0)- CodexTokenUsageText(usage: tokenUsage)+ TokenUsageText(usage: tokenUsage)}}}@@ -364,7 +364,7 @@ struct CodexActivityCenterView: View {Spacer(minLength: 4)- if let metadata = CodexActivityDisplayFormat.modelMetadata(+ if let metadata = ActivityDisplayFormat.modelMetadata(modelName: modelName,effort: effort) {@@ -379,18 +379,18 @@ struct CodexActivityCenterView: View {}private func taskDetail(- _ task: CodexActivityTaskSnapshot,+ _ task: ActivityTaskSnapshot,now: Date,isWaiting: Bool) -> String {let components = isWaiting- ? CodexActivityDisplayFormat.waitingDetailComponents(for: task, now: now)- : CodexActivityDisplayFormat.runningDetailComponents(for: task, now: now)+ ? ActivityDisplayFormat.waitingDetailComponents(for: task, now: now)+ : ActivityDisplayFormat.runningDetailComponents(for: task, now: now)return components.joined(separator: " • ")}private func historyDetail(duration: TimeInterval?, relativeText: String) -> String {- CodexActivityDisplayFormat.historyDetailComponents(+ ActivityDisplayFormat.historyDetailComponents(duration: duration,relativeText: relativeText).joined(separator: " • ")diff --git a/CodexBar/Views/Menu/CodexActivityStatusText.swift b/CodexBar/Views/Menu/ActivityStatusText.swiftsimilarity index 99%rename from CodexBar/Views/Menu/CodexActivityStatusText.swiftrename to CodexBar/Views/Menu/ActivityStatusText.swiftindex 610f977..f920d37 100644--- a/CodexBar/Views/Menu/CodexActivityStatusText.swift+++ b/CodexBar/Views/Menu/ActivityStatusText.swift@@ -1,6 +1,6 @@import SwiftUI-struct CodexActivityStatusText: View {+struct ActivityStatusText: View {enum Effect: Equatable {case nonecase shimmerdiff --git a/CodexBar/Views/Menu/CodexStatusMenuSections.swift b/CodexBar/Views/Menu/CodexStatusMenuSections.swiftindex ba52ac2..fb28b59 100644--- a/CodexBar/Views/Menu/CodexStatusMenuSections.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuSections.swift@@ -266,7 +266,7 @@ struct UpdatedAtRow: View {let countdownStartedAt: Datelet countdownInterval: TimeIntervallet isCountdownActive: Bool- let syncDisplayState: WorkflowSyncDisplayState+ let syncDisplayState: SyncDisplayStatelet updateMessage: String?let startUpdate: () -> Void@@ -331,17 +331,17 @@ struct UpdatedAtRow: View {}}-struct WorkflowSyncDisplayState: Equatable {+struct SyncDisplayState: Equatable {let symbolName: Stringlet tint: Colorlet helpText: String- static func == (lhs: WorkflowSyncDisplayState, rhs: WorkflowSyncDisplayState) -> Bool {+ static func == (lhs: SyncDisplayState, rhs: SyncDisplayState) -> Bool {lhs.symbolName == rhs.symbolName && lhs.helpText == rhs.helpText}- init(isAdvancedModeEnabled: Bool, settings: WorkflowSyncSettings) {- guard settings.isEffectivelyActive(isAdvancedModeEnabled: isAdvancedModeEnabled) else {+ init(settings: SyncSettings) {+ guard settings.isEffectivelyActive else {self = .disabledreturn}@@ -352,7 +352,7 @@ struct WorkflowSyncDisplayState: Equatable {self.init(symbolName: "exclamationmark.icloud",tint: .orange,- helpText: settings.syncFailureMessage ?? WorkflowSyncFailureReason.retryLater.message+ helpText: settings.syncFailureMessage ?? SyncFailureReason.retryLater.message)} else {self.init(@@ -370,13 +370,13 @@ struct WorkflowSyncDisplayState: Equatable {self.helpText = helpText}- private static let disabled = WorkflowSyncDisplayState(+ private static let disabled = SyncDisplayState(symbolName: "icloud.slash",tint: .codexSecondaryLabel,helpText: String(localized: "sync.status.disabled"))- private static let syncing = WorkflowSyncDisplayState(+ private static let syncing = SyncDisplayState(symbolName: "arrow.trianglehead.clockwise.icloud",tint: .blue,helpText: String(localized: "sync.status.syncing")diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swiftindex 4476aae..330c114 100644--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift@@ -34,20 +34,19 @@ struct CodexStatusMenuView: View {static let menuWidth: CGFloat = Metrics.padding * 2 + MenuMetrics.panelPadding * 2 + UsageHeatmap.Metrics.totalWidth@ObservedObject var viewModel: CodexStatusViewModel- @ObservedObject var workflowViewModel: WorkflowViewModel- @ObservedObject var advancedModeSettings: AdvancedModeSettings+ @ObservedObject var historyViewModel: HistoryViewModel@ObservedObject var mainPanelSettings: MainPanelSettings// 活动状态与时间变化由卡片自行观察, 避免刷新整个菜单树- let activityMonitor: CodexActivityMonitor- @ObservedObject var syncSettings: WorkflowSyncSettings+ let activityMonitor: ActivityMonitor+ @ObservedObject var syncSettings: SyncSettings// 同 activityMonitor, 交给活动卡片自行观察, 不让 helper 状态变化重算整个菜单树let keepAliveController: KeepAliveController@ObservedObject var menuSurfaceVisibility: MenuSurfaceVisibilityState@ObservedObject var animationState: MenuSurfaceAnimationState- let activityCenterPresentationState: CodexActivityCenterPresentationState+ let activityCenterPresentationState: ActivityCenterPresentationStatelet onUsageHeatmapHoverChange: (UsageHeatmapHoverContext?) -> Voidlet onResetCreditsTap: (ResetCreditsPanelContext) -> Void- let onActivityCenterTap: (CodexActivityCenterPanelContext) -> Void+ let onActivityCenterTap: (ActivityCenterPanelContext) -> Void@EnvironmentObject private var appUpdater: AppUpdatervar body: some View {@@ -65,7 +64,6 @@ struct CodexStatusMenuView: View {.padding(Metrics.padding).liquidGlassSurface(cornerRadius: Metrics.surfaceCornerRadius, isOuterSurface: true).animation(Metrics.statusAnimation, value: viewModel.loadState)- .animation(Metrics.statusAnimation, value: advancedModeSettings.isEnabled).animation(Metrics.statusAnimation, value: mainPanelSettings.layout).animation(Metrics.statusAnimation, value: syncSettings.isEnabled).animation(Metrics.statusAnimation, value: syncSettings.isSyncing)@@ -145,24 +143,21 @@ private extension CodexStatusMenuView {}}- @ViewBuildervar activitySection: some View {- if advancedModeSettings.isEnabled {- CodexActivityCard(- activityMonitor: activityMonitor,- presentationState: activityCenterPresentationState,- keepAliveController: keepAliveController,- showsUnavailableState: viewModel.snapshot == nil,- onTaskCenterTap: { anchorProvider in- onActivityCenterTap(- CodexActivityCenterPanelContext(- anchorProvider: anchorProvider,- preferredSide: .right- )+ ActivityCard(+ activityMonitor: activityMonitor,+ presentationState: activityCenterPresentationState,+ keepAliveController: keepAliveController,+ showsUnavailableState: viewModel.snapshot == nil,+ onTaskCenterTap: { anchorProvider in+ onActivityCenterTap(+ ActivityCenterPanelContext(+ anchorProvider: anchorProvider,+ preferredSide: .right)- }- )- }+ )+ }+ )}@ViewBuilder@@ -184,12 +179,11 @@ private extension CodexStatusMenuView {@ViewBuilderfunc usageSection(dataPlaceholderSection: MainPanelSection?) -> some View {- if let snapshot = viewModel.snapshot,- snapshot.usage != nil || advancedModeSettings.isEnabled {+ if let snapshot = viewModel.snapshot {UsageSummaryView(usage: snapshot.usage,- workflow: workflowViewModel.snapshot,- showsWorkflow: advancedModeSettings.isEnabled,+ history: historyViewModel.snapshot,+ showsActivity: true,isStale: snapshot.isUsageStale,onHoverContextChange: onUsageHeatmapHoverChange)@@ -226,8 +220,7 @@ private extension CodexStatusMenuView {case .quota:viewModel.snapshot?.limits.isEmpty == falsecase .usage:- viewModel.snapshot?.usage != nil- || (viewModel.snapshot != nil && advancedModeSettings.isEnabled)+ viewModel.snapshot != nilcase .account, .activity, .status:false}@@ -242,7 +235,7 @@ private extension CodexStatusMenuView {case .account:truecase .activity:- advancedModeSettings.isEnabled+ truecase .quota, .usage:hasData(for: section) || dataPlaceholderSection == sectioncase .status:@@ -257,8 +250,7 @@ private extension CodexStatusMenuView {countdownStartedAt: viewModel.autoRefreshCountdownStartedAt ?? snapshot.generatedAt,countdownInterval: viewModel.autoRefreshInterval,isCountdownActive: menuSurfaceVisibility.isVisible,- syncDisplayState: WorkflowSyncDisplayState(- isAdvancedModeEnabled: advancedModeSettings.isEnabled,+ syncDisplayState: SyncDisplayState(settings: syncSettings),updateMessage: appUpdater.panelUpdateMessage,diff --git a/CodexBar/Views/Menu/HeatmapDetailView.swift b/CodexBar/Views/Menu/HeatmapDetailView.swiftnew file mode 100644index 0000000..6698a5c--- /dev/null+++ b/CodexBar/Views/Menu/HeatmapDetailView.swift@@ -0,0 +1,515 @@+import SwiftUI++struct HeatmapDetailView: View {+ let context: UsageHeatmapHoverContext+ @Environment(\.colorScheme) private var colorScheme++ var body: some View {+ let panelSize = Self.panelSize(showsActivity: context.showsActivity)++ detailContent+ .padding(.horizontal, Metrics.horizontalPadding)+ .padding(.vertical, Metrics.verticalPadding)+ .frame(+ width: panelSize.width,+ height: panelSize.height,+ alignment: .topLeading+ )+ .sidePanelChrome(cornerRadius: Metrics.cornerRadius)+ .animation(Metrics.statusAnimation, value: context)+ }++ static var panelCornerRadius: CGFloat {+ Metrics.cornerRadius+ }++ static func panelSize(showsActivity: Bool) -> CGSize {+ CGSize(+ width: showsActivity ? Metrics.activityPanelWidth : Metrics.panelWidth,+ height: showsActivity ? Metrics.activityPanelHeight : Metrics.tokenPanelHeight+ )+ }++ @ViewBuilder+ private var detailContent: some View {+ if context.showsActivity {+ activityContent+ } else {+ tokenOnlyContent+ }+ }++ private var header: some View {+ HStack(alignment: .center, spacing: 0) {+ dateText+ .padding(.horizontal, 7)+ .padding(.vertical, 3)+ .liquidGlassCapsule(tint: .accentColor)++ Spacer(minLength: 8)++ tokenText+ }+ }++ private var activityContent: some View {+ VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {+ header++ LiquidGlassDivider()+ .opacity(0.72)++ tokenIntensityMetricRow++ HStack(alignment: .top, spacing: Metrics.columnSpacing) {+ VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {+ columnTitle("usage.heatmap.activity-metrics")+ Grid(alignment: .leading, horizontalSpacing: Metrics.metricRowSpacing, verticalSpacing: Metrics.metricSpacing) {+ mostUsedModelMetricRow+ ForEach(activityMetricRows) { row in+ metricRow(row)+ }+ }+ }+ .frame(minWidth: 0, maxWidth: .infinity)++ Rectangle()+ .fill(Color.primary.opacity(0.08))+ .frame(width: 1)++ VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {+ columnTitle("usage.heatmap.token-metrics")+ dailyTokenMetrics+ }+ .frame(minWidth: 0, maxWidth: .infinity)+ }+ .frame(height: Metrics.columnHeight)+ }+ }++ private func columnTitle(_ title: LocalizedStringKey) -> some View {+ Text(title)+ .font(.caption2.weight(.semibold))+ .foregroundStyle(Color.codexSecondaryLabel)+ .frame(height: Metrics.metricRowHeight)+ }++ private var dailyTokenMetrics: some View {+ let usage = context.day.tokenUsage+ let cacheHitRate = usage?.cacheHitRate ?? 0+ return Grid(alignment: .leading, horizontalSpacing: Metrics.metricRowSpacing, verticalSpacing: Metrics.metricSpacing) {+ dailyTokenRow("usage.tokens.total", tokens: usage?.totalTokens, tint: .blue)+ dailyTokenRow("usage.tokens.input", tokens: usage?.inputTokens, tint: .indigo)+ dailyTokenRow("usage.tokens.output", tokens: usage?.outputTokens, tint: .orange)+ dailyTokenRow("usage.tokens.cached-input", tokens: usage?.cachedInputTokens, tint: .green)+ dailyTokenRow("usage.tokens.cache-write-input", tokens: usage?.cacheWriteInputTokens, tint: .purple)+ metricRowLayout {+ metricDot(tint: .teal)+ Text("usage.tokens.cache-hit-rate")+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: true, vertical: false)+ .frame(height: Metrics.metricRowHeight)+ fittingMetricValue(+ cacheHitRate.formatted(.percent.precision(.fractionLength(0 ... 1))),+ comparison: cacheHitRate+ )+ }+ dailyTokenRow("usage.tokens.reasoning-output", tokens: usage?.reasoningOutputTokens, tint: .cyan)+ }+ }++ private func dailyTokenRow(_ title: LocalizedStringKey, tokens: Int64?, tint: Color) -> some View {+ let count = tokens ?? 0+ return metricRowLayout {+ metricDot(tint: tint)+ Text(title)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ .fixedSize(horizontal: true, vertical: false)+ .frame(height: Metrics.metricRowHeight)+ fittingMetricValue(TokenCountFormatter.parts(from: Int(count)).text, comparison: Double(count))+ }+ }++ private var tokenOnlyContent: some View {+ VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {+ header++ LiquidGlassDivider()+ .opacity(0.62)++ tokenIntensityMetricRow+ }+ }++ private var tokenIntensityMetricRow: some View {+ tokenIntensityStrip+ .frame(maxWidth: .infinity)+ .frame(height: Metrics.metricRowHeight)+ }++ private var mostUsedModelMetricRow: some View {+ metricRowLayout {+ metricDot(tint: .cyan)+ Text("usage.heatmap.top-model")+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: true, vertical: false)+ .frame(height: Metrics.metricRowHeight)++ fittingModelValue(context.day.history.mostUsedModel ?? "--")+ }+ }++ private func metricRowLayout(@ViewBuilder content: () -> some View) -> some View {+ GridRow(content: content)+ .font(.system(size: Metrics.activityFontSize))+ }++ private func metricDot(tint: Color, darkOpacity: Double = 0.86, lightOpacity: Double = 0.72) -> some View {+ Circle()+ .fill(tint.opacity(colorScheme == .dark ? darkOpacity : lightOpacity))+ .frame(width: Metrics.metricDotSize, height: Metrics.metricDotSize)+ }++ private var tokenIntensityStrip: some View {+ HStack(spacing: Metrics.tokenIntensitySegmentSpacing) {+ ForEach(0 ..< Metrics.tokenIntensitySegmentCount, id: \.self) { index in+ RoundedRectangle(cornerRadius: 2, style: .continuous)+ .fill(tokenIntensityFill(for: index))+ .frame(maxWidth: .infinity)+ }+ }+ .frame(height: Metrics.tokenIntensityStripHeight)+ }++ private var activityMetricRows: [ActivityMetricRow] {+ [+ ActivityMetricRow(+ label: String(localized: "history.metric.sessions"),+ value: context.day.history.sessionCount,+ tint: .green+ ),+ ActivityMetricRow(+ label: String(localized: "history.metric.turns"),+ value: context.day.history.turnCount,+ tint: .teal+ ),+ ActivityMetricRow(+ label: String(localized: "history.metric.subagents"),+ value: context.day.history.subagentCount,+ tint: .indigo+ ),+ ActivityMetricRow(+ label: String(localized: "history.metric.tool-calls"),+ value: context.day.history.toolCallCount,+ tint: .orange+ ),+ ActivityMetricRow(+ label: String(localized: "history.metric.approvals"),+ value: context.day.history.approvalRequestedCount,+ tint: .red+ ),+ ActivityMetricRow(+ label: String(localized: "history.metric.compactions"),+ value: context.day.history.contextCompactionCount,+ tint: .purple+ )+ ]+ }++ private var dateText: some View {+ AnimatedDateText(startDate: context.day.startDate, font: dateFont)+ .foregroundStyle(Color.codexSecondaryLabel)+ .lineLimit(1)+ .fixedSize(horizontal: true, vertical: false)+ .layoutPriority(1)+ }++ private var tokenText: some View {+ HeatmapTokenText(+ tokenState: context.day.tokenState,+ font: tokenFont,+ numericWidth: Metrics.tokenMinimumWidth,+ unitWidth: Metrics.tokenUnitWidth+ )+ }++ private var dateFont: Font {+ .caption2.monospacedDigit()+ }++ private var tokenFont: Font {+ .system(size: 14).monospacedDigit().weight(.semibold)+ }++ private var tokenIntensityLevel: Int {+ guard context.day.tokensForHeatmap > 0 else {+ return 0+ }++ let percent = tokenIntensityPercent+ return min(+ Metrics.tokenIntensitySegmentCount,+ max(1, Int(ceil(percent * Double(Metrics.tokenIntensitySegmentCount))))+ )+ }++ private var tokenIntensityPercent: Double {+ guard context.peakTokens > 0 else {+ return 0+ }++ return min(max(Double(context.day.tokensForHeatmap) / Double(context.peakTokens), 0), 1)+ }++ private func tokenIntensityFill(for index: Int) -> Color {+ guard context.day.tokenCount != nil else {+ return Color.secondary.opacity(colorScheme == .dark ? 0.18 : 0.12)+ }++ guard index < tokenIntensityLevel else {+ return Color.blue.opacity(colorScheme == .dark ? 0.14 : 0.10)+ }++ let position = Double(index) / Double(Metrics.tokenIntensitySegmentCount - 1)+ let opacity = colorScheme == .dark ? 0.42 + position * 0.40 : 0.34 + position * 0.36+ return Color.blue.opacity(min(opacity, 0.88))+ }++ private func metricRow(_ row: ActivityMetricRow) -> some View {+ metricRowLayout {+ metricDot(tint: row.tint)+ Text(row.label)+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: true, vertical: false)+ .frame(height: Metrics.metricRowHeight)++ fittingMetricValue("\(row.value)", comparison: Double(row.value))+ }+ }++ private func fittingMetricValue(_ value: String, comparison: Double) -> some View {+ fittingValueContent(value)+ .contentTransition(.numericText(value: comparison))+ .layoutPriority(1)+ .frame(maxWidth: .infinity, alignment: .trailing)+ }++ private func fittingModelValue(_ value: String) -> some View {+ metricValueText(value)+ .minimumScaleFactor(Metrics.metricValueMinimumScale)+ .allowsTightening(true)+ .contentTransition(.numericText())+ .layoutPriority(1)+ .frame(maxWidth: .infinity, alignment: .trailing)+ }++ private func fittingValueContent(_ value: String) -> some View {+ ViewThatFits(in: .horizontal) {+ metricValueText(value)+ .fixedSize(horizontal: true, vertical: false)++ metricValueText(value)+ .minimumScaleFactor(Metrics.metricValueMinimumScale)+ .allowsTightening(true)+ }+ }++ private func metricValueText(_ value: String) -> some View {+ Text(value)+ .foregroundStyle(Color.codexLabel)+ .fontWeight(.semibold)+ .monospacedDigit()+ .lineLimit(1)+ }++ private struct ActivityMetricRow: Identifiable {+ let label: String+ let value: Int+ let tint: Color++ var id: String {+ label+ }+ }++ private enum Metrics {+ static let panelWidth: CGFloat = 212+ static let activityPanelWidth: CGFloat = 360+ static let activityPanelHeight: CGFloat = 232+ static let columnSpacing: CGFloat = 12+ static let columnHeight: CGFloat = 150+ static let tokenPanelHeight: CGFloat = 84+ static let sectionSpacing: CGFloat = 8+ static let horizontalPadding: CGFloat = 12+ static let verticalPadding: CGFloat = 10+ static let cornerRadius: CGFloat = 12+ static let tokenMinimumWidth: CGFloat = 38+ static let tokenUnitWidth: CGFloat = 14+ static let metricSpacing: CGFloat = 5+ static let metricRowSpacing: CGFloat = 6+ static let metricDotSize: CGFloat = 5+ static let metricRowHeight: CGFloat = 14+ static let metricValueMinimumScale: CGFloat = 0.60+ static let activityFontSize: CGFloat = 11+ static let tokenIntensitySegmentCount = 10+ static let tokenIntensitySegmentSpacing: CGFloat = 3+ static let tokenIntensityStripHeight: CGFloat = 5+ static let statusAnimation = Animation.codexStatus+ }+}++/// token 详情在数字和占位状态之间切换时只做淡入淡出, 数字之间仍保留滚动过渡+private struct HeatmapTokenText: View {+ let tokenState: UsageHeatmapTokenState+ let font: Font+ let numericWidth: CGFloat+ let unitWidth: CGFloat++ @State private var displayedTokenState: UsageHeatmapTokenState+ @State private var isVisible = true++ init(+ tokenState: UsageHeatmapTokenState,+ font: Font,+ numericWidth: CGFloat,+ unitWidth: CGFloat+ ) {+ self.tokenState = tokenState+ self.font = font+ self.numericWidth = numericWidth+ self.unitWidth = unitWidth+ _displayedTokenState = State(initialValue: tokenState)+ }++ var body: some View {+ content+ .opacity(isVisible ? 1 : 0)+ .frame(minWidth: width, alignment: .trailing)+ .task(id: tokenState) {+ await updateDisplayedTokenState(tokenState)+ }+ }++ @ViewBuilder+ private var content: some View {+ switch displayedTokenState {+ case let .available(tokenCount):+ TokenCountText(+ tokens: tokenCount,+ font: font,+ reservedNumericWidth: numericWidth,+ reservedUnitWidth: unitWidth+ )+ .foregroundStyle(Color.codexLabel)++ case .pending:+ Image(systemName: "questionmark")+ .font(font)+ .foregroundStyle(Color.codexLabel)++ case .unavailable:+ Text(verbatim: "--")+ .font(font)+ .foregroundStyle(Color.codexLabel)+ }+ }++ private func updateDisplayedTokenState(_ newTokenState: UsageHeatmapTokenState) async {+ guard displayedTokenState != newTokenState || !isVisible else {+ return+ }++ if displayedTokenState.count != nil, newTokenState.count != nil {+ updateTokenStateWithoutFade(newTokenState)+ } else if displayedTokenState == newTokenState {+ withAnimation(Metrics.fadeAnimation) {+ isVisible = true+ }+ } else {+ await fadeToTokenState(newTokenState)+ }+ }++ private func updateTokenStateWithoutFade(_ newTokenState: UsageHeatmapTokenState) {+ withAnimation(Metrics.numericAnimation) {+ displayedTokenState = newTokenState+ isVisible = true+ }+ }++ private func fadeToTokenState(_ newTokenState: UsageHeatmapTokenState) async {+ withAnimation(Metrics.fadeAnimation) {+ isVisible = false+ }++ try? await Task.sleep(for: .milliseconds(Metrics.fadeDelayMilliseconds))+ guard !Task.isCancelled else {+ return+ }++ displayedTokenState = newTokenState+ withAnimation(Metrics.fadeAnimation) {+ isVisible = true+ }+ }++ private var width: CGFloat {+ numericWidth + unitWidth+ }++ private enum Metrics {+ static let fadeAnimation = Animation.easeInOut(duration: 0.12)+ static let fadeDelayMilliseconds: UInt64 = 120+ static let numericAnimation = Animation.codexStatus+ }+}++/// 日期拆成三段以固定 yyyy-MM-dd 格式并保留自然的数字滚动过渡+private struct AnimatedDateText: View {+ let startDate: String+ let font: Font++ var body: some View {+ if let components {+ HStack(spacing: 0) {+ Text(verbatim: components.year)+ Text(verbatim: "-")+ Text(verbatim: components.month)+ Text(verbatim: "-")+ Text(verbatim: components.day)+ }+ .font(font)+ .contentTransition(.numericText(value: dateValue(components)))+ } else {+ Text(verbatim: startDate)+ .font(font)+ .contentTransition(.numericText())+ }+ }++ private func dateValue(_ components: DateTextComponents) -> Double {+ guard let year = Int(components.year),+ let month = Int(components.month),+ let day = Int(components.day) else {+ return 0+ }+ return Double(year * 10000 + month * 100 + day)+ }++ private var components: DateTextComponents? {+ let parts = startDate.split(separator: "-", omittingEmptySubsequences: false).map(String.init)+ guard parts.count == 3,+ parts.allSatisfy({ !$0.isEmpty && $0.allSatisfy(\.isNumber) }) else {+ return nil+ }++ return DateTextComponents(year: parts[0], month: parts[1], day: parts[2])+ }++ private struct DateTextComponents {+ let year: String+ let month: String+ let day: String+ }+}diff --git a/CodexBar/Views/Menu/TokenCountText.swift b/CodexBar/Views/Menu/TokenCountText.swiftindex bb23b1c..10362bd 100644--- a/CodexBar/Views/Menu/TokenCountText.swift+++ b/CodexBar/Views/Menu/TokenCountText.swift@@ -36,8 +36,8 @@ struct TokenCountText: View {}}-struct CodexTokenUsageText: View {- let usage: CodexTokenUsage+struct TokenUsageText: View {+ let usage: TokenUsagevar body: some View {HStack(spacing: 3) {diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swiftindex e645638..7dae279 100644--- a/CodexBar/Views/Menu/UsageHeatmap.swift+++ b/CodexBar/Views/Menu/UsageHeatmap.swift@@ -4,7 +4,7 @@ import SwiftUI/// hover 详情面板需要的完整上下文, 包括屏幕坐标和峰值 tokennonisolated struct UsageHeatmapHoverContext: Equatable {let day: UsageHeatmapDay- let showsWorkflow: Bool+ let showsActivity: Boollet alignmentScreenFrame: CGRect?let preferredSide: UsageHeatmapDetailSidelet peakTokens: Int@@ -22,219 +22,6 @@ nonisolated struct UsageHeatmapSelection: Equatable {let row: Int}-// MARK: - 摘要区--/// Token 摘要和近期用量热力图的组合区-struct UsageSummaryView: View {- let usage: CodexUsageSnapshot?- let isStale: Bool- let showsWorkflow: Bool- let onHoverContextChange: (UsageHeatmapHoverContext?) -> Void- private let days: [UsageHeatmapDay?]- private let peakTokens: Int- @State private var hoverSelection: UsageHeatmapSelection?- @State private var heatmapScreenFrame: CGRect?-- init(- usage: CodexUsageSnapshot?,- workflow: WorkflowSnapshot,- showsWorkflow: Bool,- isStale: Bool = false,- onHoverContextChange: @escaping (UsageHeatmapHoverContext?) -> Void = { _ in }- ) {- self.usage = usage- self.isStale = isStale- self.showsWorkflow = showsWorkflow- self.onHoverContextChange = onHoverContextChange-- let days = UsageHeatmapDay.grid(- usage: usage,- workflow: workflow,- showsWorkflow: showsWorkflow,- columnCount: UsageHeatmap.Metrics.columnCount,- today: Date()- )- self.days = days- peakTokens = max(days.lazy.compactMap { $0?.tokensForHeatmap }.max() ?? 0, 1)- }-- var body: some View {- content- .markStale(isStale)- .padding(MenuMetrics.panelPadding)- .liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)- .onAppear {- clearHover()- }- .onDisappear {- clearHover()- }- .onChange(of: days) { _, newDays in- refreshHoveredDay(from: newDays)- }- .onChange(of: hoverContext) { _, context in- onHoverContextChange(context)- }- .animation(Metrics.statusAnimation, value: usage)- .animation(Metrics.statusAnimation, value: days)- }-- @ViewBuilder- private var content: some View {- if usage?.hasAppServerData == true || showsWorkflow {- VStack(alignment: .leading, spacing: 8) {- metricsGrid-- if usage?.hasDailyUsageBuckets == true || showsWorkflow {- UsageHeatmap(- days: days,- selection: $hoverSelection,- peakTokens: peakTokens,- onScreenFrameChange: { frame in- heatmapScreenFrame = frame- }- )- } else {- dailyUsageUnavailable- }- }- } else {- Text("common.empty.no-data")- .foregroundStyle(.secondary)- .frame(maxWidth: .infinity, alignment: .center)- .padding(.vertical, MenuMetrics.loadingVerticalPadding)- }- }-- private var metricsGrid: some View {- HStack(alignment: .firstTextBaseline, spacing: Metrics.metricSpacing) {- tokenMetric(label: "usage.summary.lifetime-tokens", value: usage?.summary.lifetimeTokens)- tokenMetric(label: "usage.summary.peak-tokens", value: usage?.summary.peakDailyTokens)- textMetric(- label: "usage.summary.current-streak",- value: Self.dayText(usage?.summary.currentStreakDays)- )- textMetric(- label: "usage.summary.longest-streak",- value: Self.dayText(usage?.summary.longestStreakDays)- )- textMetric(- label: "usage.summary.longest-chat",- value: Self.durationText(seconds: usage?.summary.longestRunningTurnSec)- )- }- }-- private func tokenMetric(label: LocalizedStringResource, value: Int?) -> some View {- metric(label: label) {- if let value {- TokenCountText(tokens: value)- .minimumScaleFactor(0.8)- } else {- Text(verbatim: "--")- .font(.caption.monospacedDigit().weight(.semibold))- }- }- }-- private var dailyUsageUnavailable: some View {- Text("usage.heatmap.no-data")- .font(.caption)- .foregroundStyle(.secondary)- .frame(maxWidth: .infinity, alignment: .center)- .frame(height: UsageHeatmap.Metrics.height)- }-- private func textMetric(label: LocalizedStringResource, value: String) -> some View {- metric(label: label) {- Text(value)- .font(.caption.monospacedDigit().weight(.semibold))- .lineLimit(1)- .minimumScaleFactor(0.8)- }- }-- private func metric(- label: LocalizedStringResource,- @ViewBuilder value: () -> some View- ) -> some View {- VStack(alignment: .leading, spacing: 2) {- Text(label)- .font(.caption2)- .foregroundStyle(.secondary)- .frame(maxWidth: .infinity, alignment: .center)-- value()- .frame(maxWidth: .infinity, alignment: .center)- }- .frame(maxWidth: .infinity)- }-- private static func dayText(_ days: Int?) -> String {- guard let days else {- return "--"- }-- return String(localized: "duration.days-compact", defaultValue: "\(max(days, 0), specifier: "%lld")")- }-- private static func durationText(seconds: Int?) -> String {- guard let seconds else {- return "--"- }-- return CodexDurationFormat.activityText(for: TimeInterval(seconds))- }-- private enum Metrics {- static let metricSpacing: CGFloat = 8- static let statusAnimation = Animation.codexStatus- }-- private var hoverContext: UsageHeatmapHoverContext? {- // 详情面板由控制器显示, SwiftUI 这里只负责传递屏幕坐标和数据- hoverSelection.map {- UsageHeatmapHoverContext(- day: $0.day,- showsWorkflow: showsWorkflow,- alignmentScreenFrame: heatmapScreenFrame,- preferredSide: UsageHeatmap.Metrics.preferredDetailSide(for: $0.column),- peakTokens: peakTokens- )- }- }-- private func refreshHoveredDay(from days: [UsageHeatmapDay?]) {- guard let hoverSelection else {- return- }-- guard let updatedDay = days.compactMap(\.self).first(where: { $0.id == hoverSelection.day.id }) else {- withAnimation(Metrics.statusAnimation) {- self.hoverSelection = nil- }- return- }-- guard updatedDay != hoverSelection.day else {- return- }-- withAnimation(Metrics.statusAnimation) {- self.hoverSelection = UsageHeatmapSelection(- day: updatedDay,- column: hoverSelection.column,- row: hoverSelection.row- )- }- }-- private func clearHover() {- hoverSelection = nil- onHoverContextChange(nil)- }-}-// MARK: - 热力图与 hover 吸附/// 近期 Token 用量热力图, hover 时把指针吸附到最近的有效日期格@@ -567,517 +354,3 @@ private struct UsageHeatmapSquare: View {day.tokenCount == nil ? .clear : .blue.opacity(0.22)}}--struct UsageHeatmapDayDetailView: View {- let context: UsageHeatmapHoverContext- @Environment(\.colorScheme) private var colorScheme-- var body: some View {- let panelSize = Self.panelSize(showsWorkflow: context.showsWorkflow)-- detailContent- .padding(.horizontal, Metrics.horizontalPadding)- .padding(.vertical, Metrics.verticalPadding)- .frame(- width: panelSize.width,- height: panelSize.height,- alignment: .topLeading- )- .sidePanelChrome(cornerRadius: Metrics.cornerRadius)- .animation(Metrics.statusAnimation, value: context)- }-- static var panelCornerRadius: CGFloat {- Metrics.cornerRadius- }-- static func panelSize(showsWorkflow: Bool) -> CGSize {- CGSize(- width: showsWorkflow ? Metrics.workflowPanelWidth : Metrics.panelWidth,- height: showsWorkflow ? Metrics.workflowPanelHeight : Metrics.tokenPanelHeight- )- }-- @ViewBuilder- private var detailContent: some View {- if context.showsWorkflow {- workflowContent- } else {- tokenOnlyContent- }- }-- private var header: some View {- HStack(alignment: .center, spacing: 0) {- dateText- .padding(.horizontal, 7)- .padding(.vertical, 3)- .liquidGlassCapsule(tint: .accentColor)-- Spacer(minLength: 8)-- tokenText- }- }-- private var workflowContent: some View {- VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {- header-- LiquidGlassDivider()- .opacity(0.72)-- tokenIntensityMetricRow-- HStack(alignment: .top, spacing: Metrics.columnSpacing) {- VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {- columnTitle("usage.heatmap.activity-metrics")- Grid(alignment: .leading, horizontalSpacing: Metrics.metricRowSpacing, verticalSpacing: Metrics.metricSpacing) {- mostUsedModelMetricRow- ForEach(workflowMetricRows) { row in- metricRow(row)- }- }- }- .frame(minWidth: 0, maxWidth: .infinity)-- Rectangle()- .fill(Color.primary.opacity(0.08))- .frame(width: 1)-- VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {- columnTitle("usage.heatmap.token-metrics")- dailyTokenMetrics- }- .frame(minWidth: 0, maxWidth: .infinity)- }- .frame(height: Metrics.columnHeight)- }- }-- private func columnTitle(_ title: LocalizedStringKey) -> some View {- Text(title)- .font(.caption2.weight(.semibold))- .foregroundStyle(Color.codexSecondaryLabel)- .frame(height: Metrics.metricRowHeight)- }-- private var dailyTokenMetrics: some View {- let usage = context.day.tokenUsage- let cacheHitRate = usage?.cacheHitRate ?? 0- return Grid(alignment: .leading, horizontalSpacing: Metrics.metricRowSpacing, verticalSpacing: Metrics.metricSpacing) {- dailyTokenRow("usage.tokens.total", tokens: usage?.totalTokens, tint: .blue)- dailyTokenRow("usage.tokens.input", tokens: usage?.inputTokens, tint: .indigo)- dailyTokenRow("usage.tokens.output", tokens: usage?.outputTokens, tint: .orange)- dailyTokenRow("usage.tokens.cached-input", tokens: usage?.cachedInputTokens, tint: .green)- dailyTokenRow("usage.tokens.cache-write-input", tokens: usage?.cacheWriteInputTokens, tint: .purple)- metricRowLayout {- metricDot(tint: .teal)- Text("usage.tokens.cache-hit-rate")- .foregroundStyle(.secondary)- .fixedSize(horizontal: true, vertical: false)- .frame(height: Metrics.metricRowHeight)- fittingMetricValue(- cacheHitRate.formatted(.percent.precision(.fractionLength(0 ... 1))),- comparison: cacheHitRate- )- }- dailyTokenRow("usage.tokens.reasoning-output", tokens: usage?.reasoningOutputTokens, tint: .cyan)- }- }-- private func dailyTokenRow(_ title: LocalizedStringKey, tokens: Int64?, tint: Color) -> some View {- let count = tokens ?? 0- return metricRowLayout {- metricDot(tint: tint)- Text(title)- .foregroundStyle(.secondary)- .lineLimit(1)- .fixedSize(horizontal: true, vertical: false)- .frame(height: Metrics.metricRowHeight)- fittingMetricValue(TokenCountFormatter.parts(from: Int(count)).text, comparison: Double(count))- }- }-- private var tokenOnlyContent: some View {- VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {- header-- LiquidGlassDivider()- .opacity(0.62)-- tokenIntensityMetricRow- }- }-- private var tokenIntensityMetricRow: some View {- tokenIntensityStrip- .frame(maxWidth: .infinity)- .frame(height: Metrics.metricRowHeight)- }-- private var mostUsedModelMetricRow: some View {- metricRowLayout {- metricDot(tint: .cyan)- Text("usage.heatmap.top-model")- .foregroundStyle(.secondary)- .fixedSize(horizontal: true, vertical: false)- .frame(height: Metrics.metricRowHeight)-- fittingModelValue(context.day.workflow.mostUsedModel ?? "--")- }- }-- private func metricRowLayout(@ViewBuilder content: () -> some View) -> some View {- GridRow(content: content)- .font(.system(size: Metrics.workflowFontSize))- }-- private func metricDot(tint: Color, darkOpacity: Double = 0.86, lightOpacity: Double = 0.72) -> some View {- Circle()- .fill(tint.opacity(colorScheme == .dark ? darkOpacity : lightOpacity))- .frame(width: Metrics.metricDotSize, height: Metrics.metricDotSize)- }-- private var tokenIntensityStrip: some View {- HStack(spacing: Metrics.tokenIntensitySegmentSpacing) {- ForEach(0 ..< Metrics.tokenIntensitySegmentCount, id: \.self) { index in- RoundedRectangle(cornerRadius: 2, style: .continuous)- .fill(tokenIntensityFill(for: index))- .frame(maxWidth: .infinity)- }- }- .frame(height: Metrics.tokenIntensityStripHeight)- }-- private var workflowMetricRows: [WorkflowMetricRow] {- [- WorkflowMetricRow(- label: String(localized: "workflow.metric.sessions"),- value: context.day.workflow.sessionCount,- tint: .green- ),- WorkflowMetricRow(- label: String(localized: "workflow.metric.turns"),- value: context.day.workflow.turnCount,- tint: .teal- ),- WorkflowMetricRow(- label: String(localized: "workflow.metric.subagents"),- value: context.day.workflow.subagentCount,- tint: .indigo- ),- WorkflowMetricRow(- label: String(localized: "workflow.metric.tool-calls"),- value: context.day.workflow.toolCallCount,- tint: .orange- ),- WorkflowMetricRow(- label: String(localized: "workflow.metric.approvals"),- value: context.day.workflow.permissionRequestCount,- tint: .red- ),- WorkflowMetricRow(- label: String(localized: "workflow.metric.compactions"),- value: context.day.workflow.contextCompactionCount,- tint: .purple- )- ]- }-- private var dateText: some View {- AnimatedDateText(startDate: context.day.startDate, font: dateFont)- .foregroundStyle(Color.codexSecondaryLabel)- .lineLimit(1)- .fixedSize(horizontal: true, vertical: false)- .layoutPriority(1)- }-- private var tokenText: some View {- HeatmapTokenText(- tokenState: context.day.tokenState,- font: tokenFont,- numericWidth: Metrics.tokenMinimumWidth,- unitWidth: Metrics.tokenUnitWidth- )- }-- private var dateFont: Font {- .caption2.monospacedDigit()- }-- private var tokenFont: Font {- .system(size: 14).monospacedDigit().weight(.semibold)- }-- private var tokenIntensityLevel: Int {- guard context.day.tokensForHeatmap > 0 else {- return 0- }-- let percent = tokenIntensityPercent- return min(- Metrics.tokenIntensitySegmentCount,- max(1, Int(ceil(percent * Double(Metrics.tokenIntensitySegmentCount))))- )- }-- private var tokenIntensityPercent: Double {- guard context.peakTokens > 0 else {- return 0- }-- return min(max(Double(context.day.tokensForHeatmap) / Double(context.peakTokens), 0), 1)- }-- private func tokenIntensityFill(for index: Int) -> Color {- guard context.day.tokenCount != nil else {- return Color.secondary.opacity(colorScheme == .dark ? 0.18 : 0.12)- }-- guard index < tokenIntensityLevel else {- return Color.blue.opacity(colorScheme == .dark ? 0.14 : 0.10)- }-- let position = Double(index) / Double(Metrics.tokenIntensitySegmentCount - 1)- let opacity = colorScheme == .dark ? 0.42 + position * 0.40 : 0.34 + position * 0.36- return Color.blue.opacity(min(opacity, 0.88))- }-- private func metricRow(_ row: WorkflowMetricRow) -> some View {- metricRowLayout {- metricDot(tint: row.tint)- Text(row.label)- .foregroundStyle(.secondary)- .fixedSize(horizontal: true, vertical: false)- .frame(height: Metrics.metricRowHeight)-- fittingMetricValue("\(row.value)", comparison: Double(row.value))- }- }-- private func fittingMetricValue(_ value: String, comparison: Double) -> some View {- fittingValueContent(value)- .contentTransition(.numericText(value: comparison))- .layoutPriority(1)- .frame(maxWidth: .infinity, alignment: .trailing)- }-- private func fittingModelValue(_ value: String) -> some View {- metricValueText(value)- .minimumScaleFactor(Metrics.metricValueMinimumScale)- .allowsTightening(true)- .contentTransition(.numericText())- .layoutPriority(1)- .frame(maxWidth: .infinity, alignment: .trailing)- }-- private func fittingValueContent(_ value: String) -> some View {- ViewThatFits(in: .horizontal) {- metricValueText(value)- .fixedSize(horizontal: true, vertical: false)-- metricValueText(value)- .minimumScaleFactor(Metrics.metricValueMinimumScale)- .allowsTightening(true)- }- }-- private func metricValueText(_ value: String) -> some View {- Text(value)- .foregroundStyle(Color.codexLabel)- .fontWeight(.semibold)- .monospacedDigit()- .lineLimit(1)- }-- private struct WorkflowMetricRow: Identifiable {- let label: String- let value: Int- let tint: Color-- var id: String {- label- }- }-- private enum Metrics {- static let panelWidth: CGFloat = 212- static let workflowPanelWidth: CGFloat = 360- static let workflowPanelHeight: CGFloat = 232- static let columnSpacing: CGFloat = 12- static let columnHeight: CGFloat = 150- static let tokenPanelHeight: CGFloat = 84- static let sectionSpacing: CGFloat = 8- static let horizontalPadding: CGFloat = 12- static let verticalPadding: CGFloat = 10- static let cornerRadius: CGFloat = 12- static let tokenMinimumWidth: CGFloat = 38- static let tokenUnitWidth: CGFloat = 14- static let metricSpacing: CGFloat = 5- static let metricRowSpacing: CGFloat = 6- static let metricDotSize: CGFloat = 5- static let metricRowHeight: CGFloat = 14- static let metricValueMinimumScale: CGFloat = 0.60- static let workflowFontSize: CGFloat = 11- static let tokenIntensitySegmentCount = 10- static let tokenIntensitySegmentSpacing: CGFloat = 3- static let tokenIntensityStripHeight: CGFloat = 5- static let statusAnimation = Animation.codexStatus- }-}--/// token 详情在数字和占位状态之间切换时只做淡入淡出, 数字之间仍保留滚动过渡-private struct HeatmapTokenText: View {- let tokenState: UsageHeatmapTokenState- let font: Font- let numericWidth: CGFloat- let unitWidth: CGFloat-- @State private var displayedTokenState: UsageHeatmapTokenState- @State private var isVisible = true-- init(- tokenState: UsageHeatmapTokenState,- font: Font,- numericWidth: CGFloat,- unitWidth: CGFloat- ) {- self.tokenState = tokenState- self.font = font- self.numericWidth = numericWidth- self.unitWidth = unitWidth- _displayedTokenState = State(initialValue: tokenState)- }-- var body: some View {- content- .opacity(isVisible ? 1 : 0)- .frame(minWidth: width, alignment: .trailing)- .task(id: tokenState) {- await updateDisplayedTokenState(tokenState)- }- }-- @ViewBuilder- private var content: some View {- switch displayedTokenState {- case let .available(tokenCount):- TokenCountText(- tokens: tokenCount,- font: font,- reservedNumericWidth: numericWidth,- reservedUnitWidth: unitWidth- )- .foregroundStyle(Color.codexLabel)-- case .pending:- Image(systemName: "questionmark")- .font(font)- .foregroundStyle(Color.codexLabel)-- case .unavailable:- Text(verbatim: "--")- .font(font)- .foregroundStyle(Color.codexLabel)- }- }-- private func updateDisplayedTokenState(_ newTokenState: UsageHeatmapTokenState) async {- guard displayedTokenState != newTokenState || !isVisible else {- return- }-- if displayedTokenState.count != nil, newTokenState.count != nil {- updateTokenStateWithoutFade(newTokenState)- } else if displayedTokenState == newTokenState {- withAnimation(Metrics.fadeAnimation) {- isVisible = true- }- } else {- await fadeToTokenState(newTokenState)- }- }-- private func updateTokenStateWithoutFade(_ newTokenState: UsageHeatmapTokenState) {- withAnimation(Metrics.numericAnimation) {- displayedTokenState = newTokenState- isVisible = true- }- }-- private func fadeToTokenState(_ newTokenState: UsageHeatmapTokenState) async {- withAnimation(Metrics.fadeAnimation) {- isVisible = false- }-- try? await Task.sleep(for: .milliseconds(Metrics.fadeDelayMilliseconds))- guard !Task.isCancelled else {- return- }-- displayedTokenState = newTokenState- withAnimation(Metrics.fadeAnimation) {- isVisible = true- }- }-- private var width: CGFloat {- numericWidth + unitWidth- }-- private enum Metrics {- static let fadeAnimation = Animation.easeInOut(duration: 0.12)- static let fadeDelayMilliseconds: UInt64 = 120- static let numericAnimation = Animation.codexStatus- }-}--/// 日期拆成三段以固定 yyyy-MM-dd 格式并保留自然的数字滚动过渡-private struct AnimatedDateText: View {- let startDate: String- let font: Font-- var body: some View {- if let components {- HStack(spacing: 0) {- Text(verbatim: components.year)- Text(verbatim: "-")- Text(verbatim: components.month)- Text(verbatim: "-")- Text(verbatim: components.day)- }- .font(font)- .contentTransition(.numericText(value: dateValue(components)))- } else {- Text(verbatim: startDate)- .font(font)- .contentTransition(.numericText())- }- }-- private func dateValue(_ components: DateTextComponents) -> Double {- guard let year = Int(components.year),- let month = Int(components.month),- let day = Int(components.day) else {- return 0- }- return Double(year * 10000 + month * 100 + day)- }-- private var components: DateTextComponents? {- let parts = startDate.split(separator: "-", omittingEmptySubsequences: false).map(String.init)- guard parts.count == 3,- parts.allSatisfy({ !$0.isEmpty && $0.allSatisfy(\.isNumber) }) else {- return nil- }-- return DateTextComponents(year: parts[0], month: parts[1], day: parts[2])- }-- private struct DateTextComponents {- let year: String- let month: String- let day: String- }-}diff --git a/CodexBar/Views/Menu/UsageSummaryView.swift b/CodexBar/Views/Menu/UsageSummaryView.swiftnew file mode 100644index 0000000..d23509e--- /dev/null+++ b/CodexBar/Views/Menu/UsageSummaryView.swift@@ -0,0 +1,214 @@+import SwiftUI++// MARK: - 摘要区++/// Token 摘要和近期用量热力图的组合区+struct UsageSummaryView: View {+ let usage: CodexUsageSnapshot?+ let isStale: Bool+ let showsActivity: Bool+ let onHoverContextChange: (UsageHeatmapHoverContext?) -> Void+ private let days: [UsageHeatmapDay?]+ private let peakTokens: Int+ @State private var hoverSelection: UsageHeatmapSelection?+ @State private var heatmapScreenFrame: CGRect?++ init(+ usage: CodexUsageSnapshot?,+ history: HistorySnapshot,+ showsActivity: Bool,+ isStale: Bool = false,+ onHoverContextChange: @escaping (UsageHeatmapHoverContext?) -> Void = { _ in }+ ) {+ self.usage = usage+ self.isStale = isStale+ self.showsActivity = showsActivity+ self.onHoverContextChange = onHoverContextChange++ let days = UsageHeatmapDay.grid(+ usage: usage,+ history: history,+ showsActivity: showsActivity,+ columnCount: UsageHeatmap.Metrics.columnCount,+ today: Date()+ )+ self.days = days+ peakTokens = max(days.lazy.compactMap { $0?.tokensForHeatmap }.max() ?? 0, 1)+ }++ var body: some View {+ content+ .markStale(isStale)+ .padding(MenuMetrics.panelPadding)+ .liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)+ .onAppear {+ clearHover()+ }+ .onDisappear {+ clearHover()+ }+ .onChange(of: days) { _, newDays in+ refreshHoveredDay(from: newDays)+ }+ .onChange(of: hoverContext) { _, context in+ onHoverContextChange(context)+ }+ .animation(Metrics.statusAnimation, value: usage)+ .animation(Metrics.statusAnimation, value: days)+ }++ @ViewBuilder+ private var content: some View {+ if usage?.hasAppServerData == true || showsActivity {+ VStack(alignment: .leading, spacing: 8) {+ metricsGrid++ if usage?.hasDailyUsageBuckets == true || showsActivity {+ UsageHeatmap(+ days: days,+ selection: $hoverSelection,+ peakTokens: peakTokens,+ onScreenFrameChange: { frame in+ heatmapScreenFrame = frame+ }+ )+ } else {+ dailyUsageUnavailable+ }+ }+ } else {+ Text("common.empty.no-data")+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, alignment: .center)+ .padding(.vertical, MenuMetrics.loadingVerticalPadding)+ }+ }++ private var metricsGrid: some View {+ HStack(alignment: .firstTextBaseline, spacing: Metrics.metricSpacing) {+ tokenMetric(label: "usage.summary.lifetime-tokens", value: usage?.summary.lifetimeTokens)+ tokenMetric(label: "usage.summary.peak-tokens", value: usage?.summary.peakDailyTokens)+ textMetric(+ label: "usage.summary.current-streak",+ value: Self.dayText(usage?.summary.currentStreakDays)+ )+ textMetric(+ label: "usage.summary.longest-streak",+ value: Self.dayText(usage?.summary.longestStreakDays)+ )+ textMetric(+ label: "usage.summary.longest-chat",+ value: Self.durationText(seconds: usage?.summary.longestRunningTurnSec)+ )+ }+ }++ private func tokenMetric(label: LocalizedStringResource, value: Int?) -> some View {+ metric(label: label) {+ if let value {+ TokenCountText(tokens: value)+ .minimumScaleFactor(0.8)+ } else {+ Text(verbatim: "--")+ .font(.caption.monospacedDigit().weight(.semibold))+ }+ }+ }++ private var dailyUsageUnavailable: some View {+ Text("usage.heatmap.no-data")+ .font(.caption)+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, alignment: .center)+ .frame(height: UsageHeatmap.Metrics.height)+ }++ private func textMetric(label: LocalizedStringResource, value: String) -> some View {+ metric(label: label) {+ Text(value)+ .font(.caption.monospacedDigit().weight(.semibold))+ .lineLimit(1)+ .minimumScaleFactor(0.8)+ }+ }++ private func metric(+ label: LocalizedStringResource,+ @ViewBuilder value: () -> some View+ ) -> some View {+ VStack(alignment: .leading, spacing: 2) {+ Text(label)+ .font(.caption2)+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, alignment: .center)++ value()+ .frame(maxWidth: .infinity, alignment: .center)+ }+ .frame(maxWidth: .infinity)+ }++ private static func dayText(_ days: Int?) -> String {+ guard let days else {+ return "--"+ }++ return String(localized: "duration.days-compact", defaultValue: "\(max(days, 0), specifier: "%lld")")+ }++ private static func durationText(seconds: Int?) -> String {+ guard let seconds else {+ return "--"+ }++ return CodexDurationFormat.activityText(for: TimeInterval(seconds))+ }++ private enum Metrics {+ static let metricSpacing: CGFloat = 8+ static let statusAnimation = Animation.codexStatus+ }++ private var hoverContext: UsageHeatmapHoverContext? {+ // 详情面板由控制器显示, SwiftUI 这里只负责传递屏幕坐标和数据+ hoverSelection.map {+ UsageHeatmapHoverContext(+ day: $0.day,+ showsActivity: showsActivity,+ alignmentScreenFrame: heatmapScreenFrame,+ preferredSide: UsageHeatmap.Metrics.preferredDetailSide(for: $0.column),+ peakTokens: peakTokens+ )+ }+ }++ private func refreshHoveredDay(from days: [UsageHeatmapDay?]) {+ guard let hoverSelection else {+ return+ }++ guard let updatedDay = days.compactMap(\.self).first(where: { $0.id == hoverSelection.day.id }) else {+ withAnimation(Metrics.statusAnimation) {+ self.hoverSelection = nil+ }+ return+ }++ guard updatedDay != hoverSelection.day else {+ return+ }++ withAnimation(Metrics.statusAnimation) {+ self.hoverSelection = UsageHeatmapSelection(+ day: updatedDay,+ column: hoverSelection.column,+ row: hoverSelection.row+ )+ }+ }++ private func clearHover() {+ hoverSelection = nil+ onHoverContextChange(nil)+ }+}diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex 0408b8e..51c13e3 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -6,11 +6,8 @@ struct AppSettingsView: View {@EnvironmentObject private var statusViewModel: CodexStatusViewModel@EnvironmentObject private var appUpdater: AppUpdater@StateObject private var loginItemSettings = LoginItemSettings()- @StateObject private var codexVersions = CodexCLIVersionViewModel()- @ObservedObject var proxySettings: CodexProxySettings- @State private var isShowingProxySettings = false- @ObservedObject var advancedModeSettings: AdvancedModeSettings- @ObservedObject var syncSettings: WorkflowSyncSettings+ @StateObject private var codexVersions = CodexVersionViewModel()+ @ObservedObject var syncSettings: SyncSettings@ObservedObject var globalHotKeySettings: GlobalHotKeySettings@ObservedObject var menuBarQuotaSettings: MenuBarQuotaSettingslet mainPanelSettings: MainPanelSettings@@ -19,7 +16,7 @@ struct AppSettingsView: View {@ObservedObject var autoResetSettings: AutoResetSettings@ObservedObject var keepAliveController: KeepAliveControllerlet onSyncChanged: (Bool) -> Void- let onRebuildWorkflowData: WorkflowSyncScheduler.RebuildHandler+ let onRebuildHistoryData: SyncScheduler.RebuildHandlerlet onOptionsAction: (SettingsOptionsPanelAction) -> Voidlet onContentHeightChanged: (CGFloat) -> Void@State private var selectedTab = SettingsTab.general@@ -30,7 +27,7 @@ struct AppSettingsView: View {@State private var rebuildableDates = [String]()@State private var selectedRebuildRange: RebuildDateRange?@State private var isShowingRebuildConfirmation = false- @State private var isRebuildingWorkflowData = false+ @State private var isRebuildingHistoryData = false@State private var rebuildResult: RebuildResult?@State private var helperFeatureConfirmation: HelperFeatureConfirmation?@@ -74,11 +71,6 @@ struct AppSettingsView: View {),isOuterSurface: true)- .sheet(isPresented: $isShowingProxySettings) {- ProxySettingsView(source: statusViewModel.codexSourceSelection, settings: proxySettings) {- statusViewModel.refreshAfterCurrent(trigger: .settings)- }- }.onAppear {loginItemSettings.refresh()syncSettings.refresh()@@ -90,7 +82,6 @@ struct AppSettingsView: View {refreshStatusRows()}.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in- advancedModeSettings.reconcileConfiguration()syncSettings.refresh()menuBarQuotaSettings.refresh()mainPanelSettings.refresh()@@ -129,18 +120,18 @@ struct AppSettingsView: View {onContentHeightChanged(pageHeight + Metrics.windowChromeHeight)}.alert(- LocalizedStringResource("workflow.rebuild.confirmation.title", defaultValue: "\(selectedRebuildDateKeys.count, specifier: "%lld")"),+ LocalizedStringResource("history.rebuild.confirmation.title", defaultValue: "\(selectedRebuildDateKeys.count, specifier: "%lld")"),isPresented: $isShowingRebuildConfirmation) {Button("common.action.cancel", role: .cancel) {}- Button("workflow.rebuild.action", role: .destructive) {- rebuildWorkflowData()+ Button("history.rebuild.action", role: .destructive) {+ rebuildHistoryData()}} message: {- Text(LocalizedStringResource("workflow.rebuild.confirmation.message", defaultValue: "\(selectedRebuildRange?.displayText ?? "")"))+ Text(LocalizedStringResource("history.rebuild.confirmation.message", defaultValue: "\(selectedRebuildRange?.displayText ?? "")"))}.alert(- rebuildResult?.title ?? LocalizedStringResource("workflow.rebuild.result.completed"),+ rebuildResult?.title ?? LocalizedStringResource("history.rebuild.result.completed"),isPresented: Binding(get: { rebuildResult != nil },set: {@@ -271,7 +262,6 @@ private extension AppSettingsView {LiquidGlassDivider()TaskGlowSettingsRow(settings: taskGlowSettings,- advancedModeSettings: advancedModeSettings,onOptionsAction: onOptionsAction)LiquidGlassDivider()@@ -292,8 +282,6 @@ private extension AppSettingsView {var advancedSettingsPage: some View {VStack(alignment: .leading, spacing: Metrics.rowSpacing) {- advancedModeRow- LiquidGlassDivider()notificationRowLiquidGlassDivider()autoResetRow@@ -302,14 +290,9 @@ private extension AppSettingsView {LiquidGlassDivider()syncRowLiquidGlassDivider()- ProxySettingsRow(settings: proxySettings) {- onOptionsAction(.closeAll)- isShowingProxySettings = true- }- LiquidGlassDivider()dataUpdateIntervalRowLiquidGlassDivider()- rebuildWorkflowDataRow+ rebuildHistoryDataRow}.padding(Metrics.panelPadding).liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius)@@ -458,24 +441,6 @@ private extension AppSettingsView {.frame(minHeight: SettingsRowMetrics.optionsButtonSize)}- var advancedModeRow: some View {- VStack(alignment: .leading, spacing: 4) {- SettingsToggleRow(- icon: "wrench.and.screwdriver",- title: "advanced-mode.name",- isOn: Binding(- get: { advancedModeSettings.isEnabled },- set: { advancedModeSettings.setEnabled($0) }- ),- isEnabled: !advancedModeSettings.isUpdating- )-- if let message = advancedModeSettings.errorMessage {- SettingsCaptionMessageRow(message: message)- }- }- }-var autoResetRow: some View {let isEnabled = autoResetSettings.isEnabledlet canShowOptions = isEnabled && keepAliveController.helperStatus == .enabled@@ -572,8 +537,7 @@ private extension AppSettingsView {keepAliveController.setEnabled(false)}}- ),- isEnabled: advancedModeSettings.isOperable && !advancedModeSettings.isUpdating+ )) {SettingsOptionsButton(isAvailable: canShowKeepAliveOptions) {onOptionsAction(@@ -641,9 +605,6 @@ private extension AppSettingsView {if let errorMessage = keepAliveController.errorMessage {return SettingsStatusCaption(message: errorMessage, isError: true)}- guard advancedModeSettings.isVerified else {- return SettingsStatusCaption(message: String(localized: "advanced-mode.hook.status.inactive"))- }if keepAliveController.isActivelyPreventingSleep,keepAliveController.sleepPreventionSource == .external {@@ -736,9 +697,7 @@ private extension AppSettingsView {var syncRowState: SyncRowState {SyncRowState(- isActive: syncSettings.isEffectivelyActive(isAdvancedModeEnabled: advancedModeSettings.isEnabled),- isAdvancedModeEnabled: advancedModeSettings.isEnabled,- isAdvancedModeUpdating: advancedModeSettings.isUpdating,+ isActive: syncSettings.isEffectivelyActive,isSyncAvailable: syncSettings.isSyncAvailable,isSyncing: syncSettings.isSyncing)@@ -746,13 +705,13 @@ private extension AppSettingsView {// MARK: - 数据重建- var rebuildWorkflowDataRow: some View {+ var rebuildHistoryDataRow: some View {HStack(spacing: SettingsRowMetrics.spacing) {Image(systemName: "arrow.clockwise.circle").frame(width: SettingsRowMetrics.iconWidth).foregroundStyle(.tint)- Text("workflow.rebuild.title")+ Text("history.rebuild.title").lineLimit(1).fixedSize(horizontal: true, vertical: false)@@ -761,7 +720,7 @@ private extension AppSettingsView {RebuildDatePicker(selection: $selectedRebuildRange,dataDateKeys: Set(rebuildableDates),- isEnabled: !isRebuildingWorkflowData+ isEnabled: !isRebuildingHistoryData).frame(width: RebuildLayoutMetrics.pickerWidth,@@ -769,12 +728,12 @@ private extension AppSettingsView {alignment: .leading)- if isRebuildingWorkflowData {+ if isRebuildingHistoryData {ProgressView().controlSize(.small).frame(minWidth: RebuildLayoutMetrics.actionMinimumWidth)} else {- Button("workflow.rebuild.action") {+ Button("history.rebuild.action") {isShowingRebuildConfirmation = true}.controlSize(.small)@@ -795,9 +754,9 @@ private extension AppSettingsView {func refreshRebuildableDates() {Task {let dates = await Task.detached(priority: .utility) {- let hookDates = WorkflowStorage.rebuildableEventDateKeys()- let tokenDates = await (try? CodexTokenHistoryStore().rebuildableDateKeys()) ?? []- return Set(hookDates + tokenDates).sorted()+ let eventDates = HistoryStorage.rebuildableEventDateKeys()+ let tokenDates = await (try? TokenHistoryStore().rebuildableDateKeys()) ?? []+ return Set(eventDates + tokenDates).sorted()}.valuerebuildableDates = dates}@@ -810,25 +769,22 @@ private extension AppSettingsView {refreshRebuildableDates()}- func rebuildWorkflowData() {+ func rebuildHistoryData() {let dateKeys = selectedRebuildDateKeys- guard !dateKeys.isEmpty, !isRebuildingWorkflowData else {+ guard !dateKeys.isEmpty, !isRebuildingHistoryData else {return}- isRebuildingWorkflowData = true+ isRebuildingHistoryData = truerebuildResult = nil- onRebuildWorkflowData(dateKeys) { result in- isRebuildingWorkflowData = false+ onRebuildHistoryData(dateKeys) { result in+ isRebuildingHistoryData = falserefreshRebuildableDates()switch result {case let .success(summary):rebuildResult = RebuildResult(- message: Self.rebuildSuccessMessage(- for: summary,- autoRetryAvailable: advancedModeSettings.isEnabled- ),+ message: Self.rebuildSuccessMessage(for: summary),isError: false)case let .failure(error):@@ -849,39 +805,35 @@ private extension AppSettingsView {static let rebuildFailedDateListLimit = 3/// 未完成的日期只列前几个, 避免长范围重建时结果过长- /// autoRetryAvailable: 常规维护只在进阶模式开启时运行, 关闭时不能承诺自动重试static func rebuildSuccessMessage(- for summary: WorkflowDataRebuildSummary,- autoRetryAvailable: Bool+ for summary: HistoryDataRebuildSummary) -> String {var message = String(- localized: "workflow.rebuild.summary.completed",+ localized: "history.rebuild.summary.completed",defaultValue: "\(summary.rebuiltDateCount, specifier: "%lld")\(summary.eventCount, specifier: "%lld")")- message += String(localized: "workflow.rebuild.summary.token-record-count", defaultValue: "\(summary.tokenTurnCount, specifier: "%lld")")+ message += String(localized: "history.rebuild.summary.token-record-count", defaultValue: "\(summary.tokenTurnCount, specifier: "%lld")")if summary.didFailTokenRebuild {- message += String(localized: "workflow.rebuild.summary.token-history-incomplete")+ message += String(localized: "history.rebuild.summary.token-history-incomplete")}if summary.corruptLineCount > 0 {- message += String(localized: "workflow.rebuild.summary.skipped-invalid-events", defaultValue: "\(summary.corruptLineCount, specifier: "%lld")")+ message += String(localized: "history.rebuild.summary.skipped-invalid-events", defaultValue: "\(summary.corruptLineCount, specifier: "%lld")")}if !summary.failedDateKeys.isEmpty {let listed = summary.failedDateKeys.prefix(rebuildFailedDateListLimit)var dates = listed.joined(separator: ", ")if summary.failedDateKeys.count > listed.count {- dates += String(localized: "workflow.rebuild.summary.additional-dates")+ dates += String(localized: "history.rebuild.summary.additional-dates")}- message += String(localized: "workflow.rebuild.summary.incomplete-dates", defaultValue: "\(summary.failedDateKeys.count, specifier: "%lld")\(dates)")- message += autoRetryAvailable- ? String(localized: "workflow.rebuild.summary.retry-later")- : String(localized: "workflow.rebuild.summary.retry-after-advanced-mode-enabled")+ message += String(localized: "history.rebuild.summary.incomplete-dates", defaultValue: "\(summary.failedDateKeys.count, specifier: "%lld")\(dates)")+ message += String(localized: "history.rebuild.summary.retry-later")}if summary.didFailSyncReplacementMarking {- message += String(localized: "workflow.rebuild.summary.sync-replacement-marking-failed")+ message += String(localized: "history.rebuild.summary.sync-replacement-marking-failed")} else if summary.isSyncReplacementPending {- message += String(localized: "workflow.rebuild.summary.cloud-replacement-pending")+ message += String(localized: "history.rebuild.summary.cloud-replacement-pending")}return message@@ -978,16 +930,12 @@ private extension AppSettingsView {CodexVersionSection(snapshot: codexVersions.snapshot,connectionInfo: statusViewModel.codexConnectionInfo,- sourceSelection: statusViewModel.pendingCodexSourceSelection ?? statusViewModel.codexSourceSelection,isReconnecting: statusViewModel.isReconnecting,isBusy: statusViewModel.isRefreshing || statusViewModel.isReconnecting || codexVersions.isRefreshing,errorMessage: statusViewModel.connectionErrorMessage,- unavailableSource: statusViewModel.unavailableConnectionSource,- onReconnect: { selection in+ onReconnect: {Task { @MainActor in- if await statusViewModel.reconnectCodex(selection: selection, requiresAdvancedMode: advancedModeSettings.isEnabled) {- advancedModeSettings.reconcileConfiguration()- }+ _ = await statusViewModel.reconnectCodex()codexVersions.refresh(force: true)}}@@ -1053,321 +1001,12 @@ private extension AppSettingsView {}}-private enum RebuildLayoutMetrics {- static let pickerWidth: CGFloat = 190- static let controlHeight: CGFloat = 26- static let actionMinimumWidth: CGFloat = 42-}--private struct RebuildDatePicker: View {- @Binding var selection: RebuildDateRange?- let dataDateKeys: Set<String>- let isEnabled: Bool-- @State private var isPresented = false- @State private var displayedMonth = Date()-- private enum Metrics {- static let daySize: CGFloat = 28- static let columnSpacing: CGFloat = 6- static let visibleWeekCount = 6- static let popoverWidth: CGFloat = 260- static let popoverHeight: CGFloat = 296- }-- private static let columns = Array(- repeating: GridItem(.fixed(Metrics.daySize), spacing: Metrics.columnSpacing),- count: 7- )- var body: some View {- Button {- let focusedDateKey = selection?.endDateKey ?? selection?.startDateKey- if let focusedDateKey,- let selectedDate = CodexDateFormat.dayDate(from: focusedDateKey) {- displayedMonth = startOfMonth(for: selectedDate)- }- isPresented.toggle()- } label: {- HStack(spacing: 5) {- Image(systemName: "calendar")- .font(.system(size: 11, weight: .medium))- .foregroundStyle(.tint)-- Group {- if let selection {- Text(verbatim: selection.displayText)- } else {- Text("date-picker.select-range")- }- }- .font(.caption.monospacedDigit().weight(.medium))- .foregroundStyle(.primary)- .lineLimit(1)- .minimumScaleFactor(0.9)-- Spacer(minLength: 0)-- Image(systemName: "chevron.down")- .font(.system(size: 8, weight: .semibold))- .foregroundStyle(.secondary)- }- .padding(.horizontal, 7)- .frame(maxWidth: .infinity, minHeight: RebuildLayoutMetrics.controlHeight)- .background {- RoundedRectangle(cornerRadius: 7, style: .continuous)- .fill(Color(nsColor: .controlBackgroundColor).opacity(0.72))- }- .overlay {- RoundedRectangle(cornerRadius: 7, style: .continuous)- .strokeBorder(- isPresented ? Color.accentColor.opacity(0.70) : Color.primary.opacity(0.12),- lineWidth: isPresented ? 1.2 : 0.8- )- }- .shadow(color: .black.opacity(0.06), radius: 2, y: 1)- }- .buttonStyle(.plain)- .disabled(!isEnabled)- .help("date-picker.select-range")- .popover(isPresented: $isPresented, arrowEdge: .bottom) {- calendarPopover- }- }-- private var calendarPopover: some View {- let weekdaySymbols = weekdaySymbols-- return VStack(spacing: 10) {- HStack(spacing: 8) {- monthNavigationButton(- systemImage: "chevron.left",- help: "date-picker.previous-month",- offset: -1- )-- Spacer()-- Text(monthTitle)- .font(.system(.body, design: .rounded).weight(.semibold))- .monospacedDigit()-- Spacer()-- monthNavigationButton(- systemImage: "chevron.right",- help: "date-picker.next-month",- offset: 1- )- }-- LazyVGrid(columns: Self.columns, spacing: 5) {- ForEach(weekdaySymbols.indices, id: \.self) { index in- Text(verbatim: weekdaySymbols[index])- .font(.system(size: 10, weight: .medium))- .foregroundStyle(.secondary)- .frame(width: Metrics.daySize, height: 18)- }-- ForEach(monthDates, id: \.self) { date in- dayButton(for: date)- }- }-- Group {- if selection?.isComplete == false {- Text("date-picker.select-end")- } else {- Text("date-picker.select-start")- }- }- .font(.caption2)- .foregroundStyle(.secondary)- .lineLimit(1)- .frame(height: 14)- }- .padding(12)- .frame(width: Metrics.popoverWidth, height: Metrics.popoverHeight)- }-- private func monthNavigationButton(- systemImage: String,- help: LocalizedStringResource,- offset: Int- ) -> some View {- Button {- guard let nextMonth = calendar.date(byAdding: .month, value: offset, to: displayedMonth) else {- return- }- displayedMonth = nextMonth- } label: {- Image(systemName: systemImage)- .font(.system(size: 10, weight: .semibold))- .frame(width: 24, height: 22)- .background {- RoundedRectangle(cornerRadius: 6, style: .continuous)- .fill(Color.primary.opacity(0.055))- }- }- .buttonStyle(.plain)- .disabled(!canMoveMonth(by: offset))- .help(help)- }-- private func dayButton(for date: Date) -> some View {- let dateKey = WorkflowStorage.dateKey(for: date)- let isSelectable = selectableDateRange.contains(calendar.startOfDay(for: date))- let hasData = dataDateKeys.contains(dateKey)- let isInDisplayedMonth = calendar.isDate(- date,- equalTo: displayedMonth,- toGranularity: .month- )- let isStart = selection?.startDateKey == dateKey- let isEnd = selection?.endDateKey == dateKey- let isEndpoint = isStart || isEnd- let isInCompletedRange = selection?.contains(dateKey) == true- let day = calendar.component(.day, from: date)-- return Button {- select(dateKey)- } label: {- ZStack(alignment: .bottom) {- RoundedRectangle(cornerRadius: 7, style: .continuous)- .fill(dayBackgroundColor(- isEndpoint: isEndpoint,- isInCompletedRange: isInCompletedRange- ))-- Text(String(day))- .font(.system(size: 11, weight: isEndpoint ? .semibold : .regular))- .foregroundStyle(dayTextColor(- isSelectable: isSelectable,- isEndpoint: isEndpoint,- isInDisplayedMonth: isInDisplayedMonth- ))- .frame(maxWidth: .infinity, maxHeight: .infinity)-- if hasData, !isEndpoint {- Circle()- .fill(Color.accentColor.opacity(0.75))- .frame(width: 2.5, height: 2.5)- .padding(.bottom, 2)- }- }- .frame(width: Metrics.daySize, height: Metrics.daySize)- .contentShape(Rectangle())- }- .buttonStyle(.plain)- .disabled(!isSelectable)- }-- private var monthTitle: String {- Self.monthFormatter.string(from: displayedMonth)- }-- private var monthDates: [Date] {- let monthStart = startOfMonth(for: displayedMonth)- let leadingDayCount = (- calendar.component(.weekday, from: monthStart) - calendar.firstWeekday + 7- ) % 7- guard let gridStart = calendar.date(- byAdding: .day,- value: -leadingDayCount,- to: monthStart- ) else {- return []- }-- let visibleDayCount = Self.columns.count * Metrics.visibleWeekCount- return (0 ..< visibleDayCount).compactMap { dayOffset in- calendar.date(byAdding: .day, value: dayOffset, to: gridStart)- }- }-- private var calendar: Calendar {- var calendar = Calendar(identifier: .gregorian)- calendar.locale = .autoupdatingCurrent- calendar.timeZone = .autoupdatingCurrent- return calendar- }-- private var weekdaySymbols: [String] {- let symbols = calendar.veryShortStandaloneWeekdaySymbols-- let firstIndex = max(0, min(symbols.count - 1, calendar.firstWeekday - 1))- return Array(symbols[firstIndex...] + symbols[..<firstIndex])- }-- private static let monthFormatter: DateFormatter = {- let formatter = DateFormatter()- formatter.locale = .autoupdatingCurrent- formatter.calendar = Calendar(identifier: .gregorian)- formatter.timeZone = .autoupdatingCurrent- formatter.setLocalizedDateFormatFromTemplate("yyyyMMMM")- return formatter- }()-- private var selectableDateRange: ClosedRange<Date> {- let today = calendar.startOfDay(for: Date())- let cutoff = WorkflowStorage.retentionCutoffDate(today: today, calendar: calendar)- return cutoff ... today- }-- private func startOfMonth(for date: Date) -> Date {- let components = calendar.dateComponents([.year, .month], from: date)- return calendar.date(from: components) ?? date- }-- private func canMoveMonth(by offset: Int) -> Bool {- guard let candidate = calendar.date(byAdding: .month, value: offset, to: displayedMonth) else {- return false- }-- let month = startOfMonth(for: candidate)- return month >= startOfMonth(for: selectableDateRange.lowerBound)- && month <= startOfMonth(for: selectableDateRange.upperBound)- }-- private func select(_ dateKey: String) {- if let selection, !selection.isComplete {- self.selection = selection.completing(with: dateKey)- isPresented = false- } else {- selection = .starting(at: dateKey)- }- }-- private func dayBackgroundColor(- isEndpoint: Bool,- isInCompletedRange: Bool- ) -> Color {- if isEndpoint {- return .accentColor- }- return isInCompletedRange ? Color.accentColor.opacity(0.16) : .clear- }-- private func dayTextColor(- isSelectable: Bool,- isEndpoint: Bool,- isInDisplayedMonth: Bool- ) -> Color {- if isEndpoint {- return .white- }- if !isInDisplayedMonth {- return .codexSecondaryLabel.opacity(isSelectable ? 0.58 : 0.24)- }- return isSelectable ? .codexLabel : .codexSecondaryLabel.opacity(0.36)- }-}-private struct RebuildResult {let message: Stringlet isError: Boolvar title: LocalizedStringResource {- isError ? "workflow.rebuild.result.failed" : "workflow.rebuild.result.completed"+ isError ? "history.rebuild.result.failed" : "history.rebuild.result.completed"}}@@ -1418,15 +1057,13 @@ private struct SettingsPageHeightPreferenceKey: PreferenceKey {}private struct SyncRowState {- /// 由 WorkflowSyncSettings.isEffectivelyActive 统一判定, 视图层不再拼接业务谓词+ /// 由 SyncSettings.isEffectivelyActive 统一判定, 视图层不再拼接业务谓词let isActive: Bool- let isAdvancedModeEnabled: Bool- let isAdvancedModeUpdating: Boollet isSyncAvailable: Boollet isSyncing: Boolvar canToggle: Bool {- isAdvancedModeEnabled && !isAdvancedModeUpdating && isSyncAvailable+ isSyncAvailable}func shouldShowSyncStatus(lastSyncText: String?) -> Bool {diff --git a/CodexBar/Views/Settings/AppearanceSettingsRows.swift b/CodexBar/Views/Settings/AppearanceSettingsRows.swiftindex af4887d..9a83552 100644--- a/CodexBar/Views/Settings/AppearanceSettingsRows.swift+++ b/CodexBar/Views/Settings/AppearanceSettingsRows.swift@@ -17,12 +17,11 @@ struct MainPanelAnimationsSettingsRow: View {struct TaskGlowSettingsRow: View {@ObservedObject var settings: TaskGlowSettings- @ObservedObject var advancedModeSettings: AdvancedModeSettingslet onOptionsAction: (SettingsOptionsPanelAction) -> Void@State private var anchorProvider = ScreenFrameProvider()private var canShowOptions: Bool {- settings.isEnabled && advancedModeSettings.isOperable && !advancedModeSettings.isUpdating+ settings.isEnabled}var body: some View {@@ -30,10 +29,9 @@ struct TaskGlowSettingsRow: View {icon: "light.max",title: "settings.task-glow.title",isOn: Binding(- get: { advancedModeSettings.isOperable && settings.isEnabled },+ get: { settings.isEnabled },set: { settings.setEnabled($0) }- ),- isEnabled: advancedModeSettings.isOperable && !advancedModeSettings.isUpdating+ )) {SettingsOptionsButton(isAvailable: canShowOptions) {onOptionsAction(.toggle(panel: .taskGlow, anchorProvider: anchorProvider))diff --git a/CodexBar/Views/Settings/CodexSourcePicker.swift b/CodexBar/Views/Settings/CodexSourcePicker.swiftdeleted file mode 100644index 87900c6..0000000--- a/CodexBar/Views/Settings/CodexSourcePicker.swift+++ /dev/null@@ -1,439 +0,0 @@-import AppKit-import QuartzCore-import SwiftUI--struct CodexSourcePicker: View {- let selection: CodexCLISourceSelection- let options: [CodexCLISourceSelection]- let isEnabled: Bool- let onSelect: (CodexCLISourceSelection) -> Void-- var body: some View {- SettingsDropdownPicker(- selection: selection,- options: options,- isEnabled: isEnabled,- title: options.contains(selection) ? selection.title : String(localized: "codex-cli.source.action.select"),- optionTitle: { $0.title },- onSelect: onSelect- )- }-}--/// 开合和悬停状态留在选择器内部, 避免交互时重新计算整个设置区域-struct SettingsDropdownPicker<Option: Hashable & Sendable>: View {- let selection: Option- let options: [Option]- let isEnabled: Bool- let title: String- var height: CGFloat = SettingsRowMetrics.optionsButtonSize- let optionTitle: (Option) -> String- let onSelect: (Option) -> Void- @State private var isHovered = false- @State private var isPresented = false-- var body: some View {- let shape = RoundedRectangle(cornerRadius: 5, style: .continuous)- Button {- isPresented.toggle()- } label: {- HStack(spacing: 6) {- ZStack(alignment: .leading) {- ForEach(options, id: \.self) { option in- Text(optionTitle(option)).hidden()- }- Text(title)- .foregroundStyle(isEnabled ? .primary : .secondary)- }- .font(.caption.weight(.medium))- .lineLimit(1)-- Image(systemName: "chevron.down")- .font(.system(size: 9, weight: .semibold))- .foregroundStyle(.secondary)- .rotationEffect(.degrees(isPresented ? 180 : 0))- .animation(.codexStatus, value: isPresented)- }- .padding(.horizontal, 8)- .frame(height: height)- .background {- shape- .fill(.primary.opacity((isHovered || isPresented) && isEnabled ? 0.06 : 0))- .animation(.codexStatus, value: isHovered || isPresented)- }- .liquidGlassBadge(tint: isEnabled ? .accentColor : .secondary, in: shape)- .contentShape(shape)- }- .buttonStyle(.plain)- .controlSize(.small)- .fixedSize()- .disabled(!isEnabled)- .onHover { isHovered = $0 }- .background {- SettingsDropdown(- isPresented: $isPresented,- selection: selection,- options: options,- isEnabled: isEnabled,- optionTitle: optionTitle,- onSelect: onSelect- )- }- .onDisappear {- isPresented = false- }- .onChange(of: isEnabled) { _, isEnabled in- if !isEnabled {- isPresented = false- }- }- .onChange(of: options) { _, _ in- isPresented = false- }- }-}--/// 浮层开合由同一处处理, 快速点击从当前呈现位置反向动画-private struct SettingsDropdown<Option: Hashable & Sendable>: NSViewRepresentable {- @Binding var isPresented: Bool- let selection: Option- let options: [Option]- let isEnabled: Bool- let optionTitle: (Option) -> String- let onSelect: (Option) -> Void-- func makeCoordinator() -> Coordinator {- Coordinator(configuration: self)- }-- func makeNSView(context: Context) -> AnchorView {- let view = AnchorView()- context.coordinator.anchorView = view- view.onWindowChange = { [weak coordinator = context.coordinator] in- coordinator?.scheduleReconcile()- }- return view- }-- func updateNSView(_: AnchorView, context: Context) {- context.coordinator.configuration = self- context.coordinator.scheduleReconcile()- }-- static func dismantleNSView(_ view: AnchorView, coordinator: Coordinator) {- view.onWindowChange = nil- coordinator.dispose()- }-- final class AnchorView: NSView {- var onWindowChange: (() -> Void)?-- override func hitTest(_: NSPoint) -> NSView? {- nil- }-- override func viewDidMoveToWindow() {- super.viewDidMoveToWindow()- onWindowChange?()- }- }-- final class Coordinator: NSObject, NSPopoverDelegate {- var configuration: SettingsDropdown- weak var anchorView: AnchorView?- private let popover = NSPopover()- private weak var observedWindow: NSWindow?- private var targetIsVisible = false- private var presentedOrigin = NSPoint.zero- private var animationGeneration = 0- private var reconcileTask: Task<Void, Never>?- private var localMonitor: Any?- private var observers: [NSObjectProtocol] = []- private var isAnchorPressInProgress = false- private var isDisposed = false-- init(configuration: SettingsDropdown) {- self.configuration = configuration- super.init()- popover.delegate = self- popover.behavior = .applicationDefined- popover.animates = false- }-- func scheduleReconcile() {- guard reconcileTask == nil else { return }- reconcileTask = Task { @MainActor [weak self] in- await Task.yield()- guard let self, !Task.isCancelled else { return }- reconcileTask = nil- reconcile()- }- }-- private func setPresented(_ isPresented: Bool) {- configuration.isPresented = isPresented && configuration.isEnabled- reconcile()- }-- private func reconcile() {- guard !isDisposed else { return }- guard let anchorView, let window = anchorView.window, window.isVisible else {- configuration.isPresented = false- closeImmediately()- removeMonitors()- return- }- installMonitors(for: window)- let wantsPresentation = configuration.isPresented && configuration.isEnabled- guard wantsPresentation != targetIsVisible else { return }- if wantsPresentation, !popover.isShown {- guard !anchorView.visibleRect.isEmpty, show(relativeTo: anchorView) else {- configuration.isPresented = false- return- }- }- targetIsVisible = wantsPresentation- if wantsPresentation {- popover.contentViewController?.view.window?.makeKey()- }- animateVisibility(wantsPresentation)- }-- private func show(relativeTo anchor: NSView) -> Bool {- let content = SettingsDropdownOptions(- selection: configuration.selection,- options: configuration.options,- optionTitle: configuration.optionTitle,- onSelect: { [weak self] selection in- guard let self else { return }- setPresented(false)- configuration.onSelect(selection)- }- )- let host = NSHostingController(rootView: content)- host.sizingOptions = [.preferredContentSize]- guard let size = host.view.validFittingSize else { return false }- popover.contentViewController = host- popover.contentSize = size- popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .minY)- guard popover.isShown, let window = popover.contentViewController?.view.window else {- popover.close()- return false- }- presentedOrigin = window.frame.origin- window.alphaValue = 0- window.setFrameOrigin(NSPoint(x: presentedOrigin.x, y: presentedOrigin.y + 8))- return true- }-- private func animateVisibility(_ isVisible: Bool) {- guard let window = popover.contentViewController?.view.window else {- closeImmediately()- return- }- animationGeneration += 1- let generation = animationGeneration- let targetOpacity: CGFloat = isVisible ? 1 : 0- let targetFrame = NSRect(- origin: NSPoint(x: presentedOrigin.x, y: presentedOrigin.y + (isVisible ? 0 : 8)),- size: window.frame.size- )- // 整个窗口一起移动和淡入淡出, 避免系统边框和材质与内部图层变换不同步- // animator 会从当前值转向新目标, 连续点击无需等待上一次动画结束- NSAnimationContext.runAnimationGroup { context in- context.duration = 0.18 * abs(targetOpacity - window.alphaValue)- context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)- window.animator().alphaValue = targetOpacity- window.animator().setFrame(targetFrame, display: true)- } completionHandler: { [weak self] in- Task { @MainActor [weak self] in- self?.finishAnimation(generation: generation)- }- }- }-- private func finishAnimation(generation: Int) {- guard !isDisposed, animationGeneration == generation, !targetIsVisible else { return }- popover.close()- }-- private func closeImmediately() {- animationGeneration += 1- if let window = popover.contentViewController?.view.window {- NSAnimationContext.runAnimationGroup { context in- context.duration = 0- window.animator().alphaValue = window.alphaValue- window.animator().setFrame(window.frame, display: true)- }- }- targetIsVisible = false- popover.close()- }-- func popoverWillClose(_: Notification) {- animationGeneration += 1- targetIsVisible = false- configuration.isPresented = false- }-- private func installMonitors(for window: NSWindow) {- guard observedWindow !== window || localMonitor == nil else { return }- removeMonitors()- observedWindow = window- // 锚点的按下和抬起始终走同一条路径, 不随浮层开关切换回 SwiftUI 按钮的鼠标追踪- localMonitor = NSEvent.addLocalMonitorForEvents(matching: [- .leftMouseDown, .leftMouseUp, .leftMouseDragged, .rightMouseDown, .otherMouseDown, .keyDown- ]) { [weak self] event in- guard let self else { return event }- return handleEvent(event)- }- for (name, object) in [- (NSApplication.didResignActiveNotification, NSApplication.shared as AnyObject),- (NSWindow.willCloseNotification, window as AnyObject),- (NSWindow.willMiniaturizeNotification, window as AnyObject)- ] {- observers.append(NotificationCenter.default.addObserver(forName: name, object: object, queue: .main) { [weak self] _ in- MainActor.assumeIsolated {- guard let self else { return }- if name == NSWindow.willCloseNotification {- self.configuration.isPresented = false- self.closeImmediately()- self.removeMonitors()- } else {- self.setPresented(false)- }- }- })- }- }-- private func handleEvent(_ event: NSEvent) -> NSEvent? {- if isAnchorPressInProgress, event.type == .leftMouseUp || event.type == .leftMouseDragged {- if event.type == .leftMouseUp {- isAnchorPressInProgress = false- }- return nil- }- if event.type == .leftMouseDown, configuration.isEnabled,- let anchorView, !anchorView.isHiddenOrHasHiddenAncestor,- event.window === anchorView.window,- anchorView.bounds.intersection(anchorView.visibleRect).contains(anchorView.convert(event.locationInWindow, from: nil)) {- isAnchorPressInProgress = true- setPresented(!configuration.isPresented)- return nil- }- guard popover.isShown else { return event }- if event.type == .keyDown {- guard event.keyCode == 53 else { return event }- setPresented(false)- return nil- }- if [.leftMouseDown, .rightMouseDown, .otherMouseDown].contains(event.type),- event.window !== popover.contentViewController?.view.window {- setPresented(false)- }- return event- }-- private func removeMonitors() {- if let localMonitor {- NSEvent.removeMonitor(localMonitor)- self.localMonitor = nil- }- observers.forEach(NotificationCenter.default.removeObserver)- observers.removeAll()- observedWindow = nil- isAnchorPressInProgress = false- }-- func dispose() {- isDisposed = true- reconcileTask?.cancel()- popover.delegate = nil- closeImmediately()- removeMonitors()- }- }-}--private struct SettingsDropdownOptions<Option: Hashable & Sendable>: View {- let selection: Option- let options: [Option]- let optionTitle: (Option) -> String- let onSelect: (Option) -> Void- @State private var highlightedSelection: Option?-- var body: some View {- VStack(spacing: 3) {- ForEach(options, id: \.self) { option in- Button {- onSelect(option)- } label: {- HStack(spacing: 8) {- Image(systemName: "checkmark")- .font(.system(size: 10, weight: .semibold))- .foregroundStyle(.tint)- .opacity(option == selection ? 1 : 0)- .frame(width: 12)-- Text(optionTitle(option))- .font(.caption.weight(.medium))- .lineLimit(1)- .frame(maxWidth: .infinity, alignment: .leading)-- Color.clear- .frame(width: 12, height: 10)- }- .padding(.horizontal, 8)- .frame(height: 28)- .background {- RoundedRectangle(cornerRadius: 14, style: .continuous)- .fill(.primary.opacity(highlightedSelection == option ? 0.08 : 0))- }- .contentShape(Rectangle())- }- .buttonStyle(.plain)- .focusable(false)- .onHover { isHovered in- if isHovered {- highlightedSelection = option- }- }- }- }- .padding(6)- .fixedSize(horizontal: true, vertical: false)- // 列表接收方向键, 展开时不自动聚焦或高亮某个选项- .focusable()- .focusEffectDisabled()- // 经过行间空隙时保留高亮, 离开列表才清除, 避免闪回键盘焦点所在行- .onHover { isHovered in- if !isHovered {- highlightedSelection = nil- }- }- .onKeyPress(.upArrow) {- moveFocus(by: -1)- return .handled- }- .onKeyPress(.downArrow) {- moveFocus(by: 1)- return .handled- }- .onKeyPress(.return) {- if let selected = highlightedSelection {- onSelect(selected)- }- return .handled- }- }-- private func moveFocus(by offset: Int) {- guard !options.isEmpty else { return }- if let index = highlightedSelection.flatMap({ options.firstIndex(of: $0) }) {- highlightedSelection = options[(index + offset + options.count) % options.count]- } else {- highlightedSelection = offset > 0 ? options.first : options.last- }- }-}diff --git a/CodexBar/Views/Settings/CodexVersionSection.swift b/CodexBar/Views/Settings/CodexVersionSection.swiftindex 58556fa..0630a17 100644--- a/CodexBar/Views/Settings/CodexVersionSection.swift+++ b/CodexBar/Views/Settings/CodexVersionSection.swift@@ -1,18 +1,16 @@import AppKitimport SwiftUI-/// Codex CLI/App 版本区, 同时展示磁盘版本和当前 app-server 运行版本+/// 分别展示安装版本和共享服务运行版本, 只重连当前客户端struct CodexVersionSection: View {@EnvironmentObject private var animationState: SettingsWindowAnimationState- let snapshot: CodexCLIVersionSnapshot- let connectionInfo: CodexCLIConnectionInfo?- let sourceSelection: CodexCLISourceSelection+ let snapshot: CodexVersionSnapshot+ let connectionInfo: CodexServerConnectionInfo?let isReconnecting: Boollet isBusy: Boollet errorMessage: String?- let unavailableSource: CodexCLIExecutableSource?- let onReconnect: (CodexCLISourceSelection?) -> Void- @State private var copiedPathResetTasks: [CodexCLIExecutableSource: Task<Void, Never>] = [:]+ let onReconnect: () -> Void+ @State private var copiedPathResetTasks: [String: Task<Void, Never>] = [:]var body: some View {VStack(alignment: .leading, spacing: Metrics.rowSpacing) {@@ -26,21 +24,16 @@ struct CodexVersionSection: View {reconnectButtonSpacer()-- sourcePicker}- if !displayedItems.isEmpty {- LiquidGlassDivider()- .padding(.leading, Metrics.iconWidth + 10)+ VStack(alignment: .leading, spacing: Metrics.rowSpacing) {+ daemonRow- VStack(alignment: .leading, spacing: Metrics.rowSpacing) {- ForEach(displayedItems) { item in- codexVersionRow(icon: item.source == .global ? "terminal" : "app.badge", item: item)- }+ ForEach(displayedItems) { item in+ codexVersionRow(icon: item.source == .global ? "terminal" : "app.badge", item: item)}- .padding(.leading, Metrics.childIndent)}+ .padding(.leading, Metrics.childIndent)if let message = errorMessage {Text(message)@@ -54,27 +47,15 @@ struct CodexVersionSection: View {}}- private var sourcePicker: some View {- CodexSourcePicker(- selection: sourceSelection,- options: availableSelections,- isEnabled: !isBusy- ) { selection in- guard !isBusy, availableSelections.contains(selection), selection != sourceSelection else { return }- onReconnect(selection)- }- .frame(minHeight: SettingsRowMetrics.optionsButtonSize)- }-private var reconnectButton: some View {let isWorking = isBusy || isReconnecting- let isEnabled = !isWorking && isSourceInstalled(sourceSelection)+ let isEnabled = !isWorkinglet label: LocalizedStringKey = isReconnecting? "settings.codex.connection.status.reconnecting": "settings.codex.connection.action.reconnect"return Button {- onReconnect(nil)+ onReconnect()} label: {let icon = Image(systemName: "cable.coaxial")Group {@@ -102,32 +83,47 @@ struct CodexVersionSection: View {.help(label)}- private var installedItems: [CodexCLIVersionItem] {+ private var displayedItems: [CodexVersionItem] {[snapshot.global, snapshot.bundled].filter { $0.path != nil }}- private var displayedItems: [CodexCLIVersionItem] {- [snapshot.global, snapshot.bundled].filter {- $0.path != nil || $0.source == connectionInfo?.source- || (snapshot.refreshedAt != .distantPast- && ($0.source == sourceSelection.source || $0.source == unavailableSource))- }- }-- private var availableSelections: [CodexCLISourceSelection] {- CodexCLISourceSelection.allCases.filter { $0 == .automatic || isSourceInstalled($0) }- }+ private var daemonRow: some View {+ HStack(alignment: .top, spacing: 10) {+ Image(systemName: "cpu")+ .frame(width: Metrics.iconWidth)+ .foregroundStyle(.tint)+ Text("settings.codex.daemon.title")+ .foregroundStyle(.secondary)+ Spacer(minLength: 28)+ VStack(alignment: .trailing, spacing: 3) {+ if let info = connectionInfo {+ HStack(spacing: 12) {+ Text("settings.codex.daemon.in-use")+ .font(.caption2.weight(.medium))+ .foregroundStyle(.green)+ .padding(.horizontal, 6)+ .padding(.vertical, 2)+ .liquidGlassCapsule(tint: .green)- private func isSourceInstalled(_ selection: CodexCLISourceSelection) -> Bool {- guard let source = selection.source else { return !installedItems.isEmpty }- return installedItems.contains { $0.source == source }+ Text(info.version ?? String(localized: "codex.version.unknown"))+ .monospacedDigit()+ .foregroundStyle(.secondary)+ }+ CopyablePathText(path: info.socketPath, isCopied: copiedPathResetTasks["shared"] != nil)+ .onTapGesture { copyPathToPasteboard(info.socketPath, key: "shared") }+ } else {+ Text("settings.codex.daemon.disconnected")+ .foregroundStyle(.secondary)+ }+ }+ .frame(maxWidth: Metrics.versionColumnWidth, alignment: .trailing)+ }}- private func codexVersionRow(icon: String, item: CodexCLIVersionItem) -> some View {- let row = CodexCLIVersionDisplay(item: item, connection: connectionInfo)+ private func codexVersionRow(icon: String, item: CodexVersionItem) -> some View {+ let row = CodexVersionDisplay(item: item)let isUnavailable = snapshot.refreshedAt != .distantPast && item.path == nil- let statusColor: Color = isUnavailable ? .orange : .green- let isPathCopied = copiedPathResetTasks[item.source] != nil+ let isPathCopied = copiedPathResetTasks[item.source.rawValue] != nilreturn HStack(alignment: .top, spacing: 10) {Image(systemName: icon)@@ -141,16 +137,6 @@ struct CodexVersionSection: View {VStack(alignment: .trailing, spacing: 3) {HStack(spacing: 12) {- if row.isCurrent || isUnavailable {- Text(isUnavailable ? "codex-cli.source.status.unavailable" : "codex-cli.source.status.in-use")- .font(.caption2.weight(.medium))- .foregroundStyle(statusColor)- .padding(.horizontal, 6)- .padding(.vertical, 2)- .liquidGlassCapsule(tint: statusColor)- .transition(.opacity)- }-if row.hasVersion || !isUnavailable {Text(row.displayVersion).font(row.hasVersion ? .body.monospacedDigit() : .body)@@ -160,17 +146,8 @@ struct CodexVersionSection: View {.animation(Metrics.statusAnimation, value: row.displayVersion)}}- .animation(Metrics.statusAnimation, value: row.isCurrent).animation(Metrics.statusAnimation, value: isUnavailable)- if let newerInstalledVersion = row.newerInstalledVersion {- Text(LocalizedStringResource("codex-cli.version.newer-installed", defaultValue: "\(newerInstalledVersion)"))- .font(.caption2.monospacedDigit())- .foregroundStyle(.orange)- .lineLimit(1)- .transition(.opacity)- }-if let path = row.path {CopyablePathText(path: path, isCopied: isPathCopied).animation(Metrics.statusAnimation, value: isPathCopied)@@ -180,26 +157,25 @@ struct CodexVersionSection: View {: "common.action.click-to-copy").onTapGesture {- copyPathToPasteboard(path, source: item.source)+ copyPathToPasteboard(path, key: item.source.rawValue)}.transition(.opacity)}}.frame(maxWidth: Metrics.versionColumnWidth, alignment: .trailing)- .animation(Metrics.statusAnimation, value: row.newerInstalledVersion).animation(Metrics.statusAnimation, value: row.path)}}- private func copyPathToPasteboard(_ path: String, source: CodexCLIExecutableSource) {+ private func copyPathToPasteboard(_ path: String, key: String) {PasteboardWriter.copy(path)- copiedPathResetTasks[source]?.cancel()- copiedPathResetTasks[source] = Task { @MainActor in+ copiedPathResetTasks[key]?.cancel()+ copiedPathResetTasks[key] = Task { @MainActor intry? await Task.sleep(for: .milliseconds(1500))guard !Task.isCancelled else { return }- copiedPathResetTasks[source] = nil+ copiedPathResetTasks[key] = nil}}diff --git a/CodexBar/Views/Settings/KeepAliveOptionsView.swift b/CodexBar/Views/Settings/KeepAliveOptionsView.swiftindex e55b233..5ee5f19 100644--- a/CodexBar/Views/Settings/KeepAliveOptionsView.swift+++ b/CodexBar/Views/Settings/KeepAliveOptionsView.swift@@ -4,14 +4,14 @@ import SwiftUI/// 行样式与度量沿用通知子面板, 只有面板宽度按内容收窄struct KeepAliveOptionsView: View {@ObservedObject var keepAliveController: KeepAliveController- @ObservedObject var activityProtectionSettings: ActivityProtectionSettings+ @ObservedObject var protectionSettings: ProtectionSettingsvar body: some View {VStack(alignment: .leading, spacing: Metrics.rowSpacing) {waitingApprovalRowdisplayAwakeRowmaximumDurationRow- activityProtectionRow+ protectionRow// 台式机读不到电池, 这一行整个收起而不是置灰if keepAliveController.hasBattery {@@ -47,15 +47,15 @@ struct KeepAliveOptionsView: View {)}- private var activityProtectionRow: some View {+ private var protectionRow: some View {pickerRow(- title: "activity-protection.title",- caption: "activity-protection.caption",+ title: "protection.title",+ caption: "protection.caption",selection: Binding(- get: { activityProtectionSettings.inactivityDuration },- set: { activityProtectionSettings.setInactivityDuration($0) }+ get: { protectionSettings.inactivityDuration },+ set: { protectionSettings.setInactivityDuration($0) }),- options: ActivityProtectionSettings.InactivityDuration.allCases,+ options: ProtectionSettings.InactivityDuration.allCases,label: \.title)}diff --git a/CodexBar/Views/Settings/MainPanelOptionsView.swift b/CodexBar/Views/Settings/MainPanelOptionsView.swiftindex e1c143d..ff1bb79 100644--- a/CodexBar/Views/Settings/MainPanelOptionsView.swift+++ b/CodexBar/Views/Settings/MainPanelOptionsView.swift@@ -29,7 +29,6 @@ struct MainPanelLayoutSettingsRow: View {/// 主面板布局子选项, 拖放调整区域顺序并控制显隐struct MainPanelOptionsView: View {@ObservedObject var settings: MainPanelSettings- @ObservedObject var advancedModeSettings: AdvancedModeSettingslet undoManager: UndoManager@State private var dragState: SectionDragState?@State private var dragTranslation: CGFloat = 0@@ -85,12 +84,8 @@ struct MainPanelOptionsView: View {}private func sectionRow(_ section: MainPanelSection) -> some View {- let isAvailable = section != .activity || advancedModeSettings.isEnabled- let isVisible = isAvailable && settings.layout.isVisible(section)- let visibleSectionCount = settings.layout.visibleSections.filter { visibleSection in- visibleSection != .activity || advancedModeSettings.isEnabled- }.count- let canToggle = isAvailable && (!isVisible || visibleSectionCount > 1)+ let isVisible = settings.layout.isVisible(section)+ let canToggle = !isVisible || settings.layout.visibleSections.count > 1return HStack(spacing: Metrics.controlSpacing) {Image(systemName: "line.3.horizontal")@@ -114,8 +109,7 @@ struct MainPanelOptionsView: View {section.title,isOn: Binding(get: {- (section != .activity || advancedModeSettings.isEnabled)- && settings.layout.isVisible(section)+ settings.layout.isVisible(section)},set: {settings.setSection(diff --git a/CodexBar/Views/Settings/NotificationOptionsView.swift b/CodexBar/Views/Settings/NotificationOptionsView.swiftindex 0a6b18f..d2ed11d 100644--- a/CodexBar/Views/Settings/NotificationOptionsView.swift+++ b/CodexBar/Views/Settings/NotificationOptionsView.swift@@ -5,8 +5,7 @@ import SwiftUI/// 通知开启时展开音效子行, 关闭时连同占位一起收起struct NotificationOptionsView: View {@ObservedObject var notificationSettings: NotificationSettings- @ObservedObject var advancedModeSettings: AdvancedModeSettings- @ObservedObject var codexCLINotificationSettings: CodexCLINotificationSettings+ @ObservedObject var tuiNotificationSettings: TUINotificationSettings@ObservedObject var autoResetSettings: AutoResetSettings@ObservedObject var keepAliveController: KeepAliveController@State private var previewSound: NSSound?@@ -22,7 +21,7 @@ struct NotificationOptionsView: View {lowBatteryRowkeepAliveLimitRowtaskHapticRow- codexCLINotificationRow+ tuiNotificationRow}.padding(.horizontal, Metrics.horizontalPadding).padding(.vertical, Metrics.verticalPadding)@@ -81,9 +80,8 @@ struct NotificationOptionsView: View {)}- /// 进阶模式未开启或链路校验不通时显示为关闭并置灰, 不修改持久化的 isTaskCompletionEnabledprivate var taskCompletionRow: some View {- let isDisplayedOn = advancedModeSettings.isOperable && notificationSettings.isTaskCompletionEnabled+ let isDisplayedOn = notificationSettings.isTaskCompletionEnabledreturn notificationOptionRow(title: "settings.notifications.task-completion.title",@@ -91,7 +89,6 @@ struct NotificationOptionsView: View {get: { isDisplayedOn },set: { notificationSettings.setTaskCompletionEnabled($0) }),- isEnabled: advancedModeSettings.isOperable,sound: Binding(get: { notificationSettings.taskCompletionSound },set: { notificationSettings.setTaskCompletionSound($0) }@@ -109,9 +106,8 @@ struct NotificationOptionsView: View {}}- /// 进阶模式未开启或链路校验不通时显示为关闭并置灰, 不修改持久化的 isTaskWaitingEnabledprivate var taskWaitingRow: some View {- let isDisplayedOn = advancedModeSettings.isOperable && notificationSettings.isTaskWaitingEnabled+ let isDisplayedOn = notificationSettings.isTaskWaitingEnabledreturn notificationOptionRow(title: "settings.notifications.task-waiting.title",@@ -119,7 +115,6 @@ struct NotificationOptionsView: View {get: { isDisplayedOn },set: { notificationSettings.setTaskWaitingEnabled($0) }),- isEnabled: advancedModeSettings.isOperable,sound: Binding(get: { notificationSettings.taskWaitingSound },set: { notificationSettings.setTaskWaitingSound($0) }@@ -127,9 +122,8 @@ struct NotificationOptionsView: View {)}- /// 进阶模式未开启或链路校验不通时显示为关闭并置灰, 不修改持久化的 isTaskHapticEnabledprivate var taskHapticRow: some View {- let isDisplayedOn = advancedModeSettings.isOperable && notificationSettings.isTaskHapticEnabled+ let isDisplayedOn = notificationSettings.isTaskHapticEnabledreturn VStack(spacing: 0) {optionRow(@@ -137,8 +131,7 @@ struct NotificationOptionsView: View {isOn: Binding(get: { isDisplayedOn },set: { notificationSettings.setTaskHapticEnabled($0) }- ),- isEnabled: advancedModeSettings.isOperable+ ))captionRow("settings.notifications.task-haptics.caption")@@ -220,21 +213,21 @@ struct NotificationOptionsView: View {)}- private var codexCLINotificationRow: some View {+ private var tuiNotificationRow: some View {VStack(spacing: 0) {optionRow(title: "settings.notifications.codex-tui.title",isOn: Binding(- get: { codexCLINotificationSettings.isEnabled },- set: { codexCLINotificationSettings.setEnabled($0) }+ get: { tuiNotificationSettings.isEnabled },+ set: { tuiNotificationSettings.setEnabled($0) }),- isEnabled: !codexCLINotificationSettings.isUpdating+ isEnabled: !tuiNotificationSettings.isUpdating) {- if codexCLINotificationSettings.isUpdating {+ if tuiNotificationSettings.isUpdating {ProgressView().controlSize(.mini).frame(width: Metrics.statusIconSize, height: Metrics.statusIconSize)- } else if let errorMessage = codexCLINotificationSettings.errorMessage {+ } else if let errorMessage = tuiNotificationSettings.errorMessage {Image(systemName: "exclamationmark.circle").foregroundStyle(.orange).frame(width: Metrics.statusIconSize, height: Metrics.statusIconSize)diff --git a/CodexBar/Views/Settings/ProxyPasswordField.swift b/CodexBar/Views/Settings/ProxyPasswordField.swiftdeleted file mode 100644index e2fee17..0000000--- a/CodexBar/Views/Settings/ProxyPasswordField.swift+++ /dev/null@@ -1,158 +0,0 @@-import AppKit-import QuartzCore-import SwiftUI--struct ProxyPasswordField: NSViewRepresentable {- @Binding var text: String- @Binding var isFocused: Bool- let isRevealed: Bool- @Environment(\.isEnabled) private var isEnabled-- func makeNSView(context _: Context) -> PasswordInputView {- PasswordInputView()- }-- func updateNSView(_ view: PasswordInputView, context _: Context) {- view.onChange = { text = $0 }- view.onFocusChange = { focused in- if isFocused != focused {- isFocused = focused- }- }- view.update(text: text, isEnabled: isEnabled, isRevealed: isRevealed)- }-- final class PasswordInputView: NSView, NSTextFieldDelegate {- var onChange: ((String) -> Void)?- var onFocusChange: ((Bool) -> Void)?- private let secureField = NSSecureTextField()- private let plainField = NSTextField()- private var isRevealed = false- private var lastText = ""- private var isSwitching = false- private var requestedReveal = false- private var hasPendingReveal = false- private var activeField: NSTextField {- isRevealed ? plainField : secureField- }-- override init(frame: NSRect) {- super.init(frame: frame)- wantsLayer = true- for field in [secureField, plainField] {- field.isBordered = false- field.isBezeled = false- field.drawsBackground = false- field.focusRingType = .none- field.font = .systemFont(ofSize: NSFont.systemFontSize)- field.placeholderString = String(localized: "proxy.password")- field.cell?.usesSingleLineMode = true- field.cell?.isScrollable = true- field.delegate = self- addSubview(field)- }- plainField.isHidden = true- }-- @available(*, unavailable)- required init?(coder _: NSCoder) {- fatalError()- }-- override func layout() {- super.layout()- secureField.frame = bounds- plainField.frame = bounds- }-- func update(text: String, isEnabled: Bool, isRevealed: Bool) {- for field in [secureField, plainField] {- if text != lastText {- field.stringValue = text- }- field.isEnabled = isEnabled- }- lastText = text- requestedReveal = isRevealed && isEnabled- guard !hasPendingReveal else { return }- hasPendingReveal = true- // makeFirstResponder 会同步更新 SwiftUI 焦点图, 必须离开 updateNSView 的更新周期- // 快速悬停只应用最后一次请求, 避免排队切换过期状态- DispatchQueue.main.async { [weak self] in- guard let self else { return }- hasPendingReveal = false- setRevealed(requestedReveal)- }- }-- private func setRevealed(_ revealed: Bool) {- guard revealed != isRevealed else { return }- let editor = activeField.currentEditor() as? NSTextView- let selection = editor?.selectedRange()- let value = editor?.string ?? activeField.stringValue- let hasMarkedText = editor?.hasMarkedText() == true- isSwitching = true- defer { isSwitching = false }-- // 两个原生控件保持挂载, 在同一轮更新中交接编辑器和选区- // 淡化仅作用于文字所在的图层, 外部边框和焦点环不参与动画- let transition = CATransition()- transition.type = .fade- transition.duration = 0.1- transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)- layer?.add(transition, forKey: "passwordVisibility")- // 安全编辑器不能继续输入法组合, 交接时确认现有文字并保留完整内容- if hasMarkedText {- editor?.unmarkText()- }- activeField.isHidden = true- isRevealed = revealed- activeField.stringValue = value- activeField.isHidden = false- if let selection, let window {- window.makeFirstResponder(activeField)- if let newEditor = activeField.currentEditor() as? NSTextView {- let length = (newEditor.string as NSString).length- let location = min(selection.location, length)- newEditor.setSelectedRange(NSRange(location: location, length: min(selection.length, length - location)))- newEditor.scrollRangeToVisible(newEditor.selectedRange())- }- }- if hasMarkedText, value != lastText {- lastText = value- onChange?(value)- }- }-- func controlTextDidChange(_ notification: Notification) {- guard !isSwitching, let field = notification.object as? NSTextField else { return }- lastText = field.stringValue- onChange?(field.stringValue)- }-- func controlTextDidBeginEditing(_ notification: Notification) {- if let field = notification.object as? NSTextField,- let editor = field.currentEditor() as? NSTextView {- editor.isAutomaticTextCompletionEnabled = false- editor.isAutomaticSpellingCorrectionEnabled = false- editor.isAutomaticTextReplacementEnabled = false- editor.isAutomaticQuoteSubstitutionEnabled = false- editor.isAutomaticDashSubstitutionEnabled = false- editor.isContinuousSpellCheckingEnabled = false- }- updateFocus()- }-- func controlTextDidEndEditing(_: Notification) {- updateFocus()- }-- private func updateFocus() {- // 编辑器交接也会发送结束通知, 等交接完成后统一读取焦点- Task { @MainActor [weak self] in- guard let self else { return }- onFocusChange?(activeField.currentEditor() != nil)- }- }- }-}diff --git a/CodexBar/Views/Settings/ProxySettingsView.swift b/CodexBar/Views/Settings/ProxySettingsView.swiftdeleted file mode 100644index c55f4a7..0000000--- a/CodexBar/Views/Settings/ProxySettingsView.swift+++ /dev/null@@ -1,331 +0,0 @@-import SwiftUI--struct ProxySettingsRow: View {- @EnvironmentObject private var statusViewModel: CodexStatusViewModel- @ObservedObject var settings: CodexProxySettings- let action: () -> Void- @State private var showsSaveError = false-- var body: some View {- Group {- if settings.configuration == nil {- Button(action: action) {- HStack(spacing: SettingsRowMetrics.spacing) {- rowLabel- Toggle("proxy.enabled", isOn: .constant(false))- .labelsHidden()- .toggleStyle(.switch)- .controlSize(.small)- .allowsHitTesting(false)- }- .contentShape(Rectangle())- }- .buttonStyle(.plain)- } else {- HStack(spacing: 0) {- Button(action: action) {- rowLabel- .padding(.trailing, SettingsRowMetrics.spacing)- .contentShape(Rectangle())- }- .buttonStyle(.plain)- enabledToggle- }- }- }- .disabled(settings.isSaving)- .alert("proxy.feedback.save-failed", isPresented: $showsSaveError) {- Button("common.action.close", role: .cancel) {}- }- }-- private var rowLabel: some View {- HStack(spacing: SettingsRowMetrics.spacing) {- Image(systemName: "personalhotspot")- .frame(width: SettingsRowMetrics.iconWidth)- .foregroundStyle(.tint)- Text("proxy.title")- Spacer()- }- .frame(minHeight: SettingsRowMetrics.optionsButtonSize)- }-- private var enabledToggle: some View {- Toggle("proxy.enabled", isOn: Binding(- get: { settings.configuration?.isEnabled == true },- set: { enabled in- settings.setEnabled(enabled) { succeeded in- if succeeded {- statusViewModel.refreshAfterCurrent(trigger: .settings)- } else if settings.showsValidationErrors {- action()- } else {- showsSaveError = true- }- }- }- ))- .labelsHidden()- .toggleStyle(.switch)- .controlSize(.small)- }-}--struct ProxySettingsView: View {- let source: CodexCLISourceSelection- @ObservedObject var settings: CodexProxySettings- let onApplied: () -> Void- @Environment(\.dismiss) private var dismiss- @Environment(\.controlActiveState) private var controlActiveState- @State private var showsPassword = false- @State private var serverFieldHeight: CGFloat = 24- @State private var isPasswordFocused = false-- var body: some View {- VStack(alignment: .leading, spacing: 18) {- VStack(spacing: 14) {- configurationHeader- LiquidGlassDivider()- configurationFields- LiquidGlassDivider()- authenticationFields- }- .disabled(settings.isSaving)-- actions- }- .padding(20)- .frame(width: 550)- .liquidGlassSurface(cornerRadius: 16, isOuterSurface: true)- .onAppear {- showsPassword = false- settings.loadDraft(showValidationErrors: settings.showsValidationErrors)- }- .onChange(of: settings.draft.usesAuthentication) { _, enabled in- if !enabled {- showsPassword = false- }- }- .onDisappear {- showsPassword = false- settings.closeDraft()- }- .interactiveDismissDisabled(settings.isSaving)- }-- private var configurationHeader: some View {- HStack {- Text("proxy.configuration.title")- .font(.headline)- Spacer()- if settings.hasStoredConfiguration {- Menu {- Button(role: .destructive) {- Task {- if await settings.save(clear: true) {- showsPassword = false- dismiss()- onApplied()- }- }- } label: {- Label("proxy.action.clear-configuration", systemImage: "trash")- }- } label: {- Image(systemName: "ellipsis")- .frame(width: SettingsRowMetrics.optionsButtonSize, height: SettingsRowMetrics.optionsButtonSize)- .contentShape(Rectangle())- }- .menuStyle(.borderlessButton)- .menuIndicator(.hidden)- .fixedSize()- .foregroundStyle(.secondary)- }- }- }-- private func draftBinding<Value>(_ keyPath: WritableKeyPath<CodexProxyConfiguration, Value>) -> Binding<Value> {- Binding(- get: { settings.draft[keyPath: keyPath] },- set: {- settings.draftChanged()- settings.draft[keyPath: keyPath] = $0- }- )- }-- private var configurationFields: some View {- VStack(alignment: .leading, spacing: 10) {- HStack(spacing: 12) {- Text("proxy.server")- .fixedSize()- Spacer(minLength: 0)- HStack(spacing: 6) {- SettingsDropdownPicker(- selection: settings.draft.transport,- options: CodexProxyConfiguration.Transport.allCases,- isEnabled: !settings.isSaving,- title: settings.draft.transport.rawValue,- height: serverFieldHeight,- optionTitle: { $0.rawValue },- onSelect: { transport in- draftBinding(\.transport).wrappedValue = transport- }- )- Text(verbatim: "://")- .foregroundStyle(.secondary)- TextField(text: draftBinding(\.host)) {- Text(verbatim: "127.0.0.1")- }- .textContentType(.URL)- .autocorrectionDisabled()- .frame(minWidth: 140, maxWidth: .infinity, alignment: .leading)- .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { serverFieldHeight = $0 }- .overlay { validationBorder(for: .host) }- Text(verbatim: ":")- .foregroundStyle(.secondary)- TextField(text: draftBinding(\.port)) {- Text(verbatim: "2048")- }- .frame(width: 64, alignment: .leading)- .overlay { validationBorder(for: .port) }- }- }- }- .textFieldStyle(.roundedBorder)- }-- private var authenticationFields: some View {- VStack(alignment: .leading, spacing: 14) {- HStack(spacing: 12) {- Text("proxy.authentication")- Spacer()- Toggle("proxy.authentication", isOn: draftBinding(\.usesAuthentication))- .labelsHidden()- .toggleStyle(.switch)- .controlSize(.small)- }- LiquidGlassDivider()- VStack(alignment: .leading, spacing: 12) {- VStack(alignment: .leading, spacing: 6) {- Text("proxy.username")- .font(.caption.weight(.medium))- .foregroundStyle(.secondary)- TextField("proxy.username", text: draftBinding(\.username))- .textContentType(.username)- .autocorrectionDisabled()- .overlay { validationBorder(for: .username) }- }- .frame(maxWidth: .infinity)- VStack(alignment: .leading, spacing: 6) {- Text("proxy.password")- .font(.caption.weight(.medium))- .foregroundStyle(.secondary)- passwordField- }- .frame(maxWidth: .infinity)- }- .disabled(!settings.draft.usesAuthentication)- .opacity(settings.draft.usesAuthentication ? 1 : 0.5)- }- .textFieldStyle(.roundedBorder)- }-- private var passwordField: some View {- ProxyPasswordField(- text: passwordBinding,- isFocused: $isPasswordFocused,- isRevealed: showsPassword && controlActiveState != .inactive- )- .frame(height: max(18, serverFieldHeight - 6))- .padding(.horizontal, 6)- .padding(.vertical, 3)- .contentShape(Rectangle())- .onHover { showsPassword = $0 }- .background(Color(nsColor: .textBackgroundColor), in: RoundedRectangle(cornerRadius: 5))- .overlay {- RoundedRectangle(cornerRadius: 5)- .strokeBorder(Color(nsColor: .separatorColor), lineWidth: 1)- .allowsHitTesting(false)- }- .overlay {- if isPasswordFocused {- RoundedRectangle(cornerRadius: 5)- .stroke(Color.accentColor.opacity(0.5), lineWidth: 3)- .allowsHitTesting(false)- }- }- }-- private func validationBorder(for field: CodexProxyConfiguration.InputField) -> some View {- RoundedRectangle(cornerRadius: 5)- .strokeBorder(settings.invalidFields.contains(field) ? Color.red : Color.clear, lineWidth: 1)- .allowsHitTesting(false)- }-- private var passwordBinding: Binding<String> {- Binding(- get: { settings.password },- set: {- settings.draftChanged()- settings.password = $0- }- )- }-- private var testStatus: some View {- HStack(spacing: 8) {- Button(settings.isTesting ? "proxy.action.cancel-test" : "proxy.action.test-connection") {- if settings.isTesting {- settings.cancelTest()- } else {- settings.testConnection(source: source)- }- }- .fixedSize()- if settings.isTesting || settings.isSaving {- ProgressView()- .controlSize(.small)- } else if let result = settings.feedback {- HStack(spacing: 6) {- Image(systemName: result == .success ? "checkmark" : "xmark")- .font(.callout.weight(.semibold))- .foregroundStyle(result == .success ? Color.green : Color.red)- .frame(width: 14)- Text(result.title)- .font(.caption)- .foregroundStyle(.secondary)- .fixedSize()- }- }- }- }-- private var actions: some View {- HStack(spacing: 0) {- testStatus- Spacer(minLength: 16)- actionButtons- }- .disabled(settings.isSaving)- }-- private var actionButtons: some View {- HStack(spacing: 8) {- Button("common.action.cancel") { dismiss() }- .keyboardShortcut(.cancelAction)- Button("proxy.action.save") { apply() }- .keyboardShortcut(.defaultAction)- }- .fixedSize()- }-- private func apply() {- Task {- if await settings.save() {- onApplied()- dismiss()- }- }- }-}diff --git a/CodexBar/Views/Settings/RebuildDatePicker.swift b/CodexBar/Views/Settings/RebuildDatePicker.swiftnew file mode 100644index 0000000..27607a7--- /dev/null+++ b/CodexBar/Views/Settings/RebuildDatePicker.swift@@ -0,0 +1,310 @@+import SwiftUI++enum RebuildLayoutMetrics {+ static let pickerWidth: CGFloat = 190+ static let controlHeight: CGFloat = 26+ static let actionMinimumWidth: CGFloat = 42+}++struct RebuildDatePicker: View {+ @Binding var selection: RebuildDateRange?+ let dataDateKeys: Set<String>+ let isEnabled: Bool++ @State private var isPresented = false+ @State private var displayedMonth = Date()++ private enum Metrics {+ static let daySize: CGFloat = 28+ static let columnSpacing: CGFloat = 6+ static let visibleWeekCount = 6+ static let popoverWidth: CGFloat = 260+ static let popoverHeight: CGFloat = 296+ }++ private static let columns = Array(+ repeating: GridItem(.fixed(Metrics.daySize), spacing: Metrics.columnSpacing),+ count: 7+ )+ var body: some View {+ Button {+ let focusedDateKey = selection?.endDateKey ?? selection?.startDateKey+ if let focusedDateKey,+ let selectedDate = CodexDateFormat.dayDate(from: focusedDateKey) {+ displayedMonth = startOfMonth(for: selectedDate)+ }+ isPresented.toggle()+ } label: {+ HStack(spacing: 5) {+ Image(systemName: "calendar")+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(.tint)++ Group {+ if let selection {+ Text(verbatim: selection.displayText)+ } else {+ Text("date-picker.select-range")+ }+ }+ .font(.caption.monospacedDigit().weight(.medium))+ .foregroundStyle(.primary)+ .lineLimit(1)+ .minimumScaleFactor(0.9)++ Spacer(minLength: 0)++ Image(systemName: "chevron.down")+ .font(.system(size: 8, weight: .semibold))+ .foregroundStyle(.secondary)+ }+ .padding(.horizontal, 7)+ .frame(maxWidth: .infinity, minHeight: RebuildLayoutMetrics.controlHeight)+ .background {+ RoundedRectangle(cornerRadius: 7, style: .continuous)+ .fill(Color(nsColor: .controlBackgroundColor).opacity(0.72))+ }+ .overlay {+ RoundedRectangle(cornerRadius: 7, style: .continuous)+ .strokeBorder(+ isPresented ? Color.accentColor.opacity(0.70) : Color.primary.opacity(0.12),+ lineWidth: isPresented ? 1.2 : 0.8+ )+ }+ .shadow(color: .black.opacity(0.06), radius: 2, y: 1)+ }+ .buttonStyle(.plain)+ .disabled(!isEnabled)+ .help("date-picker.select-range")+ .popover(isPresented: $isPresented, arrowEdge: .bottom) {+ calendarPopover+ }+ }++ private var calendarPopover: some View {+ let weekdaySymbols = weekdaySymbols++ return VStack(spacing: 10) {+ HStack(spacing: 8) {+ monthNavigationButton(+ systemImage: "chevron.left",+ help: "date-picker.previous-month",+ offset: -1+ )++ Spacer()++ Text(monthTitle)+ .font(.system(.body, design: .rounded).weight(.semibold))+ .monospacedDigit()++ Spacer()++ monthNavigationButton(+ systemImage: "chevron.right",+ help: "date-picker.next-month",+ offset: 1+ )+ }++ LazyVGrid(columns: Self.columns, spacing: 5) {+ ForEach(weekdaySymbols.indices, id: \.self) { index in+ Text(verbatim: weekdaySymbols[index])+ .font(.system(size: 10, weight: .medium))+ .foregroundStyle(.secondary)+ .frame(width: Metrics.daySize, height: 18)+ }++ ForEach(monthDates, id: \.self) { date in+ dayButton(for: date)+ }+ }++ Group {+ if selection?.isComplete == false {+ Text("date-picker.select-end")+ } else {+ Text("date-picker.select-start")+ }+ }+ .font(.caption2)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ .frame(height: 14)+ }+ .padding(12)+ .frame(width: Metrics.popoverWidth, height: Metrics.popoverHeight)+ }++ private func monthNavigationButton(+ systemImage: String,+ help: LocalizedStringResource,+ offset: Int+ ) -> some View {+ Button {+ guard let nextMonth = calendar.date(byAdding: .month, value: offset, to: displayedMonth) else {+ return+ }+ displayedMonth = nextMonth+ } label: {+ Image(systemName: systemImage)+ .font(.system(size: 10, weight: .semibold))+ .frame(width: 24, height: 22)+ .background {+ RoundedRectangle(cornerRadius: 6, style: .continuous)+ .fill(Color.primary.opacity(0.055))+ }+ }+ .buttonStyle(.plain)+ .disabled(!canMoveMonth(by: offset))+ .help(help)+ }++ private func dayButton(for date: Date) -> some View {+ let dateKey = HistoryStorage.dateKey(for: date)+ let isSelectable = selectableDateRange.contains(calendar.startOfDay(for: date))+ let hasData = dataDateKeys.contains(dateKey)+ let isInDisplayedMonth = calendar.isDate(+ date,+ equalTo: displayedMonth,+ toGranularity: .month+ )+ let isStart = selection?.startDateKey == dateKey+ let isEnd = selection?.endDateKey == dateKey+ let isEndpoint = isStart || isEnd+ let isInCompletedRange = selection?.contains(dateKey) == true+ let day = calendar.component(.day, from: date)++ return Button {+ select(dateKey)+ } label: {+ ZStack(alignment: .bottom) {+ RoundedRectangle(cornerRadius: 7, style: .continuous)+ .fill(dayBackgroundColor(+ isEndpoint: isEndpoint,+ isInCompletedRange: isInCompletedRange+ ))++ Text(String(day))+ .font(.system(size: 11, weight: isEndpoint ? .semibold : .regular))+ .foregroundStyle(dayTextColor(+ isSelectable: isSelectable,+ isEndpoint: isEndpoint,+ isInDisplayedMonth: isInDisplayedMonth+ ))+ .frame(maxWidth: .infinity, maxHeight: .infinity)++ if hasData, !isEndpoint {+ Circle()+ .fill(Color.accentColor.opacity(0.75))+ .frame(width: 2.5, height: 2.5)+ .padding(.bottom, 2)+ }+ }+ .frame(width: Metrics.daySize, height: Metrics.daySize)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .disabled(!isSelectable)+ }++ private var monthTitle: String {+ Self.monthFormatter.string(from: displayedMonth)+ }++ private var monthDates: [Date] {+ let monthStart = startOfMonth(for: displayedMonth)+ let leadingDayCount = (+ calendar.component(.weekday, from: monthStart) - calendar.firstWeekday + 7+ ) % 7+ guard let gridStart = calendar.date(+ byAdding: .day,+ value: -leadingDayCount,+ to: monthStart+ ) else {+ return []+ }++ let visibleDayCount = Self.columns.count * Metrics.visibleWeekCount+ return (0 ..< visibleDayCount).compactMap { dayOffset in+ calendar.date(byAdding: .day, value: dayOffset, to: gridStart)+ }+ }++ private var calendar: Calendar {+ var calendar = Calendar(identifier: .gregorian)+ calendar.locale = .autoupdatingCurrent+ calendar.timeZone = .autoupdatingCurrent+ return calendar+ }++ private var weekdaySymbols: [String] {+ let symbols = calendar.veryShortStandaloneWeekdaySymbols++ let firstIndex = max(0, min(symbols.count - 1, calendar.firstWeekday - 1))+ return Array(symbols[firstIndex...] + symbols[..<firstIndex])+ }++ private static let monthFormatter: DateFormatter = {+ let formatter = DateFormatter()+ formatter.locale = .autoupdatingCurrent+ formatter.calendar = Calendar(identifier: .gregorian)+ formatter.timeZone = .autoupdatingCurrent+ formatter.setLocalizedDateFormatFromTemplate("yyyyMMMM")+ return formatter+ }()++ private var selectableDateRange: ClosedRange<Date> {+ let today = calendar.startOfDay(for: Date())+ let cutoff = HistoryStorage.retentionCutoffDate(today: today, calendar: calendar)+ return cutoff ... today+ }++ private func startOfMonth(for date: Date) -> Date {+ let components = calendar.dateComponents([.year, .month], from: date)+ return calendar.date(from: components) ?? date+ }++ private func canMoveMonth(by offset: Int) -> Bool {+ guard let candidate = calendar.date(byAdding: .month, value: offset, to: displayedMonth) else {+ return false+ }++ let month = startOfMonth(for: candidate)+ return month >= startOfMonth(for: selectableDateRange.lowerBound)+ && month <= startOfMonth(for: selectableDateRange.upperBound)+ }++ private func select(_ dateKey: String) {+ if let selection, !selection.isComplete {+ self.selection = selection.completing(with: dateKey)+ isPresented = false+ } else {+ selection = .starting(at: dateKey)+ }+ }++ private func dayBackgroundColor(+ isEndpoint: Bool,+ isInCompletedRange: Bool+ ) -> Color {+ if isEndpoint {+ return .accentColor+ }+ return isInCompletedRange ? Color.accentColor.opacity(0.16) : .clear+ }++ private func dayTextColor(+ isSelectable: Bool,+ isEndpoint: Bool,+ isInDisplayedMonth: Bool+ ) -> Color {+ if isEndpoint {+ return .white+ }+ if !isInDisplayedMonth {+ return .codexSecondaryLabel.opacity(isSelectable ? 0.58 : 0.24)+ }+ return isSelectable ? .codexLabel : .codexSecondaryLabel.opacity(0.36)+ }+}diff --git a/CodexBar/Views/Shared/TaskGlowView.swift b/CodexBar/Views/Shared/TaskGlowView.swiftnew file mode 100644index 0000000..2a7eb46--- /dev/null+++ b/CodexBar/Views/Shared/TaskGlowView.swift@@ -0,0 +1,560 @@+import AppKit+import QuartzCore++/// 所有屏幕共享同一运动周期, 新窗口直接加入当前进度+final class TaskGlowMotionClock {+ private static let standardCycleDuration = TaskGlowAnimationTiming.cycleDuration+ private(set) var cycleDuration = standardCycleDuration+ private var isRunning = false+ private var startedAt: CFTimeInterval?++ func setAnimationSpeed(_ speed: TaskGlowAnimationSpeed) {+ let duration = Self.standardCycleDuration * speed.durationMultiplier+ guard duration != cycleDuration else { return }+ // 改速时保留当前周期进度, 各屏幕仍共享同一出发时间+ if let startedAt {+ let now = CACurrentMediaTime()+ self.startedAt = now - (now - startedAt) / cycleDuration * duration+ }+ cycleDuration = duration+ }++ func setRunning(_ running: Bool) {+ guard isRunning != running else { return }+ isRunning = running+ startedAt = nil+ }++ func restart(at time: CFTimeInterval) {+ isRunning = true+ startedAt = time+ }++ func startTime() -> CFTimeInterval {+ if let startedAt {+ return startedAt+ }+ let time = CACurrentMediaTime()+ startedAt = time+ return time+ }+}++final class TaskGlowPanel: NSPanel {+ let indicatorView: TaskGlowView++ override var canBecomeKey: Bool {+ false+ }++ override var canBecomeMain: Bool {+ false+ }++ init(screen: NSScreen, motionClock: TaskGlowMotionClock) {+ let geometry = TaskGlowGeometry(screenFrame: screen.frame)+ indicatorView = TaskGlowView(geometry: geometry, scale: screen.backingScaleFactor, motionClock: motionClock)+ super.init(contentRect: geometry.frame, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)+ isReleasedWhenClosed = false+ isOpaque = false+ backgroundColor = .clear+ hasShadow = false+ ignoresMouseEvents = true+ hidesOnDeactivate = false+ isFloatingPanel = true+ // iTerm2 等 App 的顶部窗口使用 statusBar + 1, 光带必须在其上方才能露出菜单栏顶边+ level = NSWindow.Level(rawValue: NSWindow.Level.statusBar.rawValue + 2)+ // 非激活面板跨 Space 和全屏显示, 不加入窗口循环或抢走当前 App 的焦点+ collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .ignoresCycle, .stationary]+ animationBehavior = .none+ contentView = indicatorView+ }+}++/// 移动路径贯穿屏幕, 中心部分由屏幕刘海自然遮挡+struct TaskGlowGeometry {+ let frame: NSRect+ let path: CGPath++ init(screenFrame: NSRect) {+ let height: CGFloat = 12+ frame = NSRect(x: screenFrame.minX, y: screenFrame.maxY - height, width: screenFrame.width, height: height)+ let path = CGMutablePath()+ path.move(to: CGPoint(x: 0, y: height - 1.5))+ path.addLine(to: CGPoint(x: screenFrame.width, y: height - 1.5))+ self.path = path+ }+}++final class TaskGlowView: NSView {+ private let trackLayer = CAShapeLayer()+ private let lightLayer = CALayer()+ private var lightSegments: [CAShapeLayer] = []+ static let visibilityDuration = 0.24+ private static let segmentsPerSide = 32+ private static let stationaryColorAlpha: CGFloat = 0.9+ private let convergencePoint = 0.5+ private let motionClock: TaskGlowMotionClock+ private var presentationState: TaskGlowState?+ private var terminalPresentation: TaskGlowTerminalPresentation?+ private var contentState: TaskGlowState?+ private var transitionTask: Task<Void, Never>?+ private var repeatsMotion = true+ private var playback: TaskGlowPlayback?+ private var glowAppearance = TaskGlowAppearance()++ init(+ geometry: TaskGlowGeometry,+ scale: CGFloat,+ motionClock: TaskGlowMotionClock+ ) {+ self.motionClock = motionClock+ super.init(frame: NSRect(origin: .zero, size: geometry.frame.size))+ wantsLayer = true+ layer?.opacity = 0+ trackLayer.frame = bounds+ trackLayer.path = geometry.path+ trackLayer.fillColor = nil+ trackLayer.lineWidth = 3+ trackLayer.contentsScale = scale+ trackLayer.shadowRadius = 4+ trackLayer.shadowOffset = .zero+ lightLayer.frame = bounds+ lightLayer.shadowOpacity = 0.8+ lightLayer.shadowRadius = 4+ lightLayer.shadowOffset = .zero+ layer?.addSublayer(trackLayer)+ layer?.addSublayer(lightLayer)+ // 嵌套描边让渐变沿弧长移动, 重叠区域避免相邻短线的抗锯齿接缝+ for _ in 0 ..< Self.segmentsPerSide * 2 {+ let segment = CAShapeLayer()+ segment.frame = bounds+ segment.path = geometry.path+ segment.fillColor = nil+ segment.lineWidth = 3+ segment.contentsScale = scale+ lightLayer.addSublayer(segment)+ lightSegments.append(segment)+ }+ setAccessibilityElement(false)+ }++ @available(*, unavailable)+ required init?(coder _: NSCoder) {+ fatalError("init(coder:) has not been implemented")+ }++ private var hasArtwork: Bool {+ contentState != nil && (layer?.presentation()?.opacity ?? layer?.opacity ?? 0) > 0.001+ }++ var interruptionDelay: TimeInterval {+ guard hasArtwork else { return 0 }+ let distance: CGFloat = if !trackLayer.isHidden {+ 0.5+ } else {+ lightSegments.map { segment in+ let current = segment.presentation() ?? segment+ return max(abs(current.strokeStart - convergencePoint), abs(current.strokeEnd - convergencePoint))+ }.max() ?? 0+ }+ return max(0.001, Double(distance) * TaskGlowAnimationTiming.edgeTraversalDuration) + TaskGlowAnimationTiming.transitionGap+ }++ func update(+ state: TaskGlowState,+ appearance glowAppearance: TaskGlowAppearance,+ terminalPresentation: TaskGlowTerminalPresentation? = nil,+ repeatsMotion: Bool = true,+ playback: TaskGlowPlayback? = nil+ ) {+ let previousAppearance = applyAppearance(glowAppearance, state: state)+ let changesPlayback = self.playback?.id != playback?.id+ self.playback = playback+ if !changesPlayback, presentationState == state, self.terminalPresentation == terminalPresentation, self.repeatsMotion == repeatsMotion {+ refreshStableAppearance(state, previous: previousAppearance)+ return+ }+ let continuesRunning = !changesPlayback && presentationState == .running && state == .running+ let continuesTerminal = !changesPlayback && presentationState == state && self.terminalPresentation != nil && terminalPresentation != nil+ // 同色提示延长时保留尚未完成的展开, 收尾会读取最新的淡出期限+ if continuesTerminal, transitionTask != nil {+ self.terminalPresentation = terminalPresentation+ return+ }+ let terminalOpacity = continuesTerminal ? (trackLayer.presentation() ?? trackLayer).opacity : nil+ let hasArtwork = hasArtwork+ presentationState = state+ self.terminalPresentation = terminalPresentation+ self.repeatsMotion = repeatsMotion+ transitionTask?.cancel()+ transitionTask = nil+ freezeArtwork()+ if state != .hidden {+ contentState = state+ animateVisibility(to: Float(glowAppearance.brightness))+ }++ if continuesRunning {+ showStable(.running)+ return+ }++ if let terminalOpacity {+ showStable(state, initialTerminalOpacity: terminalOpacity)+ return+ }++ if let terminalPresentation,+ Date().timeIntervalSince(terminalPresentation.startedAt) >= terminalPresentation.entranceDuration {+ showStable(state)+ return+ }++ transitionTask = Task { @MainActor [weak self] in+ guard let self, !Task.isCancelled else { return }+ do {+ try await transition(to: state, hasArtwork: hasArtwork, playback: changesPlayback ? playback : nil)+ transitionTask = nil+ } catch {+ return+ }+ }+ }++ private func transition(to state: TaskGlowState, hasArtwork: Bool, playback: TaskGlowPlayback?) async throws {+ if hasArtwork {+ let duration = animateExtent(expanded: false)+ // 预览切换共享收回期限, 避免不同屏幕分别开始计时+ let wait = playback.map { max(0, $0.mediaStart - CACurrentMediaTime()) } ?? duration+ try await Task.sleep(for: .seconds(wait))+ try Task.checkCancellation()+ }+ if state == .hidden {+ contentState = nil+ animateVisibility(to: 0)+ try await Task.sleep(for: .seconds(Self.visibilityDuration))+ try Task.checkCancellation()+ return+ }+ let delay = playback.map { max(0, $0.mediaStart - CACurrentMediaTime()) }+ ?? (hasArtwork ? TaskGlowAnimationTiming.transitionGap : 0)+ try await Task.sleep(for: .seconds(delay))+ try Task.checkCancellation()+ if state == .running {+ showStable(.running)+ fadeInMovingLight()+ } else {+ setCollapsedColor(state.color(in: glowAppearance))+ let duration = animateExtent(expanded: true)+ try await Task.sleep(for: .seconds(duration))+ try Task.checkCancellation()+ showStable(state)+ }+ }++ private func applyAppearance(_ appearance: TaskGlowAppearance, state: TaskGlowState) -> TaskGlowAppearance {+ let previous = glowAppearance+ glowAppearance = appearance+ if previous.brightness != appearance.brightness, state != .hidden {+ animateVisibility(to: Float(appearance.brightness))+ }+ return previous+ }++ private func refreshStableAppearance(_ state: TaskGlowState, previous: TaskGlowAppearance) {+ guard state != .hidden, transitionTask == nil,+ previous.colors != glowAppearance.colors || previous.animationSpeed != glowAppearance.animationSpeed else { return }+ showStable(state)+ }++ /// 面板等待实际收回和淡出结束, 不用独立计时器提前移除仍可见的光带+ func waitForDismissal() async -> Bool {+ await transitionTask?.value+ return !Task.isCancelled && presentationState == .hidden && transitionTask == nil+ }++ func stopAnimating() {+ transitionTask?.cancel()+ transitionTask = nil+ stopArtworkAnimations()+ layer?.removeAllAnimations()+ }++ private struct SegmentAppearance {+ let start: CGFloat+ let end: CGFloat+ let color: CGColor?+ }++ /// 先冻结合成器当前帧, 再移除动画, 防止中途改目标时跳到上一段的终点+ private func freezeArtwork() {+ let usesTrack = !trackLayer.isHidden+ let track = trackLayer.presentation() ?? trackLayer+ let light = lightLayer.presentation() ?? lightLayer+ let opacity = usesTrack ? track.opacity : light.opacity+ let appearances = lightSegments.enumerated().map { index, segment -> SegmentAppearance in+ if usesTrack {+ return SegmentAppearance(+ start: index < Self.segmentsPerSide ? 0 : convergencePoint,+ end: index < Self.segmentsPerSide ? convergencePoint : 1,+ color: distributedColor(track.strokeColor)+ )+ }+ let current = segment.presentation() ?? segment+ return SegmentAppearance(start: current.strokeStart, end: current.strokeEnd, color: current.strokeColor)+ }+ let shadowColor = usesTrack ? track.shadowColor : light.shadowColor+ CATransaction.begin()+ CATransaction.setDisableActions(true)+ stopArtworkAnimations()+ trackLayer.isHidden = true+ lightLayer.isHidden = false+ lightLayer.opacity = opacity+ lightLayer.shadowColor = shadowColor+ for (segment, appearance) in zip(lightSegments, appearances) {+ segment.strokeStart = appearance.start+ segment.strokeEnd = appearance.end+ segment.strokeColor = appearance.color+ }+ CATransaction.commit()+ }++ private func showStable(_ state: TaskGlowState, initialTerminalOpacity: Float? = nil) {+ CATransaction.begin()+ CATransaction.setDisableActions(true)+ stopArtworkAnimations()+ trackLayer.strokeStart = 0+ trackLayer.strokeEnd = 1+ trackLayer.strokeColor = state.color(in: glowAppearance).withAlphaComponent(Self.stationaryColorAlpha).cgColor+ trackLayer.shadowColor = state.color(in: glowAppearance).cgColor+ trackLayer.shadowOpacity = 0.8+ trackLayer.opacity = 1+ trackLayer.isHidden = state == .running+ lightLayer.isHidden = state != .running+ lightLayer.opacity = 1+ lightLayer.shadowColor = state.color(in: glowAppearance).cgColor+ if state == .running {+ configureMovingLight()+ } else if state == .waiting {+ let animation = CAKeyframeAnimation(keyPath: "opacity")+ animation.values = [1, 0, 0, 1]+ animation.keyTimes = [0, 0.45, 0.55, 1]+ animation.duration = 1.5 * glowAppearance.animationSpeed.durationMultiplier+ if !repeatsMotion, let playback {+ animation.beginTime = trackLayer.convertTime(playback.mediaStart + TaskGlowAnimationTiming.expansionDuration, from: nil)+ }+ animation.repeatCount = repeatsMotion ? .infinity : 2+ animation.timingFunctions = [+ CAMediaTimingFunction(name: .easeInEaseOut),+ CAMediaTimingFunction(name: .linear),+ CAMediaTimingFunction(name: .easeInEaseOut)+ ]+ trackLayer.add(animation, forKey: "breathe")+ } else if let terminalPresentation {+ animateTerminalFade(terminalPresentation, initialOpacity: initialTerminalOpacity)+ }+ CATransaction.commit()+ }++ private func animateTerminalFade(_ presentation: TaskGlowTerminalPresentation, initialOpacity: Float?) {+ trackLayer.opacity = 0+ let elapsed = max(0, Date().timeIntervalSince(presentation.startedAt))+ guard presentation.duration > elapsed else { return }+ let animation = CAKeyframeAnimation(keyPath: "opacity")+ if presentation.holdDuration > 0 {+ var values: [Float] = [initialOpacity ?? 1]+ var times: [NSNumber] = [0]+ var timingFunctions: [CAMediaTimingFunction] = []+ if let initialOpacity, initialOpacity < 1 {+ let recovery = min(Self.visibilityDuration, presentation.holdDuration / 2)+ values.append(1)+ times.append(NSNumber(value: recovery / presentation.duration))+ timingFunctions.append(CAMediaTimingFunction(name: .easeInEaseOut))+ }+ animation.values = values + [1, 0]+ animation.keyTimes = times + [NSNumber(value: presentation.holdDuration / presentation.duration), 1]+ animation.timingFunctions = timingFunctions + [+ CAMediaTimingFunction(name: .linear),+ CAMediaTimingFunction(name: .easeInEaseOut)+ ]+ } else {+ animation.values = [initialOpacity ?? 1, 0]+ animation.keyTimes = [0, 1]+ animation.timingFunctions = [CAMediaTimingFunction(name: .easeInEaseOut)]+ }+ animation.duration = presentation.duration+ animation.beginTime = trackLayer.convertTime(CACurrentMediaTime(), from: nil) - elapsed+ trackLayer.add(animation, forKey: "terminalFade")+ }++ private func configureMovingLight() {+ let span = min(0.336, max(0.096, 300 / bounds.width))+ let startTime = motionClock.startTime()+ var previousIntensity = 0.0+ for (index, segment) in lightSegments.enumerated() {+ let depth = index % Self.segmentsPerSide+ if depth == 0 {+ previousIntensity = 0+ }+ let position = (Double(depth) + 0.5) / Double(Self.segmentsPerSide)+ let intensity = pow(sin(position * .pi / 2), 2)+ let color = glowAppearance.color(for: .running)+ let tint = color.blended(withFraction: pow(intensity, 8) * 0.8, of: .white) ?? color+ segment.strokeColor = tint.withAlphaComponent((intensity - previousIntensity) / (1 - previousIntensity)).cgColor+ previousIntensity = intensity+ let tailLength = span * (1 - Double(depth) / Double(Self.segmentsPerSide))+ let isLeft = index < Self.segmentsPerSide+ segment.strokeStart = convergencePoint+ segment.strokeEnd = convergencePoint+ animateEmission(segment, tailLength: tailLength, span: span, isLeft: isLeft, startTime: startTime)+ }+ }++ private func animateExtent(expanded: Bool) -> TimeInterval {+ let targets = lightSegments.indices.map { index in+ (+ start: expanded && index < Self.segmentsPerSide ? 0.0 : convergencePoint,+ end: expanded && index >= Self.segmentsPerSide ? 1.0 : convergencePoint+ )+ }+ let distance = zip(lightSegments, targets).map { segment, target in+ max(abs(segment.strokeStart - target.start), abs(segment.strokeEnd - target.end))+ }.max() ?? 0+ let duration = max(0.001, Double(distance) * TaskGlowAnimationTiming.edgeTraversalDuration)+ CATransaction.begin()+ CATransaction.setDisableActions(true)+ for (segment, target) in zip(lightSegments, targets) {+ animateValue(segment, keyPath: "strokeStart", from: segment.strokeStart, to: target.start, duration: duration)+ animateValue(segment, keyPath: "strokeEnd", from: segment.strokeEnd, to: target.end, duration: duration)+ segment.strokeStart = target.start+ segment.strokeEnd = target.end+ }+ CATransaction.commit()+ return duration+ }++ private func setCollapsedColor(_ color: NSColor) {+ CATransaction.begin()+ CATransaction.setDisableActions(true)+ stopArtworkAnimations()+ lightLayer.opacity = 1+ lightLayer.shadowColor = color.cgColor+ for segment in lightSegments {+ segment.strokeStart = convergencePoint+ segment.strokeEnd = convergencePoint+ segment.strokeColor = distributedColor(color.withAlphaComponent(Self.stationaryColorAlpha).cgColor)+ }+ CATransaction.commit()+ }++ private func distributedColor(_ color: CGColor?) -> CGColor? {+ guard let color, let base = NSColor(cgColor: color) else { return color }+ let alpha = 1 - pow(1 - base.alphaComponent, 1 / Double(Self.segmentsPerSide))+ return base.withAlphaComponent(alpha).cgColor+ }++ private func animateVisibility(to opacity: Float) {+ guard let layer else { return }+ let current = layer.presentation()?.opacity ?? layer.opacity+ CATransaction.begin()+ CATransaction.setDisableActions(true)+ layer.removeAnimation(forKey: "visibility")+ layer.opacity = opacity+ animateValue(layer, keyPath: "opacity", from: current, to: opacity, duration: Self.visibilityDuration, key: "visibility")+ CATransaction.commit()+ }++ private func fadeInMovingLight() {+ animateValue(lightLayer, keyPath: "opacity", from: Float(0), to: Float(1), duration: 0.18)+ }++ private func animateValue(_ layer: CALayer, keyPath: String, from: Any?, to: Any?, duration: TimeInterval, key: String? = nil) {+ let animation = CABasicAnimation(keyPath: keyPath)+ animation.fromValue = from+ animation.toValue = to+ animation.duration = duration+ animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)+ layer.add(animation, forKey: key ?? keyPath)+ }++ private func stopArtworkAnimations() {+ trackLayer.removeAllAnimations()+ lightLayer.removeAllAnimations()+ for segment in lightSegments {+ segment.removeAllAnimations()+ }+ }++ /// 各屏幕共享出发和掉头时刻, 回程拖尾完全收进中心后才开始下一轮+ private func animateEmission(_ segment: CAShapeLayer, tailLength: Double, span: Double, isLeft: Bool, startTime: CFTimeInterval) {+ let multiplier = glowAppearance.animationSpeed.durationMultiplier+ let halfCrossing = TaskGlowAnimationTiming.travelDuration / 2 * multiplier+ let offscreen = TaskGlowAnimationTiming.offscreenDuration * multiplier+ let outwardDuration = halfCrossing + offscreen+ let inwardDuration = halfCrossing + offscreen + TaskGlowAnimationTiming.centerRetractionDuration * multiplier+ let outward = emissionAnimation(+ waypoints: [(0, convergencePoint), (halfCrossing, 1), (outwardDuration, 1 + span)],+ tailLength: tailLength, isLeft: isLeft+ )+ let inward = emissionAnimation(+ waypoints: [+ (0, 1 + span), (offscreen, 1),+ (offscreen + halfCrossing, convergencePoint), (inwardDuration, convergencePoint - span)+ ],+ tailLength: tailLength, isLeft: isLeft+ )+ inward.beginTime = outwardDuration+ // 每个单程独立缓入缓出, 保证两端掉头都平滑+ let travel = CAAnimationGroup()+ travel.animations = [outward, inward]+ travel.duration = motionClock.cycleDuration+ travel.beginTime = segment.convertTime(startTime, from: nil)+ travel.repeatCount = repeatsMotion ? .infinity : 0+ segment.add(travel, forKey: "emission")+ }++ /// 在描边进入和离开屏幕的拐点插入关键帧, 屏幕外掉头时同时翻转拖尾方向+ private func emissionAnimation(+ waypoints: [(time: Double, head: Double)],+ tailLength: Double,+ isLeft: Bool+ ) -> CAAnimationGroup {+ let duration = waypoints.last!.time+ var times: [Double] = []+ var starts: [Double] = []+ var ends: [Double] = []+ for (from, to) in zip(waypoints, waypoints.dropFirst()) {+ let distance = to.head - from.head+ let tailOffset = distance > 0 ? -tailLength : tailLength+ let crossings = [convergencePoint, 1].flatMap { boundary in+ [0, tailOffset].map { (boundary - from.head - $0) / distance }+ }+ let progress = Array(Set([0.0, 1.0] + crossings.filter { $0 > 0 && $0 < 1 })).sorted()+ for fraction in progress {+ let time = from.time + (to.time - from.time) * fraction+ if times.last == time {+ continue+ }+ let head = from.head + distance * fraction+ let tail = head + tailOffset+ let start = min(1, max(convergencePoint, min(head, tail)))+ let end = min(1, max(convergencePoint, max(head, tail)))+ times.append(time)+ starts.append(isLeft ? 1 - end : start)+ ends.append(isLeft ? 1 - start : end)+ }+ }+ let startAnimation = CAKeyframeAnimation(keyPath: "strokeStart")+ startAnimation.keyTimes = times.map { NSNumber(value: $0 / duration) }+ startAnimation.values = starts+ let endAnimation = CAKeyframeAnimation(keyPath: "strokeEnd")+ endAnimation.keyTimes = startAnimation.keyTimes+ endAnimation.values = ends+ let animation = CAAnimationGroup()+ animation.animations = [startAnimation, endAnimation]+ animation.duration = duration+ animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)+ return animation+ }+}diff --git a/CodexBarHelper/HelperError.swift b/CodexBarHelper/HelperError.swiftnew file mode 100644index 0000000..914cd68--- /dev/null+++ b/CodexBarHelper/HelperError.swift@@ -0,0 +1,21 @@+import Foundation++enum HelperError: LocalizedError {+ case insecureOwnershipDirectory(String)+ case invalidOwnershipRecord(String)+ case ownershipWriteFailed(operation: String, code: Int32)+ case codeSigningValidationFailed(String)++ var errorDescription: String? {+ switch self {+ case let .insecureOwnershipDirectory(detail):+ "睡眠设置目录无效: \(detail)"+ case let .invalidOwnershipRecord(detail):+ "睡眠所有权记录无效: \(detail)"+ case let .ownershipWriteFailed(operation, code):+ "睡眠所有权记录写入失败: operation=\(operation); errno=\(code)"+ case let .codeSigningValidationFailed(reason):+ "签名校验失败: \(reason)"+ }+ }+}diff --git a/CodexBarHelper/HelperRuntime.swift b/CodexBarHelper/HelperRuntime.swiftnew file mode 100644index 0000000..a3d8ad2--- /dev/null+++ b/CodexBarHelper/HelperRuntime.swift@@ -0,0 +1,994 @@+import Darwin+import Foundation+import IOKit+import IOKit.pwr_mgt+import os+import Security+import Synchronization++private let helperLog = Logger(+ subsystem: CodexBarHelperIPC.machServiceName,+ category: "helper"+)++enum LogFields {+ static func joined(_ fields: String...) -> String {+ fields.joined(separator: "; ")+ }+}++private enum CodexBarHelperStorage {+ static let ownershipURL: URL = {+ guard let applicationSupportURL = FileManager.default.urls(+ for: .applicationSupportDirectory,+ in: .localDomainMask+ ).first else {+ helperLog.error("Helper 启动失败: reason=applicationSupportMissing")+ exit(EXIT_FAILURE)+ }+ return applicationSupportURL+ .appending(path: "CodexBar", directoryHint: .isDirectory)+ .appending(path: "helper-state.json")+ }()+}++private struct SleepOperationResult {+ let exitCode: Int32+ let source: CodexBarSleepPreventionSource+ let sleepDisabled: Bool+}++private struct ClientLease {+ var generation: UInt64+ var isRequesting: Bool+ var connectionIdentifier: UUID?+}++private enum SleepRestoreTrigger: String {+ case appRequest+ case connectionWatchdog+ case helperStartup+ case ownershipCheck+ case helperTermination+}++private enum WakeScheduleCleanupTrigger: String {+ case appRequest+ case connectionClosed+ case helperStartup+ case ownershipCheck+ case helperTermination+}++private final class HelperSession: NSObject, CodexBarHelperProtocol,+ @unchecked Sendable {+ let identifier = UUID()+ private weak var runtime: HelperRuntime?++ init(runtime: HelperRuntime) {+ self.runtime = runtime+ }++ func setSleepPreventionRequested(+ _ requested: Bool,+ clientSessionID: String,+ generation: UInt64,+ reply: @escaping @Sendable (Int32, Int, Bool) -> Void+ ) {+ guard let runtime else {+ reply(-1, CodexBarSleepPreventionSource.none.rawValue, false)+ return+ }+ runtime.setSleepPreventionRequested(+ requested,+ clientSessionID: clientSessionID,+ generation: generation,+ for: identifier,+ reply: reply+ )+ }++ func getSleepPreventionStatus(+ reply: @escaping @Sendable (Int32, Int, Int, Bool) -> Void+ ) {+ guard let runtime else {+ reply(-1, CodexBarSleepOwnershipState.idle.rawValue, 0, false)+ return+ }+ runtime.getSleepPreventionStatus(+ for: identifier,+ reply: reply+ )+ }++ func resetSleepAfterUpdate(+ _ updateIdentifier: String,+ reply: @escaping @Sendable (Int32) -> Void+ ) {+ guard let runtime else {+ reply(-1)+ return+ }+ runtime.resetSleepAfterUpdate(+ updateIdentifier,+ for: identifier,+ reply: reply+ )+ }++ func setAutoResetWakeSchedule(+ _ unixTimestamp: TimeInterval,+ reply: @escaping @Sendable (Int32) -> Void+ ) {+ guard let runtime else {+ reply(-1)+ return+ }+ runtime.setAutoResetWakeSchedule(+ unixTimestamp,+ for: identifier,+ reply: reply+ )+ }+}++final class HelperRuntime: NSObject, NSXPCListenerDelegate, @unchecked Sendable {+ private struct Watchdog {+ let token: UUID+ let workItem: DispatchWorkItem+ }++ private let queue = DispatchQueue(label: CodexBarHelperIPC.machServiceName + ".state")+ private let ownershipStore = OwnershipStore(url: CodexBarHelperStorage.ownershipURL)+ private var ownership = SleepOwnership.idle+ private var transactionID = UUID()+ private var lastCompletedUpdateIdentifier: String?+ private var connections = Set<UUID>()+ private var clients = [UUID: ClientLease]()+ private var watchdogs = [UUID: Watchdog]()+ private var lastKnownSleepDisabled: Bool?+ private var ownershipTimer: DispatchSourceTimer?+ private var scheduledOwnershipCheckInterval: TimeInterval?+ private var autoResetWakeConnectionIdentifier: UUID?+ private var isAutoResetWakeCleanupPending = false+ private var signalSources = [DispatchSourceSignal]()+ private var listener: NSXPCListener?++ func run() {+ guard geteuid() == 0 else {+ helperLog.error("Helper 启动失败: reason=notRoot")+ exit(EXIT_FAILURE)+ }++ do {+ try ownershipStore.ensureOwnershipDirectory()+ } catch {+ let directoryPath = ownershipStore.url.deletingLastPathComponent().path+ let details = LogFields.joined(+ "reason=ownershipDirectory",+ "path=\(directoryPath)",+ "detail=\(error.localizedDescription)"+ )+ helperLog.error("Helper 启动失败: \(details, privacy: .public)")+ exit(EXIT_FAILURE)+ }++ recoverOwnershipAtStartup()+ recoverAutoResetWakeScheduleAtStartup()+ installOwnershipTimer()+ installSignalHandlers()++ let clientCodeSigningRequirement: String+ do {+ clientCodeSigningRequirement = try Self.makeClientCodeSigningRequirement()+ } catch {+ let details = LogFields.joined(+ "reason=listener",+ "detail=\(error.localizedDescription)"+ )+ helperLog.error("Helper 启动失败: \(details, privacy: .public)")+ exit(EXIT_FAILURE)+ }++ let listener = NSXPCListener(machServiceName: CodexBarHelperIPC.machServiceName)+ listener.setConnectionCodeSigningRequirement(clientCodeSigningRequirement)+ listener.delegate = self+ listener.resume()+ self.listener = listener+ }++ // MARK: - XPC 接口++ fileprivate func setSleepPreventionRequested(+ _ requested: Bool,+ clientSessionID: String,+ generation: UInt64,+ for identifier: UUID,+ reply: @escaping @Sendable (Int32, Int, Bool) -> Void+ ) {+ queue.async { [self] in+ guard connections.contains(identifier),+ let clientIdentifier = UUID(uuidString: clientSessionID) else {+ reply(-1, CodexBarSleepPreventionSource.none.rawValue, false)+ return+ }++ if let currentLease = clients[clientIdentifier] {+ guard generation >= currentLease.generation else {+ let result = currentOperationResult()+ reply(result.exitCode, result.source.rawValue, result.sleepDisabled)+ return+ }+ guard generation != currentLease.generation+ || requested == currentLease.isRequesting else {+ reply(-1, currentSource().rawValue, lastKnownSleepDisabled ?? false)+ return+ }+ }++ cancelWatchdog(for: clientIdentifier)+ let source = currentSource()+ clients[clientIdentifier] = ClientLease(+ generation: generation,+ isRequesting: requested,+ connectionIdentifier: identifier+ )++ let result: SleepOperationResult+ if requested {+ let isNewRequest = source == .none+ result = reconcileRequestedSleep(logsExternalState: isNewRequest)+ } else {+ result = reconcileReleasedSleep(source: source, trigger: .appRequest)+ }+ scheduleOwnershipTimerIfNeeded()+ reply(result.exitCode, result.source.rawValue, result.sleepDisabled)+ }+ }++ fileprivate func getSleepPreventionStatus(+ for identifier: UUID,+ reply: @escaping @Sendable (Int32, Int, Int, Bool) -> Void+ ) {+ queue.async { [self] in+ guard connections.contains(identifier),+ let lastKnownSleepDisabled else {+ reply(-1, ownership.sharedState.rawValue, activeClientCount, false)+ return+ }+ reply(+ 0,+ ownership.sharedState.rawValue,+ activeClientCount,+ lastKnownSleepDisabled+ )+ }+ }++ fileprivate func resetSleepAfterUpdate(+ _ updateIdentifier: String,+ for identifier: UUID,+ reply: @escaping @Sendable (Int32) -> Void+ ) {+ queue.async { [self] in+ guard connections.contains(identifier),+ Self.isValidUpdateIdentifier(updateIdentifier) else {+ reply(-1)+ return+ }+ guard lastCompletedUpdateIdentifier != updateIdentifier else {+ reply(0)+ return+ }++ let result = setAndVerifySleepDisabled(false)+ guard result.exitCode == 0 else {+ reply(result.exitCode)+ return+ }++ let previousUpdateIdentifier = lastCompletedUpdateIdentifier+ lastCompletedUpdateIdentifier = updateIdentifier+ do {+ try persistOwnership(.idle)+ } catch {+ lastCompletedUpdateIdentifier = previousUpdateIdentifier+ logOwnershipWriteFailure(error)+ reply(-1)+ return+ }++ helperLog.notice("Helper 更新后睡眠状态已重置")+ reply(0)+ }+ }++ fileprivate func setAutoResetWakeSchedule(+ _ unixTimestamp: TimeInterval,+ for identifier: UUID,+ reply: @escaping @Sendable (Int32) -> Void+ ) {+ queue.async { [self] in+ guard connections.contains(identifier),+ unixTimestamp.isFinite,+ unixTimestamp >= 0 else {+ reply(kIOReturnBadArgument)+ return+ }++ let date: Date?+ if unixTimestamp == 0 {+ date = nil+ } else {+ let requestedDate = Date(timeIntervalSince1970: unixTimestamp)+ guard requestedDate > Date() else {+ reply(kIOReturnBadArgument)+ return+ }+ date = requestedDate+ }++ if date == nil {+ autoResetWakeConnectionIdentifier = nil+ } else {+ autoResetWakeConnectionIdentifier = identifier+ }++ let result: IOReturn = if date == nil {+ cancelAutoResetWakeSchedule(trigger: .appRequest)+ } else {+ AutoResetWakeScheduler.replaceSchedule(with: date)+ }+ guard result == kIOReturnSuccess else {+ if date != nil {+ scheduleOwnershipTimerIfNeeded()+ }+ let details = LogFields.joined(+ "action=\(date == nil ? "cancel" : "schedule")",+ "code=\(result)"+ )+ helperLog.error("自动重置唤醒计划更新失败: \(details, privacy: .public)")+ reply(result)+ return+ }++ if date != nil {+ isAutoResetWakeCleanupPending = false+ scheduleOwnershipTimerIfNeeded()+ }+ if let date {+ let epoch = Int(date.timeIntervalSince1970)+ helperLog.notice("自动重置唤醒计划已设置: epoch=\(epoch)")+ }+ reply(kIOReturnSuccess)+ }+ }++ func listener(+ _: NSXPCListener,+ shouldAcceptNewConnection newConnection: NSXPCConnection+ ) -> Bool {+ let session = HelperSession(runtime: self)+ let identifier = session.identifier+ newConnection.exportedInterface = NSXPCInterface(+ with: CodexBarHelperProtocol.self+ )+ newConnection.exportedObject = session++ let connectionDropped: () -> Void = { [weak self] in+ self?.connectionDropped(identifier)+ }+ newConnection.invalidationHandler = connectionDropped+ newConnection.interruptionHandler = connectionDropped++ queue.sync {+ _ = connections.insert(identifier)+ }+ newConnection.resume()+ return true+ }++ private func connectionDropped(_ identifier: UUID) {+ queue.async { [self] in+ guard connections.remove(identifier) != nil else {+ return+ }++ cancelAutoResetWakeSchedule(ifOwnedBy: identifier)+ let droppedClients = clients.compactMap { clientIdentifier, lease in+ lease.connectionIdentifier == identifier ? clientIdentifier : nil+ }+ for clientIdentifier in droppedClients {+ guard var lease = clients[clientIdentifier] else {+ continue+ }+ guard lease.isRequesting else {+ clients[clientIdentifier] = nil+ continue+ }++ lease.connectionIdentifier = nil+ clients[clientIdentifier] = lease+ scheduleWatchdog(for: clientIdentifier, generation: lease.generation)+ }+ scheduleOwnershipTimerIfNeeded()+ }+ }++ private func cancelAutoResetWakeSchedule(ifOwnedBy identifier: UUID) {+ guard autoResetWakeConnectionIdentifier == identifier else {+ return+ }++ autoResetWakeConnectionIdentifier = nil+ _ = cancelAutoResetWakeSchedule(trigger: .connectionClosed)+ }++ @discardableResult+ private func cancelAutoResetWakeSchedule(+ trigger: WakeScheduleCleanupTrigger+ ) -> IOReturn {+ defer { scheduleOwnershipTimerIfNeeded() }+ let result = AutoResetWakeScheduler.replaceSchedule(with: nil)+ guard result == kIOReturnSuccess else {+ isAutoResetWakeCleanupPending = true+ let details = LogFields.joined(+ "reason=\(trigger.rawValue)",+ "code=\(result)",+ "remaining=\(AutoResetWakeScheduler.ownedEventCount)"+ )+ helperLog.error("自动重置唤醒计划取消失败: \(details, privacy: .public)")+ return result+ }++ isAutoResetWakeCleanupPending = false+ helperLog.notice(+ "自动重置唤醒计划已取消: reason=\(trigger.rawValue, privacy: .public)"+ )+ return kIOReturnSuccess+ }++ private func scheduleWatchdog(for clientIdentifier: UUID, generation: UInt64) {+ guard watchdogs[clientIdentifier] == nil else {+ return+ }++ let token = UUID()+ let workItem = DispatchWorkItem { [weak self] in+ guard let self, watchdogs[clientIdentifier]?.token == token else {+ return+ }+ watchdogs[clientIdentifier] = nil+ guard let lease = clients[clientIdentifier],+ lease.generation == generation,+ lease.isRequesting,+ lease.connectionIdentifier == nil else {+ return+ }++ let source = currentSource()+ clients[clientIdentifier] = nil+ _ = reconcileReleasedSleep(source: source, trigger: .connectionWatchdog)+ scheduleOwnershipTimerIfNeeded()+ }+ watchdogs[clientIdentifier] = Watchdog(token: token, workItem: workItem)+ queue.asyncAfter(+ deadline: .now() + CodexBarHelperIPC.watchdogGraceSeconds,+ execute: workItem+ )+ }++ private func cancelWatchdog(for clientIdentifier: UUID) {+ watchdogs.removeValue(forKey: clientIdentifier)?.workItem.cancel()+ }++ // MARK: - 所有权与睡眠切换++ private func reconcileRequestedSleep(logsExternalState: Bool) -> SleepOperationResult {+ if ownership == .restoring {+ let recovery = restoreOwnedSleep(trigger: .appRequest)+ guard recovery.exitCode == 0 else {+ return recovery+ }+ }++ if ownership == .owned {+ guard validateOrRepairOwnedRecord() else {+ return recoverFromOwnedRecordFailure()+ }++ let current = readCurrentSleepDisabled()+ guard current.result.exitCode == 0, let sleepDisabled = current.value else {+ logPmsetReadFailure(current.result)+ return SleepOperationResult(+ exitCode: normalizedFailureCode(current.result.exitCode),+ source: .codexBar,+ sleepDisabled: false+ )+ }++ if !sleepDisabled {+ let result = setAndVerifySleepDisabled(true)+ guard result.exitCode == 0 else {+ return SleepOperationResult(+ exitCode: result.exitCode,+ source: .codexBar,+ sleepDisabled: result.value ?? false+ )+ }+ guard validateOrRepairOwnedRecord() else {+ return recoverFromOwnedRecordFailure()+ }+ }+ return SleepOperationResult(exitCode: 0, source: .codexBar, sleepDisabled: true)+ }++ let current = readCurrentSleepDisabled()+ guard current.result.exitCode == 0, let sleepDisabled = current.value else {+ logPmsetReadFailure(current.result)+ return SleepOperationResult(+ exitCode: normalizedFailureCode(current.result.exitCode),+ source: .none,+ sleepDisabled: false+ )+ }++ guard !sleepDisabled else {+ if logsExternalState {+ helperLog.notice("系统睡眠已由其他来源关闭")+ }+ return SleepOperationResult(exitCode: 0, source: .external, sleepDisabled: true)+ }++ do {+ try persistOwnership(.owned)+ } catch {+ logOwnershipWriteFailure(error)+ return SleepOperationResult(exitCode: -1, source: .none, sleepDisabled: false)+ }++ let result = setAndVerifySleepDisabled(true)+ guard result.exitCode == 0 else {+ return SleepOperationResult(+ exitCode: result.exitCode,+ source: .codexBar,+ sleepDisabled: result.value ?? false+ )+ }+ guard validateOrRepairOwnedRecord() else {+ return recoverFromOwnedRecordFailure()+ }++ helperLog.notice("系统睡眠已由 CodexBar 关闭")+ return SleepOperationResult(exitCode: 0, source: .codexBar, sleepDisabled: true)+ }++ private func reconcileReleasedSleep(+ source: CodexBarSleepPreventionSource,+ trigger: SleepRestoreTrigger+ ) -> SleepOperationResult {+ guard activeClientCount == 0 else {+ return reconcileRequestedSleep(logsExternalState: false)+ }++ guard ownership.needsRestore else {+ // 未取得所有权时不写 pmset, 返回最近一次实测值+ return SleepOperationResult(+ exitCode: 0,+ source: source,+ sleepDisabled: lastKnownSleepDisabled ?? (source == .external)+ )+ }+ return restoreOwnedSleep(trigger: trigger)+ }++ @discardableResult+ private func restoreOwnedSleep(trigger: SleepRestoreTrigger) -> SleepOperationResult {+ do {+ try persistOwnership(.restoring)+ } catch {+ // 写恢复中标记失败也必须继续尝试写回 0, 否则记录故障本身会把机器永久卡在 1+ logOwnershipWriteFailure(error)+ }++ let result = setAndVerifySleepDisabled(false)+ guard result.exitCode == 0 else {+ let details = LogFields.joined(+ "trigger=\(trigger.rawValue)",+ "exit=\(result.exitCode)"+ )+ helperLog.error("系统睡眠恢复失败: \(details, privacy: .public)")+ return SleepOperationResult(+ exitCode: result.exitCode,+ source: .codexBar,+ sleepDisabled: result.value ?? true+ )+ }++ do {+ try persistOwnership(.idle)+ } catch {+ logOwnershipWriteFailure(error)+ return SleepOperationResult(exitCode: -1, source: .codexBar, sleepDisabled: false)+ }++ let details = LogFields.joined(+ "trigger=\(trigger.rawValue)",+ "sleepDisabled=0"+ )+ helperLog.notice("系统睡眠已恢复: \(details, privacy: .public)")+ return SleepOperationResult(exitCode: 0, source: .codexBar, sleepDisabled: false)+ }++ private func setAndVerifySleepDisabled(+ _ disabled: Bool+ ) -> (exitCode: Int32, value: Bool?) {+ let writeResult = PmsetRunner.setSleepDisabled(disabled)+ guard writeResult.exitCode == 0 else {+ let details = LogFields.joined(+ "target=\(disabled ? 1 : 0)",+ "exit=\(writeResult.exitCode)",+ "detail=\(writeResult.output)"+ )+ helperLog.error("pmset 写入失败: \(details, privacy: .public)")+ return (writeResult.exitCode, nil)+ }++ let readResult = readCurrentSleepDisabled()+ guard readResult.result.exitCode == 0, let value = readResult.value else {+ logPmsetReadFailure(readResult.result)+ return (normalizedFailureCode(readResult.result.exitCode), nil)+ }+ guard value == disabled else {+ let details = LogFields.joined(+ "target=\(disabled ? 1 : 0)",+ "actual=\(value ? 1 : 0)"+ )+ helperLog.error("pmset 写入校验失败: \(details, privacy: .public)")+ return (-1, value)+ }+ return (0, value)+ }++ private func readCurrentSleepDisabled() -> (result: PmsetResult, value: Bool?) {+ let current = PmsetRunner.currentSleepDisabled()+ if current.result.exitCode == 0, let value = current.value {+ lastKnownSleepDisabled = value+ }+ return current+ }++ private func validateOrRepairOwnedRecord() -> Bool {+ guard ownership == .owned else {+ return false+ }++ if case let .present(record) = ownershipStore.ownershipRecordState(),+ record.state == .owned,+ record.transaction == transactionID {+ return true+ }++ helperLog.error("睡眠所有权记录与运行状态不一致: action=repair")+ do {+ try persistOwnership(.owned)+ helperLog.notice("睡眠所有权记录已修复")+ return true+ } catch {+ logOwnershipWriteFailure(error)+ return false+ }+ }++ private func recoverFromOwnedRecordFailure() -> SleepOperationResult {+ let recovery = restoreOwnedSleep(trigger: .ownershipCheck)+ return SleepOperationResult(+ exitCode: recovery.exitCode == 0 ? -1 : recovery.exitCode,+ source: .codexBar,+ sleepDisabled: recovery.sleepDisabled+ )+ }++ private func currentSource() -> CodexBarSleepPreventionSource {+ if ownership.needsRestore {+ return .codexBar+ }+ return activeClientCount == 0 ? .none : .external+ }++ private func currentOperationResult() -> SleepOperationResult {+ guard let lastKnownSleepDisabled else {+ return SleepOperationResult(exitCode: -1, source: currentSource(), sleepDisabled: false)+ }+ return SleepOperationResult(+ exitCode: 0,+ source: currentSource(),+ sleepDisabled: lastKnownSleepDisabled+ )+ }++ private var activeClientCount: Int {+ clients.values.lazy.filter(\.isRequesting).count+ }++ private func normalizedFailureCode(_ exitCode: Int32) -> Int32 {+ exitCode == 0 ? -1 : exitCode+ }++ private func logPmsetReadFailure(_ result: PmsetResult) {+ let details = LogFields.joined(+ "exit=\(result.exitCode)",+ "detail=\(result.output)"+ )+ helperLog.error("pmset 读取失败: \(details, privacy: .public)")+ }++ // MARK: - 异常恢复++ private func recoverOwnershipAtStartup() {+ let state = ownershipStore.ownershipRecordState()+ switch state {+ case .absent:+ do {+ try persistOwnership(.idle)+ helperLog.notice("Helper 已启动: ownership=idle")+ } catch {+ logOwnershipWriteFailure(error)+ exit(EXIT_FAILURE)+ }+ case let .present(record):+ ownership = record.state+ transactionID = record.transaction+ lastCompletedUpdateIdentifier = record.identifier+ helperLog.notice(+ "Helper 已启动: ownership=\(record.state.rawValue, privacy: .public)"+ )+ if record.state.needsRestore {+ _ = restoreOwnedSleep(trigger: .helperStartup)+ }+ case let .unreadable(error):+ // 损坏记录无法证明所有权, 启动时按最安全的默认值 0 收敛+ let details = LogFields.joined(+ "detail=\(error.localizedDescription)",+ "action=forceRestore"+ )+ helperLog.error("睡眠所有权记录无效: \(details, privacy: .public)")+ ownership = .restoring+ _ = restoreOwnedSleep(trigger: .helperStartup)+ }++ if lastKnownSleepDisabled == nil {+ let current = readCurrentSleepDisabled()+ if current.result.exitCode != 0 || current.value == nil {+ logPmsetReadFailure(current.result)+ }+ }+ }++ private func recoverAutoResetWakeScheduleAtStartup() {+ let initialEventCount = AutoResetWakeScheduler.ownedEventCount+ guard initialEventCount > 0 else {+ return+ }++ var lastResult = IOReturn(kIOReturnError)+ for delay in Self.wakeCleanupStartupRetryDelays {+ if delay > 0 {+ Thread.sleep(forTimeInterval: delay)+ }+ lastResult = AutoResetWakeScheduler.replaceSchedule(with: nil)+ if lastResult == kIOReturnSuccess {+ helperLog.notice(+ "自动重置遗留唤醒计划已清理: reason=helperStartup count=\(initialEventCount)"+ )+ return+ }+ }++ isAutoResetWakeCleanupPending = true+ let details = LogFields.joined(+ "reason=\(WakeScheduleCleanupTrigger.helperStartup.rawValue)",+ "code=\(lastResult)",+ "remaining=\(AutoResetWakeScheduler.ownedEventCount)"+ )+ helperLog.error("自动重置遗留唤醒计划清理失败: \(details, privacy: .public)")+ }++ private func installOwnershipTimer() {+ let timer = DispatchSource.makeTimerSource(queue: queue)+ timer.setEventHandler { [weak self] in+ guard let self else {+ return+ }+ if activeClientCount > 0 {+ _ = reconcileRequestedSleep(logsExternalState: false)+ } else if ownership.needsRestore, watchdogs.isEmpty {+ _ = restoreOwnedSleep(trigger: .ownershipCheck)+ }+ if isAutoResetWakeCleanupPending,+ autoResetWakeConnectionIdentifier == nil {+ _ = cancelAutoResetWakeSchedule(trigger: .ownershipCheck)+ }+ scheduleOwnershipTimerIfNeeded()+ }+ ownershipTimer = timer+ scheduleOwnershipTimerIfNeeded(force: true)+ timer.resume()+ }++ private func scheduleOwnershipTimerIfNeeded(force: Bool = false) {+ guard let ownershipTimer else {+ return+ }++ let interval: TimeInterval = if isAutoResetWakeCleanupPending {+ CodexBarHelperIPC.ownedCheckIntervalSeconds+ } else if activeClientCount == 0 {+ CodexBarHelperIPC.recoveryCheckIntervalSeconds+ } else if ownership.needsRestore {+ CodexBarHelperIPC.ownedCheckIntervalSeconds+ } else {+ CodexBarHelperIPC.externalCheckIntervalSeconds+ }+ guard force || interval != scheduledOwnershipCheckInterval else {+ return+ }++ scheduledOwnershipCheckInterval = interval+ ownershipTimer.schedule(+ deadline: .now() + interval,+ repeating: interval,+ leeway: .seconds(Int(CodexBarHelperIPC.checkLeewaySeconds))+ )+ }++ private func installSignalHandlers() {+ for signalNumber in [SIGTERM, SIGINT] {+ signal(signalNumber, SIG_IGN)+ let source = DispatchSource.makeSignalSource(signal: signalNumber, queue: queue)+ source.setEventHandler { [weak self] in+ guard let self else {+ exit(EXIT_SUCCESS)+ }+ if ownership.needsRestore {+ _ = restoreOwnedSleep(trigger: .helperTermination)+ }+ autoResetWakeConnectionIdentifier = nil+ _ = cancelAutoResetWakeSchedule(trigger: .helperTermination)+ exit(EXIT_SUCCESS)+ }+ source.resume()+ signalSources.append(source)+ }+ }++ private static let wakeCleanupStartupRetryDelays: [TimeInterval] = [0, 0.25, 1]++ // MARK: - 所有权记录++ private func persistOwnership(_ state: SleepOwnership) throws {+ try ownershipStore.ensureOwnershipDirectory()+ if state == .owned, ownership == .idle {+ transactionID = UUID()+ }+ let record = SleepOwnershipRecord(+ schema: 1,+ state: state,+ transaction: transactionID,+ identifier: lastCompletedUpdateIdentifier,+ updated: Date()+ )+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ let data = try encoder.encode(record)+ try ownershipStore.writeOwnershipDataDurably(data)+ guard case let .present(savedRecord) = ownershipStore.ownershipRecordState(),+ savedRecord.state == state,+ savedRecord.transaction == transactionID,+ savedRecord.identifier == lastCompletedUpdateIdentifier else {+ throw HelperError.invalidOwnershipRecord("写入后校验失败")+ }+ ownership = state+ }++ private func logOwnershipWriteFailure(_ error: Error) {+ let path = ownershipStore.url.path+ let details = LogFields.joined(+ "path=\(path)",+ "detail=\(error.localizedDescription)"+ )+ helperLog.error("睡眠所有权记录写入失败: \(details, privacy: .public)")+ }++ private static func isValidUpdateIdentifier(_ identifier: String) -> Bool {+ let bytes = identifier.utf8+ return bytes.count == 64 && bytes.allSatisfy { byte in+ (48 ... 57).contains(byte) || (97 ... 102).contains(byte)+ }+ }++ private static func makeClientCodeSigningRequirement() throws -> String {+ var runningCode: SecCode?+ var status = SecCodeCopySelf(SecCSFlags(), &runningCode)+ guard status == errSecSuccess, let runningCode else {+ let details = LogFields.joined(+ "Operation=SecCodeCopySelf",+ "Status=\(status)"+ )+ throw HelperError.codeSigningValidationFailed(+ "读取运行签名失败: \(details)"+ )+ }++ var staticCode: SecStaticCode?+ status = SecCodeCopyStaticCode(runningCode, SecCSFlags(), &staticCode)+ guard status == errSecSuccess, let staticCode else {+ let details = LogFields.joined(+ "Operation=SecCodeCopyStaticCode",+ "Status=\(status)"+ )+ throw HelperError.codeSigningValidationFailed(+ "读取静态签名失败: \(details)"+ )+ }++ var signingInformation: CFDictionary?+ status = SecCodeCopySigningInformation(+ staticCode,+ SecCSFlags(rawValue: kSecCSSigningInformation),+ &signingInformation+ )+ guard status == errSecSuccess, let signingInformation else {+ let details = LogFields.joined(+ "Operation=SecCodeCopySigningInformation",+ "Status=\(status)"+ )+ throw HelperError.codeSigningValidationFailed(+ "读取签名信息失败: \(details)"+ )+ }++ let values = signingInformation as NSDictionary+ guard let teamIdentifier = values[kSecCodeInfoTeamIdentifier] as? String else {+ throw HelperError.codeSigningValidationFailed("Team ID 缺失")+ }+ guard let helperIdentifier = values[kSecCodeInfoIdentifier] as? String else {+ throw HelperError.codeSigningValidationFailed("Helper 标识符缺失")+ }++ guard helperIdentifier == CodexBarHelperIPC.machServiceName else {+ let details = LogFields.joined(+ "actual=\(helperIdentifier)",+ "expected=\(CodexBarHelperIPC.machServiceName)"+ )+ throw HelperError.codeSigningValidationFailed(+ "Helper 标识符错误: \(details)"+ )+ }++ let clientIdentifier = CodexBarHelperIPC.appBundleIdentifier+ let identifierCharacters = CharacterSet.alphanumerics.union(+ CharacterSet(charactersIn: ".-")+ )+ guard !teamIdentifier.isEmpty else {+ throw HelperError.codeSigningValidationFailed("Team ID 为空")+ }+ guard teamIdentifier.unicodeScalars.allSatisfy(CharacterSet.alphanumerics.contains) else {+ throw HelperError.codeSigningValidationFailed(+ "Team ID 格式错误: \(teamIdentifier)"+ )+ }+ guard !clientIdentifier.isEmpty else {+ throw HelperError.codeSigningValidationFailed("客户端标识符为空")+ }+ guard clientIdentifier.unicodeScalars.allSatisfy(identifierCharacters.contains) else {+ throw HelperError.codeSigningValidationFailed(+ "客户端标识符格式错误: \(clientIdentifier)"+ )+ }++ return "anchor apple generic"+ + " and certificate leaf[subject.OU] = \"\(teamIdentifier)\""+ + " and identifier \"\(clientIdentifier)\""+ }+}diff --git a/CodexBarHelper/OwnershipStore.swift b/CodexBarHelper/OwnershipStore.swiftnew file mode 100644index 0000000..aa299d9--- /dev/null+++ b/CodexBarHelper/OwnershipStore.swift@@ -0,0 +1,291 @@+import Darwin+import Foundation++enum SleepOwnership: String, Codable {+ case idle+ case owned+ case restoring++ var needsRestore: Bool {+ self != .idle+ }++ var sharedState: CodexBarSleepOwnershipState {+ switch self {+ case .idle:+ .idle+ case .owned:+ .owned+ case .restoring:+ .restoring+ }+ }+}++struct SleepOwnershipRecord: Codable {+ let schema: Int+ let state: SleepOwnership+ let transaction: UUID+ let identifier: String?+ let updated: Date+}++enum OwnershipRecordState {+ case absent+ case present(SleepOwnershipRecord)+ case unreadable(Error)+}++struct OwnershipStore {+ let url: URL++ func ensureOwnershipDirectory() throws {+ let directoryURL = url.deletingLastPathComponent()+ var info = stat()+ if lstat(directoryURL.path, &info) == 0 {+ try validateOwnershipDirectory(info)+ return+ }++ guard errno == ENOENT else {+ throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)+ }+ try FileManager.default.createDirectory(+ at: directoryURL,+ withIntermediateDirectories: false+ )+ try FileManager.default.setAttributes(+ [.ownerAccountID: 0, .groupOwnerAccountID: 0, .posixPermissions: 0o755],+ ofItemAtPath: directoryURL.path+ )+ }++ private func validateOwnershipDirectory(_ info: stat) throws {+ guard info.st_mode & S_IFMT == S_IFDIR else {+ let details = LogFields.joined(+ "actual=\(fileTypeName(info.st_mode))",+ "expected=directory"+ )+ throw HelperError.insecureOwnershipDirectory(+ "目录类型错误: \(details)"+ )+ }+ guard info.st_uid == 0 else {+ let details = LogFields.joined(+ "actual=\(info.st_uid)",+ "expected=0"+ )+ throw HelperError.insecureOwnershipDirectory(+ "所有者错误: \(details)"+ )+ }+ guard info.st_mode & 0o022 == 0 else {+ let details = LogFields.joined(+ "actual=\(permissionString(info.st_mode))",+ "forbidden=0022"+ )+ throw HelperError.insecureOwnershipDirectory(+ "目录权限错误: \(details)"+ )+ }+ }++ func writeOwnershipDataDurably(_ data: Data) throws {+ let directoryURL = url.deletingLastPathComponent()+ let temporaryURL = directoryURL.appending(+ path: ".helper-state.\(UUID().uuidString).tmp"+ )+ var descriptor = open(+ temporaryURL.path,+ O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC,+ mode_t(0o600)+ )+ guard descriptor >= 0 else {+ throw ownershipWriteError(operation: "open")+ }++ var shouldRemoveTemporaryFile = true+ defer {+ if descriptor >= 0 {+ _ = Darwin.close(descriptor)+ }+ if shouldRemoveTemporaryFile {+ _ = unlink(temporaryURL.path)+ }+ }++ try data.withUnsafeBytes { bytes in+ guard let baseAddress = bytes.baseAddress else {+ return+ }++ var offset = 0+ while offset < bytes.count {+ let written = Darwin.write(+ descriptor,+ baseAddress.advanced(by: offset),+ bytes.count - offset+ )+ if written < 0, errno == EINTR {+ continue+ }+ guard written > 0 else {+ throw ownershipWriteError(operation: "write")+ }+ offset += written+ }+ }++ guard fchown(descriptor, 0, 0) == 0 else {+ throw ownershipWriteError(operation: "fchown")+ }+ guard fchmod(descriptor, mode_t(0o600)) == 0 else {+ throw ownershipWriteError(operation: "fchmod")+ }+ try synchronizeOwnershipFile(descriptor)++ let closeResult = Darwin.close(descriptor)+ descriptor = -1+ guard closeResult == 0 else {+ throw ownershipWriteError(operation: "close")+ }+ guard rename(temporaryURL.path, url.path) == 0 else {+ throw ownershipWriteError(operation: "rename")+ }+ shouldRemoveTemporaryFile = false+ try synchronizeOwnershipDirectory(directoryURL)+ }++ private func synchronizeOwnershipFile(_ descriptor: Int32) throws {+ if fcntl(descriptor, F_FULLFSYNC) == 0 {+ return+ }+ guard fsync(descriptor) == 0 else {+ throw ownershipWriteError(operation: "fsync")+ }+ }++ private func synchronizeOwnershipDirectory(_ directoryURL: URL) throws {+ let descriptor = open(directoryURL.path, O_RDONLY | O_CLOEXEC)+ guard descriptor >= 0 else {+ throw ownershipWriteError(operation: "openDirectory")+ }+ defer {+ _ = Darwin.close(descriptor)+ }++ guard fsync(descriptor) == 0 else {+ let errorCode = errno+ // 部分文件系统不支持对目录执行 fsync, 文件本身已经完成 F_FULLFSYNC+ if errorCode == EINVAL || errorCode == ENOTSUP {+ return+ }+ throw ownershipWriteError(operation: "fsyncDirectory", code: errorCode)+ }+ }++ private func ownershipWriteError(+ operation: String,+ code: Int32 = errno+ ) -> HelperError {+ .ownershipWriteFailed(operation: operation, code: code)+ }++ func ownershipRecordState() -> OwnershipRecordState {+ do {+ guard let record = try readOwnershipRecord() else {+ return .absent+ }+ return .present(record)+ } catch {+ return .unreadable(error)+ }+ }++ private func readOwnershipRecord() throws -> SleepOwnershipRecord? {+ var info = stat()+ guard lstat(url.path, &info) == 0 else {+ if errno == ENOENT {+ return nil+ }+ throw HelperError.invalidOwnershipRecord(+ "读取属性失败: errno=\(errno)"+ )+ }+ guard info.st_mode & S_IFMT == S_IFREG else {+ let details = LogFields.joined(+ "actual=\(fileTypeName(info.st_mode))",+ "expected=file"+ )+ throw HelperError.invalidOwnershipRecord(+ "文件类型错误: \(details)"+ )+ }+ guard info.st_uid == 0 else {+ let details = LogFields.joined(+ "actual=\(info.st_uid)",+ "expected=0"+ )+ throw HelperError.invalidOwnershipRecord(+ "所有者错误: \(details)"+ )+ }+ guard info.st_mode & 0o022 == 0 else {+ let details = LogFields.joined(+ "actual=\(permissionString(info.st_mode))",+ "forbidden=0022"+ )+ throw HelperError.invalidOwnershipRecord(+ "文件权限错误: \(details)"+ )+ }++ let data: Data+ do {+ data = try Data(contentsOf: url)+ } catch {+ throw HelperError.invalidOwnershipRecord(+ "读取内容失败: detail=\(error.localizedDescription)"+ )+ }++ let decoder = JSONDecoder()+ decoder.dateDecodingStrategy = .iso8601+ let record: SleepOwnershipRecord+ do {+ record = try decoder.decode(SleepOwnershipRecord.self, from: data)+ } catch {+ throw HelperError.invalidOwnershipRecord(+ "解码失败: detail=\(error.localizedDescription)"+ )+ }+ guard record.schema == 1 else {+ let details = LogFields.joined(+ "actual=\(record.schema)",+ "expected=1"+ )+ throw HelperError.invalidOwnershipRecord(+ "版本错误: \(details)"+ )+ }+ return record+ }++ private func fileTypeName(_ mode: mode_t) -> String {+ let type = mode & S_IFMT+ if type == S_IFREG {+ return "file"+ }+ if type == S_IFDIR {+ return "directory"+ }+ if type == S_IFLNK {+ return "symlink"+ }+ return String(format: "0x%X", Int32(type))+ }++ private func permissionString(_ mode: mode_t) -> String {+ String(format: "%04o", Int32(mode & 0o7777))+ }+}diff --git a/CodexBarHelper/Pmset.swift b/CodexBarHelper/Pmset.swiftnew file mode 100644index 0000000..a8cc9c5--- /dev/null+++ b/CodexBarHelper/Pmset.swift@@ -0,0 +1,131 @@+import Foundation+import IOKit.pwr_mgt+import Synchronization++struct PmsetResult {+ let exitCode: Int32+ let output: String+}++// MARK: - pmset 调用++enum PmsetRunner {+ static func setSleepDisabled(_ disabled: Bool) -> PmsetResult {+ run(arguments: ["-a", "disablesleep", disabled ? "1" : "0"])+ }++ static func currentSleepDisabled() -> (result: PmsetResult, value: Bool?) {+ let result = run(arguments: ["-g"])+ return (result, parseSleepDisabled(from: result.output))+ }++ /// 所有调用均由 helper 状态队列串行执行, 未退出的旧写入不能与新操作重叠+ private static let unfinished = Mutex<Process?>(nil)++ private static func run(arguments: [String]) -> PmsetResult {+ unfinished.withLock { process in+ guard process?.isRunning != true else {+ return PmsetResult(exitCode: -1, output: "previous pmset process has not exited")+ }+ let result = BoundedProcess.run(executable: URL(fileURLWithPath: "/usr/bin/pmset"), arguments: arguments)+ process = result.runningProcess+ return PmsetResult(exitCode: result.exitCode, output: result.timedOut ? "pmset timed out: " + result.output : result.output)+ }+ }++ private static func parseSleepDisabled(from output: String) -> Bool? {+ for line in output.split(whereSeparator: \.isNewline) {+ let fields = line.split(whereSeparator: \.isWhitespace)+ guard fields.count >= 2, fields[0] == "SleepDisabled" else {+ continue+ }+ switch fields[1] {+ case "0":+ return false+ case "1":+ return true+ default:+ return nil+ }+ }+ // pmset 只在 disablesleep=1 时输出 SleepDisabled, 字段缺失表示默认值 0+ return false+ }+}++enum AutoResetWakeScheduler {+ static let owner = CodexBarHelperIPC.machServiceName + ".auto-reset"++ static func replaceSchedule(with date: Date?) -> IOReturn {+ let cancelResult = cancelOwnedEvents()+ guard cancelResult == kIOReturnSuccess else {+ return cancelResult+ }++ guard let date else {+ return kIOReturnSuccess+ }+ let scheduleResult = IOPMSchedulePowerEvent(+ date as CFDate,+ owner as CFString,+ kIOPMAutoWake as CFString+ )+ guard scheduleResult == kIOReturnSuccess else {+ return scheduleResult+ }++ let events = ownedEvents()+ guard events.count == 1,+ let scheduledDate = events[0][kIOPMPowerEventTimeKey] as? Date,+ abs(scheduledDate.timeIntervalSince(date)) <= verificationTolerance else {+ return kIOReturnError+ }+ return kIOReturnSuccess+ }++ static var ownedEventCount: Int {+ ownedEvents().count+ }++ private static func cancelOwnedEvents() -> IOReturn {+ var firstFailure: IOReturn?+ for event in ownedEvents() {+ guard let eventDate = event[kIOPMPowerEventTimeKey] as? Date else {+ firstFailure = firstFailure ?? kIOReturnBadArgument+ continue+ }++ let result = IOPMCancelScheduledPowerEvent(+ eventDate as CFDate,+ owner as CFString,+ kIOPMAutoWake as CFString+ )+ if result != kIOReturnSuccess,+ result != kIOReturnNotFound {+ firstFailure = firstFailure ?? result+ }+ }++ guard ownedEvents().isEmpty else {+ return firstFailure ?? kIOReturnError+ }+ return kIOReturnSuccess+ }++ private static func ownedEvents() -> [NSDictionary] {+ guard let events = IOPMCopyScheduledPowerEvents()?.takeRetainedValue() else {+ return []+ }++ return (events as NSArray).compactMap { value in+ guard let event = value as? NSDictionary,+ event[kIOPMPowerEventAppNameKey] as? String == owner,+ event[kIOPMPowerEventTypeKey] as? String == kIOPMAutoWake else {+ return nil+ }+ return event+ }+ }++ private static let verificationTolerance: TimeInterval = 1+}diff --git a/CodexBarHelper/main.swift b/CodexBarHelper/main.swiftindex b6db361..6bbba80 100644--- a/CodexBarHelper/main.swift+++ b/CodexBarHelper/main.swift@@ -1,1439 +1,5 @@-import Darwinimport Foundation-import IOKit-import IOKit.pwr_mgt-import os-import Security-private let helperLog = Logger(- subsystem: CodexBarHelperIPC.machServiceName,- category: "helper"-)--private enum LogFields {- static func joined(_ fields: String...) -> String {- fields.joined(separator: "; ")- }-}--private enum CodexBarHelperStorage {- static let ownershipURL: URL = {- guard let applicationSupportURL = FileManager.default.urls(- for: .applicationSupportDirectory,- in: .localDomainMask- ).first else {- helperLog.error("Helper 启动失败: reason=applicationSupportMissing")- exit(EXIT_FAILURE)- }- return applicationSupportURL- .appending(path: "CodexBar", directoryHint: .isDirectory)- .appending(path: "helper-state.json")- }()-}--private struct PmsetResult {- let exitCode: Int32- let output: String-}--private struct SleepOperationResult {- let exitCode: Int32- let source: CodexBarSleepPreventionSource- let sleepDisabled: Bool-}--private struct ClientLease {- var generation: UInt64- var isRequesting: Bool- var connectionIdentifier: UUID?-}--private enum SleepOwnership: String, Codable {- case idle- case owned- case restoring-- var needsRestore: Bool {- self != .idle- }-- var sharedState: CodexBarSleepOwnershipState {- switch self {- case .idle:- .idle- case .owned:- .owned- case .restoring:- .restoring- }- }-}--private struct SleepOwnershipRecord: Codable {- let schema: Int- let state: SleepOwnership- let transaction: UUID- let identifier: String?- let updated: Date-}--private enum OwnershipRecordState {- case absent- case present(SleepOwnershipRecord)- case unreadable(Error)-}--private enum SleepRestoreTrigger: String {- case appRequest- case connectionWatchdog- case helperStartup- case ownershipCheck- case helperTermination-}--private enum WakeScheduleCleanupTrigger: String {- case appRequest- case connectionClosed- case helperStartup- case ownershipCheck- case helperTermination-}--// MARK: - pmset 调用--private enum PmsetRunner {- static func setSleepDisabled(_ disabled: Bool) -> PmsetResult {- run(arguments: ["-a", "disablesleep", disabled ? "1" : "0"])- }-- static func currentSleepDisabled() -> (result: PmsetResult, value: Bool?) {- let result = run(arguments: ["-g"])- return (result, parseSleepDisabled(from: result.output))- }-- private static func run(arguments: [String]) -> PmsetResult {- let process = Process()- process.executableURL = URL(fileURLWithPath: "/usr/bin/pmset")- process.arguments = arguments-- let pipe = Pipe()- process.standardOutput = pipe- process.standardError = pipe-- do {- try process.run()- } catch {- return PmsetResult(exitCode: -1, output: error.localizedDescription)- }-- let data = pipe.fileHandleForReading.readDataToEndOfFile()- process.waitUntilExit()- return PmsetResult(- exitCode: process.terminationStatus,- output: String(data: data, encoding: .utf8) ?? ""- )- }-- private static func parseSleepDisabled(from output: String) -> Bool? {- for line in output.split(whereSeparator: \.isNewline) {- let fields = line.split(whereSeparator: \.isWhitespace)- guard fields.count >= 2, fields[0] == "SleepDisabled" else {- continue- }- switch fields[1] {- case "0":- return false- case "1":- return true- default:- return nil- }- }- // pmset 只在 disablesleep=1 时输出 SleepDisabled, 字段缺失表示默认值 0- return false- }-}--private enum AutoResetWakeScheduler {- static let owner = CodexBarHelperIPC.machServiceName + ".auto-reset"-- static func replaceSchedule(with date: Date?) -> IOReturn {- let cancelResult = cancelOwnedEvents()- guard cancelResult == kIOReturnSuccess else {- return cancelResult- }-- guard let date else {- return kIOReturnSuccess- }- let scheduleResult = IOPMSchedulePowerEvent(- date as CFDate,- owner as CFString,- kIOPMAutoWake as CFString- )- guard scheduleResult == kIOReturnSuccess else {- return scheduleResult- }-- let events = ownedEvents()- guard events.count == 1,- let scheduledDate = events[0][kIOPMPowerEventTimeKey] as? Date,- abs(scheduledDate.timeIntervalSince(date)) <= verificationTolerance else {- return kIOReturnError- }- return kIOReturnSuccess- }-- static var ownedEventCount: Int {- ownedEvents().count- }-- private static func cancelOwnedEvents() -> IOReturn {- var firstFailure: IOReturn?- for event in ownedEvents() {- guard let eventDate = event[kIOPMPowerEventTimeKey] as? Date else {- firstFailure = firstFailure ?? kIOReturnBadArgument- continue- }-- let result = IOPMCancelScheduledPowerEvent(- eventDate as CFDate,- owner as CFString,- kIOPMAutoWake as CFString- )- if result != kIOReturnSuccess,- result != kIOReturnNotFound {- firstFailure = firstFailure ?? result- }- }-- guard ownedEvents().isEmpty else {- return firstFailure ?? kIOReturnError- }- return kIOReturnSuccess- }-- private static func ownedEvents() -> [NSDictionary] {- guard let events = IOPMCopyScheduledPowerEvents()?.takeRetainedValue() else {- return []- }-- return (events as NSArray).compactMap { value in- guard let event = value as? NSDictionary,- event[kIOPMPowerEventAppNameKey] as? String == owner,- event[kIOPMPowerEventTypeKey] as? String == kIOPMAutoWake else {- return nil- }- return event- }- }-- private static let verificationTolerance: TimeInterval = 1-}--private final class CodexBarHelperConnectionSession: NSObject, CodexBarHelperProtocol,- @unchecked Sendable {- let identifier = UUID()- private weak var runtime: CodexBarHelperRuntime?-- init(runtime: CodexBarHelperRuntime) {- self.runtime = runtime- }-- func setSleepPreventionRequested(- _ requested: Bool,- clientSessionID: String,- generation: UInt64,- reply: @escaping @Sendable (Int32, Int, Bool) -> Void- ) {- guard let runtime else {- reply(-1, CodexBarSleepPreventionSource.none.rawValue, false)- return- }- runtime.setSleepPreventionRequested(- requested,- clientSessionID: clientSessionID,- generation: generation,- for: identifier,- reply: reply- )- }-- func getSleepPreventionStatus(- reply: @escaping @Sendable (Int32, Int, Int, Bool) -> Void- ) {- guard let runtime else {- reply(-1, CodexBarSleepOwnershipState.idle.rawValue, 0, false)- return- }- runtime.getSleepPreventionStatus(- for: identifier,- reply: reply- )- }-- func resetSleepAfterUpdate(- _ updateIdentifier: String,- reply: @escaping @Sendable (Int32) -> Void- ) {- guard let runtime else {- reply(-1)- return- }- runtime.resetSleepAfterUpdate(- updateIdentifier,- for: identifier,- reply: reply- )- }-- func setAutoResetWakeSchedule(- _ unixTimestamp: TimeInterval,- reply: @escaping @Sendable (Int32) -> Void- ) {- guard let runtime else {- reply(-1)- return- }- runtime.setAutoResetWakeSchedule(- unixTimestamp,- for: identifier,- reply: reply- )- }-}--private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unchecked Sendable {- private struct Watchdog {- let token: UUID- let workItem: DispatchWorkItem- }-- private let queue = DispatchQueue(label: CodexBarHelperIPC.machServiceName + ".state")- private let ownershipURL = CodexBarHelperStorage.ownershipURL- private var ownership = SleepOwnership.idle- private var transactionID = UUID()- private var lastCompletedUpdateIdentifier: String?- private var connections = Set<UUID>()- private var clients = [UUID: ClientLease]()- private var watchdogs = [UUID: Watchdog]()- private var lastKnownSleepDisabled: Bool?- private var ownershipTimer: DispatchSourceTimer?- private var scheduledOwnershipCheckInterval: TimeInterval?- private var autoResetWakeConnectionIdentifier: UUID?- private var isAutoResetWakeCleanupPending = false- private var signalSources = [DispatchSourceSignal]()- private var listener: NSXPCListener?-- func run() {- guard geteuid() == 0 else {- helperLog.error("Helper 启动失败: reason=notRoot")- exit(EXIT_FAILURE)- }-- do {- try ensureOwnershipDirectory()- } catch {- let directoryPath = ownershipURL.deletingLastPathComponent().path- let details = LogFields.joined(- "reason=ownershipDirectory",- "path=\(directoryPath)",- "detail=\(error.localizedDescription)"- )- helperLog.error("Helper 启动失败: \(details, privacy: .public)")- exit(EXIT_FAILURE)- }-- recoverOwnershipAtStartup()- recoverAutoResetWakeScheduleAtStartup()- installOwnershipTimer()- installSignalHandlers()-- let clientCodeSigningRequirement: String- do {- clientCodeSigningRequirement = try Self.makeClientCodeSigningRequirement()- } catch {- let details = LogFields.joined(- "reason=listener",- "detail=\(error.localizedDescription)"- )- helperLog.error("Helper 启动失败: \(details, privacy: .public)")- exit(EXIT_FAILURE)- }-- let listener = NSXPCListener(machServiceName: CodexBarHelperIPC.machServiceName)- listener.setConnectionCodeSigningRequirement(clientCodeSigningRequirement)- listener.delegate = self- listener.resume()- self.listener = listener- }-- // MARK: - XPC 接口-- fileprivate func setSleepPreventionRequested(- _ requested: Bool,- clientSessionID: String,- generation: UInt64,- for identifier: UUID,- reply: @escaping @Sendable (Int32, Int, Bool) -> Void- ) {- queue.async { [self] in- guard connections.contains(identifier),- let clientIdentifier = UUID(uuidString: clientSessionID) else {- reply(-1, CodexBarSleepPreventionSource.none.rawValue, false)- return- }-- if let currentLease = clients[clientIdentifier] {- guard generation >= currentLease.generation else {- let result = currentOperationResult()- reply(result.exitCode, result.source.rawValue, result.sleepDisabled)- return- }- guard generation != currentLease.generation- || requested == currentLease.isRequesting else {- reply(-1, currentSource().rawValue, lastKnownSleepDisabled ?? false)- return- }- }-- cancelWatchdog(for: clientIdentifier)- let source = currentSource()- clients[clientIdentifier] = ClientLease(- generation: generation,- isRequesting: requested,- connectionIdentifier: identifier- )-- let result: SleepOperationResult- if requested {- let isNewRequest = source == .none- result = reconcileRequestedSleep(logsExternalState: isNewRequest)- } else {- result = reconcileReleasedSleep(source: source, trigger: .appRequest)- }- scheduleOwnershipTimerIfNeeded()- reply(result.exitCode, result.source.rawValue, result.sleepDisabled)- }- }-- fileprivate func getSleepPreventionStatus(- for identifier: UUID,- reply: @escaping @Sendable (Int32, Int, Int, Bool) -> Void- ) {- queue.async { [self] in- guard connections.contains(identifier),- let lastKnownSleepDisabled else {- reply(-1, ownership.sharedState.rawValue, activeClientCount, false)- return- }- reply(- 0,- ownership.sharedState.rawValue,- activeClientCount,- lastKnownSleepDisabled- )- }- }-- fileprivate func resetSleepAfterUpdate(- _ updateIdentifier: String,- for identifier: UUID,- reply: @escaping @Sendable (Int32) -> Void- ) {- queue.async { [self] in- guard connections.contains(identifier),- Self.isValidUpdateIdentifier(updateIdentifier) else {- reply(-1)- return- }- guard lastCompletedUpdateIdentifier != updateIdentifier else {- reply(0)- return- }-- let result = setAndVerifySleepDisabled(false)- guard result.exitCode == 0 else {- reply(result.exitCode)- return- }-- let previousUpdateIdentifier = lastCompletedUpdateIdentifier- lastCompletedUpdateIdentifier = updateIdentifier- do {- try persistOwnership(.idle)- } catch {- lastCompletedUpdateIdentifier = previousUpdateIdentifier- logOwnershipWriteFailure(error)- reply(-1)- return- }-- helperLog.notice("Helper 更新后睡眠状态已重置")- reply(0)- }- }-- fileprivate func setAutoResetWakeSchedule(- _ unixTimestamp: TimeInterval,- for identifier: UUID,- reply: @escaping @Sendable (Int32) -> Void- ) {- queue.async { [self] in- guard connections.contains(identifier),- unixTimestamp.isFinite,- unixTimestamp >= 0 else {- reply(kIOReturnBadArgument)- return- }-- let date: Date?- if unixTimestamp == 0 {- date = nil- } else {- let requestedDate = Date(timeIntervalSince1970: unixTimestamp)- guard requestedDate > Date() else {- reply(kIOReturnBadArgument)- return- }- date = requestedDate- }-- if date == nil {- autoResetWakeConnectionIdentifier = nil- } else {- autoResetWakeConnectionIdentifier = identifier- }-- let result: IOReturn = if date == nil {- cancelAutoResetWakeSchedule(trigger: .appRequest)- } else {- AutoResetWakeScheduler.replaceSchedule(with: date)- }- guard result == kIOReturnSuccess else {- if date != nil {- scheduleOwnershipTimerIfNeeded()- }- let details = LogFields.joined(- "action=\(date == nil ? "cancel" : "schedule")",- "code=\(result)"- )- helperLog.error("自动重置唤醒计划更新失败: \(details, privacy: .public)")- reply(result)- return- }-- if date != nil {- isAutoResetWakeCleanupPending = false- scheduleOwnershipTimerIfNeeded()- }- if let date {- let epoch = Int(date.timeIntervalSince1970)- helperLog.notice("自动重置唤醒计划已设置: epoch=\(epoch)")- }- reply(kIOReturnSuccess)- }- }-- func listener(- _: NSXPCListener,- shouldAcceptNewConnection newConnection: NSXPCConnection- ) -> Bool {- let session = CodexBarHelperConnectionSession(runtime: self)- let identifier = session.identifier- newConnection.exportedInterface = NSXPCInterface(- with: CodexBarHelperProtocol.self- )- newConnection.exportedObject = session-- let connectionDropped: () -> Void = { [weak self] in- self?.connectionDropped(identifier)- }- newConnection.invalidationHandler = connectionDropped- newConnection.interruptionHandler = connectionDropped-- queue.sync {- _ = connections.insert(identifier)- }- newConnection.resume()- return true- }-- private func connectionDropped(_ identifier: UUID) {- queue.async { [self] in- guard connections.remove(identifier) != nil else {- return- }-- cancelAutoResetWakeSchedule(ifOwnedBy: identifier)- let droppedClients = clients.compactMap { clientIdentifier, lease in- lease.connectionIdentifier == identifier ? clientIdentifier : nil- }- for clientIdentifier in droppedClients {- guard var lease = clients[clientIdentifier] else {- continue- }- guard lease.isRequesting else {- clients[clientIdentifier] = nil- continue- }-- lease.connectionIdentifier = nil- clients[clientIdentifier] = lease- scheduleWatchdog(for: clientIdentifier, generation: lease.generation)- }- scheduleOwnershipTimerIfNeeded()- }- }-- private func cancelAutoResetWakeSchedule(ifOwnedBy identifier: UUID) {- guard autoResetWakeConnectionIdentifier == identifier else {- return- }-- autoResetWakeConnectionIdentifier = nil- _ = cancelAutoResetWakeSchedule(trigger: .connectionClosed)- }-- @discardableResult- private func cancelAutoResetWakeSchedule(- trigger: WakeScheduleCleanupTrigger- ) -> IOReturn {- defer { scheduleOwnershipTimerIfNeeded() }- let result = AutoResetWakeScheduler.replaceSchedule(with: nil)- guard result == kIOReturnSuccess else {- isAutoResetWakeCleanupPending = true- let details = LogFields.joined(- "reason=\(trigger.rawValue)",- "code=\(result)",- "remaining=\(AutoResetWakeScheduler.ownedEventCount)"- )- helperLog.error("自动重置唤醒计划取消失败: \(details, privacy: .public)")- return result- }-- isAutoResetWakeCleanupPending = false- helperLog.notice(- "自动重置唤醒计划已取消: reason=\(trigger.rawValue, privacy: .public)"- )- return kIOReturnSuccess- }-- private func scheduleWatchdog(for clientIdentifier: UUID, generation: UInt64) {- guard watchdogs[clientIdentifier] == nil else {- return- }-- let token = UUID()- let workItem = DispatchWorkItem { [weak self] in- guard let self, watchdogs[clientIdentifier]?.token == token else {- return- }- watchdogs[clientIdentifier] = nil- guard let lease = clients[clientIdentifier],- lease.generation == generation,- lease.isRequesting,- lease.connectionIdentifier == nil else {- return- }-- let source = currentSource()- clients[clientIdentifier] = nil- _ = reconcileReleasedSleep(source: source, trigger: .connectionWatchdog)- scheduleOwnershipTimerIfNeeded()- }- watchdogs[clientIdentifier] = Watchdog(token: token, workItem: workItem)- queue.asyncAfter(- deadline: .now() + CodexBarHelperIPC.watchdogGraceSeconds,- execute: workItem- )- }-- private func cancelWatchdog(for clientIdentifier: UUID) {- watchdogs.removeValue(forKey: clientIdentifier)?.workItem.cancel()- }-- // MARK: - 所有权与睡眠切换-- private func reconcileRequestedSleep(logsExternalState: Bool) -> SleepOperationResult {- if ownership == .restoring {- let recovery = restoreOwnedSleep(trigger: .appRequest)- guard recovery.exitCode == 0 else {- return recovery- }- }-- if ownership == .owned {- guard validateOrRepairOwnedRecord() else {- return recoverFromOwnedRecordFailure()- }-- let current = readCurrentSleepDisabled()- guard current.result.exitCode == 0, let sleepDisabled = current.value else {- logPmsetReadFailure(current.result)- return SleepOperationResult(- exitCode: normalizedFailureCode(current.result.exitCode),- source: .codexBar,- sleepDisabled: false- )- }-- if !sleepDisabled {- let result = setAndVerifySleepDisabled(true)- guard result.exitCode == 0 else {- return SleepOperationResult(- exitCode: result.exitCode,- source: .codexBar,- sleepDisabled: result.value ?? false- )- }- guard validateOrRepairOwnedRecord() else {- return recoverFromOwnedRecordFailure()- }- }- return SleepOperationResult(exitCode: 0, source: .codexBar, sleepDisabled: true)- }-- let current = readCurrentSleepDisabled()- guard current.result.exitCode == 0, let sleepDisabled = current.value else {- logPmsetReadFailure(current.result)- return SleepOperationResult(- exitCode: normalizedFailureCode(current.result.exitCode),- source: .none,- sleepDisabled: false- )- }-- guard !sleepDisabled else {- if logsExternalState {- helperLog.notice("系统睡眠已由其他来源关闭")- }- return SleepOperationResult(exitCode: 0, source: .external, sleepDisabled: true)- }-- do {- try persistOwnership(.owned)- } catch {- logOwnershipWriteFailure(error)- return SleepOperationResult(exitCode: -1, source: .none, sleepDisabled: false)- }-- let result = setAndVerifySleepDisabled(true)- guard result.exitCode == 0 else {- return SleepOperationResult(- exitCode: result.exitCode,- source: .codexBar,- sleepDisabled: result.value ?? false- )- }- guard validateOrRepairOwnedRecord() else {- return recoverFromOwnedRecordFailure()- }-- helperLog.notice("系统睡眠已由 CodexBar 关闭")- return SleepOperationResult(exitCode: 0, source: .codexBar, sleepDisabled: true)- }-- private func reconcileReleasedSleep(- source: CodexBarSleepPreventionSource,- trigger: SleepRestoreTrigger- ) -> SleepOperationResult {- guard activeClientCount == 0 else {- return reconcileRequestedSleep(logsExternalState: false)- }-- guard ownership.needsRestore else {- // 未取得所有权时不写 pmset, 返回最近一次实测值- return SleepOperationResult(- exitCode: 0,- source: source,- sleepDisabled: lastKnownSleepDisabled ?? (source == .external)- )- }- return restoreOwnedSleep(trigger: trigger)- }-- @discardableResult- private func restoreOwnedSleep(trigger: SleepRestoreTrigger) -> SleepOperationResult {- do {- try persistOwnership(.restoring)- } catch {- // 写恢复中标记失败也必须继续尝试写回 0, 否则记录故障本身会把机器永久卡在 1- logOwnershipWriteFailure(error)- }-- let result = setAndVerifySleepDisabled(false)- guard result.exitCode == 0 else {- let details = LogFields.joined(- "trigger=\(trigger.rawValue)",- "exit=\(result.exitCode)"- )- helperLog.error("系统睡眠恢复失败: \(details, privacy: .public)")- return SleepOperationResult(- exitCode: result.exitCode,- source: .codexBar,- sleepDisabled: result.value ?? true- )- }-- do {- try persistOwnership(.idle)- } catch {- logOwnershipWriteFailure(error)- return SleepOperationResult(exitCode: -1, source: .codexBar, sleepDisabled: false)- }-- let details = LogFields.joined(- "trigger=\(trigger.rawValue)",- "sleepDisabled=0"- )- helperLog.notice("系统睡眠已恢复: \(details, privacy: .public)")- return SleepOperationResult(exitCode: 0, source: .codexBar, sleepDisabled: false)- }-- private func setAndVerifySleepDisabled(- _ disabled: Bool- ) -> (exitCode: Int32, value: Bool?) {- let writeResult = PmsetRunner.setSleepDisabled(disabled)- guard writeResult.exitCode == 0 else {- let details = LogFields.joined(- "target=\(disabled ? 1 : 0)",- "exit=\(writeResult.exitCode)",- "detail=\(writeResult.output)"- )- helperLog.error("pmset 写入失败: \(details, privacy: .public)")- return (writeResult.exitCode, nil)- }-- let readResult = readCurrentSleepDisabled()- guard readResult.result.exitCode == 0, let value = readResult.value else {- logPmsetReadFailure(readResult.result)- return (normalizedFailureCode(readResult.result.exitCode), nil)- }- guard value == disabled else {- let details = LogFields.joined(- "target=\(disabled ? 1 : 0)",- "actual=\(value ? 1 : 0)"- )- helperLog.error("pmset 写入校验失败: \(details, privacy: .public)")- return (-1, value)- }- return (0, value)- }-- private func readCurrentSleepDisabled() -> (result: PmsetResult, value: Bool?) {- let current = PmsetRunner.currentSleepDisabled()- if current.result.exitCode == 0, let value = current.value {- lastKnownSleepDisabled = value- }- return current- }-- private func validateOrRepairOwnedRecord() -> Bool {- guard ownership == .owned else {- return false- }-- if case let .present(record) = ownershipRecordState(),- record.state == .owned,- record.transaction == transactionID {- return true- }-- helperLog.error("睡眠所有权记录与运行状态不一致: action=repair")- do {- try persistOwnership(.owned)- helperLog.notice("睡眠所有权记录已修复")- return true- } catch {- logOwnershipWriteFailure(error)- return false- }- }-- private func recoverFromOwnedRecordFailure() -> SleepOperationResult {- let recovery = restoreOwnedSleep(trigger: .ownershipCheck)- return SleepOperationResult(- exitCode: recovery.exitCode == 0 ? -1 : recovery.exitCode,- source: .codexBar,- sleepDisabled: recovery.sleepDisabled- )- }-- private func currentSource() -> CodexBarSleepPreventionSource {- if ownership.needsRestore {- return .codexBar- }- return activeClientCount == 0 ? .none : .external- }-- private func currentOperationResult() -> SleepOperationResult {- guard let lastKnownSleepDisabled else {- return SleepOperationResult(exitCode: -1, source: currentSource(), sleepDisabled: false)- }- return SleepOperationResult(- exitCode: 0,- source: currentSource(),- sleepDisabled: lastKnownSleepDisabled- )- }-- private var activeClientCount: Int {- clients.values.lazy.filter(\.isRequesting).count- }-- private func normalizedFailureCode(_ exitCode: Int32) -> Int32 {- exitCode == 0 ? -1 : exitCode- }-- private func logPmsetReadFailure(_ result: PmsetResult) {- let details = LogFields.joined(- "exit=\(result.exitCode)",- "detail=\(result.output)"- )- helperLog.error("pmset 读取失败: \(details, privacy: .public)")- }-- // MARK: - 异常恢复-- private func recoverOwnershipAtStartup() {- let state = ownershipRecordState()- switch state {- case .absent:- do {- try persistOwnership(.idle)- helperLog.notice("Helper 已启动: ownership=idle")- } catch {- logOwnershipWriteFailure(error)- exit(EXIT_FAILURE)- }- case let .present(record):- ownership = record.state- transactionID = record.transaction- lastCompletedUpdateIdentifier = record.identifier- helperLog.notice(- "Helper 已启动: ownership=\(record.state.rawValue, privacy: .public)"- )- if record.state.needsRestore {- _ = restoreOwnedSleep(trigger: .helperStartup)- }- case let .unreadable(error):- // 损坏记录无法证明所有权, 启动时按最安全的默认值 0 收敛- let details = LogFields.joined(- "detail=\(error.localizedDescription)",- "action=forceRestore"- )- helperLog.error("睡眠所有权记录无效: \(details, privacy: .public)")- ownership = .restoring- _ = restoreOwnedSleep(trigger: .helperStartup)- }-- if lastKnownSleepDisabled == nil {- let current = readCurrentSleepDisabled()- if current.result.exitCode != 0 || current.value == nil {- logPmsetReadFailure(current.result)- }- }- }-- private func recoverAutoResetWakeScheduleAtStartup() {- let initialEventCount = AutoResetWakeScheduler.ownedEventCount- guard initialEventCount > 0 else {- return- }-- var lastResult = IOReturn(kIOReturnError)- for delay in Self.wakeCleanupStartupRetryDelays {- if delay > 0 {- Thread.sleep(forTimeInterval: delay)- }- lastResult = AutoResetWakeScheduler.replaceSchedule(with: nil)- if lastResult == kIOReturnSuccess {- helperLog.notice(- "自动重置遗留唤醒计划已清理: reason=helperStartup count=\(initialEventCount)"- )- return- }- }-- isAutoResetWakeCleanupPending = true- let details = LogFields.joined(- "reason=\(WakeScheduleCleanupTrigger.helperStartup.rawValue)",- "code=\(lastResult)",- "remaining=\(AutoResetWakeScheduler.ownedEventCount)"- )- helperLog.error("自动重置遗留唤醒计划清理失败: \(details, privacy: .public)")- }-- private func installOwnershipTimer() {- let timer = DispatchSource.makeTimerSource(queue: queue)- timer.setEventHandler { [weak self] in- guard let self else {- return- }- if activeClientCount > 0 {- _ = reconcileRequestedSleep(logsExternalState: false)- } else if ownership.needsRestore, watchdogs.isEmpty {- _ = restoreOwnedSleep(trigger: .ownershipCheck)- }- if isAutoResetWakeCleanupPending,- autoResetWakeConnectionIdentifier == nil {- _ = cancelAutoResetWakeSchedule(trigger: .ownershipCheck)- }- scheduleOwnershipTimerIfNeeded()- }- ownershipTimer = timer- scheduleOwnershipTimerIfNeeded(force: true)- timer.resume()- }-- private func scheduleOwnershipTimerIfNeeded(force: Bool = false) {- guard let ownershipTimer else {- return- }-- let interval: TimeInterval = if isAutoResetWakeCleanupPending {- CodexBarHelperIPC.ownedCheckIntervalSeconds- } else if activeClientCount == 0 {- CodexBarHelperIPC.recoveryCheckIntervalSeconds- } else if ownership.needsRestore {- CodexBarHelperIPC.ownedCheckIntervalSeconds- } else {- CodexBarHelperIPC.externalCheckIntervalSeconds- }- guard force || interval != scheduledOwnershipCheckInterval else {- return- }-- scheduledOwnershipCheckInterval = interval- ownershipTimer.schedule(- deadline: .now() + interval,- repeating: interval,- leeway: .seconds(Int(CodexBarHelperIPC.checkLeewaySeconds))- )- }-- private func installSignalHandlers() {- for signalNumber in [SIGTERM, SIGINT] {- signal(signalNumber, SIG_IGN)- let source = DispatchSource.makeSignalSource(signal: signalNumber, queue: queue)- source.setEventHandler { [weak self] in- guard let self else {- exit(EXIT_SUCCESS)- }- if ownership.needsRestore {- _ = restoreOwnedSleep(trigger: .helperTermination)- }- autoResetWakeConnectionIdentifier = nil- _ = cancelAutoResetWakeSchedule(trigger: .helperTermination)- exit(EXIT_SUCCESS)- }- source.resume()- signalSources.append(source)- }- }-- private static let wakeCleanupStartupRetryDelays: [TimeInterval] = [0, 0.25, 1]-- // MARK: - 所有权记录-- private func ensureOwnershipDirectory() throws {- let directoryURL = ownershipURL.deletingLastPathComponent()- var info = stat()- if lstat(directoryURL.path, &info) == 0 {- try validateOwnershipDirectory(info)- return- }-- guard errno == ENOENT else {- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)- }- try FileManager.default.createDirectory(- at: directoryURL,- withIntermediateDirectories: false- )- try FileManager.default.setAttributes(- [.ownerAccountID: 0, .groupOwnerAccountID: 0, .posixPermissions: 0o755],- ofItemAtPath: directoryURL.path- )- }-- private func validateOwnershipDirectory(_ info: stat) throws {- guard info.st_mode & S_IFMT == S_IFDIR else {- let details = LogFields.joined(- "actual=\(fileTypeName(info.st_mode))",- "expected=directory"- )- throw CodexBarHelperError.insecureOwnershipDirectory(- "目录类型错误: \(details)"- )- }- guard info.st_uid == 0 else {- let details = LogFields.joined(- "actual=\(info.st_uid)",- "expected=0"- )- throw CodexBarHelperError.insecureOwnershipDirectory(- "所有者错误: \(details)"- )- }- guard info.st_mode & 0o022 == 0 else {- let details = LogFields.joined(- "actual=\(permissionString(info.st_mode))",- "forbidden=0022"- )- throw CodexBarHelperError.insecureOwnershipDirectory(- "目录权限错误: \(details)"- )- }- }-- private func persistOwnership(_ state: SleepOwnership) throws {- try ensureOwnershipDirectory()- if state == .owned, ownership == .idle {- transactionID = UUID()- }- let record = SleepOwnershipRecord(- schema: 1,- state: state,- transaction: transactionID,- identifier: lastCompletedUpdateIdentifier,- updated: Date()- )- let encoder = JSONEncoder()- encoder.dateEncodingStrategy = .iso8601- let data = try encoder.encode(record)- try writeOwnershipDataDurably(data)- guard case let .present(savedRecord) = ownershipRecordState(),- savedRecord.state == state,- savedRecord.transaction == transactionID,- savedRecord.identifier == lastCompletedUpdateIdentifier else {- throw CodexBarHelperError.invalidOwnershipRecord("写入后校验失败")- }- ownership = state- }-- private func writeOwnershipDataDurably(_ data: Data) throws {- let directoryURL = ownershipURL.deletingLastPathComponent()- let temporaryURL = directoryURL.appending(- path: ".helper-state.\(UUID().uuidString).tmp"- )- var descriptor = open(- temporaryURL.path,- O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC,- mode_t(0o600)- )- guard descriptor >= 0 else {- throw ownershipWriteError(operation: "open")- }-- var shouldRemoveTemporaryFile = true- defer {- if descriptor >= 0 {- _ = Darwin.close(descriptor)- }- if shouldRemoveTemporaryFile {- _ = unlink(temporaryURL.path)- }- }-- try data.withUnsafeBytes { bytes in- guard let baseAddress = bytes.baseAddress else {- return- }-- var offset = 0- while offset < bytes.count {- let written = Darwin.write(- descriptor,- baseAddress.advanced(by: offset),- bytes.count - offset- )- if written < 0, errno == EINTR {- continue- }- guard written > 0 else {- throw ownershipWriteError(operation: "write")- }- offset += written- }- }-- guard fchown(descriptor, 0, 0) == 0 else {- throw ownershipWriteError(operation: "fchown")- }- guard fchmod(descriptor, mode_t(0o600)) == 0 else {- throw ownershipWriteError(operation: "fchmod")- }- try synchronizeOwnershipFile(descriptor)-- let closeResult = Darwin.close(descriptor)- descriptor = -1- guard closeResult == 0 else {- throw ownershipWriteError(operation: "close")- }- guard rename(temporaryURL.path, ownershipURL.path) == 0 else {- throw ownershipWriteError(operation: "rename")- }- shouldRemoveTemporaryFile = false- try synchronizeOwnershipDirectory(directoryURL)- }-- private func synchronizeOwnershipFile(_ descriptor: Int32) throws {- if fcntl(descriptor, F_FULLFSYNC) == 0 {- return- }- guard fsync(descriptor) == 0 else {- throw ownershipWriteError(operation: "fsync")- }- }-- private func synchronizeOwnershipDirectory(_ directoryURL: URL) throws {- let descriptor = open(directoryURL.path, O_RDONLY | O_CLOEXEC)- guard descriptor >= 0 else {- throw ownershipWriteError(operation: "openDirectory")- }- defer {- _ = Darwin.close(descriptor)- }-- guard fsync(descriptor) == 0 else {- let errorCode = errno- // 部分文件系统不支持对目录执行 fsync, 文件本身已经完成 F_FULLFSYNC- if errorCode == EINVAL || errorCode == ENOTSUP {- return- }- throw ownershipWriteError(operation: "fsyncDirectory", code: errorCode)- }- }-- private func ownershipWriteError(- operation: String,- code: Int32 = errno- ) -> CodexBarHelperError {- .ownershipWriteFailed(operation: operation, code: code)- }-- private func ownershipRecordState() -> OwnershipRecordState {- do {- guard let record = try readOwnershipRecord() else {- return .absent- }- return .present(record)- } catch {- return .unreadable(error)- }- }-- private func readOwnershipRecord() throws -> SleepOwnershipRecord? {- var info = stat()- guard lstat(ownershipURL.path, &info) == 0 else {- if errno == ENOENT {- return nil- }- throw CodexBarHelperError.invalidOwnershipRecord(- "读取属性失败: errno=\(errno)"- )- }- guard info.st_mode & S_IFMT == S_IFREG else {- let details = LogFields.joined(- "actual=\(fileTypeName(info.st_mode))",- "expected=file"- )- throw CodexBarHelperError.invalidOwnershipRecord(- "文件类型错误: \(details)"- )- }- guard info.st_uid == 0 else {- let details = LogFields.joined(- "actual=\(info.st_uid)",- "expected=0"- )- throw CodexBarHelperError.invalidOwnershipRecord(- "所有者错误: \(details)"- )- }- guard info.st_mode & 0o022 == 0 else {- let details = LogFields.joined(- "actual=\(permissionString(info.st_mode))",- "forbidden=0022"- )- throw CodexBarHelperError.invalidOwnershipRecord(- "文件权限错误: \(details)"- )- }-- let data: Data- do {- data = try Data(contentsOf: ownershipURL)- } catch {- throw CodexBarHelperError.invalidOwnershipRecord(- "读取内容失败: detail=\(error.localizedDescription)"- )- }-- let decoder = JSONDecoder()- decoder.dateDecodingStrategy = .iso8601- let record: SleepOwnershipRecord- do {- record = try decoder.decode(SleepOwnershipRecord.self, from: data)- } catch {- throw CodexBarHelperError.invalidOwnershipRecord(- "解码失败: detail=\(error.localizedDescription)"- )- }- guard record.schema == 1 else {- let details = LogFields.joined(- "actual=\(record.schema)",- "expected=1"- )- throw CodexBarHelperError.invalidOwnershipRecord(- "版本错误: \(details)"- )- }- return record- }-- private func logOwnershipWriteFailure(_ error: Error) {- let path = ownershipURL.path- let details = LogFields.joined(- "path=\(path)",- "detail=\(error.localizedDescription)"- )- helperLog.error("睡眠所有权记录写入失败: \(details, privacy: .public)")- }-- private func fileTypeName(_ mode: mode_t) -> String {- let type = mode & S_IFMT- if type == S_IFREG {- return "file"- }- if type == S_IFDIR {- return "directory"- }- if type == S_IFLNK {- return "symlink"- }- return String(format: "0x%X", Int32(type))- }-- private func permissionString(_ mode: mode_t) -> String {- String(format: "%04o", Int32(mode & 0o7777))- }-- private static func isValidUpdateIdentifier(_ identifier: String) -> Bool {- let bytes = identifier.utf8- return bytes.count == 64 && bytes.allSatisfy { byte in- (48 ... 57).contains(byte) || (97 ... 102).contains(byte)- }- }-- private static func makeClientCodeSigningRequirement() throws -> String {- var runningCode: SecCode?- var status = SecCodeCopySelf(SecCSFlags(), &runningCode)- guard status == errSecSuccess, let runningCode else {- let details = LogFields.joined(- "Operation=SecCodeCopySelf",- "Status=\(status)"- )- throw CodexBarHelperError.codeSigningValidationFailed(- "读取运行签名失败: \(details)"- )- }-- var staticCode: SecStaticCode?- status = SecCodeCopyStaticCode(runningCode, SecCSFlags(), &staticCode)- guard status == errSecSuccess, let staticCode else {- let details = LogFields.joined(- "Operation=SecCodeCopyStaticCode",- "Status=\(status)"- )- throw CodexBarHelperError.codeSigningValidationFailed(- "读取静态签名失败: \(details)"- )- }-- var signingInformation: CFDictionary?- status = SecCodeCopySigningInformation(- staticCode,- SecCSFlags(rawValue: kSecCSSigningInformation),- &signingInformation- )- guard status == errSecSuccess, let signingInformation else {- let details = LogFields.joined(- "Operation=SecCodeCopySigningInformation",- "Status=\(status)"- )- throw CodexBarHelperError.codeSigningValidationFailed(- "读取签名信息失败: \(details)"- )- }-- let values = signingInformation as NSDictionary- guard let teamIdentifier = values[kSecCodeInfoTeamIdentifier] as? String else {- throw CodexBarHelperError.codeSigningValidationFailed("Team ID 缺失")- }- guard let helperIdentifier = values[kSecCodeInfoIdentifier] as? String else {- throw CodexBarHelperError.codeSigningValidationFailed("Helper 标识符缺失")- }-- guard helperIdentifier == CodexBarHelperIPC.machServiceName else {- let details = LogFields.joined(- "actual=\(helperIdentifier)",- "expected=\(CodexBarHelperIPC.machServiceName)"- )- throw CodexBarHelperError.codeSigningValidationFailed(- "Helper 标识符错误: \(details)"- )- }-- let clientIdentifier = CodexBarHelperIPC.appBundleIdentifier- let identifierCharacters = CharacterSet.alphanumerics.union(- CharacterSet(charactersIn: ".-")- )- guard !teamIdentifier.isEmpty else {- throw CodexBarHelperError.codeSigningValidationFailed("Team ID 为空")- }- guard teamIdentifier.unicodeScalars.allSatisfy(CharacterSet.alphanumerics.contains) else {- throw CodexBarHelperError.codeSigningValidationFailed(- "Team ID 格式错误: \(teamIdentifier)"- )- }- guard !clientIdentifier.isEmpty else {- throw CodexBarHelperError.codeSigningValidationFailed("客户端标识符为空")- }- guard clientIdentifier.unicodeScalars.allSatisfy(identifierCharacters.contains) else {- throw CodexBarHelperError.codeSigningValidationFailed(- "客户端标识符格式错误: \(clientIdentifier)"- )- }-- return "anchor apple generic"- + " and certificate leaf[subject.OU] = \"\(teamIdentifier)\""- + " and identifier \"\(clientIdentifier)\""- }-}--private enum CodexBarHelperError: LocalizedError {- case insecureOwnershipDirectory(String)- case invalidOwnershipRecord(String)- case ownershipWriteFailed(operation: String, code: Int32)- case codeSigningValidationFailed(String)-- var errorDescription: String? {- switch self {- case let .insecureOwnershipDirectory(detail):- "睡眠设置目录无效: \(detail)"- case let .invalidOwnershipRecord(detail):- "睡眠所有权记录无效: \(detail)"- case let .ownershipWriteFailed(operation, code):- "睡眠所有权记录写入失败: operation=\(operation); errno=\(code)"- case let .codeSigningValidationFailed(reason):- "签名校验失败: \(reason)"- }- }-}--private let runtime = CodexBarHelperRuntime()+private let runtime = HelperRuntime()runtime.run()dispatchMain()diff --git a/CodexBarTests/ActivityIsolationTests.swift b/CodexBarTests/ActivityIsolationTests.swiftnew file mode 100644index 0000000..7f866b3--- /dev/null+++ b/CodexBarTests/ActivityIsolationTests.swift@@ -0,0 +1,144 @@+import Foundation+import Synchronization+import Testing++struct ActivityIsolationTests {+ @Test(arguments: [false, true])+ func brokenThreadDoesNotStopHealthyThreadAndCanRecover(brokenQuery: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let repaired = Mutex(false)+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let now = Date().addingTimeInterval(-60)+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.160.0"])+ _ = try peer.readMessage()+ var emitted = false+ while let request = try? peer.readMessage() {+ let method = request["method"] as? String+ let id = (request["params"] as? [String: Any])?["threadId"] as? String ?? ""+ switch method {+ case "thread/loaded/list": try peer.reply(to: request, result: ["data": ["a-broken", "healthy"]])+ case "thread/read", "thread/resume":+ if id == "a-broken", brokenQuery, !repaired.withLock({ $0 }) {+ try peer.reply(to: request, result: ["thread": 123])+ } else {+ try peer.reply(to: request, result: ["thread": Self.thread(id, now: now)])+ }+ case "thread/turns/list":+ try peer.reply(to: request, result: ["data": [["id": "turn", "status": "inProgress", "startedAt": now.timeIntervalSince1970]]])+ if id == "healthy", !emitted {+ emitted = true+ if !brokenQuery {+ try peer.send(["method": "thread/status/changed", "params": ["threadId": "a-broken", "status": 123]])+ }+ try peer.send(Self.tool(thread: "healthy", id: "tool"))+ }+ if id == "healthy", repaired.withLock({ $0 }) {+ _ = release.wait(timeout: .now() + 5)+ return+ }+ default: Issue.record("Unexpected request: \(String(describing: method))")+ }+ }+ }+ defer { server.close() }+ let lifecycle = SessionLifecycleCache()+ var observed = false+ var disconnected = false+ let reader = AppServerActivityReader(+ lifecycleCache: lifecycle, socketURL: server.url,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url), recorder: ActivityRecorder(directoryURL: directory.url)+ ) { batch in+ if case .sourceUnavailable = batch {+ disconnected = true+ }+ if case let .live(events) = batch, events.contains(where: { $0.sessionID == "healthy" }) {+ observed = true+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where !observed {+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(observed && !disconnected)+ let references = ["a-broken", "healthy"].map { ActivityTurnReference(threadID: $0, turnID: "turn", startedAt: now) }+ let states = await lifecycle.lifecycleStates(for: references)+ #expect(states.first { $0.requestedThreadID == "healthy" }?.readStatus == .complete)+ #expect(states.first { $0.requestedThreadID == "a-broken" }?.readStatus == .unavailable)+ repaired.withLock { $0 = true }+ #expect(await reader.drainNow() == .completed)+ #expect(await lifecycle.lifecycleStates(for: references).allSatisfy { $0.readStatus == .complete })+ #expect(!disconnected)+ await reader.stop()+ release.signal()+ try server.finish()+ }++ @Test(arguments: [false, true])+ func fullStorageBufferStopsReadingAndKeepsAcceptedEvents(byteLimit: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let blocker = try directory.write("blocked", to: "State")+ let now = Date().addingTimeInterval(-60)+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.160.0"])+ _ = try peer.readMessage()+ try peer.reply(to: peer.readMessage(), result: ["data": ["healthy"]])+ for _ in 0 ..< 2 {+ try peer.reply(to: peer.readMessage(), result: ["thread": Self.thread("healthy", now: now)])+ }+ try peer.reply(to: peer.readMessage(), result: ["data": [["id": "turn", "status": "inProgress", "startedAt": now.timeIntervalSince1970]]])+ for id in ["one", "two", "three"] {+ try peer.send(Self.tool(thread: "healthy", id: id))+ }+ _ = try? peer.readMessage()+ }+ defer { server.close() }+ var failures = 0+ var observed = 0+ let reader = AppServerActivityReader(+ lifecycleCache: SessionLifecycleCache(), socketURL: server.url,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url), recorder: ActivityRecorder(directoryURL: directory.url),+ maximumPendingEvents: byteLimit ? 4096 : 2, maximumPendingBytes: byteLimit ? 1 : 8 * 1024 * 1024+ ) { batch in+ if case .sourceUnavailable = batch {+ failures += 1+ }+ if case let .live(events) = batch {+ observed += events.count+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where failures == 0 {+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(failures == 1)+ #expect(observed == (byteLimit ? 1 : 2))+ #expect(await reader.drainNow() == .sourceUnavailable)+ try FileManager.default.removeItem(at: blocker)+ await reader.stop()+ var recorded = 0+ let files = try FileManager.default.contentsOfDirectory(at: directory.url.appendingPathComponent("Events"), includingPropertiesForKeys: nil)+ for file in files {+ try AppServerEventJournal.read(at: file) {+ if $0.activity != nil {+ recorded += 1+ }+ }+ }+ #expect(recorded == (byteLimit ? 1 : 2))+ try server.finish()+ }++ private nonisolated static func thread(_ id: String, now: Date) -> [String: Any] {+ ["id": id, "source": "cli", "createdAt": now.timeIntervalSince1970, "cwd": "/tmp", "status": ["type": "active", "activeFlags": []]]+ }++ private nonisolated static func tool(thread: String, id: String) -> [String: Any] {+ ["method": "item/started", "params": ["threadId": thread, "turnId": "turn", "item": ["id": id, "type": "commandExecution"]]]+ }+}diff --git a/CodexBarTests/ActivityRecoveryTests.swift b/CodexBarTests/ActivityRecoveryTests.swiftnew file mode 100644index 0000000..457e268--- /dev/null+++ b/CodexBarTests/ActivityRecoveryTests.swift@@ -0,0 +1,91 @@+import Foundation+import Testing++struct ActivityRecoveryTests {+ @Test func damagedDerivedCacheRecoversRefreshAndRebuild() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let store = TokenHistoryStore(directoryURL: directory.url)+ let id = TokenTurn.identifier(thread: "t", turn: "u")+ let record = TokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: .zero)+ try await store.record([record], now: now)+ let cache = try directory.write("broken", to: "Aggregates/tokens.json")+ var refreshFailed = false+ var rebuildFailed = false+ do { _ = try await store.refresh(now: now) } catch { refreshFailed = true }+ try Data("broken".utf8).write(to: cache)+ do { _ = try await store.rebuild(for: [CodexDateFormat.dayString(from: now)], now: now) } catch { rebuildFailed = true }+ #expect(!refreshFailed && !rebuildFailed)+ try FileManager.default.removeItem(at: cache)+ let recovered = try await store.refresh(now: now)+ #expect(recovered.count == 1)+ }++ @Test(arguments: [false, true])+ func laterMalformedMessagePreservesEarlierValidEvent(_ malformed: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let timestamp = Date().timeIntervalSince1970+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.160.0"])+ _ = try peer.readMessage()+ let loaded = try peer.readMessage()+ try peer.reply(to: loaded, result: ["data": ["thread"]])+ let thread: [String: Any] = ["id": "thread", "source": "cli", "createdAt": timestamp, "cwd": "/tmp", "status": ["type": "active", "activeFlags": []]]+ let read = try peer.readMessage()+ try peer.reply(to: read, result: ["thread": thread])+ let resume = try peer.readMessage()+ try peer.reply(to: resume, result: ["thread": thread])+ let turns = try peer.readMessage()+ try peer.send(["method": "item/started", "params": ["threadId": "thread", "turnId": "turn", "item": ["id": "tool", "type": "commandExecution"]]])+ if malformed {+ try peer.send(["method": "thread/status/changed", "params": ["threadId": "thread", "status": 123]])+ }+ try peer.reply(to: turns, result: ["data": [["id": "turn", "status": "inProgress", "startedAt": timestamp]]])+ _ = release.wait(timeout: .now() + 5)+ }+ defer { server.close() }+ var failed = false+ var live = 0+ let reader = AppServerActivityReader(+ lifecycleCache: SessionLifecycleCache(),+ socketURL: server.url,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url),+ recorder: ActivityRecorder(directoryURL: directory.url)+ ) { batch in+ switch batch {+ case .sourceUnavailable: failed = true+ case let .live(events): live += events.count+ default: break+ }+ }+ await reader.start()+ for _ in 0 ..< 100 {+ if failed || live > 0 {+ break+ }+ try await Task.sleep(for: .milliseconds(10))+ }+ await reader.stop()+ release.signal()+ try server.finish()+ var recorded = 0+ let events = directory.url.appendingPathComponent("Events")+ if FileManager.default.fileExists(atPath: events.path) {+ for file in try FileManager.default.contentsOfDirectory(at: events, includingPropertiesForKeys: nil) {+ try AppServerEventJournal.read(at: file) {+ if $0.activity != nil {+ recorded += 1+ }+ }+ }+ }+ #expect(recorded == 1)+ #expect(live == 1)+ #expect(!failed)+ }+}diff --git a/CodexBarTests/ActivitySchedulingTests.swift b/CodexBarTests/ActivitySchedulingTests.swiftnew file mode 100644index 0000000..610ec86--- /dev/null+++ b/CodexBarTests/ActivitySchedulingTests.swift@@ -0,0 +1,304 @@+import Foundation+import Synchronization+import Testing++struct ActivitySchedulingTests {+ @Test func slowQueryDoesNotBlockPushOrOverwriteNewerApproval() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let observed = DispatchSemaphore(value: 0)+ let release = DispatchSemaphore(value: 0)+ defer { observed.signal()+ release.signal()+ }+ let timestamp = Date().timeIntervalSince1970+ let server = try SharedServerFixture { peer in+ try Self.bootstrap(peer, timestamp: timestamp)+ let loaded = try peer.readMessage()+ try peer.reply(to: loaded, result: ["data": ["thread"]])+ let read = try peer.readMessage()+ try peer.send(["method": "thread/status/changed", "params": ["threadId": "thread", "status": ["type": "active", "activeFlags": ["waitingOnApproval"]]]])+ try peer.send(["method": "item/started", "params": ["threadId": "thread", "turnId": "turn", "item": ["id": "tool", "type": "commandExecution"]]])+ // 如果客户端要等 read 响应才消费推送, 此处会超时+ #expect(observed.wait(timeout: .now() + 2) == .success)+ try peer.reply(to: read, result: ["thread": Self.thread(timestamp, status: "idle")])+ let turns = try peer.readMessage()+ try peer.reply(to: turns, result: ["data": [["id": "turn", "status": "inProgress", "startedAt": timestamp]]])+ _ = release.wait(timeout: .now() + 5)+ }+ defer { server.close() }+ let lifecycle = SessionLifecycleCache()+ var ready = false+ let reader = AppServerActivityReader(+ lifecycleCache: lifecycle, socketURL: server.url,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url),+ recorder: ActivityRecorder(directoryURL: directory.url)+ ) { batch in+ if case .bootstrapEnd = batch {+ ready = true+ }+ if case let .live(events) = batch, events.contains(where: { $0.eventKind == .toolStarted }) {+ observed.signal()+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where !ready {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(ready)+ #expect(await reader.drainNow() == .completed)+ let reference = ActivityTurnReference(threadID: "thread", turnID: "turn", startedAt: Date(timeIntervalSince1970: timestamp))+ #expect(await lifecycle.lifecycleStates(for: [reference]).first?.isWaitingApproval == true)+ await reader.stop()+ release.signal()+ try server.finish()+ }++ @Test func tokenUpdatesBeforeMalformedMessageArePersisted() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let timestamp = Date().addingTimeInterval(-60).timeIntervalSince1970+ let server = try SharedServerFixture { peer in+ try Self.bootstrap(peer, timestamp: timestamp)+ for total in [100, 150] {+ let usage = ["inputTokens": total, "cachedInputTokens": 0, "outputTokens": 0, "reasoningOutputTokens": 0, "totalTokens": total]+ try peer.send(["method": "thread/tokenUsage/updated", "params": ["threadId": "thread", "turnId": "turn", "tokenUsage": ["total": usage, "last": usage]]])+ }+ try peer.send(["method": "thread/status/changed", "params": ["threadId": "thread", "status": 123]])+ _ = release.wait(timeout: .now() + 5)+ }+ defer { server.close() }+ var failed = false+ let store = TokenHistoryStore(directoryURL: directory.url)+ let reader = AppServerActivityReader(+ lifecycleCache: SessionLifecycleCache(), socketURL: server.url,+ tokenHistory: store, recorder: ActivityRecorder(directoryURL: directory.url)+ ) {+ if case .sourceUnavailable = $0 {+ failed = true+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where !failed {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(!failed)+ await reader.stop()+ #expect(try await store.refresh().first?.usage?.totalTokens == 50)+ release.signal()+ try server.finish()+ }++ @Test func idleThreadsAreNotFullyReadOnEveryDiscovery() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let server = try SharedServerFixture { peer in+ try Self.bootstrap(peer, timestamp: Date().timeIntervalSince1970, idle: true)+ for _ in 0 ..< 2 {+ let loaded = try peer.readMessage()+ #expect(loaded["method"] as? String == "thread/loaded/list")+ try peer.reply(to: loaded, result: ["data": ["thread"]])+ }+ _ = release.wait(timeout: .now() + 5)+ }+ defer { server.close() }+ let reader = AppServerActivityReader(+ lifecycleCache: SessionLifecycleCache(), socketURL: server.url,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url),+ recorder: ActivityRecorder(directoryURL: directory.url), onBatch: { _ in }+ )+ await reader.start()+ try await Task.sleep(for: .milliseconds(4400))+ await reader.stop()+ release.signal()+ try server.finish()+ }++ @Test func missingRolloutDoesNotDisconnectOtherThreadsAndCanRecover() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let discoveries = Mutex(0)+ let timestamp = Date().addingTimeInterval(-60).timeIntervalSince1970+ let server = try SharedServerFixture { peer in+ try Self.serveMissingRollout(peer, timestamp: timestamp, release: release) {+ discoveries.withLock { $0 += 1 }+ }+ }+ defer { server.close() }+ let lifecycle = SessionLifecycleCache()+ var ready = false+ var disconnected = false+ var tools = 0+ let reader = AppServerActivityReader(+ lifecycleCache: lifecycle, socketURL: server.url,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url),+ recorder: ActivityRecorder(directoryURL: directory.url)+ ) { batch in+ if case .bootstrapEnd = batch {+ ready = true+ }+ if case .sourceUnavailable = batch {+ disconnected = true+ }+ if case let .live(events) = batch {+ tools += events.filter { $0.eventKind == .toolStarted }.count+ }+ }+ await reader.start()+ for _ in 0 ..< 600 where discoveries.withLock({ $0 }) < 2 && !disconnected {+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(ready)+ #expect(!disconnected)+ #expect(tools == 1)+ #expect(discoveries.withLock { $0 } == 2)+ if ready, !disconnected {+ #expect(await reader.drainNow() == .completed)+ let reference = ActivityTurnReference(threadID: "a-missing", turnID: "turn", startedAt: Date(timeIntervalSince1970: timestamp))+ #expect(await lifecycle.lifecycleStates(for: [reference]).first?.readStatus == .complete)+ #expect(!disconnected)+ }+ await reader.stop()+ release.signal()+ try server.finish()+ }++ @Test func persistedEventIsPublishedOnceAfterMaintenanceWriteRecovers() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let blocker = try directory.write("block maintenance directory", to: "State")+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let server = try SharedServerFixture { peer in+ try Self.bootstrap(peer, timestamp: Date().addingTimeInterval(-60).timeIntervalSince1970)+ try peer.send(["method": "item/started", "params": ["threadId": "thread", "turnId": "turn", "item": ["id": "tool", "type": "commandExecution"]]])+ _ = release.wait(timeout: .now() + 5)+ }+ defer { server.close() }+ var failures = 0+ var published = 0+ let reader = AppServerActivityReader(+ lifecycleCache: SessionLifecycleCache(), socketURL: server.url,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url),+ recorder: ActivityRecorder(directoryURL: directory.url)+ ) { batch in+ if case .sourceUnavailable = batch {+ failures += 1+ }+ if case let .live(events) = batch {+ published += events.count+ }+ }+ await reader.start()+ for _ in 0 ..< 100 where published == 0 {+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(published == 1)+ #expect(failures == 0)+ try FileManager.default.removeItem(at: blocker)+ for _ in 0 ..< 150 where HistoryStorage.loadMaintenanceState(in: directory.url).days.isEmpty {+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(!HistoryStorage.loadMaintenanceState(in: directory.url).days.isEmpty)+ #expect(failures == 0)+ #expect(published == 1)+ await reader.stop()+ release.signal()+ try server.finish()+ var recorded = 0+ let files = try FileManager.default.contentsOfDirectory(at: HistoryStorage.eventsDirectoryURL(in: directory.url), includingPropertiesForKeys: nil)+ for file in files {+ try AppServerEventJournal.read(at: file) {+ if $0.activity != nil {+ recorded += 1+ }+ }+ }+ #expect(recorded == 1)+ }++ private nonisolated static func serveMissingRollout(+ _ peer: SharedServerFixture.Peer,+ timestamp: Double,+ release: DispatchSemaphore,+ onDiscovery: @Sendable () -> Void+ ) throws {+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.160.0"])+ #expect(try peer.readMessage()["method"] as? String == "initialized")+ let loaded = try peer.readMessage()+ try peer.reply(to: loaded, result: ["data": ["a-missing", "thread"]])+ var missing = Self.thread(timestamp, status: "idle")+ missing["id"] = "a-missing"+ missing["ephemeral"] = false+ let read = try peer.readMessage()+ #expect(read["method"] as? String == "thread/read")+ try peer.reply(to: read, result: ["thread": missing])+ let resume = try peer.readMessage()+ #expect(resume["method"] as? String == "thread/resume")+ try peer.send(["id": #require(resume["id"]), "error": [+ "code": -32600, "message": "no rollout found for thread id a-missing"+ ]])+ // 单线程失败后继续初始化其他线程, 不重新 initialize+ for method in ["thread/read", "thread/resume"] {+ let request = try peer.readMessage()+ #expect(request["method"] as? String == method)+ try peer.reply(to: request, result: ["thread": Self.thread(timestamp)])+ }+ let turns = try peer.readMessage()+ try peer.reply(to: turns, result: ["data": [["id": "turn", "status": "inProgress", "startedAt": timestamp]]])+ try peer.send(["method": "item/started", "params": [+ "threadId": "thread", "turnId": "turn", "item": ["id": "tool", "type": "commandExecution"]+ ]])+ // 普通发现不立即重试不可用线程, 健康线程仍可接收推送+ for _ in 0 ..< 2 {+ let request = try peer.readMessage()+ #expect(request["method"] as? String == "thread/loaded/list")+ try peer.reply(to: request, result: ["data": ["a-missing", "thread"]])+ onDiscovery()+ }+ // 强制对账重新尝试失败线程, 服务端恢复后无需重连即可加入+ let discovery = try peer.readMessage()+ #expect(discovery["method"] as? String == "thread/loaded/list")+ try peer.reply(to: discovery, result: ["data": ["a-missing", "thread"]])+ for id in ["a-missing", "thread"] {+ var thread = Self.thread(timestamp)+ thread["id"] = id+ let methods = id == "a-missing" ? ["thread/read", "thread/resume"] : ["thread/read"]+ for method in methods {+ let request = try peer.readMessage()+ #expect(request["method"] as? String == method)+ #expect((request["params"] as? [String: Any])?["threadId"] as? String == id)+ try peer.reply(to: request, result: ["thread": thread])+ }+ let request = try peer.readMessage()+ #expect(request["method"] as? String == "thread/turns/list")+ try peer.reply(to: request, result: ["data": [["id": "turn", "status": "inProgress", "startedAt": timestamp]]])+ }+ _ = release.wait(timeout: .now() + 5)+ }++ private nonisolated static func thread(_ timestamp: Double, status: String = "active") -> [String: Any] {+ ["id": "thread", "source": "cli", "createdAt": timestamp, "cwd": "/tmp", "status": ["type": status, "activeFlags": []]]+ }++ private nonisolated static func bootstrap(_ peer: SharedServerFixture.Peer, timestamp: Double, idle: Bool = false) throws {+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.160.0"])+ _ = try peer.readMessage()+ let loaded = try peer.readMessage()+ try peer.reply(to: loaded, result: ["data": ["thread"]])+ for _ in 0 ..< 2 {+ let request = try peer.readMessage()+ try peer.reply(to: request, result: ["thread": thread(timestamp, status: idle ? "idle" : "active")])+ }+ let turns = try peer.readMessage()+ try peer.reply(to: turns, result: ["data": [["id": "turn", "status": idle ? "completed" : "inProgress", "startedAt": timestamp]]])+ }+}diff --git a/CodexBarTests/CodexActivityTaskTests.swift b/CodexBarTests/ActivityTaskTests.swiftsimilarity index 52%rename from CodexBarTests/CodexActivityTaskTests.swiftrename to CodexBarTests/ActivityTaskTests.swiftindex aa54b80..2237582 100644--- a/CodexBarTests/CodexActivityTaskTests.swift+++ b/CodexBarTests/ActivityTaskTests.swift@@ -1,23 +1,51 @@import Foundationimport Testing-struct CodexActivityTaskTests {+struct ActivityTaskTests {+ @Test func namelessToolAndApprovalDoNotReusePreviousToolName() {+ var task = makeTask(TestFixtures.event(.toolStarted))+ #expect(task.snapshot.toolName == "exec_command")+ let event = ActivityRecord(+ timestamp: TestFixtures.now.addingTimeInterval(1), name: ActivityEventKind.toolStarted.rawValue,+ origin: .main, cwd: nil, tool: nil, model: nil, effort: nil,+ approvalReviewer: .user, sessionID: "session-a", turnID: "turn-a", agentID: nil+ )+ var nameless = event+ nameless.source = AppServerEventSource(method: "item/started", threadID: "session-a", itemType: "fileChange")+ task.mergeMetadata(from: nameless)+ #expect(task.snapshot.toolName == nil)+ #expect(task.snapshot.toolDisplayName == "fileChange")++ var approval = ActivityRecord(+ timestamp: TestFixtures.now.addingTimeInterval(2), name: ActivityEventKind.approvalRequested.rawValue,+ origin: .main, cwd: nil, tool: nil, model: nil, effort: nil,+ approvalReviewer: .user, sessionID: "session-a", turnID: "turn-a", agentID: nil+ )+ approval.source = AppServerEventSource(method: "item/commandExecution/requestApproval", threadID: "session-a", itemType: "commandExecution")+ task.mergeMetadata(from: approval)+ let enteredWaiting = task.recordApprovalRequest(from: approval)+ #expect(enteredWaiting)+ #expect(task.snapshot.toolName == nil)+ #expect(task.snapshot.toolDisplayName == "commandExecution")+ #expect(ActivityDisplayFormat.waitingDetailComponents(for: task.snapshot, now: approval.timestamp).first == "commandExecution")+ }+@Test func anonymousTaskHasNoProtectionIdentityOrPreciseDuration() {let task = makeTask(TestFixtures.event(session: nil))#expect(task.key.isAnonymous)- #expect(task.key.activityProtectionIdentifier == nil)+ #expect(task.key.protectionIdentifier == nil)#expect(!task.snapshot.showsPreciseDuration)#expect(task.preciseDuration(until: TestFixtures.now.addingTimeInterval(60)) == nil)}@Test func taskIdentitySeparatesSessionsTurnsAndAnonymousProjects() {- #expect(CodexActivityTaskKey(event: TestFixtures.event()).sessionID == "session-a")- #expect(CodexActivityTaskKey(event: TestFixtures.event(turn: nil)).isSessionOnly)- let first = CodexActivityTaskKey.turn(session: "ab", turn: "c").activityProtectionIdentifier- let second = CodexActivityTaskKey.turn(session: "a", turn: "bc").activityProtectionIdentifier+ #expect(ActivityTaskKey(event: TestFixtures.event()).sessionID == "session-a")+ #expect(ActivityTaskKey(event: TestFixtures.event(turn: nil)).isSessionOnly)+ let first = ActivityTaskKey.turn(session: "ab", turn: "c").protectionIdentifier+ let second = ActivityTaskKey.turn(session: "a", turn: "bc").protectionIdentifier#expect(first != second)#expect(first?.count == 64)- #expect(first != CodexActivityTaskKey.session("ab").activityProtectionIdentifier)+ #expect(first != ActivityTaskKey.session("ab").protectionIdentifier)}@Test func preciseDurationRequiresKnownStartAndNonnegativeInterval() {@@ -42,72 +70,68 @@ struct CodexActivityTaskTests {#expect(!mixedEffortChanged)}- @Test func rolloutProgressDoesNotMoveHookOrderingBarrier() {+ @Test func executionProgressDoesNotMoveEventOrderingBarrier() {var task = makeTask()task.recordProgress(at: TestFixtures.now.addingTimeInterval(30))- task.recordHookEvent(at: TestFixtures.now.addingTimeInterval(10))- #expect(task.lastHookEventAt == TestFixtures.now.addingTimeInterval(10))+ task.recordEvent(at: TestFixtures.now.addingTimeInterval(10))+ #expect(task.lastEventAt == TestFixtures.now.addingTimeInterval(10))#expect(task.lastProgressAt == TestFixtures.now.addingTimeInterval(30))#expect(task.progressGeneration == 3)}- @Test func incompleteTailDeadlineAlsoWaitsForLatestHookProgressAndUsesCurrentThreshold() {+ @Test func protectionDeadlineUsesLatestProgressAndCurrentThreshold() {var task = makeTask()let observed = TestFixtures.nowlet checked = observed.addingTimeInterval(3600)- task.recordLifecycleRead(incompleteTail(since: observed), at: checked)+ task.recordLifecycleRead(healthyLifecycle(), at: checked)task.recordProgress(at: observed.addingTimeInterval(1800))- #expect(task.activityProtectionDeadline(at: checked, inactivityDuration: 3600) == observed.addingTimeInterval(5400))- #expect(task.activityProtectionDeadline(at: checked, inactivityDuration: 1800) == checked)- #expect(!task.hasFreshLifecycle(at: checked))- #expect(task.activityProtectionDeadline(at: checked.addingTimeInterval(5), inactivityDuration: 3600) == nil)+ #expect(task.protectionDeadline(at: checked, inactivityDuration: 3600) == observed.addingTimeInterval(5400))+ #expect(task.protectionDeadline(at: checked, inactivityDuration: 1800) == checked)+ #expect(task.hasFreshLifecycle(at: checked))+ #expect(task.protectionDeadline(at: checked.addingTimeInterval(5), inactivityDuration: 3600) == nil)}- @Test(arguments: [CodexSessionReadStatus.incomplete, .unavailable, .notFound])- func losingTailEvidenceRevokesProtectionEligibility(status: CodexSessionReadStatus) {+ @Test(arguments: [SessionReadStatus.unavailable, .notFound])+ func losingLifecycleCoverageRevokesProtectionEligibility(status: SessionReadStatus) {var task = makeTask()let now = TestFixtures.now.addingTimeInterval(3600)- task.recordLifecycleRead(incompleteTail(since: TestFixtures.now), at: now)- #expect(task.activityProtectionDeadline(at: now, inactivityDuration: 3600) == now)- var lost = incompleteTail(since: TestFixtures.now)+ task.recordLifecycleRead(healthyLifecycle(), at: now)+ #expect(task.protectionDeadline(at: now, inactivityDuration: 3600) == now)+ var lost = healthyLifecycle()lost.readStatus = status- lost.incompleteTailUnchangedSince = niltask.recordLifecycleRead(lost, at: now)- #expect(task.activityProtectionDeadline(at: now, inactivityDuration: 3600) == nil)- #expect(task.incompleteTailCheckedAt == nil)+ #expect(task.protectionDeadline(at: now, inactivityDuration: 3600) == nil)}- @Test func incompleteTailCannotResumeApprovalButCompleteProgressCan() {+ @Test func unavailableSourceCannotResumeApprovalButCompleteProgressCan() {var task = makeTask()- _ = task.recordApprovalRequest(from: TestFixtures.event(.permissionRequest))+ _ = task.recordApprovalRequest(from: TestFixtures.event(.approvalRequested))let now = TestFixtures.now.addingTimeInterval(3600)- var state = incompleteTail(since: TestFixtures.now)+ var state = healthyLifecycle()+ state.readStatus = .unavailablestate.lastExecutionProgressAt = now- let owner = CodexActivityExecutionKey(agentID: nil, turnID: "turn-a")+ let owner = ActivityExecutionKey(agentID: nil, turnID: "turn-a")task.recordLifecycleRead(state, at: now)task.mergeExecutionLifecycle(state, owner: owner)#expect(task.state == .waitingApproval)#expect(!task.hasFreshLifecycle(at: now))state.readStatus = .complete- state.incompleteTailUnchangedSince = niltask.recordLifecycleRead(state, at: now)task.mergeExecutionLifecycle(state, owner: owner)#expect(task.hasFreshLifecycle(at: now))- #expect(task.incompleteTailCheckedAt == nil)#expect(task.state == .running)}- private func incompleteTail(since date: Date) -> CodexSessionTaskLifecycleState {- CodexSessionTaskLifecycleState(+ private func healthyLifecycle() -> SessionLifecycleState {+ SessionLifecycleState(requestedThreadID: "session-a", turnID: "turn-a", startedAt: nil, approvalReviewer: nil, effort: nil,- lastProgressAt: nil, terminal: nil, readStatus: .incomplete, hasContext: true,- incompleteTailUnchangedSince: date+ lastProgressAt: nil, terminal: nil, readStatus: .complete, hasContext: true)}@Test(arguments: ["unchanged", "growth", "unavailable", "stale"])- func suppressionRevalidatesTailAfterNotification(scenario: String) throws {+ func suppressionRevalidatesCoverageAfterNotification(scenario: String) throws {let directory = try TestDirectory()defer { try? directory.remove() }let preferences = try TestPreferences()@@ -116,36 +140,36 @@ struct CodexActivityTaskTests {defer { monitor.stop() }let now = Date()var task = makeTask(TestFixtures.event(at: now.addingTimeInterval(-7200)))- task.recordLifecycleRead(incompleteTail(since: now.addingTimeInterval(-3601)), at: now)+ task.recordLifecycleRead(healthyLifecycle(), at: now)monitor.tasks[task.key] = task- let candidate = ActivityProtectionCandidate(+ let candidate = ProtectionCandidate(key: task.key, taskID: task.displayID, projectName: task.projectName,lastProgressAt: task.lastProgressAt, progressGeneration: task.progressGeneration, inactivityDuration: .oneHour)- #expect(monitor.isActivityProtectionCandidateRelevant(candidate, now: now))+ #expect(monitor.isProtectionCandidateRelevant(candidate, now: now))switch scenario {- case "growth": task.recordLifecycleRead(incompleteTail(since: now), at: now)+ case "growth": task.recordProgress(at: now)case "unavailable":- var state = incompleteTail(since: now)+ var state = healthyLifecycle()state.readStatus = .unavailabletask.recordLifecycleRead(state, at: now)- case "stale": task.incompleteTailCheckedAt = now.addingTimeInterval(-5)+ case "stale": task.lifecycleCoverageCheckedAt = now.addingTimeInterval(-5)default: break}monitor.tasks[task.key] = tasklet attemptID = UUID()- monitor.activityProtectionAttempts[task.key] = ActivityProtectionAttempt(+ monitor.protectionAttempts[task.key] = ProtectionAttempt(id: attemptID, candidate: candidate, markedAt: now, timeoutTask: Task {})- monitor.finishActivityProtectionAttempt(task.key, attemptID: attemptID, taskID: task.displayID, notificationWasSubmitted: false)+ monitor.finishProtectionAttempt(task.key, attemptID: attemptID, taskID: task.displayID, notificationWasSubmitted: false)#expect(monitor.tasks[task.key]?.state == (scenario == "unchanged" ? .suppressed : .running))- #expect(monitor.activityProtectionAttempts.isEmpty)+ #expect(monitor.protectionAttempts.isEmpty)}- @Test(arguments: [false, true], [ActivityProtectionSettings.InactivityDuration.thirtyMinutes, .oneHour])- func longerThresholdRestoresTailSuppressionAndUsesNewDeadline(- expiredObservation: Bool, previousDuration: ActivityProtectionSettings.InactivityDuration+ @Test(arguments: [false, true], [ProtectionSettings.InactivityDuration.thirtyMinutes, .oneHour])+ func longerThresholdRestoresSuppressionAndUsesNewDeadline(+ expiredObservation: Bool, previousDuration: ProtectionSettings.InactivityDuration) async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -155,59 +179,55 @@ struct CodexActivityTaskTests {defer { monitor.stop() }let changedAt = Date()let hiddenAfter: TimeInterval = previousDuration == .thirtyMinutes ? 3000 : 3600- let newDuration: ActivityProtectionSettings.InactivityDuration = previousDuration == .thirtyMinutes ? .oneHour : .twoHours- let tailStoppedAt = changedAt.addingTimeInterval(-hiddenAfter - 300)- let hiddenAt = tailStoppedAt.addingTimeInterval(hiddenAfter)- let newDeadline = tailStoppedAt.addingTimeInterval(newDuration.timeInterval)- var task = makeTask(TestFixtures.event(at: tailStoppedAt.addingTimeInterval(-3600)))+ let newDuration: ProtectionSettings.InactivityDuration = previousDuration == .thirtyMinutes ? .oneHour : .twoHours+ let progressStoppedAt = changedAt.addingTimeInterval(-hiddenAfter - 300)+ let hiddenAt = progressStoppedAt.addingTimeInterval(hiddenAfter)+ let newDeadline = progressStoppedAt.addingTimeInterval(newDuration.timeInterval)+ var task = makeTask(TestFixtures.event(at: progressStoppedAt))let key = task.key- let identifier = try #require(key.activityProtectionIdentifier)- task.recordLifecycleRead(incompleteTail(since: tailStoppedAt), at: hiddenAt)+ let identifier = try #require(key.protectionIdentifier)+ task.recordLifecycleRead(healthyLifecycle(), at: hiddenAt)monitor.tasks[key] = task- monitor.activityProtectionSettings.setInactivityDuration(previousDuration)- monitor.reconcileActivityProtection(now: hiddenAt, sendsNotification: false)+ monitor.protectionSettings.setInactivityDuration(previousDuration)+ monitor.reconcileProtection(now: hiddenAt, sendsNotification: false)#expect(monitor.tasks[key]?.state == .suppressed)- #expect(monitor.activityProtectionRecords[identifier] != nil)+ #expect(monitor.protectionRecords[identifier] != nil)let checkedAt = expiredObservation ? changedAt.addingTimeInterval(-5) : changedAt- monitor.tasks[key]?.recordLifecycleRead(incompleteTail(since: tailStoppedAt), at: checkedAt)- monitor.activityProtectionSettings.setInactivityDuration(newDuration)- monitor.handleActivityProtectionTimingChange()+ monitor.tasks[key]?.recordLifecycleRead(healthyLifecycle(), at: checkedAt)+ monitor.protectionSettings.setInactivityDuration(newDuration)+ monitor.handleProtectionTimingChange()#expect(monitor.tasks[key]?.state == .running)- #expect(monitor.activityProtectionRecords[identifier] == nil)+ #expect(monitor.protectionRecords[identifier] == nil)#expect(monitor.tasks[key]?.lastProgressAt == task.lastProgressAt)- #expect(monitor.tasks[key]?.hasFreshLifecycle(at: changedAt) == false)+ #expect(monitor.tasks[key]?.hasFreshLifecycle(at: changedAt) == !expiredObservation)- monitor.reconcileActivityProtection(now: newDeadline, sendsNotification: false)+ monitor.reconcileProtection(now: newDeadline, sendsNotification: false)#expect(monitor.tasks[key]?.state == .running)- monitor.tasks[key]?.recordLifecycleRead(incompleteTail(since: tailStoppedAt), at: newDeadline.addingTimeInterval(-1))- monitor.reconcileActivityProtection(now: newDeadline.addingTimeInterval(-1), sendsNotification: false)+ monitor.tasks[key]?.recordLifecycleRead(healthyLifecycle(), at: newDeadline.addingTimeInterval(-1))+ monitor.reconcileProtection(now: newDeadline.addingTimeInterval(-1), sendsNotification: false)#expect(monitor.tasks[key]?.state == .running)- monitor.reconcileActivityProtection(now: newDeadline, sendsNotification: false)+ monitor.reconcileProtection(now: newDeadline, sendsNotification: false)#expect(monitor.tasks[key]?.state == .suppressed)- #expect(monitor.activityProtectionRecords[identifier] != nil)+ #expect(monitor.protectionRecords[identifier] != nil)monitor.cancelInactivityCheck()- await monitor.activityProtectionPersistenceTask?.value+ await monitor.protectionPersistenceTask?.value}- private func makeProtectionMonitor(in directory: TestDirectory, preferences: TestPreferences) throws -> CodexActivityMonitor {- let monitor = try CodexActivityMonitor(- advancedModeSettings: AdvancedModeSettings(- hooksURL: directory.url.appendingPathComponent("hooks.json"),- codexStatusService: makeStatusService(suiteName: preferences.suite)- ),- activityProtectionSettings: ActivityProtectionSettings(defaults: preferences.defaults),- activityProtectionStateStore: ActivityProtectionStateStore(directoryURL: directory.url)+ private func makeProtectionMonitor(in directory: TestDirectory, preferences: TestPreferences) throws -> ActivityMonitor {+ let monitor = ActivityMonitor(+ protectionSettings: ProtectionSettings(defaults: preferences.defaults),+ protectionStore: ProtectionStore(directoryURL: directory.url))monitor.isStarted = true- monitor.isActivityProtectionEnabled = true+ monitor.isProtectionEnabled = truemonitor.isActivitySourceHealthy = true- monitor.tailReader = HookEventTailReader(eventsDirectoryURL: directory.url) { _ in }+ monitor.activityReader = AppServerActivityReader(lifecycleCache: SessionLifecycleCache(), socketURL: directory.url.appendingPathComponent("test.sock")) { _ in }return monitor}- private nonisolated func makeStatusService(suiteName: String) throws -> CodexStatusService {- try CodexStatusService(defaults: #require(UserDefaults(suiteName: suiteName)))+ private nonisolated func makeStatusService(suiteName: String) -> CodexStatusService {+ CodexStatusService(socketURL: URL(fileURLWithPath: "/tmp/\(suiteName).sock"))}@Test func subagentCountDeduplicatesAndRejectsOlderEvents() {@@ -231,9 +251,9 @@ struct CodexActivityTaskTests {}@Test func onlyUserApprovalTransitionsToWaiting() {- for reviewer in [CodexApprovalReviewer.user, .autoReview, .guardianSubagent] {+ for reviewer in [ApprovalReviewer.user, .autoReview, .guardianSubagent] {var task = makeTask(TestFixtures.event(reviewer: reviewer))- let transitioned = task.recordApprovalRequest(from: TestFixtures.event(.permissionRequest, reviewer: reviewer))+ let transitioned = task.recordApprovalRequest(from: TestFixtures.event(.approvalRequested, reviewer: reviewer))#expect(transitioned == (reviewer == .user))#expect(task.state == (reviewer == .user ? .waitingApproval : .running))}@@ -241,14 +261,14 @@ struct CodexActivityTaskTests {@Test func unknownApprovalWaitsForContextOfSameExecution() {var task = makeTask(TestFixtures.event(reviewer: nil))- let requestedWaiting = task.recordApprovalRequest(from: TestFixtures.event(.permissionRequest, reviewer: nil))+ let requestedWaiting = task.recordApprovalRequest(from: TestFixtures.event(.approvalRequested, reviewer: nil))#expect(!requestedWaiting)- let otherOwner = CodexActivityExecutionKey(agentID: "other", turnID: "turn-a")+ let otherOwner = ActivityExecutionKey(agentID: "other", turnID: "turn-a")task.mergeApprovalContext(reviewer: .user, observedAt: TestFixtures.now, owner: otherOwner)let resolvedOtherExecution = task.resolvePendingApprovals()#expect(!resolvedOtherExecution)#expect(task.state == .running)- let owner = CodexActivityExecutionKey(agentID: nil, turnID: "turn-a")+ let owner = ActivityExecutionKey(agentID: nil, turnID: "turn-a")task.mergeApprovalContext(reviewer: .user, observedAt: TestFixtures.now, owner: owner)let resolvedOwner = task.resolvePendingApprovals()#expect(resolvedOwner)@@ -257,53 +277,53 @@ struct CodexActivityTaskTests {@Test func mainProgressCannotDismissSubagentApproval() {var task = makeTask()- let approval = TestFixtures.event(.permissionRequest, agent: "agent", origin: .auxiliary)+ let approval = TestFixtures.event(.approvalRequested, agent: "agent", origin: .auxiliary)let enteredWaiting = task.recordApprovalRequest(from: approval)#expect(enteredWaiting)- task.resumeExecution(from: TestFixtures.event(.postToolUse, at: TestFixtures.now.addingTimeInterval(1)), latestEvent: .toolFinished)+ task.resumeExecution(from: TestFixtures.event(.toolCompleted, at: TestFixtures.now.addingTimeInterval(1)), latestEvent: .toolFinished)#expect(task.state == .waitingApproval)- task.resumeExecution(from: TestFixtures.event(.postToolUse, at: TestFixtures.now.addingTimeInterval(2), agent: "agent", origin: .auxiliary), latestEvent: .toolFinished)+ task.resumeExecution(from: TestFixtures.event(.toolCompleted, at: TestFixtures.now.addingTimeInterval(2), agent: "agent", origin: .auxiliary), latestEvent: .toolFinished)#expect(task.state == .running)}@Test func resolvingOneApprovalKeepsOtherExecutionWaiting() {var task = makeTask()- let mainEnteredWaiting = task.recordApprovalRequest(from: TestFixtures.event(.permissionRequest))+ let mainEnteredWaiting = task.recordApprovalRequest(from: TestFixtures.event(.approvalRequested))#expect(mainEnteredWaiting)- let agentRequest = TestFixtures.event(.permissionRequest, at: TestFixtures.now.addingTimeInterval(1), agent: "agent", origin: .auxiliary)+ let agentRequest = TestFixtures.event(.approvalRequested, at: TestFixtures.now.addingTimeInterval(1), agent: "agent", origin: .auxiliary)let agentEnteredWaiting = task.recordApprovalRequest(from: agentRequest)#expect(!agentEnteredWaiting)- task.finishExecution(CodexActivityExecutionKey(agentID: nil, turnID: "turn-a"), at: TestFixtures.now.addingTimeInterval(2))+ task.finishExecution(ActivityExecutionKey(agentID: nil, turnID: "turn-a"), at: TestFixtures.now.addingTimeInterval(2))#expect(task.state == .waitingApproval)#expect(task.displayedApproval?.requestedAt == TestFixtures.now.addingTimeInterval(1))- task.finishExecution(CodexActivityExecutionKey(agentID: "agent", turnID: "turn-a"), at: TestFixtures.now.addingTimeInterval(3))+ task.finishExecution(ActivityExecutionKey(agentID: "agent", turnID: "turn-a"), at: TestFixtures.now.addingTimeInterval(3))#expect(task.state == .running)}@Test func lateApprovalDoesNotUndoConfirmedExecutionProgress() {var task = makeTask()let progress = TestFixtures.now.addingTimeInterval(2)- task.resumeExecution(from: TestFixtures.event(.postToolUse, at: progress), latestEvent: .toolFinished)- let lateRequestChanged = task.recordApprovalRequest(from: TestFixtures.event(.permissionRequest))+ task.resumeExecution(from: TestFixtures.event(.toolCompleted, at: progress), latestEvent: .toolFinished)+ let lateRequestChanged = task.recordApprovalRequest(from: TestFixtures.event(.approvalRequested))#expect(!lateRequestChanged)#expect(task.state == .running)- task.finishExecution(CodexActivityExecutionKey(agentID: nil, turnID: "turn-a"), at: progress)- #expect(!task.acceptsExecutionEvent(TestFixtures.event(.preToolUse, at: progress.addingTimeInterval(1))))+ task.finishExecution(ActivityExecutionKey(agentID: nil, turnID: "turn-a"), at: progress)+ #expect(!task.acceptsExecutionEvent(TestFixtures.event(.toolStarted, at: progress.addingTimeInterval(1))))}- @Test func equalTimestampRolloutProgressDoesNotDismissApproval() {+ @Test func equalTimestampExecutionProgressDoesNotDismissApproval() {var task = makeTask()- _ = task.recordApprovalRequest(from: TestFixtures.event(.permissionRequest))- let owner = CodexActivityExecutionKey(agentID: nil, turnID: "turn-a")+ _ = task.recordApprovalRequest(from: TestFixtures.event(.approvalRequested))+ let owner = ActivityExecutionKey(agentID: nil, turnID: "turn-a")task.mergeExecutionProgress(at: TestFixtures.now, owner: owner)#expect(task.state == .waitingApproval)task.mergeExecutionProgress(at: TestFixtures.now.addingTimeInterval(0.001), owner: owner)#expect(task.state == .running)}- private func makeTask(_ event: WorkflowHookEvent = TestFixtures.event()) -> CodexActivityTask {- CodexActivityTask(- displayID: UUID(), key: CodexActivityTaskKey(event: event), event: event,+ private func makeTask(_ event: ActivityRecord = TestFixtures.event()) -> ActivityTask {+ ActivityTask(+ displayID: UUID(), key: ActivityTaskKey(event: event), event: event,state: .running, latestEvent: .promptSubmitted, startedAt: event.timestamp, progressGeneration: 1)}diff --git a/CodexBarTests/CodexActivityTokenUsageTests.swift b/CodexBarTests/ActivityTokenUsageTests.swiftsimilarity index 82%rename from CodexBarTests/CodexActivityTokenUsageTests.swiftrename to CodexBarTests/ActivityTokenUsageTests.swiftindex 7809555..e9380c6 100644--- a/CodexBarTests/CodexActivityTokenUsageTests.swift+++ b/CodexBarTests/ActivityTokenUsageTests.swift@@ -1,14 +1,14 @@import Foundationimport Testing-struct CodexActivityTokenUsageTests {+struct ActivityTokenUsageTests {@Test func cacheHitRateUsesAllInputAndIsUnavailableWithoutInput() {- let usage = CodexTokenUsage(+ let usage = TokenUsage(inputTokens: 1000, cachedInputTokens: 800, cacheWriteInputTokens: 100,outputTokens: 200, reasoningOutputTokens: 50, totalTokens: 1200)#expect(usage.cacheHitRate == 0.8)- let outputOnly = CodexTokenUsage(+ let outputOnly = TokenUsage(inputTokens: 0, cachedInputTokens: 0, cacheWriteInputTokens: 0,outputTokens: 200, reasoningOutputTokens: 50, totalTokens: 200)@@ -49,7 +49,7 @@ struct CodexActivityTokenUsageTests {@Test func knownAgentWithoutResolvedTurnPreventsPartialTotal() {let root = reference("session-a", "turn-a")- let request = CodexTaskTokenUsageRequest(+ let request = TaskTokenRequest(root: root, expectedAgentIDs: ["unknown-child"], references: [root], deadline: TestFixtures.now)#expect(request.usage(from: [state(root)]) == nil)@@ -93,8 +93,8 @@ struct CodexActivityTokenUsageTests {defer { preferences.remove() }let monitor = try makeMonitor(directory: directory, preferences: preferences)let event = TestFixtures.event()- let key = CodexActivityTaskKey(event: event)- monitor.tasks[key] = CodexActivityTask(+ let key = ActivityTaskKey(event: event)+ monitor.tasks[key] = ActivityTask(displayID: UUID(), key: key, event: event, state: .running,latestEvent: .promptSubmitted, startedAt: TestFixtures.now, progressGeneration: 1)@@ -119,7 +119,7 @@ struct CodexActivityTokenUsageTests {#expect(monitor.completions.isEmpty)let task = try #require(monitor.tasks[key])- var transitions: [CodexActivityTransition] = []+ var transitions: [ActivityTransition] = []monitor.resolveTerminal(.completed(at: TestFixtures.now, duration: 1), task: task, key: key,abortFallback: TestFixtures.now, into: &transitions@@ -135,8 +135,8 @@ struct CodexActivityTokenUsageTests {defer { preferences.remove() }let monitor = try makeMonitor(directory: directory, preferences: preferences)let event = TestFixtures.event(turn: "turn-b")- let key = CodexActivityTaskKey(event: event)- monitor.tasks[key] = CodexActivityTask(+ let key = ActivityTaskKey(event: event)+ monitor.tasks[key] = ActivityTask(displayID: UUID(), key: key, event: event, state: .running,latestEvent: .promptSubmitted, startedAt: TestFixtures.now, progressGeneration: 1)@@ -152,13 +152,13 @@ struct CodexActivityTokenUsageTests {}@Test func overflowIsRejectedAndConfirmedZeroRemainsAvailable() {- let large = CodexTokenUsage(+ let large = TokenUsage(inputTokens: .max, cachedInputTokens: 0, cacheWriteInputTokens: 0,outputTokens: 0, reasoningOutputTokens: 0, totalTokens: .max)#expect(large.isValid)#expect(large.adding(large) == nil)- let zero = CodexTokenUsage(+ let zero = TokenUsage(inputTokens: 0, cachedInputTokens: 0, cacheWriteInputTokens: 0,outputTokens: 0, reasoningOutputTokens: 0, totalTokens: 0)@@ -173,20 +173,20 @@ struct CodexActivityTokenUsageTests {defer { preferences.remove() }let monitor = try makeMonitor(directory: directory, preferences: preferences)let event = TestFixtures.event()- let key = CodexActivityTaskKey(event: event)- let task = CodexActivityTask(+ let key = ActivityTaskKey(event: event)+ let task = ActivityTask(displayID: UUID(), key: key, event: event, state: .running,latestEvent: .promptSubmitted, startedAt: TestFixtures.now, progressGeneration: 1)- var transitions: [CodexActivityTransition] = []+ var transitions: [ActivityTransition] = []monitor.resolveTerminal(.completed(at: TestFixtures.now, duration: 1), task: task, key: key,abortFallback: TestFixtures.now, into: &transitions)let completedID = try #require(monitor.completions.first?.id)let otherEvent = TestFixtures.event(turn: "turn-b")- let otherKey = CodexActivityTaskKey(event: otherEvent)- monitor.tasks[otherKey] = CodexActivityTask(+ let otherKey = ActivityTaskKey(event: otherEvent)+ monitor.tasks[otherKey] = ActivityTask(displayID: UUID(), key: otherKey, event: otherEvent, state: .running,latestEvent: .promptSubmitted, startedAt: TestFixtures.now, progressGeneration: 1)@@ -227,23 +227,23 @@ struct CodexActivityTokenUsageTests {defer { preferences.remove() }let monitor = try makeMonitor(directory: directory, preferences: preferences)let first = TestFixtures.event()- let firstKey = CodexActivityTaskKey(event: first)- let task = CodexActivityTask(+ let firstKey = ActivityTaskKey(event: first)+ let task = ActivityTask(displayID: UUID(), key: firstKey, event: first, state: .running,latestEvent: .promptSubmitted, startedAt: TestFixtures.now, progressGeneration: 1)- var transitions: [CodexActivityTransition] = []+ var transitions: [ActivityTransition] = []monitor.resolveTerminal(.completed(at: TestFixtures.now, duration: 1), task: task, key: firstKey, abortFallback: TestFixtures.now, into: &transitions)let firstState = state(reference("session-a", "turn-a"))_ = monitor.applyTerminalTokenUsage([firstState])#expect(monitor.completions.first?.tokenUsage?.totalTokens == 110)let second = TestFixtures.event(at: TestFixtures.now.addingTimeInterval(2), turn: "turn-b")- let secondKey = CodexActivityTaskKey(event: second)- monitor.tasks[secondKey] = CodexActivityTask(+ let secondKey = ActivityTaskKey(event: second)+ monitor.tasks[secondKey] = ActivityTask(displayID: UUID(), key: secondKey, event: second, state: .running,latestEvent: .promptSubmitted, startedAt: second.timestamp, progressGeneration: 2)- let child = TestFixtures.event(.subagentStart, at: TestFixtures.now.addingTimeInterval(3), turn: "child-turn-b", agent: "child-b")+ let child = TestFixtures.event(.subagentStarted, at: TestFixtures.now.addingTimeInterval(3), turn: "child-turn-b", agent: "child-b")#expect(monitor.deferUnassociatedSubagentEvent(child, source: .live))_ = monitor.applyTerminalTokenUsage([firstState])#expect(monitor.completions.first?.tokenUsage?.totalTokens == 110)@@ -268,19 +268,19 @@ struct CodexActivityTokenUsageTests {defer { preferences.remove() }let monitor = try makeMonitor(directory: directory, preferences: preferences)monitor.isActivitySourceHealthy = true- monitor.isActivityProtectionRecoveryInProgress = false+ monitor.isProtectionRecoveryInProgress = falselet now = Date()monitor.sessionTransitionNotBefore = now.addingTimeInterval(-1)monitor.terminalPresentationNotBefore = now.addingTimeInterval(-1)#expect(monitor.canPublishActivityTransitions)for publishesEvents in [false, true] {let event = TestFixtures.event(at: now, turn: publishesEvents ? "live-turn" : "historical-turn")- let key = CodexActivityTaskKey(event: event)- let task = CodexActivityTask(+ let key = ActivityTaskKey(event: event)+ let task = ActivityTask(displayID: UUID(), key: key, event: event, state: .running,latestEvent: .promptSubmitted, startedAt: now, progressGeneration: 1)- var transitions: [CodexActivityTransition] = []+ var transitions: [ActivityTransition] = []monitor.resolveTerminal(aborted ? .aborted(at: now) : .completed(at: now, duration: 1),task: task, key: key, abortFallback: now, publishesEvents: publishesEvents, into: &transitions@@ -307,17 +307,17 @@ struct CodexActivityTokenUsageTests {defer { preferences.remove() }let monitor = try makeMonitor(directory: directory, preferences: preferences)monitor.isActivitySourceHealthy = true- monitor.isActivityProtectionRecoveryInProgress = false+ monitor.isProtectionRecoveryInProgress = falselet now = Date()monitor.sessionTransitionNotBefore = now.addingTimeInterval(-1)monitor.terminalPresentationNotBefore = now.addingTimeInterval(-1)- let event = TestFixtures.event(.interrupt, at: now, session: anonymous ? nil : "session-a")- let key = CodexActivityTaskKey(event: event)- let task = CodexActivityTask(+ let event = TestFixtures.event(.turnAborted, at: now, session: anonymous ? nil : "session-a")+ let key = ActivityTaskKey(event: event)+ let task = ActivityTask(displayID: UUID(), key: key, event: event, state: .running,latestEvent: .promptSubmitted, startedAt: now, progressGeneration: 1)- var transitions: [CodexActivityTransition] = []+ var transitions: [ActivityTransition] = []if interrupted {monitor.tasks[key] = taskmonitor.interruptTask(from: event, source: .live)@@ -338,43 +338,80 @@ struct CodexActivityTokenUsageTests {#expect(monitor.terminalTokenUsageRequests.count == (anonymous ? 0 : 1))}- private func reference(_ thread: String, _ turn: String) -> CodexActivityTurnReference {- CodexActivityTurnReference(threadID: thread, turnID: turn, startedAt: TestFixtures.now)+ private func reference(_ thread: String, _ turn: String) -> ActivityTurnReference {+ ActivityTurnReference(threadID: thread, turnID: turn, startedAt: TestFixtures.now)}- private func request(root: CodexActivityTurnReference, children: [CodexActivityTurnReference]) -> CodexTaskTokenUsageRequest {- CodexTaskTokenUsageRequest(+ private func request(root: ActivityTurnReference, children: [ActivityTurnReference]) -> TaskTokenRequest {+ TaskTokenRequest(root: root, expectedAgentIDs: Set(children.map(\.threadID)), references: Set([root] + children), deadline: TestFixtures.now)}private func state(- _ reference: CodexActivityTurnReference, input: Int64 = 100,- terminal: CodexSessionTaskTerminalState? = .completed(at: TestFixtures.now, duration: 1)- ) -> CodexSessionTaskLifecycleState {- CodexSessionTaskLifecycleState(+ _ reference: ActivityTurnReference, input: Int64 = 100,+ terminal: SessionTerminalState? = .completed(at: TestFixtures.now, duration: 1)+ ) -> SessionLifecycleState {+ SessionLifecycleState(requestedThreadID: reference.threadID, turnID: reference.turnID, startedAt: TestFixtures.now,approvalReviewer: nil, effort: nil, lastProgressAt: TestFixtures.now, terminal: terminal,rootTurnID: "turn-a", recordedThreadID: reference.threadID, rootSessionID: "session-a",- tokenUsage: CodexTokenUsage(+ tokenUsage: TokenUsage(inputTokens: input, cachedInputTokens: 20, cacheWriteInputTokens: 0,outputTokens: 10, reasoningOutputTokens: 2, totalTokens: input + 10))}- private func makeMonitor(directory: TestDirectory, preferences: TestPreferences) throws -> CodexActivityMonitor {- try CodexActivityMonitor(- advancedModeSettings: AdvancedModeSettings(- hooksURL: directory.url.appendingPathComponent("hooks.json"),- codexStatusService: makeStatusService(suiteName: preferences.suite)- ),- activityProtectionSettings: ActivityProtectionSettings(defaults: preferences.defaults),- activityProtectionStateStore: ActivityProtectionStateStore(directoryURL: directory.url)+ private func makeMonitor(directory: TestDirectory, preferences: TestPreferences) throws -> ActivityMonitor {+ try ActivityMonitor(+ protectionSettings: ProtectionSettings(defaults: preferences.defaults),+ protectionStore: ProtectionStore(directoryURL: directory.url))}- private nonisolated func makeStatusService(suiteName: String) throws -> CodexStatusService {- try CodexStatusService(defaults: #require(UserDefaults(suiteName: suiteName)))+ private nonisolated func makeStatusService(suiteName: String) -> CodexStatusService {+ CodexStatusService(socketURL: URL(fileURLWithPath: "/tmp/\(suiteName).sock"))+ }+}++extension ActivityTokenUsageTests {+ @Test func unknownCompletionTimeDoesNotInventDurationOrRepeatCompletion() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = try makeMonitor(directory: directory, preferences: preferences)+ let now = Date()+ let event = TestFixtures.event(at: now.addingTimeInterval(-60))+ let key = ActivityTaskKey(event: event)+ let task = ActivityTask(+ displayID: UUID(),+ key: key,+ event: event,+ state: .running,+ latestEvent: .promptSubmitted,+ startedAt: now.addingTimeInterval(-60),+ progressGeneration: 1+ )+ var transitions: [ActivityTransition] = []+ monitor.resolveTerminal(+ .completed(at: nil, duration: nil),+ task: task,+ key: key,+ abortFallback: now,+ publishesEvents: false,+ into: &transitions+ )+ monitor.resolveTerminal(+ .completed(at: now.addingTimeInterval(-10), duration: 10),+ task: task,+ key: key,+ abortFallback: now,+ into: &transitions+ )+ #expect(monitor.completions.count == 1)+ #expect(monitor.completions.first?.duration == nil)+ #expect(transitions.isEmpty)}}diff --git a/CodexBarTests/AppServerActivityTests.swift b/CodexBarTests/AppServerActivityTests.swiftnew file mode 100644index 0000000..a880fd9--- /dev/null+++ b/CodexBarTests/AppServerActivityTests.swift@@ -0,0 +1,487 @@+import Foundation+import Testing++struct AppServerActivityTests {+ private let now = TestFixtures.now++ private func thread(_ id: String = "main", source: String = #""cli""#) throws -> ActivityThread {+ try TestFixtures.decode(ActivityThread.self, """+ {"id":"\(id)","cwd":"/test","model":"gpt-5","reasoningEffort":"high","createdAt":\(now.timeIntervalSince1970),+ "status":{"type":"active","activeFlags":[]},"source":\(source)}+ """)+ }++ private func turn(_ id: String = "turn", status: String = "inProgress") -> ActivityTurn {+ ActivityTurn(id: id, status: status, startedAt: now.timeIntervalSince1970)+ }++ private func message(_ method: String, params: String, id: Int? = nil) throws -> ActivityNotification {+ let request = id.map { "\"id\":\($0)," } ?? ""+ return try TestFixtures.decode(ActivityNotification.self, "{\(request)\"method\":\"\(method)\",\"params\":\(params)}")+ }++ private func prepared() throws -> AppServerActivityReducer {+ var reducer = AppServerActivityReducer()+ _ = try reducer.reconcile(thread: thread(), turns: [turn()], reviewer: .user, now: now)+ return reducer+ }++ @Test(arguments: [+ "item/agentMessage/delta", "item/plan/delta", "item/reasoning/textDelta", "item/reasoning/summaryTextDelta",+ "item/commandExecution/outputDelta", "item/fileChange/outputDelta"+ ])+ func recognizedProgressOnlyRefreshesActivity(_ method: String) throws {+ var reducer = try prepared()+ _ = try reducer.consume(message("item/commandExecution/requestApproval", params: """+ {"threadId":"main","turnId":"turn","itemId":"command"}+ """, id: 1), now: now)+ _ = try reducer.consume(tokenMessage(total: 100), now: now)+ _ = try reducer.consume(tokenMessage(total: 110), now: now)+ let tokens = reducer.tokenTurns+ let later = now.addingTimeInterval(30)+ let events = try reducer.consume(message(method, params: """+ {"threadId":"main","turnId":"turn","itemId":"item","delta":"content"}+ """), now: later)+ let state = try #require(reducer.states.values.first)+ #expect(state.lastProgressAt == later)+ #expect(state.lastExecutionProgressAt == later)+ #expect(state.isWaitingApproval == true)+ #expect(state.approvalChangedAt == now)+ #expect(events.isEmpty)+ #expect(reducer.tokenTurns == tokens)+ #expect(state.tokenUsage?.totalTokens == 10)+ }++ @Test(arguments: [+ "item/future/delta", "item/future/outputDelta", "hook/delta", "command/exec/outputDelta",+ "process/outputDelta", "item/reasoning/textDelta/extra", "item/agentMessage/Delta"+ ])+ func unknownMethodsCannotRefreshActivity(_ method: String) throws {+ var reducer = try prepared()+ let events = try reducer.consume(message(method, params: """+ {"threadId":"main","turnId":"turn","delta":"content"}+ """), now: now.addingTimeInterval(30))+ let state = try #require(reducer.states.values.first)+ #expect(ActivityNotification.category(for: method) == .ignored)+ #expect(state.lastProgressAt == now)+ #expect(state.lastExecutionProgressAt == nil)+ #expect(events.isEmpty)+ #expect(reducer.tokenTurns.isEmpty)+ }++ @Test(arguments: ["agentMessage", "reasoning", "userMessage", "plan", "subAgentActivity"])+ func nonToolsNeverIncreaseToolCalls(_ type: String) throws {+ var reducer = try prepared()+ let events = try reducer.consume(message("item/completed", params: """+ {"threadId":"main","turnId":"turn","item":{"id":"item","type":"\(type)","kind":"interacted","agentThreadId":"child"}}+ """), now: now)+ #expect(events.isEmpty)+ }++ @Test(arguments: ["commandExecution", "fileChange", "webSearch", "imageView", "imageGeneration", "sleep", "mcpToolCall", "dynamicToolCall", "collabAgentToolCall"], [false, true])+ func toolStartAndEndPreserveOneInvocation(_ type: String, hasToolName: Bool) throws {+ var reducer = try prepared()+ let expectedTool = hasToolName && type != "commandExecution" ? "test" : nil+ let toolField = hasToolName ? #""tool":"test","# : ""+ let params = """+ {"threadId":"main","turnId":"turn","item":{"id":"item","type":"\(type)",\(toolField)"status":"completed"}}+ """+ let started = try reducer.consume(message("item/started", params: params), now: now)+ let ended = try reducer.consume(message("item/completed", params: params), now: now)+ #expect(started.first?.eventKind == .toolStarted)+ #expect(started.first?.source?.method == "item/started")+ #expect(started.first?.source?.threadID == "main")+ #expect(started.first?.source?.itemType == type)+ #expect(started.first?.tool == expectedTool)+ #expect(ended.first?.tool == expectedTool)+ #expect(ended.first?.eventKind == .toolCompleted)+ #expect(started.first?.name == "toolStarted")+ #expect(started.first?.id == "main:turn:item:toolStarted")+ #expect(ended.first?.name == "toolCompleted")+ #expect(ended.first?.id == "main:turn:item:toolCompleted")+ #expect(try reducer.consume(message("item/completed", params: params), now: now).isEmpty)+ var accumulator = ActivityAccumulator(rebuilding: CodexDateFormat.dayString(from: now), generationID: nil, generationStartedEmpty: true, eventCountAvailability: .all)+ for event in started + ended {+ accumulator.record(event)+ }+ #expect(accumulator.finalized(identifierStorage: .retained).metrics.toolCallCount == 1)+ let event = try #require(started.first)+ let data = try AppServerEventRecord(activity: event, recordedAt: now).jsonLineData()+ let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])+ let activity = try #require(object["activityPayload"] as? [String: Any])+ #expect(activity["tool"] as? String == expectedTool)+ #expect((object["source"] as? [String: Any])?["itemType"] as? String == type)+ let restored = try #require(AppServerEventRecord.decode(from: data).activity)+ var task = ActivityTask(+ displayID: UUID(), key: ActivityTaskKey(event: restored), event: restored,+ state: .running, latestEvent: .toolStarted, startedAt: now, progressGeneration: 0+ )+ #expect(task.snapshot.toolDisplayName == (expectedTool ?? type))+ #expect(ActivityDisplayFormat.eventText(for: task.snapshot).contains(expectedTool ?? type))+ try task.mergeMetadata(from: #require(ended.first))+ task.latestEvent = .toolFinished+ #expect(ActivityDisplayFormat.eventText(for: task.snapshot).contains(expectedTool ?? type))+ }++ @Test(arguments: ["item/started", "item/completed"])+ func commandActionsPreserveFirstOccurrenceOrderInDisplayedActivity(_ method: String) throws {+ var reducer = try prepared()+ let events = try reducer.consume(message(method, params: """+ {"threadId":"main","turnId":"turn","item":{"id":"command","type":"commandExecution","commandActions":[+ {"type":"search","command":"private command","query":"private query"},+ {"type":"unknown","command":"private command"},+ {"type":"read","name":"private file","path":"/private/file"},+ {"type":"search"},{"type":"listFiles"},{"type":"read"}+ ]}}+ """), now: now)+ let event = try #require(events.first)+ let data = try AppServerEventRecord(activity: event, recordedAt: now).jsonLineData()+ let storedText = try #require(String(data: data, encoding: .utf8))+ #expect(!storedText.contains("private"))+ let restored = try #require(AppServerEventRecord.decode(from: data).activity)+ let task = ActivityTask(+ displayID: UUID(), key: ActivityTaskKey(event: restored), event: restored,+ state: .running, latestEvent: method == "item/started" ? .toolStarted : .toolFinished,+ startedAt: now, progressGeneration: 0+ )+ #expect(task.snapshot.toolDisplayName == "search/read/listFiles")+ #expect(ActivityDisplayFormat.eventText(for: task.snapshot).contains("search/read/listFiles"))+ #expect(restored.source?.itemType == "commandExecution")+ #expect(restored.eventKind == (method == "item/started" ? .toolStarted : .toolCompleted))+ }++ @Test(arguments: ["", #", "commandActions":null"#, #", "commandActions":[]"#, #", "commandActions":[{"type":"unknown"},{"type":"unknown"}]"#])+ func commandWithoutKnownActionsFallsBackToItemType(_ actions: String) throws {+ var reducer = try prepared()+ let events = try reducer.consume(message("item/started", params: """+ {"threadId":"main","turnId":"turn","item":{"id":"command","type":"commandExecution"\(actions)}}+ """), now: now)+ let event = try #require(events.first)+ let task = ActivityTask(+ displayID: UUID(), key: ActivityTaskKey(event: event), event: event,+ state: .running, latestEvent: .toolStarted, startedAt: now, progressGeneration: 0+ )+ #expect(event.tool == nil)+ #expect(task.snapshot.toolDisplayName == "commandExecution")+ }++ @Test func commandActionsDoNotOverrideOtherToolNames() throws {+ var reducer = try prepared()+ let events = try reducer.consume(message("item/started", params: """+ {"threadId":"main","turnId":"turn","item":{"id":"tool","type":"mcpToolCall","tool":"actual_tool","commandActions":[{"type":"read"}]}}+ """), now: now)+ #expect(events.first?.tool == "actual_tool")+ }++ @Test func approvalResolutionDoesNotInventAnotherToolCall() throws {+ var reducer = try prepared()+ let events = try reducer.consume(message("item/commandExecution/requestApproval", params: """+ {"threadId":"main","turnId":"turn","itemId":"command"}+ """, id: 1), now: now)+ #expect(events.first?.eventKind == .approvalRequested)+ #expect(events.first?.source?.requestID != nil)+ #expect(events.first?.source?.itemID == "command")+ #expect(events.first?.source?.itemType == "commandExecution")+ #expect(events.first?.tool == nil)+ let key = ActivityTurnReference(threadID: "main", turnID: "turn", startedAt: now)+ #expect(reducer.states[key]?.isWaitingApproval == true)+ #expect(try reducer.consume(message("serverRequest/resolved", params: #"{"threadId":"main","requestId":1}"#), now: now).isEmpty)+ #expect(reducer.states[key]?.isWaitingApproval == false)+ }++ @Test func automaticReviewCountsRequestWithoutWaitingForUser() throws {+ var reducer = try prepared()+ let events = try reducer.consume(message("item/autoApprovalReview/started", params: """+ {"threadId":"main","turnId":"turn","targetItemId":"command","reviewId":"review"}+ """), now: now)+ #expect(events.first?.approvalReviewer == .autoReview)+ #expect(reducer.states.values.first?.isWaitingApproval != true)+ }++ @Test func snapshotWaitingDoesNotInventHistoricalApprovalCount() throws {+ var reducer = try prepared()+ let events = try reducer.consume(message("thread/status/changed", params: """+ {"threadId":"main","status":{"type":"active","activeFlags":["waitingOnApproval"]}}+ """), now: now)+ #expect(events.isEmpty)+ #expect(reducer.states.values.first?.isWaitingApproval == true)+ }++ @Test func detachedHistoryWithoutTerminalTimestampDoesNotEndLiveTask() throws {+ var reducer = try prepared()+ var detached = try thread()+ detached.status = ActivityThreadStatus(type: "notLoaded")+ _ = reducer.reconcile(thread: detached, turns: [turn(status: "interrupted")], reviewer: nil, now: now)+ #expect(reducer.states.values.first?.terminal == nil)+ #expect(reducer.states.values.first?.readStatus == .unavailable)+ }++ @Test func reconnectRestoresActiveSnapshotWithoutRecountingPrompt() throws {+ var reducer = try prepared()+ reducer.reconnect()+ let events = try reducer.reconcile(thread: thread(), turns: [turn()], reviewer: .user, now: now, bootstrap: true)+ #expect(events.count == 1)+ #expect(events.first?.timestamp == now)+ }++ @Test func compactionAndSubagentActivitiesRetainTheirOwnMeaning() throws {+ var reducer = try prepared()+ let compact = try reducer.consume(message("item/completed", params: """+ {"threadId":"main","turnId":"turn","item":{"id":"compact","type":"contextCompaction"}}+ """), now: now)+ #expect(compact.first?.eventKind == .compactionCompleted)+ let agent = try reducer.consume(message("item/completed", params: """+ {"threadId":"main","turnId":"turn","item":{"id":"spawn","type":"subAgentActivity","kind":"started","agentThreadId":"child"}}+ """), now: now)+ #expect(agent.first?.eventKind == .subagentStarted)+ #expect(agent.first?.tool == nil)+ }++ private func tokenMessage(total: Int) throws -> ActivityNotification {+ try message("thread/tokenUsage/updated", params: """+ {"threadId":"main","turnId":"turn","tokenUsage":{+ "total":{"inputTokens":\(total),"cachedInputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":\(total)},+ "last":{"inputTokens":10,"cachedInputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":10}}}+ """)+ }++ @Test func tokenTotalsUseDeltasAndReconnectDiscardsOfflineGap() throws {+ var reducer = try prepared()+ _ = try reducer.consume(tokenMessage(total: 1000), now: now)+ #expect(reducer.tokenTurns.isEmpty)+ _ = try reducer.consume(tokenMessage(total: 1100), now: now)+ #expect(reducer.tokenTurns.first?.usage?.totalTokens == 100)+ _ = try reducer.consume(tokenMessage(total: 1100), now: now)+ #expect(reducer.tokenTurns.first?.usage?.totalTokens == 100)+ reducer.reconnect()+ _ = try reducer.consume(tokenMessage(total: 5000), now: now)+ _ = try reducer.consume(tokenMessage(total: 5020), now: now)+ #expect(reducer.tokenTurns.first?.usage?.totalTokens == 120)+ }++ @Test func newThreadIncludesFirstResponseAndCounterResetDoesNotSubtractUsage() throws {+ var reducer = try prepared()+ reducer.markNewThread("main")+ _ = try reducer.consume(tokenMessage(total: 100), now: now)+ #expect(reducer.tokenTurns.first?.usage?.totalTokens == 100)+ _ = try reducer.consume(tokenMessage(total: 20), now: now)+ _ = try reducer.consume(tokenMessage(total: 30), now: now)+ #expect(reducer.tokenTurns.first?.usage?.totalTokens == 110)+ }++ @Test func eventRecorderDeduplicatesAcrossInstancesAndRestarts() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let first = ActivityRecorder(directoryURL: directory.url)+ let second = ActivityRecorder(directoryURL: directory.url)+ var reducer = try prepared()+ let events = try reducer.consume(message("item/started", params: """+ {"threadId":"main","turnId":"turn","item":{"id":"command","type":"commandExecution"}}+ """), now: now)+ let event = try #require(events.first)+ try await first.record(event: event)+ try await second.record(event: event)+ try await first.record(event: event)+ let url = directory.url.appendingPathComponent("Events/\(CodexDateFormat.dayString(from: now)).jsonl")+ var stored: [ActivityRecord] = []+ try AppServerEventJournal.read(at: url) {+ if let event = $0.activity {+ stored.append(event)+ }+ }+ #expect(stored.count == 1)+ }++ @Test func incrementalTokenStorageRetainsAllCountersAcrossRestart() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ let usage = TokenUsage(+ inputTokens: 100,+ cachedInputTokens: 50,+ cacheWriteInputTokens: 10,+ outputTokens: 20,+ reasoningOutputTokens: 5,+ totalTokens: 120+ )+ let record = TokenTurn(id: "one", rootID: "one", startedAt: now, updatedAt: now, usage: usage)+ try await store.record([record, record], now: now)+ let restarted = TokenHistoryStore(directoryURL: directory.url)+ let records = try await restarted.refresh(now: now)+ #expect(records.count == 1)+ #expect(records.first?.usage == usage)+ }++ @Test func tokenWriterLeaseTransfersWithoutTwoWriters() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let first = TokenHistoryStore(directoryURL: directory.url)+ let second = TokenHistoryStore(directoryURL: directory.url)+ #expect(try await first.acquireRecordingLease())+ #expect(try await !second.acquireRecordingLease())+ await first.releaseRecordingLease()+ #expect(try await second.acquireRecordingLease())+ await second.releaseRecordingLease()+ }++ @Test func rebuildUsesObservedRecordsAndContinuesCollecting() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ let usage = TokenUsage(+ inputTokens: 100,+ cachedInputTokens: 30,+ cacheWriteInputTokens: 10,+ outputTokens: 20,+ reasoningOutputTokens: 5,+ totalTokens: 120+ )+ let record = TokenTurn(id: "one", rootID: "one", startedAt: now, updatedAt: now)+ let first = TokenObservation(turn: record, rootStartedAt: now, streamID: "stream", sequence: 1, previous: .zero, current: usage)+ _ = try await store.recordObservations([first], now: now)+ let rebuilt = try await store.rebuild(for: [CodexDateFormat.dayString(from: now)], now: now.addingTimeInterval(1))+ #expect(rebuilt.turnCount == 1)+ let second = try TokenObservation(+ turn: record,+ rootStartedAt: now,+ streamID: "stream",+ sequence: 2,+ previous: usage,+ current: #require(usage.adding(usage))+ )+ _ = try await store.recordObservations([second], now: now.addingTimeInterval(2))+ let records = try await store.refresh(now: now.addingTimeInterval(2))+ #expect(records.first?.usage == usage.adding(usage))+ #expect(records.first?.rebuiltAt == now.addingTimeInterval(1))+ #expect(records.first?.generationID != "initial")+ }++ @Test func multipleApprovalRequestsResolveIndependently() throws {+ var reducer = try prepared()+ for id in [1, 2] {+ _ = try reducer.consume(message("item/commandExecution/requestApproval", params: """+ {"threadId":"main","turnId":"turn","itemId":"command-\(id)"}+ """, id: id), now: now)+ }+ _ = try reducer.consume(message("serverRequest/resolved", params: #"{"threadId":"main","requestId":1}"#), now: now)+ #expect(reducer.states.values.first?.isWaitingApproval == true)+ _ = try reducer.consume(message("serverRequest/resolved", params: #"{"threadId":"main","requestId":2}"#), now: now)+ #expect(reducer.states.values.first?.isWaitingApproval == false)+ }++ @Test func childKeepsItsOriginalRootAcrossParentTurns() throws {+ var reducer = try prepared()+ let child = try thread("child", source: #"{"subAgent":{"thread_spawn":{"parent_thread_id":"main"}}}"#)+ _ = reducer.reconcile(thread: child, turns: [turn("child-turn")], reviewer: .user, now: now)+ let next = ActivityTurn(id: "next", status: "inProgress", startedAt: now.addingTimeInterval(10).timeIntervalSince1970)+ _ = try reducer.reconcile(thread: thread(), turns: [next], reviewer: .user, now: now.addingTimeInterval(10))+ _ = reducer.reconcile(thread: child, turns: [turn("child-followup")], reviewer: .user, now: now.addingTimeInterval(11))+ let state = reducer.states[ActivityTurnReference(threadID: "child", turnID: "child-followup", startedAt: now)]+ #expect(state?.rootSessionID == "main")+ #expect(state?.rootTurnID == "turn")+ }++ @Test func settingsUpdateChangesMetadataWithoutInventingEvents() throws {+ var reducer = try prepared()+ let events = try reducer.consume(message("thread/settings/updated", params: """+ {"threadId":"main","threadSettings":{"model":"new-model","effort":"low","approvalsReviewer":"auto_review"}}+ """), now: now)+ #expect(events.isEmpty)+ var snapshot = try thread()+ snapshot.model = nil+ snapshot.reasoningEffort = nil+ _ = reducer.reconcile(thread: snapshot, turns: [turn()], reviewer: nil, now: now)+ let command = try reducer.consume(message("item/started", params: """+ {"threadId":"main","turnId":"turn","item":{"id":"command","type":"commandExecution"}}+ """), now: now)+ #expect(command.first?.model == "new-model")+ #expect(command.first?.effort == "low")+ #expect(command.first?.approvalReviewer == .autoReview)+ }++ @Test func missingFirstTurnUsageDoesNotMoveItsTokensIntoNextTurn() throws {+ var reducer = try prepared()+ reducer.markNewThread("main")+ _ = try reducer.consume(message("turn/completed", params: """+ {"threadId":"main","turn":{"id":"turn","status":"completed"}}+ """), now: now)+ _ = try reducer.consume(message("turn/started", params: """+ {"threadId":"main","turn":{"id":"next","status":"inProgress"}}+ """), now: now)+ let raw = """+ {"threadId":"main","turnId":"next","tokenUsage":{+ "total":{"inputTokens":500,"cachedInputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":500},+ "last":{"inputTokens":100,"cachedInputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":100}}}+ """+ _ = try reducer.consume(message("thread/tokenUsage/updated", params: raw), now: now)+ #expect(reducer.tokenTurns.isEmpty)+ }+}++extension AppServerActivityTests {+ @Test(arguments: ["completed", "failed", "interrupted"])+ func loadedTerminalWithoutTimestampEndsLiveTurn(status: String) throws {+ var reducer = try prepared()+ let idle = ActivityThread(id: "main", status: ActivityThreadStatus(type: "idle"))+ _ = reducer.reconcile(thread: idle, turns: [ActivityTurn(id: "turn", status: status)], reviewer: nil, now: now.addingTimeInterval(30))+ let state = try #require(reducer.states.values.first { $0.turnID == "turn" })+ #expect(state.terminal != nil)+ #expect(state.readStatus == .complete)+ #expect(state.isHistoricalTerminal)+ if case let .completed(at, duration) = state.terminal {+ #expect(at == nil)+ #expect(duration == nil)+ }+ }++ @Test func unknownTurnStatusNeverFabricatesCompletion() throws {+ var reducer = try prepared()+ let events = try reducer.consume(message("turn/completed", params: #"{"threadId":"main","turn":{"id":"turn","status":"futureStatus"}}"#), now: now)+ #expect(events.isEmpty)+ #expect(reducer.states.values.first?.terminal == nil)+ }+}++extension AppServerActivityTests {+ @Test func collectorContinuesFromCommittedCorrectionWithoutResettingServerCounter() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ var reducer = try prepared()+ reducer.markNewThread("main")+ _ = try reducer.consume(tokenMessage(total: 100), now: now)+ let committed = try await store.recordObservations(reducer.takeTokenObservations(), now: now)+ reducer.acceptTokenTurns(committed)+ var correction = try #require(committed.first { $0.usage != nil })+ correction.usage = TokenUsage(+ inputTokens: 60,+ cachedInputTokens: 0,+ cacheWriteInputTokens: 0,+ outputTokens: 0,+ reasoningOutputTokens: 0,+ totalTokens: 60+ )+ correction.startNewGeneration(at: now)+ try await store.record([correction], now: now)+ // 修正发生在采集器提交下一笔之前, 内存仍可能暂时持有旧累计值+ _ = try reducer.consume(tokenMessage(total: 110), now: now.addingTimeInterval(1))+ let result = try await store.recordObservations(reducer.takeTokenObservations(), now: now)+ reducer.acceptTokenTurns(result)+ #expect(reducer.tokenTurns.first?.usage?.totalTokens == 70)+ #expect(reducer.states.values.first?.tokenUsage?.totalTokens == 70)+ _ = try reducer.consume(tokenMessage(total: 120), now: now.addingTimeInterval(2))+ #expect(reducer.tokenTurns.first?.usage?.totalTokens == 80)+ }++ @Test func repeatedHistoricalTerminalKeepsObservationTimeAndNotificationPolicy() throws {+ var reducer = try prepared()+ let idle = ActivityThread(id: "main", status: ActivityThreadStatus(type: "idle"))+ let completed = ActivityTurn(id: "turn", status: "completed")+ _ = reducer.reconcile(thread: idle, turns: [completed], reviewer: nil, now: now)+ _ = reducer.reconcile(thread: idle, turns: [completed], reviewer: nil, now: now.addingTimeInterval(60))+ let state = try #require(reducer.states.values.first)+ #expect(state.terminalObservedAt == now)+ #expect(state.lastProgressAt == now)+ #expect(state.isHistoricalTerminal)+ }+}diff --git a/CodexBarTests/AppServerEventStorageTests.swift b/CodexBarTests/AppServerEventStorageTests.swiftnew file mode 100644index 0000000..8d39495--- /dev/null+++ b/CodexBarTests/AppServerEventStorageTests.swift@@ -0,0 +1,277 @@+import Darwin+import Foundation+import Testing++struct AppServerEventStorageTests {+ private let now = TestFixtures.now++ private func token(id: String = "root", root: String = "root", at date: Date? = nil, input: Int64 = 100) -> TokenTurn {+ TokenTurn(id: id, rootID: root, startedAt: date ?? now, updatedAt: date ?? now, usage: TokenUsage(+ inputTokens: input, cachedInputTokens: 20, cacheWriteInputTokens: 5,+ outputTokens: 10, reasoningOutputTokens: 2, totalTokens: input + 10+ ))+ }++ private func events(in directory: URL, date: Date? = nil) throws -> [AppServerEventRecord] {+ var records: [AppServerEventRecord] = []+ let url = HistoryStorage.eventLogURL(for: HistoryStorage.dateKey(for: date ?? now), in: HistoryStorage.eventsDirectoryURL(in: directory))+ try AppServerEventJournal.read(at: url) { records.append($0) }+ return records+ }++ @Test func mixedJournalPreservesEveryActivityMetricAndSkipsTokensWithoutCorruption() throws {+ let activity = ActivityEventKind.allCases.map { TestFixtures.event($0) }+ var before = ActivityAccumulator(rebuilding: HistoryStorage.dateKey(for: now), generationID: nil, generationStartedEmpty: true, eventCountAvailability: .all)+ var after = before+ var corrupt = 0+ for event in activity {+ before.record(event)+ let record = AppServerEventRecord(activity: event, recordedAt: now)+ corrupt += try HistoryService.decode(record.jsonLineData()) { after.record($0) }+ let token = AppServerEventRecord(token: token(), recordedAt: now)+ corrupt += try HistoryService.decode(token.jsonLineData()) { after.record($0) }+ }+ let expected = before.finalized(identifierStorage: .retained)+ let actual = after.finalized(identifierStorage: .retained)+ #expect(corrupt == 0)+ #expect(actual == expected)+ }++ @Test func nativeMetadataRoundTripsWithoutChangingBusinessIdentity() throws {+ var event = TestFixtures.event(.toolStarted, session: "root", turn: "child-turn", agent: "child", origin: .auxiliary)+ event.source = AppServerEventSource(+ method: "item/started", threadID: "child", turnID: "child-turn", parentThreadID: "parent",+ rootThreadID: "root", rootTurnID: "root-turn", itemID: "item", itemType: "commandExecution", itemStatus: "inProgress"+ )+ let record = AppServerEventRecord(activity: event, recordedAt: now)+ let decoded = try AppServerEventRecord.decode(from: record.jsonLineData())+ #expect(decoded.activity == event)+ #expect(decoded.source?.threadID == "child")+ #expect(decoded.activity?.sessionID == "root")+ let text = try #require(String(bytes: record.jsonLineData(), encoding: .utf8))+ #expect(text.contains("toolStarted"))+ #expect(!text.contains("PreToolUse"))+ #expect(!text.contains("commandLine"))+ }++ @Test func activityStorageSeparatesProtocolContextFromBusinessFields() throws {+ var event = TestFixtures.event(.approvalRequested, agent: "child", reviewer: .user)+ event.source = AppServerEventSource(+ method: "item/commandExecution/requestApproval", threadID: "child", turnID: "child-turn",+ parentThreadID: "parent", rootThreadID: "root", rootTurnID: "root-turn", itemID: "item",+ itemType: "commandExecution", itemStatus: "inProgress", agentThreadID: "child",+ itemKind: "started", requestID: "request", reviewID: "review", turnStatus: "inProgress",+ turnStartedAt: now, turnCompletedAt: now.addingTimeInterval(1), durationMs: 1000+ )+ let data = try AppServerEventRecord(activity: event, recordedAt: now).jsonLineData()+ let record = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])+ #expect(Set(record.keys) == ["version", "kind", "recordedAt", "source", "activityPayload"])+ let context = try #require(record["source"] as? [String: Any])+ #expect(Set(context.keys) == [+ "method", "threadID", "turnID", "parentThreadID", "rootThreadID",+ "rootTurnID", "itemID", "itemType", "itemStatus", "agentThreadID",+ "itemKind", "requestID", "reviewID", "turnStatus", "turnStartedAt", "turnCompletedAt", "durationMs"+ ])+ #expect(context["itemKind"] as? String == "started")+ #expect(context["durationMs"] as? Double == 1000)+ #expect(context["turnStartedAt"] as? Double == now.timeIntervalSince1970 * 1000)+ let payload = try #require(record["activityPayload"] as? [String: Any])+ #expect(Set(payload.keys) == [+ "timestamp", "name", "origin", "cwd", "tool", "model", "effort",+ "approvalReviewer", "sessionID", "turnID", "agentID"+ ])+ #expect(try AppServerEventRecord.decode(from: data).activity == event)+ }++ @Test func tokenStorageAndCheckpointsUsePropertyNamesAndPreserveAllCounters() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ var turn = token()+ turn.rebuiltAt = now+ try await store.record([turn], now: now)+ let data = try AppServerEventRecord(token: turn, recordedAt: now).jsonLineData()+ let record = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])+ #expect(Set(record.keys) == ["version", "kind", "recordedAt", "token"])+ let snapshot = try #require(record["token"] as? [String: Any])+ #expect(Set(snapshot.keys) == ["id", "rootID", "startedAt", "updatedAt", "rebuiltAt", "usage", "generationID", "ancestorIDs", "checkpoint", "hasConflict"])+ let counts = try #require(snapshot["usage"] as? [String: Int64])+ #expect(counts == ["inputTokens": 100, "cachedInputTokens": 20, "cacheWriteInputTokens": 5, "outputTokens": 10, "reasoningOutputTokens": 2, "totalTokens": 110])+ #expect(try AppServerEventRecord.decode(from: data).token == turn)+ _ = try await store.refresh(now: now)+ let cacheData = try Data(contentsOf: directory.url.appendingPathComponent("Aggregates/tokens.json"))+ let cache = try #require(JSONSerialization.jsonObject(with: cacheData) as? [String: Any])+ #expect(Set(cache.keys) == ["version", "turns", "files"])+ let checkpoints = try #require(cache["files"] as? [String: [String: Any]])+ let checkpoint = try #require(checkpoints[HistoryStorage.dateKey(for: now)])+ #expect(Set(checkpoint.keys) == ["size", "identifier", "modificationTime"])+ #expect(try await TokenHistoryStore(directoryURL: directory.url).refresh(now: now) == [turn])+ }++ @Test func unsupportedVersionAndMixedPayloadAreRejected() throws {+ let valid = try #require(String(bytes: AppServerEventRecord(token: token(), recordedAt: now).jsonLineData(), encoding: .utf8))+ let future = valid.replacingOccurrences(of: "\"version\":2", with: "\"version\":99")+ let mixed = valid.replacingOccurrences(of: "\"version\":2", with: "\"version\":2,\"activityPayload\":{}")+ for text in [future, mixed] {+ #expect(throws: (any Error).self) { try AppServerEventRecord.decode(from: Data(text.utf8)) }+ }+ }++ @Test func sharedJournalSurvivesRestartCacheDeletionAndDuplicateSnapshots() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let first = TokenHistoryStore(directoryURL: directory.url)+ let second = TokenHistoryStore(directoryURL: directory.url)+ try await first.record([token()], now: now)+ try await second.record([token()], now: now)+ #expect(try events(in: directory.url).count == 1)+ let update = token(at: now.addingTimeInterval(1), input: 200)+ try await second.record([update], now: now)+ #expect(try await first.refresh(now: now).first?.usage == update.usage)+ try FileManager.default.removeItem(at: directory.url.appendingPathComponent("Aggregates/tokens.json"))+ let restarted = TokenHistoryStore(directoryURL: directory.url)+ let restored = try await restarted.refresh(now: now)+ #expect(restored.count == 1)+ #expect(restored.first?.usage == update.usage)+ #expect(!FileManager.default.fileExists(atPath: directory.url.appendingPathComponent("Tokens").path))+ }++ @Test func submillisecondTimestampsRecoverExactlyFromJournal() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ let timestamp = now.addingTimeInterval(0.1234567)+ try await store.record([token(at: timestamp)], now: timestamp)+ _ = try await store.rebuild(for: [HistoryStorage.dateKey(for: timestamp)], now: timestamp.addingTimeInterval(0.0000456))+ let original = try await store.refresh(now: timestamp)+ try FileManager.default.removeItem(at: directory.url.appendingPathComponent("Aggregates/tokens.json"))+ let recovered = try await TokenHistoryStore(directoryURL: directory.url).refresh(now: timestamp)+ #expect(recovered == original)+ }++ @Test func timestampsUseIntegerMillisecondsAcrossJournalAndSyncCache() throws {+ let timestamp = now.addingTimeInterval(0.1234567)+ let expected = Int64(now.timeIntervalSince1970 * 1000) + 123+ var event = TestFixtures.event(.turnStarted)+ event.source = AppServerEventSource(+ method: "turn/started", threadID: "thread", turnStartedAt: timestamp,+ turnCompletedAt: timestamp, durationMs: 0.4567+ )+ let data = try AppServerEventRecord(activity: event, recordedAt: timestamp).jsonLineData()+ let text = try #require(String(data: data, encoding: .utf8))+ #expect(text.contains("\"recordedAt\":\(expected),"))+ #expect(text.contains("\"turnStartedAt\":\(expected)}"))+ let decoded = try AppServerEventRecord.decode(from: data)+ #expect(decoded.recordedAt == Date(timeIntervalSince1970: Double(expected) / 1000))+ #expect(decoded.source?.durationMs == 0.4567)++ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = directory.url.appendingPathComponent("cache.jsonl")+ let record = try ActivitySyncRecord(+ deviceID: "device", daily: ActivityAggregate(date: "2026-09-15", generationID: "source").syncedAggregate,+ updatedAt: timestamp, recordName: "device_2026-09-15_source"+ )+ try JSONFileStorage.save(record, to: url)+ let stored = try Data(contentsOf: url)+ let object = try #require(JSONSerialization.jsonObject(with: stored) as? [String: Any])+ #expect(object["updatedAt"] as? Int64 == expected)+ #expect((object["daily"] as? [String: Any])?["date"] as? String == "2026-09-15")+ let records = JSONLines.decode(ActivitySyncRecord.self, from: stored)+ #expect(records.first?.updatedAt == decoded.recordedAt)+ #expect(try JSONLines.stableEncoder.encode(#require(records.first)) == stored)++ var cache = TokenFileCache<[TokenTurn]>(url: directory.url.appendingPathComponent("tokens.json"))+ try cache.save([token(at: timestamp)])+ var reopened = TokenFileCache<[TokenTurn]>(url: cache.url)+ #expect(try reopened.load()?.first?.updatedAt == decoded.recordedAt)+ }++ @Test func sameMillisecondSameSizeRewriteIsReadAgain() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ try await store.record([token()], now: now)+ let url = HistoryStorage.eventLogURL(for: HistoryStorage.dateKey(for: now), in: HistoryStorage.eventsDirectoryURL(in: directory.url))+ let seconds = Int(now.timeIntervalSince1970)+ let firstTimes = [timespec(tv_sec: seconds, tv_nsec: 1000100), timespec(tv_sec: seconds, tv_nsec: 1000100)]+ #expect(utimensat(AT_FDCWD, url.path, firstTimes, 0) == 0)+ _ = try await store.refresh(now: now)+ let before = try #require(HistoryStorage.fileStat(at: url))+ let replacement = try AppServerEventRecord(token: token(input: 200), recordedAt: now).jsonLineData()+ #expect(UInt64(replacement.count) == before.size)+ let handle = try FileHandle(forWritingTo: url)+ try handle.write(contentsOf: replacement)+ try handle.close()+ let secondTimes = [timespec(tv_sec: seconds, tv_nsec: 1000900), timespec(tv_sec: seconds, tv_nsec: 1000900)]+ #expect(utimensat(AT_FDCWD, url.path, secondTimes, 0) == 0)+ let after = try #require(HistoryStorage.fileStat(at: url))+ #expect(before.modificationTime == after.modificationTime)+ #expect(before.modifiedAtNanoseconds != after.modifiedAtNanoseconds)+ #expect(try await store.refresh(now: now).first?.usage?.inputTokens == 200)+ #expect(try await TokenHistoryStore(directoryURL: directory.url).refresh(now: now).first?.usage?.inputTokens == 200)+ let cache = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: directory.url.appendingPathComponent("Aggregates/tokens.json"))) as? [String: Any])+ let checkpoints = try #require(cache["files"] as? [String: [String: Any]])+ #expect(checkpoints[HistoryStorage.dateKey(for: now)]?["modificationTime"] as? Int64 == after.modificationTime)+ }++ @Test func rebuildMarkerAlsoSurvivesDeletingAggregateCache() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ let value = token()+ let observation = try TokenObservation(+ turn: TokenTurn(id: value.id, rootID: value.rootID, startedAt: now, updatedAt: now),+ rootStartedAt: now,+ streamID: "stream",+ sequence: 1,+ previous: .zero,+ current: #require(value.usage)+ )+ _ = try await store.recordObservations([observation], now: now)+ let rebuiltAt = now.addingTimeInterval(1)+ _ = try await store.rebuild(for: [HistoryStorage.dateKey(for: now)], now: rebuiltAt)+ try FileManager.default.removeItem(at: directory.url.appendingPathComponent("Aggregates/tokens.json"))+ #expect(try await store.refresh(now: rebuiltAt).first?.rebuiltAt == rebuiltAt)+ }++ @Test func childAfterMidnightKeepsRootDateWhenAllCachesAreDeleted() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let start = try #require(CodexDateFormat.dayDate(from: "2026-09-15")).addingTimeInterval(86390)+ let next = start.addingTimeInterval(60)+ let store = TokenHistoryStore(directoryURL: directory.url)+ try await store.record([token(at: start)], now: start)+ try await store.record([token(id: "child", at: next, input: 200)], now: next)+ try FileManager.default.removeItem(at: directory.url.appendingPathComponent("Aggregates/tokens.json"))+ let restored = try await store.refresh(now: next)+ #expect(TokenTurn.dailyUsage(restored, now: next)["2026-09-15"]?.totalTokens == 320)+ #expect(TokenTurn.dailyUsage(restored, now: next).count == 1)+ }++ @Test func partialTailAndInterleavedActivityDoNotLoseTokensOrDefeatDeduplication() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let recorder = ActivityRecorder(directoryURL: directory.url)+ let store = TokenHistoryStore(directoryURL: directory.url)+ let event = ActivityRecord(+ timestamp: now, name: ActivityEventKind.toolStarted.rawValue, origin: .main,+ cwd: nil, tool: "Bash", model: "model", effort: nil,+ approvalReviewer: nil, sessionID: "thread", turnID: "turn", agentID: nil, id: "tool"+ )+ try await recorder.record(event: event)+ try await store.record([token()], now: now)+ let url = HistoryStorage.eventLogURL(for: HistoryStorage.dateKey(for: now), in: HistoryStorage.eventsDirectoryURL(in: directory.url))+ let handle = try FileHandle(forWritingTo: url)+ try handle.seekToEnd()+ try handle.write(contentsOf: Data("{\"partial\":".utf8))+ try handle.close()+ let updated = token(at: now.addingTimeInterval(1), input: 300)+ try await store.record([updated], now: now)+ try await recorder.record(event: event)+ let entries = try events(in: directory.url)+ #expect(entries.compactMap(\.activity).count == 1)+ #expect(entries.compactMap(\.token).count == 2)+ #expect(try await store.refresh(now: now).first?.usage == updated.usage)+ }+}diff --git a/CodexBarTests/AppServerLogTests.swift b/CodexBarTests/AppServerLogTests.swiftnew file mode 100644index 0000000..76436fa--- /dev/null+++ b/CodexBarTests/AppServerLogTests.swift@@ -0,0 +1,330 @@+import Foundation+import SQLite3+import Testing++struct AppServerLogTests {+ @Test func corruptPendingRowPreservesPagingAppendAndClear() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ let first = storage.beginRequest(method: "healthy", payload: "{}")+ storage.finishRequest(first, response: "ok")+ let broken = storage.beginRequest(method: "broken", payload: "{}")+ _ = try await storage.page()+ var database: OpaquePointer?+ #expect(sqlite3_open(directory.url.appendingPathComponent(AppServerLogStore.databaseName).path, &database) == SQLITE_OK)+ defer { sqlite3_close(database) }+ #expect(sqlite3_exec(database, "UPDATE entries SET payload = x'7B' WHERE id = '\(broken.uuidString)'", nil, nil, nil) == SQLITE_OK)+ let reopened = AppServerLogStore(directoryURL: directory.url)+ let page = try await reopened.page(limit: 1)+ #expect(page.entries.first?.id == broken)+ #expect(page.entries.first?.method == "log/corrupt")+ #expect(page.entries.first?.detail?.hasSuffix("{") == true)+ #expect(page.hasMore)+ let next = try await reopened.page(before: #require(page.entries.first?.position), limit: 1)+ #expect(next.entries.first?.id == first)+ #expect(!next.hasMore)+ reopened.recordFailure(message: "still writes")+ #expect(try await reopened.page().total == 3)+ let again = AppServerLogStore(directoryURL: directory.url)+ #expect(try await again.page().entries.first(where: { $0.id == broken })?.detail == page.entries.first?.detail)+ try await again.clear()+ #expect(try await again.page().total == 0)+ }++ @Test func persistsBeyondFiveHundredAndRestoresOriginalPayloads() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ for index in 0 ..< 625 {+ let id = storage.beginRequest(method: "probe/\(index)", payload: "{\"secret\":\"unchanged\",\"index\":\(index)}", connection: "activity")+ storage.finishRequest(id, response: " response \(index)\n")+ }+ let page = try await storage.page(limit: 100)+ #expect(page.total == 625)+ #expect(page.entries.count == 100)+ #expect(page.entries.first?.method == "probe/624")+ #expect(page.entries.first?.detail == " response 624\n")+ #expect(page.hasMore)+ let reopened = AppServerLogStore(directoryURL: directory.url)+ let restored = try await reopened.page(limit: 700)+ #expect(restored.total == 625)+ #expect(restored.entries.count == 625)+ #expect(restored.entries.first?.request == "{\"secret\":\"unchanged\",\"index\":624}")+ #expect(restored.entries.last?.method == "probe/0")+ #expect(restored.entries.allSatisfy { $0.status == .success && $0.connection == "activity" })+ }++ @Test func cursorRemainsStableWhileNewRequestsAndOldResponsesArrive() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ var ids: [UUID] = []+ for index in 0 ..< 12 {+ ids.append(storage.beginRequest(method: "probe/\(index)", payload: "{}"))+ }+ let first = try await storage.page(limit: 5)+ let cursor = try #require(first.entries.last?.position)+ storage.finishRequest(ids[0], response: "late")+ let newest = storage.beginRequest(method: "new", payload: "{}")+ let second = try await storage.page(before: cursor, limit: 5)+ let third = try await storage.page(before: #require(second.entries.last?.position), limit: 5)+ let historical = first.entries + second.entries + third.entries+ #expect(Set(historical.map(\.id)) == Set(ids))+ #expect(historical.count == 12)+ #expect(!third.hasMore)+ #expect(third.entries.last?.detail == "late")+ let changes = try await storage.changes(since: first.revision)+ #expect(Set(changes.entries.map(\.id)) == Set([ids[0], newest]))+ }++ @Test func clearDoesNotResurrectAnInflightRequestAndPersists() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ let pending = storage.beginRequest(method: "old", payload: "{}")+ let before = try await storage.page()+ try await storage.clear()+ storage.finishRequest(pending, response: "late response")+ let new = storage.beginRequest(method: "new", payload: "{}")+ storage.finishRequest(new, response: "done")+ let after = try await storage.page()+ #expect(after.total == 1)+ #expect(after.entries.first?.id == new)+ #expect(after.generation > before.generation)+ #expect(after.entries.first?.position ?? 0 > before.entries.first?.position ?? 0)+ let reopened = AppServerLogStore(directoryURL: directory.url)+ #expect(try await reopened.page().entries.map(\.id) == [new])+ }++ @Test func unfinishedPreviousRunIsNotShownAsWaitingForever() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ var writer: AppServerLogStore? = AppServerLogStore(directoryURL: directory.url)+ let id = try #require(writer).beginRequest(method: "unfinished", payload: "{}")+ _ = try await writer?.page()+ writer = nil+ let reopened = AppServerLogStore(directoryURL: directory.url)+ let entry = try #require(try await reopened.page().entries.first)+ #expect(entry.id == id)+ #expect(entry.status == .failure)+ #expect(entry.respondedAt == nil)+ #expect(entry.request == "{}")+ #expect(entry.detail != nil)+ }++ @Test func viewMergesLiveUpdatesWithoutDroppingLoadedHistory() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ var ids: [UUID] = []+ for index in 0 ..< 9 {+ ids.append(storage.beginRequest(method: "probe/\(index)", payload: "{}"))+ }+ let store = AppServerLogViewModel(storage: storage, pageSize: 3)+ await store.refresh()+ #expect(store.entries.count == 3)+ #expect(store.totalCount == 9)+ await store.loadMore()+ let position = store.entries.last?.position+ storage.finishRequest(ids[3], response: "updated")+ let new = storage.beginRequest(method: "new", payload: "{}")+ await store.refresh()+ #expect(store.entries.count == 7)+ #expect(store.entries.first?.id == new)+ #expect(store.entries.last?.position == position)+ #expect(store.entries.last?.detail == "updated")+ await store.loadMore()+ #expect(store.entries.count == 10)+ #expect(Set(store.entries.map(\.id)).count == 10)+ #expect(!store.hasMore)+ await store.clear()+ #expect(store.entries.isEmpty)+ #expect(store.totalCount == 0)+ storage.recordFailure(message: "new failure")+ await store.refresh()+ #expect(store.entries.count == 1)+ }++ @Test func closedWindowCanReloadFromDiskWithBoundedInitialRead() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ for _ in 0 ..< 10 {+ storage.recordFailure(message: "failure")+ }+ let store = AppServerLogViewModel(storage: storage, pageSize: 3)+ await store.refresh()+ await store.loadMore()+ #expect(store.entries.count == 6)+ store.stop()+ #expect(store.entries.isEmpty)+ storage.recordFailure(message: "closed-window failure")+ await store.refresh()+ #expect(store.entries.count == 3)+ #expect(store.totalCount == 11)+ #expect(store.entries.first?.detail == "closed-window failure")+ }++ @Test func terminationDrainsQueuedWritesAndRejectsLateCallbacks() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ let id = storage.beginRequest(method: "last", payload: "{}")+ storage.finishRequest(id, response: "saved")+ try await storage.finish()+ storage.recordFailure(message: "after shutdown")+ let reopened = AppServerLogStore(directoryURL: directory.url)+ let page = try await reopened.page()+ #expect(page.total == 1)+ #expect(page.entries.first?.detail == "saved")+ }++ @Test func storageFailureIsVisibleAndDoesNotBreakRequestRecordingCallers() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let file = try directory.write("not a directory", to: "blocked")+ let storage = AppServerLogStore(directoryURL: file)+ storage.recordFailure(message: "recording remains nonthrowing")+ let store = AppServerLogViewModel(storage: storage)+ await store.refresh()+ #expect(store.errorMessage != nil)+ #expect(store.entries.isEmpty)+ }+}++extension AppServerLogTests {+ @Test func retentionPrunesOldPendingRequestsAndLateRepliesStayDeleted() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url, limits: .init(entries: 10))+ let first = storage.beginRequest(method: "old", payload: "{}")+ let initial = try await storage.page()+ for index in 0 ..< 40 {+ storage.recordFailure(message: "failure-\(index)")+ }+ let retained = try await storage.page()+ #expect(retained.total <= 10)+ #expect(retained.entries.first?.detail == "failure-39")+ #expect(!retained.entries.contains { $0.id == first })+ #expect(retained.generation > initial.generation)+ storage.finishRequest(first, response: "late")+ #expect(try await storage.page().total == retained.total)+ }++ @Test func byteLimitAndUnicodeBodyTruncationAreBoundedAcrossReopen() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let limits = AppServerLogStore.Limits(entries: 100, bytes: 4096, bodyBytes: 256, pageEntries: 10)+ let storage = AppServerLogStore(directoryURL: directory.url, limits: limits)+ let text = String(repeating: "你好🙂", count: 300)+ for index in 0 ..< 30 {+ let id = storage.beginRequest(method: "large-\(index)", payload: text)+ _ = try await storage.page()+ storage.finishRequest(id, response: text)+ _ = try await storage.page()+ }+ let page = try await storage.page(limit: 100)+ #expect(page.total < 30)+ #expect(page.entries.count <= 10)+ for entry in page.entries {+ #expect(entry.requestOriginalBytes == text.utf8.count)+ #expect(entry.detailOriginalBytes == text.utf8.count)+ #expect((entry.request?.utf8.count ?? 0) <= 256)+ #expect((entry.detail?.utf8.count ?? 0) <= 256)+ #expect(entry.request?.contains("Truncated") == true)+ #expect(entry.request?.contains("�") == false)+ }+ try await storage.finish()+ let reopened = AppServerLogStore(directoryURL: directory.url, limits: limits)+ #expect(try await reopened.page().total == page.total)+ let size = try directory.url.appendingPathComponent(AppServerLogStore.databaseName)+ .resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0+ #expect(size < 128 * 1024)+ }++ @Test func changeOverflowReloadsAndHistoryWindowRemainsBounded() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url, limits: .init(pageEntries: 5))+ let model = AppServerLogViewModel(storage: storage, pageSize: 3, maximumEntries: 6)+ await model.refresh()+ for index in 0 ..< 20 {+ storage.recordFailure(message: "entry-\(index)")+ }+ await model.refresh()+ #expect(model.entries.count == 3)+ #expect(model.entries.first?.detail == "entry-19")+ var visited = Set(model.entries.map(\.id))+ while model.hasMore {+ await model.loadMore()+ #expect(model.entries.count <= 6)+ visited.formUnion(model.entries.map(\.id))+ }+ #expect(visited.count == 20)+ #expect(model.browsingHistory)+ storage.recordFailure(message: "latest")+ await model.refresh()+ #expect(model.entries.count <= 6)+ await model.showLatest()+ #expect(!model.browsingHistory)+ #expect(model.entries.first?.detail == "latest")+ }+}++extension AppServerLogTests {+ @Test func requestSourceSurvivesBothSuccessfulAndFailedCompletion() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ let success = storage.beginRequest(method: "success", payload: "{}")+ let failure = storage.beginRequest(method: "failure", payload: "{}")+ let pending = try await storage.page().entries+ #expect(pending.allSatisfy { $0.source == .request && $0.status == .pending })+ storage.finishRequest(success, response: "{}")+ storage.failRequest(failure, message: "timeout")+ let completed = try await storage.page().entries+ #expect(completed.count == 2)+ #expect(completed.allSatisfy { $0.source == .request })+ #expect(completed.first { $0.id == success }?.status == .success)+ #expect(completed.first { $0.id == failure }?.status == .failure)+ }++ @Test func messageDirectionAndLocalErrorsHaveIndependentStatuses() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ storage.recordSent(method: "initialized", payload: "{}")+ storage.recordSent(method: "websocket/pong", payload: "ping", error: "disconnected")+ storage.recordReceived(method: "turn/completed", payload: #"{"status":"failed"}"#, connection: "activity")+ storage.recordFailure(method: "activity/storage", message: "disk full")+ let entries = try await storage.page().entries+ #expect(entries.first { $0.method == "initialized" }?.source == .sent)+ #expect(entries.first { $0.method == "initialized" }?.status == .success)+ #expect(entries.first { $0.method == "websocket/pong" }?.source == .sent)+ #expect(entries.first { $0.method == "websocket/pong" }?.status == .failure)+ #expect(entries.first { $0.method == "turn/completed" }?.source == .received)+ #expect(entries.first { $0.method == "turn/completed" }?.status == .information)+ #expect(entries.first { $0.method == "activity/storage" }?.source == .local)+ #expect(entries.first { $0.method == "activity/storage" }?.status == .failure)+ }++ @Test func connectionAttemptFinishesInPlaceAndClosedConnectionIsInformational() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ let attempt = storage.recordConnection(method: "connection/open", detail: "socket", connection: "activity", status: .pending)+ #expect(try await storage.page().entries.first?.status == .pending)+ storage.finishRequest(attempt, response: "socket")+ let handshake = storage.beginRequest(method: "websocket/handshake", payload: "GET /", source: .connection)+ storage.failRequest(handshake, message: "handshake failed")+ storage.recordConnection(method: "connection/closed", detail: "socket", connection: "activity", status: .information)+ let entries = try await storage.page().entries+ #expect(entries.allSatisfy { $0.source == .connection })+ #expect(entries.first { $0.id == attempt }?.status == .success)+ #expect(entries.first { $0.id == handshake }?.status == .failure)+ #expect(entries.first { $0.method == "connection/closed" }?.status == .information)+ let reopened = AppServerLogStore(directoryURL: directory.url)+ #expect(try await reopened.page().entries == entries)+ }+}diff --git a/CodexBarTests/AppServerRPCTests.swift b/CodexBarTests/AppServerRPCTests.swiftnew file mode 100644index 0000000..1af33d6--- /dev/null+++ b/CodexBarTests/AppServerRPCTests.swift@@ -0,0 +1,55 @@+import Foundation+import Testing++struct AppServerRPCTests {+ @Test(arguments: [-32601, -32602, -32600, -32700])+ func rpcCodesWorkWithoutEnglishErrorMessages(_ code: Int) throws {+ let data = try JSONSerialization.data(withJSONObject: ["id": 1, "error": ["code": code, "message": "本地化错误", "data": ["field": "test"]]])+ do {+ let _: [String: Int] = try AppServerRPC.decode(data, as: [String: Int].self)+ Issue.record("Expected RPC error")+ } catch let error as CodexStatusError {+ guard case let .serverError(detail) = error else { Issue.record("Lost RPC error")+ return+ }+ #expect(detail.code == code)+ #expect(detail.message == "本地化错误")+ let value = try JSONSerialization.jsonObject(with: #require(detail.data)) as? [String: String]+ #expect(value == ["field": "test"])+ #expect(!error.isRetriableServerError)+ #expect(code == -32601 ? error.isUnsupportedMethod : error.isProtocolOrParameterFailure)+ }+ #expect(!AppServerRPC.permitsRetry("config/value/write"))+ }++ @Test func missingRolloutClassificationRequiresExactThreadAndError() {+ let missing = CodexStatusError.serverError(AppServerRPCError(+ code: -32600, message: "no rollout found for thread id thread-a", data: nil+ ))+ #expect(missing.isMissingRollout(for: "thread-a"))+ #expect(!missing.isMissingRollout(for: "thread-b"))+ #expect(missing.isProtocolOrParameterFailure)+ for code in [-32700, -32602, -32603] {+ let error = CodexStatusError.serverError(AppServerRPCError(+ code: code, message: "no rollout found for thread id thread-a", data: nil+ ))+ #expect(!error.isMissingRollout(for: "thread-a"))+ }+ let invalid = CodexStatusError.serverError(AppServerRPCError(code: -32600, message: "invalid request", data: nil))+ #expect(!invalid.isMissingRollout(for: "thread-a"))+ #expect(invalid.isProtocolOrParameterFailure)+ #expect(!CodexStatusError.serverConnectionClosed.isMissingRollout(for: "thread-a"))+ #expect(!CodexStatusError.invalidResponsePayload.isMissingRollout(for: "thread-a"))+ }++ @Test func rpcMalformedEnvelopeAndPayloadHaveDifferentBoundaries() {+ #expect(throws: CodexStatusError.self) {+ let _: Int = try AppServerRPC.decode(Data(#"{"error":{},"result":3}"#.utf8), as: Int.self)+ }+ do {+ let _: Int = try AppServerRPC.decode(Data(#"{"result":"wrong"}"#.utf8), as: Int.self)+ } catch let error as CodexStatusError {+ #expect(!error.isTransportFailure)+ } catch { Issue.record(error) }+ }+}diff --git a/CodexBarTests/AppServerSessionTests.swift b/CodexBarTests/AppServerSessionTests.swiftnew file mode 100644index 0000000..c4a21a3--- /dev/null+++ b/CodexBarTests/AppServerSessionTests.swift@@ -0,0 +1,389 @@+import CryptoKit+import Darwin+import Foundation+import Testing++struct AppServerSessionTests {+ @Test(arguments: [true, false])+ func activityReaderValidatesVersionAndReusesConnection(_ supported: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let releaseServer = DispatchSemaphore(value: 0)+ defer { releaseServer.signal() }+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ #expect(initialize["method"] as? String == "initialize")+ try peer.reply(to: initialize, result: ["userAgent": supported ? "codex/0.160.0" : "codex/0.159.0"])+ if supported {+ #expect(try peer.readMessage()["method"] as? String == "initialized")+ for _ in 0 ..< 4 {+ let loaded = try peer.readMessage()+ #expect(loaded["method"] as? String == "thread/loaded/list")+ // 未知增量不能因业务载荷不兼容导致重连+ for method in ["item/future/delta", "item/future/outputDelta", "hook/delta"] {+ try peer.send(["method": method, "params": ["threadId": 123, "turn": false]])+ }+ try peer.reply(to: loaded, result: ["data": []])+ }+ #expect(releaseServer.wait(timeout: .now() + 5) == .success)+ }+ }+ defer { server.close() }+ var disconnected = false+ var bootstrapped = false+ let reader = AppServerActivityReader(+ lifecycleCache: SessionLifecycleCache(), socketURL: server.url,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url),+ recorder: ActivityRecorder(directoryURL: directory.url)+ ) { batch in+ switch batch {+ case .sourceUnavailable:+ disconnected = true+ case .bootstrapEnd:+ bootstrapped = true+ default:+ break+ }+ }+ await reader.start()+ for _ in 0 ..< 100 {+ if supported ? bootstrapped : disconnected {+ break+ }+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(disconnected != supported)+ if supported {+ #expect(bootstrapped)+ for _ in 0 ..< 3 {+ #expect(await reader.drainNow() == .completed)+ }+ #expect(!disconnected)+ } else {+ #expect(!bootstrapped)+ #expect(disconnected)+ }+ await reader.stop()+ releaseServer.signal()+ try server.finish()+ }++ @Test(arguments: [true, false])+ func logsOnlyConsumedPushesWithoutChangingNotificationDelivery(_ interleaved: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ let filtered = try unusedNotifications()+ var retained = try [+ "thread/started", "thread/status/changed", "thread/settings/updated", "turn/started", "turn/completed",+ "item/autoApprovalReview/started", "serverRequest/resolved", "error", "warning"+ ].map { try notification($0, params: ["marker": $0]) }+ for count in 1 ... 3 {+ try retained.append(notification("thread/tokenUsage/updated", params: ["total": count]))+ }+ for type in [+ "commandExecution",+ "fileChange",+ "webSearch",+ "imageView",+ "imageGeneration",+ "sleep",+ "mcpToolCall",+ "dynamicToolCall",+ "collabAgentToolCall",+ "contextCompaction",+ "subAgentActivity"+ ] {+ for method in ["item/started", "item/completed"] {+ try retained.append(notification(method, params: ["item": ["type": type, "id": type, "output": "full output"]]))+ }+ }+ for method in ["item/commandExecution/requestApproval", "item/fileChange/requestApproval", "item/permissions/requestApproval"] {+ try retained.append(JSONSerialization.data(withJSONObject: [+ "id": "approval", "method": method, "params": ["command": "original"]+ ]))+ }+ try retained.append(notification("item/completed", params: ["item": ["id": "malformed", "type": 123]]))+ let messages = filtered + retained+ let server = try SharedServerFixture { peer in+ let request = try peer.readMessage()+ if interleaved {+ for message in messages {+ try peer.sendRaw(message)+ }+ }+ try peer.reply(to: request, result: ["value": 7])+ if !interleaved {+ for message in messages {+ try peer.sendRaw(message)+ }+ }+ let done = try peer.readMessage()+ try peer.reply(to: done, result: ["value": 8])+ }+ defer { server.close() }+ let session = try AppServerSession(socketURL: server.url, logStorage: storage)+ defer { session.close() }+ let response: Value = try session.request("probe")+ #expect(response.value == 7)+ for message in messages {+ #expect(try session.nextEvent() == message)+ }+ let _: Value = try session.request("done")+ session.close()+ try server.finish()+ let page = try await storage.page(limit: 200)+ for message in filtered {+ #expect(!page.entries.contains { $0.detail == String(data: message, encoding: .utf8) })+ }+ for message in retained {+ #expect(page.entries.filter { $0.detail == String(data: message, encoding: .utf8) }.count == 1)+ }+ #expect(page.entries.filter { $0.method == "thread/tokenUsage/updated" }.count == 3)+ #expect(page.entries.first { $0.method == "probe" }?.status == .success)+ #expect(page.entries.contains { $0.method == "connection/closed" })+ let reopened = AppServerLogStore(directoryURL: directory.url)+ #expect(try await reopened.page(limit: 200).entries == page.entries)+ }++ private func notification(_ method: String, params: [String: Any]) throws -> Data {+ try JSONSerialization.data(withJSONObject: ["method": method, "params": params])+ }++ private func unusedNotifications() throws -> [Data] {+ var messages: [Data] = []+ for method in [+ "hook/started", "hook/completed", "hook/futureEvent", "account/updated", "account/rateLimits/updated",+ "mcpServer/startupStatus/updated", "remoteControl/status/changed", "thread/goal/cleared",+ "thread/name/updated", "item/autoApprovalReview/completed", "future/tool/delta"+ ] {+ try messages.append(notification(method, params: ["marker": method]))+ }+ for method in ["hook/started", "item/tool/call", "item/tool/requestUserInput", "mcpServer/elicitation/request"] {+ try messages.append(JSONSerialization.data(withJSONObject: ["id": "unused", "method": method, "params": [:]]))+ }+ try messages.append(notification("item/agentMessage/delta", params: ["delta": 123]))+ for method in [+ "item/agentMessage/delta",+ "item/plan/delta",+ "item/reasoning/summaryTextDelta",+ "item/reasoning/textDelta",+ "item/commandExecution/outputDelta",+ "item/fileChange/outputDelta"+ ] {+ try messages.append(notification(method, params: [+ "threadId": "thread", "turnId": "turn", "itemId": "item", "delta": "original fragment", "summaryIndex": 0, "contentIndex": 0+ ]))+ }+ for method in ["command/exec/outputDelta", "process/outputDelta", "item/future/delta", "item/future/outputDelta", "hook/delta"] {+ try messages.append(notification(method, params: ["deltaBase64": "dGVzdA==", "stream": "stdout"]))+ }+ try messages.append(notification("item/reasoning/summaryPartAdded", params: ["summaryIndex": 0]))+ try messages.append(notification("turn/diff/updated", params: ["diff": "patch"]))+ try messages.append(notification("turn/plan/updated", params: ["plan": [["step": "test", "status": "pending"]]]))+ try messages.append(notification("item/mcpToolCall/progress", params: ["message": "working"]))+ for type in ["userMessage", "agentMessage", "reasoning", "plan", "hookPrompt", "functionCallOutput", "enteredReviewMode", "exitedReviewMode", "futureItem"] {+ for method in ["item/started", "item/completed"] {+ try messages.append(notification(method, params: ["item": ["id": type, "type": type, "text": "body"]]))+ }+ }+ return messages+ }++ @Test func accountHandshakeUsesSharedSocketAndLeavesServerAvailable() throws {+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ #expect(initialize["method"] as? String == "initialize")+ #expect((initialize["params"] as? [String: Any])?["capabilities"] as? [String: Bool] == ["experimentalApi": true])+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.160.0"])+ #expect(try peer.readMessage()["method"] as? String == "initialized")+ let account = try peer.readMessage()+ #expect(account["method"] as? String == "account/read")+ #expect((account["params"] as? [String: Any])?["refreshToken"] as? Bool == false)+ try peer.reply(to: account, result: ["account": ["type": "apiKey"]])+ }+ defer { server.close() }+ let session = try AccountSession(socketURL: server.url, logStorage: nil)+ let result = try session.initializeAccount()+ #expect(result.version == "0.160.0")+ #expect(result.account.account != nil)+ session.close()+ #expect(!session.isOpen)+ try server.finish()+ #expect(FileManager.default.fileExists(atPath: server.url.path))+ }++ @Test func accountMatchesResponseAfterNotificationAndPreservesPayloadErrorBoundary() throws {+ let server = try SharedServerFixture { peer in+ let first = try peer.readMessage()+ try peer.send(["method": "thread/tokenUsage/updated", "params": [:]])+ try peer.reply(to: first, result: ["value": "invalid"])+ let second = try peer.readMessage()+ try peer.reply(to: second, result: ["value": 42])+ }+ defer { server.close() }+ let session = try AccountSession(socketURL: server.url, logStorage: nil)+ defer { session.close() }+ do {+ _ = try session.request("probe", as: Value.self)+ Issue.record("Expected a payload error")+ } catch let error as CodexStatusError {+ #expect(!error.isTransportFailure)+ if case .invalidResponsePayload = error {} else {+ Issue.record("Wrong error: \(error)")+ }+ }+ #expect(session.isOpen)+ let value = try session.request("probe", as: Value.self)+ #expect(value.value == 42)+ try server.finish()+ }++ @Test func activityRetainsInterleavedApprovalWithoutAnsweringIt() throws {+ let server = try SharedServerFixture { peer in+ let request = try peer.readMessage()+ try peer.send(["id": "approval", "method": "item/commandExecution/requestApproval", "params": [:]])+ try peer.reply(to: request, result: ["value": 7])+ let next = try peer.readMessage()+ #expect(next["method"] as? String == "probe")+ try peer.reply(to: next, result: ["value": 8])+ }+ defer { server.close() }+ let session = try AppServerSession(socketURL: server.url, logStorage: nil)+ defer { session.close() }+ let first: Value = try session.request("probe")+ #expect(first.value == 7)+ let event = try #require(try session.nextEvent())+ let object = try #require(JSONSerialization.jsonObject(with: event) as? [String: Any])+ #expect(object["id"] as? String == "approval")+ let second: Value = try session.request("probe")+ #expect(second.value == 8)+ try server.finish()+ }++ @Test func missingSharedSocketFailsWithoutFallback() throws {+ let url = URL(fileURLWithPath: "/tmp/\(UUID().uuidString).sock")+ #expect(throws: CodexStatusError.self) {+ _ = try AccountSession(socketURL: url, logStorage: nil)+ }+ #expect(!FileManager.default.fileExists(atPath: url.path))+ }++ @Test func disconnectedServerClosesAccountTransport() throws {+ let server = try SharedServerFixture { peer in+ _ = try peer.readMessage()+ }+ defer { server.close() }+ let session = try AccountSession(socketURL: server.url, logStorage: nil)+ #expect(throws: CodexStatusError.self) {+ _ = try session.request("probe", as: Value.self)+ }+ #expect(!session.isOpen)+ try server.finish()+ }++ @Test(arguments: ["account", "activity"])+ func bothConnectionsPersistFullWireRequestAndError(_ connection: String) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ let server = try SharedServerFixture { peer in+ let request = try peer.readMessage()+ try peer.send(["id": #require(request["id"]), "error": ["message": "body and secret", "code": -1]])+ }+ defer { server.close() }+ let session = try AppServerSession(socketURL: server.url, logStorage: storage, connectionName: connection)+ defer { session.close() }+ #expect(throws: CodexStatusError.self) {+ let _: Value = try session.request("probe", params: ["text": "original body", "apiKey": "original secret"])+ }+ try server.finish()+ let page = try await storage.page()+ #expect(page.entries.filter { $0.method == "websocket/handshake" }.count == 1)+ #expect(page.entries.filter { $0.method == "probe" }.count == 1)+ let entry = try #require(page.entries.first { $0.method == "probe" })+ #expect(entry.connection == connection)+ #expect(entry.status == .failure)+ #expect(entry.request?.contains("original body") == true)+ #expect(entry.request?.contains("original secret") == true)+ #expect(entry.detail?.contains("body and secret") == true)+ }++ @Test(arguments: [true, false])+ func logsPushesApprovalsAndControlFramesOnceBeforeRouting(_ retainsNotifications: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ let server = try SharedServerFixture { peer in+ let request = try peer.readMessage()+ try peer.send(["method": "thread/tokenUsage/updated", "params": ["token": 123]])+ try peer.send(["id": #require(request["id"]), "method": "item/commandExecution/requestApproval", "params": ["command": "original"]])+ try peer.sendRaw(Data([0xFF, 0x00]), opcode: 9)+ #expect(try peer.readPayload(opcode: 10) == Data([0xFF, 0x00]))+ try peer.send(["id": 999, "result": ["unmatched": true]])+ try peer.reply(to: request, result: ["value": 7])+ try peer.send(["method": "item/completed", "params": ["text": "full content"]])+ let next = try peer.readMessage()+ #expect(next["method"] as? String == "done")+ try peer.reply(to: next, result: ["value": 8])+ }+ defer { server.close() }+ let session = try AppServerSession(socketURL: server.url, retainsNotifications: retainsNotifications, logStorage: storage)+ let first: Value = try session.request("probe")+ #expect(first.value == 7)+ if retainsNotifications {+ for _ in 0 ..< 3 {+ #expect(try session.nextEvent() != nil)+ }+ }+ let live = try #require(try session.nextEvent())+ #expect(String(data: live, encoding: .utf8)?.contains("full content") == true)+ let _: Value = try session.request("done")+ session.close()+ session.close()+ try server.finish()+ let entries = try await storage.page().entries+ for method in [+ "thread/tokenUsage/updated", "item/commandExecution/requestApproval", "item/completed",+ "app-server/message", "websocket/ping", "websocket/pong", "connection/closed"+ ] {+ #expect(entries.filter { $0.method == method }.count == 1)+ }+ #expect(entries.first { $0.method == "websocket/ping" }?.detail == "base64:/wA=")+ #expect(entries.first { $0.method == "websocket/pong" }?.request == "base64:/wA=")+ #expect(entries.first { $0.method == "item/commandExecution/requestApproval" }?.isReceived == true)+ #expect(entries.first { $0.method == "item/completed" }?.detail?.contains("full content") == true)+ #expect(entries.filter { $0.method == "probe" }.count == 1)+ #expect(entries.first { $0.method == "probe" }?.status == .success)+ }++ @Test func malformedIncomingMessageAndConnectionFailureArePreserved() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ let server = try SharedServerFixture { peer in+ _ = try peer.readMessage()+ try peer.sendRaw(Data("{broken JSON".utf8))+ }+ defer { server.close() }+ let session = try AppServerSession(socketURL: server.url, logStorage: storage)+ do {+ let _: Value = try session.request("probe")+ Issue.record("Expected malformed JSON to fail")+ } catch {}+ session.close()+ try server.finish()+ let entries = try await storage.page().entries+ #expect(entries.first { $0.method == "app-server/message" }?.detail == "{broken JSON")+ #expect(entries.first { $0.method == "probe" }?.status == .failure)+ #expect(entries.filter { $0.method == "connection/closed" }.count == 1)+ #expect(throws: CodexStatusError.self) {+ _ = try AppServerSession(socketURL: directory.url.appendingPathComponent("missing.sock"), logStorage: storage)+ }+ #expect(try await storage.page().entries.contains { $0.method == "connection/open" && $0.status == .failure })+ }++ private nonisolated struct Value: Decodable {+ let value: Int+ }+}diff --git a/CodexBarTests/BoundedProcessTests.swift b/CodexBarTests/BoundedProcessTests.swiftnew file mode 100644index 0000000..90746d8--- /dev/null+++ b/CodexBarTests/BoundedProcessTests.swift@@ -0,0 +1,20 @@+import Foundation+import Testing++struct BoundedProcessTests {+ @Test nonisolated func processTimeoutKillsUncooperativeChildAndBoundsOutput() {+ let started = ContinuousClock.now+ let result = BoundedProcess.run(+ executable: URL(fileURLWithPath: "/bin/sh"),+ arguments: ["-c", "trap '' TERM; while :; do printf '0123456789abcdef'; done"], timeout: 0.1+ )+ #expect(result.timedOut)+ #expect(result.exitCode != 0)+ #expect(result.runningProcess == nil)+ #expect(result.output.utf8.count <= 65536)+ #expect(started.duration(to: .now) < .seconds(3))+ let next = BoundedProcess.run(executable: URL(fileURLWithPath: "/usr/bin/printf"), arguments: ["recovered"])+ #expect(next.exitCode == 0)+ #expect(next.output == "recovered")+ }+}diff --git a/CodexBarTests/CodexSessionLifecycleReaderTests.swift b/CodexBarTests/CodexSessionLifecycleReaderTests.swiftdeleted file mode 100644index 93cdb7d..0000000--- a/CodexBarTests/CodexSessionLifecycleReaderTests.swift+++ /dev/null@@ -1,992 +0,0 @@-import Foundation-import Testing--struct CodexSessionLifecycleReaderTests {- @Test(arguments: [false, true], ["whitespace", "invalid-json", "invalid-utf8"])- func singleLineDecodingPreservesCoverageInBothDirections(historical: Bool, content: String) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- var data = Data(([metadata(session: "session-a"), context, start, tokenUsage(input: 100)]- .joined(separator: "\r\n") + "\r\n").utf8)- switch content {- case "invalid-json": data.append(contentsOf: "{broken}\r\n".utf8)- case "invalid-utf8": data.append(contentsOf: [0xFF, 0x0D, 0x0A])- default: data.append(contentsOf: "\r\n \t\r\n".utf8)- }- if historical {- data.append(contentsOf: (oversizedLine(type: "compacted", payloadByteCount: 1024 * 1024) + "\r\n").utf8)- }- let url = try directory.write(data, to: "archived_sessions/rollout-test-session-a.jsonl")- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == (content == "whitespace" ? .complete : .incomplete))- #expect(state.hasContext)- #expect(state.startedAt == TestFixtures.now)- #expect(state.tokenUsage?.totalTokens == (content == "whitespace" ? 110 : nil))- try append(completion + "\r\n", to: url)- let completed = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(completed.readStatus == .complete)- #expect(completed.terminal != nil)- #expect(!completed.isHistoricalTerminal)- }-- @Test func completionHasStartDurationContextAndProgress() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- _ = try writeRollout(in: directory, lines: [context, start, completion])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == .complete)- #expect(state.recordedThreadID == "session-a")- #expect(state.startedAt == Date(timeIntervalSince1970: 1789459200))- #expect(state.approvalReviewer == .user)- #expect(state.effort == "high")- guard case let .completed(at, duration) = state.terminal else {- Issue.record("Expected a completed turn")- return- }- #expect(at == Date(timeIntervalSince1970: 1789459260))- #expect(duration == 60)- }-- @Test func partialCompletionIsNotPublishedUntilLineIsComplete() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [context, start])- try append(completion, to: url)- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let partial = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(partial.readStatus == .incomplete)- #expect(partial.terminal == nil)- let unchanged = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(unchanged.readStatus == .incomplete)- #expect(unchanged.terminal == nil)- try append("\n", to: url)- let complete = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(complete.readStatus == .complete)- #expect(complete.terminal != nil)- }-- @Test func incompleteTailWaitsForFullThresholdAndGrowthRestartsObservation() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [context, start])- try append(String(completion.dropLast()), to: url)- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let firstObserved = TestFixtures.now.addingTimeInterval(7200)- var task = CodexActivityTask(- displayID: UUID(), key: CodexActivityTaskKey(event: TestFixtures.event()), event: TestFixtures.event(),- state: .running, latestEvent: .promptSubmitted, startedAt: TestFixtures.now, progressGeneration: 1- )-- for elapsed in [0.0, 3599, 3600] {- let now = firstObserved.addingTimeInterval(elapsed)- let state = try #require(await reader.lifecycleStates(for: [reference], now: now).first)- #expect(state.readStatus == .incomplete)- #expect(state.incompleteTailUnchangedSince == firstObserved)- task.recordLifecycleRead(state, at: now)- let deadline = try #require(task.activityProtectionDeadline(at: now, inactivityDuration: 3600))- #expect((deadline <= now) == (elapsed == 3600))- #expect(!task.hasFreshLifecycle(at: now))- #expect(task.lastProgressAt == TestFixtures.now)- }-- try append("}", to: url)- let growthTime = firstObserved.addingTimeInterval(3601)- let growing = try #require(await reader.lifecycleStates(for: [reference], now: growthTime).first)- #expect(growing.incompleteTailUnchangedSince == growthTime)- task.recordLifecycleRead(growing, at: growthTime)- #expect(task.activityProtectionDeadline(at: growthTime, inactivityDuration: 3600) == growthTime.addingTimeInterval(3600))-- try append("\n", to: url)- let completed = try #require(await reader.lifecycleStates(for: [reference], now: growthTime).first)- #expect(completed.readStatus == .complete)- #expect(completed.terminal != nil)- #expect(completed.incompleteTailUnchangedSince == nil)- }-- @Test func restartAndFileReplacementStartNewTailObservation() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [context, start])- try append(completion, to: url)- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- _ = await reader.lifecycleStates(for: [reference], now: TestFixtures.now)- let later = TestFixtures.now.addingTimeInterval(3600)- let restarted = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await restarted.lifecycleStates(for: [reference], now: later).first?.incompleteTailUnchangedSince == later)-- let replacement = (metadata(session: "session-a") + "\n" + context + "\n" + start + "\n" + completion)- try Data(replacement.utf8).write(to: url, options: .atomic)- #expect(await reader.lifecycleStates(for: [reference], now: later).first?.incompleteTailUnchangedSince == later)- }-- @Test func unreadableTailClearsObservationAndRecoveryStartsAgain() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [context, start])- try append(completion, to: url)- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- _ = await reader.lifecycleStates(for: [reference], now: TestFixtures.now)- try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: url.path)- defer { try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) }- let unavailable = try #require(await reader.lifecycleStates(for: [reference], now: TestFixtures.now.addingTimeInterval(1)).first)- #expect(unavailable.readStatus == .unavailable)- #expect(unavailable.incompleteTailUnchangedSince == nil)-- try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)- let later = TestFixtures.now.addingTimeInterval(3600)- #expect(await reader.lifecycleStates(for: [reference], now: later).first?.incompleteTailUnchangedSince == later)- }-- @Test(arguments: ["missing-context", "read-gap"])- func incompleteTailRequiresContextWithoutOtherGapsOrTerminal(scenario: String) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let lines = switch scenario {- case "missing-context": [start]- case "read-gap": [context, start, "broken"]- default: [context, start, "broken"]- }- let url = try writeRollout(in: directory, lines: lines)- try append("{", to: url)- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- for _ in 0 ..< 2 {- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == .incomplete)- #expect(state.incompleteTailUnchangedSince == nil)- #expect(state.terminal == nil)- }- }-- @Test func corruptGapBlocksInactivityButExplicitTerminalStillResolves() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [context, start, "broken"])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let partial = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(partial.readStatus == .incomplete)- try append(completion + "\n", to: url)- let resolved = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(resolved.readStatus == .complete)- #expect(resolved.terminal != nil)- }-- @Test func lineLargerThanIncrementalBudgetContinuesAcrossReads() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [context, start])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- _ = await reader.lifecycleStates(for: [reference])-- let compacted = oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024)- try append(compacted + "\n" + completion + "\n", to: url)-- let partial = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(partial.readStatus == .incomplete)- #expect(partial.terminal == nil)- #expect(partial.incompleteTailUnchangedSince == nil)- let resolved = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(resolved.readStatus == .complete)- #expect(resolved.terminal != nil)- }-- @Test func lineLargerThanBufferLimitIsSkippedWithoutBlockingTerminal() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [context, start])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- _ = await reader.lifecycleStates(for: [reference])-- let compacted = oversizedLine(type: "compacted", payloadByteCount: 17 * 1024 * 1024)- try append(compacted + "\n" + completion + "\n", to: url)-- for _ in 0 ..< 2 {- let partial = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(partial.readStatus == .incomplete)- #expect(partial.terminal == nil)- #expect(partial.incompleteTailUnchangedSince == nil)- }- let resolved = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(resolved.readStatus == .complete)- #expect(resolved.terminal != nil)- }-- @Test func tokenUsageDoesNotResumeApprovalButAssistantOutputDoes() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let usage = #"{"timestamp":"2026-09-15T08:00:30Z","type":"token_usage_record","payload":{"turn_id":"turn-a"}}"#- let output = #"{"timestamp":"2026-09-15T08:00:40Z","type":"response_item","payload":{"type":"message","role":"assistant","#- + #""internal_chat_message_metadata_passthrough":{"turn_id":"turn-a"}}}"#- let url = try writeRollout(in: directory, lines: [context, start, usage])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let usageState = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(usageState.lastProgressAt != nil)- #expect(usageState.lastExecutionProgressAt == nil)- try append(output + "\n", to: url)- let outputState = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(outputState.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:00:40Z"))- }-- @Test func missingOrMismatchedRolloutCannotSupplyCachedTerminal() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [context, start, completion])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await reader.lifecycleStates(for: [reference]).first?.terminal != nil)- try FileManager.default.removeItem(at: url)- let missing = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(missing.readStatus == .notFound)- #expect(missing.terminal == nil)- _ = try writeRollout(in: directory, lines: [context, completion], session: "other-session")- let freshReader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let mismatch = try #require(await freshReader.lifecycleStates(for: [reference]).first)- #expect(mismatch.readStatus == .notFound)- #expect(mismatch.terminal == nil)- }-- @Test func fileReplacementDiscardsPriorTerminal() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [context, start, completion])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await reader.lifecycleStates(for: [reference]).first?.terminal != nil)- try Data((metadata(session: "session-a") + "\n" + context + "\n" + start + "\n").utf8).write(to: url, options: .atomic)- let replacement = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(replacement.readStatus == .complete)- #expect(replacement.terminal == nil)- }-- @Test func archivedRolloutAndAlternateFilenameAreRecognized() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let filename = "archived_sessions/rollout-test-session-a_00000000-0000-0000-0000-000000000001.jsonl"- _ = try directory.write(metadata(session: "session-a") + "\n" + completion + "\n", to: filename)- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await reader.lifecycleStates(for: [reference]).first?.terminal != nil)- }-- @Test(arguments: [false, true])- func historicalTerminalIsFoundDespiteCompleteTailContextOrPartialTail(partialTail: Bool) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [- context, start, completion, oversizedLine(type: "compacted", payloadByteCount: 1500 * 1024), context- ])- if partialTail {- try append("{", to: url)- }- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == .complete)- #expect(state.terminal != nil)- #expect(state.isHistoricalTerminal)- #expect(state.incompleteTailUnchangedSince == nil)- }-- @Test func completeTerminalRemainsUsableWhileNextLineIsPartial() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [context, start, completion])- try append("{", to: url)- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == .complete)- #expect(state.terminal != nil)- #expect(state.tokenUsage == nil)- #expect(state.incompleteTailUnchangedSince == nil)- }-- @Test func partialTerminalSpanningBootstrapBoundaryIsRecoveredWhenCompleted() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [context, start])- let largeTerminal = String(completion.dropLast(2)) + ",\"last_agent_message\":\"" + String(repeating: "x", count: 1024 * 1024) + "\"}}"- try append(largeTerminal, to: url)- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await reader.lifecycleStates(for: [reference]).first?.terminal == nil)- try append("\n", to: url)- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == .complete)- #expect(state.terminal != nil)- }-- @Test func historicalReadsContinuePastEightMiBAndAcrossOversizedLines() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- _ = try writeRollout(in: directory, lines: [- context, start, completion, oversizedLine(type: "compacted", payloadByteCount: 17 * 1024 * 1024), context- ])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- for _ in 0 ..< 2 {- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == .incomplete)- #expect(state.terminal == nil)- #expect(state.incompleteTailUnchangedSince == nil)- }- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == .complete)- #expect(state.terminal != nil)- }-- @Test func historicalTerminalCrossingReadBoundaryIsNotDropped() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let tailCount = (8 * 1024 * 1024 - 512 * 1024) - 80- let tail = oversizedLine(type: "compacted", payloadByteCount: tailCount)- _ = try writeRollout(in: directory, lines: [context, start, completion, tail])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await reader.lifecycleStates(for: [reference]).first?.terminal == nil)- #expect(await reader.lifecycleStates(for: [reference]).first?.terminal != nil)- }-- @Test func historicalReadsPreserveNewContextUsageAndImplicitProgress() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let newerContext = context.replacingOccurrences(of: "high", with: "low")- .replacingOccurrences(of: "08:00:00", with: "08:01:00")- let progress = #"{"timestamp":"2026-09-15T08:02:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#- let url = try writeRollout(in: directory, lines: [- context, start, tokenUsage(input: 100), newerContext,- oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024),- tokenUsage(input: 200), progress- ])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await reader.lifecycleStates(for: [reference]).first?.readStatus == .incomplete)- try append(progress.replacingOccurrences(of: "08:02:00", with: "08:04:00") + "\n", to: url)- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == .complete)- #expect(state.terminal == nil)- #expect(state.effort == "low")- #expect(state.contextObservedAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:01:00Z"))- #expect(state.tokenUsage?.totalTokens == 210)- #expect(state.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:04:00Z"))- try append(progress.replacingOccurrences(of: "08:02:00", with: "08:05:00") + "\n", to: url)- let live = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(live.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:05:00Z"))- try append(completion + "\n", to: url)- let completed = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(completed.terminal != nil)- #expect(!completed.isHistoricalTerminal)- }-- @Test(arguments: ["agent_message", "function_call_output", "token_count"])- func progressArrivingAcrossHistoricalReadsKeepsItsExecutionMeaning(kind: String) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [- context, start, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024)- ])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await reader.lifecycleStates(for: [reference]).first?.readStatus == .incomplete)- let type = kind == "function_call_output" ? "response_item" : "event_msg"- try append("""- {"timestamp":"2026-09-15T08:04:00Z","type":"\(type)","payload":{"type":"\(kind)"}}-- """, to: url)- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == .complete)- #expect(state.lastProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:04:00Z"))- #expect((state.lastExecutionProgressAt != nil) == (kind != "token_count"))- #expect(state.terminal == nil)- }-- @Test(arguments: [false, true])- func pendingInitialProgressDoesNotCrossIntoTheNextTurn(switchBeforeFirstRead: Bool) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [- context, start, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024)- ])- let progress = #"{"timestamp":"2026-09-15T08:04:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#- let nextContext = context.replacingOccurrences(of: "turn-a", with: "turn-b")- let nextStart = start.replacingOccurrences(of: "turn-a", with: "turn-b")- let boundary = [progress, nextContext, nextStart].joined(separator: "\n") + "\n"- let next = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- if switchBeforeFirstRead {- try append(boundary, to: url)- }- _ = await reader.lifecycleStates(for: [reference, next])- if !switchBeforeFirstRead {- try append(boundary, to: url)- }- let states = await reader.lifecycleStates(for: [reference, next])- let previous = try #require(states.first { $0.turnID == "turn-a" })- let current = try #require(states.first { $0.turnID == "turn-b" })- #expect(previous.readStatus == .complete)- #expect(previous.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:04:00Z"))- #expect(current.readStatus == .complete)- #expect(current.lastExecutionProgressAt == nil)- try append(progress.replacingOccurrences(of: "08:04:00", with: "08:05:00") + "\n", to: url)- let live = await reader.lifecycleStates(for: [reference, next])- #expect(live.first { $0.turnID == "turn-a" }?.lastExecutionProgressAt == previous.lastExecutionProgressAt)- #expect(live.first { $0.turnID == "turn-b" }?.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:05:00Z"))- }-- @Test(arguments: ["history", "bootstrap", "append"], [1, 9])- func lateOldTerminalPreservesNewTurnProgressDuringBackfill(location: String, paddingMiB: Int) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let progress = #"{"timestamp":"2026-09-15T08:04:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#- var lines = [- context, start, context.replacingOccurrences(of: "turn-a", with: "turn-b"),- start.replacingOccurrences(of: "turn-a", with: "turn-b")- ]- if location == "history" {- lines.append(completion)- }- lines.append(oversizedLine(type: "compacted", payloadByteCount: paddingMiB * 1024 * 1024))- if location == "bootstrap" {- lines.append(completion)- }- if location != "append" {- lines.append(progress)- }- let url = try writeRollout(in: directory, lines: lines)- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let next = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)- var state = try #require(await reader.lifecycleStates(for: [next]).first)- if location == "append" {- try append(completion + "\n" + progress + "\n", to: url)- }- for _ in 0 ..< 3 {- state = try #require(await reader.lifecycleStates(for: [next]).first)- }- #expect(state.readStatus == .complete)- #expect(state.terminal == nil)- #expect(state.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:04:00Z"))- try append(progress.replacingOccurrences(of: "08:04:00", with: "08:05:00") + "\n", to: url)- let live = try #require(await reader.lifecycleStates(for: [next]).first)- #expect(live.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:05:00Z"))- }-- @Test func historicalProgressStopsAtItsOwnTerminalDespiteOtherLateTerminals() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let progress = #"{"timestamp":"2026-09-15T08:02:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#- _ = try writeRollout(in: directory, lines: [- context, start, context.replacingOccurrences(of: "turn-a", with: "turn-b"),- start.replacingOccurrences(of: "turn-a", with: "turn-b"), progress,- completion.replacingOccurrences(of: "turn-a", with: "turn-b"), completion,- progress.replacingOccurrences(of: "08:02:00", with: "08:04:00"),- oversizedLine(type: "compacted", payloadByteCount: 1024 * 1024)- ])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let next = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)- let state = try #require(await reader.lifecycleStates(for: [next]).first)- #expect(state.terminal != nil)- #expect(state.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:02:00Z"))- }-- @Test(arguments: [false, true], ["progress", "context", "usage"])- func corruptGapSurvivesLateTurnDiscoveryWithoutTaintingNewTurns(duringBackfill: Bool, recordKind: String) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let progress = #"{"timestamp":"2026-09-15T08:04:00Z","type":"event_msg","payload":{"type":"agent_message","turn_id":"turn-a"}}"#- let record = recordKind == "context" ? context : recordKind == "usage" ? tokenUsage(input: 200) : progress- let suffix = [- "{broken}", record, context.replacingOccurrences(of: "turn-a", with: "turn-b"),- start.replacingOccurrences(of: "turn-a", with: "turn-b"), tokenUsage(input: 300, turn: "turn-b")- ]- var lines = [context, start, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024)]- if !duringBackfill {- lines += suffix- }- let url = try writeRollout(in: directory, lines: lines)- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let next = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)- _ = await reader.lifecycleStates(for: [reference, next])- if duringBackfill {- try append(suffix.joined(separator: "\n") + "\n", to: url)- }- for _ in 0 ..< 3 {- let states = await reader.lifecycleStates(for: [reference, next])- let old = try #require(states.first { $0.turnID == "turn-a" })- #expect(old.readStatus == .incomplete)- #expect(old.incompleteTailUnchangedSince == nil)- #expect(old.tokenUsage == nil)- #expect(states.first { $0.turnID == "turn-b" }?.readStatus == .complete)- #expect(states.first { $0.turnID == "turn-b" }?.tokenUsage?.totalTokens == 310)- }- try append(completion + "\n", to: url)- let states = await reader.lifecycleStates(for: [reference, next])- #expect(states.first { $0.turnID == "turn-a" }?.terminal != nil)- #expect(states.first { $0.turnID == "turn-b" }?.terminal == nil)- }-- @Test func pendingProgressStopsAtTerminalBeforeAnotherTurnBegins() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [- context, start, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024)- ])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- _ = await reader.lifecycleStates(for: [reference])- let progress = #"{"timestamp":"2026-09-15T08:04:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#- try append([- progress, completion, progress.replacingOccurrences(of: "08:04:00", with: "08:09:00"),- context.replacingOccurrences(of: "turn-a", with: "turn-b"), start.replacingOccurrences(of: "turn-a", with: "turn-b")- ].joined(separator: "\n") + "\n", to: url)- let next = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)- let states = await reader.lifecycleStates(for: [reference, next])- let previous = try #require(states.first { $0.turnID == "turn-a" })- let current = try #require(states.first { $0.turnID == "turn-b" })- #expect(previous.terminal != nil)- #expect(previous.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:04:00Z"))- #expect(current.terminal == nil)- #expect(current.readStatus == .complete)- #expect(current.lastExecutionProgressAt == nil)- }-- @Test func corruptBoundaryDiscardsPendingProgressWithoutBlockingANewTurn() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [- context, start, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024)- ])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- _ = await reader.lifecycleStates(for: [reference])- let progress = #"{"timestamp":"2026-09-15T08:04:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#- try append([- progress, "broken", context.replacingOccurrences(of: "turn-a", with: "turn-b"),- start.replacingOccurrences(of: "turn-a", with: "turn-b")- ].joined(separator: "\n") + "\n", to: url)- let next = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)- let states = await reader.lifecycleStates(for: [reference, next])- #expect(states.first { $0.turnID == "turn-a" }?.readStatus == .incomplete)- #expect(states.first { $0.turnID == "turn-b" }?.readStatus == .complete)- #expect(states.first { $0.turnID == "turn-b" }?.lastExecutionProgressAt == nil)- }-- @Test func unassignedProgressAtFileHeadDoesNotClaimCompleteCoverage() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024)])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- _ = await reader.lifecycleStates(for: [reference])- let progress = #"{"timestamp":"2026-09-15T08:04:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#- try append(progress + "\n", to: url)- for _ in 0 ..< 2 {- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == .incomplete)- #expect(state.lastExecutionProgressAt == nil)- #expect(state.incompleteTailUnchangedSince == nil)- }- }-- @Test(arguments: [false, true])- func replacingFileClearsUnassignedProgress(atomic: Bool) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let progress = #"{"timestamp":"2026-09-15T08:09:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#- let url = try writeRollout(in: directory, lines: [- context, start, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024), progress- ])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- _ = await reader.lifecycleStates(for: [reference])- let replacement = [metadata(session: "session-a"), context, start, progress.replacingOccurrences(of: "08:09:00", with: "08:02:00")]- .joined(separator: "\n") + "\n"- try Data(replacement.utf8).write(to: url, options: atomic ? .atomic : [])- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == .complete)- #expect(state.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:02:00Z"))- }-- @Test func oldTerminalNeverCompletesAnotherTurnAndHistoryDoesNotReplaceFreshUsage() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let nextContext = context.replacingOccurrences(of: "turn-a", with: "turn-b")- let nextStart = start.replacingOccurrences(of: "turn-a", with: "turn-b")- _ = try writeRollout(in: directory, lines: [- context, start, tokenUsage(input: 100), completion,- oversizedLine(type: "compacted", payloadByteCount: 1200 * 1024),- tokenUsage(input: 200), nextContext, nextStart- ])- let next = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let states = await reader.lifecycleStates(for: [reference, next])- let previous = try #require(states.first { $0.turnID == "turn-a" })- #expect(previous.terminal != nil)- #expect(previous.tokenUsage?.totalTokens == 210)- let running = try #require(states.first { $0.turnID == "turn-b" })- #expect(running.terminal == nil)- #expect(running.readStatus == .complete)- }-- @Test func multipleFilesShareBudgetAndAllEventuallyReachTheirTerminals() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- var references: [CodexActivityTurnReference] = []- for session in ["session-a", "session-b", "session-c"] {- let text = [- metadata(session: session),- context,- start,- completion,- oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024),- context- ].joined(separator: "\n") + "\n"- _ = try directory.write(text, to: "archived_sessions/rollout-test-\(session)_00000000-0000-0000-0000-000000000001.jsonl")- references.append(CodexActivityTurnReference(threadID: session, turnID: "turn-a", startedAt: TestFixtures.now))- }- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let first = await reader.lifecycleStates(for: references)- #expect(first.allSatisfy { $0.terminal == nil })- var completed: Set<String> = []- for _ in 0 ..< 6 {- let states = await reader.lifecycleStates(for: references)- completed.formUnion(states.filter { $0.terminal != nil }.map(\.requestedThreadID))- }- #expect(completed == Set(references.map(\.threadID)))- }-- @Test(arguments: [false, true])- func replacementOrTruncationDiscardsPendingHistory(atomic: Bool) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [- context, start, completion, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024), context- ])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await reader.lifecycleStates(for: [reference]).first?.terminal == nil)- let replacement = Data(([metadata(session: "session-a"), context, start].joined(separator: "\n") + "\n").utf8)- try replacement.write(to: url, options: atomic ? .atomic : [])- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == .complete)- #expect(state.terminal == nil)- #expect(!state.isHistoricalTerminal)- }-- @Test func archiveMoveDuringHistoricalReadRelocatesWithoutUsingOldCursor() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [- context, start, completion, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024), context- ])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await reader.lifecycleStates(for: [reference]).first?.terminal == nil)- let archived = directory.url.appendingPathComponent("archived_sessions")- try FileManager.default.createDirectory(at: archived, withIntermediateDirectories: true)- try FileManager.default.moveItem(at: url, to: archived.appendingPathComponent(url.lastPathComponent))- #expect(await reader.lifecycleStates(for: [reference]).first?.terminal == nil)- #expect(await reader.lifecycleStates(for: [reference]).first?.terminal != nil)- }-- private var reference: CodexActivityTurnReference {- CodexActivityTurnReference(threadID: "session-a", turnID: "turn-a", startedAt: TestFixtures.now)- }-- @Test(arguments: [1, 9])- func terminalBackfillsUsageAndOwnershipWithoutDelayingCompletion(paddingMiB: Int) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- _ = try writeRollout(- in: directory,- lines: [context, start, tokenUsage(input: 100)]- + historyPadding(mebibytes: paddingMiB) + [completion]- )- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let first = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(first.terminal != nil)- #expect(first.readStatus == .complete)- #expect(!first.isHistoricalTerminal)- #expect(first.tokenUsage?.totalTokens == (paddingMiB == 1 ? 110 : nil))- let recovered = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(recovered.tokenUsage?.totalTokens == 110)- #expect(recovered.rootTurnID == "turn-a")- #expect(!recovered.isHistoricalTerminal)- }-- @Test(arguments: [31, 33], [false, true])- func supplementalHistoryStopsAtLimitAndAcceptsAppendedUsage(paddingMiB: Int, hookEnded: Bool) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let other = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)- let url = try writeRollout(- in: directory,- lines: [context, start, tokenUsage(input: 100)]- + historyPadding(mebibytes: paddingMiB) + (hookEnded ? [] : [completion])- + [- context.replacingOccurrences(of: "turn-a", with: "turn-b"),- tokenUsage(input: 300, turn: "turn-b"),- completion.replacingOccurrences(of: "turn-a", with: "turn-b")- ]- )- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- var query = reference- query.isTerminalUsageOnly = hookEnded- for _ in 0 ..< 12 {- _ = await reader.lifecycleStates(for: [query], now: TestFixtures.now)- // 用量查询间隔中的其他轮次轮询不能重置累计预算- _ = await reader.lifecycleStates(for: [other], now: TestFixtures.now)- }- let state = try #require(await reader.lifecycleStates(for: [query], now: TestFixtures.now).first)- #expect(state.tokenUsage?.totalTokens == (paddingMiB == 31 ? 110 : nil))- #expect(state.rootTurnID == (paddingMiB == 31 ? "turn-a" : nil))- #expect((state.terminal != nil) == !hookEnded)-- try append([context, start, tokenUsage(input: 200), completion].joined(separator: "\n") + "\n", to: url)- let updated = try #require(await reader.lifecycleStates(for: [query], now: TestFixtures.now).first)- #expect(updated.terminal != nil)- #expect(updated.tokenUsage?.totalTokens == 210)- }-- @Test(arguments: [false, true])- func laterSearchCanContinueBeyondSupplementalLimitAndShareResults(usageOnly: Bool) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- var other = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)- other.isTerminalUsageOnly = usageOnly- _ = try writeRollout(in: directory, lines: [- context.replacingOccurrences(of: "turn-a", with: "turn-b"),- start.replacingOccurrences(of: "turn-a", with: "turn-b"),- completion.replacingOccurrences(of: "turn-a", with: "turn-b"),- context, start, tokenUsage(input: 100)- ] + historyPadding(mebibytes: 33) + [completion])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- for _ in 0 ..< 8 {- _ = await reader.lifecycleStates(for: [reference])- }- #expect(await reader.lifecycleStates(for: [reference]).first?.tokenUsage == nil)- let states = await reader.lifecycleStates(for: [reference, other])- #expect(states.first { $0.turnID == "turn-b" }?.terminal != nil)- #expect(states.first { $0.turnID == "turn-b" }?.isHistoricalTerminal == true)- #expect(states.first { $0.turnID == "turn-a" }?.tokenUsage?.totalTokens == 110)- }-- @Test func missingSupplementalInformationReachesHeadAndReplacementResetsBudget() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: historyPadding(mebibytes: 33) + [completion])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- for _ in 0 ..< 8 {- _ = await reader.lifecycleStates(for: [reference])- }- let replacement = [metadata(session: "session-a"), context, start]- + historyPadding(mebibytes: 1) + [completion]- try Data((replacement.joined(separator: "\n") + "\n").utf8).write(to: url, options: .atomic)- for _ in 0 ..< 3 {- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.startedAt == TestFixtures.now)- #expect(state.terminal != nil)- #expect(state.tokenUsage == nil)- #expect(state.rootTurnID == nil)- }- try append(tokenUsage(input: 200) + "\n", to: url)- #expect(await reader.lifecycleStates(for: [reference]).first?.tokenUsage?.totalTokens == 210)- }-- @Test(arguments: [false, true])- func terminalBackfillDoesNotReplaceLatestUsageWithOlderSnapshot(invalidLatest: Bool) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let rootContext = context.replacingOccurrences(of: "\"turn_id\":\"turn-a\"", with: "\"turn_id\":\"turn-a\",\"root_turn_id\":\"turn-a\"")- let latest = invalidLatest ? tokenUsage(input: 200).replacingOccurrences(of: "\"total_tokens\":210", with: "\"total_tokens\":-1") : tokenUsage(input: 200)- _ = try writeRollout(- in: directory,- lines: [rootContext, start, tokenUsage(input: 100)]- + historyPadding(mebibytes: 9) + [latest, completion]- )- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- for _ in 0 ..< 4 {- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.terminal != nil)- #expect(state.tokenUsage?.totalTokens == (invalidLatest ? nil : 210))- }- #expect(await reader.lifecycleStates(for: [reference]).first?.rootTurnID == "turn-a")- }-- private func historyPadding(mebibytes: Int) -> [String] {- Array(repeating: oversizedLine(type: "compacted", payloadByteCount: 1024 * 1024), count: mebibytes)- }-- @Test func tokenUsageUpdatesIncrementallyBeforeTaskCompletion() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [context, start])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await reader.lifecycleStates(for: [reference]).first?.tokenUsage == nil)- for input in [100, 200, 300] {- try append(tokenUsage(input: input) + "\n", to: url)- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == .complete)- #expect(state.terminal == nil)- #expect(state.tokenUsage?.totalTokens == Int64(input + 10))- }- try append(completion + "\n", to: url)- let completed = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(completed.terminal != nil)- #expect(completed.tokenUsage?.totalTokens == 310)- }-- @Test func tokenUsageUsesLatestTurnSnapshotWithoutDoubleCounting() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let latest = tokenUsage(input: 200)- _ = try writeRollout(in: directory, lines: [context, start, tokenUsage(input: 100), latest, latest, completion])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.tokenUsage?.inputTokens == 200)- #expect(state.tokenUsage?.totalTokens == 210)- #expect(state.rootTurnID == "turn-a")- }-- @Test func lateUsageAfterAbortIsReadWithoutIncludingNextTurn() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let abort = #"{"type":"event_msg","payload":{"type":"turn_aborted","turn_id":"turn-a"}}"#- let url = try writeRollout(in: directory, lines: [context, start, tokenUsage(input: 100), abort])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await reader.lifecycleStates(for: [reference]).first?.tokenUsage?.totalTokens == 110)- try append(tokenUsage(input: 200) + "\n" + tokenUsage(input: 999, turn: "turn-b") + "\n", to: url)- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.tokenUsage?.totalTokens == 210)- guard case .aborted = state.terminal else {- Issue.record("Expected the aborted turn to retain its terminal state")- return- }- }-- @Test(arguments: ["wrong-thread", "wrong-session", "missing", "negative", "overflow", "wrong-type"])- func invalidUsageDoesNotBreakTerminalOrReusePreviousCount(scenario: String) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let valid = tokenUsage(input: 100)- let invalid = switch scenario {- case "wrong-thread": valid.replacingOccurrences(of: #""thread_id":"session-a""#, with: #""thread_id":"other""#)- case "wrong-session": valid.replacingOccurrences(of: #""session_id":"session-a""#, with: #""session_id":"other""#)- case "missing": valid.replacingOccurrences(of: #""input_tokens":100,"#, with: "")- case "negative": valid.replacingOccurrences(of: #""cached_input_tokens":20"#, with: #""cached_input_tokens":-1"#)- case "overflow": valid.replacingOccurrences(of: #""input_tokens":100"#, with: #""input_tokens":9223372036854775807"#)- default: valid.replacingOccurrences(of: #""input_tokens":100"#, with: #""input_tokens":"100""#)- }- _ = try writeRollout(in: directory, lines: [context, start, valid, invalid, completion])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.readStatus == .complete)- #expect(state.terminal != nil)- #expect(state.tokenUsage == nil)- }-- @Test func oldTokenCountDoesNotBecomeZeroOrAUsageRecord() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- _ = try writeRollout(in: directory, lines: [- context,- start,- #"{"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"total_tokens":999}}}}"#,- completion- ])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await reader.lifecycleStates(for: [reference]).first?.tokenUsage == nil)- }-- @Test func corruptGapDropsUsageUntilAFreshCumulativeRecordArrives() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [context, start, tokenUsage(input: 100), completion, "broken"])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let state = try #require(await reader.lifecycleStates(for: [reference]).first)- #expect(state.terminal != nil)- #expect(state.tokenUsage == nil)- try append(tokenUsage(input: 200) + "\n", to: url)- #expect(await reader.lifecycleStates(for: [reference]).first?.tokenUsage?.totalTokens == 210)- }-- @Test func tailBootstrapUsesCumulativeUsageEvenWhenEarlierResponsesAreOutsideWindow() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- _ = try writeRollout(in: directory, lines: [- context,- start,- tokenUsage(input: 100),- oversizedLine(type: "response_item", payloadByteCount: 600 * 1024),- tokenUsage(input: 200),- completion- ])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await reader.lifecycleStates(for: [reference]).first?.tokenUsage?.totalTokens == 210)- }-- @Test func partialUsageAndFileReplacementDoNotExposeStaleCounts() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = try writeRollout(in: directory, lines: [context, start, tokenUsage(input: 100), completion])- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- #expect(await reader.lifecycleStates(for: [reference]).first?.tokenUsage?.totalTokens == 110)- try append(tokenUsage(input: 200), to: url)- #expect(await reader.lifecycleStates(for: [reference]).first?.tokenUsage == nil)- try append("\n", to: url)- #expect(await reader.lifecycleStates(for: [reference]).first?.tokenUsage?.totalTokens == 210)- try Data((metadata(session: "session-a") + "\n" + context + "\n" + completion + "\n").utf8).write(to: url, options: .atomic)- #expect(await reader.lifecycleStates(for: [reference]).first?.tokenUsage == nil)- }-- private func tokenUsage(input: Int, turn: String = "turn-a") -> String {- """- {"type":"token_usage_record","payload":{"thread_id":"session-a","session_id":"session-a","turn_id":"\(turn)",\- "root_turn_id":"\(turn)","response_id":"response-\(input)","turn_token_usage":{\- "input_tokens":\(input),"cached_input_tokens":20,"cache_write_input_tokens":0,\- "output_tokens":10,"reasoning_output_tokens":2,"total_tokens":\(input + 10)}}}- """- }-- @Test(arguments: [0, 9])- func forkedMetadataDoesNotReplaceChildUsageIdentity(paddingMiB: Int) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let childMetadata = #"{"type":"session_meta","payload":{"id":"child-a","session_id":"session-a","parent_thread_id":"session-a","#- + #""source":{"subagent":{"thread_spawn":{"parent_thread_id":"session-a"}}}}}"#- let usage = tokenUsage(input: 100, turn: "child-turn")- .replacingOccurrences(of: #""thread_id":"session-a""#, with: #""thread_id":"child-a""#)- .replacingOccurrences(of: #""root_turn_id":"child-turn""#, with: #""root_turn_id":"turn-a""#)- let datePath = CodexDateFormat.dayString(from: TestFixtures.now).replacingOccurrences(of: "-", with: "/")- _ = try directory.write(- ([childMetadata, metadata(session: "session-a"), usage] + historyPadding(mebibytes: paddingMiB)- + [completion.replacingOccurrences(of: "turn-a", with: "child-turn")])- .joined(separator: "\n") + "\n",- to: "sessions/\(datePath)/rollout-test-child-a.jsonl"- )- let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)- let child = CodexActivityTurnReference(threadID: "child-a", turnID: "child-turn", startedAt: TestFixtures.now)- #expect(await reader.lifecycleStates(for: [child]).first?.terminal != nil)- let state = try #require(await reader.lifecycleStates(for: [child]).first)- #expect(state.recordedThreadID == "child-a")- #expect(state.rootSessionID == "session-a")- #expect(state.rootTurnID == "turn-a")- #expect(state.tokenUsage?.totalTokens == 110)- }-- private var context: String {- #"{"timestamp":"2026-09-15T08:00:00Z","type":"turn_context","payload":{"turn_id":"turn-a","approvals_reviewer":"user","effort":" high "}}"#- }-- private var start: String {- #"{"type":"event_msg","payload":{"type":"task_started","turn_id":"turn-a","started_at":1789459200}}"#- }-- private var completion: String {- #"{"type":"event_msg","payload":{"type":"task_complete","turn_id":"turn-a","completed_at":1789459260,"duration_ms":60000}}"#- }-- private func metadata(session: String) -> String {- "{\"type\":\"session_meta\",\"payload\":{\"id\":\"\(session)\",\"source\":\"cli\"}}"- }-- private func oversizedLine(type: String, payloadByteCount: Int) -> String {- "{\"type\":\"\(type)\",\"payload\":{\"data\":\"\(String(repeating: "x", count: payloadByteCount))\"}}"- }-- private func writeRollout(in directory: TestDirectory, lines: [String], session: String = "session-a") throws -> URL {- let datePath = CodexDateFormat.dayString(from: TestFixtures.now).replacingOccurrences(of: "-", with: "/")- return try directory.write(([metadata(session: session)] + lines).joined(separator: "\n") + "\n", to: "sessions/\(datePath)/rollout-test-session-a.jsonl")- }-- private func append(_ text: String, to url: URL) throws {- let handle = try FileHandle(forWritingTo: url)- defer { try? handle.close() }- try handle.seekToEnd()- try handle.write(contentsOf: Data(text.utf8))- }-}diff --git a/CodexBarTests/CodexTokenHistoryTests.swift b/CodexBarTests/CodexTokenHistoryTests.swiftdeleted file mode 100644index b0b583c..0000000--- a/CodexBarTests/CodexTokenHistoryTests.swift+++ /dev/null@@ -1,684 +0,0 @@-import CloudKit-import CryptoKit-import Foundation-import Synchronization-import Testing--struct CodexTokenHistoryTests {- @Test func unchangedTokenStorageDoesNotReplaceFile() throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = directory.url.appendingPathComponent("cache.json")- let values = [turn("main", "a", input: 100)]- try CodexTokenFileStorage.save(values, to: url)- let before = try #require(WorkflowStorage.fileStat(at: url))- try CodexTokenFileStorage.save(values, to: url)- let after = try #require(WorkflowStorage.fileStat(at: url))- #expect(after.identifier == before.identifier)- #expect(after.modifiedAtNanoseconds == before.modifiedAtNanoseconds)- #expect(try CodexTokenFileStorage.load([CodexTokenTurn].self, from: url) == values)- }-- @Test func tokenIdentitiesMatchExistingEncodingExactly() throws {- let bytes = Data((0 ... 255).map(UInt8.init))- #expect(CodexTokenTurn.hexString(bytes) == bytes.map { String(format: "%02x", $0) }.joined())- #expect(CodexTokenTurn.hexString(Data()).isEmpty)- let salt = Data((0 ... 255).map(UInt8.init))- for thread in ["", "thread", "中文/路径", "a\u{0000}b", String(repeating: "x", count: 1024)] {- let data = try JSONEncoder().encode(["token-turn-v1", thread, "turn"])- let expected = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()- #expect(CodexTokenTurn.identifier(thread: thread, turn: "turn") == expected)- for root in [expected, "other-root"] {- let value = CodexTokenTurn(id: expected, rootID: root, updatedAt: TestFixtures.now)- let exported = value.pseudonymized(salt: salt)- func legacyHash(_ text: String) -> String {- HMAC<SHA256>.authenticationCode(for: Data(text.utf8), using: SymmetricKey(data: salt))- .map { String(format: "%02x", $0) }.joined()- }- #expect(exported.id == legacyHash(expected))- #expect(exported.rootID == legacyHash(root))- #expect(exported.updatedAt == value.updatedAt)- }- }- }-- @Test func batchPseudonymsPreserveUpdatedValuesAndAccountIsolation() {- let root = turn("main", "a", input: 100)- let child = turn("child", "b", root: root.id, input: 200)- var updated = child- updated.usage = usage(input: 50)- updated.rebuiltAt = TestFixtures.now.addingTimeInterval(60)- let records = [root, child, updated]- for salt in [Data("account-a".utf8), Data("account-b".utf8), Data()] {- #expect(CodexTokenTurn.pseudonymized(records, salt: salt) == records.map { $0.pseudonymized(salt: salt) })- }- }-- @Test func cachedTokenFileChecksBytesAcrossExternalWritesAndDeletion() throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let url = directory.url.appendingPathComponent("cache.json")- var first = CodexTokenFileCache<[String: Int]>(url: url)- var second = CodexTokenFileCache<[String: Int]>(url: url)- try first.save(["cursor": 1])- #expect(try first.load() == ["cursor": 1])- #expect(try second.load() == ["cursor": 1])- let initial = try #require(WorkflowStorage.fileStat(at: url))- try first.save(["cursor": 1])- #expect(WorkflowStorage.fileStat(at: url)?.identifier == initial.identifier)- let modifiedAt = try FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate]- try Data("{\"cursor\":2}".utf8).write(to: url)- if let modifiedAt {- try FileManager.default.setAttributes([.modificationDate: modifiedAt], ofItemAtPath: url.path)- }- #expect(WorkflowStorage.fileStat(at: url)?.size == initial.size)- #expect(try first.load() == ["cursor": 2])- #expect(try second.load() == ["cursor": 2])- try second.save(["cursor": 3])- #expect(try first.load() == ["cursor": 3])- // 内存命中不能跳过另一进程修改后的保存检查点- try second.save(["cursor": 4])- try first.save(["cursor": 3])- #expect(try second.load() == ["cursor": 3])- try Data("invalid".utf8).write(to: url)- #expect(throws: (any Error).self) { try first.load() }- try FileManager.default.removeItem(at: url)- #expect(try first.load() == nil)- try first.save(["cursor": 3])- #expect(try second.load() == ["cursor": 3])- }-- @Test func idleRefreshPreservesResultsAndPersistedScanScheduling() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let source = try directory.write(lines(input: 100), to: "sessions/rollout-main.jsonl")- let store = makeStore(directory)- let original = try await store.refresh(now: TestFixtures.now)- let later = TestFixtures.now.addingTimeInterval(60)- #expect(try await store.refresh(now: later) == original)- let ledgerURL = directory.url.appendingPathComponent("history/ledger.json")- let json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: ledgerURL)) as? [String: Any])- let cursors = try #require(json["files"] as? [String: [String: Any]])- let cursor = try #require(cursors.values.first)- #expect(cursor["lastReadAt"] as? Double == later.timeIntervalSinceReferenceDate)- let sourceSize = try Data(contentsOf: source).count- #expect(cursor["offset"] as? Int == sourceSize)- #expect(try await makeStore(directory).refresh(now: later) == original)- }-- @Test func replayProgressReportsBackfillAndCompletionWithoutIdleOrIncrementalSpam() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let records = (1 ... 20).map { record(input: $0 * 100) + "\n" }.joined()- let file = try directory.write(metadata() + "\n" + start() + "\n" + records, to: "sessions/rollout-main.jsonl")- let reports = Mutex<[CodexTokenReplayProgress]>([])- let store = CodexTokenHistoryStore(- codexHomeURL: directory.url, directoryURL: directory.url.appendingPathComponent("history"), byteBudget: 256,- reportProgress: { progress in reports.withLock { $0.append(progress) } }- )- for _ in 0 ..< 30 {- _ = try await store.refresh(now: TestFixtures.now)- }- let progress = reports.withLock { $0 }- #expect(progress.count > 1)- #expect(progress.first?.isComplete == false)- #expect(progress.first?.remainingBytes ?? 0 > 0)- #expect(progress.allSatisfy { $0.totalFiles == 1 && $0.unavailableFiles == 0 })- #expect(zip(progress, progress.dropFirst()).allSatisfy { $0.processedBytes < $1.processedBytes })- let completed = try #require(progress.last)- #expect(completed.isComplete)- #expect(completed.remainingBytes == 0)- #expect(try completed.processedBytes == UInt64(Data(contentsOf: file).count))- let count = progress.count- try append(record(input: 3000) + "\n", to: file)- _ = try await store.refresh(now: TestFixtures.now)- #expect(reports.withLock { $0.count } == count)- #expect(try await daily(store)[day]?.totalTokens == 3010)- }-- @Test func replayProgressDoesNotCallPartialOrUnreadableFilesComplete() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let file = try directory.write(lines(input: 100) + record(input: 200), to: "sessions/rollout-main.jsonl")- let broken = try directory.write("invalid metadata\n", to: "sessions/rollout-broken.jsonl")- let reports = Mutex<[CodexTokenReplayProgress]>([])- let store = CodexTokenHistoryStore(- codexHomeURL: directory.url, directoryURL: directory.url.appendingPathComponent("history"),- reportProgress: { progress in reports.withLock { $0.append(progress) } }- )- _ = try await store.refresh(now: TestFixtures.now)- let first = try #require(reports.withLock { $0.last })- #expect(!first.isComplete)- #expect(first.waitingFiles == 1)- #expect(first.unavailableFiles == 1)- #expect(first.completedFiles == 0)- _ = try await store.refresh(now: TestFixtures.now)- #expect(reports.withLock { $0.count } == 1)- try append("\n", to: file)- _ = try await store.refresh(now: TestFixtures.now)- let partial = try #require(reports.withLock { $0.last })- #expect(!partial.isComplete)- #expect(partial.completedFiles == 1)- #expect(partial.waitingFiles == 0)- try FileManager.default.removeItem(at: broken)- _ = try await store.refresh(now: TestFixtures.now)- #expect(reports.withLock { $0.last?.isComplete } == true)- }-- @Test func replayProgressResumesPersistedOffsetsAndReportsReplacement() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let file = try directory.write(lines(input: 100), to: "sessions/rollout-main.jsonl")- let reports = Mutex<[CodexTokenReplayProgress]>([])- let first = CodexTokenHistoryStore(- codexHomeURL: directory.url, directoryURL: directory.url.appendingPathComponent("history"), byteBudget: 256,- reportProgress: { progress in reports.withLock { $0.append(progress) } }- )- _ = try await first.refresh(now: TestFixtures.now)- let initial = try #require(reports.withLock { $0.last })- let restarted = CodexTokenHistoryStore(- codexHomeURL: directory.url, directoryURL: directory.url.appendingPathComponent("history"),- reportProgress: { progress in reports.withLock { $0.append(progress) } }- )- _ = try await restarted.refresh(now: TestFixtures.now)- let completed = try #require(reports.withLock { $0.last })- #expect(completed.isComplete)- #expect(completed.processedBytes > initial.processedBytes)- #expect(UInt64(completed.batchBytes) < completed.totalBytes)- try Data((metadata() + "\n" + start() + "\n" + record(input: 200)).utf8).write(to: file, options: .atomic)- _ = try await restarted.refresh(now: TestFixtures.now)- #expect(reports.withLock { $0.last?.waitingFiles } == 1)- #expect(reports.withLock { $0.last?.isComplete } == false)- try append("\n", to: file)- _ = try await restarted.refresh(now: TestFixtures.now)- #expect(reports.withLock { $0.last?.isComplete } == true)- }-- @Test func rebuildReplacesOnlySelectedLocalTurnsAndKeepsIncrementalReading() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let source = try directory.write(lines(input: 500), to: "sessions/rollout-main.jsonl")- let otherDay = TestFixtures.now.addingTimeInterval(-86400)- let other = lines(input: 200).replacingOccurrences(of: "thread-main", with: "thread-other")- .replacingOccurrences(of: String(TestFixtures.now.timeIntervalSince1970), with: String(otherDay.timeIntervalSince1970))- let otherFile = try directory.write(other, to: "sessions/rollout-other.jsonl")- let store = makeStore(directory)- let initial = try await store.refresh(now: TestFixtures.now.addingTimeInterval(60))- let otherID = CodexTokenTurn.identifier(thread: "thread-other", turn: "turn-main")- let previousOther = try #require(initial.first { $0.id == otherID })- try Data(lines(input: 100).utf8).write(to: source, options: .atomic)- let changedOther = lines(input: 400).replacingOccurrences(of: "thread-main", with: "thread-other")- .replacingOccurrences(of: String(TestFixtures.now.timeIntervalSince1970), with: String(otherDay.timeIntervalSince1970))- try Data(changedOther.utf8).write(to: otherFile, options: .atomic)- _ = try directory.write(lines(input: 100), to: "archived_sessions/rollout-copy.jsonl")- let result = try await store.rebuild(for: [day], now: TestFixtures.now.addingTimeInterval(120))- #expect(result.dateKeys == [day])- #expect(result.turnCount == 1)- let current = try await store.currentTurns()- #expect(current.first { $0.id == otherID } == previousOther)- #expect(CodexTokenTurn.dailyUsage(current, now: TestFixtures.now.addingTimeInterval(180))[day]?.totalTokens == 110)- #expect(CodexTokenTurn.dailyUsage(current + initial, now: TestFixtures.now.addingTimeInterval(180))[day]?.totalTokens == 110)- try append(record(input: 300) + "\n", to: source)- #expect(try await daily(makeStore(directory))[day]?.totalTokens == 310)- }-- @Test func rebuildWithMissingRolloutsPreservesKnownTurns() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let source = try directory.write(lines(input: 500), to: "sessions/rollout-main.jsonl")- let store = makeStore(directory)- let before = try await store.refresh(now: TestFixtures.now)- try FileManager.default.removeItem(at: source)- let result = try await store.rebuild(for: [day], now: TestFixtures.now)- #expect(result.dateKeys.isEmpty)- #expect(try await store.currentTurns() == before)- }-- @Test func rebuildCanClearPreviouslyCountedUsageAndExcludesConcurrentRebuilds() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let source = try directory.write(lines(input: 500), to: "sessions/rollout-main.jsonl")- let store = makeStore(directory)- let before = try await store.refresh(now: TestFixtures.now)- let lock = try #require(try CodexTokenFileStorage.acquireLock(in: directory.url.appendingPathComponent("history"), name: "rebuild.lock"))- await #expect(throws: (any Error).self) { try await store.rebuild(for: [day], now: TestFixtures.now) }- CodexTokenFileStorage.releaseLock(lock)- #expect(try await store.currentTurns() == before)- try Data((metadata() + "\n" + start() + "\n").utf8).write(to: source, options: .atomic)- _ = try await store.rebuild(for: [day], now: TestFixtures.now.addingTimeInterval(60))- let current = try await store.currentTurns()- #expect(current.count == 1)- #expect(current.first?.usage == nil)- #expect(current.first?.rebuiltAt != nil)- #expect(CodexTokenTurn.dailyUsage(current + before, now: TestFixtures.now.addingTimeInterval(60)).isEmpty)- }-- @Test func incompleteOrCancelledRebuildDoesNotPublishPartialResults() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let source = try directory.write(lines(input: 500), to: "sessions/rollout-main.jsonl")- let store = makeStore(directory)- let before = try await store.refresh(now: TestFixtures.now)- try Data(lines(input: 100).utf8).write(to: source, options: .atomic)- let cancelled = Task { try await store.rebuild(for: [day], now: TestFixtures.now) }- cancelled.cancel()- await #expect(throws: CancellationError.self) { try await cancelled.value }- #expect(try await store.currentTurns() == before)- _ = try directory.write("broken metadata\n", to: "sessions/rollout-broken.jsonl")- await #expect(throws: (any Error).self) { try await store.rebuild(for: [day], now: TestFixtures.now) }- #expect(try await store.currentTurns() == before)- }-- @Test func rebuildReadsAllBatchesButLeavesPartialTailForIncrementalRefresh() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let body = "{\"type\":\"response_item\",\"payload\":\"" + String(repeating: "x", count: 2 * 1024 * 1024) + "\"}\n"- let source = try directory.write(lines(input: 100) + body + record(input: 300), to: "sessions/rollout-main.jsonl")- let store = CodexTokenHistoryStore(codexHomeURL: directory.url, directoryURL: directory.url.appendingPathComponent("history"), byteBudget: 4096)- let result = try await store.rebuild(for: [day], now: TestFixtures.now.addingTimeInterval(60))- #expect(result.turnCount == 1)- let current = try await store.currentTurns()- #expect(CodexTokenTurn.dailyUsage(current, now: TestFixtures.now.addingTimeInterval(60))[day]?.totalTokens == 110)- try append("\n", to: source)- #expect(try await daily(makeStore(directory))[day]?.totalTokens == 310)- }-- @Test func rebuildGroupsCrossMidnightChildUsageUnderRootStartDay() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let rootStart = try #require(CodexDateFormat.dayDate(from: day)).addingTimeInterval(-10)- let rootDay = CodexDateFormat.dayString(from: rootStart)- let main = lines(input: 100).replacingOccurrences(- of: String(TestFixtures.now.timeIntervalSince1970), with: String(rootStart.timeIntervalSince1970)- )- _ = try directory.write(main, to: "sessions/rollout-main.jsonl")- let child = metadata(thread: "thread-child") + "\n" + start(turn: "turn-child") + "\n"- + record(input: 300, thread: "thread-child", turn: "turn-child") + "\n"- _ = try directory.write(child, to: "sessions/rollout-child.jsonl")- let store = makeStore(directory)- let result = try await store.rebuild(for: [rootDay], now: TestFixtures.now.addingTimeInterval(60))- #expect(result.turnCount == 2)- #expect(result.dateKeys == [rootDay])- let current = try await store.currentTurns()- #expect(CodexTokenTurn.dailyUsage(current, now: TestFixtures.now.addingTimeInterval(60))[rootDay]?.totalTokens == 420)- }-- @Test func cloudRebuildMarkerOverridesStaleTotalsAndCanClearUsage() {- let stale = turn("main", "a", input: 500)- var rebuilt = turn("main", "a", input: 100)- rebuilt.rebuiltAt = TestFixtures.now- #expect(stale.merging(rebuilt) == rebuilt)- #expect(rebuilt.merging(stale) == rebuilt)- let exported = rebuilt.pseudonymized(salt: Data("account".utf8))- let record = CKRecord(recordType: CodexTokenHistorySync.recordType, recordID: .init(recordName: exported.id))- CodexTokenHistorySync.apply(exported, to: record)- #expect(CodexTokenHistorySync.turn(from: record) == exported)- var cleared = exported- cleared.usage = nil- cleared.rebuiltAt = TestFixtures.now.addingTimeInterval(1)- CodexTokenHistorySync.apply(cleared, to: record)- #expect(CodexTokenHistorySync.turn(from: record) == cleared)- #expect(exported.merging(cleared).usage == nil)- #expect(CodexTokenTurn.syncable([cleared]) == [cleared])- }-- @Test(arguments: [false, true])- func cloudBaselineRecoveryReplaysNewUsageWithoutRevivingOldTotals(scanBeforeRecovery: Bool) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let source = try directory.write(lines(input: 100), to: "sessions/rollout-main.jsonl")- let store = makeStore(directory)- let rebuiltAt = TestFixtures.now.addingTimeInterval(60)- _ = try await store.rebuild(for: [day], now: rebuiltAt)- let corrected = try #require(try await store.currentTurns().first)- let salt = Data("test-account".utf8)- let remote = corrected.pseudonymized(salt: salt)- let unrelated = turn("other-device", "other-turn", input: 900).pseudonymized(salt: salt)- let baseline = CodexTokenHistoryBaseline(salt: salt, turns: [remote.id: remote, unrelated.id: unrelated])- try FileManager.default.removeItem(at: directory.url.appendingPathComponent("history"))- // 同一文件混有旧的大数值和重建后的新记录, 聚合时间较新不能证明聚合值也较新- let newRecord = record(input: 200).replacingOccurrences(- of: "2026-09-15T08:00:10Z", with: rebuiltAt.addingTimeInterval(20).ISO8601Format()- )- try Data((lines(input: 500) + newRecord + "\n").utf8).write(to: source)- if scanBeforeRecovery {- #expect(try await daily(makeStore(directory))[day]?.totalTokens == 510)- }- let restored = try await makeStore(directory).refresh(now: rebuiltAt.addingTimeInterval(30), baseline: baseline)- let recovered = try #require(restored.first)- #expect(restored.count == 1)- #expect(recovered.rebuiltAt == corrected.rebuiltAt)- #expect(recovered.usage?.totalTokens == 210)- #expect(remote.merging(recovered.pseudonymized(salt: salt)).usage?.totalTokens == 210)- // 新进程且本轮云端不可用, 仍然记住恢复边界, 归档旧副本不能重新抬高统计- _ = try directory.write(lines(input: 700), to: "archived_sessions/rollout-old.jsonl")- #expect(try await daily(makeStore(directory))[day]?.totalTokens == 210)- let nextRecord = record(input: 300).replacingOccurrences(- of: "2026-09-15T08:00:10Z", with: rebuiltAt.addingTimeInterval(40).ISO8601Format()- )- try append(nextRecord + "\n", to: source)- #expect(try await daily(makeStore(directory))[day]?.totalTokens == 310)- }-- @Test func recoveredClearUsageAndSmallBudgetSurviveRestarts() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let body = "{\"type\":\"response_item\",\"payload\":\"" + String(repeating: "x", count: 8192) + "\"}\n"- let file = try directory.write(lines(input: 500) + body, to: "sessions/rollout-main.jsonl")- let original = try #require(try await makeStore(directory).refresh(now: TestFixtures.now).first)- var cleared = original- cleared.usage = nil- cleared.rebuiltAt = TestFixtures.now.addingTimeInterval(60)- let salt = Data("account".utf8)- let cloud = cleared.pseudonymized(salt: salt)- let baseline = CodexTokenHistoryBaseline(salt: salt, turns: [cloud.id: cloud])- let record = record(input: 200).replacingOccurrences(- of: "2026-09-15T08:00:10Z", with: TestFixtures.now.addingTimeInterval(80).ISO8601Format()- )- try append(record + "\n", to: file)- var turns: [CodexTokenTurn] = []- for iteration in 0 ..< 12 {- let store = CodexTokenHistoryStore(- codexHomeURL: directory.url, directoryURL: directory.url.appendingPathComponent("history"), byteBudget: 1024- )- turns = try await store.refresh(now: TestFixtures.now.addingTimeInterval(90), baseline: baseline)- if iteration == 0 {- #expect(turns.first?.usage == nil)- }- }- #expect(turns.first?.usage?.totalTokens == 210)- #expect(turns.first?.rebuiltAt == cleared.rebuiltAt)- // 较早的云端基线不能覆盖后续手动重建- try Data(lines(input: 100).utf8).write(to: file, options: .atomic)- _ = try await makeStore(directory).rebuild(for: [day], now: TestFixtures.now.addingTimeInterval(120))- let rebuilt = try await makeStore(directory).refresh(now: TestFixtures.now.addingTimeInterval(130), baseline: baseline)- #expect(rebuilt.first?.usage?.totalTokens == 110)- }-- @Test func recoveryKeepsChildUsageUnderRootDayWithoutImportingRemoteOnlyTurns() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- _ = try directory.write(lines(input: 100), to: "sessions/rollout-main.jsonl")- let child = metadata(thread: "thread-child") + "\n" + start(turn: "turn-child") + "\n"- + record(input: 200, thread: "thread-child", turn: "turn-child") + "\n"- let childFile = try directory.write(child, to: "sessions/rollout-child.jsonl")- let store = makeStore(directory)- _ = try await store.rebuild(for: [day], now: TestFixtures.now.addingTimeInterval(60))- let salt = Data("account".utf8)- let remote = try await store.currentTurns().map { $0.pseudonymized(salt: salt) }- let baseline = CodexTokenHistoryBaseline(salt: salt, turns: CodexTokenTurn.merged(remote))- try FileManager.default.removeItem(at: directory.url.appendingPathComponent("history"))- let updated = record(input: 300, thread: "thread-child", turn: "turn-child").replacingOccurrences(- of: "2026-09-15T08:00:10Z", with: TestFixtures.now.addingTimeInterval(80).ISO8601Format()- )- try append(updated + "\n", to: childFile)- let turns = try await makeStore(directory).refresh(now: TestFixtures.now.addingTimeInterval(90), baseline: baseline)- #expect(turns.count == 2)- #expect(CodexTokenTurn.dailyUsage(turns, now: TestFixtures.now.addingTimeInterval(90))[day]?.totalTokens == 420)- let childID = CodexTokenTurn.identifier(thread: "thread-child", turn: "turn-child")- #expect(turns.first { $0.id == childID }?.startedAt == TestFixtures.now)- #expect(turns.first { $0.id == childID }?.rootID == CodexTokenTurn.identifier(thread: "thread-main", turn: "turn-main"))- }-- @Test func cloudRecoveryMatchesAccountSaltAndRootIdentity() {- let local = turn("child", "b", root: CodexTokenTurn.identifier(thread: "main", turn: "a"), input: 100)- var remote = local.pseudonymized(salt: Data("account-a".utf8))- remote.rebuiltAt = TestFixtures.now- #expect(CodexTokenHistoryBaseline(salt: Data("account-b".utf8), turns: [remote.id: remote]).replacement(for: local) == nil)- let baseline = CodexTokenHistoryBaseline(salt: Data("account-a".utf8), turns: [remote.id: remote])- #expect(baseline.replacement(for: local)?.rootID == local.rootID)- var unknownRoot = local- unknownRoot.rootID = local.id- #expect(baseline.replacement(for: unknownRoot) == nil)- }-- @Test func sharedSyncLockExcludesConcurrentWritersWithoutBlockingCacheReads() throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let first = try #require(try CodexTokenFileStorage.acquireLock(in: directory.url, name: "sync.lock", nonblocking: true))- let competing = try CodexTokenFileStorage.acquireLock(in: directory.url, name: "sync.lock", nonblocking: true)- #expect(competing == nil)- if let competing {- CodexTokenFileStorage.releaseLock(competing)- }- try CodexTokenFileStorage.withLock(in: directory.url) {}- CodexTokenFileStorage.releaseLock(first)- let next = try #require(try CodexTokenFileStorage.acquireLock(in: directory.url, name: "sync.lock", nonblocking: true))- CodexTokenFileStorage.releaseLock(next)- }-- @Test func freshHistoryReadsRecentFilesBeforeOlderBackfill() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- for index in 0 ..< 20 {- _ = try directory.write(lines(input: 100), to: "sessions/rollout-\(index).jsonl")- }- let files = try FileManager.default.contentsOfDirectory(at: directory.url.appendingPathComponent("sessions"), includingPropertiesForKeys: nil)- let recent = try #require(files.last)- for file in files {- try FileManager.default.setAttributes([.modificationDate: TestFixtures.now.addingTimeInterval(-86400)], ofItemAtPath: file.path)- }- try Data(lines(input: 10000).utf8).write(to: recent)- try FileManager.default.setAttributes([.modificationDate: TestFixtures.now], ofItemAtPath: recent.path)- let store = CodexTokenHistoryStore(codexHomeURL: directory.url, directoryURL: directory.url.appendingPathComponent("history"), byteBudget: 2048)- #expect(try await daily(store)[day]?.totalTokens == 10010)- }-- @Test func cumulativeSnapshotsAndMultipleDevicesCountEachThreadTurnOnce() {- let root = turn("main", "a", input: 100)- var updated = turn("main", "a", input: 200)- updated.updatedAt = TestFixtures.now.addingTimeInterval(10)- let child = turn("child", "b", root: root.id, input: 300)- let result = CodexTokenTurn.dailyUsage([root, updated, root, child, child], now: TestFixtures.now.addingTimeInterval(60))- #expect(result[day]?.totalTokens == 520)- #expect(CodexTokenTurn.merged([updated, root])[root.id] == CodexTokenTurn.merged([root, updated])[root.id])- }-- @Test func allChildrenIncludingLaterTurnsBelongToRootStartDate() throws {- let start = try #require(CodexDateFormat.dayDate(from: "2026-09-15")?.addingTimeInterval(86390))- var root = turn("main", "a", input: 100)- root.startedAt = start- root.updatedAt = start.addingTimeInterval(30)- var child = turn("child", "b", root: root.id, input: 200)- child.startedAt = start.addingTimeInterval(20)- child.updatedAt = start.addingTimeInterval(80)- var followup = turn("child", "c", root: root.id, input: 300)- followup.startedAt = start.addingTimeInterval(40)- followup.updatedAt = start.addingTimeInterval(90)- let days = CodexTokenTurn.dailyUsage([root, child, followup], now: start.addingTimeInterval(100))- #expect(days.count == 1)- #expect(days["2026-09-15"]?.totalTokens == 630)- #expect(CodexTokenTurn.dailyUsage([child], now: start.addingTimeInterval(100)).isEmpty)- }-- @Test func cacheRateUsesDailyTotalsAndMissingUsageDoesNotBecomeZero() {- var a = turn("main", "a", input: 100)- var b = turn("other", "a", input: 300)- a.usage = usage(input: 100, cached: 80)- b.usage = usage(input: 300, cached: 30)- let merged = CodexTokenTurn.dailyUsage([a, b], now: TestFixtures.now)- #expect(merged[day]?.cacheHitRate == 0.275)- a.usage = nil- #expect(CodexTokenTurn.dailyUsage([a], now: TestFixtures.now).isEmpty)- a.usage = CodexTokenUsage(inputTokens: 0, cachedInputTokens: 0, cacheWriteInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0, totalTokens: 0)- #expect(CodexTokenTurn.dailyUsage([a], now: TestFixtures.now)[day]?.totalTokens == 0)- }-- @Test func cloudCodecUsesAccountScopedHashesAndRetainsAllCounters() throws {- let source = turn("private-thread", "private-turn", input: 100)- let exported = source.pseudonymized(salt: Data("account-a".utf8))- #expect(exported.id == exported.rootID)- #expect(exported.id != source.id)- #expect(exported.id != source.pseudonymized(salt: Data("account-b".utf8)).id)- let zone = CKRecordZone.ID(zoneName: "test", ownerName: CKCurrentUserDefaultName)- let id = CodexTokenHistorySync.recordID(exported.id, zoneID: zone)- #expect(id.recordName == exported.id)- let record = CKRecord(recordType: CodexTokenHistorySync.recordType, recordID: id)- CodexTokenHistorySync.apply(exported, to: record)- #expect(CodexTokenHistorySync.turn(from: record) == exported)- #expect(record.allKeys().sorted() == ["observedAt", "rootID", "schemaVersion", "startedAt", "usage"])- let text = try #require(String(data: JSONEncoder().encode(exported), encoding: .utf8))- #expect(!text.contains("private-thread"))- #expect(!text.contains("private-turn"))- record["schemaVersion"] = 99 as CKRecordValue- #expect(record.recordID == CodexTokenHistorySync.recordID(exported.id, zoneID: zone))- #expect(CodexTokenHistorySync.turn(from: record) == nil)- }-- @Test func incrementalReadRestartAndArchivedCopiesDoNotDuplicateUsage() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let file = try directory.write(lines(input: 100), to: "sessions/2026/09/15/rollout-main.jsonl")- let store = makeStore(directory)- #expect(try await daily(store)[day]?.totalTokens == 110)- try append(record(input: 200), to: file)- #expect(try await daily(store)[day]?.totalTokens == 110)- try append("\n", to: file)- #expect(try await daily(store)[day]?.totalTokens == 210)- let restarted = makeStore(directory)- _ = try directory.write(Data(contentsOf: file), to: "archived_sessions/rollout-copy.jsonl")- #expect(try await daily(restarted)[day]?.totalTokens == 210)- let ledger = try String(contentsOf: directory.url.appendingPathComponent("history/ledger.json"), encoding: .utf8)- #expect(!ledger.contains("thread-main"))- #expect(!ledger.contains("turn-main"))- #expect(!ledger.contains("PRIVATE_BODY"))- }-- @Test func childInheritedHistoryIsIgnoredAndNewUsageIsIncludedOnce() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- _ = try directory.write(lines(input: 100), to: "sessions/rollout-main.jsonl")- let child = metadata(thread: "thread-child", session: "thread-main") + "\n" + lines(input: 100)- + start(turn: "turn-child") + "\n" + record(input: 300, thread: "thread-child", turn: "turn-child") + "\n"- _ = try directory.write(child, to: "sessions/rollout-child.jsonl")- #expect(try await daily(makeStore(directory))[day]?.totalTokens == 420)- }-- @Test func truncationAndReplacementPreserveKnownConsumptionWithoutDoubleCounting() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let file = try directory.write(lines(input: 100), to: "sessions/rollout-main.jsonl")- let store = makeStore(directory)- #expect(try await daily(store)[day]?.totalTokens == 110)- try Data(lines(input: 300).utf8).write(to: file)- #expect(try await daily(store)[day]?.totalTokens == 310)- try Data(lines(input: 100).utf8).write(to: file, options: .atomic)- #expect(try await daily(store)[day]?.totalTokens == 310)- }-- @Test func boundedReadsCrossOversizedBodyAndNeverLoseFollowingUsage() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let body = "{\"type\":\"response_item\",\"payload\":{\"text\":\"" + String(repeating: "x", count: 3 * 1024 * 1024) + "\"}}\n"- _ = try directory.write(lines(input: 100) + body + record(input: 300) + "\n", to: "sessions/rollout-main.jsonl")- let store = CodexTokenHistoryStore(codexHomeURL: directory.url, directoryURL: directory.url.appendingPathComponent("history"), byteBudget: 256 * 1024)- var result: [String: CodexTokenUsage] = [:]- for _ in 0 ..< 15 {- result = try await daily(store)- }- #expect(result[day]?.totalTokens == 310)- }-- @Test func malformedUsageAndLegacySnapshotsCannotInventCounts() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let invalid = record(input: 100).replacingOccurrences(of: "\"input_tokens\":100", with: "\"input_tokens\":-1")- let legacy = "{\"type\":\"event_msg\",\"payload\":{\"type\":\"token_count\"}}\n"- _ = try directory.write(metadata() + "\n" + start() + "\n" + invalid + "\n" + legacy, to: "sessions/rollout-main.jsonl")- #expect(try await daily(makeStore(directory)).isEmpty)- }-- @Test func smallReadBudgetStopsAtOneLineAndEventuallyCatchesUp() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let records = (1 ... 100).map { record(input: $0 * 100) + "\n" }.joined()- _ = try directory.write(metadata() + "\n" + start() + "\n" + records, to: "sessions/rollout-main.jsonl")- let store = CodexTokenHistoryStore(codexHomeURL: directory.url, directoryURL: directory.url.appendingPathComponent("history"), byteBudget: 256)- let initial = try await daily(store)- #expect((initial[day]?.totalTokens ?? 0) < 10010)- var result = initial- for _ in 0 ..< 110 {- result = try await daily(store)- }- #expect(result[day]?.totalTokens == 10010)- }-- @Test func childUsageWaitsForRootStartAndNeedsNoRootUsageRecord() {- var root = turn("main", "a", input: 100)- root.usage = nil- let child = turn("child", "b", root: root.id, input: 200)- #expect(CodexTokenTurn.dailyUsage([child], now: TestFixtures.now).isEmpty)- #expect(CodexTokenTurn.dailyUsage([root, child], now: TestFixtures.now)[day]?.totalTokens == 210)- #expect(Set(CodexTokenTurn.syncable([root, child]).map(\.id)) == [root.id, child.id])- }-- @Test func dailyOverflowIsUnavailableAndExpiredTurnsAreExcluded() {- var root = turn("main", "a", input: 100)- root.usage = CodexTokenUsage(- inputTokens: .max, cachedInputTokens: 0, cacheWriteInputTokens: 0,- outputTokens: 0, reasoningOutputTokens: 0, totalTokens: .max- )- let child = turn("child", "b", root: root.id, input: 200)- #expect(CodexTokenTurn.dailyUsage([root, child], now: TestFixtures.now).isEmpty)- root.startedAt = TestFixtures.now.addingTimeInterval(-220 * 86400)- #expect(CodexTokenTurn.dailyUsage([root], now: TestFixtures.now).isEmpty)- }-- @Test func heatmapSeparatesAccountIntensityFromRolloutDailyMetrics() throws {- var workflow = WorkflowSnapshot.empty- workflow.tokenUsageByDate = [day: usage(input: 100)]- let grid = UsageHeatmapDay.grid(usage: nil, workflow: workflow, showsWorkflow: true, columnCount: 2, today: TestFixtures.now)- let today = try #require(grid.compactMap(\.self).first { $0.startDate == day })- #expect(today.tokenState == .unavailable)- #expect(today.tokenUsage?.totalTokens == 110)- #expect(today.workflow.turnCount == 0)- }-- private var day: String {- CodexDateFormat.dayString(from: TestFixtures.now)- }-- private func usage(input: Int64, cached: Int64 = 20) -> CodexTokenUsage {- CodexTokenUsage(inputTokens: input, cachedInputTokens: cached, cacheWriteInputTokens: 5, outputTokens: 10, reasoningOutputTokens: 2, totalTokens: input + 10)- }-- private func turn(_ thread: String, _ turn: String, root: String? = nil, input: Int64) -> CodexTokenTurn {- let id = CodexTokenTurn.identifier(thread: thread, turn: turn)- return CodexTokenTurn(id: id, rootID: root ?? id, startedAt: TestFixtures.now, updatedAt: TestFixtures.now, usage: usage(input: input))- }-- private func makeStore(_ directory: TestDirectory) -> CodexTokenHistoryStore {- CodexTokenHistoryStore(codexHomeURL: directory.url, directoryURL: directory.url.appendingPathComponent("history"))- }-- private func daily(_ store: CodexTokenHistoryStore) async throws -> [String: CodexTokenUsage] {- try await CodexTokenTurn.dailyUsage(store.refresh(now: TestFixtures.now.addingTimeInterval(60)), now: TestFixtures.now.addingTimeInterval(60))- }-- private func metadata(thread: String = "thread-main", session: String = "thread-main") -> String {- "{\"type\":\"session_meta\",\"payload\":{\"id\":\"\(thread)\",\"session_id\":\"\(session)\",\"source\":\"cli\"}}"- }-- private func start(turn: String = "turn-main") -> String {- "{\"type\":\"event_msg\",\"payload\":{\"type\":\"task_started\",\"turn_id\":\"\(turn)\",\"started_at\":\(TestFixtures.now.timeIntervalSince1970)}}"- }-- private func record(input: Int, thread: String = "thread-main", turn: String = "turn-main") -> String {- """- {"timestamp":"2026-09-15T08:00:10Z","type":"token_usage_record","payload":{"thread_id":"\(thread)","session_id":"thread-main",\- "turn_id":"\(turn)","root_turn_id":"turn-main","response_id":"response-\(input)","turn_token_usage":{\- "input_tokens":\(input),"cached_input_tokens":20,"cache_write_input_tokens":5,"output_tokens":10,"reasoning_output_tokens":2,"total_tokens":\(input + 10)}}}- """- }-- private func lines(input: Int) -> String {- metadata() + "\n" + start() + "\n{\"type\":\"response_item\",\"payload\":{\"text\":\"PRIVATE_BODY\"}}\n" + record(input: input) + "\n"- }-- private func append(_ text: String, to url: URL) throws {- let handle = try FileHandle(forWritingTo: url)- defer { try? handle.close() }- try handle.seekToEnd()- try handle.write(contentsOf: Data(text.utf8))- }-}diff --git a/CodexBarTests/CodexVersionAndProxyTests.swift b/CodexBarTests/CodexVersionAndProxyTests.swiftdeleted file mode 100644index 4ac9610..0000000--- a/CodexBarTests/CodexVersionAndProxyTests.swift+++ /dev/null@@ -1,166 +0,0 @@-import Foundation-import Testing--struct CodexVersionAndProxyTests {- @Test(arguments: [- ("0.150.0", false),- ("0.152.1", false),- ("0.153.0-alpha.2", false),- ("0.153.0", true),- ("0.153.1", true)- ])- func advancedModeRequiresTokenUsageRecordSupport(_ version: String, _ expected: Bool) {- #expect(CodexCLIVersionReader.isVersion(version, atLeast: CodexCLIMinimumVersion.advancedMode) == expected)- #expect(CodexCLIVersionReader.isVersion(version, atLeast: CodexCLIMinimumVersion.global) == true)- }-- @Test(arguments: [- ("0.149.9", "0.150.0", false),- ("0.150.0", "0.150.0", true),- ("0.150.0-alpha.2", "0.150.0", false),- ("0.150.0-alpha.10", "0.150.0-alpha.2", true),- ("0.150.0-beta", "0.150.0-alpha.10", true),- ("1.0.0", "0.150.0", true),- ("codex-cli 0.150.0+build1", "0.150.0+build2", true)- ])- func minimumVersionComparesNumericAndPrereleaseComponents(_ version: String, _ minimum: String, _ expected: Bool) {- #expect(CodexCLIVersionReader.isVersion(version, atLeast: minimum) == expected)- }-- @Test(arguments: ["unknown", "0.150", "0.150.x", "0.150.0-", "0.150.0-alpha..1"])- func unrecognizedVersionHasNoOrdering(_ version: String) {- #expect(CodexCLIVersionReader.isVersion(version, atLeast: "0.150.0") == nil)- }-- @Test func installedUpgradeDoesNotReplaceActualRunningVersion() {- let item = CodexCLIVersionItem(source: .global, path: "/new/codex", version: "0.151.0")- let connection = CodexCLIConnectionInfo(source: .global, executablePath: "/running/codex", version: "0.149.0", openedAt: TestFixtures.now)- let display = CodexCLIVersionDisplay(item: item, connection: connection)- #expect(display.displayVersion == "0.149.0")- #expect(display.path == "/running/codex")- #expect(display.newerInstalledVersion == "0.151.0")- }-- @Test func explicitMissingCLISourceDoesNotSilentlyFallback() throws {- let installations = CodexCLIInstallations(globalPath: nil, bundledPath: "/app/codex")- #expect(try CodexCLIResolver.command(from: installations).source == .bundled)- #expect(throws: (any Error).self) {- try CodexCLIResolver.command(from: installations, source: .global)- }- }-- @Test func codexHomeUsesExplicitEnvironmentAndTrimsWhitespace() {- #expect(CodexCLIResolver.codexHomeDirectory(environment: ["CODEX_HOME": " /tmp/custom ", "HOME": "/tmp/home"]).path == "/tmp/custom")- #expect(CodexCLIResolver.codexHomeDirectory(environment: ["CODEX_HOME": " ", "HOME": "/tmp/home"]).path == "/tmp/home/.codex")- }-- @Test func bundledCLIUsesManifestEntrypointBeforeLegacyPath() throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- _ = try directory.write(#"{"entrypoint":"custom/cli","version":"0.158.0","layoutVersion":1}"#, to: "codex-cli/codex-package.json")- let entrypoint = try writeExecutable(in: directory, path: "codex-cli/custom/cli")- _ = try writeExecutable(in: directory, path: "codex")-- let installations = CodexCLIResolver.resolveInstallations(environment: ["PATH": ""], bundledResourceURL: directory.url)- #expect(installations.bundledPath == entrypoint.path)- #expect(installations.globalPath == nil)- #expect(try CodexCLIResolver.command(from: installations).executablePath == entrypoint.path)- }-- @Test(arguments: [nil, "invalid", "{}", #"{"entrypoint":42}"#, #"{"entrypoint":""}"#, #"{"entrypoint":"bin/missing"}"#, #"{"entrypoint":"bin/codex"}"#])- func unavailablePackageFallsBackToLegacyPath(_ manifest: String?) throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- if let manifest {- _ = try directory.write(manifest, to: "codex-cli/codex-package.json")- }- let nonExecutable = try directory.write("", to: "codex-cli/bin/codex")- try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: nonExecutable.path)- let legacy = try writeExecutable(in: directory, path: "codex")-- let installations = CodexCLIResolver.resolveInstallations(environment: ["PATH": ""], bundledResourceURL: directory.url)- #expect(installations.bundledPath == legacy.path)- #expect(installations.globalPath == nil)- try FileManager.default.removeItem(at: legacy)- let missing = CodexCLIResolver.resolveInstallations(environment: ["PATH": ""], bundledResourceURL: directory.url)- #expect(missing.bundledPath == nil)- }-- @Test func globalCLIStillTakesPriorityOverManifestEntrypoint() throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- _ = try directory.write(#"{"entrypoint":"bin/codex"}"#, to: "codex-cli/codex-package.json")- let bundled = try writeExecutable(in: directory, path: "codex-cli/bin/codex")- let global = try writeExecutable(in: directory, path: "global/codex")-- let installations = CodexCLIResolver.resolveInstallations(- environment: ["PATH": global.deletingLastPathComponent().path],- bundledResourceURL: directory.url- )- #expect(installations.globalPath == global.path)- #expect(installations.bundledPath == bundled.path)- #expect(try CodexCLIResolver.command(from: installations).source == .global)- #expect(try CodexCLIResolver.command(from: installations, source: .bundled).executablePath == bundled.path)- }-- @Test(arguments: ["codex-cli/bin/codex", "codex"])- func pathSymlinkToBundledCLIIsNotClassifiedAsGlobal(_ target: String) throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- _ = try directory.write(#"{"entrypoint":"bin/codex"}"#, to: "codex-cli/codex-package.json")- let bundled = try writeExecutable(in: directory, path: "codex-cli/bin/codex")- _ = try writeExecutable(in: directory, path: "codex")- let link = directory.url.appendingPathComponent("global/codex")- try FileManager.default.createDirectory(at: link.deletingLastPathComponent(), withIntermediateDirectories: true)- try FileManager.default.createSymbolicLink(at: link, withDestinationURL: directory.url.appendingPathComponent(target))-- let installations = CodexCLIResolver.resolveInstallations(- environment: ["PATH": link.deletingLastPathComponent().path],- bundledResourceURL: directory.url- )- #expect(installations.globalPath == nil)- #expect(installations.bundledPath == bundled.path)- }-- private func writeExecutable(in directory: TestDirectory, path: String) throws -> URL {- let url = try directory.write("#!/bin/sh\nexit 0\n", to: path)- try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url.path)- return url- }-- @Test(arguments: ["https://proxy.example", "host/path", "user@host", "host?query", "host#fragment", "host name", "[invalid]", "fe80::1%en0"])- func proxyRejectsAmbiguousHostInput(_ host: String) {- let configuration = CodexProxyConfiguration(host: host, port: "8080")- #expect(throws: (any Error).self) { try configuration.validated() }- }-- @Test(arguments: ["0", "65536", "-1", "abc", "1.5"])- func proxyRejectsInvalidPorts(_ port: String) {- #expect(throws: (any Error).self) { try CodexProxyConfiguration(host: "localhost", port: port).validated() }- }-- @Test func proxyNormalizesIPv6AndPortAndEncodesCredentials() throws {- let configuration = CodexProxyConfiguration(isEnabled: true, transport: .https, host: " ::1 ", port: " 08080 ", usesAuthentication: true, username: "user@name")- let validated = try configuration.validated()- #expect(validated.host == "[::1]")- #expect(validated.port == "8080")- let environment = try configuration.environment(overriding: ["PATH": "/bin", "NO_PROXY": "*"], password: "p:@/#")- for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "WS_PROXY", "WSS_PROXY"] {- #expect(environment[key] == "https://user%40name:p%3A%40%2F%23@[::1]:8080")- #expect(environment[key.lowercased()] == environment[key])- }- #expect(environment["NO_PROXY"] == "localhost,127.0.0.1,::1")- #expect(environment["PATH"] == "/bin")- }-- @Test func disabledInvalidProxyPreservesInheritedEnvironment() throws {- let base = ["HTTPS_PROXY": "http://inherited:80", "NO_PROXY": "example.com"]- #expect(try CodexProxyConfiguration().environment(overriding: base, password: "") == base)- }-- @Test(arguments: ["", "name:password", "name\n"])- func proxyRejectsInvalidAuthenticationUsernames(_ username: String) {- let configuration = CodexProxyConfiguration(host: "localhost", port: "80", usesAuthentication: true, username: username)- #expect(configuration.validationIssues.contains { $0.field == .username })- }-}diff --git a/CodexBarTests/CodexVersionTests.swift b/CodexBarTests/CodexVersionTests.swiftnew file mode 100644index 0000000..5c091e5--- /dev/null+++ b/CodexBarTests/CodexVersionTests.swift@@ -0,0 +1,117 @@+import Foundation+import Testing++struct CodexVersionTests {+ @Test(arguments: [+ ("0.150.0", false),+ ("0.152.1", false),+ ("0.160.0-alpha.2", false),+ ("0.160.0", true),+ ("0.160.1", true)+ ])+ func activityRequiresSharedServerProtocol(_ version: String, _ expected: Bool) {+ #expect(CodexVersionReader.isVersion(version, atLeast: CodexMinimumVersion.activity) == expected)+ #expect(CodexVersionReader.isVersion(version, atLeast: CodexMinimumVersion.global) == expected)+ }++ @Test(arguments: [+ ("0.149.9", "0.150.0", false),+ ("0.150.0", "0.150.0", true),+ ("0.150.0-alpha.2", "0.150.0", false),+ ("0.150.0-alpha.10", "0.150.0-alpha.2", true),+ ("0.150.0-beta", "0.150.0-alpha.10", true),+ ("1.0.0", "0.150.0", true),+ ("codex-cli 0.150.0+build1", "0.150.0+build2", true)+ ])+ func minimumVersionComparesNumericAndPrereleaseComponents(_ version: String, _ minimum: String, _ expected: Bool) {+ #expect(CodexVersionReader.isVersion(version, atLeast: minimum) == expected)+ }++ @Test(arguments: ["unknown", "0.150", "0.150.x", "0.150.0-", "0.150.0-alpha..1"])+ func unrecognizedVersionHasNoOrdering(_ version: String) {+ #expect(CodexVersionReader.isVersion(version, atLeast: "0.150.0") == nil)+ }++ @Test func installedVersionDoesNotClaimToBeSharedServerVersion() {+ let item = CodexVersionItem(source: .global, path: "/installed/codex", version: "0.160.1")+ let display = CodexVersionDisplay(item: item)+ #expect(display.displayVersion == "0.160.1")+ #expect(display.path == "/installed/codex")+ }++ @Test func codexHomeUsesExplicitEnvironmentAndTrimsWhitespace() {+ #expect(CodexPaths.codexHomeDirectory(environment: ["CODEX_HOME": " /tmp/custom ", "HOME": "/tmp/home"]).path == "/tmp/custom")+ #expect(CodexPaths.codexHomeDirectory(environment: ["CODEX_HOME": " ", "HOME": "/tmp/home"]).path == "/tmp/home/.codex")+ }++ @Test func bundledCLIUsesManifestEntrypointBeforeLegacyPath() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ _ = try directory.write(#"{"entrypoint":"custom/cli","version":"0.158.0","layoutVersion":1}"#, to: "codex-cli/codex-package.json")+ let entrypoint = try writeExecutable(in: directory, path: "codex-cli/custom/cli")+ _ = try writeExecutable(in: directory, path: "codex")++ let installations = CodexPaths.resolveInstallations(environment: ["PATH": ""], bundledResourceURL: directory.url)+ #expect(installations.bundledPath == entrypoint.path)+ #expect(installations.globalPath == nil)+ }++ @Test(arguments: [nil, "invalid", "{}", #"{"entrypoint":42}"#, #"{"entrypoint":""}"#, #"{"entrypoint":"bin/missing"}"#, #"{"entrypoint":"bin/codex"}"#])+ func unavailablePackageFallsBackToLegacyPath(_ manifest: String?) throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ if let manifest {+ _ = try directory.write(manifest, to: "codex-cli/codex-package.json")+ }+ let nonExecutable = try directory.write("", to: "codex-cli/bin/codex")+ try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: nonExecutable.path)+ let legacy = try writeExecutable(in: directory, path: "codex")++ let installations = CodexPaths.resolveInstallations(environment: ["PATH": ""], bundledResourceURL: directory.url)+ #expect(installations.bundledPath == legacy.path)+ #expect(installations.globalPath == nil)+ try FileManager.default.removeItem(at: legacy)+ let missing = CodexPaths.resolveInstallations(environment: ["PATH": ""], bundledResourceURL: directory.url)+ #expect(missing.bundledPath == nil)+ }++ @Test func globalCLIStillTakesPriorityOverManifestEntrypoint() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ _ = try directory.write(#"{"entrypoint":"bin/codex"}"#, to: "codex-cli/codex-package.json")+ let bundled = try writeExecutable(in: directory, path: "codex-cli/bin/codex")+ let global = try writeExecutable(in: directory, path: "global/codex")++ let installations = CodexPaths.resolveInstallations(+ environment: ["PATH": global.deletingLastPathComponent().path],+ bundledResourceURL: directory.url+ )+ #expect(installations.globalPath == global.path)+ #expect(installations.bundledPath == bundled.path)+ }++ @Test(arguments: ["codex-cli/bin/codex", "codex"])+ func pathSymlinkToBundledCLIIsNotClassifiedAsGlobal(_ target: String) throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ _ = try directory.write(#"{"entrypoint":"bin/codex"}"#, to: "codex-cli/codex-package.json")+ let bundled = try writeExecutable(in: directory, path: "codex-cli/bin/codex")+ _ = try writeExecutable(in: directory, path: "codex")+ let link = directory.url.appendingPathComponent("global/codex")+ try FileManager.default.createDirectory(at: link.deletingLastPathComponent(), withIntermediateDirectories: true)+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: directory.url.appendingPathComponent(target))++ let installations = CodexPaths.resolveInstallations(+ environment: ["PATH": link.deletingLastPathComponent().path],+ bundledResourceURL: directory.url+ )+ #expect(installations.globalPath == nil)+ #expect(installations.bundledPath == bundled.path)+ }++ private func writeExecutable(in directory: TestDirectory, path: String) throws -> URL {+ let url = try directory.write("#!/bin/sh\nexit 0\n", to: path)+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url.path)+ return url+ }+}diff --git a/CodexBarTests/DateAndPresentationTests.swift b/CodexBarTests/DateAndPresentationTests.swiftindex 7ff794b..997cd66 100644--- a/CodexBarTests/DateAndPresentationTests.swift+++ b/CodexBarTests/DateAndPresentationTests.swift@@ -30,18 +30,18 @@ struct DateAndPresentationTests {let today = try #require(CodexDateFormat.dayDate(from: "2026-09-15"))let summary = try TestFixtures.decode(UsageSummary.self, "{}")let usage = CodexUsageSnapshot(summary: summary, dailyBuckets: [])- let grid = UsageHeatmapDay.grid(usage: usage, workflow: .empty, showsWorkflow: true, columnCount: 2, today: today).compactMap(\.self)+ let grid = UsageHeatmapDay.grid(usage: usage, history: .empty, showsActivity: true, columnCount: 2, today: today).compactMap(\.self)#expect(grid.last?.tokenState == .pending)#expect(grid.first?.tokenState == .available(0))- let unavailable = UsageHeatmapDay.grid(usage: nil, workflow: .empty, showsWorkflow: true, columnCount: 2, today: today).compactMap(\.self)+ let unavailable = UsageHeatmapDay.grid(usage: nil, history: .empty, showsActivity: true, columnCount: 2, today: today).compactMap(\.self)#expect(unavailable.allSatisfy { $0.tokenState == .unavailable })- let hiddenToday = UsageHeatmapDay.grid(usage: usage, workflow: .empty, showsWorkflow: false, columnCount: 2, today: today).compactMap(\.self)+ let hiddenToday = UsageHeatmapDay.grid(usage: usage, history: .empty, showsActivity: false, columnCount: 2, today: today).compactMap(\.self)#expect(!hiddenToday.contains { $0.startDate == "2026-09-15" })}@Test func statusItemTerminalExpiresAtTenSecondsWhileCardKeepsHistory() {- let completion = CodexActivityCompletion(id: UUID(), isAnonymous: false, projectName: nil, modelName: nil, effort: nil, completedAt: TestFixtures.now, duration: 30)- let snapshot = CodexActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])+ let completion = ActivityCompletion(id: UUID(), isAnonymous: false, projectName: nil, modelName: nil, effort: nil, completedAt: TestFixtures.now, duration: 30)+ let snapshot = ActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])#expect(snapshot.statusItemActivity(at: TestFixtures.now.addingTimeInterval(9.999)) == .completed(completion))#expect(snapshot.statusItemActivity(at: TestFixtures.now.addingTimeInterval(10)) == .idle)#expect(snapshot.primaryActivity == .completed(completion))@@ -52,14 +52,14 @@ struct DateAndPresentationTests {@Test func waitingTaskTakesPriorityAndAnonymousTasksRemainVisible() {let waiting = task(isAnonymous: true)let running = task(isAnonymous: false)- let snapshot = CodexActivitySnapshot(waitingTasks: [waiting], runningTasks: [running], recentCompletions: [], recentTerminations: [])+ let snapshot = ActivitySnapshot(waitingTasks: [waiting], runningTasks: [running], recentCompletions: [], recentTerminations: [])#expect(snapshot.primaryActivity == .waiting(waiting))#expect(snapshot.activeCount == 2)#expect(snapshot.statusItemActivityExpiration == nil)}- private func task(isAnonymous: Bool) -> CodexActivityTaskSnapshot {- CodexActivityTaskSnapshot(+ private func task(isAnonymous: Bool) -> ActivityTaskSnapshot {+ ActivityTaskSnapshot(id: UUID(), isAnonymous: isAnonymous, latestEvent: .promptSubmitted,projectName: nil, modelName: nil, effort: nil, toolName: nil,startedAt: TestFixtures.now, stateChangedAt: TestFixtures.now,diff --git a/CodexBarTests/HelperRuntimeStatusMonitorTests.swift b/CodexBarTests/HelperStatusMonitorTests.swiftsimilarity index 96%rename from CodexBarTests/HelperRuntimeStatusMonitorTests.swiftrename to CodexBarTests/HelperStatusMonitorTests.swiftindex 964f3f6..f61f8ab 100644--- a/CodexBarTests/HelperRuntimeStatusMonitorTests.swift+++ b/CodexBarTests/HelperStatusMonitorTests.swift@@ -2,9 +2,9 @@ import Foundationimport Testing@Suite(.timeLimit(.minutes(1)))-struct HelperRuntimeStatusMonitorTests {+struct HelperStatusMonitorTests {@Test func observationCanRestartAfterCancellationBeforeFirstTick() async {- let monitor = HelperRuntimeStatusMonitor()+ let monitor = HelperStatusMonitor()defer { monitor.cancelObservation() }let finished = MonitorCheckpoint()monitor.startObservation(interval: .seconds(60)) {@@ -19,7 +19,7 @@ struct HelperRuntimeStatusMonitorTests {}@Test func cancelledObservationCannotClearReplacementWhileItsActionFinishes() async {- let monitor = HelperRuntimeStatusMonitor()+ let monitor = HelperStatusMonitor()defer { monitor.cancelObservation() }let oldEntered = MonitorCheckpoint()let oldRelease = MonitorCheckpoint()@@ -52,7 +52,7 @@ struct HelperRuntimeStatusMonitorTests {}@Test func cancelledStatusReplyCannotFinishNewWakeRequest() async {- let monitor = HelperRuntimeStatusMonitor()+ let monitor = HelperStatusMonitor()let helper = MonitorHelper()let connection = MonitorConnection(helper: helper)defer { monitor.cancelRequest() }@@ -85,7 +85,7 @@ struct HelperRuntimeStatusMonitorTests {}@Test func timeoutClearsRequestAndLateReplyDoesNotPreventReuse() async {- let monitor = HelperRuntimeStatusMonitor()+ let monitor = HelperStatusMonitor()let helper = MonitorHelper()let connection = MonitorConnection(helper: helper)defer { monitor.cancelRequest() }diff --git a/CodexBarTests/HistoryAggregationTests.swift b/CodexBarTests/HistoryAggregationTests.swiftnew file mode 100644index 0000000..dd684c0--- /dev/null+++ b/CodexBarTests/HistoryAggregationTests.swift@@ -0,0 +1,252 @@+import CloudKit+import Foundation+import Testing++struct HistoryAggregationTests {+ @Test func syncStateIsIsolatedByApplicationRoot() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let debugRoot = directory.url.appendingPathComponent("CodexBar Debug", isDirectory: true)+ let releaseRoot = directory.url.appendingPathComponent("CodexBar", isDirectory: true)+ let debugSync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: debugRoot), isEnabled: { false })+ let releaseSync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: releaseRoot), isEnabled: { false })+ try await releaseSync.markReplacementNeeded(for: ["2026-09-15"])+ #expect(await !debugSync.hasPendingReplacement(for: ["2026-09-15"]))+ try await debugSync.markReplacementNeeded(for: ["2026-10-05"])+ #expect(await !releaseSync.hasPendingReplacement(for: ["2026-10-05"]))+ let restored = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: debugRoot), isEnabled: { false })+ #expect(await restored.hasPendingReplacement(for: ["2026-10-05"]))+ #expect(FileManager.default.fileExists(atPath: debugRoot.appendingPathComponent("Sync/Activity/cache.json").path))+ #expect(FileManager.default.fileExists(atPath: releaseRoot.appendingPathComponent("Sync/Activity/cache.json").path))+ #expect(SyncCloudKit.zoneName == "CodexBarAppZone")+ let root = AppStorage.directoryURL()+ #if DEBUG+ #expect(root.lastPathComponent == "CodexBar Debug")+ #else+ #expect(root.lastPathComponent == "CodexBar")+ #endif+ #expect(HistoryStorage.directoryURL() == root)+ #expect(HistoryStorage.syncDirectoryURL() == root.appendingPathComponent("Sync", isDirectory: true))+ #expect(AppServerLogStore.defaultDirectory == root.appendingPathComponent("Logs", isDirectory: true))+ }++ @Test func identifierFieldsUseModelPropertyNames() throws {+ let aggregate = try TestFixtures.decode(ActivityAggregate.self, #"{"date":"2026-09-15","sessionIDs":["session-a"],"turnIDs":["turn-a"]}"#)+ #expect(aggregate.sessionIDs == ["session-a"])+ #expect(aggregate.turnIDs == ["turn-a"])+ let encoded = try JSONEncoder().encode(aggregate)+ let fields = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any])+ #expect(fields["sessionIDs"] as? [String] == ["session-a"])+ #expect(fields["turnIDs"] as? [String] == ["turn-a"])+ #expect(fields["sessionIds"] == nil)+ #expect(fields["turnIds"] == nil)++ let record = try TestFixtures.decode(ActivitySyncRecord.self, """+ {"deviceID":"device-a","recordName":"device-a_2026-09-15_source","daily":{"date":"2026-09-15","generationID":"source"}}+ """)+ #expect(record.deviceID == "device-a")+ let recordData = try JSONEncoder().encode(record)+ let recordFields = try #require(JSONSerialization.jsonObject(with: recordData) as? [String: Any])+ #expect(recordFields["deviceID"] as? String == "device-a")+ #expect(recordFields["deviceIdentifier"] == nil)+ }++ @Test func missingEventCountsRemainUnavailableThroughBothStorageFormats() throws {+ let aggregate = try TestFixtures.decode(ActivityAggregate.self, #"{"date":"2026-09-15","turnCompletedCount":0}"#)+ #expect(aggregate.eventCount == nil)+ #expect(aggregate.turnAbortedCount == nil)+ #expect(aggregate.turnCompletedCount == 0)+ let local = try JSONDecoder().decode(ActivityAggregate.self, from: aggregate.jsonLineData())+ let synced = try JSONDecoder().decode(SyncedActivity.self, from: aggregate.syncedAggregate.jsonLineData())+ #expect(local == aggregate)+ #expect(synced.turnAbortedCount == nil)+ #expect(synced.turnCompletedCount == 0)+ }++ @Test func eventPairsAndIdentifiersAreCountedWithoutDoubleCounting() {+ var accumulator = makeAccumulator()+ for name in [ActivityEventKind.sessionStarted, .turnStarted, .toolStarted, .toolCompleted, .compactionStarted, .compactionCompleted, .subagentStarted, .subagentEnded] {+ accumulator.record(TestFixtures.event(name))+ }+ accumulator.record(TestFixtures.event(.turnCompleted, session: "terminal-only", turn: "terminal-only"))+ accumulator.record(TestFixtures.event(.turnAborted, session: "interrupt-only", turn: "interrupt-only"))+ let retained = accumulator.finalized(identifierStorage: .retained)+ let compacted = accumulator.finalized(identifierStorage: .compacted)+ #expect(retained.eventCount == 10)+ #expect(retained.sessionIDs == ["interrupt-only", "session-a", "terminal-only"])+ #expect(retained.turnIDs == ["turn-a"])+ #expect(retained.metrics.toolCallCount == 1)+ #expect(retained.metrics.contextCompactionCount == 1)+ #expect(retained.metrics.subagentCount == 1)+ #expect(retained.metrics.turnAbortedCount == 1)+ #expect(retained.metrics == compacted.metrics)+ #expect(compacted.sessionIDs == nil)+ #expect(compacted.turnIDs == nil)+ #expect(!compacted.supportsIncrementalAggregation)+ }++ @Test func incrementalAggregationMatchesFullReplay() {+ let firstEvents = [TestFixtures.event(.sessionStarted), TestFixtures.event()]+ let laterEvents = [TestFixtures.event(.toolStarted), TestFixtures.event(turn: "turn-b")]+ var full = makeAccumulator()+ (firstEvents + laterEvents).forEach { full.record($0) }+ var initial = makeAccumulator()+ firstEvents.forEach { initial.record($0) }+ var incremental = ActivityAccumulator(+ appending: initial.finalized(identifierStorage: .retained), generationID: "source", generationStartedEmpty: true+ )+ laterEvents.forEach { incremental.record($0) }+ #expect(incremental.finalized(identifierStorage: .retained) == full.finalized(identifierStorage: .retained))+ }++ @Test func historicalAggregationIncludesAutoReviewEvents() {+ var accumulator = makeAccumulator()+ accumulator.record(TestFixtures.event(origin: .autoReview))+ #expect(accumulator.finalized(identifierStorage: .compacted).metrics.turnCount == 1)+ }++ @Test func sessionEndAloneDoesNotCreateAnActiveSession() {+ var accumulator = makeAccumulator()+ accumulator.record(TestFixtures.event(.sessionEnded, turn: nil))+ let aggregate = accumulator.finalized(identifierStorage: .compacted)+ #expect(aggregate.sessionEndedCount == 1)+ #expect(aggregate.metrics.sessionCount == 0)+ #expect(aggregate.metrics.turnCount == 0)+ }++ @Test func unavailableInterruptCountPropagatesAcrossDeviceMetrics() {+ var known = TestFixtures.aggregate()+ known.turnAbortedCount = 3+ var unknown = TestFixtures.aggregate()+ unknown.turnAbortedCount = nil+ #expect(known.metrics.adding(unknown.metrics).turnAbortedCount == nil)+ #expect(known.metrics.adding(known.metrics).turnAbortedCount == 6)+ }++ @Test func modelRankingHasDeterministicTiesAndIgnoresZeroCounts() {+ var aggregate = TestFixtures.aggregate()+ aggregate.modelCounts = ["z-model": 3, "a-model": 3, "unused": 0]+ #expect(aggregate.metrics.mostUsedModel == "a-model")+ aggregate.modelCounts = ["unused": 0]+ #expect(aggregate.metrics.mostUsedModel == nil)+ }++ @Test func compactingLegacyIdentifiersPreservesUniqueCounts() throws {+ var aggregate = try TestFixtures.decode(ActivityAggregate.self, """+ {"date":"2026-09-15","sessionCount":0,"sessionIDs":["a","a","b"],"turnIDs":["x","x"],"turnCompletedCount":9}+ """)+ aggregate.normalizeIdentifierStorage(retainsIdentifiers: false)+ #expect(aggregate.sessionCount == 2)+ #expect(aggregate.turnCount == 1)+ #expect(aggregate.sessionIDs == nil)+ }++ @Test func syncExportContainsCountsWithoutRawTaskIdentifiers() throws {+ var accumulator = makeAccumulator()+ accumulator.record(TestFixtures.event())+ let data = try accumulator.finalized(identifierStorage: .retained).syncedAggregate.jsonLineData()+ let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])+ #expect(object["sessionIDs"] == nil)+ #expect(object["turnIDs"] == nil)+ #expect(object["sessionCount"] as? Int == 1)+ let text = try #require(String(data: data, encoding: .utf8))+ #expect(!text.contains("session-a"))+ }++ @Test func cloudDailyCountsRoundTripWithEventNames() throws {+ let counts = [+ "sessionStartedCount": 1, "sessionEndedCount": 2, "turnStartedCount": 3,+ "turnCompletedCount": 4, "turnAbortedCount": 5, "toolStartedCount": 6,+ "toolCompletedCount": 7, "approvalRequestedCount": 8, "compactionStartedCount": 9,+ "compactionCompletedCount": 10, "subagentStartedCount": 11, "subagentEndedCount": 12+ ]+ var fields: [String: Any] = counts+ fields["date"] = "2026-09-15"+ fields["generationID"] = "source"+ let aggregate = try JSONDecoder().decode(+ SyncedActivity.self, from: JSONSerialization.data(withJSONObject: fields)+ )+ let record = CKRecord(recordType: "Activity", recordID: CKRecord.ID(recordName: "device-a_2026-09-15_source"))+ ActivityRecordCodec.apply(aggregate, deviceID: "device-a", to: record)+ #expect(Set(record.allKeys()) == Set(counts.keys).union([+ "version", "deviceID", "date", "generationID", "projectCounts", "modelCounts", "updatedAt"+ ]))+ for (name, count) in counts {+ #expect((record[name] as? NSNumber)?.intValue == count)+ }+ let restored = try #require(try ActivityRecordCodec.remoteDailyRecord(from: record))+ #expect(restored.deviceID == "device-a")+ #expect(restored.daily == aggregate)++ record["turnAbortedCount"] = nil+ record["toolStartedCount"] = 0 as CKRecordValue+ let missing = try #require(try ActivityRecordCodec.remoteDailyRecord(from: record))+ #expect(missing.daily.turnAbortedCount == nil)+ #expect(missing.daily.toolStartedCount == 0)+ }++ @Test(arguments: [nil, "", " "]) func cloudActivityRejectsMissingGeneration(generation: String?) {+ let record = CKRecord(recordType: "Activity", recordID: CKRecord.ID(recordName: "device_2026-09-15_source"))+ record["deviceID"] = "device" as CKRecordValue+ record["date"] = "2026-09-15" as CKRecordValue+ record["generationID"] = generation as CKRecordValue?+ #expect(throws: ActivitySyncError.self) { try ActivityRecordCodec.remoteDailyRecord(from: record) }+ }++ @Test func cloudAndCachedActivityRejectMismatchedIdentity() throws {+ let daily = SyncedActivity(date: "2026-09-15", generationID: "source", projectCounts: [:], modelCounts: [:])+ let record = CKRecord(recordType: "Activity", recordID: CKRecord.ID(recordName: "device_2026-09-15"))+ ActivityRecordCodec.apply(daily, deviceID: "device", to: record)+ #expect(throws: ActivitySyncError.self) { try ActivityRecordCodec.remoteDailyRecord(from: record) }+ #expect(throws: DecodingError.self) {+ try TestFixtures.decode(ActivitySyncRecord.self, #"{"deviceID":"device","recordName":"device_2026-09-15","daily":{"date":"2026-09-15","generationID":"source"}}"#)+ }+ }++ private func makeAccumulator() -> ActivityAccumulator {+ ActivityAccumulator(rebuilding: "2026-09-15", generationID: "source", generationStartedEmpty: true, eventCountAvailability: .all)+ }+}++struct HistoryMergeTests {+ @Test func sameGenerationUsesOneMostCompleteContribution() throws {+ let local = TestFixtures.aggregate(events: 2, turns: 1)+ let remote = try record(TestFixtures.aggregate(events: 4, turns: 2))+ #expect(snapshot(local, [remote]).dailyMetrics.first?.turnCount == 2)+ #expect(snapshot(TestFixtures.aggregate(events: 6, turns: 3), [remote]).dailyMetrics.first?.turnCount == 3)+ }++ @Test func freshIndependentGenerationAddsToPreviousContribution() throws {+ let local = TestFixtures.aggregate(generation: "new", fresh: true, turns: 2)+ #expect(try snapshot(local, [record(TestFixtures.aggregate(turns: 3))]).dailyMetrics.first?.turnCount == 5)+ }++ @Test func unverifiedLocalGenerationDoesNotDoubleCountRemoteHistory() throws {+ let local = TestFixtures.aggregate(generation: "unknown", fresh: false, turns: 2)+ #expect(try snapshot(local, [record(TestFixtures.aggregate(turns: 3))]).dailyMetrics.first?.turnCount == 3)+ }++ @Test func sameGenerationDeduplicatesAndOtherDevicesStillAdd() throws {+ let local = TestFixtures.aggregate()+ let remote = try record(TestFixtures.aggregate())+ let otherDevice = try record(TestFixtures.aggregate(turns: 4), device: "other")+ #expect(snapshot(local, [remote, otherDevice]).dailyMetrics.first?.turnCount == 5)+ }++ @Test func remoteOnlyDaysRemainVisible() throws {+ let result = try HistorySnapshot(localAggregates: [], syncedRecords: [record(TestFixtures.aggregate(turns: 4))], currentDeviceID: "device")+ #expect(result.dailyMetrics.first?.turnCount == 4)+ }++ private func record(_ aggregate: ActivityAggregate, device: String = "device") throws -> ActivitySyncRecord {+ let generation = try aggregate.syncedAggregate.requiredGenerationID()+ return try ActivitySyncRecord(+ deviceID: device, daily: aggregate.syncedAggregate,+ recordName: ActivitySyncRecord.recordName(deviceID: device, date: aggregate.date, generation: generation)+ )+ }++ private func snapshot(_ local: ActivityAggregate, _ remote: [ActivitySyncRecord]) -> HistorySnapshot {+ HistorySnapshot(localAggregates: [local], syncedRecords: remote, currentDeviceID: "device")+ }+}diff --git a/CodexBarTests/HistoryMaintenanceTests.swift b/CodexBarTests/HistoryMaintenanceTests.swiftnew file mode 100644index 0000000..de79774--- /dev/null+++ b/CodexBarTests/HistoryMaintenanceTests.swift@@ -0,0 +1,153 @@+import Darwin+import Foundation+import Testing++struct HistoryMaintenanceTests {+ @Test func historyMaintenanceUsesOnlyInjectedRoot() async throws {+ let first = try TestDirectory()+ let second = try TestDirectory()+ defer { try? first.remove()+ try? second.remove()+ }+ let recorder = ActivityRecorder(directoryURL: first.url)+ let event = ActivityRecord(+ timestamp: Date(), name: ActivityEventKind.turnStarted.rawValue, origin: .main,+ cwd: nil, tool: nil, model: nil, effort: nil, approvalReviewer: .user,+ sessionID: "session", turnID: "turn", agentID: nil, id: "isolated"+ )+ try await recorder.record(event: event)+ let sync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: first.url), isEnabled: { false })+ let service = HistoryService(directoryURL: first.url, syncService: sync)+ let result = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ #expect(result.counts?.events == 1)+ #expect(FileManager.default.fileExists(atPath: HistoryStorage.dailyURL(in: first.url).path))+ #expect(!FileManager.default.fileExists(atPath: HistoryStorage.dailyURL(in: second.url).path))+ #expect(!HistoryStorage.loadMaintenanceState(in: first.url).days.isEmpty)+ #expect(HistoryStorage.loadMaintenanceState(in: second.url).days.isEmpty)+ }+}++extension HistoryMaintenanceTests {+ @Test func boundaryVerificationDetectsSameMillisecondRewriteAndSurvivesRestart() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let date = HistoryStorage.dateKey(for: now)+ let original = try AppServerEventRecord(activity: TestFixtures.event(.turnStarted, at: now), recordedAt: now).jsonLineData()+ let replacement = try AppServerEventRecord(activity: TestFixtures.event(.toolStarted, at: now), recordedAt: now).jsonLineData()+ #expect(original.count == replacement.count)+ let url = try directory.write(original, to: "Events/\(date).jsonl")+ let seconds = Int(now.timeIntervalSince1970)+ let firstTimes = [timespec(tv_sec: seconds, tv_nsec: 1000100), timespec(tv_sec: seconds, tv_nsec: 1000100)]+ #expect(utimensat(AT_FDCWD, url.path, firstTimes, 0) == 0)+ let sync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { false })+ let service = HistoryService(directoryURL: directory.url, syncService: sync)+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ let stateBefore = HistoryStorage.loadMaintenanceState(in: directory.url)+ let maintenanceBefore = try #require(HistoryStorage.fileStat(at: HistoryStorage.maintenanceURL(in: directory.url)))+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ #expect(HistoryStorage.fileStat(at: HistoryStorage.maintenanceURL(in: directory.url)) == maintenanceBefore)+ let before = try #require(HistoryStorage.fileStat(at: url))+ let handle = try FileHandle(forWritingTo: url)+ try handle.write(contentsOf: replacement)+ try handle.close()+ let secondTimes = [timespec(tv_sec: seconds, tv_nsec: 1000900), timespec(tv_sec: seconds, tv_nsec: 1000900)]+ #expect(utimensat(AT_FDCWD, url.path, secondTimes, 0) == 0)+ let after = try #require(HistoryStorage.fileStat(at: url))+ #expect(before.modificationTime == after.modificationTime)+ #expect(before.modifiedAtNanoseconds != after.modifiedAtNanoseconds)+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ let rebuilt = try #require(JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: HistoryStorage.dailyURL(in: directory.url))).first)+ #expect(rebuilt.toolStartedCount == 1)+ #expect(rebuilt.turnStartedCount == 0)+ #expect(rebuilt.generationID != stateBefore.days[date]?.generationID)+ let restarted = HistoryService(directoryURL: directory.url, syncService: sync)+ let maintenanceAfter = try #require(HistoryStorage.fileStat(at: HistoryStorage.maintenanceURL(in: directory.url)))+ _ = await restarted.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ #expect(HistoryStorage.fileStat(at: HistoryStorage.maintenanceURL(in: directory.url)) == maintenanceAfter)+ }++ @Test func historyLockIsExclusiveAndReleasedWhenWorkThrows() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ enum TestError: Error { case expected }+ #expect(throws: TestError.self) {+ try HistoryStorage.withExclusiveLock(in: directory.url) {+ let descriptor = open(HistoryStorage.lockURL(in: directory.url).path, O_RDWR)+ #expect(descriptor >= 0)+ guard descriptor >= 0 else { throw TestError.expected }+ defer { close(descriptor) }+ let result = flock(descriptor, LOCK_EX | LOCK_NB)+ let lockError = errno+ #expect(result == -1)+ #expect(lockError == EWOULDBLOCK)+ throw TestError.expected+ }+ }+ let descriptor = open(HistoryStorage.lockURL(in: directory.url).path, O_RDWR)+ #expect(descriptor >= 0)+ guard descriptor >= 0 else { return }+ defer { close(descriptor) }+ #expect(flock(descriptor, LOCK_EX | LOCK_NB) == 0)+ #expect(flock(descriptor, LOCK_UN) == 0)+ }++ @Test func legacyMaintenanceStateRequiresRebuildAndNormalizesDateQueues() throws {+ let state = try TestFixtures.decode(HistoryMaintenanceState.self, """+ {"pending":["2026-09-15","invalid","2026-09-14","2026-09-15"],"dirty":["2026-02-30","2026-09-14"]}+ """)+ #expect(state.version == 0)+ #expect(state.pending == ["2026-09-14", "2026-09-15"])+ #expect(state.dirty == ["2026-09-14"])+ }++ @Test func fileReplacementResetsOffsetsHashesAndMarksDayDirty() throws {+ let date = "2026-09-15"+ var state = HistoryMaintenanceState(days: [date: HistoryDayMaintenanceState(+ offset: 50, size: 60, corrupt: 2, generationID: "old", generationStartedEmpty: false,+ fileIdentifier: 1, boundaryHash: "old-hash"+ )])+ state.startNewGeneration(for: date, startedEmpty: true, fileIdentifier: 2)+ let day = try #require(state.days[date])+ #expect(day.offset == 0)+ #expect(day.corrupt == 0)+ #expect(day.generationID != "old")+ #expect(day.generationStartedEmpty)+ #expect(day.fileIdentifier == 2)+ #expect(day.boundaryHash == nil)+ #expect(state.dirty == [date])+ }++ @Test func maintenanceStoragePreservesReadBoundaryAndFileIdentity() throws {+ let date = "2026-09-15"+ let state = HistoryMaintenanceState(pending: [date], dirty: [date], days: [date: HistoryDayMaintenanceState(+ offset: 50, size: 60, corrupt: 2, generationID: "source", generationStartedEmpty: true,+ fileIdentifier: 7, boundaryHash: "digest"+ )])+ let data = try JSONLines.stableEncoder.encode(state)+ let root = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])+ #expect(Set(root.keys) == ["version", "pending", "dirty", "days"])+ let days = try #require(root["days"] as? [String: [String: Any]])+ let day = try #require(days[date])+ #expect(Set(day.keys) == [+ "offset", "size", "corrupt", "generationID", "generationStartedEmpty",+ "fileIdentifier", "boundaryHash"+ ])+ #expect(try JSONDecoder().decode(HistoryMaintenanceState.self, from: data) == state)+ }++ @Test func repeatedPendingAndSourceUpdatesAreIdempotent() throws {+ var state = HistoryMaintenanceState()+ let firstPending = state.markPending("2026-09-15")+ let secondPending = state.markPending("2026-09-15")+ #expect(firstPending)+ #expect(!secondPending)+ let firstSource = state.ensureGenerationID(for: "2026-09-15", fileIdentifier: 1)+ let generation = try #require(state.days["2026-09-15"]?.generationID)+ let secondSource = state.ensureGenerationID(for: "2026-09-15", fileIdentifier: 1)+ #expect(firstSource)+ #expect(!secondSource)+ #expect(state.days["2026-09-15"]?.generationID == generation)+ #expect(state.days["2026-09-15"]?.generationStartedEmpty == false)+ }+}diff --git a/CodexBarTests/HookEventTailReaderTests.swift b/CodexBarTests/HookEventTailReaderTests.swiftdeleted file mode 100644index a012def..0000000--- a/CodexBarTests/HookEventTailReaderTests.swift+++ /dev/null@@ -1,131 +0,0 @@-import Foundation-import Testing--struct HookEventTailReaderTests {- @Test func bootstrapFiltersRetentionAndLiveDrainDoesNotReplayOldEvents() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let recorder = HookBatchRecorder()- let now = TestFixtures.now- let old = TestFixtures.event(at: now.addingTimeInterval(-86401), turn: "old")- let current = TestFixtures.event(at: now, turn: "current")- let path = "\(WorkflowStorage.dateKey(for: now)).jsonl"- let url = try directory.write(old.jsonLineData() + current.jsonLineData(), to: path)- let reader = HookEventTailReader(eventsDirectoryURL: directory.url, now: { now }, onBatch: recorder.receive)- await reader.start()- #expect(recorder.bootstrapEvents.map(\.turnID) == ["current"])- #expect(recorder.liveEvents.isEmpty)- let live = TestFixtures.event(.preToolUse, at: now.addingTimeInterval(1), turn: "live")- try append(live.jsonLineData(), to: url)- let first = await reader.drainNow()- let second = await reader.drainNow()- await reader.stop()- #expect(first == .completed)- #expect(second == .completed)- #expect(recorder.liveEvents.map(\.turnID) == ["live"])- }-- @Test func partialLiveLineWaitsForNewlineAndIsDeliveredOnce() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let recorder = HookBatchRecorder()- let now = TestFixtures.now- let reader = HookEventTailReader(eventsDirectoryURL: directory.url, now: { now }, onBatch: recorder.receive)- await reader.start()- let line = try TestFixtures.event().jsonLineData()- let url = try directory.write(Data(line.dropLast()), to: "\(WorkflowStorage.dateKey(for: now)).jsonl")- let partial = await reader.drainNow()- #expect(recorder.liveEvents.isEmpty)- try append(Data([JSONLines.newlineByte]), to: url)- let completed = await reader.drainNow()- await reader.stop()- #expect(partial == .sourceUnavailable)- #expect(completed == .completed)- #expect(recorder.liveEvents.count == 1)- }-- @Test func replacingEventFileRebootstrapsInsteadOfPublishingHistoricalTransitions() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let recorder = HookBatchRecorder()- let now = TestFixtures.now- let url = try directory.write(TestFixtures.event().jsonLineData(), to: "\(WorkflowStorage.dateKey(for: now)).jsonl")- let reader = HookEventTailReader(eventsDirectoryURL: directory.url, now: { now }, onBatch: recorder.receive)- await reader.start()- try TestFixtures.event(turn: "replacement").jsonLineData().write(to: url, options: .atomic)- let result = await reader.drainNow()- await reader.stop()- #expect(result == .completed)- #expect(recorder.bootstrapCount == 2)- #expect(recorder.bootstrapEvents.map(\.turnID) == ["replacement"])- #expect(recorder.liveEvents.isEmpty)- }-- @Test func corruptedLineReportsUnhealthyWhilePreservingValidEvents() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let recorder = HookBatchRecorder()- let now = TestFixtures.now- _ = try directory.write(Data("broken\n".utf8) + TestFixtures.event().jsonLineData(), to: "\(WorkflowStorage.dateKey(for: now)).jsonl")- let reader = HookEventTailReader(eventsDirectoryURL: directory.url, now: { now }, onBatch: recorder.receive)- await reader.start()- let result = await reader.drainNow()- await reader.stop()- #expect(recorder.bootstrapEvents.count == 1)- #expect(recorder.degraded == true)- #expect(recorder.health.last == false)- #expect(result == .sourceUnavailable)- }-- @Test func stoppedReaderRejectsDrainRequests() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let reader = HookEventTailReader(eventsDirectoryURL: directory.url, onBatch: { _ in })- #expect(await reader.drainNow() == .cancelled)- await reader.start()- await reader.stop()- #expect(await reader.drainNow() == .cancelled)- }-- @Test func missingDirectoryReportsUnavailableDuringRetryBackoff() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let missing = directory.url.appendingPathComponent("missing")- let recorder = HookBatchRecorder()- let reader = HookEventTailReader(eventsDirectoryURL: missing, now: { TestFixtures.now }, onBatch: recorder.receive)- await reader.start()- let result = await reader.drainNow()- await reader.stop()- #expect(result == .sourceUnavailable)- #expect(recorder.degraded == true)- #expect(recorder.bootstrapEvents.isEmpty)- }-- private func append(_ data: Data, to url: URL) throws {- let handle = try FileHandle(forWritingTo: url)- defer { try? handle.close() }- try handle.seekToEnd()- try handle.write(contentsOf: data)- }-}--@MainActor-private final class HookBatchRecorder {- var bootstrapEvents: [WorkflowHookEvent] = []- var liveEvents: [WorkflowHookEvent] = []- var bootstrapCount = 0- var degraded: Bool?- var health: [Bool] = []-- func receive(_ batch: HookEventBatch) {- switch batch {- case .bootstrapStart:- bootstrapCount += 1- bootstrapEvents.removeAll()- case let .bootstrapEvents(events): bootstrapEvents.append(contentsOf: events)- case let .bootstrapEnd(degraded, _): self.degraded = degraded- case let .live(events): liveEvents.append(contentsOf: events)- case let .sourceHealthChanged(healthy): health.append(healthy)- }- }-}diff --git a/CodexBarTests/JSONLinesAndActivityTests.swift b/CodexBarTests/JSONLinesAndActivityTests.swiftnew file mode 100644index 0000000..7c4749e--- /dev/null+++ b/CodexBarTests/JSONLinesAndActivityTests.swift@@ -0,0 +1,73 @@+import Foundation+import Testing++struct JSONLinesAndActivityTests {+ @Test func millisecondTimestampsRemainStableAcrossRepeatedEncoding() throws {+ let base = Int64(TestFixtures.now.timeIntervalSince1970 * 1000)+ for offset in 0 ..< 1000 {+ let expected = base + Int64(offset)+ let data = Data("{\"time\":\(expected)}".utf8)+ let dates = try JSONLines.decoder.decode([String: Date].self, from: data)+ #expect(try JSONLines.stableEncoder.encode(dates) == data)+ }+ }++ @Test func corruptUTF8DoesNotDiscardNeighboringJSONLines() {+ let data = Data("1\n \t\r\n".utf8) + Data([0xFF, 0x0A]) + Data("{broken}\n2\n3".utf8)+ let result = JSONLines.decodeWithFailures(Int.self, from: data)+ #expect(result.values == [1, 2, 3])+ #expect(result.failedLineCount == 2)+ }++ @Test func leadingPartialLineIsDroppedAtByteBoundary() {+ #expect(JSONLines.droppingLeadingPartialLine(Data("partial\n1\n2\n".utf8)) == Data("1\n2\n".utf8))+ #expect(JSONLines.droppingLeadingPartialLine(Data("partial\n".utf8)).isEmpty)+ #expect(JSONLines.droppingLeadingPartialLine(Data("partial".utf8)) == Data("partial".utf8))+ }++ @Test(arguments: ["PermissionRequest", "permission_request", "permission-request", "approval.requested"])+ func eventAliasesAreNotAccepted(_ name: String) {+ #expect(ActivityEventKind(eventName: name) == nil)+ #expect(ActivityEventKind(eventName: "approvalRequested") == .approvalRequested)+ }++ @Test func unknownEventNamesAreNotGuessed() {+ #expect(ActivityEventKind(eventName: "future_event") == nil)+ }++ @Test func eventDecodingToleratesMissingMetadataAndUnknownOrigins() throws {+ let event = try TestFixtures.decode(ActivityRecord.self, """+ {"timestamp":0,"name":"turnStarted","origin":"future","sessionID":" ","tool":123}+ """)+ #expect(event.eventKind == .turnStarted)+ #expect(event.origin == .unknown)+ #expect(event.sessionID == nil)+ #expect(event.tool == nil)+ }++ @Test(arguments: [#"{"name":"turnCompleted"}"#, #"{"timestamp":"invalid","name":"turnCompleted"}"#, #"{"timestamp":0,"name":" "}"#])+ func eventDecodingRequiresTimestampAndEvent(_ json: String) {+ #expect(throws: (any Error).self) {+ try TestFixtures.decode(ActivityRecord.self, json)+ }+ }++ @Test func eventSerializationRoundTripsEscapedMetadata() throws {+ let event = ActivityRecord(+ timestamp: TestFixtures.now, name: "toolStarted", origin: .main,+ cwd: "/projects/a\"b", tool: "line\nbreak", model: nil,+ effort: nil, approvalReviewer: nil,+ sessionID: "session", turnID: "turn", agentID: "agent"+ )+ let data = try JSONLines.stableEncoder.encode(event)+ #expect(!data.contains(JSONLines.newlineByte))+ #expect(try JSONLines.decoder.decode(ActivityRecord.self, from: data) == event)+ }++ @Test func guardianModelOnlyFillsUnknownOrigin() throws {+ let unknown = try TestFixtures.decode(ActivityRecord.self, #"{"timestamp":0,"name":"turnCompleted","model":"codex-auto-review"}"#)+ let explicit = try TestFixtures.decode(ActivityRecord.self, #"{"timestamp":0,"name":"turnCompleted","model":"codex-auto-review","origin":"main"}"#)+ #expect(unknown.origin == .autoReview)+ #expect(explicit.origin == .main)+ }+}diff --git a/CodexBarTests/JSONLinesAndHookTests.swift b/CodexBarTests/JSONLinesAndHookTests.swiftdeleted file mode 100644index d80319f..0000000--- a/CodexBarTests/JSONLinesAndHookTests.swift+++ /dev/null@@ -1,101 +0,0 @@-import Foundation-import Testing--struct JSONLinesAndHookTests {- @Test func corruptUTF8DoesNotDiscardNeighboringJSONLines() {- let data = Data("1\n \t\r\n".utf8) + Data([0xFF, 0x0A]) + Data("{broken}\n2\n3".utf8)- let result = JSONLines.decodeWithFailures(Int.self, from: data)- #expect(result.values == [1, 2, 3])- #expect(result.failedLineCount == 2)- }-- @Test func leadingPartialLineIsDroppedAtByteBoundary() {- #expect(JSONLines.droppingLeadingPartialLine(Data("partial\n1\n2\n".utf8)) == Data("1\n2\n".utf8))- #expect(JSONLines.droppingLeadingPartialLine(Data("partial\n".utf8)).isEmpty)- #expect(JSONLines.droppingLeadingPartialLine(Data("partial".utf8)) == Data("partial".utf8))- }-- @Test(arguments: ["PermissionRequest", "permissionRequest", "permission_request", "permission-request"])- func hookNamesNormalizeAcrossWireFormats(_ name: String) {- #expect(CodexHookEvent(eventName: name) == .permissionRequest)- }-- @Test func unknownHookNamesAreNotGuessed() {- #expect(CodexHookEvent(eventName: "future_event") == nil)- }-- @Test func hookDecodingToleratesMissingMetadataAndUnknownOrigins() throws {- let event = try TestFixtures.decode(WorkflowHookEvent.self, """- {"timestamp":"2026-09-15 12:00:00.000","event":" UserPromptSubmit ","origin":"future","session":" ","tool":123}- """)- #expect(event.hookEvent == .userPromptSubmit)- #expect(event.origin == .unknown)- #expect(event.sessionID == nil)- #expect(event.toolName == nil)- }-- @Test(arguments: [#"{"event":"Stop"}"#, #"{"timestamp":"invalid","event":"Stop"}"#, #"{"timestamp":"2026-09-15 12:00:00.000","event":" "}"#])- func hookDecodingRequiresTimestampAndEvent(_ json: String) {- #expect(throws: (any Error).self) {- try TestFixtures.decode(WorkflowHookEvent.self, json)- }- }-- @Test func hookSerializationRoundTripsEscapedMetadata() throws {- let event = WorkflowHookEvent(- timestamp: TestFixtures.now, name: "PreToolUse", origin: .main,- directoryPath: "/projects/a\"b", toolName: "line\nbreak", modelName: nil,- effort: nil, permissionMode: nil, approvalReviewer: nil,- sessionID: "session", turnID: "turn", agentID: "agent"- )- let data = try event.jsonLineData()- #expect(data.filter { $0 == JSONLines.newlineByte }.count == 1)- #expect(try JSONDecoder().decode(WorkflowHookEvent.self, from: data) == event)- }-- @Test func guardianModelOnlyFillsUnknownOrigin() throws {- let unknown = try TestFixtures.decode(WorkflowHookEvent.self, #"{"timestamp":"2026-09-15 12:00:00.000","event":"Stop","model":"codex-auto-review"}"#)- let explicit = try TestFixtures.decode(WorkflowHookEvent.self, #"{"timestamp":"2026-09-15 12:00:00.000","event":"Stop","model":"codex-auto-review","origin":"main"}"#)- #expect(unknown.origin == .autoReview)- #expect(explicit.origin == .main)- }-- @Test func terminalHookTimeoutsRespectCodexDeadline() {- for event in CodexHookEvent.allCases {- #expect(WorkflowHookEventRecorder.hookTimeoutSeconds(for: event) == ([.sessionEnd, .interrupt].contains(event) ? 3 : 5))- }- }-- @Test(arguments: [- (#""cli""#, WorkflowEventOrigin.main),- (#"{"custom":"integration"}"#, .main),- (#"{"subagent":{"other":"guardian"}}"#, .autoReview),- (#"{"subagent":{"thread_spawn":{"parent_thread_id":"parent"}}}"#, .auxiliary),- (#"{"subagent":"review"}"#, .auxiliary),- (#""future""#, .unknown),- (#"{"subagent":{"other":""}}"#, .unknown)- ])- func rolloutSourcesAreClassifiedConservatively(_ json: String, _ expected: WorkflowEventOrigin) throws {- #expect(try TestFixtures.decode(WorkflowRolloutSource.self, json).origin == expected)- }-- @Test func metadataReaderExtractsSourceBeforeLargeInstructions() throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let prefix = #"{"type":"session_meta","payload":{"id":"thread","source":"cli","instructions":""#- let url = try directory.write(prefix + String(repeating: "x", count: 300000) + "\"}}\n", to: "large.jsonl")- #expect(WorkflowRolloutMetadataReader.origin(transcriptPath: url.path) == .main)- #expect(WorkflowRolloutMetadataReader.metadata(transcriptPath: url.path)?.id == "thread")- }-- @Test func metadataReaderDoesNotSearchOtherLinesOrBeyondBudget() throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let late = #"{"type":"session_meta","payload":{"source":"cli"}}"#- let wrongFirstLine = try directory.write("{}\n" + late + "\n", to: "wrong.jsonl")- #expect(WorkflowRolloutMetadataReader.origin(transcriptPath: wrongFirstLine.path) == .unknown)- let oversized = try directory.write(String(repeating: " ", count: 256 * 1024) + late + "\n", to: "oversized.jsonl")- #expect(WorkflowRolloutMetadataReader.origin(transcriptPath: oversized.path) == .unknown)- #expect(WorkflowRolloutMetadataReader.origin(transcriptPath: nil) == .unknown)- }-}diff --git a/CodexBarTests/ActivityProtectionStateStoreTests.swift b/CodexBarTests/ProtectionStoreTests.swiftsimilarity index 70%rename from CodexBarTests/ActivityProtectionStateStoreTests.swiftrename to CodexBarTests/ProtectionStoreTests.swiftindex 4009a51..79aec83 100644--- a/CodexBarTests/ActivityProtectionStateStoreTests.swift+++ b/CodexBarTests/ProtectionStoreTests.swift@@ -1,50 +1,50 @@import Foundationimport Testing-struct ActivityProtectionStateStoreTests {+struct ProtectionStoreTests {@Test func expiredRecordsArePrunedAtExactDeadline() async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let store = ActivityProtectionStateStore(directoryURL: directory.url)+ let store = ProtectionStore(directoryURL: directory.url)let record = makeRecord("task", markedAfter: 0, expiresAfter: 10)try await store.apply(upserts: [record], now: TestFixtures.now)#expect(await store.load(now: TestFixtures.now.addingTimeInterval(9))["task"] == record)#expect(await store.load(now: TestFixtures.now.addingTimeInterval(10)).isEmpty)- let reopened = ActivityProtectionStateStore(directoryURL: directory.url)+ let reopened = ProtectionStore(directoryURL: directory.url)#expect(await reopened.load(now: TestFixtures.now).isEmpty)}@Test func olderUpsertAndStaleRemovalCannotOverwriteNewerRecord() async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let first = ActivityProtectionStateStore(directoryURL: directory.url)- let second = ActivityProtectionStateStore(directoryURL: directory.url)+ let first = ProtectionStore(directoryURL: directory.url)+ let second = ProtectionStore(directoryURL: directory.url)let older = makeRecord("task", markedAfter: 0)let newer = makeRecord("task", markedAfter: 5)try await first.apply(upserts: [newer], now: TestFixtures.now)- try await second.apply(upserts: [older], removals: [ActivityProtectionRemoval(taskIdentifier: "task", matchingMarkedAt: older.markedAt)], now: TestFixtures.now)+ try await second.apply(upserts: [older], removals: [ProtectionRemoval(taskIdentifier: "task", matchingMarkedAt: older.markedAt)], now: TestFixtures.now)#expect(await first.load(now: TestFixtures.now)["task"] == newer)- try await second.apply(removals: [ActivityProtectionRemoval(taskIdentifier: "task", matchingMarkedAt: newer.markedAt)], now: TestFixtures.now)+ try await second.apply(removals: [ProtectionRemoval(taskIdentifier: "task", matchingMarkedAt: newer.markedAt)], now: TestFixtures.now)#expect(await first.load(now: TestFixtures.now).isEmpty)}@Test func concurrentStoreInstancesPreserveIndependentRecords() async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let first = ActivityProtectionStateStore(directoryURL: directory.url)- let second = ActivityProtectionStateStore(directoryURL: directory.url)+ let first = ProtectionStore(directoryURL: directory.url)+ let second = ProtectionStore(directoryURL: directory.url)async let firstWrite: Void = first.apply(upserts: [makeRecord("first", markedAfter: 0)], now: TestFixtures.now)async let secondWrite: Void = second.apply(upserts: [makeRecord("second", markedAfter: 0)], now: TestFixtures.now)_ = try await (firstWrite, secondWrite)#expect(await Set(first.load(now: TestFixtures.now).keys) == ["first", "second"])}- @Test(arguments: ["not-json", #"{"schemaVersion":999,"records":[]}"#])+ @Test(arguments: ["not-json", #"{"version":999,"records":[]}"#])func invalidStateLoadsEmptyAndCanBeReplaced(_ content: String) async throws {let directory = try TestDirectory()defer { try? directory.remove() }_ = try directory.write(content, to: "state.json")- let store = ActivityProtectionStateStore(directoryURL: directory.url)+ let store = ProtectionStore(directoryURL: directory.url)#expect(await store.load(now: TestFixtures.now).isEmpty)let record = makeRecord("task", markedAfter: 0)try await store.apply(upserts: [record], now: TestFixtures.now)@@ -57,16 +57,16 @@ struct ActivityProtectionStateStoreTests {let older = makeRecord("task", markedAfter: 0)let newer = makeRecord("task", markedAfter: 5)let records = try #require(String(data: JSONEncoder().encode([newer, older]), encoding: .utf8))- let url = try directory.write("{\"schemaVersion\":1,\"records\":\(records)}", to: "state.json")- let store = ActivityProtectionStateStore(directoryURL: directory.url)+ let url = try directory.write("{\"version\":1,\"records\":\(records)}", to: "state.json")+ let store = ProtectionStore(directoryURL: directory.url)#expect(await store.load(now: TestFixtures.now)["task"] == newer)try await store.apply(now: TestFixtures.now)let attributes = try FileManager.default.attributesOfItem(atPath: url.path)#expect((attributes[.posixPermissions] as? NSNumber)?.intValue == 0o600)}- private nonisolated func makeRecord(_ identifier: String, markedAfter: TimeInterval, expiresAfter: TimeInterval = 60) -> ActivityProtectionRecord {- ActivityProtectionRecord(+ private nonisolated func makeRecord(_ identifier: String, markedAfter: TimeInterval, expiresAfter: TimeInterval = 60) -> ProtectionRecord {+ ProtectionRecord(taskIdentifier: identifier, lastProgressAt: TestFixtures.now.addingTimeInterval(-3600),markedAt: TestFixtures.now.addingTimeInterval(markedAfter), expiresAt: TestFixtures.now.addingTimeInterval(expiresAfter))diff --git a/CodexBarTests/SessionLifecycleCacheTests.swift b/CodexBarTests/SessionLifecycleCacheTests.swiftnew file mode 100644index 0000000..7917da6--- /dev/null+++ b/CodexBarTests/SessionLifecycleCacheTests.swift@@ -0,0 +1,141 @@+import Foundation+import Testing++struct SessionLifecycleCacheTests {+ @Test func unavailableChildInvalidatesAncestorsButNotOtherThreads() async {+ let reader = SessionLifecycleCache()+ let now = Date()+ var states: [ActivityTurnReference: SessionLifecycleState] = [:]+ for id in ["root", "child", "grandchild", "other"] {+ let reference = ActivityTurnReference(threadID: id, turnID: "turn", startedAt: now)+ var state = SessionLifecycleState(+ requestedThreadID: id, turnID: "turn", startedAt: now, approvalReviewer: nil,+ effort: nil, lastProgressAt: now, terminal: nil+ )+ state.parentThreadID = id == "grandchild" ? "child" : id == "child" ? "root" : nil+ state.rootSessionID = id == "grandchild" || id == "child" ? "root" : nil+ state.rootTurnID = "turn"+ states[reference] = state+ }+ await reader.replace(states, verifiedThreads: ["root": now, "child": now, "other": now])+ let result = await reader.lifecycleStates(for: Array(states.keys), now: now)+ #expect(result.first { $0.requestedThreadID == "other" }?.readStatus == .complete)+ #expect(result.filter { $0.requestedThreadID != "other" }.allSatisfy { $0.readStatus == .unavailable })+ }++ @Test func disconnectAndCoverageExpiryInvalidateCachedLifecycle() async {+ let reader = SessionLifecycleCache()+ let now = TestFixtures.now+ let reference = ActivityTurnReference(threadID: "thread", turnID: "turn", startedAt: now)+ let state = SessionLifecycleState(+ requestedThreadID: "thread", turnID: "turn", startedAt: now, approvalReviewer: .user,+ effort: "high", lastProgressAt: now, terminal: nil, hasContext: true+ )+ await reader.replace([reference: state], verifiedThreads: [reference.threadID: now])+ #expect(await reader.lifecycleStates(for: [reference], now: now).first?.readStatus == .complete)+ #expect(await reader.lifecycleStates(for: [reference], now: now.addingTimeInterval(16)).first?.readStatus == .unavailable)+ await reader.invalidate()+ #expect(await reader.lifecycleStates(for: [reference], now: now).first?.readStatus == .unavailable)+ await reader.replace([:], verifiedThreads: [reference.threadID: now])+ #expect(await reader.lifecycleStates(for: [reference], now: now).first?.readStatus == .notFound)+ await reader.replace([:], verifiedThreads: [:])+ #expect(await reader.lifecycleStates(for: [reference], now: now).first?.readStatus == .unavailable)+ }+}++extension SessionLifecycleCacheTests {+ @Test func lifecycleVerificationDoesNotRefreshOtherThreads() async {+ let reader = SessionLifecycleCache()+ let now = TestFixtures.now+ func reference(_ id: String) -> ActivityTurnReference {+ .init(threadID: id, turnID: "turn", startedAt: now)+ }+ func state(_ id: String) -> SessionLifecycleState {+ .init(+ requestedThreadID: id,+ turnID: "turn",+ startedAt: now,+ approvalReviewer: .user,+ effort: nil,+ lastProgressAt: now,+ terminal: nil+ )+ }+ await reader.replace([reference("a"): state("a"), reference("b"): state("b")], verifiedThreads: ["a": now, "b": now.addingTimeInterval(-16)])+ #expect(await reader.lifecycleStates(for: [reference("a")], now: now).first?.readStatus == .complete)+ #expect(await reader.lifecycleStates(for: [reference("b")], now: now).first?.readStatus == .unavailable)+ }+}++extension SessionLifecycleCacheTests {+ @Test(arguments: [false, true])+ func finishedChildCannotExpireRunningRoot(previousTurn: Bool) async {+ let cache = SessionLifecycleCache()+ let now = TestFixtures.now+ let root = ActivityTurnReference(threadID: "root", turnID: "current", startedAt: now)+ let child = ActivityTurnReference(threadID: "child", turnID: "child", startedAt: now)+ let rootState = SessionLifecycleState(+ requestedThreadID: "root",+ turnID: "current",+ startedAt: now,+ approvalReviewer: nil,+ effort: nil,+ lastProgressAt: now,+ terminal: nil+ )+ let childState = SessionLifecycleState(+ requestedThreadID: "child",+ turnID: "child",+ startedAt: now,+ approvalReviewer: nil,+ effort: nil,+ lastProgressAt: now,+ terminal: .completed(at: nil, duration: nil),+ rootTurnID: previousTurn ? "old" : "current",+ rootSessionID: "root",+ parentThreadID: "root"+ )+ await cache.replace([root: rootState, child: childState], verifiedThreads: ["root": now])+ let states = await cache.lifecycleStates(for: [root], now: now)+ #expect(states.first { $0.requestedThreadID == "root" }?.readStatus == .complete)+ #expect(states.allSatisfy { $0.readStatus == .complete })+ }++ @Test func unavailablePreviousTurnDoesNotInvalidateCurrentTurn() async {+ let cache = SessionLifecycleCache()+ let now = TestFixtures.now+ func reference(_ thread: String, _ turn: String) -> ActivityTurnReference {+ .init(threadID: thread, turnID: turn, startedAt: now)+ }+ var states: [ActivityTurnReference: SessionLifecycleState] = [:]+ for turn in ["old", "current"] {+ states[reference("root", turn)] = SessionLifecycleState(+ requestedThreadID: "root",+ turnID: turn,+ startedAt: now,+ approvalReviewer: nil,+ effort: nil,+ lastProgressAt: now,+ terminal: nil+ )+ }+ states[reference("child", "child")] = SessionLifecycleState(+ requestedThreadID: "child",+ turnID: "child",+ startedAt: now,+ approvalReviewer: nil,+ effort: nil,+ lastProgressAt: now,+ terminal: nil,+ rootTurnID: "old",+ rootSessionID: "root",+ parentThreadID: "root"+ )+ await cache.replace(states, verifiedThreads: ["root": now])+ let result = await cache.lifecycleStates(for: [reference("root", "old"), reference("root", "current")], now: now)+ #expect(result.first { $0.turnID == "old" }?.readStatus == .unavailable)+ #expect(result.first { $0.turnID == "current" }?.readStatus == .complete)+ await cache.replace(states, verifiedThreads: ["root": now, "child": now])+ #expect(await cache.lifecycleStates(for: Array(states.keys), now: now).allSatisfy { $0.readStatus == .complete })+ }+}diff --git a/CodexBarTests/SettingsAndMaintenanceTests.swift b/CodexBarTests/SettingsTests.swiftsimilarity index 53%rename from CodexBarTests/SettingsAndMaintenanceTests.swiftrename to CodexBarTests/SettingsTests.swiftindex 905e069..76db28a 100644--- a/CodexBarTests/SettingsAndMaintenanceTests.swift+++ b/CodexBarTests/SettingsTests.swift@@ -1,12 +1,39 @@import Foundationimport Testing-struct SettingsAndMaintenanceTests {+struct SettingsTests {+ @Test(arguments: [false, true])+ func syncPreferencePreservesOldValueAndPrefersNewKey(_ oldValue: Bool) throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let defaults = preferences.defaults+ #expect(!SyncSettings.isEnabled(defaults: defaults))+ defaults.set(oldValue, forKey: "WorkflowSync.isEnabled")+ #expect(SyncSettings.isEnabled(defaults: defaults) == oldValue)+ defaults.set(!oldValue, forKey: "Sync.isEnabled")+ #expect(SyncSettings.isEnabled(defaults: defaults) == !oldValue)+ }++ @Test func protectionPreferencePreservesOldValueAndWritesNewKey() throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let defaults = preferences.defaults+ defaults.set(7200, forKey: "KeepAlive.abnormalTaskInactivitySeconds")+ let settings = ProtectionSettings(defaults: defaults)+ #expect(settings.inactivityDuration == .twoHours)+ settings.setInactivityDuration(.thirtyMinutes)+ #expect(defaults.integer(forKey: "Protection.inactivityDuration") == 1800)+ defaults.set(14400, forKey: "KeepAlive.abnormalTaskInactivitySeconds")+ settings.refresh()+ #expect(settings.inactivityDuration == .thirtyMinutes)+ #expect(ProtectionSettings(defaults: defaults).inactivityDuration == .thirtyMinutes)+ }+@Test(arguments: DataUpdateInterval.allCases)func dataUpdateIntervalPersistsAndUpdatesCountdown(_ interval: DataUpdateInterval) throws {let preferences = try TestPreferences()defer { preferences.remove() }- let service = try makeStatusService(suiteName: preferences.suite)+ let service = makeStatusService(suiteName: preferences.suite)let model = CodexStatusViewModel(service: service, defaults: preferences.defaults)#expect(model.dataUpdateInterval == .oneMinute)model.setDataUpdateInterval(interval)@@ -23,7 +50,7 @@ struct SettingsAndMaintenanceTests {let preferences = try TestPreferences()defer { preferences.remove() }preferences.defaults.set(seconds, forKey: "DataUpdate.intervalSeconds")- let model = try CodexStatusViewModel(+ let model = CodexStatusViewModel(service: makeStatusService(suiteName: preferences.suite),defaults: preferences.defaults)@@ -41,8 +68,8 @@ struct SettingsAndMaintenanceTests {#expect(DataUpdateInterval.fiveMinutes.remainingTime(since: now, now: now) == 300)}- private nonisolated func makeStatusService(suiteName: String) throws -> CodexStatusService {- try CodexStatusService(defaults: #require(UserDefaults(suiteName: suiteName)))+ private nonisolated func makeStatusService(suiteName: String) -> CodexStatusService {+ CodexStatusService(socketURL: URL(fileURLWithPath: "/tmp/\(suiteName).sock"))}@Test func mainPanelAnimationsPreserveStoredPreferenceAndDefault() throws {@@ -60,7 +87,7 @@ struct SettingsAndMaintenanceTests {#expect(!settings.areAnimationsEnabled)}- @Test func rebuildRangeIncludesDatesWithoutHookEvents() {+ @Test func rebuildRangeIncludesDatesWithoutActivityEvents() {let range = RebuildDateRange.starting(at: "2026-09-15").completing(with: "2026-09-17")#expect(range.dateKeys == ["2026-09-15", "2026-09-16", "2026-09-17"])#expect(RebuildDateRange.starting(at: "2026-09-15").dateKeys.isEmpty)@@ -85,111 +112,46 @@ struct SettingsAndMaintenanceTests {#expect(initial.leadTime == .sixHours)}- @Test func activityProtectionFallsBackToOneHourAndReloadsChanges() throws {+ @Test func protectionFallsBackToOneHourAndReloadsChanges() throws {let preferences = try TestPreferences()defer { preferences.remove() }- preferences.defaults.set("invalid", forKey: "KeepAlive.abnormalTaskInactivitySeconds")- let settings = ActivityProtectionSettings(defaults: preferences.defaults)+ preferences.defaults.set("invalid", forKey: "Protection.inactivityDuration")+ let settings = ProtectionSettings(defaults: preferences.defaults)#expect(settings.inactivityDuration == .oneHour)settings.setInactivityDuration(.thirtyMinutes)- #expect(ActivityProtectionSettings(defaults: preferences.defaults).inactivityDuration == .thirtyMinutes)- preferences.defaults.set(7200, forKey: "KeepAlive.abnormalTaskInactivitySeconds")+ #expect(ProtectionSettings(defaults: preferences.defaults).inactivityDuration == .thirtyMinutes)+ preferences.defaults.set(7200, forKey: "Protection.inactivityDuration")settings.refresh()#expect(settings.inactivityDuration == .twoHours)}- @Test func disabledProxyCanStoreInvalidDraftAndUnauthenticatedPasswordIsDiscarded() throws {- let preferences = try TestPreferences()- defer { preferences.remove() }- let configuration = CodexProxyConfiguration(host: "invalid/address", port: "")- try CodexProxyStore.save(configuration, password: "unused-secret", to: preferences.defaults)- let loaded = try CodexProxyStore.load(from: preferences.defaults)- let stored = try #require(loaded)- #expect(stored.configuration == configuration)- #expect(stored.password.isEmpty)- try CodexProxyStore.save(nil, password: "", to: preferences.defaults)- #expect(!CodexProxyStore.containsConfiguration(in: preferences.defaults))- }-- @Test func invalidEnabledProxyDoesNotOverwriteLastSavedConfiguration() throws {- let preferences = try TestPreferences()- defer { preferences.remove() }- let valid = CodexProxyConfiguration(isEnabled: true, host: "localhost", port: "8080")- try CodexProxyStore.save(valid, password: "", to: preferences.defaults)- #expect(throws: (any Error).self) {- try CodexProxyStore.save(CodexProxyConfiguration(isEnabled: true), password: "", to: preferences.defaults)- }- #expect(try CodexProxyStore.load(from: preferences.defaults)?.configuration == valid)- }-- @Test func corruptStoredProxyIsReportedInsteadOfTreatedAsMissing() throws {- let preferences = try TestPreferences()- defer { preferences.remove() }- preferences.defaults.set("broken", forKey: "CodexProxy.configuration")- #expect(CodexProxyStore.containsConfiguration(in: preferences.defaults))- #expect(throws: (any Error).self) { try CodexProxyStore.load(from: preferences.defaults) }- }-@Test func layoutRepairsDuplicateOrderAndAlwaysKeepsAVisibleSection() {let layout = MainPanelLayout(orderedSections: [.usage, .usage, .activity], hiddenSections: Set(MainPanelSection.allCases))#expect(layout.orderedSections == [.usage, .activity, .account, .quota, .status])#expect(layout.visibleSections == [.usage])let activityOnly = MainPanelLayout(orderedSections: [.activity], hiddenSections: Set(MainPanelSection.allCases).subtracting([.activity]))- #expect(activityOnly.disablingActivitySection().visibleSections == [.account])+ #expect(activityOnly.visibleSections == [.activity])}- @Test func advancedModeDisableHidesTasksAndExplicitReenableRestoresThem() throws {+ @Test func taskVisibilityFollowsLayoutPreferenceAndSupportsUndo() throws {let preferences = try TestPreferences()defer { preferences.remove() }let settings = MainPanelSettings(defaults: preferences.defaults)- settings.updateAdvancedModeEnabled(false)- #expect(!settings.layout.isVisible(.activity))- settings.updateAdvancedModeEnabled(true)#expect(settings.layout.isVisible(.activity))let undo = UndoManager()+ undo.groupsByEvent = false+ undo.beginUndoGrouping()settings.setSection(.activity, isVisible: false, undoManager: undo)+ undo.endUndoGrouping()let restored = MainPanelSettings(defaults: preferences.defaults)- restored.updateAdvancedModeEnabled(true)#expect(!restored.layout.isVisible(.activity))- }-- @Test func legacyMaintenanceStateRequiresRebuildAndNormalizesDateQueues() throws {- let state = try TestFixtures.decode(WorkflowMaintenanceState.self, #"{"pending":["2026-09-15","invalid","2026-09-14","2026-09-15"],"dirty":["2026-02-30","2026-09-14"]}"#)- #expect(state.schema == 0)- #expect(state.pending == ["2026-09-14", "2026-09-15"])- #expect(state.dirty == ["2026-09-14"])- }-- @Test func fileReplacementResetsOffsetsHashesAndMarksDayDirty() throws {- let date = "2026-09-15"- var state = WorkflowMaintenanceState(days: [date: WorkflowDayMaintenanceState(- offset: 50, size: 60, corrupt: 2, sourceGeneration: "old", sourceIsFresh: false,- fileIdentifier: 1, boundaryHash: "old-hash", boundaryVerifiedAtNanoseconds: 42- )])- state.startNewSourceGeneration(for: date, isFresh: true, fileIdentifier: 2)- let day = try #require(state.days[date])- #expect(day.offset == 0)- #expect(day.corrupt == 0)- #expect(day.sourceGeneration != "old")- #expect(day.sourceIsFresh)- #expect(day.fileIdentifier == 2)- #expect(day.boundaryHash == nil)- #expect(day.boundaryVerifiedAtNanoseconds == nil)- #expect(state.dirty == [date])- }-- @Test func repeatedPendingAndSourceUpdatesAreIdempotent() throws {- var state = WorkflowMaintenanceState()- let firstPending = state.markPending("2026-09-15")- let secondPending = state.markPending("2026-09-15")- #expect(firstPending)- #expect(!secondPending)- let firstSource = state.ensureSourceGeneration(for: "2026-09-15", fileIdentifier: 1)- let generation = try #require(state.days["2026-09-15"]?.sourceGeneration)- let secondSource = state.ensureSourceGeneration(for: "2026-09-15", fileIdentifier: 1)- #expect(firstSource)- #expect(!secondSource)- #expect(state.days["2026-09-15"]?.sourceGeneration == generation)- #expect(state.days["2026-09-15"]?.sourceIsFresh == false)+ settings.refresh()+ #expect(!settings.layout.isVisible(.activity))+ undo.beginUndoGrouping()+ settings.setSection(.activity, isVisible: true, undoManager: undo)+ undo.endUndoGrouping()+ #expect(settings.layout.isVisible(.activity))+ undo.undo()+ #expect(!settings.layout.isVisible(.activity))}}diff --git a/CodexBarTests/Support/SharedServerFixture.swift b/CodexBarTests/Support/SharedServerFixture.swiftnew file mode 100644index 0000000..f644fcb--- /dev/null+++ b/CodexBarTests/Support/SharedServerFixture.swift@@ -0,0 +1,142 @@+import CryptoKit+import Darwin+import Foundation+import Testing++/// 只绑定临时 Unix socket, 不访问用户的 Codex 服务或配置+final nonisolated class SharedServerFixture: @unchecked Sendable {+ let url = URL(fileURLWithPath: "/tmp/\(UUID().uuidString).sock")+ private let descriptor: Int32+ private let completed = DispatchSemaphore(value: 0)+ private let lock = NSLock()+ private var failure: (any Error)?++ init(connections: Int = 1, handler: @escaping @Sendable (Peer) throws -> Void) throws {+ descriptor = socket(AF_UNIX, SOCK_STREAM, 0)+ guard descriptor >= 0 else { throw FixtureError.io }+ var address = sockaddr_un()+ address.sun_family = sa_family_t(AF_UNIX)+ withUnsafeMutableBytes(of: &address.sun_path) { bytes in+ Array(url.path.utf8CString).withUnsafeBytes { bytes.copyBytes(from: $0) }+ }+ let bound = withUnsafePointer(to: &address) {+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ Darwin.bind(descriptor, $0, socklen_t(MemoryLayout<sockaddr_un>.size))+ }+ }+ guard bound == 0, listen(descriptor, 1) == 0 else {+ Darwin.close(descriptor)+ throw FixtureError.io+ }+ DispatchQueue.global().async { [self] in+ defer { completed.signal() }+ do {+ for _ in 0 ..< connections {+ var poller = pollfd(fd: descriptor, events: Int16(POLLIN), revents: 0)+ guard poll(&poller, 1, 5000) > 0 else { throw FixtureError.io }+ let client = accept(descriptor, nil, nil)+ guard client >= 0 else { throw FixtureError.io }+ defer { Darwin.close(client) }+ var timeout = timeval(tv_sec: 5, tv_usec: 0)+ _ = setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))+ _ = setsockopt(client, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))+ var enabled: Int32 = 1+ _ = setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &enabled, socklen_t(MemoryLayout<Int32>.size))+ let peer = Peer(descriptor: client)+ try peer.handshake()+ try handler(peer)+ }+ } catch {+ lock.withLock { failure = error }+ }+ }+ }++ func finish() throws {+ guard completed.wait(timeout: .now() + 6) == .success else { throw FixtureError.io }+ if let error = lock.withLock({ failure }) {+ throw error+ }+ }++ func close() {+ Darwin.close(descriptor)+ try? FileManager.default.removeItem(at: url)+ }++ struct Peer {+ let descriptor: Int32++ func handshake() throws {+ var header = Data()+ while !header.suffix(4).elementsEqual([13, 10, 13, 10]), header.count < 16384 {+ try header.append(read(1))+ }+ let text = try #require(String(data: header, encoding: .utf8))+ let key = try #require(text.components(separatedBy: "\r\n").first { $0.hasPrefix("Sec-WebSocket-Key: ") }?.dropFirst(19))+ let accept = Data(Insecure.SHA1.hash(data: Data((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").utf8))).base64EncodedString()+ try write(Data("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: \(accept)\r\n\r\n".utf8))+ }++ func readMessage() throws -> [String: Any] {+ let data = try readPayload(opcode: 1)+ return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])+ }++ func readPayload(opcode: UInt8) throws -> Data {+ let header = try [UInt8](read(2))+ #expect(header[0] == 0x80 | opcode)+ #expect(header[1] & 0x80 != 0)+ var length = Int(header[1] & 127)+ if length == 126 || length == 127 {+ length = try read(length == 126 ? 2 : 8).reduce(0) { ($0 << 8) | Int($1) }+ }+ guard length < 65536 else { throw FixtureError.io }+ let mask = try [UInt8](read(4))+ return try Data(read(length).enumerated().map { $0.element ^ mask[$0.offset % 4] })+ }++ func reply(to request: [String: Any], result: [String: Any]) throws {+ try send(["id": #require(request["id"]), "result": result])+ }++ func send(_ object: [String: Any]) throws {+ try sendRaw(JSONSerialization.data(withJSONObject: object))+ }++ func sendRaw(_ payload: Data, opcode: UInt8 = 1) throws {+ var frame = Data([0x80 | opcode])+ if payload.count < 126 {+ frame.append(UInt8(payload.count))+ } else {+ frame.append(contentsOf: [126, UInt8(payload.count >> 8), UInt8(payload.count & 255)])+ }+ frame.append(payload)+ try write(frame)+ }++ private func read(_ count: Int) throws -> Data {+ var data = Data()+ while data.count < count {+ var buffer = [UInt8](repeating: 0, count: count - data.count)+ let received = Darwin.read(descriptor, &buffer, buffer.count)+ guard received > 0 else { throw FixtureError.io }+ data.append(contentsOf: buffer.prefix(received))+ }+ return data+ }++ private func write(_ data: Data) throws {+ try data.withUnsafeBytes { bytes in+ var offset = 0+ while offset < bytes.count {+ let written = Darwin.write(descriptor, bytes.baseAddress!.advanced(by: offset), bytes.count - offset)+ guard written > 0 else { throw FixtureError.io }+ offset += written+ }+ }+ }+ }++ private enum FixtureError: Error { case io }+}diff --git a/CodexBarTests/SyncRecoveryTests.swift b/CodexBarTests/SyncRecoveryTests.swiftnew file mode 100644index 0000000..141b3c3--- /dev/null+++ b/CodexBarTests/SyncRecoveryTests.swift@@ -0,0 +1,403 @@+import CloudKit+import Foundation+import Testing++struct SyncRecoveryTests {+ private static let zone = CKRecordZone.ID(zoneName: SyncCloudKit.zoneName, ownerName: CKCurrentUserDefaultName)+ private static let salt = Data(repeating: 1, count: 32)++ @Test func damagedActivityCursorRebuildsWithoutBlockingTokens() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = SyncDatabaseFixture()+ let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ _ = await service.synchronizeIfEnabled(localAggregates: [], trigger: .manual)+ let url = directory.url.appendingPathComponent("Activity/cache.json")+ var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])+ json["cursor"] = Data("broken cursor".utf8).base64EncodedString()+ try JSONSerialization.data(withJSONObject: json).write(to: url)+ let queriesBefore = await database.queryCount+ _ = await service.synchronizeIfEnabled(localAggregates: [], localTokenTurns: [Self.turn(0)], trigger: .manual)+ #expect(await database.queryCount > queriesBefore)+ #expect(await database.savedTypes.contains(TokenSync.recordType))+ #expect(try ActivitySyncStore(directoryURL: directory.url).load().cursor == nil)+ }++ @Test(arguments: [false, true]) func damagedTokenCacheOrCursorRebuilds(cursorOnly: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = SyncDatabaseFixture()+ let service = TokenSync(database: database, directoryURL: directory.url, isEnabled: { true })+ try await service.synchronize(local: [Self.turn(0)], accountScopedDeviceID: "device", salt: Self.salt, zoneID: Self.zone)+ let url = directory.url.appendingPathComponent("cache.json")+ if cursorOnly {+ var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])+ json["cursor"] = Data("broken cursor".utf8).base64EncodedString()+ try JSONSerialization.data(withJSONObject: json).write(to: url)+ } else {+ try Data("broken cache".utf8).write(to: url)+ }+ let reopened = TokenSync(database: database, directoryURL: directory.url, isEnabled: { true })+ try await reopened.synchronize(local: [], accountScopedDeviceID: "device", salt: Self.salt, zoneID: Self.zone)+ #expect(try Self.cachedTurnCount(in: directory.url) == 1)+ }++ @Test func failedTokenRebuildPreservesOriginalBytes() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let original = Data("broken cache".utf8)+ let url = try directory.write(original, to: "cache.json")+ let database = SyncDatabaseFixture(changesFail: true)+ let service = TokenSync(database: database, directoryURL: directory.url, isEnabled: { true })+ await #expect(throws: (any Error).self) {+ try await service.synchronize(local: [], accountScopedDeviceID: "device", salt: Self.salt, zoneID: Self.zone)+ }+ #expect(try Data(contentsOf: url) == original)+ }++ @Test(arguments: [false, true]) func activityFailureOnlyStopsTokensForSharedErrors(shared: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = SyncDatabaseFixture(queryError: shared ? .networkFailure : .invalidArguments)+ let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ _ = await service.synchronizeIfEnabled(localAggregates: [], localTokenTurns: [Self.turn(0)], trigger: .manual)+ #expect(await database.savedTypes.contains(TokenSync.recordType) == !shared)+ }++ @Test(arguments: [false, true]) func partialTokenBatchContinuesAndRetainsSuccesses(readFailure: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let turns = (0 ..< 30).map(Self.turn)+ let badID = turns[0].pseudonymized(salt: Self.salt).id+ let database = SyncDatabaseFixture(failingName: badID, readFailure: readFailure)+ let service = TokenSync(database: database, directoryURL: directory.url, isEnabled: { true })+ await #expect(throws: (any Error).self) {+ try await service.synchronize(local: turns, accountScopedDeviceID: "device", salt: Self.salt, zoneID: Self.zone)+ }+ #expect(await database.savedTypes.filter { $0 == TokenSync.recordType }.count == 29)+ #expect(try Self.cachedTurnCount(in: directory.url) == 29)+ await database.repair()+ try await service.synchronize(local: turns, accountScopedDeviceID: "device", salt: Self.salt, zoneID: Self.zone)+ #expect(await database.savedTypes.filter { $0 == TokenSync.recordType }.count == 30)+ }++ @Test func partialActivityBatchConfirmsSuccessesAndContinuesLaterDates() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let dates = (0 ..< 30).map { HistoryStorage.dateKey(for: Date().addingTimeInterval(Double(-$0) * 86400)) }+ let aggregates = dates.map { date in+ var value = ActivityAggregate(date: date, generationID: "source", generationStartedEmpty: true)+ value.eventCount = 1+ return value+ }+ let database = SyncDatabaseFixture(failingDate: dates[0])+ let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ _ = await service.synchronizeIfEnabled(localAggregates: aggregates, localTokenTurns: [Self.turn(0)], trigger: .manual)+ #expect(ActivitySyncStore(directoryURL: directory.url).loadState().hashByDate.count == 29)+ #expect(await database.savedTypes.filter { $0 == "Activity" }.count == 29)+ #expect(await database.savedTypes.contains(TokenSync.recordType))+ }++ @Test func failedRecordDuringFetchDoesNotCommitPartialCache() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = SyncDatabaseFixture()+ let service = TokenSync(database: database, directoryURL: directory.url, isEnabled: { true })+ try await service.synchronize(local: [Self.turn(0)], accountScopedDeviceID: "device", salt: Self.salt, zoneID: Self.zone)+ let url = directory.url.appendingPathComponent("cache.json")+ let original = try Data(contentsOf: url)+ await database.failChangesRecord()+ await #expect(throws: (any Error).self) {+ try await service.synchronize(local: [Self.turn(1)], accountScopedDeviceID: "device", salt: Self.salt, zoneID: Self.zone)+ }+ #expect(try Data(contentsOf: url) == original)+ }++ @Test func unsupportedTokenVersionIsNotTreatedAsCorruption() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = SyncDatabaseFixture()+ let service = TokenSync(database: database, directoryURL: directory.url, isEnabled: { true })+ try await service.synchronize(local: [], accountScopedDeviceID: "device", salt: Self.salt, zoneID: Self.zone)+ let url = directory.url.appendingPathComponent("cache.json")+ let original = Data(#"{"version":999,"futureField":"unsupported"}"#.utf8)+ try original.write(to: url)+ await #expect(throws: (any Error).self) {+ try await service.synchronize(local: [], accountScopedDeviceID: "device", salt: Self.salt, zoneID: Self.zone)+ }+ #expect(try Data(contentsOf: url) == original)+ }++ @Test func activityCacheCommitsRecordsAndCursorTogether() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = ActivitySyncStore(directoryURL: directory.url)+ let state = SyncState(deviceID: "device", hashByDate: ["2026-10-05": "hash"])+ try store.saveState(state)+ let url = directory.url.appendingPathComponent("Activity/cache.json")+ var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])+ json["cursor"] = Data("previous cursor".utf8).base64EncodedString()+ try JSONSerialization.data(withJSONObject: json).write(to: url)+ var updated = state+ updated.replacementDates = ["2026-10-05"]+ try store.saveState(updated)+ #expect(try store.load().cursor == Data("previous cursor".utf8))+ let daily = SyncedActivity(date: "2026-10-05", generationID: "source", eventCount: 2, projectCounts: [:], modelCounts: [:])+ let record = try ActivitySyncRecord(deviceID: "device", daily: daily, recordName: "device_2026-10-05_source")+ try store.saveFetchedRecords([record], cursor: nil)+ let reopened = try ActivitySyncStore(directoryURL: directory.url).load()+ #expect(reopened.state == updated)+ #expect(reopened.records == [record])+ #expect(reopened.cursor == nil)+ let files = try FileManager.default.contentsOfDirectory(atPath: url.deletingLastPathComponent().path)+ #expect(Set(files) == ["cache.json", "store.lock"])+ try store.reset(state: SyncState())+ #expect(try store.load() == ActivitySyncCache())+ }++ @Test(arguments: ["missingFields", "missingGeneration", "mismatchedIdentity"])+ func damagedActivityRecordsInvalidateCursorAndUploadState(_ damage: String) throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = ActivitySyncStore(directoryURL: directory.url)+ try store.saveState(SyncState(deviceID: "device", hashByDate: ["2026-10-05": "hash"]))+ let url = directory.url.appendingPathComponent("Activity/cache.json")+ var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])+ json["cursor"] = Data("stale cursor".utf8).base64EncodedString()+ let daily: [String: Any] = damage == "missingGeneration"+ ? ["date": "2026-10-05"] : ["date": "2026-10-05", "generationID": "source"]+ json["records"] = damage == "missingFields" ? [["invalid": true]] : [[+ "deviceID": "device", "recordName": "device_2026-10-05_other", "daily": daily+ ]]+ try JSONSerialization.data(withJSONObject: json).write(to: url)+ #expect(try store.load() == ActivitySyncCache())+ try store.saveState(SyncState(deviceID: "new"))+ #expect(try store.load().records.isEmpty)+ #expect(try store.load().cursor == nil)+ #expect(try store.load().state.deviceID == "new")+ }++ @Test func unsupportedActivityCacheIsNotOverwritten() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let original = Data(#"{"version":999,"futureField":"unsupported"}"#.utf8)+ let url = try directory.write(original, to: "Activity/cache.json")+ let store = ActivitySyncStore(directoryURL: directory.url)+ #expect(throws: SyncRecovery.Failure.self) { try store.saveState(SyncState()) }+ #expect(throws: SyncRecovery.Failure.self) { try store.reset(state: SyncState()) }+ #expect(try Data(contentsOf: url) == original)+ }++ @Test func failedActivitySavePreservesCacheAndCursor() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = ActivitySyncStore(directoryURL: directory.url)+ try store.saveState(SyncState(deviceID: "device"))+ let url = directory.url.appendingPathComponent("Activity/cache.json")+ var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])+ json["cursor"] = Data("previous cursor".utf8).base64EncodedString()+ let original = try JSONSerialization.data(withJSONObject: json)+ try original.write(to: url)+ let daily = SyncedActivity(date: "2026-10-05", generationID: "source", eventCount: 2, projectCounts: [:], modelCounts: [:])+ let record = try ActivitySyncRecord(deviceID: "device", daily: daily, updatedAt: Date(timeIntervalSince1970: .infinity), recordName: "device_2026-10-05_source")+ #expect(throws: EncodingError.self) {+ try store.saveFetchedRecords([record], cursor: nil)+ }+ #expect(try Data(contentsOf: url) == original)+ }++ @Test func activityUsesOneIdentityAndPreservesMoreCompleteRemoteCounts() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = SyncDatabaseFixture()+ let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ var local = ActivityAggregate(date: HistoryStorage.dateKey(for: Date()), generationID: "source", generationStartedEmpty: true)+ local.eventCount = 5+ _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)+ let records = await database.activityRecords()+ let remote = try #require(records.first)+ let deviceID = try #require(remote["deviceID"] as? String)+ let identity = "\(deviceID)_\(local.date)_source"+ #expect(records.count == 1)+ #expect(remote.recordID.recordName == identity)+ #expect(await database.requestedIDs.filter { $0.recordName != "accountSalt" }.map(\.recordName) == [identity])++ local.eventCount = 2+ _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)+ #expect(await database.activityRecords().first?["eventCount"] as? Int == 5)+ }++ @Test func missingLocalGenerationFailsBeforeReplacingRemoteRecords() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = SyncDatabaseFixture()+ let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ var local = ActivityAggregate(date: HistoryStorage.dateKey(for: Date()), generationID: "source", generationStartedEmpty: true)+ local.eventCount = 5+ _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)+ let before = await database.activityRecords().map(\.recordID)+ try await service.markReplacementNeeded(for: [local.date])+ local.generationID = nil+ _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)+ #expect(await database.deletedIDs.isEmpty)+ #expect(await database.activityRecords().map(\.recordID) == before)+ #expect(await service.hasPendingReplacement(for: [local.date]))+ }++ @Test func invalidGenerationDuringCursorBaselineStopsActivityUpload() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = SyncDatabaseFixture()+ let invalid = CKRecord(recordType: "Activity", recordID: CKRecord.ID(recordName: "device_invalid"))+ invalid["deviceID"] = "device" as CKRecordValue+ invalid["date"] = HistoryStorage.dateKey(for: Date()) as CKRecordValue+ await database.injectChangesRecord(invalid)+ let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ var local = ActivityAggregate(date: HistoryStorage.dateKey(for: Date()), generationID: "source", generationStartedEmpty: true)+ local.eventCount = 1+ _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)+ #expect(await database.activityRecords().isEmpty)+ #expect(try ActivitySyncStore(directoryURL: directory.url).load().cursor == nil)+ #expect(ActivitySyncStore(directoryURL: directory.url).loadState().hashByDate.isEmpty)+ }++ @Test func replacingHistoryDeletesEveryPreviousGeneration() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = SyncDatabaseFixture()+ let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ var local = ActivityAggregate(date: HistoryStorage.dateKey(for: Date()), generationID: "first", generationStartedEmpty: true)+ local.eventCount = 1+ _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)+ local.generationID = "second"+ _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)+ let previous = await Set(database.activityRecords().map(\.recordID))+ #expect(previous.count == 2)+ local.generationID = "rebuilt"+ local.generationStartedEmpty = false+ try await service.markReplacementNeeded(for: [local.date])+ _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)+ let current = await database.activityRecords()+ #expect(current.count == 1)+ #expect(current.first?["generationID"] as? String == "rebuilt")+ #expect(await previous.isSubset(of: Set(database.deletedIDs)))+ #expect(await !service.hasPendingReplacement(for: [local.date]))+ }++ private static func cachedTurnCount(in directory: URL) throws -> Int {+ let data = try Data(contentsOf: directory.appendingPathComponent("cache.json"))+ let json = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])+ return try #require(json["turns"] as? [String: Any]).count+ }++ private static func turn(_ index: Int) -> TokenTurn {+ let id = TokenTurn.identifier(thread: "test", turn: String(index))+ let now = Date().addingTimeInterval(Double(-index))+ return TokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: .zero)+ }+}++private actor SyncDatabaseFixture: SyncDatabase {+ private var stored: [CKRecord.ID: CKRecord] = [:]+ private let queryError: CKError.Code?+ private let changesFail: Bool+ private var changesRecordFails = false+ private var failingName: String?+ private let failingDate: String?+ private let readFailure: Bool+ private(set) var queryCount = 0+ private(set) var savedTypes: [String] = []+ private(set) var requestedIDs: [CKRecord.ID] = []+ private(set) var deletedIDs: [CKRecord.ID] = []+ private var changesRecord: CKRecord?++ func activityRecords() -> [CKRecord] {+ stored.values.filter { $0.recordType == "Activity" }.map(Self.copy)+ }++ func injectChangesRecord(_ record: CKRecord) {+ changesRecord = Self.copy(record)+ }++ init(queryError: CKError.Code? = nil, changesFail: Bool = false, failingName: String? = nil, failingDate: String? = nil, readFailure: Bool = false) {+ self.queryError = queryError+ self.changesFail = changesFail+ self.failingName = failingName+ self.failingDate = failingDate+ self.readFailure = readFailure+ }++ private nonisolated static func copy(_ record: CKRecord) -> CKRecord {+ record.copy() as? CKRecord ?? record+ }++ func failChangesRecord() {+ changesRecordFails = true+ }++ func repair() {+ failingName = nil+ }++ func records(for ids: [CKRecord.ID], desiredKeys _: [CKRecord.FieldKey]?) async throws -> Records {+ requestedIDs.append(contentsOf: ids)+ return Dictionary(uniqueKeysWithValues: ids.map { id in+ if readFailure, id.recordName == failingName {+ return (id, .failure(CKError(.constraintViolation)))+ }+ return (id, stored[id].map { .success(Self.copy($0)) } ?? .failure(CKError(.unknownItem)))+ })+ }++ func modifyRecords(saving records: [CKRecord], deleting ids: [CKRecord.ID], savePolicy _: CKModifyRecordsOperation.RecordSavePolicy, atomically _: Bool) async throws -> Modification {+ var saved: Records = [:]+ for record in records {+ if record.recordID.recordName == failingName || (failingDate != nil && record["date"] as? String == failingDate) {+ saved[record.recordID] = .failure(CKError(.constraintViolation))+ } else {+ stored[record.recordID] = record.copy() as? CKRecord+ saved[record.recordID] = .success(record)+ savedTypes.append(record.recordType)+ }+ }+ deletedIDs.append(contentsOf: ids)+ for id in ids {+ stored[id] = nil+ }+ return (saved, Dictionary(uniqueKeysWithValues: ids.map { ($0, .success(())) }))+ }++ func records(matching query: CKQuery, inZoneWith _: CKRecordZone.ID?, desiredKeys _: [CKRecord.FieldKey]?, resultsLimit _: Int) async throws -> QueryPage {+ queryCount += 1+ if let queryError {+ throw CKError(queryError)+ }+ return (stored.values.filter { $0.recordType == query.recordType }.map { ($0.recordID, .success(Self.copy($0))) }, nil)+ }++ func records(continuingMatchFrom _: CKQueryOperation.Cursor, desiredKeys _: [CKRecord.FieldKey]?, resultsLimit _: Int) async throws -> QueryPage {+ ([], nil)+ }++ func recordZone(for id: CKRecordZone.ID) async throws -> CKRecordZone {+ CKRecordZone(zoneID: id)+ }++ func modifyRecordZones(saving zones: [CKRecordZone], deleting _: [CKRecordZone.ID]) async throws -> ZoneModification {+ (Dictionary(uniqueKeysWithValues: zones.map { ($0.zoneID, .success($0)) }), [:])+ }++ func fetchChanges(inZoneWith _: CKRecordZone.ID, since _: CKServerChangeToken?, resultsLimit _: Int) async throws -> SyncChanges {+ if changesFail {+ throw CKError(.networkFailure)+ }+ var records = stored.mapValues { Result<CKRecord, Error>.success(Self.copy($0)) }+ if let changesRecord {+ records[changesRecord.recordID] = .success(Self.copy(changesRecord))+ }+ if changesRecordFails {+ records[CKRecord.ID(recordName: "failed-record")] = .failure(CKError(.constraintViolation))+ }+ return SyncChanges(records: records, deletions: [], token: nil, moreComing: false)+ }+}diff --git a/CodexBarTests/SyncSchedulerTests.swift b/CodexBarTests/SyncSchedulerTests.swiftnew file mode 100644index 0000000..55b7548--- /dev/null+++ b/CodexBarTests/SyncSchedulerTests.swift@@ -0,0 +1,46 @@+import Foundation+import Testing++struct SyncSchedulerTests {+ @Test func cancellingSyncDoesNotReviveOldTaskAfterReenable() async throws {+ var active = true+ var starts = 0+ var cancelled = false+ var release: CheckedContinuation<Void, Never>?+ let scheduler = SyncScheduler(+ syncActivation: { active ? .active : .syncOff },+ maintenance: { _, _ in+ starts += 1+ if starts == 1 {+ await withCheckedContinuation { release = $0 }+ do {+ try SyncCancellation.check(isEnabled: { true })+ } catch is CancellationError {+ cancelled = true+ } catch {+ Issue.record(error)+ }+ }+ return nil+ },+ rebuild: { _, _ in throw CancellationError() }+ )+ scheduler.requestSync(trigger: .manual)+ for _ in 0 ..< 100 where release == nil {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(starts == 1)+ active = false+ scheduler.requestSync(trigger: .settings)+ active = true+ scheduler.requestSync(trigger: .settings)+ #expect(starts == 1)+ release?.resume()+ for _ in 0 ..< 100 where starts != 2 {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(cancelled)+ #expect(starts == 2)+ scheduler.cancel()+ }+}diff --git a/CodexBarTests/TaskGlowPreviewTests.swift b/CodexBarTests/TaskGlowPreviewTests.swiftindex 0f9b935..8aab111 100644--- a/CodexBarTests/TaskGlowPreviewTests.swift+++ b/CodexBarTests/TaskGlowPreviewTests.swift@@ -83,11 +83,11 @@ struct TaskGlowPreviewTests {state.resume(now: time(10.4))state.refresh(now: time(10), terminalDuration: 15)state.suspend(now: time(10.1))- let termination = CodexActivityTermination(+ let termination = ActivityTermination(id: UUID(), isAnonymous: false, projectName: nil, modelName: nil,effort: nil, terminatedAt: time(10.2), duration: 60)- let snapshot = CodexActivitySnapshot(+ let snapshot = ActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: completed(at: 0).recentCompletions,recentTerminations: [termination])@@ -204,14 +204,14 @@ struct TaskGlowPreviewTests {#expect(abs(preview.playback.mediaStart - 100 - preview.playback.startsAt.timeIntervalSince(now)) < 0.00001)}- private func enabledState(snapshot: CodexActivitySnapshot = .empty) -> TaskGlowPresentationState {+ private func enabledState(snapshot: ActivitySnapshot = .empty) -> TaskGlowPresentationState {var state = TaskGlowPresentationState()update(&state, snapshot: snapshot, at: 0)state.refresh(now: now, terminalDuration: 15)return state}- private func update(_ state: inout TaskGlowPresentationState, snapshot: CodexActivitySnapshot, at seconds: TimeInterval) {+ private func update(_ state: inout TaskGlowPresentationState, snapshot: ActivitySnapshot, at seconds: TimeInterval) {state.update(snapshot: snapshot, terminalEvents: [], isEnabled: true, acceptsBriefEvents: true, now: time(seconds))}@@ -219,21 +219,21 @@ struct TaskGlowPreviewTests {now.addingTimeInterval(seconds)}- private func completed(at seconds: TimeInterval) -> CodexActivitySnapshot {- let completion = CodexActivityCompletion(+ private func completed(at seconds: TimeInterval) -> ActivitySnapshot {+ let completion = ActivityCompletion(id: UUID(), isAnonymous: false, projectName: nil, modelName: nil,effort: nil, completedAt: time(seconds), duration: 60)- return CodexActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])+ return ActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])}- private func active(waiting: Bool = false) -> CodexActivitySnapshot {- let task = CodexActivityTaskSnapshot(+ private func active(waiting: Bool = false) -> ActivitySnapshot {+ let task = ActivityTaskSnapshot(id: UUID(), isAnonymous: false, latestEvent: .toolStarted, projectName: nil,modelName: nil, effort: nil, toolName: nil, startedAt: now,stateChangedAt: now, showsPreciseDuration: true, activeSubagentCount: nil)- return CodexActivitySnapshot(+ return ActivitySnapshot(waitingTasks: waiting ? [task] : [], runningTasks: waiting ? [] : [task], recentCompletions: [], recentTerminations: [])}diff --git a/CodexBarTests/TaskGlowTests.swift b/CodexBarTests/TaskGlowTests.swiftindex b2b8f0b..0867fc1 100644--- a/CodexBarTests/TaskGlowTests.swift+++ b/CodexBarTests/TaskGlowTests.swift@@ -201,12 +201,12 @@ struct TaskGlowTests {@Test func concurrentTaskCompletionStillShowsBrieflyThenRestoresRunning() throws {var presentation = TaskGlowPresentationState()- let running = CodexActivityTaskSnapshot(+ let running = ActivityTaskSnapshot(id: UUID(), isAnonymous: false, latestEvent: .toolStarted, projectName: nil,modelName: nil, effort: nil, toolName: nil, startedAt: TestFixtures.now,stateChangedAt: TestFixtures.now, showsPreciseDuration: true, activeSubagentCount: nil)- let snapshot = CodexActivitySnapshot(+ let snapshot = ActivitySnapshot(waitingTasks: [], runningTasks: [running],recentCompletions: completedSnapshot().recentCompletions, recentTerminations: [])@@ -222,11 +222,11 @@ struct TaskGlowTests {#expect(presentation.state == .running)}- private func completedSnapshot() -> CodexActivitySnapshot {- let completion = CodexActivityCompletion(+ private func completedSnapshot() -> ActivitySnapshot {+ let completion = ActivityCompletion(id: UUID(), isAnonymous: false, projectName: nil, modelName: nil,effort: nil, completedAt: TestFixtures.now, duration: 60)- return CodexActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])+ return ActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])}}diff --git a/CodexBarTests/TestSupport.swift b/CodexBarTests/TestSupport.swiftindex 3bdc178..a6ecfeb 100644--- a/CodexBarTests/TestSupport.swift+++ b/CodexBarTests/TestSupport.swift@@ -9,18 +9,18 @@ nonisolated enum TestFixtures {}static func event(- _ name: CodexHookEvent = .userPromptSubmit,+ _ name: ActivityEventKind = .turnStarted,at timestamp: Date = now,session: String? = "session-a",turn: String? = "turn-a",agent: String? = nil,- origin: WorkflowEventOrigin = .main,- reviewer: CodexApprovalReviewer? = .user- ) -> WorkflowHookEvent {- WorkflowHookEvent(+ origin: ActivityOrigin = .main,+ reviewer: ApprovalReviewer? = .user+ ) -> ActivityRecord {+ ActivityRecord(timestamp: timestamp, name: name.rawValue, origin: origin,- directoryPath: "/projects/example", toolName: "exec_command", modelName: "gpt-5",- effort: "high", permissionMode: nil, approvalReviewer: reviewer,+ cwd: "/projects/example", tool: "exec_command", model: "gpt-5",+ effort: "high", approvalReviewer: reviewer,sessionID: session, turnID: turn, agentID: agent)}@@ -30,8 +30,8 @@ nonisolated enum TestFixtures {fresh: Bool = false,events: Int = 2,turns: Int = 1- ) -> WorkflowDailyAggregate {- var aggregate = WorkflowDailyAggregate(date: "2026-09-15", sourceGeneration: generation, sourceIsFresh: fresh)+ ) -> ActivityAggregate {+ var aggregate = ActivityAggregate(date: "2026-09-15", generationID: generation, generationStartedEmpty: fresh)aggregate.eventCount = eventsaggregate.turnCount = turnsaggregate.sessionCount = 1diff --git a/CodexBarTests/TokenHistoryTests.swift b/CodexBarTests/TokenHistoryTests.swiftnew file mode 100644index 0000000..19529c5--- /dev/null+++ b/CodexBarTests/TokenHistoryTests.swift@@ -0,0 +1,403 @@+import CloudKit+import CryptoKit+import Foundation+import Synchronization+import Testing++struct TokenHistoryTests {+ @Test func unchangedTokenStorageDoesNotReplaceFile() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = directory.url.appendingPathComponent("cache.json")+ let values = [turn("main", "a", input: 100)]+ try JSONFileStorage.save(values, to: url)+ let before = try #require(HistoryStorage.fileStat(at: url))+ try JSONFileStorage.save(values, to: url)+ let after = try #require(HistoryStorage.fileStat(at: url))+ #expect(after.identifier == before.identifier)+ #expect(after.modifiedAtNanoseconds == before.modifiedAtNanoseconds)+ #expect(try JSONFileStorage.load([TokenTurn].self, from: url) == values)+ }++ @Test func tokenIdentitiesMatchExistingEncodingExactly() throws {+ let bytes = Data((0 ... 255).map(UInt8.init))+ #expect(TokenTurn.hexString(bytes) == bytes.map { String(format: "%02x", $0) }.joined())+ #expect(TokenTurn.hexString(Data()).isEmpty)+ let salt = Data((0 ... 255).map(UInt8.init))+ for thread in ["", "thread", "中文/路径", "a\u{0000}b", String(repeating: "x", count: 1024)] {+ let data = try JSONEncoder().encode(["token-turn-v1", thread, "turn"])+ let expected = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ #expect(TokenTurn.identifier(thread: thread, turn: "turn") == expected)+ for root in [expected, "other-root"] {+ let value = TokenTurn(id: expected, rootID: root, updatedAt: TestFixtures.now)+ let exported = value.pseudonymized(salt: salt)+ func legacyHash(_ text: String) -> String {+ HMAC<SHA256>.authenticationCode(for: Data(text.utf8), using: SymmetricKey(data: salt))+ .map { String(format: "%02x", $0) }.joined()+ }+ #expect(exported.id == legacyHash(expected))+ #expect(exported.rootID == legacyHash(root))+ #expect(exported.updatedAt == value.updatedAt)+ }+ }+ }++ @Test func batchPseudonymsPreserveUpdatedValuesAndAccountIsolation() {+ let root = turn("main", "a", input: 100)+ let child = turn("child", "b", root: root.id, input: 200)+ var updated = child+ updated.usage = usage(input: 50)+ updated.rebuiltAt = TestFixtures.now.addingTimeInterval(60)+ let records = [root, child, updated]+ for salt in [Data("account-a".utf8), Data("account-b".utf8), Data()] {+ #expect(TokenTurn.pseudonymized(records, salt: salt) == records.map { $0.pseudonymized(salt: salt) })+ }+ }++ @Test func cachedTokenFileChecksBytesAcrossExternalWritesAndDeletion() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = directory.url.appendingPathComponent("cache.json")+ var first = TokenFileCache<[String: Int]>(url: url)+ var second = TokenFileCache<[String: Int]>(url: url)+ try first.save(["cursor": 1])+ #expect(try first.load() == ["cursor": 1])+ #expect(try second.load() == ["cursor": 1])+ let initial = try #require(HistoryStorage.fileStat(at: url))+ try first.save(["cursor": 1])+ #expect(HistoryStorage.fileStat(at: url)?.identifier == initial.identifier)+ let modifiedAt = try FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate]+ try Data("{\"cursor\":2}".utf8).write(to: url)+ if let modifiedAt {+ try FileManager.default.setAttributes([.modificationDate: modifiedAt], ofItemAtPath: url.path)+ }+ #expect(HistoryStorage.fileStat(at: url)?.size == initial.size)+ #expect(try first.load() == ["cursor": 2])+ #expect(try second.load() == ["cursor": 2])+ try second.save(["cursor": 3])+ #expect(try first.load() == ["cursor": 3])+ // 内存命中不能跳过另一进程修改后的保存检查点+ try second.save(["cursor": 4])+ try first.save(["cursor": 3])+ #expect(try second.load() == ["cursor": 3])+ try Data("invalid".utf8).write(to: url)+ #expect(throws: (any Error).self) { try first.load() }+ try FileManager.default.removeItem(at: url)+ #expect(try first.load() == nil)+ try first.save(["cursor": 3])+ #expect(try second.load() == ["cursor": 3])+ }++ @Test func cloudRebuildMarkerOverridesStaleTotalsAndCanClearUsage() {+ let stale = turn("main", "a", input: 500)+ var rebuilt = turn("main", "a", input: 100)+ rebuilt.startNewGeneration(at: TestFixtures.now)+ #expect(stale.merging(rebuilt) == rebuilt)+ #expect(rebuilt.merging(stale) == rebuilt)+ let exported = rebuilt.pseudonymized(salt: Data("account".utf8))+ let record = CKRecord(recordType: TokenSync.recordType, recordID: .init(recordName: exported.id))+ TokenSync.apply(exported, to: record)+ #expect(TokenSync.turn(from: record) == exported)+ var cleared = exported+ cleared.usage = nil+ cleared.startNewGeneration(at: TestFixtures.now.addingTimeInterval(1))+ TokenSync.apply(cleared, to: record)+ #expect(TokenSync.turn(from: record) == cleared)+ #expect(exported.merging(cleared).usage == nil)+ #expect(TokenTurn.syncable([cleared]) == [cleared])+ }++ @Test func cloudRecoveryMatchesAccountSaltAndRootIdentity() {+ let local = turn("child", "b", root: TokenTurn.identifier(thread: "main", turn: "a"), input: 100)+ var remote = local.pseudonymized(salt: Data("account-a".utf8))+ remote.startNewGeneration(at: TestFixtures.now)+ #expect(TokenHistoryBaseline(salt: Data("account-b".utf8), turns: [remote.id: remote]).replacement(for: local) == nil)+ let baseline = TokenHistoryBaseline(salt: Data("account-a".utf8), turns: [remote.id: remote])+ #expect(baseline.replacement(for: local)?.rootID == local.rootID)+ var unknownRoot = local+ unknownRoot.rootID = local.id+ #expect(baseline.replacement(for: unknownRoot) == nil)+ }++ @Test func sharedSyncLockExcludesConcurrentWritersWithoutBlockingCacheReads() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let first = try #require(try JSONFileStorage.acquireLock(in: directory.url, name: "sync.lock", nonblocking: true))+ let competing = try JSONFileStorage.acquireLock(in: directory.url, name: "sync.lock", nonblocking: true)+ #expect(competing == nil)+ if let competing {+ JSONFileStorage.releaseLock(competing)+ }+ try JSONFileStorage.withLock(in: directory.url) {}+ JSONFileStorage.releaseLock(first)+ let next = try #require(try JSONFileStorage.acquireLock(in: directory.url, name: "sync.lock", nonblocking: true))+ JSONFileStorage.releaseLock(next)+ }++ @Test func cumulativeSnapshotsAndMultipleDevicesCountEachThreadTurnOnce() {+ let root = turn("main", "a", input: 100)+ var updated = turn("main", "a", input: 200)+ updated.updatedAt = TestFixtures.now.addingTimeInterval(10)+ let child = turn("child", "b", root: root.id, input: 300)+ let result = TokenTurn.dailyUsage([root, updated, root, child, child], now: TestFixtures.now.addingTimeInterval(60))+ #expect(result[day]?.totalTokens == 520)+ #expect(TokenTurn.merged([updated, root])[root.id] == TokenTurn.merged([root, updated])[root.id])+ }++ @Test func allChildrenIncludingLaterTurnsBelongToRootStartDate() throws {+ let start = try #require(CodexDateFormat.dayDate(from: "2026-09-15")?.addingTimeInterval(86390))+ var root = turn("main", "a", input: 100)+ root.startedAt = start+ root.updatedAt = start.addingTimeInterval(30)+ var child = turn("child", "b", root: root.id, input: 200)+ child.startedAt = start.addingTimeInterval(20)+ child.updatedAt = start.addingTimeInterval(80)+ var followup = turn("child", "c", root: root.id, input: 300)+ followup.startedAt = start.addingTimeInterval(40)+ followup.updatedAt = start.addingTimeInterval(90)+ let days = TokenTurn.dailyUsage([root, child, followup], now: start.addingTimeInterval(100))+ #expect(days.count == 1)+ #expect(days["2026-09-15"]?.totalTokens == 630)+ #expect(TokenTurn.dailyUsage([child], now: start.addingTimeInterval(100)).isEmpty)+ }++ @Test func cacheRateUsesDailyTotalsAndMissingUsageDoesNotBecomeZero() {+ var a = turn("main", "a", input: 100)+ var b = turn("other", "a", input: 300)+ a.usage = usage(input: 100, cached: 80)+ b.usage = usage(input: 300, cached: 30)+ let merged = TokenTurn.dailyUsage([a, b], now: TestFixtures.now)+ #expect(merged[day]?.cacheHitRate == 0.275)+ a.usage = nil+ #expect(TokenTurn.dailyUsage([a], now: TestFixtures.now).isEmpty)+ a.usage = TokenUsage(inputTokens: 0, cachedInputTokens: 0, cacheWriteInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0, totalTokens: 0)+ #expect(TokenTurn.dailyUsage([a], now: TestFixtures.now)[day]?.totalTokens == 0)+ }++ @Test func cloudCodecUsesAccountScopedHashesAndRetainsAllCounters() throws {+ let source = turn("private-thread", "private-turn", input: 100)+ let exported = source.pseudonymized(salt: Data("account-a".utf8))+ #expect(exported.id == exported.rootID)+ #expect(exported.id != source.id)+ #expect(exported.id != source.pseudonymized(salt: Data("account-b".utf8)).id)+ let zone = CKRecordZone.ID(zoneName: "test", ownerName: CKCurrentUserDefaultName)+ let id = TokenSync.recordID(exported.id, zoneID: zone)+ #expect(id.recordName == exported.id)+ let record = CKRecord(recordType: TokenSync.recordType, recordID: id)+ TokenSync.apply(exported, to: record)+ #expect(TokenSync.turn(from: record) == exported)+ #expect(Set(record.allKeys()) == ["updatedAt", "rootID", "version", "startedAt", "usage", "generationID", "ancestorIDs", "checkpoint", "hasConflict"])+ let cloudUsage = try #require(record["usage"] as? Data)+ let cloudCounts = try #require(JSONSerialization.jsonObject(with: cloudUsage) as? [String: Int64])+ #expect(Set(cloudCounts.keys) == [+ "inputTokens", "cachedInputTokens", "cacheWriteInputTokens",+ "outputTokens", "reasoningOutputTokens", "totalTokens"+ ])+ let text = try #require(String(data: JSONEncoder().encode(exported), encoding: .utf8))+ #expect(!text.contains("private-thread"))+ #expect(!text.contains("private-turn"))+ record["version"] = 99 as CKRecordValue+ #expect(record.recordID == TokenSync.recordID(exported.id, zoneID: zone))+ #expect(TokenSync.turn(from: record) == nil)+ }++ @Test func childUsageWaitsForRootStartAndNeedsNoRootUsageRecord() {+ var root = turn("main", "a", input: 100)+ root.usage = nil+ let child = turn("child", "b", root: root.id, input: 200)+ #expect(TokenTurn.dailyUsage([child], now: TestFixtures.now).isEmpty)+ #expect(TokenTurn.dailyUsage([root, child], now: TestFixtures.now)[day]?.totalTokens == 210)+ #expect(Set(TokenTurn.syncable([root, child]).map(\.id)) == [root.id, child.id])+ }++ @Test func dailyOverflowIsUnavailableAndExpiredTurnsAreExcluded() {+ var root = turn("main", "a", input: 100)+ root.usage = TokenUsage(+ inputTokens: .max, cachedInputTokens: 0, cacheWriteInputTokens: 0,+ outputTokens: 0, reasoningOutputTokens: 0, totalTokens: .max+ )+ let child = turn("child", "b", root: root.id, input: 200)+ #expect(TokenTurn.dailyUsage([root, child], now: TestFixtures.now).isEmpty)+ root.startedAt = TestFixtures.now.addingTimeInterval(-220 * 86400)+ #expect(TokenTurn.dailyUsage([root], now: TestFixtures.now).isEmpty)+ }++ @Test func heatmapSeparatesAccountIntensityFromLocalDailyMetrics() throws {+ var history = HistorySnapshot.empty+ history.tokenUsageByDate = [day: usage(input: 100)]+ let grid = UsageHeatmapDay.grid(usage: nil, history: history, showsActivity: true, columnCount: 2, today: TestFixtures.now)+ let today = try #require(grid.compactMap(\.self).first { $0.startDate == day })+ #expect(today.tokenState == .unavailable)+ #expect(today.tokenUsage?.totalTokens == 110)+ #expect(today.history.turnCount == 0)+ }++ private var day: String {+ CodexDateFormat.dayString(from: TestFixtures.now)+ }++ private func usage(input: Int64, cached: Int64 = 20) -> TokenUsage {+ TokenUsage(inputTokens: input, cachedInputTokens: cached, cacheWriteInputTokens: 5, outputTokens: 10, reasoningOutputTokens: 2, totalTokens: input + 10)+ }++ private func turn(_ thread: String, _ turn: String, root: String? = nil, input: Int64) -> TokenTurn {+ let id = TokenTurn.identifier(thread: thread, turn: turn)+ return TokenTurn(id: id, rootID: root ?? id, startedAt: TestFixtures.now, updatedAt: TestFixtures.now, usage: usage(input: input))+ }+}++extension TokenHistoryTests {+ @Test func unknownCacheVersionIsNotOverwritten() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let data = Data(#"{"version":999,"turns":{},"files":{}}"#.utf8)+ let url = try directory.write(data, to: "Aggregates/tokens.json")+ let store = TokenHistoryStore(directoryURL: directory.url)+ await #expect(throws: TokenCacheError.self) { try await store.refresh() }+ #expect(try Data(contentsOf: url) == data)+ }++ @Test func cacheReadFailureIsNotReplacedWithEmptyData() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = directory.url.appendingPathComponent("Aggregates/tokens.json")+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)+ let store = TokenHistoryStore(directoryURL: directory.url)+ await #expect(throws: (any Error).self) { try await store.refresh() }+ #expect(try (url.resourceValues(forKeys: [.isDirectoryKey])).isDirectory == true)+ }++ @Test func incompleteJournalDoesNotOverwriteDamagedCache() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let cache = try directory.write("broken cache", to: "Aggregates/tokens.json")+ _ = try directory.write("broken event\n", to: "Events/\(HistoryStorage.dateKey(for: Date())).jsonl")+ let store = TokenHistoryStore(directoryURL: directory.url)+ await #expect(throws: TokenCacheError.self) { try await store.refresh() }+ #expect(try String(contentsOf: cache, encoding: .utf8) == "broken cache")+ }+}++extension TokenHistoryTests {+ private func observation(sequence: Int64, previous: Int64, current: Int64, stream: String = "stream") -> TokenObservation {+ let id = TokenTurn.identifier(thread: "observed", turn: "turn")+ func counts(_ count: Int64) -> TokenUsage {+ TokenUsage(+ inputTokens: count,+ cachedInputTokens: 0,+ cacheWriteInputTokens: 0,+ outputTokens: 0,+ reasoningOutputTokens: 0,+ totalTokens: count+ )+ }+ return TokenObservation(+ turn: TokenTurn(id: id, rootID: id, startedAt: TestFixtures.now, updatedAt: TestFixtures.now),+ rootStartedAt: TestFixtures.now,+ streamID: stream,+ sequence: sequence,+ previous: counts(previous),+ current: counts(current)+ )+ }++ @Test func correctionAndRetryPreserveOnlyUncoveredUsageAcrossRestart() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ let first = observation(sequence: 1, previous: 0, current: 100)+ var corrected = try #require(try await store.recordObservations([first], now: TestFixtures.now).first)+ corrected.usage = observation(sequence: 1, previous: 0, current: 60).current+ corrected.startNewGeneration(at: TestFixtures.now.addingTimeInterval(-60))+ let salt = Data("test".utf8)+ let remote = corrected.pseudonymized(salt: salt)+ _ = try await store.refresh(now: TestFixtures.now, baseline: TokenHistoryBaseline(salt: salt, turns: [remote.id: remote]))+ let second = observation(sequence: 2, previous: 100, current: 110)+ let result = try await store.recordObservations([first, second, second], now: TestFixtures.now)+ #expect(result.first?.usage?.totalTokens == 70)+ #expect(result.first?.generationID == corrected.generationID)+ let restarted = TokenHistoryStore(directoryURL: directory.url)+ #expect(try await restarted.recordObservations([second], now: TestFixtures.now).first?.usage?.totalTokens == 70)+ try FileManager.default.removeItem(at: directory.url.appendingPathComponent("Aggregates/tokens.json"))+ #expect(try await restarted.refresh(now: TestFixtures.now).first?.usage?.totalTokens == 70)+ }++ @Test func remoteCoveredObservationIsNotAddedTwice() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ let first = observation(sequence: 1, previous: 0, current: 100)+ let second = observation(sequence: 2, previous: 100, current: 110)+ let local = try #require(try await store.recordObservations([first], now: TestFixtures.now).first)+ var corrected = try second.applying(to: local)+ corrected.startNewGeneration(at: TestFixtures.now)+ corrected.usage = observation(sequence: 1, previous: 0, current: 60).current+ let salt = Data("test".utf8)+ let remote = corrected.pseudonymized(salt: salt)+ _ = try await store.refresh(now: TestFixtures.now, baseline: TokenHistoryBaseline(salt: salt, turns: [remote.id: remote]))+ #expect(try await store.recordObservations([second], now: TestFixtures.now).first?.usage?.totalTokens == 60)+ }++ @Test func rebuildRecomputesFromCountersAndRejectsIncompleteCoverage() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ let first = observation(sequence: 1, previous: 1000, current: 1100)+ var bad = try #require(try await store.recordObservations([first], now: TestFixtures.now).first)+ bad.startNewGeneration(at: TestFixtures.now)+ bad.usage = observation(sequence: 1, previous: 0, current: 900).current+ try await store.record([bad], now: TestFixtures.now)+ _ = try await store.rebuild(for: [day], now: TestFixtures.now)+ let restored = try #require(try await store.currentTurns(now: TestFixtures.now).first)+ #expect(restored.usage?.totalTokens == 100)+ #expect(restored.generationID != bad.generationID)+ let second = observation(sequence: 2, previous: 1100, current: 1120)+ var remote = try second.applying(to: restored)+ remote.startNewGeneration(at: TestFixtures.now)+ try await store.record([remote], now: TestFixtures.now)+ await #expect(throws: TokenCacheError.self) { try await store.rebuild(for: [day], now: TestFixtures.now) }+ #expect(try await store.currentTurns(now: TestFixtures.now).first == remote)+ }++ @Test func concurrentCorrectionsConvergeToExplicitConflictWithoutClockOrdering() throws {+ let original = try observation(sequence: 1, previous: 0, current: 100).applying(to: nil)+ var a = original+ var b = original+ a.startNewGeneration(at: TestFixtures.now.addingTimeInterval(9999))+ b.startNewGeneration(at: TestFixtures.now.addingTimeInterval(-9999))+ a.usage = observation(sequence: 1, previous: 0, current: 60).current+ b.usage = observation(sequence: 1, previous: 0, current: 80).current+ let merged = a.merging(b)+ #expect(merged.hasConflict)+ #expect(merged.usage == nil)+ #expect(merged.generationID == b.merging(a).generationID)+ #expect(merged.merging(a).generationID == merged.generationID)+ #expect(merged.merging(b).generationID == merged.generationID)+ #expect(TokenTurn.dailyUsage([merged], now: TestFixtures.now).isEmpty)+ }++ @Test func missingObservationCannotAdvanceCheckpoint() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ let missingFirst = observation(sequence: 2, previous: 100, current: 110)+ await #expect(throws: TokenCacheError.self) { try await store.recordObservations([missingFirst], now: TestFixtures.now) }+ #expect(try await store.currentTurns(now: TestFixtures.now).isEmpty)+ }+}++extension TokenHistoryTests {+ @Test func staleSnapshotRebasesOnlyItsUncoveredCheckpointTail() throws {+ let original = try observation(sequence: 1, previous: 0, current: 100).applying(to: nil)+ var correction = original+ correction.startNewGeneration(at: TestFixtures.now)+ correction.usage = observation(sequence: 1, previous: 0, current: 60).current+ let stale = try observation(sequence: 2, previous: 100, current: 110).applying(to: original)+ let merged = correction.merging(stale)+ #expect(merged.usage?.totalTokens == 70)+ #expect(merged.generationID == correction.generationID)+ #expect(stale.merging(correction) == merged)+ #expect(merged.merging(stale) == merged)+ #expect(merged.merging(correction) == merged)+ }+}diff --git a/CodexBarTests/WorkflowAggregationTests.swift b/CodexBarTests/WorkflowAggregationTests.swiftdeleted file mode 100644index 5aca1ce..0000000--- a/CodexBarTests/WorkflowAggregationTests.swift+++ /dev/null@@ -1,168 +0,0 @@-import Foundation-import Testing--struct WorkflowAggregationTests {- @Test func identifierFieldsKeepTheirStoredNames() throws {- let aggregate = try TestFixtures.decode(WorkflowDailyAggregate.self, #"{"date":"2026-09-15","sessionIds":["session-a"],"turnIds":["turn-a"]}"#)- #expect(aggregate.sessionIDs == ["session-a"])- #expect(aggregate.turnIDs == ["turn-a"])- let encoded = try JSONEncoder().encode(aggregate)- let fields = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any])- #expect(fields["sessionIds"] as? [String] == ["session-a"])- #expect(fields["turnIds"] as? [String] == ["turn-a"])- #expect(fields["sessionIDs"] == nil)- #expect(fields["turnIDs"] == nil)-- let record = try TestFixtures.decode(WorkflowSyncedDailyRecord.self, #"{"deviceId":"device-a","daily":{"date":"2026-09-15"}}"#)- #expect(record.deviceID == "device-a")- let recordData = try JSONEncoder().encode(record)- let recordFields = try #require(JSONSerialization.jsonObject(with: recordData) as? [String: Any])- #expect(recordFields["deviceId"] as? String == "device-a")- #expect(recordFields["deviceID"] == nil)- }-- @Test func missingHookCountsRemainUnavailableThroughBothStorageFormats() throws {- let aggregate = try TestFixtures.decode(WorkflowDailyAggregate.self, #"{"date":"2026-09-15","stopCount":0}"#)- #expect(aggregate.eventCount == nil)- #expect(aggregate.interruptCount == nil)- #expect(aggregate.stopCount == 0)- let local = try JSONDecoder().decode(WorkflowDailyAggregate.self, from: aggregate.jsonLineData())- let synced = try JSONDecoder().decode(WorkflowSyncedDailyAggregate.self, from: aggregate.syncedAggregate.jsonLineData())- #expect(local == aggregate)- #expect(synced.interruptCount == nil)- #expect(synced.stopCount == 0)- }-- @Test func eventPairsAndIdentifiersAreCountedWithoutDoubleCounting() {- var accumulator = makeAccumulator()- for name in [CodexHookEvent.sessionStart, .userPromptSubmit, .preToolUse, .postToolUse, .preCompact, .postCompact, .subagentStart, .subagentStop] {- accumulator.record(TestFixtures.event(name))- }- accumulator.record(TestFixtures.event(.stop, session: "terminal-only", turn: "terminal-only"))- accumulator.record(TestFixtures.event(.interrupt, session: "interrupt-only", turn: "interrupt-only"))- let retained = accumulator.finalized(identifierStorage: .retained)- let compacted = accumulator.finalized(identifierStorage: .compacted)- #expect(retained.eventCount == 10)- #expect(retained.sessionIDs == ["interrupt-only", "session-a", "terminal-only"])- #expect(retained.turnIDs == ["turn-a"])- #expect(retained.metrics.toolCallCount == 1)- #expect(retained.metrics.contextCompactionCount == 1)- #expect(retained.metrics.subagentCount == 1)- #expect(retained.metrics.interruptCount == 1)- #expect(retained.metrics == compacted.metrics)- #expect(compacted.sessionIDs == nil)- #expect(compacted.turnIDs == nil)- #expect(!compacted.supportsIncrementalAggregation)- }-- @Test func incrementalAggregationMatchesFullReplay() {- let firstEvents = [TestFixtures.event(.sessionStart), TestFixtures.event()]- let laterEvents = [TestFixtures.event(.preToolUse), TestFixtures.event(turn: "turn-b")]- var full = makeAccumulator()- (firstEvents + laterEvents).forEach { full.record($0) }- var initial = makeAccumulator()- firstEvents.forEach { initial.record($0) }- var incremental = WorkflowDailyAccumulator(- appending: initial.finalized(identifierStorage: .retained), sourceGeneration: "source", sourceIsFresh: true- )- laterEvents.forEach { incremental.record($0) }- #expect(incremental.finalized(identifierStorage: .retained) == full.finalized(identifierStorage: .retained))- }-- @Test func historicalAggregationIncludesAutoReviewEvents() {- var accumulator = makeAccumulator()- accumulator.record(TestFixtures.event(origin: .autoReview))- #expect(accumulator.finalized(identifierStorage: .compacted).metrics.turnCount == 1)- }-- @Test func sessionEndAloneDoesNotCreateAnActiveSession() {- var accumulator = makeAccumulator()- accumulator.record(TestFixtures.event(.sessionEnd, turn: nil))- let aggregate = accumulator.finalized(identifierStorage: .compacted)- #expect(aggregate.sessionEndCount == 1)- #expect(aggregate.metrics.sessionCount == 0)- #expect(aggregate.metrics.turnCount == 0)- }-- @Test func unavailableInterruptCountPropagatesAcrossDeviceMetrics() {- var known = TestFixtures.aggregate()- known.interruptCount = 3- var unknown = TestFixtures.aggregate()- unknown.interruptCount = nil- #expect(known.metrics.adding(unknown.metrics).interruptCount == nil)- #expect(known.metrics.adding(known.metrics).interruptCount == 6)- }-- @Test func modelRankingHasDeterministicTiesAndIgnoresZeroCounts() {- var aggregate = TestFixtures.aggregate()- aggregate.modelCounts = ["z-model": 3, "a-model": 3, "unused": 0]- #expect(aggregate.metrics.mostUsedModel == "a-model")- aggregate.modelCounts = ["unused": 0]- #expect(aggregate.metrics.mostUsedModel == nil)- }-- @Test func compactingLegacyIdentifiersPreservesUniqueCounts() throws {- var aggregate = try TestFixtures.decode(WorkflowDailyAggregate.self, """- {"date":"2026-09-15","sessionCount":0,"sessionIds":["a","a","b"],"turnIds":["x","x"],"stopCount":9}- """)- aggregate.normalizeIdentifierStorage(retainsIdentifiers: false)- #expect(aggregate.sessionCount == 2)- #expect(aggregate.turnCount == 1)- #expect(aggregate.sessionIDs == nil)- }-- @Test func syncExportContainsCountsWithoutRawTaskIdentifiers() throws {- var accumulator = makeAccumulator()- accumulator.record(TestFixtures.event())- let data = try accumulator.finalized(identifierStorage: .retained).syncedAggregate.jsonLineData()- let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])- #expect(object["sessionIds"] == nil)- #expect(object["turnIds"] == nil)- #expect(object["sessionCount"] as? Int == 1)- let text = try #require(String(data: data, encoding: .utf8))- #expect(!text.contains("session-a"))- }-- private func makeAccumulator() -> WorkflowDailyAccumulator {- WorkflowDailyAccumulator(rebuilding: "2026-09-15", sourceGeneration: "source", sourceIsFresh: true, hookCountAvailability: .all)- }-}--struct WorkflowMergeTests {- @Test func sameGenerationUsesOneMostCompleteContribution() {- let local = TestFixtures.aggregate(events: 2, turns: 1)- let remote = record(TestFixtures.aggregate(events: 4, turns: 2))- #expect(snapshot(local, [remote]).dailyMetrics.first?.turnCount == 2)- #expect(snapshot(TestFixtures.aggregate(events: 6, turns: 3), [remote]).dailyMetrics.first?.turnCount == 3)- }-- @Test func freshIndependentGenerationAddsToPreviousContribution() {- let local = TestFixtures.aggregate(generation: "new", fresh: true, turns: 2)- #expect(snapshot(local, [record(TestFixtures.aggregate(turns: 3))]).dailyMetrics.first?.turnCount == 5)- }-- @Test func unverifiedLocalGenerationDoesNotDoubleCountRemoteHistory() {- let local = TestFixtures.aggregate(generation: "unknown", fresh: false, turns: 2)- #expect(snapshot(local, [record(TestFixtures.aggregate(turns: 3))]).dailyMetrics.first?.turnCount == 3)- }-- @Test func legacyContentMatchDeduplicatesAndOtherDevicesStillAdd() {- let local = TestFixtures.aggregate()- let remote = record(TestFixtures.aggregate(generation: nil))- let otherDevice = record(TestFixtures.aggregate(turns: 4), device: "other")- #expect(snapshot(local, [remote, otherDevice]).dailyMetrics.first?.turnCount == 5)- }-- @Test func remoteOnlyDaysRemainVisible() {- let result = WorkflowSnapshot(localAggregates: [], syncedRecords: [record(TestFixtures.aggregate(turns: 4))], currentDeviceID: "device")- #expect(result.dailyMetrics.first?.turnCount == 4)- }-- private func record(_ aggregate: WorkflowDailyAggregate, device: String = "device") -> WorkflowSyncedDailyRecord {- WorkflowSyncedDailyRecord(deviceID: device, daily: aggregate.syncedAggregate)- }-- private func snapshot(_ local: WorkflowDailyAggregate, _ remote: [WorkflowSyncedDailyRecord]) -> WorkflowSnapshot {- WorkflowSnapshot(localAggregates: [local], syncedRecords: remote, currentDeviceID: "device")- }-}diff --git a/CodexBarTests/ZoneRecoveryTests.swift b/CodexBarTests/ZoneRecoveryTests.swiftnew file mode 100644index 0000000..b037173--- /dev/null+++ b/CodexBarTests/ZoneRecoveryTests.swift@@ -0,0 +1,332 @@+import CloudKit+import Foundation+import Synchronization+import Testing++struct ZoneRecoveryTests {+ private static let zone = CKRecordZone.ID(zoneName: SyncCloudKit.zoneName, ownerName: CKCurrentUserDefaultName)++ @Test(arguments: [CKError.Code.zoneNotFound, .userDeletedZone, .unknownItem], [false, true])+ func absentZoneIsCreatedAndLocalDataIsUploaded(code: CKError.Code, wrapped: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = ZoneDatabase()+ await database.removeZone(code: code, wrapped: wrapped)+ _ = try directory.write("invalid activity cache", to: "Activity/cache.json")+ _ = try directory.write("invalid token cache", to: "Tokens/cache.json")+ let service = service(database, directory)+ let snapshot = await service.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ #expect(snapshot.currentDeviceID != nil)+ #expect(await database.creations == 1)+ #expect(await database.recordCount("Activity") == 1)+ #expect(await database.recordCount("Tokens") == 1)+ #expect(ActivitySyncStore(directoryURL: directory.url).loadState().hashByDate.count == 1)+ }++ @Test(arguments: [ZoneDatabase.Point.metadata, .query, .changes, .activityUpload, .tokenUpload], [false, true])+ private func deletionDuringSyncResetsBothPipelinesAndRetries(point: ZoneDatabase.Point, wrapped: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = ZoneDatabase()+ let service = service(database, directory)+ _ = await service.synchronizeIfEnabled(localAggregates: [aggregate(0), aggregate(1)], localTokenTurns: [turn(0), turn(1)], trigger: .manual)+ let previousID = ActivitySyncStore(directoryURL: directory.url).loadState().deviceID+ // 保留 salt 可以验证恢复不依赖设备 ID 碰巧变化+ await database.failOnce(at: point, wrapped: wrapped, preservingSalt: true)+ let snapshot = await service.synchronizeIfEnabled(localAggregates: [aggregate(0, events: 3)], localTokenTurns: [turn(0, tokens: 3)], trigger: .manual)+ #expect(snapshot.currentDeviceID == previousID)+ #expect(await database.creations == 1)+ #expect(await database.recordCount("Activity") == 1)+ #expect(await database.recordCount("Tokens") == 1)+ #expect(snapshot.records.count == 1)+ #expect(try cachedTokenCount(directory) == 1)+ #expect(ActivitySyncStore(directoryURL: directory.url).loadState().hashByDate.count == 1)+ }++ @Test func peerRecreatingSameZoneInvalidatesCachedIdentityAndUploadHashes() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = ZoneDatabase()+ let service = service(database, directory)+ let first = await service.synchronizeIfEnabled(localAggregates: [aggregate(0), aggregate(1)], localTokenTurns: [turn(0), turn(1)], trigger: .manual)+ await database.recreateByPeer()+ let second = await service.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ #expect(first.currentDeviceID != second.currentDeviceID)+ #expect(second.currentDeviceID != nil)+ #expect(await database.creations == 0)+ #expect(await database.recordCount("Activity") == 1)+ #expect(await database.recordCount("Tokens") == 1)+ #expect(second.records.count == 1)+ #expect(try cachedTokenCount(directory) == 1)+ }++ @Test(arguments: [nil, "iCloud.app.zabrian.codexbar"] as [String?])+ func switchingContainerDiscardsOldSyncState(containerIdentifier: String?) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = ZoneDatabase()+ let first = service(database, directory)+ _ = await first.synchronizeIfEnabled(localAggregates: [aggregate(0), aggregate(1)], localTokenTurns: [turn(0), turn(1)], trigger: .manual)+ let store = ActivitySyncStore(directoryURL: directory.url)+ var state = store.loadState()+ state.containerIdentifier = containerIdentifier+ try store.saveState(state)++ // 新容器已有 zone 时也必须重新上传并移除旧容器缓存+ let nextDatabase = ZoneDatabase()+ let next = service(nextDatabase, directory)+ let snapshot = await next.snapshotFromCacheIfEnabled()+ #expect(snapshot.currentDeviceID == nil)+ #expect(snapshot.records.isEmpty)+ #expect(await next.tokenRecoveryBaselineIfEnabled() == nil)+ #expect(store.loadState().hashByDate.isEmpty)+ let synced = await next.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ #expect(synced.currentDeviceID != nil)+ #expect(synced.records.count == 1)+ #expect(try cachedTokenCount(directory) == 1)+ #expect(await nextDatabase.recordCount("Activity") == 1)+ #expect(await nextDatabase.recordCount("Tokens") == 1)+ #expect(store.loadState().containerIdentifier == SyncCloudKit.containerIdentifier)+ }++ @Test func repeatedDeletionHasBoundedRecoveryAndCanRecoverOnNextRun() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = ZoneDatabase()+ await database.failOnce(at: .query, repeats: true)+ let service = service(database, directory)+ let failed = await service.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ #expect(await database.queryCount == 2)+ #expect(await database.creations == 1)+ #expect(failed.currentDeviceID == nil)+ #expect(ActivitySyncStore(directoryURL: directory.url).loadState().hashByDate.isEmpty)+ await database.repair()+ let recovered = await service.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ #expect(recovered.currentDeviceID != nil)+ #expect(await database.creations == 2)+ #expect(await database.recordCount("Activity") == 1)+ #expect(await database.recordCount("Tokens") == 1)+ }++ @Test(arguments: [CKError.Code.networkFailure, .notAuthenticated, .permissionFailure, .quotaExceeded])+ func unrelatedFailuresDoNotResetZoneOrSyncedState(code: CKError.Code) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = ZoneDatabase()+ let service = service(database, directory)+ _ = await service.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ let before = ActivitySyncStore(directoryURL: directory.url).loadState()+ let tokens = try Data(contentsOf: directory.url.appendingPathComponent("Tokens/cache.json"))+ await database.rejectQueries(code)+ _ = await service.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ #expect(await database.creations == 0)+ #expect(ActivitySyncStore(directoryURL: directory.url).loadState() == before)+ #expect(try Data(contentsOf: directory.url.appendingPathComponent("Tokens/cache.json")) == tokens)+ }++ @Test func switchingSyncOffDuringFailurePreventsZoneCreation() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let enabled = Mutex(true)+ let database = ZoneDatabase(onFailure: { enabled.withLock { $0 = false } })+ await database.removeZone()+ let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { enabled.withLock { $0 } })+ _ = await service.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ #expect(await database.creations == 0)+ #expect(await database.recordCount("Metadata") == 0)+ }++ @Test func interruptedCacheResetRemainsRecoverableAfterRestart() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = ZoneDatabase()+ await database.removeZone()+ let store = ActivitySyncStore(directoryURL: directory.url)+ try store.saveState(SyncState(deviceID: "stale", hashByDate: [aggregate(0).date: "stale"]))+ let blocked = directory.url.appendingPathComponent("Tokens/store.lock")+ try FileManager.default.createDirectory(at: blocked, withIntermediateDirectories: true)+ _ = await service(database, directory).synchronizeIfEnabled(localAggregates: [aggregate(0)], trigger: .manual)+ #expect(store.loadState().deviceID == nil)+ #expect(store.loadState().hashByDate.isEmpty)+ #expect(await database.creations == 0)+ try FileManager.default.removeItem(at: blocked)+ let snapshot = await service(database, directory).synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ #expect(snapshot.currentDeviceID != nil)+ #expect(await database.creations == 1)+ #expect(await database.recordCount("Activity") == 1)+ }++ @Test func zoneClassificationKeepsRecordAndZoneErrorsSeparate() {+ let item = CKRecord.ID(recordName: "missing", zoneID: Self.zone)+ let other = CKRecordZone.ID(zoneName: "another")+ func partial(_ key: AnyHashable, _ code: CKError.Code) -> CKError {+ CKError(.partialFailure, userInfo: [CKPartialErrorsByItemIDKey: [key: CKError(code)]])+ }+ #expect(!SyncRecovery.isMissingZone(CKError(.unknownItem), zoneID: Self.zone))+ #expect(SyncRecovery.isMissingZone(CKError(.unknownItem), zoneID: Self.zone, queryingZone: true))+ #expect(!SyncRecovery.isMissingZone(partial(item, .unknownItem), zoneID: Self.zone, queryingZone: true))+ #expect(!SyncRecovery.isMissingZone(partial(other, .userDeletedZone), zoneID: Self.zone))+ #expect(SyncRecovery.isMissingZone(partial(item, .userDeletedZone), zoneID: Self.zone))+ #expect(!SyncRecovery.isMissingZone(CKError(.changeTokenExpired), zoneID: Self.zone))+ }++ private func service(_ database: ZoneDatabase, _ directory: TestDirectory) -> SyncService {+ SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ }++ private func aggregate(_ index: Int, events: Int = 1) -> ActivityAggregate {+ var value = ActivityAggregate(date: HistoryStorage.dateKey(for: Date().addingTimeInterval(Double(-index) * 86400)), generationID: "source", generationStartedEmpty: true)+ value.eventCount = events+ return value+ }++ private func turn(_ index: Int, tokens: Int = 1) -> TokenTurn {+ let id = TokenTurn.identifier(thread: "test", turn: String(index))+ let now = Date().addingTimeInterval(Double(-index) * 86400)+ let usage = TokenUsage(+ inputTokens: Int64(tokens), cachedInputTokens: 0, cacheWriteInputTokens: 0,+ outputTokens: 0, reasoningOutputTokens: 0, totalTokens: Int64(tokens)+ )+ return TokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: usage)+ }++ private func cachedTokenCount(_ directory: TestDirectory) throws -> Int {+ let data = try Data(contentsOf: directory.url.appendingPathComponent("Tokens/cache.json"))+ let json = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])+ return try #require(json["turns"] as? [String: Any]).count+ }+}++private actor ZoneDatabase: SyncDatabase {+ enum Point: Sendable { case metadata, query, changes, activityUpload, tokenUpload }+ private var exists = true+ private var stored: [CKRecord.ID: CKRecord] = [:]+ private var missingCode = CKError.Code.userDeletedZone+ private var wrapped = false+ private var failurePoint: Point?+ private var repeats = false+ private var savedMetadata: CKRecord?+ private var preservesSalt = false+ private var queryError: CKError.Code?+ private let onFailure: @Sendable () -> Void+ private(set) var creations = 0+ private(set) var queryCount = 0++ init(onFailure: @escaping @Sendable () -> Void = {}) {+ self.onFailure = onFailure+ }++ func recordCount(_ type: String) -> Int {+ stored.values.filter { $0.recordType == type }.count+ }++ func removeZone(code: CKError.Code = .userDeletedZone, wrapped: Bool = false) {+ exists = false+ stored = [:]+ missingCode = code+ self.wrapped = wrapped+ }++ func failOnce(at point: Point, wrapped: Bool = false, preservingSalt: Bool = false, repeats: Bool = false) {+ failurePoint = point+ self.wrapped = wrapped+ preservesSalt = preservingSalt+ self.repeats = repeats+ }++ func repair() {+ failurePoint = nil+ }++ func rejectQueries(_ code: CKError.Code) {+ queryError = code+ }++ func recreateByPeer() {+ let metadata = stored.values.first { $0.recordType == "Metadata" }?.copy() as? CKRecord+ stored = [:]+ metadata?["salt"] = Data(repeating: 7, count: 32) as CKRecordValue+ if let metadata {+ stored[metadata.recordID] = metadata+ }+ }++ private func check(_ point: Point?, zone: CKRecordZone.ID, record: CKRecord.ID? = nil) throws {+ if let point, failurePoint == point {+ savedMetadata = preservesSalt ? stored.values.first { $0.recordType == "Metadata" } : nil+ stored = [:]+ exists = false+ if !repeats {+ failurePoint = nil+ }+ }+ guard !exists else { return }+ onFailure()+ let error = CKError(missingCode)+ if wrapped {+ let key: AnyHashable = record.map(AnyHashable.init) ?? AnyHashable(zone)+ throw CKError(.partialFailure, userInfo: [CKPartialErrorsByItemIDKey: [key: error]])+ }+ throw error+ }++ func recordZone(for id: CKRecordZone.ID) async throws -> CKRecordZone {+ try check(nil, zone: id)+ return CKRecordZone(zoneID: id)+ }++ func modifyRecordZones(saving zones: [CKRecordZone], deleting _: [CKRecordZone.ID]) async throws -> ZoneModification {+ creations += 1+ exists = true+ if let savedMetadata {+ stored[savedMetadata.recordID] = savedMetadata+ }+ return (Dictionary(uniqueKeysWithValues: zones.map { ($0.zoneID, .success($0)) }), [:])+ }++ func records(for ids: [CKRecord.ID], desiredKeys _: [CKRecord.FieldKey]?) async throws -> Records {+ if let id = ids.first {+ try check(id.recordName == "accountSalt" ? .metadata : nil, zone: id.zoneID, record: id)+ }+ return Dictionary(uniqueKeysWithValues: ids.map { id in+ (id, stored[id].map { .success(copy($0)) } ?? .failure(CKError(.unknownItem)))+ })+ }++ func modifyRecords(saving records: [CKRecord], deleting ids: [CKRecord.ID], savePolicy _: CKModifyRecordsOperation.RecordSavePolicy, atomically _: Bool) async throws -> Modification {+ if let record = records.first {+ let point: Point? = record.recordType == "Activity" ? .activityUpload : record.recordType == "Tokens" ? .tokenUpload : nil+ try check(point, zone: record.recordID.zoneID, record: record.recordID)+ }+ for record in records {+ stored[record.recordID] = copy(record)+ }+ for id in ids {+ try check(nil, zone: id.zoneID, record: id)+ stored[id] = nil+ }+ return (Dictionary(uniqueKeysWithValues: records.map { ($0.recordID, .success(copy($0))) }), Dictionary(uniqueKeysWithValues: ids.map { ($0, .success(())) }))+ }++ func records(matching query: CKQuery, inZoneWith zone: CKRecordZone.ID?, desiredKeys _: [CKRecord.FieldKey]?, resultsLimit _: Int) async throws -> QueryPage {+ queryCount += 1+ if let queryError {+ throw CKError(queryError)+ }+ try check(.query, zone: zone ?? CKRecordZone.default().zoneID)+ return (stored.values.filter { $0.recordType == query.recordType }.map { ($0.recordID, .success(copy($0))) }, nil)+ }++ func records(continuingMatchFrom _: CKQueryOperation.Cursor, desiredKeys _: [CKRecord.FieldKey]?, resultsLimit _: Int) async throws -> QueryPage {+ ([], nil)+ }++ func fetchChanges(inZoneWith zone: CKRecordZone.ID, since _: CKServerChangeToken?, resultsLimit _: Int) async throws -> SyncChanges {+ try check(.changes, zone: zone)+ return SyncChanges(records: stored.mapValues { .success(copy($0)) }, deletions: [], token: nil, moreComing: false)+ }++ private func copy(_ record: CKRecord) -> CKRecord {+ record.copy() as? CKRecord ?? record+ }+}diff --git a/Config/CloudKit.ckdb b/Config/CloudKit.ckdbnew file mode 100644index 0000000..1de36b6--- /dev/null+++ b/Config/CloudKit.ckdb@@ -0,0 +1,98 @@+DEFINE SCHEMA++ RECORD TYPE Activity (+ deviceID STRING QUERYABLE SORTABLE,+ date STRING SORTABLE,+ generationID STRING,++ eventCount INT64,+ sessionCount INT64,+ turnCount INT64,++ sessionStartedCount INT64,+ sessionEndedCount INT64,+ turnStartedCount INT64,+ turnCompletedCount INT64,+ turnAbortedCount INT64,+ toolStartedCount INT64,+ toolCompletedCount INT64,+ approvalRequestedCount INT64,+ subagentStartedCount INT64,+ subagentEndedCount INT64,+ compactionStartedCount INT64,+ compactionCompletedCount INT64,++ modelCounts BYTES,+ projectCounts BYTES,++ updatedAt TIMESTAMP,+ version INT64,++ "___recordID" REFERENCE QUERYABLE,+ "___createTime" TIMESTAMP,+ "___createdBy" REFERENCE,+ "___modTime" TIMESTAMP,+ "___modifiedBy" REFERENCE,+ "___etag" STRING,++ GRANT WRITE TO "_creator",+ GRANT CREATE TO "_icloud",+ GRANT READ TO "_world"+ );++ RECORD TYPE Metadata (+ salt BYTES QUERYABLE SORTABLE,+ version INT64 QUERYABLE SORTABLE,++ "___recordID" REFERENCE QUERYABLE,+ "___createTime" TIMESTAMP,+ "___createdBy" REFERENCE,+ "___modTime" TIMESTAMP,+ "___modifiedBy" REFERENCE,+ "___etag" STRING,++ GRANT WRITE TO "_creator",+ GRANT CREATE TO "_icloud",+ GRANT READ TO "_world"+ );++ RECORD TYPE Tokens (+ rootID STRING,+ startedAt TIMESTAMP,++ generationID STRING,+ ancestorIDs LIST<STRING>,+ checkpoint BYTES,+ hasConflict INT64,++ usage BYTES,++ rebuiltAt TIMESTAMP,+ updatedAt TIMESTAMP,+ version INT64,++ "___recordID" REFERENCE QUERYABLE,+ "___createTime" TIMESTAMP,+ "___createdBy" REFERENCE,+ "___modTime" TIMESTAMP,+ "___modifiedBy" REFERENCE,+ "___etag" STRING,++ GRANT WRITE TO "_creator",+ GRANT CREATE TO "_icloud",+ GRANT READ TO "_world"+ );++ RECORD TYPE Users (+ roles LIST<INT64>,++ "___recordID" REFERENCE,+ "___createTime" TIMESTAMP,+ "___createdBy" REFERENCE,+ "___modTime" TIMESTAMP,+ "___modifiedBy" REFERENCE,+ "___etag" STRING,++ GRANT WRITE TO "_creator",+ GRANT READ TO "_world"+ );diff --git a/Docs/DeveloperGuide/README.md b/Docs/DeveloperGuide/README.mddeleted file mode 100644index 2ecc4d7..0000000--- a/Docs/DeveloperGuide/README.md+++ /dev/null@@ -1,50 +0,0 @@-# CodexBar 开发者指南--简体中文 | [English](../en/DeveloperGuide/README.md)--## 按职责查找--| 文档 | 内容 |-| --- | --- |-| [整体架构](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) | 私有数据库、设备标识哈希、上传、合并和重建 |-| [通知系统](notifications.md) | 通知触发、去重、声音、触觉和点击行为 |-| [UI 与应用生命周期](ui-and-lifecycle.md) | 菜单栏、面板、焦点、全局快捷键和服务装配 |-| [数据与隐私边界](data-and-privacy.md) | 本地文件、网络访问、云端字段和日志边界 |-| [开发与验证](development.md) | 工程结构、构建检查、调试和变更验收 |--## 在线资料--- [运行架构](https://codexbar.zabrian.app/architecture)-- [性能报告](https://codexbar.zabrian.app/performance)--## 核心术语--| 术语 | 在本项目中的准确含义 |-| --- | --- |-| snapshot | 可重复读取的当前状态,不代表刚刚发生了一次事件 |-| transition | 由可信 live 输入产生的一次性状态变化,可驱动通知等副作用 |-| bootstrap | 从现有本地数据恢复内存基线,不应补发历史副作用 |-| stale | 有可展示旧值,但本轮未能从来源确认 |-| unavailable | 当前无法得到可信来源,不能等价为空或 `0` |-| generation | 数据源或异步操作的代际,用于拒绝迟到结果 |-| source generation | 某日原始 Hook 文件的来源身份,与代码 schema 不同 |-| owned | CodexBar 已持久化系统睡眠恢复责任 |-| external | 系统状态已经由 CodexBar 之外的来源设置 |--## 主要入口--- App 启动入口:[`CodexBarApp.swift`](../../CodexBar/App/CodexBarApp.swift)-- 服务装配入口:[`CodexBarAppDelegate.swift`](../../CodexBar/Controllers/CodexBarAppDelegate.swift)-- app-server 服务:[`CodexStatusService.swift`](../../CodexBar/Services/CodexStatus/CodexStatusService.swift)-- Hook 子进程入口:[`WorkflowHookEventRecorder.swift`](../../CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift)-- 实时任务状态机:[`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift)-- 自动重置状态机:[`AutoResetController.swift`](../../CodexBar/Services/CodexStatus/AutoResetController.swift)-- 自动重置唤醒同步:[`AutoResetWakeScheduler.swift`](../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift)-- 防睡眠编排:[`KeepAliveController.swift`](../../CodexBar/Services/KeepAlive/KeepAliveController.swift)-- CodexBarHelper:[`main.swift`](../../CodexBarHelper/main.swift)diff --git a/Docs/DeveloperGuide/activity-monitor.md b/Docs/DeveloperGuide/activity-monitor.mddeleted file mode 100644index fb92db1..0000000--- a/Docs/DeveloperGuide/activity-monitor.md+++ /dev/null@@ -1,604 +0,0 @@-# 实时任务监控--简体中文 | [English](../en/DeveloperGuide/activity-monitor.md)--## 目标--实时任务链路需要回答以下问题:--- 当前是否有任务正在运行-- 当前是否在等待用户批准-- 最近任务是完成还是终止-- 哪些运行任务已经长时间没有进展-- 当前轮次及其子 Agent 已产生多少 Token 用量--Hook 事件提供实时进展和中断信号,rollout 文件补充生命周期和轮次 Token 用量。[`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) 合并两者并发布唯一任务快照:--```text-Codex Hook -> WorkflowHookEventRecorder -> Hook JSONL- |-> WorkflowService -> 历史日聚合- |-> HookEventTailReader -----+- |-> CodexActivityMonitor-rollout JSONL -> CodexSessionLifecycleReader ----------------------------+ |- v- CodexActivitySnapshot- |-> 活动卡片和任务中心- |-> 流光和防睡眠-```--`WorkflowHookEventRecorder` 从 `stdin` 提取最小字段,按需有界回查 rollout 元数据,加锁追加事件后退出。历史聚合和实时任务分别读取同一份 Hook JSONL;app-server 额度与用量走独立链路。采集与聚合细节见 [Hook 采集与历史聚合](hook-and-aggregation.md)--通知和触觉反馈消费 monitor 发布的实时转场。流光消费快照与终态展示事件,颜色跟随流光设置:默认等待用户批准为橙色,运行中为青色,完成为绿色,终止为红色。存在等待任务时,活跃状态优先显示等待状态;短暂终态提示可以覆盖活跃状态。--### 两种来源的分工--| 信息 | 优先来源 | 补充来源 |-| --- | --- | --- |-| prompt, tool, compact, subagent 实时进展 | Hook | rollout progress |-| 用户审批候选 | `PermissionRequest` | rollout reviewer 确认 |-| turn 起点 | `UserPromptSubmit` | rollout startedAt 或历史回查 |-| 完成候选 | `Stop` | rollout terminal |-| 明确的 turn 中断 | `Interrupt` | rollout terminal |-| 其他终态确认 | rollout terminal | 无明确终态时保留待确认任务,到期清理 |-| effort | Hook recorder 回查 | rollout lifecycle backfill |--Hook 每轮读取后等待 2 秒,rollout 每轮对账后等待 1 秒。--### 快照与转场--snapshot 可以在 View 重建、新消费者订阅或设置变化时反复读取。transition 只允许 live 数据产生一次。--例如 App 启动时 bootstrap 恢复出一个已经等待批准的任务:--- snapshot 显示它正在等待-- transition 不发布等待事件-- 通知服务因此不会补发一条历史通知--任务完成也一样。通知服务消费 `.completed` transition,不扫描 `recentCompletions`,避免 App 重启或 UI 刷新重复提醒。--## HookEventTailReader--[`HookEventTailReader.swift`](../../CodexBar/Services/Workflow/HookEventTailReader.swift) 是 actor,默认每 2 秒检查 Hook 事件文件。--### Bootstrap--首次启动读取最近 24 小时文件以建立任务基线:--- 每块最多读取 512 KiB-- 最多尝试 3 次获得稳定文件边界-- 使用 inode 和 size 判断读取期间是否发生替换或追加-- bootstrap 结果不会触发历史完成或等待通知--无法得到稳定边界时,reader 清空恢复态,跳到各日期文件末尾,并发布不健康状态。--### bootstrap 是一个逻辑事务--24 小时窗口可能跨两个自然日文件,单个文件又会分成多个 512 KiB batch 发送。--monitor 在 `.bootstrapStart` 时先清空上一次恢复态并暂停副作用,接收所有 `.bootstrapEvents`,最后在 `.bootstrapEnd` 才统一:--- 用 rollout 补齐生命周期-- 应用持久化异常保护记录-- 按当前阈值静默对账-- 定向回查缺失 prompt 起点-- 发布完整 snapshot--中间 batch 只更新内部任务状态。rollout 补齐和异常保护对账要求数据源健康,且系统未处于睡眠。--### 稳定边界重试--reader 在每次尝试开始时固定所有日期文件的 inode 和 size,读取到这些上界后再次验证:--- 历史日期必须 inode 和 size 都不变-- 当前日期允许在固定上界之后继续 append-- 当前自然日不能在读取期间跨过零点--任何条件不成立都从新的基线重试。连续 3 次失败后跳到当前文件末尾,并发布 degraded health,暂停异常会话保护判断。--bootstrap 因目录暂时不存在、不可读或边界不稳定而失败后,reader 最多每 10 秒重新尝试一次。目录恢复后的已有事件通过 bootstrap 静默重放,成功后才恢复正常增量读取。完整坏行导致的历史覆盖缺口不会因普通读取成功而消失,也不会触发无限历史重读。--### 完整行游标--Hook recorder 可能正在写最后一行。reader 只把最后一个 newline 之前的字节计入 `completeOffset`--半行不会丢弃,也不会被当作损坏事件。下一轮从旧 offset 重新读取,等行完整后再提交。未读完固定上界时,屏障返回 `sourceUnavailable`。完整坏行会使对应日期游标降级,不能因跳过坏行而报告健康;该日期退出读取窗口或文件替换重放后重新确定健康状态。--Hook 数据源降级期间仍会为已知任务读取 rollout,但只接受本轮读取成功、线程和轮次匹配的明确完成或中断记录,并静默结束对应任务。该路径不应用普通进展、不回填审批状态、不恢复隐藏任务,也不恢复异常会话保护。系统睡眠和 bootstrap 期间暂停该路径;任务取消或 reader 代次变化后丢弃读取结果。完整生命周期恢复仍要求 Hook 读取屏障成功。--### 跨日与文件替换--reader 为滚动 24 小时覆盖的每个自然日保留独立游标,每轮读取窗口内的全部日期。跨多日恢复会补读中间日期,切日后仍读取前一日的迟到追加。inode 改变或文件缩小时重新 bootstrap,不沿用旧游标。--当 `UserPromptSubmit` 早于当前增量窗口时,reader 可以向前回查最多 8 MiB,为现存任务补齐 prompt 起点。--### drainNow 读取屏障--`drainNow()` 的每个调用方必须等待一轮在本次请求之后开始的读取:--```text-调用 drainNow- -> 记录请求代际- -> 等待下一轮新读取开始- -> 等待该轮读取完成- -> 返回该轮结果-```--调用发生前已经在执行的读取不能满足屏障。reader 被替换、数据源不可用或任务取消时,调用方不能使用旧快照继续判定。--### 屏障的具体代际语义--每次 `drainNow()` 都递增 `requestedDrainGeneration` 并注册独立 waiter。--如果读取已经在途,新请求只把 `hasPendingDrain` 设为 true。当前轮完成后 reader 必须再开始一轮,这轮才会捕获该请求的 generation。--一轮读取可以同时满足在它开始前排队的多个 waiter,但不能满足读取开始后才加入的 waiter。这正是唤醒恢复需要的 happens-after 保证。--actor 在 `await` 期间可以重入,因此 `isProcessingReads` 和 `hasPendingDrain` 共同把所有外部请求收敛成一个串行 drain loop,避免两个读取同时推进 offset。--## Rollout 生命周期读取--[`CodexSessionLifecycleReader.swift`](../../CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift) 读取 `$CODEX_HOME/sessions` 和 `$CODEX_HOME/archived_sessions`--读取规则如下:--- 默认每 1 秒检查一次-- 初始尾部窗口为 512 KiB-- 缺少生命周期或轮次上下文时分轮向前补查,正文读取每轮共享 8 MiB 预算-- 解析线程归属、生命周期、轮次进展、`effort`、`reviewer` 和轮次 Token 用量-- 对话内容不进入活动模型或产品展示--Hook 的 `Stop` 将任务标记为“正在收尾”,保留在活动列表;仍有其他 Agent 等待用户批准时优先显示等待。后续工具、审批等进展继续更新同一任务;rollout 的完成记录确认本轮结束,满足转场时效和恢复条件时发布完成转场。--rollout 暂时不可读或无法关联 session、turn 时,任务继续等待对账。`Stop` 不启动终态超时;新 turn 或 `SessionEnd` 将旧任务移出活动列表,开始前 5 秒的快速终态查询,之后每 30 秒继续查询。迟到的 `Stop` 只更新待确认任务的元数据与进展,不恢复展示或重置窗口。--### 明确中断--`Interrupt` 结束匹配的顶层 turn,清理保护状态和通知,并保存终止记录。运行、等待批准、已隐藏和待确认终态的任务均可匹配;同一 session 的新 turn 保持活跃。身份有歧义时忽略该事件。--同一任务的 Hook 和 rollout 终态共用去重记录,先确认的完成或终止结果保留。终止记录用于展示,不触发完成通知或触觉反馈。--### session 文件如何定位--reader 先检查最可能的少量目录:--1. 任务开始日期对应的 `sessions/YYYY/MM/DD`-2. 当前日期目录-3. `archived_sessions`--resume 可能继续很早以前创建的 session。快速路径找不到时,快速路径每 10 秒允许重试,递归兜底每 60 秒允许重试,避免每秒 poll 都扫描整个 sessions 树,同时允许发现迟到或移动的文件。--文件被移到 archive 后,已缓存 URL 不存在会清除 cursor 并允许重新完整定位。--文件名按线程 ID 精确匹配,允许线程 ID 后带一个下划线和 UUID 后缀。候选文件须唯一,且首条 `session_meta.id` 与目标线程一致;读取元数据时采用与 Hook recorder 相同的[有界首行解析](hook-and-aggregation.md#来源归一化)--### Rollout 读取预算--文件超过 512 KiB 时,初始游标从最后 512 KiB 开始并丢弃第一条可能不完整的行;较小文件从头读取。正向游标持续消费新增内容,反向游标分轮恢复历史。活动任务未确认终态且缺少开始记录、上下文、`effort`、`reviewer` 或启动片段的进展归属时继续补查,直到所需信息齐全、确认终态或到达文件头。启动时跨过的半行后来补齐后,会重新定位并补读该行。--读取成功且线程、轮次匹配时,reader 返回明确终态,不等待用量补齐;子任务终态应用到主任务前还须确认归属。终态后的补查寻找缺失的归属和用量,不因缺少 `effort` 或 `reviewer` 继续扫描;最新用量记录无效时,不使用更早的有效值替代。每个轮次的补充查询累计最多读取 32 MiB 历史正文,Hook 已确认结束后的用量查询也受此限制。活动任务寻找结束记录不受该累计上限限制。--同一文件的查询共用历史游标、解析结果和累计实际读取量。每个补充查询以登记时的累计量为起点,用差值计算已消耗预算,其他查询推动的历史读取也计入差值。查询登记和相关终态按最近查询时间保留 24 小时,重复查询只刷新时间。找到所需信息、到达文件头或耗尽预算后,该查询停止推动补查;到达文件头表示历史已查完,预算耗尽时仍可能有未检查内容。后续新增记录或其他必要查询读到的信息仍可补齐结果。短读、后置检查失败和重试中实际读到的字节均计入预算。游标和预算保存在内存中,文件替换、可检测的截断或 reader 重建后重新建立。--每轮增量扫描与历史补查共享 8 MiB 正文读取预算,多个 session 轮转使用预算;待确认任务每轮最多查询 16 个。正向扫描未追到文件末尾、存在半行或未结束轮次存在覆盖缺口时返回 `incomplete`,读取失败返回 `unavailable`,未找到文件返回 `notFound`。本轮读取成功且已明确匹配的终态返回 `complete`,即使末尾另一条记录尚未写完;Token 用量仍要求尾部完整。轮次状态为 `complete` 且具有 turn 上下文时,`lifecycleCoverageCheckedAt` 记录本次检查时间;读取未完成、失败、文件不存在或缺少上下文时将其清空。常规异常静默判定要求该时间存在且距当前不足 5 秒。--增量扫描按实际读取字节推进 offset,并跨轮拼接未结束的行。单行最多缓冲 16 MiB;超过缓冲上限时标记读取缺口并分块跳到换行,后续记录继续消费。明确的 rollout 终态不受此前读取缺口影响。--文件可读且已经追到实际末尾,仅剩有界残缺末行时,reader 记录首次观察或最近一次追加的时间。任务已有 turn 上下文、没有其他覆盖缺口或已知终态,且本次观察距当前不足 5 秒时,可以使用残缺末行兜底:任务最后进展和末行最后增长均达到用户设置的静默阈值后,允许隐藏任务。末行继续增长会重新计时;读取失败、文件替换或截断、App 重启后重新开始观察。积压未读完、缺少上下文和超限丢弃中的行不能使用此兜底。--残缺末行始终返回 `incomplete`,观察结果用于保护计时、调度和隐藏前复核,不作为终态或进展,也不直接触发任务恢复。后续补完记录后,按正常完整读取流程处理进展和终态。--rollout 坏行将当时尚未结束的 turn 标记为有覆盖缺口,后续重复的同一 turn 上下文不能清除此标记。新的 turn 独立建立覆盖,身份明确的完成或中断记录可以结束有缺口的任务;后续坏行不会撤销已经读到的明确终态。读取失败或尚未读完时,缓存进展不推进任务的执行时间,也不能恢复隐藏任务或清除保护记录。--坏行出现时尚未定位的旧轮次,在历史补查中按文件位置继承覆盖缺口;坏行后带有明确 turn ID 的进展或重复上下文不能消除缺口。坏行之后开始的新轮次独立判断覆盖。历史补查发现的终态更新任务记录和去重状态,但不补发通知或终态展示事件。--### Rollout 进展的 turn 归属--每个 session 的文件游标保存独立的 `currentTurnID`,按 JSONL 文件顺序更新:--- 外层 `type = "turn_context"`,或外层 `type = "event_msg"` 且 `payload.type` 为 `task_started` 或 `turn_started` 时,以 `payload.turn_id` 建立上下文-- `response_item` 优先使用 `payload.internal_chat_message_metadata_passthrough.turn_id`;其他进展记录使用 `payload.turn_id`,缺失时沿用游标上下文-- 当前 turn 的 `task_complete`、`turn_complete` 或 `turn_aborted` 清空上下文;迟到的其他 turn 终态不清空它-- 检测到文件标识变化或文件大小小于正向读取位置时重建游标,同时清空上下文、生命周期缓存和补查预算--进展记录包括外层 `type` 为 `response_item` 或 `token_usage_record` 的记录,以及外层为 `event_msg`、`payload.type` 为 `token_count`、`item_completed`、`agent_message`、`agent_reasoning`、`task_started`、`turn_started`、`task_complete`、`turn_complete` 或 `turn_aborted` 的记录。时间依次取外层 `timestamp`、`payload.completed_at`、`payload.started_at`。--记录须有可用时间和 turn 归属,本轮读取完整且时间晚于任务的 `lastProgressAt` 时才更新进展。`token_usage_record` 按活动记录处理,不比较 token 数量是否增加。启动片段中缺少显式 turn 和上下文的进展只暂存时间,补查恢复可靠归属后再合并;无法确定归属的进展不计入任务。正向暂存和反向补查都按轮次匹配结束记录,迟到的其他轮次终态不能截断当前轮次进展,当前轮次自身结束后的无归属进展也不能回填给它。--能用于推断审批恢复的执行进展单独记录为 `lastExecutionProgressAt`:包括 `response_item` 中 `role = "assistant"` 的记录及类型为 `function_call_output`、`custom_tool_call_output`、`tool_search_output` 的工具结果,以及 `agent_message`、`agent_reasoning` 事件。只有同一 Agent/轮次中晚于审批请求的执行进展才清除该等待;用量记录等普通活动只更新任务进展时间。--### Rollout 解析字段--共享的 `CodexRolloutLineEnvelope` 只提取 turn context, lifecycle 和 progress 所需字段。prompt, response 和 tool 内容不会进入活动模型。--终态要求 `payload.turn_id` 非空,并且本轮读取状态为 `complete`。外层 `type = "event_msg"` 时,`payload.type` 为 `task_complete` 或 `turn_complete` 确认完成,完成时间优先使用有效的 `payload.completed_at`(Unix 秒),缺失或无效时使用外层 `timestamp`;两者均不可用时不确认完成。`payload.type = "turn_aborted"` 确认中断。非负且有限的 `payload.duration_ms` 换算为秒后用于耗时展示;中断时间缺失时,活动任务使用对账时间,待确认任务使用移出活动列表的时间,结果均不早于任务最后活动时间。--## 本轮 Token 用量--`CodexSessionLifecycleReader` 从外层 `type == token_usage_record` 的记录读取 `payload.turn_token_usage`。使用线程轮次累计值,不累加每条累计快照;`event_msg/token_count` 只提供进展信号,不作为本轮用量来源。--| 展示指标 | `turn_token_usage` 字段或计算方式 |-| --- | --- |-| 总量 | `total_tokens`,等于输入加输出 |-| 输入 | `input_tokens`,包含缓存命中和写入 |-| 输出 | `output_tokens`,包含推理输出 |-| 缓存命中 | `cached_input_tokens` |-| 缓存写入 | `cache_write_input_tokens` |-| 缓存命中率 | `cached_input_tokens / input_tokens`,输入为零时不可计算 |-| 推理输出 | `reasoning_output_tokens` |--所需的 Token 计数均需存在且非负,总量必须等于输入加输出,缓存命中加写入不能超过输入,推理不能超过输出。解析同时校验 `thread_id`、`session_id`、`turn_id`、`root_turn_id` 和 `response_id` 的归属与有效性;字段缺失或校验失败时不生成用量。有效记录中的缓存写入或推理输出为零时直接展示零值。--`CodexActivityTokenUsage.swift` 按根任务收集主线程及已关联子线程的轮次引用,并按线程、轮次去重。运行中汇总本次读取完整且归属匹配的线程,尚未有用量的线程等待后续刷新;显示值因此可以是已知线程的小计。实时卡片使用内存任务快照,不读取历史日汇总或 iCloud 缓存。--完成和终止记录创建时用量为空,由结束后补读填入。补读从登记查询时起最多持续 30 秒,每 2 秒安排一次,每批最多处理 16 个待补读任务。最终汇总要求已知子 Agent 身份齐全、各线程用量可用,且子线程已结束。取得用量后,在期限内继续接受更新;读取不完整时保留已有值。到期移除查询,未取得用量的记录保持为空。迟到的子线程关联只加入所属根轮次,不影响后续轮次。结束状态、通知和防睡眠释放不等待 Token 补读。--历史回放使用独立的账本与读取游标,见 [Rollout Token 历史](sync.md#rollout-token-历史)--## 任务身份--任务 key 按可用信息选择最精确身份:--1. `session ID + turn ID`-2. `session ID`-3. 匿名 project key--新的 prompt 会替代同一 session 的旧 turn。旧 turn 在后台等待明确终态,前 5 秒快速查询,之后每 30 秒补查,最长保留到移出活动列表后的 24 小时。--subagent 事件更新父任务的 subagent 活动,不创建独立顶层任务卡片。--### 身份精度与回退--`session ID + turn ID` 能精确区分同一 session 中顺序执行的 turn,是首选身份。--某些事件只有 session ID。后续顶层 Hook 匹配到该任务并提供 turn ID 时,任务在内存中补充 `associatedTurnId` 和终态别名,用于 rollout 查询与去重;初始 key 和保护哈希保持不变。--终态匹配先检查精确 key 及别名,再按 session 检查待确认任务。待确认候选唯一时使用该任务,多个时返回 `ambiguous`;没有待确认候选时再检查活动任务。候选须满足 Hook 时间顺序及 turn 身份条件。--完全没有 session ID 时只能使用 project key。这个 key 可能把同项目并发匿名任务合并,所以匿名任务只承担可撤销的 UI 展示,不驱动通知、防睡眠或持久化保护。--### 实时任务来源过滤--`CodexActivityMonitor.apply` 先解析实时链路的有效来源,再执行任务状态转换。沿用缓存来源时,事件副本使用该来源进行过滤和执行身份判断,原始 JSONL 保持不变。来源归一化规则见 [Hook 来源归一化](hook-and-aggregation.md#来源归一化)--monitor 按精确的 `session ID + turn ID` 在内存中保存来源,保留 24 小时。Codex 的 subagent Hook 复用父 session ID,因此来源判定不扩大到整个 session。--| 事件来源 | 实时处理 |-| --- | --- |-| `main`、`auxiliary` | 记录明确来源,并按正常状态机处理 |-| `autoReview` | 忽略事件,清理同 key 的活动任务、待确认终态、展示记录和异常保护;保留来源记忆 |-| `unknown`,同 key 有有效的 `main` 或 `auxiliary` 来源 | 沿用已确认来源,继续处理事件 |-| `unknown`,没有有效的正常来源记忆 | 忽略事件 |--缺少 session ID 或 turn ID 时不保存来源记忆,`unknown` 和 `autoReview` 事件直接忽略。来源已确认的任务不会因一次 rollout 读取失败被移除;迟到事件仍须通过状态机的时间和终态去重检查。--这些规则同时用于 bootstrap 和实时读取。其他 subagent(包括 Memories)归类为 `auxiliary`,按辅助任务规则关联。历史聚合仍消费全部原始事件,来源记忆不持久化或上传。--### 新 prompt 与终态确认--新 prompt 到来时,同一 session 的旧 turn 移到 `pendingTerminalTasks`,等待 rollout 确认结果:--- 从 active snapshot 立即移除-- 保留原任务元数据和开始时间-- 前 5 秒快速查询 rollout terminal,随后每 30 秒补查-- terminal 到达时准确分类 completed 或 aborted-- 24 小时后仍无终态则清理,不生成完成、终止、通知或流光提示--`SessionEnd` 使用同一个终态确认窗口,只是按 session 一次移动所有不晚于该事件的任务。--### 迟到事件如何被拒绝--Hook 顺序按 Agent/轮次隔离,任务整体进展另行汇总:--| 字段 | 来源与用途 |-| --- | --- |-| execution 的 `lastHookEventAt` | 同一 Agent/轮次已接受的最新 Hook 时间,用于拒绝该执行的迟到状态变化 |-| `lastMainHookEventAt` | 主 Agent 的最新 Hook 时间,用于顶层 prompt、中断及会话结束判断 |-| execution 的 `lastExecutionProgressAt` | 同一执行的 Hook 恢复信号与 rollout 执行进展时间,用于审批恢复和迟到审批过滤 |-| `lastProgressAt` | Hook 与 rollout 的最新进展时间,用于异常会话保护 |-| `lastActivityAt` | 由 `lastProgressAt` 派生,用于展示排序、保留期和终态时间校正 |--rollout 进展不会推进 Hook 时钟,其他 Agent 的较晚事件也不阻止本 Agent 的合法事件。审批请求还须不早于同一执行已知的执行进展,并晚于上次审批请求;任务的 `lastProgressAt` 和 `lastActivityAt` 保持单调递增。--完成和终止共用内存中的 `recentlyEndedTaskAt` 记录结束时间。展示记录仍分别保存在完成和终止列表,保留 10 分钟;去重记忆保留 24 小时,不随展示记录一起删除。来源过滤移除记录时,从剩余终态记忆重新计算对应 session 别名的最新时间。--迟到事件按以下规则处理:--- 工具、压缩、子 Agent 和审批 Hook 按执行归属检查时间;已确认终态的执行不接受新的状态变化-- 精确 turn 在终态记忆保留期间不允许重新创建;session 和匿名键只允许时间更新的新 prompt 复用-- `Stop` 命中多个候选时不猜测-- 已进入 terminal 去重记忆的 key 会清除异常顺序留下的恢复任务--这种比较依赖事件自身时间,而不是 batch 到达顺序,因为跨进程文件写入和 rollout poll 都可能让旧事件晚到。--### 匿名任务--`WorkflowHookEvent.sessionId` 缺失时,task key 使用匿名 project key。`isAnonymous` 会保留到 `CodexActivityTaskSnapshot`, `CodexActivityCompletion` 和 `CodexActivityTermination`--匿名任务仍进入活动快照和最近终态记录。活动卡片与任务中心统一显示橙色 `person.crop.circle.dashed` 图标,help 为 `匿名任务不参与防睡眠`。活动卡片的 `+N` 只表示其他活跃任务总数。--匿名运行任务不展示精确运行时长,匿名完成和终止记录也不包含精确耗时。--匿名任务不向通知消费者发布等待批准或完成 transition、不触发任务触觉反馈、不进入 KeepAlive 的运行中或等待任务集合、不参与异常会话保护。`activityProtectionIdentifier` 对匿名 key 返回 nil,保护状态文件不会保存匿名任务记录。--## 状态机--内部活动任务主要有以下状态:--| 状态 | 含义 |-| --- | --- |-| `running` | Codex 正在处理当前 turn |-| `waitingApproval` | 任务内至少一个主 Agent 或子 Agent 的执行正在等待用户批准 |-| `suppressed` | 任务被异常会话保护隐藏,等待新进展恢复 |--`PermissionRequest` 只有在 reviewer 是用户时才进入 `waitingApproval`。自动审批或策略审批不会被视为用户等待。--任务结束按以下信号处理:--- `Stop` 将任务标记为正在收尾,继续保留在活动列表-- `Interrupt` 将匹配的 turn 记录为终止-- rollout terminal 确认完成或终止-- 新 turn 或 `SessionEnd` 将旧任务移出活动列表并后台补查;没有明确终态就保持未确认,到期只清理--### 事件到状态的主要转换--| 当前状态 | 输入 | 新状态 | 额外动作 |-| --- | --- | --- | --- |-| 不存在 | `UserPromptSubmit` | running | 保存可信 startedAt |-| 不存在 | 顶层 tool 或 compact | running | 恢复任务,startedAt 暂缺 |-| running | tool, compact, subagent progress | running | 更新 last progress 和 generation |-| running | `PermissionRequest` + reviewer user | waitingApproval | 发布 live waiting transition |-| waitingApproval | 审批所属 Agent/轮次的有效 Hook 或 rollout 执行进展 | waitingApproval 或 running | 清除该执行的审批;仍有其他等待时保持等待 |-| waitingApproval | 其他 Agent 的进展 | waitingApproval | 更新进展,保留等待及其工具展示 |-| running 或 waiting | 顶层 `Stop` | running 或 waitingApproval | 清除主执行等待;仍有子 Agent 等待时继续显示等待,否则显示正在收尾 |-| active | 新 prompt 或 `SessionEnd` | pending terminal | 从快照移除并开始后台终态查询 |-| active、suppressed 或 pending terminal | `Interrupt` | terminated | 移除匹配任务、记录终止并清理保护状态和通知 |-| running | 满足保护条件且静默达到阈值 | suppressed | 隐藏并退出防睡眠贡献 |-| suppressed | 有效的工具、压缩、子任务或 `Stop` Hook,或健康对账读到新进展 | running | 清除持久化保护与旧通知 |-| active、suppressed 或 pending terminal | 完整读取的匹配 rollout terminal | completed 或 terminated | 记录明确终态并清理任务,降级期间静默处理 |--### 等待批准的两阶段确认--任务按 Agent/轮次保存执行记录,主 Agent 使用无 `agentId` 的明确主来源身份,子 Agent 使用自身线程 ID。每个执行独立保存 `approvalReviewer`,来源为 Hook 或 rollout 的 `payload.approvals_reviewer`,取值为 `user`、`auto_review` 或 `guardian_subagent`--每个执行只有一份可选审批记录:`pending` 表示路由待确认,`waiting` 表示等待用户。收到 `PermissionRequest` 后,已知 reviewer 为 `user` 时立即确认等待,未知时保留候选;确认为自动审批时清除候选。请求时间、工具名和顺序随审批记录保存,重复请求不覆盖正在等待的展示信息。--只有身份可靠且属于同一 Agent/轮次的进展才能清除该执行的审批。有效的工具、压缩、子 Agent 生命周期或顶层 `Stop` Hook 按现有恢复规则处理;rollout 执行进展须严格晚于请求时间。已清除的候选不会因后续 reviewer 回填重新进入等待,子线程的明确 rollout 终态也会清除对应执行的等待。--任务中仍有任意用户等待时保持 `waitingApproval`,展示请求时间最早的等待;同时间按记录顺序选择。等待持续期间切换展示对象不重置任务的等待起点。其他 Agent 的进展和身份不完整的进展不解除已知等待。同一 Agent/轮次内的并行调用仍共享审批记录,恢复依据是进展推断。--### Effort 合并--同一 turn 的多个上下文事件可能报告不同 reasoning effort。Task 不让最后一条静默覆盖前一条,而是在观察到冲突后标记为 `mixed`--### Subagent 计数可靠性--子 Agent Hook 的 `agent_id` 和 `turn_id` 标识子线程及其轮次。monitor 读取相关子线程 rollout,使用 `session_meta.id` 校验线程,使用 `parent_thread_id`(缺失时取 `source.subagent.thread_spawn.parent_thread_id`)校验父线程信息,并通过上下文或开始事件中的 `root_turn_id` 关联根任务轮次。`root_turn_id` 指向根轮次,不是直接父 Agent 的轮次。--根会话 ID 优先取 `session_meta.session_id`,缺失时使用已有关联或该子轮次 Hook 中唯一的根会话 ID。关联前暂存身份完整的子事件,确认后按原始来源重放;字段不足或关联冲突时不回退到当前唯一活动任务。子 Agent 活动只更新匹配的活动根任务,不创建独立卡片。--活跃子 Agent 数按已关联的 `SubagentStart` 和 `SubagentStop` 维护,与审批记录分开。计数可靠性由是否已知 prompt 起点初始化;首次观察某个 Agent 就收到 stop 时设为 `false`,UI 隐藏数量。每个 Agent 按自己的事件时间更新运行状态,已确认结束的执行不会被迟到的 start 计为运行。--## 快照优先级--活动卡片的 `primaryActivity` 按以下优先级选择内容:--```text-等待批准 > 运行中 > 最新的完成或终止 > 空闲-```--`latestTerminalEvent` 按结束时间选择最新的完成或终止,时间相同优先终止。活动卡片、菜单栏和空闲时的任务流光共用该结果。菜单栏在 `primaryActivity` 的基础上限制终态显示到结束时间后 10 秒。任务中心的终态记录保留 10 分钟,terminal 去重记忆保留 24 小时。--快照由以下模块消费:--- 菜单栏人物图标-- 主面板任务卡片-- 活动中心-- 任务流光-- 通知系统-- 防睡眠控制器--### 快照发布--monitor 每秒检查 rollout,并在清理 deadline 到达时刷新。--新快照先与当前值比较,只有结构变化才发布。运行时长文案由 View 使用当前时间格式化,不要求每秒修改任务对象。--### 展示更新--`presentationPublisher` 发布当前快照和本轮仍有效的 `terminalEvents`,供任务流光使用。展示事件包含匿名任务;通知使用独立的 `transitionPublisher`--完成转场和终态短提示要求结束时间距当前不超过 10 秒,并且不早于各自的恢复界限。Hook 直接确认或 rollout 补齐 reviewer 后确认的等待转场,均要求任务进入等待的时间距当前不超过 10 秒且不早于 `sessionTransitionNotBefore`。--历史重读、睡眠恢复和数据源健康状态变化时清空待发布事件,并更新 `terminalPresentationNotBefore`。bootstrap、恢复对账和数据源不健康期间暂停发布。--### 稳定排序--同一 batch 中多个任务可能具有相同时间戳,仅按时间比较无法确定它们之间的顺序。--所有列表先按最近时间降序,时间相同再按 display UUID 字符串排序。稳定顺序让 SwiftUI diff 不会因为等价任务随机交换位置而产生跳动。--### 清理采用最近 deadline--monitor 管理待确认任务、活动任务、历史记录、终态去重和保护记录的过期时间。菜单栏终态提示和任务流光分别由 `StatusItemController`、`TaskGlowController` 管理到期时间。提示到期不重新发布活动快照。--清理任务只等待最近的未来 deadline,到点处理后安排下一次。--## 系统睡眠与唤醒--系统即将睡眠时暂停异常会话保护判断。唤醒后的完整恢复顺序为:--1. 进入恢复状态并继续暂停保护-2. 等待 `HookEventTailReader.drainNow()` 成功-3. 重置 rollout 生命周期解析的 fallback-4. 使用新 Hook 结果和 rollout 结果统一对账-5. 恢复异常会话保护判断--Hook 屏障返回 `sourceUnavailable` 时,仅为已知任务对账明确终态,保持静默并继续暂停保护,后续轮询重试完整恢复。reader 被更换或任务取消时丢弃该轮结果。--### 系统睡眠期间暂停判定--系统睡眠期间不进行异常静默判定。恢复后,monitor 根据新读取的 Hook 与 rollout 进展静默对账,再恢复正常判定。--检查任务使用 `SuspendingClock` 等待,但静默时长仍按 `Date` 与 `lastProgressAt` 的差值计算,不扣除系统睡眠经过的时间。will-sleep 进入 recovery,did-wake 通过新的数据读取屏障后重新判定。--### 唤醒恢复的关联与代次--完整恢复先消费 Hook,以建立睡眠期间产生的任务身份,再合并 rollout 的生命周期和进展,最后恢复保护判断。降级终态对账仅处理已有任务。--bootstrap 等待 rollout 期间如果恢复代次改变,会丢弃旧生命周期结果;结束 bootstrap 后重新进入读取屏障,不能直接结束较新的恢复。--`tailReaderGeneration` 防止唤醒 Task 返回时 reader 已因 Hook 设置变化被替换。`activityProtectionRecoveryGeneration` 防止两次睡眠或设置变化交错后,较早恢复流程提前解除暂停。--## 异常会话保护--异常会话保护只在防睡眠主开关开启时工作,只处理非匿名 `running` 任务。--等待批准任务不参与静默阈值判断。原因是等待批准本身就是一个合法的无进展状态。--可选阈值为:--- 30 分钟-- 1 小时(默认值)-- 2 小时-- 4 小时--任务达到阈值后:--1. 先更新内存保护记录并加入串行持久化队列-2. 同时启动通知提交和 3 秒 grace-3. 通知提交完成或 grace 到期后再次校验候选-4. 候选仍有效时从活动快照隐藏任务-5. 如果期间或之后出现新进展,清除保护并恢复展示--隐藏任务不依赖通知成功。3 秒只是等待解释性通知提交的最大时间,到期后仍会释放防睡眠。--保护判断在以下阶段暂停:--- Hook bootstrap-- 系统睡眠-- 唤醒恢复-- Hook 数据源不可用-- reader 正在更换-- 当前任务的 rollout 未读全且不满足残缺末行兜底条件、读取失败、上下文缺失或读取结果过期--### progress generation 的作用--只比较时间戳不足以保护异步尝试。两条进展可能具有相同秒级时间,设置阈值也可能在通知提交期间变化。--每次有效进展都会递增 `progressGeneration`。保护候选保存:--- task display ID-- last progress timestamp-- progress generation-- 当时的阈值--通知返回或 3 秒 grace 到期时,上述条件都必须仍匹配才允许 suppress。任意新进展或阈值变化都会让旧尝试失效。--使用残缺末行兜底的候选还要复核末行观察的新鲜度和静默期限。末行继续增长或读取失败时取消尚未完成的隐藏尝试。--### 保护记录的保存顺序--候选开始时同步更新内存记录,再由 Task 按顺序调用 `ActivityProtectionStateStore.apply`。磁盘写入失败会记录日志,不阻止任务隐藏。--已保存的记录用于下次 bootstrap 恢复保护状态。隐藏动作不等待磁盘提交,因此跨重启恢复取决于记录是否成功写入。--### 阈值改变如何对账--阈值变短时,已经超过新阈值的 running 任务会立即重新判定。--阈值变长时,未超过新阈值的 suppressed 任务会静默恢复,并清除保护记录和通知;仍超过阈值的任务继续隐藏。--恢复与隐藏共用保护计时起点:取任务最后进展与已保留的残缺末行最后增长观察时间中的较晚者。调大阈值后的恢复不要求读取结果仍在 5 秒有效期内;再次隐藏仍须取得新鲜读取依据并达到新期限。--关闭防睡眠主开关会停用异常保护,并恢复当前进程内所有 suppressed 任务。--## 保护状态持久化--[`ActivityProtectionStateStore.swift`](../../CodexBar/Services/Workflow/ActivityProtectionStateStore.swift) 保存到:--```text-~/Library/Application Support/CodexBar/ActivityProtection/state.json-```--- 当前 schema 为 `1`-- 只保存哈希任务身份和时间戳-- 文件权限为 `0600`-- Debug 与 Release 通过 `flock` 共用文件-- 记录最长保留到最后进展后的 24 小时--任务身份使用 SHA-256 摘要,不把 session ID 或 turn ID 原文写入该状态文件。匿名任务没有保护标识,不写入该文件。--### 哈希身份的构造--turn 和 session key 先使用带类型前缀与 NUL 分隔的 canonical 字符串,再加固定 domain separator `CodexBar.ActivityProtection.v1` 执行 SHA-256。--类型和分隔符避免不同字段拼接后产生边界歧义。domain separator 避免同一原始 ID 在其他用途中的 hash 被直接关联。--### 跨进程状态合并--两个 App bundle ID 可以同时运行,但都观察同一份 Codex Hook 数据。如果各自保存独立保护状态,一个版本隐藏的异常任务可能被另一个版本重新用于防睡眠。--状态 store 使用 actor 串行单进程访问,再用 `flock` 保护跨进程 read-modify-write。removal 还可以附带 `matchingMarkedAt`,防止旧进程的迟到删除误删另一进程刚写入的新记录。--写入按 task identifier 稳定排序并原子替换,文件权限最终校正为 `0600`--## 代际和旧结果隔离--Monitor 为 reader 和异步恢复任务维护 generation:--- reader 更换后丢弃旧 reader 的迟到结果-- bootstrap 未完成时不发布转场副作用-- 取消的 drain 不满足恢复屏障-- 数据源显式不健康时不沿用最后健康快照做静默判断--### monitor 中的主要 generation--| generation | 保护的异步路径 |-| --- | --- |-| `tailReaderGeneration` | reader batch, rollout poll 和 prompt backfill |-| `bootstrapCompletionGeneration` | bootstrap 的异步 lifecycle 补齐,以及跨 bootstrap 的 rollout 对账结果 |-| `activityProtectionRecoveryGeneration` | 睡眠、唤醒恢复流程,以及跨恢复批次的 rollout 对账结果 |-| task `progressGeneration` | 通知宽限期间的保护候选 |--任务进展只使对应的保护尝试失效;reader、bootstrap 和恢复代次分别隔离各自的异步结果。--## 建议验证的故障场景--- Stop handler 要求继续后完成或中断,确认没有提前完成提醒-- Stop handler 执行期间中断,只产生一条终止记录和红色提示-- rollout 不可读超过 5 秒仍不判定完成,恢复后只确认一次-- Stop 后继续请求用户批准,等待状态和中断清理正常-- 中断运行、等待批准和隐藏任务,确认状态、耗时、保护清理且无完成通知-- Hook 与 rollout 终止以两种顺序到达,确认单条记录和单次提示-- 新 turn 开始后收到旧 turn 中断,新任务保持活跃-- 重复 Interrupt 和迟到工具或 prompt 事件不能恢复已结束的 turn-- App 在任务已运行时启动,bootstrap 展示任务但不补发通知-- bootstrap 文件持续追加时能重试并最终获得稳定边界-- 连续 3 次不稳定后进入 degraded,不启动异常静默判断-- 新 prompt 替换旧 turn,分别验证终态在前 5 秒及之后到达时的补分类-- 同 session 多个 terminal 候选时不猜测 `Stop` 归属-- 主 Agent 与多个子 Agent 同时等待,逐个恢复时只清除自己的等待,最后一项清除后才切回运行-- 普通 rollout 活动保持等待;同一执行的较新执行进展清除等待,同时间进展保持等待,迟到审批或 reviewer 回填不恢复已清除的等待-- 子线程 `root_turn_id` 指向旧轮次时不更新新任务;关联缺失或冲突时不猜测父任务-- 新 turn 边界后无 `turn_id` 的记录只推进新任务;迟到旧终态、分批读取和文件替换不串用上下文-- reviewer 缺失后由 rollout 确认为 user 才进入等待-- auto review 始终不发布等待 transition-- 子任务计数可靠性为 `false` 时 UI 隐藏数量-- reader 进行中调用 `drainNow()` 必须再执行一轮新读取-- 唤醒 drain 失败时保护继续暂停;Hook 坏行期间明确 rollout 终态静默结束已知任务,普通进展不恢复隐藏任务-- 静默候选在 3 秒窗口内出现进展后不隐藏,迟到通知被撤回-- 阈值调长后未超新阈值的 suppressed 任务恢复-- Debug 与 Release 并发更新保护记录时新记录不被旧 removal 删除-- 匿名任务始终不进入 transition、KeepAlive 和保护状态文件--## 关键源码--- [`CodexActivityTokenUsage.swift`](../../CodexBar/Services/Workflow/CodexActivityTokenUsage.swift)-- [`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift)-- [`CodexActivityTask.swift`](../../CodexBar/Services/Workflow/CodexActivityTask.swift)-- [`CodexActivitySubagentTracking.swift`](../../CodexBar/Services/Workflow/CodexActivitySubagentTracking.swift)-- [`CodexActivityTerminalResolution.swift`](../../CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift)-- [`HookEventTailReader.swift`](../../CodexBar/Services/Workflow/HookEventTailReader.swift)-- [`CodexSessionLifecycleReader.swift`](../../CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift)-- [`CodexActivityProtection.swift`](../../CodexBar/Services/Workflow/CodexActivityProtection.swift)-- [`ActivityProtectionStateStore.swift`](../../CodexBar/Services/Workflow/ActivityProtectionStateStore.swift)diff --git a/Docs/DeveloperGuide/app-server.md b/Docs/DeveloperGuide/app-server.mddeleted file mode 100644index d3292e9..0000000--- a/Docs/DeveloperGuide/app-server.md+++ /dev/null@@ -1,485 +0,0 @@-# app-server 数据链路--简体中文 | [English](../en/DeveloperGuide/app-server.md)--## 职责--app-server 链路负责读取 Codex 账户和服务端状态:--- 当前账户和套餐-- Codex 返回的额度分组和窗口-- token 用量与用量历史-- Reset Credits 状态-- Hook 功能开关、handler 列表和配置写入能力--这条链路不负责 Hook 历史统计,也不负责实时任务状态。--### 输入与输出边界--```text-CodexCLIResolver- -> AppServerCommand- -> CodexStatusService actor- -> AppServerSession- -> Process + stdin/stdout/stderr- -> CodexQuotaSnapshot- -> CodexStatusViewModel- -> 菜单栏与主面板-```--`CodexStatusService` 拥有连接和同账户缓存。`CodexStatusViewModel` 只拥有 UI 级加载状态、自动刷新节奏和最后一次连接信息。--设置页复用该 session 读写 Hook 与 TUI 配置。--## Codex CLI 定位--[`CodexCLIResolver.swift`](../../CodexBar/Services/CodexCLI/CodexCLIResolver.swift) 从进程 `PATH` 查找全局 `codex`,并检查 App 的资源目录:--```text-/Applications/ChatGPT.app/Contents/Resources-```--先读取资源目录下的 `codex-cli/codex-package.json`,将 `entrypoint` 相对于 `codex-cli` 目录解析为可执行文件路径。清单无法解析或入口不可执行时,检查资源目录下的 `codex`。--菜单栏 App 从 Finder 启动时可能没有交互式 shell 的完整 `PATH`,因此 resolver 还会补充常见安装目录:--```text-/opt/homebrew/bin-/usr/local/bin-~/.npm-global/bin-~/.local/bin-~/.volta/bin-/usr/bin-/bin-/usr/sbin-/sbin-```--数据目录优先使用 `CODEX_HOME`,未设置时使用真实用户主目录下的 `~/.codex`--### 进程环境归一化--从 Finder 或登录项启动的 `LSUIElement` App 通常没有用户交互式 shell 注入的完整 `PATH`。如果只调用 `/usr/bin/env codex`,Homebrew, Volta 或 npm 全局安装会在 Terminal 中可用,在 CodexBar 中却不可见。--resolver 按以下步骤归一化进程环境:--1. 使用 `getpwuid(getuid())` 解析真实登录用户主目录,避免继承 Xcode 或容器环境的错误 `HOME`-2. 保留现有 `PATH`,再按顺序补充常见目录并去重-3. 对候选路径解析 symlink 和 standardized URL,避免同一内置 binary 同时被识别成 global 与 bundled--`CodexCLISourceSelection.automatic` 优先使用全局 CLI,找不到时使用 App 内置 CLI。手动选择 `global` 或 `bundled` 后只使用指定来源,缺失时返回 `sourceUnavailable`。来源选择由 `CodexStatusService` 保存,重建连接时沿用。--### 磁盘版本与运行版本--设置页可以读取磁盘上两个候选 CLI 的版本,但全局和 Hook 最低版本检查只使用 `initialize` 返回的 app-server `userAgent`--原因是连接最长复用 1 小时。用户在连接存活期间升级磁盘 binary 后,当前进程仍然是旧版本。用磁盘版本判断会让 UI 声称能力可用,实际调用的旧 app-server 却不支持对应方法。--## App 内代理--代理由以下类型协作完成:--| 类型 | 职责 |-| --- | --- |-| [`CodexProxyConfiguration`](../../CodexBar/Models/CodexProxyConfiguration.swift) | HTTP/HTTPS 配置、输入校验和子进程环境变量 |-| [`CodexProxyStore`](../../CodexBar/Services/Settings/CodexProxyStore.swift) | 在 UserDefaults 的 `CodexProxy.configuration` 中保存配置和密码 |-| [`CodexProxySettings`](../../CodexBar/Services/Settings/CodexProxySettings.swift) | 已保存配置、编辑草稿、开关提交和测试状态 |-| [`CodexProxyConnectionTester`](../../CodexBar/Services/CodexStatus/CodexProxyConnectionTester.swift) | 使用草稿启动独立测试进程 |--未配置或未启用时,正式连接沿用 `CodexCLIResolver.environment`。启用后写入 `HTTP_PROXY`、`HTTPS_PROXY`、`ALL_PROXY`、`WS_PROXY`、`WSS_PROXY` 及其小写形式,`NO_PROXY` 和 `no_proxy` 设为 `localhost,127.0.0.1,::1`。只有自定义代理进程追加 `-c features.respect_system_proxy=false`,配置不写入 Codex 全局文件。--读取存储时保留可解码的原始输入。启用代理和保存编辑表单时校验地址、端口和认证用户名;停用时允许保存无效字段。无法解码的记录仍保留清除入口。--开关在创建异步任务前更新显示状态并设置 `isSaving`,处理期间重复切换被忽略。`CodexStatusService.applyProxy` 串行保存设置、关闭旧连接并清空补充缓存,完成后恢复交互并触发刷新;失败时恢复原开关状态。配置对话框使用独立草稿,只有保存或清除才提交。--### 连接测试--测试将草稿临时视为启用,解析所选 Codex 来源,并通过 `AppServerSession.initializeAccount()` 执行与正式连接相同的握手和账户检查,随后调用 `account/rateLimits/read`。正式连接在握手之后继续读取额度和用量。--测试请求共享 8 秒截止时间,不重试服务端业务错误,不记录交互日志。退出时关闭临时进程;进程清理仍使用 session 的关闭等待预算。编辑字段、取消测试或关闭窗口会取消外层任务和 worker,已取消任务返回的结果不会更新 UI。--## 进程与协议--CodexBar 启动以下命令并通过 stdio 通信:--```bash-codex app-server --listen stdio://-```--协议是逐行 JSON-RPC。建立连接后先发送 `initialize`,再发送 `initialized`,然后读取账户:--```text-启动子进程- -> initialize(clientInfo)- -> 校验实际版本 >= 0.145.0- -> initialized- -> account/read- -> account/rateLimits/read- -> account/usage/read-```--stdout 可能包含非 JSON 输出。pipe reader 会持续读取完整行,只把能够解码且 response id 匹配的消息交给等待中的请求。stderr 独立排空,防止子进程因管道写满而阻塞。--### 一次建连的完整事务--```text-解析 executable- -> 创建 stdin/stdout/stderr pipe- -> 启动 Process- -> initialize(clientInfo)- -> 从 userAgent 保存实际版本- -> 校验实际版本 >= 0.145.0- -> initialized notification- -> account/read(refreshToken: false)- -> account 存在: 提交 connection- -> account 缺失: 关闭进程并返回 notLoggedIn-```--只有实际版本满足全局门槛,并且 handshake 与首次账户读取都成功,connection 才进入 service 状态。明确低于 `0.145.0` 时返回版本不支持;版本缺失或无法解析时返回无效响应,不能作为 Hook 自动清理的低版本依据。两种情况都会关闭半初始化 session,不继续发送账户请求。--### Stdout 分行与响应匹配--app-server 的 framing 是一行一个 JSON message。pipe 回调收到的 `Data` 块可能:--- 只包含半行-- 同时包含多行-- 在 JSON 行之间混有普通日志-- 在进程结束时留下没有换行的最后一行--`PipeReadBuffer` 维护 byte buffer,读取期间按换行发布非空行,在 EOF 或停止读取时也会发布末尾尚未换行的非空内容。会话层先轻量解码 response ID,只有 ID 匹配才完整解码 result 或 error。--这既避免把日志误判成协议错误,也让大响应只进行一次完整泛型解码。--### Stderr 排空--即使 CodexBar 不展示 stderr 正文,也必须 drain pipe。子进程 pipe buffer 有上限,如果父进程从不读取 stderr,app-server 写满后会阻塞,随后的 stdout response 也不会到达。--`PipeDrain` 不解析内容,只负责持续排空 stderr。--### 关闭策略--session 关闭时按以下顺序收口:--1. 停止 stdout 和 stderr reader-2. 关闭 stdin 写端-3. 向仍在运行的进程发送 `SIGTERM`,最多等待 1 秒-4. 仍未退出时发送 `SIGKILL`,再等待 0.5 秒-5. 仍存活则记录诊断错误--进程提前退出后继续写 pipe 可能触发 `SIGPIPE`。service 在初始化时忽略该 signal,让写入以 Swift error 返回并进入 transport failure 重建路径,而不是杀死整个菜单栏 App。--## API 使用范围--| 方法 | 用途 |-| --- | --- |-| `account/read` | 读取账户、套餐和认证状态 |-| `account/rateLimits/read` | 读取额度窗口 |-| `account/rateLimitResetCredit/consume` | 使用指定的 Reset Credit |-| `account/usage/read` | 读取 token 和历史用量 |-| `config/read` | 读取 Codex 配置 |-| `hooks/list` | 校验 Hook 来源和事件能力 |-| `config/batchWrite` | 修改 Hook 或 TUI 通知相关配置 |--### Session 能力缓存--`AppServerSession` 缓存 app-server 明确返回 method unsupported 的方法,当前连接后续跳过这些方法。缓存仅存在于内存,连接重建后重新探测能力。--## 会话生命周期--[`CodexStatusService.swift`](../../CodexBar/Services/CodexStatus/CodexStatusService.swift) 是 actor,持有连接和刷新状态:--- 单次请求超时为 20 秒-- 请求时检查连接年龄,达到 1 小时则重建-- 业务错误在 session 内最多重试 1 次-- transport 失败最多重建连接 1 次-- 认证需要刷新时,`account/read` 最多使用 `refreshToken = true` 再试 1 次-- 连接关闭或释放时执行子进程终止流程;请求读取遇到关闭时按连接错误处理--业务错误与 transport 错误分开处理。前者可能是某个方法暂时失败,后者代表当前 stdio 会话已经不可信。--### 连接状态机--```text-no connection- -> resolve CLI- -> open and initialize- -> ready--ready- -> age < 1h and process alive: reuse- -> process exited: close and rebuild- -> age >= 1h: close and rebuild- -> transport failure: close and rebuild once- -> account missing after refresh: close and notLoggedIn-```--1 小时是请求时检查的连接复用上限。达到上限后的下一次请求会重建连接并使用当时磁盘上的 Codex binary,没有独立的定时销毁任务。--手动重连、切换来源和连接到期重建都先关闭旧连接;新连接失败时保持断开。来源选择只在手动重连成功后保存。自动刷新和手动重连的错误都会更新 `CodexStatusViewModel.connectionErrorMessage`,关于页面直接展示该状态。--### 错误分类--| 错误 | 当前请求 | 当前连接 | 整轮刷新 |-| --- | --- | --- | --- |-| retriable server error | 同一方法再试 1 次 | 保留 | 根据第二次结果继续 |-| method unsupported | 标记当前 session 不支持 | 保留 | 对应字段为 missing |-| 普通业务失败 | 不再重试 | 保留 | 同账户缓存可降级 |-| authentication required | 本轮统一刷新 token 后再试 | 保留或转未登录 | 全程最多刷新 1 次 |-| timeout, pipe close, invalid transport | 失败 | 立即丢弃 | 仅复用连接时重建 1 次 |--限制重建次数是为了避免故障状态下反复拉起子进程。一轮刷新结束后,下一次正常定时刷新仍有新的尝试机会。--### 认证刷新预算--一次刷新会读取 account、rate limits 和 usage,Reset Credits 明细包含在 rate limits 响应中。多个接口可能同时发现 token 过期。--`fetchData` 内部用同一个 `didRefresh` 锁存本轮刷新资格。第一个认证失败触发 `account/read(refreshToken: true)`,后续接口复用刷新结果。再次需要认证时直接归类为未登录。--## 刷新模型--状态 ViewModel 按用户选择的数据更新间隔刷新,支持 1、2、3、5 或 10 分钟,默认 1 分钟。用户也可以在主面板双击账户图标立即触发。--一次刷新先解析账户,再读取额度和用量。补充数据缓存严格绑定到账户身份:--- 账户不变且补充请求失败时可以继续展示缓存值-- 账户变化时立即清空旧账户缓存-- 服务端明确不支持的方法显示为来源缺失-- 来源缺失不能转换为业务值 `0`--刷新或重连进行中会忽略普通刷新触发。需要补刷的操作通过 `refreshAfterCurrent` 保留一个待执行触发,待当前请求结束后执行;协调器负责取消和校验过期结果。--### 一次刷新如何组装快照--```text-确认或新建 connection- -> 复用连接时 account/read- -> 确认 account identity- -> account/rateLimits/read(包含 Reset Credits 明细)- -> account/usage/read- -> 组合 CodexQuotaSnapshot- -> MainActor 提交 loadState 与连接信息-```--rate limits 与 usage 是补充数据。只要账户有效,即使两个接口都没有数据,仍然生成快照让 UI 展示账户和明确的“暂无数据”。--### 缓存决策表--| 当前结果 | 同账户有缓存 | 输出 | stale |-| --- | --- | --- | --- |-| 成功 | 任意 | 新值并更新缓存 | `false` |-| 普通请求失败 | 是 | 缓存值 | `true` |-| 普通请求失败 | 否 | `nil` | 不适用 |-| method unsupported | 任意 | `nil` | 不适用 |-| 账户变化 | 旧账户缓存 | 先整体清空 | 不适用 |--method unsupported 不使用旧缓存,因为它是明确能力结论。普通请求失败使用缓存,因为来源可能只是一轮暂时故障。--### stale 如何影响消费者--- UI 可以展示旧值,但降低菜单栏和进度条透明度-- `hasTrustedData` 只把非 stale 的额度或用量算作可信-- 额度通知完全跳过 stale rate limits-- 系统日志只记录 step 为 `cached`,不记录实际额度数值--stale 是数据可信度的一部分,新增展示时不能只复制数值而丢掉标记。--### 刷新结果的代际校验--`isRefreshing` guard 可以阻止普通重复触发,但 cancellation 和对象生命周期仍可能让旧 Task 返回。--`RefreshTaskCoordinator` 每次开始先推进 generation,取消旧 Task,最终只有 `canCommit(generation)` 成立的结果可以写回 UI。这让“最后发起的刷新获胜”成为显式规则。--自动刷新每轮按距离上次完成的剩余时间等待。手动刷新完成后倒计时自然重新对齐,不会在几秒后又被原来的 timer 立刻刷新一次。--### 数据模型与展示投影--`CodexUsageSnapshot` 构造时把可能重复的 daily bucket 聚合成 `tokensByDate`--热力图在一次渲染中会反复查询日期。提前构造可选索引避免每个方块都线性扫描原始 bucket,并让快照相等比较只关注汇总指标、每日数据可用性和聚合后的每日 Token。原始 bucket 的顺序或拆分方式不影响展示结果,也不单独触发动画。--`account/usage/read` 的 `summary` 必须存在,但汇总指标和 `dailyUsageBuckets` 均可为空。模型保留空值语义:汇总指标缺失时显示 `--`;`dailyUsageBuckets == nil` 表示每日数据不可用,空数组才表示已成功读取但没有记录。合法的部分响应不使用旧值填充;业务 payload 解码失败则按补充接口失败处理,不重建 app-server 会话或清空额度数据。--额度 limit 的展示顺序也在模型层统一:--- app-server 顶层 `rateLimits` 指向的主 limit 优先-- 其余按本地化名称和 limit id 稳定排序-- primary 与 secondary 使用稳定枚举,View 不根据标签字符串猜测窗口类型--## Reset Credits--界面将可用数量显示为“留存重置”或“Banked Resets”,本地化键为 `banked-reset.count`。协议字段仍使用 `rateLimitResetCredits`--`account/rateLimits/read` 的 `rateLimitResetCredits` 同时返回可用数量和可选明细:--- `availableCount` 是权威总数-- `credits == nil` 表示只知道数量-- 空数组表示服务端已获取明细,但没有返回可用凭证-- 明细列表可能被服务端截断,长度可以小于 `availableCount`-- 每条明细包含 opaque `id`、`status` 和可空的 Unix 秒级 `expiresAt`-- 每条明细还包含 `resetType`,自动重置只接受 `codexRateLimits`--模型层只保留 `status == available` 且晚于快照生成时间的过期日,并按时间排序。数量仍独立使用 `availableCount`,不能从过滤后的日期数量反推。--过期明细属于增强信息。`credits == nil` 时主面板仍展示可用数量,详情显示未知过期时间,不影响额度和用量。额度响应来自同账户缓存时,UI 可以继续展示旧明细,但通知服务不会用 stale 数据触发新的临期通知。--### 自动重置--用户主动开启自动重置后,[`AutoResetController.swift`](../../CodexBar/Services/CodexStatus/AutoResetController.swift) 只处理最新 `account/rateLimits/read` 明确返回的凭证明细:--- 快照为 stale、`credits == nil`、缺少 `expiresAt`、状态不是 `available` 或 `resetType` 不是 `codexRateLimits` 时不调用消费接口-- 明细可能被截断,只处理实际返回的凭证,不从 `availableCount` 猜测未列出的 `creditId`-- 同一时间只处理返回明细中最早到期的一条,完成或消失后再选择下一条-- 进入用户设置的临期时间窗口后,消费前再次强制读取账户和凭证明细-- 请求始终显式传入 `creditId`,不会让后端代选-- 消费结果返回后立即再读一次 rate limits-- `reset`、`alreadyRedeemed` 和 `noCredit` 会请求完整额度刷新;`nothingToReset` 在目标仍存在时只安排下一次重试,目标已经变化时再请求完整刷新--调用形状如下:--```text-account/rateLimitResetCredit/consume- creditId: <exact opaque id>- idempotencyKey: <deterministic UUIDv5>-```--结果按以下语义处理:--| `outcome` | 结论 | 后续动作 |-| --- | --- | --- |-| `reset` | 本次调用完成消费 | 成功通知、刷新额度、停止该凭证重试 |-| `alreadyRedeemed` | 相同幂等键此前已经完成消费 | 与 `reset` 相同,按成功处理 |-| `nothingToReset` | 当前没有可重置的额度窗口 | 凭证未消费,继续使用同一幂等键重试 |-| `noCredit` | 当前账户没有可用凭证 | 强制刷新;目标消失时静默停止,否则按暂时不一致重试 |--`alreadyRedeemed` 确认同一逻辑请求此前已成功;收到后停止重试,并按通知设置发送本机成功通知。--### 跨设备幂等契约--同一个 Codex 账户可能同时在多台 Mac 上运行 CodexBar。设备之间不依赖 CloudKit 协调,而是对相同 `creditId` 计算完全相同的 UUIDv5:--```text-namespace = c2904ab3-0a87-5648-997d-bd8515edd401-name = creditId 的原始 UTF-8 字节-output = lowercase UUID string-```--namespace 来自 URL namespace 对 `https://codexbar.zabrian.app/idempotency/auto-reset/v1` 执行 UUIDv5。这个 URL 只用于确定 namespace,不代表运行时网络请求。--固定测试向量为:--```text-creditId = RateLimitResetCredit_123-idempotencyKey = 4035685d-9ca4-524f-8193-6e0ae2a7b3b9-```--namespace、UUID 版本、原始 UTF-8 输入和小写输出共同构成跨版本兼容协议,不能在普通重构中修改。最先成功的设备完成消费,其他设备用同一个 key 调用时会得到 `alreadyRedeemed`,或者在前置刷新时发现凭证已经消失。--凭证消失无法区分手动使用、其他设备使用和服务端过期,因此只停止本机任务,不发送自动重置成功通知。只有明确收到 `reset` 或 `alreadyRedeemed` 的设备才发送成功通知。--### 调度与重试--自动重置状态机和网络请求仍位于普通 App 进程,CodexBarHelper 只负责受限的系统唤醒计划:--- 开启功能时复用现有 CodexBarHelper 注册与批准流程,不依赖“防止系统睡眠”主开关-- App 只把最近一次阈值或重试时间交给 helper;helper 使用固定 owner 和固定 `wake` 类型替换 CodexBar 自己的事件,不接受任意事件类型-- helper 设置或取消后必须回读系统事件;只有恰好存在一个目标时间事件或确认事件已经清零时才回复成功-- 定时或唤醒触发后,App 仅在新鲜读取和消费请求期间持有 `PreventUserIdleSystemSleep` assertion,不保持显示器唤醒,也不修改 `SleepDisabled`-- 任务变化、功能关闭、App 退出或对应 XPC 连接关闭时取消 CodexBar 自己的唤醒事件-- helper 启动时先清除固定 owner 的遗留事件再接受连接;取消失败会放弃失效的连接所有者并在 helper 内重试-- App 正常退出会等待取消回读;App 强制终止或 XPC 连接中断时由 helper 立即取消,突然断电留下的事件由 helper 下次启动收敛,之后 App 按新鲜明细重新调度-- App 启动、用户开启功能或系统唤醒时先做新鲜读取;已经进入临期窗口且尚未过期时立即补试,否则按临期时间重新调度-- App 退出后不持久化原始 `creditId`;下次启动通过新鲜明细重建任务和同一确定性幂等键-- 同一 `creditId` 的 `expiresAt` 变化时保留幂等身份,但取消当前阈值或重试任务并按新时间重排;新临期点已经过去时立即补检-- 只有已经掌握 `creditId + expiresAt` 的目标才能注册重试唤醒事件;只知道数量或读取失败时不为查询重试唤醒 Mac-- 网络、超时、连接断开或暂时服务错误按 `15s, 30s, 1m, 2m, 5m` 序列计算退避,但不安排落在本轮 5 分钟截止点及之后的重试-- 单轮超时后取消本地任务和系统唤醒事件,但不标记目标失败;后续普通额度刷新仍可为同一目标开启新一轮重试-- `nothingToReset` 在距过期不足 10 分钟且本轮重试窗口尚未结束时固定等待 60 秒,其他时间沿用通用退避-- 认证失败先沿用 service 的单次 token refresh;仍失败时暂停当前凭证并按通知设置告知用户,后续可信快照证明认证恢复后再继续-- 参数、协议或方法错误停止当前凭证,不进行无意义重试--自动重置触发完整额度刷新时,如果普通额度刷新正在执行,新刷新会排队到当前刷新结束后运行,不能被 `isRefreshing` guard 丢弃。--## Hook 版本与配置校验--Hook 设置也复用 app-server 链路,但采用独立的可用性状态:--- `isEnabled` 表示当前进程中的开启状态,首次从已有 handler 恢复;运行期间配置缺失时触发自愈-- `isVerified` 默认 `true`,随后保存最近一次明确校验结论-- `isOperable` 只有在两者都为 `true` 时成立-- 短暂 RPC 失败保留上一次明确校验结果--启用或校验 Hook 时必须确认实际 app-server 版本不低于 `0.153.0`--详细配置流程见 [Hook 采集与历史聚合](hook-and-aggregation.md)--### 实际版本检查的时序--启用或校验 Hook 时调用 `readyConnectionInfo()`--- 没有连接时先建立连接-- 有连接时复用当前真实进程-- 从 handshake user agent 解析运行版本-- 无法解析版本时拒绝连接,但不触发低版本 Hook 自动清理--## 请求日志--[`RequestLog.swift`](../../CodexBar/Services/CodexStatus/RequestLog.swift) 在内存中保留最近 500 条请求日志,用于 App 内日志窗口诊断。--日志用于观察进程启动、JSON-RPC 方法、重试和错误分类。不应写入 access token 或 Hook prompt 内容。--`CodexProxyError` 的配置错误只写入系统日志 `settings` 分类,不创建 app-server 请求日志。RPC 响应及错误写入交互日志前,先解析 JSON 转义并遍历字符串值,将 HTTP/HTTPS URL 中的用户名和密码替换为 `<redacted>`;非 JSON 文本直接执行同样的替换。--### 请求日志与系统日志--系统统一日志只保存控制流分类,适合长期排查 App 是否在刷新,失败在哪个阶段。--App 内 `RequestLog` 保存最多 500 条请求交互预览,只存在进程内存,适合用户主动检查协议细节。--Reset Credits 明细包含 opaque credit ID。系统日志不能记录 ID 或原始响应,App 内请求日志仍只按既有规则保存在当前进程内存。对新 RPC 增加日志时,需要检查 payload 是否可能包含凭据或内容字段。--## 建议验证的故障场景--- Finder 启动时仍能找到 Homebrew, npm 或 Volta 安装的 Codex-- 全局 CLI 缺失时正确回退到 ChatGPT App 或 Codex App 内置 binary-- stdout 混有普通文本时仍能匹配正确 response id-- stderr 持续输出时请求不会因 pipe 背压卡住-- 复用连接的 transport failure 只重建一次-- 磁盘 CLI 升级后,当前连接版本与磁盘版本能被区分-- app-server 低于 `0.145.0` 时阻断账户主链路并提示升级-- app-server 不低于 `0.145.0` 且低于 `0.153.0` 时账户主链路可用,但 Hook 仍提示需要 `0.153.0`-- app-server 不低于 `0.153.0` 时账户主链路和 Hook 校验均可用-- rate limits 失败但同账户有缓存时展示 stale,通知不误触发-- 账户切换后旧额度和用量立即清空-- unsupported method 在同一连接中不会重复请求-- Reset Credits `credits == nil` 时保留权威数量并显示未知过期时间-- Reset Credits 明细为空或被截断时不从明细长度反推可用数量-- 过期、非 available 的 Reset Credits 不进入详情或通知-- stale rate limits 可以展示旧明细,但不触发临期通知-- 自动重置关闭时不会调用消费接口,缺失设置默认关闭且提前量默认 30 分钟-- 自动重置不会消费 stale、缺少明细、缺少过期时间或未列出的凭证-- 两台设备对固定 `creditId` 生成相同幂等键,并与固定测试向量一致-- 同一 `creditId` 的过期时间提前或推迟时都重新调度,幂等键保持不变-- `reset` 和 `alreadyRedeemed` 均停止重试并发送成功通知-- `nothingToReset` 保留凭证并按退避策略重试-- 防睡眠关闭时仍可注册并批准 helper,未来阈值会写入固定 owner 的 `wake` 事件-- 计划时间处于系统睡眠期间时唤醒 Mac,触发后重新读取;自然唤醒和 App 启动仍执行相同补检-- 功能关闭、目标变化和 App 退出时取消已有唤醒事件,且不影响其他应用的计划事件-- 只有数量或读取失败、没有具体目标时不注册查询重试唤醒事件-- 已知目标的单轮连续重试在临期触发 5 分钟后停止,后续普通额度刷新仍可重新开启一轮-- 消费成功后的完整额度刷新不会被并发普通刷新丢弃-- 手动刷新后按所选数据更新间隔重新对齐倒计时-- 在自动刷新等待期间切换间隔,按上次结果提交时间重新安排等待;正在进行的请求继续完成,重启后恢复所选间隔--代理相关验证还包括:停用无效配置、清除损坏记录、测试取消后旧结果隔离、快速连续切换只提交一次、提交失败回滚,以及日志中普通 URL 和 JSON 转义 URL 的用户名、密码替换。--## 关键源码--- [`CodexCLIResolver.swift`](../../CodexBar/Services/CodexCLI/CodexCLIResolver.swift)-- [`AppServerSession.swift`](../../CodexBar/Services/CodexStatus/AppServerSession.swift)-- [`AppServerPipeReaders.swift`](../../CodexBar/Services/CodexStatus/AppServerPipeReaders.swift)-- [`CodexStatusService.swift`](../../CodexBar/Services/CodexStatus/CodexStatusService.swift)-- [`CodexStatusViewModel.swift`](../../CodexBar/Services/CodexStatus/CodexStatusViewModel.swift)-- [`AutoResetController.swift`](../../CodexBar/Services/CodexStatus/AutoResetController.swift)-- [`AutoResetIdentity.swift`](../../CodexBar/Services/CodexStatus/AutoResetIdentity.swift)-- [`AutoResetWakeScheduler.swift`](../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift)-- [`CodexBarHelperXPC.swift`](../../Shared/CodexBarHelperXPC.swift)diff --git a/Docs/DeveloperGuide/architecture.md b/Docs/DeveloperGuide/architecture.mddeleted file mode 100644index 082323b..0000000--- a/Docs/DeveloperGuide/architecture.md+++ /dev/null@@ -1,304 +0,0 @@-# 整体架构--简体中文 | [English](../en/DeveloperGuide/architecture.md)--进程、数据链路与恢复路径的交互式总览见[运行架构](https://codexbar.zabrian.app/architecture)--## 技术基线--CodexBar 是 macOS 15+ 菜单栏应用,使用 Swift 6, SwiftUI, AppKit 和 MVVM。--工程只有 `CodexBar` scheme,包含以下 target:--| Target | 职责 |-| --- | --- |-| `CodexBar` | 菜单栏 UI、Codex 数据采集、自动重置、通知、同步和系统电源编排 |-| `CodexBarHelper` | 以 root LaunchDaemon 运行,负责固定的系统睡眠开关和自动重置唤醒计划 |-| `CodexBarTests` | 无 App 宿主的 Swift Testing 单元测试,直接编译生产源码并隔离测试数据 |--App 与 helper 通过 [`CodexBarHelperXPC.swift`](../../Shared/CodexBarHelperXPC.swift) 共享 XPC 协议。--App 使用 Sparkle 检查更新。工程默认启用 `MainActor` 隔离,Debug 和 Release 使用不同的 App 与 CodexBarHelper bundle ID。--## 进程与信任边界--```text-Codex- | 启动 --hook-event 子进程, 通过 stdin 传入事件- v-CodexBar executable- |-- Hook 模式: 最小解析 + flock + JSONL append + exit- |- `-- 普通模式- |-- stdio JSON-RPC <-> codex app-server(账户、额度、Reset Credits)- |-- 本地只读 <-> Hook JSONL / rollout JSONL- |-- HTTPS <-> Sparkle- |-- CloudKit private database <-> 日级聚合- `-- signed XPC lease / wake date <-> root CodexBarHelper- |-- fixed pmset commands- `-- fixed IOPM wake event-```--边界设计遵循以下原则:--- 同一个可执行文件承载 Hook 模式可以让 handler 始终指向当前 App 版本,不需要额外部署采集工具-- root helper 不知道 Codex 任务、账户或重置凭证,只接收经过签名校验的睡眠租约和自动重置唤醒时间--### 进程生命周期差异--| 进程 | 生命周期 | 可以做什么 | 不能做什么 |-| --- | --- | --- | --- |-| Hook 子进程 | 单个事件,最长几秒 | 读取 stdin、提取最小字段、追加本地 JSONL | 初始化 UI、建立网络连接、等待长期服务 |-| 主 App | 用户登录会话内长期运行 | 编排 UI、数据链路和副作用 | 直接以 root 修改系统设置 |-| app-server | 达到 1 小时后的下一次请求重建 | 通过 JSON-RPC 提供账户和配置能力 | 成为 Hook 历史或实时任务的替代来源 |-| CodexBarHelper | LaunchDaemon | 执行固定 `pmset` 操作、管理固定 owner 的 `wake` 事件并恢复系统状态 | 访问账户、Hook、rollout、网络或任意命令 |--## 目录职责--```text-CodexBar/- App/ App 入口- Controllers/ AppKit 窗口, 菜单栏和面板控制器- Models/ DTO, 状态快照和展示模型- Services/ 数据获取, 状态机, 设置, 通知和系统服务- Views/ SwiftUI 视图- Resources/ Info.plist, entitlement, 本地化和声音资源-CodexBarHelper/ root LaunchDaemon-Shared/ 跨 target XPC 接口-Config/ 版本配置-Scripts/ 构建, DMG, appcast 和 CodexBarHelper 清理脚本-```--## 启动顺序--[`CodexBarApp.swift`](../../CodexBar/App/CodexBarApp.swift) 按以下顺序分流启动:--```text-进程启动- -> WorkflowHookEventRecorder.handleIfRequested()- -> 命中 --hook-event 时读取 stdin, 写入 JSONL, 立即退出- -> 普通启动时继续- -> 创建 CodexBarAppDelegate- -> AppDelegate 装配长期服务- -> 创建菜单栏和辅助窗口- -> 启动刷新、活动监控、自动重置、通知和系统电源协调-```--`--hook-event` 是 Codex 调用的短命子进程模式。它必须在任何 UI、CloudKit、通知或长期服务初始化之前完成。采集失败也不能阻断 Codex 主流程。--普通模式由 `CodexBarAppDelegate` 统一创建和持有长期对象,主要包括:--- `CodexStatusService` 和 `CodexStatusViewModel`-- `CodexProxySettings`-- `WorkflowService` 和对应 ViewModel-- `AdvancedModeSettings`-- `CodexActivityMonitor`-- `KeepAliveController`-- `AutoResetController`-- `WorkflowSyncSettings` 和同步调度器-- `CodexNotificationService`-- 菜单栏、快捷键、设置窗口和更新服务--App 退出时需要先取消自动重置唤醒计划并释放防睡眠状态。如果 CodexBarHelper 尚未回读确认两类系统状态都已恢复,终止流程会等待或取消退出。helper 启动时还会在接受新连接前清除固定 owner 的遗留唤醒事件,用于收敛突然断电或强制终止留下的状态。--### Hook 启动分流--`@NSApplicationDelegateAdaptor` 会把 AppKit 生命周期接入 SwiftUI App。一旦普通生命周期开始,可能创建菜单栏对象、注册通知 delegate 或访问 CloudKit。--Hook handler 在 Codex 的关键路径上,它需要的是接近命令行工具的行为。因此 `WorkflowHookEventRecorder.handleIfRequested()` 必须在 `CodexBarApp.init()` 的第一段执行,命中后直接 `exit(EXIT_SUCCESS)`--这个顺序还保证 Hook 采集失败不会污染正常退出诊断。`AppProcessDiagnostics.install()` 只在 `applicationDidFinishLaunching` 中执行,Hook 子进程不会被误记为一次异常退出的完整 App。--### 退出协调--`applicationShouldTerminate` 先调用 `KeepAliveController.prepareForTermination()` 并返回 `.terminateLater`--如果 helper 明确确认自动重置唤醒事件已经取消且防睡眠 release 已完成,App 再回复允许退出。任一清理失败时,本次退出被取消,controller 回到正常协调状态并继续按当前设置运行。--直接在 `applicationWillTerminate` 中异步释放已经太晚,因为该回调不能可靠延长进程寿命。--## 3 条独立数据链路--各数据链路分别管理不同的输入、时效和失败状态:--| 链路 | 输入 | 输出 | 主要消费者 |-| --- | --- | --- | --- |-| app-server | `codex app-server` JSON-RPC | 账户、额度、token 用量、Reset Credit 使用、Hook 配置能力 | 主面板、菜单栏额度、设置、自动重置状态机 |-| 历史统计 | Hook JSONL 与 rollout JSONL,分别读取和聚合 | 日级活动统计、线程轮次 Token 累计值及日汇总 | 热力图日期详情、历史统计、CloudKit |-| 实时任务 | Hook 增量事件加 rollout 生命周期与轮次用量 | 运行、等待批准、完成、终止、本轮 Token | 菜单栏状态、任务中心、任务流光、通知、防睡眠 |--### 依赖方向--```text-CodexStatusService ----------------> CodexStatusViewModel ----------------> UI-CodexStatusViewModel --------------> CodexNotificationService-CodexStatusService ----------------> AutoResetController-CodexStatusViewModel --------------> AutoResetController-AutoResetController ---------------> CodexNotificationService-AutoResetController ---------------> KeepAliveController ---> AutoResetWakeScheduler ---> helper--WorkflowService -------> WorkflowViewModel -----------> UI--Hook + rollout --------> CodexActivityMonitor --------> UI- | |- | +------------> CodexNotificationService- `-----------------------> KeepAliveController --> helper-```--箭头表示数据或只读状态的消费方向。下游不能反向成为上游的事实来源。--### 共享刷新触发--历史维护挂在额度刷新完成事件上,间隔由数据更新设置决定,默认 1 分钟,这是为了减少常驻 timer 和日志噪音。两条链路共享调度时机,但没有共享事实。--因此修改刷新节奏时需要区分:--- 触发来源可以调整-- 维护任务仍必须在 app-server 失败时具备独立执行能力-- UI 打开时的轻量统计刷新不能隐式发起 CloudKit 网络操作--## 并发边界--工程启用 Swift 6 严格并发和默认 `MainActor` 隔离。--### MainActor 对象--- SwiftUI ViewModel 和 Settings-- AppKit Controller-- `CodexActivityMonitor`-- `KeepAliveController`-- `CodexNotificationService`-- `AutoResetController`-- `AutoResetWakeScheduler`--这些对象负责可观察状态和 UI 协调,不应直接执行阻塞 I/O。--### Actor 服务--- `CodexStatusService` 管理 app-server 连接和刷新-- `WorkflowService` 协调 Hook 日聚合与 Token 历史快照-- `CodexTokenHistoryStore` 管理 rollout 历史账本、读取游标和显式重建-- `CodexTokenHistorySync` 管理轮次用量的 CloudKit 记录和缓存-- `HookEventTailReader` 管理 Hook 文件游标-- `CodexSessionLifecycleReader` 管理 rollout 文件游标-- `WorkflowSyncService` 管理 CloudKit 状态-- `ActivityProtectionStateStore` 管理跨进程保护记录--跨 actor 传递的 DTO 必须是不可变值类型,并按需要声明 `Sendable` 或 `nonisolated`--### Monitor 的 MainActor 边界--`CodexActivityMonitor` 的输入读取在 actor 中完成,但状态机本身与多个 Combine 消费者紧密相连。--把 monitor 放在 `MainActor` 有以下收益:--- `@Published snapshot` 和 transition 发布顺序天然串行-- 通知与防睡眠消费者看到相同的状态提交顺序-- App 睡眠、唤醒和 Hook 设置变化可以与 UI 生命周期统一排序--前提是 monitor 不能直接执行阻塞文件读取。`HookEventTailReader`, `CodexSessionLifecycleReader` 和 `ActivityProtectionStateStore` 各自承担 I/O 边界。--## 模型分层--模型按外部输入、持久化、领域状态和展示职责分层:--| 模型类型 | 作用 | 设计要求 |-| --- | --- | --- |-| 外部 DTO | 解码 app-server, Hook, rollout 或 CloudKit | 宽容版本差异,不承载 UI 副作用 |-| 持久化模型 | 保存可恢复状态和 schema | 兼容旧值,明确 missing 语义 |-| 领域快照 | 向消费者表达当前可信状态 | 不可变、可比较、跨 actor 安全 |-| transition | 表达一次 live 状态变化 | 不从历史快照反推,需要上游去重 |-| 展示格式 | 日期、百分比、文案和颜色 | 按各展示字段的地区设置或固定格式输出,不参与业务判定 |--例如 `CodexQuotaSnapshot` 可以同时携带当前值和 stale 标记。`CodexActivitySnapshot` 只保存展示需要的任务字段,原始 session ID 不进入 View。--## 生命周期与保留时间--各类状态的生命周期如下:--| 状态 | 生命周期 | 原因 |-| --- | --- | --- |-| app-server connection | 请求时检查 1 小时复用上限 | 后续请求重建连接时使用磁盘上的 binary |-| app-server supplemental cache | 当前账户内 | 避免跨账户串值 |-| Hook live bootstrap window | 24 小时 | 覆盖可能仍在运行的长任务 |-| 菜单栏完成或终止提示 | 10 秒 | 最新终态的短时反馈 |-| 任务中心 terminal 历史 | 10 分钟 | 提供近期上下文但不长期占用 UI |-| terminal 去重记忆 | 24 小时 | 防止迟到 Hook 或 rollout 复活旧任务 |-| Hook 原始和日聚合 | 210 天 | 支持长期统计和重建 |-| Token 轮次账本 | 按最近记录时间保留 210 天,保留仍被子轮次引用的根记录 | 支持日汇总、增量续读和重建 |-| 日聚合身份明细 | 3 天 | 近期精确去重与隐私、文件体积折中 |-| Activity Protection 记录 | 最后进展后 24 小时 | 跨重启保持抑制,同时限制身份留存 |--修改其中一个时间窗口时,要先确认是否存在配对不变量。例如 tail reader bootstrap 窗口必须和活动任务保留窗口一致。--## 状态所有权--| 状态 | 唯一所有者 | 其他模块的权限 |-| --- | --- | --- |-| app-server 连接与同账户缓存 | `CodexStatusService` | 通过服务方法读取数据、修改配置或重连 |-| 代理草稿、测试和开关交互 | `CodexProxySettings` | 设置页通过方法提交,`CodexStatusService` 应用正式连接配置 |-| 主面板账户加载状态 | `CodexStatusViewModel` | 观察发布值 |-| 自动重置的目标、deadline 和重试 | `AutoResetController` | 设置页只修改开关和提前量 |-| 自动重置唤醒时间同步 | `AutoResetWakeScheduler` | `AutoResetController` 只提交下一次时间,`KeepAliveController` 只提交 helper 就绪状态 |-| Hook 安装与验证 | `AdvancedModeSettings` | 读取 `isOperable` |-| 历史聚合和维护游标 | `WorkflowService` | 请求快照或重建 |-| 实时任务 | `CodexActivityMonitor` | 读取快照、通知转场或包含新增终态的展示更新 |-| 同步游标与远端缓存 | `WorkflowSyncService` | 请求合并快照 |-| 防睡眠策略与 App assertion | `KeepAliveController` | 读取派生状态或调用设置入口 |-| root 睡眠所有权 | `CodexBarHelper` | 通过 XPC 请求和查询 |-| root 自动重置唤醒事件 | `CodexBarHelper` | 通过 XPC 替换或取消固定 owner 的单个 `wake` 事件 |-| 通知去重 | `CodexNotificationService` | 上游只发布候选事件 |--新增消费者时,优先订阅已有快照。如果现有快照缺字段,应在状态所有者处扩展稳定值类型,不应让消费者重新读取原始文件。--## 错误和降级原则--- 短暂网络或 RPC 失败优先保留上一次可解释的状态-- 数据源不可用必须显式表达,不能伪装为空数据-- bootstrap 阶段只建立基线,不发送历史状态变化通知-- reader 更换或数据源代际变化时丢弃旧异步结果-- 恢复流程必须完成新的读取屏障后才能继续判定-- 持久化文件写入需要原子替换或文件锁,避免 Debug 与 Release 并发破坏--### 错误分类--| 错误类别 | 典型处理 | 不应采取的处理 |-| --- | --- | --- |-| 明确业务不支持 | 缓存 method unsupported,显示来源缺失 | 同一连接中重复请求或展示 `0` |-| 短暂业务失败 | 同账户范围内使用 stale 缓存 | 清空整个账户快照 |-| transport 失败 | 丢弃连接,最多重建一次 | 在不可信 pipe 上继续请求 |-| 数据源身份变化 | 新 generation,从原始来源重建 | 沿用旧 offset 继续追加 |-| 迟到异步结果 | generation 不匹配时丢弃 | 覆盖新设置或新 reader 状态 |-| 特权状态不确定 | 保留可能租约或唤醒事件并主动确认清理 | 假定 helper 没有执行 |-| Hook recorder 失败 | 吞掉本次采集并退出成功 | 阻断 Codex 或弹 UI |--## 系统集成--| 能力 | 系统接口 |-| --- | --- |-| 菜单栏 | `NSStatusItem` |-| 主面板 | `NSPopover` 和浮动备用面板 |-| 全局快捷键 | Carbon Hot Key API |-| App 防空闲睡眠 | IOKit power assertion |-| 系统睡眠控制 | CodexBarHelper 调用固定参数的 `/usr/bin/pmset` |-| 自动重置系统唤醒 | CodexBarHelper 调用 `IOPMSchedulePowerEvent` 和 `IOPMCancelScheduledPowerEvent` |-| CodexBarHelper 安装和启动 | `SMAppService` |-| App 与 CodexBarHelper 通信 | XPC |-| 通知 | `UNUserNotificationCenter` |-| 云同步 | CloudKit private database |-| 自动更新 | Sparkle |--## 关键源码--- [`CodexBarApp.swift`](../../CodexBar/App/CodexBarApp.swift) 定义启动入口-- [`CodexBarAppDelegate.swift`](../../CodexBar/Controllers/CodexBarAppDelegate.swift) 负责普通模式服务装配-- [`StatusItemController.swift`](../../CodexBar/Controllers/StatusItemController.swift) 负责菜单栏编排-- [`CodexStatusService.swift`](../../CodexBar/Services/CodexStatus/CodexStatusService.swift) 管理 app-server-- [`WorkflowService.swift`](../../CodexBar/Services/Workflow/WorkflowService.swift) 管理 Hook 历史聚合-- [`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) 管理实时任务-- [`AutoResetController.swift`](../../CodexBar/Services/CodexStatus/AutoResetController.swift) 管理自动重置目标和重试-- [`AutoResetWakeScheduler.swift`](../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift) 同步下一次系统唤醒时间-- [`KeepAliveController.swift`](../../CodexBar/Services/KeepAlive/KeepAliveController.swift) 管理 helper 注册、防睡眠策略和唤醒调度就绪状态-- [`WorkflowSyncService.swift`](../../CodexBar/Services/Workflow/WorkflowSyncService.swift) 管理 CloudKit 同步-- [`CodexBarHelperXPC.swift`](../../Shared/CodexBarHelperXPC.swift) 定义受限特权接口-- [`CodexBarHelper/main.swift`](../../CodexBarHelper/main.swift) 执行并验证系统睡眠与唤醒操作diff --git a/Docs/DeveloperGuide/data-and-privacy.md b/Docs/DeveloperGuide/data-and-privacy.mddeleted file mode 100644index ba657da..0000000--- a/Docs/DeveloperGuide/data-and-privacy.md+++ /dev/null@@ -1,315 +0,0 @@-# 数据与隐私边界--简体中文 | [English](../en/DeveloperGuide/data-and-privacy.md)--## 数据分类模型--数据按以下类别确定存储和传播范围:--| 分类 | 示例 | 默认处理 |-| --- | --- | --- |-| 内容 | prompt, response, tool 参数和输出 | 不采集 |-| 身份和上下文 | session ID、完整路径、project 名 | 原始 session ID 和完整路径不上传;Token 轮次使用哈希标识,项目显示名随统计上传 |-| 聚合指标 | 每日事件数、model 计数 | 可本地持久化,用户 opt-in 后上传规定字段 |--## 信任边界--```text-Codex hook stdin / rollout / app-server- |- v- 普通用户权限的 CodexBar- | |- v v- CloudKit private DB 受限 XPC 接口- |- v- CodexBarHelper-```--边界含义如下:--- Codex 输入文件和协议数据都视为外部输入,解码失败不能扩大成任意文件访问或命令执行-- CloudKit 是用户主动开启的远端边界,即使使用 private database 也只允许规定聚合字段-- root helper 是权限提升边界,接口能力必须比 App 业务能力更窄-- Debug 和 Release 是两个 App 身份,但部分本地文件有意共享,因此需要进程锁和兼容 schema--## 最小化发生在采集入口--CodexBar 的最小化顺序是:--1. Hook recorder 从 stdin 只提取白名单结构字段-2. rollout reader 使用最小 Codable 结构跳过正文-3. 聚合器把较老 identity 明细压成计数-4. sync model 再投影成 CloudKit 允许字段-5. 日志层只记录阶段、分类和非敏感计数--## 数据流总览--| 来源 | CodexBar 使用方式 | 是否持久化 | 是否上传 CloudKit |-| --- | --- | --- | --- |-| app-server 账户、额度和 Reset Credits | 主面板、通知判断和用户启用的自动重置 | 仅短期状态 | 否 |-| Hook 结构化事件 | 历史聚合和实时任务 | 是,最长 210 天 | 只上传日聚合 |-| rollout 生命周期 | terminal 和进展对账 | 不单独持久化 | 否 |-| rollout token 累计值 | 轮次去重和日汇总 | 轮次哈希标识、时间和计数,210 天 | 用户启用同步后上传轮次哈希标识及累计值 |-| App 设置 | 功能开关和阈值 | UserDefaults | 否 |-| Activity Protection | 异常会话恢复 | 任务哈希标识,最长 24 小时 | 否 |-| CodexBarHelper ownership | 系统睡眠恢复 | root 状态文件 | 否 |-| 自动重置唤醒计划 | 固定 owner、`wake` 类型和下一次时间 | 系统电源管理 | 否 |--## 本地读取--### Codex app-server--App 通过本机 `codex app-server --listen stdio://` 获取账户、额度、token 用量、Reset Credits 明细和 Codex 配置。用户主动开启自动重置后,App 还会通过同一 stdio 会话调用 Reset Credit 消费方法。--CodexBar 不自行实现账户登录。app-server 是否访问 OpenAI 服务由 Codex CLI 的正常认证和协议行为决定。--CodexBar 只通过 stdio 与本机进程通信,不从 app-server 响应中复制认证材料。request log 保存规范化后的完整请求与响应 JSON,只存在当前 App 进程内存,不持久化。日志保留账户响应、opaque credit ID 和幂等键等协议字段。--### Hook 事件--Hook 子进程从 stdin 提取:--- 时间和事件类型-- 工作目录-- tool, model 和 effort-- permission 和 reviewer-- session, turn 和 agent 身份--Hook 子进程从 rollout 首条 `session_meta` 的完整记录或已完成字段前缀中提取来源,按 32 KiB 分块且总计不超过 256 KiB。JSONL 只持久化归一化后的 `main`、`autoReview`、`auxiliary` 或 `unknown`,具体分类与 model 后备规则见 [来源归一化](hook-and-aggregation.md#来源归一化)--不把 prompt, response, tool 参数或 tool 输出写入 CodexBar 的 Hook 事件文件。--工作目录只用于派生 project display name 和实时归属。原始 Hook JSONL 仍可能包含 `cwd`,因此它属于本地敏感上下文,受保留期和文件权限约束。rollout 路径、原始 source 和任意 subagent `other` 值不会持久化。CloudKit 只上传派生后的 project 名计数,并明确依赖用户 opt-in。--### Rollout 文件--Hook recorder 通过 `transcript_path` 读取当前 rollout,`SubagentStop` 的来源使用子线程自身的 `agent_transcript_path`。实时活动 reader 访问 `$CODEX_HOME/sessions` 和 `$CODEX_HOME/archived_sessions` 中相关主线程及子线程的文件。--这些读取只解析来源分类、线程及轮次归属、生命周期、时间、turn context、progress、effort、reviewer 和 token 计数等结构字段。实时线程关联只在内存中使用;历史 token 账本仅保存轮次哈希标识、必要时间和 Token 累计计数。对话正文不进入 CodexBar 存储或 UI。--Token 历史扫描从文件起点建立轮次账本,再按游标增量读取。云端身份使用账户 salt 做 HMAC-SHA256,不上传原始线程或轮次 ID。字段和保留规则见 [Rollout Token 历史](sync.md#rollout-token-历史)--实时 rollout reader 初始读取末尾最多 512 KiB,随后增量读取追加内容,并按需向前补查历史。解析 DTO 只声明所需字段,`JSONDecoder` 忽略其余内容。补查停止条件和预算见 [Rollout 读取预算](activity-monitor.md#rollout-读取预算)--### Reset Credits 明细--`account/rateLimits/read` 在 app-server 响应中返回 Reset Credits 数量和可选明细。--- `availableCount` 是可用总数的权威值-- `credits == nil` 表示服务端只提供数量-- 空明细数组表示服务端已读取明细,但没有返回可用凭证-- 明细列表可能被截断,不能用数组长度覆盖总数-- 菜单和临期通知只使用仍为 `available` 且尚未过期的 `expiresAt`-- 自动重置只处理新鲜响应明确列出的 `available + codexRateLimits + expiresAt` 明细-- opaque credit ID 和确定性幂等键只存在于当前进程内存,包括 app-server 响应与缓存、额度快照、自动重置状态机和内存请求日志,不持久化或上传-- 自动重置通知写入 UserDefaults 的去重 key 只包含账户与 credit ID 的 SHA-256 组合,不保存原值--额度响应来自旧缓存时可以继续展示,但不能触发新的临期通知或消费操作。自动重置设置和调度状态不进入 CloudKit,Mac 之间只通过服务端消费接口的确定性幂等键收敛。--## 本地持久化--### App 用户目录--```text-~/Library/Application Support/CodexBar/- HookEvents/- events/YYYY-MM-DD.jsonl- daily.jsonl- maintenance.json- stats.lock- Tokens/- ledger.json- store.lock- rebuild.lock- Sync/- state.json- cache.jsonl- cursor.data- Tokens/- cache.json- store.lock- sync.lock- ActivityProtection/- state.json-```--| 路径 | 内容 | 生命周期 |-| --- | --- | --- |-| `HookEvents/events` | 原始结构化 Hook 事件 | 210 天 |-| `HookEvents/daily.jsonl` | 日级聚合 | 210 天 |-| `HookEvents/maintenance.json` | 文件游标、generation 和维护状态 | 持续更新 |-| `HookEvents/Tokens/ledger.json` | 哈希轮次身份、累计值、重建与恢复边界、文件读取游标 | 用量按最近记录时间保留 210 天;仍被保留子轮次引用的根记录一同保留 |-| `HookEvents/Sync` | Hook 日聚合的云端缓存、游标和替换状态 | 同步状态有效期间 |-| `HookEvents/Sync/Tokens/cache.json` | 账户域轮次记录、salt 和 CloudKit 游标 | 同步时清理过期轮次,保留仍被引用的根记录 |-| `ActivityProtection/state.json` | 哈希任务身份和时间戳 | 最后进展后最长 24 小时 |--最近 3 天的日聚合可以保留 session 和 turn ID 明细用于准确去重。更早数据只保留计数。--匿名任务不生成异常会话保护标识,因此不会写入 `ActivityProtection/state.json`--Token 账本和同步缓存由 Debug 与 Release 共用。`store.lock` 保护对应目录中的文件读写;`rebuild.lock` 排斥并发 Token 重建,`sync.lock` 排斥并发 Token 同步。`stats.lock` 用于 Hook 聚合事务。锁文件本身不保存统计或进度。--### UserDefaults--UserDefaults 保存:--- 功能开关和设置选项-- 数据更新间隔(`DataUpdate.intervalSeconds`,单位为秒)-- 通知阈值和声音名称-- 全局快捷键-- 代理启用状态、协议、服务器、端口、认证用户名和密码-- 菜单栏显示选择-- 自动重置开关和提前量-- 有界的通知去重 key-- CodexBarHelper fingerprint 等运行配置--持久化 key、数据结构、枚举 raw value 或缺失默认值的变化属于兼容性问题,修改前必须确定迁移和降级策略。--代理使用 `CodexProxy.configuration` 保存一条包含 `configuration` 和 `password` 的 JSON 数据。密码明文保存在本机 UserDefaults,保存关闭身份验证的配置或删除配置时删除。Debug 与 Release 使用各自的偏好域,不共享代理配置:--- Debug:`~/Library/Preferences/app.zabrian.codexbar.debug.plist`-- Release:`~/Library/Preferences/app.zabrian.codexbar.plist`--`CodexProxyStore` 区分记录不存在与解码失败;解码失败时保留记录,以便配置窗口提供清除入口。--### CodexBarHelper 目录--```text-/Library/Application Support/CodexBar/helper-state.json-```--文件只保存 CodexBarHelper 是否拥有 `SleepDisabled` 的恢复事务,不包含 Codex 任务、账户或 Hook 数据。--自动重置唤醒计划由系统电源管理保存,只包含 CodexBar 固定 owner、`wake` 类型和下一次时间。helper 不接收或保存账户、`creditId`、幂等键或网络数据。--目录和文件由 root 管理。详细权限和恢复策略见 [防睡眠系统](sleep-prevention.md)--## 内存日志和系统日志--App 内 [`RequestLog.swift`](../../CodexBar/Services/CodexStatus/RequestLog.swift) 是最多 500 条的内存 ring buffer,进程退出后消失。--请求日志用于诊断 app-server 协议。即使只存在内存,也不应写入 OAuth token 或 Hook 内容。--统一系统日志 subsystem 为 `app.zabrian.codexbar`,Debug 版本带 `.debug` 后缀。--系统日志只应记录:--- 操作阶段和结果-- 状态分类-- 不敏感计数-- 可定位模块的错误信息--自动 rollout 回放在 `workflow` 分类记录文件数、读取字节数、剩余量、等待或不可读文件数及耗时,不记录文件路径、身份和用量。进度含义见 [Rollout Token 历史](sync.md#rollout-token-历史)--系统日志不应记录:--- OAuth token-- prompt, response 或 tool 内容-- session ID, turn ID 或 agent ID-- 完整项目路径或敏感项目名-- 账户额度和 token 用量明细--`CodexProxyError` 的固定错误文案写入系统日志的 `settings` 分类,不包含配置值。app-server 响应写入 App 交互日志前会解析 JSON 转义,将字符串值中 HTTP/HTTPS URL 的用户名和密码替换为 `<redacted>`;其他账户和协议字段仍按请求日志规则保留。--## 网络访问--| 目标 | 用途 | 触发条件 |-| --- | --- | --- |-| CloudKit private database | 同步日级 Hook 聚合、轮次哈希标识及 Token 累计值 | 用户主动开启同步 |-| Codex 服务(app-server 子进程) | 认证、额度、用量和 Reset Credit 消费 | 正式刷新、代理测试或自动重置 |-| Sparkle appcast 和更新资源 | 检查或安装更新 | 自动检查或用户手动检查 |--账户、额度、token 用量、Reset Credits 明细和用户明确开启的 Reset Credit 消费通过本机 app-server stdio 完成。CodexBar 不为自动重置增加独立 HTTP 客户端。--CodexBarHelper 不进行任何网络访问。--启用代理后,地址及可选认证信息仅通过环境变量交给 CodexBar 启动的 app-server。配置不会修改系统网络设置、Sparkle、CloudKit 或其他 Codex 进程。连接测试另起临时 app-server,结束后关闭且不写入 App 交互日志。--## CloudKit 边界--CloudKit 上传以下 Hook 日聚合字段:--- 设备哈希标识 `deviceId`-- 日期和 source generation-- Hook 事件计数-- session 和 turn 计数-- project 显示名计数-- model 计数-- 更新时间--此外,token 历史上传账户内稳定的哈希轮次标识、根轮次关联、必要时间和 Token 累计计数,用于跨设备去重和按日汇总。--CloudKit 不上传:--- 原始 Hook JSONL-- 原始 session, turn 或 agent ID-- 完整工作目录-- prompt, response, tool 参数或输出-- app-server 的 Codex 账户、额度和账户 token 用量-- Reset Credits 明细、自动重置设置和消费状态-- access token-- App 请求日志-- Activity Protection 状态-- 代理配置和代理密码--project 显示名可能由目录名派生,仍可能包含用户敏感信息。同步开关必须保持用户主动选择。--## root helper 的数据隔离--CodexBarHelper 只接收以下状态:--- 哪个已验证客户端持有哪一代 lease-- `SleepDisabled` 当前实测值-- CodexBar 是否拥有恢复责任-- 自动重置唤醒计划的有限 Unix 时间戳和当前连接所有者--它不需要 task ID、project 名、Hook 路径、账户状态、`creditId` 或用户设置全文。XPC 只传布尔请求、client session ID、generation、update identifier 和有限 Unix 时间戳。--helper target 只包含受限电源操作和共享 XPC 协议,不链接 App 的业务 service。--helper 的 ownership 文件不是用户偏好,而是 crash recovery 事务记录。它必须由 root 拥有,拒绝 group 或 world 可写目录,并通过 full sync 加原子 rename 确保重启后能判断是否需要恢复。--## 文件安全--- Hook 子进程和 App 聚合器通过 `flock` 协调写入-- JSONL 只追加完整行-- 聚合和状态文件使用可恢复写入流程-- Activity Protection 文件权限为 `0600`-- CodexBarHelper 状态通过 root owner、权限检查、full sync 和原子 rename 提交-- Debug 和 Release 共享的数据必须使用锁和兼容 schema--## 新增数据字段前的审查清单--1. 写明产品目标以及没有该字段时无法完成的行为-2. 确认字段属于凭据、内容、身份上下文还是聚合指标-3. 定义采集入口和最早可以丢弃原文的层-4. 明确内存、UserDefaults, Application Support, system log 和 CloudKit 中的存在范围-5. 定义保留期、删除触发和失败后的清理行为-6. 检查 Debug 与 Release 是否共享文件或 identity-7. 检查字段缺失与明确空值的区别-8. 检查日志和错误对象是否会间接复制原文-9. 如涉及 CloudKit、网络或日志数据,先更新隐私说明并取得明确产品决策-10. 如涉及 schema 或旧版本共存,先确认兼容方案再改代码--## 建议的隐私故障验证--- 用包含明显标记字符串的 prompt 和 tool 参数运行任务,确认 Hook JSONL、App 日志和 CloudKit cache 均没有该字符串-- 让项目目录名包含敏感测试词,确认它只出现在允许的本地展示和 opt-in 聚合字段-- 模拟 Reset Credits 请求失败,确认 access token 不出现在内存日志和 unified log-- 检查 CloudKit record 不包含原始 session, turn, agent ID 或完整路径-- 以非 root 用户验证 helper 状态目录不可写-- 损坏各类缓存文件,确认系统降级或重建,而不是扩大到备用数据采集--## 关键源码--- [`CodexTokenHistoryStore.swift`](../../CodexBar/Services/Workflow/CodexTokenHistoryStore.swift)-- [`CodexTokenHistorySync.swift`](../../CodexBar/Services/Workflow/CodexTokenHistorySync.swift)-- [`WorkflowHookEventRecorder.swift`](../../CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift)-- [`WorkflowService.swift`](../../CodexBar/Services/Workflow/WorkflowService.swift)-- [`CodexSessionLifecycleReader.swift`](../../CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift)-- [`WorkflowSyncService.swift`](../../CodexBar/Services/Workflow/WorkflowSyncService.swift)-- [`ActivityProtectionStateStore.swift`](../../CodexBar/Services/Workflow/ActivityProtectionStateStore.swift)-- [`RequestLog.swift`](../../CodexBar/Services/CodexStatus/RequestLog.swift)-- [`CodexBarHelper/main.swift`](../../CodexBarHelper/main.swift)diff --git a/Docs/DeveloperGuide/design-decisions.md b/Docs/DeveloperGuide/design-decisions.mddeleted file mode 100644index 7dfdbca..0000000--- a/Docs/DeveloperGuide/design-decisions.md+++ /dev/null@@ -1,61 +0,0 @@-# 设计原则与关键决策--简体中文 | [English](../en/DeveloperGuide/design-decisions.md)--## 状态所有权--每条数据链路由一个服务维护事实,消费者读取快照或转场:--| 链路 | 状态来源 | 输出用途 |-| --- | --- | --- |-| app-server | 账户、额度和用量响应 | 周期性展示,同账户内可使用 stale 缓存 |-| 历史统计 | Hook 事件与 rollout 用量分别维护 | 可重建的日级活动统计、线程轮次 Token 账本与跨设备同步 |-| 实时任务 | Hook 增量事件与 rollout 生命周期、轮次用量 | 含本轮 Token 的活动快照、任务通知和防睡眠 |--快照可以反复读取;通知使用 live transition,bootstrap 只建立基线,不补发历史通知。历史聚合与额度刷新共享部分触发时机,但读取和失败处理独立。组件关系见 [整体架构](architecture.md)--## 用户意图与实际效果--保存的开关表示用户意图,依赖状态决定是否能执行,结果状态表示已经确认的效果。依赖临时不可用时保留用户开关,恢复后重新协调。--防睡眠的 `isEnabled`、`sleepBlockReason` 和 `isPreventingSleep` 分别对应这三层。`AdvancedModeSettings` 的 `isEnabled` 与 `isVerified` 共同决定 `isOperable`;实时任务依赖可操作状态,历史聚合仍可处理已落盘数据。--## 缺失、陈旧与不可信数据--| 状态 | 当前处理 |-| --- | --- |-| app-server 补充接口暂时失败 | 使用同账户缓存并标记 stale,降低 UI 透明度,不触发额度通知或自动消费 |-| method unsupported | 当前 session 缓存能力缺失,重建连接后重新探测 |-| 历史 Hook 计数字段缺失 | 持久化和同步模型保留 `nil`,展示投影按指标规则回退 |-| 实时 reader 无法取得稳定边界 | 发布 degraded health,暂停异常会话保护 |--这些状态由来源层给出,消费方按用途决定是否展示或执行副作用。计数投影见 [Hook 聚合](hook-and-aggregation.md),账户缓存见 [app-server](app-server.md)--## 并发与过期结果--| 手段 | 保护范围 |-| --- | --- |-| `MainActor` | UI、控制器及可观察状态的提交顺序 |-| actor | 服务进程内的共享状态和 I/O 协调 |-| `NSLock` 等锁 | 非隔离 pipe reader 等同步接口的可变状态 |-| `flock` | Hook 子进程、主 App、Debug 与 Release 之间的共享文件事务 |--异步调用返回时,配置或 reader 可能已经变化。不能取消的系统回调通过 generation 校验后才提交;请求取消与代际检查各自处理任务生命周期和结果归属。--菜单淡入淡出的完成任务在取消检查后同步提交,因此只保存一个可取消 Task。XPC、reader 更换和系统唤醒路径仍需 generation;各路径的具体字段见对应专题。--Combine 的 `@Published` 在 `willSet` 发布。组合设置状态时使用订阅闭包收到的新值,避免回读尚未更新的属性。--## 可重建数据与恢复记录--Hook 原始 JSONL 是历史重建来源,日聚合是派生结果。聚合语义变化通过 schema 递增触发保留期内完整重建。文件替换由 `sourceGeneration` 区分,同日同源数据按替换合并,独立来源才累加。--Token 账本以线程和轮次组成稳定身份,累计快照去重后按根轮次开始日汇总。显式重建先完成本机扫描,再提交所选日期的已读轮次;`rebuiltAt` 使更小的修正值优先于旧副本。缺失原始文件的轮次保留已有统计,其他设备的独有轮次保留在同步缓存中。字段和合并规则见 [Rollout Token 历史](sync.md#rollout-token-历史)--异常会话保护记录和 helper ownership 则用于恢复已经发生的状态变化。前者异步保存,隐藏不等待落盘;后者必须先持久化恢复责任,再修改系统睡眠值。具体顺序见 [实时任务监控](activity-monitor.md) 和 [防睡眠系统](sleep-prevention.md)--## 特权与上传范围--任务识别、自动重置策略和网络访问在主 App 中执行。root helper 只接受固定的睡眠租约与唤醒操作,通过签名校验客户端,并回读系统结果。--CloudKit 同步日级活动聚合与线程轮次 Token 记录,轮次标识由 thread ID 和 turn ID 组合后计算哈希生成。原始事件、原始会话标识、账户和代理密码留在本机;项目显示名属于上传内容,必须由用户开启同步。字段和存储范围见 [数据与隐私边界](data-and-privacy.md)diff --git a/Docs/DeveloperGuide/development.md b/Docs/DeveloperGuide/development.mddeleted file mode 100644index 70e89a4..0000000--- a/Docs/DeveloperGuide/development.md+++ /dev/null@@ -1,147 +0,0 @@-# 开发与验证--简体中文 | [English](../en/DeveloperGuide/development.md)--## 环境与构建--需要 macOS 15+、Xcode、Swift 6、`swiftformat` 和 `swiftlint`。唯一 scheme 为 `CodexBar`,包含 App、`CodexBarHelper` 和 `CodexBarTests` target。--```bash-xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build-xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'platform=macOS' test-swiftformat .-swiftlint-```--格式配置见 `.swiftformat`,使用 Swift 6 和 4 空格缩进。`swiftlint` 检查 `CodexBar/` 和 `CodexBarTests/`,不覆盖 `Shared/`、`CodexBarHelper/` 和 `Scripts/`--修改前检查 `git status --short`。已有未提交改动时,仅格式化本次涉及的 Swift 文件,或使用 `swiftformat --lint . --cache ignore` 检查。`swiftlint --no-cache` 可避免写入缓存。--日常构建不需要 Developer ID 或公证凭据。写作、Git 和兼容性规则见 [AGENTS.md](../../AGENTS.md)--## 单元测试--`CodexBarTests` 使用 Swift Testing,并加入共享的 `CodexBar` scheme,可用 Xcode 的 Test 操作或上述命令执行。--测试 target 无 App 宿主,与 App 使用相同的 Swift 6、`MainActor` 和并发设置,直接编译 `CodexBar/` 与 `Shared/` 源码。`CODEXBAR_TESTING` 仅在测试 target 定义,用于移除 `@main`;测试不实例化 App,不启动 Codex、CloudKit 同步或 helper。这样无需为测试拆分生产模块,代价是测试构建会额外编译一份 App 源码。--| 测试范围 | 关键约束 |-| --- | --- |-| Hook 与 JSONL | 名称归一化、坏行隔离、元数据读取预算、半行补齐、bootstrap 与 live 分流、文件替换 |-| 实时任务 | 匿名身份、时长、乱序进展、子 Agent 计数、各执行归属独立的审批状态 |-| rollout 生命周期 | 完成与进展、读取覆盖、损坏行、文件丢失或替换、归档定位 |-| 本轮 Token | 计数校验、主子线程归属与去重、运行中更新、结束后补读、轮次隔离、溢出和零值 |-| Token 历史 | 跨午夜归属、增量续读、回放日志、重建降低或清除计数、缺失文件保留、云端修正恢复、取消与跨实例锁 |-| 聚合与同步模型 | ID 去重、事件对计数、缺失计数、增量与重放一致性、同设备 generation 去重 |-| 持久化与设置 | 保护记录过期、跨实例合并、条件删除、旧记录默认值、配置损坏与回填 |-| 额度、代理与展示 | 凭证筛选、稳定 UUID、实际运行版本、代理输入和环境变量、日期与热力图状态 |-| 异步刷新 | 取消和代际过期后不提交结果、不结束较新的刷新 |--每个文件测试创建独立临时目录,每个偏好测试创建独立 `UserDefaults` suite,并在结束时清理。测试使用固定时间、显式日历和受控异步检查点;新增测试应沿用这些隔离方式。--单元测试不覆盖真实 CloudKit、app-server、系统通知、窗口焦点和 helper 电源行为。这些流程仍按下方手动场景验证。--## 修改入口--| 功能 | 主要位置 | 实现说明 |-| --- | --- | --- |-| app-server、代理、自动重置 | `Services/CodexStatus` 与对应 Settings | [app-server 数据链路](app-server.md) |-| Hook 安装与统计 | `AdvancedModeSettings`、`WorkflowService`、聚合模型 | [Hook 采集与历史聚合](hook-and-aggregation.md) |-| 实时任务与异常保护 | `CodexActivityMonitor` 和 readers | [实时任务监控](activity-monitor.md) |-| 防睡眠与系统唤醒 | `KeepAliveController`、`AutoResetWakeScheduler`、helper | [防睡眠系统](sleep-prevention.md) |-| 通知与音效 | `CodexNotificationService`、通知 Settings | [通知系统](notifications.md) |-| Token 历史与同步 | `CodexTokenHistoryStore`、`CodexTokenHistorySync` 与 `CodexTokenTurn` | [Rollout Token 历史](sync.md#rollout-token-历史) |-| Hook 同步 | `WorkflowSyncService` 与 scheduler | [CloudKit 同步](sync.md) |-| 菜单、窗口、快捷键 | `Controllers` 与对应 View | [UI 与应用生命周期](ui-and-lifecycle.md) |--长期对象由 `CodexBarAppDelegate` 装配。新增状态优先放入现有所有者,View 消费快照并发出操作意图。源码阅读入口见 [整体架构](architecture.md)--## 变更检查--涉及持久化 key、schema、身份计算、最低系统版本或新旧版本共存时,先说明影响和可选兼容方案,等待用户选定。新增网络访问、日志字段或 CloudKit 字段时核对 [数据与隐私边界](data-and-privacy.md)--聚合算法、输出字段含义或去重规则变化时,递增 `WorkflowMaintenanceState.currentAggregationSchema`,从保留期内原始 JSONL 完整重建,不增加字段级历史迁移。--异步修改需要检查取消、结果提交时的资格和 generation。跨进程文件仍使用 `flock`;actor 只保护单进程。`@Published` 订阅使用闭包的新值参与判断,避免 `willSet` 阶段回读旧属性。--## 验证流程--1. 检查修改范围,确认未覆盖已有工作-2. 格式化并运行 `swiftlint`-3. 构建 App 与 helper,并运行单元测试-4. 手动验证受影响的正常、失败和恢复流程-5. 检查文档及 `git diff --check`--构建失败时先定位第一条实际 `error:`。签名或 entitlement 错误要核对 Debug/Release 身份;helper 协议修改同时检查两个 target 与 `Shared`。编译和静态检查不覆盖窗口焦点、系统授权或硬件电源行为。--纯文档修改运行格式检查、lint 和构建,并检查相对链接与中英文内容。--### 手动场景--| 改动范围 | 重点场景 |-| --- | --- |-| 菜单与窗口 | 快速开关、淡出中重开、popover/fallback、多屏与 Space、设置和日志焦点、通知点击和快捷键 |-| Hook 与聚合 | 保留已有 handler、最低版本、并发追加、半行和损坏行、文件替换与截断、完整重建 |-| 实时任务 | bootstrap 不补通知、等待审批、迟到终态、匿名任务、唤醒读取屏障失败与恢复 |-| 通知 | 授权拒绝与恢复、阈值跨越、同周期去重、任务恢复撤回、声音缺失 |-| 代理 | 首次配置、启停、无效配置停用、损坏记录删除、测试取消、快速操作与失败回滚 |-| 同步 | 首次上传、多设备合并、断网续传、部分上传失败、重建替换、iCloud 账户切换 |-| Token 回放与重建 | 大量历史断点续读、后台重建时使用主面板、关闭设置窗口、退出后自动回放与手动重建的区别、修正值跨设备收敛 |-| 系统电源与 helper | 首次授权、任务运行/等待切换、低电量、时长上限、外部睡眠来源、异常退出与重启 |-| 自动重置唤醒 | 计划替换、关闭与退出清理、连接中断、helper 重启、注销前清零、到点重新读取 |--helper 改动还需检查 App 包内可执行文件和 plist 的位置、签名与注册指纹。各专题末尾列出更细的状态转换场景。--记录验证使用的构建、前置设置、操作序列、实际结果和相关日志,便于复现。--### 性能验证--CPU、内存、唤醒、磁盘活动与采集环境见[性能报告](https://codexbar.zabrian.app/performance)--结果对应报告中记录的构建和测试场景。采集、生成报告和基线对比方法见[性能采集工具说明](../../Scripts/performance/README.md)--## Debug 与 Release--| 配置 | App bundle ID | Helper bundle ID |-| --- | --- | --- |-| Debug | `app.zabrian.codexbar.debug` | `app.zabrian.codexbar.helper.debug` |-| Release | `app.zabrian.codexbar` | `app.zabrian.codexbar.helper` |--App 偏好和系统授权按身份隔离,Hook 数据与异常会话保护文件共享。排查时确认正在运行的 App、helper 和已安装 Hook 的可执行路径。--## 日志--Release 系统日志:--```bash-/usr/bin/log stream --predicate 'subsystem == "app.zabrian.codexbar"' --style compact-```--Debug 使用 `app.zabrian.codexbar.debug`,helper 的 subsystem 使用对应 helper bundle ID。--App 内日志窗口保留最近 500 条 app-server 交互。代理配置错误在系统日志的 `settings` 分类中,临时代理测试不写交互日志。--| 问题 | 查看内容 |-| --- | --- |-| 额度未刷新 | handshake、method、retry、stale |-| Hook 未生效 | hooks 配置、版本、信任与完整性 |-| 任务未结束 | reader generation、rollout 对账、数据源健康 |-| 同步缺数据 | zone、fetch、upload、replacement、prune 阶段 |-| 通知未出现 | authorization、kind、duplicate、obsolete |-| 防睡眠未生效 | block reason、helper 注册、XPC generation、source |-| 自动重置未执行 | target、threshold、retry window、wake schedule |--日志使用 `LogTrigger`、`LogDuration` 和 `LogFields.joined`,记录阶段、分类、计数及耗时。请求内容和身份信息的限制见 [数据与隐私边界](data-and-privacy.md)--## 发布与清理脚本--| 脚本 | 用途 |-| --- | --- |-| `Scripts/build.sh` | Release archive、Developer ID 导出、公证、staple 与 Gatekeeper 校验 |-| `Scripts/dmg.sh` | 打包 DMG |-| `Scripts/appcast.sh` | 签名更新并生成 appcast |-| `Scripts/cleanup.swift` | 注销 helper;先退出所有 CodexBar 实例,`--check` 只检查,`--debug` 或 `--release` 限定范围 |--发布脚本需要签名和公证凭据,不用于日常验证。版本号从 [`Version.xcconfig`](../../Config/Version.xcconfig) 读取。--helper 清理先取消并确认系统唤醒计划清零,再注销服务;失败时停止。详细行为见 [防睡眠系统](sleep-prevention.md)diff --git a/Docs/DeveloperGuide/hook-and-aggregation.md b/Docs/DeveloperGuide/hook-and-aggregation.mddeleted file mode 100644index 439729e..0000000--- a/Docs/DeveloperGuide/hook-and-aggregation.md+++ /dev/null@@ -1,477 +0,0 @@-# Hook 采集与历史聚合--简体中文 | [English](../en/DeveloperGuide/hook-and-aggregation.md)--## 链路职责--Hook 链路把 Codex 生命周期事件转换为可重建的本地历史统计:--```text-Codex Hook- -> CodexBar --hook-event- -> 原始 JSONL- -> WorkflowService 增量聚合- -> daily.jsonl- -> 活跃度 UI 和 CloudKit 同步-```--原始事件是事实来源,日级聚合是可重建缓存。聚合算法或字段语义变化时,必须从保留期内的原始事件完整重建。--## 安装与校验--[`AdvancedModeSettings.swift`](../../CodexBar/Services/Settings/AdvancedModeSettings.swift) 直接读写本地 `hooks.json`,通过 app-server 读取或修改相关配置,并在写入后调用 `hooks/list` 校验安装结果。--启用流程检查以下条件,其中来源、信任和事件完整性在写入后校验:--- 当前可执行文件路径可解析-- 实际 app-server 版本不低于 `0.153.0`-- `features.hooks` 可用-- `hooks/list` 返回可信来源-- 所需事件集合完整--目标配置文件位于 `$CODEX_HOME/hooks.json`,未设置 `CODEX_HOME` 时位于 `~/.codex/hooks.json`--安装逻辑把 CodexBar handler 作为独立命令加入现有配置。它不会用一份模板覆盖整个文件:--- 保留用户已有字段-- 保留其他应用已有 handler-- 只更新与当前可执行文件和 `--hook-event` 匹配的 handler-- 禁用时只移除精确匹配的 CodexBar handler-- 无法识别的配置保持原样--`isEnabled` 表示当前进程中的开启状态,首次从已有 CodexBar handler 恢复。`isVerified` 默认 `true`,随后保存最近一次明确校验结论。实时任务和相关功能使用两者合取的 `isOperable`;历史聚合和同步按 `isEnabled` 消费已落盘数据。--### 校验状态--`hooks.json` 中有 handler 不代表 Codex 会执行。`isOperable` 由开启状态和最近明确校验结果共同决定。临时 RPC 失败保留上次结论并显示操作错误;版本、全局开关、来源、信任或事件集合不满足要求时校验失败。--### 已开启 Hook 的对账--App 启动、设置状态刷新、主面板打开和每轮额度刷新完成时,都会对账已开启的 Hook。自动刷新按所选数据更新间隔从上一轮完成后计时,默认 1 分钟:--- 只有已确认的实际 app-server 版本低于当前 Hook 最低版本时,才移除 CodexBar handler 并尽力清理对应信任项;低于全局最低版本时也执行本地移除-- 版本无法确认或 RPC 临时失败时保留用户配置-- 配置在当前进程中丢失不会关闭开关,而是标记配置损坏并触发自愈-- 版本受支持时遍历 `CodexHookEvent.allCases`,为缺失或非标准事件重建独立 group,然后复用信任和完整性校验-- 信任项缺失或哈希变化时,只修复 `command`、`sourcePath` 和 `event` 都属于当前 CodexBar 的条目-- 必需事件全部存在时不写 `hooks.json`--对账比较必需事件集合与配置文件,补齐缺失 handler。启动时没有可识别的 CodexBar handler 则保持关闭。--### 启用事务的顺序--```text-确认运行中 app-server >= 0.153.0- -> 确认 features.hooks 没有全局关闭- -> 读取现有 hooks.json- -> 只移除当前 executable 的旧 CodexBar handler- -> 为全部事件追加独立 group- -> 原子写回 hooks.json- -> hooks/list 读取 app-server 实际解析结果- -> 仅信任 command + sourcePath + event 都匹配的条目- -> 再次 hooks/list 完整校验-```--信任匹配同时要求 command 和 `sourcePath`。只按 executable 匹配可能误信任另一份配置中的相同命令,只按 source 匹配则可能碰到用户自己的 handler。--### 禁用与信任清理--app-server 的 Hook key 来自它当前解析到的 handler。如果先从 `hooks.json` 删除命令,后续 `hooks/list` 已经无法反查对应 key。--因此禁用流程先保存精确匹配条目的 key、再删 handler、最后从 `hooks.state` 中清理这些 key。清理时先读取完整 state 再 replace,保留用户和其他工具的信任项。--低于全局最低版本时,app-server 连接已被拒绝,禁用流程直接移除本地 handler,保留无法查询和删除的信任项,不额外显示信任清理提示。其他情况下,信任查询或清理失败显示无法清理信任状态的提示,Hook 保持关闭。本地配置移除失败仍显示错误,并在后续对账时重试。--### 事件分组--CodexBar 不把命令塞进用户已有 group。独立 group 让卸载时可以只删除自身 handler,不需要理解用户 matcher 或其他 handler 之间的组合语义。--移除时跳过结构异常的同级条目,只处理能精确识别的 CodexBar 命令。--### 异步设置操作的代际--用户开关进阶模式或触发校验时,`AdvancedModeSettings` 通过 `updateCoordinator` 启动操作,由 `RefreshTaskCoordinator` 推进代际并取消旧 Task。--每个文件写入或 RPC await 之后都会再次检查 generation。旧操作即使无法真正取消,也不能把新的开关状态或错误信息覆盖回去。--## 支持的事件--CodexBar 订阅以下 Hook 事件:--| 事件 | 聚合或实时用途 |-| --- | --- |-| `SessionStart` | 建立 session 生命周期 |-| `SessionEnd` | 结束 session |-| `UserPromptSubmit` | 建立 turn 和任务起点 |-| `PreToolUse` | 记录工具调用开始 |-| `PostToolUse` | 记录工具调用结束 |-| `PermissionRequest` | 识别用户批准等待 |-| `PreCompact` | 记录上下文压缩开始 |-| `PostCompact` | 记录上下文压缩结束 |-| `Stop` | 形成任务完成候选 |-| `Interrupt` | 结束对应 turn 并记录中断统计 |-| `SubagentStart` | 记录 subagent 启动 |-| `SubagentStop` | 记录 subagent 结束 |--### 事件字段和用途并不完全相同--历史计数需要事件名、日期、project、model 和身份集合。实时状态还需要 turn, reviewer, effort, tool, agent 关联和归一化来源。--recorder 将两类链路所需字段写入同一条原始记录,历史聚合与实时监控分别读取各自需要的字段。--recorder 为来源分类有界读取 rollout 首行。普通事件使用 `transcript_path`,`SubagentStop` 使用指向子线程自身的 `agent_transcript_path`。rollout 来源无法确定时,只有精确匹配 `codex-auto-review` 的 model 才作为 Auto-review 来源的后备判定。`PermissionRequest` 和 `UserPromptSubmit` 的 reviewer 或 effort 可能不在 Hook payload 中,只有这两个事件还会按 turn 定向读取 rollout 尾部。--## Hook 子进程--[`WorkflowHookEventRecorder.swift`](../../CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift) 在 App 启动最早阶段检查 `--hook-event`--命中后只执行以下工作:--1. 从 stdin 读取事件 JSON-2. 提取统计和状态机需要的最小字段-3. 获取文件锁-4. 追加一条完整 JSONL-5. 在同一个锁事务中标记维护状态-6. 立即退出--handler 超时由事件决定:--| 事件 | 超时 |-| --- | --- |-| `SessionEnd`、`Interrupt` | 3 秒 |-| 其他事件 | 5 秒 |--锁等待预算为 handler 超时减 2 秒。获取锁时从 1 ms 开始指数退避,单次等待最多 20 ms。--### 失败退出--进入 `--hook-event` 后,无效输入、锁超时和写入错误均以成功状态退出,避免采集失败阻断 Codex。--### 事件与维护状态的锁内事务--一次采集在同一把 `stats.lock` 内完成:--```text-检查当前文件身份- -> 必要时开始新 source generation- -> append 完整 JSONL 行- -> 标记该日期 pending- -> 原子保存 maintenance.json-```--如果 append 和 pending 分成两个锁事务,App 可能在中间完成一次维护并认为当天已经追平。随后 recorder 只写事件却来不及标记 pending,新行会静默等待到下一次全目录对账。--锁内联合提交让“文件已经增长”和“维护知道需要读取”保持一致。--### 锁文件创建--不能先判断文件不存在,创建后再打开。两个进程可能分别创建不同 inode,后创建的一方替换目录项后,双方会各自锁住不同文件并都认为自己独占。--单次 `open` 让创建和打开成为同一个原子入口,所有参与者对同一路径上的同一 inode 使用 `flock`--## 采集字段--原始记录只保留计算统计和实时状态所需的信息:--- 时间戳和事件名-- 工作目录-- tool 名称-- model 和 reasoning effort-- permission 与 approval reviewer-- session ID 和 turn ID-- agent ID-- 归一化来源 `origin`--对于 `UserPromptSubmit` 和 `PermissionRequest`,输入事件可能不包含 reviewer 或 effort。recorder 会在必要时从 rollout transcript 尾部回查匹配的 `turn_context`--回查范围如下:--- 单次最多读取 8 MiB-- 只提取 reviewer 和 effort 等结构字段-- 不把 prompt 或 response 内容写入 Hook 统计--### 来源归一化--`WorkflowHookEvent.origin` 是 CodexBar 自己维护的有限枚举,不是 rollout 原始 `source` 的副本。构造器和解码器都在事件输入边界应用同一套来源解析规则,因此下游只读取归一化后的 `origin`:--| 有效来源 | 判定 |-| --- | --- |-| `main` | `source` 是已知顶层字符串来源 `cli`, `vscode`, `exec`, `mcp`,或有效对象来源 `{ "custom": "..." }` |-| `autoReview` | `source.subagent.other` 与 `guardian` 完全匹配,或 rollout 来源为 `unknown` 且 model 与 `codex-auto-review` 完全匹配 |-| `auxiliary` | `source` 明确表示其他 subagent,包括 `review`, `thread_spawn` 和 Memories 相关来源 |-| `unknown` | 字段缺失、结构损坏、无法读取或遇到未知顶层来源,并且 model 不满足 Auto-review 后备判定 |--来源读取从文件起点按 32 KiB 分块,总预算为 256 KiB。遇到首个 newline 时解码完整首行;首行尚未读完时,在完整字段边界构造可解码的元数据前缀。确认类型为 `session_meta` 且 `source` 已完整解码后即可返回,大型指令字段无需读完。预算内无法取得来源、记录类型不符或读取与解码失败时,rollout 来源回退到 `unknown`。model 后备判定只接受精确字符串。--recorder 在写入前完成来源解析,JSONL 的来源字段只保存上述枚举值。`transcript_path`、原始 `source`、任意 `other` 字符串和 transcript 内容都不会写入 Hook 文件或系统日志。--JSONL 中缺少 `origin`,或枚举值无法识别时,来源字段先解码为 `unknown`。`WorkflowHookEvent` 解码器随后应用相同的精确 model 后备判定,因此 `model == "codex-auto-review"` 的事件在内存中的 `origin` 为 `autoReview`。读取过程不会回填或重写原始 JSONL。--历史聚合按全部 Hook 事件统计,包含 `autoReview` 和 `unknown` 来源;聚合结果和 CloudKit 投影不包含来源字段。--### 输入归一化--Hook payload 在不同版本中可能把标识或时间表示为不同 JSON 类型。`WorkflowHookPayload` 集中做宽松归一化:--- string 会去掉首尾空白,空串转为缺失-- number 标识转换为字符串-- 时间同时接受 ISO-8601、本地 timestamp、Unix 秒和 Unix 毫秒-- 缺失时间回退到 recorder 当前时间-- 缺失 cwd 回退到子进程当前目录--宽松只发生在外部输入边界。一旦转成 `WorkflowHookEvent`,下游使用统一类型,不在聚合器和 monitor 中重复猜测协议差异。--### rollout 尾部回查的边界--回查只读取 transcript 最后 8 MiB、丢弃可能被截断的第一行,再从后向前寻找匹配 turn 的 `turn_context`--从后向前是因为同一个 turn 的最新上下文更接近文件尾。限制读取范围是为了守住 Hook 超时,找不到时保留字段缺失而不是扩大成无界扫描。--## 本地文件--默认数据根目录是:--```text-~/Library/Application Support/CodexBar/HookEvents/-```--目录结构如下:--```text-HookEvents/- events/- YYYY-MM-DD.jsonl- daily.jsonl- maintenance.json- stats.lock- Sync/- state.json- cache.jsonl- cursor.data-```--| 文件 | 作用 |-| --- | --- |-| `events/YYYY-MM-DD.jsonl` | 按天保存原始 Hook 事件 |-| `daily.jsonl` | 按日期和来源代际保存聚合结果 |-| `maintenance.json` | 保存待处理维护和 schema 状态 |-| `stats.lock` | 协调 Hook 子进程和 App 维护任务 |-| `Sync/*` | CloudKit 同步游标和缓存 |--原始事件和日聚合最长保留 210 天。session ID 和 turn ID 的明细列表只保留 3 天,更早日期压缩为计数,降低本地文件体积和身份信息留存。--### 完整行是提交单位--reader 只推进到最后一个 newline 对应的 offset。文件尾如果正在写入半行,本轮保留旧 offset,下一轮等完整行出现后再处理。--`JSONLines.decodeWithFailures` 按行解码。一条坏行只增加 corrupt count,不会连带丢掉同一读取块中的其他正确事件。--### 身份明细压缩--session 和 turn ID 用于近期精确去重,但长期展示只需要计数。--3 天后把 identifiers 压缩为 count。累加器在 `finalized(identifierStorage:)` 中选择保留 ID 列表或只保存计数;`retained` 和 `compacted` 是此次输出的选择,不是单独持久化的模式字段。--## 增量读取与来源代际--聚合器记录每个原始文件的 inode, size, offset 和 source generation:--- 正常追加时从上次 offset 继续读取-- inode 改变表示文件被替换-- size 小于 offset 表示文件被截断-- 替换或截断会创建新的 source generation--source generation 让同一天的不同原始来源可被区分。同源结果按替换处理,明确独立的 generation 可以累加,用户完整重建则通过同步层的 replacement 标记声明旧 generation 全部失效。--### `pending` 和 `dirty` 的区别--`maintenance.json` 对每个日期维护以下待办:--| 状态 | 何时使用 | 下一步 |-| --- | --- | --- |-| `pending` | 已确认是同一来源上的正常追加 | 从旧 offset 增量聚合 |-| `dirty` | 来源变化、schema 变化、缓存缺失或上次处理失败 | 从文件起点完整重建 |--`dirty` 优先于 `pending`。同一天同时出现在两个集合时只生成重建任务,避免先追加到旧聚合再完整覆盖。--这种显式状态比通过 `offset == 0` 猜测任务类型更安全。全新空文件、被截断文件和主动重建都可能具有 offset 0,但它们的 source generation 和同步语义不同。--### 如何判断文件还是同一来源--维护层综合以下证据:--- inode 标识是否变化-- 当前 size 是否小于已处理 offset-- 当前 size 是否与维护记录的上次 size 一致-- offset 前 4 KB 的 boundary hash 是否仍匹配--inode 与 size 能发现替换和截断,boundary hash 能发现保持相同长度的原地改写。--### Boundary hash 与 mtime--每轮都给 210 天内所有文件重算 hash 会长时间持有 `stats.lock`,直接增加 Hook recorder 的等待概率。--维护状态记录上次验证 boundary 时的 nanosecond mtime。inode, size 和 mtime 都没变化时直接跳过 hash。文件变化后才重算 offset 前 4 KB。--正常 append 只修改 offset 之后的字节,所以 boundary 仍匹配,maintenance 可以继续增量处理。boundary 改变则创建新 generation 并标脏。--### 构建与提交校验--聚合器不能在读取整天文件时一直持有 `stats.lock`,否则 Hook 子进程可能连续超时。--实际流程是:--```text-锁内 prepare- -> 固定 sourceGeneration, inode, startOffset 和读取上界-解锁后 build- -> 分块读取并生成候选 aggregate-锁内 validate- -> generation 仍相同- -> inode 仍匹配- -> 候选上界仍存在- -> boundary hash 仍匹配-提交 daily.jsonl-锁内再次 validate 并推进 maintenance offset-```--读取期间允许 recorder 继续 append。只要候选上界之前的字节没变,本次结果仍然有效,新增尾部会保留为下一轮 pending。--如果来源在 build 期间被替换,候选结果不会提交,maintenance 会开始新 generation 并等待重建。--## 聚合规则--日级结果包括:--- Hook 事件总数和各事件计数-- session 数和 turn 数-- tool call 数-- compaction 数-- subagent 数-- project 分布-- model 分布--session 数使用当天除 `SessionEnd` 外所有事件中的非空 session ID 去重计算。turn 数使用当天除 `Stop` 和 `Interrupt` 外所有事件中的非空 turn ID 去重计算。跨天 session 或 turn 只要当天仍有未被排除的事件,就计入当天;当天只有 `SessionEnd` 的 session 和只有 `Stop` 或 `Interrupt` 的 turn 不计入。--成对事件可能只有一侧成功落盘。因此计数使用能够避免重复且允许缺失的规则:--- tool call 使用 `max(PreToolUse, PostToolUse)`-- compaction 使用 `max(PreCompact, PostCompact)`-- subagent 使用 `max(SubagentStart, SubagentStop)`--字段缺失与数值 `0` 的含义不同:--- 缺失表示该日期的历史来源无法提供该指标-- `0` 表示来源可用且明确没有发生--解码和持久化保留可选值。`WorkflowDailyMetrics` 保留 `interruptCount` 的缺失值,其他单项事件计数缺失时显示为 `0`;session 和 turn 计数优先使用 ID 去重结果或已压缩计数,再回退到对应事件计数。--### 成对事件计数--`PreToolUse` 和 `PostToolUse` 描述同一次工具调用的两侧。recorder 允许失败后,任意一侧都可能缺失:--- 相加会把完整的一次调用统计为 2 次-- 只看 pre 会漏掉 pre 写入失败而 post 成功的调用-- 只看 post 会漏掉工具开始后进程中断的调用-- `max(pre, post)` 在没有稳定 call ID 时给出最不容易重复的估计--compaction 和 subagent 成对事件使用相同规则。--### 计数可用性--`WorkflowHookCountAvailability` 保存每类计数的来源可用性。重建继承已有日期的可用性;没有聚合时使用 `.legacy`,其中 `interruptCount` 为不可用,其他事件计数从 `0` 开始。实际读到 `Interrupt` 后,中断计数从缺失变为正数;其他事件保留其缺失值。--`interruptCount` 在展示投影中仍为可选值,同日任一贡献缺失时合计也不可用。热力图详情不展示此指标。--## Schema 演进与重建--当前聚合 schema 为 `9`,由 `WorkflowMaintenanceState.currentAggregationSchema` 管理。--以下变化必须递增 schema:--- 原始事件到聚合结果的算法变化-- 输出字段增删-- 字段含义变化-- 去重规则变化-- 来源代际合并语义变化--schema 不一致时,从 210 天保留期内的原始 JSONL 完整重建,不执行字段级历史迁移。--用户手动重建时也走同一条完整重算路径,并向同步层标记需要替换的日期。--### aggregation schema 与 source generation 不同--| 标识 | 描述 | 何时变化 |-| --- | --- | --- |-| aggregation schema | 当前代码如何从原始事件计算聚合 | 算法、字段或语义变化 |-| source generation | 某一天的原始文件属于哪一代来源 | 替换、截断、主动重建或边界改写 |--schema 变化通常把保留期内所有事件日期标脏。source generation 变化只影响具体日期。--两者都不能用 App 版本号替代。一个 App 版本可能不改变聚合,开发构建也可能在不变更版本号时多次迭代 schema。--### 重建来源--聚合语义变化后使用原始 JSONL 完整重建。旧聚合已经丢失的身份或事件关系无法靠补字段恢复;只有原始来源缺少字段时,才保留 missing 语义。--### 用户手动重建的提交语义--批量重建按日期独立处理。单日失败不会阻断已经成功的日期,失败日期会标脏交给常规维护继续尝试。--成功和失败日期都会先登记 CloudKit replacement。原因是失败日期已经进入新 generation,后续自动重建成功时会使用新 record identity。如果没有提前标记,旧 generation 可能留在云端与新值叠加。--只有所有日期都失败时,操作整体返回失败。部分成功会返回详细 summary,包括成功日期、损坏行和 replacement pending 状态。--## 维护调度--[`WorkflowService.swift`](../../CodexBar/Services/Workflow/WorkflowService.swift) 是 actor,串行执行读取、聚合、清理和重建。--维护任务与额度刷新周期协调,但两条数据链路没有数据依赖。Workflow ViewModel 对 UI 的最短刷新间隔为 5 秒,避免频繁文件变更造成重复渲染。--### 维护日志--`WorkflowService` 累计连续 idle 轮数,在写入、跳过、失败或清理时输出摘要,并附带累计空转次数。--### scheduler 如何合并请求--`WorkflowSyncScheduler` 串行处理以下请求:--1. 用户重建,优先级最高-2. 带同步的维护-3. 仅本地维护--同步完成后有 8 秒冷却。冷却期间的多个请求合并成一次,并保留最先到达的 trigger 作为真正起因。--UI 打开只读取当前本地快照,不自动越过 scheduler 发起无条件 CloudKit 请求。--## 建议验证的故障场景--- 多个 Codex session 并发写入时每行完整且无覆盖-- 主 App 持锁时 Hook recorder 能在预算内成功或安全放弃-- stdin 非 JSON 或缺少 event name 时子进程仍立即成功退出-- 文件尾半行不会推进 offset,补全后下一轮能读取-- 单条损坏 JSONL 只增加 corrupt count-- inode 变化、文件缩小和 boundary 改写都触发新 generation-- build 期间继续 append 时只提交固定上界,尾部保留 pending-- schema 变化后保留期内日期全部用当前算法重建-- 旧日期缺失字段在解码及持久化中保留可选值,展示投影按当前回退规则生成计数-- 关闭进阶模式不删除用户 handler 和信任项-- 快速开关 Hook 时旧 RPC 结果不能覆盖最后一次操作--## 故障边界--- 单条损坏 JSONL 不应让整个保留期不可读-- 文件来源改变后不能继续使用旧 offset-- 重建失败时保留最后一份可用聚合-- 维护中断不能把部分结果当作完整日期提交-- Hook 不可用时 UI 应表达来源不可用,而不是清空为 `0`-- 配置写入失败不能破坏原有 handler--## 关键源码--- [`AdvancedModeSettings.swift`](../../CodexBar/Services/Settings/AdvancedModeSettings.swift)-- [`WorkflowHookEventRecorder.swift`](../../CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift)-- [`CodexHookEvent.swift`](../../CodexBar/Models/CodexHookEvent.swift)-- [`JSONLines.swift`](../../CodexBar/Services/Workflow/JSONLines.swift)-- [`WorkflowService.swift`](../../CodexBar/Services/Workflow/WorkflowService.swift)-- [`CodexWorkflowModels.swift`](../../CodexBar/Models/CodexWorkflowModels.swift)diff --git a/Docs/DeveloperGuide/notifications.md b/Docs/DeveloperGuide/notifications.mddeleted file mode 100644index c03e222..0000000--- a/Docs/DeveloperGuide/notifications.md+++ /dev/null@@ -1,301 +0,0 @@-# 通知系统--简体中文 | [English](../en/DeveloperGuide/notifications.md)--## 职责--[`CodexNotificationService.swift`](../../CodexBar/Services/Notifications/CodexNotificationService.swift) 是通知副作用的统一入口。--它接收以下状态:--- app-server 账户与额度快照-- `CodexActivityMonitor` 任务转场与异常会话保护候选-- `KeepAliveController` 防睡眠恢复结果-- `AutoResetController` 已确认的消费结果或需要告知用户的失败状态--## 设置与系统授权--`NotificationSettings` 分开保存 App 内意图与 macOS 授权:--| 状态 | 含义 |-| --- | --- |-| `isEnabled` | 用户在 CodexBar 内打开总开关 |-| `authorizationStatus` | 系统是否允许通知 |-| `canDeliver` | 两者同时允许后的实际资格 |--总开关默认关闭,用户开启时才请求系统授权。--App 激活、设置窗口重新获得焦点或显式打开时会重新读取系统状态。系统返回 `denied` 时保留 App 内的通知开关,显示灰色未授权提示和“打开系统设置”按钮。实际查询返回 `notDetermined` 时关闭 App 内开关,用户再次开启后重新申请授权;初始化时的占位值不修改已保存的开关。--授权请求期间不重复发起请求,焦点变化也不会取消正在等待用户回应的请求。只要 App 内开关开启且系统尚未授权,就显示未授权提示。请求结束后若系统仍返回 `notDetermined`,开关恢复关闭,允许用户再次开启重试。--授权请求结束后,权限读取统一走普通刷新流程。查询期间再次收到焦点刷新时,新查询替换旧查询,旧结果不会覆盖最新权限状态。--触觉反馈不依赖 `UNUserNotificationCenter` 授权,但仍服从 App 内总开关。--## 通知开关--通知总开关默认关闭。各可配置分类的子开关默认开启,触觉反馈默认关闭。--总开关关闭时不会申请系统通知权限,也不会发送任何分类通知。子开关用于在总开关开启后选择具体类型:--| 分类 | 数据来源 | 控制条件 |-| --- | --- | --- |-| 额度重置 | app-server 额度窗口 | 独立子开关 |-| 低额度 | app-server 剩余额度 | 独立子开关和阈值 |-| Reset Credits 到期 | app-server 重置凭证明细 | 独立子开关 |-| 自动重置 | 已确认消费结果或需要告知用户的失败状态 | 自动重置开关、独立通知子开关和通知总开关 |-| 任务完成 | 实时任务 terminal 转场 | 独立子开关和最短时长 |-| 等待批准 | 实时任务 waiting 转场 | 独立子开关 |-| 异常会话保护 | Activity Protection | 防睡眠主开关和通知总开关 |-| 低电量保护停止 | KeepAlive 恢复结果 | 独立子开关,仅在保护可用时启用 |-| 防睡眠达到上限 | KeepAlive 恢复结果 | 独立子开关,仅在有限时长时启用 |--异常会话保护跟随防睡眠主开关,通知服从总开关和系统授权,没有独立通知子开关。低电量和时长上限的通知偏好会保留,对应保护条件不可用时 UI 显示为关闭并置灰。--## 额度重置--额度重置通知需要先观察到窗口被消费,再观察到新窗口恢复为未消费状态。--判断状态按账户和额度窗口隔离。账户变化时不把前一账户的消费状态延续到新账户。--每个额度窗口还带一个会话内 lifecycle token。窗口从可信快照消失后再出现会得到新 token。如果旧窗口的通知提交失败回调迟到,只有 token 仍相同时才把 `hasObservedConsumption` 恢复为 true。--重置状态不持久化。App 每次启动后重新观察消费和归零,不补发离线期间发生的重置通知。--## 自动重置--自动重置操作和额度窗口重置是两个独立事件,因此保留两条通知:--- “自动重置”说明 CodexBar 的自动操作收到 `reset` 或 `alreadyRedeemed`-- “额度已重置”说明普通额度快照先观察到消耗,随后观察到归零--一次自动重置可能同时满足两者,同一台设备可以先后收到两条通知,分别服从各自的开关。--成功通知正文优先带上消费后新鲜读取的剩余重置次数,包括明确的 `0`。后置读取失败时仍保留已经明确的成功结果,并发送只有标题、没有正文的通知。--`alreadyRedeemed` 表示相同幂等键此前已经成功,不应继续重试。多台设备同时调用时,每台明确收到 `reset` 或 `alreadyRedeemed` 的设备都可以发送本机成功通知。某台设备只在刷新中看到凭证消失时无法区分手动使用、其他设备使用或过期,因此静默停止,不发送成功通知。--失败通知使用“自动重置失败”,当前包括:--- 单次认证刷新后仍未登录,当前凭证暂停到可信快照证明认证恢复-- 参数、协议或方法错误,当前凭证停止重试-- 本机明确观察到目标已经过期,当前凭证停止重试--短暂网络和服务错误只进入退避重试,不在每次失败时打扰用户。同一凭证的同一失败原因最多通知一次;认证、永久错误和本机明确观察到的过期使用不同去重键,因此同一凭证可能先后出现不同失败通知。目标从服务端明细消失时无法判断原因,状态机会静默停止,不补发过期通知。--成功和失败通知共用“自动重置通知”子开关及声音,默认开启并使用系统默认声音。自动重置功能关闭时设置行置灰,但不覆盖已经保存的通知和声音选择;重新开启后恢复原值。--## 低额度--低额度阈值可选 5%, 10% 或 25%,默认 10%。--持久化去重 key 保留 app-server 返回的秒级重置时间。相同账户和额度窗口的重置时间与已记录值相差不超过 60 秒时视为同一周期,只有差值超过 60 秒才视为新的重置周期。--额度恢复到阈值上方后会重新启用穿越判定,但同一重置周期仍只通知一次。进入新的重置周期后,下一次向下跨越可以再次通知。--### 阈值穿越判定--服务为每个 `account + limit + window` 保存上一帧剩余比例,按以下规则判定通知:--- 上一帧高于阈值且当前不高于阈值时发送-- 会话内第一帧已经不高于阈值时发送一次-- 一直停留在低区间时不发送-- 阈值设置变化时清除当前观察并立即按新阈值重判--设置订阅使用回调给出的新值。Combine 的 `@Published` 在 `willSet` 阶段发送,此时重新读取 settings 属性仍会得到旧值。这项实现细节是为了保证用户把阈值从 5% 改到 25% 时立即按 25% 判断。--stale app-server 快照不会推进上一帧,也不会触发低额度或重置。旧缓存只能用于展示连续性,不能成为一次新副作用的证据。--### 重置周期匹配--app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正。如果 dedup key 使用绝对相等,同一周期会被当成新周期再次通知。--服务在相同账户、limit 和 window 范围内寻找 60 秒容差内的已发送或正在提交 key,并复用原 key。容差只用于身份归一化,UI 仍展示服务返回的实际时间。--## Reset Credits 到期--当 Reset Credits 数量大于 `0` 且能够读取到期日时,通知服务在到期前 7 天到 1 天按天提醒。--去重 key 包含账户、到期日和剩余天数。同一天多次刷新不会重复发送。--服务只调度最近一个未来检查点,到点后根据当前快照重新计算并安排下一次。--这样做可以处理:--- Reset Credits 数量或到期时间被 app-server 更新-- 通知设置中途关闭-- Mac 睡过 deadline 后通过 wake observer 补检-- 多个相同到期秒的次数合并成一条通知--日期判断基于距到期的剩余秒数,7 天到 1 天分别有独立 dedup key。调度器只负责唤醒检查,最终资格仍由当前快照决定。--## 任务完成--任务通知只响应 monitor 发布的新 terminal 转场,不扫描历史列表推导:--- bootstrap 建立的历史任务不发送通知-- 终态任务键在活动监控层保留 24 小时去重-- 通知服务还维护自己的已发送 key-- `Stop` 保留正在收尾的任务;rollout 确认完成后,结束时间不早于恢复界限且距当前不超过 10 秒时发布完成转场-- bootstrap、恢复对账和 Hook 数据源不健康期间,完成记录静默更新-- `Interrupt` 和其他终止记录不触发完成通知或任务触觉反馈--匿名任务不会发布给任务通知消费者。通知服务在 transition 入口再次过滤 `isAnonymous`,因此匿名任务不发送完成或等待批准通知,也不触发任务触觉反馈。--任务完成最短持续时间可选 30, 60, 120 或 300 秒,默认 60 秒。持续时间较短的完成任务不会通知,但仍可以在 UI 中短暂展示。--触觉在每个 task transition 到达时启动,新 transition 会取消上一串 10 次脉冲并重新开始。每次脉冲前重新检查设置,用户关闭开关后不会继续完成旧序列。--## 等待批准--只有 `PermissionRequest` 的 reviewer 确认是用户时才发送等待批准通知:--- 自动审批不通知-- 同一任务连续等待期间只通知一次,其他 Agent 的进展不结束该等待;审批归属规则见 [等待批准的两阶段确认](activity-monitor.md#等待批准的两阶段确认)-- 任务离开等待状态后从相关集合移除-- bootstrap、恢复对账和 Hook 数据源不健康期间不发布等待转场-- Hook 直接确认和 rollout 补齐 reviewer 后确认均要求任务进入等待的时间不早于恢复界限且距当前不超过 10 秒--等待状态是否维持防睡眠是独立设置,不影响是否可以发送等待批准通知。--等待通知使用稳定 task ID 作为系统通知 identifier。服务同时观察活动快照:--- 提交前任务已经离开 waiting 时跳过-- `UNUserNotificationCenter.add` 成功后状态又变化时立即撤回-- 后续快照不再包含任务时同时移除 delivered 和 pending notification-- 提交失败时从内存相关集合移除,允许未来真实的新等待再次尝试--前后两次 relevance 检查覆盖了异步提交窗口。只在提交前检查仍可能让一个已经获批的任务在通知中心留下过时提醒。--## 异常会话保护--非匿名运行任务静默达到阈值时,Activity Protection 先更新内存保护记录并安排异步保存,再并行启动通知提交和 3 秒宽限。通知处理返回或宽限到期后,monitor 重新校验候选,仍有效时才隐藏任务。隐藏不等待磁盘写入或通知成功。--通知使用 `taskID + attemptID` 作为 identifier,有效性由 monitor 的当前保护尝试决定。提交前后校验 attempt ID、progress generation 和静默时长。保护尝试失效时,通知服务按该 identifier 移除 delivered 和 pending notification。--保护通知使用系统默认声音,`retryCount` 为 `0`,避免重试已经失效的候选。--## 防睡眠停止--低电量或最长时长导致防睡眠停止时,`KeepAliveController` 先撤销 CodexBarHelper 租约。只有回复确认来源为 `.codexBar` 且 `SleepDisabled=0` 时,才提交对应通知;其他结果会清除本轮待发通知。--App idle assertion 保留到通知提交结束,随后释放,由 macOS 按系统电源策略决定睡眠时机。--## 声音--[`NotificationSoundOption.swift`](../../CodexBar/Services/Notifications/NotificationSoundOption.swift) 提供以下声音选择:--- 系统默认通知音-- 静音-- macOS 可用系统声音-- App bundle 内置声音--内置声音位于 [`NotificationSounds`](../../CodexBar/Resources/NotificationSounds)--已保存的声音名称在新系统或新版 App 中不存在时,回退到默认声音,不阻断通知。--不同通知分类可以保存各自的声音设置。--声音选项保存稳定 ID,而不是绝对文件路径:--- 内置声音通过 bundle resource 解析-- 系统声音首次访问时扫描用户、Local 和 System 声音目录-- `/Network/Library/Sounds` 刻意不扫描,自动挂载点探测可能阻塞 UI-- 同名声音按系统查找顺序选择靠前目录-- 内置 ID 预先保留,防止本机同名文件在重启后改变已保存选项的含义-- 已保存 ID 无法解析时回退 system default--系统默认声音和静音不可试听,预览只支持有明确文件的系统音和内置音。--## 触觉反馈--触觉反馈默认关闭。开启后通过连续短脉冲提供提醒。--触觉是系统通知之外的独立本地反馈。它响应非匿名任务的完成或等待 transition,服从通知总开关和触觉开关,但不依赖系统通知授权、分类通知开关或完成时长阈值。--## 提交与去重--通知通过 `UNUserNotificationCenter` 提交:--- 普通通知提交失败最多重试 1 次,异常会话保护通知不重试-- 已发送 dedup key 保存到 UserDefaults-- 最多保留 300 个 key-- key 必须包含足够的账户或任务范围,避免不同对象相互压制-- 过期或不再相关的 waiting key 会被移除--持久化去重避免 App 重启后立即重复发送同一事件,但不能替代上游任务 terminal 去重。--### 提交中与已发送去重--`submittingDedupKeys` 和 `sentDedupKeys` 不能合并:--| 集合 | 生命周期 | 防止的问题 |-| --- | --- | --- |-| `submittingDedupKeys` | 当前异步提交期间 | 两个同步调用在第一个 `await` 前同时通过检查 |-| `sentDedupKeys` | UserDefaults,最多 300 条 | App 重启后重复发送同一业务周期 |--dedup 检查和 `submitting` 插入在创建 Task 前同步完成,因此正确性不依赖 Swift task 调度顺序。--只有 `UNUserNotificationCenter.add` 成功且事件在提交后仍相关时才写入 sent key。如果提前记录,一次系统提交失败会永久吃掉这条提醒。--### 发送入口的统一语义--所有通知内容最终经过同一个 `send` 和 `deliver`--```text-同步检查 dedup- -> 构造不可延迟的 notification request- -> 提交前检查 relevance- -> 调用系统中心- -> 提交后再次检查 relevance- -> 成功后持久化 dedup- -> 失败时按 retryCount 重试并执行分类清理(默认 1 次,异常会话保护为 0 次)-```--日志只记录 `kind` 和失败原因,不记录 title 或 body。通知正文可能包含项目名和任务信息,即使日志位于本机也不应复制这些内容。--## 前台展示与点击--App 是 `LSUIElement`,通知中心 delegate 明确允许 App 在前台时继续展示 banner 和声音。--点击处理不直接创建新窗口,而是调用 `openMenuSurface`。这保证锚点有效时复用 popover,锚点无效时使用 fallback panel,并继续遵守同一套焦点和 dismiss 规则。--## Codex TUI 通知--设置页中的 Codex TUI 通知是 Codex 自身配置,通过 app-server 的 `config/read` 读取,并通过 `config/batchWrite` 写入。--它与 CodexBar 系统通知完全独立:--- 关闭 CodexBar 通知不代表关闭 TUI 通知-- TUI 设置失败不影响 App 通知状态-- UI 必须清楚区分两个开关的作用域--## 手动验证--- 首次开启总开关时正确请求系统权限-- 系统拒绝权限时设置页展示可理解状态-- 首次读数不高于低额度阈值或向下跨越阈值时提醒,同一重置周期去重-- 初次加载 100% 额度不误报重置-- 自动重置明确返回 `reset` 时发送“自动重置”,后续额度归零时仍可独立发送“额度已重置”-- 自动重置明确返回 `alreadyRedeemed` 时按成功通知并停止重试-- 只看到目标凭证消失时不发送自动重置通知-- 网络重试期间不发送失败通知,同一凭证的同一失败原因最多通知一次-- 自动重置关闭时通知子项置灰,重新开启后恢复原来的开关和音效-- 成功和失败通知使用“自动重置通知”所选音效,选择静音时两者都无声-- 完成时长低于和高于阈值时行为正确-- `Stop` 与 rollout terminal 同时出现时只通知一次-- 自动审批不发送等待批准通知-- App 前台时仍展示配置允许的通知-- 点击通知能够激活 `LSUIElement` App 并打开主面板-- 已保存声音资源缺失时回退正确-- App 重启后不重复发送已经持久化的事件--## 关键源码--- [`CodexNotificationService.swift`](../../CodexBar/Services/Notifications/CodexNotificationService.swift)-- [`NotificationSettings.swift`](../../CodexBar/Services/Settings/NotificationSettings.swift)-- [`NotificationSoundOption.swift`](../../CodexBar/Services/Notifications/NotificationSoundOption.swift)-- [`CodexCLINotificationSettings.swift`](../../CodexBar/Services/Settings/CodexCLINotificationSettings.swift)-- [`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift)-- [`KeepAliveController.swift`](../../CodexBar/Services/KeepAlive/KeepAliveController.swift)diff --git a/Docs/DeveloperGuide/sleep-prevention.md b/Docs/DeveloperGuide/sleep-prevention.mddeleted file mode 100644index e4adaed..0000000--- a/Docs/DeveloperGuide/sleep-prevention.md+++ /dev/null@@ -1,453 +0,0 @@-# 防睡眠系统--简体中文 | [English](../en/DeveloperGuide/sleep-prevention.md)--## 控制链路--普通 App 进程负责策略和用户界面,CodexBarHelper 只执行受限的系统睡眠与唤醒操作:--```text-CodexActivityMonitor- -> KeepAliveController- -> App IOKit assertion- -> XPC lease- -> CodexBarHelper- -> /usr/bin/pmset--AutoResetController- -> AutoResetWakeScheduler- -> XPC wake date- -> CodexBarHelper- -> IOPMSchedulePowerEvent-```--## 状态分层--系统按职责区分状态:--| 层级 | 代表字段 | 回答的问题 |-| --- | --- | --- |-| 用户意图 | `isEnabled` | 用户是否希望使用功能 |-| 决策条件 | `sleepBlockReason` | 当前是否满足生效条件 |-| 请求状态 | `appliedSleepPreventionRequested` 和 `requestInFlight` | App 最近向 helper 请求了什么 |-| 已确认效果 | `isPreventingSleep` 和 `sleepPreventionSource` | App 是否收到系统状态已经符合预期的证据 |--- helper 暂时不可用时保留用户开关,修复依赖后可以自动恢复,不需要用户重新开启-- XPC 请求发出但尚未确认时不提前显示成功,避免界面和系统实际状态相反--`sleepBlockReason` 是所有条件的唯一决策出口。UI 派生状态、条件日志和实际切换都读取同一个结果,新增条件时必须在穷尽的 `switch` 中说明设置入口是否仍应可用。--## 两层睡眠控制--两套机制的作用域不同:--| 机制 | 生命周期 | 作用 | 失效方式 |-| --- | --- | --- | --- |-| IOKit assertion | App 进程 | 阻止空闲系统睡眠,可选阻止显示器睡眠 | App 退出后由系统自动回收 |-| `pmset disablesleep` | 系统全局 | 覆盖 assertion 无法保证的系统睡眠路径 | 必须显式恢复,因此需要 ownership 和 watchdog |--App 侧 assertion 会在 XPC 获取流程开始前建立。这样 helper 切换期间不会出现短暂的空闲睡眠窗口。如果 helper 请求失败,统一清理路径会释放 assertion,避免形成只有 App 自己知道的半成功状态。--## 获取与释放事务--获取流程在系统状态验证成功后更新已生效状态:--```text-条件求值为允许- -> 建立 App idle assertion- -> 标记 helper 可能已经收到租约- -> 发送带 generation 的 XPC 请求- -> helper 读取当前 SleepDisabled- -> 必要时写入并回读验证- -> App 校验来源和实测值- -> 发布已生效状态并开始累计时长-```--释放流程按相反方向收口:--```text-条件求值为阻断- -> 请求 helper 撤销租约- -> helper 仅在有恢复责任且无其他租约时恢复系统值- -> App 收到实测结果- -> 发布未防睡眠状态并释放 display assertion- -> 停止时长累计- -> 提交低电量或时长上限通知- -> 释放 App idle assertion-```--低电量和时长上限通知仅在 helper 回复来源为 `.codexBar` 且 `SleepDisabled=0` 后提交。--App idle assertion 保留到通知提交结束,避免系统在提交前进入空闲睡眠。随后释放 assertion,由 macOS 按系统电源策略决定睡眠时机。--## 不确定的租约状态--XPC 超时只证明 App 没收到回复,不证明 helper 没执行请求。请求可能已经把租约写入 helper,只是回复在连接断开时丢失。--因此 `mayHaveHelperLease` 采用保守语义:--- 请求获取时立即设为 `true`-- 超时或连接失效时保持 `true`-- 只有一次已确认的释放结果才能清为 `false`--## XPC 代际校验--用户关闭开关、任务结束和重试可能在前一条 XPC 回复返回前连续发生。如果只按回复到达顺序更新状态,旧的“获取成功”可能覆盖新的“释放成功”。--App 和 helper 都使用单调递增 generation:--- App 只接收当前 `requestGeneration` 的回调-- helper 忽略比现有租约 generation 更旧的请求-- 连接作废时 App 推进 generation,让在途回调自然失效--## 生效条件--[`KeepAliveController.swift`](../../CodexBar/Services/KeepAlive/KeepAliveController.swift) 只有在以下条件全部成立时才建立防睡眠:--- 防睡眠主开关已开启-- `AdvancedModeSettings.isOperable` 为 `true`-- 至少存在一个符合设置的实时任务-- CodexBarHelper 已安装并可连接-- 未触发低电量阈值-- 未达到单次最长防睡眠时长-- App 不在终止流程--等待批准任务默认不计入有效任务,用户可以单独开启。异常会话保护抑制的任务也不再维持防睡眠。--`KeepAliveController` 会先从运行中和等待批准快照中排除 `isAnonymous` 任务。只有非匿名任务能够进入运行任务集合,启动新一轮最长时长计时或维持防睡眠。--控制器会发布明确的阻塞原因:--| 原因 | 含义 |-| --- | --- |-| `notStarted` | 服务尚未启动 |-| `userOff` | 用户关闭主开关 |-| `advancedModeDisabled` | Hook 不可工作 |-| `noTasks` | 没有符合条件的任务 |-| `helperUnavailable` | CodexBarHelper 未安装或不可连接 |-| `helperRefreshing` | CodexBarHelper 状态正在恢复或确认 |-| `terminating` | App 正在退出 |-| `lowBattery` | 电池低于阈值 |-| `limitReached` | 达到单次时长上限 |--## App 侧 assertion--[`SystemSleepService.swift`](../../CodexBar/Services/KeepAlive/SystemSleepService.swift) 使用 IOKit 建立 `PreventUserIdleSystemSleep` assertion。--如果用户开启保持显示器唤醒,还会建立 `NoDisplaySleep` assertion,并每 30 秒调用一次用户活动声明,避免显示器空闲计时提前生效。--App 侧 assertion 只覆盖当前进程生命周期。系统级 `SleepDisabled` 由 CodexBarHelper 管理,用于覆盖 assertion 无法保证的系统睡眠路径。--## CodexBarHelper 安装与通信--CodexBarHelper 通过 `SMAppService` 注册为 LaunchDaemon。App 和 CodexBarHelper 使用 [`CodexBarHelperXPC.swift`](../../Shared/CodexBarHelperXPC.swift) 定义的 XPC 接口。--接口只提供以下能力:--- 设置或撤销 App 租约-- 查询 CodexBarHelper 运行和拥有状态-- App 更新后重置 CodexBarHelper 状态-- 设置或取消 CodexBar 固定 owner 的下一次自动重置 `wake` 事件--自动重置与防睡眠共用 helper 注册和系统批准状态,但使用独立 XPC 连接。开启自动重置时,即使防睡眠主开关关闭,也会尝试注册 helper;尚未批准时,自动重置设置行会提供相同的状态和“打开系统设置”入口。--设置页把用户确认、helper 注册和 Helper 授权系统设置跳转分成独立职责:--- `HelperFeatureConfirmation` 为自动重置和防睡眠提供统一确认框,每次从关闭切换为开启时显示-- `.notRegistered` 与 `.notFound` 在确认框提示安装并授权后台运行,`.requiresApproval` 提示已安装但仍需授权,`.enabled` 只显示功能说明-- 用户确认后才调用 `AutoResetSettings.setEnabled(true)` 或 `KeepAliveController.setEnabled(true)`,取消时不写入开关状态-- `ensureHelperRegistration()` 只负责注册、刷新和后续协调,不负责打开 Helper 授权系统设置-- `AppSettingsView` 只在已开启设置行的 `.requiresApproval` 状态显示 `打开系统设置`,按钮调用 `KeepAliveController.openSystemSettings()`-- 自动重置选项入口要求开关已开启且 `helperStatus == .enabled`,条件失效时关闭已展开的自动重置面板-- 防睡眠选项入口读取 `KeepAliveController.canShowOptions`,没有任务、低电量阻断、达到上限或 helper 刷新期间仍允许调整设置-- 自动重置和防睡眠开关关闭时,设置行不显示状态说明--关于页面和两个功能说明统一读取 `helperInstallationStatus`。系统注册状态、包校验结果与操作错误分别保存:--- `.notRegistered` 和 `.notFound` 在没有已知安装异常时显示“未安装”-- App 启动和再次激活时,后台校验 Helper 可执行文件、plist 关键配置、App 资源签名及 Helper 的签名团队和标识;签名校验不访问网络-- 确认组件缺失、配置异常或签名无效时显示“不可用”,即使系统仍返回 `.enabled`;后续包校验成功后清除该异常-- 安装前发现组件缺失时只更新包异常并发起新校验,不另存一份注册错误;旧校验结果不能覆盖新发现的缺失,关闭功能后修复组件也能通过再次校验恢复显示-- 待授权和已授权状态不会被历史注册错误覆盖;未注册且安装失败时显示“不可用”-- 包校验结果只保存在内存中;XPC 超时和电源操作失败由操作错误单独表示--唤醒计划采用系统状态收敛而不是只依赖正常退出清理:--- helper 每次启动都在开放 XPC listener 前清除固定 owner 的遗留事件,App 重连后再按最新目标重新安排-- 设置成功必须回读到恰好一个时间匹配的事件,取消成功必须回读到零个事件-- 对应 XPC 连接断开时立即放弃内存所有者;取消失败会进入待清理状态,并由 helper 短周期重试-- App 退出会等待唤醒计划和防睡眠租约分别确认释放;helper 更新会先冻结唤醒同步,并在当前进程存在唤醒连接或已应用时间时显式取消计划-- `Scripts/cleanup.swift` 注销 helper 前会检查固定 owner;事件无法取消并回读清零时停止注销,避免同时失去最后一个具备清理权限的进程;注销成功后同时关闭防睡眠和自动重置,避免 App 下次启动时重新注册 helper--每个 App 进程生成稳定的 `clientSessionID`,XPC 重连期间保持不变。每次租约变更带单调递增 generation,CodexBarHelper 只接受更新的请求,避免迟到消息覆盖新状态:--- 单次 XPC 请求超时为 10 秒-- 连接丢失后 watchdog 宽限为 15 秒-- CodexBarHelper 每 5 秒检查租约和系统状态-- 异常状态每 60 秒尝试恢复--## CodexBarHelper 权限边界--[`CodexBarHelper/main.swift`](../../CodexBarHelper/main.swift) 以 root 运行,但能力被刻意限制:--- 系统睡眠切换只执行固定路径 `/usr/bin/pmset`-- 只使用固定参数读取或切换 `disablesleep`-- 只使用固定 owner 和固定 `wake` 类型设置或取消一个系统唤醒事件-- 唤醒接口只接受有限时间戳,不接受任意 owner、事件类型或命令-- 不接受任意命令或参数-- 不访问 Hook、rollout、账户或日志数据-- 不进行网络访问-- 不负责判断 Codex 任务状态--CodexBarHelper 使用自身签名中的 Team ID 和当前构建配置对应的 App 标识生成客户端 code-signing requirement,并应用到 XPC listener。--## 系统状态所有权--CodexBarHelper 先通过以下命令读取当前值:--```bash-/usr/bin/pmset -g-```--需要系统级防睡眠时只会执行固定操作:--```bash-/usr/bin/pmset -a disablesleep 1-```--释放时执行:--```bash-/usr/bin/pmset -a disablesleep 0-```--所有权规则是防止破坏外部状态的关键:--- 如果 CodexBarHelper 观察到初始值已经是 `1`,它把状态标记为 external-- external 状态不会被 CodexBar 声明为自己拥有-- CodexBar 读取到 `0` 后先持久化 owned,再执行并验证 `0 -> 1` 切换-- 最后一个租约结束后,owned 或 restoring 状态执行恢复为 `0`--因此,用户或其他工具预先开启的 `SleepDisabled=1` 不会在 CodexBar 退出时被关闭。--### Ownership 恢复事务--helper 按以下顺序写入恢复记录和系统值:--```text-获取: persist owned -> pmset 1 -> read back 1-释放: persist restoring -> pmset 0 -> read back 0 -> persist idle-```--获取时先写 owned。如果进程在写文件后,`pmset 1` 前崩溃,下次启动多执行一次幂等 `pmset 0`,不会留下全局禁止睡眠。如果先写系统值再持久化,两步之间崩溃就会失去恢复责任。--释放时先写 restoring。如果在 `pmset 0` 或最终 idle 提交前崩溃,下次启动仍知道这是一笔未完成恢复。只有回读确认系统值为 `0` 后才允许持久化 idle。--### 外部来源消失后的接管--`external` 不是永久判断。CodexBar 在仍有有效任务时周期性读取 helper 缓存的系统状态:--- 外部来源仍存在时继续借用现有 `SleepDisabled=1`,不写系统设置-- 外部来源消失而任务仍在时重新申请租约,由 helper 完成新的 `0 -> 1`-- helper 已经因为其他有效客户端转为 owned 时更新来源展示,不重复创建计时周期--## CodexBarHelper 状态持久化--CodexBarHelper 把系统所有权记录保存在:--```text-/Library/Application Support/CodexBar/helper-state.json-```--安全和可靠性要求如下:--- 当前 schema 为 `1`-- 目录由 root 拥有,权限为 `0755`-- 目录不能被 group 或 world 写入-- 文件由 root 拥有,权限为 `0600`-- 使用临时文件、full sync 和原子 rename 提交-- 启动时记录缺失则写入 idle;记录为 owned 或 restoring 时恢复 `disablesleep 0`;记录无法读取或不可信时也尝试恢复为 `0`--自动重置唤醒事件不写入该文件。它由 macOS 电源管理保存,身份固定为当前 Debug 或 Release helper 的 mach service 名加 `.auto-reset`,类型固定为 `wake`。--## 租约与故障恢复--App 持有有效任务时保持带身份的 XPC lease。CodexBarHelper 不把一次请求解释为脱离连接的永久授权:--```text-租约有效 -> 保持 owned 状态-连接短暂断开 -> 等待 15 秒 watchdog-宽限内重连 -> 使用相同 clientSessionID 继续-宽限超时 -> 撤销租约并恢复 owned 状态-```--异常退出后,CodexBarHelper 依靠连接失效、watchdog 和持久化所有权共同恢复系统设置。--App 正常退出时先取消自动重置唤醒计划,再撤销租约和 IOKit assertion。如果 CodexBarHelper 尚未确认两类 root 状态都已清理,App 终止流程会等待,避免在不确定状态下直接离开。--### 正常退出--`applicationShouldTerminate` 不能在未确认释放时直接返回允许。`prepareForTermination()` 会先停止新重试,取消可能存在的自动重置唤醒计划,再请求释放可能存在的租约,然后等待 helper 回读结果:--- 释放成功时继续终止-- 释放失败时取消本次终止,恢复正常条件求值和重试--强制退出时,helper 在 15 秒 watchdog 宽限结束后撤销失联客户端的租约。--### Helper 自检--helper 会分别检查 lease、ownership 记录和实测 `SleepDisabled`--- owned 且仍有租约时,若系统值被外部改回 `0`,helper 会重新建立 `1`-- owned 且已无租约时恢复 `0`-- external 时只观察,不把外部状态写成自己的 ownership-- 持久化记录不可信时采取 fail-safe 恢复,不把损坏记录当成继续持有权限的依据-- 自动重置唤醒事件取消失败且已经没有连接所有者时,每 5 秒继续回读并清理固定 owner--周期检查修复系统值被其他进程改写、回调丢失或进程重启后的状态偏差。--## 时长和电池策略--单次时长只统计实际处于防睡眠的时间:--- 没有任务时暂停或重置周期-- 新一轮任务可以开始新的周期-- 默认上限为 12 小时-- 可选 1, 2, 4, 8, 12, 24 小时或无限制--低电量停止只在使用电池供电时生效:--- 可选阈值为 5%, 10%, 15%, 20%, 25%-- 默认关闭-- 恢复使用 5 个百分点滞回,避免电量在阈值附近反复切换--防睡眠因低电量或时长上限结束时,通知必须在睡眠状态已经恢复后发送。--### 时长周期如何定义--“单次最长时长”不是从任务出现到任务消失的墙钟时间,而是系统实际被 CodexBar 挡住睡眠的累计时间。--`KeepAliveDurationLimiter` 使用 `SuspendingClock`--- 系统睡眠期间时钟暂停,醒来后不会把睡眠时间误算为防睡眠时间-- helper 不可用、低电量或其他条件阻断期间暂停累计-- 新运行任务出现时开始新周期-- 等待任务恢复运行时开始新周期-- 同一批任务只是在运行和观察之间刷新快照时不重复清零--`hasReached` 是当前周期内的粘滞状态。达到上限后不能因为一次普通快照刷新立即恢复,只有明确的新任务周期或设置变化才能重新求值。--任务集合使用稳定 task ID 判断“新任务”和“等待后恢复”,而不是只比较数量。如果一个任务结束同时另一个任务开始,数量仍为 1,但新的任务应得到完整时长预算。--### 电池读取状态--电池读取使用 `unavailable`, `unreadable` 和 `present` 三态,不能压成一个可选值:--| 状态 | 含义 | 策略 |-| --- | --- | --- |-| `unavailable` | 已确认没有内置电池 | 隐藏低电量设置并清除阻断 |-| `unreadable` | 本轮 IOKit 读取失败 | 保留上一次结论 |-| `present` | 有可信电量和供电来源 | 正常执行阈值判断 |--读取失败时维持上一次状态,是为了避免一次 IOKit 枚举缺口让设置行闪烁,也避免正在生效的低电量保护被瞬时解除。一台机器只要曾经读到电池,后续空列表就按 `unreadable` 处理,因为硬件不会在运行中消失。--是否使用电池通过 power source state 判断,不能通过 `isCharging` 推断。接通电源但停止充电时 `isCharging` 也是 false,此时电量并没有被任务持续消耗。--### 低电量锁存与滞回--阈值为 `T` 时,进入条件是电池供电且电量不高于 `T`,退出条件是电量至少达到 `T + 5`--低电量通知还保留单轮锁存:--- 只有此前确实由 CodexBar 防止睡眠时才排队通知-- 只在恢复成功后记录已经通知-- 接上电源会解除当前阻断,但只有电量越过恢复门槛才结束这一轮锁存-- 修改阈值会开启新一轮,避免旧阈值的通知状态污染新设置--## 显示器常亮是附加效果--保持显示器唤醒只依赖“防睡眠已确认生效”和用户选项,不独立维持系统睡眠。--`NoDisplaySleep` 只能阻止显示器休眠,不能阻止屏保和闲置锁屏。因此实现还每 30 秒声明一次用户活动。声明会复用同一个 assertion ID,否则 `pmset -g assertions` 中会持续堆积同名记录。--显示断言失败只记独立错误,不覆盖主防睡眠结果。这是有意区分核心效果和附加效果,避免设置页把“屏幕没有保持常亮”误报成“系统防睡眠完全失败”。--assertion 名称使用 ASCII。某些系统版本中带中文的名称会在 `pmset -g assertions` 中显示为空,使诊断信息失去标识。--## 恢复系统电源管理--任务结束、关闭功能、低电量或达到时长上限时,CodexBar 释放租约和 App assertion。Helper 仅在持有恢复责任且无其他租约时恢复系统睡眠设置,外部来源的设置保持原样。--解除防睡眠不主动请求系统睡眠。合盖和外接显示器场景均由 macOS 按系统电源策略决定是否睡眠,任务结束不保证立即进入睡眠。--## 失败与重试策略--防睡眠采用有界重试,因为每次重试都会重新建立特权连接并可能启动 root 进程:--- 10 秒请求超时早于 15 秒 helper watchdog,App 先放弃不可信连接,helper 随后有机会清理租约-- 每次重试前重新比较期望状态,用户已经关闭功能时不会继续重试获取-- 重试耗尽后保留明确错误,不无限循环消耗系统资源-- 连接失效会立即释放 App assertion,避免 UI 已降级但进程仍永久阻止空闲睡眠-- 旧请求通过 generation 失效,不依赖每条取消路径都成功撤回底层消息--诊断时应区分系统注册状态、包校验异常、注册错误和操作错误。未安装与待批准属于注册状态;组件缺失、配置或签名无效属于包校验异常;注册或更新失败属于注册错误;已安装 helper 的某次切换未得到可信结果属于操作错误。--自动重置唤醒计划使用独立的有界同步策略:--- 设置或替换失败后按 `2s, 4s, 8s, 16s, 32s, 64s` 重试,耗尽后在自动重置设置行保留错误-- 正常退出或 helper 更新前按立即、`250ms`、`1s` 三次尝试取消并回读-- 目标时间距现在不超过 5 秒时不再登记系统事件,App 内任务直接进入到点执行路径-- XPC 连接丢失后清除 App 侧已应用状态并重新协调;helper 同时取消该连接拥有的固定事件--## CodexBarHelper 更新--App 更新可能改变内嵌 CodexBarHelper 的签名或内容。App 会记录 CodexBarHelper fingerprint,检测变化后通过 `SMAppService` 和重置接口刷新安装状态。--验证更新时需要同时检查:--- CodexBarHelper 位于 App 包的正确位置-- LaunchDaemon plist 与 Debug 或 Release bundle ID 匹配-- App 和 CodexBarHelper 签名匹配预期-- 首次系统授权流程可完成-- 更新后旧 owned 状态能够安全恢复-- 更新前自动重置唤醒计划已取消,新 helper 就绪后按当前目标重新登记--## 手动验证--- 运行任务开始和结束时,App assertion 与 CodexBarHelper 租约同步切换-- 合盖、接电并使用外接显示器时,任务结束仅解除保活,不主动熄屏或锁屏-- 开盖时,任务结束后恢复系统设定的闲置睡眠-- 无外接显示器且合盖运行任务时,记录任务结束后系统实际进入睡眠的时机-- 关闭防睡眠、低电量和时长上限触发时,租约与 assertion 正确释放且不发起软件睡眠-- 等待批准设置关闭和开启时,有效任务判断正确-- 外部先设置 `disablesleep 1` 时,CodexBar 不声明所有权也不恢复为 `0`-- App 正常退出时恢复 owned 状态-- App 强制退出或 XPC 断开后,watchdog 恢复 owned 状态-- 自动重置和防睡眠每次开启都显示确认,取消后保持关闭-- 未注册、等待批准和已批准等 helper 状态的确认文案与功能说明正确-- 包完整且没有注册错误时,`.notRegistered` 和 `.notFound` 均显示“未安装”-- 在测试包中分别移除 Helper、移除或篡改 plist、破坏签名,启动或再次激活后显示“不可用”,已授权状态也不能掩盖包异常-- 安装前发现缺失后,旧校验结果不覆盖新异常;关闭两个功能并修复完整 App 包后,再次激活能清除异常,关于页面仍显示状态-- 开启操作只触发 helper 注册,Helper 授权系统设置仅由设置行的 `打开系统设置` 按钮打开-- 自动重置选项入口只在开关开启且 helper 已批准时显示,条件失效后已展开面板关闭-- 自动重置开启且防睡眠关闭时仍能完成 helper 注册与批准-- 未来阈值和重试只保留一个固定 owner 的 `wake` 事件,替换时不影响其他 owner-- 自动重置关闭、目标变化和正常退出时回读确认计划清零-- 自动重置 XPC 连接断开或 helper 重启时清理遗留计划-- `Scripts/cleanup.swift` 只在固定 owner 的计划确认清零后注销 helper-- 达到时长上限后先恢复睡眠再通知-- 低电量触发和 5% 滞回恢复正确-- 异常会话保护隐藏任务后释放防睡眠-- Debug 与 Release 版本的 CodexBarHelper 不混用--## 关键源码--- [`KeepAliveController.swift`](../../CodexBar/Services/KeepAlive/KeepAliveController.swift)-- [`KeepAliveHelperConfiguration.swift`](../../CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swift)-- [`SystemSleepService.swift`](../../CodexBar/Services/KeepAlive/SystemSleepService.swift)-- [`HelperRuntimeStatusMonitor.swift`](../../CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift)-- [`AutoResetWakeScheduler.swift`](../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift)-- [`KeepAliveDurationLimiter.swift`](../../CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift)-- [`PowerSourceMonitor.swift`](../../CodexBar/Services/KeepAlive/PowerSourceMonitor.swift)-- [`CodexBarHelperXPC.swift`](../../Shared/CodexBarHelperXPC.swift)-- [`CodexBarHelper/main.swift`](../../CodexBarHelper/main.swift)diff --git a/Docs/DeveloperGuide/sync.md b/Docs/DeveloperGuide/sync.mddeleted file mode 100644index 2d8cd09..0000000--- a/Docs/DeveloperGuide/sync.md+++ /dev/null@@ -1,350 +0,0 @@-# CloudKit 同步--简体中文 | [English](../en/DeveloperGuide/sync.md)--## 同步范围--CloudKit 同步用于在同一 iCloud 账户的 Mac 之间合并 Hook 日级统计和 rollout Token 用量。--Hook 同步以日聚合为单位:--```text-本机原始 Hook JSONL- -> 本机日级聚合- -> 当前设备 CloudKit 记录- -> 下载其他设备记录- -> 按日期合并展示-```--app-server 账户、额度、账户 token 总量、Reset Credits、自动重置设置与状态、实时任务和防睡眠状态不参与同步。--## 数据来源--Hook 日聚合展示使用以下数据。Token 轮次账本及其云端缓存见 [Rollout Token 历史](#rollout-token-历史)--| 数据 | 权威来源 | 断网时行为 |-| --- | --- | --- |-| 当前设备当天和历史贡献 | 本机 `daily.jsonl` 与同源云端缓存按完整性合并 | 本机聚合继续更新,保留云端缓存 |-| 其他设备贡献 | `cache.jsonl` 中最近成功拉取的记录 | 保留最后快照 |-| 上传确认和增量位置 | `state.json` 与 `cursor.data` | 下次继续或重建 |--当前设备的本地聚合与云端副本按来源和完整性合并,同源贡献只计算一次。云端也可补充本地缺失的数据,或提供事件数更多的同源聚合。--远端缓存是可重建投影,游标只是加速状态。任何游标错误都可以退化成全量读取 custom zone,不要求用户清理本地文件。--## CloudKit 结构--[`WorkflowSyncService.swift`](../../CodexBar/Services/Workflow/WorkflowSyncService.swift) 使用 App 的 CloudKit private database:--| 项目 | 值 |-| --- | --- |-| Container | `iCloud.app.zabrian.codexbar` |-| Custom zone | `CodexBarZone` |-| 元数据 record type | `CodexBarSyncMetadata` |-| 日聚合 record type | `CodexBarDailyAggregate` |-| Token 轮次 record type | `CodexBarTokenTurn` |--private database 中的数据只属于当前 iCloud 账户,不写入 public database。--custom zone 的意义不只是命名空间。它提供 zone change token 和删除事件,使设备可以增量同步新增、修改和删除,而不需要每轮扫描整个 private database。--zone 确认和账户 salt 在 actor 内跨轮次缓存;同步失败时使两者失效,下轮重新读取。--## 启用条件--同步只有在以下条件全部成立时运行:--- 用户打开 CloudKit 同步-- `AdvancedModeSettings.isEnabled` 为 `true`,历史同步可继续消费已落盘聚合-- 当前 iCloud 账户可用-- 本地聚合服务可用--每轮同步都会检查本地保留期内的全部日期,通过 hash 筛选需要上传的数据,首次启用和后续补传使用同一流程。同步调度有最短 8 秒冷却,合并短时间内的多次本地变化。--## 设备标识哈希--同步需要区分设备贡献,但不能直接上传硬件标识:--1. 在 private database 创建 32 字节随机账户 salt-2. 读取本机 `IOPlatformUUID`-3. 使用账户 salt 对 UUID 执行 HMAC-SHA256-4. 把结果作为云端 `deviceId`--原始 `IOPlatformUUID` 不会上传。同一设备在同一 iCloud 账户中得到稳定的设备哈希标识,不同账户得到不同结果。--salt 存在同一个 private custom zone 中。多台设备先后创建时通过 CloudKit 冲突后回读现有记录收敛到同一份 salt,而不是让每台设备各自产生不兼容身份。--本地状态记录最近解析出的 `deviceId`。如果它变化,同步会清除旧游标和远端缓存,但保留待 replacement 日期。设备身份变化意味着缓存的账户作用域已经不可信,不能继续增量套用。--## 日聚合字段--每条日记录包含:--- schema-- 设备哈希标识 `deviceId`-- 日期-- source generation-- Hook 事件计数-- session 数和 turn 数-- project 计数-- model 计数-- 更新时间--不会上传:--- 原始 Hook JSONL-- session ID 或 turn ID 原文-- 完整工作目录-- prompt 或 response 内容-- Codex 账户和额度-- 认证 token 或 `auth.json` 等凭证-- App 请求日志-- 异常会话保护状态--更完整的数据边界见 [数据与隐私边界](data-and-privacy.md)--## Rollout Token 历史--Token 历史使用同一 private zone 中独立的 `CodexBarTokenTurn` 记录,schema 为 `1`。一条记录对应一个线程轮次,同一轮的累计快照更新原记录,不按设备相加。主线程和子线程分别计数,子线程归入根轮次开始日。日期按查看设备的本地时区计算。--本地轮次标识先对线程和轮次 ID 做 SHA-256,再使用账户 salt 做 HMAC-SHA256,生成云端标识。不同设备读取同一份 rollout 时生成相同记录名,缓存和本地数据也按该标识去重。记录不包含原始 session、turn 或 agent ID。--云端字段如下,发布环境需要在 CloudKit Console 部署该记录类型及字段:--| 字段 | 类型 | 内容 |-| --- | --- | --- |-| `schemaVersion` | Int64 | `1` |-| `rootID` | String | 根轮次的账户域哈希 |-| `startedAt` | Date | 轮次开始时间,可缺失 |-| `observedAt` | Date | 最近累计记录的时间 |-| `rebuiltAt` | Date | 可选的显式重建时间,用于拒绝旧统计回流 |-| `usage` | Bytes | Token 整数计数的 JSON,可缺失 |--记录名直接使用轮次哈希,保持稳定;数据格式版本由 `schemaVersion` 字段管理。缺少 `usage` 的记录不贡献用量:根记录可用于确定子轮次日期,带 `rebuiltAt` 的记录可用于清除该轮旧计数。上传前读取服务端记录,保留更完整的累计快照,使用 `ifServerRecordUnchanged` 条件写入;并发冲突留待下一轮重新获取、合并和重试。不会把多个累计快照相加,也不会对输入、缓存和输出字段分别拼接最大值。--显式重建扫描本机保留期内的 rollout,按根轮次开始日筛选结果,只更新所选日期重新读到的轮次。本地 `rebuild.lock` 防止多个进程同时重建;扫描时不持有账本锁,每批读取后让出执行机会,完整成功后加锁提交。读取开始后的活跃轮次进展保留,原始文件缺失的旧轮次不删除。失败或取消保留提交前账本,App 退出后不自动续跑这次手动重建。--需要同步的重建记录携带 `rebuiltAt`。合并优先选择较新的重建结果,再在同一次重建内保留完整累计值,允许显式修正为更小的计数。正常增量读取继承本地轮次的重建时间。本地账本恢复或云端存在更新的重建结果时,只对账户与根轮次身份匹配的本地轮次恢复云端基线。已读取的文件按每轮读取预算重新扫描,恢复边界之前的用量保留云端修正值,之后的累计记录继续更新。恢复边界与读取游标保存在本地账本,重启后继续补读,不导入其他机器独有的轮次。重建后没有用量的旧轮次仍可同步,以清除云端旧计数;其他轮次和其他机器独有的记录不受影响。--日汇总累加去重后的线程轮次,缓存命中率使用日缓存命中总量除以日输入总量。热力图颜色和账户用量来自 app-server,与 rollout 用量独立。热力图日期详情将缺失用量显示为 `0`,缓存命中率显示为 `0%`;存储与同步仍保留缺失状态。--本地账本位于 `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` 时无法补出用量。--自动回放每批提交后在 `workflow` 系统日志输出进度,包括已追平文件数、字节进度、本轮读取量、剩余量、等待完整行的文件数、不可读文件数和耗时。全部文件追平后输出一次“Rollout 回放完成”;正常增量追加和位置不变的等待不重复输出。完成状态只表示本轮检查范围内的本地文件已读完,不表示 iCloud 已同步。日志不包含文件路径、会话身份、正文或 token 用量。--## 一次同步的阶段--```text-读取本地同步状态- -> 创建或确认 custom zone- -> 读取账户 salt 并计算设备哈希标识- -> 按设备身份和 schema 更新本地状态- -> 拉取远端变更到缓存,处理待替换日期- -> 上传当前设备变化日期- -> 再次拉取 Hook 远端变更到缓存- -> 拉取、上传并清理 Token 轮次记录- -> 清理当前设备超过保留期的 Hook 记录- -> 保存状态并发布合并结果-```--上传前后的拉取各有用途:--- 上传前知道远端是否已经有同设备同日记录,才能选择更新、新建 generation 记录或跳过-- replacement 前必须先全量拉取,才能找到增量缓存可能遗漏的旧 generation-- 上传后再次拉取,才能把本轮写入和其他设备并发写入统一进本地缓存-- 最后清理过期记录,避免清理失败阻断本轮有效数据上传--每个阶段都写入日志中的 `stage`,失败信息会标明 `zone`、`device`、`fetch`、`upload`、`tokens` 或 `prune` 阶段:--- 上传每批最多 25 条记录-- 每轮上传按 20 秒预算决定是否启动下一批-- 拉取单页最多 200 条变更-- 本地内容使用 SHA-256 hash 跳过未改变记录--上传循环在每批开始前检查 20 秒预算。已开始的批次继续等待结果;预算耗尽后,剩余日期留到后续同步处理。--每个日期的稳定 JSON 只编码并 hash 一次,同一结果用于待上传筛选和上传确认。--上传使用 `atomically: false`,远端允许单批部分成功。但只要该批出现错误,调用方就移除整批日期的本地确认 hash,下轮重新检查这一批。此前已完成批次的确认保留,远端已成功写入的记录不回滚。--## Hook 日聚合的合并语义--同一天可能有多个设备记录,也可能有当前设备尚未上传的最新本地结果。--合并规则是:--- 其他设备贡献按字段相加-- 当前设备没有本地聚合时使用云端贡献-- 同源记录按 `sourceGeneration` 或旧记录的内容匹配,云端事件数较多时使用云端,否则使用本地-- 本地来源尚未确认完整且没有匹配云端记录时,优先展示已有云端贡献-- 未匹配的独立云端来源继续累加--`confirmedDates` 包括实际上传成功和上传决策为跳过的日期,不表示本地与云端内容必然逐字段相同。--### 同设备同日的多来源记录--记录名支持 `deviceId + date`,以及带来源代际的 `deviceId + date + sourceGeneration` 两种形式。--generation 记录用于表达某一份原始来源的身份。同源的本地和云端结果是替换关系,明确不同的来源则可能是同一天先后产生的独立贡献。--读取层先寻找与本地 `sourceGeneration` 匹配的 record。匹配项只取本地或远端中更完整的一份,其他 generation 继续累加。旧 legacy record 没有 generation 时,内容完全相同也可视为同源,用于兼容早期记录。--“所有旧 generation 都应失效”不是从 generation 本身推断,而是由显式 `replacementDates` 事务表达。这一区分避免正常文件换代丢掉独立贡献,又让用户主动完整重建可以删除历史副本。--上传目标的选择遵循以下原则:--| 远端状态 | 本地来源 | 动作 |-| --- | --- | --- |-| 没有同日记录 | 任意 | 创建 legacy 或 generation record |-| 有同源记录 | 本地不少于远端 | 更新该记录 |-| 有同源且远端事件更多 | 本地带 generation | 保留远端,避免较短的陈旧扫描覆盖较完整结果 |-| 有其他来源记录 | 本地来源新鲜 | 创建当前 generation record |-| 有其他来源记录 | 本地来源不新鲜 | 跳过,等待权威重建 |--`sourceIsFresh` 是一次读取对原始来源完整性的判断,不是时间新旧。文件被替换、截断或仍在稳定边界确认中时,较新的时间戳也不代表更权威。--### 缺失计数字段--CloudKit record schema 演进时,旧记录可能没有新计数字段。`nil` 表示该设备那天无法提供这项统计,`0` 表示明确观察到零次。--CloudKit 解码及持久化模型保留可选计数字段。本地与远端聚合共用 `WorkflowDailyMetrics` 展示投影:保留 `interruptCount` 的缺失值,其他单项事件计数缺失时转换为 `0`;session 和 turn 计数缺失时先回退到对应的开始或停止事件计数,再回退为 `0`。--CloudKit 使用可选整数字段 `interruptCount` 保存中断次数。同日合并的任一贡献缺少该字段时,中断次数合计保持不可用。--## Hook 来源替换与重建--用户执行重新扫描时:--1. 本地聚合从原始 JSONL 重建-2. 受影响日期标记为 replacement-3. 当前设备对应日期的云端记录被覆盖或删除后重建-4. 其他设备记录保持不变--这种设计让重建只修正当前设备贡献。--### Replacement 事务--重建和 CloudKit 同步不一定在同一进程生命周期完成。`replacementDates` 因此保存在 `state.json`,不能只留在内存。--对每个 replacement 日期,同步执行:--1. 全量重建远端缓存-2. 枚举当前设备同日所有已知 legacy 和 generation record ID-3. 删除这些旧贡献,`unknownItem` 按幂等成功处理-4. 从本地 hash 表移除该日期,强制重新上传-5. 只有新内容得到确认后才清除 replacement 标记--replacement 进行中时,快照会临时过滤当前设备该日期的云端缓存,同时展示本机最新聚合。即使 App 在删除和重传之间退出,UI 也不会把旧云端贡献与新本地贡献相加。--replacement 删除前全量拉取当前设备同日记录,覆盖本地增量缓存中缺失的 generation。--## 增量游标与本地缓存--同步状态位于:--```text-~/Library/Application Support/CodexBar/HookEvents/Sync/-```--| 文件 | 作用 |-| --- | --- |-| `state.json` | 同步 schema、本地 hash 和替换状态 |-| `cache.jsonl` | 远端设备日聚合缓存 |-| `cursor.data` | CloudKit zone change token |--Hook 日聚合的 CloudKit record schema 为 `6`。本地同步状态 schema 为 `4`,能读取上一版 schema `3`--各文件的可恢复等级如下:--| 文件 | 丢失后代价 | 恢复方式 |-| --- | --- | --- |-| `state.json` | 失去上传 hash 和 replacement 进度 | 重新比较并上传,replacement 需依赖仍存在的标记 |-| `cache.jsonl` | 暂时看不到其他设备贡献 | 全量拉取 custom zone |-| `cursor.data` | 失去增量位置 | 全量拉取并重新建立 baseline |--`cursor.data` 使用 secure coding 保存 CloudKit opaque token。代码不解析其内部结构。全量拉取后还要建立新的 cursor baseline,否则下一轮可能从空游标重复消费刚拉取的全部变化。--读取本地 schema `3` 时先重建远端缓存,再保存为 schema `4`;未知 schema 按空同步状态重新同步。--任何 record 字段、identity 或 schema 的变化都是兼容性决策。需要同时考虑旧 App 仍在写入、新 App 如何读取旧字段,以及降级后是否会覆盖新记录,不能只递增一个常量。--## 同步调度器--本地维护和 CloudKit 同步共享聚合输入,但触发频率不同。`WorkflowSyncScheduler` 把多处触发合并为单线程状态机。--优先级为:--```text-用户请求重建 > 可立即执行的同步维护 > 纯本地维护 > 冷却中的同步-```--关键细节包括:--- 同步完成后 8 秒内的新请求合并到下一轮,避免一次 Hook burst 触发多轮网络操作-- 合并请求保留最早 trigger,因为它才是这轮工作的真实起因-- 重建会取消前一个尚未开始的重建 completion,不让调用方永远等待-- 同步在等待期间被关闭时清除 pending sync,但仍允许必要的本地维护继续-- `@Published` 订阅发生在 `willSet`,从回调内读取属性仍是旧值,因此 activation 由新回调参数显式计算后传入--## 失败和恢复语义--同步失败不回滚远端已经写入的记录,也不清空最后一份可用 cache。下轮通过 hash、record ID 和 CloudKit API 继续同步:--| 失败点 | 已保留状态 | 下轮动作 |-| --- | --- | --- |-| zone 或账户确认 | 本地聚合和旧 cache | 重新确认 zone 和 salt |-| 增量拉取 | 旧 cache | 退化为全量重建 |-| 部分上传 | 之前完整批次的 hash 和远端已成功记录 | 重新检查失败批次的所有日期 |-| replacement 删除 | replacement 标记 | 重新枚举并幂等删除 |-| prune | 有效期内数据和上传结果 | 后续再清理 |--同步失败会使 actor 内缓存的 zone 确认和账户 salt 失效。下轮重新解析账户及设备身份;本地状态中的设备身份变化时重建远端缓存。--## 保留与清理--CloudKit 记录保留期与本地 Hook 历史一致,最长 210 天:--- 本地原始和日聚合过期后删除-- 当前设备过期云端记录进入清理-- 本地远端缓存同步移除过期日期-- 清理失败不影响仍在保留期内的数据展示--## 错误分类--同步层区分以下状态,供设置页和主面板显示:--- 网络不可用-- iCloud 账户不可用-- CloudKit 服务不可用-- 服务端要求稍后重试-- 本地数据或 schema 不兼容-- 同步成功或无需变化--临时错误保留最后一份可用远端缓存。账户切换或身份失效时不能继续把旧账户缓存当作当前账户数据。--## 手动验证--- 首次启用后上传保留期内本机聚合-- 第二台设备能够合并显示,不重复当前设备贡献-- 包含和缺少 `interruptCount` 的设备记录合并后,该指标保持不可用-- 关闭同步后只显示本地统计-- iCloud 未登录时显示明确状态,本地统计继续工作-- 网络断开后使用最后缓存,恢复后完成增量同步-- 本机重建后只替换当前设备的 Hook 记录与本机重新读到的 Token 轮次-- Token 重建可降低或清除计数;其他设备刷新后收敛,旧缓存不会恢复旧计数-- 缺失 rollout 时保留已知轮次;本地账本恢复后,旧文件回放不覆盖云端修正值-- 同一轮次的文件副本及跨设备副本只计一次,主线程与子线程按根轮次开始日归属-- 超过 210 天的本地和远端缓存被清理-- iCloud 账户切换后不显示前一账户缓存--## 关键源码--- [`CodexTokenHistoryStore.swift`](../../CodexBar/Services/Workflow/CodexTokenHistoryStore.swift)-- [`CodexTokenHistorySync.swift`](../../CodexBar/Services/Workflow/CodexTokenHistorySync.swift)-- [`WorkflowSyncService.swift`](../../CodexBar/Services/Workflow/WorkflowSyncService.swift)-- [`WorkflowSyncScheduler.swift`](../../CodexBar/Services/Workflow/WorkflowSyncScheduler.swift)-- [`WorkflowSyncSettings.swift`](../../CodexBar/Services/Settings/WorkflowSyncSettings.swift)-- [`CodexWorkflowModels.swift`](../../CodexBar/Models/CodexWorkflowModels.swift)-- [`CodexBar.entitlements`](../../CodexBar/Resources/CodexBar.entitlements)diff --git a/Docs/DeveloperGuide/ui-and-lifecycle.md b/Docs/DeveloperGuide/ui-and-lifecycle.mddeleted file mode 100644index b19e5eb..0000000--- a/Docs/DeveloperGuide/ui-and-lifecycle.md+++ /dev/null@@ -1,371 +0,0 @@-# UI 与应用生命周期--简体中文 | [English](../en/DeveloperGuide/ui-and-lifecycle.md)--## LSUIElement 约束--CodexBar 在 [`Info.plist`](../../CodexBar/Resources/Info.plist) 中配置为 `LSUIElement`--它没有 Dock 图标和普通主窗口生命周期。菜单栏、popover、浮动面板、设置窗口和通知点击都必须显式处理 App 激活与焦点。--UI 使用 SwiftUI 声明内容,由 AppKit Controller 管理窗口。--## `LSUIElement` 下的焦点状态--开发时需要区分:--- App 是否 active-- 某个 window 是否 key-- 菜单表面是否逻辑上 presented--这些状态不会自动同步。例如 Command-Space 会让 App resign active,但用户可能只是临时打开 Spotlight,不希望菜单立即消失。设置窗口可能已经可见,但菜单关闭动画期间不应抢回 key 造成闪烁。--因此代码不使用 `NSApp.isActive` 作为菜单唯一真相,而是维护显式的 menu surface 状态和当前容器,再由事件监听器协调 activation。--## 服务装配--[`CodexBarAppDelegate.swift`](../../CodexBar/Controllers/CodexBarAppDelegate.swift) 是普通模式的 composition root,[`StatusItemController.swift`](../../CodexBar/Controllers/StatusItemController.swift) 只负责菜单栏和相关窗口编排。--### 启动顺序--普通模式的装配顺序体现依赖关系:--```text-创建 settings、数据服务、ViewModel 和更新服务- -> 创建并安装 StatusItemController- -> 装配菜单栏、观察者和快捷键- -> 对账 Hook 并启动周期刷新- -> 启动通知与自动重置- -> 连接异常会话保护回调- -> 启动任务流光订阅- -> 启动 activity monitor 与 keep-alive 协调-```--通知和防睡眠只消费 monitor 已发布的快照或转场,不反向控制 reader。Controller 通过闭包连接这些服务,从而避免服务层依赖 AppKit 容器。--终止时顺序反转,但 helper 系统状态是例外。AppDelegate 先异步确认自动重置唤醒计划已经取消,并确认防睡眠 lease 已释放,全部成功后才允许进程终止。详细事务见 [防睡眠系统](sleep-prevention.md)--## 任务流光--`TaskGlowController` 在 `TaskGlowSettings.isEnabled` 和 `AdvancedModeSettings.isOperable` 均为 `true` 时显示任务状态,与主面板动画开关独立。输入来自 `CodexActivityMonitor.presentationPublisher`,包含当前快照与本轮结束事件,见[展示更新](activity-monitor.md#展示更新)--| 场景 | 展示规则 |-| --- | --- |-| 存在活跃任务 | 等待批准优先于运行 |-| 其他任务仍活跃时确认结束事件 | 最新事件短暂覆盖活动状态后淡出;新事件替换提示并重新计时 |-| 无活跃任务 | 快照中的最新终态按设置的结束时长显示,到期前淡出 |--颜色、速度、亮度和结束时长由 `TaskGlowSettings.appearance` 提供。默认运行使用青色,等待批准使用橙色,完成使用绿色,终止使用红色;结束时间相同优先终止。所有计时包含进场动画,到期后按最新快照恢复展示。--设置从关闭切换为开启且进阶模式可用时,`TaskGlowSettings.previewRequests` 请求一次使用当前外观设置的运行预览,完成一个往返周期后恢复实际状态。启动和设置刷新只恢复开关值,不触发预览。--双击设置面板中的颜色块请求对应状态的预览:运行展示往返流光,等待批准展示呼吸效果,完成和终止短暂显示后淡出。颜色预览可以替换正在播放的预览;收起设置子面板只结束颜色预览。开启预览在已有预览或窗口收尾期间忽略重复请求。--预览覆盖期间继续接收真实任务更新,不产生任务事件。真实结束提示暂停计时,恢复时按最新快照展示:已有提示继续剩余时长,暂停期间产生的提示保留完整时长。预览切换时各屏幕共用开始时刻,旧光带收回时间不占用目标效果的展示时长。--关闭开关取消预览,光带快速收回到中心并淡出,所有屏幕实际收尾完成后移除窗口。Hook 不可用、系统睡眠、屏幕休眠或会话不活跃时取消预览;睡眠期间真实结束提示按墙上时间到期。--光带使用不激活、穿透鼠标的 `NSPanel`,跨 Space 和全屏显示。系统睡眠、屏幕休眠或用户会话不活跃时移除窗口,恢复后按当前时间接续有效状态。屏幕配置变化时重建窗口,各显示器共享运动时钟。运动时钟根据分段时长和速度计算周期,改速时保留当前进度。--## 状态栏图标--状态图标综合 app-server 加载状态、菜单栏额度设置和任务活动快照。--图标优先级是:--```text-账户异常 > 等待批准 > 运行中 > 最近 10 秒内的完成或终止 > 空闲-```--`CodexActivitySnapshot.statusItemActivity(at:)` 在没有活跃任务时按结束时间选择最新终态。`StatusItemController` 按结束时间加 10 秒安排到期任务,到期后恢复普通人形;系统唤醒时按当前时间重算,状态变化和卸载时取消旧任务。--### 分离图标与 tooltip 状态--`StatusIconState` 保存活动、额度和 `ordinaryUsageAllowed` 输入。`StatusItemIconPresentation` 发布符号名称、常规用量受限状态、额度、显隐和缓存标记,相同渲染状态不会重复发布:--- 活跃任务持续时间每分钟变化,只更新 tooltip-- 额度过期但仍展示缓存时,图标和进度使用降低后的 alpha-- `StatusItemIconView` 按符号名称和屏幕倍率缓存预渲染图片,缩放时复用图片,避免带徽章符号实时渲染时的卡顿-- 符号名称变化时,新旧图片交叉淡入淡出并配合缩放过渡;只切换额度显隐时不触发图片替换-- 额度显隐时将彩色圆弧从零绘制到当前额度,或从当前额度收回到零,底轨独立淡入淡出-- 人物按符号基线对齐,隐藏额度时恢复正常大小;大小和位置平滑过渡-- 关闭额度时保留最后的额度和配色供收回动画使用,零额度与缺失额度保持不同语义-- 初次渲染和唤醒重算时不播放过渡动画--SwiftUI 视图持续挂载在原生 `NSStatusBarButton` 中,透明图片用于系统自适应占位。`ordinaryUsageAllowed == false` 时,人物及徽章使用适配浅色、深色外观的浅橙色;值为 `true` 或缺失时使用系统前景色。额度圆弧按剩余比例配色。宿主视图不接受焦点或鼠标命中,左右键交给原按钮处理。--圆弧和人物通过 `drawingGroup()` 合成为一个绘制结果,保持全屏与普通桌面切换时额度圆弧的长度和颜色一致。--tooltip 在存在活跃任务时每 60 秒更新,空闲时停止计时。--左键打开主面板。右键或按住 Control 点击打开上下文菜单。--## 主面板--主面板优先使用 `NSPopover`,`behavior` 设为 `applicationDefined`,`animates` 设为 `false`--[`MenuSurfaceDismissMonitor.swift`](../../CodexBar/Controllers/MenuSurfaceDismissMonitor.swift) 监听鼠标、键盘和激活事件,通过 `onDismiss` 请求关闭。[`MenuSurfaceFadeCoordinator.swift`](../../CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift) 执行淡入淡出,`StatusItemController` 通过 `NSPopoverDelegate` 接收 popover 的实际关闭回调。--### 开合状态机--`menuSurfaceState` 的状态流转如下:--```text-hidden -> opening -> shown -> closing -> hidden-```--各状态的操作如下:--- `opening` 或 `shown` 时再次 toggle 进入关闭-- `closing` 时再次 toggle 先完成旧关闭,再打开新表面-- 关闭开始后取消未完成的淡入任务-- 非动画关闭直接完成状态清理--`activeMenuSurface` 记录当前容器,取值为 `none`、`popover` 或 `fallbackPanel`。主动关闭容器前先将其设为 `none`--`popoverDidClose` 只处理当前 popover 已关闭的通知,并关闭该宿主的动画许可。当前容器仍为 `popover` 时,它调用 `completeMenuSurfaceClose`,取消待执行任务、收起侧边面板、移除事件监听、结束展示状态并安排辅助窗口焦点恢复。--### 关闭事件监听--主面板的允许点击区域是一个集合:--```text-当前菜单窗口 + status item 按钮 + 所有已显示侧边面板-```--本地 monitor 处理 App 内鼠标和键盘,global monitor 处理其他 App 上的鼠标点击,workspace 和 window observer 处理激活变化。任一入口最后都调用同一 `onDismiss`--特殊规则包括:--- Escape 消费事件并关闭-- Command-Tab 允许系统切换,同时关闭面板-- Command-Space 短暂抑制 activation dismiss,避免打开 Spotlight 时误关-- 点击后重新固定 `NSVisualEffectView` 为 inactive,避免 AppKit 自动强调背景导致明暗跳变-- 初次安装 observer 后 `Task.yield()` 再补一次窗口获取和聚焦,覆盖 popover window 尚未挂载的时机-- 菜单窗口聚焦只执行 `orderFrontRegardless()` 和 `makeKey()`,不额外激活 App,避免原生 popover 在其他 App 全屏时因激活切换而关闭;备用面板在自身展示入口处理 App 激活--### 淡入淡出与完成任务--`MenuSurfaceFadeCoordinator` 同时调整活动容器的内容视图和窗口透明度,实现面板的淡入淡出。控制器只保存一个完成任务;新动画开始前取消旧任务,任务等待结束后检查取消状态,再标记已显示或完成关闭。--关闭期间设置和日志窗口暂时拒绝 `makeKey()`,关闭完成后短暂延迟再恢复。完成任务弱引用当次窗口,关闭后恢复内容视图和窗口透明度。--### 内容动画与展示状态--popover 和备用面板分别持有 `MenuSurfaceAnimationState`。展示前将 `allowsAnimations` 设为 `true`,淡出期间保持开启,实际关闭后设为 `false`--`CodexStatusMenuView` 在宿主动画许可关闭时,将根视图事务的 `animation` 设为 `nil`、`disablesAnimations` 设为 `true`。主面板内的持续动画使用 `mainPanelAnimationsEnabled` 环境值,同时要求宿主动画许可和设置中的“动画效果”开关开启。宿主隐藏或用户关闭动画效果时移除持续动画视图,后台数据刷新继续执行。--`MenuSurfaceVisibilityState` 在面板展示后开启,在关闭开始时结束。每次展示递增 `presentationGeneration`,额度和用量区域以该值作为视图身份,重新执行入场动画。--主面板根视图使用固定宽度和内容所需的高度。Popover 通过 `preferredContentSize` 跟随内容尺寸;备用面板通过 `onGeometryChange` 获取内容高度,在可见时直接更新窗口高度,保持宽度和顶边位置。--### 活动卡片--`CodexActivityCard` 使用 `primaryActivity`,优先显示等待批准,其次是运行中;无活跃任务时按结束时间选择最新的完成或终止,时间相同优先终止。`isActivelyPreventingSleep` 为 `true` 且卡片数据可用时显示青绿色 `sun.max.fill`,tooltip 按 `sleepPreventionSource` 显示来源。所属宿主的 `mainPanelAnimationsEnabled` 开启时,太阳徽标匀速顺时针旋转;关闭时移除旋转视图并显示静态图标。--活动卡片和任务中心共用 `CodexActivityStatusText`,文字颜色跟随任务状态。运行时显示扫光,等待批准时显示橙色粒子,完成和终止时静态显示。卡片状态文字动画由 `mainPanelAnimationsEnabled` 控制,任务中心状态文字动画要求 `presentationState.isPresented` 和 `MainPanelSettings.areAnimationsEnabled` 同时开启。每个面板共用一条粒子时间线,只从可见的等待文字发射粒子,按面板边界裁剪;没有发射源时移除时间线。--活动卡片在 `primaryActivity.tokenUsage` 可用时展示 Token 指标和分割线,为空时隐藏整个用量区域。完成或终止后的用量补读在后台进行,界面先显示结束状态,取得用量后再展开指标;查询到期不显示超时提示。任务中心的完成和终止条目仅在用量可用时显示总 Token。状态行固定在卡片顶部,卡片高度随 Token 区域显隐调整。--展开和收起采用平滑减速的过渡,独立于“动画效果”设置。Token 区域随展开进度淡入并轻微上移,收起时提前淡出。`ActivityCardHeight` 逐帧提交插值后的布局高度,使相邻区块和主面板尺寸同步变化。防睡眠徽标、匿名图标和并发任务数的动画限定在状态行内。--## Fallback panel--全局快捷键触发时,状态栏按钮的屏幕位置可能不可用或不可信。此时 [`FallbackPanelController.swift`](../../CodexBar/Controllers/FallbackPanelController.swift) 在鼠标所在屏幕显示浮动面板。--### 锚点校验--全局快捷键可能在 status item 尚未完成布局、菜单栏位于另一块屏幕,或系统暂时不给出 button window 时触发。代码不会只检查 button 非 nil,还验证:--- window 和 screen 存在-- button 没有隐藏且 bounds 非空-- 转换后的屏幕 rect 有效且满足最小尺寸要求-- rect 与目标屏幕 frame 在允许的容差内相交--只有全部成立才使用 popover 箭头。否则 fallback panel 放到鼠标所在屏幕。这避免 popover 被 AppKit 放到错误显示器或完全不可见的位置。--fallback panel 展示前使用主面板固定宽度和 SwiftUI fitting height,在目标屏幕可见区域水平居中,顶部留有间距。无法取得有效 fitting size 时,使用默认高度。--## 侧边详情面板--主面板可以打开:--- 活跃度热力图详情-- Reset Credits 详情-- 活动中心--这些面板互斥,打开一个时关闭其他侧边面板。它们会把自己的屏幕区域加入主表面的额外 hit region,用户在主面板和侧边面板之间移动或点击时不会触发误关闭。--所有详情面板实现 `MenuSideDetailPanel` 并登记在 `sideDetailPanels` 数组。互斥关闭、主表面关闭和 hit testing 都遍历同一份名册。--热力图悬停请求以动画收起其他侧边面板;重置次数和任务中心的点击请求立即关闭其他侧边面板。--主面板关闭时立即清理侧边面板。热力图详情和共享抽屉在立即关闭或窗口已不可见时,重置抽屉动画、执行 `orderOut` 并移除父子窗口关系。任务中心已结束逻辑展示时,立即关闭请求仍传递给共享抽屉。--热力图按格子的列、行位置错开入场。启用入场动画时,每个格子在入场过渡后接受悬停;关闭入场动画时立即接受悬停。--热力图详情面板以包含标题、日期范围和方格矩阵的完整热力图区域作为垂直锚点,因此主面板区域重排后仍优先保持两者顶边对齐。如果详情面板从该位置向下会超过主面板底边,则定位逻辑将它整体上移到与主面板底边对齐。--主面板可见时,数字随数据变化滚动,Token 数字与待查询或不可用占位之间淡入淡出。“动画效果”控制入场动画、太阳徽标旋转和任务状态文字动画,数字更新不受此开关控制。--进阶模式开启时,热力图详情按活动统计和会话 Token 分组,并展示用量强度条。各组用 `Grid` 对齐名称和数值。日期切换时,Token 与活动数值使用相同的 `numericText` 过渡,最常用模型使用同一文本视图过渡并按可用宽度缩小字号。--共享 `LiquidGlassDivider` 使用银灰和冷白渐变,缓慢循环移动。它通过所在 `NSView` 的窗口可见状态暂停或恢复时间线,不受“动画效果”设置控制。--相关控制器包括:--- [`HeatmapDetailPanelController.swift`](../../CodexBar/Controllers/HeatmapDetailPanelController.swift)-- [`ResetCreditsPanelController.swift`](../../CodexBar/Controllers/ResetCreditsPanelController.swift)-- [`ActivityCenterPanelController.swift`](../../CodexBar/Controllers/ActivityCenterPanelController.swift)-- [`SidePanelSupport.swift`](../../CodexBar/Controllers/SidePanelSupport.swift)--## 设置和日志窗口--设置与日志由独立的 `HostingWindowController` 管理 `NSWindow`--打开设置或日志窗口时,`HostingWindowController` 允许目标窗口成为 key 并激活 App。`AuxiliaryHostingWindow` 可以成为 key window,但不能成为 main window。--上下文菜单 action 会延迟到 menu tracking 结束后执行,避免 AppKit 仍在菜单事件循环中时创建或激活窗口。--### 辅助窗口的持有和定位--`HostingWindowController` 懒创建并长期复用单个 window:--- `isReleasedWhenClosed = false`,关闭只隐藏,下次保留窗口对象和 SwiftUI 状态-- `.moveToActiveSpace`,重开时跟随当前 Space,不把用户切回旧桌面-- 优先在 status item 所在屏幕居中,再退到 window screen 或 main screen-- miniaturized 窗口先 deminiaturize 再激活--设置窗口按当前 tab 的完整内容调整高度,固定上边缘,并限制到屏幕可见区域。内容超出屏幕高度时使用 `ScrollView`。--SwiftUI 可能在窗口创建完成前上报高度。`SettingsWindowController` 缓存最近一次有效测量,在 `HostingWindowController.window` 就绪后应用。--主面板布局、流光、通知、自动重置和防睡眠的二级设置面板在首次打开时创建,之后复用内容及必要的高度变化订阅。--这些设置子面板使用可获得键盘焦点的 `KeyableBorderlessPanel`,展开时保留主设置窗口的焦点,点击输入框后进入编辑。收起面板前结束原生编辑,颜色输入在结束编辑回调中完成校验并同步显示。主面板的热力图、Reset Credits 和活动中心详情使用不会激活的 `NonactivatingSidePanel`。收起设置子面板时,`SidePanelSupport.orderOut` 只在该子面板仍是 key window 时恢复父窗口焦点;焦点已转移到其他窗口时不恢复父窗口焦点。--自动重置与防睡眠从关闭切换为开启时,`AppSettingsView` 使用 `HelperFeatureConfirmation` 显示统一确认框。确认框按 `KeepAliveController.HelperStatus` 组合 Helper 提示与对应功能说明,用户确认后才调用设置对象写入开启状态。已开启设置行在 `.requiresApproval` 状态显示 `打开系统设置` 按钮。--二级设置入口使用各自的可用性结论:--- 主面板布局入口始终可用-- 流光要求 `TaskGlowSettings.isEnabled`、`AdvancedModeSettings.isOperable` 为 `true`,且进阶模式未在更新-- 通知读取 `NotificationSettings.canShowOptions`-- 自动重置要求 `AutoResetSettings.isEnabled` 且 `KeepAliveController.helperStatus == .enabled`-- 防睡眠读取 `KeepAliveController.canShowOptions`--入口条件失效时设置页发送对应的 `close` 动作,避免不可用的子面板继续显示。主开关关闭时,自动重置和防睡眠设置行不显示状态说明。--`MainPanelSettings` 使用稳定区域标识保存账户、任务中心、额度、Token 用量和底部状态的顺序与显隐。布局归一化会去重、忽略无效值、补齐缺失区域,并保证至少保留一个可见区域。`StatusItemController` 在读取到进阶模式关闭状态后调用 `updateAdvancedModeEnabled(_:)`,持久化关闭任务中心;如果任务中心原本是唯一可见区域,则同时开启账户区域。从关闭切换到开启时自动显示任务中心,首次恢复开启状态和重复开启通知均保留用户布局。设置面板只禁用任务中心开关,拖拽手柄仍保持可用。其他数据链路的临时可用性只影响当次渲染。--布局排序使用手柄上的自定义 `DragGesture`。拖动项通过悬浮副本跟随指针,其他行随拖动位置按视图内预览顺序实时让位,松手后才调用 `setSectionOrder(_:)` 一次性持久化最终顺序。--`SettingsWindowController` 持有这一窗口组唯一的 `UndoManager`。设置主窗口通过 `AuxiliaryHostingWindow` 暴露它,各设置子面板展示时从父窗口取得同一实例,因此焦点位于设置主窗口或任一子面板时,`⌘Z` 和 `⌘⇧Z` 都作用于同一份布局历史。Hook 状态变化引起的任务中心自动显隐不进入用户撤销历史。--### 代理配置对话框--`CodexBarAppDelegate` 持有 `CodexProxySettings`,并经窗口控制器注入设置页。`AppSettingsView` 使用 SwiftUI `sheet` 展示 `ProxySettingsView`,打开前关闭侧边设置面板。--未配置时点击整行或开关都会打开配置;已有配置时,行主体打开对话框,开关单独启停。对话框显示时从本机偏好加载草稿,关闭时取消测试并清空内存中的密码草稿。右上角清除菜单按保存记录是否存在显示,即使记录无法解码也可使用。--关于页面的重连按钮紧邻 `Codex 版本` 标题,来源选择器位于行尾。重连及刷新期间两者禁用;没有可用来源时重连按钮禁用。--重连按钮的持续绘制或摆动动画只在设置窗口可见且正在重连或刷新时创建。`SettingsWindowController` 根据窗口遮挡、最小化和关闭通知更新动画许可;窗口隐藏时移除整个动画分支,恢复可见后按当前忙碌状态重新创建。切离关于页时,现有分页分支会移除版本区。窗口是否获得键盘焦点不参与动画许可判断。--## 全局快捷键--[`GlobalHotKeyController.swift`](../../CodexBar/Controllers/GlobalHotKeyController.swift) 使用 Carbon Hot Key API。--快捷键约束:--- 至少包含 2 个修饰键-- 拒绝 `Command-Space`-- 拒绝 `Command-Tab`-- 系统注册冲突时回滚到之前可用设置-- 设置变更立即重新注册--Carbon API 适合无 Dock 菜单栏 App,不需要安装全局键盘事件 tap 或请求输入监控权限。--注册新快捷键采用先试后换:--1. 为候选快捷键安装临时 handler 和 hot key-2. 注册成功后才释放当前 registration-3. 注册失败时清理候选资源并恢复设置中的旧值--`GlobalHotKeyRegistration` 在显式 invalidate 和 deinit 中清理 Carbon 引用。--## 自动刷新与面板打开--app-server 状态按数据更新间隔自动刷新,可选 1、2、3、5 或 10 分钟,默认 1 分钟。主面板淡入完成且面板仍可见时,调用 `refreshIfNeeded`;倒计时起点为空或已达到所选间隔时才发起请求。成功和失败的结果提交都会重置倒计时。修改间隔只重新安排等待任务,不取消正在进行的请求。--主面板显示刷新倒计时,双击账户图标可立即手动刷新。--普通刷新在刷新或重连进行中被忽略。需要在当前请求后补刷的操作通过 `refreshAfterCurrent` 保存一个待执行触发,当前请求结束后再执行。--淡入完成回调依次触发 Hook 配置对账、进阶模式开启时的本地统计刷新检查,以及账户、额度和用量刷新检查。面板在淡入完成前关闭时,取消完成任务及其尚未触发的刷新。--## 本地化和格式化--简体中文和英文界面字符串位于 [`Localizable.xcstrings`](../../CodexBar/Resources/Localizable.xcstrings)--百分比、时长和部分时间显示使用系统地区设置。`CodexDateFormat` 的日期键及日期范围固定为 `yyyy-MM-dd`,设置页最后上传时间和重置次数详情固定为本地时间 `yyyy-MM-dd HH:mm:ss`。本地化字符串不参与状态机判定。--## 自动更新--[`AppUpdater.swift`](../../CodexBar/Services/Updates/AppUpdater.swift) 封装 Sparkle:--- appcast URL 来自 App 配置-- 自动检查间隔为 3600 秒-- 更新 UI 由设置页和主面板的新版本提示触发-- CodexBarHelper 变化在更新后单独执行 fingerprint 和注册状态检查--发布脚本需要 Developer ID、签名和公证凭据,不属于日常本地构建流程。--## 手动验证--- 左键打开主面板,右键和 Control 点击打开上下文菜单-- 多任务运行或等待批准期间,完成和终止触发短暂流光提示;颜色跟随配置,全部任务结束后按所选结束时长到期-- 开启流光按当前颜色、速度和亮度播放一次预览,关闭时收回并淡出,收尾期间不重播开启预览,收尾后可再次开启预览;双击颜色块可连续替换预览,收起子面板结束颜色预览;恢复时已有结束提示继续剩余时长,预览期间产生的提示按最新状态显示并保留完整时长-- 历史重读及唤醒对账不补播旧终态短提示,恢复后的真实结束仍有提示;多显示器和屏幕配置变化后运动与到期时间一致-- 菜单栏符号随任务状态切换,最新终态在结束 10 秒后恢复空闲,跨睡眠唤醒后按当前时间显示-- 普通人物与各任务徽章之间切换时过渡完整,快速连续切换后显示最新状态;带徽章时反复切换额度显隐仍保持流畅,首次显示和唤醒重算不播放过渡-- 切换额度圆弧显隐时动画完整,零额度保留底轨,缓存额度变淡-- 防睡眠生效时太阳徽标仅在“动画效果”开启且所属面板展示期间旋转;关闭动画效果后保留静态太阳,再次开启后仅可见宿主恢复旋转;冷启动后不打开面板、关闭后继续运行任务时均无持续旋转开销;重开、快速开关和 popover 与 fallback 切换后均保持匀速旋转,任务结束后徽标消失-- 代理密码显隐切换时淡化正常,输入内容、选区和焦点保留-- 点击主面板外部正确关闭,点击侧边面板不误关闭-- 热力图、Reset Credits 和活动中心保持互斥-- 活动卡片和任务中心在运行、等待批准、完成和终止之间切换时,文字颜色与动画匹配;关闭“动画效果”后保持静态,关闭面板后停止持续动画;滚动任务中心时,仅可见的等待文字发射粒子-- Token 用量区域处于不同排序位置时,热力图详情优先与完整热力图区域顶边对齐;详情高度放不下时与主面板底边对齐-- 全局快捷键在状态栏锚点有效和无效场景都能打开面板-- 从通知点击激活 App 并打开面板-- 设置窗口首次打开、关闭和再次打开时焦点正确-- 关于页刷新或重连期间,关闭、最小化、完全遮挡设置窗口或切离关于页后,重连图标不再持续绘制或摆动;恢复展示后仅在仍忙碌时恢复动画,窗口失焦但仍可见时行为正常-- 冷启动后首次打开设置时通用页直接使用完整内容高度;切换各设置页时窗口高度自适应,屏幕空间充足时均不显示滚动条-- 主面板布局、流光、通知、自动重置和防睡眠子面板互斥,顶边对齐对应设置行,内容变化后高度正确-- 流光子面板展开时颜色输入框不自动聚焦;六位输入限制、粘贴过滤和大写转换正确;无效颜色在回车、失焦及收起时恢复默认,显示与实际颜色一致-- 设置子面板展开时从菜单栏打开主面板,主面板保持打开,设置子面板收起且不把焦点抢回设置窗口-- 主面板区域拖动时悬浮行跟随指针,其他行随拖动位置实时让位,松手后平滑落位并只保存最终顺序;拖拽和显隐操作可以通过 `⌘Z` 逐步撤销并通过 `⌘⇧Z` 重做,焦点在设置主窗口或任一设置子面板时均有效;重启后保持配置,最后一个可见区域无法关闭;进阶模式关闭时任务中心自动关闭、开关置灰但仍可拖动,任务中心为唯一可见区域时账户自动开启;重新开启进阶模式后任务中心自动显示,手动隐藏后重启仍保持隐藏,自动联动不进入用户撤销历史-- 上下文菜单打开设置或日志时没有焦点丢失-- 多显示器和不同菜单栏位置下 fallback panel 位于鼠标屏幕-- 快捷键冲突后原快捷键仍可用-- 面板打开刷新不会造成动画卡顿或重复请求-- 数字首次递减、连续增减、Token 单位切换和日期跨月时方向正确,主面板关闭后停止数字动画--- 中英文下快速切换热力图日期,名称列宽稳定,Token 数字和模型名原位过渡-- Token 区域从无到有、由有到无或动画中途反向切换时,卡片、相邻区块和 popover、fallback 尺寸同步变化,区块间距不变且无重叠;关闭动画设置后仍保留此效果-- 所有共享分割线缓慢流动,关闭或隐藏所属窗口后停止持续绘制--## 关键源码--- [`CodexBarAppDelegate.swift`](../../CodexBar/Controllers/CodexBarAppDelegate.swift)-- [`StatusItemController.swift`](../../CodexBar/Controllers/StatusItemController.swift)-- [`FallbackPanelController.swift`](../../CodexBar/Controllers/FallbackPanelController.swift)-- [`MenuSurfaceDismissMonitor.swift`](../../CodexBar/Controllers/MenuSurfaceDismissMonitor.swift)-- [`MenuSurfaceFadeCoordinator.swift`](../../CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift)-- [`GlobalHotKeyController.swift`](../../CodexBar/Controllers/GlobalHotKeyController.swift)-- [`SettingsWindowController.swift`](../../CodexBar/Controllers/SettingsWindowController.swift)-- [`LogWindowController.swift`](../../CodexBar/Controllers/LogWindowController.swift)-- [`CodexStatusMenuView.swift`](../../CodexBar/Views/Menu/CodexStatusMenuView.swift)-- [`StatusItemIconView.swift`](../../CodexBar/Views/Menu/StatusItemIconView.swift)-- [`CodexActivityCard.swift`](../../CodexBar/Views/Menu/CodexActivityCard.swift)diff --git a/Docs/README.md b/Docs/README.mddeleted file mode 100644index 317b65e..0000000--- a/Docs/README.md+++ /dev/null@@ -1,33 +0,0 @@-# CodexBar 文档--简体中文 | [English](en/README.md)--## 用户指南--- [安装与快速开始](UserGuide/getting-started.md)-- [主面板与菜单栏](UserGuide/main-panel.md)-- [实时任务与进阶模式](UserGuide/advanced-mode.md)-- [通知与提醒](UserGuide/notifications.md)-- [防止系统睡眠](UserGuide/sleep-prevention.md)-- [数据、同步与隐私](UserGuide/sync-data-privacy.md)-- [设置参考](UserGuide/settings.md)-- [常见问题与排查](UserGuide/troubleshooting.md)--## 开发者指南--- [整体架构](DeveloperGuide/architecture.md)-- [设计原则与关键决策](DeveloperGuide/design-decisions.md)-- [app-server 数据链路](DeveloperGuide/app-server.md)-- [Hook 采集与历史聚合](DeveloperGuide/hook-and-aggregation.md)-- [实时任务监控](DeveloperGuide/activity-monitor.md)-- [防睡眠系统](DeveloperGuide/sleep-prevention.md)-- [CloudKit 同步](DeveloperGuide/sync.md)-- [通知系统](DeveloperGuide/notifications.md)-- [UI 与应用生命周期](DeveloperGuide/ui-and-lifecycle.md)-- [数据与隐私边界](DeveloperGuide/data-and-privacy.md)-- [开发与验证](DeveloperGuide/development.md)--## 在线资料--- [运行架构](https://codexbar.zabrian.app/architecture)-- [性能报告](https://codexbar.zabrian.app/performance)diff --git a/Docs/UserGuide/advanced-mode.md b/Docs/UserGuide/advanced-mode.mddeleted file mode 100644index a2049f5..0000000--- a/Docs/UserGuide/advanced-mode.md+++ /dev/null@@ -1,50 +0,0 @@-# 实时任务与进阶模式--简体中文 | [English](../en/UserGuide/advanced-mode.md)--进阶模式用于显示实时任务,并支持任务通知、触觉反馈、按任务防睡眠,以及每日会话、轮次和工具调用统计。开启后也可以同步每日活动统计和 rollout Token 历史;重建数据可重新计算本机保留的两类历史。--## 开启方法--1. 打开 `设置 > 高级`-2. 开启 `进阶模式` 并等待校验完成-3. 开始一轮 Codex 任务,在主面板查看状态--进阶模式要求当前使用的 Codex 为 `0.153.0` 或更高版本。更新后仍提示版本过低时,在 `设置 > 关于` 点击 `重新建立连接`。其他错误见 [常见问题与排查](troubleshooting.md#进阶模式无法开启或校验失败)--CodexBar 自动检查和修复已开启的 Hook 配置,保留用户和其他 App 的 handler。确认 Codex 低于最低版本时,会关闭进阶模式并移除自己的 handler;更新 Codex 后需要重新开启进阶模式。暂时无法连接或确认版本时保留配置,等待下次校验。--## 任务状态--| 状态 | 含义 |-| --- | --- |-| 运行中 | Codex 正在处理任务 |-| 等待批准 | 需要你批准下一步操作 |-| 最近完成 | 一轮任务已结束,不代表结果一定成功 |-| 最近终止 | 中断或其他终态信号确认任务终止,不发送完成通知 |--收到 `Stop` 后会先显示“正在收尾”;仍有子 Agent 等待批准时优先显示等待。确认本轮完成且满足通知设置后才发送完成提醒,期间中断则显示已终止。--中断只结束对应轮次,同一会话随后开始的新任务保持活跃。全部符合条件的任务结束后,按任务防睡眠会释放。--子 Agent 的活动合并到所属任务中。内部自动审核任务和来源始终无法确认的任务不显示为实时任务,也不触发流光、任务提醒或防睡眠;它们的活动仍计入每日统计。同一会话和轮次已确认是正常任务后,后续暂时无法识别来源的事件仍会更新任务状态。--主 Agent 或子 Agent 等待批准时,其他 Agent 的进展不会解除它的等待。只要该任务仍有一项用户审批等待,卡片就继续显示等待状态。--来源明确但无法识别会话的任务会带有橙色匿名图标。这类任务可以查看,但不触发通知或触觉反馈,也不参与防睡眠和异常会话保护。--长时间没有进展的运行任务可能被 [异常会话保护](sleep-prevention.md#异常会话保护) 隐藏,恢复进展后重新显示。--## 每日统计--在主面板热力图上悬停日期,左栏显示当天的会话数、对话轮次、工具调用、权限请求、上下文压缩、子 Agent 和最常用模型,右栏显示会话 Token 汇总。Token 按根轮次开始日累计,与活动计数的按日归属方式不同。详见 [Token 用量与热力图](main-panel.md#token-用量与热力图)--会话和轮次按天去重,跨天继续活动会计入新的一天。当天只有会话结束事件的会话,以及只有完成候选或中断事件的轮次,不计入当天活跃数。工具调用按开始和结束事件数的较大值统计。--## 关闭进阶模式--关闭后,实时任务、任务通知、触觉反馈、防睡眠和 Hook 统计停止更新,活动与 Token 历史的跨设备同步停止。热力图隐藏历史详情,账户、额度和 app-server Token 热力图仍可使用。--Hook 记录任务的时间、模型、工具名和项目等信息,不保存提问、回复或工具输入输出正文。保存期限与同步内容见 [数据、同步与隐私](sync-data-privacy.md)--返回 [用户指南](../README.md#用户指南)diff --git a/Docs/UserGuide/getting-started.md b/Docs/UserGuide/getting-started.mddeleted file mode 100644index be18e07..0000000--- a/Docs/UserGuide/getting-started.md+++ /dev/null@@ -1,73 +0,0 @@-# 安装与快速开始--简体中文 | [English](../en/UserGuide/getting-started.md)--## 运行要求--- macOS 15.0 或更高版本-- 已安装并登录 [Codex CLI](https://github.com/openai/codex),或安装了内置 Codex 的 ChatGPT App 或 Codex App-- 当前使用的 Codex 版本需要为 `0.145.0` 或更高版本-- 启用进阶模式时,当前使用的 Codex 版本需要为 `0.153.0` 或更高版本-- 使用跨设备同步时,Mac 需要登录可用的 iCloud 账户--CodexBar 默认自动选择来源,优先使用全局安装的 Codex CLI,找不到时再尝试 ChatGPT App 和 Codex App 内置的 Codex。可在“设置 > 关于 > Codex 版本 > 来源”中手动选择。--## 安装--### 通过 Homebrew--```bash-brew install --cask bob-zebedy/tap/codexbar-```--### 通过 DMG--1. 从 [GitHub Releases](https://github.com/bob-zebedy/CodexBar/releases) 下载最新 DMG-2. 打开 DMG 并将 CodexBar 拖入 Applications-3. 从 Applications 启动 CodexBar--## 第一次启动--CodexBar 是菜单栏 App,启动后不会在 Dock 中显示图标:--1. 在屏幕顶部菜单栏找到 CodexBar 图标-2. 左键点击图标打开主面板-3. 等待首次账户和用量刷新完成-4. 如果显示未登录,先在当前 Codex 中完成登录-5. 如果需要实时任务、任务类通知、防睡眠或 Hook 统计,在 `设置 > 高级` 中开启进阶模式--CodexBar 默认每 1 分钟自动刷新账户、额度和 Token 用量,可在 `设置 > 高级 > 数据更新间隔` 选择 1、2、3、5 或 10 分钟。双击主面板中的账户图标可以立即刷新。--## 基本操作--| 操作 | 结果 |-| --- | --- |-| 左键点击菜单栏图标 | 打开或关闭主面板 |-| 右键或 Control 点击菜单栏图标 | 打开设置、日志和退出菜单 |-| `⌘⇧E` | 使用默认全局快捷键打开或关闭主面板 |-| `⌘,` | 打开设置窗口 |-| `⌘L` | 主面板打开时关闭面板并打开日志窗口 |-| 双击账户图标 | 立即刷新账户、额度和用量 |-| 双击账户邮箱 | 切换邮箱模糊显示 |-| 悬停热力图方块 | 查看当天 Token 和 Hook 统计 |-| 点击活动卡片 | 打开并发任务中心 |-| 点击 `留存重置` | 查看各批次过期时间 |-| `设置 > 高级 > 自动重置` | 配置是否自动重置以及提前量 |--全局快捷键优先在鼠标所在屏幕打开主面板,菜单栏锚点不可用时会使用独立浮动面板。--## 开启更多功能--- [进阶模式](advanced-mode.md):实时任务、每日活动统计和按任务防睡眠-- [系统通知](notifications.md):任务和额度提醒,需允许 macOS 通知权限-- [自动重置](settings.md#自动重置):提前使用即将过期的留存重置,可能短暂唤醒 Mac-- [防止系统睡眠](sleep-prevention.md):长任务期间保持 Mac 唤醒,需批准后台服务-- [跨设备同步](sync-data-privacy.md):合并多台 Mac 的 Hook 统计,需登录 iCloud--## 语言与地区--CodexBar 提供简体中文和英文界面,默认跟随 macOS 的 App 语言偏好。--需要单独切换时,可在 macOS 系统设置的语言与地区页面为 CodexBar 指定 App 语言。--下一步可以阅读 [主面板与菜单栏](main-panel.md) 或 [设置参考](settings.md)diff --git a/Docs/UserGuide/main-panel.md b/Docs/UserGuide/main-panel.mddeleted file mode 100644index 8b4eab8..0000000--- a/Docs/UserGuide/main-panel.md+++ /dev/null@@ -1,153 +0,0 @@-# 主面板与菜单栏--简体中文 | [English](../en/UserGuide/main-panel.md)--## 菜单栏图标--CodexBar 用人物图标和可选额度圆弧表达账户、任务和额度状态:--| 外观 | 含义 |-| --- | --- |-| 普通人形 | 默认或空闲状态 |-| 浅橙色人物及徽章 | 账户数据表明常规用量受限 |-| 斜杠人形 | 未登录、初始化失败或缺少可信额度与用量数据 |-| 时钟徽章 | 至少有一个任务正在运行 |-| 钥匙徽章 | 至少有一个任务正在等待用户批准 |-| 盾牌勾徽章 | 任务刚刚完成,显示 10 秒 |-| 盾牌感叹号徽章 | 任务刚刚被终止,显示 10 秒 |-| 人物上方的缺口圆弧 | 所选额度窗口的剩余比例,颜色与面板百分比一致 |--多个状态同时存在时,账户异常优先,其次是等待批准、运行中,最后是最近 10 秒内的完成或终止;两种结束记录按时间选择最新的一条。--隐藏额度圆弧时,人物图标会放大。--鼠标悬停在菜单栏图标上可以查看当前任务状态、项目名、持续时间、并发任务数量和额度窗口剩余比例。--显示缓存额度时,图标和圆弧变淡。额度为零时保留底轨;没有额度数据或关闭显示时隐藏圆弧。--## 自定义布局--在 `设置 > 通用 > 主面板布局` 中调整区域顺序和显隐,支持撤销与重做。具体操作见 [设置参考](settings.md#主面板布局)--## 账户区域--- 展示当前登录账户或账户类型-- 展示 Enterprise, Team, Business, ProMax, Pro, ProLite, Plus, Go, Edu 和 Free 等套餐标识-- 双击账户图标会立即刷新账户、额度和用量-- 双击邮箱会切换模糊显示-- 未登录时显示 `未登录`-- 当前 Codex 版本低于要求时显示最低版本提示-- Codex 连接无法初始化时显示 `初始化失败`--具体连接失败原因可在设置的关于页面查看,完整请求和响应可在日志窗口查看。--## 额度区域--CodexBar 会展示 Codex 返回的全部额度分组和窗口。--每个额度窗口包含以下信息:--- 窗口名称,例如 `5 Hours` 或 `Weekly`-- 剩余比例-- 分段进度条-- 下一次重置时间--开启 `动画效果` 时,分段进度条会在每次打开主面板时从零填充到当前剩余比例。--玻璃分割线的渐变会缓慢流动,独立于 `动画效果` 开关;所在窗口隐藏后暂停。--主额度分组还可能展示以下信息:--- 可用积分或无限积分状态-- 可用留存重置-- 每批留存重置的过期时间--点击 `留存重置` 可查看各批次的过期时间,入口只在可用次数大于 `0` 时显示。--## Token 用量与热力图--账户用量来自 app-server,汇总区域会展示以下指标:--- 全时累计 Token-- 单日 Token 峰值-- 当前连续使用天数-- 最长连续使用天数-- 最长任务时长--热力图按日期展示近期每日 Token 用量,颜色强度相对于当前热力图中的峰值计算。--开启 `动画效果` 时,日期方块会在每次打开主面板时从左上到右下依次展示。--悬停日期方块时会显示日期、Token 数量和用量强度。--进阶模式开启时,日期详情还会显示以下统计:--- 最常用模型-- 会话数-- 对话轮次-- 子 Agent 数-- 工具调用次数-- 权限请求次数-- 上下文压缩次数--日期详情按活动统计和 rollout 日 Token 用量分组展示,并通过强度条表示当日用量强度。Token 指标包括总量、输入输出、缓存使用和推理输出等。Token 数量使用 K/M/B 缩写,缺失计数和零值均显示 `0`,缺失或为零的缓存命中率显示 `0%`。切换日期时,活动统计、Token 数字和最常用模型使用滚动切换动画。--每个线程轮次只计一次,主 Agent 和子 Agent 的用量归到根任务开始日期,跨午夜也不拆分。缓存命中率用当日缓存命中总量除以输入总量计算。启用 iCloud 同步后,各 Mac 的同一轮记录先去重再汇总。--热力图颜色、日期标题旁的 Token 数量和用量强度来自 app-server,右栏会话 Token 来自本地 rollout 及 iCloud 历史,两者的来源和统计范围不同。历史回放、续读和重建方式见 [数据、同步与隐私](sync-data-privacy.md#历史-token-回放)--## 活动卡片--活动卡片优先显示等待批准,其次是运行中任务。没有活跃任务时,显示结束时间最新的完成或终止记录;时间相同优先显示终止。--卡片会按实际可用字段展示以下内容:--- 项目名-- 模型和推理强度-- 当前工具或执行阶段-- 已运行或已等待时间-- 活跃子 Agent 数-- 其他并发任务数-- 匿名任务图标--防睡眠实际生效时,活动卡片右侧显示青绿色太阳徽标,悬停可查看防睡眠来源。开启“动画效果”时徽标持续旋转,关闭时静态显示。--无法识别会话的任务带有橙色匿名图标,悬停显示 `匿名任务不参与防睡眠`--活动卡片的 `+N` 表示其他活跃任务总数。--点击有内容的活动卡片可以打开任务中心。活动卡片和任务中心的状态文字颜色随任务状态变化。开启“动画效果”时,运行状态文字播放扫光,等待批准文字周围显示橙色粒子;关闭后保留静态彩色文字。--### 本轮 Token 用量--活动卡片取得本轮 rollout 用量后,在状态下方展示 Token 总量、输入输出、缓存使用和推理输出等指标,数量使用 K/M/B 缩写。用量区域和上方分割线一起展开或收起,动画不受 `动画效果` 开关控制。没有用量时隐藏整个区域。--运行中和等待批准时,已能确认归属的主线程与子 Agent 用量会持续更新;后续线程记录到达后继续补齐。确认完成或终止后,后台最多追查 30 秒本轮用量,取得完整汇总后显示,期限内继续接受更新。结束状态立即展示,追查期间没有倒计时或加载提示。到期仍未取得用量时,用量区域保持隐藏;已经取得的数值会保留。统计范围是当前对话轮次及其子 Agent。--总量等于输入加输出;缓存命中和缓存写入包含在输入中,推理输出包含在输出中,不能再次加到总量上。缓存命中率为缓存命中除以输入;输入为零时,卡片显示 `—`。英文标签 `Cached`、`Cache-W` 和 `Cache-H` 分别表示缓存命中、缓存写入和缓存命中率。--## 任务中心--任务中心按状态分组展示以下内容:--- 等待确认-- 运行中-- 最近完成-- 最近终止--最近完成和最近终止记录保留 10 分钟。完成表示一轮任务结束,不代表执行成功;终止记录包括中断及其他终止情况,不触发完成通知。--最近完成和最近终止条目在有用量数据时显示本轮总 Token,使用 K/M/B 缩写。运行中和等待批准条目只显示任务状态;主面板活动卡片显示当前摘要任务的用量。--## 底部状态--主面板底部包含以下信息:--- 数据更新时间-- 距离下一次自动刷新的倒计时-- iCloud 同步关闭、同步中、已同步或失败状态-- 可用更新提示--发现新版本时,双击更新提示可以开始更新。--返回 [用户指南](../README.md#用户指南)diff --git a/Docs/UserGuide/notifications.md b/Docs/UserGuide/notifications.mddeleted file mode 100644index 8399bce..0000000--- a/Docs/UserGuide/notifications.md+++ /dev/null@@ -1,86 +0,0 @@-# 通知与提醒--简体中文 | [English](../en/UserGuide/notifications.md)--## 开启通知--1. 打开 `设置 > 高级`-2. 开启 `系统通知`-3. 在 macOS 授权窗口中允许通知-4. 点击右侧滑杆按钮配置各类通知--如果系统权限被拒绝,设置页会显示 `打开系统设置` 按钮。--通知总开关默认关闭,关闭时所有 CodexBar 系统通知和任务触觉反馈都停止。--## 通知类型--| 通知 | 触发条件 | 默认子开关 | 额外依赖 |-| --- | --- | --- | --- |-| 任务完成 | 任务完成且运行时长达到所选阈值 | 开启,1 分钟 | 进阶模式 |-| 任务等待 | 任务进入等待用户批准状态 | 开启 | 进阶模式 |-| 额度预警 | 剩余额度达到预警阈值 | 开启,10% | 无 |-| 额度重置 | 已观察到消耗的额度窗口回到未消耗状态 | 开启 | 无 |-| 重置临期 | 留存重置进入过期前 7 天窗口 | 开启 | 存在可用留存重置 |-| 自动重置 | 自动重置明确返回成功或此前已成功 | 开启 | 自动重置开关、通知子开关和通知总开关 |-| 自动重置失败 | 认证失败导致暂停、协议错误导致停止,或本机明确观察到过期 | 与成功通知共用设置 | 自动重置开关、通知子开关和通知总开关 |-| 低电量保护 | 低电量保护成功恢复系统睡眠 | 开启 | 防睡眠和低电量保护 |-| 防睡眠上限 | 达到时长上限并成功恢复系统睡眠 | 开启 | 防睡眠和有限时长上限 |-| 异常会话保护 | 运行中任务持续无进展,达到保护阈值 | 固定行为 | 进阶模式和防睡眠主开关 |--异常会话保护没有独立通知开关,使用系统默认声音。--即使系统通知没有发送成功,已确认超时的异常任务仍会被隐藏并停止参与防睡眠。--匿名任务不触发任务完成通知、等待批准通知、异常会话保护通知或任务触觉反馈,但仍保留在活动卡片和任务中心中。--## 可选阈值--| 设置 | 可选值 |-| --- | --- |-| 任务完成最短时长 | 30 秒, 1 分钟, 2 分钟, 5 分钟 |-| 低额度阈值 | 5%, 10%, 25% |--剩余额度降到阈值或以下时触发预警,启动后首次读到低额度也会提醒。额度需要有明确的重置时间,同一重置周期只提醒一次。--留存重置会在过期前 7, 6, 5, 4, 3, 2 和 1 天分别判断是否需要提醒。--## 自动重置通知--自动重置成功或因登录、设置错误、过期而停止时,会按通知设置提醒。暂时的网络失败只在后台重试。--一次自动重置可能同时产生“自动重置”和“额度已重置”两条通知:前者是操作结果,后者是额度变化。成功和失败共用“自动重置通知”开关及音效。--多台 Mac 同时尝试时,收到成功确认的设备会分别提醒;仅发现留存重置已消失的设备不提醒。同一留存重置的同一失败原因最多通知一次。--## 通知音效--每类可配置通知都可以选择以下声音:--- 默认通知音-- 静音-- 当前 Mac 可用的系统提示音-- CodexBar 内置的 Modern 和 Material 提示音--非默认且非静音的声音可以在设置面板中试听。--如果已经保存的声音在当前 Mac 上不存在,CodexBar 会回退到默认通知音。--## 触觉反馈--`任务触觉反馈` 默认关闭。开启后,任务完成或进入等待批准时会触发触摸板震动。--触觉反馈不依赖 macOS 通知授权,但仍然服从 CodexBar 的系统通知总开关和进阶模式状态。--## Codex TUI 通知--此选项控制 Codex 自身的通知,与 CodexBar 通知相互独立。--## 通知交互--- CodexBar 位于前台时仍会显示通知横幅、通知列表项和声音-- 点击任意 CodexBar 通知会打开主面板-- 任务不再等待批准时,对应等待通知会从通知中心撤回-- 任务恢复进展或不再符合异常会话保护条件时,对应通知会从通知中心撤回--返回 [用户指南](../README.md#用户指南)diff --git a/Docs/UserGuide/settings.md b/Docs/UserGuide/settings.mddeleted file mode 100644index 5403479..0000000--- a/Docs/UserGuide/settings.md+++ /dev/null@@ -1,127 +0,0 @@-# 设置参考--简体中文 | [English](../en/UserGuide/settings.md)--右键或 Control 点击菜单栏图标并选择 `设置`,或按 `⌘,` 打开设置窗口。--## 通用设置--| 设置 | 作用 | 默认或初始状态 |-| --- | --- | --- |-| 主面板布局 | 调整账户、任务、额度、用量和状态的顺序与显隐 | 全部显示;进阶模式关闭时任务区域关闭 |-| 动画效果 | 控制额度条和热力图入场动画、太阳徽标旋转,以及活动卡片和任务中心的状态文字动画 | 开启 |-| 流光效果 | 在各显示器顶部用颜色显示任务状态 | 关闭 |-| 开机自动启动 | 登录 Mac 后启动 CodexBar | 跟随系统登录项状态 |-| 自动检查更新 | 定期检查 CodexBar 更新 | 跟随当前更新设置 |-| 菜单栏额度指示 | 显示所选额度窗口的剩余比例 | 主额度 |-| 全局快捷键 | 在任意 App 中开关主面板 | `⌘⇧E` |--### 主面板布局--点击右侧选项按钮后,可拖动排序或切换区域开关,至少保留一个区域。使用 `⌘Z` 撤销、`⌘⇧Z` 重做。隐藏区域不会停止相关功能。--进阶模式关闭时任务区域自动关闭,从关闭切换到开启时自动显示。开启后仍可手动隐藏任务区域,重启 App 会保留这一选择。如果任务是唯一可见区域,关闭进阶模式时账户区域会自动开启。--### 流光效果--在各显示器顶部显示任务状态,需要进阶模式开启且校验通过。此开关默认关闭,与主面板的“动画效果”独立。开启后,点击右侧选项按钮可调整各状态颜色、动画速度、亮度和结束时长。--开启时按当前运行颜色、速度和亮度播放一次往返预览,随后显示实际任务状态。关闭时光带快速收回到屏幕中心并淡出,收尾完成前再次开启不会重播开启预览。--双击选项面板中的颜色块可预览对应状态:运行展示往返流光,等待批准展示呼吸效果,完成和终止短暂显示后淡出。再次双击会替换当前预览,收起选项面板会结束颜色预览并恢复实际任务状态。--| 默认颜色 | 含义 |-| --- | --- |-| 青色往返流光 | 任务运行中 |-| 橙色呼吸光带 | 等待批准,优先于运行状态 |-| 绿色 | 任务完成 |-| 红色 | 任务终止,包括中断 |--颜色使用 Display P3 六位十六进制值,字母自动转为大写,空输入框显示默认颜色值。无效颜色以红框提示,按回车、移开焦点或收起面板时恢复默认颜色。动画速度可选较慢、标准和较快,默认标准;亮度可调范围为 20%–100%,默认 100%。--并发任务中有任务结束时,短暂显示完成或终止提示,再恢复当前任务状态。全部任务结束后,从最新记录的结束时间起,按所选“结束时长”显示提示;可选 3、5、10、15、30 或 60 秒,默认 10 秒。预览期间继续接收任务更新,结束提示暂停计时。恢复时按最新任务状态展示,已有结束提示继续剩余时长,预览期间产生的结束提示按完整时长显示。--进阶模式不可用时隐藏光带并保留开关选择。系统睡眠、屏幕休眠或用户会话不活跃时也会隐藏;恢复后显示当前状态,已过期的结束提示不会重播。--### 菜单栏额度指示--选择要显示的额度窗口。关闭后再开启,会恢复上次选择;数据变淡表示显示的是缓存额度。--### 全局快捷键--快捷键至少需要两个修饰键,不能使用 `Command-Space` 或 `Command-Tab`。组合已被占用时会提示冲突。可以清除快捷键或恢复默认值。--## 高级设置--| 设置 | 作用 | 默认状态 |-| --- | --- | --- |-| [进阶模式](advanced-mode.md) | 启用实时任务和每日活动统计 | 未安装时关闭 |-| [系统通知](notifications.md) | 配置通知类型、阈值、音效和触觉反馈 | 总开关关闭 |-| 自动重置 | 提前使用即将过期的留存重置 | 关闭,提前 30 分钟 |-| [防止系统睡眠](sleep-prevention.md) | 在符合条件的任务运行时保持 Mac 唤醒 | 关闭 |-| [跨设备同步](sync-data-privacy.md) | 通过 iCloud 合并每日活动统计和会话 Token 用量 | 关闭 |-| 网络代理 | 配置 CodexBar 的 Codex 服务连接代理 | 关闭 |-| 数据更新间隔 | 设置账户、额度及其附带历史维护和同步的自动更新间隔 | 1 分钟 |-| [重建数据](sync-data-privacy.md#重建数据) | 在后台重新计算所选日期的活动统计和会话 Token 用量 | 手动操作 |--### 数据更新间隔--可选 1、2、3、5 或 10 分钟,默认 1 分钟,保存在本机。间隔从上一轮刷新结果提交时开始计算;修改后立即重新计算剩余等待时间,已经到期时尽快刷新。手动刷新会重置倒计时,实时任务监控不受此设置影响。--### 网络代理--点击设置行打开配置,填写服务器地址和端口。支持 HTTP、HTTPS、域名、IPv4 和 IPv6;端口范围为 `1~65535`。开启身份验证后用户名必填,密码可留空。--HTTP 代理也能转发 HTTPS 请求。只有代理端口本身支持 TLS 时才选择 HTTPS,证书需有效。--- `测试连接` 检查尚未保存的配置,可取消,不会保存或启用代理-- `保存` 应用配置;首次保存后仍需打开设置行右侧开关-- `取消` 丢弃本次编辑-- `⋯ > 删除配置` 删除配置和密码并关闭代理,配置损坏时也可使用-- 关闭右侧开关会保留配置,便于下次启用--密码默认隐藏,鼠标移入密码框时显示。代理只影响 CodexBar 的 Codex 服务连接,密码以明文保存在本机。详情见 [数据、同步与隐私](sync-data-privacy.md)--### 自动重置--自动重置会在留存重置即将过期时自动使用它。每次开启均需确认;如提示后台服务需要授权,点击设置行下方的 `打开系统设置` 并允许 CodexBar 后台运行。--开启且 CodexBarHelper 获得批准后,点击右侧选项按钮设置临期时间:`15 分钟`、`30 分钟`、`1 小时`、`2 小时`、`4 小时` 或 `6 小时`,默认提前 `30 分钟`。--- 优先处理最早到期的可用留存重置,使用前重新检查登录和可用状态-- 可能短暂唤醒 Mac,但不点亮屏幕,也不会打开防睡眠开关-- 暂时失败时自动重试,每轮最多持续 5 分钟;后续刷新仍可再次尝试-- Mac 唤醒或 App 重新启动后,会补查尚未过期的留存重置-- 关闭功能或退出 App 会取消已安排的唤醒-- 多台 Mac 同时开启时,同一留存重置不会因重复尝试而多次消费--自动重置不依赖通知开关。结果提醒可在 [通知选项](notifications.md#自动重置通知) 中配置。该功能的设置只保存在当前 Mac。--## 关于页面--| 项目 | 操作或含义 |-| --- | --- |-| 来源 | 自动优先选择 Codex CLI,找不到时使用 ChatGPT App 或 Codex App 内置的 Codex,也可手动选择 |-| 重新建立连接 | 使用所选 Codex 来源重新连接,更新 Codex 后可用它立即切换到新版本 |-| Codex CLI / Codex App | 查看检测到的版本,点击路径可复制 |-| 当前使用 | 当前连接所用的来源和版本 |-| 不可用(Codex 来源) | 之前使用或选择的来源已无法找到 |-| CodexBar Helper | 查看后台组件的安装与授权状态 |-| CodexBar 版本 / 检查更新 | 查看版本并检查可用更新 |-| GitHub 项目 | 打开项目页面 |-| 退出 CodexBar | 退出 App |--连接期间暂时不能切换来源。连接失败原因显示在版本区域底部,可据此排查或重新选择来源。--CodexBar Helper 状态始终显示在关于页面,不受自动重置和防睡眠开关影响:--| 状态 | 含义 |-| --- | --- |-| 未安装 | 尚未注册,且未发现组件或安装异常;首次使用时属于正常状态 |-| 未授权 | 已注册,仍需允许后台运行 |-| 已授权 | 系统已允许后台运行,当前未发现组件异常 |-| 不可用 | 组件缺失、配置或签名异常,或未注册且安装失败 |--发现组件异常时,即使之前已授权,也会显示“不可用”。处理方式见 [CodexBarHelper 无法注册](troubleshooting.md#codexbarhelper-无法注册)--返回 [用户指南](../README.md#用户指南)diff --git a/Docs/UserGuide/sleep-prevention.md b/Docs/UserGuide/sleep-prevention.mddeleted file mode 100644index 903a43d..0000000--- a/Docs/UserGuide/sleep-prevention.md+++ /dev/null@@ -1,63 +0,0 @@-# 防止系统睡眠--简体中文 | [English](../en/UserGuide/sleep-prevention.md)--CodexBar 可以在任务运行时保持 Mac 唤醒,任务结束或保护条件触发后恢复睡眠。--## 开启与生效条件--1. 在 `设置 > 高级` 开启进阶模式-2. 开启 `防止系统睡眠` 并确认-3. 如需后台授权,点击 `打开系统设置` 并允许 CodexBar 后台运行--防睡眠需要 CodexBar 正在运行、Hook 和后台服务可用,并有符合条件的任务。低电量或时长上限触发时会停止,条件恢复后按任务状态重新生效。活动卡片上的太阳徽标表示防睡眠已生效。--匿名任务和被异常会话保护隐藏的任务不参与防睡眠。--## 设置选项--点击防睡眠行右侧的选项按钮调整:--| 选项 | 作用 | 默认值 | 可选值 |-| --- | --- | --- | --- |-| 等待批准时保持防睡眠 | 等待你批准时继续保持唤醒 | 关闭 | 开启或关闭 |-| 保持屏幕常亮 | 阻止显示器睡眠、屏保和闲置锁屏 | 关闭 | 开启或关闭 |-| 最长防睡眠时间 | 限制一轮累计防睡眠时长 | 12 小时 | 1, 2, 4, 8, 12, 24 小时或无限制 |-| 异常会话保护 | 隐藏长时间没有进展的运行任务 | 1 小时 | 30 分钟, 1, 2, 4 小时 |-| 低电量保护 | 电池供电且电量过低时恢复睡眠 | 关闭 | 关闭或 5%, 10%, 15%, 20%, 25% |--没有内置电池的 Mac 不显示低电量保护。--## 等待批准与屏幕常亮--默认只在任务运行期间防睡眠。开启等待批准选项后,无人处理批准请求时也会保持唤醒,直到达到时长上限或任务状态变化。--保持屏幕常亮只在防睡眠生效时工作,可能让离开电脑后的界面仍保持解锁状态。--## 最长防睡眠时间--只累计实际防睡眠时间,暂停和系统睡眠期间不计时。新运行任务出现或等待任务恢复运行时会开始新一轮计时;没有活跃任务时重置。达到上限后恢复睡眠,等待下一轮任务。--## 异常会话保护--运行任务超过所选时间没有进展时,会从活动卡片和任务中心隐藏,并停止支持防睡眠。恢复进展后自动重新显示;调长阈值时,未超过新阈值的任务也会恢复。--保护跟随防睡眠主开关,仅判断非匿名运行任务,不判断等待批准任务。启动恢复、系统睡眠和任务数据暂时不可用期间暂停判断。--系统通知开启且获得授权时会尝试提醒,通知失败不影响保护生效。--## 低电量保护--使用电池时,电量降到阈值或以下即停止防睡眠。回升到阈值加 5 个百分点,或接通电源后解除;仍有任务时自动恢复防睡眠。--例如阈值为 10% 时,电量降到 10% 会停止,回升到 15% 才恢复。--## 后台服务与其他 App--CodexBarHelper 是随 App 安装的后台服务,负责系统睡眠控制。未获批准或服务异常时,设置页会提示处理方式,参见 [常见问题与排查](troubleshooting.md#codexbarhelper-无法注册)--如果其他 App 已经关闭系统睡眠,设置页会显示外部来源,CodexBar 结束任务时会保留该设置。外部来源停止后,仍有任务时 CodexBar 会按需接管。--正常退出前,CodexBar 会恢复自己管理的睡眠状态并取消自动重置唤醒计划。退出未完成时,请查看设置页的后台服务错误。--返回 [用户指南](../README.md#用户指南)diff --git a/Docs/UserGuide/sync-data-privacy.md b/Docs/UserGuide/sync-data-privacy.mddeleted file mode 100644index 273dca2..0000000--- a/Docs/UserGuide/sync-data-privacy.md+++ /dev/null@@ -1,79 +0,0 @@-# 数据、同步与隐私--简体中文 | [English](../en/UserGuide/sync-data-privacy.md)--## 跨设备同步--在 `设置 > 高级` 开启 `跨设备同步`,可以合并同一 iCloud 账户下多台 Mac 的每日 Hook 统计和 rollout Token 用量。需要先开启进阶模式,并登录可用的 iCloud 账户。--首次开启会上传本机保留期内的统计,之后自动同步变化。关闭同步会保留本机数据。--| 状态 | 含义 |-| --- | --- |-| 同步未开启 | 同步开关或进阶模式已关闭 |-| 正在同步 | 正在传输数据 |-| 已同步 | 最近一轮同步成功 |-| 同步失败 | 网络、iCloud 账户或服务暂时不可用,稍后重试 |--主面板底部和设置页显示同步状态,设置页还显示最近成功上传时间。--## 哪些数据会上传--同步数据保存在 iCloud 私有数据库中,包括日期、每日事件和会话统计、项目显示名、模型名,以及用于区分设备和避免重复计数的标识。Token 历史另行同步由 thread ID 和 turn ID 生成的哈希标识、必要时间和 Token 累计计数,用于跨设备去重后计算日汇总。--以下内容不参与同步:--- 原始 Hook 事件、会话和任务标识、完整工作目录-- 提问、Codex 回复、工具参数和输出-- Codex 账户、额度、app-server 账户用量和留存重置-- App 设置、代理配置和密码-- 日志、实时任务状态和异常会话保护记录--项目显示名会上传。若不希望将项目名存入 iCloud,请关闭跨设备同步。--## 本机数据--| 数据 | 内容与保留方式 |-| --- | --- |-| Hook 记录与每日统计 | 时间、事件、模型、工具、项目和任务标识等,保留 210 天;每日统计中的会话和轮次明细仅保留最近 3 天 |-| rollout Token 历史 | 哈希轮次标识、开始时间、累计计数和读取游标,保留 210 天;仍被子轮次引用的根时间一同保留 |-| 异常会话保护 | 无法直接还原的任务标识和时间,最长保留到最后进展后的 24 小时 |-| App 设置 | 保存在当前 Mac,包括代理配置;代理密码以明文保存 |-| 交互日志 | 最近 500 条 Codex 请求和响应,只在本次运行期间保留 |-| 后台服务状态 | 用于恢复睡眠设置和清理自动重置唤醒计划 |--CodexBar 读取本机 Codex 的任务状态和活动记录,但不保存提问、回复或工具内容,也不复制 Codex 登录凭据。--关闭代理会保留配置和密码;保存关闭身份验证的配置或选择 `删除配置` 时会删除密码。--## 历史 Token 回放--App 在历史统计刷新时自动读取本机 Codex 的 rollout,逐步补全保留期内的轮次用量,无需手动重建。每批保存用量和读取位置;退出后再次打开,会从保存的位置继续。追平历史后,后续刷新按读取位置处理追加内容。文件被替换或截断时会重新读取,同一线程轮次仍只计一次。--历史很多时可能需要多轮刷新才能补全。回放进度写入系统日志的 `workflow` 分类,读完当前检查范围内的文件后记录 `Rollout 回放完成`。这个状态表示本地回放进度,云端传输状态在同步区域查看。--日用量按根轮次开始时间和查看设备的本地时区归属。原始 rollout 已缺失或没有记录用量时,无法补出对应计数。--## 重建数据--统计异常时,可在 `设置 > 高级 > 重建数据` 选择日期范围并确认。可选范围为最近 210 天,有本机 Hook 记录或已发现 Token 轮次的日期会显示标记;未标记的日期也可以选择。--重建使用保留的本机 Hook 事件和 rollout,重新计算所选日期的活动统计与 Token 用量。Token 按根轮次开始日期归属,同一轮及其子线程不会重复累计。日期没有 Hook 事件时,也可以重建本机 rollout 中的 会话数据。--重建在后台运行,可以继续使用主面板或关闭设置窗口。Token 按批读取,扫描完整成功后一次更新;取消或读取失败不会发布部分结果。退出 App 会停止本次重建,未完成的 Token 重建需要重新发起。完成后通过弹窗显示处理天数、Hook 事件数和 Token 轮次数。--开启同步时,重建结果会替换当前设备对应日期的活动统计,以及本机重新读到的 Token 轮次记录;其他轮次保留。重建可以降低 Token 计数;重新读到轮次但没有用量记录时,会清除该轮旧计数并同步到云端。本机已经缺失 rollout 的轮次保留已有统计,不会因此删除云端记录。账户信息、额度和 app-server 的账户用量不受影响。--## 网络与日志--| 网络访问 | 用途 |-| --- | --- |-| Codex 服务 | 获取账户、额度和用量,执行自动重置 |-| 更新服务 | 检查并下载 CodexBar 更新 |-| iCloud | 开启同步后传输每日 Hook 统计和会话数据 |--代理只用于 CodexBar 的 Codex 服务连接,不影响更新、iCloud 或其他 App。--交互日志可能包含账户和请求响应内容,退出 App 后清除。分享日志前,请检查其中是否有不希望公开的信息。--返回 [用户指南](../README.md#用户指南)diff --git a/Docs/UserGuide/troubleshooting.md b/Docs/UserGuide/troubleshooting.mddeleted file mode 100644index 5bf89cd..0000000--- a/Docs/UserGuide/troubleshooting.md+++ /dev/null@@ -1,148 +0,0 @@-# 常见问题与排查--简体中文 | [English](../en/UserGuide/troubleshooting.md)--## 菜单栏找不到 CodexBar--- CodexBar 是菜单栏 App,不显示 Dock 图标-- 在 macOS 控制中心设置中确认菜单栏项目没有被隐藏-- 从 Applications 再次启动不会创建第二个实例-- 仍然找不到时,在活动监视器中确认 CodexBar 是否正在运行--## 主面板显示未登录--1. 打开当前正在使用的 Codex CLI, ChatGPT App 或 Codex App-2. 完成 Codex 登录-3. 双击 CodexBar 主面板中的账户图标刷新-4. 仍然未登录时退出并重新打开 CodexBar--自动模式优先使用全局 Codex CLI,关于页面的 `当前使用` 标记可以确认实际来源,也可以通过“来源”选择器切换。--## 主面板显示初始化失败--到 `设置 > 关于` 查看连接错误,确认 Codex 已安装、路径可用,并检查代理配置。修正后点击 `重新建立连接`;持续失败时打开日志查看详情。--## 代理配置或连接失败--在 `设置 > 高级 > 网络代理` 中打开配置,使用 `测试连接` 检查。服务器地址和端口必填,开启身份验证后用户名必填;输入问题会标红并显示简短原因。--- 关于页面提示服务器或用户名无效时,修正后保存,或关闭代理开关-- 配置无法读取时,在配置窗口右上角 `⋯ > 删除配置` 删除损坏数据-- 地址和端口格式正确但代理不可达时,开关仍可保存为开启;使用测试连接检查网络-- 选择 HTTPS 时,代理端口本身必须支持 TLS,并提供有效证书--## 额度或 Token 显示变淡--变淡表示本轮读取失败后回退到了同一账户的缓存数据。--双击账户图标重试;持续变淡时,在关于页面查看连接错误或打开日志。--<a id="hook-无法开启或校验失败"></a>--## 进阶模式无法开启或校验失败--| 提示 | 处理方法 |-| --- | --- |-| 需要更高 Codex 版本 | 更新 Codex 后在关于页面点击 `重新建立连接` |-| 无法确认 Codex 版本 | 在关于页面确认来源可用,点击 `重新建立连接` 后重试 |-| Codex Hook 已全局关闭 | 在 Codex 配置中重新开启 `features.hooks` |-| 进阶模式的 Hook 配置不完整 | 重新打开设置等待自动修复,仍未恢复时关闭后重新开启进阶模式 |-| 进阶模式的 Hook 未被信任 | 重新开启进阶模式,并检查 Codex 的信任提示 |-| 进阶模式的 Hook 来源异常 | 确认当前 Codex 来源和 `CODEX_HOME` 指向预期位置 |-| `hooks.json` 文件格式错误 | 修复该文件的 JSON 格式后重试 |-| 无法验证 Codex Hook | 等 Codex 连接恢复后重新打开设置 |--默认配置文件位于 `~/.codex/hooks.json`;设置过 `CODEX_HOME` 时,位于该目录下的 `hooks.json`--## 实时任务没有出现--1. 确认进阶模式已开启且没有错误提示-2. 确认 `通用 > 主面板布局` 中的 `任务` 区域已开启-3. 新建一轮 Codex 任务以产生实时事件-4. 打开设置窗口触发一次 Hook 重新校验--重新启动 CodexBar 不会补发旧任务通知。--## 收不到系统通知--按以下顺序检查:--1. `系统通知` 总开关是否开启-2. macOS 是否允许 CodexBar 发送通知-3. 对应通知子开关是否开启-4. 任务类通知所需的进阶模式是否有效-5. 任务完成时长是否达到所选阈值-6. 通知音效是否选择了静音--触觉反馈不依赖 macOS 通知权限,但依赖 CodexBar 通知总开关。--## 防睡眠没有生效--按以下顺序检查:--1. 进阶模式是否有效-2. `防止系统睡眠` 是否开启-3. 当前是否存在运行中任务-4. 只有等待任务时,`等待批准时保持防睡眠` 是否开启-5. 设置页是否提示需要批准 CodexBar 后台运行-6. 是否正在触发低电量保护-7. 是否已经达到最长防睡眠时间--太阳徽标只在防睡眠实际生效且活动卡片有可用数据时显示;关闭“动画效果”后静态显示。--如果设置页显示 `系统睡眠已由其他来源关闭`,CodexBar 不会覆盖该来源。--## CodexBarHelper 无法注册--- 在关于页面查看 `CodexBar Helper` 状态;功能开关关闭时仅隐藏对应设置行的说明,关于页面仍显示状态-- 首次使用显示“未安装”属于正常状态;开启 `自动重置` 或 `防止系统睡眠` 并确认后,App 才会尝试安装和注册-- 显示“未授权”时,点击已开启功能设置行下方的 `打开系统设置` 并允许 CodexBar 后台运行-- 确认 CodexBar 位于 Applications 中且 App 包完整-- 提示 `CodexBar Helper 组件或配置丢失, 请重新安装 CodexBar` 时,包内缺少必要组件或配置;提示 `CodexBar Helper 组件或配置异常, 请重新安装 CodexBar` 时,配置或签名校验未通过;两种情况都需要重新安装完整 CodexBar App-- 修复 App 包后,重新启动或再次激活 App 会重新校验;校验成功后自动清除组件异常,无需为了清除提示而开启功能-- 更新后持续失败时退出 CodexBar,重新打开并再次检查授权--## 自动重置没有按时执行--按以下顺序检查:--1. `自动重置` 是否开启,提前量是否符合预期-2. 自动重置设置行是否提示 CodexBarHelper 待批准、未注册或唤醒计划失败;临期选项按钮只在 Helper 已获得系统批准时显示-3. 主面板是否显示可用留存重置及其过期时间-4. 计划时间到达后,网络与 Codex 登录状态是否可用-5. “自动重置通知”是否开启;通知关闭不会阻止自动重置本身执行--暂时故障每轮最多连续重试 5 分钟,后续刷新仍可再次尝试。关闭自动重置或退出 CodexBar 会取消唤醒计划。--## 跨设备同步不可用--- 确认 Mac 已登录 iCloud-- 确认 iCloud Drive 和 CloudKit 服务当前可用-- 确认进阶模式已开启-- 确认 `跨设备同步` 开关已开启-- 将鼠标悬停在主面板底部 iCloud 图标上查看具体状态--同步失败不会删除本机 Hook 数据,后续维护会再次尝试。--## 更新 Codex 后仍显示旧版本--在关于页面点击 `重新建立连接`,让 CodexBar 使用更新后的 Codex。--## 使用日志窗口--打开方式如下:--- 右键菜单栏图标并选择 `日志`-- 主面板打开时按 `⌘L`--日志窗口保留本次运行期间最近 500 条 Codex 交互记录。--每条记录包含请求时间、方法、状态和响应时间,展开后可以查看请求、响应或错误预览。--完整内容可以在独立窗口中查看或复制,清空或退出 App 后不会恢复。--## 反馈问题--提交问题时说明复现步骤、CodexBar 与 Codex 版本、可见错误。交互日志可能包含账户和请求内容,分享前请检查隐私信息。--返回 [用户指南](../README.md#用户指南)diff --git a/Docs/en/DeveloperGuide/README.md b/Docs/en/DeveloperGuide/README.mddeleted file mode 100644index 9525060..0000000--- a/Docs/en/DeveloperGuide/README.md+++ /dev/null@@ -1,50 +0,0 @@-# CodexBar Developer Guide--[简体中文](../../DeveloperGuide/README.md) | English--## Find by Responsibility--| Document | Contents |-| --- | --- |-| [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 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 |-| [Development and Validation](development.md) | Project structure, build checks, debugging, and change acceptance |--## Online Resources--- [Runtime Architecture](https://codexbar.zabrian.app/architecture)-- [Performance Report](https://codexbar.zabrian.app/performance)--## Core Terminology--| Term | Precise meaning in this project |-| --- | --- |-| snapshot | Repeatable current state; it does not imply that an event just occurred |-| transition | A one-time state change from trusted live input that may drive side effects such as notifications |-| bootstrap | Restoring an in-memory baseline from existing local data without replaying historical side effects |-| stale | An old value is available for display, but the source could not confirm it in the current cycle |-| unavailable | No trusted source is currently available; this is not equivalent to empty or `0` |-| generation | The generation of a data source or asynchronous operation, used to reject late results |-| source generation | The source identity of a day's raw Hook file; distinct from a code schema |-| owned | CodexBar has persisted responsibility for restoring system sleep |-| external | A source outside CodexBar had already set the system state |--## Main Entry Points--- App startup: [`CodexBarApp.swift`](../../../CodexBar/App/CodexBarApp.swift)-- Service assembly: [`CodexBarAppDelegate.swift`](../../../CodexBar/Controllers/CodexBarAppDelegate.swift)-- app-server service: [`CodexStatusService.swift`](../../../CodexBar/Services/CodexStatus/CodexStatusService.swift)-- Hook subprocess entry: [`WorkflowHookEventRecorder.swift`](../../../CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift)-- Live task state machine: [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift)-- Automatic Reset state machine: [`AutoResetController.swift`](../../../CodexBar/Services/CodexStatus/AutoResetController.swift)-- Automatic Reset wake synchronization: [`AutoResetWakeScheduler.swift`](../../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift)-- Sleep-prevention orchestration: [`KeepAliveController.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveController.swift)-- CodexBarHelper: [`main.swift`](../../../CodexBarHelper/main.swift)diff --git a/Docs/en/DeveloperGuide/activity-monitor.md b/Docs/en/DeveloperGuide/activity-monitor.mddeleted file mode 100644index 1a9f72c..0000000--- a/Docs/en/DeveloperGuide/activity-monitor.md+++ /dev/null@@ -1,606 +0,0 @@-# Live Task Monitoring--[简体中文](../../DeveloperGuide/activity-monitor.md) | English--## Goals--The live-task flow answers these questions:--- Is a task currently running?-- Is a task waiting for user approval?-- Did a recent task complete or terminate?-- Which running tasks have made no progress for too long?-- How many tokens have the current turn and its subagents used?--Hook events provide live progress and interruption signals, while rollout files supply lifecycle context and turn token usage. [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) merges both into the sole task snapshot:--```text-Codex Hook -> WorkflowHookEventRecorder -> Hook JSONL- |-> WorkflowService -> Daily history aggregates- |-> HookEventTailReader -----+- |-> CodexActivityMonitor-rollout JSONL -> CodexSessionLifecycleReader ----------------------------+ |- v- CodexActivitySnapshot- |-> Activity card and task center- |-> Glow and sleep prevention-```--`WorkflowHookEventRecorder` extracts minimal fields from `stdin`, performs bounded rollout metadata lookup when needed, appends under a file lock, and exits. Historical aggregation and live monitoring independently read the same Hook JSONL. App-server quota and usage use a separate pipeline. See [Hook Collection and Aggregation](hook-and-aggregation.md) for collection details.--Notifications and haptics consume live transitions from the monitor. Glow consumes snapshots and terminal presentation events, using the configured colors: by default, orange for user approval, cyan for running, green for completion, and red for termination. Waiting takes precedence among active tasks; a short terminal indication can temporarily override active state.--### Division Between Sources--| Information | Primary source | Supplemental source |-| --- | --- | --- |-| Live prompt, tool, compact, and subagent progress | Hook | Rollout progress |-| User-approval candidate | `PermissionRequest` | Rollout reviewer confirmation |-| Turn start | `UserPromptSubmit` | Rollout `startedAt` or historical lookup |-| Completion candidate | `Stop` | Rollout terminal |-| Explicit turn interruption | `Interrupt` | Rollout terminal |-| Other terminal resolution | Rollout terminal | Retain unresolved tasks until expiration |-| Effort | Hook-recorder lookup | Rollout lifecycle backfill |--Each field is resolved from the sources listed above. Hook polling waits 2 seconds after each read, and rollout polling waits 1 second after each reconciliation round.--### Snapshots and Transitions--A snapshot may be read repeatedly after view reconstruction, a new subscription, or a settings change. A transition may be emitted once from live data only.--For example, bootstrap may recover a task already waiting for approval when the app starts:--- The snapshot shows it waiting-- No waiting transition is emitted-- The notification service therefore does not replay a historical alert--Completion works the same way. Notifications consume `.completed` transitions rather than scanning `recentCompletions`, preventing reminders on app restart or UI refresh.--## HookEventTailReader--[`HookEventTailReader.swift`](../../../CodexBar/Services/Workflow/HookEventTailReader.swift) is an actor that checks Hook event files every 2 seconds by default.--### Bootstrap--Initial startup reads the latest 24 hours to establish a task baseline:--- Read chunks of at most 512 KiB-- Try at most 3 times to obtain stable file boundaries-- Use inode and size to detect replacement or append during reading-- Never trigger historical completion or waiting notifications from bootstrap results--If stable boundaries cannot be obtained, the reader clears recovered state, moves to each date file’s tail, and publishes unhealthy state.--### Bootstrap Is One Logical Transaction--The 24-hour window may span two calendar-day files, and one file may arrive in several 512 KiB batches.--At `.bootstrapStart`, the monitor clears previous recovered state and pauses side effects. It consumes every `.bootstrapEvents` batch, then waits until `.bootstrapEnd` to:--- Fill in lifecycle from rollout-- Apply persisted Activity Protection records-- Reconcile silence under the current threshold-- Look up missing prompt starts selectively-- Publish one complete snapshot--Intermediate batches update internal task state only. Rollout backfill and protection reconciliation require a healthy source and an awake system.--### Stable-Boundary Retries--At the start of an attempt, the reader fixes inode and size for all relevant date files and validates them again after reading to those bounds:--- A historical date must retain both inode and size-- The current date may append only beyond the fixed upper bound-- The calendar day must not cross midnight during the read--If any condition fails, the reader retries from a new baseline. After three consecutive failures, it moves to the current tail and publishes degraded health, pausing Activity Protection checks.--A bootstrap that fails because a directory is unavailable or its boundaries are unstable is retried at most every 10 seconds. Existing events are replayed silently before normal incremental reading resumes. Complete malformed lines retain their coverage gaps without triggering repeated history scans.--### Complete-Line Cursor--The Hook recorder may be writing the final line. The reader includes only bytes before the last newline in `completeOffset`.--A partial line is neither discarded nor classified as corrupt. The next cycle rereads from the old offset and commits after the line is complete. Until the fixed boundary is fully consumed, the barrier returns `sourceUnavailable`. A malformed complete line degrades its date cursor until that date leaves the reading window or a replacement file is replayed.--While the Hook source is degraded, rollout reads continue for known tasks, accepting only explicit completion or interruption records after a successful current read with matching thread and turn identity. These tasks end silently. This path does not apply ordinary progress, backfill approval state, restore suppressed tasks, or resume Activity Protection. It pauses during system sleep and bootstrap, and discards results after cancellation or a reader generation change. Full lifecycle recovery still requires a successful Hook read barrier.--### Date Rollover and File Replacement--The reader keeps an independent cursor for each calendar date in the rolling 24-hour window. Every cycle covers all these dates, including intermediate dates after a long pause and late appends to the previous date. An inode change or file shrink restarts bootstrap.--When `UserPromptSubmit` predates the current incremental window, the reader can look backward up to 8 MiB to recover the prompt start of an existing task.--### `drainNow()` Read Barrier--Every caller of `drainNow()` must wait for a read that begins after its request:--```text-Call drainNow- -> Record request generation- -> Wait for the next new read to begin- -> Wait for that read to finish- -> Return that read's result-```--A read already in progress before the call cannot satisfy the barrier. If the reader is replaced, the data source is unavailable, or the task is canceled, the caller must not continue evaluating from an old snapshot.--### Exact Generational Semantics of the Barrier--Each `drainNow()` increments `requestedDrainGeneration` and registers its own waiter.--If a read is in flight, the request sets only `hasPendingDrain`. After the current cycle completes, the reader must begin another cycle that captures this request generation.--One read can satisfy several waiters queued before it begins, but not a waiter added afterward. This is the happens-after guarantee required for wake recovery.--Actors can reenter during `await`; `isProcessingReads` and `hasPendingDrain` converge all external requests into one serial drain loop so two reads never advance offset concurrently.--## Rollout Lifecycle Reading--[`CodexSessionLifecycleReader.swift`](../../../CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift) reads `$CODEX_HOME/sessions` and `$CODEX_HOME/archived_sessions`.--Rules are:--- Poll every 1 second by default-- Begin with a 512 KiB tail window-- Backfill missing lifecycle or turn context over multiple cycles, sharing an 8 MiB body-read budget per cycle-- Parse thread relationships, lifecycle, turn progress, `effort`, `reviewer`, and turn token usage-- Keep conversation content out of the activity model and product presentation--Hook `Stop` marks the task as “Finishing up” and keeps it active; approval waiting takes priority while another agent is still waiting. Tools, approvals, and other progress continue updating the same task. Rollout completion records confirm the end of the turn; transition freshness and recovery conditions determine whether a completion transition is emitted.--If rollout is temporarily unreadable or the session or turn cannot be matched, the task continues waiting for reconciliation. `Stop` does not start a terminal timeout. A new turn or `SessionEnd` removes the old task from the active list and starts five seconds of fast terminal polling, followed by polling every 30 seconds. A late `Stop` updates only the pending task's metadata and progress, without restoring its presentation or resetting the deadline.--### Explicit Interruptions--`Interrupt` ends the matching top-level turn, clears protection state and notifications, and stores a termination record. It can match running, approval-waiting, suppressed, and pending-terminal tasks; a newer turn in the same session stays active. Ambiguous matches are ignored.--Hook and rollout terminal signals share deduplication records, retaining the first confirmed completion or termination. Terminations are displayed without triggering completion notifications or haptics.--### Locating Session Files--The reader checks a few likely directories first:--1. `sessions/YYYY/MM/DD` for the task start date-2. The current date directory-3. `archived_sessions`--A resume can continue a session created long ago. If the fast path misses, the fast path can retry every 10 seconds and the recursive fallback every 60 seconds. This discovers delayed or moved files without traversing the tree every second.--If a file moves to the archive, a missing cached URL clears its cursor and allows full discovery again.--Filenames match the thread ID exactly, optionally followed by an underscore and UUID suffix. A candidate must be unique, and its initial `session_meta.id` must match the requested thread. Metadata uses the same [bounded first-line parser](hook-and-aggregation.md#origin-normalization) as the Hook recorder.--### Rollout Read Budget--For files larger than 512 KiB, the initial cursor starts at the last 512 KiB and discards the first potentially partial line. Smaller files are read from the beginning.--The forward cursor consumes appended content while a reverse cursor restores history over multiple cycles. For an active turn without a confirmed terminal, backfill continues while its start, context, effort, reviewer, or initial progress ownership is missing, until the required information is available, a terminal is confirmed, or the file head is reached. A line straddling the bootstrap boundary that finishes later is located and read again.--After a successful read with matching thread and turn identity, the reader returns a confirmed terminal without waiting for usage. Applying a child terminal to its parent task also requires confirmed ownership. Supplemental backfill seeks missing ownership and usage, not missing `effort` or `reviewer` fields. An invalid latest usage record cannot be replaced with an older valid snapshot. Each turn's supplemental query may read at most 32 MiB of historical body data, including usage-only queries after a Hook-confirmed end. Active lifecycle searches are not subject to this cumulative cap.--Queries for the same file share a reverse cursor, decoded facts, and cumulative bytes actually read. Each supplemental query records the cumulative count at registration and uses the difference to calculate its consumed budget, including reads driven by other queries. Registrations and associated terminal facts are retained for 24 hours after the latest query; repeated queries refresh only that time. Finding the required information, reaching the file head, or exhausting the budget stops that query from driving backfill. The file head means history is exhausted; a spent budget may leave history unchecked. Appended records or reads required by other queries can still supply missing facts. Bytes read during short reads, failed post-read checks, and retries all count toward the budget. Cursors and budgets are in-memory and reset on file replacement, detectable truncation, or reader recreation.--Incremental scanning and historical backfill share an 8 MiB body-read budget per cycle across sessions in rotating order. At most 16 pending tasks are queried per cycle. An unread tail, a partial line, or a coverage gap for a nonterminal turn returns `incomplete`; read failures return `unavailable`, and unresolved files return `notFound`. A confirmed matching terminal returns `complete` after a successful current read even when another trailing record is unfinished; token usage still requires a complete tail. A turn with `complete` status and turn context sets `lifecycleCoverageCheckedAt` to the check time; an incomplete or failed read, a missing file, or missing context clears it. Normal inactivity protection requires this timestamp to be present and less than five seconds old.--The incremental scan advances its offset by bytes read and carries an unfinished line across cycles. A single line may buffer up to 16 MiB. Larger lines mark a read gap and are skipped in chunks through their newline so later records remain consumable. An explicit rollout terminal remains authoritative despite an earlier read gap.--When the file is readable and scanning reaches its actual end with only a bounded partial line remaining, the reader records the first observation or latest append time. A task with turn context, no other coverage gap or known terminal, and an observation less than five seconds old may use a partial-tail fallback: both its last progress and the tail's last growth must be at least the configured inactivity threshold ago before suppression. Further growth restarts the timer. Read failures, file replacement or truncation, and app restarts require a new observation period. Unread backlog, missing context, and oversized lines being discarded do not qualify.--A partial tail always returns `incomplete`. Its observation affects protection timing, scheduling, and revalidation before hiding; it does not establish a terminal or progress, or directly restore a task. Once the line is completed, normal complete-read progress and terminal handling apply.--A malformed rollout line marks unfinished turns as having a coverage gap. Repeated context for the same turn does not clear the gap. New turns establish independent coverage, and explicit terminal records can end a task with incomplete history. Later malformed lines do not revoke known terminal facts. Failed or incomplete reads cannot use cached progress to advance task progress, restore suppressed tasks, or remove protection records.--Older turns not yet identified when corruption occurs inherit the gap by file position during backfill. Later progress with an explicit turn ID or repeated context cannot clear that gap. Turns beginning after the malformed line establish independent coverage. Historical terminals update task records and deduplication state without publishing notifications or terminal presentation events.--### Associating Rollout Progress with a Turn--Each session file cursor stores its own `currentTurnID`, updated in JSONL file order:--- Outer `type = "turn_context"`, or `type = "event_msg"` with `payload.type` equal to `task_started` or `turn_started`, establishes context from `payload.turn_id`-- `response_item` prefers `payload.internal_chat_message_metadata_passthrough.turn_id`; other progress records use `payload.turn_id`, falling back to cursor context when absent-- `task_complete`, `turn_complete`, or `turn_aborted` for the current turn clears context; a late terminal for another turn does not-- A changed file identifier or file size below the forward read position rebuilds the cursor and clears context, cached lifecycle, and supplemental budgets--Progress includes records whose outer `type` is `response_item` or `token_usage_record`, and `event_msg` records whose `payload.type` is `token_count`, `item_completed`, `agent_message`, `agent_reasoning`, `task_started`, `turn_started`, `task_complete`, `turn_complete`, or `turn_aborted`. Time comes from outer `timestamp`, then `payload.completed_at`, then `payload.started_at`.--A record needs a usable timestamp and turn identity. It advances task progress only after a complete current read and when newer than `lastProgressAt`. A `token_usage_record` is treated as activity without comparing token totals. Initial records without an explicit turn or context retain only their progress times until backfill establishes reliable ownership; unresolved progress does not update a task. Both forward buffering and reverse backfill match terminals by turn: another turn's late terminal cannot cut off current progress, and unassigned progress after a turn's own terminal cannot be attributed back to it.--Execution progress eligible to infer approval recovery is recorded separately as `lastExecutionProgressAt`: `response_item` records with `role = "assistant"` or a type of `function_call_output`, `custom_tool_call_output`, or `tool_search_output`, and `agent_message` or `agent_reasoning` events. Only execution progress from the same agent and turn, later than the approval request, clears that wait. Ordinary activity such as usage records updates only task progress time.--### Rollout Fields--The shared `CodexRolloutLineEnvelope` extracts only fields needed for turn context, lifecycle, and progress. Prompt, response, and tool content never enters the activity model.--Terminal resolution requires a nonempty `payload.turn_id` and a `complete` current read. With outer `type = "event_msg"`, `payload.type` equal to `task_complete` or `turn_complete` confirms completion. Completion time prefers a valid `payload.completed_at` in Unix seconds, falling back to outer `timestamp` when absent or invalid; neither being usable leaves completion unconfirmed. `payload.type = "turn_aborted"` confirms interruption. A finite, nonnegative `payload.duration_ms` is converted to seconds for duration display. A missing interruption timestamp uses reconciliation time for an active task or removal time for a pending task, never earlier than its last activity.--## Token Usage for the Current Turn--`CodexSessionLifecycleReader` reads `payload.turn_token_usage` from records whose outer `type` is `token_usage_record`. These are cumulative thread-turn snapshots, so successive snapshots are not added together. `event_msg/token_count` supplies progress signals, not turn usage.--| Display metric | `turn_token_usage` field or calculation |-| --- | --- |-| Total | `total_tokens`, equal to input plus output |-| Input | `input_tokens`, including cache hits and writes |-| Output | `output_tokens`, including reasoning |-| Cached | `cached_input_tokens` |-| Cache write | `cache_write_input_tokens` |-| Cache hit rate | `cached_input_tokens / input_tokens`; undefined when input is zero |-| Reasoning | `reasoning_output_tokens` |--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.--Completed and terminated records start without usage and receive it through terminal rereads. Rereading lasts up to 30 seconds from query registration, scheduled every 2 seconds for at most 16 pending tasks per batch. Final aggregation requires all expected child identities and thread usage, with child threads ended. After usage is obtained, further updates are accepted until the deadline; incomplete reads preserve the existing value. Expiry removes the query, leaving records without usage empty. Late child associations join only their root turn, without affecting subsequent turns. Terminal state, notifications, and sleep-prevention release do not wait for token rereads.--Historical replay uses its own ledger and read cursors. See [Rollout Token History](sync.md#rollout-token-history).--## Task Identity--The task key chooses the most precise available identity:--1. `session ID + turn ID`-2. `session ID`-3. Anonymous project key--A new prompt replaces the old turn in the same session. The old turn waits for an explicit terminal result in the background: fast polling for five seconds, then every 30 seconds, retained for at most 24 hours after removal from the active list.--Subagent events update activity under their parent task and do not create separate top-level cards.--### Identity Precision and Fallback--`session ID + turn ID` precisely distinguishes sequential turns in one session and is preferred.--Some events contain only session ID. A later top-level Hook that matches the task and supplies a turn ID fills the in-memory `associatedTurnId` and terminal alias for rollout lookup and deduplication, retaining the original key and protection hash.--Terminal matching checks exact keys and aliases first, then pending tasks in the session. One pending candidate is selected; several return `ambiguous`. Active tasks are checked only when no pending candidate matches. Candidates must satisfy Hook timestamp ordering and turn identity conditions.--Without a session ID, only a project key remains. It may merge concurrent anonymous tasks in one project, so anonymous tasks provide reversible UI visibility but cannot drive notifications, sleep prevention, or persisted protection.--### Live Task Origin Filtering--`CodexActivityMonitor.apply` resolves the effective live origin before task-state transitions. When using a cached origin, an event copy carries that origin through filtering and execution identity checks; raw JSONL remains unchanged. See [Origin Normalization](hook-and-aggregation.md#origin-normalization) for input classification.--The monitor remembers origins in memory for 24 hours by exact `session ID + turn ID`. Codex subagent Hooks reuse the parent session ID, so origin decisions do not apply to an entire session.--| Event origin | Live processing |-| --- | --- |-| `main`, `auxiliary` | Remember the explicit origin and apply normal state-machine rules |-| `autoReview` | Ignore the event and remove the same key's activity, pending terminals, display records, and stalled-task protection; retain origin memory |-| `unknown` with a valid remembered `main` or `auxiliary` origin for the same key | Continue processing with the confirmed origin |-| `unknown` without valid normal-origin memory | Ignore the event |--Events missing a session ID or turn ID do not create origin memory; `unknown` and `autoReview` events are ignored. A task with a confirmed origin survives a temporary rollout read failure. Late events still pass the state machine's timestamp and terminal-deduplication checks.--These rules apply to bootstrap and live reads. Other subagents, including Memories, are classified as `auxiliary` and follow auxiliary-task association rules. Historical aggregation still consumes all raw events. Origin memory is neither persisted nor uploaded.--### New Prompts and Terminal Confirmation--A new prompt moves the previous turn in the same session to `pendingTerminalTasks` while rollout confirms its result:--- Remove it from the active snapshot immediately-- Retain task metadata and start time-- Poll quickly for five seconds, then every 30 seconds for rollout terminal-- Classify accurately as completed or aborted when terminal arrives-- Remove unresolved tasks after 24 hours without inventing completion, termination, notification, or glow events--`SessionEnd` uses the same confirmation window but moves all tasks in the session no later than that event.--### Rejecting Late Events--Hook ordering is isolated by agent and turn, while overall task progress is aggregated separately:--| Field | Source and purpose |-| --- | --- |-| Execution `lastHookEventAt` | Latest accepted Hook timestamp for an agent and turn, used to reject that execution's stale state changes |-| `lastMainHookEventAt` | Latest main-agent Hook timestamp, used for top-level prompt, interruption, and session-end decisions |-| Execution `lastExecutionProgressAt` | Hook recovery signals and rollout execution progress for the same execution, used for approval recovery and rejecting stale requests |-| `lastProgressAt` | Latest progress from Hook and rollout, used by inactivity protection |-| `lastActivityAt` | Computed from `lastProgressAt`, used for ordering, retention, and terminal timestamp adjustment |--Rollout progress never advances Hook clocks, and a later event from another agent does not block this agent's valid events. An approval request must also be no earlier than known execution progress for the same owner and later than its previous approval request. Task `lastProgressAt` and `lastActivityAt` remain monotonic.--Completion and termination share the in-memory `recentlyEndedTaskAt` map of end times. Their display records remain separate and expire after 10 minutes; deduplication memory lasts 24 hours independently. Removing a record through origin filtering recomputes its session alias from the remaining terminal timestamps.--Late events follow these rules:--- Tool, compaction, subagent, and approval Hooks check time within their execution scope; an execution with a confirmed terminal rejects further state changes-- An exact turn cannot be recreated while terminal memory is retained; session and anonymous keys can be reused only by a newer prompt-- A `Stop` matching several candidates is not guessed-- A key already in terminal deduplication memory clears recovery tasks left by abnormal ordering--These comparisons use event time rather than batch-arrival order because cross-process file writes and rollout polling can deliver old events late.--### Anonymous Tasks--When `WorkflowHookEvent.sessionId` is missing, the key is an anonymous project key. `isAnonymous` propagates through `CodexActivityTaskSnapshot`, `CodexActivityCompletion`, and `CodexActivityTermination`.--Anonymous tasks remain in activity snapshots and recent terminal records. The activity card and Task Center use the orange `person.crop.circle.dashed` icon with help text `Anonymous tasks do not prevent sleep`. The card's `+N` counts all other active tasks only.--Anonymous running tasks do not show precise elapsed time, and anonymous completion and termination records omit precise duration.--They publish no waiting or completion transitions to notification consumers, trigger no task haptics, enter neither the running nor waiting sets for KeepAlive, and do not participate in Stalled Task Protection. `activityProtectionIdentifier` returns `nil` for an anonymous key, so protection state never persists an anonymous task.--## State Machine--Active tasks mainly use these internal states:--| State | Meaning |-| --- | --- |-| `running` | Codex is processing the current turn |-| `waitingApproval` | At least one main-agent or subagent execution in the task is waiting for user approval |-| `suppressed` | Stalled Task Protection hid the task pending new progress |--`PermissionRequest` enters `waitingApproval` only when the reviewer is the user. Automatic or policy approval does not count as user waiting.--Task endings are handled by signal:--- `Stop` marks the task as finishing while retaining it in the active list-- `Interrupt` records the matching turn as terminated-- Rollout terminal confirms completion or termination-- A new turn or `SessionEnd` removes the old task from the active list and starts background reconciliation; missing terminal evidence stays unresolved until cleanup--### Main Event-to-State Transitions--| Current state | Input | New state | Additional action |-| --- | --- | --- | --- |-| Absent | `UserPromptSubmit` | running | Save trusted `startedAt` |-| Absent | Top-level tool or compact | running | Recover task with unknown `startedAt` |-| running | Tool, compact, or subagent progress | running | Update last progress and generation |-| running | `PermissionRequest` + reviewer user | waitingApproval | Publish live waiting transition |-| waitingApproval | Valid Hook or rollout execution progress from the agent and turn owning the approval | waitingApproval or running | Clear that execution's approval; retain waiting while other waits remain |-| waitingApproval | Progress from another agent | waitingApproval | Update progress while preserving the wait and its tool presentation |-| running or waiting | Top-level `Stop` | running or waitingApproval | Clear the main execution's wait; show waiting while a subagent still waits, otherwise Finishing up |-| active | New prompt or `SessionEnd` | pending terminal | Remove from snapshot and begin background terminal polling |-| active, suppressed, or pending terminal | `Interrupt` | terminated | Remove the matching task, record termination, and clear protection state and notifications |-| running | Protection conditions hold and silence reaches threshold | suppressed | Hide and remove sleep-prevention contribution |-| suppressed | Valid tool, compaction, subagent, or `Stop` Hook, or new progress from healthy reconciliation | running | Clear persisted protection and old notification |-| active, suppressed, or pending terminal | Matching rollout terminal from a complete read | completed or terminated | Record the terminal and remove the task; process silently while degraded |--### Two-Stage Approval Confirmation--Tasks keep execution records by agent and turn. The main agent uses an explicit main origin without `agentId`; subagents use their own thread IDs. Each execution has its own `approvalReviewer`, sourced from Hook or rollout `payload.approvals_reviewer`, with values `user`, `auto_review`, or `guardian_subagent`.--Each execution has one optional approval record: `pending` means the route is unconfirmed, and `waiting` means user approval is required. A `PermissionRequest` is confirmed immediately when the known reviewer is `user`; an unknown reviewer retains the candidate, and an automatic reviewer clears it. The record carries request time, tool name, and sequence. Repeated requests do not overwrite an existing wait's presentation.--Only progress reliably attributed to the same agent and turn can clear that execution's approval. Valid tool, compaction, subagent lifecycle, and top-level `Stop` Hooks follow their recovery rules; rollout execution progress must be strictly later than the request. Reviewer backfill cannot reopen a cleared candidate. An explicit child rollout terminal also clears that execution's wait.--The task stays in `waitingApproval` while any user wait remains, displaying the earliest request and using sequence to break time ties. Changing the displayed wait does not reset the task's waiting start time. Other agents' progress and progress with incomplete identity do not clear known waits. Parallel calls within one agent and turn share an approval record, with recovery inferred from progress.--### Effort Merging--Several context events in one turn may report different reasoning efforts. The task does not silently let the last overwrite the first. It marks `mixed` after observing conflict.--### Subagent Count Reliability--Subagent Hook `agent_id` and `turn_id` identify the child thread and turn. The monitor reads that thread's rollout, validates thread identity with `session_meta.id`, checks parent-thread information using `parent_thread_id` or its fallback `source.subagent.thread_spawn.parent_thread_id`, and associates the root task through `root_turn_id` in context or start records. `root_turn_id` identifies the root turn, not the direct parent agent's turn.--The root session ID comes first from `session_meta.session_id`, falling back to an existing association or the unique root session ID in Hooks for that child turn. Child events with complete identity are buffered until association, then replayed with their original source. Missing fields or conflicting associations do not fall back to the sole active task. Subagent activity updates only the matching active root task and creates no independent card.--The active subagent count follows associated `SubagentStart` and `SubagentStop` events, separately from approval records. Reliability is initialized from whether the prompt start is known; a stop first observed for an agent sets it to `false`, hiding the count in the UI. Each agent's running state follows its own event timestamps. A late start does not count an execution already confirmed ended as running.--## Snapshot Priority--The activity card selects content through `primaryActivity` in this order:--```text-Waiting for approval > Running > Latest completion or termination > Idle-```--`latestTerminalEvent` selects the latest completion or termination by end time, with termination taking precedence on ties. The activity card, menu bar, and idle task glow share this result. The menu bar uses `primaryActivity` and limits terminal display to 10 seconds after the end timestamp. Task Center retains terminal records for 10 minutes; terminal deduplication memory lasts 24 hours.--The snapshot feeds:--- Menu bar person symbol-- Main-panel task card-- Task Center-- Task glow, receiving snapshots and new terminal events through `presentationPublisher`-- Notification system-- Sleep-prevention controller--### Snapshot Publication--The monitor checks rollout each second and refreshes at cleanup deadlines.--A candidate snapshot is compared with the current value and published only after structural change. Views format elapsed time from the current clock and do not require per-second mutation of task objects.--### Presentation Updates--`presentationPublisher` publishes the current snapshot and the batch's still-valid `terminalEvents` for Task Glow. Presentation events include anonymous tasks; notifications use the separate `transitionPublisher`.--Completion transitions and terminal indicators require an end timestamp no more than 10 seconds old and no earlier than their respective recovery boundaries. Waiting transitions, whether confirmed directly by Hook or through rollout reviewer backfill, require the task's waiting start time to be no more than 10 seconds old and no earlier than `sessionTransitionNotBefore`.--History reloads, sleep recovery, and source health changes clear pending events and update `terminalPresentationNotBefore`. Publication pauses during bootstrap, recovery reconciliation, and unhealthy source state.--### Stable Ordering--Several tasks in one batch can share a timestamp; comparing timestamps alone does not determine their relative order.--All lists sort by most recent time first and then display UUID string. Stable order keeps SwiftUI diffing from jumping when equivalent tasks randomly exchange positions.--### Cleanup Uses the Nearest Deadline--The monitor manages expiration for pending tasks, active tasks, history, terminal deduplication, and protection records. Menu bar terminal hints and task glow have their expiry managed by `StatusItemController` and `TaskGlowController`, respectively. Hint expiry does not republish activity snapshots.--The cleanup task waits for the nearest future deadline, processes it, then schedules the next.--## System Sleep and Wake--Stalled Task Protection pauses when the system is about to sleep. Full recovery after wake follows this order:--1. Enter recovery and keep protection paused-2. Wait for `HookEventTailReader.drainNow()` to succeed-3. Reset rollout-lifecycle parsing fallback-4. Reconcile from the new Hook and rollout results together-5. Resume Stalled Task Protection--If the Hook barrier returns `sourceUnavailable`, only explicit terminal records for known tasks are reconciled, silently, while protection stays paused. Later polling retries full recovery. Reader replacement or task cancellation discards that round’s results.--### Evaluation Pauses During System Sleep--Silence evaluation stops during system sleep. On recovery, the monitor silently reconciles progress from newly read Hook and rollout data before resuming normal evaluation.--The check task waits with `SuspendingClock`, but silence duration is calculated from `Date` and `lastProgressAt` without subtracting time spent asleep. `will-sleep` enters recovery; `did-wake` reevaluates after a new data read barrier.--### Identity and Generations During Wake Recovery--Full recovery consumes Hook events first to establish task identities created during sleep, then merges rollout lifecycle and progress before resuming protection. Degraded terminal reconciliation handles known tasks only.--`tailReaderGeneration` prevents a returning wake task from using a reader replaced by a Hook settings change. `activityProtectionRecoveryGeneration` prevents an older recovery from unpausing evaluation after two overlapping sleep or settings changes.--If the recovery generation changes while bootstrap awaits rollout, its old lifecycle result is discarded. Bootstrap then enters a fresh read barrier instead of completing the newer recovery generation.--## Stalled Task Protection--Stalled Task Protection works only while Prevent System Sleep is enabled and evaluates only non-anonymous `running` tasks.--Tasks waiting for approval are excluded because waiting is a legitimate no-progress state.--Threshold options are:--- 30 minutes-- 1 hour, the default-- 2 hours-- 4 hours--At the threshold:--1. Update the in-memory protection record and enqueue its serial persistence-2. Start notification submission and a 3-second grace period together-3. Revalidate the candidate after notification completes or grace expires-4. If still valid, hide it from the activity snapshot-5. If new progress appears during or after this process, clear protection and restore display--Hiding does not depend on notification success. The 3 seconds is only the maximum wait for an explanatory notification; sleep-prevention contribution is still released afterward.--Evaluation pauses during:--- Hook bootstrap-- System sleep-- Wake recovery-- Hook data-source unavailability-- Reader replacement-- An incomplete rollout that does not qualify for the partial-tail fallback, a read failure, missing context, or an expired read result--### Purpose of Progress Generation--Timestamps alone cannot protect an asynchronous attempt. Two progress events may share the same second, and the threshold setting may change while notification submission is in flight.--Every valid progress event increments `progressGeneration`. A protection candidate stores:--- Task display ID-- Last-progress timestamp-- Progress generation-- Threshold at the time--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.--### Protection Record Save Ordering--An attempt updates the in-memory record synchronously, then a task calls `ActivityProtectionStateStore.apply` in sequence. A disk-write failure is logged and does not prevent hiding the task.--Saved records restore protection during the next bootstrap. Hiding does not wait for disk commit, so recovery across restarts depends on the write succeeding.--### Reconciling Threshold Changes--Shortening the threshold immediately reevaluates running tasks already past it.--Increasing the threshold silently restores suppressed tasks that no longer exceed it and clears their records and notifications. Tasks still beyond the threshold remain hidden.--Restoration and suppression use the same timing reference: the later of task progress and the retained observation of the partial tail's last growth. Restoration after increasing the threshold does not require the read result to remain within its five-second validity window. Suppressing the task again still requires fresh read evidence and reaching the new deadline.--Turning off the sleep-prevention switch disables Activity Protection and restores all suppressed tasks in the current process.--## Protection-State Persistence--[`ActivityProtectionStateStore.swift`](../../../CodexBar/Services/Workflow/ActivityProtectionStateStore.swift) writes:--```text-~/Library/Application Support/CodexBar/ActivityProtection/state.json-```--- Current schema is `1`-- Contains only hashed task identities and timestamps-- File permissions are `0600`-- Debug and Release share it through `flock`-- Records remain at most 24 hours after last progress--Task identity uses a SHA-256 digest; raw session and turn IDs never enter this state file. Anonymous tasks have no protection identity and never enter it.--### Constructing the Hashed Identity--Turn and session keys first become canonical strings with type prefixes and NUL separators, then SHA-256 is applied with the fixed domain separator `CodexBar.ActivityProtection.v1`.--Types and separators prevent boundary ambiguity between concatenated fields. The domain separator prevents directly correlating the same raw ID hashed for another use.--### Cross-Process State Merge--Both app bundle IDs can run together and observe the same Codex Hook data. With separate protection state, a stalled task hidden by one build might still drive sleep prevention in the other.--The state store uses an actor to serialize within one process and `flock` for cross-process read-modify-write. A removal can include `matchingMarkedAt`, preventing a late delete from an old process from removing a new record just written by another.--Writes sort by task identifier, atomically replace the file, and correct final permissions to `0600`.--## Generation and Old-Result Isolation--The monitor maintains generations for readers and asynchronous recovery:--- Discard late results from a replaced reader-- Publish no transition side effects before bootstrap completes-- A canceled drain does not satisfy a recovery barrier-- Explicitly unhealthy source state cannot reuse the last healthy snapshot for silence evaluation--### Main Generations in the Monitor--| Generation | Protected asynchronous path |-| --- | --- |-| `tailReaderGeneration` | Reader batch, rollout polling, and prompt backfill |-| `bootstrapCompletionGeneration` | Bootstrap lifecycle completion and rollout reconciliation results spanning a bootstrap |-| `activityProtectionRecoveryGeneration` | Sleep/wake recovery and rollout reconciliation results spanning recovery generations |-| Task `progressGeneration` | Protection candidate during notification grace |--Task progress invalidates its protection attempt. Reader, bootstrap, and recovery generations each isolate their own asynchronous results.--## Suggested Failure-Scenario Tests--- Continue from a Stop handler, then complete or interrupt, without premature completion notifications-- Interrupt while a Stop handler is running and confirm one termination record and red hint-- Keep rollout unreadable for more than five seconds, then recover and confirm completion once-- Request approval after Stop continuation, then interrupt and clear the waiting task-- Interrupt running, waiting, and suppressed tasks; verify state, duration, protection cleanup, and no completion notification-- Deliver Hook and rollout termination in both orders; verify one record and one hint-- Interrupt an old turn after starting a new one; keep the new turn active-- Replay duplicate Interrupt and late tool/prompt events without restoring the ended turn-- Starting the app while a task is running shows it through bootstrap without replaying notifications-- Bootstrap retries while files continuously append and eventually obtains a stable boundary-- Three unstable attempts enter degraded state without starting silence evaluation-- Replace an old turn with a new prompt and verify classification when the terminal arrives within and after the first five seconds-- A `Stop` is not guessed when one session has several terminal candidates-- Put the main agent and multiple subagents into waiting; each recovery clears only its own wait, and running resumes after the last wait clears-- Ordinary rollout activity preserves waiting; newer execution progress from the same owner clears it, equal-time progress preserves it, and late approvals or reviewer backfill do not reopen cleared waits-- A child `root_turn_id` pointing to an old turn does not update the new task; missing or conflicting associations do not guess the parent-- Attribute turnless records after a new boundary only to the new turn; late old terminals, incremental reads, and file replacement preserve context isolation-- A missing reviewer enters waiting only after rollout confirms user-- Automatic review never emits a waiting transition-- The UI hides the subagent count when count reliability is `false`-- Calling `drainNow()` during a read forces another new read-- A failed wake drain keeps protection paused; explicit rollout terminals silently end known tasks during Hook corruption, while ordinary progress leaves suppressed tasks hidden-- A silence candidate that progresses within the 3-second window is not hidden, and a late notification is withdrawn-- Lengthening the threshold restores suppressed tasks below the new threshold-- Concurrent Debug and Release updates do not let an old removal delete a new protection record-- Anonymous tasks never enter transitions, KeepAlive, or the protection state file--## Key Source Files--- [`CodexActivityTokenUsage.swift`](../../../CodexBar/Services/Workflow/CodexActivityTokenUsage.swift)-- [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift)-- [`CodexActivityTask.swift`](../../../CodexBar/Services/Workflow/CodexActivityTask.swift)-- [`CodexActivitySubagentTracking.swift`](../../../CodexBar/Services/Workflow/CodexActivitySubagentTracking.swift)-- [`CodexActivityTerminalResolution.swift`](../../../CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift)-- [`HookEventTailReader.swift`](../../../CodexBar/Services/Workflow/HookEventTailReader.swift)-- [`CodexSessionLifecycleReader.swift`](../../../CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift)-- [`CodexActivityProtection.swift`](../../../CodexBar/Services/Workflow/CodexActivityProtection.swift)-- [`ActivityProtectionStateStore.swift`](../../../CodexBar/Services/Workflow/ActivityProtectionStateStore.swift)diff --git a/Docs/en/DeveloperGuide/app-server.md b/Docs/en/DeveloperGuide/app-server.mddeleted file mode 100644index 8d36f38..0000000--- a/Docs/en/DeveloperGuide/app-server.md+++ /dev/null@@ -1,485 +0,0 @@-# app-server Data Flow--[简体中文](../../DeveloperGuide/app-server.md) | English--## Responsibilities--The app-server flow reads Codex account and server state:--- Current account and plan-- Rate-limit groups and windows returned by Codex-- Token usage and usage history-- Reset Credits state-- Hook feature flags, handler lists, and configuration-write capabilities--It does not own historical Hook metrics or live task state.--### Input and Output Boundaries--```text-CodexCLIResolver- -> AppServerCommand- -> CodexStatusService actor- -> AppServerSession- -> Process + stdin/stdout/stderr- -> CodexQuotaSnapshot- -> CodexStatusViewModel- -> Menu bar and main panel-```--`CodexStatusService` owns the connection and same-account cache. `CodexStatusViewModel` owns only UI loading state, automatic-refresh timing, and the latest connection information.--Settings reuses this session for Hook and TUI configuration.--## Locating Codex CLI--[`CodexCLIResolver.swift`](../../../CodexBar/Services/CodexCLI/CodexCLIResolver.swift) searches the process `PATH` for global `codex` and checks the app resource directory:--```text-/Applications/ChatGPT.app/Contents/Resources-```--The resolver reads `codex-cli/codex-package.json` in the resource directory and resolves `entrypoint` relative to the `codex-cli` directory. If the manifest cannot be decoded or the entrypoint is not executable, it checks `codex` in the resource directory.--A menu bar app launched from Finder may lack the complete `PATH` of an interactive shell, so the resolver also adds common installation directories:--```text-/opt/homebrew/bin-/usr/local/bin-~/.npm-global/bin-~/.local/bin-~/.volta/bin-/usr/bin-/bin-/usr/sbin-/sbin-```--The data directory uses `CODEX_HOME` when set and otherwise uses `~/.codex` under the real user's home directory.--### Process Environment Normalization--An `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 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 container-2. Preserve the existing `PATH`, then append common directories in order and deduplicate-3. Resolve symlinks and standardized URLs for candidates so one bundled binary is not identified as both global and bundled--`CodexCLISourceSelection.automatic` prefers the global CLI and falls back to the bundled CLI when none is found. Selecting `global` or `bundled` uses only that source and returns `sourceUnavailable` if it is missing. `CodexStatusService` saves the selection and reuses it when rebuilding the connection.--### Disk and Running Versions--Settings may read versions from both CLI candidates on disk, but minimum-version checks for the primary flow and Hook use only the app-server `userAgent` returned by `initialize`.--A connection may be reused for up to 1 hour. If the user upgrades the on-disk binary while it remains alive, the current process is still the old version. Checking the disk value would let the UI claim a capability is available while the running app-server does not support its method.--## In-App Proxy--The proxy is implemented by the following types:--| Type | Responsibility |-| --- | --- |-| [`CodexProxyConfiguration`](../../../CodexBar/Models/CodexProxyConfiguration.swift) | HTTP/HTTPS settings, input validation, and child-process environment |-| [`CodexProxyStore`](../../../CodexBar/Services/Settings/CodexProxyStore.swift) | Settings and password stored under `CodexProxy.configuration` in UserDefaults |-| [`CodexProxySettings`](../../../CodexBar/Services/Settings/CodexProxySettings.swift) | Saved configuration, editing draft, toggle commits, and test state |-| [`CodexProxyConnectionTester`](../../../CodexBar/Services/CodexStatus/CodexProxyConnectionTester.swift) | Independent test process using the draft |--Without an enabled configuration, the regular connection uses `CodexCLIResolver.environment`. Enabling a proxy sets `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `WS_PROXY`, `WSS_PROXY`, and their lowercase forms. `NO_PROXY` and `no_proxy` become `localhost,127.0.0.1,::1`. Only custom-proxy processes append `-c features.respect_system_proxy=false`; the configuration is not written to global Codex files.--Loading preserves decodable raw input. Enabling the proxy and saving an edited form validate the server, port, and authentication username; disabling it permits invalid fields to remain stored. Undecodable records still have a clear action.--The toggle updates its displayed state and sets `isSaving` before creating the asynchronous task; repeated toggles are ignored while it runs. `CodexStatusService.applyProxy` serially saves settings, closes the old connection, and clears supplemental caches. Completion restores interaction and triggers a refresh; failure restores the previous toggle state. The dialog edits a separate draft, committed only by Save or Clear.--### Connection Tests--Testing temporarily enables the draft, resolves the selected Codex source, and calls `AppServerSession.initializeAccount()` for the same handshake and account checks used by regular connections. It then calls `account/rateLimits/read`. Regular connections continue with rate limits and usage after the handshake.--Test requests share an eight-second deadline, do not retry server business errors, and do not record interaction logs. The temporary process is closed on exit using the session’s shutdown wait budget. Editing fields, canceling a test, or closing the dialog cancels both the outer task and its worker; canceled results cannot update the UI.--## Process and Protocol--CodexBar launches this command and communicates over stdio:--```bash-codex app-server --listen stdio://-```--The protocol is line-delimited JSON-RPC. A connection sends `initialize`, then `initialized`, then reads the account:--```text-Start subprocess- -> initialize(clientInfo)- -> Validate actual version >= 0.145.0- -> initialized- -> account/read- -> account/rateLimits/read- -> account/usage/read-```--stdout may contain non-JSON output. The pipe reader continuously reads complete lines and forwards only messages that decode and match the response ID of a pending request. stderr is drained separately so the subprocess cannot block on a full pipe.--### Complete Connection Transaction--```text-Resolve executable- -> Create stdin/stdout/stderr pipes- -> Start Process- -> initialize(clientInfo)- -> Save actual version from userAgent- -> Validate actual version >= 0.145.0- -> initialized notification- -> account/read(refreshToken: false)- -> Account exists: commit connection- -> Account missing: close process and return notLoggedIn-```--A connection enters service state only after the actual version passes the global threshold and both handshake and first account read succeed. A confirmed version below `0.145.0` returns an unsupported-version error. A missing or unparseable version returns an invalid-response error and cannot trigger Hook removal for an unsupported version. Both cases close the half-initialized session without further account requests.--### Stdout Framing and Response Matching--app-server frames one JSON message per line. A `Data` block delivered to the pipe callback may:--- Contain half a line-- Contain several lines-- Mix ordinary logs between JSON lines-- End with an unterminated final line when the process exits--`PipeReadBuffer` maintains a byte buffer, emits nonempty newline-delimited lines during reading, and flushes a nonempty trailing fragment at EOF or when stopped. The session first decodes the response ID and fully decodes the result or error only for a matching ID.--This avoids treating logs as protocol errors and fully decodes a large response only once.--### Stderr Draining--Even though CodexBar does not display stderr content, it must drain the pipe. A subprocess pipe buffer is finite; if the parent never reads stderr, app-server eventually blocks while writing and no later stdout response can arrive.--`PipeDrain` does not parse content; it continuously drains stderr.--### Shutdown Strategy--A session shuts down in this order:--1. Stop stdout and stderr readers-2. Close the stdin writer-3. Send `SIGTERM` if the process is still running and wait up to 1 second-4. If still running, send `SIGKILL` and wait another 0.5 seconds-5. Record a diagnostic error if it remains alive--Writing after an early process exit may raise `SIGPIPE`. The service ignores that signal during initialization so the write returns a Swift error and follows the transport-rebuild path instead of terminating the entire menu bar app.--## API Surface--| Method | Purpose |-| --- | --- |-| `account/read` | Read account, plan, and authentication state |-| `account/rateLimits/read` | Read rate-limit windows |-| `account/rateLimitResetCredit/consume` | Use a specified Reset Credit |-| `account/usage/read` | Read tokens and usage history |-| `config/read` | Read Codex configuration |-| `hooks/list` | Validate Hook source and event capabilities |-| `config/batchWrite` | Change Hook or TUI notification configuration |--### Session Capability Cache--`AppServerSession` caches methods for which app-server explicitly returns method unsupported and skips them for the rest of that connection. The cache exists only in memory; capabilities are probed again after the connection is rebuilt.--## Session Lifecycle--[`CodexStatusService.swift`](../../../CodexBar/Services/CodexStatus/CodexStatusService.swift) is an actor that owns the connection and refresh state:--- One request times out after 20 seconds-- Connection age is checked on requests; a connection aged 1 hour is rebuilt-- A business error retries at most once in the same session-- A transport failure rebuilds the connection at most once-- When authentication requires refresh, `account/read` retries with `refreshToken = true` at most once-- Closing or releasing a connection terminates its subprocess; a request that encounters a closed reader reports a connection error--Business and transport errors are separate. The former may be a temporary failure of one method; the latter makes the current stdio session untrustworthy.--### Connection State Machine--```text-no connection- -> resolve CLI- -> open and initialize- -> ready--ready- -> age < 1h and process alive: reuse- -> process exited: close and rebuild- -> age >= 1h: close and rebuild- -> transport failure: close and rebuild once- -> account missing after refresh: close and notLoggedIn-```--One hour is the reuse limit checked at request time. The next request after that limit rebuilds the connection using the Codex binary then on disk; no independent timer destroys the connection.--Manual reconnection, source changes, and expired-connection rebuilding all close the old connection first; a failed replacement leaves the app disconnected. Source selection is saved only after successful manual reconnection. Automatic refresh and manual reconnect errors both update `CodexStatusViewModel.connectionErrorMessage`, which About displays.--### Error Classification Matrix--| Error | Current request | Current connection | Full refresh |-| --- | --- | --- | --- |-| Retriable server error | Retry the same method once | Preserve | Continue from second result |-| Method unsupported | Mark unsupported for this session | Preserve | Corresponding field is missing |-| Ordinary business failure | Do not retry | Preserve | Same-account cache may degrade |-| Authentication required | Refresh the token once for the cycle, then retry | Preserve or become signed out | At most one refresh overall |-| Timeout, pipe close, invalid transport | Fail | Discard immediately | Rebuild once only when reusing a connection |--Limiting reconstructions prevents a fault from repeatedly launching subprocesses. The next normal timed refresh still gets a new attempt after the current cycle ends.--### Authentication Refresh Budget--One refresh reads account, rate limits, and usage; Reset Credits details are included in the rate-limit response. Several interfaces may detect an expired token in the same cycle.--`fetchData` uses one `didRefresh` latch for the entire cycle. The first authentication failure triggers `account/read(refreshToken: true)`, and later methods reuse that result. A second authentication requirement is classified as signed out.--## Refresh Model--The status view model refreshes at the selected data update interval of 1, 2, 3, 5, or 10 minutes, defaulting to 1 minute. Users can double-click the account icon in the main panel to request an immediate refresh.--Each refresh resolves the account first, then reads rate limits and usage. Supplemental caches are strictly bound to account identity:--- If the account is unchanged and a supplemental request fails, cached values may remain visible-- If the account changes, the old-account cache is cleared immediately-- An explicitly unsupported method appears as a missing source-- A missing source must not become the business value `0`--Ordinary refresh triggers are ignored during a refresh or reconnect. Operations requiring a follow-up use `refreshAfterCurrent` to retain one pending trigger until the current request ends; the coordinator handles cancellation and stale-result checks.--### Building One Snapshot--```text-Confirm or create connection- -> On reuse, account/read- -> Confirm account identity- -> account/rateLimits/read (including Reset Credits details)- -> account/usage/read- -> Build CodexQuotaSnapshot- -> Commit loadState and connection info on MainActor-```--Rate limits and usage are supplemental. As long as the account is valid, CodexBar still creates a snapshot when both interfaces return no data so the UI can show the account and an explicit “No Data.”--### Cache Decision Table--| Current result | Same-account cache | Output | stale |-| --- | --- | --- | --- |-| Success | Any | New value and cache update | `false` |-| Ordinary request failure | Yes | Cached value | `true` |-| Ordinary request failure | No | `nil` | Not applicable |-| Method unsupported | Any | `nil` | Not applicable |-| Account changed | Old-account cache | Clear all first | Not applicable |--Method unsupported does not use old cache because it is an explicit capability result. Ordinary failure does because the source may be transiently unavailable for one cycle.--### How Stale State Affects Consumers--- The UI may display old values but reduces menu bar and progress-bar opacity-- `hasTrustedData` counts only non-stale rate-limit or usage data as trusted-- Rate-limit notifications skip stale rate limits entirely-- System logs record only a `cached` step, never actual rate-limit values--Stale is part of data confidence. A new presentation must not copy the value while dropping the marker.--### Refresh Generation Checks--An `isRefreshing` guard prevents ordinary duplicate triggers, but cancellation and object lifecycle may still let an old `Task` return.--`RefreshTaskCoordinator` advances its generation at each start, cancels the old task, and allows only a result satisfying `canCommit(generation)` to update UI. “Last requested refresh wins” becomes an explicit rule.--Automatic refresh waits for the remaining interval since the last completion. After a manual refresh, the countdown realigns naturally rather than letting the old timer refresh again a few seconds later.--### Data Models and Display Projection--`CodexUsageSnapshot` aggregates potentially repeated daily buckets into `tokensByDate` during initialization.--A heatmap queries dates repeatedly during one render. Building an optional index up front avoids a linear scan for every cell and limits snapshot equality to summary metrics, daily-data availability, and aggregated daily tokens. Raw bucket ordering or partitioning does not affect the rendered result or independently trigger animation.--The `summary` object from `account/usage/read` is required, but every summary metric and `dailyUsageBuckets` may be absent or null. The model preserves those states: a missing summary metric renders as `--`; `dailyUsageBuckets == nil` means daily data is unavailable, while an empty array means the read succeeded with no records. A valid partial response is not filled from older values. A business payload decoding failure is handled as a supplemental-read failure without rebuilding the app-server session or clearing rate-limit data.--Rate-limit ordering is also centralized in the model:--- The primary limit referenced by the top-level app-server `rateLimits` comes first-- Remaining limits use a stable sort by localized name and limit ID-- Stable enums distinguish primary and secondary; views do not infer window type from label strings--## Reset Credits--The UI labels the available count “Banked Resets” or “留存重置”, using the localization key `banked-reset.count`. The protocol field remains `rateLimitResetCredits`.--`rateLimitResetCredits` from `account/rateLimits/read` provides both an available count and optional details:--- `availableCount` is the authoritative total-- `credits == nil` means only the count is known-- An empty array means the server obtained details but returned no available credit-- The server may truncate details, so their length can be less than `availableCount`-- Each detail includes an opaque `id`, `status`, and optional Unix-seconds `expiresAt`-- Each detail also includes `resetType`; Automatic Reset accepts only `codexRateLimits`--The model retains expiration dates only for entries with `status == available` and a time later than snapshot creation, then sorts them by time. The count still comes independently from `availableCount` and cannot be inferred from filtered dates.--Expiration details are supplemental. With `credits == nil`, the main panel still shows the available count and details show an unknown expiration time without affecting rate limits or usage. When rate-limit data comes from same-account cache, the UI may display old details, but notifications never use stale data for new expiration alerts.--### Automatic Reset--After the user explicitly enables Automatic Reset, [`AutoResetController.swift`](../../../CodexBar/Services/CodexStatus/AutoResetController.swift) processes only credit details explicitly returned by the latest `account/rateLimits/read`:--- It never calls consume for a stale snapshot, `credits == nil`, missing `expiresAt`, non-`available` state, or a `resetType` other than `codexRateLimits`-- Details may be truncated; it processes only returned credits and never guesses unlisted `creditId` values from `availableCount`-- It selects only the earliest-expiring returned credit at a time, then selects the next after completion or disappearance-- After entering the user-selected lead-time window, it forces another account and credit read before redemption-- The request always passes an explicit `creditId`; the backend never chooses implicitly-- It reads rate limits again immediately after a redemption result-- `reset`, `alreadyRedeemed`, and `noCredit` request a full rate-limit refresh; `nothingToReset` schedules another attempt if the target remains, otherwise it requests a full refresh--The call has this shape:--```text-account/rateLimitResetCredit/consume- creditId: <exact opaque id>- idempotencyKey: <deterministic UUIDv5>-```--Results have these semantics:--| `outcome` | Conclusion | Next action |-| --- | --- | --- |-| `reset` | This call redeemed the credit | Success notification, rate-limit refresh, stop retrying this credit |-| `alreadyRedeemed` | The same idempotency key redeemed it previously | Treat like `reset` and as success |-| `nothingToReset` | No rate-limit window can currently be reset | Credit remains unredeemed; retry with the same idempotency key |-| `noCredit` | The account currently has no available credit | Force refresh; stop silently if the target disappears, otherwise retry as temporary inconsistency |--`alreadyRedeemed` confirms that the same logical request previously succeeded. It stops retries and sends a local success notification according to notification settings.--### Cross-Device Idempotency Contract--The same Codex account may run CodexBar on several Macs. Devices do not coordinate through CloudKit. They calculate the exact same UUIDv5 for the same `creditId`:--```text-namespace = c2904ab3-0a87-5648-997d-bd8515edd401-name = raw UTF-8 bytes of creditId-output = lowercase UUID string-```--The namespace is UUIDv5 of the URL namespace and `https://codexbar.zabrian.app/idempotency/auto-reset/v1`. This URL determines the namespace only and does not represent a runtime network request.--The fixed test vector is:--```text-creditId = RateLimitResetCredit_123-idempotencyKey = 4035685d-9ca4-524f-8193-6e0ae2a7b3b9-```--The namespace, UUID version, raw UTF-8 input, and lowercase output form a cross-version compatibility protocol and must not change in an ordinary refactor. The first successful device redeems the credit; other devices calling with the same key receive `alreadyRedeemed` or discover during preread that the credit disappeared.--Disappearance cannot distinguish manual use, use by another device, or server expiration. The local task therefore stops without an Automatic Reset success notification. Only a device that explicitly receives `reset` or `alreadyRedeemed` sends one.--### Scheduling and Retry--The Automatic Reset state machine and network requests remain in the regular app process. CodexBarHelper owns only a constrained system wake schedule:--- Enabling the feature reuses existing CodexBarHelper registration and approval without depending on Prevent System Sleep-- The app submits only the nearest threshold or retry time; the helper replaces only CodexBar's own event with a fixed owner and `wake` type and accepts no arbitrary event type-- After setting or canceling, the helper reads back system events and reports success only if exactly one target-time event exists or the event is confirmed absent-- After a timer or wake, the app holds `PreventUserIdleSystemSleep` only during fresh reads and redemption; it does not keep the display awake or change `SleepDisabled`-- A task change, feature disable, app exit, or corresponding XPC disconnect cancels CodexBar's wake event-- On startup, the helper removes stale events for its fixed owner before accepting connections; if cancellation fails, it abandons the invalid connection owner and retries internally-- Normal app exit waits for cancellation read-back; a forced exit or XPC disconnect makes the helper cancel immediately, while a sudden-power-loss event converges at next helper startup, after which the app reschedules from fresh details-- On app launch, feature enable, or system wake, the app performs a fresh read first; it attempts immediately if the credit is inside its lead-time window and unexpired, otherwise it schedules for that window-- The app does not persist raw `creditId` after exit; next launch rebuilds tasks and the same deterministic idempotency key from fresh details-- When `expiresAt` changes for the same `creditId`, it preserves idempotent identity but cancels the current threshold or retry and reschedules; if the new lead-time point has passed, it rechecks immediately-- A retry wake event requires a known `creditId + expiresAt`; a count-only or failed read never wakes the Mac merely to query again-- Network, timeout, disconnect, or temporary service errors use `15s, 30s, 1m, 2m, 5m` backoff but never schedule a retry at or after the current 5-minute deadline-- At round timeout, local work and the system wake event are canceled without marking the target failed; a later normal rate-limit refresh may start a new round for it-- `nothingToReset` waits a fixed 60 seconds when expiration is less than 10 minutes away and the round remains active; otherwise it uses general backoff-- Authentication failure first uses the service's single token refresh; if still unsuccessful, it pauses the current credit and notifies according to settings, then resumes after a trusted snapshot proves recovery-- Parameter, protocol, or method errors stop the current credit without meaningless retries--When Automatic Reset requests a full rate-limit refresh while an ordinary refresh is in progress, the new refresh queues behind it and must not be dropped by the `isRefreshing` guard.--## Hook Version and Configuration Validation--Hook settings reuse the app-server flow but maintain independent availability state:--- `isEnabled` tracks enabled state for the current process, initially restored from an existing handler; configuration lost during runtime triggers repair-- `isVerified` defaults to `true`, then retains the latest explicit validation result-- `isOperable` is true only when both are `true`-- A transient RPC failure preserves the last explicit validation result--Enabling or validating Hook requires the actual app-server version to be at least `0.153.0`.--See [Hook Capture and Historical Aggregation](hook-and-aggregation.md) for the full configuration flow.--### Timing of the Actual-Version Check--Enabling or validating Hook calls `readyConnectionInfo()`:--- If no connection exists, it establishes one first-- If a connection exists, it reuses the actual current process-- It parses the running version from the handshake user agent-- An unparseable version rejects the connection without triggering Hook removal for an unsupported version--## Request Logs--[`RequestLog.swift`](../../../CodexBar/Services/CodexStatus/RequestLog.swift) keeps the latest 500 request records in memory for the in-app Logs window.--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 replace usernames and passwords in HTTP/HTTPS URLs with `<redacted>`. Non-JSON messages receive the same replacement directly.--### Request and System Logs--Unified system logs retain only control-flow classifications and support long-term diagnosis of whether refresh ran and which stage failed.--The in-app `RequestLog` keeps previews of at most 500 request interactions in current-process memory for user-initiated protocol inspection.--Reset Credits details include opaque credit IDs. Unified logs must not record IDs or raw responses; the in-app request log remains current-process-only under its existing rules. Before logging a new RPC, check whether its payload can contain credentials or content fields.--## Suggested Failure-Scenario Tests--- A Finder launch still finds Codex installed by Homebrew, npm, or Volta-- When the global CLI is absent, fallback correctly uses the binary bundled with ChatGPT App or Codex App-- Ordinary text mixed into stdout does not prevent matching the correct response ID-- Continuous stderr output does not stall requests through pipe backpressure-- A transport failure on a reused connection rebuilds only once-- After an on-disk CLI upgrade, the current connection version remains distinct from the disk version-- app-server below `0.145.0` blocks the primary account flow and asks for an upgrade-- app-server from `0.145.0` up to but excluding `0.153.0` supports the primary account flow while Hook still requires `0.153.0`-- app-server `0.153.0` or later supports both the account flow and Hook validation-- A failed rate-limit read with same-account cache displays stale data without triggering notifications-- An account switch clears old rate-limit and usage data immediately-- An unsupported method is not retried within the same connection-- Reset Credits with `credits == nil` preserve the authoritative count and show unknown expiration-- Empty or truncated Reset Credits details do not redefine the available count from array length-- Expired or non-available Reset Credits do not enter details or notifications-- Stale rate limits may show old details but do not trigger expiration notifications-- Automatic Reset does not call consume while off; a missing setting defaults off and lead time defaults to 30 minutes-- Automatic Reset does not consume stale, detail-less, expiration-less, or unlisted credits-- Two devices derive the same idempotency key for a fixed `creditId`, matching the fixed test vector-- Changing expiration earlier or later for the same `creditId` reschedules while preserving the idempotency key-- Both `reset` and `alreadyRedeemed` stop retries and send success notifications-- `nothingToReset` retains the credit and retries under backoff-- With sleep prevention off, the helper can still register and receive approval, and a future threshold writes a fixed-owner `wake` event-- A scheduled time during system sleep wakes the Mac and triggers a reread; natural wake and app launch run the same catch-up check-- Disabling the feature, changing the target, or quitting cancels the wake event without affecting other apps' scheduled events-- Count-only or failed reads with no specific target do not schedule a query-retry wake event-- A known target stops continuous retries 5 minutes after the near-expiration trigger; a later normal refresh may start a new round-- A full rate-limit refresh after redemption is not dropped behind a concurrent ordinary refresh-- The countdown realigns to the selected data update interval after manual refresh-- Changing the interval during an automatic-refresh wait reschedules it from the last committed result; in-flight requests continue, and the selected interval is restored after restarting--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 Files--- [`CodexCLIResolver.swift`](../../../CodexBar/Services/CodexCLI/CodexCLIResolver.swift)-- [`AppServerSession.swift`](../../../CodexBar/Services/CodexStatus/AppServerSession.swift)-- [`AppServerPipeReaders.swift`](../../../CodexBar/Services/CodexStatus/AppServerPipeReaders.swift)-- [`CodexStatusService.swift`](../../../CodexBar/Services/CodexStatus/CodexStatusService.swift)-- [`CodexStatusViewModel.swift`](../../../CodexBar/Services/CodexStatus/CodexStatusViewModel.swift)-- [`AutoResetController.swift`](../../../CodexBar/Services/CodexStatus/AutoResetController.swift)-- [`AutoResetIdentity.swift`](../../../CodexBar/Services/CodexStatus/AutoResetIdentity.swift)-- [`AutoResetWakeScheduler.swift`](../../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift)-- [`CodexBarHelperXPC.swift`](../../../Shared/CodexBarHelperXPC.swift)diff --git a/Docs/en/DeveloperGuide/architecture.md b/Docs/en/DeveloperGuide/architecture.mddeleted file mode 100644index 46d9fee..0000000--- a/Docs/en/DeveloperGuide/architecture.md+++ /dev/null@@ -1,304 +0,0 @@-# Architecture--[简体中文](../../DeveloperGuide/architecture.md) | English--Explore the processes, data flows, and recovery paths in the [Runtime Architecture](https://codexbar.zabrian.app/architecture).--## Technical Baseline--CodexBar 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 the following targets:--| Target | Responsibility |-| --- | --- |-| `CodexBar` | Menu bar UI, Codex data collection, Automatic Reset, notifications, sync, and system-power orchestration |-| `CodexBarHelper` | A root LaunchDaemon that handles fixed system-sleep controls and Automatic Reset wake schedules |-| `CodexBarTests` | Swift Testing unit tests without an app host, compiling production sources with isolated test data |--The app and helper share their XPC protocol through [`CodexBarHelperXPC.swift`](../../../Shared/CodexBarHelperXPC.swift).--The app uses Sparkle for update checks. The project enables `MainActor` isolation by default, and Debug and Release use different app and CodexBarHelper bundle IDs.--## Process and Trust Boundaries--```text-Codex- | launches a --hook-event subprocess and passes the event through stdin- v-CodexBar executable- |-- Hook mode: minimal parsing + flock + JSONL append + exit- |- `-- Normal mode- |-- stdio JSON-RPC <-> codex app-server (account, rate limits, Reset Credits)- |-- local read-only <-> Hook JSONL / rollout JSONL- |-- HTTPS <-> Sparkle- |-- CloudKit private database <-> daily aggregations- `-- signed XPC lease / wake date <-> root CodexBarHelper- |-- fixed pmset commands- `-- fixed IOPM wake event-```--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--### Process Lifecycle Differences--| Process | Lifetime | May do | Must not do |-| --- | --- | --- | --- |-| Hook subprocess | One event, at most a few seconds | Read stdin, extract minimal fields, append local JSONL | Initialize UI, open network connections, or wait for long-running services |-| Main app | Long-running within the user login session | Orchestrate UI, data flows, and side effects | Change system settings directly as root |-| app-server | Rebuilt on the next request after reaching 1 hour | Expose account and configuration capabilities through JSON-RPC | Substitute for Hook history or live task state |-| CodexBarHelper | LaunchDaemon | Run fixed `pmset` operations, manage a `wake` event for a fixed owner, and restore system state | Access accounts, Hook data, rollout files, the network, or arbitrary commands |--## Directory Responsibilities--```text-CodexBar/- App/ App entry points- Controllers/ AppKit window, menu bar, and panel controllers- Models/ DTOs, state snapshots, and presentation models- Services/ Data access, state machines, settings, notifications, and system services- Views/ SwiftUI views- Resources/ Info.plist, entitlements, localization, and sounds-CodexBarHelper/ root LaunchDaemon-Shared/ Cross-target XPC interface-Config/ Version configuration-Scripts/ Build, DMG, appcast, and CodexBarHelper cleanup scripts-```--## Startup Order--[`CodexBarApp.swift`](../../../CodexBar/App/CodexBarApp.swift) branches startup in this order:--```text-Process starts- -> WorkflowHookEventRecorder.handleIfRequested()- -> in --hook-event mode, read stdin, write JSONL, and exit immediately- -> in normal mode, continue- -> Create CodexBarAppDelegate- -> AppDelegate assembles long-lived services- -> Create the menu bar and auxiliary windows- -> Start refresh, activity monitoring, Automatic Reset, notifications, and power coordination-```--`--hook-event` is the short-lived subprocess mode invoked by Codex. It must finish before any UI, CloudKit, notification, or long-lived service is initialized. Capture failure must not block the main Codex workflow.--In normal mode, `CodexBarAppDelegate` creates and owns long-lived objects, including:--- `CodexStatusService` and `CodexStatusViewModel`-- `CodexProxySettings`-- `WorkflowService` and its view model-- `AdvancedModeSettings`-- `CodexActivityMonitor`-- `KeepAliveController`-- `AutoResetController`-- `WorkflowSyncSettings` and the sync scheduler-- `CodexNotificationService`-- Menu bar, shortcut, Settings-window, and update services--Before quitting, the app must cancel the Automatic Reset wake schedule and release sleep prevention. If CodexBarHelper has not confirmed that both categories of system state were restored, termination waits or is canceled. Before accepting a new connection at startup, the helper also removes stale wake events for its fixed owner, converging state left by sudden power loss or forced termination.--### Hook Startup Branch--`@NSApplicationDelegateAdaptor` connects the AppKit lifecycle to the SwiftUI app. Once the normal lifecycle begins, it may create menu bar objects, register a notification delegate, or access CloudKit.--The Hook handler runs on Codex's critical path and must behave like a command-line tool. `WorkflowHookEventRecorder.handleIfRequested()` therefore runs at the very beginning of `CodexBarApp.init()` and calls `exit(EXIT_SUCCESS)` immediately when Hook mode matches.--This order also prevents Hook capture failures from contaminating normal-exit diagnostics. `AppProcessDiagnostics.install()` runs only in `applicationDidFinishLaunching`, so a Hook subprocess is not misclassified as a complete app that exited abnormally.--### Termination Coordination--`applicationShouldTerminate` first calls `KeepAliveController.prepareForTermination()` and returns `.terminateLater`.--The app allows termination only after the helper explicitly confirms that the Automatic Reset wake event was canceled and the sleep-prevention release completed. If either cleanup fails, that termination attempt is canceled and the controller returns to normal coordination under the current settings.--Releasing asynchronously in `applicationWillTerminate` is too late because that callback cannot reliably extend process lifetime.--## Three Independent Data Flows--The data flows manage distinct inputs, freshness requirements, and failure states:--| Flow | Input | Output | Main consumers |-| --- | --- | --- | --- |-| app-server | `codex app-server` JSON-RPC | Account, rate limits, token usage, Reset Credit use, Hook configuration capabilities | Main panel, menu bar rate limit, Settings, Automatic Reset state machine |-| Historical statistics | Hook JSONL and rollout JSONL, read and aggregated separately | Daily activity metrics, cumulative thread-turn tokens, and daily token totals | Heatmap date details, historical metrics, CloudKit |-| Live tasks | Incremental Hook events plus rollout lifecycle and turn usage | Running, waiting for approval, completed, terminated, current-turn tokens | Menu bar status, Task Center, task glow, notifications, sleep prevention |--### Dependency Direction--```text-CodexStatusService ----------------> CodexStatusViewModel ----------------> UI-CodexStatusViewModel --------------> CodexNotificationService-CodexStatusService ----------------> AutoResetController-CodexStatusViewModel --------------> AutoResetController-AutoResetController ---------------> CodexNotificationService-AutoResetController ---------------> KeepAliveController ---> AutoResetWakeScheduler ---> helper--WorkflowService -------> WorkflowViewModel -----------> UI--Hook + rollout --------> CodexActivityMonitor --------> UI- | |- | +------------> CodexNotificationService- `-----------------------> KeepAliveController --> helper-```--Arrows show the direction in which data or read-only state is consumed. A downstream component must not become an upstream source of truth.--### Shared Refresh Triggers--Historical maintenance runs after rate-limit refreshes at the selected data update interval, defaulting to 1 minute, to reduce resident timers and log noise. The flows share scheduling, not facts.--When changing refresh timing, distinguish among these constraints:--- The trigger source may change-- Maintenance must still be able to run independently when app-server fails-- A lightweight statistics refresh when the UI opens must not implicitly start CloudKit network activity--## Concurrency Boundaries--The project uses Swift 6 strict concurrency with default `MainActor` isolation.--### MainActor Objects--- SwiftUI view models and settings-- AppKit controllers-- `CodexActivityMonitor`-- `KeepAliveController`-- `CodexNotificationService`-- `AutoResetController`-- `AutoResetWakeScheduler`--These objects own observable state and UI coordination. They must not perform blocking I/O directly.--### Actor Services--- `CodexStatusService` manages app-server connections and refreshes-- `WorkflowService` coordinates Hook daily aggregates and token-history snapshots-- `CodexTokenHistoryStore` manages the rollout ledger, read cursors, and explicit rebuilds-- `CodexTokenHistorySync` manages CloudKit turn-usage records and their cache-- `HookEventTailReader` manages Hook-file cursors-- `CodexSessionLifecycleReader` manages rollout-file cursors-- `WorkflowSyncService` manages CloudKit state-- `ActivityProtectionStateStore` manages cross-process protection records--DTOs crossing actor boundaries must be immutable value types and declare `Sendable` or `nonisolated` where appropriate.--### Monitor MainActor Boundary--Actors read inputs for `CodexActivityMonitor`, but the state machine itself is closely connected to several Combine consumers.--Keeping the monitor on `MainActor` provides:--- Naturally serialized publication order for `@Published snapshot` and transitions-- Identical state-commit order for notification and sleep-prevention consumers-- Unified ordering of system sleep, wake, Hook-setting changes, and UI lifecycle--The monitor must not perform blocking file reads directly. `HookEventTailReader`, `CodexSessionLifecycleReader`, and `ActivityProtectionStateStore` own those I/O boundaries.--## Model Layers--Models separate external input, persistence, domain state, and presentation:--| Model type | Role | Design requirement |-| --- | --- | --- |-| External DTO | Decode app-server, Hook, rollout, or CloudKit data | Tolerate version differences and carry no UI side effects |-| Persistence model | Store recoverable state and schema | Remain compatible with old values and express missing semantics |-| Domain snapshot | Express current trusted state to consumers | Immutable, comparable, and safe across actors |-| Transition | Represent one live state change | Never inferred from historical snapshots; deduplicated upstream |-| Presentation format | Dates, percentages, copy, and colors | Use regional settings or a fixed format for each field; never feed back into business decisions |--For example, `CodexQuotaSnapshot` can carry both a current value and a stale marker. `CodexActivitySnapshot` contains only task fields needed for presentation; raw session IDs do not enter views.--## Lifecycles and Retention--State lifetimes are:--| State | Lifetime | Reason |-| --- | --- | --- |-| app-server connection | A 1-hour reuse limit checked on requests | Later requests rebuild with the binary on disk |-| app-server supplemental cache | Current account only | Prevents values from leaking across accounts |-| Hook live bootstrap window | 24 hours | Covers long-running tasks that may still be active |-| Menu bar completion or termination | 10 seconds | Brief feedback for the latest terminal state |-| Task Center terminal history | 10 minutes | Provides recent context without occupying the UI indefinitely |-| Terminal deduplication memory | 24 hours | Prevents late Hook or rollout data from reviving old tasks |-| Raw Hook data and daily aggregations | 210 days | Supports long-term metrics and rebuilding |-| Token-turn ledger | 210 days from the latest record, retaining roots referenced by child turns | Supports daily totals, incremental reads, and rebuilding |-| Daily-aggregation identity details | 3 days | Balances recent exact deduplication with privacy and file size |-| Activity Protection records | 24 hours after the last progress | Preserves suppression across restarts while limiting identity retention |--Before changing one time window, check for paired invariants. For example, the tail-reader bootstrap window must match the active-task retention window.--## State Ownership--| State | Sole owner | Permissions of other modules |-| --- | --- | --- |-| app-server connection and same-account cache | `CodexStatusService` | Read data, change configuration, or reconnect through service methods |-| Proxy draft, tests, and toggle interaction | `CodexProxySettings` | Settings submits through methods; `CodexStatusService` applies the active connection configuration |-| Main-panel account loading state | `CodexStatusViewModel` | Observe published values |-| Automatic Reset target, deadline, and retries | `AutoResetController` | Settings changes only the switch and lead time |-| Automatic Reset wake-time synchronization | `AutoResetWakeScheduler` | `AutoResetController` submits only the next time; `KeepAliveController` submits only helper readiness |-| Hook installation and validation | `AdvancedModeSettings` | Read `isOperable` |-| Historical aggregation and maintenance cursor | `WorkflowService` | Request snapshots or rebuilds |-| Live tasks | `CodexActivityMonitor` | Read snapshots, notification transitions, or presentation updates containing new terminal events |-| Sync cursors and remote cache | `WorkflowSyncService` | Request merged snapshots |-| Sleep-prevention policy and app assertion | `KeepAliveController` | Read derived state or invoke settings entry points |-| Root sleep ownership | `CodexBarHelper` | Request and query through XPC |-| Root Automatic Reset wake event | `CodexBarHelper` | Replace or cancel one `wake` event for the fixed owner through XPC |-| Notification deduplication | `CodexNotificationService` | Upstream publishes candidate events only |--When adding a consumer, subscribe to an existing snapshot first. If it lacks a field, extend the stable value type at the state owner instead of making the consumer reread raw files.--## Error and Degradation Principles--- On transient network or RPC failure, prefer the last explainable state-- Explicitly represent an unavailable data source; do not disguise it as empty data-- Bootstrap establishes a baseline without sending notifications for historical transitions-- When a reader or data-source generation changes, discard results from the old generation-- Recovery must complete a new read barrier before evaluation continues-- Persistent writes require atomic replacement or file locking to avoid corruption from concurrent Debug and Release processes--### Error Classification--| Error class | Typical handling | Incorrect handling |-| --- | --- | --- |-| Explicitly unsupported capability | Cache method unsupported and show the source as unavailable | Retry within the same connection or display `0` |-| Transient business failure | Use stale cache scoped to the same account | Clear the entire account snapshot |-| Transport failure | Discard the connection and rebuild it at most once | Continue sending requests over an untrusted pipe |-| Data-source identity change | Start a new generation and rebuild from the raw source | Continue appending from the old offset |-| Late asynchronous result | Discard when generations differ | Overwrite new settings or new reader state |-| Uncertain privileged state | Retain the possible lease or wake event and actively confirm cleanup | Assume the helper did nothing |-| Hook recorder failure | Drop this capture and exit successfully | Block Codex or present UI |--## System Integration--| Capability | System interface |-| --- | --- |-| Menu bar | `NSStatusItem` |-| Main panel | `NSPopover` and a floating fallback panel |-| Global shortcut | Carbon Hot Key API |-| App idle-sleep prevention | IOKit power assertion |-| System-sleep control | CodexBarHelper invokes `/usr/bin/pmset` with fixed arguments |-| Automatic Reset system wake | CodexBarHelper calls `IOPMSchedulePowerEvent` and `IOPMCancelScheduledPowerEvent` |-| CodexBarHelper installation and launch | `SMAppService` |-| App-to-CodexBarHelper communication | XPC |-| Notifications | `UNUserNotificationCenter` |-| Cloud sync | CloudKit private database |-| Automatic updates | Sparkle |--## Key Source Files--- [`CodexBarApp.swift`](../../../CodexBar/App/CodexBarApp.swift) defines the startup entry point-- [`CodexBarAppDelegate.swift`](../../../CodexBar/Controllers/CodexBarAppDelegate.swift) assembles services in normal mode-- [`StatusItemController.swift`](../../../CodexBar/Controllers/StatusItemController.swift) orchestrates the menu bar-- [`CodexStatusService.swift`](../../../CodexBar/Services/CodexStatus/CodexStatusService.swift) manages app-server-- [`WorkflowService.swift`](../../../CodexBar/Services/Workflow/WorkflowService.swift) manages historical Hook aggregation-- [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) manages live tasks-- [`AutoResetController.swift`](../../../CodexBar/Services/CodexStatus/AutoResetController.swift) manages Automatic Reset targets and retries-- [`AutoResetWakeScheduler.swift`](../../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift) synchronizes the next system wake time-- [`KeepAliveController.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveController.swift) manages helper registration, sleep-prevention policy, and wake-scheduler readiness-- [`WorkflowSyncService.swift`](../../../CodexBar/Services/Workflow/WorkflowSyncService.swift) manages CloudKit sync-- [`CodexBarHelperXPC.swift`](../../../Shared/CodexBarHelperXPC.swift) defines the constrained privileged interface-- [`CodexBarHelper/main.swift`](../../../CodexBarHelper/main.swift) executes and validates system sleep and wake operationsdiff --git a/Docs/en/DeveloperGuide/data-and-privacy.md b/Docs/en/DeveloperGuide/data-and-privacy.mddeleted file mode 100644index cc5272a..0000000--- a/Docs/en/DeveloperGuide/data-and-privacy.md+++ /dev/null@@ -1,315 +0,0 @@-# Data and Privacy Boundaries--[简体中文](../../DeveloperGuide/data-and-privacy.md) | English--## Data Classification Model--Classifying data during development helps determine its storage and propagation scope:--| Class | Examples | Default handling |-| --- | --- | --- |-| Content | Prompts, responses, tool arguments, and output | Do not collect |-| 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--```text-Codex hook stdin / rollout / app-server- |- v- User-privileged CodexBar- | |- v v-CloudKit private DB Constrained XPC interface- |- v- CodexBarHelper-```--These boundaries mean:--- Codex input files and protocol data are external input; decode failure must not expand into arbitrary file access or command execution-- CloudKit is a user-enabled remote boundary; even a private database may receive only the specified aggregate fields-- The root helper is a privilege-escalation boundary whose capabilities must be narrower than the app's business capabilities-- Debug and Release are separate app identities but intentionally share some local files, requiring process locks and compatible schemas--## Minimize at the Capture Boundary--CodexBar narrows data in this order:--1. The Hook recorder extracts only allowlisted structural fields from stdin-2. The rollout reader uses minimal Codable structures that omit content-3. The aggregator reduces older identity details to counts-4. The sync model projects again into CloudKit-allowed fields-5. Logging records only stages, classifications, and nonsensitive counts--## Data-Flow Overview--| Source | Use in CodexBar | Persisted? | Uploaded to CloudKit? |-| --- | --- | --- | --- |-| 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 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 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 |--## Local Reads--### Codex app-server--The app launches local `codex app-server --listen stdio://` to obtain account data, rate limits, token usage, Reset Credits details, and Codex configuration. After the user explicitly enables Automatic Reset, it also calls the Reset Credit redemption method through the same stdio session.--CodexBar 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. The log retains protocol fields such as account responses, opaque credit IDs, and idempotency keys.--### Hook Events--The Hook subprocess extracts from stdin:--- Time and event type-- Working directory-- Tool, model, and effort-- Permission and reviewer-- Session, turn, and agent identities--The Hook subprocess extracts origin from the first rollout `session_meta`, using either the complete record or a prefix of completed fields. Reads use 32 KiB chunks with a total limit of 256 KiB. JSONL persists only the normalized `main`, `autoReview`, `auxiliary`, or `unknown` value. See [Origin Normalization](hook-and-aggregation.md#origin-normalization) for classification and model fallback rules.--It does not write prompt text, responses, tool arguments, or tool output to the Hook event files maintained by CodexBar.--The working directory is used only to derive a project display name and live-task ownership. Raw Hook JSONL may still include `cwd`, making it sensitive local context subject to retention and file-permission limits. Rollout paths, raw source values, and arbitrary subagent `other` values are not persisted. CloudKit uploads only derived project-name counts and only after explicit opt-in.--### Rollout Files--The 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 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.--The live rollout reader initially reads up to the last 512 KiB, then consumes appended content incrementally and backfills earlier history as needed. Parsing DTOs declare only required fields, and `JSONDecoder` ignores everything else. See [Rollout Read Budget](activity-monitor.md#rollout-read-budget) for stopping conditions and budgets.--### Reset Credits Details--`account/rateLimits/read` returns the Reset Credits count and optional details in the app-server response.--- `availableCount` is authoritative for the available total-- `credits == nil` means the server provides a count only-- An empty details array means the server read details but returned no available credit-- The details list may be truncated and its length must not overwrite the total count-- The menu and expiration notifications use only `available` credits with a future `expiresAt`-- Automatic Reset processes only `available + codexRateLimits + expiresAt` details explicitly listed in a fresh response-- Opaque credit IDs and deterministic idempotency keys exist only in current-process memory, including app-server responses and cache, quota snapshots, the Automatic Reset state machine, and the in-memory request log; they are neither persisted nor uploaded-- Automatic Reset notification deduplication keys in UserDefaults contain only a SHA-256 combination of the account and credit ID, never raw values--A rate-limit response from stale cache may remain visible but cannot trigger a new expiration notification or redemption. Automatic Reset settings and scheduling state do not enter CloudKit; Macs converge only through deterministic idempotency keys at the server redemption interface.--## Local Persistence--### App User Directory--```text-~/Library/Application Support/CodexBar/- HookEvents/- events/YYYY-MM-DD.jsonl- daily.jsonl- maintenance.json- stats.lock- Tokens/- ledger.json- store.lock- rebuild.lock- Sync/- state.json- cache.jsonl- cursor.data- Tokens/- cache.json- store.lock- sync.lock- ActivityProtection/- state.json-```--| Path | Contents | Lifetime |-| --- | --- | --- |-| `HookEvents/events` | Raw structured Hook events | 210 days |-| `HookEvents/daily.jsonl` | Daily aggregations | 210 days |-| `HookEvents/maintenance.json` | File cursors, generation, and maintenance state | Continuously updated |-| `HookEvents/Tokens/ledger.json` | Hashed turn identities, cumulative usage, rebuild and recovery boundaries, file cursors | Usage retained for 210 days from its latest record; roots referenced by retained child turns are also kept |-| `HookEvents/Sync` | Cloud cache, cursor, and replacement state for Hook daily aggregates | While sync state remains valid |-| `HookEvents/Sync/Tokens/cache.json` | Account-scoped turns, salt, and CloudKit cursor | Sync prunes expired turns while retaining referenced roots |-| `ActivityProtection/state.json` | Hashed task identities and timestamps | Up to 24 hours after the last progress |--Daily aggregations for the latest 3 days may retain session and turn ID details for exact deduplication. Older data retains counts only.--Anonymous tasks do not create Stalled Task Protection identifiers and therefore never write to `ActivityProtection/state.json`.--Debug and Release share the token ledger and sync cache. Each `store.lock` protects reads and writes in its directory; `rebuild.lock` excludes concurrent token rebuilds, and `sync.lock` excludes concurrent token sync passes. `stats.lock` protects Hook aggregation transactions. Lock files do not contain statistics or progress.--### UserDefaults--UserDefaults stores:--- Feature switches and options-- Data update interval (`DataUpdate.intervalSeconds`, in seconds)-- Notification thresholds and sound names-- Global shortcut-- Proxy enabled state, protocol, server, port, authentication username, and password-- Menu bar display selection-- Automatic Reset switch and lead time-- Bounded notification deduplication keys-- Runtime configuration such as the CodexBarHelper fingerprint--Changes to persistence keys, data structures, enum raw values, or defaults for missing values require an agreed migration and downgrade strategy before implementation.--The `CodexProxy.configuration` key stores one JSON data value containing `configuration` and `password`. Passwords are stored in plain text in local UserDefaults and removed when settings are saved with authentication disabled or the configuration is cleared. Debug and Release use separate preference domains:--- Debug: `~/Library/Preferences/app.zabrian.codexbar.debug.plist`-- Release: `~/Library/Preferences/app.zabrian.codexbar.plist`--`CodexProxyStore` distinguishes a missing record from a decoding failure. A failed record remains available for the configuration dialog’s clear action.--### CodexBarHelper Directory--```text-/Library/Application Support/CodexBar/helper-state.json-```--The file stores only the recovery transaction describing whether CodexBarHelper owns `SleepDisabled`. It contains no Codex task, account, or Hook data.--System power management stores the Automatic Reset wake schedule, which contains only a fixed CodexBar owner, `wake` type, and next time. The helper neither receives nor stores account data, `creditId`, idempotency keys, or network data.--The directory and file are root-managed. See [Sleep Prevention System](sleep-prevention.md) for permissions and recovery.--## In-Memory and System Logs--The in-app [`RequestLog.swift`](../../../CodexBar/Services/CodexStatus/RequestLog.swift) is an in-memory ring buffer of at most 500 entries and disappears when the process exits.--It diagnoses the app-server protocol. Even in memory, it must not contain OAuth tokens or Hook content.--The unified logging subsystem is `app.zabrian.codexbar`, with a `.debug` suffix in Debug builds.--System logs may contain only:--- Operation stage and result-- State classification-- Nonsensitive counts-- Errors that identify a module--Automatic rollout replay logs file counts, bytes read, remaining bytes, waiting or unreadable files, and elapsed time in the `workflow` category, without paths, identities, or usage counts. See [Rollout Token History](sync.md#rollout-token-history) for progress semantics.--System logs must not contain:--- OAuth tokens-- Prompts, responses, or tool content-- Raw session, turn, or agent IDs-- 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 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, 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 |--Account data, rate limits, token usage, Reset Credits details, and explicitly enabled Reset Credit redemption use local app-server stdio. CodexBar does not add a separate HTTP client for Automatic Reset.--CodexBarHelper performs no network access.--When a proxy is enabled, its address and optional credentials are passed through environment variables to app-server processes started by CodexBar. This does not configure system networking, Sparkle, CloudKit, or other Codex processes. Connection tests use a temporary app-server, close it afterward, and do not write app interaction logs.--## CloudKit Boundary--CloudKit uploads these daily Hook aggregate fields:--- Hashed device identifier `deviceId`-- Date and source generation-- Hook event counts-- Session and turn counts-- Project display-name counts-- Model counts-- Update time--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:--- Raw Hook JSONL-- Raw session, turn, or agent IDs-- Full working directories-- Prompts, responses, tool arguments, or output-- Codex account, rate-limit, or account token usage data from app-server-- Reset Credits details, Automatic Reset settings, or redemption state-- Access tokens-- App request logs-- Activity Protection state-- Proxy settings and passwords--A project display name may derive from a directory name and still contain sensitive information. Sync must remain an explicit user choice.--## Root Helper Data Isolation--CodexBarHelper receives only the following state:--- Which verified client holds which lease generation-- The currently measured `SleepDisabled` value-- Whether CodexBar owns restoration responsibility-- A bounded Unix timestamp for the Automatic Reset wake schedule and the current connection owner--It does not need task IDs, project names, Hook paths, account state, `creditId`, or complete user settings. XPC carries only Boolean requests, client session ID, generation, update identifier, and a bounded Unix timestamp.--The helper target contains restricted power operations and the shared XPC protocol; it does not link the app’s business services.--The helper ownership file is a crash-recovery transaction record, not a user preference. It must be root-owned, reject group- or world-writable directories, and use full sync plus atomic rename so a restart can decide whether restoration is required.--## File Security--- Hook subprocesses and the app aggregator coordinate writes with `flock`-- JSONL appends complete lines only-- Aggregation and state files use recoverable write workflows-- Activity Protection files have `0600` permissions-- CodexBarHelper state commits with root ownership, permission checks, full sync, and atomic rename-- Data shared by Debug and Release uses locking and compatible schemas--## Checklist Before Adding a Data Field--1. State the product goal and the behavior that is impossible without the field-2. Classify it as credential, content, identity context, or aggregate metric-3. Define its capture boundary and the earliest layer that can discard the raw value-4. Define whether and where it exists in memory, UserDefaults, Application Support, system logs, and CloudKit-5. Define retention, deletion triggers, and cleanup after failure-6. Check whether Debug and Release share its file or identity-7. Distinguish missing from explicitly empty values-8. Check whether logs or error objects copy the raw value indirectly-9. If it affects CloudKit, network access, or logs, update the privacy explanation and obtain an explicit product decision first-10. If it affects a schema or old-version coexistence, agree on compatibility before changing code--## Suggested Privacy-Failure Tests--- Run a task with a conspicuous marker in the prompt and tool arguments; confirm the marker is absent from Hook JSONL, app logs, and CloudKit cache-- Put a sensitive test term in a project directory name; confirm it appears only in allowed local presentation and opt-in aggregate fields-- Simulate a failed Reset Credits request and confirm that access tokens do not enter the in-memory or unified logs-- Confirm CloudKit records contain no raw session, turn, or agent IDs or full paths-- As a non-root user, verify that the helper-state directory is not writable-- Corrupt each cache type and confirm the system degrades or rebuilds rather than broadening fallback data collection--## Key Source Files--- [`CodexTokenHistoryStore.swift`](../../../CodexBar/Services/Workflow/CodexTokenHistoryStore.swift)-- [`CodexTokenHistorySync.swift`](../../../CodexBar/Services/Workflow/CodexTokenHistorySync.swift)-- [`WorkflowHookEventRecorder.swift`](../../../CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift)-- [`WorkflowService.swift`](../../../CodexBar/Services/Workflow/WorkflowService.swift)-- [`CodexSessionLifecycleReader.swift`](../../../CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift)-- [`WorkflowSyncService.swift`](../../../CodexBar/Services/Workflow/WorkflowSyncService.swift)-- [`ActivityProtectionStateStore.swift`](../../../CodexBar/Services/Workflow/ActivityProtectionStateStore.swift)-- [`RequestLog.swift`](../../../CodexBar/Services/CodexStatus/RequestLog.swift)-- [`CodexBarHelper/main.swift`](../../../CodexBarHelper/main.swift)diff --git a/Docs/en/DeveloperGuide/design-decisions.md b/Docs/en/DeveloperGuide/design-decisions.mddeleted file mode 100644index c6b3de5..0000000--- a/Docs/en/DeveloperGuide/design-decisions.md+++ /dev/null@@ -1,61 +0,0 @@-# Design Principles and Key Decisions--[简体中文](../../DeveloperGuide/design-decisions.md) | English--## State Ownership--Each data flow has one service owning its facts; consumers read snapshots or transitions:--| Flow | Source of state | Output use |-| --- | --- | --- |-| app-server | Account, quota, and usage responses | Periodic display with same-account stale-cache fallback |-| Historical statistics | Independently maintained Hook events and rollout usage | Rebuildable daily activity metrics, thread-turn token ledger, and cross-device sync |-| Live tasks | Incremental Hook events, rollout lifecycle, and turn usage | Activity snapshots with current-turn tokens, task alerts, and sleep prevention |--Snapshots can be read repeatedly. Notifications use live transitions; bootstrap establishes a baseline without replaying historical alerts. Historical aggregation shares some refresh triggers with quota, but reads and failure handling remain independent. See [Architecture](architecture.md) for component relationships.--## User Intent and Actual Effects--A saved switch expresses intent, dependencies determine whether execution is possible, and result state expresses a confirmed effect. Temporary dependency failures preserve the user’s switch and reconcile again on recovery.--Sleep prevention represents these layers with `isEnabled`, `sleepBlockReason`, and `isPreventingSleep`. `AdvancedModeSettings` combines `isEnabled` and `isVerified` into `isOperable`; live tasks require operability, while historical aggregation can still process recorded data.--## Missing, Stale, and Untrusted Data--| State | Current handling |-| --- | --- |-| Temporary app-server supplemental failure | Use same-account stale cache with reduced UI opacity; do not trigger quota alerts or automatic redemption |-| Unsupported method | Cache missing capability for the session and probe again after rebuilding the connection |-| Missing historical Hook count | Persisted and sync models retain `nil`; display projection applies each metric’s fallback rule |-| Live reader cannot obtain a stable boundary | Publish degraded health and pause Activity Protection |--The source layer supplies these states; consumers determine whether to display data or perform effects. See [Hook Aggregation](hook-and-aggregation.md) for count projection and [app-server](app-server.md) for account caches.--## Concurrency and Stale Results--| Mechanism | Protected scope |-| --- | --- |-| `MainActor` | UI, controllers, and observable-state commit ordering |-| Actors | Shared service state and I/O coordination within a process |-| `NSLock` and similar locks | Mutable state behind synchronous interfaces such as nonisolated pipe readers |-| `flock` | Shared-file transactions across Hook subprocesses, the main app, Debug, and Release |--Configuration or readers may change while an asynchronous call runs. Noncancelable system callbacks validate their generation before committing. Cancellation controls task lifetime; generation checks establish result ownership.--Menu fade completion commits synchronously after checking cancellation, so it keeps one cancelable task. XPC, reader replacement, and wake recovery still require generations; their fields are documented in the corresponding topics.--Combine’s `@Published` emits during `willSet`. Combined-setting decisions use the new value delivered to the subscription instead of rereading a property that has not changed yet.--## Rebuildable Data and Recovery Records--Raw Hook JSONL is the source for rebuilding history; daily aggregates are derived output. Aggregation-semantic changes increment the schema and rebuild retained history. `sourceGeneration` distinguishes file replacements: same-day, same-source data replaces a contribution, while independent sources add together.--Token history uses stable thread-and-turn identities, deduplicates cumulative snapshots, and aggregates by the root turn’s start date. Explicit rebuilds finish the local scan before committing reread turns for selected dates. `rebuiltAt` gives corrected lower counts precedence over stale copies. Turns with missing source files retain known statistics, while remote-only turns remain in the sync cache. See [Rollout Token History](sync.md#rollout-token-history) for fields and merge rules.--Activity Protection and helper ownership records recover state changes that have already occurred. Protection saves asynchronously and does not wait for disk before hiding a task. The helper persists recovery responsibility before changing system sleep state. See [Live Task Monitoring](activity-monitor.md) and [Sleep Prevention](sleep-prevention.md) for ordering.--## Privileged Operations and Upload Scope--Task identification, Automatic Reset policy, and networking run in the main app. The root helper accepts only fixed sleep-lease and wake operations, validates client signatures, and reads back system results.--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/development.md b/Docs/en/DeveloperGuide/development.mddeleted file mode 100644index 812306a..0000000--- a/Docs/en/DeveloperGuide/development.md+++ /dev/null@@ -1,147 +0,0 @@-# Development and Validation--[简体中文](../../DeveloperGuide/development.md) | English--## Environment and Build--Requires macOS 15+, Xcode, Swift 6, `swiftformat`, and `swiftlint`. The only scheme is `CodexBar`, containing the app, `CodexBarHelper`, and `CodexBarTests` targets.--```bash-xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build-xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'platform=macOS' test-swiftformat .-swiftlint-```--`.swiftformat` configures Swift 6 and 4-space indentation. `swiftlint` checks `CodexBar/` and `CodexBarTests/`, excluding `Shared/`, `CodexBarHelper/`, and `Scripts/`.--Check `git status --short` before editing. With existing uncommitted work, format only Swift files touched by the change, or check with `swiftformat --lint . --cache ignore`. `swiftlint --no-cache` avoids cache writes.--Daily builds do not need Developer ID or notarization credentials. See [AGENTS.md](../../../AGENTS.md) for writing, Git, and compatibility rules.--## Unit Tests--`CodexBarTests` uses Swift Testing and belongs to the shared `CodexBar` scheme. Run it with Xcode’s Test action or the command above.--The test target has no app host. It compiles the production sources in `CodexBar/` and `Shared/` with the same Swift 6, `MainActor`, and concurrency settings. The test-only `CODEXBAR_TESTING` condition removes `@main`; tests do not instantiate the app or start Codex, CloudKit sync, or the helper. This avoids extracting production modules solely for testing, at the cost of compiling the app sources again for tests.--| Test area | Key constraints |-| --- | --- |-| Hook and JSONL | Name normalization, corrupt-line isolation, metadata read budget, partial lines, bootstrap/live separation, file replacement |-| Live tasks | Anonymous identity, duration, out-of-order progress, subagent counts, approvals scoped to each execution |-| Rollout lifecycle | Completion and progress, read coverage, corrupt lines, missing/replaced files, archived sessions |-| Current-turn tokens | Counter validation, main/child ownership and deduplication, live updates, terminal rereads, turn isolation, overflow and zero values |-| Token history | Cross-midnight attribution, persisted cursors, replay logs, rebuilds lowering or clearing counts, missing-file preservation, cloud-baseline recovery, cancellation and cross-instance locks |-| Aggregation and sync models | Identifier deduplication, paired events, missing counts, incremental/replay equivalence, same-device generation deduplication |-| Persistence and settings | Protection expiry, merging across store instances, conditional removal, legacy defaults, corrupt configuration and draft restoration |-| Quota, proxy, and presentation | Credit filtering, stable UUIDs, actual running versions, proxy validation and environment, dates and heatmap states |-| Asynchronous refresh | Cancellation and stale generations cannot commit results or finish newer refreshes |--Each file test creates and removes its own temporary directory. Each preferences test uses and cleans up a unique `UserDefaults` suite. Tests use fixed dates, explicit calendars, and controlled asynchronous checkpoints; follow these isolation patterns when adding tests.--Unit tests do not cover live CloudKit, app-server, system notifications, window focus, or helper power behavior. Validate those flows with the manual scenarios below.--## Implementation Entry Points--| Feature | Main location | Implementation guide |-| --- | --- | --- |-| app-server, proxy, Automatic Reset | `Services/CodexStatus` and corresponding Settings | [app-server Data Flow](app-server.md) |-| Hook installation and statistics | `AdvancedModeSettings`, `WorkflowService`, aggregate models | [Hook Collection and Aggregation](hook-and-aggregation.md) |-| Live tasks and protection | `CodexActivityMonitor` and readers | [Live Task Monitoring](activity-monitor.md) |-| Sleep prevention and system wakes | `KeepAliveController`, `AutoResetWakeScheduler`, helper | [Sleep Prevention](sleep-prevention.md) |-| Notifications and sound | `CodexNotificationService`, notification Settings | [Notifications](notifications.md) |-| Token history and sync | `CodexTokenHistoryStore`, `CodexTokenHistorySync`, and `CodexTokenTurn` | [Rollout Token History](sync.md#rollout-token-history) |-| Hook sync | `WorkflowSyncService` and scheduler | [CloudKit Sync](sync.md) |-| Menus, windows, hot keys | `Controllers` and corresponding views | [UI and Lifecycle](ui-and-lifecycle.md) |--`CodexBarAppDelegate` assembles long-lived objects. Add state to its existing owner where possible; views consume snapshots and emit action intents. See [Architecture](architecture.md) for source entry points.--## Change Review--Changes to persisted keys, schemas, identity computation, minimum OS versions, or version coexistence require explaining the impact and compatibility options, then waiting for the user’s choice. Review [Data and Privacy Boundaries](data-and-privacy.md) before adding networking, log fields, or CloudKit fields.--Changes to aggregation algorithms, output semantics, or deduplication increment `WorkflowMaintenanceState.currentAggregationSchema` and rebuild from retained raw JSONL instead of adding field-level historical migrations.--For asynchronous changes, check cancellation, commit eligibility, and generation. Cross-process files still need `flock`; actors protect only one process. `@Published` subscriptions use the closure’s new value rather than rereading old state during `willSet`.--## Validation Workflow--1. Review the change scope and preserve existing work-2. Format and run `swiftlint`-3. Build the app and helper, and run unit tests-4. Manually verify affected normal, failure, and recovery flows-5. Review documentation and run `git diff --check`--For build failures, find the first actual `error:`. Check Debug/Release identity for signing or entitlement errors, and both targets plus `Shared` for helper protocol changes. Compilation and static checks do not cover window focus, system authorization, or hardware power behavior.--Documentation-only changes run format checks, lint, and build, plus relative-link and bilingual-content checks.--### Manual Scenarios--| Change area | Key scenarios |-| --- | --- |-| Menus and windows | Rapid toggles, reopen during fade-out, popover/fallback, displays and Spaces, settings/log focus, notification clicks and hot keys |-| Hook and aggregation | Preserve handlers, minimum version, concurrent append, partial/corrupt lines, replacement/truncation, full rebuild |-| Live tasks | Bootstrap without replayed alerts, approval waits, late terminals, anonymous tasks, wake read-barrier failure and recovery |-| Notifications | Authorization denial/recovery, threshold crossing, cycle deduplication, withdrawal after progress, missing sounds |-| Proxy | First configuration, enable/disable, disable invalid data, delete corrupt records, cancel tests, rapid actions and failure rollback |-| Sync | First upload, multiple devices, offline recovery, partial upload failure, rebuild replacement, iCloud account changes |-| Token replay and rebuild | Large-history resume, main-panel use during rebuild, closing Settings, automatic replay versus manual rebuild after restart, cross-device convergence of corrected counts |-| Power and helper | First approval, running/waiting transitions, low battery, duration limit, external sleep sources, abnormal exit and restart |-| Automatic Reset wakes | Replace schedules, disable/exit cleanup, connection loss, helper restart, clear before unregistering, fresh reads when due |--Helper changes also require checking executable and plist placement inside the app, signatures, and registration fingerprints. Each feature guide lists more detailed state-transition scenarios.--Record the build, initial settings, action sequence, actual results, and relevant logs so validation can be reproduced.--### Performance Validation--View CPU, memory, wakeups, disk activity, and the recording environment in the [Performance Report](https://codexbar.zabrian.app/performance). Results apply to the build and workload recorded in the report.--For collection, report generation, and baseline comparisons, see the [performance tool guide (Chinese)](../../../Scripts/performance/README.md).--## Debug and Release--| Configuration | App bundle ID | Helper bundle ID |-| --- | --- | --- |-| Debug | `app.zabrian.codexbar.debug` | `app.zabrian.codexbar.helper.debug` |-| Release | `app.zabrian.codexbar` | `app.zabrian.codexbar.helper` |--Preferences and system approval are isolated by identity; Hook data and Activity Protection files are shared. Identify the running app, helper, and installed Hook executable path when debugging.--## Logs--Release system logs:--```bash-/usr/bin/log stream --predicate 'subsystem == "app.zabrian.codexbar"' --style compact-```--Debug uses `app.zabrian.codexbar.debug`; the helper subsystem uses its corresponding bundle ID.--The app’s Logs window retains the latest 500 app-server interactions. Proxy configuration errors use the system-log `settings` category; temporary proxy tests do not write interaction logs.--| Problem | Inspect |-| --- | --- |-| Quota did not refresh | Handshake, method, retry, stale |-| Hook not working | Configuration, version, trust, completeness |-| Task did not finish | Reader generation, rollout reconciliation, source health |-| Missing sync data | Zone, fetch, upload, replacement, prune stages |-| Missing notification | Authorization, kind, duplicate, obsolete |-| Sleep prevention inactive | Block reason, helper registration, XPC generation, source |-| Automatic Reset did not run | Target, threshold, retry window, wake schedule |--Logs use `LogTrigger`, `LogDuration`, and `LogFields.joined` for stages, classifications, counts, and elapsed time. See [Data and Privacy Boundaries](data-and-privacy.md) for request-content and identity restrictions.--## Release and Cleanup Scripts--| Script | Purpose |-| --- | --- |-| `Scripts/build.sh` | Release archive, Developer ID export, notarization, stapling, and Gatekeeper checks |-| `Scripts/dmg.sh` | Package a DMG |-| `Scripts/appcast.sh` | Sign updates and generate the appcast |-| `Scripts/cleanup.swift` | Unregister helpers after all CodexBar instances exit; `--check` checks only, and `--debug` or `--release` limits scope |--Release scripts require signing and notarization credentials and are not daily validation tools. The version comes from [`Version.xcconfig`](../../../Config/Version.xcconfig).--Helper cleanup cancels and verifies an empty system wake schedule before unregistering; failure stops cleanup. See [Sleep Prevention](sleep-prevention.md).diff --git a/Docs/en/DeveloperGuide/hook-and-aggregation.md b/Docs/en/DeveloperGuide/hook-and-aggregation.mddeleted file mode 100644index 758673e..0000000--- a/Docs/en/DeveloperGuide/hook-and-aggregation.md+++ /dev/null@@ -1,477 +0,0 @@-# Hook Capture and Historical Aggregation--[简体中文](../../DeveloperGuide/hook-and-aggregation.md) | English--## Flow Responsibilities--The Hook flow turns Codex lifecycle events into rebuildable local history:--```text-Codex Hook- -> CodexBar --hook-event- -> Raw JSONL- -> Incremental WorkflowService aggregation- -> daily.jsonl- -> Activity UI and CloudKit sync-```--Raw events are the fact source; daily aggregation is a rebuildable cache. A change to the aggregation algorithm or field semantics requires a full rebuild from raw events within retention.--## Installation and Validation--[`AdvancedModeSettings.swift`](../../../CodexBar/Services/Settings/AdvancedModeSettings.swift) reads and writes local `hooks.json` directly, reads or updates related configuration through app-server, and calls `hooks/list` after writing to validate installation.--The enable flow checks the following conditions, validating source, trust, and event completeness after writing:--- A resolvable current executable path-- Actual app-server version `0.153.0` or later-- Available `features.hooks`-- A trusted source returned by `hooks/list`-- A complete required event set--The target file is `$CODEX_HOME/hooks.json`, or `~/.codex/hooks.json` when `CODEX_HOME` is unset.--Installation adds the CodexBar handler as a separate command within the existing configuration. It never overwrites the entire file from a template:--- Preserve existing user fields-- Preserve handlers from other applications-- Update only handlers matching the current executable and `--hook-event`-- On disable, remove only an exact CodexBar handler match-- Preserve unrecognized configuration unchanged--`isEnabled` tracks enabled state for the current process, initially restored from an existing CodexBar handler. `isVerified` defaults to `true`, then retains the latest explicit validation result. Live tasks and related features use their conjunction, `isOperable`; historical aggregation and sync use `isEnabled` to consume stored data.--### Validation State--A handler in `hooks.json` does not prove Codex will execute it. `isOperable` combines the enabled state with the last explicit validation result. Temporary RPC failures preserve the previous result and expose the operation error; unsupported versions, disabled global hooks, incorrect sources, trust failures, or incomplete events fail validation.--### Reconciliation of an Enabled Hook--An enabled Hook is reconciled at app launch, when Settings refreshes, when the main panel opens, and after each quota refresh. Automatic refresh waits for the selected data update interval after the previous round completes, defaulting to 1 minute:--- Only a confirmed running app-server version below the current Hook minimum triggers removal of CodexBar handlers and best-effort cleanup of matching trust entries; versions below the global minimum also trigger local removal-- An unknown version or transient RPC failure preserves the user's configuration-- Configuration lost during the current process does not turn off the switch; CodexBar marks it damaged and starts repair-- A supported version traverses `CodexHookEvent.allCases`, rebuilds a separate group for every missing or noncanonical event, then reuses trust and completeness validation-- Missing trust entries or changed hashes are repaired only for entries whose command, `sourcePath`, and event belong to the current CodexBar-- A complete required event set leaves `hooks.json` unchanged--Reconciliation compares the required event set with the configuration and restores missing handlers. If no recognizable CodexBar handler exists at startup, Hook remains off.--### Enable Transaction Order--```text-Confirm running app-server >= 0.153.0- -> Confirm features.hooks is not globally disabled- -> Read existing hooks.json- -> Remove only old CodexBar handlers for this executable- -> Append a separate group for every event- -> Atomically write hooks.json- -> Use hooks/list to read app-server's parsed result- -> Trust only entries matching command + sourcePath + event- -> Run hooks/list again for full validation-```--Trust matching requires both command and `sourcePath`. Command-only matching might trust the same command from another configuration; source-only matching might select the user's own handler.--### Disable and Trust Cleanup--An app-server Hook key comes from the handler it currently parsed. Removing the command from `hooks.json` first would make a later `hooks/list` unable to recover the corresponding key.--Disable therefore saves keys for exact matches, removes handlers, then removes those keys from `hooks.state`. Cleanup reads and replaces the complete state so trust entries belonging to users and other tools survive.--Below the global minimum, the app-server connection has already been rejected, so disabling directly removes local handlers and preserves trust entries that cannot be queried or deleted, without an additional trust-cleanup warning. In other cases, trust discovery or cleanup failures report that trust cannot be cleared, while Hook remains disabled. Failure to remove local configuration still displays an error and is retried during subsequent reconciliation.--### Event Groups--CodexBar does not insert commands into an existing user group. Separate groups make uninstall remove only its own handler without interpreting the composition of user matchers and other handlers.--Removal skips malformed sibling entries and processes only precisely identified CodexBar commands.--### Generations for Asynchronous Settings Operations--When the user toggles Advanced Mode or validation is triggered, `AdvancedModeSettings` starts the operation through `updateCoordinator`. Its `RefreshTaskCoordinator` advances the generation and cancels the previous task.--After every file write or RPC `await`, it checks the generation again. Even if an old operation cannot truly be canceled, it cannot overwrite the latest switch state or error.--## Supported Events--CodexBar subscribes to:--| Event | Aggregation or live use |-| --- | --- |-| `SessionStart` | Establish session lifecycle |-| `SessionEnd` | End session |-| `UserPromptSubmit` | Establish turn and task start |-| `PreToolUse` | Record tool-call start |-| `PostToolUse` | Record tool-call end |-| `PermissionRequest` | Detect user approval waiting |-| `PreCompact` | Record context-compaction start |-| `PostCompact` | Record context-compaction end |-| `Stop` | Create a task-completion candidate |-| `Interrupt` | Ends the matching turn and records interruption statistics |-| `SubagentStart` | Record subagent start |-| `SubagentStop` | Record subagent end |--### Event Fields Serve Different Uses--Historical counts need event name, date, project, model, and identity sets. Live state additionally needs turn, reviewer, effort, tool, agent relationships, and normalized origin.--The recorder writes the fields needed by both data flows into one raw record. Historical aggregation and live monitoring each read the fields they use.--The recorder performs a bounded read of the rollout's first line to classify origin. Ordinary events use `transcript_path`; `SubagentStop` uses `agent_transcript_path`, which points to the child thread itself. If the rollout origin cannot be determined, only an exact `codex-auto-review` model match serves as the Auto-review fallback. Reviewer or effort for `PermissionRequest` and `UserPromptSubmit` may be absent from the Hook payload, so only those two events also read the rollout tail for that turn.--## Hook Subprocess--[`WorkflowHookEventRecorder.swift`](../../../CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift) checks for `--hook-event` at the earliest startup point.--When matched, it only:--1. Reads event JSON from stdin-2. Extracts the minimal fields needed for metrics and state machines-3. Acquires the file lock-4. Appends one complete JSONL line-5. Marks maintenance state in the same lock transaction-6. Exits immediately--Timeout depends on event:--| Event | Timeout |-| --- | --- |-| `SessionEnd`, `Interrupt` | 3 seconds |-| Other events | 5 seconds |--The lock-wait budget is the handler timeout minus 2 seconds. Lock acquisition starts with 1 ms exponential backoff capped at 20 ms per wait.--### Failure Exit--In `--hook-event` mode, invalid input, lock timeouts, and write errors all exit successfully so capture failures do not block Codex.--### Locked Event and Maintenance Transaction--One capture performs under the same `stats.lock`:--```text-Check current file identity- -> Start a new source generation if required- -> Append one complete JSONL line- -> Mark the date pending- -> Atomically save maintenance.json-```--If append and pending were separate lock transactions, the app could finish maintenance between them and consider the date caught up. The recorder might then append the event but fail before marking pending, leaving the new line invisible until a later full-directory reconciliation.--The joint commit keeps “the file grew” consistent with “maintenance knows it must read.”--### Lock File Creation--Code must not check for absence, create, then reopen. Two processes could create different inodes; after one replaces the directory entry, both would lock separate files and each believe it has exclusivity.--One `open` makes creation and opening an atomic entry point so all participants use `flock` on the same inode at that path.--## Captured Fields--Raw records retain only information required for statistics and live state:--- Timestamp and event name-- Working directory-- Tool name-- Model and reasoning effort-- Permission and approval reviewer-- Session and turn IDs-- Agent ID-- Normalized `origin`--For `UserPromptSubmit` and `PermissionRequest`, input may omit reviewer or effort. When needed, the recorder looks for a matching `turn_context` near the end of the rollout transcript.--The lookup:--- Reads at most 8 MiB once-- Extracts only structural fields such as reviewer and effort-- Never writes prompt or response content to Hook statistics--### Origin Normalization--`WorkflowHookEvent.origin` is a finite CodexBar-owned enum, not a copy of the rollout's raw `source`. Both the initializer and decoder apply the same origin-resolution rule at the event input boundary, so downstream consumers read only the normalized `origin`:--| Effective origin | Classification |-| --- | --- |-| `main` | `source` is a known top-level string source `cli`, `vscode`, `exec`, or `mcp`, or a valid object source `{ "custom": "..." }` |-| `autoReview` | `source.subagent.other` exactly equals `guardian`, or the rollout origin is `unknown` and the model exactly equals `codex-auto-review` |-| `auxiliary` | `source` explicitly represents another subagent, including `review`, `thread_spawn`, and Memories-related sources |-| `unknown` | The field is missing, malformed, unreadable, or an unknown top-level source, and the model does not satisfy the Auto-review fallback |--Origin reading starts at byte zero in 32 KiB chunks with a total budget of 256 KiB. At the first newline, the parser decodes the complete first line. Before that line is complete, it constructs a decodable metadata prefix at a complete field boundary. It can return once the type is confirmed as `session_meta` and `source` has been fully decoded, without reading large instruction fields to completion. Missing origin within the budget, a different record type, or a read or decoding failure yields `unknown`. The model fallback accepts only the exact string.--The recorder resolves origin before writing, and the JSONL origin field stores only this enum. It never stores `transcript_path`, raw `source`, arbitrary `other` strings, or transcript content, and none of those values enter system logs.--When JSONL omits `origin` or contains an unrecognized enum value, the origin field first decodes as `unknown`. The `WorkflowHookEvent` decoder then applies the same exact model fallback, so an event with `model == "codex-auto-review"` has `origin` equal to `autoReview` in memory. Reading never backfills or rewrites raw JSONL.--Historical aggregation counts all Hook events, including `autoReview` and `unknown` origins. Aggregates and CloudKit projections do not contain an origin field.--### Input Normalization--Hook payload versions may represent identifiers and time as different JSON types. `WorkflowHookPayload` centralizes permissive normalization:--- Trim strings and turn empty strings into missing values-- Convert numeric identifiers to strings-- Accept ISO-8601, local timestamps, Unix seconds, and Unix milliseconds-- Fall back to recorder current time when time is missing-- Fall back to the subprocess current directory when cwd is missing--Permissiveness exists only at the external-input boundary. After conversion to `WorkflowHookEvent`, downstream aggregation and monitoring use uniform types instead of guessing protocol differences again.--### Rollout Tail-Lookup Boundary--The lookup reads only the last 8 MiB of the transcript, discards a potentially truncated first line, then searches backward for the matching turn's `turn_context`.--Backward search finds the latest context for a turn nearest the file tail. The read limit protects Hook timeout; a miss leaves the field absent instead of expanding into an unbounded scan.--## Local Files--The default data root is:--```text-~/Library/Application Support/CodexBar/HookEvents/-```--Directory structure:--```text-HookEvents/- events/- YYYY-MM-DD.jsonl- daily.jsonl- maintenance.json- stats.lock- Sync/- state.json- cache.jsonl- cursor.data-```--| File | Purpose |-| --- | --- |-| `events/YYYY-MM-DD.jsonl` | Store raw Hook events by day |-| `daily.jsonl` | Store aggregations by date and source generation |-| `maintenance.json` | Store pending maintenance and schema state |-| `stats.lock` | Coordinate Hook subprocesses and app maintenance |-| `Sync/*` | CloudKit sync cursor and cache |--Raw events and daily aggregations are retained for up to 210 days. Detailed session and turn ID lists remain only for 3 days; older dates compact them to counts to reduce file size and identity retention.--### A Complete Line Is the Commit Unit--The reader advances only to the offset of the final newline. If a partial line is being written at the tail, the current cycle keeps its old offset and processes the line after a future cycle sees it complete.--`JSONLines.decodeWithFailures` decodes per line. One malformed line increments the corrupt count without discarding valid events from the same read block.--### Identity Compaction--Session and turn IDs support recent exact deduplication, while long-term presentation needs counts only.--After 3 days, identifiers are compacted into counts. The accumulator chooses ID lists or counts in `finalized(identifierStorage:)`; `retained` and `compacted` select the output form and are not separately persisted mode fields.--## Incremental Reading and Source Generations--For each raw file, the aggregator records inode, size, offset, and source generation:--- Normal appends resume at the previous offset-- An inode change means file replacement-- Size below offset means truncation-- Replacement or truncation creates a new source generation--Source generation distinguishes raw sources for the same day. Same-source results replace one another; clearly independent generations may add together. A user-requested full rebuild tells sync that all old generations are invalid through a replacement marker.--### `pending` Versus `dirty`--`maintenance.json` tracks the following work states for a date:--| State | Used when | Next step |-| --- | --- | --- |-| `pending` | Confirmed normal append to the same source | Aggregate incrementally from the old offset |-| `dirty` | Source change, schema change, missing cache, or previous failure | Fully rebuild from the file start |--`dirty` takes priority. If a date appears in both sets, only a rebuild task is created, avoiding an append to the old aggregate followed by complete replacement.--Explicit states are safer than guessing from `offset == 0`. A new empty file, truncated file, and requested rebuild can all have offset 0 but differ in source generation and sync semantics.--### Determining Whether a File Is the Same Source--Maintenance combines the following evidence:--- Whether inode identity changed-- Whether current size is below consumed offset-- Whether current size equals the previous recorded size-- Whether the boundary hash over the 4 KB before offset still matches--Inode and size detect replacement and truncation; the boundary hash detects an in-place rewrite at the same length.--### Boundary Hash and mtime--Rehashing every file across 210 days each cycle would hold `stats.lock` for too long and directly increase Hook recorder wait probability.--Maintenance records nanosecond mtime from the last boundary validation. If inode, size, and mtime are unchanged, it skips hashing. It recomputes the 4 KB before offset only after file change.--A normal append changes bytes only after offset, so the boundary continues to match and maintenance can aggregate incrementally. A changed boundary creates a new generation and marks it dirty.--### Build and Commit Validation--The aggregator cannot hold `stats.lock` while reading a full day because Hook subprocesses could time out repeatedly.--The actual flow is:--```text-Prepare under lock- -> Fix sourceGeneration, inode, startOffset, and read upper bound-Build without lock- -> Read in chunks and produce a candidate aggregate-Validate under lock- -> Generation still matches- -> Inode still matches- -> Candidate upper bound still exists- -> Boundary hash still matches-Commit daily.jsonl-Validate again under lock and advance maintenance offset-```--The recorder may continue appending during the read. As long as bytes before the candidate upper bound remain unchanged, the result is valid and the new tail remains pending for the next cycle.--If the source is replaced during build, the candidate does not commit; maintenance starts a new generation and waits for rebuild.--## Aggregation Rules--Daily results include:--- Total Hook events and per-event counts-- Session and turn counts-- Tool-call count-- Compaction count-- Subagent count-- Project distribution-- Model distribution--The session count deduplicates nonempty session IDs from all events except `SessionEnd` on that day. The turn count deduplicates nonempty turn IDs from all events except `Stop` and `Interrupt` on that day. A session or turn spanning multiple days contributes to each day with a nonexcluded event; a session observed only through `SessionEnd` and a turn observed only through `Stop` or `Interrupt` do not contribute.--Only one side of a paired event may persist. Counts therefore use rules that avoid duplicates while tolerating missing data:--- Tool calls use `max(PreToolUse, PostToolUse)`-- Compactions use `max(PreCompact, PostCompact)`-- Subagents use `max(SubagentStart, SubagentStop)`--A missing field differs from numeric `0`:--- Missing means the historical source cannot provide this metric for the date-- `0` means the source is available and explicitly observed none--Decoding and persistence retain optional values. The `WorkflowDailyMetrics` display projection preserves a missing `interruptCount` and converts other missing individual event counts to `0`; session and turn counts use deduplicated IDs or compacted counts first, then fall back to corresponding event counts.--### Paired Event Counts--`PreToolUse` and `PostToolUse` describe the two sides of one tool call. Since the recorder may fail, either side may be absent:--- Adding counts one complete call twice-- Pre-only misses a failed pre write followed by a successful post-- Post-only misses a tool that started before process interruption-- `max(pre, post)` is the least duplicate-prone estimate without stable call IDs--Compaction and subagent pairs follow the same rule.--### Count Availability--`WorkflowHookCountAvailability` records source availability for each count. Rebuild inherits availability from the existing date's aggregate. Without an aggregate, it uses `.legacy`, where `interruptCount` is unavailable and other event counts start at `0`. Reading an `Interrupt` changes a missing interruption count to a positive value; other events preserve its absence.--`interruptCount` remains optional in the display projection. If any contribution for a day lacks it, the total is unavailable. Heatmap details do not display this metric.--## Schema Evolution and Rebuild--The current aggregation schema is `9`, managed by `WorkflowMaintenanceState.currentAggregationSchema`.--Increment the schema for:--- Changes to the raw-event-to-aggregate algorithm-- Added or removed output fields-- Changed field meanings-- Changed deduplication rules-- Changed source-generation merge semantics--A schema mismatch triggers a full rebuild from raw JSONL within the 210-day retention period, without field-level historical migration.--User-requested rebuilding uses the same full-recalculation path and marks dates for replacement in sync.--### Aggregation Schema Versus Source Generation--| Identity | Describes | Changes when |-| --- | --- | --- |-| Aggregation schema | How current code calculates an aggregate from raw events | Algorithm, fields, or semantics change |-| Source generation | Which generation of raw file a particular day belongs to | Replacement, truncation, requested rebuild, or boundary rewrite |--A schema change usually marks all event dates in retention dirty. A source-generation change affects only a specific date.--Neither can be replaced with the app version. One app version may not change aggregation, while development builds may iterate schemas without changing a version number.--### Rebuild Source--Aggregation-semantic changes rebuild from raw JSONL. Filling fields cannot recover identities or event relationships already lost in old aggregates. Missing semantics are retained when the raw source itself lacks the field.--### Commit Semantics for a User Rebuild--A batch rebuild handles dates independently. Failure on one day does not block days that succeeded; failed dates become dirty for normal maintenance to retry.--Both successful and failed dates register CloudKit replacement first. A failed date already entered a new generation, and its later successful automatic rebuild will use a new record identity. Without an early marker, the old generation might remain in the cloud and be added to the new value.--The operation fails as a whole only if every date fails. Partial success returns a detailed summary of successful dates, damaged lines, and pending replacement state.--## Maintenance Scheduling--[`WorkflowService.swift`](../../../CodexBar/Services/Workflow/WorkflowService.swift) is an actor that serializes reading, aggregation, pruning, and rebuild.--Maintenance coordinates with the rate-limit refresh cycle but has no data dependency on it. The Workflow view model refreshes UI no more often than every 5 seconds to avoid rerendering for frequent file changes.--### Maintenance Logs--`WorkflowService` accumulates consecutive idle cycles and emits a summary on a write, skip, failure, or cleanup, including the accumulated idle count.--### How the Scheduler Coalesces Requests--`WorkflowSyncScheduler` serializes the following requests:--1. User rebuild, highest priority-2. Maintenance with sync-3. Local-only maintenance--After sync completes, an 8-second cooldown combines incoming requests and retains the earliest trigger as the real cause.--Opening the UI reads the current local snapshot and does not bypass the scheduler to start an unconditional CloudKit request.--## Suggested Failure-Scenario Tests--- Concurrent Codex sessions write complete lines without overwriting one another-- While the main app holds the lock, the Hook recorder succeeds within budget or abandons safely-- Non-JSON stdin or missing event name still exits successfully and immediately-- A partial tail line does not advance offset and is read after completion-- One malformed JSONL line increments only the corrupt count-- Inode change, file shrink, and boundary rewrite each create a new generation-- Appends during build commit only to the fixed upper bound and leave the tail pending-- A schema change rebuilds every in-retention date with the current algorithm-- Missing historical fields remain optional in decoding and persistence; display counts follow the current fallback rules-- Disabling Advanced Mode preserves user handlers and trust entries-- During rapid Hook toggling, old RPC results cannot overwrite the final operation--## Failure Boundaries--- One malformed JSONL line must not make the entire retention period unreadable-- A changed file source must not continue from the old offset-- A failed rebuild preserves the last usable aggregate-- Interrupted maintenance must not commit a partial result as a complete date-- When Hook is unavailable, the UI shows source unavailability rather than clearing to `0`-- A failed configuration write must not damage existing handlers--## Key Source Files--- [`AdvancedModeSettings.swift`](../../../CodexBar/Services/Settings/AdvancedModeSettings.swift)-- [`WorkflowHookEventRecorder.swift`](../../../CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift)-- [`CodexHookEvent.swift`](../../../CodexBar/Models/CodexHookEvent.swift)-- [`JSONLines.swift`](../../../CodexBar/Services/Workflow/JSONLines.swift)-- [`WorkflowService.swift`](../../../CodexBar/Services/Workflow/WorkflowService.swift)-- [`CodexWorkflowModels.swift`](../../../CodexBar/Models/CodexWorkflowModels.swift)diff --git a/Docs/en/DeveloperGuide/notifications.md b/Docs/en/DeveloperGuide/notifications.mddeleted file mode 100644index 0cdb871..0000000--- a/Docs/en/DeveloperGuide/notifications.md+++ /dev/null@@ -1,301 +0,0 @@-# Notification System--[简体中文](../../DeveloperGuide/notifications.md) | English--## Responsibility--[`CodexNotificationService.swift`](../../../CodexBar/Services/Notifications/CodexNotificationService.swift) is the single entry point for notification side effects.--It consumes the following state:--- App-server account and quota snapshots-- `CodexActivityMonitor` task transitions and Activity Protection candidates-- `KeepAliveController` sleep-prevention restoration results-- `AutoResetController` confirmed redemption results or reportable failures--## Settings and System Authorization--`NotificationSettings` stores in-app intent separately from macOS authorization:--| State | Meaning |-| --- | --- |-| `isEnabled` | The user enabled the master switch in CodexBar |-| `authorizationStatus` | Whether macOS permits notifications |-| `canDeliver` | Effective eligibility when both allow delivery |--The main switch defaults to off; system authorization is requested when the user enables it.--The app rereads system state on app activation, when the settings window regains focus, and when settings are explicitly opened. A `denied` result preserves the in-app switch and displays a secondary-color permission message with an Open System Settings button. An actual `notDetermined` result turns the in-app switch off; enabling it again requests authorization. The initial placeholder status does not modify the saved switch.--While an authorization request is pending, duplicate requests are suppressed and focus changes do not cancel the request awaiting the user's response. The permission message remains visible whenever the in-app switch is on and system authorization is missing. If the system still returns `notDetermined` after the request, the switch returns to off so the user can enable it again to retry.--After the authorization request finishes, permission reads use the normal refresh flow. If another focus refresh arrives during a query, the new query replaces the old one so stale results cannot overwrite the latest permission state.--Haptic feedback does not depend on `UNUserNotificationCenter` authorization but still follows the in-app master switch.--## Notification Switches--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:--| Category | Data source | Control |-| --- | --- | --- |-| Rate-limit reset | app-server rate-limit window | Independent category switch |-| Low rate limit | app-server remaining allowance | Independent category switch and threshold |-| Reset Credits expiration | app-server reset-credit details | Independent category switch |-| Automatic Reset | Confirmed redemption result or user-facing failure | Automatic Reset, category, and master switches |-| Task completion | Live-task terminal transition | Independent category switch and minimum duration |-| Waiting for approval | Live-task waiting transition | Independent category switch |-| Stalled Task Protection | Activity Protection | Prevent System Sleep and notification master switches |-| Low-battery stop | KeepAlive restoration result | Independent category switch, enabled only when protection is available |-| Keep-awake limit | KeepAlive restoration result | Independent category switch, enabled only for a finite duration |--Stalled Task Protection follows Prevent System Sleep. Its notifications require the master switch and system authorization, with no separate category switch. Low-battery and duration-limit notification preferences are retained while their controls appear off and disabled when the corresponding protection is unavailable.--## Rate-Limit Reset--A rate-limit reset notification requires observing a consumed window first and then a new window restored to an unconsumed state.--Observation state is isolated by account and rate-limit window. An account change does not carry the previous account's consumption state into the new account.--Each window also has an in-session lifecycle token. A window that disappears from trusted snapshots and later returns receives a new token. If a failed submission callback for the old window arrives late, it restores `hasObservedConsumption` only if the token still matches.--Reset state is not persisted. After each launch, the app observes consumption and a return to zero again; it does not replay resets that occurred while offline.--## Automatic Reset--An automatic reset operation and a rate-limit-window reset are separate events, so they retain separate notifications:--- “Automatic Reset” means CodexBar's automatic action returned `reset` or `alreadyRedeemed`-- “Rate Limit Reset” means a normal rate-limit snapshot first showed consumption and later returned to zero--One automatic reset can satisfy both conditions, so one device may receive both notifications, each controlled by its own switch.--The success body prefers a fresh post-redemption read of remaining reset credits, including an explicit `0`. If that read fails, the explicit success still stands and CodexBar sends a title-only notification.--`alreadyRedeemed` means the same idempotency key succeeded previously and must not be retried. When several devices call concurrently, every device that explicitly receives `reset` or `alreadyRedeemed` may send its local success notification. A device that only sees the credit disappear during refresh cannot distinguish manual use, use by another device, or expiration, so it stops silently.--Failure notifications use “Automatic Reset Failed” and currently cover:--- Still signed out after one authentication refresh: pause the current credit until a trusted snapshot proves recovery-- Parameter, protocol, or method error: stop retrying the current credit-- This Mac explicitly observes that the target expired: stop retrying the current credit--Transient network and service failures enter backoff without bothering the user on every attempt. The same failure reason notifies at most once per credit. Authentication, permanent error, and locally observed expiration use different deduplication keys, so one credit may produce different failure notifications over time. When the target disappears from server details, its cause is unknown and the state machine stops silently without adding an expiration notification.--Success and failure share the Automatic Reset Notifications switch and sound, enabled by default with the system default sound. When Automatic Reset is off, the setting row is disabled without overwriting saved notification or sound choices; re-enabling restores them.--## Low Rate Limit--Available thresholds are 5%, 10%, and 25%; the default is 10%.--The persisted deduplication key contains the second-level reset time returned by app-server. For the same account and rate-limit window, a reset time within 60 seconds of the recorded value belongs to the same cycle; only a difference greater than 60 seconds creates a new cycle.--Returning above the threshold rearms crossing detection, but one reset cycle still notifies only once. After a new reset cycle begins, the next downward crossing may notify again.--### Threshold Crossing--For each `account + limit + window`, the service stores the previous remaining percentage and applies these notification rules:--- Notify when the previous value was above the threshold and the current value is not-- Notify once when the first in-session value is already at or below the threshold-- Do not notify while remaining continuously in the low region-- When the threshold setting changes, clear the observation and reevaluate immediately against the new threshold--The settings subscription uses the new value passed to its callback. Combine publishes `@Published` during `willSet`, when rereading the settings property would still return the old value. This detail ensures that changing the threshold from 5% to 25% evaluates immediately at 25%.--A stale app-server snapshot neither advances the previous value nor triggers low-rate-limit or reset notifications. Old cache data supports display continuity but cannot prove a new side effect.--### Reset Cycle Matching--After rebuilding an app-server connection, the same window's `resetsAt` may receive a seconds-level correction. Absolute equality would treat it as a new cycle and notify twice.--Within the same account, limit, and window, the service finds sent or in-flight keys within a 60-second tolerance and reuses the original key. This tolerance normalizes identity only; the UI still displays the actual time returned by the service.--## Reset Credits Expiration--When the number of Reset Credits is greater than `0` and an expiration date is available, the notification service sends daily reminders from 7 days to 1 day before expiration.--The deduplication key includes account, expiration date, and days remaining. Multiple refreshes on one day do not repeat the notification.--The service schedules only the nearest future checkpoint, then recalculates from the current snapshot and schedules the next one.--This handles:--- app-server changes to the number or expiration time of Reset Credits-- Notification settings being disabled midway-- A Mac sleeping past the deadline and rechecking through the wake observer-- Combining multiple credits with the same expiration second into one notification--Date classification uses seconds remaining until expiration, with separate deduplication keys for 7 through 1 day. The scheduler only wakes the check; the current snapshot makes the final eligibility decision.--## Task Completion--Task notifications respond only to new terminal transitions published by the monitor and never infer them by scanning historical lists:--- Tasks established during bootstrap do not notify-- The activity monitor retains terminal task keys for 24-hour deduplication-- The notification service also tracks its own sent keys-- `Stop` retains the finishing task; rollout confirmation emits a completion transition when its end time is no earlier than the recovery boundary and no more than 10 seconds old-- Completion records update silently during bootstrap, recovery reconciliation, and unhealthy Hook source state-- `Interrupt` and other termination records do not trigger completion notifications or task haptics--Anonymous tasks are not published to task-notification consumers. The notification service filters `isAnonymous` again at the transition boundary, so anonymous tasks cannot send completion or approval notifications or trigger task haptics.--Minimum completion duration is 30, 60, 120, or 300 seconds; the default is 60 seconds. A shorter completed task does not notify but may still appear briefly in the UI.--Haptics start for every task transition. A new transition cancels the previous sequence of 10 pulses and begins again. Settings are rechecked before each pulse, so disabling haptics stops an old sequence immediately.--## Waiting for Approval--A waiting notification is sent only when the `PermissionRequest` reviewer is confirmed to be the user:--- Automatic review does not notify-- A task notifies once during a continuous wait; progress from other agents does not end that wait. See [Two-Stage Approval Confirmation](activity-monitor.md#two-stage-approval-confirmation) for ownership rules-- Leaving waiting state removes the item from the relevant set-- Waiting transitions pause during bootstrap, recovery reconciliation, and unhealthy Hook source state-- Both direct Hook confirmation and rollout reviewer backfill require the task's waiting start time to be no earlier than the recovery boundary and no more than 10 seconds ago--Whether waiting maintains sleep prevention is an independent setting and does not affect notification eligibility.--The notification uses stable task ID as its system identifier. The service also observes activity snapshots:--- Skip submission if the task has already left waiting state-- If state changes after `UNUserNotificationCenter.add` succeeds, withdraw immediately-- When a later snapshot no longer contains the task, remove both delivered and pending notifications-- On submission failure, remove it from the in-memory relevance set so a genuinely new wait may try again later--Relevance checks both before and after submission cover the asynchronous window. Checking only before submission could leave a stale reminder in Notification Center after approval.--## Stalled Task Protection--When a non-anonymous running task reaches its silence threshold, Activity Protection updates its in-memory record and schedules an asynchronous save, then starts notification submission and a 3-second grace period together. After notification handling returns or grace expires, the monitor revalidates the candidate before hiding it. Hiding waits for neither disk commit nor notification success.--The notification identifier uses `taskID + attemptID`, and relevance is determined by the monitor's current protection attempt. Checks before and after submission validate the attempt ID, progress generation, and silence duration. When the attempt becomes invalid, the notification service removes delivered and pending notifications with that identifier.--Protection notifications use the system default sound and a `retryCount` of `0` to avoid retrying an obsolete candidate.--## Sleep Prevention Stopped--When low battery or the duration limit stops sleep prevention, `KeepAliveController` first releases its helper lease. It submits the notification only if the reply reports source `.codexBar` and `SleepDisabled=0`; other results clear the pending notice for that cycle.--The app idle assertion remains until notification submission finishes, then is released, leaving sleep timing to macOS power management.--## Sounds--[`NotificationSoundOption.swift`](../../../CodexBar/Services/Notifications/NotificationSoundOption.swift) provides these sound choices:--- System default notification sound-- Silence-- System sounds available on macOS-- Sounds bundled with the app--Bundled sounds are under [`NotificationSounds`](../../../CodexBar/Resources/NotificationSounds).--If a saved sound name does not exist on a new system or app version, CodexBar falls back to the default sound without blocking the notification.--Each notification category stores its own sound setting.--Sound options persist stable IDs rather than absolute file paths:--- Bundled sounds resolve through bundle resources-- On first access, system sounds are scanned from User, Local, and System sound directories-- `/Network/Library/Sounds` is intentionally excluded because probing automounted paths may block the UI-- Duplicate names choose the earlier directory in system search order-- Bundled IDs are reserved in advance so a same-named local file cannot change the meaning of a saved choice after restart-- An unresolvable saved ID falls back to system default--System default and silent choices cannot be previewed. Preview is available for system and built-in sounds with a concrete audio file.--## Haptic Feedback--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.--## Submission and Deduplication--Notifications are submitted through `UNUserNotificationCenter`:--- Ordinary failed submissions retry at most once; Activity Protection notifications do not retry-- Sent deduplication keys persist in UserDefaults-- No more than 300 keys are retained-- Keys include enough account or task scope to avoid suppressing different objects-- Expired or irrelevant waiting keys are removed--Persistent deduplication prevents immediate repeats after restart but does not replace upstream terminal deduplication.--### In-Flight and Sent Deduplication--`submittingDedupKeys` and `sentDedupKeys` cannot be merged:--| Set | Lifetime | Prevents |-| --- | --- | --- |-| `submittingDedupKeys` | Current asynchronous submission | Two synchronous calls passing the check before the first `await` |-| `sentDedupKeys` | UserDefaults, up to 300 entries | Repeating the same business cycle after an app restart |--The deduplication check and `submitting` insertion happen synchronously before creating a `Task`, so correctness does not depend on Swift task scheduling order.--A key enters the sent set only after `UNUserNotificationCenter.add` succeeds and the event is still relevant afterward. Recording it earlier would permanently consume an alert after one system submission failure.--### Shared Delivery Semantics--All notification content eventually passes through the same `send` and `deliver` flow:--```text-Synchronously check deduplication- -> Build an immediate notification request- -> Check relevance before submission- -> Call the system notification center- -> Check relevance again after submission- -> Persist deduplication after success- -> Retry failures according to retryCount and perform classified cleanup (default 1, Activity Protection 0)-```--Logs record only `kind` and the failure reason, never title or body. Notification bodies may contain project names or task information and must not be copied into logs even when those logs remain local.--## Foreground Presentation and Clicks--CodexBar is an `LSUIElement`, so its notification-center delegate explicitly allows banners and sounds while the app is in the foreground.--Click handling calls `openMenuSurface` instead of constructing a new window. This reuses the popover when its anchor is valid, uses the fallback panel otherwise, and preserves the same focus and dismissal rules.--## Codex TUI Notifications--Codex TUI notifications are Codex settings, read through app-server `config/read` and written through `config/batchWrite`.--It is completely independent of CodexBar system notifications:--- Turning off CodexBar notifications does not turn off TUI notifications-- A failed TUI setting does not affect app notification state-- The UI must distinguish the scope of both switches clearly--## Manual Validation Matrix--- Enabling the master switch for the first time requests system permission correctly-- Settings presents an understandable state when permission is denied-- Low-quota alerts fire on a first reading at or below the threshold or a downward threshold crossing, with deduplication within each reset cycle-- An initial 100% rate limit does not produce a false reset alert-- Explicit Automatic Reset `reset` sends “Automatic Reset”; a later return to zero can independently send “Rate Limit Reset”-- Explicit `alreadyRedeemed` is treated as success and stops retries-- Merely observing the target credit disappear does not send an Automatic Reset notification-- Network retries do not send failure alerts, and one credit reports the same failure reason at most once-- Turning off Automatic Reset disables its notification option; re-enabling restores the prior switch and sound-- Success and failure notifications use the sound selected for Automatic Reset Notifications; both are silent when no sound is selected-- Behavior is correct for completed tasks below and above the duration threshold-- `Stop` and rollout terminal arriving together produce one notification-- Automatic approval does not send a waiting notification-- Allowed notifications still appear while the app is foregrounded-- Clicking a notification activates the `LSUIElement` app and opens the main panel-- A missing saved sound resource falls back correctly-- Restarting the app does not repeat persisted events--## Key Source Files--- [`CodexNotificationService.swift`](../../../CodexBar/Services/Notifications/CodexNotificationService.swift)-- [`NotificationSettings.swift`](../../../CodexBar/Services/Settings/NotificationSettings.swift)-- [`NotificationSoundOption.swift`](../../../CodexBar/Services/Notifications/NotificationSoundOption.swift)-- [`CodexCLINotificationSettings.swift`](../../../CodexBar/Services/Settings/CodexCLINotificationSettings.swift)-- [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift)-- [`KeepAliveController.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveController.swift)diff --git a/Docs/en/DeveloperGuide/sleep-prevention.md b/Docs/en/DeveloperGuide/sleep-prevention.mddeleted file mode 100644index 1b2febc..0000000--- a/Docs/en/DeveloperGuide/sleep-prevention.md+++ /dev/null@@ -1,453 +0,0 @@-# Sleep Prevention System--[简体中文](../../DeveloperGuide/sleep-prevention.md) | English--## Control Flow--The regular app process owns policy and UI. CodexBarHelper executes only constrained system sleep and wake operations:--```text-CodexActivityMonitor- -> KeepAliveController- -> App IOKit assertion- -> XPC lease- -> CodexBarHelper- -> /usr/bin/pmset--AutoResetController- -> AutoResetWakeScheduler- -> XPC wake date- -> CodexBarHelper- -> IOPMSchedulePowerEvent-```--## State Layers--State is separated by responsibility:--| Layer | Representative field | Question answered |-| --- | --- | --- |-| User intent | `isEnabled` | Does the user want the feature? |-| Decision condition | `sleepBlockReason` | Are activation conditions currently met? |-| Request state | `appliedSleepPreventionRequested` and `requestInFlight` | What did the app most recently request from the helper? |-| Confirmed effect | `isPreventingSleep` and `sleepPreventionSource` | Has the app received evidence that system state matches? |--- Temporary helper unavailability preserves the user's switch, allowing automatic recovery without requiring them to enable it again-- UI does not claim success after an XPC request but before confirmation, avoiding disagreement with actual system state--`sleepBlockReason` is the sole decision output for all conditions. Derived UI state, condition logging, and actual switching read the same result. Every new condition must state whether the settings entry remains available in an exhaustive `switch`.--## Two Layers of Sleep Control--The mechanisms have different scopes:--| Mechanism | Lifetime | Effect | How it ends |-| --- | --- | --- | --- |-| IOKit assertion | App process | Prevents idle system sleep and optionally display sleep | Reclaimed automatically after app exit |-| `pmset disablesleep` | System-wide | Covers system-sleep paths not guaranteed by assertions | Requires explicit restoration, ownership, and a watchdog |--The app assertion is established before XPC acquisition begins so there is no idle-sleep gap while the helper switches state. A shared cleanup path releases it after helper failure, preventing a half-success known only to the app.--## Acquire and Release Transactions--Acquisition updates the effective state after system verification succeeds:--```text-Conditions allow activation- -> Establish app idle assertion- -> Mark that helper may have received a lease- -> Send generation-tagged XPC request- -> Helper reads current SleepDisabled- -> Write and read back when needed- -> App validates source and measured value- -> Publish active state and begin duration accumulation-```--Release converges in the opposite direction:--```text-Conditions block activation- -> Ask helper to revoke lease- -> Helper restores system value only when it has restoration responsibility and no leases remain- -> App receives measured result- -> Publish inactive state and release display assertion- -> Stop duration accumulation- -> Submit low-battery or duration-limit notification- -> Release app idle assertion-```--Low-battery and duration-limit notices are submitted only when the helper replies with source `.codexBar` and `SleepDisabled=0`.--The app retains its idle assertion until notification submission finishes to prevent idle sleep before submission. It then releases the assertion, leaving sleep timing to macOS power management.--## Uncertain Lease State--An XPC timeout proves only that the app received no reply, not that the helper did not execute the request. The helper may hold the lease while its reply was lost during disconnect.--`mayHaveHelperLease` therefore uses conservative semantics:--- Set `true` immediately when requesting acquisition-- Remain `true` after timeout or connection invalidation-- Change to `false` only after an explicitly confirmed release--## XPC Generation Checks--The user may turn off the switch, a task may finish, and retry may start before an earlier XPC reply returns. Applying replies by arrival order could let old acquisition success overwrite newer release success.--Both app and helper use monotonically increasing generations:--- The app accepts callbacks only for current `requestGeneration`-- The helper ignores requests older than a lease's current generation-- Invalidating a connection advances app generation so in-flight callbacks become stale--## Activation Conditions--[`KeepAliveController.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveController.swift) establishes sleep prevention only when all conditions hold:--- Prevent System Sleep is enabled-- `AdvancedModeSettings.isOperable` is `true`-- At least one live task qualifies under settings-- CodexBarHelper is installed and connectable-- The low-battery threshold is not active-- The per-period maximum duration has not been reached-- The app is not terminating--Waiting-for-approval tasks do not count by default but can be enabled separately. Tasks suppressed by Activity Protection no longer maintain sleep prevention.--`KeepAliveController` first removes `isAnonymous` tasks from running and waiting snapshots. Only non-anonymous tasks can enter active sets, begin a new duration period, or keep sleep prevention alive.--The controller publishes an explicit blocking reason:--| Reason | Meaning |-| --- | --- |-| `notStarted` | Service has not started |-| `userOff` | User turned off the master switch |-| `advancedModeDisabled` | Hook is not operational |-| `noTasks` | No task qualifies |-| `helperUnavailable` | CodexBarHelper is not installed or connectable |-| `helperRefreshing` | CodexBarHelper state is recovering or being confirmed |-| `terminating` | App is quitting |-| `lowBattery` | Battery is below the threshold |-| `limitReached` | Per-period duration limit was reached |--## App-Side Assertions--[`SystemSleepService.swift`](../../../CodexBar/Services/KeepAlive/SystemSleepService.swift) creates an IOKit `PreventUserIdleSystemSleep` assertion.--If Keep Display Awake is enabled, it also creates `NoDisplaySleep` and declares user activity every 30 seconds so display idle timing does not activate early.--App assertions cover only the current process. CodexBarHelper manages system-level `SleepDisabled` to cover sleep paths assertions cannot guarantee.--## CodexBarHelper Installation and Communication--CodexBarHelper registers as a LaunchDaemon through `SMAppService`. The app and helper use the XPC interface in [`CodexBarHelperXPC.swift`](../../../Shared/CodexBarHelperXPC.swift).--The interface exposes the following capabilities:--- Set or revoke an app lease-- Query helper runtime and ownership state-- Reset helper state after an app update-- Set or cancel the next Automatic Reset `wake` event for CodexBar's fixed owner--Automatic Reset and sleep prevention share helper registration and macOS approval but use separate XPC connections. Enabling Automatic Reset attempts helper registration even when Prevent System Sleep is off; while approval is pending, its setting row shows the same state and `Open System Settings` entry.--Settings separates user confirmation, helper registration, and navigation to Helper authorization:--- `HelperFeatureConfirmation` presents one shared dialog whenever Automatic Reset or Prevent System Sleep changes from off to on-- `.notRegistered` and `.notFound` explain that background installation and authorization are required; `.requiresApproval` explains that installation succeeded but authorization is pending; `.enabled` shows only the feature description-- Only user confirmation calls `AutoResetSettings.setEnabled(true)` or `KeepAliveController.setEnabled(true)`; cancellation does not write enabled state-- `ensureHelperRegistration()` handles registration, refresh, and coordination only; it does not open authorization settings-- `AppSettingsView` shows `Open System Settings` only for an enabled row in `.requiresApproval`; the button calls `KeepAliveController.openSystemSettings()`-- Automatic Reset options require its switch on and `helperStatus == .enabled`; losing that condition closes an open panel-- Sleep-prevention options read `KeepAliveController.canShowOptions`; settings remain adjustable with no task, low-battery block, limit reached, or helper refresh-- Automatic Reset and sleep-prevention rows show no status explanation while their switches are off--The About row and both feature captions use `helperInstallationStatus`. System registration, package validation, and operation errors remain separate facts:--- `.notRegistered` and `.notFound` display Not Installed when there is no known installation failure-- At startup and when the app becomes active, background validation checks the helper executable, key plist fields, the app resource seal, and the helper's signing team and identifier; signature validation does not access the network-- Missing components, invalid configuration, or invalid signatures display Unavailable even when macOS still returns `.enabled`; a later successful package check clears the issue-- Missing components found before registration update only the package issue and start a fresh check, without storing a duplicate registration error; older results cannot overwrite the new issue, and revalidation can restore the display after repairs even with both features off-- Historical registration errors do not override pending approval or authorization; an unregistered helper with a failed installation displays Unavailable-- Package validation results stay in memory; separate operation errors report XPC timeouts and power-operation failures--Wake schedules converge from actual system state rather than depending only on normal-exit cleanup:--- Before opening the XPC listener on every startup, the helper removes stale events for its fixed owner; after reconnect, the app reschedules from the latest target-- Set succeeds only after read-back finds exactly one time-matching event; cancel succeeds only after read-back finds none-- A corresponding XPC disconnect abandons the in-memory owner immediately; failed cancellation enters pending cleanup and retries on a short helper cycle-- App exit waits separately for wake-schedule and sleep-lease release; helper update freezes wake synchronization first and explicitly cancels when the current process has a wake connection or applied time-- Before unregistering the helper, `Scripts/cleanup.swift` checks the fixed owner and stops if it cannot cancel and confirm an empty schedule, avoiding removal of the last process able to clean it; after successful unregister it turns off both sleep prevention and Automatic Reset so the next app launch does not reregister--Each app process creates a stable `clientSessionID` that survives XPC reconnection. Every lease change carries a monotonically increasing generation, and CodexBarHelper accepts only newer requests:--- One XPC request times out after 10 seconds-- Lost connections have a 15-second watchdog grace period-- CodexBarHelper checks leases and system state every 5 seconds-- Abnormal state retries recovery every 60 seconds--## CodexBarHelper Privilege Boundary--[`CodexBarHelper/main.swift`](../../../CodexBarHelper/main.swift) runs as root but is intentionally constrained:--- System sleep switching invokes only fixed `/usr/bin/pmset`-- It uses only fixed arguments to read or toggle `disablesleep`-- It sets or cancels one system wake event with a fixed owner and fixed `wake` type-- The wake interface accepts only bounded timestamps, never arbitrary owners, event types, or commands-- It accepts no arbitrary command or arguments-- It does not access Hook, rollout, account, or log data-- It performs no network access-- It does not determine Codex task state--CodexBarHelper builds the client code-signing requirement from the Team ID in its own signature and the app identifier for the current build configuration, then applies it to the XPC listener.--## System-State Ownership--CodexBarHelper first reads the current value with:--```bash-/usr/bin/pmset -g-```--When system-level prevention is needed, it runs only:--```bash-/usr/bin/pmset -a disablesleep 1-```--On release it runs:--```bash-/usr/bin/pmset -a disablesleep 0-```--Ownership rules prevent damage to external state:--- If the initial observed value is already `1`, the helper marks it external-- CodexBar does not claim external state-- After observing `0`, CodexBar persists owned before performing and verifying its own `0 -> 1` transition-- When the final lease ends, owned or restoring state restores to `0`--Thus, `SleepDisabled=1` set earlier by a user or another tool remains on after CodexBar exits.--### Ownership Recovery Transaction--The helper writes recovery records and system state in this order:--```text-Acquire: persist owned -> pmset 1 -> read back 1-Release: persist restoring -> pmset 0 -> read back 0 -> persist idle-```--Acquisition persists owned first. A crash after file write but before `pmset 1` causes one extra idempotent `pmset 0` at next start rather than leaving global sleep disabled. Writing the system value first could crash before recording restoration responsibility.--Release persists restoring first. A crash before `pmset 0` or final idle commit still leaves a known incomplete restoration. Idle may persist only after read-back confirms system value `0`.--### Taking Over After an External Source Disappears--`external` is not a permanent decision. While eligible tasks remain, CodexBar periodically reads system state cached by the helper:--- Continue borrowing `SleepDisabled=1` without writing while the external source remains-- If it disappears while a task remains, reacquire a lease and let the helper perform a new `0 -> 1`-- If another valid client already made helper state owned, update source presentation without restarting the duration period--## CodexBarHelper State Persistence--CodexBarHelper stores ownership at:--```text-/Library/Application Support/CodexBar/helper-state.json-```--Security and reliability requirements are:--- Current schema is `1`-- Directory is root-owned with `0755` permissions-- Directory is not group- or world-writable-- File is root-owned with `0600` permissions-- Commits use a temporary file, full sync, and atomic rename-- At startup, a missing record creates idle state; owned or restoring records restore `disablesleep 0`; unreadable or untrusted records also trigger restoration to `0`--Automatic Reset wake events are not stored there. macOS power management persists them under an identity formed from the current Debug or Release helper mach service plus `.auto-reset`, with fixed type `wake`.--## Leases and Failure Recovery--While the app has eligible tasks, it holds an identified XPC lease. CodexBarHelper does not interpret one request as permanent authorization detached from its connection:--```text-Lease valid -> Keep owned state-Connection briefly lost -> Wait 15-second watchdog-Reconnect within grace -> Continue with the same clientSessionID-Grace expires -> Revoke lease and restore owned state-```--After abnormal exit, connection invalidation, the watchdog, and persisted ownership together restore system settings.--Normal app exit first cancels the Automatic Reset wake schedule, then revokes the lease and IOKit assertion. If the helper has not confirmed both root-state categories clean, app termination waits instead of leaving under uncertainty.--### Normal Exit--`applicationShouldTerminate` cannot approve exit before confirmed release. `prepareForTermination()` stops new retries, cancels a possible Automatic Reset wake schedule, requests release of a possible lease, and waits for helper read-back:--- Continue termination after successful release-- Cancel this termination and resume normal condition evaluation and retries after failure--On forced exit, the helper revokes the disconnected client’s lease after the 15-second watchdog grace period.--### Helper Self-Checks--The helper checks leases, ownership records, and measured `SleepDisabled` independently:--- While owned with leases, reestablish `1` if another source changes the system value to `0`-- While owned without leases, restore `0`-- While external, observe only and never persist external state as owned-- On an untrusted persistence record, fail safe by restoring rather than treating corruption as permission to remain active-- If Automatic Reset cancellation failed and no connection owner remains, reread and clean the fixed owner every 5 seconds--Periodic checks repair state divergence after external writes, lost callbacks, or process restarts.--## Duration and Battery Policy--The per-period duration counts only time when sleep prevention is actually active:--- Pause or reset when no task exists-- A new task period can receive a fresh budget-- Default limit is 12 hours-- Choices are 1, 2, 4, 8, 12, or 24 hours, or unlimited--Low-battery stopping applies only on battery power:--- Threshold options are 5%, 10%, 15%, 20%, and 25%-- Off by default-- Recovery uses 5 percentage points of hysteresis to prevent toggling near the threshold--When low battery or duration limit stops prevention, notification must follow confirmed sleep restoration.--### Defining a Duration Period--“Maximum per-period duration” is accumulated time that CodexBar actually blocks system sleep, not wall time from task appearance to disappearance.--`KeepAliveDurationLimiter` uses `SuspendingClock`:--- The clock pauses in system sleep, so sleeping time does not count as prevention-- Accumulation pauses while helper is unavailable, low battery blocks, or another condition prevents activation-- A new running task begins a new period-- A waiting task resuming running begins a new period-- Refreshing snapshots for the same task set across running and observation does not reset repeatedly--`hasReached` is sticky for the current period. An ordinary snapshot refresh cannot immediately reactivate after the limit; only a clearly new task period or a settings change reevaluates it.--The task set uses stable task IDs to detect “new task” and “resumed from waiting,” not count alone. If one task ends as another starts, count remains one, but the new task deserves a full budget.--### Battery Read States--Battery reads use `unavailable`, `unreadable`, and `present` rather than one optional value:--| State | Meaning | Policy |-| --- | --- | --- |-| `unavailable` | Confirmed no built-in battery | Hide low-battery settings and clear the block |-| `unreadable` | IOKit read failed this cycle | Preserve the previous decision |-| `present` | Trusted level and power source | Evaluate the threshold normally |--Preserving state through one read failure prevents the row from flickering and avoids transiently disabling active low-battery protection. Once a machine has reported a battery, a later empty list is `unreadable` because hardware cannot disappear at runtime.--Battery use comes from power-source state, not `isCharging`. A connected Mac that has stopped charging also reports `isCharging == false`, but tasks are not draining its battery.--### Low-Battery Latch and Hysteresis--For threshold `T`, protection enters while on battery at or below `T` and exits only at or above `T + 5`.--Low-battery notification has a per-period latch:--- Queue it only if CodexBar previously prevented sleep-- Record it as notified only after successful restoration-- Connecting power clears the current block, but only crossing the recovery threshold ends the latch period-- Changing the threshold starts a new period so notification state under the old threshold cannot contaminate the new setting--## Display Awake Is a Supplemental Effect--Keeping the display awake depends on confirmed sleep prevention plus the user option; it does not independently maintain system sleep.--`NoDisplaySleep` prevents display sleep but not the screen saver or idle lock, so the app also declares user activity every 30 seconds. It reuses one assertion ID; otherwise `pmset -g assertions` would accumulate same-named entries.--A failed display assertion records its own error without overriding primary sleep-prevention success. This intentionally separates core and supplemental effects so Settings does not report “sleep prevention completely failed” when only the display did not stay awake.--Assertion names use ASCII. On some system versions, Chinese names appear empty in `pmset -g assertions` and lose diagnostic identity.--## Restoring System Power Management--When tasks finish, the feature is disabled, the battery runs low, or the duration limit is reached, CodexBar releases its lease and app assertions. The helper restores system sleep settings only when it has restoration responsibility and no other leases remain. Settings owned by external sources remain unchanged.--Releasing sleep prevention does not explicitly request system sleep. macOS decides whether to sleep according to system power policy, including when the lid is closed or external displays are connected. Task completion does not guarantee immediate sleep.--## Failure and Retry--Sleep prevention uses bounded retries because each attempt reconstructs a privileged connection and may launch a root process:--- A 10-second request timeout precedes the 15-second helper watchdog; the app abandons the untrusted connection first, then the helper can clean its lease-- Recompare desired state before each retry so acquisition stops after the user disables the feature-- Preserve an explicit error after exhaustion instead of looping forever and consuming resources-- Release the app assertion immediately on connection invalidation so a degraded UI does not coexist with indefinite process-level idle prevention-- Invalidate old requests by generation rather than relying on every cancellation path to retract the underlying message--Diagnostics distinguish system registration status, package validation issues, registration errors, and operation errors. Not installed and awaiting approval are registration states. Missing components or invalid configuration or signatures are package issues. Failed registration or update produces a registration error. An operation error means an installed helper did not produce a trusted result for one transition.--Automatic Reset wake scheduling uses a separate bounded synchronization policy:--- After set or replace failure, retry at `2s, 4s, 8s, 16s, 32s, 64s`; preserve the error on the Automatic Reset row after exhaustion-- Before normal exit or helper update, cancel and read back immediately, then after `250ms`, then after `1s`-- Do not register a system event within 5 seconds of now; the in-app task proceeds directly to deadline execution-- After XPC loss, clear app-side applied state and recoordinate; the helper simultaneously cancels the fixed event owned by that connection--## CodexBarHelper Updates--An app update may change the bundled helper's signature or content. The app records a CodexBarHelper fingerprint and refreshes installation through `SMAppService` and the reset interface after detecting change.--Validation must cover:--- CodexBarHelper is in the correct app-bundle location-- LaunchDaemon plist matches the Debug or Release bundle ID-- App and helper signatures match expectations-- First-time system authorization completes-- Old owned state restores safely after update-- Automatic Reset wake schedules are canceled before update and recreated from the current target after the new helper is ready--## Manual Validation Matrix--- App assertion and CodexBarHelper lease switch together when a running task starts and ends-- With the lid closed, AC power connected, and external displays in use, task completion releases sleep prevention without explicitly sleeping the displays or locking the screen-- With the lid open, task completion restores the configured system idle-sleep policy-- With the lid closed and no external displays, record when the system actually sleeps after task completion-- Disabling sleep prevention, low battery, and the duration limit release leases and assertions without requesting software sleep-- Eligible-task decisions are correct with Keep Awake While Waiting off and on-- If an external source sets `disablesleep 1` first, CodexBar neither claims ownership nor restores `0`-- Normal app exit restores owned state-- Forced exit or XPC disconnect lets the watchdog restore owned state-- Automatic Reset and sleep prevention show confirmation every time they are enabled and remain off after cancellation-- Confirmation text and feature descriptions are correct for unregistered, awaiting-approval, and approved helper states-- With a valid package and no registration error, both `.notRegistered` and `.notFound` display Not Installed-- In a test bundle, separately remove the Helper, remove or alter the plist, and invalidate signatures; launch or reactivate to confirm Unavailable, including when already authorized-- After detecting missing components before installation, older validation results cannot overwrite the new issue; disable both features, repair the complete app bundle, and reactivate to clear the issue while About continues showing the status-- Enabling only triggers helper registration; authorization settings opens solely from `Open System Settings` on the row-- Automatic Reset options appear only when enabled and approved and close when that condition fails-- Automatic Reset can register and gain approval while sleep prevention remains off-- Future thresholds and retries retain one `wake` event for the fixed owner and do not affect other owners when replaced-- Disabling Automatic Reset, changing its target, and normal exit each confirm the schedule is empty by read-back-- An Automatic Reset XPC disconnect or helper restart cleans stale schedules-- `Scripts/cleanup.swift` unregisters the helper only after the fixed-owner schedule is confirmed empty-- Reaching the duration limit restores sleep before notifying-- Low-battery triggering and 5% hysteresis recovery work correctly-- Hiding a task through Activity Protection releases sleep prevention-- Debug and Release CodexBarHelper instances are never mixed--## Key Source Files--- [`KeepAliveController.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveController.swift)-- [`KeepAliveHelperConfiguration.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swift)-- [`SystemSleepService.swift`](../../../CodexBar/Services/KeepAlive/SystemSleepService.swift)-- [`HelperRuntimeStatusMonitor.swift`](../../../CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift)-- [`AutoResetWakeScheduler.swift`](../../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift)-- [`KeepAliveDurationLimiter.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift)-- [`PowerSourceMonitor.swift`](../../../CodexBar/Services/KeepAlive/PowerSourceMonitor.swift)-- [`CodexBarHelperXPC.swift`](../../../Shared/CodexBarHelperXPC.swift)-- [`CodexBarHelper/main.swift`](../../../CodexBarHelper/main.swift)diff --git a/Docs/en/DeveloperGuide/sync.md b/Docs/en/DeveloperGuide/sync.mddeleted file mode 100644index 196c892..0000000--- a/Docs/en/DeveloperGuide/sync.md+++ /dev/null@@ -1,350 +0,0 @@-# CloudKit Sync--[简体中文](../../DeveloperGuide/sync.md) | English--## Sync Scope--CloudKit sync merges daily Hook metrics and rollout token usage across Macs signed in to the same iCloud account.--Hook sync transfers daily aggregates:--```text-Local raw Hook JSONL- -> Local daily aggregation- -> Current-device CloudKit record- -> Download records from other devices- -> Merge by date for display-```--App-server account data, rate limits, account token totals, Reset Credits, Automatic Reset settings and state, live tasks, and sleep-prevention state do not sync.--## Data Sources--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 |-| --- | --- | --- |-| Current-device contributions for today and history | Local `daily.jsonl` merged with same-source cloud cache by completeness | Local aggregation continues; cloud cache is retained |-| Contributions from other devices | Last successfully fetched records in `cache.jsonl` | Preserves the last snapshot |-| Upload confirmation and incremental position | `state.json` and `cursor.data` | Continues or rebuilds next time |--Current-device local aggregates and cloud copies are merged by source and completeness, counting each source once. The cloud can supply missing local data or a same-source aggregate with more events.--The remote cache is a rebuildable projection, and the cursor is only an optimization. Any cursor failure can fall back to a full custom-zone read without requiring the user to delete local files.--## CloudKit Structure--[`WorkflowSyncService.swift`](../../../CodexBar/Services/Workflow/WorkflowSyncService.swift) uses the app's CloudKit private database:--| Item | Value |-| --- | --- |-| Container | `iCloud.app.zabrian.codexbar` |-| Custom zone | `CodexBarZone` |-| Metadata record type | `CodexBarSyncMetadata` |-| Daily aggregate record type | `CodexBarDailyAggregate` |-| Token-turn record type | `CodexBarTokenTurn` |--Private-database content belongs only to the current iCloud account and is never written to the public database.--The custom zone is more than a namespace. It provides zone change tokens and deletion events so devices can sync additions, modifications, and deletions incrementally instead of scanning the entire private database each cycle.--Zone confirmation and account salt are cached in the actor across cycles. Sync failure invalidates both for the next cycle to reread.--## Activation Conditions--Sync runs only when all conditions hold:--- The user enabled CloudKit sync-- `AdvancedModeSettings.isEnabled` is `true`; historical sync can consume aggregates already stored locally-- The current iCloud account is available-- The local aggregation service is available--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 Identifier Hashing--Sync must distinguish device contributions without uploading a raw hardware identifier:--1. Create a random 32-byte account salt in the private database-2. Read the local `IOPlatformUUID`-3. Compute HMAC-SHA256 of the UUID with the account salt-4. Use the result as the cloud `deviceId`--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.--Local state records the most recently resolved `deviceId`. If it changes, sync clears the old cursor and remote cache while retaining pending replacement dates. A device-identity change means the cached account scope is untrusted and cannot continue incrementally.--## Daily Aggregate Fields--Each daily record contains:--- Schema-- Hashed device identifier `deviceId`-- Date-- Source generation-- Hook event counts-- Session and turn counts-- Project counts-- Model counts-- Update time--It does not upload:--- Raw Hook JSONL-- Raw session or turn IDs-- Full working directories-- Prompt or response content-- Codex account or rate-limit data-- Authentication tokens or credential files such as `auth.json`-- App request logs-- Stalled Task Protection state--For complete boundaries, see [Data and Privacy Boundaries](data-and-privacy.md).--## Rollout Token History--Token history uses a separate `CodexBarTokenTurn` record type with schema `1` in the same private zone. Each record represents one thread and turn. Cumulative snapshots replace the previous contribution; they are never summed by device. Main and child threads contribute once each, attributed to the root turn's start date in the viewing device's local time zone.--Local identities are SHA-256 hashes of thread and turn IDs. Cloud identities apply account-salted HMAC-SHA256 to those hashes, so copied rollouts on different Macs resolve to the same record. No raw session, turn, or agent ID is uploaded.--Deploy the following record type and fields to the CloudKit production schema before distribution:--| Field | CloudKit type | Meaning |-| --- | --- | --- |-| `schemaVersion` | Int64 | `1` |-| `rootID` | String | Account-scoped root-turn hash |-| `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 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.--Explicit rebuilds scan retained local rollouts, select records by the root turn's start date, and replace only reread turns in the requested dates. A local `rebuild.lock` excludes concurrent rebuilds across processes. Scanning yields between batches without holding the ledger lock; a complete successful scan is committed atomically. Live progress observed after the scan began is preserved. Missing source files do not remove known turns. Read failures and cancellation preserve the previous ledger; restarting the app does not resume an unfinished manual rebuild.--Rebuilt turns that need syncing carry `rebuiltAt`. Merging first selects the newer rebuild, then retains the more complete cumulative snapshot within that rebuild. This allows corrections to lower counts. Incremental reads inherit the local turn's rebuild time. When recovering the local ledger or observing a newer cloud rebuild, restore the cloud baseline only for locally discovered turns with matching account and root identities. Previously read files replay within the usual byte budget. Usage records at or before the restored rebuild boundary cannot replace the corrected baseline; later cumulative records continue updating it. Recovery boundaries and file cursors persist locally so replay resumes after restart without importing remote-only turns. A previously counted turn rebuilt without usage remains syncable to clear its old cloud usage. Other turns and sessions from other Macs remain untouched.--Daily cache hit rate is total cached input divided by total input. Account usage and heatmap intensity come from app-server. Heatmap date details present missing usage as `0` and a missing cache hit rate as `0%`; storage and sync preserve missing values.--The local ledger is `HookEvents/Tokens/ledger.json`; its separate process lock coordinates Debug and Release. Account-scoped sync state lives in `HookEvents/Sync/Tokens/cache.json`. Debug and Release share this cache. A nonblocking `sync.lock` serializes complete sync passes while the separate file lock allows reads between writes. Hook daily aggregates use separate storage and sync records.--Scanning includes `rollout-*.jsonl` files modified within the last 210 days under `$CODEX_HOME/sessions` and `$CODEX_HOME/archived_sessions`, with a 64 MiB pass budget plus at most one additional bounded line. Later maintenance passes continue historical backfill. Equally unread files are ordered by most recent modification first, so recent sessions are processed before older history. Partial lines are retried; large body lines are skipped without storing their contents. Replacement, truncation, and changed read boundaries trigger replay without counting known cumulative usage again. Turns are retained for 210 days by `updatedAt`, along with root records referenced by retained child turns. Daily totals include only root start dates within retention. Missing rollouts or missing `token_usage_record` entries cannot be reconstructed.--Automatic replay reports progress in the `workflow` system log after each committed batch: caught-up file count, byte progress, bytes read this pass, remaining bytes, files waiting for a complete line, unreadable files, and elapsed time. Once all files are caught up, it logs “Rollout 回放完成” once. Routine incremental appends and unchanged waits do not repeat the message. Completion refers to local files checked in that pass, not iCloud synchronization. Logs contain no paths, session identities, conversation content, or token usage.--## One Sync Cycle--```text-Read local sync state- -> Create or confirm custom zone- -> 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- -> Fetch remote Hook changes into the cache again- -> Fetch, upload, and prune token-turn records- -> Prune this device’s expired Hook records- -> Save state and publish merged results-```--The fetches before and after upload serve different purposes:--- Before uploading, it must know whether a same-device, same-day remote record exists so it can update, create a generation record, or skip-- Before replacement, it must perform a full fetch to discover old generations that an incremental cache may have missed-- It fetches again after upload to merge this cycle's writes and concurrent writes from other devices into the local cache-- It prunes expired records last so a pruning failure cannot block valid uploads in the same cycle--Every stage writes a `stage` field to logs, identifying failures in `zone`, `device`, `fetch`, `upload`, `tokens`, or `prune`:--- Upload batches contain at most 25 records-- Each upload cycle uses a 20-second budget to decide whether to start another batch-- A fetch page contains at most 200 changes-- SHA-256 hashes of local content skip unchanged records--The upload loop checks its 20-second budget before each batch. A batch already in progress continues waiting for its result. Once the budget is exhausted, remaining dates wait for a later sync.--Each date’s stable JSON is encoded and hashed once, reusing the result for pending-upload filtering and upload confirmation.--Uploads use `atomically: false`, allowing partial success remotely. If any error occurs in a batch, the caller removes local confirmation hashes for every date in that batch and rechecks it next cycle. Confirmations from earlier completed batches remain, and successful remote writes are not rolled back.--## Hook Daily Aggregate Merge Semantics--One day may have records from several devices plus a newer local result that the current device has not uploaded yet.--Merge rules are:--- Add other-device contributions by field-- Use cloud contributions when the current device has no local aggregate-- Match sources by `sourceGeneration` or legacy-record content; use the cloud aggregate if it has more events, otherwise use local data-- If local source completeness is unconfirmed and no cloud record matches it, prefer existing cloud contributions-- Continue adding unmatched independent cloud sources--`confirmedDates` includes both successful uploads and dates skipped by the upload decision; it does not guarantee field-for-field equality between local and cloud content.--### Multiple Sources for One Device and Date--Record names support both `deviceId + date` and `deviceId + date + sourceGeneration`.--A generation record identifies one raw source. Same-source local and cloud results replace one another, while clearly distinct sources may represent independent contributions created on the same day.--The read layer first finds the record matching local `sourceGeneration`. It uses whichever local or remote copy is more complete and continues adding other generations. A legacy record has no generation, but identical content can still be treated as the same source for compatibility.--The system does not infer “all old generations are invalid” from generation values. An explicit `replacementDates` transaction expresses that intent. This distinction preserves independent contributions during normal source rotation while allowing a user-requested full rebuild to remove historical copies.--Upload targets follow these rules:--| Remote state | Local source | Action |-| --- | --- | --- |-| No record for the date | Any | Create a legacy or generation record |-| Same-source record exists | Local is at least as complete as remote | Update that record |-| Same-source remote has more events | Local has a generation | Keep remote so a shorter stale scan cannot overwrite a more complete result |-| Other-source record exists | Local source is fresh | Create a record for the current generation |-| Other-source record exists | Local source is not fresh | Skip and wait for an authoritative rebuild |--`sourceIsFresh` describes the completeness of the raw source for one read, not its timestamp. A newer timestamp is not more authoritative while a file is replaced, truncated, or awaiting stable-boundary confirmation.--### Missing Count Fields--As the CloudKit record schema evolves, an old record may lack a new count field. `nil` means that device cannot provide the metric for that day; `0` means it explicitly observed zero occurrences.--CloudKit decoding and persisted models preserve optional counts. Local and remote aggregates share the `WorkflowDailyMetrics` display projection: a missing `interruptCount` stays unavailable, while other missing individual event counts become `0`. Missing session and turn counts fall back to the corresponding start or stop event counts, then to `0`.--CloudKit stores interruption counts in the optional integer field `interruptCount`. If any contribution for a combined date lacks this field, the total interruption count remains unavailable.--## Hook Source Replacement and Rebuilding--When the user requests a rescan:--1. Local aggregation rebuilds from raw JSONL-2. Affected dates are marked for replacement-3. Cloud records for those dates on the current device are overwritten or deleted and recreated-4. Other-device records remain unchanged--This design limits a rebuild to correcting the current device's contribution.--### Replacement Transaction--Rebuild and CloudKit synchronization may not finish in one process lifetime, so `replacementDates` persists in `state.json` instead of memory only.--For each replacement date, sync:--1. Rebuilds the remote cache in full-2. Enumerates all known legacy and generation record IDs for that date on the current device-3. Deletes those contributions, treating `unknownItem` as idempotent success-4. Removes the date from the local hash table to force reupload-5. Clears the replacement marker only after confirming the new content--While replacement is in progress, the snapshot filters the current device's cloud cache for that date and shows the latest local aggregation. Even if the app quits between deletion and reupload, the UI does not add the old cloud contribution to the new local contribution.--Before replacement deletes records, a full fetch finds every generation for the device and date, including records missing from the incremental cache.--## Incremental Cursor and Local Cache--Sync state lives at:--```text-~/Library/Application Support/CodexBar/HookEvents/Sync/-```--| File | Purpose |-| --- | --- |-| `state.json` | Sync schema, local hashes, and replacement state |-| `cache.jsonl` | Cached daily aggregates from remote devices |-| `cursor.data` | CloudKit zone change token |--The current CloudKit record schema is `6`. The local sync-state schema is `4` and can read the previous schema `3`.--Recovery costs differ by file:--| File | Cost if lost | Recovery |-| --- | --- | --- |-| `state.json` | Loses upload hashes and replacement progress | Recompare and upload; replacement depends on markers that still exist |-| `cache.jsonl` | Temporarily loses other-device contributions | Full custom-zone fetch |-| `cursor.data` | Loses incremental position | Full fetch and new baseline |--`cursor.data` stores the opaque CloudKit token with secure coding; code does not inspect its structure. After a full fetch, sync must also create a new cursor baseline, or the next cycle may consume all recently fetched changes again from an empty cursor.--Reading local schema `3` rebuilds the remote cache before saving schema `4`; unknown schemas resynchronize from empty local state.--Any change to record fields, identity, or schema is a compatibility decision. It must account for old apps still writing, new apps reading old fields, and whether downgrade can overwrite new records—not merely increment a constant.--## Sync Scheduler--Local maintenance and CloudKit sync share aggregation input but require different trigger rates. `WorkflowSyncScheduler` coalesces triggers into a single-threaded state machine.--Priority is:--```text-User-requested rebuild > Sync maintenance ready now > Local-only maintenance > Sync in cooldown-```--Important details include:--- Requests during the 8 seconds after a sync finishes merge into the next cycle so one Hook burst does not trigger many network operations-- Merged requests retain the earliest trigger because it is the real cause of the cycle-- A rebuild cancels completion for an earlier rebuild that has not started, preventing a caller from waiting forever-- Disabling sync during a wait clears pending sync but still allows required local maintenance-- `@Published` subscriptions run during `willSet`, when rereading the property returns the old value, so activation is calculated explicitly from the new callback argument--## Failure and Recovery Semantics--A sync failure does not roll back remote writes or clear the last usable cache. The next cycle continues through hashes, record IDs, and CloudKit APIs:--| Failure point | Preserved state | Next cycle |-| --- | --- | --- |-| Zone or account confirmation | Local aggregation and old cache | Reconfirm zone and salt |-| Incremental fetch | Old cache | Fall back to a full rebuild |-| Partial upload | Hashes from earlier completed batches and successful remote writes | Recheck all dates in the failed batch |-| Replacement deletion | Replacement marker | Re-enumerate and delete idempotently |-| Prune | In-retention data and upload results | Prune later |--A sync failure invalidates the actor’s cached zone confirmation and account salt. The next cycle resolves account and device identity again; a change from the device identity stored locally rebuilds the remote cache.--## Retention and Pruning--CloudKit records share the local Hook-history retention period of up to 210 days:--- Expired local raw data and daily aggregations are deleted-- Expired cloud records for the current device enter pruning-- Expired dates are removed from the local remote cache-- Prune failure does not affect in-retention display--## Error Classification--The sync layer distinguishes the following states for Settings and the main panel:--- Network unavailable-- iCloud account unavailable-- CloudKit service unavailable-- Server requested a later retry-- Local data or schema incompatible-- Sync succeeded or had no changes--Transient errors preserve the last usable remote cache. After account switching or identity invalidation, old-account cache must not be presented as current-account data.--## Manual Validation Matrix--- First enable uploads local aggregations within retention-- A second device merges contributions without duplicating the current device-- Merging device records with and without `interruptCount` preserves its unavailable state-- Disabling sync shows local metrics only-- When iCloud is signed out, the app shows a clear state and local metrics keep working-- After network loss, the app uses the last cache and completes incremental sync on recovery-- Local rebuilds replace this device’s Hook records and token turns reread locally-- Token rebuilds can lower or clear counts; other devices converge without restoring stale counts-- Missing rollouts preserve known turns; replay after ledger recovery respects cloud corrections-- File copies and cross-device copies of a turn count once; main and child threads use the root turn’s start date-- Local and remote cache older than 210 days is pruned-- Switching iCloud accounts does not show cache from the previous account--## Key Source Files--- [`CodexTokenHistoryStore.swift`](../../../CodexBar/Services/Workflow/CodexTokenHistoryStore.swift)-- [`CodexTokenHistorySync.swift`](../../../CodexBar/Services/Workflow/CodexTokenHistorySync.swift)-- [`WorkflowSyncService.swift`](../../../CodexBar/Services/Workflow/WorkflowSyncService.swift)-- [`WorkflowSyncScheduler.swift`](../../../CodexBar/Services/Workflow/WorkflowSyncScheduler.swift)-- [`WorkflowSyncSettings.swift`](../../../CodexBar/Services/Settings/WorkflowSyncSettings.swift)-- [`CodexWorkflowModels.swift`](../../../CodexBar/Models/CodexWorkflowModels.swift)-- [`CodexBar.entitlements`](../../../CodexBar/Resources/CodexBar.entitlements)diff --git a/Docs/en/DeveloperGuide/ui-and-lifecycle.md b/Docs/en/DeveloperGuide/ui-and-lifecycle.mddeleted file mode 100644index a5b651d..0000000--- a/Docs/en/DeveloperGuide/ui-and-lifecycle.md+++ /dev/null@@ -1,371 +0,0 @@-# UI and App Lifecycle--[简体中文](../../DeveloperGuide/ui-and-lifecycle.md) | English--## `LSUIElement` Constraints--CodexBar is configured as an `LSUIElement` in [`Info.plist`](../../../CodexBar/Resources/Info.plist).--It has no Dock icon or conventional main-window lifecycle. The menu bar, popover, floating panel, Settings window, and notification clicks must all manage app activation and focus explicitly.--The UI declares content in SwiftUI and manages windows through AppKit controllers.--## Focus States Under `LSUIElement`--Development must distinguish among:--- Whether the app is active-- Whether a window is key-- Whether the menu surface is logically presented--These states do not synchronize automatically. Command-Space, for example, makes the app resign active while the user briefly opens Spotlight; that should not necessarily close the menu. A Settings window may already be visible, but it must not retake key status during the menu's closing animation and cause a flash.--The code therefore does not treat `NSApp.isActive` as the sole truth for the menu. It maintains explicit menu-surface state and the current container, then lets event monitors coordinate activation.--## Service Assembly--[`CodexBarAppDelegate.swift`](../../../CodexBar/Controllers/CodexBarAppDelegate.swift) is the composition root for normal mode. [`StatusItemController.swift`](../../../CodexBar/Controllers/StatusItemController.swift) is responsible only for the menu bar and related window orchestration.--### Startup Ordering--Normal-mode assembly reflects dependency direction:--```text-Create settings, data services, view models, and updater- -> Create and install StatusItemController- -> Set up the status item, observers, and hot key- -> Reconcile Hook and start periodic refresh- -> Start notifications and automatic reset- -> Connect Activity Protection callbacks- -> Start the task-glow subscription- -> Start the activity monitor and keep-alive coordination-```--Notifications and sleep prevention consume only snapshots or transitions already published by the monitor; they do not control readers upstream. Controllers connect these services through closures, keeping AppKit containers out of the service layer.--Shutdown reverses the order, except for helper-owned system state. AppDelegate first confirms asynchronously that the Automatic Reset wake schedule is canceled and the sleep-prevention lease is released, then allows process termination. See [Sleep Prevention System](sleep-prevention.md) for the transaction.--## Task Glow--`TaskGlowController` presents activity while both `TaskGlowSettings.isEnabled` and `AdvancedModeSettings.isOperable` are `true`, independently of the main panel's animation setting. It consumes snapshots and terminal events from `CodexActivityMonitor.presentationPublisher`; see [Presentation Updates](activity-monitor.md#presentation-updates).--| Scenario | Presentation rule |-| --- | --- |-| Active tasks exist | Approval waiting takes priority over running |-| 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 Advanced Mode 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 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.--Turning the switch off cancels the preview, retracts the glow quickly to the center, and fades it out. Windows are removed once every display finishes dismissal. Hook unavailability, system sleep, display sleep, or an inactive session cancels the preview; real terminal indicators expire according to wall time during sleep.--The glow uses nonactivating, mouse-transparent `NSPanel` windows across Spaces and full-screen apps. System sleep, display sleep, or an inactive user session removes the windows. On return, valid state resumes according to the current time. Screen configuration changes rebuild the windows; all displays share a motion clock. The clock calculates the cycle from segment durations and speed, preserving progress when speed changes.--## Status Bar Icon--The status icon combines app-server loading state, the menu bar rate-limit setting, and the task-activity snapshot.--Icon priority is:--```text-Account error > Waiting for approval > Running > Latest completion or termination within 10 seconds > Idle-```--When no tasks are active, `CodexActivitySnapshot.statusItemActivity(at:)` selects the latest terminal timestamp. `StatusItemController` schedules expiration 10 seconds after that timestamp, then restores the plain person. It recalculates on wake and cancels the old task on state changes or uninstall.--### Separating Icon State from Tooltip State--`StatusIconState` retains activity, quota, and `ordinaryUsageAllowed` inputs. `StatusItemIconPresentation` publishes changes to symbol name, ordinary-usage restriction state, quota, visibility, and stale state:--- 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 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 transitions--A persistent SwiftUI view lives inside the native `NSStatusBarButton`, with a transparent image preserving automatic spacing. When `ordinaryUsageAllowed == false`, the person and badge use pale orange adapted to light and dark appearances; `true` or an absent value uses the system foreground color. The quota arc uses colors based on the remaining percentage. The hosting view rejects focus and hit testing, leaving mouse actions with the original button.--The arc and person symbol are composited with `drawingGroup()` so the quota arc keeps the same length and color when switching between full-screen and regular desktops.--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.--## Main Panel--The main panel prefers an `NSPopover` with `behavior` set to `applicationDefined` and `animates` set to `false`.--[`MenuSurfaceDismissMonitor.swift`](../../../CodexBar/Controllers/MenuSurfaceDismissMonitor.swift) observes mouse, keyboard, and activation events and requests dismissal through `onDismiss`. [`MenuSurfaceFadeCoordinator.swift`](../../../CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift) performs fades, and `StatusItemController` receives the popover's actual close callback through `NSPopoverDelegate`.--### Open and Close State Machine--`menuSurfaceState` transitions as follows:--```text-hidden -> opening -> shown -> closing -> hidden-```--Operations follow these rules:--- Toggling in `opening` or `shown` starts closing-- Toggling in `closing` finishes the old close, then opens a new surface-- Starting a close cancels the pending fade-in completion task-- A nonanimated close completes state cleanup immediately--`activeMenuSurface` identifies the current container as `none`, `popover`, or `fallbackPanel`. An explicit container close sets it to `none` before closing the window.--`popoverDidClose` handles notifications only for the owned popover when it is closed and disables that host's animations. If the current container is still `popover`, it calls `completeMenuSurfaceClose` to cancel pending tasks, hide side panels, remove event monitors, end presentation state, and schedule auxiliary-window focus restoration.--### Dismiss Event Monitoring--The allowed click region for the main panel is a set:--```text-Current menu window + status item button + all visible side panels-```--A local monitor handles mouse and keyboard events inside the app, a global monitor handles clicks over other apps, and workspace and window observers handle activation changes. Every path ends in the same `onDismiss` callback.--Special rules include:--- Escape consumes the event and closes the surface-- Command-Tab allows the system switch and closes the surface-- Command-Space temporarily suppresses activation dismissal so opening Spotlight does not close the surface accidentally-- After a click, the code pins `NSVisualEffectView` back to inactive so AppKit background emphasis does not cause a brightness jump-- After first installing observers, `Task.yield()` performs a second window acquisition and focus pass in case the popover window was not attached yet-- Focusing the menu window only calls `orderFrontRegardless()` and `makeKey()`, without activating the app again, so an activation transition does not dismiss the native popover over another app's full-screen window; the fallback panel handles app activation in its own presentation entry point--### Fades and Completion Tasks--`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 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--The popover and fallback panel each hold a separate `MenuSurfaceAnimationState`. `allowsAnimations` is set to `true` before presentation, remains enabled during fade-out, and becomes `false` after the surface closes.--When host animation permission is disabled, `CodexStatusMenuView` sets the root transaction's `animation` to `nil` and `disablesAnimations` to `true`. Continuous animations within the main panel use the `mainPanelAnimationsEnabled` environment value, which requires both host permission and the Animation Effects setting. Hiding the host or disabling Animation Effects removes the continuously animated view. Background data refresh continues.--`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. 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.areAnimationsEnabled`. 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, hiding the entire usage area when it is absent. Usage rereads after completion or termination run in the background: the UI shows the terminal state first and expands the metrics when usage arrives, without a timeout message on expiry. Completed and terminated entries in Task Center show total tokens only when usage 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--The status-bar button's screen position may be unavailable or untrusted when a global shortcut fires. [`FallbackPanelController.swift`](../../../CodexBar/Controllers/FallbackPanelController.swift) then presents a floating panel on the screen under the pointer.--### Anchor Validation--A global shortcut may fire before status-item layout completes, while the menu bar is on another display, or when the system temporarily provides no button window. The code validates more than a non-`nil` button:--- The window and screen exist-- The button is visible and has nonempty bounds-- The converted screen rect is valid and meets the minimum size requirement-- The rect intersects the target screen frame within the allowed tolerance--Only 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 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--The main panel can open:--- Activity heatmap details-- Reset Credits details-- Task Center--These panels are mutually exclusive. Opening one closes the others. Each adds its screen region to the main surface's extra hit regions, so moving or clicking between the main and side panels does not dismiss them accidentally.--All detail panels implement `MenuSideDetailPanel` and register in the `sideDetailPanels` array. Mutual exclusion, main-surface closing, and hit testing all iterate over this one registry.--Heatmap hover requests animate the dismissal of other side panels. Click requests for Reset Credits and Task Center close other side panels immediately.--Closing 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 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.--With Advanced Mode 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 in a repeating cycle. It pauses or resumes its timeline using its `NSView` window visibility, independently of Animation Effects.--Related controllers include:--- [`HeatmapDetailPanelController.swift`](../../../CodexBar/Controllers/HeatmapDetailPanelController.swift)-- [`ResetCreditsPanelController.swift`](../../../CodexBar/Controllers/ResetCreditsPanelController.swift)-- [`ActivityCenterPanelController.swift`](../../../CodexBar/Controllers/ActivityCenterPanelController.swift)-- [`SidePanelSupport.swift`](../../../CodexBar/Controllers/SidePanelSupport.swift)--## Settings and Logs Windows--Separate `HostingWindowController` instances manage `NSWindow` for Settings and Logs.--When opening settings or logs, `HostingWindowController` allows the target window to become key and activates the app. `AuxiliaryHostingWindow` can become key but cannot become the main window.--Context-menu actions wait until menu tracking finishes before running, avoiding window creation or activation inside AppKit's menu event loop.--### Auxiliary Window Retention and Placement--`HostingWindowController` lazily creates and reuses one window:--- `isReleasedWhenClosed = false`: closing hides it and preserves the window object and SwiftUI state-- `.moveToActiveSpace`: reopening follows the current Space instead of switching the user back to an old desktop-- Placement prefers centering on the status item's screen, then falls back to the window screen or main screen-- A minimized window is deminiaturized before activation--The Settings window sizes to the current tab, keeps its top edge fixed, and stays within the visible screen. `ScrollView` handles content taller than the available screen height.--SwiftUI may report height before window creation finishes. `SettingsWindowController` caches the latest valid measurement and applies it once `HostingWindowController.window` is ready.--Secondary panels for main-panel layout, task glow, notifications, Automatic Reset, and sleep prevention are created on first use, then reuse their content and required height subscriptions.--These settings child panels use a keyable `KeyableBorderlessPanel`. Opening a panel preserves focus in the Settings window; clicking a text field begins editing. Closing a panel ends native editing, and the color field validates and synchronizes its display in the end-editing callback. The main panel's Heatmap, Reset Credits, and Task Center details use a nonactivating `NonactivatingSidePanel`. When a settings child panel closes, `SidePanelSupport.orderOut` restores focus to its parent only if that child panel is still the key window. If focus has moved to another window, parent focus is not restored.--When Automatic Reset or Prevent System Sleep changes from off to on, `AppSettingsView` presents a shared confirmation through `HelperFeatureConfirmation`. It combines guidance from `KeepAliveController.HelperStatus` with the feature description and writes enabled state only after user confirmation. An enabled settings row in `.requiresApproval` shows `Open System Settings`.--Each secondary-settings entry uses its own availability decision:--- Main Panel Layout is always available-- Task Glow requires `TaskGlowSettings.isEnabled` and `AdvancedModeSettings.isOperable` to be `true`, with no Advanced Mode update in progress-- Notifications reads `NotificationSettings.canShowOptions`-- Automatic Reset requires `AutoResetSettings.isEnabled` and `KeepAliveController.helperStatus == .enabled`-- Sleep prevention reads `KeepAliveController.canShowOptions`--When a condition becomes false, Settings sends the corresponding `close` action so an unavailable child panel does not remain visible. Automatic Reset and sleep-prevention rows show no status explanation while their main switches are off.--`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 `updateAdvancedModeEnabled(_:)` 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 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.--### Proxy Configuration Dialog--`CodexBarAppDelegate` owns `CodexProxySettings` and injects it into Settings through the window controllers. `AppSettingsView` presents `ProxySettingsView` in a SwiftUI `sheet`, closing side settings panels first.--Without a configuration, clicking the row or toggle opens the dialog. With one saved, the row opens the dialog and the toggle independently enables or disables it. Presentation loads the draft from local preferences; dismissal cancels tests and clears the in-memory password draft. The top-right clear menu depends on whether a saved record exists and remains available when decoding fails.--In About, the reconnect button sits immediately after the Codex Versions title, with the source picker at the end of the row. Both are disabled during reconnection and refresh; Reconnect is also disabled when no source is available.--The reconnect button creates its continuous drawing or wiggle animation only while the Settings window is visible and reconnection or refresh is in progress. `SettingsWindowController` updates animation permission from window occlusion, minimization, and close notifications. Hiding the window removes the entire animated branch; becoming visible recreates it according to the current busy state. Switching away from About removes the version section through the existing page branches. Keyboard focus does not determine animation permission.--## Global Shortcut--[`GlobalHotKeyController.swift`](../../../CodexBar/Controllers/GlobalHotKeyController.swift) uses the Carbon Hot Key API.--Shortcut constraints:--- At least two modifier keys-- Reject `Command-Space`-- Reject `Command-Tab`-- Roll back to the previous working setting if system registration conflicts-- Reregister immediately after a setting change--The Carbon API fits a menu bar app without a Dock icon and avoids a global keyboard event tap or Input Monitoring permission.--Registration uses try-before-swap:--1. Install a temporary handler and hot key for the candidate shortcut-2. Release the current registration only after the candidate succeeds-3. On failure, clean up candidate resources and restore the previous setting--`GlobalHotKeyRegistration` clears Carbon references on explicit invalidation and deinitialization.--## Automatic Refresh and Panel Opening--App-server state refreshes at the selected data update interval: 1, 2, 3, 5, or 10 minutes, defaulting to 1 minute. Once the main panel's fade-in finishes and the panel is still visible, `refreshIfNeeded` requests data if no countdown origin exists or the selected interval has elapsed. Both successful and failed results reset the countdown. Changing the interval reschedules the wait without canceling an in-flight request.--The main panel shows a refresh countdown. Double-clicking the account icon requests an immediate manual refresh.--Ordinary refreshes are ignored while a refresh or reconnect is in progress. Operations requiring a follow-up use `refreshAfterCurrent` to retain one pending trigger and run it after the current request finishes.--The fade-in completion callback triggers Hook configuration reconciliation, a local-statistics refresh check when Advanced Mode is enabled, and an account, rate-limit, and usage refresh check in that order. Closing the panel before fade-in finishes cancels the completion task and its pending refresh work.--## Localization and Formatting--Simplified Chinese and English interface strings are in [`Localizable.xcstrings`](../../../CodexBar/Resources/Localizable.xcstrings).--Percentages, durations, and some time displays use system regional settings. `CodexDateFormat` fixes date keys and ranges to `yyyy-MM-dd`; the settings page’s last-upload time and reset-credit details use local time in `yyyy-MM-dd HH:mm:ss`. Localized strings do not drive state-machine decisions.--## Automatic Updates--[`AppUpdater.swift`](../../../CodexBar/Services/Updates/AppUpdater.swift) wraps Sparkle:--- The appcast URL comes from app configuration-- Automatic checks run every 3,600 seconds-- Update UI is triggered from settings and the main panel’s new-version notice-- After an update, CodexBar checks CodexBarHelper fingerprint and registration state separately if the helper changed--Release scripts require Developer ID, signing, and notarization credentials and are not part of routine local builds.--## Manual Validation Matrix--- 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 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 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 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-- Activity-card and Task Center text colors and animations match running, approval-waiting, completed, and terminated states; disabling Animation Effects keeps text static, closing the panel stops continuous animations, and scrolling Task Center emits particles only from visible waiting text-- With Token Usage at different positions in the main-panel order, heatmap details align to the complete heatmap area's top edge when possible and fall back to the main panel's bottom edge when the detail height does not fit-- The global shortcut opens the panel with both valid and invalid status-bar anchors-- 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 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 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-- Panel-open refresh does not stall animation or issue duplicate requests-- 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 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 Files--- [`CodexBarAppDelegate.swift`](../../../CodexBar/Controllers/CodexBarAppDelegate.swift)-- [`StatusItemController.swift`](../../../CodexBar/Controllers/StatusItemController.swift)-- [`FallbackPanelController.swift`](../../../CodexBar/Controllers/FallbackPanelController.swift)-- [`MenuSurfaceDismissMonitor.swift`](../../../CodexBar/Controllers/MenuSurfaceDismissMonitor.swift)-- [`MenuSurfaceFadeCoordinator.swift`](../../../CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift)-- [`GlobalHotKeyController.swift`](../../../CodexBar/Controllers/GlobalHotKeyController.swift)-- [`SettingsWindowController.swift`](../../../CodexBar/Controllers/SettingsWindowController.swift)-- [`LogWindowController.swift`](../../../CodexBar/Controllers/LogWindowController.swift)-- [`CodexStatusMenuView.swift`](../../../CodexBar/Views/Menu/CodexStatusMenuView.swift)-- [`StatusItemIconView.swift`](../../../CodexBar/Views/Menu/StatusItemIconView.swift)-- [`CodexActivityCard.swift`](../../../CodexBar/Views/Menu/CodexActivityCard.swift)diff --git a/Docs/en/README.md b/Docs/en/README.mddeleted file mode 100644index 755d036..0000000--- a/Docs/en/README.md+++ /dev/null@@ -1,33 +0,0 @@-# CodexBar Documentation--[简体中文](../README.md) | English--## User Guide--- [Installation and Quick Start](UserGuide/getting-started.md)-- [Main Panel and Menu Bar](UserGuide/main-panel.md)-- [Live Tasks and Advanced Mode](UserGuide/advanced-mode.md)-- [Notifications and Alerts](UserGuide/notifications.md)-- [Prevent System Sleep](UserGuide/sleep-prevention.md)-- [Data, Sync, and Privacy](UserGuide/sync-data-privacy.md)-- [Settings Reference](UserGuide/settings.md)-- [Troubleshooting](UserGuide/troubleshooting.md)--## Developer Guide--- [Architecture](DeveloperGuide/architecture.md)-- [Design Principles and Key Decisions](DeveloperGuide/design-decisions.md)-- [app-server Data Flow](DeveloperGuide/app-server.md)-- [Hook Collection and Historical Aggregation](DeveloperGuide/hook-and-aggregation.md)-- [Live Task Monitoring](DeveloperGuide/activity-monitor.md)-- [Sleep Prevention](DeveloperGuide/sleep-prevention.md)-- [CloudKit Sync](DeveloperGuide/sync.md)-- [Notifications](DeveloperGuide/notifications.md)-- [UI and Lifecycle](DeveloperGuide/ui-and-lifecycle.md)-- [Data and Privacy Boundaries](DeveloperGuide/data-and-privacy.md)-- [Development and Validation](DeveloperGuide/development.md)--## Online Resources--- [Runtime Architecture](https://codexbar.zabrian.app/architecture)-- [Performance Report](https://codexbar.zabrian.app/performance)diff --git a/Docs/en/UserGuide/README.md b/Docs/en/UserGuide/README.mddeleted file mode 100644index 4c0e05c..0000000--- a/Docs/en/UserGuide/README.md+++ /dev/null@@ -1,23 +0,0 @@-# CodexBar User Guide--[简体中文](../../README.md#用户指南) | English--## Contents--| Document | Contents |-| --- | --- |-| [Installation and Quick Start](getting-started.md) | Requirements, installation, basic controls, and feature dependencies |-| [Main Panel and Menu Bar](main-panel.md) | Menu bar states, account, rate limits, token heatmap, and Task Center |-| [Live Tasks and Advanced Mode](advanced-mode.md) | What Advanced Mode does, how to enable it, task states, and historical metrics |-| [Notifications and Alerts](notifications.md) | Triggers, defaults, sounds, and haptic feedback for each notification type |-| [Preventing System Sleep](sleep-prevention.md) | Activation conditions, protection options, CodexBarHelper authorization, and coexistence with external sleep settings |-| [Data, Sync, and Privacy](sync-data-privacy.md) | Local data, iCloud sync, rebuilding data, and network boundaries |-| [Settings Reference](settings.md) | Every setting on the General, Advanced, and About pages, including Automatic Reset |-| [Troubleshooting](troubleshooting.md) | Sign-in, Hook, notifications, Automatic Reset, sleep prevention, sync, and logging issues |--## Common Names--- Advanced Mode: enables live tasks and daily activity statistics-- CodexBarHelper: the included background service for sleep prevention and Automatic Reset wakes--Back to the [CodexBar README](../../../README.en.md).diff --git a/Docs/en/UserGuide/advanced-mode.md b/Docs/en/UserGuide/advanced-mode.mddeleted file mode 100644index 5535d9d..0000000--- a/Docs/en/UserGuide/advanced-mode.md+++ /dev/null@@ -1,50 +0,0 @@-# Live Tasks and Advanced Mode--[简体中文](../../UserGuide/advanced-mode.md) | English--Advanced Mode provides live task status, task notifications, haptics, task-based sleep prevention, and daily session, turn, and tool-call statistics. It also enables syncing daily activity statistics and rollout token history. Rebuild Data recalculates both types of retained local history.--## Enable Advanced Mode--1. Open `Settings > Advanced`-2. Enable `Advanced Mode` and wait for validation-3. Start a Codex task and check its status in the main panel--Advanced Mode requires the Codex currently in use to be `0.153.0` or later. If the version warning remains after upgrading, click `Reconnect` in `Settings > About`. For other errors, see [Troubleshooting](troubleshooting.md#advanced-mode-cannot-be-enabled-or-validated).--CodexBar automatically checks and repairs enabled Hook configuration, preserving handlers belonging to users and other apps. If Codex is confirmed to be below the minimum version, Advanced Mode is disabled and CodexBar removes its handlers; enable Advanced Mode again after upgrading Codex. Configuration is retained for the next check if the connection or version is temporarily unavailable.--## Task States--| State | Meaning |-| --- | --- |-| Running | Codex is processing the task |-| Waiting for Approval | You need to approve the next action |-| Recently Completed | A turn ended; its result is not necessarily successful |-| Recently Terminated | An interruption or other terminal signal confirmed termination; no completion notification is sent |--After `Stop`, the task shows “Finishing up”, with approval waiting taking priority while a subagent still waits. A completion notification is sent after the turn is confirmed complete and the notification settings are satisfied; an interruption during that time is shown as terminated.--Interruption ends only the matching turn; a newer turn in the same session stays active. Task-based sleep prevention releases once all eligible tasks end.--Subagent activity is combined with its parent task. Internal automatic-review tasks and tasks whose origin remains unconfirmed do not appear as live tasks or trigger Task Glow, task alerts, or sleep prevention; their activity still contributes to daily statistics. Once the same session and turn have been confirmed as a normal task, later events with a temporarily unknown origin continue updating its state.--When the main agent or a subagent waits for approval, progress from another agent does not clear its wait. The card stays in the waiting state while any user approval wait remains in that task.--Tasks with a known origin whose session cannot be identified show an orange anonymous icon. You can view them, but they do not trigger notifications or haptics, prevent sleep, or participate in Stalled Task Protection.--[Stalled Task Protection](sleep-prevention.md#stalled-task-protection) may hide running tasks that stop making progress. They reappear when progress resumes.--## Daily Statistics--Hover over a day in the main-panel heatmap to see sessions, turns, tool calls, permission requests, context compactions, subagents, and the most-used model in the left column, with session token totals on the right. Token usage belongs to the root turn’s start date, unlike daily activity counts. See [Token Usage and Heatmap](main-panel.md#token-usage-and-heatmap).--Sessions and turns are deduplicated within each day; activity continuing into another day counts toward that day. Sessions with only a session-end event and turns with only completion-candidate or interruption events do not count as active that day. Tool calls use the larger of the start and end event counts.--## Disable Advanced Mode--Disabling Advanced Mode 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.--Back to the [User Guide](README.md).diff --git a/Docs/en/UserGuide/getting-started.md b/Docs/en/UserGuide/getting-started.mddeleted file mode 100644index 3bb60ad..0000000--- a/Docs/en/UserGuide/getting-started.md+++ /dev/null@@ -1,73 +0,0 @@-# Installation and Quick Start--[简体中文](../../UserGuide/getting-started.md) | English--## Requirements--- macOS 15.0 or later-- [Codex CLI](https://github.com/openai/codex) installed and signed in, or ChatGPT App or Codex App with bundled Codex installed-- The Codex currently in use must be `0.145.0` or later-- Advanced Mode requires the Codex currently in use to be `0.153.0` or later-- Cross-device sync requires an available iCloud account on the Mac--By default, CodexBar automatically prefers a globally installed Codex CLI. If it cannot find one, it tries the Codex bundled with ChatGPT App and Codex App. You can select a source under Settings > About > Codex Versions > Source.--## Installation--### Homebrew--```bash-brew install --cask bob-zebedy/tap/codexbar-```--### DMG--1. Download the latest DMG from [GitHub Releases](https://github.com/bob-zebedy/CodexBar/releases)-2. Open the DMG and drag CodexBar into Applications-3. Launch CodexBar from Applications--## First Launch--CodexBar is a menu bar app, so it does not show an icon in the Dock after launch:--1. Find the CodexBar icon in the menu bar at the top of the screen-2. Left-click the icon to open the main panel-3. Wait for the initial account and usage refresh to finish-4. If the panel says you are not signed in, sign in through the active Codex installation first-5. For live tasks, task notifications, sleep prevention, or Hook metrics, enable Advanced Mode under `Settings > Advanced`--CodexBar refreshes account, rate-limit, and token usage data every minute by default. Choose 1, 2, 3, 5, or 10 minutes under `Settings > Advanced > Data Update Interval`. Double-click the account icon in the main panel to refresh immediately.--## Basic Controls--| Action | Result |-| --- | --- |-| Left-click the menu bar icon | Open or close the main panel |-| Right-click or Control-click the menu bar icon | Open the Settings, Logs, and Quit menu |-| `⌘⇧E` | Open or close the main panel with the default global shortcut |-| `⌘,` | Open the Settings window |-| `⌘L` | Close the main panel and open the Logs window while the panel is open |-| Double-click the account icon | Refresh account, rate-limit, and usage data immediately |-| Double-click the account email | Toggle email blurring |-| Hover over a heatmap cell | View token and Hook metrics for that day |-| Click the activity card | Open Task Center for concurrent tasks |-| Click `Banked Resets` | View the expiration time of each batch |-| `Settings > Advanced > Automatic Reset` | Configure automatic use and lead time |--The global shortcut opens the main panel on the screen under the pointer when possible. If the menu bar anchor is unavailable, CodexBar uses a standalone floating panel.--## Enable More Features--- [Advanced Mode](advanced-mode.md): live tasks, daily activity statistics, and task-based sleep prevention-- [System Notifications](notifications.md): task and quota alerts, requiring macOS notification permission-- [Automatic Reset](settings.md#automatic-reset): use banked resets shortly before expiration; may briefly wake your Mac-- [Prevent System Sleep](sleep-prevention.md): keep your Mac awake during long tasks, requiring background-service approval-- [Cross-Device Sync](sync-data-privacy.md): combine Hook statistics across Macs, requiring iCloud sign-in--## Language and Region--CodexBar provides Simplified Chinese and English interfaces. By default, it follows the macOS per-app language preference.--To choose a language specifically for CodexBar, use Language & Region in macOS System Settings.--Next, read [Main Panel and Menu Bar](main-panel.md) or the [Settings Reference](settings.md).diff --git a/Docs/en/UserGuide/main-panel.md b/Docs/en/UserGuide/main-panel.mddeleted file mode 100644index 496dfed..0000000--- a/Docs/en/UserGuide/main-panel.md+++ /dev/null@@ -1,153 +0,0 @@-# Main Panel and Menu Bar--[简体中文](../../UserGuide/main-panel.md) | English--## Menu Bar Icon--CodexBar combines a person symbol with an optional circular rate-limit arc:--| Appearance | Meaning |-| --- | --- |-| Plain person | Default or idle state |-| Pale orange person and badge | Account data indicates ordinary usage is restricted |-| Slashed person | You are signed out, initialization failed, or trusted rate-limit and usage data is unavailable |-| Clock badge | At least one task is running |-| Key badge | At least one task is waiting for approval |-| Shield with a checkmark | A task finished within the last 10 seconds |-| Shield with an exclamation mark | A task was terminated within the last 10 seconds |-| Circular arc with a bottom gap | Remaining percentage in the selected rate-limit window, using the same colors as the panel |--Account errors take priority, followed by waiting for approval, running, and the latest completion or termination within 10 seconds. The most recent timestamp determines which terminal state appears.--The person symbol grows when the quota arc is hidden.--Hover over the menu bar icon to see the current task state, project name, elapsed time, number of concurrent tasks, and remaining percentage in the selected rate-limit window.--Cached rate-limit data dims the icon and arc. Zero quota retains the empty track; unavailable or disabled quota hides the arc.--## Layout Customization--Reorder and show or hide sections in `Settings > General > Main Panel Layout`, with undo and redo support. See [Settings Reference](settings.md#main-panel-layout).--## Account--- Shows the signed-in account or account type-- Identifies Enterprise, Team, Business, ProMax, Pro, ProLite, Plus, Go, Edu, and Free plans-- Double-clicking the account icon refreshes account, rate-limit, and usage data immediately-- Double-clicking the email toggles blurring-- Shows `Not signed in` when no account is signed in-- Shows the minimum-version requirement when the Codex currently in use is too old-- Shows `Initialization failed` when the Codex connection cannot initialize--The About page in Settings shows the connection failure reason; the Logs window provides complete requests and responses.--## Rate Limits--CodexBar shows every rate-limit group and window returned by Codex.--Each rate-limit window includes:--- A window name, such as `5 Hours` or `Weekly`-- Remaining percentage-- A segmented progress bar-- The next reset time--When `Animation Effects` is enabled, each segmented progress bar fills from zero to its current remaining percentage whenever the main panel opens.--Glass dividers use a slowly flowing gradient independently of `Animation Effects`; the animation pauses while their window is hidden.--The primary rate-limit group may also show:--- Available credits or unlimited-credit status-- Available banked resets-- The expiration time for each batch of banked resets--Click `Banked Resets` to view expiration times by batch. The entry appears when the available count is greater than `0`.--## Token Usage and Heatmap--Account usage comes from app-server. The summary area shows:--- All-time token usage-- Highest daily token usage-- Current usage streak-- Longest usage streak-- Longest task duration--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.--Hover over a day to see its date, token count, and usage intensity.--When Advanced Mode is enabled, the details also include:--- Most-used model-- Sessions-- Turns-- Subagents-- Tool calls-- Permission requests-- Context compactions--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.--Heatmap colors, the token count beside the date, and intensity come from app-server. Session tokens in the right column come from local rollouts and iCloud history, with a different scope. See [Data, Sync, and Privacy](sync-data-privacy.md#historical-token-replay) for backfill, incremental reads, and rebuilding.--## Activity Card--The activity card prioritizes tasks waiting for approval, then running tasks. With no active tasks, it shows the latest completion or termination by end time, with termination taking precedence on ties.--The card shows the following fields when available:--- Project name-- Model and reasoning effort-- Current tool or execution stage-- Running or waiting duration-- Active subagent count-- Number of other concurrent tasks-- Anonymous-task icon--While sleep prevention is active, a teal sun badge appears on the right side of the activity card. Hover over it to see the sleep-prevention source. The badge rotates while Animation Effects is enabled and stays static when it is disabled.--Tasks whose session cannot be identified show an orange anonymous icon with the tooltip `Anonymous tasks do not prevent sleep`.--The activity card’s `+N` shows the total number of other active tasks.--Click a populated activity card to open Task Center. In both views, status-text colors follow task state. With Animation Effects enabled, running status text shimmers and orange particles appear around approval-waiting text. Disabling the setting keeps the colored text static.--### Token Usage for the Current Turn--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. After completion or termination is confirmed, background usage queries run for up to 30 seconds, displaying a complete total when available and accepting updates until the deadline. The terminal state appears immediately, without a query countdown or loading indicator. If usage is still unavailable at expiry, the usage area stays hidden; values already obtained remain visible. These values cover the current turn and its subagents.--Total equals input plus output. Cached input and cache write are included in input; reasoning is included in output. These subsets must not be added to the total again. Cache-H is cached input divided by input; the card shows `—` when input is zero. Cached shows the number of input tokens served from cache; Cache-W shows cache writes.--## Task Center--Task Center groups tasks into:--- Waiting for Approval-- Running-- Recently Completed-- Recently Terminated--Recently completed and terminated records remain for 10 minutes. Completion means a turn ended, without implying success. Termination records include interruptions and other task terminations, and do not trigger completion notifications.--Recently completed and terminated entries show total tokens for the turn when available, using K/M/B units. Running and waiting entries show task status; the main-panel activity card displays usage for the task it summarizes.--## Footer Status--The bottom of the main panel shows:--- Data update time-- Countdown to the next automatic refresh-- iCloud sync status: off, syncing, synced, or failed-- Available-update indicator--When a new version is available, double-click the update indicator to start the update.--Back to the [User Guide](README.md)diff --git a/Docs/en/UserGuide/notifications.md b/Docs/en/UserGuide/notifications.mddeleted file mode 100644index 7685548..0000000--- a/Docs/en/UserGuide/notifications.md+++ /dev/null@@ -1,86 +0,0 @@-# Notifications and Alerts--[简体中文](../../UserGuide/notifications.md) | English--## Enabling Notifications--1. Open `Settings > Advanced`-2. Enable `System Notifications`-3. Allow notifications in the macOS permission dialog-4. Click the slider button on the right to configure individual notification types--If system permission is denied, Settings shows an `Open System Settings` button.--System Notifications is off by default. Turning it off disables all CodexBar system notifications and task haptic feedback.--## Notification Types--| Notification | Trigger | Default option | Additional requirement |-| --- | --- | --- | --- |-| Task completed | A task finishes after running for at least the selected duration | On, 1 minute | Advanced Mode |-| Waiting for approval | A task starts waiting for user approval | On | Advanced Mode |-| Low rate limit | Remaining quota reaches the alert threshold | On, 10% | None |-| Rate limit reset | A rate-limit window previously observed as consumed returns to an unconsumed state | On | None |-| Banked resets expiring | Banked resets enter the 7-day expiration window | On | Available banked resets |-| Automatic Reset | An automatic reset explicitly returns success or reports that it already succeeded | On | Automatic Reset, its notification option, and System Notifications |-| Automatic Reset failed | Authentication failure pauses the task, a protocol error stops it, or this Mac explicitly observes expiration | Shares the success-notification setting | Automatic Reset, its notification option, and System Notifications |-| Low Battery Protection | Low Battery Protection successfully restores system sleep | On | Sleep prevention and Low Battery Protection |-| Keep-awake limit | The time limit is reached and system sleep is successfully restored | On | Sleep prevention and a finite time limit |-| Stalled Task Protection | A running task makes no progress for the selected protection interval | Fixed behavior | Advanced Mode and Prevent System Sleep |--Stalled Task Protection has no separate notification option and uses the default system sound.--Even if its notification cannot be delivered, a confirmed stalled task is still hidden and stops participating in sleep prevention.--Anonymous tasks do not trigger completion, approval, or Stalled Task Protection notifications or task haptic feedback, but remain visible in the activity card and Task Center.--## Thresholds--| Setting | Options |-| --- | --- |-| Minimum duration for completed tasks | 30 seconds, 1 minute, 2 minutes, 5 minutes |-| Low rate-limit threshold | 5%, 10%, 25% |--A low-quota alert fires when remaining quota drops to or below the threshold, including when the first reading after startup is already low. A known reset time is required, and each reset cycle is notified only once.--Banked resets are checked for reminders at 7, 6, 5, 4, 3, 2, and 1 day before expiration.--## Automatic Reset Notifications--Automatic Reset sends alerts, subject to notification settings, when it succeeds or stops because of sign-in, configuration, or expiration issues. Temporary network failures retry in the background.--One reset may produce both “Automatic Reset” and “Quota Reset” notifications: one reports the operation result, the other the quota change. Success and failure share the Automatic Reset Notifications switch and sound.--When multiple Macs try a reset, each device receiving success confirmation may notify. Devices that only discover the reset has disappeared do not notify. Each failure reason is reported at most once per banked reset.--## Notification Sounds--Each configurable notification can use:--- Default notification sound-- No sound-- Any system alert sound available on the current Mac-- CodexBar's built-in Modern and Material sounds--You can preview any sound other than the default or silent options in Settings.--If a saved sound is unavailable on the current Mac, CodexBar falls back to the default notification sound.--## Haptic Feedback--`Task Haptic Feedback` is off by default. When enabled, the trackpad vibrates when a task finishes or starts waiting for approval.--Haptic feedback does not require macOS notification permission, but it still follows CodexBar's System Notifications switch and Advanced Mode status.--## Codex TUI Notifications--This option controls Codex’s own notifications independently of CodexBar notifications.--## Notification Interaction--- Banners, Notification Center entries, and sounds still appear while CodexBar is in the foreground-- Clicking any CodexBar notification opens the main panel-- When a task is no longer waiting for approval, its waiting notification is removed from Notification Center-- When a task resumes progress or no longer meets the Stalled Task Protection conditions, its notification is removed from Notification Center--Back to the [User Guide](README.md)diff --git a/Docs/en/UserGuide/settings.md b/Docs/en/UserGuide/settings.mddeleted file mode 100644index 6f5005b..0000000--- a/Docs/en/UserGuide/settings.md+++ /dev/null@@ -1,127 +0,0 @@-# Settings Reference--[简体中文](../../UserGuide/settings.md) | English--Right-click or Control-click the menu bar icon and choose `Settings`, or press `⌘,`.--## General Settings--| Setting | Purpose | Default or initial state |-| --- | --- | --- |-| Main Panel Layout | Reorder and show or hide Account, Tasks, Quota, Usage, and Status | All visible; Tasks is off when Advanced Mode is disabled |-| Animation Effects | Control quota-bar and heatmap entrance animations, sun-badge rotation, and status-text animations in the activity card and Task Center | On |-| Glow Effect | Show task status with colors along the top of each display; requires Advanced Mode to be enabled and verified | Off |-| Launch at Login | Start CodexBar when you sign in to your Mac | Follows the system login-item state |-| Automatically Check for Updates | Periodically check for CodexBar updates | Follows the current update setting |-| Menu Bar Quota Indicator | Show the remaining allowance in a selected window | Primary quota |-| Global Shortcut | Toggle the main panel from any app | `⌘⇧E` |--### Main Panel Layout--Click the options button to drag sections into order or toggle visibility, keeping at least one section visible. Use `⌘Z` to undo and `⌘⇧Z` to redo. Hiding a section does not stop its features.--Disabling Advanced Mode hides Tasks; switching Advanced Mode from off to on shows Tasks automatically. You can still hide Tasks manually while Advanced Mode is enabled, and restarting the app preserves that choice. If Tasks was the only visible section, disabling Advanced Mode enables Account automatically.--### Glow Effect--Shows task status along the top of each display. Advanced Mode must be enabled and verified. The switch is off by default and independent of the main panel's Animation Effects setting. Once enabled, click the options button to adjust status colors, animation speed, brightness, and end duration.--Turning 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 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 |-| --- | --- |-| Cyan moving glow | Tasks are running |-| Orange pulsing glow | Waiting for approval; takes priority over running |-| Green | Task completed |-| Red | Task terminated, including interruptions |--Colors 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 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 Advanced Mode 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.--### Menu Bar Quota Indicator--Choose the quota window to display. Turning the indicator off and back on restores the last choice. Faded data indicates cached quota.--### Global Shortcut--A shortcut needs at least two modifier keys and cannot use `Command-Space` or `Command-Tab`. Conflicting combinations produce a warning. You can clear the shortcut or restore the default.--## Advanced Settings--| Setting | Purpose | Default |-| --- | --- | --- |-| [Advanced Mode](advanced-mode.md) | Enable live tasks and daily activity statistics | Off if not installed |-| [System Notifications](notifications.md) | Configure notification types, thresholds, sounds, and haptics | Main switch off |-| Automatic Reset | Use banked resets shortly before expiration | Off, 30-minute lead time |-| [Prevent System Sleep](sleep-prevention.md) | Keep your Mac awake while eligible tasks run | Off |-| [Cross-Device Sync](sync-data-privacy.md) | Combine daily activity statistics and session token usage through iCloud | Off |-| Network Proxy | Configure the proxy for CodexBar’s Codex service connection | Off |-| Data Update Interval | Set the automatic update interval for account data, quota, and accompanying historical maintenance and sync | 1 minute |-| [Rebuild Data](sync-data-privacy.md#rebuild-data) | Recalculate activity statistics and session token usage for selected dates in the background | Manual |--### Data Update Interval--Choose 1, 2, 3, 5, or 10 minutes. The default is 1 minute, saved locally. The interval starts when the previous refresh result is committed. Changing it immediately recalculates the remaining wait; an overdue refresh runs shortly afterward. Manual refresh resets the countdown. Live task monitoring is unaffected.--### Network Proxy--Click the setting row and enter a server address and port. HTTP, HTTPS, hostnames, IPv4, and IPv6 are supported; ports must be within `1–65535`. Authentication requires a username; the password may be empty.--An HTTP proxy can forward HTTPS requests. Select HTTPS only if the proxy port itself supports TLS with a valid certificate.--- `Test Connection` checks unsaved settings and can be canceled; it does not save or enable the proxy-- `Save` applies the configuration; after the first save, enable the switch on the setting row-- `Cancel` discards this edit-- `⋯ > Delete Configuration` removes the configuration and password and disables the proxy, even if the saved configuration is damaged-- Turning off the row’s switch retains the configuration for later use--Passwords are hidden until you hover over the field. The proxy affects only CodexBar’s Codex service connection, and its password is stored locally in plain text. See [Data, Sync, and Privacy](sync-data-privacy.md).--### Automatic Reset--Automatic Reset uses banked resets shortly before expiration. Every enable action requires confirmation. If the background service needs approval, click `Open System Settings` below the row and allow CodexBar to run in the background.--Once enabled and CodexBarHelper is approved, use the options button to choose a lead time of `15 Minutes`, `30 Minutes`, `1 Hour`, `2 Hours`, `4 Hours`, or `6 Hours`. The default is `30 Minutes`.--- Processes the earliest-expiring available reset first, rechecking sign-in and availability before use-- May briefly wake your Mac without lighting the display or enabling Prevent System Sleep-- Retries temporary failures for up to 5 minutes per round; later refreshes may try again-- Rechecks unexpired resets when the Mac wakes or the app restarts-- Cancels scheduled wakes when disabled or when the app quits-- Multiple Macs trying the same banked reset do not consume it multiple times--Automatic Reset runs independently of notifications. Configure result alerts in [Notification Options](notifications.md#automatic-reset-notifications). Its settings apply only to the current Mac.--## About--| Item | Action or meaning |-| --- | --- |-| Source | Automatic selection prefers Codex CLI, then Codex bundled with ChatGPT App or Codex App; manual selection is also available |-| Reconnect | Reconnect using the selected source; use after upgrading Codex to switch immediately to the new version |-| Codex CLI / Codex App | View detected versions; click a path to copy it |-| Currently Using | Source and version used by the current connection |-| Unavailable (Codex source) | A previously used or selected source can no longer be found |-| CodexBar Helper | View the background component's installation and authorization status |-| CodexBar Version / Check for Updates | View the version and check for updates |-| GitHub Project | Open the project page |-| Quit CodexBar | Exit the app |--Source selection is temporarily disabled while connecting. Connection failure reasons appear below the version area to help you troubleshoot or choose another source.--CodexBar Helper status always appears in About, regardless of the Automatic Reset and sleep prevention switches:--| Status | Meaning |-| --- | --- |-| Not Installed | Not yet registered, with no detected component or installation issue; normal on first use |-| Not Authorized | Registered, but still needs permission to run in the background |-| Authorized | Background execution is approved and no component issue is currently detected |-| Unavailable | Components are missing, configuration or signatures are invalid, or installation failed while unregistered |--A detected component issue displays Unavailable even if authorization was previously granted. See [CodexBarHelper Cannot Be Registered](troubleshooting.md#codexbarhelper-cannot-be-registered).--Back to the [User Guide](README.md).diff --git a/Docs/en/UserGuide/sleep-prevention.md b/Docs/en/UserGuide/sleep-prevention.mddeleted file mode 100644index 98f3727..0000000--- a/Docs/en/UserGuide/sleep-prevention.md+++ /dev/null@@ -1,63 +0,0 @@-# Prevent System Sleep--[简体中文](../../UserGuide/sleep-prevention.md) | English--CodexBar can keep your Mac awake while tasks run and restore sleep when tasks finish or a protection condition takes effect.--## Enable and Activate--1. Enable Advanced Mode in `Settings > Advanced`-2. Enable `Prevent System Sleep` and confirm-3. If background approval is required, click `Open System Settings` and allow CodexBar to run in the background--Sleep prevention requires CodexBar to be running, Hook and its background service to be available, and an eligible task to exist. Low battery or the duration limit stops it; when conditions recover, task state determines whether it resumes. The sun badge on the activity card indicates that sleep prevention is active.--Anonymous tasks and tasks hidden by Stalled Task Protection do not prevent sleep.--## Options--Click the options button beside the sleep-prevention setting:--| Option | Purpose | Default | Choices |-| --- | --- | --- | --- |-| Keep Awake While Waiting | Remain awake while waiting for your approval | Off | On or off |-| Keep Display Awake | Prevent display sleep, screen saver, and idle locking | Off | On or off |-| Keep-Awake Limit | Limit cumulative sleep prevention in one cycle | 12 hours | 1, 2, 4, 8, 12, or 24 hours; unlimited |-| Stalled Task Protection | Hide running tasks that stop making progress | 1 hour | 30 minutes; 1, 2, or 4 hours |-| Low Battery Protection | Restore sleep at low charge while on battery | Off | Off; 5%, 10%, 15%, 20%, or 25% |--Low Battery Protection is hidden on Macs without a built-in battery.--## Waiting and Display Wake--By default, only running tasks prevent sleep. Enabling the waiting option keeps the Mac awake while approval requests are unattended, until the duration limit is reached or task state changes.--Keep Display Awake works only while sleep prevention is active and may leave the screen unlocked after you step away.--## Keep-Awake Limit--Only time actually preventing sleep is counted; pauses and system sleep are excluded. A new running task or a waiting task returning to running starts a new cycle. No active tasks resets the timer. Reaching the limit restores sleep until the next task cycle.--## Stalled Task Protection--A running task with no progress for the selected duration is hidden from the activity card and Task Center and stops preventing sleep. New progress restores it. Increasing the threshold also restores tasks that no longer exceed it.--Protection follows the main sleep-prevention switch and evaluates only non-anonymous running tasks, not tasks waiting for approval. Evaluation pauses during startup recovery, system sleep, and temporary task-data unavailability.--If notifications are enabled and authorized, CodexBar attempts an alert. Notification failure does not block protection.--## Low Battery Protection--On battery power, sleep prevention stops when charge reaches the threshold or lower. It resumes with eligible tasks after charge rises 5 percentage points above the threshold or power is connected.--For example, a 10% threshold stops sleep prevention at 10% and resumes it at 15%.--## Background Service and Other Apps--CodexBarHelper is the background service included with the app that controls system sleep. Settings provides guidance when approval is missing or the service fails; see [Troubleshooting](troubleshooting.md#codexbarhelper-cannot-be-registered).--If another app has already disabled system sleep, Settings identifies an external source. CodexBar preserves that setting when its tasks finish. If the external source stops while tasks remain, CodexBar takes over as needed.--Before a normal exit, CodexBar restores sleep state it manages and cancels Automatic Reset wake schedules. If exit does not complete, check Settings for background-service errors.--Back to the [User Guide](README.md).diff --git a/Docs/en/UserGuide/sync-data-privacy.md b/Docs/en/UserGuide/sync-data-privacy.mddeleted file mode 100644index 7d1de67..0000000--- a/Docs/en/UserGuide/sync-data-privacy.md+++ /dev/null@@ -1,79 +0,0 @@-# Data, Sync, and Privacy--[简体中文](../../UserGuide/sync-data-privacy.md) | English--## Cross-Device Sync--Enable `Cross-Device Sync` in `Settings > Advanced` to combine daily Hook statistics and rollout token usage from Macs using the same iCloud account. Advanced Mode must be enabled and an available iCloud account signed in.--The first sync uploads statistics within local retention; later changes sync automatically. Turning sync off keeps local data.--| State | Meaning |-| --- | --- |-| Sync Off | Sync or Advanced Mode is disabled |-| Syncing | Data is being transferred |-| Synced | The latest sync cycle succeeded |-| Sync Failed | The network, iCloud account, or service is temporarily unavailable; CodexBar will retry |--The main panel footer and Settings show sync status. Settings also shows the last successful upload time.--## 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 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:--- Raw Hook events, session and task identifiers, and full working-directory paths-- Prompts, Codex replies, and tool parameters or output-- Codex account data, quota, app-server account usage, and banked resets-- App settings, proxy configuration, and passwords-- Logs, live task state, and Stalled Task Protection records--Project display names are uploaded. Disable cross-device sync if you do not want those names stored in iCloud.--## Local Data--| Data | Contents and retention |-| --- | --- |-| Hook records and daily statistics | Times, events, models, tools, projects, and task identifiers, retained for 210 days; session and turn details in daily statistics are retained for only the latest 3 days |-| Rollout token history | Hashed turn identities, timestamps, cumulative counts, and read cursors, retained for 210 days; root timestamps referenced by retained child turns are also kept |-| Stalled Task Protection | Irreversible task identifiers and times, retained for up to 24 hours after the last progress |-| App settings | Stored on the current Mac, including proxy configuration; proxy passwords are stored in plain text |-| Interaction logs | The latest 500 Codex requests and responses, retained only during the current run |-| Background-service state | Used to restore sleep settings and clean up Automatic Reset wake schedules |--CodexBar reads local Codex task state and activity records without saving prompts, replies, or tool content, or copying Codex sign-in credentials.--Turning the proxy off retains its configuration and password. Saving with authentication disabled or choosing `Delete Configuration` removes the password.--## Historical Token Replay--During historical-statistics refreshes, the app automatically reads local Codex rollouts to backfill retained turn usage. No manual rebuild is required. Each batch saves usage and read positions; reopening the app resumes from those positions. Once caught up, later refreshes read appended content. Replaced or truncated files are reread, with each thread and turn still counted once.--Large histories may take several refreshes to complete. Progress appears in the `workflow` system-log category. `Rollout 回放完成` means the files checked in that pass are caught up locally; the sync area reports cloud transfer status.--Daily usage follows the root turn’s start time in the viewing device’s local time zone. Missing rollouts or records without usage cannot supply the corresponding counts.--## Rebuild Data--If statistics look incorrect, choose a date range in `Settings > Advanced > Rebuild Data` and confirm. You can select from the last 210 days; dates with local Hook records or discovered token turns are marked; unmarked dates can also be selected.--Rebuilding recalculates activity statistics and token usage for the selected dates from local Hook events and rollouts. Tokens belong to the root turn's start date; each thread and turn contributes once. Dates without Hook events can still rebuild token usage from local rollouts.--The work runs in the background. You can keep using the main panel or close Settings. Token files are read in batches and committed only after the complete scan succeeds; cancellation and read errors do not publish partial results. Quitting the app stops the operation, and an unfinished token rebuild must be started again. The result dialog reports the number of days, Hook events, and token turns processed.--With sync enabled, rebuilding replaces this device's activity statistics and the token turns reread locally, preserving other turns. Rebuilding can lower token counts. If a turn is reread without usage records, its previous counts are cleared and that correction syncs to iCloud. Turns whose local rollouts are missing retain known statistics; missing files do not delete cloud records. Account details, quota, and app-server account usage are unaffected.--## Network and Logs--| Network access | Purpose |-| --- | --- |-| Codex service | Read account, quota, and usage data; perform Automatic Reset |-| Update service | Check for and download CodexBar updates |-| iCloud | After enabling synchronization, transmit daily Hook statistics and session data |--The proxy applies only to CodexBar’s Codex service connection, not updates, iCloud, or other apps.--Interaction logs may contain account data and request or response content and are cleared when the app quits. Check for private information before sharing them.--Back to the [User Guide](README.md).diff --git a/Docs/en/UserGuide/troubleshooting.md b/Docs/en/UserGuide/troubleshooting.mddeleted file mode 100644index 04e6f22..0000000--- a/Docs/en/UserGuide/troubleshooting.md+++ /dev/null@@ -1,148 +0,0 @@-# Troubleshooting--[简体中文](../../UserGuide/troubleshooting.md) | English--## CodexBar Is Missing from the Menu Bar--- CodexBar is a menu bar app and does not show a Dock icon-- Check Control Center settings in macOS to make sure the menu bar item is not hidden-- Launching CodexBar again from Applications does not create a second instance-- If it is still missing, check Activity Monitor to confirm that CodexBar is running--## The Main Panel Says “Not Signed In”--1. Open the Codex CLI, ChatGPT App, or Codex App currently in use-2. Sign in to Codex-3. Double-click the account icon in the CodexBar main panel to refresh-4. If it still says you are not signed in, quit and reopen CodexBar--Automatic mode prefers the global Codex CLI. The `In Use` indicator on the About page identifies the actual source, which you can change with the Source selector.--## The Main Panel Says “Initialization Failed”--Check the connection error in `Settings > About`, confirm Codex is installed at an available path, and review proxy settings. Click `Reconnect` after fixing the issue. If it persists, open Logs for details.--## Proxy Configuration or Connection Failures--Open `Settings > Advanced > Network Proxy` and use `Test Connection` to check the draft. Server and port are required; authentication also requires a username. Invalid fields are outlined in red with a short reason beside the test button.--- If About reports an invalid server or username, correct and save the settings, or turn the proxy off-- If the configuration cannot be read, use `⋯ > Delete Configuration` at the top right of the dialog-- A correctly formatted but unreachable proxy can still be saved and enabled; use Test Connection to check connectivity-- HTTPS requires the proxy endpoint itself to support TLS and present a valid certificate--## Rate Limits or Tokens Appear Dimmed--A dimmed value means that the current read failed and CodexBar fell back to cached data for the same account.--Double-click the account icon to retry. If data remains faded, check the connection error in About or open Logs.--<a id="codexbar-hook-cannot-be-enabled-or-validated"></a>--## Advanced Mode Cannot Be Enabled or Validated--| Message | Action |-| --- | --- |-| A newer Codex version is required | Update Codex, then click `Reconnect` in About |-| Could not determine the Codex version | Check that the selected source is available in About, then click `Reconnect` and retry |-| Codex Hook is globally disabled | Re-enable `features.hooks` in Codex configuration |-| Advanced Mode Hook configuration is incomplete | Reopen Settings for automatic repair; if needed, turn Advanced Mode off and back on |-| Advanced Mode Hook is not trusted | Re-enable Advanced Mode and review Codex’s trust prompts |-| Unexpected Hook source for Advanced Mode | Verify the selected Codex source and the location of `CODEX_HOME` |-| Invalid `hooks.json` format | Repair the file’s JSON format and retry |-| Cannot validate Codex Hook | Reopen Settings after the Codex connection recovers |--The default configuration file is `~/.codex/hooks.json`. If `CODEX_HOME` is set, use `hooks.json` in that directory.--## Live Tasks Do Not Appear--1. Confirm that Advanced Mode is enabled with no error-2. Confirm that `Tasks` is enabled under `General > Main Panel Layout`-3. Start a new Codex task to generate live events-4. Open Settings to trigger Hook validation again--Restarting CodexBar does not replay old task notifications.--## System Notifications Do Not Arrive--Check in this order:--1. `System Notifications` is enabled-2. macOS allows notifications from CodexBar-3. The relevant notification option is enabled-4. Advanced Mode is valid for task notifications-5. The completed task reached the selected duration threshold-6. The notification sound is not set to silent--Haptic feedback does not require macOS notification permission, but it does require CodexBar's System Notifications switch.--## Sleep Prevention Does Not Engage--Check in this order:--1. Advanced Mode is valid-2. `Prevent System Sleep` is enabled-3. A task is currently running-4. If only waiting tasks exist, `Keep Awake While Waiting` is enabled-5. Settings does not report that CodexBar needs approval to run in the background-6. Low Battery Protection is not active-7. The Keep-Awake Limit has not been reached--The sun badge appears only while sleep prevention is active and activity-card data is available. It stays static when Animation Effects is disabled.--If Settings says `System sleep is disabled by another source`, CodexBar does not overwrite that source.--## CodexBarHelper Cannot Be Registered--- Check `CodexBar Helper` in About; turning off a feature hides only its settings-row caption, while About still shows the status-- Not Installed is normal on first use; the app attempts installation and registration after you enable `Automatic Reset` or `Prevent System Sleep` and confirm-- For Not Authorized, click `Open System Settings` below an enabled feature's settings row and allow CodexBar to run in the background-- Confirm that CodexBar is in Applications and that the app bundle is complete-- `Helper incomplete. Reinstall CodexBar` means required bundle components or configuration are absent; `Helper validation failed. Reinstall CodexBar` means configuration or signature validation failed; reinstall the complete CodexBar app in either case-- After repairing the app bundle, restart or reactivate the app to recheck it; a successful check automatically clears the component issue without requiring either feature to be enabled-- If failures continue after an update, quit CodexBar, reopen it, and check authorization again--## Automatic Reset Did Not Run on Time--Check in this order:--1. `Automatic Reset` is enabled and its lead time is what you expect-2. The Automatic Reset row does not report pending CodexBarHelper approval, missing registration, or wake-schedule failure; the lead-time options appear only after the Helper is approved-3. The main panel shows an available banked reset and its expiration time-4. Network access and Codex sign-in were available at the scheduled time-5. `Automatic Reset Notifications` is enabled if you expected a notification; disabling notifications does not stop Automatic Reset itself--Temporary failures retry for up to 5 minutes per round; later refreshes may try again. Disabling Automatic Reset or quitting CodexBar cancels its wake schedule.--## Cross-Device Sync Is Unavailable--- Confirm that the Mac is signed in to iCloud-- Confirm that iCloud Drive and CloudKit are available-- Confirm that Advanced Mode is enabled-- Confirm that `Sync Across Devices` is enabled-- Hover over the iCloud icon at the bottom of the main panel for the detailed status--A sync failure does not delete local Hook data. A later maintenance run retries it.--## CodexBar Still Shows the Old Version After Updating Codex--Click `Reconnect` in About to use the updated Codex.--## Using the Logs Window--Open it by either:--- Right-clicking the menu bar icon and selecting `Log`-- Pressing `⌘L` while the main panel is open--The Logs window retains the latest 500 Codex interactions from the current run.--Each entry includes request time, method, status, and response time. Expand it to inspect a request, response, or error preview.--You can view or copy the full content in a separate window. It cannot be recovered after you clear the log or quit the app.--## Report a Problem--Include reproduction steps, CodexBar and Codex versions, and visible errors. Interaction logs may contain account and request content; review private information before sharing.--Back to the [User Guide](README.md).diff --git a/README.en.md b/README.en.mdindex 7181da7..43890fa 100644--- a/README.en.md+++ b/README.en.md@@ -14,7 +14,7 @@[](https://github.com/bob-zebedy/CodexBar/releases)[](LICENSE)-[Features](#features) | [Installation](#installation) | [Quick Start](#quick-start) | [Documentation](#documentation) | [Privacy](#privacy) | [Runtime Architecture](https://codexbar.zabrian.app/architecture) | [Performance Report](https://codexbar.zabrian.app/performance)+[Features](#features) | [Installation](#installation) | [Quick Start](#quick-start) | [Privacy](#privacy) | [Runtime Architecture](https://codexbar.zabrian.app/architecture) | [Performance Report](https://codexbar.zabrian.app/performance)<img src="Images/preview.gif" width="640" alt="CodexBar preview">@@ -24,7 +24,7 @@CodexBar is a menu bar app for macOS 15 and later that brings your Codex account, rate limits, token usage, and live task status into one place.-It can notify you when a task finishes, needs approval, or when your rate limits change. It can also keep your Mac awake only while Codex tasks are running.+It can notify you when a task finishes, needs approval, or when your rate limits change. It can also keep your Mac awake while eligible Codex tasks are active.## Features@@ -41,7 +41,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 recent daily token usage in a heatmap-- Enable Advanced Mode for daily session, turn, tool call, subagent, and other activity metrics+- View daily session, turn, tool call, subagent, and other activity metrics### Keep track of active tasks@@ -63,8 +63,7 @@ It can notify you when a task finishes, needs approval, or when your rate limits- Runs as a menu bar app without taking up space in the Dock- Supports a global keyboard shortcut, launch at login, and automatic updates- Provides Simplified Chinese and English interfaces-- Configurable HTTP/HTTPS proxy for the Codex service-- Optionally merges daily Hook metrics across Macs through iCloud+- Optionally merges daily activity metrics and token usage records across Macs through iCloud## Installation@@ -82,8 +81,7 @@ Download the latest version from [GitHub Releases](https://github.com/bob-zebedy- macOS 15.0 or later- [Codex CLI](https://github.com/openai/codex) installed and signed in, or ChatGPT App or Codex App with bundled Codex installed-- The running Codex version must be `0.145.0` or later-- Advanced Mode requires the running Codex version to be `0.153.0` or later+- A running Codex interactive session with the background service enabled, using shared-service version `0.160.0` or later- Cross-device sync requires an available iCloud account on the Mac## Quick Start@@ -91,23 +89,19 @@ Download the latest version from [GitHub Releases](https://github.com/bob-zebedy1. Launch CodexBar and find its icon in the menu bar2. Left-click the icon to view your account, rate limits, and token usage3. Right-click or Control-click the icon to open Settings, Logs, or the Quit menu-4. Enable Advanced Mode under `Settings > Advanced` to unlock live tasks, task notifications, sleep prevention, and Hook metrics+4. Activity capture and statistics start with the app; configure notifications, sleep prevention, and sync under `Settings > Advanced`The default global shortcut is `⌘⇧E`. You can record a different shortcut or disable it in Settings.-## Documentation+## Privacy-| Document | Contents |-| --- | --- |-| [User Guide](Docs/en/UserGuide/README.md) | Installation, main panel, Hook, notifications, sleep prevention, sync, settings, and troubleshooting |-| [Developer Guide](Docs/en/DeveloperGuide/README.md) | Architecture, data flows, core state machines, storage, privacy boundaries, and development validation |-| [Documentation Index](Docs/en/README.md) | Complete documentation index |+Raw activity events and live tasks are processed locally. Enabling cross-device sync uploads daily activity aggregates and per-turn token usage records to your private iCloud database. Account and usage data come through the local Codex app-server, which connects to the service; update checks use Sparkle.-## Privacy+## Local history and logs-Raw Hook events and live tasks are processed locally. Enabling cross-device sync uploads daily Hook aggregates to your private iCloud database. Account and usage data come through the local Codex app-server, which connects to the service; update checks use Sparkle.+Activity history is rebuilt from recorded events. Token history is recomputed from raw cumulative counter observations captured while collection was active. Both retain 210 days of data; rebuilding cannot recover unobserved usage or deleted source records. If cross-device token corrections lack a verifiable coverage relationship, no historical token aggregate is generated for the affected date.-See [Data, Sync, and Privacy](Docs/en/UserGuide/sync-data-privacy.md) for complete details about data access, local storage, and network boundaries.+Request logs retain at most 10,000 entries and 50 MiB of serialized records. Each request or response body is limited to 64 KiB and includes a truncation marker when shortened. The oldest entries are removed when limits are exceeded. The log window caches at most 1,000 entries; use **Latest** to return from older history to the live list. Database indexes and WAL files add storage overhead.## Feedbackdiff --git a/README.md b/README.mdindex 3d3e69d..b3913da 100644--- a/README.md+++ b/README.md@@ -14,7 +14,7 @@[](https://github.com/bob-zebedy/CodexBar/releases)[](LICENSE)-[功能](#功能) | [安装](#安装) | [快速开始](#快速开始) | [使用文档](#使用文档) | [隐私](#隐私) | [运行架构](https://codexbar.zabrian.app/architecture) | [性能报告](https://codexbar.zabrian.app/performance)+[功能](#功能) | [安装](#安装) | [快速开始](#快速开始) | [隐私](#隐私) | [运行架构](https://codexbar.zabrian.app/architecture) | [性能报告](https://codexbar.zabrian.app/performance)<img src="Images/preview.gif" width="640" alt="CodexBar 预览">@@ -24,7 +24,7 @@CodexBar 是面向 macOS 15 及更高版本的菜单栏 App,用于集中展示 Codex 账户、额度、Token 用量和实时任务状态。-它可以在任务完成、等待批准或额度变化时提醒你,也能只在 Codex 任务运行期间自动防止系统睡眠。+它可以在任务完成、等待批准或额度变化时提醒你,也能在符合条件的 Codex 任务存在时自动防止系统睡眠。## 功能@@ -41,7 +41,7 @@ CodexBar 是面向 macOS 15 及更高版本的菜单栏 App,用于集中展示- 展示累计 Token、单日峰值和连续使用天数- 展示最长任务时长- 通过热力图回顾近期每日 Token 用量-- 开启进阶模式后可查看会话、对话轮次、工具调用和子 Agent 等每日统计+- 可查看会话、对话轮次、工具调用和子 Agent 等每日统计### 不错过正在发生的任务@@ -63,8 +63,7 @@ CodexBar 是面向 macOS 15 及更高版本的菜单栏 App,用于集中展示- 作为菜单栏 App 运行,不占用 Dock- 支持全局快捷键、开机启动和自动更新- 支持简体中文和英文界面-- 支持为 Codex 服务配置 HTTP/HTTPS 代理-- 可选通过 iCloud 合并多台 Mac 的每日 Hook 统计+- 可选通过 iCloud 合并多台 Mac 的每日活动统计和 Token 用量记录## 安装@@ -82,8 +81,7 @@ brew install --cask bob-zebedy/tap/codexbar- macOS 15.0 或更高版本- 已安装并登录 [Codex CLI](https://github.com/openai/codex) 或安装了内置 Codex 的 ChatGPT App 或 Codex App-- 当前运行的 Codex 版本需要为 `0.145.0` 或更高版本-- 启用进阶模式时,当前运行的 Codex 版本需要为 `0.153.0` 或更高版本+- 已启动启用后台服务的 Codex 交互会话,共享服务版本为 `0.160.0` 或更高版本- 使用跨设备同步时,Mac 需要登录可用的 iCloud 账户## 快速开始@@ -91,23 +89,19 @@ brew install --cask bob-zebedy/tap/codexbar1. 启动 CodexBar,在菜单栏找到 CodexBar 图标2. 左键点击图标查看账户、额度和 Token 用量3. 右键或按住 Control 点击图标打开设置、日志或退出菜单-4. 在 `设置 > 高级` 中启用进阶模式,解锁实时任务、任务类通知、防睡眠和 Hook 统计+4. 会话活动和统计随 App 启动;在 `设置 > 高级` 中按需配置通知、防睡眠和同步默认全局快捷键为 `⌘⇧E`,可在设置中重新录制或关闭。-## 使用文档+## 隐私-| 文档 | 内容 |-| --- | --- |-| [用户指南](Docs/README.md#用户指南) | 安装、主面板、Hook、通知、防睡眠、同步、全部设置和问题排查 |-| [开发者指南](Docs/DeveloperGuide/README.md) | 架构、数据链路、核心状态机、存储、隐私边界和开发验证 |-| [文档导航](Docs/README.md) | 全部文档入口 |+活动原始事件和实时任务在本机处理。开启跨设备同步后,日级活动聚合和 Token 用量记录会上传到 iCloud private database。账户和用量通过本机 Codex app-server 获取,由 Codex 连接服务端;更新检查使用 Sparkle。-## 隐私+## 本地历史与日志-Hook 原始事件和实时任务在本机处理。开启跨设备同步后,日级 Hook 聚合会上传到 iCloud private database。账户和用量通过本机 Codex app-server 获取,由 Codex 连接服务端;更新检查使用 Sparkle。+活动历史按已记录的事件重建,Token 历史按采集期间保存的原始累计计数观测重新计算。两者保留 210 天的数据;重建无法补回未采集的消耗或已删除的原始记录。跨设备 Token 修正缺少可核对的覆盖关系时,对应日期不生成历史 Token 汇总。-完整的数据访问、本机存储和网络边界见 [数据、同步与隐私](Docs/UserGuide/sync-data-privacy.md)+请求日志最多保留 10,000 条,序列化记录总量不超过 50 MiB,单份请求或响应正文最多保留 64 KiB。超过限制时清理最旧记录,超长正文带截断标记。日志窗口最多缓存 1,000 条,浏览更早记录后可通过“最新日志”返回实时列表。数据库索引和 WAL 会产生额外文件开销。## 反馈diff --git a/Scripts/CodexBar.provisionprofile b/Scripts/CodexBar.provisionprofileindex abf51d5..b507822 100644Binary files a/Scripts/CodexBar.provisionprofile and b/Scripts/CodexBar.provisionprofile differdiff --git a/Scripts/DeveloperID.plist b/Scripts/DeveloperID.plistindex 44413df..2f997c8 100644--- a/Scripts/DeveloperID.plist+++ b/Scripts/DeveloperID.plist@@ -20,7 +20,7 @@<key>provisioningProfiles</key><dict><key>app.zabrian.codexbar</key>- <string>90c33faf-6747-4248-9ef6-701ff8277501</string>+ <string>f946b12f-4e82-4384-9076-aa1c561b1f94</string></dict><key>stripSwiftSymbols</key>diff --git a/Scripts/build.sh b/Scripts/build.shindex cd5b8ba..b34e1f3 100755--- a/Scripts/build.sh+++ b/Scripts/build.sh@@ -35,9 +35,9 @@ Options:--project PATH Xcode project. Defaults to CodexBar.xcodeproj.--scheme NAME Xcode scheme. Defaults to CodexBar.--configuration NAME Xcode configuration. Defaults to Release.- --build-dir DIR Build output directory. Defaults to Build/.+ --build-dir DIR Build output directory within Build/. Defaults to Build/.Cleaned before each build.- --derived-data PATH DerivedData path. Defaults to Build/DerivedData.+ --derived-data PATH DerivedData path within Build/. Defaults to Build/DerivedData.--archive-path PATH Archive path. Defaults to Build/<scheme>.xcarchive.--export-options PATH Export options plist. Generated when unset.--team-id ID Apple Developer team ID. Defaults to the@@ -461,505 +461,7 @@ validation_summary() {fi}-validate_final_app() {- local app_path="$1"- local contents_path="${app_path}/Contents"- local info_plist="${contents_path}/Info.plist"- local executable_path="${contents_path}/MacOS/${PRODUCT_NAME}"- local helper_path="${contents_path}/Resources/CodexBarHelper"- local launch_daemons_path="${contents_path}/Library/LaunchDaemons"- local embedded_profile="${contents_path}/embedded.provisionprofile"- local validation_dir="${TEMP_ROOT}/validation"- local main_entitlements="${validation_dir}/main-entitlements.plist"- local helper_entitlements="${validation_dir}/helper-entitlements.plist"- local profile_plist="${validation_dir}/embedded-profile.plist"- local profile_decode_error="${validation_dir}/profile-decode-error.log"- local profile_entitlements="${validation_dir}/profile-entitlements.plist"- local signing_certificate_prefix="${validation_dir}/signing-certificate"- local signing_certificate="${signing_certificate_prefix}0"- local helper_signing_certificate_prefix="${validation_dir}/helper-signing-certificate"- local helper_signing_certificate="${helper_signing_certificate_prefix}0"- local bundle_identifier=""- local display_name=""- local short_version=""- local build_version=""- local minimum_system_version=""- local ui_element=""- local architectures=""- local helper_architectures=""- local architecture=""- local command_output=""- local signature_details=""- local helper_signature_details=""- local signature_identifier=""- local helper_signature_identifier=""- local signing_authority=""- local signing_timestamp=""- local signing_team=""- local helper_signing_team=""- local signing_cdhash=""- local signing_certificate_sha1=""- local helper_signing_certificate_sha1=""- local expected_signing_certificate=""- local normalized_expected_certificate=""- local export_certificate_selector=""- local main_application_identifier=""- local helper_application_identifier=""- local main_team_identifier=""- local debugger_entitlement=""- local helper_debugger_entitlement=""- local app_debugger_status="disabled"- local helper_debugger_status="disabled"- local icloud_environment=""- local icloud_containers=""- local icloud_services=""- local launch_daemon_count="0"- local launch_daemon_plist=""- local launch_daemon_label=""- local launch_daemon_bundle_identifier=""- local launch_daemon_program=""- local profile_name=""- local profile_uuid=""- local profile_team=""- local profile_application_identifier=""- local profile_expiration=""- local profile_certificate_count="0"- local profile_certificate_index="0"- local profile_certificate_path=""- local profile_certificate_sha1=""- local profile_certificate_match_count="0"- local -a profile_certificate_sha1s=()- local profile_icloud_environment=""- local profile_icloud_containers=""- local profile_icloud_services=""- local profile_ubiquity_containers=""- local profile_ubiquity_kvstore=""- local profile_keychain_access_groups=""- local expected_profile=""- local gatekeeper_source=""-- echo "==> Validating final app"- validation_section "Bundle"-- if [[ ! -d "${app_path}" || ! -f "${info_plist}" || ! -x "${executable_path}" ]]; then- validation_fail "App bundle structure" "Missing app directory, Info.plist, or executable at ${app_path}"- return 1- fi- validation_pass "App bundle structure"-- if [[ ! -x "${helper_path}" ]]; then- validation_fail "Embedded helper" "Executable helper not found at ${helper_path}"- return 1- fi- validation_pass "Embedded helper"-- mkdir -p "${validation_dir}"-- bundle_identifier="$(read_plist_value "${info_plist}" CFBundleIdentifier)"- display_name="$(read_plist_value "${info_plist}" CFBundleDisplayName)"- short_version="$(read_plist_value "${info_plist}" CFBundleShortVersionString)"- build_version="$(read_plist_value "${info_plist}" CFBundleVersion)"- minimum_system_version="$(read_plist_value "${info_plist}" LSMinimumSystemVersion)"- ui_element="$(read_plist_value "${info_plist}" LSUIElement)"-- if [[ -z "${bundle_identifier}" || -z "${short_version}" || -z "${build_version}" ]]; then- validation_fail "Required bundle metadata" "CFBundleIdentifier, CFBundleShortVersionString, or CFBundleVersion is missing"- return 1- fi- validation_pass "Required bundle metadata"-- if ! architectures="$(lipo -archs "${executable_path}" 2>&1)"; then- validation_fail "App architectures" "lipo could not inspect the main executable" "${architectures}"- return 1- fi-- if ! helper_architectures="$(lipo -archs "${helper_path}" 2>&1)"; then- validation_fail "Helper architectures" "lipo could not inspect the helper executable" "${helper_architectures}"- return 1- fi- validation_pass "Architectures inspected"-- validation_field "Path" "${app_path}"- validation_field "Display name" "${display_name}"- validation_field "Bundle identifier" "${bundle_identifier}"- validation_field "Version" "${short_version} (${build_version})"- validation_field "Minimum macOS" "${minimum_system_version}"- validation_field "LSUIElement" "${ui_element}"- validation_field "App architectures" "${architectures}"- validation_field "Helper architectures" "${helper_architectures}"-- validation_section "Code signature"-- if ! command_output="$(codesign --verify --deep --strict --verbose=4 "${app_path}" 2>&1)"; then- validation_fail "Deep strict app signature" "codesign rejected the app bundle" "${command_output}"- return 1- fi- validation_pass "Deep strict app signature"-- for architecture in ${architectures}; do- if ! command_output="$(codesign --verify --strict --verbose=4 --arch "${architecture}" "${app_path}" 2>&1)"; then- validation_fail "App ${architecture} signature" "codesign rejected the ${architecture} slice" "${command_output}"- return 1- fi- done- validation_pass "App signature slices: ${architectures}"-- if ! command_output="$(codesign --verify --strict --verbose=4 "${helper_path}" 2>&1)"; then- validation_fail "Helper signature" "codesign rejected the helper executable" "${command_output}"- return 1- fi- validation_pass "Helper signature"-- for architecture in ${helper_architectures}; do- if ! command_output="$(codesign --verify --strict --verbose=4 --arch "${architecture}" "${helper_path}" 2>&1)"; then- validation_fail "Helper ${architecture} signature" "codesign rejected the helper ${architecture} slice" "${command_output}"- return 1- fi- done- validation_pass "Helper signature slices: ${helper_architectures}"-- if ! signature_details="$(codesign -d --verbose=4 "${app_path}" 2>&1)"; then- validation_fail "App signature metadata" "codesign could not read the app signature" "${signature_details}"- return 1- fi-- if ! helper_signature_details="$(codesign -d --verbose=4 "${helper_path}" 2>&1)"; then- validation_fail "Helper signature metadata" "codesign could not read the helper signature" "${helper_signature_details}"- return 1- fi-- signature_identifier="$(printf '%s\n' "${signature_details}" | awk -F= '/^Identifier=/ {print $2; exit}')"- helper_signature_identifier="$(printf '%s\n' "${helper_signature_details}" | awk -F= '/^Identifier=/ {print $2; exit}')"- signing_authority="$(printf '%s\n' "${signature_details}" | awk -F= '/^Authority=/ {print substr($0, index($0, "=") + 1); exit}')"- signing_timestamp="$(printf '%s\n' "${signature_details}" | awk -F= '/^Timestamp=/ {print substr($0, index($0, "=") + 1); exit}')"- signing_team="$(printf '%s\n' "${signature_details}" | awk -F= '/^TeamIdentifier=/ {print $2; exit}')"- helper_signing_team="$(printf '%s\n' "${helper_signature_details}" | awk -F= '/^TeamIdentifier=/ {print $2; exit}')"- signing_cdhash="$(printf '%s\n' "${signature_details}" | awk -F= '/^CDHash=/ {print $2; exit}')"-- if [[ "${signature_identifier}" != "${bundle_identifier}" ||- "${helper_signature_identifier}" != "${bundle_identifier}.helper" ||- -z "${signing_team}" || "${helper_signing_team}" != "${signing_team}" ]]; then- validation_fail \- "Code signature identifiers" \- "Expected app ${bundle_identifier}, helper ${bundle_identifier}.helper, and one shared team; got app ${signature_identifier}, helper ${helper_signature_identifier}, teams ${signing_team:-none}/${helper_signing_team:-none}"- return 1- fi- validation_pass "Code signature identifiers"-- if ! printf '%s\n' "${signature_details}" | grep -Eq '^CodeDirectory .*flags=.*\(runtime\)'; then- validation_fail "App Hardened Runtime" "The app CodeDirectory does not contain the runtime flag"- return 1- fi- validation_pass "App Hardened Runtime"-- if ! printf '%s\n' "${helper_signature_details}" | grep -Eq '^CodeDirectory .*flags=.*\(runtime\)'; then- validation_fail "Helper Hardened Runtime" "The helper CodeDirectory does not contain the runtime flag"- return 1- fi- validation_pass "Helper Hardened Runtime"-- if ! codesign --display --extract-certificates="${signing_certificate_prefix}" "${app_path}" >/dev/null 2>&1 || [[ ! -f "${signing_certificate}" ]]; then- validation_fail "App signing certificate" "codesign could not extract the app leaf certificate"- return 1- fi-- if ! codesign --display --extract-certificates="${helper_signing_certificate_prefix}" "${helper_path}" >/dev/null 2>&1 || [[ ! -f "${helper_signing_certificate}" ]]; then- validation_fail "Helper signing certificate" "codesign could not extract the helper leaf certificate"- return 1- fi-- if ! signing_certificate_sha1="$(certificate_sha1 "${signing_certificate}")"; then- validation_fail "App signing certificate" "Unable to calculate the app certificate SHA-1"- return 1- fi-- if ! helper_signing_certificate_sha1="$(certificate_sha1 "${helper_signing_certificate}")"; then- validation_fail "Helper signing certificate" "Unable to calculate the helper certificate SHA-1"- return 1- fi-- if [[ "${helper_signing_certificate_sha1}" != "${signing_certificate_sha1}" ]]; then- validation_fail \- "App and helper certificate match" \- "App uses ${signing_certificate_sha1}, helper uses ${helper_signing_certificate_sha1}"- return 1- fi- validation_pass "App and helper certificate match"-- expected_signing_certificate="$(read_plist_value "${EXPORT_OPTIONS_PLIST}" signingCertificate)"- normalized_expected_certificate="$(printf '%s' "${expected_signing_certificate}" | tr -d ':' | tr '[:lower:]' '[:upper:]')"- if [[ "${normalized_expected_certificate}" =~ ^[0-9A-F]{40}$ ]]; then- if [[ "${signing_certificate_sha1}" != "${normalized_expected_certificate}" ]]; then- validation_fail \- "Export certificate match" \- "ExportOptions requires ${normalized_expected_certificate}, app uses ${signing_certificate_sha1}"- return 1- fi- validation_pass "Export certificate match"- elif [[ -n "${expected_signing_certificate}" ]]; then- export_certificate_selector="${expected_signing_certificate}"- fi-- validation_field "App identifier" "${signature_identifier}"- validation_field "Helper identifier" "${helper_signature_identifier}"- validation_field "Authority" "${signing_authority}"- validation_field "Team identifier" "${signing_team}"- validation_field "App certificate SHA-1" "${signing_certificate_sha1}"- validation_field "Helper certificate SHA-1" "${helper_signing_certificate_sha1}"- validation_field "Timestamp" "${signing_timestamp:-none}"- validation_field "CDHash" "${signing_cdhash}"- if [[ -n "${export_certificate_selector}" ]]; then- validation_field "Export certificate selector" "${export_certificate_selector}"- fi-- validation_section "Entitlements"-- if ! codesign --display --entitlements="${main_entitlements}" --xml "${app_path}" >/dev/null 2>&1 || [[ ! -s "${main_entitlements}" ]]; then- validation_fail "App entitlements" "codesign did not return an app entitlements plist"- return 1- fi- validation_pass "App entitlements extracted"-- if ! codesign --display --entitlements="${helper_entitlements}" --xml "${helper_path}" >/dev/null 2>&1 || [[ ! -s "${helper_entitlements}" ]]; then- validation_fail "Helper entitlements" "codesign did not return a helper entitlements plist"- return 1- fi- validation_pass "Helper entitlements extracted"-- main_application_identifier="$(read_plist_value "${main_entitlements}" com.apple.application-identifier)"- helper_application_identifier="$(read_plist_value "${helper_entitlements}" com.apple.application-identifier)"- main_team_identifier="$(read_plist_value "${main_entitlements}" com.apple.developer.team-identifier)"- debugger_entitlement="$(read_plist_value "${main_entitlements}" com.apple.security.get-task-allow)"- helper_debugger_entitlement="$(read_plist_value "${helper_entitlements}" com.apple.security.get-task-allow)"- icloud_environment="$(read_plist_compact_value "${main_entitlements}" com.apple.developer.icloud-container-environment)"- icloud_containers="$(read_plist_compact_value "${main_entitlements}" com.apple.developer.icloud-container-identifiers)"- icloud_services="$(read_plist_compact_value "${main_entitlements}" com.apple.developer.icloud-services)"- if [[ "${debugger_entitlement}" == "true" || "${debugger_entitlement}" == "1" ]]; then- app_debugger_status="allowed"- fi- if [[ "${helper_debugger_entitlement}" == "true" || "${helper_debugger_entitlement}" == "1" ]]; then- helper_debugger_status="allowed"- fi-- if [[ "${main_application_identifier}" != "${signing_team}.${bundle_identifier}" ||- "${helper_application_identifier}" != "${signing_team}.${bundle_identifier}.helper" ]]; then- validation_fail \- "Entitlement application identifiers" \- "Expected ${signing_team}.${bundle_identifier} and ${signing_team}.${bundle_identifier}.helper; got ${main_application_identifier:-none} and ${helper_application_identifier:-none}"- return 1- fi- validation_pass "Entitlement application identifiers"-- if [[ "${CONFIGURATION}" == "Release" &&- ("${app_debugger_status}" == "allowed" || "${helper_debugger_status}" == "allowed") ]]; then- validation_fail \- "Release debugger attachment" \- "get-task-allow is enabled for app=${debugger_entitlement:-false}, helper=${helper_debugger_entitlement:-false}"- return 1- fi-- if ! command_output="$(plutil -p "${main_entitlements}" 2>&1)"; then- validation_fail "App entitlements" "Unable to read app entitlements" "${command_output}"- return 1- fi-- if ! command_output="$(plutil -p "${helper_entitlements}" 2>&1)"; then- validation_fail "Helper entitlements" "Unable to read helper entitlements" "${command_output}"- return 1- fi- validation_pass "Debugger attachment policy"-- validation_field "App identifier" "${main_application_identifier}"- validation_field "Helper identifier" "${helper_application_identifier}"- validation_field "Team identifier" "${main_team_identifier}"- validation_field "iCloud environment" "${icloud_environment}"- validation_field "iCloud containers" "${icloud_containers}"- validation_field "iCloud services" "${icloud_services}"- validation_field "App debugger attachment" "${app_debugger_status}"- validation_field "Helper debugger attachment" "${helper_debugger_status}"-- validation_section "LaunchDaemon"-- if [[ ! -d "${launch_daemons_path}" ]]; then- validation_fail "LaunchDaemon directory" "Missing ${launch_daemons_path}"- return 1- fi-- if ! command_output="$(find "${launch_daemons_path}" -maxdepth 1 -type f -name '*.plist' 2>&1)"; then- validation_fail "LaunchDaemon plist discovery" "Unable to read ${launch_daemons_path}" "${command_output}"- return 1- fi- launch_daemon_count="$(printf '%s\n' "${command_output}" | awk 'NF {count++} END {print count + 0}')"- launch_daemon_plist="$(printf '%s\n' "${command_output}" | sort | sed -n '1p')"- if [[ "${launch_daemon_count}" -ne 1 || -z "${launch_daemon_plist}" ]]; then- validation_fail "LaunchDaemon plist count" "Expected exactly 1 plist, found ${launch_daemon_count}"- return 1- fi-- launch_daemon_label="$(read_plist_value "${launch_daemon_plist}" Label)"- launch_daemon_bundle_identifier="$(read_plist_value "${launch_daemon_plist}" AssociatedBundleIdentifiers:0)"- launch_daemon_program="$(read_plist_value "${launch_daemon_plist}" BundleProgram)"- if [[ "${launch_daemon_label}" != "${bundle_identifier}.helper" ||- "${launch_daemon_bundle_identifier}" != "${bundle_identifier}" ||- "${launch_daemon_program}" != "Contents/Resources/CodexBarHelper" ]]; then- validation_fail \- "LaunchDaemon configuration" \- "Expected label ${bundle_identifier}.helper, bundle ${bundle_identifier}, and program Contents/Resources/CodexBarHelper; got ${launch_daemon_label:-none}, ${launch_daemon_bundle_identifier:-none}, ${launch_daemon_program:-none}"- return 1- fi- validation_pass "LaunchDaemon configuration"-- validation_field "File" "$(basename "${launch_daemon_plist}")"- validation_field "Label" "${launch_daemon_label}"- validation_field "Associated bundle" "${launch_daemon_bundle_identifier}"- validation_field "Program" "${launch_daemon_program}"-- validation_section "Provisioning profile"-- if [[ -f "${embedded_profile}" ]]; then- if ! security cms -D -i "${embedded_profile}" > "${profile_plist}" 2> "${profile_decode_error}"; then- validation_fail \- "Embedded provisioning profile" \- "security cms could not decode embedded.provisionprofile" \- "$(< "${profile_decode_error}")"- return 1- fi- validation_pass "Embedded provisioning profile decoded"-- profile_name="$(read_plist_value "${profile_plist}" Name)"- profile_uuid="$(read_plist_value "${profile_plist}" UUID)"- profile_team="$(read_plist_value "${profile_plist}" TeamIdentifier:0)"- profile_application_identifier="$(read_plist_value "${profile_plist}" Entitlements:com.apple.application-identifier)"- profile_expiration="$(read_plist_value "${profile_plist}" ExpirationDate)"- if ! profile_certificate_count="$(- plutil -extract DeveloperCertificates xml1 -o - "${profile_plist}" |- awk '{line = $0; while (match(line, /<data>/)) {count++; line = substr(line, RSTART + RLENGTH)}} END {print count + 0}'- )"; then- validation_fail "Profile certificates" "DeveloperCertificates is missing or malformed"- return 1- fi-- if [[ "${profile_application_identifier}" != "${main_application_identifier}" || "${profile_team}" != "${signing_team}" ]]; then- validation_fail \- "Profile signature identity" \- "Expected application ${main_application_identifier} and team ${signing_team}; got ${profile_application_identifier:-none} and ${profile_team:-none}"- return 1- fi- validation_pass "Profile signature identity"-- if [[ "${profile_certificate_count}" -lt 1 ]]; then- validation_fail "Profile certificates" "DeveloperCertificates contains no signing certificates"- return 1- fi-- for ((profile_certificate_index = 0; profile_certificate_index < profile_certificate_count; profile_certificate_index++)); do- profile_certificate_path="${validation_dir}/profile-certificate-${profile_certificate_index}.der"- if ! plutil -extract "DeveloperCertificates.${profile_certificate_index}" raw -o - "${profile_plist}" |- base64 -D > "${profile_certificate_path}"; then- validation_fail \- "Profile certificate $((profile_certificate_index + 1))" \- "Unable to decode the certificate from DeveloperCertificates"- return 1- fi- if ! profile_certificate_sha1="$(certificate_sha1 "${profile_certificate_path}")"; then- validation_fail \- "Profile certificate $((profile_certificate_index + 1))" \- "Unable to calculate the certificate SHA-1"- return 1- fi- profile_certificate_sha1s+=("${profile_certificate_sha1}")- if [[ "${profile_certificate_sha1}" == "${signing_certificate_sha1}" ]]; then- profile_certificate_match_count=$((profile_certificate_match_count + 1))- fi- done- validation_pass "Profile certificates decoded"-- if [[ "${profile_certificate_match_count}" -lt 1 ]]; then- validation_fail \- "App certificate authorization" \- "App certificate ${signing_certificate_sha1} is not listed in the embedded profile"- return 1- fi- validation_pass "App certificate authorization"-- expected_profile="$(read_plist_value "${EXPORT_OPTIONS_PLIST}" "provisioningProfiles:${bundle_identifier}")"- if [[ -n "${expected_profile}" ]]; then- if [[ "${expected_profile}" != "${profile_uuid}" && "${expected_profile}" != "${profile_name}" ]]; then- validation_fail \- "Export profile match" \- "ExportOptions requires ${expected_profile}, embedded profile is ${profile_name} (${profile_uuid})"- return 1- fi- validation_pass "Export profile match"- fi-- if ! command_output="$(plutil -extract Entitlements xml1 -o "${profile_entitlements}" "${profile_plist}" 2>&1)"; then- validation_fail "Profile entitlements" "Unable to extract authorized entitlements" "${command_output}"- return 1- fi- if ! command_output="$(plutil -p "${profile_entitlements}" 2>&1)"; then- validation_fail "Profile entitlements" "Unable to read authorized entitlements" "${command_output}"- return 1- fi- profile_icloud_environment="$(read_plist_compact_value "${profile_entitlements}" com.apple.developer.icloud-container-environment)"- profile_icloud_containers="$(read_plist_compact_value "${profile_entitlements}" com.apple.developer.icloud-container-identifiers)"- profile_icloud_services="$(read_plist_compact_value "${profile_entitlements}" com.apple.developer.icloud-services)"- profile_ubiquity_containers="$(read_plist_compact_value "${profile_entitlements}" com.apple.developer.ubiquity-container-identifiers)"- profile_ubiquity_kvstore="$(read_plist_compact_value "${profile_entitlements}" com.apple.developer.ubiquity-kvstore-identifier)"- profile_keychain_access_groups="$(read_plist_compact_value "${profile_entitlements}" keychain-access-groups)"- validation_pass "Profile entitlements"-- validation_field "Name" "${profile_name}"- validation_field "UUID" "${profile_uuid}"- validation_field "Team identifier" "${profile_team}"- validation_field "Application identifier" "${profile_application_identifier}"- validation_field "Expiration" "${profile_expiration}"- validation_field "Authorized certificates" "${profile_certificate_count}"- for ((profile_certificate_index = 0; profile_certificate_index < profile_certificate_count; profile_certificate_index++)); do- validation_field \- "Certificate $((profile_certificate_index + 1)) SHA-1" \- "${profile_certificate_sha1s[${profile_certificate_index}]}"- done- validation_field "iCloud environment" "${profile_icloud_environment}"- validation_field "iCloud containers" "${profile_icloud_containers}"- validation_field "iCloud services" "${profile_icloud_services}"- validation_field "Ubiquity containers" "${profile_ubiquity_containers}"- validation_field "Ubiquity KV store" "${profile_ubiquity_kvstore}"- validation_field "Keychain access groups" "${profile_keychain_access_groups}"- elif [[ -n "${icloud_containers}" ]]; then- validation_fail "Embedded provisioning profile" "CloudKit entitlements require embedded.provisionprofile"- return 1- else- validation_pass "Provisioning profile not required"- fi-- validation_section "Distribution"-- if [[ "${SKIP_NOTARIZATION}" == "1" ]]; then- validation_skip "Notarization ticket"- validation_skip "Gatekeeper assessment"- else- if ! command_output="$(xcrun stapler validate "${app_path}" 2>&1)"; then- validation_fail "Notarization ticket" "stapler could not validate the ticket" "${command_output}"- return 1- fi- validation_pass "Notarization ticket"-- if [[ "${SPCTL_ASSESS}" == "1" ]]; then- if ! command_output="$(spctl --assess --type execute --verbose=4 "${app_path}" 2>&1)"; then- validation_fail "Gatekeeper assessment" "spctl rejected the app" "${command_output}"- return 1- fi- gatekeeper_source="$(printf '%s\n' "${command_output}" | awk -F= '/^source=/ {print substr($0, index($0, "=") + 1); exit}')"- validation_pass "Gatekeeper assessment"- validation_field "Gatekeeper source" "${gatekeeper_source}"- else- validation_skip "Gatekeeper assessment"- fi- fi-- validation_summary "Final app validation passed"-}+source "${SCRIPT_DIR}/lib/validate.sh"safe_remove_path() {local path="$1"@@ -973,43 +475,48 @@ safe_remove_path() {parent="$(cd "$(dirname "${path}")" && pwd)"resolved="${parent}/$(basename "${path}")"+ validate_build_path "${resolved}"case "${resolved}" in- "${BUILD_DIR}"/*|/private/tmp/*)+ "${BUILD_DIR}"/*)rm -rf "${resolved}";;*)- echo "error: refusing to remove path outside build or /private/tmp: ${resolved}" >&2+ echo "error: refusing to remove path outside build: ${resolved}" >&2exit 1;;esac}-clean_build_dir() {- case "${BUILD_DIR}" in- *"/.."*|*"../"*|"..")- echo "error: refusing to clean build path containing '..': ${BUILD_DIR}" >&2- exit 1- ;;- "${PROJECT_DIR}"|"${PROJECT_DIR}/"|"${PROJECT_DIR}/.git"|\- "${PROJECT_DIR}/.github"|"${PROJECT_DIR}/CodexBar"|\- "${PROJECT_DIR}/Docs"|"${PROJECT_DIR}/Images"|\- "${PROJECT_DIR}/Scripts")- echo "error: refusing to clean protected project path: ${BUILD_DIR}" >&2+validate_build_path() {+ local path="$1"+ local current=""+ local part=""+ local parts=()+ case "${path}" in+ "${PROJECT_DIR}/Build"|"${PROJECT_DIR}/Build/"*) ;;+ *) echo "error: build paths must be inside ${PROJECT_DIR}/Build: ${path}" >&2; exit 1 ;;+ esac+ IFS='/' read -r -a parts <<< "${path}"+ for part in "${parts[@]}"; do+ [[ -z "${part}" ]] && continue+ if [[ "${part}" == "." || "${part}" == ".." ]]; then+ echo "error: ambiguous build path: ${path}" >&2exit 1- ;;- "${PROJECT_DIR}"/*|/private/tmp/*)- ;;- *)- echo "error: refusing to clean build directory outside project or /private/tmp: ${BUILD_DIR}" >&2+ fi+ current="${current}/${part}"+ if [[ -L "${current}" ]]; then+ echo "error: build paths must not traverse symbolic links: ${current}" >&2exit 1- ;;- esac+ fi+ done+}+clean_build_dir() {+ validate_build_path "${BUILD_DIR}"if [[ -e "${BUILD_DIR}" && ! -d "${BUILD_DIR}" ]]; thenecho "error: build path exists but is not a directory: ${BUILD_DIR}" >&2exit 1fi-echo "==> Cleaning build directory ${BUILD_DIR}"rm -rf "${BUILD_DIR}"mkdir -p "${BUILD_DIR}"@@ -1155,6 +662,25 @@ if [[ "${SKIP_NOTARIZATION}" != "1" ]]; thenfifi+validate_build_path "${BUILD_DIR}"+validate_build_path "${ARCHIVE_PATH}"+validate_build_path "${DERIVED_DATA_PATH}"+if [[ -n "${OUTPUT_APP_PATH}" ]]; then+ validate_build_path "$(absolute_path "${OUTPUT_APP_PATH}")"+fi+BUILD_LOCK="${PROJECT_DIR}/.codexbar-build.lock"+if ! mkdir "${BUILD_LOCK}" 2>/dev/null; then+ echo "error: build lock exists: ${BUILD_LOCK}; wait for the running build, or remove the stale lock after verifying no build is running" >&2+ exit 1+fi+TEMP_ROOT=""+cleanup() {+ [[ -z "${TEMP_ROOT}" ]] || rm -rf "${TEMP_ROOT}"+ rmdir "${BUILD_LOCK}"+}+trap cleanup EXIT+trap 'exit 130' INT+trap 'exit 143' TERMmkdir -p "${BUILD_DIR}" "$(dirname "${ARCHIVE_PATH}")" "${DERIVED_DATA_PATH}"BUILD_DIR="$(cd "${BUILD_DIR}" && pwd)"DERIVED_DATA_PATH="$(cd "${DERIVED_DATA_PATH}" && pwd)"@@ -1209,10 +735,6 @@ EXPORT_DIR="${TEMP_ROOT}/export"NOTARY_ZIP="${TEMP_ROOT}/${PRODUCT_NAME}-notary.zip"GENERATED_EXPORT_OPTIONS="${TEMP_ROOT}/ExportOptions.plist"-cleanup() {- rm -rf "${TEMP_ROOT}"-}-trap cleanup EXITif [[ -z "${EXPORT_OPTIONS_PLIST}" ]]; thenEXPORT_OPTIONS_PLIST="${GENERATED_EXPORT_OPTIONS}"diff --git a/Scripts/lib/validate.sh b/Scripts/lib/validate.shnew file mode 100644index 0000000..f6c7678--- /dev/null+++ b/Scripts/lib/validate.sh@@ -0,0 +1,501 @@+#!/usr/bin/env bash++validate_final_app() {+ local app_path="$1"+ local contents_path="${app_path}/Contents"+ local info_plist="${contents_path}/Info.plist"+ local executable_path="${contents_path}/MacOS/${PRODUCT_NAME}"+ local helper_path="${contents_path}/Resources/CodexBarHelper"+ local launch_daemons_path="${contents_path}/Library/LaunchDaemons"+ local embedded_profile="${contents_path}/embedded.provisionprofile"+ local validation_dir="${TEMP_ROOT}/validation"+ local main_entitlements="${validation_dir}/main-entitlements.plist"+ local helper_entitlements="${validation_dir}/helper-entitlements.plist"+ local profile_plist="${validation_dir}/embedded-profile.plist"+ local profile_decode_error="${validation_dir}/profile-decode-error.log"+ local profile_entitlements="${validation_dir}/profile-entitlements.plist"+ local signing_certificate_prefix="${validation_dir}/signing-certificate"+ local signing_certificate="${signing_certificate_prefix}0"+ local helper_signing_certificate_prefix="${validation_dir}/helper-signing-certificate"+ local helper_signing_certificate="${helper_signing_certificate_prefix}0"+ local bundle_identifier=""+ local display_name=""+ local short_version=""+ local build_version=""+ local minimum_system_version=""+ local ui_element=""+ local architectures=""+ local helper_architectures=""+ local architecture=""+ local command_output=""+ local signature_details=""+ local helper_signature_details=""+ local signature_identifier=""+ local helper_signature_identifier=""+ local signing_authority=""+ local signing_timestamp=""+ local signing_team=""+ local helper_signing_team=""+ local signing_cdhash=""+ local signing_certificate_sha1=""+ local helper_signing_certificate_sha1=""+ local expected_signing_certificate=""+ local normalized_expected_certificate=""+ local export_certificate_selector=""+ local main_application_identifier=""+ local helper_application_identifier=""+ local main_team_identifier=""+ local debugger_entitlement=""+ local helper_debugger_entitlement=""+ local app_debugger_status="disabled"+ local helper_debugger_status="disabled"+ local icloud_environment=""+ local icloud_containers=""+ local icloud_services=""+ local launch_daemon_count="0"+ local launch_daemon_plist=""+ local launch_daemon_label=""+ local launch_daemon_bundle_identifier=""+ local launch_daemon_program=""+ local profile_name=""+ local profile_uuid=""+ local profile_team=""+ local profile_application_identifier=""+ local profile_expiration=""+ local profile_certificate_count="0"+ local profile_certificate_index="0"+ local profile_certificate_path=""+ local profile_certificate_sha1=""+ local profile_certificate_match_count="0"+ local -a profile_certificate_sha1s=()+ local profile_icloud_environment=""+ local profile_icloud_containers=""+ local profile_icloud_services=""+ local profile_ubiquity_containers=""+ local profile_ubiquity_kvstore=""+ local profile_keychain_access_groups=""+ local expected_profile=""+ local gatekeeper_source=""++ echo "==> Validating final app"+ validation_section "Bundle"++ if [[ ! -d "${app_path}" || ! -f "${info_plist}" || ! -x "${executable_path}" ]]; then+ validation_fail "App bundle structure" "Missing app directory, Info.plist, or executable at ${app_path}"+ return 1+ fi+ validation_pass "App bundle structure"++ if [[ ! -x "${helper_path}" ]]; then+ validation_fail "Embedded helper" "Executable helper not found at ${helper_path}"+ return 1+ fi+ validation_pass "Embedded helper"++ mkdir -p "${validation_dir}"++ bundle_identifier="$(read_plist_value "${info_plist}" CFBundleIdentifier)"+ display_name="$(read_plist_value "${info_plist}" CFBundleDisplayName)"+ short_version="$(read_plist_value "${info_plist}" CFBundleShortVersionString)"+ build_version="$(read_plist_value "${info_plist}" CFBundleVersion)"+ minimum_system_version="$(read_plist_value "${info_plist}" LSMinimumSystemVersion)"+ ui_element="$(read_plist_value "${info_plist}" LSUIElement)"++ if [[ -z "${bundle_identifier}" || -z "${short_version}" || -z "${build_version}" ]]; then+ validation_fail "Required bundle metadata" "CFBundleIdentifier, CFBundleShortVersionString, or CFBundleVersion is missing"+ return 1+ fi+ validation_pass "Required bundle metadata"++ if ! architectures="$(lipo -archs "${executable_path}" 2>&1)"; then+ validation_fail "App architectures" "lipo could not inspect the main executable" "${architectures}"+ return 1+ fi++ if ! helper_architectures="$(lipo -archs "${helper_path}" 2>&1)"; then+ validation_fail "Helper architectures" "lipo could not inspect the helper executable" "${helper_architectures}"+ return 1+ fi+ validation_pass "Architectures inspected"++ validation_field "Path" "${app_path}"+ validation_field "Display name" "${display_name}"+ validation_field "Bundle identifier" "${bundle_identifier}"+ validation_field "Version" "${short_version} (${build_version})"+ validation_field "Minimum macOS" "${minimum_system_version}"+ validation_field "LSUIElement" "${ui_element}"+ validation_field "App architectures" "${architectures}"+ validation_field "Helper architectures" "${helper_architectures}"++ validation_section "Code signature"++ if ! command_output="$(codesign --verify --deep --strict --verbose=4 "${app_path}" 2>&1)"; then+ validation_fail "Deep strict app signature" "codesign rejected the app bundle" "${command_output}"+ return 1+ fi+ validation_pass "Deep strict app signature"++ for architecture in ${architectures}; do+ if ! command_output="$(codesign --verify --strict --verbose=4 --arch "${architecture}" "${app_path}" 2>&1)"; then+ validation_fail "App ${architecture} signature" "codesign rejected the ${architecture} slice" "${command_output}"+ return 1+ fi+ done+ validation_pass "App signature slices: ${architectures}"++ if ! command_output="$(codesign --verify --strict --verbose=4 "${helper_path}" 2>&1)"; then+ validation_fail "Helper signature" "codesign rejected the helper executable" "${command_output}"+ return 1+ fi+ validation_pass "Helper signature"++ for architecture in ${helper_architectures}; do+ if ! command_output="$(codesign --verify --strict --verbose=4 --arch "${architecture}" "${helper_path}" 2>&1)"; then+ validation_fail "Helper ${architecture} signature" "codesign rejected the helper ${architecture} slice" "${command_output}"+ return 1+ fi+ done+ validation_pass "Helper signature slices: ${helper_architectures}"++ if ! signature_details="$(codesign -d --verbose=4 "${app_path}" 2>&1)"; then+ validation_fail "App signature metadata" "codesign could not read the app signature" "${signature_details}"+ return 1+ fi++ if ! helper_signature_details="$(codesign -d --verbose=4 "${helper_path}" 2>&1)"; then+ validation_fail "Helper signature metadata" "codesign could not read the helper signature" "${helper_signature_details}"+ return 1+ fi++ signature_identifier="$(printf '%s\n' "${signature_details}" | awk -F= '/^Identifier=/ {print $2; exit}')"+ helper_signature_identifier="$(printf '%s\n' "${helper_signature_details}" | awk -F= '/^Identifier=/ {print $2; exit}')"+ signing_authority="$(printf '%s\n' "${signature_details}" | awk -F= '/^Authority=/ {print substr($0, index($0, "=") + 1); exit}')"+ signing_timestamp="$(printf '%s\n' "${signature_details}" | awk -F= '/^Timestamp=/ {print substr($0, index($0, "=") + 1); exit}')"+ signing_team="$(printf '%s\n' "${signature_details}" | awk -F= '/^TeamIdentifier=/ {print $2; exit}')"+ helper_signing_team="$(printf '%s\n' "${helper_signature_details}" | awk -F= '/^TeamIdentifier=/ {print $2; exit}')"+ signing_cdhash="$(printf '%s\n' "${signature_details}" | awk -F= '/^CDHash=/ {print $2; exit}')"++ if [[ "${signature_identifier}" != "${bundle_identifier}" ||+ "${helper_signature_identifier}" != "${bundle_identifier}.helper" ||+ -z "${signing_team}" || "${helper_signing_team}" != "${signing_team}" ]]; then+ validation_fail \+ "Code signature identifiers" \+ "Expected app ${bundle_identifier}, helper ${bundle_identifier}.helper, and one shared team; got app ${signature_identifier}, helper ${helper_signature_identifier}, teams ${signing_team:-none}/${helper_signing_team:-none}"+ return 1+ fi+ validation_pass "Code signature identifiers"++ if ! printf '%s\n' "${signature_details}" | grep -Eq '^CodeDirectory .*flags=.*\(runtime\)'; then+ validation_fail "App Hardened Runtime" "The app CodeDirectory does not contain the runtime flag"+ return 1+ fi+ validation_pass "App Hardened Runtime"++ if ! printf '%s\n' "${helper_signature_details}" | grep -Eq '^CodeDirectory .*flags=.*\(runtime\)'; then+ validation_fail "Helper Hardened Runtime" "The helper CodeDirectory does not contain the runtime flag"+ return 1+ fi+ validation_pass "Helper Hardened Runtime"++ if ! codesign --display --extract-certificates="${signing_certificate_prefix}" "${app_path}" >/dev/null 2>&1 || [[ ! -f "${signing_certificate}" ]]; then+ validation_fail "App signing certificate" "codesign could not extract the app leaf certificate"+ return 1+ fi++ if ! codesign --display --extract-certificates="${helper_signing_certificate_prefix}" "${helper_path}" >/dev/null 2>&1 || [[ ! -f "${helper_signing_certificate}" ]]; then+ validation_fail "Helper signing certificate" "codesign could not extract the helper leaf certificate"+ return 1+ fi++ if ! signing_certificate_sha1="$(certificate_sha1 "${signing_certificate}")"; then+ validation_fail "App signing certificate" "Unable to calculate the app certificate SHA-1"+ return 1+ fi++ if ! helper_signing_certificate_sha1="$(certificate_sha1 "${helper_signing_certificate}")"; then+ validation_fail "Helper signing certificate" "Unable to calculate the helper certificate SHA-1"+ return 1+ fi++ if [[ "${helper_signing_certificate_sha1}" != "${signing_certificate_sha1}" ]]; then+ validation_fail \+ "App and helper certificate match" \+ "App uses ${signing_certificate_sha1}, helper uses ${helper_signing_certificate_sha1}"+ return 1+ fi+ validation_pass "App and helper certificate match"++ expected_signing_certificate="$(read_plist_value "${EXPORT_OPTIONS_PLIST}" signingCertificate)"+ normalized_expected_certificate="$(printf '%s' "${expected_signing_certificate}" | tr -d ':' | tr '[:lower:]' '[:upper:]')"+ if [[ "${normalized_expected_certificate}" =~ ^[0-9A-F]{40}$ ]]; then+ if [[ "${signing_certificate_sha1}" != "${normalized_expected_certificate}" ]]; then+ validation_fail \+ "Export certificate match" \+ "ExportOptions requires ${normalized_expected_certificate}, app uses ${signing_certificate_sha1}"+ return 1+ fi+ validation_pass "Export certificate match"+ elif [[ -n "${expected_signing_certificate}" ]]; then+ export_certificate_selector="${expected_signing_certificate}"+ fi++ validation_field "App identifier" "${signature_identifier}"+ validation_field "Helper identifier" "${helper_signature_identifier}"+ validation_field "Authority" "${signing_authority}"+ validation_field "Team identifier" "${signing_team}"+ validation_field "App certificate SHA-1" "${signing_certificate_sha1}"+ validation_field "Helper certificate SHA-1" "${helper_signing_certificate_sha1}"+ validation_field "Timestamp" "${signing_timestamp:-none}"+ validation_field "CDHash" "${signing_cdhash}"+ if [[ -n "${export_certificate_selector}" ]]; then+ validation_field "Export certificate selector" "${export_certificate_selector}"+ fi++ validation_section "Entitlements"++ if ! codesign --display --entitlements="${main_entitlements}" --xml "${app_path}" >/dev/null 2>&1 || [[ ! -s "${main_entitlements}" ]]; then+ validation_fail "App entitlements" "codesign did not return an app entitlements plist"+ return 1+ fi+ validation_pass "App entitlements extracted"++ if ! codesign --display --entitlements="${helper_entitlements}" --xml "${helper_path}" >/dev/null 2>&1 || [[ ! -s "${helper_entitlements}" ]]; then+ validation_fail "Helper entitlements" "codesign did not return a helper entitlements plist"+ return 1+ fi+ validation_pass "Helper entitlements extracted"++ main_application_identifier="$(read_plist_value "${main_entitlements}" com.apple.application-identifier)"+ helper_application_identifier="$(read_plist_value "${helper_entitlements}" com.apple.application-identifier)"+ main_team_identifier="$(read_plist_value "${main_entitlements}" com.apple.developer.team-identifier)"+ debugger_entitlement="$(read_plist_value "${main_entitlements}" com.apple.security.get-task-allow)"+ helper_debugger_entitlement="$(read_plist_value "${helper_entitlements}" com.apple.security.get-task-allow)"+ icloud_environment="$(read_plist_compact_value "${main_entitlements}" com.apple.developer.icloud-container-environment)"+ icloud_containers="$(read_plist_compact_value "${main_entitlements}" com.apple.developer.icloud-container-identifiers)"+ icloud_services="$(read_plist_compact_value "${main_entitlements}" com.apple.developer.icloud-services)"+ if [[ "${debugger_entitlement}" == "true" || "${debugger_entitlement}" == "1" ]]; then+ app_debugger_status="allowed"+ fi+ if [[ "${helper_debugger_entitlement}" == "true" || "${helper_debugger_entitlement}" == "1" ]]; then+ helper_debugger_status="allowed"+ fi++ if [[ "${main_application_identifier}" != "${signing_team}.${bundle_identifier}" ||+ "${helper_application_identifier}" != "${signing_team}.${bundle_identifier}.helper" ]]; then+ validation_fail \+ "Entitlement application identifiers" \+ "Expected ${signing_team}.${bundle_identifier} and ${signing_team}.${bundle_identifier}.helper; got ${main_application_identifier:-none} and ${helper_application_identifier:-none}"+ return 1+ fi+ validation_pass "Entitlement application identifiers"++ if [[ "${CONFIGURATION}" == "Release" &&+ ("${app_debugger_status}" == "allowed" || "${helper_debugger_status}" == "allowed") ]]; then+ validation_fail \+ "Release debugger attachment" \+ "get-task-allow is enabled for app=${debugger_entitlement:-false}, helper=${helper_debugger_entitlement:-false}"+ return 1+ fi++ if ! command_output="$(plutil -p "${main_entitlements}" 2>&1)"; then+ validation_fail "App entitlements" "Unable to read app entitlements" "${command_output}"+ return 1+ fi++ if ! command_output="$(plutil -p "${helper_entitlements}" 2>&1)"; then+ validation_fail "Helper entitlements" "Unable to read helper entitlements" "${command_output}"+ return 1+ fi+ validation_pass "Debugger attachment policy"++ validation_field "App identifier" "${main_application_identifier}"+ validation_field "Helper identifier" "${helper_application_identifier}"+ validation_field "Team identifier" "${main_team_identifier}"+ validation_field "iCloud environment" "${icloud_environment}"+ validation_field "iCloud containers" "${icloud_containers}"+ validation_field "iCloud services" "${icloud_services}"+ validation_field "App debugger attachment" "${app_debugger_status}"+ validation_field "Helper debugger attachment" "${helper_debugger_status}"++ validation_section "LaunchDaemon"++ if [[ ! -d "${launch_daemons_path}" ]]; then+ validation_fail "LaunchDaemon directory" "Missing ${launch_daemons_path}"+ return 1+ fi++ if ! command_output="$(find "${launch_daemons_path}" -maxdepth 1 -type f -name '*.plist' 2>&1)"; then+ validation_fail "LaunchDaemon plist discovery" "Unable to read ${launch_daemons_path}" "${command_output}"+ return 1+ fi+ launch_daemon_count="$(printf '%s\n' "${command_output}" | awk 'NF {count++} END {print count + 0}')"+ launch_daemon_plist="$(printf '%s\n' "${command_output}" | sort | sed -n '1p')"+ if [[ "${launch_daemon_count}" -ne 1 || -z "${launch_daemon_plist}" ]]; then+ validation_fail "LaunchDaemon plist count" "Expected exactly 1 plist, found ${launch_daemon_count}"+ return 1+ fi++ launch_daemon_label="$(read_plist_value "${launch_daemon_plist}" Label)"+ launch_daemon_bundle_identifier="$(read_plist_value "${launch_daemon_plist}" AssociatedBundleIdentifiers:0)"+ launch_daemon_program="$(read_plist_value "${launch_daemon_plist}" BundleProgram)"+ if [[ "${launch_daemon_label}" != "${bundle_identifier}.helper" ||+ "${launch_daemon_bundle_identifier}" != "${bundle_identifier}" ||+ "${launch_daemon_program}" != "Contents/Resources/CodexBarHelper" ]]; then+ validation_fail \+ "LaunchDaemon configuration" \+ "Expected label ${bundle_identifier}.helper, bundle ${bundle_identifier}, and program Contents/Resources/CodexBarHelper; got ${launch_daemon_label:-none}, ${launch_daemon_bundle_identifier:-none}, ${launch_daemon_program:-none}"+ return 1+ fi+ validation_pass "LaunchDaemon configuration"++ validation_field "File" "$(basename "${launch_daemon_plist}")"+ validation_field "Label" "${launch_daemon_label}"+ validation_field "Associated bundle" "${launch_daemon_bundle_identifier}"+ validation_field "Program" "${launch_daemon_program}"++ validation_section "Provisioning profile"++ if [[ -f "${embedded_profile}" ]]; then+ if ! security cms -D -i "${embedded_profile}" > "${profile_plist}" 2> "${profile_decode_error}"; then+ validation_fail \+ "Embedded provisioning profile" \+ "security cms could not decode embedded.provisionprofile" \+ "$(< "${profile_decode_error}")"+ return 1+ fi+ validation_pass "Embedded provisioning profile decoded"++ profile_name="$(read_plist_value "${profile_plist}" Name)"+ profile_uuid="$(read_plist_value "${profile_plist}" UUID)"+ profile_team="$(read_plist_value "${profile_plist}" TeamIdentifier:0)"+ profile_application_identifier="$(read_plist_value "${profile_plist}" Entitlements:com.apple.application-identifier)"+ profile_expiration="$(read_plist_value "${profile_plist}" ExpirationDate)"+ if ! profile_certificate_count="$(+ plutil -extract DeveloperCertificates xml1 -o - "${profile_plist}" |+ awk '{line = $0; while (match(line, /<data>/)) {count++; line = substr(line, RSTART + RLENGTH)}} END {print count + 0}'+ )"; then+ validation_fail "Profile certificates" "DeveloperCertificates is missing or malformed"+ return 1+ fi++ if [[ "${profile_application_identifier}" != "${main_application_identifier}" || "${profile_team}" != "${signing_team}" ]]; then+ validation_fail \+ "Profile signature identity" \+ "Expected application ${main_application_identifier} and team ${signing_team}; got ${profile_application_identifier:-none} and ${profile_team:-none}"+ return 1+ fi+ validation_pass "Profile signature identity"++ if [[ "${profile_certificate_count}" -lt 1 ]]; then+ validation_fail "Profile certificates" "DeveloperCertificates contains no signing certificates"+ return 1+ fi++ for ((profile_certificate_index = 0; profile_certificate_index < profile_certificate_count; profile_certificate_index++)); do+ profile_certificate_path="${validation_dir}/profile-certificate-${profile_certificate_index}.der"+ if ! plutil -extract "DeveloperCertificates.${profile_certificate_index}" raw -o - "${profile_plist}" |+ base64 -D > "${profile_certificate_path}"; then+ validation_fail \+ "Profile certificate $((profile_certificate_index + 1))" \+ "Unable to decode the certificate from DeveloperCertificates"+ return 1+ fi+ if ! profile_certificate_sha1="$(certificate_sha1 "${profile_certificate_path}")"; then+ validation_fail \+ "Profile certificate $((profile_certificate_index + 1))" \+ "Unable to calculate the certificate SHA-1"+ return 1+ fi+ profile_certificate_sha1s+=("${profile_certificate_sha1}")+ if [[ "${profile_certificate_sha1}" == "${signing_certificate_sha1}" ]]; then+ profile_certificate_match_count=$((profile_certificate_match_count + 1))+ fi+ done+ validation_pass "Profile certificates decoded"++ if [[ "${profile_certificate_match_count}" -lt 1 ]]; then+ validation_fail \+ "App certificate authorization" \+ "App certificate ${signing_certificate_sha1} is not listed in the embedded profile"+ return 1+ fi+ validation_pass "App certificate authorization"++ expected_profile="$(read_plist_value "${EXPORT_OPTIONS_PLIST}" "provisioningProfiles:${bundle_identifier}")"+ if [[ -n "${expected_profile}" ]]; then+ if [[ "${expected_profile}" != "${profile_uuid}" && "${expected_profile}" != "${profile_name}" ]]; then+ validation_fail \+ "Export profile match" \+ "ExportOptions requires ${expected_profile}, embedded profile is ${profile_name} (${profile_uuid})"+ return 1+ fi+ validation_pass "Export profile match"+ fi++ if ! command_output="$(plutil -extract Entitlements xml1 -o "${profile_entitlements}" "${profile_plist}" 2>&1)"; then+ validation_fail "Profile entitlements" "Unable to extract authorized entitlements" "${command_output}"+ return 1+ fi+ if ! command_output="$(plutil -p "${profile_entitlements}" 2>&1)"; then+ validation_fail "Profile entitlements" "Unable to read authorized entitlements" "${command_output}"+ return 1+ fi+ profile_icloud_environment="$(read_plist_compact_value "${profile_entitlements}" com.apple.developer.icloud-container-environment)"+ profile_icloud_containers="$(read_plist_compact_value "${profile_entitlements}" com.apple.developer.icloud-container-identifiers)"+ profile_icloud_services="$(read_plist_compact_value "${profile_entitlements}" com.apple.developer.icloud-services)"+ profile_ubiquity_containers="$(read_plist_compact_value "${profile_entitlements}" com.apple.developer.ubiquity-container-identifiers)"+ profile_ubiquity_kvstore="$(read_plist_compact_value "${profile_entitlements}" com.apple.developer.ubiquity-kvstore-identifier)"+ profile_keychain_access_groups="$(read_plist_compact_value "${profile_entitlements}" keychain-access-groups)"+ validation_pass "Profile entitlements"++ validation_field "Name" "${profile_name}"+ validation_field "UUID" "${profile_uuid}"+ validation_field "Team identifier" "${profile_team}"+ validation_field "Application identifier" "${profile_application_identifier}"+ validation_field "Expiration" "${profile_expiration}"+ validation_field "Authorized certificates" "${profile_certificate_count}"+ for ((profile_certificate_index = 0; profile_certificate_index < profile_certificate_count; profile_certificate_index++)); do+ validation_field \+ "Certificate $((profile_certificate_index + 1)) SHA-1" \+ "${profile_certificate_sha1s[${profile_certificate_index}]}"+ done+ validation_field "iCloud environment" "${profile_icloud_environment}"+ validation_field "iCloud containers" "${profile_icloud_containers}"+ validation_field "iCloud services" "${profile_icloud_services}"+ validation_field "Ubiquity containers" "${profile_ubiquity_containers}"+ validation_field "Ubiquity KV store" "${profile_ubiquity_kvstore}"+ validation_field "Keychain access groups" "${profile_keychain_access_groups}"+ elif [[ -n "${icloud_containers}" ]]; then+ validation_fail "Embedded provisioning profile" "CloudKit entitlements require embedded.provisionprofile"+ return 1+ else+ validation_pass "Provisioning profile not required"+ fi++ validation_section "Distribution"++ if [[ "${SKIP_NOTARIZATION}" == "1" ]]; then+ validation_skip "Notarization ticket"+ validation_skip "Gatekeeper assessment"+ else+ if ! command_output="$(xcrun stapler validate "${app_path}" 2>&1)"; then+ validation_fail "Notarization ticket" "stapler could not validate the ticket" "${command_output}"+ return 1+ fi+ validation_pass "Notarization ticket"++ if [[ "${SPCTL_ASSESS}" == "1" ]]; then+ if ! command_output="$(spctl --assess --type execute --verbose=4 "${app_path}" 2>&1)"; then+ validation_fail "Gatekeeper assessment" "spctl rejected the app" "${command_output}"+ return 1+ fi+ gatekeeper_source="$(printf '%s\n' "${command_output}" | awk -F= '/^source=/ {print substr($0, index($0, "=") + 1); exit}')"+ validation_pass "Gatekeeper assessment"+ validation_field "Gatekeeper source" "${gatekeeper_source}"+ else+ validation_skip "Gatekeeper assessment"+ fi+ fi++ validation_summary "Final app validation passed"+}diff --git a/Scripts/performance/__main__.py b/Scripts/performance/__main__.pyindex 02a75dc..659ff41 100644--- a/Scripts/performance/__main__.py+++ b/Scripts/performance/__main__.py@@ -1,48 +1,28 @@"""Non-invasive profiling of an already running macOS app, using xctrace"""import argparse-import ctypesimport datetime as dtimport hashlibimport jsonimport osimport platform-import plistlib-import reimport signal-import subprocessimport sysimport tempfileimport time-import xml.etree.ElementTree as ETfrom pathlib import Pathfrom types import FrameType-from typing import Literal, cast+from typing import castsys.dont_write_bytecode = True-from .analyze import (- Table,- event_summary,- profile_summary,- resource_summary,- system_summary,-)-from .performance import write_report-from .models import (- CommandResult, Comparison, Phase, PhasePlan, ProcessIdentity, Report, SchemaKey, Schemas, Target,-)+from .capture import capture, inspect_target, load_schemas, now, optional, record_phase, save, status+from .compare import compare+from .report import write_report+from .models import Phase, PhasePlan, ReportVERSION = "1"ROOT = Path(__file__).resolve().parents[2]-SCHEMAS: tuple[SchemaKey, ...] = (- "activity-monitor-process-live",- "time-profile",- "potential-hangs",- "hang-risks",- "device-thermal-state-intervals",- "activity-monitor-system",-)PRESETS = {"quick": (5, 30, 2, 90, 30),"standard": (20, 60, 4, 300, 60),@@ -62,372 +42,6 @@ class Arguments(argparse.Namespace):render: Path | None-def now() -> str:- return dt.datetime.now().astimezone().isoformat(timespec="seconds")---def status(message: str) -> None:- print(f"[{now()}] {message}", flush=True)---def capture(args: list[str], timeout: float = 20) -> str:- result = subprocess.run(args, capture_output=True, timeout=timeout)- if result.returncode:- raise RuntimeError(- f"{args[0]} exited {result.returncode}: {result.stderr.decode(errors='replace')[-1000:]}"- )- return result.stdout.decode(errors="replace").strip()---def optional(args: list[str]) -> str | None:- try:- return capture(args)- except (OSError, RuntimeError, subprocess.TimeoutExpired):- return None---def process_path(pid: int) -> Path | None:- lib = ctypes.CDLL("/usr/lib/libproc.dylib")- lib.proc_pidpath.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32]- lib.proc_pidpath.restype = ctypes.c_int- buffer = ctypes.create_string_buffer(4096)- size = lib.proc_pidpath(pid, buffer, len(buffer))- return Path(os.fsdecode(buffer.value)).resolve() if size > 0 else None---def identity(pid: int) -> ProcessIdentity:- path = process_path(pid)- started = optional(["/bin/ps", "-p", str(pid), "-o", "lstart="])- return {"pid": pid, "path": str(path) if path else None, "started": started}---def inspect_target(app: Path, pid: int | None) -> Target:- info = plistlib.loads((app / "Contents/Info.plist").read_bytes())- executable = (app / "Contents/MacOS" / info["CFBundleExecutable"]).resolve()- if not executable.is_file():- raise ValueError("App executable does not exist")- if pid is None:- candidates = [int(p) for p in capture(["/bin/ps", "-A", "-o", "pid="]).split()]- matches = [p for p in candidates if process_path(p) == executable]- if len(matches) != 1:- raise ValueError(- f"Expected one running instance of {app.name}, found {len(matches)}; specify --pid"- )- pid = matches[0]- original = identity(pid)- if original["path"] != str(executable) or not original["started"]:- raise ValueError("PID does not match the requested app executable")- entitlements = subprocess.run(- ["/usr/bin/codesign", "-d", "--entitlements", ":-", str(app)],- capture_output=True,- timeout=20,- )- ent = None- for stream in (entitlements.stdout, entitlements.stderr):- start = stream.find(b"<?xml")- end = stream.find(b"</plist>")- if 0 <= start <= end:- ent = plistlib.loads(stream[start: end + len(b"</plist>")])- break- uuids = optional(["/usr/bin/xcrun", "dwarfdump", "--uuid", str(executable)])- uuid_list = re.findall(r"UUID: ([A-Fa-f0-9-]+) \(([^)]+)\)", uuids or "")- with executable.open("rb") as file:- binary_hash = hashlib.file_digest(file, "sha256").hexdigest()- return {- "name": app.stem,- "bundle_id": info.get("CFBundleIdentifier"),- "version": info.get("CFBundleShortVersionString"),- "build": info.get("CFBundleVersion"),- "binary_sha256": binary_hash,- "uuids": uuid_list,- "get_task_allow": bool(ent.get("com.apple.security.get-task-allow"))- if ent is not None- else None,- "identity": original,- }---def load_schemas(developer: str) -> Schemas:- base = Path(developer).parent / "Applications/Instruments.app/Contents/Packages"- found: Schemas = {}- for path in base.rglob("schemas.xml"):- for schema in ET.parse(path).getroot().findall("schema"):- name = schema.get("name")- for known_name in SCHEMAS:- if name != known_name:- continue- columns = [c.get("mnemonic") for c in schema.findall("column")]- if any(column is None for column in columns):- raise ValueError(f"Missing column mnemonic in schema: {name}")- found[known_name] = [column for column in columns if column is not None]- if "activity-monitor-process-live" not in found:- raise RuntimeError(- "No Activity Monitor column schema found in the selected Xcode"- )- return found---def run_command(- args: list[str], logfile: Path, timeout: float, expected: ProcessIdentity | None = None,-) -> CommandResult:- began = time.monotonic()- interrupted = False- failure = None- directory = logfile.parent.stat()-- def check_output() -> None:- try:- current = logfile.parent.stat()- if (current.st_dev, current.st_ino) == (directory.st_dev, directory.st_ino):- return- except FileNotFoundError:- pass- raise RuntimeError(- f"Output directory removed or replaced during capture: {logfile.parent}"- )-- with logfile.open("w") as log:- process = subprocess.Popen(- args, stdout=log, stderr=subprocess.STDOUT, start_new_session=True- )- try:- while process.poll() is None:- check_output()- elapsed = time.monotonic() - began- if elapsed >= timeout:- failure = "Command timeout"- break- if expected and identity(expected["pid"]) != expected:- failure = "Target exited or process identity changed"- break- time.sleep(1)- except KeyboardInterrupt:- interrupted = True- finally:- if process.poll() is None:- os.killpg(process.pid, signal.SIGINT)- try:- process.wait(timeout=20)- except subprocess.TimeoutExpired:- os.killpg(process.pid, signal.SIGKILL)- process.wait(timeout=10)- check_output()- result: CommandResult = {- "argv": args,- "exit_code": process.returncode,- "elapsed_s": round(time.monotonic() - began, 2),- "log": logfile.name,- }- if failure:- result["error"] = failure- if interrupted:- raise KeyboardInterrupt- return result---def save(data: Report, output: Path) -> None:- temporary = output / "performance.json.tmp"- temporary.write_text(- json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False) + "\n"- )- temporary.replace(output / "performance.json")- write_report(data, output / "performance.html")---def analyze_phase(phase: Phase, output: Path, schemas: Schemas, pid: int) -> None:- for name, columns in schemas.items():- file = output / f"{phase['id']}-{name}.xml"- if not file.exists() or name not in phase.get("exported", []):- continue- try:- table = Table(file, columns)- if name == "activity-monitor-process-live":- phase["resources"] = resource_summary(table, pid)- elif name == "time-profile":- phase["profile"] = profile_summary(table, pid)- elif name == "activity-monitor-system":- phase["system"] = system_summary(table)- else:- phase[name] = event_summary(- table, pid if name in ("potential-hangs", "hang-risks") else None- )- except (ValueError, KeyError, ET.ParseError, TypeError) as error:- phase.setdefault("errors", []).append(f"{name}: {error}")---def record_phase(phase: Phase, data: Report, output: Path, schemas: Schemas) -> None:- target = data["target"].get("identity")- if target is None:- raise RuntimeError("Target process identity is unavailable")- if identity(target["pid"]) != target:- raise RuntimeError("Target process changed before recording")- phase["started"] = now()- errors: list[str] = []- commands: list[CommandResult] = []- exported: list[SchemaKey] = []- phase["errors"] = errors- phase["commands"] = commands- phase["exported"] = exported- phase["trace"] = phase["id"] + ".trace"- args = [- "/usr/bin/xcrun",- "xctrace",- "record",- "--template",- phase["template"],- "--attach",- str(target["pid"]),- "--time-limit",- f"{phase['seconds']}s",- "--output",- str(output / phase["trace"]),- "--no-prompt",- ]- if phase["template"] == "Time Profiler":- args.extend(["--instrument", "Activity Monitor"])- command = run_command(- args, output / f"{phase['id']}-record.log", phase["seconds"] + 150, target- )- commands.append(command)- if command["exit_code"] or command.get("error"):- errors.append(- command.get("error", "xctrace recording failed; see record log")- )- elif "[Error]" in (output / command["log"]).read_text(errors="replace"):- errors.append("xctrace reported an error despite a zero exit code")- if identity(target["pid"]) != target:- errors.append("Target identity changed during recording")- trace = output / phase["trace"]- if not trace.exists():- errors.append("No trace artifact was created")- return- toc = output / f"{phase['id']}-toc.xml"- cmd = run_command(- [- "/usr/bin/xcrun",- "xctrace",- "export",- "--input",- str(trace),- "--toc",- "--output",- str(toc),- ],- output / f"{phase['id']}-toc.log",- 120,- )- commands.append(cmd)- if cmd["exit_code"] or cmd.get("error"):- errors.append("TOC export failed")- return- root = ET.parse(toc).getroot()- duration = root.findtext(".//summary/duration", "0")- phase["recorded_s"] = float(duration)- phase["trace_started"] = root.findtext(".//summary/start-date")- phase["hang_settings"] = [- e.text for e in root.findall(".//instrument[@name='Hangs']//key")- ]- phase["tables"] = [e.get("schema") for e in root.findall(".//data/table")]- if phase["recorded_s"] < phase["seconds"] * 0.9:- errors.append("Recording duration below 90% of requested duration")- for name in SCHEMAS:- if name not in phase["tables"] or name not in schemas:- continue- xml = output / f"{phase['id']}-{name}.xml"- cmd = run_command(- [- "/usr/bin/xcrun",- "xctrace",- "export",- "--input",- str(trace),- "--xpath",- f'/trace-toc/run[@number="1"]/data/table[@schema="{name}"]',- "--output",- str(xml),- ],- output / f"{phase['id']}-{name}.log",- 120,- )- commands.append(cmd)- if cmd["exit_code"] or cmd.get("error"):- errors.append(f"{name}: export failed")- else:- exported.append(name)- analyze_phase(phase, output, schemas, target["pid"])- if "resources" not in phase:- errors.append("No valid resource measurements")- else:- resource = phase["resources"]- errors.extend(resource["errors"])- if resource["span_s"] < phase["seconds"] * 0.8:- errors.append("Resource coverage below 80% of requested duration")- if resource["max_gap_s"] > 5:- errors.append("Resource sample gap exceeds 5 seconds")- if resource["cpu_coverage"] < 0.95:- errors.append("CPU sample coverage below 95%")- if resource.get("footprint") is None:- errors.append("Physical footprint was not available")- if phase["template"] == "Time Profiler" and "profile" not in phase:- errors.append("No decoded CPU profile")- phase["ended"] = now()---def compare(data: Report, path: Path) -> Comparison:- previous = cast(Report, json.loads(path.read_text()))- keys: list[tuple[Literal["target", "environment", "config"], str]] = [- ("target", "bundle_id"),- ("environment", "os"),- ("environment", "chip"),- ("environment", "arch"),- ("environment", "cores"),- ("environment", "memory_bytes"),- ("environment", "power_source"),- ("environment", "instruments"),- ("config", "workload"),- ("config", "preset"),- ("config", "cpu_mean_budget"),- ("config", "footprint_budget"),- ]- differences = [- f"{a}.{b}"- for a, b in keys- if data.get(a, {}).get(b) != previous.get(a, {}).get(b)- ]- if data.get("format_version") != previous.get("format_version"):- differences.append("format_version")- if previous.get("state") != "complete":- differences.append("baseline.state")- if data.get("state") != "complete":- differences.append("current.state")- if [(p["id"], p["seconds"]) for p in data["phases"]] != [- (p["id"], p["seconds"]) for p in previous.get("phases", [])- ]:- differences.append("phase_plan")- result: Comparison = {- "baseline_version": previous.get("target", {}).get("version"),- "compatible": not differences,- "differences": differences,- "deltas": [],- }- if not differences:- for current, old in zip(data["phases"], previous["phases"]):- a, b = current.get("resources"), old.get("resources")- if a and b and not current.get("errors") and not old.get("errors"):- current_cpu, old_cpu = a["cpu_mean"], b["cpu_mean"]- current_memory, old_memory = a["footprint"], b["footprint"]- if current_cpu is None or old_cpu is None or current_memory is None or old_memory is None:- raise ValueError("Complete phases must contain CPU and footprint measurements")- result["deltas"].append(- {- "phase": current["id"],- "cpu_pp": current_cpu - old_cpu,- "footprint_mib": current_memory["median"] - old_memory["median"],- }- )- return result--def main() -> int:parser = argparse.ArgumentParser(prog="python3 -m Scripts.performance", description=__doc__@@ -492,7 +106,9 @@ def main() -> int:"__main__.py","analyze.py","models.py",- "performance.py",+ "capture.py",+ "compare.py",+ "report.py","performance.html",):source = Path(__file__).with_name(name).read_bytes()diff --git a/Scripts/performance/capture.py b/Scripts/performance/capture.pynew file mode 100644index 0000000..d19e594--- /dev/null+++ b/Scripts/performance/capture.py@@ -0,0 +1,345 @@+"""Non-invasive profiling of an already running macOS app, using xctrace"""++import ctypes+import datetime as dt+import hashlib+import json+import os+import plistlib+import re+import signal+import subprocess+import time+import xml.etree.ElementTree as ET+from pathlib import Path+++from .analyze import (+ Table,+ event_summary,+ profile_summary,+ resource_summary,+ system_summary,+)+from .report import write_report+from .models import (CommandResult, Phase, ProcessIdentity, Report, SchemaKey, Schemas, Target)++SCHEMAS: tuple[SchemaKey, ...] = (+ "activity-monitor-process-live",+ "time-profile",+ "potential-hangs",+ "hang-risks",+ "device-thermal-state-intervals",+ "activity-monitor-system",+)+++def now() -> str:+ return dt.datetime.now().astimezone().isoformat(timespec="seconds")+++def status(message: str) -> None:+ print(f"[{now()}] {message}", flush=True)+++def capture(args: list[str], timeout: float = 20) -> str:+ result = subprocess.run(args, capture_output=True, timeout=timeout)+ if result.returncode:+ raise RuntimeError(+ f"{args[0]} exited {result.returncode}: {result.stderr.decode(errors='replace')[-1000:]}"+ )+ return result.stdout.decode(errors="replace").strip()+++def optional(args: list[str]) -> str | None:+ try:+ return capture(args)+ except (OSError, RuntimeError, subprocess.TimeoutExpired):+ return None+++def process_path(pid: int) -> Path | None:+ lib = ctypes.CDLL("/usr/lib/libproc.dylib")+ lib.proc_pidpath.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32]+ lib.proc_pidpath.restype = ctypes.c_int+ buffer = ctypes.create_string_buffer(4096)+ size = lib.proc_pidpath(pid, buffer, len(buffer))+ return Path(os.fsdecode(buffer.value)).resolve() if size > 0 else None+++def identity(pid: int) -> ProcessIdentity:+ path = process_path(pid)+ started = optional(["/bin/ps", "-p", str(pid), "-o", "lstart="])+ return {"pid": pid, "path": str(path) if path else None, "started": started}+++def inspect_target(app: Path, pid: int | None) -> Target:+ info = plistlib.loads((app / "Contents/Info.plist").read_bytes())+ executable = (app / "Contents/MacOS" / info["CFBundleExecutable"]).resolve()+ if not executable.is_file():+ raise ValueError("App executable does not exist")+ if pid is None:+ candidates = [int(p) for p in capture(["/bin/ps", "-A", "-o", "pid="]).split()]+ matches = [p for p in candidates if process_path(p) == executable]+ if len(matches) != 1:+ raise ValueError(+ f"Expected one running instance of {app.name}, found {len(matches)}; specify --pid"+ )+ pid = matches[0]+ original = identity(pid)+ if original["path"] != str(executable) or not original["started"]:+ raise ValueError("PID does not match the requested app executable")+ entitlements = subprocess.run(+ ["/usr/bin/codesign", "-d", "--entitlements", ":-", str(app)],+ capture_output=True,+ timeout=20,+ )+ ent = None+ for stream in (entitlements.stdout, entitlements.stderr):+ start = stream.find(b"<?xml")+ end = stream.find(b"</plist>")+ if 0 <= start <= end:+ ent = plistlib.loads(stream[start: end + len(b"</plist>")])+ break+ uuids = optional(["/usr/bin/xcrun", "dwarfdump", "--uuid", str(executable)])+ uuid_list = re.findall(r"UUID: ([A-Fa-f0-9-]+) \(([^)]+)\)", uuids or "")+ with executable.open("rb") as file:+ binary_hash = hashlib.file_digest(file, "sha256").hexdigest()+ return {+ "name": app.stem,+ "bundle_id": info.get("CFBundleIdentifier"),+ "version": info.get("CFBundleShortVersionString"),+ "build": info.get("CFBundleVersion"),+ "binary_sha256": binary_hash,+ "uuids": uuid_list,+ "get_task_allow": bool(ent.get("com.apple.security.get-task-allow"))+ if ent is not None+ else None,+ "identity": original,+ }+++def load_schemas(developer: str) -> Schemas:+ base = Path(developer).parent / "Applications/Instruments.app/Contents/Packages"+ found: Schemas = {}+ for path in base.rglob("schemas.xml"):+ for schema in ET.parse(path).getroot().findall("schema"):+ name = schema.get("name")+ for known_name in SCHEMAS:+ if name != known_name:+ continue+ columns = [c.get("mnemonic") for c in schema.findall("column")]+ if any(column is None for column in columns):+ raise ValueError(f"Missing column mnemonic in schema: {name}")+ found[known_name] = [column for column in columns if column is not None]+ if "activity-monitor-process-live" not in found:+ raise RuntimeError(+ "No Activity Monitor column schema found in the selected Xcode"+ )+ return found+++def run_command(+ args: list[str], logfile: Path, timeout: float, expected: ProcessIdentity | None = None,+) -> CommandResult:+ began = time.monotonic()+ interrupted = False+ failure = None+ directory = logfile.parent.stat()++ def check_output() -> None:+ try:+ current = logfile.parent.stat()+ if (current.st_dev, current.st_ino) == (directory.st_dev, directory.st_ino):+ return+ except FileNotFoundError:+ pass+ raise RuntimeError(+ f"Output directory removed or replaced during capture: {logfile.parent}"+ )++ with logfile.open("w") as log:+ process = subprocess.Popen(+ args, stdout=log, stderr=subprocess.STDOUT, start_new_session=True+ )+ try:+ while process.poll() is None:+ check_output()+ elapsed = time.monotonic() - began+ if elapsed >= timeout:+ failure = "Command timeout"+ break+ if expected and identity(expected["pid"]) != expected:+ failure = "Target exited or process identity changed"+ break+ time.sleep(1)+ except KeyboardInterrupt:+ interrupted = True+ finally:+ if process.poll() is None:+ os.killpg(process.pid, signal.SIGINT)+ try:+ process.wait(timeout=20)+ except subprocess.TimeoutExpired:+ os.killpg(process.pid, signal.SIGKILL)+ process.wait(timeout=10)+ check_output()+ result: CommandResult = {+ "argv": args,+ "exit_code": process.returncode,+ "elapsed_s": round(time.monotonic() - began, 2),+ "log": logfile.name,+ }+ if failure:+ result["error"] = failure+ if interrupted:+ raise KeyboardInterrupt+ return result+++def save(data: Report, output: Path) -> None:+ temporary = output / "performance.json.tmp"+ temporary.write_text(+ json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False) + "\n"+ )+ temporary.replace(output / "performance.json")+ write_report(data, output / "performance.html")+++def analyze_phase(phase: Phase, output: Path, schemas: Schemas, pid: int) -> None:+ for name, columns in schemas.items():+ file = output / f"{phase['id']}-{name}.xml"+ if not file.exists() or name not in phase.get("exported", []):+ continue+ try:+ table = Table(file, columns)+ if name == "activity-monitor-process-live":+ phase["resources"] = resource_summary(table, pid)+ elif name == "time-profile":+ phase["profile"] = profile_summary(table, pid)+ elif name == "activity-monitor-system":+ phase["system"] = system_summary(table)+ else:+ phase[name] = event_summary(+ table, pid if name in ("potential-hangs", "hang-risks") else None+ )+ except (ValueError, KeyError, ET.ParseError, TypeError) as error:+ phase.setdefault("errors", []).append(f"{name}: {error}")+++def record_phase(phase: Phase, data: Report, output: Path, schemas: Schemas) -> None:+ target = data["target"].get("identity")+ if target is None:+ raise RuntimeError("Target process identity is unavailable")+ if identity(target["pid"]) != target:+ raise RuntimeError("Target process changed before recording")+ phase["started"] = now()+ errors: list[str] = []+ commands: list[CommandResult] = []+ exported: list[SchemaKey] = []+ phase["errors"] = errors+ phase["commands"] = commands+ phase["exported"] = exported+ phase["trace"] = phase["id"] + ".trace"+ args = [+ "/usr/bin/xcrun",+ "xctrace",+ "record",+ "--template",+ phase["template"],+ "--attach",+ str(target["pid"]),+ "--time-limit",+ f"{phase['seconds']}s",+ "--output",+ str(output / phase["trace"]),+ "--no-prompt",+ ]+ if phase["template"] == "Time Profiler":+ args.extend(["--instrument", "Activity Monitor"])+ command = run_command(+ args, output / f"{phase['id']}-record.log", phase["seconds"] + 150, target+ )+ commands.append(command)+ if command["exit_code"] or command.get("error"):+ errors.append(+ command.get("error", "xctrace recording failed; see record log")+ )+ elif "[Error]" in (output / command["log"]).read_text(errors="replace"):+ errors.append("xctrace reported an error despite a zero exit code")+ if identity(target["pid"]) != target:+ errors.append("Target identity changed during recording")+ trace = output / phase["trace"]+ if not trace.exists():+ errors.append("No trace artifact was created")+ return+ toc = output / f"{phase['id']}-toc.xml"+ cmd = run_command(+ [+ "/usr/bin/xcrun",+ "xctrace",+ "export",+ "--input",+ str(trace),+ "--toc",+ "--output",+ str(toc),+ ],+ output / f"{phase['id']}-toc.log",+ 120,+ )+ commands.append(cmd)+ if cmd["exit_code"] or cmd.get("error"):+ errors.append("TOC export failed")+ return+ root = ET.parse(toc).getroot()+ duration = root.findtext(".//summary/duration", "0")+ phase["recorded_s"] = float(duration)+ phase["trace_started"] = root.findtext(".//summary/start-date")+ phase["hang_settings"] = [+ e.text for e in root.findall(".//instrument[@name='Hangs']//key")+ ]+ phase["tables"] = [e.get("schema") for e in root.findall(".//data/table")]+ if phase["recorded_s"] < phase["seconds"] * 0.9:+ errors.append("Recording duration below 90% of requested duration")+ for name in SCHEMAS:+ if name not in phase["tables"] or name not in schemas:+ continue+ xml = output / f"{phase['id']}-{name}.xml"+ cmd = run_command(+ [+ "/usr/bin/xcrun",+ "xctrace",+ "export",+ "--input",+ str(trace),+ "--xpath",+ f'/trace-toc/run[@number="1"]/data/table[@schema="{name}"]',+ "--output",+ str(xml),+ ],+ output / f"{phase['id']}-{name}.log",+ 120,+ )+ commands.append(cmd)+ if cmd["exit_code"] or cmd.get("error"):+ errors.append(f"{name}: export failed")+ else:+ exported.append(name)+ analyze_phase(phase, output, schemas, target["pid"])+ if "resources" not in phase:+ errors.append("No valid resource measurements")+ else:+ resource = phase["resources"]+ errors.extend(resource["errors"])+ if resource["span_s"] < phase["seconds"] * 0.8:+ errors.append("Resource coverage below 80% of requested duration")+ if resource["max_gap_s"] > 5:+ errors.append("Resource sample gap exceeds 5 seconds")+ if resource["cpu_coverage"] < 0.95:+ errors.append("CPU sample coverage below 95%")+ if resource.get("footprint") is None:+ errors.append("Physical footprint was not available")+ if phase["template"] == "Time Profiler" and "profile" not in phase:+ errors.append("No decoded CPU profile")+ phase["ended"] = now()diff --git a/Scripts/performance/compare.py b/Scripts/performance/compare.pynew file mode 100644index 0000000..5992331--- /dev/null+++ b/Scripts/performance/compare.py@@ -0,0 +1,59 @@+import json+from pathlib import Path+from typing import Literal, cast++from .models import Comparison, Report++def compare(data: Report, path: Path) -> Comparison:+ previous = cast(Report, json.loads(path.read_text()))+ keys: list[tuple[Literal["target", "environment", "config"], str]] = [+ ("target", "bundle_id"),+ ("environment", "os"),+ ("environment", "chip"),+ ("environment", "arch"),+ ("environment", "cores"),+ ("environment", "memory_bytes"),+ ("environment", "power_source"),+ ("environment", "instruments"),+ ("config", "workload"),+ ("config", "preset"),+ ("config", "cpu_mean_budget"),+ ("config", "footprint_budget"),+ ]+ differences = [+ f"{a}.{b}"+ for a, b in keys+ if data.get(a, {}).get(b) != previous.get(a, {}).get(b)+ ]+ if data.get("format_version") != previous.get("format_version"):+ differences.append("format_version")+ if previous.get("state") != "complete":+ differences.append("baseline.state")+ if data.get("state") != "complete":+ differences.append("current.state")+ if [(p["id"], p["seconds"]) for p in data["phases"]] != [+ (p["id"], p["seconds"]) for p in previous.get("phases", [])+ ]:+ differences.append("phase_plan")+ result: Comparison = {+ "baseline_version": previous.get("target", {}).get("version"),+ "compatible": not differences,+ "differences": differences,+ "deltas": [],+ }+ if not differences:+ for current, old in zip(data["phases"], previous["phases"]):+ a, b = current.get("resources"), old.get("resources")+ if a and b and not current.get("errors") and not old.get("errors"):+ current_cpu, old_cpu = a["cpu_mean"], b["cpu_mean"]+ current_memory, old_memory = a["footprint"], b["footprint"]+ if current_cpu is None or old_cpu is None or current_memory is None or old_memory is None:+ raise ValueError("Complete phases must contain CPU and footprint measurements")+ result["deltas"].append(+ {+ "phase": current["id"],+ "cpu_pp": current_cpu - old_cpu,+ "footprint_mib": current_memory["median"] - old_memory["median"],+ }+ )+ return resultdiff --git a/Scripts/performance/performance.py b/Scripts/performance/report.pysimilarity index 100%rename from Scripts/performance/performance.pyrename to Scripts/performance/report.pydiff --git a/Shared/BoundedProcess.swift b/Shared/BoundedProcess.swiftnew file mode 100644index 0000000..6c8428c--- /dev/null+++ b/Shared/BoundedProcess.swift@@ -0,0 +1,68 @@+import Darwin+import Foundation++/// 同步调用必须在非主队列执行, 管道读取和进程终止均有期限+nonisolated enum BoundedProcess {+ struct Result {+ let exitCode: Int32+ let output: String+ let timedOut: Bool+ let runningProcess: Process?+ }++ static func run(executable: URL, arguments: [String], timeout: TimeInterval = 2.5) -> Result {+ let process = Process()+ process.executableURL = executable+ process.arguments = arguments+ let pipe = Pipe()+ process.standardOutput = pipe+ process.standardError = pipe+ do { try process.run() } catch {+ return Result(exitCode: -1, output: error.localizedDescription, timedOut: false, runningProcess: nil)+ }+ pipe.fileHandleForWriting.closeFile()+ let descriptor = pipe.fileHandleForReading.fileDescriptor+ _ = fcntl(descriptor, F_SETFL, O_NONBLOCK)+ defer { pipe.fileHandleForReading.closeFile() }+ let clock = ContinuousClock()+ let deadline = clock.now.advanced(by: .seconds(max(0, timeout)))+ let killDeadline = deadline.advanced(by: .milliseconds(250))+ let end = killDeadline.advanced(by: .milliseconds(500))+ var output = Data()+ var buffer = [UInt8](repeating: 0, count: 8192)+ var terminated = false+ var killed = false+ while true {+ // 每轮读取有界, 持续输出不能阻止检查超时+ for _ in 0 ..< 8 {+ let count = Darwin.read(descriptor, &buffer, buffer.count)+ guard count > 0 else { break }+ if output.count < 65536 {+ output.append(contentsOf: buffer.prefix(min(count, 65536 - output.count)))+ }+ }+ if !process.isRunning {+ break+ }+ if clock.now >= deadline, !terminated {+ terminated = true+ process.terminate()+ }+ if clock.now >= killDeadline, !killed {+ killed = true+ kill(process.processIdentifier, SIGKILL)+ }+ if clock.now >= end {+ break+ }+ Thread.sleep(forTimeInterval: 0.01)+ }+ let running = process.isRunning+ return Result(+ exitCode: terminated || running ? -1 : process.terminationStatus,+ output: String(decoding: output, as: UTF8.self),+ timedOut: terminated,+ runningProcess: running ? process : nil+ )+ }+}