CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
feat: 增强工作流同步与通知设置并发布 3.3.10
Bobb281d04ac403
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex 5fc6b74..3ed7f0b 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -274,7 +274,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 47;+ CURRENT_PROJECT_VERSION = 48;DEAD_CODE_STRIPPING = YES;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;@@ -290,7 +290,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 3.3.9;+ MARKETING_VERSION = 3.3.10;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";REGISTER_APP_GROUPS = YES;@@ -313,7 +313,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 47;+ CURRENT_PROJECT_VERSION = 48;DEAD_CODE_STRIPPING = YES;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;@@ -329,7 +329,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 3.3.9;+ MARKETING_VERSION = 3.3.10;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";diff --git a/CodexBar/Controllers/NotificationOptionsPanelController.swift b/CodexBar/Controllers/NotificationOptionsPanelController.swiftindex 5c49ee4..159f25e 100644--- a/CodexBar/Controllers/NotificationOptionsPanelController.swift+++ b/CodexBar/Controllers/NotificationOptionsPanelController.swift@@ -14,6 +14,7 @@ nonisolated enum NotificationOptionsPanelAction: Equatable {final class NotificationOptionsPanelController {private let notificationSettings: NotificationSettingsprivate let codexHookSettings: CodexHookSettings+ private let codexCLINotificationSettings: CodexCLINotificationSettingsprivate var panel: NSPanel?private var hostingController: NSHostingController<NotificationOptionsView>?private lazy var presenter = SidePanelDrawerPresenter(@@ -29,10 +30,12 @@ final class NotificationOptionsPanelController {init(notificationSettings: NotificationSettings,- codexHookSettings: CodexHookSettings+ codexHookSettings: CodexHookSettings,+ codexCLINotificationSettings: CodexCLINotificationSettings) {self.notificationSettings = notificationSettingsself.codexHookSettings = codexHookSettings+ self.codexCLINotificationSettings = codexCLINotificationSettings}var isVisible: Bool {@@ -70,6 +73,7 @@ final class NotificationOptionsPanelController {return}+ codexCLINotificationSettings.refresh()let panel = ensurePanel()let windowSurfaceFrame = SidePanelSupport.contentScreenFrame(for: contentView, in: window) ?? window.framelet panelSize = measuredPanelSize()@@ -111,7 +115,8 @@ final class NotificationOptionsPanelController {let hostingController = NSHostingController(rootView: NotificationOptionsView(notificationSettings: notificationSettings,- codexHookSettings: codexHookSettings+ codexHookSettings: codexHookSettings,+ codexCLINotificationSettings: codexCLINotificationSettings))hostingController.sizingOptions = [.preferredContentSize]diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftindex 1a130bd..b6da555 100644--- a/CodexBar/Controllers/SettingsWindowController.swift+++ b/CodexBar/Controllers/SettingsWindowController.swift@@ -7,6 +7,7 @@ final class SettingsWindowController: HostingWindowController {private let viewModel: CodexStatusViewModelprivate let appUpdater: AppUpdaterprivate let codexHookSettings: CodexHookSettings+ private let codexCLINotificationSettings: CodexCLINotificationSettingsprivate let syncSettings: WorkflowSyncSettingsprivate let globalHotKeySettings: GlobalHotKeySettingsprivate let menuBarQuotaSettings: MenuBarQuotaSettings@@ -15,13 +16,15 @@ final class SettingsWindowController: HostingWindowController {private let onSyncChanged: (Bool) -> Voidprivate lazy var notificationOptionsPanelController = NotificationOptionsPanelController(notificationSettings: notificationSettings,- codexHookSettings: codexHookSettings+ codexHookSettings: codexHookSettings,+ codexCLINotificationSettings: codexCLINotificationSettings)init(viewModel: CodexStatusViewModel,appUpdater: AppUpdater,codexHookSettings: CodexHookSettings,+ codexCLINotificationSettings: CodexCLINotificationSettings,syncSettings: WorkflowSyncSettings,globalHotKeySettings: GlobalHotKeySettings,menuBarQuotaSettings: MenuBarQuotaSettings,@@ -33,6 +36,7 @@ final class SettingsWindowController: HostingWindowController {self.viewModel = viewModelself.appUpdater = appUpdaterself.codexHookSettings = codexHookSettings+ self.codexCLINotificationSettings = codexCLINotificationSettingsself.syncSettings = syncSettingsself.globalHotKeySettings = globalHotKeySettingsself.menuBarQuotaSettings = menuBarQuotaSettings@@ -90,6 +94,7 @@ final class SettingsWindowController: HostingWindowController {private func refreshSettingsState() {codexHookSettings.refresh()codexHookSettings.verifyInstalledHooks()+ codexCLINotificationSettings.refresh()syncSettings.refresh()menuBarQuotaSettings.refresh()mainPanelSettings.refresh()diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex 3abb57b..630150c 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -9,6 +9,9 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {lazy var viewModel = CodexStatusViewModel(service: codexStatusService)let workflowViewModel = WorkflowViewModel()lazy var codexHookSettings = CodexHookSettings(codexStatusService: codexStatusService)+ lazy var codexCLINotificationSettings = CodexCLINotificationSettings(+ codexStatusService: codexStatusService+ )lazy var activityMonitor = CodexActivityMonitor(codexHookSettings: codexHookSettings)let syncSettings = WorkflowSyncSettings()let globalHotKeySettings = GlobalHotKeySettings()@@ -25,6 +28,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {viewModel: viewModel,workflowViewModel: workflowViewModel,codexHookSettings: codexHookSettings,+ codexCLINotificationSettings: codexCLINotificationSettings,activityMonitor: activityMonitor,syncSettings: syncSettings,globalHotKeySettings: globalHotKeySettings,@@ -64,6 +68,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {private let viewModel: CodexStatusViewModelprivate let workflowViewModel: WorkflowViewModelprivate let codexHookSettings: CodexHookSettings+ private let codexCLINotificationSettings: CodexCLINotificationSettingsprivate let activityMonitor: CodexActivityMonitorprivate let syncSettings: WorkflowSyncSettingsprivate let globalHotKeySettings: GlobalHotKeySettings@@ -94,6 +99,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {viewModel: viewModel,appUpdater: appUpdater,codexHookSettings: codexHookSettings,+ codexCLINotificationSettings: codexCLINotificationSettings,syncSettings: syncSettings,globalHotKeySettings: globalHotKeySettings,menuBarQuotaSettings: menuBarQuotaSettings,@@ -153,6 +159,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {viewModel: CodexStatusViewModel,workflowViewModel: WorkflowViewModel,codexHookSettings: CodexHookSettings,+ codexCLINotificationSettings: CodexCLINotificationSettings,activityMonitor: CodexActivityMonitor,syncSettings: WorkflowSyncSettings,globalHotKeySettings: GlobalHotKeySettings,@@ -164,6 +171,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {self.viewModel = viewModelself.workflowViewModel = workflowViewModelself.codexHookSettings = codexHookSettings+ self.codexCLINotificationSettings = codexCLINotificationSettingsself.activityMonitor = activityMonitorself.syncSettings = syncSettingsself.globalHotKeySettings = globalHotKeySettingsdiff --git a/CodexBar/Models/CodexWorkflowModels.swift b/CodexBar/Models/CodexWorkflowModels.swiftindex 06c6dd3..9ff9b2d 100644--- a/CodexBar/Models/CodexWorkflowModels.swift+++ b/CodexBar/Models/CodexWorkflowModels.swift@@ -301,23 +301,64 @@ nonisolated struct WorkflowSnapshot: Equatable {self.dailyMetrics = dailyMetrics}- /// syncedRecords 由 WorkflowSyncService 保证不含本机设备的记录+ /// 同 generation 只采用一份数据;确认独立的新 generation 与历史贡献累加init(localAggregates: [WorkflowDailyAggregate],- syncedRecords: [WorkflowSyncedDailyRecord]+ syncedRecords: [WorkflowSyncedDailyRecord],+ currentDeviceId: String?) {var metricsByDate = [String: WorkflowDailyMetrics]()- for aggregate in localAggregates {- Self.merge(aggregate.metrics, into: &metricsByDate)- }- for record in syncedRecords {- Self.merge(record.daily.metrics, into: &metricsByDate)+ 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 > local.eventCount {+ merge(remoteRecords[matchingIndex].daily.metrics, into: &metricsByDate)+ } else {+ merge(local.metrics, into: &metricsByDate)+ }+ }+func recentWeekGrid(columnCount: Int, endingDaysAgo: Int = 0, today: Date = Date()) -> [WorkflowDailyMetrics?] {let metricsByDate = dailyMetrics.reduce(into: [String: WorkflowDailyMetrics]()) { result, metrics inresult[metrics.startDate] = metrics@@ -336,6 +377,15 @@ nonisolated struct WorkflowSnapshot: Equatable {}}+ 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]@@ -362,6 +412,8 @@ nonisolated struct WorkflowDailyIdentifierCache {/// daily.jsonl 中的持久化聚合行, 同时兼容保留 ID 和只保留计数两种形态nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {let date: String+ var sourceGeneration: String?+ var sourceIsFresh: Boolvar eventCount: Intvar sessionStartCount: Intvar stopCount: Int@@ -383,8 +435,14 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {date}- init(date: String) {+ init(+ date: String,+ sourceGeneration: String? = nil,+ sourceIsFresh: Bool = false+ ) {self.date = date+ self.sourceGeneration = sourceGeneration+ self.sourceIsFresh = sourceIsFresheventCount = 0sessionStartCount = 0stopCount = 0@@ -406,6 +464,8 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {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) ?? falseeventCount = try container.decodeIfPresent(Int.self, forKey: .eventCount) ?? 0sessionStartCount = try container.decodeIfPresent(Int.self, forKey: .sessionStartCount) ?? 0stopCount = try container.decodeIfPresent(Int.self, forKey: .stopCount) ?? 0@@ -540,6 +600,8 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {func jsonLineData() throws -> Data {let fields = try [WorkflowJSON.field("date", date),+ WorkflowJSON.field("sourceGeneration", sourceGeneration),+ WorkflowJSON.field("sourceIsFresh", sourceIsFresh),WorkflowJSON.field("eventCount", eventCount),WorkflowJSON.field("sessionStartCount", sessionStartCount),WorkflowJSON.field("stopCount", stopCount),@@ -564,6 +626,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {var syncedAggregate: WorkflowSyncedDailyAggregate {WorkflowSyncedDailyAggregate(date: date,+ sourceGeneration: sourceGeneration,eventCount: eventCount,sessionStartCount: sessionStartCount,stopCount: stopCount,@@ -621,6 +684,8 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {private enum CodingKeys: String, CodingKey {case date+ case sourceGeneration+ case sourceIsFreshcase eventCountcase sessionStartCountcase stopCount@@ -643,6 +708,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {/// 同步存储中保存的脱敏每日聚合行: 对应 daily.jsonl 但不包含 sessionIds / turnIdsnonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable, Identifiable {let date: String+ var sourceGeneration: String?var eventCount: Intvar sessionStartCount: Intvar stopCount: Int@@ -687,6 +753,7 @@ nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable, Identifiablfunc jsonLineData() throws -> Data {let fields = try [WorkflowJSON.field("date", date),+ WorkflowJSON.field("sourceGeneration", sourceGeneration),WorkflowJSON.field("eventCount", eventCount),WorkflowJSON.field("sessionStartCount", sessionStartCount),WorkflowJSON.field("stopCount", stopCount),@@ -705,22 +772,39 @@ nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable, Identifiablreturn WorkflowJSON.lineData(fields)}++ 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)+ }}nonisolated struct WorkflowSyncedDailyRecord: Codable, Equatable, Identifiable {let deviceId: Stringlet daily: WorkflowSyncedDailyAggregatevar updatedAt: Date?+ var recordName: String?var id: String {- Self.id(deviceId: deviceId, date: daily.date)+ recordName ?? Self.legacyRecordName(deviceId: deviceId, date: daily.date)}var date: String {daily.date}- static func id(deviceId: String, date: String) -> String {- "\(deviceId)|\(date)"+ static func legacyRecordName(deviceId: String, date: String) -> String {+ "\(deviceId)_\(date)"}}diff --git a/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift b/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swiftindex 0998e7e..862e023 100644--- a/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift+++ b/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift@@ -1,6 +1,6 @@import Foundation-/// config/read 的最小响应模型, 只解出 Hook 开关和信任状态+/// config/read 的最小响应模型, 只解出 Hook 与 TUI 通知相关状态nonisolated struct CodexConfigReadResponse: Decodable {let config: CodexAppServerConfig@@ -11,12 +11,17 @@ nonisolated struct CodexConfigReadResponse: Decodable {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@@ -43,19 +48,89 @@ nonisolated struct CodexHookTrustState: Decodable {}}+/// 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 {+nonisolated struct CodexConfigBatchEdit: Sendable {let keyPath: String- let value: [String: [String: 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,+ "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 {}diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swiftindex c64d070..277463e 100644--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift@@ -127,7 +127,7 @@ actor CodexStatusService {)}- /// Hook 自动信任和清理统一走批量写入, 让 Codex 负责刷新用户配置+ /// 设置写入统一走批量接口, 让 Codex 负责刷新用户配置func writeCodexConfigBatch(edits: [CodexConfigBatchEdit]) async throws -> CodexConfigWriteResponse {let connection = try readyConnection()return try connection.session.request(diff --git a/CodexBar/Services/Settings/CodexCLINotificationSettings.swift b/CodexBar/Services/Settings/CodexCLINotificationSettings.swiftnew file mode 100644index 0000000..2c8ee61--- /dev/null+++ b/CodexBar/Services/Settings/CodexCLINotificationSettings.swift@@ -0,0 +1,125 @@+import Combine+import Foundation++/// Codex TUI 通知设置, 通过 app-server 读写用户级 config.toml+@MainActor+final class CodexCLINotificationSettings: ObservableObject {+ @Published private(set) var isEnabled = true+ @Published private(set) var isUpdating = false+ @Published private(set) var errorMessage: String?++ private let codexStatusService: CodexStatusService+ private var updateTask: Task<Void, Never>?+ private var updateGeneration = 0++ init(codexStatusService: CodexStatusService) {+ self.codexStatusService = codexStatusService+ }++ deinit {+ updateTask?.cancel()+ }++ func refresh() {+ guard !isUpdating else {+ return+ }++ runLatestUpdate(errorPrefix: "读取 Codex TUI 通知失败") { settings, generation in+ let response = try await settings.codexStatusService.readCodexConfig()+ try settings.ensureCurrentUpdate(generation)+ return response.areTUINotificationsEnabled+ }+ }++ func setEnabled(_ enabled: Bool) {+ guard enabled != isEnabled else {+ return+ }++ runLatestUpdate(errorPrefix: "设置 Codex TUI 通知失败") { settings, generation in+ _ = try await settings.codexStatusService.writeCodexConfigBatch(+ edits: [+ .init(+ keyPath: Self.configKeyPath,+ value: enabled,+ mergeStrategy: Self.configMergeStrategy+ )+ ]+ )+ try settings.ensureCurrentUpdate(generation)++ let response = try await settings.codexStatusService.readCodexConfig()+ try settings.ensureCurrentUpdate(generation)+ guard response.areTUINotificationsEnabled == enabled else {+ throw SettingsError.verificationFailed+ }+ return enabled+ }+ }++ private func runLatestUpdate(+ errorPrefix: String,+ operation: @escaping @MainActor (CodexCLINotificationSettings, Int) async throws -> Bool+ ) {+ updateTask?.cancel()+ updateGeneration += 1+ let generation = updateGeneration++ isUpdating = true+ errorMessage = nil+ updateTask = Task { [weak self] in+ guard let self else {+ return+ }++ do {+ let isEnabled = try await operation(self, generation)+ guard isCurrentUpdate(generation) else {+ return+ }+ self.isEnabled = isEnabled+ } catch is CancellationError {+ return+ } catch {+ guard isCurrentUpdate(generation) else {+ return+ }+ errorMessage = "\(errorPrefix): \(error.localizedDescription)"+ }++ finishUpdate(generation)+ }+ }++ private func finishUpdate(_ generation: Int) {+ guard isCurrentUpdate(generation) else {+ return+ }++ isUpdating = false+ updateTask = nil+ }++ private func ensureCurrentUpdate(_ generation: Int) throws {+ try Task.checkCancellation()+ guard isCurrentUpdate(generation) else {+ throw CancellationError()+ }+ }++ private func isCurrentUpdate(_ generation: Int) -> Bool {+ generation == updateGeneration+ }++ private enum SettingsError: LocalizedError {+ case verificationFailed++ var errorDescription: String? {+ "Codex TUI 通知状态与设置不一致"+ }+ }++ private static let configKeyPath = "tui.notifications"+ private static let configMergeStrategy = "upsert"+}diff --git a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swiftindex c55b0e6..67ceb85 100644--- a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift+++ b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift@@ -76,11 +76,50 @@ nonisolated enum WorkflowHookEventRecorder {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+ && existingStat.identifier != 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) {+ if maintenanceState.markPending(dateKey) || stateChanged {try WorkflowStorage.saveMaintenanceState(maintenanceState)}}diff --git a/CodexBar/Services/Workflow/WorkflowService.swift b/CodexBar/Services/Workflow/WorkflowService.swiftindex de626a7..fccd4a7 100644--- a/CodexBar/Services/Workflow/WorkflowService.swift+++ b/CodexBar/Services/Workflow/WorkflowService.swift@@ -1,4 +1,5 @@import Combine+import CryptoKitimport Darwinimport Foundation@@ -25,20 +26,13 @@ actor WorkflowService {performMaintenance: Bool = false,synchronize: Bool = false) async -> WorkflowSnapshot {- var changedDates = Set<String>()if performMaintenance {- // changedDates 只在实际执行 iCloud 同步时被消费, 其余场景跳过 payload 比对- changedDates = performMaintenanceIfNeeded(- computesChangedDates: synchronize && WorkflowSyncSettings.isEnabled()- )+ performMaintenanceIfNeeded()}let aggregates = loadDailyAggregates() ?? []let syncSnapshot: WorkflowSyncSnapshot = if synchronize {- await syncService.synchronizeIfEnabled(- localAggregates: aggregates,- changedDates: changedDates- )+ await syncService.synchronizeIfEnabled(localAggregates: aggregates)} else {await syncService.snapshotFromCacheIfEnabled()}@@ -49,7 +43,8 @@ actor WorkflowService {return WorkflowSnapshot(localAggregates: aggregates,- syncedRecords: syncSnapshot.records+ syncedRecords: syncSnapshot.records,+ currentDeviceId: syncSnapshot.currentDeviceId)}@@ -66,9 +61,7 @@ actor WorkflowService {return WorkflowDailyAggregate.normalized(aggregates: aggregates)}- private func performMaintenanceIfNeeded(computesChangedDates: Bool) -> Set<String> {- let beforePayloads = computesChangedDates ? syncPayloadByDate() : [:]-+ private func performMaintenanceIfNeeded() {do {let tasks = try prepareMaintenanceTasks()let didWriteDailyLog = perform(tasks)@@ -78,14 +71,8 @@ actor WorkflowService {}try pruneExpiredEventFiles()} catch {- return []- }-- guard computesChangedDates else {- return []+ return}-- return changedSyncPayloadDates(before: beforePayloads, after: syncPayloadByDate())}/// 返回是否写入过 daily.jsonl; 批次内共享同一份内存聚合, 避免每个任务重新读盘@@ -172,14 +159,37 @@ actor WorkflowService {) -> Bool {var changed = state.markDirty(contentsOf: eventDateKeys.filter { state.days[$0] == nil })- // 文件变小说明被外部截断, 必须全量重建- // 变大则从旧 offset 增量追上- for (dateKey, day) in state.days {- let actualSize = eventLogSize(for: dateKey)- if actualSize < day.offset || day.offset != day.size {+ 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+ && stat.identifier != nil+ && day.fileIdentifier != stat.identifier+ let boundaryChanged = day.boundaryHash.map {+ (try? eventLogBoundaryHash(for: dateKey, endingAt: day.offset)) != $0+ } ?? false++ if identifierChanged || stat.size < day.offset || boundaryChanged {+ 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 actualSize > day.offset,+ } else if stat.size > day.offset,!state.pending.contains(dateKey),!state.dirty.contains(dateKey) {state.markPending(dateKey)@@ -196,7 +206,12 @@ actor WorkflowService {changedState: inout Bool) -> [WorkflowMaintenanceTask] {let dirty = Set(state.dirty)- var tasks = state.dirty.map { dirtyTask(for: $0) }+ var tasks: [WorkflowMaintenanceTask] = state.dirty.compactMap { dateKey in+ guard let day = state.days[dateKey] else {+ return nil+ }+ return dirtyTask(for: dateKey, day: day)+ }for dateKey in state.pending where !dirty.contains(dateKey) {let day = state.days[dateKey] ?? WorkflowDayMaintenanceState()@@ -207,10 +222,11 @@ actor WorkflowService {continue}- guard let baseAggregate = dailyByDate[dateKey] else {+ guard let baseAggregate = dailyByDate[dateKey],+ baseAggregate.sourceGeneration == day.sourceGeneration else {state.markDirty(dateKey)changedState = true- tasks.append(dirtyTask(for: dateKey, size: size))+ tasks.append(dirtyTask(for: dateKey, day: day, size: size))continue}@@ -227,13 +243,21 @@ actor WorkflowService {return tasks}- private func dirtyTask(for dateKey: String, size: UInt64? = nil) -> WorkflowMaintenanceTask {- WorkflowMaintenanceTask(+ private func dirtyTask(+ for dateKey: String,+ day: WorkflowDayMaintenanceState,+ size: UInt64? = nil+ ) -> WorkflowMaintenanceTask {+ let stat = WorkflowStorage.fileStat(at: eventLogURL(for: dateKey))+ return WorkflowMaintenanceTask(dateKey: dateKey,startOffset: 0,- size: size ?? eventLogSize(for: dateKey),+ size: size ?? stat?.size ?? 0,baseAggregate: nil,- existingCorrupt: 0+ existingCorrupt: 0,+ sourceGeneration: day.sourceGeneration,+ sourceIsFresh: day.sourceIsFresh,+ fileIdentifier: stat?.identifier)}@@ -248,7 +272,10 @@ actor WorkflowService {startOffset: day.offset,size: size,baseAggregate: baseAggregate,- existingCorrupt: day.corrupt+ existingCorrupt: day.corrupt,+ sourceGeneration: day.sourceGeneration,+ sourceIsFresh: day.sourceIsFresh,+ fileIdentifier: day.fileIdentifier)}@@ -260,6 +287,31 @@ actor WorkflowService {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)@@ -275,7 +327,13 @@ actor WorkflowService {private func buildDailyAggregate(for task: WorkflowMaintenanceTask) throws -> WorkflowMaintenanceResult {- var aggregate = task.baseAggregate ?? WorkflowDailyAggregate(date: task.dateKey)+ var aggregate = task.baseAggregate ?? WorkflowDailyAggregate(+ date: task.dateKey,+ sourceGeneration: task.sourceGeneration,+ sourceIsFresh: task.sourceIsFresh+ )+ aggregate.sourceGeneration = task.sourceGeneration+ aggregate.sourceIsFresh = task.sourceIsFreshvar corrupt = task.existingCorruptvar identifierCache = WorkflowDailyIdentifierCache(aggregate: aggregate)let keepsIdentifiers = keepsIdentifiers(for: task.dateKey)@@ -293,11 +351,13 @@ actor WorkflowService {}aggregate.compactIdentifiersIfNeeded(keepsIdentifiers: keepsIdentifiers)- return WorkflowMaintenanceResult(+ return try WorkflowMaintenanceResult(dateKey: task.dateKey,aggregate: aggregate,size: task.size,- corrupt: corrupt+ corrupt: corrupt,+ fileIdentifier: task.fileIdentifier,+ boundaryHash: eventLogBoundaryHash(for: task.dateKey, endingAt: task.size))}@@ -375,7 +435,7 @@ actor WorkflowService {_ result: WorkflowMaintenanceResult,aggregates: inout [WorkflowDailyAggregate]) throws -> Bool {- guard try eventLogHasNotShrunk(for: result) else {+ guard try eventLogSourceIsValid(for: result) else {return false}@@ -386,26 +446,45 @@ actor WorkflowService {return true}- private func eventLogHasNotShrunk(for result: WorkflowMaintenanceResult) throws -> Bool {+ private func eventLogSourceIsValid(for result: WorkflowMaintenanceResult) throws -> Bool {try WorkflowStorage.withExclusiveLock {var state = WorkflowStorage.loadMaintenanceState()- return try eventLogSizeIfNotShrunk(for: result, state: &state) != nil+ return try validatedEventLogSize(for: result, state: &state) != nil}}- /// 锁内校验事件文件未被外部截断; 已收缩时标脏并落盘, 返回 nil- private func eventLogSizeIfNotShrunk(+ /// 锁内确认读取期间仍是同一份追加源;断代时换 generation 并等待重建+ private func validatedEventLogSize(for result: WorkflowMaintenanceResult,state: inout WorkflowMaintenanceState) throws -> UInt64? {- let currentSize = WorkflowStorage.fileSize(at: eventLogURL(for: result.dateKey))- guard currentSize >= result.size else {- state.markDirty(result.dateKey)+ 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+ || stat?.identifier == 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 currentSize+ return stat.size}private func writeDailyAggregate(@@ -462,38 +541,22 @@ actor WorkflowService {}}- private func syncPayloadByDate() -> [String: String] {- loadDailyAggregatesWithFailures().values.reduce(into: [String: String]()) { result, aggregate in- guard let data = try? aggregate.syncedAggregate.jsonLineData() else {- return- }-- result[aggregate.date] = data.base64EncodedString()- }- }-- private func changedSyncPayloadDates(- before: [String: String],- after: [String: String]- ) -> Set<String> {- let allDates = Set(before.keys).union(after.keys)- return Set(allDates.filter {- before[$0] != after[$0]- })- }-private func commitMaintenanceState(_ result: WorkflowMaintenanceResult) throws {try WorkflowStorage.withExclusiveLock {var state = WorkflowStorage.loadMaintenanceState()- guard let currentSize = try eventLogSizeIfNotShrunk(for: result, state: &state) else {+ guard let currentSize = try validatedEventLogSize(for: result, state: &state) else {return}state.days[result.dateKey] = WorkflowDayMaintenanceState(offset: result.size,size: result.size,- corrupt: result.corrupt+ corrupt: result.corrupt,+ sourceGeneration: result.aggregate.sourceGeneration,+ sourceIsFresh: result.aggregate.sourceIsFresh,+ fileIdentifier: result.fileIdentifier,+ boundaryHash: result.boundaryHash)state.removeDirty(result.dateKey)@@ -587,21 +650,8 @@ nonisolated enum WorkflowStorage {}static func syncDirectoryURL() -> URL {- let currentURL = directoryURL()+ directoryURL().appendingPathComponent("Sync", isDirectory: true)- let legacyURL = directoryURL()- .appendingPathComponent(legacySyncDirectoryName, isDirectory: true)-- if FileManager.default.fileExists(atPath: legacyURL.path),- !FileManager.default.fileExists(atPath: currentURL.path) {- return legacyURL- }-- return currentURL- }-- private static var legacySyncDirectoryName: String {- ["i", "Cloud", "Sync"].joined()}static func directoryURL() -> URL {@@ -729,17 +779,44 @@ nonisolated struct WorkflowDayMaintenanceState: Codable, Equatable {var offset: UInt64var size: UInt64var corrupt: Int+ var sourceGeneration: String?+ var sourceIsFresh: Bool+ var fileIdentifier: UInt64?+ var boundaryHash: String?- init(offset: UInt64 = 0, size: UInt64 = 0, corrupt: Int = 0) {+ init(+ offset: UInt64 = 0,+ size: UInt64 = 0,+ corrupt: Int = 0,+ sourceGeneration: String? = nil,+ sourceIsFresh: Bool = false,+ fileIdentifier: UInt64? = nil,+ boundaryHash: String? = nil+ ) {self.offset = offsetself.size = sizeself.corrupt = corrupt+ self.sourceGeneration = sourceGeneration+ self.sourceIsFresh = sourceIsFresh+ 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+ 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)}}/// maintenance.json 的全局状态, pending 表示可增量, dirty 表示需全量重建nonisolated struct WorkflowMaintenanceState: Codable, Equatable {- static let currentSchema = 3+ static let currentSchema = 4var schema: Intvar pending: [String]@@ -814,6 +891,41 @@ nonisolated struct WorkflowMaintenanceState: Codable, Equatable {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+ }++ 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 = pendinglet previousDirty = dirty@@ -839,6 +951,10 @@ nonisolated struct WorkflowMaintenanceState: Codable, Equatable {private static func normalizedDates(_ dates: [String]) -> [String] {Array(Set(dates.filter { WorkflowStorage.isValidDateKey($0) })).sorted()}++ private static func newSourceGeneration() -> String {+ UUID().uuidString.lowercased()+ }}/// daily.jsonl 某一时刻的 stat 快照与当天日期键, 用于跳过稳态下的重复归一化@@ -855,6 +971,9 @@ private nonisolated struct WorkflowMaintenanceTask {let size: UInt64let baseAggregate: WorkflowDailyAggregate?let existingCorrupt: Int+ let sourceGeneration: String?+ let sourceIsFresh: Bool+ let fileIdentifier: UInt64?}/// 维护任务的提交结果, corrupt 统计保留给后续诊断@@ -863,6 +982,8 @@ private nonisolated struct WorkflowMaintenanceResult {let aggregate: WorkflowDailyAggregatelet size: UInt64let corrupt: Int+ let fileIdentifier: UInt64?+ let boundaryHash: String?}/// UI 层的工作流状态, 节流普通刷新, 维护刷新由上层调度器合并diff --git a/CodexBar/Services/Workflow/WorkflowSyncService.swift b/CodexBar/Services/Workflow/WorkflowSyncService.swiftindex 83d3bc4..79c7fe4 100644--- a/CodexBar/Services/Workflow/WorkflowSyncService.swift+++ b/CodexBar/Services/Workflow/WorkflowSyncService.swift@@ -35,8 +35,7 @@ actor WorkflowSyncService {}func synchronizeIfEnabled(- localAggregates: [WorkflowDailyAggregate],- changedDates: Set<String>+ localAggregates: [WorkflowDailyAggregate]) async -> WorkflowSyncSnapshot {guard WorkflowSyncSettings.isEnabled() else {return .disabled@@ -58,22 +57,24 @@ actor WorkflowSyncService {do {try await ensureSyncZoneExists()let deviceId = try await resolveCurrentDeviceId()- resetStateIfDeviceChanged(deviceId, state: &state)+ try resetStateIfDeviceChanged(deviceId, state: &state)+ try await migrateStateIfNeeded(&state)+ try await refreshCacheFromRemote()let localByDate = Self.syncedAggregatesByDate(localAggregates)let forceBackfill = WorkflowSyncSettings.needsBackfill()- try await uploadChangedAggregates(+ let confirmedDates = try await uploadChangedAggregates(localByDate: localByDate,- changedDates: changedDates,- forceBackfill: forceBackfill,+ remoteRecords: loadCachedRecords(),state: &state)- if forceBackfill, backfillCompleted(localByDate: localByDate, state: state) {+ if forceBackfill,+ backfillCompleted(localByDate: localByDate, confirmedDates: confirmedDates) {WorkflowSyncSettings.clearBackfillRequest()}- try await refreshCacheFromRemote(currentDeviceId: deviceId)+ try await refreshCacheFromRemote()try await pruneCurrentDeviceRecordsIfNeeded(deviceId: deviceId, state: &state)try saveState(state)didSucceed = true@@ -90,54 +91,79 @@ actor WorkflowSyncService {private func resetStateIfDeviceChanged(_ deviceId: String,state: inout WorkflowSyncState- ) {+ ) throws {guard state.deviceId != deviceId else {return}- state = WorkflowSyncState(deviceId: deviceId)- try? saveCachedRecords([])- try? fileManager.removeItem(at: cursorURL)+ try removeCursorIfPresent()+ try saveCachedRecords([])++ let resetState = WorkflowSyncState(deviceId: deviceId)+ try saveState(resetState)+ state = resetState}private static func syncedAggregatesByDate(_ aggregates: [WorkflowDailyAggregate]- ) -> [String: WorkflowSyncedDailyAggregate] {- aggregates.reduce(into: [String: WorkflowSyncedDailyAggregate]()) { result, aggregate in- result[aggregate.date] = aggregate.syncedAggregate+ ) -> [String: LocalSyncAggregate] {+ aggregates.reduce(into: [String: LocalSyncAggregate]()) { result, aggregate in+ result[aggregate.date] = LocalSyncAggregate(+ aggregate: aggregate.syncedAggregate,+ sourceIsFresh: aggregate.sourceIsFresh+ )}}private func backfillCompleted(- localByDate: [String: WorkflowSyncedDailyAggregate],- state: WorkflowSyncState+ localByDate: [String: LocalSyncAggregate],+ confirmedDates: Set<String>) -> Bool {- localByDate.allSatisfy { date, aggregate in- (try? hash(for: aggregate)) == state.hashByDate[date]- }+ localByDate.keys.allSatisfy(confirmedDates.contains)}private func snapshot(from state: WorkflowSyncState) -> WorkflowSyncSnapshot {WorkflowSyncSnapshot(records: state.deviceId == nil? []- : Self.filteredRetained(records: loadCachedRecords(), excluding: state.deviceId)+ : Self.filteredRetained(records: loadCachedRecords()),+ currentDeviceId: state.deviceId)}}private extension WorkflowSyncService {+ struct LocalSyncAggregate {+ let aggregate: WorkflowSyncedDailyAggregate+ let sourceIsFresh: Bool+ }+struct PendingUpload {let date: Stringlet aggregate: WorkflowSyncedDailyAggregate+ let sourceIsFresh: Boollet hash: String}- typealias PendingRecord = (upload: PendingUpload, recordID: CKRecord.ID)- typealias UploadedHash = (date: String, 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 = 3+ static let syncSchemaVersion = 4static let syncZoneName = "CodexBarZone"static let saltByteCount = 32static let recordFetchLimit = 200@@ -156,6 +182,7 @@ private extension WorkflowSyncService {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 stopCount = "stopCount"@@ -200,27 +227,28 @@ private extension WorkflowSyncService {}func uploadChangedAggregates(- localByDate: [String: WorkflowSyncedDailyAggregate],- changedDates: Set<String>,- forceBackfill: Bool,+ localByDate: [String: LocalSyncAggregate],+ remoteRecords: [WorkflowSyncedDailyRecord],state: inout WorkflowSyncState- ) async throws {+ ) async throws -> Set<String> {guard let deviceId = state.deviceId else {- return+ return []+ }++ var confirmedDates = Set<String>()+ for (date, local) in localByDate {+ if try hash(for: local.aggregate) == state.hashByDate[date] {+ confirmedDates.insert(date)+ }}let pendingUploads = try makePendingUploads(- for: uploadCandidateDates(- localByDate: localByDate,- changedDates: changedDates,- forceBackfill: forceBackfill,- state: state- ),+ for: Set(localByDate.keys),localByDate: localByDate,state: state)guard !pendingUploads.isEmpty else {- return+ return confirmedDates}let deadline = Date().addingTimeInterval(Metrics.uploadTimeBudget)@@ -232,88 +260,176 @@ private extension WorkflowSyncService {let batchEnd = min(batchStart + Metrics.uploadBatchSize, pendingUploads.count)let batch = Array(pendingUploads[batchStart ..< batchEnd])- let uploadedBatch = try await uploadAggregateBatch(batch, deviceId: deviceId)+ let confirmedBatch: [ConfirmedHash]+ do {+ confirmedBatch = try await processUploadBatch(+ batch,+ deviceId: deviceId,+ remoteRecords: remoteRecords+ )+ } catch {+ try markPendingForRetry(batch, state: &state)+ throw error+ }- try applyUploadedHashes(uploadedBatch, to: &state)+ try applyConfirmedHashes(confirmedBatch, to: &state)+ confirmedDates.formUnion(confirmedBatch.map(\.date))}- }- func uploadCandidateDates(- localByDate: [String: WorkflowSyncedDailyAggregate],- changedDates: Set<String>,- forceBackfill: Bool,- state: WorkflowSyncState- ) -> Set<String> {- var candidateDates = Set(changedDates)- candidateDates.formUnion(localByDate.keys.filter { state.hashByDate[$0] == nil })+ return confirmedDates+ }- if forceBackfill {- candidateDates.formUnion(localByDate.keys)+ func markPendingForRetry(+ _ pendingUploads: [PendingUpload],+ state: inout WorkflowSyncState+ ) throws {+ for upload in pendingUploads {+ state.hashByDate.removeValue(forKey: upload.date)}-- return candidateDates+ try saveState(state)}- func applyUploadedHashes(- _ uploadedBatch: [UploadedHash],+ func applyConfirmedHashes(+ _ confirmedBatch: [ConfirmedHash],to state: inout WorkflowSyncState) throws {- guard !uploadedBatch.isEmpty else {+ guard !confirmedBatch.isEmpty else {return}- for uploaded in uploadedBatch {- state.hashByDate[uploaded.date] = uploaded.hash+ for confirmation in confirmedBatch {+ state.hashByDate[confirmation.date] = confirmation.hash}- state.lastUploadAt = Date()+ if confirmedBatch.contains(where: \.didUpload) {+ state.lastUploadAt = Date()+ }try saveState(state)}func makePendingUploads(for candidateDates: Set<String>,- localByDate: [String: WorkflowSyncedDailyAggregate],+ localByDate: [String: LocalSyncAggregate],state: WorkflowSyncState) throws -> [PendingUpload] {try candidateDates.compactMap { date in- guard let aggregate = localByDate[date] else {+ guard let local = localByDate[date] else {return nil}- let hash = try hash(for: aggregate)+ let hash = try hash(for: local.aggregate)guard state.hashByDate[date] != hash else {return nil}- return PendingUpload(date: date, aggregate: aggregate, hash: hash)+ return PendingUpload(+ date: date,+ aggregate: local.aggregate,+ sourceIsFresh: local.sourceIsFresh,+ hash: hash+ )}.sorted { $0.date < $1.date }}- func uploadAggregateBatch(+ func processUploadBatch(_ pendingUploads: [PendingUpload],- deviceId: String- ) async throws -> [UploadedHash] {- let pendingRecords: [PendingRecord] = pendingUploads.map {- (upload: $0, recordID: recordID(deviceId: deviceId, date: $0.date))+ 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 = pendingRecords.map(\.recordID)+ let recordIDs = Array(Set(pendingRecords.flatMap { pendingRecord in+ [pendingRecord.legacyRecordID, pendingRecord.generationRecordID].compactMap(\.self)+ }))let existingRecords = try await database.records(for: recordIDs)- let records = pendingRecords.map { pendingRecord in- let existingRecord: CKRecord? = if case let .success(record) = existingRecords[pendingRecord.recordID] {- record+ var confirmedHashes = [ConfirmedHash]()+ var recordsToSave = [RecordToSave]()++ for pendingRecord in pendingRecords {+ 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)+ }++ 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 let matchingRecord,+ let remoteAggregate = Self.remoteDailyRecord(from: matchingRecord)?.daily,+ remoteAggregate.eventCount > pendingRecord.upload.aggregate.eventCount,+ pendingRecord.upload.aggregate.sourceGeneration != nil {+ confirmedHashes.append(+ ConfirmedHash(+ date: pendingRecord.upload.date,+ hash: pendingRecord.upload.hash,+ didUpload: false+ )+ )+ continue+ }++ let record: CKRecord+ if let matchingRecord {+ record = matchingRecord+ } else if knownRemoteRecords.isEmpty {+ record = CKRecord(+ recordType: RecordTypes.dailyAggregate,+ recordID: pendingRecord.generationRecordID ?? pendingRecord.legacyRecordID+ )+ } else if pendingRecord.upload.sourceIsFresh,+ let generationRecordID = pendingRecord.generationRecordID,+ generationRecord == nil {+ record = CKRecord(+ recordType: RecordTypes.dailyAggregate,+ recordID: generationRecordID+ )+ } else {+ confirmedHashes.append(+ ConfirmedHash(+ date: pendingRecord.upload.date,+ hash: pendingRecord.upload.hash,+ didUpload: false+ )+ )+ continue+ }- let record = existingRecord ?? CKRecord(- recordType: RecordTypes.dailyAggregate,- recordID: pendingRecord.recordID- )apply(pendingRecord.upload.aggregate, deviceId: deviceId, to: record)- return 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: [],@@ -321,40 +437,47 @@ private extension WorkflowSyncService {atomically: false)- return pendingRecords.compactMap { pendingRecord in- if case .success = result.saveResults[pendingRecord.recordID] {- return (date: pendingRecord.upload.date, hash: pendingRecord.upload.hash)+ 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 nil}++ return confirmedHashes}- func refreshCacheFromRemote(currentDeviceId: String) async throws {+ func refreshCacheFromRemote() async throws {guard let token = try loadCursor() else {- try await rebuildCacheFromRemote(currentDeviceId: currentDeviceId)+ try await rebuildCacheFromRemote()return}do {try await applyZoneChangesToCache(since: token,- cachedRecords: loadCachedRecords(),- currentDeviceId: currentDeviceId+ cachedRecords: loadCachedRecords())} catch {- try await rebuildCacheFromRemote(currentDeviceId: currentDeviceId)+ try await rebuildCacheFromRemote()}}func applyZoneChangesToCache(since initialToken: CKServerChangeToken?,- cachedRecords: [WorkflowSyncedDailyRecord],- currentDeviceId: String+ cachedRecords: [WorkflowSyncedDailyRecord]) async throws {- var cacheByID = Self.recordsByID(- records: cachedRecords,- excluding: currentDeviceId- )+ var cacheByID = Self.recordsByID(records: cachedRecords)var token: CKServerChangeToken? = initialTokenvar moreComing = true@@ -366,9 +489,8 @@ private extension WorkflowSyncService {resultsLimit: Metrics.recordFetchLimit)- mergeChangedRecords(+ try mergeChangedRecords(result.modificationResultsByID.values,- currentDeviceId: currentDeviceId,into: &cacheByID)removeDeletedRecords(result.deletions, from: &cacheByID)@@ -378,21 +500,19 @@ private extension WorkflowSyncService {}try saveCachedRecords(- Self.filteredRetained(- records: Array(cacheByID.values),- excluding: currentDeviceId- )+ Self.filteredRetained(records: Array(cacheByID.values)))if let token {try saveCursor(token)}}- func rebuildCacheFromRemote(currentDeviceId: String) async throws {+ func rebuildCacheFromRemote() async throws {+ try removeCursorIfPresent()let syncedRecords = try await fetchAllRemoteDailyRecords()- let retainedRecords = Self.filteredRetained(records: syncedRecords, excluding: currentDeviceId)+ let retainedRecords = Self.filteredRetained(records: syncedRecords)try saveCachedRecords(retainedRecords)- await establishCursorBaseline(cachedRecords: retainedRecords, currentDeviceId: currentDeviceId)+ await establishCursorBaseline(cachedRecords: retainedRecords)}func fetchAllRemoteDailyRecords() async throws -> [WorkflowSyncedDailyRecord] {@@ -411,7 +531,7 @@ private extension WorkflowSyncService {desiredKeys: nil,resultsLimit: Metrics.queryFetchLimit)- var records = Self.remoteDailyRecords(from: firstPage.matchResults)+ var records = try Self.remoteDailyRecords(from: firstPage.matchResults)var queryCursor = firstPage.queryCursorwhile let cursor = queryCursor {@@ -420,22 +540,18 @@ private extension WorkflowSyncService {desiredKeys: nil,resultsLimit: Metrics.queryFetchLimit)- records.append(contentsOf: Self.remoteDailyRecords(from: page.matchResults))+ try records.append(contentsOf: Self.remoteDailyRecords(from: page.matchResults))queryCursor = page.queryCursor}return records}- func establishCursorBaseline(- cachedRecords: [WorkflowSyncedDailyRecord],- currentDeviceId: String- ) async {+ func establishCursorBaseline(cachedRecords: [WorkflowSyncedDailyRecord]) async {do {try await applyZoneChangesToCache(since: nil,- cachedRecords: cachedRecords,- currentDeviceId: currentDeviceId+ cachedRecords: cachedRecords)} catch {try? fileManager.removeItem(at: cursorURL)@@ -444,17 +560,11 @@ private extension WorkflowSyncService {func mergeChangedRecords(_ modificationResults: Dictionary<CKRecord.ID, Result<CKDatabase.RecordZoneChange.Modification, Error>>.Values,- currentDeviceId: String,into cacheByID: inout [String: WorkflowSyncedDailyRecord]- ) {+ ) throws {for modificationResult in modificationResults {- guard case let .success(modification) = modificationResult,- let record = Self.remoteDailyRecord(from: modification.record) else {- continue- }-- guard record.deviceId != currentDeviceId else {- cacheByID.removeValue(forKey: record.id)+ let modification = try modificationResult.get()+ guard let record = Self.remoteDailyRecord(from: modification.record) else {continue}@@ -467,9 +577,10 @@ private extension WorkflowSyncService {from cacheByID: inout [String: WorkflowSyncedDailyRecord]) {for deletion in deletions where deletion.recordType == RecordTypes.dailyAggregate {- if let cacheID = cacheID(fromRecordName: deletion.recordID.recordName) {- cacheByID.removeValue(forKey: cacheID)+ guard let cacheID = cacheID(fromRecordName: deletion.recordID.recordName) else {+ continue}+ cacheByID.removeValue(forKey: cacheID)}}@@ -483,25 +594,38 @@ private extension WorkflowSyncService {}let cutoffKey = WorkflowStorage.dateKey(for: WorkflowStorage.retentionCutoffDate())- let expiredDates = state.hashByDate.keys- .filter { $0 < cutoffKey }- .sorted()+ let expiredDates = Set(state.hashByDate.keys.filter { $0 < cutoffKey })+ let expiredRecords = loadCachedRecords().filter {+ $0.deviceId == deviceId && $0.date < cutoffKey+ }+ var recordNames = Set(expiredRecords.map(\.id))+ for date in expiredDates {+ recordNames.insert(+ WorkflowSyncedDailyRecord.legacyRecordName(deviceId: deviceId, date: date)+ )+ }- guard !expiredDates.isEmpty else {+ guard !recordNames.isEmpty else {+ for date in expiredDates {+ state.hashByDate.removeValue(forKey: date)+ }state.lastPrunedDate = todayreturn}+ let recordIDs = recordNames.map {+ CKRecord.ID(recordName: $0, zoneID: syncZoneID)+ }+let result = try await database.modifyRecords(saving: [],- deleting: expiredDates.map { recordID(deviceId: deviceId, date: $0) },+ deleting: recordIDs,savePolicy: .changedKeys,atomically: false)- let allDeleted = expiredDates.allSatisfy { date in- let recordID = recordID(deviceId: deviceId, date: date)- return Self.isSuccessfulDeleteResult(result.deleteResults[recordID])+ let allDeleted = recordIDs.allSatisfy { recordID in+ Self.isSuccessfulDeleteResult(result.deleteResults[recordID])}if allDeleted {@@ -540,7 +664,14 @@ private extension WorkflowSyncService {func fetchAccountSalt(_ recordID: CKRecord.ID) async throws -> Data? {let result = try await database.records(for: [recordID])- return Self.accountSalt(from: result[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 {@@ -556,8 +687,13 @@ private extension WorkflowSyncService {savePolicy: .ifServerRecordUnchanged,atomically: true)- if case .success = saveResult.saveResults[recordID] {+ 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) {@@ -577,8 +713,13 @@ private extension WorkflowSyncService {let zone = CKRecordZone(zoneID: syncZoneID)let result = try await database.modifyRecordZones(saving: [zone], deleting: [])- if case let .failure(error) = result.saveResults[syncZoneID] {+ switch result.saveResults[syncZoneID] {+ case .success:+ break+ case let .failure(error):throw error+ case nil:+ throw WorkflowSyncError.missingRecordResult}}@@ -607,6 +748,7 @@ private extension WorkflowSyncService {record[FieldKeys.schemaVersion] = Metrics.syncSchemaVersion as CKRecordValuerecord[FieldKeys.deviceId] = deviceId as CKRecordValuerecord[FieldKeys.date] = aggregate.date as CKRecordValue+ record[FieldKeys.sourceGeneration] = aggregate.sourceGeneration as CKRecordValue?record[FieldKeys.eventCount] = aggregate.eventCount as CKRecordValuerecord[FieldKeys.sessionStartCount] = aggregate.sessionStartCount as CKRecordValuerecord[FieldKeys.stopCount] = aggregate.stopCount as CKRecordValue@@ -625,25 +767,34 @@ private extension WorkflowSyncService {}func recordID(deviceId: String, date: String) -> CKRecord.ID {- CKRecord.ID(recordName: recordName(deviceId: deviceId, date: date), zoneID: syncZoneID)+ recordID(deviceId: deviceId, date: date, generation: nil)}- func recordName(deviceId: String, date: String) -> String {- "\(deviceId)_\(date)"+ func recordID(+ deviceId: String,+ date: String,+ generation: String?+ ) -> CKRecord.ID {+ CKRecord.ID(+ recordName: recordName(deviceId: deviceId, date: date, generation: generation),+ zoneID: syncZoneID+ )}- func cacheID(fromRecordName recordName: String) -> String? {- guard let separatorIndex = recordName.lastIndex(of: "_") else {- return nil- }-- let deviceId = String(recordName[..<separatorIndex])- let date = String(recordName[recordName.index(after: separatorIndex)...])- guard WorkflowStorage.isValidDateKey(date), !deviceId.isEmpty else {- return nil- }+ func recordName(+ deviceId: String,+ date: String,+ generation: String?+ ) -> String {+ let legacyName = WorkflowSyncedDailyRecord.legacyRecordName(+ deviceId: deviceId,+ date: date+ )+ return generation.map { "\(legacyName)_\($0)" } ?? legacyName+ }- return WorkflowSyncedDailyRecord.id(deviceId: deviceId, date: date)+ func cacheID(fromRecordName recordName: String) -> String? {+ recordName.isEmpty ? nil : recordName}func hash(for aggregate: WorkflowSyncedDailyAggregate) throws -> String {@@ -686,12 +837,25 @@ private extension WorkflowSyncService {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 state.schema == WorkflowSyncState.currentSchema else {+ guard WorkflowSyncState.supports(state.schema) else {return WorkflowSyncState()}return state@@ -718,6 +882,9 @@ private extension WorkflowSyncService {let data = try records.sorted { lhs, rhs inif lhs.deviceId == rhs.deviceId {+ if lhs.date == rhs.date {+ return lhs.id < rhs.id+ }return lhs.date < rhs.date}return lhs.deviceId < rhs.deviceId@@ -749,6 +916,13 @@ private extension WorkflowSyncService {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)}@@ -757,13 +931,9 @@ private extension WorkflowSyncService {private extension WorkflowSyncService {static func remoteDailyRecords(from matchResults: [(CKRecord.ID, Result<CKRecord, Error>)]- ) -> [WorkflowSyncedDailyRecord] {- matchResults.compactMap { _, result in- guard case let .success(record) = result else {- return nil- }-- return remoteDailyRecord(from: record)+ ) throws -> [WorkflowSyncedDailyRecord] {+ try matchResults.compactMap { _, result in+ try remoteDailyRecord(from: result.get())}}@@ -777,6 +947,7 @@ private extension WorkflowSyncService {let aggregate = WorkflowSyncedDailyAggregate(date: date,+ sourceGeneration: record[FieldKeys.sourceGeneration] as? String,eventCount: intValue(record[FieldKeys.eventCount]),sessionStartCount: intValue(record[FieldKeys.sessionStartCount]),stopCount: intValue(record[FieldKeys.stopCount]),@@ -796,39 +967,37 @@ private extension WorkflowSyncService {return WorkflowSyncedDailyRecord(deviceId: deviceId,daily: aggregate,- updatedAt: record[FieldKeys.updatedAt] as? Date ?? record.modificationDate+ updatedAt: record[FieldKeys.updatedAt] as? Date ?? record.modificationDate,+ recordName: record.recordID.recordName)}- static func accountSalt(from result: Result<CKRecord, Error>?) -> Data? {- guard case let .success(record) = result,- let salt = record[FieldKeys.salt] as? Data,- salt.count == Metrics.saltByteCount else {+ 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}-- return salt}static func filteredRetained(- records: [WorkflowSyncedDailyRecord],- excluding currentDeviceId: String? = nil+ records: [WorkflowSyncedDailyRecord]) -> [WorkflowSyncedDailyRecord] {let cutoffKey = WorkflowStorage.dateKey(for: WorkflowStorage.retentionCutoffDate())- return records.filter { record in- guard record.date >= cutoffKey else {- return false- }-- return currentDeviceId.map { record.deviceId != $0 } ?? true- }+ return records.filter { $0.date >= cutoffKey }}static func recordsByID(- records: [WorkflowSyncedDailyRecord],- excluding currentDeviceId: String? = nil+ records: [WorkflowSyncedDailyRecord]) -> [String: WorkflowSyncedDailyRecord] {- filteredRetained(records: records, excluding: currentDeviceId)+ filteredRetained(records: records).reduce(into: [String: WorkflowSyncedDailyRecord]()) { result, record inresult[record.id] = record}@@ -910,15 +1079,21 @@ private extension WorkflowSyncService {}}-/// records 永不包含本机设备的记录: 写缓存与读取时都经 filteredRetained(excluding:) 过滤+/// records 包含所有设备的脱敏聚合;currentDeviceId 用于展示时替换而不是叠加本机云端副本nonisolated struct WorkflowSyncSnapshot: Equatable {let records: [WorkflowSyncedDailyRecord]+ let currentDeviceId: String?- static let disabled = WorkflowSyncSnapshot(records: [])+ static let disabled = WorkflowSyncSnapshot(records: [], currentDeviceId: nil)}private nonisolated struct WorkflowSyncState: Codable, Equatable {- static let currentSchema = 3+ static let currentSchema = 4+ static let previousSchema = 3++ static func supports(_ schema: Int) -> Bool {+ schema == currentSchema || schema == previousSchema+ }var schema: Intvar deviceId: String?@@ -963,5 +1138,6 @@ private nonisolated struct WorkflowSyncState: Codable, Equatable {private nonisolated enum WorkflowSyncError: Error {case missingAccountSaltcase missingIOPlatformUUID+ case missingRecordResultcase randomSaltFailed}diff --git a/CodexBar/Views/Settings/NotificationOptionsView.swift b/CodexBar/Views/Settings/NotificationOptionsView.swiftindex fe9dcfd..edeb55a 100644--- a/CodexBar/Views/Settings/NotificationOptionsView.swift+++ b/CodexBar/Views/Settings/NotificationOptionsView.swift@@ -5,6 +5,7 @@ import SwiftUIstruct NotificationOptionsView: View {@ObservedObject var notificationSettings: NotificationSettings@ObservedObject var codexHookSettings: CodexHookSettings+ @ObservedObject var codexCLINotificationSettings: CodexCLINotificationSettingsvar body: some View {VStack(alignment: .leading, spacing: Metrics.rowSpacing) {@@ -14,6 +15,7 @@ struct NotificationOptionsView: View {taskWaitingRowtaskHapticRowcreditExpiryRow+ codexCLINotificationRow}.padding(.horizontal, Metrics.horizontalPadding).padding(.vertical, Metrics.verticalPadding)@@ -135,6 +137,29 @@ struct NotificationOptionsView: View {)}+ private var codexCLINotificationRow: some View {+ optionRow(+ title: "Codex TUI 通知",+ isOn: Binding(+ get: { codexCLINotificationSettings.isEnabled },+ set: { codexCLINotificationSettings.setEnabled($0) }+ ),+ isEnabled: !codexCLINotificationSettings.isUpdating+ ) {+ if codexCLINotificationSettings.isUpdating {+ ProgressView()+ .controlSize(.small)+ .scaleEffect(0.7)+ .frame(width: Metrics.statusIconSize, height: Metrics.statusIconSize)+ } else if let errorMessage = codexCLINotificationSettings.errorMessage {+ Image(systemName: "exclamationmark.circle")+ .foregroundStyle(.orange)+ .frame(width: Metrics.statusIconSize, height: Metrics.statusIconSize)+ .help(errorMessage)+ }+ }+ }+private func optionRow(title: String,isOn: Binding<Bool>,@@ -194,10 +219,11 @@ struct NotificationOptionsView: View {static let panelWidth: CGFloat = 300static let horizontalPadding: CGFloat = 12static let verticalPadding: CGFloat = 10- static let optionRowCount = 6+ static let optionRowCount = 7static let rowSpacing: CGFloat = 7static let rowHeight: CGFloat = 22static let pickerWidth: CGFloat = 72+ static let statusIconSize: CGFloat = 16static let cornerRadius: CGFloat = 12static let statusAnimation = Animation.codexStatus}diff --git a/Docs/AppServer.md b/Docs/AppServer.mdindex 50b62a6..adf2d19 100644--- a/Docs/AppServer.md+++ b/Docs/AppServer.md@@ -51,9 +51,9 @@ codex app-server --listen stdio://- `account/read` 每轮复用连接时用 `refreshToken: false` 更新账户状态。- `account/rateLimits/read` 读取额度, 包括可选的 `rateLimitResetCredits.availableCount`。当可用重置次数大于 0 时, 主 App 会通过 `CodexResetCreditsService` 额外读取本机 Codex OAuth token, 只读请求 `https://chatgpt.com/backend-api/wham/rate-limit-reset-credits` 获取各重置机会的 `expires_at`; 这条请求不走 app-server 日志, 失败时重置次数按钮仍可显示, 但侧边详情面板只展示未知过期时间。- `account/usage/read` 读取 `summary.lifetimeTokens`、`summary.peakDailyTokens`、`dailyUsageBuckets`。-- `config/read` 在开启 Codex Hook 前读取有效配置,用于判断 `[features] hooks = false` 或兼容旧名 `codex_hooks = false` 是否禁用了 Hook;关闭清理时也读取 `hooks.state` 以保留其他 Hook 的信任状态。+- `config/read` 在开启 Codex Hook 前读取有效配置,用于判断 `[features] hooks = false` 或兼容旧名 `codex_hooks = false` 是否禁用了 Hook;关闭清理时也读取 `hooks.state` 以保留其他 Hook 的信任状态。打开设置窗口或通知选项面板时还会读取 `[tui].notifications`,缺失时按 Codex 默认开启处理,布尔值 `false` 或空事件数组按关闭处理。- `hooks/list` 在写入 Hook 后或设置页刷新时验证 Codex 实际识别到的 Hook,检查 `command`、`eventName`、`enabled`、`sourcePath`、`trustStatus`、`key`、`currentHash`、`warnings` 和 `errors`。-- `config/batchWrite` 只用于写回 `hooks.state`:开启后把 CodexBar Hook 的 `key/currentHash` upsert 成 `trusted_hash`,关闭时移除对应 key。+- `config/batchWrite` 用于写回 `hooks.state` 和 `tui.notifications`:Hook 开启后把 CodexBar Hook 的 `key/currentHash` upsert 成 `trusted_hash`,关闭时移除对应 key;通知选项面板切换「Codex TUI 通知」时只 upsert `tui.notifications` 的布尔值并要求 app-server reload 用户配置,不修改顶层 `notify` 外部回调。`account/rateLimits/read` 的额度模型约定:diff --git a/Docs/CodexHook.md b/Docs/CodexHook.mdindex 3da01d7..7b43d8c 100644--- a/Docs/CodexHook.md+++ b/Docs/CodexHook.md@@ -88,7 +88,7 @@ Hook stdin 会尝试解析为 Codex 官方 JSON 对象,只读取顶层字段- 轮次: `turn_id`- 子 Agent 标识: `agent_id`,字段存在时写为 `agent`,用于本机实时配对 `SubagentStart` / `SubagentStop`-事件名来自 payload 顶层 `hook_event_name`。没有 `--hook-event` 参数时按普通 App 启动;有 `--hook-event` 参数但 stdin 为空、不是 JSON 或事件名缺失时吞掉本次 Hook,避免 Hook 子进程继续启动完整菜单栏 App。事件时间优先读取 payload 顶层 `timestamp`,解析后按本机时区写成 `yyyy-MM-dd HH:mm:ss.SSS`;如果 `timestamp` 缺失或无法解析,记录当前时间作为兜底。同一个事件时间也会按本机时区格式化为 `yyyy-MM-dd` 的 date key,用于选择 `events/YYYY-MM-DD.jsonl` 文件。日期和时间解析统一走 `CodexDateFormat`,其中高频的 `yyyy-MM-dd` key 由本机 Gregorian 日历组件生成和校验,不暴露可变 `DateFormatter` 实例。每行按固定顺序写入 `timestamp`、`event`、`model`、`effort`、`permission`、`approval`、`session`、`turn`、`agent`、`tool`、`cwd`;缺少对应 Hook 字段或当前 rollout 无法读取时写为 `null`。旧版事件行缺少新增字段时仍可正常解码。+事件名来自 payload 顶层 `hook_event_name`。没有 `--hook-event` 参数时按普通 App 启动;有 `--hook-event` 参数但 stdin 为空、不是 JSON 或事件名缺失时吞掉本次 Hook,避免 Hook 子进程继续启动完整菜单栏 App。事件时间优先读取 payload 顶层 `timestamp`,解析后按本机时区写成 `yyyy-MM-dd HH:mm:ss.SSS`;如果 `timestamp` 缺失或无法解析,记录当前时间作为兜底。同一个事件时间也会按本机时区格式化为 `yyyy-MM-dd` 的 date key,用于选择 `events/YYYY-MM-DD.jsonl` 文件。日期和时间解析统一走 `CodexDateFormat`,其中高频的 `yyyy-MM-dd` key 由本机 Gregorian 日历组件生成和校验,不暴露可变 `DateFormatter` 实例。每行按固定顺序写入 `timestamp`、`event`、`model`、`effort`、`permission`、`approval`、`session`、`turn`、`agent`、`tool`、`cwd`;缺少对应 Hook 字段或当前 rollout 无法读取时写为 `null`。事件行缺少可选字段时仍可正常解码。事件名统计时会去掉 `_` 和 `-` 并转小写,因此 `PreToolUse`、`pre_tool_use`、`pre-tool-use` 会归为同一个事件。@@ -113,24 +113,28 @@ Hook 数据目录:```json{- "schema": 3,+ "schema": 4,"pending": ["2026-06-21"],"dirty": [],"days": {"2026-06-21": {"offset": 102400,"size": 122880,- "corrupt": 0+ "corrupt": 0,+ "sourceGeneration": "<uuid>",+ "sourceIsFresh": true,+ "fileIdentifier": 123456,+ "boundaryHash": "<sha256>"}}}```-`pending` 表示有新增事件等待整理的日期;`dirty` 表示需要从头重建 `daily.jsonl` 对应日期的日期;`offset` 是当天 events 文件已经处理到的字节位置;`size` 是上次处理完成时当天 events 文件大小;`corrupt` 是当天解析失败的 JSONL 行数。+`pending` 表示有新增事件等待整理的日期;`dirty` 表示需要从头重建 `daily.jsonl` 对应日期的日期;`offset` 是当天 events 文件已经处理到的字节位置;`size` 是上次处理完成时当天 events 文件大小;`corrupt` 是当天解析失败的 JSONL 行数。`sourceGeneration` 标识这份日期文件从空文件开始后的连续追加阶段,`sourceIsFresh` 表示该阶段是否由 CodexBar 确认从空文件开始;`fileIdentifier` 和 `boundaryHash` 只在本机用于识别文件替换、截断或原位置内容变化,不进入 CloudKit。`WorkflowStorage` 定义这些路径和保留策略。UI 读取时优先加载 `daily.jsonl`;原始事件文件不再作为 UI 临时快照回退源。-旧版单文件 `HookEvents/events.jsonl` 不参与新版统计、迁移或清理。+当前统计只读取按日期拆分的 `events/YYYY-MM-DD.jsonl`;`HookEvents/events.jsonl` 不参与统计或清理。## 实时活动状态@@ -161,7 +165,7 @@ Codex Hook 事件可能缺少起点、结束或中断信号。`CodexSessionLifec- `PermissionRequest` 先成为审批候选;只有 rollout 已确认该 turn 的 `approvals_reviewer == user` 才进入等待批准,自动 reviewer 产生的同名 Hook 不改变运行状态。重复的用户等待事件不重复发布等待 transition。live 读取一次可能包含多个事件,monitor 会在整批应用后按任务键合并等待候选:最终仍在等待时使用最终快照发布一次,已经恢复运行、完成或移除时不发布过期等待 transition;完成候选保持事件顺序,并按 completion ID 防止同批重复发布。- Hook `Stop` 或 rollout `task_complete` 结束任务并产生最近完成记录,两者在进程内按精确任务键和 session 回退键去重,保留第一次确认的完成及精确耗时且不重复发布 transition。后到的重复完成不会覆盖首次确认结果,也不会缩短 24 小时去重窗口。期间迟到的工具、压缩或权限事件不会恢复已完成任务,只有时间晚于完成记录的新 `UserPromptSubmit` 可以开始下一段生命周期。rollout `turn_aborted` 会直接进入最近终止列表;同 session 新 prompt 淘汰的旧 turn 则立即退出活动列表并进入 5 秒终态确认窗口,期间继续参与 rollout 查询并优先接受 `task_complete`、`turn_aborted` 或迟到 Hook `Stop`,到期仍无终态才进入最近终止列表。“完成”只表示该 turn 已结束,不表示任务成功。- 精确 turn 匹配失败时,回退同 session 最近活动任务,再回退同项目匿名任务。-- UI 优先展示最近等待任务,其次最近运行任务、最近完成任务和最近终止任务,同时保留运行与等待数量。只有终止历史时,活动卡片使用灰色终止状态展示最近一项。活动卡片第一行按“模型 ` • ` 推理强度 ` • ` 项目”组合可用字段,第二行展示运行时间、可靠时的“`N 个子 Agent`”及最近的请求/工具/压缩/子智能体事件;其他任务数量以右侧 `+N` 徽标展示。任务中心在模型后使用 ` • ` 展示推理强度,但不展示子 Agent 数量。菜单栏完成绿色保留 30 秒,任务中心的最近完成和最近终止记录保留 10 分钟,24 小时没有新事件的活动自动过期。+- UI 优先展示最近等待任务,其次最近运行任务、最近完成任务和最近终止任务,同时保留运行与等待数量。只有终止历史时,活动卡片使用灰色终止状态展示最近一项。活动卡片第一行按“模型 `•` 推理强度 `•` 项目”组合可用字段,第二行展示运行时间、可靠时的“`N 个子 Agent`”及最近的请求/工具/压缩/子智能体事件;其他任务数量以右侧 `+N` 徽标展示。任务中心在模型后使用 `•` 展示推理强度,但不展示子 Agent 数量。菜单栏完成绿色保留 30 秒,任务中心的最近完成和最近终止记录保留 10 分钟,24 小时没有新事件的活动自动过期。跨日时仍在内存中的运行任务会继续保留;重启 App 后由滚动 24 小时 bootstrap 恢复近期活动,并为更早开始的精确 turn 定向回填起点。任务会一直保留到收到 Hook `Stop` 或 rollout `task_complete`、检测到 `turn_aborted`、同 session 新 prompt 将其淘汰、Hook 被关闭或连续 24 小时没有新事件。完成高亮、最近完成、最近终止、完成去重键和活动过期共用按最近到期时刻创建的单次清理任务,不运行常驻清理计时器;读取完成键时还会惰性淘汰已经超过 24 小时的记录,避免系统休眠或计时任务稍晚唤醒时误拦第一条新事件。@@ -170,14 +174,17 @@ Codex Hook 事件可能缺少起点、结束或中断信号。`CodexSessionLifecHook 可能由多个 Codex 进程并发触发。`WorkflowHookEventRecorder` 会在同一个 `flock(LOCK_EX)` 中完成轻量写入事务:1. 解析事件时间并格式化为本机时间戳与 date key-2. 追加当前事件到 `events/YYYY-MM-DD.jsonl`-3. 将 date key 加入 `maintenance.json` 的 `pending`;如果当天已在 `pending` 且已有日期状态记录(稳态下的绝大多数事件),跳过 `maintenance.json` 重写+2. 检查当天事件文件是否不存在、已清空、缩小或更换 inode;确认从空文件开始时创建可独立累加的新 generation,非空替换则创建来源不明确的新 generation+3. 追加当前事件到 `events/YYYY-MM-DD.jsonl`+4. 将 date key 加入 `maintenance.json` 的 `pending`;如果来源状态和 pending 都没有变化,跳过 `maintenance.json` 重写Hook 写入路径不更新 `daily.jsonl`,也不执行重建或清理旧文件,避免在 Hook timeout 内持锁执行重活。`WorkflowService` 是 actor,只在现有自动刷新或手动刷新触发工作流统计刷新时检查 `maintenance.json`。打开菜单面板时只读取现有 `daily.jsonl`。如果没有 `pending` 或 `dirty`,服务不会执行维护。-维护时优先处理 `dirty`,从对应日期文件第一行开始流式重建当天聚合;再处理 `pending`,从 `days[date].offset` 开始流式读取新增事件并合并到已有当天聚合。同一维护批次只读取一次现有 `daily.jsonl`,所有日期任务共享并逐步更新同一份内存聚合集合,每次落盘前仍对整份集合执行当前保留策略的归一化。每条坏行会被跳过并计入 `days[date].corrupt`。处理完成后先在 `stats.lock` 外原子写回 `daily.jsonl`,再短暂持有 `stats.lock` 更新 `maintenance.json`,避免主 App 写 daily 时阻塞 Hook 追加事件。批次没有写入时,服务使用文件 size、identifier 和当天日期键组成的进程内 stamp 跳过未变化文件的重复全量归一化;日期跨天或文件变化后会重新检查并在需要时原子改写。+维护时优先处理 `dirty`,从对应日期文件第一行开始流式重建当天聚合;再处理 `pending`,从 `days[date].offset` 开始流式读取新增事件并合并到已有当天聚合。同一维护批次只读取一次现有 `daily.jsonl`,所有日期任务共享并逐步更新同一份内存聚合集合,每次落盘前仍对整份集合执行当前保留策略的归一化。每条坏行会被跳过并计入 `days[date].corrupt`。处理前后会同时校验文件大小、inode 和上次处理边界前最多 4 KB 的 SHA256;无法证明仍为连续追加时换 generation 并重新构建。处理完成后先在 `stats.lock` 外原子写回 `daily.jsonl`,再短暂持有 `stats.lock` 更新 `maintenance.json`,避免主 App 写 daily 时阻塞 Hook 追加事件。批次没有写入时,服务使用文件 size、identifier 和当天日期键组成的进程内 stamp 跳过未变化文件的重复全量归一化;日期跨天或文件变化后会重新检查并在需要时原子改写。++维护只会根据当前仍存在的 events 文件发现和重建日期。直接删除某个历史 `events/YYYY-MM-DD.jsonl` 不会连带删除现有 `daily.jsonl` 行,也不会单独触发 generation 变化;历史日期不再写入新事件时,界面会继续使用已有 daily。若 daily 行也被删除,开启同步时可从本地同步缓存回退到云端贡献。把仍存在的 events 文件清空、截断或替换则不同:连续性校验会识别变化,并按来源是否可确认从空文件开始来切换 generation 和重建。## 保留策略@@ -199,7 +206,7 @@ CloudKit 中每个 iCloud 账号会保存一条账号级 salt:zoneName = CodexBarZonerecordType = CodexBarSyncMetadatarecordName = accountSalt-schemaVersion = 3+schemaVersion = 4salt = 32 bytes```@@ -214,23 +221,26 @@ CodexBar 不上传原始 `IOPlatformUUID`。同一台 Mac 在同一 iCloud 账跨设备同步上传的是 `daily.jsonl` 单日聚合行的内存副本,去掉:```text-sessionIds, turnIds+sourceIsFresh, sessionIds, turnIds```-除 `sessionCount` / `turnCount` 按下述规则生成外,其余字段保持原值同步,包括 `projectCounts` 和 `modelCounts`。上传副本中的这两个 count 只接受已有正数压缩 count,或本地非空 `sessionIds` / `turnIds` 的去重数量;两者都没有时写为 `null`,不会把空数组或真实全零日上传成明确的 count。脱敏只发生在上传副本上,不会写回本地 `daily.jsonl`,因此最近 3 天本地仍保留非空 `sessionIds` / `turnIds` 用于本机精确去重。接收端读取同步记录时不恢复 ID;正数 count 优先,否则分别回退到 `sessionStartCount` / `stopCount`,所以旧版错误的明确 `0` 和缺失字段都不会压过起止事件计数。+`sourceGeneration` 会同步,用于区分同一设备、同一天的独立贡献;它只是随机 UUID。`sourceIsFresh` 只留在本机决定是否允许创建独立贡献,不上传。除 `sessionCount` / `turnCount` 按下述规则生成外,其余统计字段保持原值同步,包括 `projectCounts` 和 `modelCounts`。上传副本中的这两个 count 只接受已有正数压缩 count,或本地非空 `sessionIds` / `turnIds` 的去重数量;两者都没有时写为 `null`,不会把空数组或真实全零日上传成明确的 count。脱敏只发生在上传副本上,不会写回本地 `daily.jsonl`,因此最近 3 天本地仍保留非空 `sessionIds` / `turnIds` 用于本机精确去重。接收端读取同步记录时不恢复 ID;正数 count 优先,否则分别回退到 `sessionStartCount` / `stopCount`,所以明确的 `0` 和缺失字段都不会压过起止事件计数。-每台设备每天一条记录:+正常情况下每台设备每天只有一个 generation、一条记录;确认事件文件从空文件重新开始后,会为同一天创建新的 generation 记录:```textzoneName = CodexBarZonerecordType = CodexBarDailyAggregate-recordName = <deviceId>_<yyyy-MM-dd>-schemaVersion = 3+recordName = <deviceId>_<yyyy-MM-dd>[_<sourceGeneration>]+schemaVersion = 4+sourceGeneration = UUID?```-Hook 子进程不访问网络。主 App 在工作流统计维护刷新后对本次可能变化的日期生成脱敏 daily 副本,计算稳定 hash,并和本地同步状态比较。只有 hash 变化的日期才 upsert 到 CloudKit;上传成功后才更新本地 hash,失败则下次刷新继续重试。+上传匹配只在当前 `deviceId`、当前待上传日期的云端记录内进行,其他设备同一天的贡献不会参与本机副本判断。云端记录没有 `sourceGeneration` 时,必须与本机脱敏聚合的全部同步业务字段完全一致才会被认作同一来源;即使两边 generation 都是 `nil` 也不会跳过内容比较。内容不一致时保留云端贡献,不覆盖、不相加,也不把来源不明确的本机聚合另建为独立贡献。++Hook 子进程不访问网络。主 App 每次实际同步都会为保留窗口内的本机 daily 生成脱敏副本并计算稳定 hash,和本地同步状态相同的日期直接跳过,因此不会依赖某次维护刷新是否恰好与 CloudKit 同步同时发生。只有整批待写记录都返回成功才更新本地 hash。单条读取只有 `unknownItem` 会被视为记录不存在;其他读取错误、请求错误、结果缺失或任一单条保存失败都会清除失败批次日期的 hash,使整批在下次刷新继续重试。-上传按日期稳定排序并分批执行。每轮同步最多处理 20 秒,每批最多 25 天;每批成功后立即把对应日期的 hash 和 `lastUploadAt` 写入 `state.json`。如果时间预算用完、任务被取消或本批 CloudKit 请求失败,本轮停止,剩余日期留给后续每分钟刷新继续。首次开启同步时设置 `needsBackfill`,只有本地所有日期的 hash 都已与 state 匹配后才清除 backfill 请求。+上传按日期稳定排序并分批执行。每轮同步最多处理 20 秒,每批最多 25 天;每批全部确认后立即把对应日期的 hash 和 `lastUploadAt` 写入 `state.json`。如果时间预算用完、任务被取消或本批 CloudKit 请求失败,本轮停止,剩余日期留给后续每分钟刷新继续;部分成功、部分失败的批次会整体重试,重复 upsert 不改变聚合内容。首次开启同步时设置 `needsBackfill`,只有本地所有日期的 hash 都已与 state 匹配后才清除 backfill 请求。本地同步状态保存在:@@ -240,21 +250,23 @@ Hook 子进程不访问网络。主 App 在工作流统计维护刷新后对本~/Library/Application Support/CodexBar/HookEvents/Sync/cursor.data```-- `state.json`: 保存 `deviceId`、按日期记录的 `hashByDate`、`lastUploadAt` 和 `lastPrunedDate`。-- `cache.jsonl`: 保存从 iCloud 拉到的其他设备脱敏 daily 记录,一行一条;不保存当前设备自己的云端副本。+- `state.json`: 保存 `deviceId`、按日期记录的已上传或已按保护规则处理的 `hashByDate`、`lastUploadAt` 和 `lastPrunedDate`。+- `cache.jsonl`: 保存从 iCloud 拉到的所有设备脱敏 daily 记录,一行一条;当前设备自己的云端副本用于本地数据缩减时回退。- `cursor.data`: 保存 CloudKit custom zone `CodexBarZone` 的 `CKServerChangeToken`,用于下次只拉取增量变化;没有游标时会 query 全量 `CodexBarDailyAggregate` 重建 `cache.jsonl`,随后建立新的游标基线;游标失效或增量拉取失败时会重新全量重建。+CloudKit 返回删除变化时只会按 record name 从 `cache.jsonl` 移除记录,不会清除 `state.json` 已确认的日期 hash。因此外部删除云端记录后,如果本机该日聚合没有变化,不会在下一轮立即重新上传;本机内容变化或对应 hash 被清除后才会再次进入候选。+接收云端变化时只更新 `cache.jsonl` 和 `cursor.data`,不直接发布新的 `WorkflowSnapshot`,也不让面板立即跳数。缓存和游标按「先写 `cache.jsonl`,再写 `cursor.data`」提交;如果缓存写入失败,游标不会提前推进,下一轮会重新拉取同一批变化或全量回填。面板仍只在现有每分钟自动刷新或用户手动刷新时重新读取本地 `daily.jsonl` 与同步缓存。展示合并规则:```text-最终展示 = 本机 daily.jsonl + 同步缓存中的其他设备记录+最终展示 = 各设备、各安全 generation 的 daily 贡献之和```-`cache.jsonl` 写入前必须过滤本机自己的 CloudKit 记录,否则本机会把本地 daily 和自己上传的云端副本重复相加。本机数据永远以本地 `daily.jsonl` 为准;同步缓存只补其他设备。热力图详情的 6 个计数指标按每台设备各自 daily 口径先生成展示值,再按日期相加;`projectCounts` 和 `modelCounts` 分别按项目名、模型名逐项相加,最后从合并后的模型计数中选出「最热模型」。+同一 generation 的本机 daily 和本机云端副本不会重复相加:本机 `eventCount` 大于等于同 generation 云端副本时使用本机,否则回退云端。确认从空文件开始的新 generation 会作为同设备、同日期的独立贡献,与已有 generation 相加;来源不明确的非空替换不会自动加入已有云端贡献,避免重复统计。云端记录没有 generation 时,只有其全部同步业务字段与本机完全相同才会认作同一 generation;不一致则继续保护云端。其他设备记录照常累加;热力图详情的 6 个计数指标按每条安全贡献各自 daily 口径先生成展示值,再按日期相加,`projectCounts` 和 `modelCounts` 分别按项目名、模型名逐项相加,最后从合并后的模型计数中选出「最热模型」。-CloudKit 也按最近 210 天保留。每天第一次工作流刷新时,当前设备会删除 `deviceId == 本机 deviceId` 且早于保留窗口的 CloudKit 记录;其他设备记录不由本机清理。展示侧始终忽略最近 210 天外的缓存记录。+CloudKit 也按最近 210 天保留。每天第一次工作流刷新时,当前设备会删除 `deviceId == 本机 deviceId` 且早于保留窗口的全部 generation 记录;其他设备记录不由本机清理。展示侧始终忽略最近 210 天外的缓存记录。维护和同步请求由 `WorkflowSyncScheduler` 统一调度。菜单面板打开时只读取现有 `daily.jsonl` 和同步缓存;app-server 自动刷新倒计时重置、同步开关开启、Hook 重新开启或同步账号恢复可用时, 调度器合并维护/同步请求。同步中不会取消重启,冷却窗口内只保留一次待补跑请求,补跑前会重新校验 Hook、同步偏好和账号可用性。@@ -267,12 +279,12 @@ CloudKit 也按最近 210 天保留。每天第一次工作流刷新时,当前`daily.jsonl` 每一行 JSON 的字段顺序固定为:```text-date, eventCount, sessionStartCount, stopCount, preToolUseCount, postToolUseCount,+date, sourceGeneration, sourceIsFresh, eventCount, sessionStartCount, stopCount, preToolUseCount, postToolUseCount,permissionRequestCount, preCompactCount, postCompactCount, subagentStartCount,subagentStopCount, sessionCount, turnCount, projectCounts, modelCounts, sessionIds, turnIds```-其中 `sessionIds` / `turnIds` / `sessionCount` / `turnCount` 没有值时写为 `null`,`projectCounts` 和 `modelCounts` 内部键按稳定顺序写出。+其中 `sourceGeneration` 是本地日期事件源的随机 UUID,`sourceIsFresh` 只表示 CodexBar 是否确认该 generation 从空文件开始;两者不包含事件内容。`sessionIds` / `turnIds` / `sessionCount` / `turnCount` 没有值时写为 `null`,`projectCounts` 和 `modelCounts` 内部键按稳定顺序写出。能参与统计的事件行必须至少满足:@@ -312,12 +324,12 @@ subagentStopCount, sessionCount, turnCount, projectCounts, modelCounts, sessionI| `subagentStopCount` | `event` | `event` 归一化后等于 `subagentstop` 时 `+1`。 | 参与「子智能体」。 || `sessionIds` | `session` | 新建聚合初始化为 `[]`。最近 3 个本地自然日内,任意事件行只要 `session` 是非空字符串,就插入当天集合并去重、排序;不要求事件类型是 `SessionStart`。聚合结束后仍为空或进入窗口外压缩时写成 `null`;只有非空数组会持久化。 | 参与「会话总数」去重。 || `turnIds` | `turn` | 新建聚合初始化为 `[]`。最近 3 个本地自然日内,任意事件行只要 `turn` 是非空字符串,就插入当天集合并去重、排序;不要求事件类型是 `Stop`。聚合结束后仍为空或进入窗口外压缩时写成 `null`;只有非空数组会持久化。 | 参与「对话轮次」去重。 |-| `sessionCount` | `sessionIds`、旧 `sessionCount`、`sessionStartCount` | 最近 3 天通常为 `null`;日期进入 3 天外窗口后,归一化时优先沿用已有正数 `sessionCount`,否则使用非空 `sessionIds` 的去重数量,再否则使用 `sessionStartCount`,然后移除 `sessionIds`。空 ID 数组不表示权威的零;历史 `sessionCount == 0` 但 `sessionStartCount > 0` 时也会自动修复。 | 参与「会话总数」。 |-| `turnCount` | `turnIds`、旧 `turnCount`、`stopCount` | 最近 3 天通常为 `null`;日期进入 3 天外窗口后,归一化时优先沿用已有正数 `turnCount`,否则使用非空 `turnIds` 的去重数量,再否则使用 `stopCount`,然后移除 `turnIds`。空 ID 数组不表示权威的零;历史 `turnCount == 0` 但 `stopCount > 0` 时也会自动修复。 | 参与「对话轮次」。 |+| `sessionCount` | `sessionIds`、`sessionCount`、`sessionStartCount` | 最近 3 天通常为 `null`;日期进入 3 天外窗口后,归一化时优先沿用已有正数 `sessionCount`,否则使用非空 `sessionIds` 的去重数量,再否则使用 `sessionStartCount`,然后移除 `sessionIds`。空 ID 数组不表示权威的零;`sessionCount == 0` 但 `sessionStartCount > 0` 时会自动修复。 | 参与「会话总数」。 |+| `turnCount` | `turnIds`、`turnCount`、`stopCount` | 最近 3 天通常为 `null`;日期进入 3 天外窗口后,归一化时优先沿用已有正数 `turnCount`,否则使用非空 `turnIds` 的去重数量,再否则使用 `stopCount`,然后移除 `turnIds`。空 ID 数组不表示权威的零;`turnCount == 0` 但 `stopCount > 0` 时会自动修复。 | 参与「对话轮次」。 || `projectCounts` | `cwd` | 任意事件行只要 `cwd` 非空,就取标准化路径的最后一层目录名作为项目名并 `+1`;如果最后一层为空,回退使用完整路径字符串。统计的是事件数,不是会话数或调用工具数。未知事件也会计入。 | 用于计算 `mostActiveProject`,当前页面不展示。 || `modelCounts` | `model` | 任意事件行只要 `model` 非空,就按原始模型名 `+1`。统计的是带模型字段的事件数,不是 token 数;未知事件也会计入。 | 合并后用于计算并展示「最热模型」。 |-读取旧 `daily.jsonl` 时,缺失的数字字段按 `0` 处理,缺失的 `projectCounts` / `modelCounts` 按空字典处理,缺失的 `sessionIds` / `turnIds` / `sessionCount` / `turnCount` 保持为 `nil`。维护 schema 升级到 `3` 后会把保留窗口内已有事件日期标记为 dirty,从原始事件重建模型计数;后续归一化仍按当前保留策略补齐或压缩 ID 字段,并把由空 ID 数组错误压缩出的零计数修复为起止事件兜底值。+读取 `daily.jsonl` 时,缺失的数字字段按 `0` 处理,缺失的 `projectCounts` / `modelCounts` 按空字典处理,缺失的 `sessionIds` / `turnIds` / `sessionCount` / `turnCount` / `sourceGeneration` 保持为 `nil`,缺失的 `sourceIsFresh` 按 `false` 处理。仍有原始 events 文件的日期会在维护时确保存在来源 generation;已有非空事件文件默认视为来源不明确,只有 Hook 明确从不存在或空文件开始时才标记 fresh。只剩 daily、原始 events 已不存在的日期不会凭空生成 generation,原 daily 行会继续保留。后续归一化仍按当前保留策略补齐或压缩 ID 字段,并把由空 ID 数组产生的不一致零计数修复为起止事件兜底值。UI 不直接展示所有原始字段,而是先生成 `WorkflowDailyMetrics`:diff --git a/Docs/CrossDeviceSync.md b/Docs/CrossDeviceSync.mdindex 71476de..854aaab 100644--- a/Docs/CrossDeviceSync.md+++ b/Docs/CrossDeviceSync.md@@ -9,6 +9,7 @@- `daily.jsonl` 中每一天的工作流统计聚合副本- 会话总数、对话轮次、子智能体、调用工具、权限请求、上下文压缩等计数字段- `eventCount`、`projectCounts` 和 `modelCounts`+- 用于区分同设备、同日期独立贡献的随机 `sourceGeneration`不会同步:@@ -51,21 +52,19 @@ Sync/cache.jsonlSync/cursor.data```-如果旧版 `HookEvents/iCloudSync/` 已存在且新的 `HookEvents/Sync/` 不存在,`WorkflowStorage.syncDirectoryURL()` 会继续使用旧目录,避免已有同步状态丢失;新写入默认使用 `Sync/`。-各文件职责:-| 文件 | 内容 |-| ------------- | ---------------------------------------------------------------------------------- |-| `state.json` | 本机同步状态,包括 `deviceId`、每天上传过的 hash、`lastUploadAt`、`lastPrunedDate` |-| `cache.jsonl` | 从 iCloud 拉取到的其他设备脱敏 daily 记录,一行一条;不保存当前设备自己的云端副本 |-| `cursor.data` | CloudKit custom zone `CodexBarZone` 的 `CKServerChangeToken`,用于下次增量拉取 |+| 文件 | 内容 |+| ------------- | --------------------------------------------------------------------------------------- |+| `state.json` | 本机同步状态,包括 `deviceId`、每天已处理的本机 hash、`lastUploadAt`、`lastPrunedDate` |+| `cache.jsonl` | 从 iCloud 拉取到的所有设备脱敏 daily 记录,一行一条;同一天可包含多个 generation |+| `cursor.data` | CloudKit custom zone `CodexBarZone` 的 `CKServerChangeToken`,用于下次增量拉取 |`state.json` 的逻辑结构:```json{- "schema": 3,+ "schema": 4,"deviceId": "<当前设备在当前 iCloud 账号下的匿名设备 ID>","hashByDate": {"2026-06-25": "<脱敏 daily 聚合的 SHA256>"@@ -95,19 +94,20 @@ zoneName = CodexBarZonerecordType = CodexBarSyncMetadatarecordName = accountSaltfields:- schemaVersion: 3+ schemaVersion: 4salt: Data(32 bytes)```-每天的工作流统计记录保存在 custom zone `CodexBarZone`:+每天的工作流统计贡献记录保存在 custom zone `CodexBarZone`。正常情况下每台设备每天只有一个 generation;确认原始事件文件从空文件重新开始后,同一天会增加一条 generation 记录:```textrecordType = CodexBarDailyAggregate-recordName = <deviceId>_<yyyy-MM-dd>+recordName = <deviceId>_<yyyy-MM-dd>[_<sourceGeneration>]fields:- schemaVersion: 3+ schemaVersion: 4deviceId: Stringdate: String+ sourceGeneration: String?eventCount: IntsessionStartCount: IntstopCount: Int@@ -129,6 +129,8 @@ fields:`modelCounts` 会保留 Hook 事件中的模型名及其当天事件计数,用于跨设备合并后计算热力图详情的「最热模型」;不会包含 prompt、response 或原始事件内容。+CloudKit Production schema 必须包含当前 schema `4` 使用的字段,包括 `CodexBarDailyAggregate.sourceGeneration`。schema 变化需要通过 CloudKit Dashboard 从 Development 部署到 Production;App 只负责读写记录,不会自动部署 Production schema。开发签名通常访问 Development,发布签名访问 Production。+## 设备标识设备标识不直接上传 `IOPlatformUUID`。同步服务会先在当前 iCloud private database 中读取或创建 32 字节账号级 salt,然后计算:@@ -143,7 +145,7 @@ deviceId = HMAC_SHA256(accountSalt, IOPlatformUUID)- 同一台 Mac 切换 iCloud 账号后会得到不同的 `deviceId`- CloudKit 中不会保存原始 `IOPlatformUUID`-如果本地 `state.json` 的 `schema` 和当前代码不一致,服务会丢弃旧同步状态。下一轮同步会按当前设备重新写入 `state.json`,清空旧 `cache.jsonl` / `cursor.data`,再从 `CodexBarZone` 重建缓存。当前 iCloud sync state schema 为 `3`;从 schema `2` 升级时会重新上传本机 daily,用修复后的会话和轮次计数覆盖历史错误的明确 `0`。+当前 iCloud sync state schema 为 `4`。服务会在实际同步前校验 `state.json`;状态无法按当前 schema 使用时,会重建同步状态并重新拉取 CloudKit 缓存。只读本地缓存用于展示时不会改写同步 state。如果本地 `state.json` 中的 `deviceId` 和当前解析出的 `deviceId` 不一致,说明 iCloud 账号或账号级 salt 已变化。此时同步服务会重置本地同步状态,清空 `cache.jsonl`,并删除 `cursor.data`,然后按新账号重新同步。@@ -224,7 +226,7 @@ WorkflowService.loadSnapshot(performMaintenance: true, synchronize: true)- 同步账号从不可用变为可用,且 Hook 与跨设备同步都已开启- app-server 自动刷新倒计时重置时,如果 Hook、跨设备同步和同步账号都可用-Hook 子进程不访问网络。它只把原始事件写入本机 `events/YYYY-MM-DD.jsonl` 并标记 `maintenance.json` 的 pending 日期(当天已 pending 时跳过重写)。真正的 daily 重建和 CloudKit 同步都由主 App 的维护刷新完成。+Hook 子进程不访问网络。它只检查事件文件是否从空文件重新开始、维护本地 generation 状态、把原始事件写入 `events/YYYY-MM-DD.jsonl` 并标记 `maintenance.json` 的 pending 日期。真正的 daily 重建和 CloudKit 同步都由主 App 的维护刷新完成。调度器规则:@@ -247,11 +249,13 @@ flowchart TDF --> G{"deviceId 是否变化?"}G -- "是" --> H["重置 state/cache/cursor"]G -- "否" --> I["沿用本地同步状态"]- H --> J["生成脱敏 daily 副本"]- I --> J- J --> K["按 hash 判断待上传日期"]+ H --> Q["校验 sync state schema"]+ I --> Q+ Q --> P["先刷新 CloudKit 缓存"]+ P --> J["生成脱敏 daily 副本"]+ J --> K["按 generation 与 hash 判断待上传日期"]K --> L["分批上传到 CloudKit"]- L --> M["拉取 CloudKit 增量变化"]+ L --> M["再次拉取上传后的增量变化"]M --> N["清理本设备过期云端记录"]N --> O["保存 state 并合并快照"]```@@ -274,28 +278,27 @@ CodexBar.workflowSyncDidFinish- 保留各类计数字段- 保留 `projectCounts`- 保留 `modelCounts`+- 保留随机 UUID `sourceGeneration`+- 不包含只用于本机判断来源是否从空文件开始的 `sourceIsFresh`- 不包含 `sessionIds`- 不包含 `turnIds`- 优先把本机已有的正数 `sessionCount` / `turnCount` 写入同步副本- 如果没有正数压缩 count,但本机还有非空 `sessionIds` / `turnIds`,会把去重数量写入对应 count- 如果两者都没有,对应同步 count 为 `null`,不会上传空数组得到的 `0`-明确的 `sessionCount == 0` / `turnCount == 0` 如果分别与正数 `sessionStartCount` / `stopCount` 冲突,会被视为旧版空数组压缩产生的不一致值;上传源会在本地归一化时修复。接收端不恢复 ID,生成 `WorkflowDailyMetrics` 时使用「正数 `sessionCount`,否则 `sessionStartCount`」和「正数 `turnCount`,否则 `stopCount`」,所以在云端记录被覆盖前也能立即正确展示。真正没有会话或轮次的日期因为起止事件计数同样为 `0`,最终仍显示为 `0`。+明确的 `sessionCount == 0` / `turnCount == 0` 如果分别与正数 `sessionStartCount` / `stopCount` 冲突,会被视为不一致值并在本地归一化时修复。接收端不恢复 ID,生成 `WorkflowDailyMetrics` 时使用「正数 `sessionCount`,否则 `sessionStartCount`」和「正数 `turnCount`,否则 `stopCount`」。真正没有会话或轮次的日期因为起止事件计数同样为 `0`,最终仍显示为 `0`。本机 `daily.jsonl` 不会因为上传而被改写。也就是说,最近 3 个本地自然日实际收集到的非空 `sessionIds` / `turnIds` 仍然只保存在本机,用于本机精确去重。## 待上传日期选择-每次同步先构造候选日期:+每次同步会检查保留窗口内的全部本机日期:```text-候选日期 =- 本轮维护后内容发生变化的日期- + state.hashByDate 中还没有记录的本机日期- + needsBackfill 为 true 时的全部本机日期+候选日期 = 本机 daily.jsonl 中的全部保留日期```-「本轮维护后内容发生变化的日期」通过对比维护前后的脱敏同步 payload 得出;只有本轮会实际执行同步(`synchronize: true` 且 `WorkflowSync.isEnabled == true`)时才会计算,其余维护刷新跳过这两次全量对比。+最多只有 210 个日期;逐日稳定 hash 相同的记录会立即跳过。这样维护和 CloudKit 同步即使分两轮发生,也不会因为变化日期已经被维护流程消费而漏传。对每个候选日期:@@ -303,7 +306,7 @@ CodexBar.workflowSyncDidFinish2. 转换成脱敏 cloud aggregate。3. 用固定字段顺序序列化为 JSON line。4. 计算 SHA256。-5. 如果 hash 和 `state.hashByDate[date]` 相同,则跳过。+5. 如果 hash 和 `state.hashByDate[date]` 相同,表示这份本机数据已经上传或已按保护规则处理,直接跳过。6. 否则加入待上传列表。待上传列表按日期升序排列,保证每次补传顺序稳定。@@ -321,19 +324,21 @@ CodexBar.workflowSyncDidFinish1. 以 25 天为一批切分待上传列表。2. 每批开始前检查 Task 是否取消,以及是否仍在 20 秒预算内。-3. 先按 record ID 批量读取已有 CloudKit 记录。-4. 已存在的记录复用后改字段;不存在的记录创建新 `CKRecord`。-5. 使用 `database.modifyRecords(saving:deleting:savePolicy:.changedKeys, atomically:false)` 保存。-6. 对保存成功的日期,立即更新 `state.hashByDate[date]`。-7. 如果本批至少有成功日期,更新 `state.lastUploadAt`,并立刻写回 `state.json`。+3. 先按当前设备、当前待上传日期的不带 generation record ID 和当前 generation record ID 批量读取已有 CloudKit 记录;只有单条结果明确为 `unknownItem` 才视为不存在,其他读取错误会终止本批。+4. 同 generation 记录存在时复用更新;云端记录没有 generation 时,只有全部同步业务字段与本机完全一致才认作同一来源。即使本机 generation 也为空,仍必须比较完整内容。+5. 当前 generation 不存在时,只有云端没有该日期记录,或本机明确标记为从空文件开始,才创建新的 generation 记录;来源不明确的非空替换不会自动加入云端已有贡献。+6. 使用 `database.modifyRecords(saving:deleting:savePolicy:.changedKeys, atomically:false)` 保存。+7. 只有本批所有待写记录都成功,或该日期已经明确按防倒退/来源保护规则保留云端,才更新对应的 `state.hashByDate[date]`。+8. 如果读取、请求或任一单条保存失败,会删除本批日期在 `hashByDate` 中的确认值并立即保存,使整批日期稳定进入下轮候选。+9. 本批全部确认后,如果至少有成功写入的日期,更新 `state.lastUploadAt`,并立刻写回 `state.json`。-如果某批 CloudKit 请求整体抛错,本轮上传停止。已经成功的批次不会回滚,剩余日期留给下一次刷新继续处理。+如果某批 CloudKit 请求整体抛错或返回单条失败,本轮上传停止。已经成功确认的前序批次不会回滚;失败批次即使已有部分记录实际写入,也会整批重试,重复 upsert 不改变聚合内容。`needsBackfill` 只有在本机所有 daily 日期的 hash 都已经和 `state.hashByDate` 匹配后才会清除。这样首次开启时即使 20 秒内没有补完,后续每分钟刷新也会继续补传。## 拉取缓存和游标-上传之后会更新本地同步缓存。`CodexBarDailyAggregate` 保存在 custom zone `CodexBarZone`, 因为 CloudKit 默认 zone 不支持 `getChanges`/zone change token。没有 `cursor.data` 时, App 会先 query 全量 `CodexBarDailyAggregate` 记录, 过滤掉当前设备自己的记录后回填 `cache.jsonl`, 然后从 `nil` 调用 CloudKit zone changes 补齐这段变化并保存新的 `cursor.data`; 有游标时优先拉取 custom zone 的增量变化:+上传之后会更新本地同步缓存。`CodexBarDailyAggregate` 保存在 custom zone `CodexBarZone`, 因为 CloudKit 默认 zone 不支持 `getChanges`/zone change token。没有 `cursor.data` 时, App 会先 query 全量 `CodexBarDailyAggregate` 记录(包含当前设备自己的记录)回填 `cache.jsonl`, 然后从 `nil` 调用 CloudKit zone changes 补齐这段变化并保存新的 `cursor.data`; 有游标时优先拉取 custom zone 的增量变化:```textdatabase.recordZoneChanges(@@ -346,12 +351,14 @@ database.recordZoneChanges(处理规则:-- 修改记录: 只接受 `CodexBarDailyAggregate`,转换成 `WorkflowSyncedDailyRecord` 后写入内存 cache;如果 `deviceId == 当前设备`, 从 cache 中移除并跳过-- 删除记录: 如果删除的是 `CodexBarDailyAggregate`,按 record name 解析出 `deviceId` 和 `date`,从 cache 中移除+- 修改记录: 只接受 `CodexBarDailyAggregate`,转换成 `WorkflowSyncedDailyRecord` 后按 CloudKit record name 写入内存 cache,因此同设备、同日期可以保留多个 generation+- 删除记录: 如果删除的是 `CodexBarDailyAggregate`,按原 record name 从 cache 中移除对应 generation- `moreComing == true`: 继续用新的 change token 拉下一页- `changeTokenExpired` 或增量拉取失败: 不写入日志窗口,直接 query 全量 `CodexBarDailyAggregate` 重建 `cache.jsonl`- 全量重建后的游标基线建立失败: 保留已写入的 `cache.jsonl`, 不保存 `cursor.data`, 下轮刷新继续全量重建并再次尝试建立游标+删除变化只会从 `cache.jsonl` 移除对应 record,不会同时清除 `state.hashByDate`。因此,如果用户在 CloudKit Dashboard 或其他客户端删除某天的云端记录,而本机 daily 内容和上次确认的 hash 没有变化,下一轮同步不会立即把它重新上传;只有本机该日聚合之后发生变化,或同步 state 被重置、对应 hash 被清除时,它才会再次成为上传候选。+本地落盘顺序很重要:1. 先写 `cache.jsonl`@@ -364,10 +371,10 @@ database.recordZoneChanges(UI 展示使用 `WorkflowSnapshot`。合并规则是:```text-最终展示 = 本机 daily.jsonl + 同步缓存中的其他设备记录+最终展示 = 各设备、各安全 generation 的 daily 贡献之和```-`cache.jsonl` 写入前会过滤当前设备自己的 CloudKit 记录,否则本机 daily 和自己上传到云端的副本会重复相加。+`cache.jsonl` 会保留当前设备自己的全部 generation。当前本机 generation 与其云端副本不会重复相加:本机 `eventCount` 大于等于同 generation 云端副本时使用本机,否则回退云端。其他 generation 只有在 CodexBar 确认它们分别从空文件开始时才作为独立贡献相加。来源不明确的非空替换不会自动加入已有云端贡献,界面继续使用已有云端记录,避免重复统计。同一天多设备数据相加时,会先把每台设备的 daily aggregate 转成 `WorkflowDailyMetrics`,再按日期求和:@@ -383,7 +390,7 @@ contextCompactionCount += other.contextCompactionCountsubagentCount += other.subagentCount```-本机数据永远以本机 `daily.jsonl` 为准。同步缓存只补其他设备的数据。+上传同样按 generation 防倒退:同 generation 云端 `eventCount` 更大时保留云端副本;本机追平后才继续写回。不同 generation 不再互相覆盖;确认从空文件开始的新 generation 使用独立 record,展示时与已有 contribution 相加。云端记录没有 generation 时,只有全部同步业务字段与本机一致才会认作同一来源;不一致则保留云端记录。CloudKit 拉取不会单独向 UI 推送新快照;只有当前这次 `WorkflowService` 刷新最终提交结果时,菜单面板和热力图才会看到更新。非维护刷新只读取已有 `cache.jsonl`,不会主动联网。@@ -395,7 +402,7 @@ CloudKit 拉取不会单独向 UI 推送新快照;只有当前这次 `Workflow- 保存 `cache.jsonl` 前也会过滤 210 天窗口外的记录- 当前设备每天最多执行一次云端清理-云端清理只删除当前设备自己的过期记录:+云端清理只删除当前设备自己的过期记录,包括同一天的全部 generation:```textdeviceId == 当前 deviceId@@ -406,6 +413,8 @@ date < retentionCutoffDate当前实现不会因为本机 `daily.jsonl` 删除了某个仍在 210 天窗口内的日期,就主动删除该日期对应的 CloudKit 记录。它会等到该记录超过 210 天保留窗口后再清理。+单独删除某天的本机 events 文件也不会删除已有 daily 行:历史日期不再产生事件时,界面仍使用保留下来的本机 daily,并与同 generation 云端副本择优。如果 daily 行也被删除,开启同步时界面会回退到 `cache.jsonl` 中的云端贡献;关闭同步或云端没有副本时,该日期才会从界面消失。相比之下,把仍存在的 events 文件清空或截断会被识别为文件连续性变化,并按维护规则重建或切换 generation。+## 失败和重试失败处理以不中断工作流统计展示为目标。@@ -415,11 +424,15 @@ date < retentionCutoffDate| iCloud 未登录或不可用 | 设置页禁用「跨设备同步」,显示 `同步不可用`; 主面板同步图标走非 active 同步态, 显示 `icloud.slash` 和「同步未开启」 || 用户尝试在同步账号不可用时开启 | `setEnabled(true)` 直接返回,不写入开启状态 || `CodexBarZone` 不存在 | 同步开始时创建 custom zone |-| CloudKit 上传失败 | 本轮上传停止,已成功批次保留,失败日期下次刷新继续 |+| CloudKit 上传读取失败 | 只有 `unknownItem` 视为记录不存在;其他单条读取错误终止本轮,整批日期持久化为待重试 |+| CloudKit 上传保存失败 | 请求抛错、结果缺失或任一单条失败都会终止本轮;已确认的前序批次保留,失败批次清除 hash 后在下次刷新整批重试 |+| 确认从空文件开始的新 generation | 为同设备、同日期创建独立记录,与旧 generation 一起展示和清理 |+| 来源不明确的非空替换 | 不上传为新的独立贡献,继续使用已有云端记录,避免和可能重叠的事件重复相加 || CloudKit 增量拉取失败 | 不写入日志窗口,尝试全量重建缓存 |+| 云端记录被外部删除 | 从本地 cache 移除;如果本机 daily hash 未变化则不会立即重新上传,等待本机内容变化,或 state 重置、对应 hash 被清除后重新进入候选 || CloudKit 全量重建失败 | 本轮同步失败,保存已有 state,保留已有 cache,后续刷新重试 || 账号 salt 创建冲突 | 重新读取 CloudKit 中已有 salt |-| 本地 state schema 不匹配 | 丢弃旧 state,按当前 schema 重新同步 |+| 本地 state schema 不兼容 | 丢弃旧 state,按当前 schema 重新同步 || `deviceId` 变化 | 重置本地同步 state/cache/cursor,按当前 iCloud 账号重新同步 || `changeTokenExpired` | 不写入日志窗口,尝试全量重建缓存并建立新的 cursor || `cache.jsonl` 写入失败 | 不保存新 cursor,下一轮重新拉取同一批变化 |diff --git a/Docs/DevelopmentGuide.md b/Docs/DevelopmentGuide.mdindex 8984724..e6972b1 100644--- a/Docs/DevelopmentGuide.md+++ b/Docs/DevelopmentGuide.md@@ -630,6 +630,8 @@ Hook 开启且当天没有 token bucket 时, 今天的 token 数显示 `--`。开启前会复用 App 当前的 `CodexStatusService` app-server 会话调用 `config/read`, 如果有效配置中 `[features] hooks = false` 或兼容旧名 `codex_hooks = false`, 则不写入 Hook, 并在 Hook 选项下方提示。`config/read` 请求失败时同样不写入 Hook, 并显示"设置 Codex Hook 失败"。开启写入后会继续调用 `hooks/list`, 检查 Codex 实际识别到的 `command`, `eventName`, `enabled`, `sourcePath`, `trustStatus`, `key`, `currentHash`, `warnings` 和 `errors`。如果 `trustStatus` 是 `untrusted` 或 `modified`, CodexBar 只对 `sourcePath` 指向全局 `~/.codex/hooks.json` 且 command 属于当前 CodexBar 的 Hook, 用 `config/batchWrite` 把对应 `trusted_hash` upsert 到 `hooks.state` 并重新 `hooks/list` 验证。`hooks/list`、自动信任写入或验证未通过不会回滚已写入 Hook, 只在 Hook 选项下方显示验证摘要。这些 app-server 请求和响应都会进入日志窗口。+Hook command 保存当前可执行文件的绝对路径。移动或替换 App 后如果不同安装路径的 CodexBar Hook 同时生效,Codex 会让每个 command 都处理同一事件,造成重复追加;另一安装位置的二进制还可能改写共享的 maintenance state。配置维护只增删当前可执行文件对应的 Hook,不会自动清除其他安装路径留下的条目,因此移动 App 和排障时需要显式检查并移除原路径。+下面的时序图展示开启 Hook, Codex 触发事件, 本机写入, 后台维护, 以及常见错误后的处理```mermaid@@ -825,7 +827,7 @@ Hook 数据目录:| `events/YYYY-MM-DD.jsonl` | 按本机日期拆分的原始 Hook 事件 || `daily.jsonl` | 每日聚合结果, UI 优先读取 || `stats.lock` | `flock` 锁文件 |-| `maintenance.json` | pending, dirty, offset, size, corrupt 等维护状态 |+| `maintenance.json` | pending、dirty、offset、来源 generation 和文件连续性校验状态 |## 12. Workflow 维护与聚合流程@@ -860,13 +862,15 @@ flowchart TD任务类型:-| 类型 | 触发条件 | 读取方式 |-| ------- | ---------------------------------------------------------- | ------------------------------- |-| dirty | schema 变化, daily 缺失或坏行, events 状态不一致, 文件缩小 | 从当天 events 文件开头重建 |-| pending | Hook 新增事件或 events 文件变大 | 从 `days[date].offset` 增量读取 |+| 类型 | 触发条件 | 读取方式 |+| ------- | ------------------------------------------------------------------------ | ------------------------------- |+| dirty | schema 变化、daily 缺失或坏行、events 来源 generation 或文件连续性不一致 | 从当天 events 文件开头重建 |+| pending | Hook 新增事件或 events 文件变大 | 从 `days[date].offset` 增量读取 |同一维护批次只读取一次现有 `daily.jsonl`,随后让所有 dirty/pending 日期任务共享并逐步更新同一份内存聚合集合;每次落盘前仍对整份集合执行当前保留策略的归一化。批次没有写入时,服务用文件 size、identifier 和当天日期键组成的进程内 stamp 跳过未变化文件的重复全量解码;日期跨天或文件发生变化后会重新检查并在需要时原子改写。+事件文件发现以当前实际存在的 `events/YYYY-MM-DD.jsonl` 为准。物理删除历史 events 文件不会删除已有 daily 行,也不会单独切换 generation;如果 daily 行也不存在,开启同步时快照可回退到当前 cache 中的云端贡献。仍存在的文件被清空、截断、替换 inode 或边界内容变化时,维护才会按连续性校验切换 generation 并重建。+聚合规则:- 事件名先去掉 `_` 和 `-`, 再转小写@@ -893,9 +897,11 @@ UI 展示指标来自 `WorkflowDailyAggregate.metrics`:| 上下文压缩 | `max(preCompactCount, postCompactCount)` || 最热模型 | 合并 `modelCounts` 后取计数最高的模型, 并列时按名称升序 |-跨设备同步只在 `performMaintenance: true, synchronize: true` 的刷新中执行。`WorkflowSyncScheduler` 会合并同步开关、Hook 重新开启、同步账号恢复可用和自动刷新产生的同步请求;同步中不取消重启, 冷却窗口内只保留一次待补跑请求, 补跑前重新校验 Hook 开启、跨设备同步偏好为 true 且同步账号可用。`WorkflowSyncService` 先用本机 daily 聚合生成脱敏 `WorkflowSyncedDailyAggregate`, 保留 `projectCounts` 和 `modelCounts`, 再按日期稳定排序候选项, 每批最多上传 25 天, 每轮最多使用 20 秒。zone 存在性确认和 account salt 首次成功后在 actor 内跨轮缓存, 任一轮同步失败时作废, 下一轮重新确认(覆盖 iCloud 账号切换)。每批成功后立即保存 `state.hashByDate` 和 `lastUploadAt`, 未完成的 backfill 留给后续自动刷新继续。没有 `cursor.data` 时先 query 全量 `CodexBarDailyAggregate` 回填 `cache.jsonl`; 有游标时优先拉 CloudKit 增量, 游标失效或增量失败时不写入日志窗口, 直接全量重建缓存。写入 `cache.jsonl` 前会过滤当前设备自己的记录, 只保留其他设备记录。增量路径先写 `cache.jsonl`, 成功后再写 `cursor.data`, 避免游标提前推进导致未落盘记录被跳过。同步失败会通过 `CodexBar.workflowSyncDidFinish` 通知发送 `didSucceed=false` 和归类后的 `failureMessage`, 主面板同步图标进入失败态。+跨设备同步只在 `performMaintenance: true, synchronize: true` 的刷新中执行。`WorkflowSyncScheduler` 会合并同步开关、Hook 重新开启、同步账号恢复可用和自动刷新产生的同步请求;同步中不取消重启, 冷却窗口内只保留一次待补跑请求, 补跑前重新校验 Hook 开启、跨设备同步偏好为 true 且同步账号可用。`WorkflowSyncService` 先用本机 daily 聚合生成脱敏 `WorkflowSyncedDailyAggregate`, 保留 `sourceGeneration`、`projectCounts` 和 `modelCounts`, 再为保留窗口内的全部本机日期计算稳定 hash、按日期稳定排序候选项, 每批最多上传 25 天, 每轮最多使用 20 秒。zone 存在性确认和 account salt 首次成功后在 actor 内跨轮缓存, 任一轮同步失败时作废, 下一轮重新确认(覆盖 iCloud 账号切换)。同步先刷新一次 CloudKit 缓存再决定上传:只在当前 `deviceId`、当前待上传日期内查找本机副本;同 generation 复用现有记录并按 `eventCount` 防倒退;没有 generation 的记录必须与本机全部同步业务字段完全一致才会被认作同一来源,即使两边 generation 都是 `nil` 也不能跳过内容比较;确认从空文件开始的新 generation 使用独立记录;来源不明确的非空替换在已有云端贡献时只确认保留云端,不自动上传为新贡献。每批处理后立即保存已经上传或确认保留的 `state.hashByDate`; 只有实际上传时更新 `lastUploadAt`, 未完成的 backfill 留给后续自动刷新继续。上传后再次拉取 CloudKit 变化。没有 `cursor.data` 时先 query 全量 `CodexBarDailyAggregate` 回填 `cache.jsonl`; 有游标时优先拉 CloudKit 增量, 游标失效或增量失败时不写入日志窗口, 直接全量重建缓存。删除变化只移除 cache 记录,不清除已确认 hash,所以外部删除不会在本机 daily 未变化时立即回传。`cache.jsonl` 按 record name 保存所有设备和 generation 的记录;展示时当前本机 generation 与同 generation 云端副本按 `eventCount` 择优,确认独立的其他 generation 与其他设备记录继续累加;来源不明确的替换继续使用已有云端记录。增量路径先写 `cache.jsonl`, 成功后再写 `cursor.data`, 避免游标提前推进导致未落盘记录被跳过。同步失败会通过 `CodexBar.workflowSyncDidFinish` 通知发送 `didSucceed=false` 和归类后的 `failureMessage`, 主面板同步图标进入失败态。++当前代码写入的 CloudKit `schemaVersion` 是 `4`, 本地同步 state schema 是 `4`,本地工作流维护 state schema 也是 `4`。同步 state 无法按当前 schema 使用时会重建并重新同步。daily 或 CloudKit 记录没有 `sourceGeneration` 时仍可读取;只有其全部同步业务字段与当前本机聚合一致时,才会认作同一 generation。-当前代码写入的 CloudKit `schemaVersion` 和本地同步 state schema 都是 `3`。本地 state 从 schema `2` 升级时会丢弃旧 hash 和游标基线,重新上传本机 daily,并从 custom zone 重建其他设备缓存,从而覆盖旧版空数组压缩产生的错误零 count。+CloudKit Production schema 必须包含当前 schema `4` 使用的字段;schema 变化需要通过 CloudKit Dashboard 从 Development 部署到 Production,运行时代码不会代替发布流程执行部署。## 13. 设置窗口流程@@ -905,6 +911,7 @@ UI 展示指标来自 `WorkflowDailyAggregate.metrics`:- `CodexHookSettings.refresh()`- `CodexHookSettings.verifyInstalledHooks()`+- `CodexCLINotificationSettings.refresh()`- `WorkflowSyncSettings.refresh()`- `MenuBarQuotaSettings.refresh()`- `MainPanelSettings.refresh()`@@ -934,6 +941,7 @@ App 再次成为 active 时, 也会刷新 Codex 版本区、同步可用性, 并| 菜单栏额度指示 | `MenuBarQuotaSettings.selection` / `MenuBarQuota.lastWindowSelection` | 开关写入 `.off` 或恢复持久化的上次窗口选择, 窗口菜单写入所选窗口并同步记住; 标签优先来自当前账号 Codex limit 返回的额度窗口, 缺失时使用 fallback 标题 || 主面板任务中心 | `MainPanelSettings.showsTaskCenter` + Codex Hook 状态 | 写入 `MainPanel.showsTaskCenter`; 缺失时默认开启。Hook 关闭时显示为关闭并置灰但保留偏好, 重新开启后恢复 || 系统通知 | `NotificationSettings` + `UNUserNotificationCenter` | 总开关、五类通知子开关、任务触觉开关与阈值写入 `UserDefaults`; 首次开启时请求系统通知授权 |+| Codex TUI 通知 | `CodexCLINotificationSettings` + app-server `config/read` / `config/batchWrite` | 读取用户级 `[tui].notifications`; 缺失时按开启处理,关闭/开启分别 upsert `false` / `true`,不修改顶层 `notify` || 使用快捷键 | `GlobalHotKeySettings.shortcut` | 写入 `UserDefaults` 并注册 hot key || 启用 Codex Hook | app-server `config/read` / `hooks/list` / `config/batchWrite`, `~/.codex/hooks.json` | 检查全局 Hook 开关后追加或移除当前 CodexBar command hook, 并维护对应 `hooks.state` 信任状态 || 跨设备同步 | `WorkflowSyncSettings` + CloudKit account status + `WorkflowSyncScheduler` | Hook 开启且同步账号可用时写入 `UserDefaults`; 开启时标记 `needsBackfill` 并请求调度同步 |@@ -1093,6 +1101,7 @@ App 再次成为 active 时, 也会刷新 Codex 版本区、同步可用性, 并- 主 App 维护 `daily.jsonl` 时, 先锁外原子写 daily, 再短暂持锁提交维护状态, 减少阻塞 Hook 写入- `maintenance.json` 和 `daily.jsonl` 使用 atomic write- 设置 Hook 时通过当前 app-server 会话先读 `config/read`, 未全局禁用时 pretty printed 写回 `~/.codex/hooks.json`, 只移除 command 同时包含当前 App 可执行路径和 `--hook-event` 参数的 handler, 写入后再用 `hooks/list` 验证有效状态;未信任或已修改时, 仅把当前 CodexBar command 且来源为全局 `hooks.json` 的 `key/currentHash` 通过 `config/batchWrite` 写入 `hooks.state`+- `CodexCLINotificationSettings` 通过同一 app-server 会话读取有效 `tui.notifications`,并用 `config/batchWrite` 只 upsert 该布尔值;不直接重写 `config.toml`,也不修改顶层 `notify`隐私和敏感信息边界:@@ -1100,7 +1109,7 @@ App 再次成为 active 时, 也会刷新 Codex 版本区、同步可用性, 并- 不展示 Codex OAuth token 或 `auth.json` 内容; 只用 access token 发起 `rate-limit-reset-credits` 只读请求, 丢弃原始响应, 只保留可用且未过期的过期时间数组- 不把原始敏感 RPC 响应写入文档或测试夹具- 日志完整保存 request/detail, UI 默认只渲染单行预览; 完整内容通过标题行预览或复制查看-- Hook 统计默认只保存在用户 Application Support 的 CodexBar 目录;开启「跨设备同步」后, CloudKit 只保存去掉 `sessionIds` / `turnIds` 的 daily 聚合副本, 不保存原始 Hook events+- Hook 统计默认只保存在用户 Application Support 的 CodexBar 目录;开启「跨设备同步」后, CloudKit 只保存去掉 `sourceIsFresh`、`sessionIds` 和 `turnIds` 的 daily 聚合副本,以及用于区分独立数据段的随机 `sourceGeneration`,不保存原始 Hook events、文件 inode 或边界 hash- 实时任务状态只保存在 `CodexActivityMonitor` 内存中,UI 只展示项目最后一级名称、模型、推理强度、工具名与最近 Hook 事件类型;活动卡片第一行以 `•` 组合模型、推理强度和项目,第二行组合运行时间、可靠且大于 0 的活跃子 Agent 数量与请求/工具/压缩/子智能体状态,其他任务数使用右侧 `+N` 徽标。并发任务中心消费同一快照中的完整等待、运行、最近完成和最近终止列表,在模型后以 `•` 展示推理强度,但不展示子 Agent 数量;列表身份使用进程内 UUID,不展示或持久化 session/turn/agent ID。不写历史文件、不上传 CloudKit,也不新增网络请求。`CodexSessionLifecycleReader` 只对活跃 session + turn 读取本机 rollout,提取事件类型、turn ID、起止时间、耗时、审批 reviewer 和推理强度;不提取、保存或展示提示词、回复、推理内容、工具内容、审批内容或 token 数据## 19. 通知与触觉提醒链路@@ -1108,6 +1117,7 @@ App 再次成为 active 时, 也会刷新 Codex 版本区、同步可用性, 并通知与触觉反馈判定在 `CodexBar/Services/Notifications/`, 偏好类随其他设置类放在 `CodexBar/Services/Settings/`:- `NotificationSettings` (`Services/Settings/`): 总开关、五类通知子开关、任务触觉开关、低额度阈值 (5%/10%/25%, 默认 10%) 和长任务时长 (30s/1m/2m/5m, 默认 1m), 持久化到 UserDefaults; 负责系统授权请求、被拒状态镜像和设置页选项面板可展示状态+- `CodexCLINotificationSettings` (`Services/Settings/`): 通过 app-server 读取和写入用户级 `tui.notifications`; 支持解析布尔值与事件数组,缺失时按默认开启,写入后回读验证并把错误显示在通知选项行- `CodexNotificationService`: 集中判定、去重、调度与发送; 由 `CodexBarAppDelegate` 创建, 订阅 `CodexStatusViewModel.$snapshot`、`CodexActivityMonitor` live transition 与 `NSWorkspace.didWakeNotification`; 五类正式通知共用 `CodexNotificationContent` 文案工厂,系统提交失败时重试一次,等待与完成 transition 还会按偏好请求 AppKit `.levelChange` 触觉反馈- `CodexActivityMonitor`: Hook 开启期间始终运行并维护并发任务;向 UI 发布快照,向提醒服务发布 live transition。`PermissionRequest` 先作为审批候选,只有同 turn 的 rollout reviewer 为 `user` 才确认等待;自动 reviewer 或未知 reviewer 保持运行。单个 live 批次先完整应用事件,再按任务键合并已确认的等待候选;只有批次结束后仍处于等待的任务会使用最终快照发布一次等待 transition,完成候选保持顺序并按 completion ID 做批内去重。通知与触觉开关不会停止活动监测- `HookEventTailReader` (`Services/Workflow/`): 后台 actor;bootstrap 以 512 KB 为单次分块流式读取滚动 24 小时事件,并用 start/events/end 三阶段恢复状态。当前文件用 inode + 完整行 offset 固定 bootstrap/live 边界;bootstrap 结束后 monitor 再发起一次定向回溯,为缺少起点的精确 turn 向旧日期文件最多回读 8 MB。之后每 2 秒 tail 当日增量,保留半行、跨日先读旧文件尾部;live 每成功处理一个分块就推进到最后完整行 offset,后续分块失败只重试未处理部分。旧文件异常触发 bootstrap 时保留 bootstrap 设置的新日期 offset,临时读取失败则保留旧日期等待下轮重试。bootstrap、定时轮询和 Mac 唤醒补读共用串行入口,读取期间到达的请求合并为当前读取结束后的一次补读;monitor generation 会丢弃停用 reader 的迟到批次@@ -1115,7 +1125,7 @@ App 再次成为 active 时, 也会刷新 Codex 版本区、同步可用性, 并活动并发以 session 为边界:不同 session 可以同时运行;同一 session 的 turn 按顺序执行。收到新的 `UserPromptSubmit` 时,monitor 会让该 session 中更早且缺少结束信号的 turn 立即退出活动列表,但保留为等待终态确认任务并触发一次即时 rollout 查询;5 秒内收到 Hook `Stop`、rollout `task_complete` 或 `turn_aborted` 时按真实终态归类,到期仍无终态才生成灰色最近终止记录。子 Agent 事件只能通过共享 session 关联父任务,早于当前顶层任务可信开始时间的事件会被当作上一 turn 的迟到事件忽略。已完成和已终止任务键分别保留 24 小时 tombstone,避免迟到事件恢复旧任务或误操作同 session 的新 turn。终止不会触发绿色完成状态、长任务通知或完成触觉反馈。Hook `Stop` 与 rollout `task_complete` 均视为完成信号,先到者生效,后到者按任务键和 session 回退键去重;重复完成不会覆盖首次确认结果,也不会缩短去重窗口或再次触发反馈。-设置页交互: 「系统通知」主开关行保留在设置窗口内, 子选项 (五类通知子开关、任务触觉开关与两个阈值 Picker) 在主选项右侧的子面板中展开 (`NotificationOptionsPanelController`, 复用 SidePanelSupport 抽屉机制挂在设置窗口上, 内容用常驻 hosting controller + ObservableObject 驱动, 面板尺寸在 Hook 开/关两种状态下保持不变)。「任务等待通知」和「任务触觉反馈」依次排列在「任务完成通知」下方。主开关开启后仅在系统授权允许时展开, 首次授权场景会等待授权结果; 点击行内滑杆按钮可手动展开; 设置窗口 resign key/关闭、主开关关闭或授权变为被拒时自动收起。任务完成、任务等待与任务触觉子项在 Hook 未开启时显示为关闭并置灰, 不修改各自持久化偏好, Hook 重新开启后恢复用户原选择。「主面板任务中心」沿用相同依赖语义;关闭只隐藏活动卡片和任务中心入口,不停止 Monitor、状态点、通知或触觉反馈。授权被拒的引导文案与"打开系统设置"按钮仍内联显示在主开关行下方, 插入提示时不触发设置项纵向动画。+设置页交互: 「系统通知」主开关行保留在设置窗口内, 子选项 (五类通知子开关、任务触觉开关、Codex TUI 通知开关与两个阈值 Picker) 在主选项右侧的子面板中展开 (`NotificationOptionsPanelController`, 复用 SidePanelSupport 抽屉机制挂在设置窗口上, 内容用常驻 hosting controller + ObservableObject 驱动, 面板尺寸在 Hook 开/关两种状态下保持不变)。「任务等待通知」和「任务触觉反馈」依次排列在「任务完成通知」下方。主开关开启后仅在系统授权允许时展开, 首次授权场景会等待授权结果; 点击行内滑杆按钮可手动展开; 设置窗口 resign key/关闭、主开关关闭或授权变为被拒时自动收起。任务完成、任务等待与任务触觉子项在 Hook 未开启时显示为关闭并置灰, 不修改各自持久化偏好, Hook 重新开启后恢复用户原选择。「Codex TUI 通知」与用户级 `[tui] notifications` 联动,面板打开时刷新,写入后回读验证;已有 CLI 会话需重启后生效。该项不服从 CodexBar 通知发送判定,也不修改顶层 `notify`。「主面板任务中心」沿用相同依赖语义;关闭只隐藏活动卡片和任务中心入口,不停止 Monitor、状态点、通知或触觉反馈。授权被拒的引导文案与"打开系统设置"按钮仍内联显示在主开关行下方, 插入提示时不触发设置项纵向动画。五类通知的触发与去重:diff --git a/Docs/UserGuide.md b/Docs/UserGuide.mdindex e3545af..3465b5b 100644--- a/Docs/UserGuide.md+++ b/Docs/UserGuide.md@@ -214,7 +214,7 @@ Hook 统计只从开启后开始记录,不能补出开启前的工作流历史### 配置通知子选项-开启「系统通知」后,点击该行右侧的滑杆图标,可以分别设置额度预警、额度重置、任务完成、任务等待、任务触觉和重置次数临期提醒。具体说明见[通知与触觉反馈](#8-通知与触觉反馈)。+开启「系统通知」后,点击该行右侧的滑杆图标,可以分别设置额度预警、额度重置、任务完成、任务等待、任务触觉、重置次数临期提醒和 Codex TUI 通知。具体说明见[通知与触觉反馈](#8-通知与触觉反馈)。## 6. Codex Hook 与实时任务@@ -254,6 +254,8 @@ CodexBar 只增删属于当前 CodexBar 可执行文件的 Hook,不会删除Hook 命令包含 CodexBar 当前可执行文件的完整路径。如果准备把 `CodexBar.app` 移到其他目录,建议先在旧位置关闭 Hook,移动后再重新开启。已经移动且旧 Hook 无法执行时,需要检查 `~/.codex/hooks.json` 中是否仍有指向旧路径的 CodexBar 命令。+不要同时保留指向不同 CodexBar 安装位置的 Hook。Codex 会分别调用每条生效命令,同一个事件可能被追加多次,导致统计重复;其他位置的 CodexBar 还可能改写共享的维护状态,使当天的 generation 再次变化。移动或替换 App 后应先移除原路径 Hook,再只启用最终安装位置的版本。+### Codex 被关闭后为什么任务仍显示运行中如果 Codex 正常写入 `Stop`、`task_complete` 或 `turn_aborted`,CodexBar 可以识别完成或终止。@@ -282,6 +284,10 @@ Hook 命令包含 CodexBar 当前可执行文件的完整路径。如果准备同步使用当前 iCloud 账号的 CloudKit private database,只上传按设备、按天生成的脱敏聚合数据,用于合并热力图中的工作流统计。+同一台 Mac 同一天、同一 generation 的本地聚合和 iCloud 副本不会重复相加,通常显示事件数更完整的一份。如果当天事件文件被完整删除或清空,CodexBar 能确认后续事件属于新的独立 generation,因此新统计会与已有云端贡献相加;如果文件被替换成一份非空且来源不明确的数据,CodexBar 会继续使用已有云端记录,不自动覆盖或叠加,避免重复统计。++直接删除某个历史日期的本机 events 文件不会同步删除 daily 聚合或云端记录,因此页面通常仍会显示原来的统计。如果连对应 daily 行也删除,开启同步时页面会回退使用已缓存的云端贡献;关闭同步或云端没有副本时,该日期才会消失。+不会上传:- Codex 账号和额度。@@ -315,17 +321,20 @@ Hook 命令包含 CodexBar 当前可执行文件的完整路径。如果准备### 可用通知-| 选项 | 触发条件 | 配置或频率 |-| ---------------- | ---------------------------------- | -------------------------------- |-| 额度预警通知 | 可信额度从阈值上方跌到阈值或以下 | 5%、10%、25%,默认 10% |-| 额度重置通知 | 已发生消耗的额度窗口恢复到 100% | 提供重置时间时,同周期提醒一次 |-| 任务完成通知 | Hook 任务确认完成且耗时达到阈值 | 30 秒、1、2、5 分钟,默认 1 分钟 |+| 选项 | 触发条件 | 配置或频率 |+| ---------------- | -------------------------------------------------- | -------------------------------- |+| 额度预警通知 | 可信额度从阈值上方跌到阈值或以下 | 5%、10%、25%,默认 10% |+| 额度重置通知 | 已发生消耗的额度窗口恢复到 100% | 提供重置时间时,同周期提醒一次 |+| 任务完成通知 | Hook 任务确认完成且耗时达到阈值 | 30 秒、1、2、5 分钟,默认 1 分钟 || 任务等待通知 | 用户审批模式下,任务在一批事件处理结束后仍等待批准 | 无 |-| 任务触觉反馈 | 任务进入等待批准或确认结束 | 需要 Hook;服从通知总开关 |-| 重置次数临期通知 | 手动重置机会将在 7 天内过期 | 最多每 24 小时提醒一次 |+| 任务触觉反馈 | 任务进入等待批准或确认结束 | 需要 Hook;服从通知总开关 |+| 重置次数临期通知 | 手动重置机会将在 7 天内过期 | 最多每 24 小时提醒一次 |+| Codex TUI 通知 | Codex CLI TUI 发送终端通知 | 与 `[tui] notifications` 联动 |任务完成、任务等待和任务触觉选项需要 Hook。Hook 关闭时,这些选项会显示为关闭并置灰,但不会丢失用户原来的偏好。+「Codex TUI 通知」读取用户级 `~/.codex/config.toml`:`[tui] notifications = false` 时显示为关闭。切换开关会通过本机 Codex app-server 写入 `tui.notifications = false/true`,不会修改顶层 `notify` 外部回调。已经运行的 Codex CLI 需要重新启动会话后采用新设置;读取或写入失败时,选项旁显示警告图标,悬停可查看原因。+当前 App 进程发出的等待批准通知会跟随 Monitor 中的任务状态;任务恢复运行、完成、终止或以其他方式离开等待状态后,通知会自动从通知中心移除,不影响其他仍在等待的并发任务。触觉反馈是否真的发生、震感强弱和形式由 Mac、触控板、辅助功能及系统偏好决定。CodexBar 请求了触觉,不代表所有设备都能产生明显反馈。@@ -512,6 +521,10 @@ Hook 保存的是 App 可执行文件的完整路径。将 App 移回原位置通常不需要。网络、账号或 CloudKit 服务暂时失败时,后续刷新会重试未完成日期。长期失败时检查 iCloud 登录状态和系统网络。+#### 在 CloudKit Dashboard 删除记录后为什么没有自动传回来?++云端删除会从本机同步缓存移除,但不会清除已经确认上传的本机日期 hash。如果该日的本机聚合没有变化,下一轮不会立即重复上传;只有本机内容变化,或同步状态中的对应 hash 被清除后,才会再次进入上传候选。+### F. 通知与触觉反馈#### 为什么开启通知后仍收不到提醒?diff --git a/README.md b/README.mdindex 395a35c..32197c5 100644--- a/README.md+++ b/README.md@@ -89,6 +89,8 @@ CodexBar 会把该设备的使用详情数据同步到当前 iCloud 账号的 Cl五类通知可以单独开关;全部为本地通知,不新增网络请求。+通知子面板还可以控制「Codex TUI 通知」。该开关与用户级 `~/.codex/config.toml` 中的 `[tui] notifications` 联动:关闭时写入 `false`,开启时写入 `true`,不会修改顶层 `notify` 外部回调;已经运行的 Codex CLI 需要重新启动会话后采用新设置。+通知子面板中的「任务触觉反馈」默认开启;当任务进入等待批准或确认结束时,CodexBar 会每 100 ms 请求一次层级变化触觉反馈,连续 10 次。该功能服从 App 内「系统通知」总开关,但不依赖系统通知授权或长任务时长阈值;是否实际反馈及震感强弱由当前输入设备、辅助功能和系统偏好决定。Hook 事件可能在一次轮询中成批到达。CodexBar 会先处理完整批次,再按任务合并等待状态:只有 reviewer 为 `user`、批次结束后仍在等待批准的任务才通知一次;自动审批以及已经恢复运行、完成或移除的短暂候选不会产生过期提醒。@@ -129,6 +131,8 @@ brew install --cask bob-zebedy/tap/codexbarCodexBar 默认通过本机 Codex app-server 读取账号、额度和 Token 用量。若 app-server 返回可用手动重置机会,CodexBar 会使用本机 Codex OAuth token 向 `https://chatgpt.com/backend-api/wham/rate-limit-reset-credits` 发起只读请求,用于读取这些重置机会的过期时间;请求失败时不展示具体过期时间,重置次数侧边详情面板显示「未知过期时间」,也不会保留原始响应。+用户在通知子面板切换「Codex TUI 通知」时,CodexBar 通过本机 app-server 只更新用户级 `config.toml` 的 `tui.notifications`,不修改顶层 `notify` 或其他 Codex 配置。+Codex Hook 工作流数据默认只保存在本机:```text@@ -137,7 +141,7 @@ Codex Hook 工作流数据默认只保存在本机:菜单栏实时任务状态只存在于当前 App 进程内。活动卡片和并发任务中心只展示工作目录最后一级项目名、模型、推理强度、工具、阶段与耗时;可可靠统计且存在活跃子 Agent 时,活动卡片还会显示其数量。不展示完整路径、会话 ID、轮次 ID 或 agent ID。这份状态不会上传到 CloudKit,也不会产生新的网络请求。为补齐 Hook 缺失的起点、结束、中断、审批路由或推理强度,CodexBar 只对当前活跃 turn 读取 `~/.codex/sessions/` 或 `~/.codex/archived_sessions/` 下对应 rollout JSONL:正常情况下只增量解析生命周期事件、turn ID、起止耗时、`turn_context.approvals_reviewer` 和 `turn_context.effort`,effort 缺失时最多额外读取文件尾部 8 MB;不会提取、保存或展示其中的提示词、回复、推理内容、工具内容或 token 数据。-只有在用户开启「跨设备同步」后,CodexBar 才会通过 `CloudKit private database` 同步每日使用详情数据; 同步的数据副本只包含各个事件数量、项目聚合和模型名使用次数,不包含事件具体的数据。+只有在用户开启「跨设备同步」后,CodexBar 才会通过 `CloudKit private database` 同步每日使用详情数据;同步的数据副本只包含各个事件数量、项目聚合、模型名使用次数,以及用于区分同一日期独立数据段的随机 generation,不包含原始事件、会话 ID 或轮次 ID。正常追加时,同一 generation 的本机数据和云端副本只取一份;确认事件文件从空文件重新开始时,新 generation 会与旧云端贡献相加;无法确认来源的非空替换不会自动覆盖或叠加旧云端数据。除上述重置机会过期时间查询、Sparkle appcast / DMG 下载,以及用户开启跨设备同步后的 CloudKit 请求外,CodexBar 自身不发起其他网络请求。diff --git a/appcast.xml b/appcast.xmlindex 704266d..7e0aba0 100644--- a/appcast.xml+++ b/appcast.xml@@ -7,6 +7,15 @@<link>https://codexbar.zabrian.app/appcast.xml</link><description>CodexBar appcast feed</description><language>zh-CN</language>+ <item>+ <title>CodexBar.app 3.3.10</title>+ <sparkle:version>48</sparkle:version>+ <sparkle:shortVersionString>3.3.10</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.3.10</sparkle:releaseNotesLink>+ <pubDate>Mon, 20 Jul 2026 16:20:40 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.3.10.dmg" sparkle:edSignature="Dv5jMFE4wzTDrSVGQM9uabHkQk1n0VxY/tcPIti902ml684AvlDPKG5LgLRuMv82Ca1blYdGWTlQQrJ5j6htBw==" length="4097809" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 3.3.9</title><sparkle:version>47</sparkle:version>