CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
feat: 建立系统日志规范并补齐全链路日志
Bob9f22e06978d9
diff --git a/.swiftlint.yml b/.swiftlint.ymlindex de2cea2..af0398a 100644--- a/.swiftlint.yml+++ b/.swiftlint.yml@@ -9,14 +9,17 @@ line_length:ignores_function_declarations: trueignores_interpolated_strings: true+# 这两项放宽只为容纳 StatusItemController: 它是文件级 private 类, 拆到别的文件写 extension+# 就得把类和存储属性从 private 放宽到 internal, 为消一条 warning 暴露实现细节不划算+# 余量只留了 4% 左右, 继续变长仍会报; 新文件不要向这个上限看齐file_length:- warning: 1200+ warning: 1300error: 1500ignore_comment_only_lines: truetype_body_length:- warning: 800- error: 1200+ warning: 1200+ error: 1400function_body_length:warning: 80diff --git a/CLAUDE.md b/CLAUDE.mdindex d225d3b..846f637 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -160,9 +160,18 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- 菜单面板的 `CodexFetchOutcome` 只暴露有数据, 未登录, 初始化失败三种结果, 而启动失败, 超时, 断连, 解析失败等细节全部只进日志窗口, 由 `RequestLogStorage` 保存, 上限 500 条- app-server 之外的模块走 `Services/Support/AppLog.swift` 写系统日志, 用户可见文案只留步骤名, 错误码与 `localizedDescription` 这类细节进 os_log; 现有 category 为 `app` `keepalive` `activity` `workflow` `sync` `hooks` `codexcli` `settings` `notification`, helper 进程另用 `helper`- 日志的目标是出问题时能从中重建当时的状态, 所以不只记失败, 状态转换, 关键操作与决策依据同样要记; 启动时由 `logLaunchState` 记一条含全部开关的基线, 后续变更日志都是相对它的增量-- 记日志要区分错误与运行时信息, 状态转换和降级决策用 `.notice`, 失败用 `.error`; 逐事件与逐快照这类高频路径一律不记, 例如两个 Reader 的 `try?` 文件 IO 失败是预期常态, 记了会刷屏-- 文案只描述事实, 不写"用户做了什么"这类主语, 也不写推论; 字段一律 `名=值` 并用 `; ` 分隔, App 与 helper 两侧保持同一套格式+- **级别只用 `.notice` 与 `.error`**, 状态转换和降级决策用 `.notice`, 失败用 `.error`; `.info` 与 `.debug` 只落在内存环形缓冲里, 事后 `log show` 捞不全, 一律不用+- 详细度靠**结果字段化**而不是多记几条: 一次操作只留开始与收尾两条, 每一步的成功结果压成收尾那条里的一个字段, 只有失败才单独发一条 `.error` 带 `stage=` 与 `detail=`; 逐事件与逐快照这类高频路径仍然一律不记, 例如两个 Reader 的 `try?` 文件 IO 失败是预期常态, 记了会刷屏+- 文案骨架是 `<主体><动作>: 字段=值; 字段=值`, 标题只说发生了什么, 理由进 `reason=`, 处置进 `action=`; 起止用 `开始` `完成` `失败`, 中间状态用 `已<动作>`+- 字段顺序固定为 标识 (`trigger` `generation` `date`) 输入 结果 `elapsed` `reason`/`detail`; 公共字段有 `trigger` `result` `reason` `action` `detail` `code` (系统返回码) `exit` (进程退出码) `elapsed`, 其中 `code` 与 `exit` 必须分开, 不要用一个 `error=` 同时装 OSStatus IOReturn 和退出码+- 文案只描述事实, 不写"用户做了什么"这类主语, 也不写推论; 字段值要可 grep, 用枚举 rawValue 而不是中文句子, App 与 helper 两侧保持同一套格式+- 词根固定, 一个词能 grep 出整条链路: 额度, 统计刷新 (调度层), 事件汇总 (计算层), 同步, KeepAlive (防休眠决策层), 空闲断言 (进程内 `IOPMAssertion`), Helper 注册 (`SMAppService`), Helper XPC (`NSXPCConnection`), 系统休眠 (helper 的 pmset 效果), 任务, Hook, codex, 通知+- 防休眠日志按两套机制分组: `KeepAlive` 是两套共用的决策层, `空闲断言` 是机制一, `Helper 注册` `Helper XPC` `系统休眠` 是机制二的授权 传输 效果三层, 故障定位就是在这几层里找+- `trigger=` 由 `LogTrigger` 提供, 从 UI 入口透传到服务层, 用来区分同一条链路是被用户动作 定时轮询还是系统事件踢起来的; 统计维护挂在额度刷新完成事件上, 它的 trigger 继承那一次刷新+- 变化检测类日志只在值真的变了才记, 例如 `KeepAlive 条件已变化` 与 `Hook 配置已变化` 各自存一份上次的值, 否则每次开面板都会刷一条+- 设置项的变更日志照抄设置页那一行的标题, 例如 `菜单栏额度指示变更` `开机自动启动变更`, 用户说"我改了那个开关"时能直接对上; 只有本身带完整链路的才用链路词根, 例如 Hook 同步 通知 KeepAlive 快捷键- 成对的操作要留成对的日志, 例如 XPC 的发送与回复各记一条并带同一个 `generation`, 缺一条就说明请求丢在途中+- 耗时用 `LogDuration` 取, 只加在收尾那一条上- `Logger` 的插值是 autoclosure, 里面直接访问属性会被要求显式 `self`, 而 `.swiftformat` 配了 `--self remove`, 两边会打架; 把属性先取到局部常量再插值即可, 不需要 lint 豁免- 账号有效时 rate limits 和 usage 允许单独失败, 复用同账号旧缓存并标记 stale, UI 显示为半透明, 无缓存则该区域不显示; 账号变化时整体丢弃缓存避免串号- 各 Settings 类把读取类错误与操作类错误分开存储, 定时 refresh 不能抹掉用户操作或校验的结论, 参见 `CodexHookSettings` 与 `KeepAliveController`diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex c88f924..acf9e33 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -424,7 +424,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 59;+ CURRENT_PROJECT_VERSION = 60;DEAD_CODE_STRIPPING = YES;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;@@ -441,7 +441,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 3.5.5;+ MARKETING_VERSION = 3.5.6;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.debug;PRODUCT_NAME = "$(TARGET_NAME)";REGISTER_APP_GROUPS = YES;@@ -464,7 +464,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 59;+ CURRENT_PROJECT_VERSION = 60;DEAD_CODE_STRIPPING = YES;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;@@ -481,7 +481,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 3.5.5;+ MARKETING_VERSION = 3.5.6;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";diff --git a/CodexBar/Controllers/GlobalHotKeyController.swift b/CodexBar/Controllers/GlobalHotKeyController.swiftindex f50cbb1..19a925c 100644--- a/CodexBar/Controllers/GlobalHotKeyController.swift+++ b/CodexBar/Controllers/GlobalHotKeyController.swift@@ -29,7 +29,7 @@ final class GlobalHotKeyController {userData,&installedHandlerRef) == noErr else {- AppLog.settings.error("全局快捷键事件处理器安装失败")+ AppLog.settings.error("快捷键注册失败: stage=handler")return false}@@ -46,12 +46,12 @@ final class GlobalHotKeyController {guard status == noErr else {// 最常见的原因是快捷键已被其他 App 占用, 用户只会看到"按了没反应"- AppLog.settings.error("全局快捷键注册失败: error=\(status)")+ AppLog.settings.error("快捷键注册失败: stage=register; code=\(status)")GlobalHotKeyRegistration.remove(hotKeyRef: nil, eventHandlerRef: installedHandlerRef)return false}- AppLog.settings.notice("全局快捷键已注册")+ AppLog.settings.notice("快捷键已注册")clearCurrentRegistration()registration = GlobalHotKeyRegistration(diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex a76bcb9..e5f813c 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -29,6 +29,8 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {private var notificationService: CodexNotificationService?func applicationDidFinishLaunching(_: Notification) {+ // Hook 子进程模式绝不会走到这里, 干净退出标志因此不会被它改写+ AppProcessDiagnostics.install()let controller = StatusItemController(viewModel: viewModel,workflowViewModel: workflowViewModel,@@ -61,7 +63,8 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {}func applicationWillTerminate(_: Notification) {- AppLog.app.notice("APP 即将退出")+ AppLog.app.notice("App 即将退出: reason=userQuit")+ AppProcessDiagnostics.recordCleanExit()statusItemController?.uninstall()keepAliveController.stop()activityMonitor.stop()@@ -82,7 +85,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {let taskCenter = mainPanelSettings.showsTaskCenter ? 1 : 0let hotKey = globalHotKeySettings.shortcut == nil ? 0 : 1AppLog.app.notice(- "APP 已启动: version=\(version, privacy: .public); build=\(build, privacy: .public); hook=\(hook); keepAlive=\(keepAlive); keepAliveLimit=\(keepAliveLimit, privacy: .public); sync=\(sync); notification=\(notification); menuBarQuota=\(menuBarQuota, privacy: .public); taskCenter=\(taskCenter); hotKey=\(hotKey)"+ "App 已启动: version=\(version, privacy: .public); build=\(build, privacy: .public); hook=\(hook); keepAlive=\(keepAlive); keepAliveLimit=\(keepAliveLimit, privacy: .public); sync=\(sync); notification=\(notification); menuBarQuota=\(menuBarQuota, privacy: .public); taskCenter=\(taskCenter); hotKey=\(hotKey)")}@@ -138,8 +141,9 @@ private final class StatusItemController: NSObject, NSMenuDelegate {keepAliveController: keepAliveController) { [weak self] inself?.statusItem.button?.window?.screen- } onSyncChanged: { [weak self] enabled in- self?.handleSyncChanged(enabled)+ } onSyncChanged: { [weak self] _ in+ // setEnabled 在回调之前已经写回属性, 现场求值就是新结论+ self?.workflowSyncScheduler.requestSync(trigger: .settings)} onRebuildWorkflowData: { [weak self] dateKeys, completion inguard let self else {completion(.failure(CancellationError()))@@ -154,8 +158,8 @@ private final class StatusItemController: NSObject, NSMenuDelegate {private lazy var workflowSyncScheduler = WorkflowSyncScheduler(viewModel: workflowViewModel,- canSynchronize: { [weak self] in- self?.canSynchronizeWorkflow == true+ syncActivation: { [weak self] in+ self?.workflowSyncActivation ?? .syncOff})@@ -690,7 +694,11 @@ private final class StatusItemController: NSObject, NSMenuDelegate {}if isEnabled {- workflowSyncScheduler.requestSync()+ // 回调跑在 willSet, codexHookSettings.isEnabled 此刻还是旧值, 只能用参数+ workflowSyncScheduler.requestSync(+ trigger: .hookEnabled,+ activation: syncSettings.activation(isHookEnabled: true)+ )} else {workflowSyncScheduler.clearPendingMaintenance()activityCenterPanelController.hide(immediate: true)@@ -701,7 +709,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {syncSettings.$syncAvailability.removeDuplicates().sink { [weak self] availability in- self?.handleSyncChanged(availability.isAvailable)+ self?.handleSyncChanged(isSyncAvailable: availability.isAvailable)}.store(in: &cancellables)}@@ -1245,7 +1253,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {return}- viewModel.refreshIfNeeded()+ viewModel.refreshIfNeeded(trigger: .panelOpen)}}@@ -1258,22 +1266,31 @@ private final class StatusItemController: NSObject, NSMenuDelegate {}if performMaintenance {- workflowSyncScheduler.requestMaintenance(allowsSync: true)+ // 统计维护挂在额度刷新完成事件上, 触发来源继承那一次刷新+ workflowSyncScheduler.requestMaintenance(+ allowsSync: true,+ trigger: viewModel.lastRefreshTrigger+ )} else {workflowViewModel.refreshIfNeeded()}}- private func handleSyncChanged(_ isEnabled: Bool) {- if isEnabled {- workflowSyncScheduler.requestSync()- } else {- workflowSyncScheduler.clearPendingSync()- }+ /// isSyncAvailable 由调用方传入+ /// 从 $syncAvailability 的订阅进来时 syncSettings.isSyncAvailable 还是旧值, 只有回调参数是新的+ /// 不在这里判断该不该跳过: requestSync 的 guard 已经统一处理并记下 reason=+ private func handleSyncChanged(isSyncAvailable: Bool) {+ workflowSyncScheduler.requestSync(+ trigger: .settings,+ activation: syncSettings.activation(+ isHookEnabled: codexHookSettings.isEnabled,+ isSyncAvailable: isSyncAvailable+ )+ )}- private var canSynchronizeWorkflow: Bool {- syncSettings.isEffectivelyActive(isHookEnabled: codexHookSettings.isEnabled)+ private var workflowSyncActivation: WorkflowSyncActivation {+ syncSettings.activation(isHookEnabled: codexHookSettings.isEnabled)}private func updateHeatmapDetailPanel(_ context: UsageHeatmapHoverContext?) {diff --git a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swiftindex 8d7bad8..c57c417 100644--- a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift+++ b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift@@ -183,7 +183,7 @@ actor CodexCLIVersionService {process.terminationHandler = nilstopCollectors(outputCollector: outputCollector, errorCollector: errorCollector)AppLog.codexCLI.error(- "版本检测启动失败: source=\(source.rawValue, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"+ "版本检测失败: source=\(source.rawValue, privacy: .public); stage=launch; detail=\(error.localizedDescription, privacy: .public)")return CodexCLIVersionItem(source: source, path: path, errorMessage: "启动失败")}@@ -197,7 +197,7 @@ actor CodexCLIVersionService {outputCollector: outputCollector,errorCollector: errorCollector)- AppLog.codexCLI.error("版本检测超时: source=\(source.rawValue, privacy: .public)")+ AppLog.codexCLI.error("版本检测失败: source=\(source.rawValue, privacy: .public); stage=timeout")return CodexCLIVersionItem(source: source, path: path, errorMessage: "读取超时")}@@ -206,13 +206,13 @@ actor CodexCLIVersionService {guard process.terminationStatus == 0 else {AppLog.codexCLI.error(- "版本检测退出码非零: source=\(source.rawValue, privacy: .public); error=\(process.terminationStatus)"+ "版本检测失败: source=\(source.rawValue, privacy: .public); stage=exit; exit=\(process.terminationStatus)")return CodexCLIVersionItem(source: source, path: path, errorMessage: "读取失败")}guard let version = firstLine(in: output) ?? firstLine(in: errorOutput) else {- AppLog.codexCLI.error("版本检测无法解析输出: source=\(source.rawValue, privacy: .public)")+ AppLog.codexCLI.error("版本检测失败: source=\(source.rawValue, privacy: .public); stage=parse")return CodexCLIVersionItem(source: source, path: path, errorMessage: "版本未知")}diff --git a/CodexBar/Services/CodexStatus/CodexResetCreditsService.swift b/CodexBar/Services/CodexStatus/CodexResetCreditsService.swiftindex 4bb86d2..454d32e 100644--- a/CodexBar/Services/CodexStatus/CodexResetCreditsService.swift+++ b/CodexBar/Services/CodexStatus/CodexResetCreditsService.swift@@ -75,53 +75,53 @@ nonisolated enum CodexResetCreditsService {}}-private nonisolated extension CodexResetCreditsService {- struct RateLimitResetCreditsResponse: Decodable {- let credits: [RateLimitResetCredit]- }+/// DTO 与凭据放在文件级而不是 extension 内+/// 套进类型里会让 CodingKeys 落到第二层嵌套+private nonisolated struct RateLimitResetCreditsResponse: Decodable {+ let credits: [RateLimitResetCredit]+}- struct RateLimitResetCredit: Decodable {- let status: String- let expiresAt: Date?+private nonisolated struct RateLimitResetCredit: Decodable {+ let status: String+ let expiresAt: Date?- private enum CodingKeys: String, CodingKey {- case status- case expiresAt = "expires_at"- }+ private enum CodingKeys: String, CodingKey {+ case status+ case expiresAt = "expires_at"}+}- struct CodexOAuthCredentials {- let accessToken: String- let accountId: String?-- static func load(environment: [String: String]) throws -> Self {- let authURL = authFileURL(environment: environment)- let data = try Data(contentsOf: authURL)- let authFile = try JSONDecoder().decode(CodexAuthFile.self, from: data)- guard let accessToken = authFile.tokens?.accessToken, !accessToken.isEmpty else {- throw FetchError.invalidResponse- }+private nonisolated struct CodexOAuthCredentials {+ let accessToken: String+ let accountId: String?- return Self(accessToken: accessToken, accountId: authFile.tokens?.accountId)+ static func load(environment: [String: String]) throws -> Self {+ let authURL = authFileURL(environment: environment)+ let data = try Data(contentsOf: authURL)+ let authFile = try JSONDecoder().decode(CodexAuthFile.self, from: data)+ guard let accessToken = authFile.tokens?.accessToken, !accessToken.isEmpty else {+ throw CodexResetCreditsService.FetchError.invalidResponse}- private static func authFileURL(environment: [String: String]) -> URL {- CodexCLIResolver.codexHomeDirectory(environment: environment)- .appendingPathComponent("auth.json")- }+ return Self(accessToken: accessToken, accountId: authFile.tokens?.accountId)}- struct CodexAuthFile: Decodable {- let tokens: Tokens?+ private static func authFileURL(environment: [String: String]) -> URL {+ CodexCLIResolver.codexHomeDirectory(environment: environment)+ .appendingPathComponent("auth.json")+ }+}++private nonisolated struct CodexAuthFile: Decodable {+ let tokens: CodexAuthTokens?+}- struct Tokens: Decodable {- let accessToken: String?- let accountId: String?+private nonisolated struct CodexAuthTokens: Decodable {+ let accessToken: String?+ let accountId: String?- private enum CodingKeys: String, CodingKey {- case accessToken = "access_token"- case accountId = "account_id"- }- }+ private enum CodingKeys: String, CodingKey {+ case accessToken = "access_token"+ case accountId = "account_id"}}diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swiftindex 55b106f..5889ada 100644--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift@@ -8,6 +8,43 @@ nonisolated enum CodexFetchOutcome {case initializationFailed}+/// 一次刷新里各步的结果分类, 只用于日志+/// 成功路径压进收尾那一条, 不为每步单独记一行+nonisolated struct CodexFetchTrace {+ enum ConnectionMode: String {+ case reused+ case new+ }++ enum StepResult: String {+ case ok+ case refreshed+ case cached+ case missing+ case skipped+ case failed+ }++ /// 失败时定位到哪一步, 成功时为 nil+ enum FailureStage: String {+ case connect+ case account+ case snapshot+ }++ var connection: ConnectionMode?+ var account: StepResult?+ var rateLimits: StepResult?+ var usage: StepResult?+ var resetCredits: StepResult?+ var failureStage: FailureStage?+}++nonisolated struct CodexFetchResult {+ let outcome: CodexFetchOutcome+ let trace: CodexFetchTrace+}+private nonisolated enum ConnectionResolution {case ready(connection: AppServerConnection, reused: Bool)case notLoggedIn@@ -34,7 +71,12 @@ private nonisolated enum FetchFailure: Error {private nonisolated struct CachedSupplementalRead<Value> {let value: Value?- let isStale: Bool+ let step: CodexFetchTrace.StepResult++ /// 只驱动 UI 的半透明展示; 新增 step 分支时要确认它算不算"给出的是旧数据"+ var isStale: Bool {+ step == .cached+ }}/// 只缓存同一账号下的补充数据, 账号变化时整体丢弃避免串号@@ -43,9 +85,13 @@ private nonisolated struct SupplementalDataCache {var rateLimits: AccountRateLimitsResponse?var usage: AccountUsageResponse?- mutating func useAccount(_ account: CodexAccount) {- guard self.account != account else { return }+ /// 返回是否因为换账号而丢弃了缓存, 调用方据此记日志, 不必再比一遍账号+ @discardableResult+ mutating func useAccount(_ account: CodexAccount) -> Bool {+ guard self.account != account else { return false }+ let hadCachedAccount = self.account != nilself = Self(account: account)+ return hadCachedAccount}}@@ -87,6 +133,7 @@ actor CodexStatusService {private var connection: AppServerConnection?private var supplementalDataCache = SupplementalDataCache()+ private var lastResolvedSource: CodexCLIExecutableSource?/// app-server 退出后继续写管道会触发 SIGPIPE/// 忽略信号, 让 write 抛错后走重建@@ -98,8 +145,10 @@ actor CodexStatusService {_ = Self.ignoreBrokenPipeSignal}- func fetchOutcome() async -> CodexFetchOutcome {- await resolveOutcome(allowRebuild: true)+ func fetchOutcome() async -> CodexFetchResult {+ var trace = CodexFetchTrace()+ let outcome = await resolveOutcome(allowRebuild: true, trace: &trace)+ return CodexFetchResult(outcome: outcome, trace: trace)}func currentConnectionInfo() async -> CodexCLIConnectionInfo? {@@ -143,15 +192,25 @@ actor CodexStatusService {/// 复用连接出现传输故障时只重建重试一次/// 避免故障状态下反复拉起进程- private func resolveOutcome(allowRebuild: Bool) async -> CodexFetchOutcome {+ private func resolveOutcome(+ allowRebuild: Bool,+ trace: inout CodexFetchTrace+ ) async -> CodexFetchOutcome {switch ensureConnection() {case .notLoggedIn:+ trace.failureStage = .connectreturn .notLoggedIncase .initializationFailed:+ trace.failureStage = .connectreturn .initializationFailedcase let .ready(connection, reused):+ trace.connection = reused ? .reused : .newdo {- let snapshot = try await fetchData(using: connection, refreshAccountInfo: reused)+ let snapshot = try await fetchData(+ using: connection,+ refreshAccountInfo: reused,+ trace: &trace+ )return .data(snapshot)} catch FetchFailure.notLoggedIn {supplementalDataCache = SupplementalDataCache()@@ -160,7 +219,8 @@ actor CodexStatusService {} catch FetchFailure.needsRebuild {teardownConnection()if reused, allowRebuild {- return await resolveOutcome(allowRebuild: false)+ AppLog.app.notice("codex 连接已失效: reason=transportError")+ return await resolveOutcome(allowRebuild: false, trace: &trace)}return .initializationFailed} catch {@@ -187,24 +247,47 @@ actor CodexStatusService {return .ready(connection: connection, reused: true)}+ // 只记失效这个事实: 下面还可能解析不到 codex 或者开不起来+ // 收尾由额度刷新那条的 conn=new 承载, 不必在这里再记一条+ if let connection {+ let reason = connection.session.process.isRunning ? "expired" : "processExited"+ AppLog.app.notice("codex 连接已失效: reason=\(reason, privacy: .public)")+ }teardownConnection()let command: AppServerCommanddo {command = try CodexCLIResolver.resolveAppServerCommand(environment: Self.environment)} catch {+ AppLog.app.error(+ "codex 连接失败: stage=resolveCLI; detail=\(error.localizedDescription, privacy: .public)"+ )RequestLogStorage.shared.recordFailure(message: error.localizedDescription)return .initializationFailed}+ // 可执行文件路径含用户名, 只记来源分类+ // 每次新建连接都重新解析, 换了来源才值得记一条+ if lastResolvedSource != command.source {+ lastResolvedSource = command.source+ AppLog.codexCLI.notice(+ "codex 路径已解析: source=\(command.source.rawValue, privacy: .public)"+ )+ }+let resolution = Self.openConnection(command: command,environment: Self.environment,clientVersion: Self.clientVersion(),timeout: Self.requestTimeout)- if case let .ready(newConnection, _) = resolution {+ switch resolution {+ case let .ready(newConnection, _):connection = newConnection+ case .initializationFailed:+ AppLog.app.error("codex 连接失败: stage=open")+ case .notLoggedIn:+ break}return resolution}@@ -217,7 +300,11 @@ actor CodexStatusService {/// 额度与用量独立读取/// 认证失败全程只刷新一次 token/// 传输故障交给外层重建连接- private func fetchData(using connection: AppServerConnection, refreshAccountInfo: Bool) async throws -> CodexQuotaSnapshot {+ private func fetchData(+ using connection: AppServerConnection,+ refreshAccountInfo: Bool,+ trace: inout CodexFetchTrace+ ) async throws -> CodexQuotaSnapshot {var didRefresh = falsefunc refreshTokenIfNeeded() throws {@@ -251,6 +338,8 @@ actor CodexStatusService {// 新建连接已读过 account; 复用连接才刷新账户状态+ // 失败定位随流程推进, 不靠事后从别的字段反推+ trace.failureStage = .accountif refreshAccountInfo {let accountResult: ReadResult<AccountReadResponse> = try readResultWithAuthRefresh {Self.read("account/read", params: ["refreshToken": false], using: connection, as: AccountReadResponse.self)@@ -259,30 +348,44 @@ actor CodexStatusService {guard response.account != nil else { throw FetchFailure.notLoggedIn }connection.accountResponse = response}+ trace.account = Self.accountStepResult(response: accountResult.value, didRefresh: didRefresh)+ } else {+ trace.account = .skipped}guard let account = connection.accountResponse.account else {throw FetchFailure.notLoggedIn}+ trace.failureStage = .snapshot- supplementalDataCache.useAccount(account)+ if supplementalDataCache.useAccount(account) {+ AppLog.app.notice("额度缓存已丢弃: reason=accountChanged")+ }let rateLimitsRead = try readSupplemental("account/rateLimits/read",as: AccountRateLimitsResponse.self,cache: &supplementalDataCache.rateLimits)+ trace.rateLimits = rateLimitsRead.steplet usageRead = try readSupplemental("account/usage/read",as: AccountUsageResponse.self,cache: &supplementalDataCache.usage)+ trace.usage = usageRead.step+ let availableResetCredits = rateLimitsRead.value?.rateLimitResetCredits?.availableCountlet resetCreditExpirationDates = await fetchResetCreditExpirationDates(- availableCount: rateLimitsRead.value?.rateLimitResetCredits?.availableCount,+ availableCount: availableResetCredits,refreshTokenIfNeeded: refreshTokenIfNeeded)+ if let availableResetCredits, availableResetCredits > 0 {+ trace.resetCredits = resetCreditExpirationDates == nil ? .failed : .ok+ } else {+ trace.resetCredits = .skipped+ }// rateLimits/usage 都可为空, 只要账户有效就让 UI 展示"暂无数据"@@ -297,6 +400,7 @@ actor CodexStatusService {throw FetchFailure.notLoggedIn}+ trace.failureStage = nilreturn snapshot}@@ -333,9 +437,22 @@ actor CodexStatusService {}}+ /// 读不到账号时后面会沿用连接上缓存的那份+ /// 这种一轮记成 ok 的话, UI 展示的账号其实来自缓存这件事就无从发现+ private static func accountStepResult(+ response: AccountReadResponse?,+ didRefresh: Bool+ ) -> CodexFetchTrace.StepResult {+ guard response != nil else {+ return .cached+ }+ return didRefresh ? .refreshed : .ok+ }+/// 新值更新缓存- /// 本轮请求失败则回退到缓存并标记陈旧- /// 方法不支持/认证/断连一律视为无数据+ /// 本轮请求失败则回退到缓存并标记陈旧, 没有缓存才算这一步失败+ /// step 在这里判定而不是事后从 value 与 isStale 反推: 只有这里还看得到原始的 ReadResult+ /// 反推会把"请求失败"和"codex 不支持这个方法"压成同一个值, 而两者的处置完全不同private func cachedRead<Value>(_ result: ReadResult<Value>,cache: inout Value?@@ -343,11 +460,17 @@ actor CodexStatusService {switch result {case let .value(value):cache = value- return CachedSupplementalRead(value: value, isStale: false)+ return CachedSupplementalRead(value: value, step: .ok)case .skipped(.requestFailed):- return CachedSupplementalRead(value: cache, isStale: cache != nil)- default:- return CachedSupplementalRead(value: nil, isStale: false)+ guard let cachedValue = cache else {+ return CachedSupplementalRead(value: nil, step: .failed)+ }+ return CachedSupplementalRead(value: cachedValue, step: .cached)+ case .skipped(.methodUnsupported):+ return CachedSupplementalRead(value: nil, step: .skipped)+ case .authRequired, .broken:+ // resultAfterAuthAttempt 已经把这两种上抛, 到不了这里, 写出来只为穷尽+ return CachedSupplementalRead(value: nil, step: .missing)}}diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swiftindex 882739a..51a802c 100644--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift@@ -26,6 +26,9 @@ final class CodexStatusViewModel: ObservableObject {@Published private(set) var codexConnectionInfo: CodexCLIConnectionInfo?@Published private(set) var autoRefreshCountdownStartedAt: Date?+ /// 统计维护挂在额度刷新完成事件上, 由它继承本次刷新的触发来源+ private(set) var lastRefreshTrigger: LogTrigger = .launch+var autoRefreshInterval: TimeInterval {Self.refreshInterval}@@ -45,12 +48,12 @@ final class CodexStatusViewModel: ObservableObject {refreshCoordinator.cancel()}- func refreshIfNeeded() {+ func refreshIfNeeded(trigger: LogTrigger) {guard Date().timeIntervalSince(autoRefreshCountdownStartedAt ?? .distantPast) > Self.refreshInterval else {return}- refresh()+ refresh(trigger: trigger)}func startAutoRefresh() {@@ -59,7 +62,7 @@ final class CodexStatusViewModel: ObservableObject {}autoRefreshTask = Task { [weak self] in- self?.refreshIfNeeded()+ self?.refreshIfNeeded(trigger: .launch)// 每轮按剩余时间休眠, 手动刷新后倒计时会自然重新对齐while !Task.isCancelled {@@ -68,27 +71,31 @@ final class CodexStatusViewModel: ObservableObject {break}- self?.refreshIfNeeded()+ self?.refreshIfNeeded(trigger: .auto)}}}- func refresh() {+ func refresh(trigger: LogTrigger) {guard !isRefreshing else {return}+ lastRefreshTrigger = trigger+ AppLog.app.notice("额度刷新开始: trigger=\(trigger.rawValue, privacy: .public)")+ let duration = LogDuration()+refreshCoordinator.run(setRefreshing: { [weak self] in self?.isRefreshing = $0 },operation: { [service = self.service] in- await (outcome: service.fetchOutcome(), connectionInfo: service.currentConnectionInfo())+ await (fetch: service.fetchOutcome(), connectionInfo: service.currentConnectionInfo())},commit: { [weak self] result inguard let self else {return}- switch result.outcome {+ switch result.fetch.outcome {case let .data(snapshot):self.snapshot = snapshotloadState = .loaded@@ -100,16 +107,50 @@ final class CodexStatusViewModel: ObservableObject {loadState = .initializationFailed}- // 只记结果分类, 额度与用量是用户数据, 不进系统日志+ // 只记各步结果分类, 额度与用量是用户数据, 不进系统日志// RPC 层面的请求响应细节仍然只进日志窗口- let state = loadState- AppLog.app.notice("额度信息刷新完成: state=\(String(describing: state), privacy: .public)")+ logRefreshOutcome(+ trigger: trigger,+ trace: result.fetch.trace,+ elapsed: duration.elapsed+ )codexConnectionInfo = result.connectionInfoautoRefreshCountdownStartedAt = Date()})}+ /// 成功路径把各步结果压进一条, 失败才带上定位到哪一步+ private func logRefreshOutcome(+ trigger: LogTrigger,+ trace: CodexFetchTrace,+ elapsed: String+ ) {+ let triggerName = trigger.rawValue+ let state = String(describing: loadState)+ switch loadState {+ case .loaded:+ let connection = trace.connection?.rawValue ?? "-"+ let account = trace.account?.rawValue ?? "-"+ let rateLimits = trace.rateLimits?.rawValue ?? "-"+ let usage = trace.usage?.rawValue ?? "-"+ let resetCredits = trace.resetCredits?.rawValue ?? "-"+ AppLog.app.notice(+ "额度刷新完成: trigger=\(triggerName, privacy: .public); state=\(state, privacy: .public); conn=\(connection, privacy: .public); account=\(account, privacy: .public); rateLimits=\(rateLimits, privacy: .public); usage=\(usage, privacy: .public); reset=\(resetCredits, privacy: .public); elapsed=\(elapsed, privacy: .public)"+ )+ case .notLoggedIn:+ // 未登录是正常状态, 混进失败词根会让每分钟一条噪声盖掉真故障+ AppLog.app.notice(+ "额度刷新已跳过: trigger=\(triggerName, privacy: .public); reason=notLoggedIn; elapsed=\(elapsed, privacy: .public)"+ )+ case .initializationFailed, .loading:+ let stage = trace.failureStage?.rawValue ?? "-"+ AppLog.app.error(+ "额度刷新失败: trigger=\(triggerName, privacy: .public); stage=\(stage, privacy: .public); state=\(state, privacy: .public); elapsed=\(elapsed, privacy: .public)"+ )+ }+ }+func refreshCodexConnectionInfo() {Task {self.codexConnectionInfo = await service.currentConnectionInfo()diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swiftindex 1616990..819789f 100644--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift@@ -57,6 +57,33 @@ final class KeepAliveController: ObservableObject {private var isRefreshingHelper = falseprivate var cancellables = Set<AnyCancellable>()private var isStarted = false+ private var lastLoggedSleepConditions: SleepConditions?+ /// codexHookSettings.isEnabled 的最新值, 由订阅维护+ /// 不直接读那个属性: 订阅回调跑在 willSet, 那时它还是改动前的值+ private var isHookEnabled: Bool++ /// 阻止休眠没生效时缺的是哪一项, 同时充当日志里的 reason= 取值+ private enum SleepBlockReason: String {+ case notStarted+ case userOff+ case hookDisabled+ case noTasks+ case helperUnavailable+ case helperRefreshing+ case limitReached+ }++ /// shouldDisableSleep 的求值结果与它依赖的各项, 只用于变化检测与日志+ /// blockReason 与 shouldDisableSleep 同源, 不会出现"字段都满足却报某项缺失"+ private struct SleepConditions: Equatable {+ let blockReason: SleepBlockReason?+ let enabled: Bool+ let hook: Bool+ let tasks: Bool+ let helper: HelperStatus+ let refreshing: Bool+ let limited: Bool+ }init(activityMonitor: CodexActivityMonitor,@@ -66,6 +93,7 @@ final class KeepAliveController: ObservableObject {self.activityMonitor = activityMonitorself.codexHookSettings = codexHookSettingsself.defaults = defaults+ isHookEnabled = codexHookSettings.isEnabledisEnabled = defaults.bool(forKey: Self.enabledKey)maximumDuration = (defaults.object(forKey: Self.maximumDurationKey) as? Int).flatMap(MaximumDuration.init(rawValue:)) ?? .twelveHours@@ -79,10 +107,13 @@ final class KeepAliveController: ObservableObject {// Hook 是本功能的依赖, 不是用户意图// 只重新求值当前该不该阻止休眠, 绝不改写用户保存的开关+ // @Published 在 willSet 就发信号, 此刻回读 codexHookSettings.isEnabled 拿到的还是旧值+ // 因此把新值先存进 isHookEnabled, 判定与日志都只认它codexHookSettings.$isEnabled.removeDuplicates()- .sink { [weak self] _ in- self?.reconcileSleepState()+ .sink { [weak self] isEnabled in+ self?.isHookEnabled = isEnabled+ self?.reconcileSleepState(trigger: .hookChanged)}.store(in: &cancellables)@@ -128,18 +159,19 @@ final class KeepAliveController: ObservableObject {if isEnabled || helperStatus.isRegisteredOrAwaitingApproval {ensureHelperRegistration(opensSystemSettings: false)}- reconcileSleepState()+ reconcileSleepState(trigger: .statusRefresh)}func setEnabled(_ enabled: Bool) {- guard !enabled || codexHookSettings.isEnabled else {+ // 与 sleepBlockReason 读同一份镜像, 类内只保留一个 Hook 状态的真相来源+ guard !enabled || isHookEnabled else {return}guard enabled != isEnabled else {return}- AppLog.keepAlive.notice("阻止休眠开关已变更: enabled=\(enabled ? 1 : 0)")+ AppLog.keepAlive.notice("KeepAlive 开关变更: enabled=\(enabled ? 1 : 0)")isEnabled = enableddefaults.set(enabled, forKey: Self.enabledKey)registrationErrorMessage = nil@@ -150,7 +182,7 @@ final class KeepAliveController: ObservableObject {} else {resetMaximumDurationState()}- reconcileSleepState()+ reconcileSleepState(trigger: .settings)}func setMaximumDuration(_ duration: MaximumDuration) {@@ -158,7 +190,7 @@ final class KeepAliveController: ObservableObject {return}- AppLog.keepAlive.notice("最长阻止时间已变更: duration=\(duration.title, privacy: .public)")+ AppLog.keepAlive.notice("KeepAlive 上限变更: duration=\(duration.title, privacy: .public)")maximumDuration = durationdefaults.set(duration.rawValue, forKey: Self.maximumDurationKey)@@ -174,7 +206,7 @@ final class KeepAliveController: ObservableObject {hasReachedMaximumDuration = falsescheduleMaximumDurationTask()- reconcileSleepState()+ reconcileSleepState(trigger: .settings)}private func handleActivitySnapshot(_ snapshot: CodexActivitySnapshot) {@@ -196,7 +228,7 @@ final class KeepAliveController: ObservableObject {} else if !newRunningTaskIDs.isEmpty || !resumedRunningTaskIDs.isEmpty {restartMaximumDurationPeriod()}- reconcileSleepState()+ reconcileSleepState(trigger: .taskChanged)}private func restartMaximumDurationPeriod() {@@ -234,14 +266,14 @@ final class KeepAliveController: ObservableObject {}}- AppLog.keepAlive.notice("开始注册服务")+ AppLog.keepAlive.notice("Helper 注册开始")do {try service.register()} catch {refreshHelperStatus()if !helperStatus.isRegisteredOrAwaitingApproval {AppLog.keepAlive.error(- "注册服务失败: detail=\(error.localizedDescription, privacy: .public)"+ "Helper 注册失败: detail=\(error.localizedDescription, privacy: .public)")registrationErrorMessage = "注册服务失败"}@@ -294,7 +326,7 @@ final class KeepAliveController: ObservableObject {recordHelperRegistrationIfCurrent()} else if let registrationError {AppLog.keepAlive.error(- "更新服务失败: detail=\(registrationError.localizedDescription, privacy: .public)"+ "Helper 注册更新失败: detail=\(registrationError.localizedDescription, privacy: .public)")registrationErrorMessage = "更新服务失败"}@@ -304,7 +336,7 @@ final class KeepAliveController: ObservableObject {if helperStatus == .requiresApproval, opensSystemSettings {openSystemSettings()}- reconcileSleepState(force: true)+ reconcileSleepState(trigger: .helperRegistered, force: true)}}@@ -353,7 +385,7 @@ final class KeepAliveController: ObservableObject {let currentStatus = helperStatusif currentStatus != previousStatus {AppLog.keepAlive.notice(- "服务状态变化: from=\(String(describing: previousStatus), privacy: .public); to=\(String(describing: currentStatus), privacy: .public)"+ "Helper 注册状态变化: from=\(String(describing: previousStatus), privacy: .public); to=\(String(describing: currentStatus), privacy: .public)")}if helperStatus == .enabled {@@ -366,8 +398,10 @@ final class KeepAliveController: ObservableObject {}}- private func reconcileSleepState(force: Bool = false) {- let wantsSleepDisabled = shouldDisableSleep+ private func reconcileSleepState(trigger: LogTrigger, force: Bool = false) {+ let blockReason = sleepBlockReason+ let wantsSleepDisabled = blockReason == nil+ logSleepConditionsIfChanged(blockReason: blockReason, trigger: trigger)guard wantsSleepDisabled else {cancelRetryTask()@@ -385,6 +419,41 @@ final class KeepAliveController: ObservableObject {applySleepDisabled(true)}+ /// 任何一项变了才记一条, 逐次求值不记+ /// want 为 0 时这条是唯一能看出「是哪一项把它拉下来」的依据+ private func logSleepConditionsIfChanged(+ blockReason: SleepBlockReason?,+ trigger: LogTrigger+ ) {+ let conditions = SleepConditions(+ blockReason: blockReason,+ enabled: isEnabled,+ hook: isHookEnabled,+ tasks: hasRunningTasks,+ helper: helperStatus,+ refreshing: isRefreshingHelper,+ limited: hasReachedMaximumDuration+ )+ guard conditions != lastLoggedSleepConditions else {+ return+ }++ let previous = lastLoggedSleepConditions+ lastLoggedSleepConditions = conditions++ let triggerName = trigger.rawValue+ let helperName = String(describing: conditions.helper)+ AppLog.keepAlive.notice(+ "KeepAlive 条件变化: trigger=\(triggerName, privacy: .public); want=\(blockReason == nil ? 1 : 0); enabled=\(conditions.enabled ? 1 : 0); hook=\(conditions.hook ? 1 : 0); tasks=\(conditions.tasks ? 1 : 0); helper=\(helperName, privacy: .public); refreshing=\(conditions.refreshing ? 1 : 0); limited=\(conditions.limited ? 1 : 0)"+ )++ guard let previous, previous.blockReason == nil, let blockReason else {+ return+ }++ AppLog.keepAlive.notice("KeepAlive 已解除: reason=\(blockReason.rawValue, privacy: .public)")+ }+private func applySleepDisabled(_ disabled: Bool) {guard appliedSleepDisabled != disabled else {return@@ -393,7 +462,7 @@ final class KeepAliveController: ObservableObject {if disabled {let result = systemSleepService.beginPreventingIdleSleep()guard result == kIOReturnSuccess else {- AppLog.keepAlive.error("阻止空闲休眠失败: error=\(result)")+ AppLog.keepAlive.error("空闲断言建立失败: code=\(result)")operationErrorMessage = "阻止空闲休眠失败"scheduleRetryIfNeeded(for: true)return@@ -407,7 +476,7 @@ final class KeepAliveController: ObservableObject {let generation = requestGeneration// 与下面的回复日志配成一对, 缺回复即说明请求丢在 XPC 途中或 helper 无响应AppLog.keepAlive.notice(- "发送休眠请求: disabled=\(disabled ? 1 : 0); generation=\(generation)"+ "Helper XPC 请求已发送: op=\(disabled ? "disable" : "restore", privacy: .public); generation=\(generation)")let errorHandler: (Error) -> Void = { [weak self] error in@@ -430,13 +499,14 @@ final class KeepAliveController: ObservableObject {return}self.requestInFlight = false+ let replyResult = exitCode == 0 ? "ok" : "failed"AppLog.keepAlive.notice(- "收到休眠回复: generation=\(generation); error=\(exitCode); sleepDisabled=\(sleepDisabledAfterOperation ? 1 : 0)"+ "Helper XPC 回复已收到: generation=\(generation); result=\(replyResult, privacy: .public); exit=\(exitCode)")guard exitCode == 0 else {// invalidateConnection 会连同 assertion 一起收self.invalidateConnection()- AppLog.keepAlive.error("切换休眠状态失败: error=\(exitCode)")+ AppLog.keepAlive.error("系统休眠切换失败: generation=\(generation); exit=\(exitCode)")self.operationErrorMessage = "切换休眠状态失败"self.scheduleRetryIfNeeded(for: disabled)return@@ -446,7 +516,14 @@ final class KeepAliveController: ObservableObject {self.isPreventingSleep = disabledself.operationErrorMessage = nilif disabled {- AppLog.keepAlive.notice("已接管系统休眠")+ // lidCausesSleep=0 说明这一轮 pmset 是空转的, 真正在挡的只有空闲断言+ // 排查「开了却还是睡了」时先看这个字段+ let lidStatus = SystemSleepService.currentStatus()+ let lidCausesSleep = lidStatus+ .map { $0.lidClosureCausesSleep ? "1" : "0" } ?? "unknown"+ AppLog.keepAlive.notice(+ "系统休眠已关闭: generation=\(generation); lidCausesSleep=\(lidCausesSleep, privacy: .public)"+ )self.canTrustRestoreResult = trueself.beginMaximumDurationCountdownIfNeeded()} else {@@ -504,15 +581,15 @@ final class KeepAliveController: ObservableObject {cancelMaximumDurationTask()hasReachedMaximumDuration = truelet durationTitle = maximumDuration.title- AppLog.keepAlive.notice("已到阻止休眠上限: duration=\(durationTitle, privacy: .public)")- reconcileSleepState()+ AppLog.keepAlive.notice("KeepAlive 已达上限: duration=\(durationTitle, privacy: .public)")+ reconcileSleepState(trigger: .limitReached)}private func finishSleepRestore(sleepDisabledAfterOperation: Bool) {// assertion 无论回复可不可信都要释放, 与下面的判断无关let idleSleepResult = systemSleepService.endPreventingIdleSleep()if idleSleepResult != kIOReturnSuccess {- AppLog.keepAlive.error("恢复空闲休眠策略失败: error=\(idleSleepResult)")+ AppLog.keepAlive.error("空闲断言释放失败: code=\(idleSleepResult)")operationErrorMessage = "恢复空闲休眠策略失败"}@@ -521,32 +598,36 @@ final class KeepAliveController: ObservableObject {// 不能据此补发合盖休眠: 本轮可能压根不是我们禁用的休眠guard canTrustRestoreResult else {// 这条判断是防止误发强制休眠的唯一屏障, 生效时必须留痕, 否则误判无从追查- AppLog.keepAlive.notice("跳过恢复处理: 接管期间连接断开")+ AppLog.keepAlive.notice("系统休眠恢复结果不可信: reason=connectionLost")return}- AppLog.keepAlive.notice("已恢复系统休眠: SleepDisabled=\(sleepDisabled)")+ AppLog.keepAlive.notice("系统休眠已恢复: sleepDisabled=\(sleepDisabled)")let lidStatus = SystemSleepService.currentStatus()let shouldRequestSystemSleep = !sleepDisabledAfterOperation&& lidStatus?.shouldSleepForLidClosure == true- let lidClosed = lidStatus.map { $0.isLidClosed ? "1" : "0" } ?? "unknown"- let lidCausesSleep = lidStatus.map { $0.lidClosureCausesSleep ? "1" : "0" } ?? "unknown"-+ // 合盖是边沿事件, 错过那一刻系统不会再评估+ // 我们挡过一次就得在恢复后补一脚, 否则盖着的机器会一直醒着guard shouldRequestSystemSleep else {+ let reason: String = if sleepDisabledAfterOperation {+ "stillDisabled"+ } else if let lidStatus {+ lidStatus.isLidClosed ? "clamshellMode" : "lidOpen"+ } else {+ "unknown"+ }AppLog.keepAlive.notice(- "不请求系统休眠: sleepDisabled=\(sleepDisabled); lidClosed=\(lidClosed, privacy: .public); lidCausesSleep=\(lidCausesSleep, privacy: .public)"+ "休眠补发已跳过: reason=\(reason, privacy: .public)")return}- AppLog.keepAlive.notice(- "请求系统休眠: sleepDisabled=\(sleepDisabled); lidClosed=\(lidClosed, privacy: .public); lidCausesSleep=\(lidCausesSleep, privacy: .public)"- )+ AppLog.keepAlive.notice("休眠补发已请求")let result = SystemSleepService.requestSystemSleep()if result != kIOReturnSuccess {- AppLog.keepAlive.error("请求系统休眠失败: error=\(result)")+ AppLog.keepAlive.error("休眠补发失败: code=\(result)")operationErrorMessage = "请求系统休眠失败"}}@@ -595,7 +676,7 @@ final class KeepAliveController: ObservableObject {}connection.resume()self.connection = connection- AppLog.keepAlive.notice("已建立服务连接")+ AppLog.keepAlive.notice("Helper XPC 已连接")return connection}@@ -604,7 +685,7 @@ final class KeepAliveController: ObservableObject {let desiredSleepDisabled = shouldDisableSleepinvalidateConnection()AppLog.keepAlive.error(- "连接服务失败: detail=\(error.localizedDescription, privacy: .public)"+ "Helper XPC 连接失败: detail=\(error.localizedDescription, privacy: .public)")operationErrorMessage = "连接服务失败"if shouldRetry {@@ -621,7 +702,10 @@ final class KeepAliveController: ObservableObject {connection?.invalidate()// 无连接时也会走到这里, 只记真的断掉了一条, 避免空转刷屏if connection != nil {- AppLog.keepAlive.notice("服务连接已失效")+ // trusted 记的是断开这一刻的可信度: 它一断, 后面那轮恢复回复就不再可信+ // 也就不会补发休眠, 这是追查「任务结束了机器却没睡」的唯一线索+ let trusted = canTrustRestoreResult ? 1 : 0+ AppLog.keepAlive.notice("Helper XPC 已断开: trusted=\(trusted)")}// 所有能让我们在哨兵已删的情况下再发一次恢复请求的路径都汇到这里, 标志清在这里才严密canTrustRestoreResult = false@@ -663,7 +747,7 @@ final class KeepAliveController: ObservableObject {// 固定 2 秒无上限重试会让持续失败的 helper 变成无限循环guard retryAttempt < Self.sleepToggleRetryDelays.count else {AppLog.keepAlive.error(- "阻止休眠多次失败, 已停止重试: attempts=\(Self.sleepToggleRetryDelays.count)"+ "阻止休眠多次失败: attempts=\(Self.sleepToggleRetryDelays.count)")operationErrorMessage = "阻止休眠多次失败, 已停止重试"return@@ -672,8 +756,9 @@ final class KeepAliveController: ObservableObject {let delay = Self.sleepToggleRetryDelays[retryAttempt]retryAttempt += 1let attempt = retryAttempt+ let wait = LogDuration.seconds(delay)AppLog.keepAlive.notice(- "安排重试: attempt=\(attempt); delay=\(delay.components.seconds)s; disabled=\(disabled ? 1 : 0)"+ "休眠切换重试: attempt=\(attempt); delay=\(wait, privacy: .public); disabled=\(disabled ? 1 : 0)")retryTask = Task { @MainActor [weak self] in@@ -683,7 +768,7 @@ final class KeepAliveController: ObservableObject {}retryTask = nilguard disabled == shouldDisableSleep else {- reconcileSleepState()+ reconcileSleepState(trigger: .retry)return}appliedSleepDisabled = nil@@ -694,13 +779,34 @@ final class KeepAliveController: ObservableObject {/// 用户意图 (isEnabled) 与依赖可用性在这里汇合/// 依赖不满足只让效果失效, 不回写 isEnabledprivate var shouldDisableSleep: Bool {- isStarted- && isEnabled- && codexHookSettings.isEnabled- && hasRunningTasks- && helperStatus == .enabled- && !isRefreshingHelper- && !hasReachedMaximumDuration+ sleepBlockReason == nil+ }++ /// 按顺序返回第一个不满足的条件, 全部满足时为 nil+ /// 判定与日志共用这一份顺序, 新增条件不会漏进日志+ private var sleepBlockReason: SleepBlockReason? {+ if !isStarted {+ return .notStarted+ }+ if !isEnabled {+ return .userOff+ }+ if !isHookEnabled {+ return .hookDisabled+ }+ if !hasRunningTasks {+ return .noTasks+ }+ if helperStatus != .enabled {+ return .helperUnavailable+ }+ if isRefreshingHelper {+ return .helperRefreshing+ }+ if hasReachedMaximumDuration {+ return .limitReached+ }+ return nil}private static let enabledKey = "KeepAlive.isEnabled"diff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swiftindex 17eefe8..5946538 100644--- a/CodexBar/Services/Notifications/CodexNotificationService.swift+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift@@ -26,6 +26,22 @@ final class CodexNotificationService: NSObject {/// 阈值穿越判定的会话内上一帧剩余比例, key 为 account|limitId|windowIdprivate var lastRemainingPercents: [String: Int] = [:]+ /// 低额度判定依据的两个设置项+ /// 订阅回调跑在 @Published 的 willSet, 那时属性还是旧值, 只有回调参数是新的+ /// 所以由调用方给出而不是在判定处回读 settings+ private struct LowQuotaConditions {+ let isEnabled: Bool+ let thresholdPercent: Int+ }++ /// 额度刷新那条路径上设置没有在变, 现场取值就是最新的+ private var currentLowQuotaConditions: LowQuotaConditions {+ LowQuotaConditions(+ isEnabled: settings.isLowQuotaEnabled,+ thresholdPercent: settings.lowQuotaThresholdPercent+ )+ }+/// 可信快照中每个额度窗口的重置观察状态; 窗口消失后重现会获得新的生命周期标记private var quotaWindowResetObservations: [String: QuotaWindowResetObservation] = [:]@@ -65,8 +81,10 @@ final class CodexNotificationService: NSObject {settings.$lowQuotaThresholdPercent).dropFirst()- .sink { [weak self] _, _ in- self?.reevaluateLowQuotaSettings()+ .sink { [weak self] isEnabled, thresholdPercent in+ self?.reevaluateLowQuota(+ LowQuotaConditions(isEnabled: isEnabled, thresholdPercent: thresholdPercent)+ )}.store(in: &cancellables)@@ -201,7 +219,7 @@ final class CodexNotificationService: NSObject {// stale 快照是旧缓存, 不参与额度判定, 避免误报if !snapshot.isRateLimitsStale {- processQuotaWindows(snapshot)+ processQuotaWindows(snapshot, lowQuota: currentLowQuotaConditions)}guard settings.canDeliver else {@@ -212,14 +230,17 @@ final class CodexNotificationService: NSObject {processCreditExpirations(snapshot)}- private func processQuotaWindows(_ snapshot: CodexQuotaSnapshot) {+ private func processQuotaWindows(+ _ snapshot: CodexQuotaSnapshot,+ lowQuota: LowQuotaConditions+ ) {var observedWindowKeys = Set<String>()forEachQuotaWindowWithData(in: snapshot) { window, limit, stateKey inobservedWindowKeys.insert(stateKey)if quotaWindowResetObservations[stateKey] == nil {quotaWindowResetObservations[stateKey] = QuotaWindowResetObservation()}- processQuotaWindow(window, limit: limit, stateKey: stateKey)+ processQuotaWindow(window, limit: limit, stateKey: stateKey, lowQuota: lowQuota)}quotaWindowResetObservations = quotaWindowResetObservations.filter {observedWindowKeys.contains($0.key)@@ -244,16 +265,18 @@ final class CodexNotificationService: NSObject {}}- private func reevaluateLowQuotaSettings() {+ /// 设置刚变就按新值重判一次, 不必等下一个刷新周期+ /// 清掉上一帧观察是为了让新阈值能立刻穿越, 所以这里必须用新值判断, 否则清了也白清+ private func reevaluateLowQuota(_ conditions: LowQuotaConditions) {guard settings.canDeliver,- settings.isLowQuotaEnabled,+ conditions.isEnabled,let snapshot = latestQuotaSnapshot,!snapshot.isRateLimitsStale else {return}resetLowQuotaObservation(for: snapshot)- processQuotaWindows(snapshot)+ processQuotaWindows(snapshot, lowQuota: conditions)}private func resetLowQuotaObservation(for snapshot: CodexQuotaSnapshot) {@@ -265,7 +288,8 @@ final class CodexNotificationService: NSObject {private func processQuotaWindow(_ window: QuotaWindow,limit: CodexQuotaLimitSnapshot,- stateKey: String+ stateKey: String,+ lowQuota: LowQuotaConditions) {guard let usedPercent = window.usedPercent else {return@@ -286,24 +310,30 @@ final class CodexNotificationService: NSObject {lastRemainingPercents[stateKey] = window.remainingPercentguard let resetsAt = window.resetsAt,- window.remainingPercent <= settings.lowQuotaThresholdPercent,- settings.isLowQuotaEnabled else {+ window.remainingPercent <= lowQuota.thresholdPercent,+ lowQuota.isEnabled else {return}// 穿越判定: 上一帧高于阈值才提醒; 会话内首次观察即低于也视为穿越// (App 可能在跌破后才启动), 持久化去重键保证每周期只发一次if let previousRemainingPercent,- previousRemainingPercent <= settings.lowQuotaThresholdPercent {+ previousRemainingPercent <= lowQuota.thresholdPercent {return}+ // 阈值是用户设置值不是用量数据, 记它才能解释这条通知为什么会发出来+ let threshold = lowQuota.thresholdPercent+ AppLog.notification.notice(+ "阈值已穿越: kind=lowQuota; threshold=\(threshold); direction=down"+ )+let dedupKey = "low|\(stateKey)|\(Self.epoch(resetsAt))"send(.lowQuota(limitTitle: limit.title,windowLabel: window.label,- thresholdPercent: settings.lowQuotaThresholdPercent+ thresholdPercent: lowQuota.thresholdPercent),sound: settings.lowQuotaSound,dedupKey: dedupKey,@@ -333,6 +363,8 @@ final class CodexNotificationService: NSObject {return}+ AppLog.notification.notice("额度已重置: kind=quotaReset")+let dedupKey = window.resetsAt.map { resetsAt in"quotaReset|\(stateKey)|\(Self.epoch(resetsAt))"}@@ -488,7 +520,9 @@ final class CodexNotificationService: NSObject {}// 重试全部用尽才记, 循环内的单次失败会重试- AppLog.notification.error("通知发送失败: kind=\(kind, privacy: .public); reason=retryExhausted")+ AppLog.notification.error(+ "通知发送失败: kind=\(kind, privacy: .public); reason=retryExhausted"+ )onSubmissionFailure?()}}diff --git a/CodexBar/Services/Settings/CodexCLINotificationSettings.swift b/CodexBar/Services/Settings/CodexCLINotificationSettings.swiftindex 62359e1..6b7d1d1 100644--- a/CodexBar/Services/Settings/CodexCLINotificationSettings.swift+++ b/CodexBar/Services/Settings/CodexCLINotificationSettings.swift@@ -26,7 +26,7 @@ final class CodexCLINotificationSettings: ObservableObject {return}- runLatestUpdate(errorPrefix: "读取 Codex TUI 通知失败") { settings, generation in+ runLatestUpdate(operation: .read) { settings, generation inlet response = try await settings.codexStatusService.readCodexConfig()try settings.ensureCurrentUpdate(generation)return response.areTUINotificationsEnabled@@ -34,12 +34,12 @@ final class CodexCLINotificationSettings: ObservableObject {}func setEnabled(_ enabled: Bool) {- AppLog.settings.notice("Codex 通知配置已变更: enabled=\(enabled ? 1 : 0)")+ AppLog.settings.notice("Codex TUI 通知变更: enabled=\(enabled ? 1 : 0)")guard enabled != isEnabled else {return}- runLatestUpdate(errorPrefix: "设置 Codex TUI 通知失败") { settings, generation in+ runLatestUpdate(operation: .write) { settings, generation in_ = try await settings.codexStatusService.writeCodexConfigBatch(edits: [.init(@@ -60,9 +60,30 @@ final class CodexCLINotificationSettings: ObservableObject {}}+ /// 一次操作的用户文案与日志标题由它一处派生, 不在调用点各写一份+ /// 两者都是固定字面量, 日志标题仍然能直接 grep+ private enum ConfigOperation {+ case read+ case write++ var errorPrefix: String {+ switch self {+ case .read: "读取 Codex TUI 通知设置失败"+ case .write: "写入 Codex TUI 通知设置失败"+ }+ }++ var logStage: String {+ switch self {+ case .read: "read"+ case .write: "write"+ }+ }+ }+private func runLatestUpdate(- errorPrefix: String,- operation: @escaping @MainActor (CodexCLINotificationSettings, Int) async throws -> Bool+ operation: ConfigOperation,+ body: @escaping @MainActor (CodexCLINotificationSettings, Int) async throws -> Bool) {updateTask?.cancel()updateGeneration += 1@@ -76,7 +97,7 @@ final class CodexCLINotificationSettings: ObservableObject {}do {- let isEnabled = try await operation(self, generation)+ let isEnabled = try await body(self, generation)guard isCurrentUpdate(generation) else {return}@@ -87,10 +108,11 @@ final class CodexCLINotificationSettings: ObservableObject {guard isCurrentUpdate(generation) else {return}+ let logStage = operation.logStageAppLog.settings.error(- "\(errorPrefix, privacy: .public): detail=\(error.localizedDescription, privacy: .public)"+ "Codex TUI 通知失败: stage=\(logStage, privacy: .public); detail=\(error.localizedDescription, privacy: .public)")- errorMessage = errorPrefix+ errorMessage = operation.errorPrefix}finishUpdate(generation)diff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swiftindex 7599600..a2a3389 100644--- a/CodexBar/Services/Settings/CodexHookSettings.swift+++ b/CodexBar/Services/Settings/CodexHookSettings.swift@@ -23,6 +23,9 @@ final class CodexHookSettings: ObservableObject {private let codexStatusService: CodexStatusServiceprivate var updateTask: Task<Void, Never>?private var updateGeneration = 0+ /// refresh() 上次读到的安装结论, 首次读取前为 nil+ /// 不能用 isEnabled 代替: 它的初始值是 false, 会把首次读取当成一次配置变化+ private var lastKnownInstalled: Bool?init(hooksURL: URL = CodexHookSettings.defaultHooksURL(),@@ -41,24 +44,32 @@ final class CodexHookSettings: ObservableObject {func refresh() {do {let config = try readConfigIfPresent()- isEnabled = Self.containsAnyCodexBarHook(+ let installed = Self.containsAnyCodexBarHook(in: config,executablePath: currentExecutablePath)+ // 每次开面板都会读一遍, 无条件记会刷屏+ // 只在结论变了才记, 外部改动 ~/.codex/hooks.json 就是从这条看出来的+ // 首次读取没有可比的上次值; 拿 isEnabled 的初始 false 去比, 会让装了 Hook 的用户每次启动误报一条+ if let lastKnownInstalled, lastKnownInstalled != installed {+ AppLog.hooks.notice("Hook 配置变化: enabled=\(installed ? 1 : 0)")+ }+ lastKnownInstalled = installed+ isEnabled = installedreadErrorMessage = nil} catch {// 只有 I/O 失败和 JSON 格式错误会走到这里, 它们对「Hook 装没装」不提供信息// 文件不存在或配置里没有 CodexBar 都由 readConfigIfPresent 正常返回// 因此保留上次已知值, 不能把读取失败当成用户关闭了 HookAppLog.hooks.error(- "读取 Hook 配置失败: detail=\(error.localizedDescription, privacy: .public)"+ "Hook 读取失败: detail=\(error.localizedDescription, privacy: .public); action=keepLastKnown")readErrorMessage = "读取 Codex Hook 配置失败"}}func setEnabled(_ enabled: Bool) {- AppLog.hooks.notice("Hook 开关已变更: enabled=\(enabled ? 1 : 0)")+ AppLog.hooks.notice("Hook 开关变更: enabled=\(enabled ? 1 : 0)")runLatestUpdate(showProgress: true) { settings, generation inawait settings.applyEnabled(enabled, generation: generation)}@@ -178,14 +189,15 @@ final class CodexHookSettings: ObservableObject {if let hookError = error as? HookConfigError,hookError.isPreflightFailure {- AppLog.hooks.error(- "前置检查未通过, 未改动配置: detail=\(hookError.localizedDescription, privacy: .public)"+ // 前置检查拦下是预期内的拒绝, 配置一个字没动, 不是故障+ AppLog.hooks.notice(+ "Hook 前置检查未通过: detail=\(hookError.localizedDescription, privacy: .public)")isEnabled = falseoperationErrorMessage = hookError.localizedDescription} else {AppLog.hooks.error(- "设置 Hook 失败: detail=\(error.localizedDescription, privacy: .public)"+ "Hook 写入失败: detail=\(error.localizedDescription, privacy: .public)")refresh()operationErrorMessage = "设置 Codex Hook 失败"@@ -321,7 +333,7 @@ private extension CodexHookSettings {try write(config)// 改的是用户自己的 ~/.codex/hooks.json, 每次写入都要留痕- AppLog.hooks.notice("已写入 Hook 配置: enabled=\(enabled ? 1 : 0)")+ AppLog.hooks.notice("Hook 配置已写入: enabled=\(enabled ? 1 : 0)")}func codexBarHookTrustKeysFromAppServer() async throws -> Set<String> {@@ -343,12 +355,12 @@ private extension CodexHookSettings {if !keys.isEmpty {try await removeCodexBarHookTrust(keys)try ensureCurrentUpdate(generation)- AppLog.hooks.notice("已清理 Hook 信任状态: keys=\(keys.count)")+ AppLog.hooks.notice("Hook 信任状态已清理: keys=\(keys.count)")}if let discoveryError {AppLog.hooks.error(- "清理信任状态失败: stage=discovery; detail=\(discoveryError.localizedDescription, privacy: .public)"+ "Hook 信任清理失败: stage=discovery; detail=\(discoveryError.localizedDescription, privacy: .public)")operationErrorMessage = "已关闭 Codex Hook, 清理信任状态失败"} else {@@ -362,7 +374,7 @@ private extension CodexHookSettings {}AppLog.hooks.error(- "清理信任状态失败: stage=remove; detail=\(error.localizedDescription, privacy: .public)"+ "Hook 信任清理失败: stage=remove; detail=\(error.localizedDescription, privacy: .public)")operationErrorMessage = "已关闭 Codex Hook, 清理信任状态失败"}diff --git a/CodexBar/Services/Settings/GlobalHotKeySettings.swift b/CodexBar/Services/Settings/GlobalHotKeySettings.swiftindex caf3230..bb91130 100644--- a/CodexBar/Services/Settings/GlobalHotKeySettings.swift+++ b/CodexBar/Services/Settings/GlobalHotKeySettings.swift@@ -22,14 +22,14 @@ final class GlobalHotKeySettings: ObservableObject {return}- AppLog.settings.notice("全局快捷键已设置")+ AppLog.settings.notice("快捷键已设置")self.shortcut = shortcutsaveShortcut(shortcut)errorMessage = nil}func clearShortcut() {- AppLog.settings.notice("全局快捷键已清除")+ AppLog.settings.notice("快捷键已清除")shortcut = nilsaveShortcut(nil)errorMessage = nil@@ -39,15 +39,17 @@ final class GlobalHotKeySettings: ObservableObject {setShortcut(.default)}+ /// 只设用户可见文案, 不记日志+ /// 注册失败由 GlobalHotKeyController 记且带 code=, 这里再记一条会把一次冲突算成两次+ /// 另一个调用方是录制时的按键解析失败, 那次根本没发起注册, 记成 stage=register 更是误导func setRegistrationError(_ message: String) {- AppLog.settings.error("全局快捷键注册失败: detail=\(message, privacy: .public)")errorMessage = message}/// 参数不可为空: 传 nil 会经 saveShortcut 清空用户保存的配置/// 没有可回退的快捷键时应改用 setRegistrationErrorfunc restoreShortcut(_ shortcut: GlobalHotKeyShortcut, message: String) {- AppLog.settings.notice("全局快捷键已回退: detail=\(message, privacy: .public)")+ AppLog.settings.notice("快捷键已回退: reason=occupied")self.shortcut = shortcutsaveShortcut(shortcut)errorMessage = messagediff --git a/CodexBar/Services/Settings/LoginItemSettings.swift b/CodexBar/Services/Settings/LoginItemSettings.swiftindex a3beb07..7802703 100644--- a/CodexBar/Services/Settings/LoginItemSettings.swift+++ b/CodexBar/Services/Settings/LoginItemSettings.swift@@ -16,7 +16,7 @@ final class LoginItemSettings: ObservableObject {func setEnabled(_ enabled: Bool) {errorMessage = nil- AppLog.settings.notice("开机启动已变更: enabled=\(enabled ? 1 : 0)")+ AppLog.settings.notice("开机自动启动变更: enabled=\(enabled ? 1 : 0)")do {if enabled {try SMAppService.mainApp.register()@@ -27,7 +27,7 @@ final class LoginItemSettings: ObservableObject {refresh()} catch {AppLog.settings.error(- "设置开机启动失败: enabled=\(enabled ? 1 : 0); detail=\(error.localizedDescription, privacy: .public)"+ "开机自动启动失败: enabled=\(enabled ? 1 : 0); detail=\(error.localizedDescription, privacy: .public)")refresh()errorMessage = "设置开机启动失败"diff --git a/CodexBar/Services/Settings/MainPanelSettings.swift b/CodexBar/Services/Settings/MainPanelSettings.swiftindex 45ae3ff..342a19f 100644--- a/CodexBar/Services/Settings/MainPanelSettings.swift+++ b/CodexBar/Services/Settings/MainPanelSettings.swift@@ -28,7 +28,7 @@ final class MainPanelSettings: ObservableObject {return}- AppLog.settings.notice("任务中心显示已变更: enabled=\(showsTaskCenter ? 1 : 0)")+ AppLog.settings.notice("主面板任务中心变更: enabled=\(showsTaskCenter ? 1 : 0)")defaults.set(showsTaskCenter, forKey: Self.showsTaskCenterKey)self.showsTaskCenter = showsTaskCenter}diff --git a/CodexBar/Services/Settings/MenuBarQuotaSettings.swift b/CodexBar/Services/Settings/MenuBarQuotaSettings.swiftindex d022bdb..cda228b 100644--- a/CodexBar/Services/Settings/MenuBarQuotaSettings.swift+++ b/CodexBar/Services/Settings/MenuBarQuotaSettings.swift@@ -37,7 +37,7 @@ final class MenuBarQuotaSettings: ObservableObject {}AppLog.settings.notice(- "菜单栏额度显示已变更: selection=\(selection.rawValue, privacy: .public)"+ "菜单栏额度指示变更: selection=\(selection.rawValue, privacy: .public)")saveSelection(selection)publishSelection(selection)diff --git a/CodexBar/Services/Settings/NotificationSettings.swift b/CodexBar/Services/Settings/NotificationSettings.swiftindex 3fc9dd1..af3eb4a 100644--- a/CodexBar/Services/Settings/NotificationSettings.swift+++ b/CodexBar/Services/Settings/NotificationSettings.swift@@ -96,7 +96,7 @@ final class NotificationSettings: ObservableObject {return}- AppLog.notification.notice("通知总开关已变更: enabled=\(enabled ? 1 : 0)")+ AppLog.notification.notice("通知总开关变更: enabled=\(enabled ? 1 : 0)")isEnabled = enableddefaults.set(enabled, forKey: Self.enabledKey)if enabled {@@ -187,7 +187,7 @@ final class NotificationSettings: ObservableObject {let previousStatus = authorizationStatusif status != previousStatus {AppLog.notification.notice(- "通知授权状态变化: from=\(String(describing: previousStatus), privacy: .public); to=\(String(describing: status), privacy: .public)"+ "通知授权变化: from=\(String(describing: previousStatus), privacy: .public); to=\(String(describing: status), privacy: .public)")}authorizationStatus = status@@ -220,7 +220,7 @@ final class NotificationSettings: ObservableObject {// 被拒时通知会静默不发, 这是最常见的"设置开了却收不到"来源, 必须留痕AppLog.notification.notice(- "通知授权请求结果: status=\(String(describing: status), privacy: .public)"+ "通知授权结果: status=\(String(describing: status), privacy: .public)")authorizationStatus = status}@@ -233,7 +233,7 @@ final class NotificationSettings: ObservableObject {// 六个通知细项都走这里, 用持久化 key 区分是哪一项, 不必逐个 setter 铺日志AppLog.notification.notice(- "通知选项已变更: key=\(key, privacy: .public); enabled=\(value ? 1 : 0)"+ "通知选项变更: key=\(key, privacy: .public); enabled=\(value ? 1 : 0)")current = valuedefaults.set(value, forKey: key)diff --git a/CodexBar/Services/Settings/WorkflowSyncSettings.swift b/CodexBar/Services/Settings/WorkflowSyncSettings.swiftindex 91a5fc0..671c905 100644--- a/CodexBar/Services/Settings/WorkflowSyncSettings.swift+++ b/CodexBar/Services/Settings/WorkflowSyncSettings.swift@@ -47,7 +47,7 @@ final class WorkflowSyncSettings: ObservableObject {let previousValue = isEnabledif previousValue != enabled {- AppLog.sync.notice("同步开关已变更: enabled=\(enabled ? 1 : 0)")+ AppLog.sync.notice("同步开关变更: enabled=\(enabled ? 1 : 0)")}defaults.set(enabled, forKey: Self.enabledKey)if enabled {@@ -65,8 +65,31 @@ final class WorkflowSyncSettings: ObservableObject {}/// "同步是否实际生效"的唯一判定: Hook 已启用且同步开关打开且 iCloud 可用+ /// 按顺序返回第一个不满足的项, 日志的 reason= 直接取它的 rawValue+ func activation(isHookEnabled: Bool) -> WorkflowSyncActivation {+ activation(isHookEnabled: isHookEnabled, isSyncAvailable: isSyncAvailable)+ }++ /// 两项依赖都可以由调用方指定+ /// @Published 的订阅回调跑在 willSet, 那时属性还是旧值, 只有回调参数是新值+ func activation(+ isHookEnabled: Bool,+ isSyncAvailable: Bool+ ) -> WorkflowSyncActivation {+ if !isHookEnabled {+ return .hookOff+ }+ if !isEnabled {+ return .syncOff+ }+ if !isSyncAvailable {+ return .unavailable+ }+ return .active+ }+func isEffectivelyActive(isHookEnabled: Bool) -> Bool {- isHookEnabled && isEnabled && isSyncAvailable+ activation(isHookEnabled: isHookEnabled).isActive}var unavailableMessage: String? {@@ -197,6 +220,18 @@ final class WorkflowSyncSettings: ObservableObject {private nonisolated static let needsBackfillKey = "WorkflowSync.needsBackfill"}+/// 同步没生效时缺的是哪一项, 同时充当日志里的 reason= 取值+nonisolated enum WorkflowSyncActivation: String {+ case active+ case hookOff+ case syncOff+ case unavailable++ var isActive: Bool {+ self == .active+ }+}+nonisolated enum WorkflowSyncAvailability: Equatable {case unknowncase availablediff --git a/CodexBar/Services/Support/AppLog.swift b/CodexBar/Services/Support/AppLog.swiftindex cdcade5..32e8acb 100644--- a/CodexBar/Services/Support/AppLog.swift+++ b/CodexBar/Services/Support/AppLog.swift@@ -20,8 +20,49 @@ nonisolated enum AppLog {static let settings = Logger(subsystem: subsystem, category: "settings")/// codex 可执行文件检测与版本读取static let codexCLI = Logger(subsystem: subsystem, category: "codexcli")- /// 本地通知投递+ /// 本地通知static let notification = Logger(subsystem: subsystem, category: "notification")private static let subsystem = Bundle.main.bundleIdentifier ?? "app.zabrian.codexbar"}++/// 一次操作的触发来源, 作为日志里的 trigger 字段+/// 同一条链路可能被用户动作 定时轮询 系统事件分别踢起来, 事后只有这个字段能区分+nonisolated enum LogTrigger: String {+ case manual+ case panelOpen+ case auto+ case launch+ case wake+ case settings+ case retry+ /// Hook 开关转为开启后补跑同步+ case hookEnabled+ case hookChanged+ case taskChanged+ case helperRegistered+ case limitReached+ case statusRefresh+}++/// 日志里耗时字段的统一取值方式, 保留两位小数并带单位+nonisolated struct LogDuration {+ private let startedAt = ContinuousClock.now++ var elapsed: String {+ Self.seconds(startedAt.duration(to: .now))+ }++ /// 已经算好的秒数走这里, 保证和 elapsed 同一种写法+ static func seconds(_ value: TimeInterval) -> String {+ String(format: "%.2fs", max(0, value))+ }++ /// 重试间隔这类 Duration 走这里, 不必在调用点各写一遍换算+ static func seconds(_ duration: Duration) -> String {+ seconds(+ Double(duration.components.seconds)+ + Double(duration.components.attoseconds) / 1e18+ )+ }+}diff --git a/CodexBar/Services/Support/AppProcessDiagnostics.swift b/CodexBar/Services/Support/AppProcessDiagnostics.swiftnew file mode 100644index 0000000..d0879ef--- /dev/null+++ b/CodexBar/Services/Support/AppProcessDiagnostics.swift@@ -0,0 +1,33 @@+import Foundation+import os++/// 崩溃时进程直接消失, 日志会停在最后一条正常记录上, 事后分不清是崩了还是被退出+/// 这里补两条线索: ObjC 异常当场留痕, 其余终止方式 (Swift trap, kill, 断电) 靠下次启动补记+/// 干净退出标志由 install 与 recordCleanExit 成对维护, 两侧都在这里, 不散到调用方+nonisolated enum AppProcessDiagnostics {+ static func install(defaults: UserDefaults = .standard) {+ // 首次运行没有这个键, 不能当成崩溃过+ // kill, 活动监视器强制退出和 Xcode 停止按钮都到不了 recordCleanExit, 与崩溃无法区分+ // 因此只记 notice: 这条是线索不是结论, 用 error 会让按级别筛的排查开局就追一个不存在的故障+ if let didExitCleanly = defaults.object(forKey: didExitCleanlyKey) as? Bool,+ !didExitCleanly {+ AppLog.app.notice("App 上次非正常退出: reason=unknown")+ }+ defaults.set(false, forKey: didExitCleanlyKey)++ // 只兜得住 ObjC 异常; Swift 的 fatalError 与越界是 trap, 到不了这里, 由上面那条补记+ NSSetUncaughtExceptionHandler { exception in+ let name = exception.name.rawValue+ let reason = exception.reason ?? "-"+ AppLog.app.error(+ "未捕获异常: name=\(name, privacy: .public); reason=\(reason, privacy: .public)"+ )+ }+ }++ static func recordCleanExit(defaults: UserDefaults = .standard) {+ defaults.set(true, forKey: didExitCleanlyKey)+ }++ private static let didExitCleanlyKey = "Diagnostics.didExitCleanly"+}diff --git a/CodexBar/Services/Updates/AppUpdater.swift b/CodexBar/Services/Updates/AppUpdater.swiftindex 45504b7..b2907d1 100644--- a/CodexBar/Services/Updates/AppUpdater.swift+++ b/CodexBar/Services/Updates/AppUpdater.swift@@ -55,7 +55,7 @@ final class AppUpdater: NSObject, ObservableObject {return}- AppLog.app.notice("开始检查更新")+ AppLog.app.notice("更新检查开始: trigger=\(LogTrigger.manual.rawValue, privacy: .public)")beginManualCheck()showSettingsStatusMessage("正在检查更新")updaterController.updater.checkForUpdateInformation()@@ -78,7 +78,7 @@ final class AppUpdater: NSObject, ObservableObject {return}- AppLog.app.notice("自动检查更新已变更: enabled=\(isEnabled ? 1 : 0)")+ AppLog.app.notice("自动检查更新变更: enabled=\(isEnabled ? 1 : 0)")updaterController.updater.automaticallyChecksForUpdates = isEnabledrefreshAutomaticCheckSetting()}@@ -102,6 +102,11 @@ final class AppUpdater: NSObject, ObservableObject {}}+ /// 手动与自动检查共用 Sparkle 的几个回调, 触发来源只能从当前是不是手动态推出来+ private var checkTrigger: LogTrigger {+ isManualCheckInProgress ? .manual : .auto+ }+/// 手动检查态只影响结果去向 (设置窗 vs 菜单面板), 复位失败会永久隐藏面板更新提示private func finishManualCheck() {manualCheckTimeoutTask?.cancel()@@ -142,6 +147,11 @@ extension AppUpdater: SPUUpdaterDelegate {func updater(_: SPUUpdater, didFindValidUpdate item: SUAppcastItem) {let message = "发现新版本: v\(item.displayVersionString)"availableUpdateMessage = message+ let trigger = checkTrigger.rawValue+ let version = item.displayVersionString+ AppLog.app.notice(+ "更新检查完成: trigger=\(trigger, privacy: .public); result=available; version=\(version, privacy: .public)"+ )if isManualCheckInProgress {showSettingsStatusMessage(message, autoDismissDelay: nil)@@ -155,6 +165,10 @@ extension AppUpdater: SPUUpdaterDelegate {func updaterDidNotFindUpdate(_: SPUUpdater, error _: Error) {availableUpdateMessage = nilpanelUpdateMessage = nil+ let trigger = checkTrigger.rawValue+ AppLog.app.notice(+ "更新检查完成: trigger=\(trigger, privacy: .public); result=upToDate"+ )if isManualCheckInProgress {showSettingsStatusMessage("没有可用更新", autoDismissDelay: .milliseconds(1000))@@ -163,7 +177,16 @@ extension AppUpdater: SPUUpdaterDelegate {finishManualCheck()}- func updater(_: SPUUpdater, didAbortWithError _: Error) {+ func updater(_: SPUUpdater, didAbortWithError error: Error) {+ // 没有可用更新时 Sparkle 也会走这个回调, 那不是失败+ // 这一轮的结果已由 updaterDidNotFindUpdate 记成 result=upToDate+ if (error as NSError).code != Int(SUError.noUpdateError.rawValue) {+ let trigger = checkTrigger.rawValue+ AppLog.app.error(+ "更新检查失败: trigger=\(trigger, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"+ )+ }+guard isManualCheckInProgress else {return}diff --git a/CodexBar/Services/Workflow/CodexActivityMonitor.swift b/CodexBar/Services/Workflow/CodexActivityMonitor.swiftindex 41a3c9a..ad9f698 100644--- a/CodexBar/Services/Workflow/CodexActivityMonitor.swift+++ b/CodexBar/Services/Workflow/CodexActivityMonitor.swift@@ -30,6 +30,10 @@ final class CodexActivityMonitor: ObservableObject {private var cancellables = Set<AnyCancellable>()private var isStarted = falseprivate var isBootstrapping = false+ /// 历史回放跨多个批次到达, 事件数累加到 bootstrapEnd 才一次记完+ /// reader 每次重试都会重新发一遍 bootstrapStart, 所以事件数跟着重置, 但耗时要累计+ private var bootstrapEventCount = 0+ private var bootstrapDuration = LogDuration()private var sessionTransitionNotBefore: Date?init(codexHookSettings: CodexHookSettings) {@@ -56,7 +60,9 @@ final class CodexActivityMonitor: ObservableObject {guard let self else {return}- AppLog.activity.notice("系统唤醒, 立即重新读取")+ AppLog.activity.notice(+ "事件重读已触发: trigger=\(LogTrigger.wake.rawValue, privacy: .public)"+ )if let reader = tailReader {Task {await reader.drainNow()@@ -78,7 +84,7 @@ final class CodexActivityMonitor: ObservableObject {private func setMonitoringEnabled(_ enabled: Bool) {guard enabled else {- AppLog.activity.notice("已停止监控")+ AppLog.activity.notice("任务监控已停止: reason=hookDisabled")stopReaderAndClearState()return}@@ -87,7 +93,7 @@ final class CodexActivityMonitor: ObservableObject {return}- AppLog.activity.notice("已开始监控")+ AppLog.activity.notice("任务监控已启动: reason=hookEnabled")tailReaderGeneration &+= 1let generation = tailReaderGeneration@@ -171,6 +177,79 @@ final class CodexActivityMonitor: ObservableObject {}}+ /// 把一条 rollout 生命周期状态合进当前任务, 返回是否改动过状态+ /// 待确认终态的任务与在跑的任务走两条分支, 前者已经从 tasks 里挪走+ private func applyLifecycleState(+ _ state: CodexSessionTaskLifecycleState,+ into transitions: inout [CodexActivityTransition]+ ) -> Bool {+ let key = CodexActivityTaskKey.turn(session: state.sessionId, turn: state.turnId)+ if var pending = pendingTerminalTasks[key] {+ let pendingDidChange = Self.mergeLifecycleBackfill(+ from: state,+ into: &pending.task+ )++ guard let terminal = state.terminal else {+ guard pendingDidChange else {+ return false+ }+ pendingTerminalTasks[key] = pending+ return true+ }+ pendingTerminalTasks.removeValue(forKey: key)+ resolveTerminal(+ terminal,+ task: pending.task,+ key: key,+ abortFallback: pending.supersededAt,+ into: &transitions+ )+ return true+ }++ guard var task = tasks[key] else {+ return false+ }++ var taskDidChange = Self.mergeLifecycleBackfill(from: state, into: &task)++ if let terminal = state.terminal {+ tasks.removeValue(forKey: key)+ if case .completed = terminal, recentCompletionDate(for: key) != nil {+ // 迟到事件恢复出的任务不能被 rollout 再次完成+ return true+ }+ resolveTerminal(+ terminal,+ task: task,+ key: key,+ abortFallback: Date(),+ into: &transitions+ )+ return true+ }++ if let approvalReviewer = state.approvalReviewer,+ task.approvalReviewer != approvalReviewer {+ task.approvalReviewer = approvalReviewer+ taskDidChange = true+ }++ if resolvePendingApprovalIfPossible(+ for: &task,+ into: &transitions+ ) {+ taskDidChange = true+ }++ guard taskDidChange else {+ return false+ }+ tasks[key] = task+ return true+ }+private func reconcileSessionLifecycles(generation: UInt64) async {guard generation == tailReaderGeneration,tailReader != nil,@@ -194,72 +273,7 @@ final class CodexActivityMonitor: ObservableObject {var didChange = falsevar transitions: [CodexActivityTransition] = []for state in states {- let key = CodexActivityTaskKey.turn(session: state.sessionId, turn: state.turnId)- if var pending = pendingTerminalTasks[key] {- let pendingDidChange = Self.mergeLifecycleBackfill(- from: state,- into: &pending.task- )-- guard let terminal = state.terminal else {- if pendingDidChange {- pendingTerminalTasks[key] = pending- didChange = true- }- continue- }- pendingTerminalTasks.removeValue(forKey: key)- resolveTerminal(- terminal,- task: pending.task,- key: key,- abortFallback: pending.supersededAt,- into: &transitions- )- didChange = true- continue- }-- guard var task = tasks[key] else {- continue- }-- var taskDidChange = Self.mergeLifecycleBackfill(from: state, into: &task)-- if let terminal = state.terminal {- tasks.removeValue(forKey: key)- didChange = true- if case .completed = terminal, recentCompletionDate(for: key) != nil {- // 迟到事件恢复出的任务不能被 rollout 再次完成- continue- }- resolveTerminal(- terminal,- task: task,- key: key,- abortFallback: Date(),- into: &transitions- )- continue- }-- if let approvalReviewer = state.approvalReviewer,- task.approvalReviewer != approvalReviewer {- task.approvalReviewer = approvalReviewer- taskDidChange = true- }-- if resolvePendingApprovalIfPossible(- for: &task,- into: &transitions- ) {- taskDidChange = true- }-- if taskDidChange {- tasks[key] = task- didChange = true- }+ didChange = applyLifecycleState(state, into: &transitions) || didChange}if didChange {@@ -273,21 +287,38 @@ final class CodexActivityMonitor: ObservableObject {private func consume(_ batch: HookEventBatch) {switch batch {case .bootstrapStart:+ // 重试会重放整段历史, 计时从第一次开始算才是用户等到的总时长+ if !isBootstrapping {+ bootstrapDuration = LogDuration()+ }isBootstrapping = truesessionTransitionNotBefore = nil+ bootstrapEventCount = 0clearCollectedActivityState()case let .bootstrapEvents(events):+ bootstrapEventCount += events.countfor event in events {_ = apply(event)}- case .bootstrapEnd:+ case let .bootstrapEnd(degraded, attempts):isBootstrapping = falsesessionTransitionNotBefore = Date()refreshSnapshot(now: Date())refreshSessionLifecycleNow()backfillPromptStartTimesFromHistory()let activeCount = snapshot.activeCount- AppLog.activity.notice("历史回放完成: activeTasks=\(activeCount)")+ let eventCount = bootstrapEventCount+ let elapsed = bootstrapDuration.elapsed+ guard !degraded else {+ AppLog.activity.notice(+ "历史回放已降级: attempts=\(attempts); events=\(eventCount); activeTasks=\(activeCount); elapsed=\(elapsed, privacy: .public); reason=unstableBoundary; action=skipHistory"+ )+ return+ }++ AppLog.activity.notice(+ "历史回放完成: attempts=\(attempts); events=\(eventCount); activeTasks=\(activeCount); elapsed=\(elapsed, privacy: .public)"+ )case let .live(events):let pendingKeysBefore = Set(pendingTerminalTasks.keys)let activeCountBefore = snapshot.activeCount@@ -304,7 +335,7 @@ final class CodexActivityMonitor: ObservableObject {let activeCountAfter = snapshot.activeCountif activeCountAfter != activeCountBefore || !transitions.isEmpty {AppLog.activity.notice(- "任务状态变化: from=\(activeCountBefore); to=\(activeCountAfter); transitions=\(transitions.count)"+ "任务数变化: from=\(activeCountBefore); to=\(activeCountAfter); transitions=\(transitions.count)")}publishLiveTransitions(transitions)diff --git a/CodexBar/Services/Workflow/HookEventTailReader.swift b/CodexBar/Services/Workflow/HookEventTailReader.swiftindex babda9a..5948323 100644--- a/CodexBar/Services/Workflow/HookEventTailReader.swift+++ b/CodexBar/Services/Workflow/HookEventTailReader.swift@@ -3,7 +3,9 @@ import Foundationnonisolated enum HookEventBatch {case bootstrapStartcase bootstrapEvents([WorkflowHookEvent])- case bootstrapEnd+ /// degraded 表示放弃回放直接跳到文件末尾, 这一轮的活跃任务是空的而不是真的没有+ /// attempts 由 reader 给出, 它才知道循环跑了几轮以及放弃时补发过一次清场+ case bootstrapEnd(degraded: Bool, attempts: Int)case live([WorkflowHookEvent])}@@ -86,7 +88,7 @@ actor HookEventTailReader {}private func bootstrapRecentActivity() async {- for _ in 0 ..< Self.bootstrapAttemptLimit {+ for attempt in 0 ..< Self.bootstrapAttemptLimit {guard isRunning, !Task.isCancelled else {return}@@ -94,19 +96,20 @@ actor HookEventTailReader {activeDateKey = result.activeDateKeyactiveFileOffset = result.activeFileOffsetactiveFileIdentifier = result.activeFileIdentifier- await onBatch(.bootstrapEnd)+ await onBatch(.bootstrapEnd(degraded: false, attempts: attempt + 1))return}}// 连续读取失败时清空恢复态并跳过当前已有字节, 避免稍后误当 live 发送历史通知+ // 代价是丢掉最多 24 小时的任务状态, 所以要让下游知道这一轮是降级而不是真的没有历史let dateKey = WorkflowStorage.dateKey(for: Date())let stat = WorkflowStorage.fileStat(at: WorkflowStorage.eventLogURL(for: dateKey))activeDateKey = dateKeyactiveFileOffset = stat?.size ?? 0activeFileIdentifier = stat?.identifierawait onBatch(.bootstrapStart)- await onBatch(.bootstrapEnd)+ await onBatch(.bootstrapEnd(degraded: true, attempts: Self.bootstrapAttemptLimit))}private func bootstrapAttempt(now: Date) async -> BootstrapResult? {diff --git a/CodexBar/Services/Workflow/WorkflowService.swift b/CodexBar/Services/Workflow/WorkflowService.swiftindex 9bad80b..41f251d 100644--- a/CodexBar/Services/Workflow/WorkflowService.swift+++ b/CodexBar/Services/Workflow/WorkflowService.swift@@ -4,6 +4,35 @@ import Darwinimport Foundationimport os+/// 汇总失败时定位到哪一步, 只用于日志+private nonisolated enum MaintenanceStage: String {+ case prepare+ case write+ case prune+}++/// 一轮汇总的计数, 成功路径压进 WorkflowSyncScheduler 的收尾那一条日志, 不为每天单独记一行+/// dates 由三个分支相加得出, 不额外存一份+nonisolated struct WorkflowMaintenanceCounts {+ var events = 0+ var written = 0+ var skipped = 0+ var failed = 0+ var pruned = 0+ var dateRange = "-"+ /// 这条之前连续空转了多少轮, 用来确认静默期是没事干而不是没跑+ var idle = 0++ var dates: Int {+ written + skipped + failed+ }++ /// 这一轮有没有真的改变过状态+ var hasWork: Bool {+ dates > 0 || pruned > 0+ }+}+/// 从 Hook 原始事件维护每日聚合, 对外只发布 UI 需要的统计快照actor WorkflowService {private let eventsDirectoryURL: URL@@ -11,6 +40,8 @@ actor WorkflowService {private let syncService: WorkflowSyncService/// 上次归一化时 daily.jsonl 的 stat 与当天日期键private var lastNormalizedDailyLog: WorkflowDailyLogStamp?+ /// 上一条维护日志之后连续空转的轮数, 记出去就清零+ private var idleMaintenanceRounds = 0private static let eventReadChunkSize = 64 * 1024init(@@ -24,25 +55,34 @@ actor WorkflowService {}func loadSnapshot(- performMaintenance: Bool = false,- synchronize: Bool = false+ synchronize: Bool = false,+ trigger: LogTrigger = .auto) async -> WorkflowSnapshot {- if performMaintenance {- performMaintenanceIfNeeded()- }-- return await makeSnapshot(+ await makeSnapshot(localAggregates: loadDailyAggregates() ?? [],- synchronize: synchronize+ synchronize: synchronize,+ trigger: trigger)}+ /// 先跑一轮维护再取快照+ /// counts 为 nil 表示这一轮空转, 由调用方决定记不记日志+ func loadSnapshotWithMaintenance(+ synchronize: Bool,+ trigger: LogTrigger+ ) async -> (snapshot: WorkflowSnapshot, counts: WorkflowMaintenanceCounts?) {+ let counts = performMaintenanceIfNeeded()+ let snapshot = await loadSnapshot(synchronize: synchronize, trigger: trigger)+ return (snapshot, counts)+ }+private func makeSnapshot(localAggregates: [WorkflowDailyAggregate],- synchronize: Bool+ synchronize: Bool,+ trigger: LogTrigger) async -> WorkflowSnapshot {let syncSnapshot: WorkflowSyncSnapshot = if synchronize {- await syncService.synchronizeIfEnabled(localAggregates: localAggregates)+ await syncService.synchronizeIfEnabled(localAggregates: localAggregates, trigger: trigger)} else {await syncService.snapshotFromCacheIfEnabled()}@@ -63,6 +103,7 @@ actor WorkflowService {for dateKeys: [String],synchronize: Bool) async throws -> WorkflowDataRebuildOutcome {+ let duration = LogDuration()let normalizedDateKeys = Set(dateKeys).sorted()guard !normalizedDateKeys.isEmpty else {throw WorkflowDataRebuildError.sourceUnavailable@@ -79,7 +120,7 @@ actor WorkflowService {} catch {// 整批成功时这个原因不会往上抛, 摘要只带得走日期AppLog.workflow.error(- "重建失败: date=\(dateKey, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"+ "数据重建失败: stage=date; date=\(dateKey, privacy: .public); detail=\(error.localizedDescription, privacy: .public)")failedDateKeys.append(dateKey)if firstFailure == nil {@@ -96,7 +137,7 @@ actor WorkflowService {try await syncService.markReplacementNeeded(for: normalizedDateKeys)} catch {AppLog.workflow.error(- "登记待替换记录失败: dates=\(normalizedDateKeys.count); detail=\(error.localizedDescription, privacy: .public)"+ "数据重建失败: stage=replacementMarking; dates=\(normalizedDateKeys.count); detail=\(error.localizedDescription, privacy: .public)")didFailReplacementMarking = true}@@ -106,9 +147,11 @@ actor WorkflowService {throw firstFailure ?? WorkflowDataRebuildError.sourceUnavailable}+ // 重建只由设置页的用户操作发起let snapshot = await makeSnapshot(localAggregates: loadDailyAggregates() ?? [],- synchronize: synchronize+ synchronize: synchronize,+ trigger: .manual)let summary = await WorkflowDataRebuildSummary(rebuiltDateCount: rebuildResults.count,@@ -118,8 +161,9 @@ actor WorkflowService {failedDateKeys: failedDateKeys,didFailSyncReplacementMarking: didFailReplacementMarking)+ let elapsed = duration.elapsedAppLog.workflow.notice(- "重建完成: dates=\(summary.rebuiltDateCount); events=\(summary.eventCount); corruptLines=\(summary.corruptLineCount); failedDates=\(failedDateKeys.count)"+ "数据重建完成: dates=\(summary.rebuiltDateCount); events=\(summary.eventCount); corruptLines=\(summary.corruptLineCount); failedDates=\(failedDateKeys.count); elapsed=\(elapsed, privacy: .public)")return WorkflowDataRebuildOutcome(snapshot: snapshot, summary: summary)}@@ -198,38 +242,76 @@ actor WorkflowService {}) ?? false}- private func performMaintenanceIfNeeded() {+ /// 空转的一轮返回 nil+ /// 它跟着每 60 秒的额度刷新跑, 无条件记会让空闲机器每天多出上千条没有信息的日志+ /// 收尾日志由 WorkflowSyncScheduler 统一记, 这里只负责判断有没有值得记的东西+ private func performMaintenanceIfNeeded() -> WorkflowMaintenanceCounts? {+ let duration = LogDuration()+ var counts = WorkflowMaintenanceCounts()+ var stage = MaintenanceStage.preparedo {let tasks = try prepareMaintenanceTasks()- let didWriteDailyLog = perform(tasks)+ stage = .write+ let didWriteDailyLog = perform(tasks, counts: &counts)// 每次落盘前都已整体归一化, 写入过就不必再做一轮全量解码比对if !didWriteDailyLog {try normalizeDailyAggregatesIfNeeded()}- try pruneExpiredEventFiles()+ stage = .prune+ counts.pruned = try pruneExpiredEventFiles()} catch {+ let elapsed = duration.elapsedAppLog.workflow.error(- "维护未完成: detail=\(error.localizedDescription, privacy: .public)"+ "事件汇总失败: stage=\(stage.rawValue, privacy: .public); elapsed=\(elapsed, privacy: .public); detail=\(error.localizedDescription, privacy: .public)")- return+ idleMaintenanceRounds = 0+ return nil}++ guard counts.hasWork else {+ idleMaintenanceRounds += 1+ return nil+ }++ counts.idle = idleMaintenanceRounds+ idleMaintenanceRounds = 0+ return counts}/// 返回是否写入过 daily.jsonl; 批次内共享同一份内存聚合, 避免每个任务重新读盘- private func perform(_ tasks: [WorkflowMaintenanceTask]) -> Bool {- guard !tasks.isEmpty else {+ private func perform(+ _ tasks: [WorkflowMaintenanceTask],+ counts: inout WorkflowMaintenanceCounts+ ) -> Bool {+ // 任务是 dirty 与 pending 两段拼接, 只在各自半边有序, 取首尾会得到反向区间+ let dateKeys = tasks.map(\.dateKey)+ guard let oldestDateKey = dateKeys.min(),+ let newestDateKey = dateKeys.max() else {return false}+ counts.dateRange = oldestDateKey == newestDateKey+ ? oldestDateKey+ : oldestDateKey + ".." + newestDateKey+var aggregates = loadDailyAggregates() ?? []var didWrite = falsefor task in tasks {do {let result = try buildDailyAggregate(for: task)- didWrite = try commit(result, aggregates: &aggregates) || didWrite+ if try commit(result, aggregates: &aggregates) {+ didWrite = true+ counts.written += 1+ // 记本轮新摄入的量; 累加 eventCount 会变成当日总数, Hook 停写也看不出来+ // dirty 任务没有 base, 差值即整天重算的量, 与"这轮处理了多少"仍然一致+ counts.events += result.aggregate.eventCount - (task.baseAggregate?.eventCount ?? 0)+ } else {+ counts.skipped += 1+ }} catch {+ counts.failed += 1AppLog.workflow.error(- "聚合失败, 已标记待重建: date=\(task.dateKey, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"+ "事件汇总失败: stage=daily; date=\(task.dateKey, privacy: .public); detail=\(error.localizedDescription, privacy: .public); action=markDirty")markDirty(task.dateKey)}@@ -753,14 +835,22 @@ actor WorkflowService {}private func markDirty(_ dateKey: String) {- try? WorkflowStorage.withExclusiveLock {- var state = WorkflowStorage.loadMaintenanceState()- state.markDirty(dateKey)- try WorkflowStorage.saveMaintenanceState(state)+ do {+ try WorkflowStorage.withExclusiveLock {+ var state = WorkflowStorage.loadMaintenanceState()+ state.markDirty(dateKey)+ try WorkflowStorage.saveMaintenanceState(state)+ }+ } catch {+ // 标记丢了下一轮就不会重建这天, 数据会静默缺一块+ AppLog.workflow.error(+ "事件汇总失败: stage=markDirty; date=\(dateKey, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"+ )}}- private func pruneExpiredEventFiles() throws {+ @discardableResult+ private func pruneExpiredEventFiles() throws -> Int {let cutoffDate = WorkflowStorage.retentionCutoffDate()let expiredDateKeys = eventDateKeys().filter { dateKey inguard let date = CodexDateFormat.dayDate(from: dateKey) else {@@ -771,7 +861,7 @@ actor WorkflowService {}guard !expiredDateKeys.isEmpty else {- return+ return 0}try WorkflowStorage.withExclusiveLock {@@ -785,8 +875,9 @@ actor WorkflowService {}// 保留期到点会真的删掉原始事件文件, 数据对不上时要能查到哪些日期被清掉了AppLog.workflow.notice(- "已清理过期事件文件: dates=\(expiredDateKeys.count); oldest=\(expiredDateKeys.first ?? "-", privacy: .public)"+ "过期事件已清理: dates=\(expiredDateKeys.count); oldest=\(expiredDateKeys.first ?? "-", privacy: .public)")+ return expiredDateKeys.count}private func keepsIdentifiers(for dateKey: String) -> Bool {@@ -1318,20 +1409,25 @@ final class WorkflowViewModel: ObservableObject {}/// 由 WorkflowSyncScheduler 串行调度, 无需自行判断并发, 只执行一次明确的维护刷新- func refreshMaintenance(synchronize: Bool) async {+ /// 返回这一轮的维护计数, 空转为 nil; 收尾日志由调用方按它决定记不记+ func refreshMaintenance(+ synchronize: Bool,+ trigger: LogTrigger+ ) async -> WorkflowMaintenanceCounts? {refreshCoordinator.cancel()isRefreshing = truedefer {isRefreshing = false}- let snapshot = await service.loadSnapshot(- performMaintenance: true,- synchronize: synchronize+ let result = await service.loadSnapshotWithMaintenance(+ synchronize: synchronize,+ trigger: trigger)- self.snapshot = snapshot+ snapshot = result.snapshotlastRefreshedAt = Date()+ return result.counts}func rebuildData(diff --git a/CodexBar/Services/Workflow/WorkflowSyncScheduler.swift b/CodexBar/Services/Workflow/WorkflowSyncScheduler.swiftindex 6143635..74b3e7a 100644--- a/CodexBar/Services/Workflow/WorkflowSyncScheduler.swift+++ b/CodexBar/Services/Workflow/WorkflowSyncScheduler.swift@@ -10,43 +10,51 @@ final class WorkflowSyncScheduler {private static let syncCooldown: TimeInterval = 8private let viewModel: WorkflowViewModel- private let canSynchronize: () -> Bool+ private let syncActivation: () -> WorkflowSyncActivationprivate var isRunning = false- private var pendingSync = false- private var pendingLocalMaintenance = falseprivate var pendingRebuild: RebuildRequest?private var cooldownTask: Task<Void, Never>?private var lastSyncFinishedAt: Date?+ /// 请求会被合并成一次执行, 触发来源跟着一起排队, 非 nil 即代表有一个请求在等+ /// 合并时保留先到的那个, 它才是这一轮真正的起因+ private var pendingSyncTrigger: LogTrigger?+ private var pendingMaintenanceTrigger: LogTrigger?init(viewModel: WorkflowViewModel,- canSynchronize: @escaping () -> Bool+ syncActivation: @escaping () -> WorkflowSyncActivation) {self.viewModel = viewModel- self.canSynchronize = canSynchronize+ self.syncActivation = syncActivation}deinit {cooldownTask?.cancel()}- func requestMaintenance(allowsSync: Bool) {- if allowsSync, canSynchronize() {- pendingSync = true+ func requestMaintenance(allowsSync: Bool, trigger: LogTrigger) {+ if allowsSync, syncActivation().isActive {+ pendingSyncTrigger = pendingSyncTrigger ?? trigger} else {- pendingLocalMaintenance = true+ pendingMaintenanceTrigger = pendingMaintenanceTrigger ?? trigger}drain()}- func requestSync() {- guard canSynchronize() else {+ /// activation 传 nil 时现场求值+ /// 从 @Published 的订阅里调用必须显式传入: 那时属性还是旧值, 现场求值会得到刚被改掉的那个结论+ func requestSync(trigger: LogTrigger, activation overrideActivation: WorkflowSyncActivation? = nil) {+ let activation = overrideActivation ?? syncActivation()+ guard activation.isActive else {+ AppLog.sync.notice(+ "同步已跳过: trigger=\(trigger.rawValue, privacy: .public); reason=\(activation.rawValue, privacy: .public)"+ )clearPendingSync()return}- pendingSync = true+ pendingSyncTrigger = pendingSyncTrigger ?? triggerdrain()}@@ -61,14 +69,14 @@ final class WorkflowSyncScheduler {}func clearPendingSync() {- pendingSync = false+ pendingSyncTrigger = nilcancelCooldownTask()drain()}func clearPendingMaintenance() {- pendingSync = false- pendingLocalMaintenance = false+ pendingSyncTrigger = nil+ pendingMaintenanceTrigger = nilcancelCooldownTask()}@@ -88,34 +96,38 @@ final class WorkflowSyncScheduler {return}- let canSync = pendingSync && canSynchronize()- if canSync {- if remainingSyncCooldown() <= 0 {+ var syncCooldownRemaining: TimeInterval?+ if pendingSyncTrigger != nil, syncActivation().isActive {+ let remaining = remainingSyncCooldown()+ if remaining <= 0 {startMaintenance(synchronize: true)return}++ syncCooldownRemaining = remaining} else {- pendingSync = false+ pendingSyncTrigger = nilcancelCooldownTask()}- if pendingLocalMaintenance {+ if pendingMaintenanceTrigger != nil {startMaintenance(synchronize: false)return}- if canSync {- scheduleCooldownDrain(after: remainingSyncCooldown())+ if let syncCooldownRemaining {+ scheduleCooldownDrain(after: syncCooldownRemaining)}}private func startMaintenance(synchronize: Bool) {- AppLog.workflow.notice("开始维护: synchronize=\(synchronize ? 1 : 0)")+ let trigger = (synchronize ? pendingSyncTrigger : pendingMaintenanceTrigger) ?? .auto+ let duration = LogDuration()isRunning = true- pendingLocalMaintenance = false+ pendingMaintenanceTrigger = nilif synchronize {- pendingSync = false+ pendingSyncTrigger = nilcancelCooldownTask()}@@ -124,21 +136,39 @@ final class WorkflowSyncScheduler {return}- await viewModel.refreshMaintenance(synchronize: synchronize)- finishMaintenance(synchronize: synchronize)+ let counts = await viewModel.refreshMaintenance(+ synchronize: synchronize,+ trigger: trigger+ )+ finishMaintenance(+ synchronize: synchronize,+ trigger: trigger,+ duration: duration,+ counts: counts+ )}}- private func finishMaintenance(synchronize: Bool) {- AppLog.workflow.notice("维护结束: synchronize=\(synchronize ? 1 : 0)")+ private func finishMaintenance(+ synchronize: Bool,+ trigger: LogTrigger,+ duration: LogDuration,+ counts: WorkflowMaintenanceCounts?+ ) {+ logMaintenanceOutcome(+ synchronize: synchronize,+ trigger: trigger,+ duration: duration,+ counts: counts+ )isRunning = falseif synchronize {lastSyncFinishedAt = Date()}- if !canSynchronize() {- pendingSync = false+ if !syncActivation().isActive {+ pendingSyncTrigger = nilcancelCooldownTask()}@@ -148,7 +178,7 @@ final class WorkflowSyncScheduler {private func startRebuild(_ request: RebuildRequest) {isRunning = truependingRebuild = nil- let synchronize = canSynchronize()+ let synchronize = syncActivation().isActiveTask { @MainActor [weak self] inguard let self else {@@ -165,7 +195,7 @@ final class WorkflowSyncScheduler {)} catch {AppLog.workflow.error(- "重建请求失败: dates=\(request.dateKeys.count); detail=\(error.localizedDescription, privacy: .public)"+ "数据重建失败: stage=request; dates=\(request.dateKeys.count); detail=\(error.localizedDescription, privacy: .public)")result = .failure(error)}@@ -179,6 +209,27 @@ final class WorkflowSyncScheduler {}}+ /// 空转的一轮什么都没改, 跟着 60 秒额度刷新记一条会把空闲机器的日志刷没+ /// 同步自身的起止由 WorkflowSyncService 记, 这里只承载维护结果, 不给 sync 开后门+ private func logMaintenanceOutcome(+ synchronize: Bool,+ trigger: LogTrigger,+ duration: LogDuration,+ counts: WorkflowMaintenanceCounts?+ ) {+ guard let counts else {+ return+ }++ let triggerName = trigger.rawValue+ let sync = synchronize ? 1 : 0+ let range = counts.dateRange+ let elapsed = duration.elapsed+ AppLog.workflow.notice(+ "统计刷新完成: trigger=\(triggerName, privacy: .public); sync=\(sync); idle=\(counts.idle); dates=\(counts.dates); range=\(range, privacy: .public); events=\(counts.events); written=\(counts.written); skipped=\(counts.skipped); failed=\(counts.failed); pruned=\(counts.pruned); elapsed=\(elapsed, privacy: .public)"+ )+ }+private func remainingSyncCooldown() -> TimeInterval {guard let lastSyncFinishedAt else {return 0@@ -188,11 +239,20 @@ final class WorkflowSyncScheduler {return max(0, Self.syncCooldown - elapsed)}+ /// 冷却延后只在真的排上队时记一条+ /// drain 一轮会被多个入口调用, 无条件记会把一次延后刷成好几条+ /// 标题与 requestSync 的 已跳过 分开: 这里的请求冷却结束后照常执行, 不是被丢弃private func scheduleCooldownDrain(after delay: TimeInterval) {guard cooldownTask == nil else {return}+ let trigger = pendingSyncTrigger ?? .auto+ let remaining = LogDuration.seconds(delay)+ AppLog.sync.notice(+ "同步已延后: trigger=\(trigger.rawValue, privacy: .public); reason=cooldown; remaining=\(remaining, privacy: .public)"+ )+let milliseconds = max(1, Int((delay * 1000).rounded(.up)))cooldownTask = Task { @MainActor [weak self] intry? await Task.sleep(for: .milliseconds(milliseconds))diff --git a/CodexBar/Services/Workflow/WorkflowSyncService.swift b/CodexBar/Services/Workflow/WorkflowSyncService.swiftindex e94e63f..bc4e726 100644--- a/CodexBar/Services/Workflow/WorkflowSyncService.swift+++ b/CodexBar/Services/Workflow/WorkflowSyncService.swift@@ -13,6 +13,15 @@ nonisolated enum WorkflowSyncCloudKit {}}+/// 同步失败时定位到哪一步, 只用于日志+private nonisolated enum WorkflowSyncStage: String {+ case zone+ case device+ case fetch+ case upload+ case prune+}+/// 将本机 daily.jsonl 的脱敏聚合行同步到 CloudKit private databaseactor WorkflowSyncService {private let database: CKDatabase@@ -65,12 +74,19 @@ actor WorkflowSyncService {}func synchronizeIfEnabled(- localAggregates: [WorkflowDailyAggregate]+ localAggregates: [WorkflowDailyAggregate],+ trigger: LogTrigger) async -> WorkflowSyncSnapshot {guard WorkflowSyncSettings.isEnabled() else {+ AppLog.sync.notice(+ "同步已跳过: trigger=\(trigger.rawValue, privacy: .public); reason=syncOff"+ )return .disabled}+ AppLog.sync.notice("同步开始: trigger=\(trigger.rawValue, privacy: .public)")+ let duration = LogDuration()+ var stage = WorkflowSyncStage.zonevar didSucceed = falsevar failureMessage: String?Self.postSyncNotification(.workflowSyncDidStart)@@ -86,50 +102,52 @@ actor WorkflowSyncService {do {try await ensureSyncZoneExists()+ stage = .devicelet deviceId = try await resolveCurrentDeviceId()try resetStateIfDeviceChanged(deviceId, state: &state)try await migrateStateIfNeeded(&state)+ stage = .fetchlet localByDate = Self.syncedAggregatesByDate(localAggregates)- if state.replacementDates.isEmpty {- try await refreshCacheFromRemote()- } else {- // 替换前全量拉取, 避免增量缓存遗漏同设备同日期的旧 generation- try await rebuildCacheFromRemote()- try await preparePendingReplacements(- localByDate: localByDate,- deviceId: deviceId,- state: &state- )- }+ try await refreshCacheBeforeUpload(+ localByDate: localByDate,+ deviceId: deviceId,+ state: &state+ )+ stage = .uploadlet forceBackfill = WorkflowSyncSettings.needsBackfill()let confirmedDates = try await uploadChangedAggregates(localByDate: localByDate,remoteRecords: loadCachedRecords(),state: &state)-- let completedReplacementDates = Set(state.replacementDates).intersection(confirmedDates)- if !completedReplacementDates.isEmpty {- state.replacementDates.removeAll { completedReplacementDates.contains($0) }- try saveState(state)- }-- if forceBackfill,- backfillCompleted(localByDate: localByDate, confirmedDates: confirmedDates) {- WorkflowSyncSettings.clearBackfillRequest()- }+ try finalizeUpload(+ confirmedDates: confirmedDates,+ localByDate: localByDate,+ forceBackfill: forceBackfill,+ state: &state+ )try await refreshCacheFromRemote()- try await pruneCurrentDeviceRecordsIfNeeded(deviceId: deviceId, state: &state)+ stage = .prune+ let deletedCount = try await pruneCurrentDeviceRecordsIfNeeded(+ deviceId: deviceId,+ state: &state+ )try saveState(state)didSucceed = true- AppLog.sync.notice("同步完成")+ // confirmed 是本地与远端已对齐的日期数, 含哈希未变而无需上传的那些+ // 它小于 local 就说明这一轮还有日期没落到云上+ let elapsed = duration.elapsed+ AppLog.sync.notice(+ "同步完成: trigger=\(trigger.rawValue, privacy: .public); local=\(localByDate.count); confirmed=\(confirmedDates.count); deleted=\(deletedCount); elapsed=\(elapsed, privacy: .public)"+ )} catch {let reason = WorkflowSyncFailureReason.classify(error)+ let elapsed = duration.elapsedAppLog.sync.error(- "同步失败: reason=\(reason.rawValue, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"+ "同步失败: trigger=\(trigger.rawValue, privacy: .public); stage=\(stage.rawValue, privacy: .public); elapsed=\(elapsed, privacy: .public); reason=\(reason.rawValue, privacy: .public); detail=\(error.localizedDescription, privacy: .public)")invalidateAccountScopedCaches()failureMessage = reason.message@@ -140,6 +158,43 @@ actor WorkflowSyncService {return snapshot(from: latestState)}+ private func refreshCacheBeforeUpload(+ localByDate: [String: LocalSyncAggregate],+ deviceId: String,+ state: inout WorkflowSyncState+ ) async throws {+ guard !state.replacementDates.isEmpty else {+ try await refreshCacheFromRemote()+ return+ }++ // 替换前全量拉取, 避免增量缓存遗漏同设备同日期的旧 generation+ try await rebuildCacheFromRemote()+ try await preparePendingReplacements(+ localByDate: localByDate,+ deviceId: deviceId,+ state: &state+ )+ }++ private func finalizeUpload(+ confirmedDates: Set<String>,+ localByDate: [String: LocalSyncAggregate],+ forceBackfill: Bool,+ state: inout WorkflowSyncState+ ) throws {+ let completedReplacementDates = Set(state.replacementDates).intersection(confirmedDates)+ if !completedReplacementDates.isEmpty {+ state.replacementDates.removeAll { completedReplacementDates.contains($0) }+ try saveState(state)+ }++ if forceBackfill,+ backfillCompleted(localByDate: localByDate, confirmedDates: confirmedDates) {+ WorkflowSyncSettings.clearBackfillRequest()+ }+ }+private func resetStateIfDeviceChanged(_ deviceId: String,state: inout WorkflowSyncState@@ -297,16 +352,19 @@ private extension WorkflowSyncService {return []}+ // 每个日期的 hash 是一次 JSON 编码加 SHA256, 本轮只算一次+ // 既用来判定"和上次一样不必上传", 也直接填进待上传项+ let localHashByDate = try localByDate.mapValues { try hash(for: $0.aggregate) }+var confirmedDates = Set<String>()- for (date, local) in localByDate {- if try hash(for: local.aggregate) == state.hashByDate[date] {- confirmedDates.insert(date)- }+ for (date, hash) in localHashByDate where state.hashByDate[date] == hash {+ confirmedDates.insert(date)}- let pendingUploads = try makePendingUploads(+ let pendingUploads = makePendingUploads(for: Set(localByDate.keys),localByDate: localByDate,+ localHashByDate: localHashByDate,state: state)guard !pendingUploads.isEmpty else {@@ -431,18 +489,17 @@ private extension WorkflowSyncService {try saveState(state)}+ /// hash 由调用方一次算好传进来, 这里只做筛选func makePendingUploads(for candidateDates: Set<String>,localByDate: [String: LocalSyncAggregate],+ localHashByDate: [String: String],state: WorkflowSyncState- ) throws -> [PendingUpload] {- try candidateDates.compactMap { date in- guard let local = localByDate[date] else {- return nil- }-- let hash = try hash(for: local.aggregate)- guard state.hashByDate[date] != hash else {+ ) -> [PendingUpload] {+ candidateDates.compactMap { date in+ guard let local = localByDate[date],+ let hash = localHashByDate[date],+ state.hashByDate[date] != hash else {return nil}@@ -456,6 +513,74 @@ private extension WorkflowSyncService {.sorted { $0.date < $1.date }}+ /// 单条待上传记录落到哪个 CKRecord 上, 或者本轮不需要上传+ private enum UploadTarget {+ case skip+ case save(CKRecord)+ }++ /// 远端已有更完整的同源聚合, 或者同日已有记录且本地不是新鲜来源时都不覆盖+ private func resolveUploadTarget(+ _ pendingRecord: PendingRecord,+ deviceId: String,+ remoteRecords: [WorkflowSyncedDailyRecord],+ existingRecords: [CKRecord.ID: Result<CKRecord, any Error>]+ ) throws -> UploadTarget {+ let legacyRecord = try Self.fetchedRecord(+ from: existingRecords[pendingRecord.legacyRecordID]+ )+ let generationRecord: CKRecord? = if let recordID = pendingRecord.generationRecordID {+ try Self.fetchedRecord(from: existingRecords[recordID])+ } else {+ nil+ }+ let fetchedRecords = [legacyRecord, generationRecord].compactMap(\.self)+ let matchingRecord = fetchedRecords.first { record in+ guard let remote = Self.remoteDailyRecord(from: record) else {+ return false+ }+ return pendingRecord.upload.aggregate.matchesRemoteSource(remote.daily)+ }++ if let matchingRecord,+ let remoteAggregate = Self.remoteDailyRecord(from: matchingRecord)?.daily,+ remoteAggregate.eventCount > pendingRecord.upload.aggregate.eventCount,+ pendingRecord.upload.aggregate.sourceGeneration != nil {+ return .skip+ }++ if let matchingRecord {+ return .save(matchingRecord)+ }++ // 上面两个分支都用不到它; 放在早退之后, 命中缓存的那些 pending 就不必扫一遍全量远端记录+ var knownRemoteRecords = remoteRecords.filter {+ $0.deviceId == deviceId && $0.date == pendingRecord.upload.date+ }+ for record in fetchedRecords.compactMap({ Self.remoteDailyRecord(from: $0) })+ where !knownRemoteRecords.contains(where: { $0.id == record.id }) {+ knownRemoteRecords.append(record)+ }++ if knownRemoteRecords.isEmpty {+ return .save(CKRecord(+ recordType: RecordTypes.dailyAggregate,+ recordID: pendingRecord.generationRecordID ?? pendingRecord.legacyRecordID+ ))+ }++ if pendingRecord.upload.sourceIsFresh,+ let generationRecordID = pendingRecord.generationRecordID,+ generationRecord == nil {+ return .save(CKRecord(+ recordType: RecordTypes.dailyAggregate,+ recordID: generationRecordID+ ))+ }++ return .skip+ }+func processUploadBatch(_ pendingUploads: [PendingUpload],deviceId: String,@@ -478,34 +603,13 @@ private extension WorkflowSyncService {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 {+ switch try resolveUploadTarget(+ pendingRecord,+ deviceId: deviceId,+ remoteRecords: remoteRecords,+ existingRecords: existingRecords+ ) {+ case .skip:confirmedHashes.append(ConfirmedHash(date: pendingRecord.upload.date,@@ -513,39 +617,12 @@ private extension WorkflowSyncService {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+ case let .save(record):+ apply(pendingRecord.upload.aggregate, deviceId: deviceId, to: record)+ recordsToSave.append(+ RecordToSave(upload: pendingRecord.upload, record: record))- } else {- confirmedHashes.append(- ConfirmedHash(- date: pendingRecord.upload.date,- hash: pendingRecord.upload.hash,- didUpload: false- )- )- continue}-- apply(pendingRecord.upload.aggregate, deviceId: deviceId, to: record)- recordsToSave.append(- RecordToSave(upload: pendingRecord.upload, record: record)- )}guard !recordsToSave.isEmpty else {@@ -595,7 +672,7 @@ private extension WorkflowSyncService {} catch {// 增量拉取退化成全量重建, 代价高得多, 反复出现说明游标或缓存有问题AppLog.sync.notice(- "增量拉取失败, 改为全量重建: detail=\(error.localizedDescription, privacy: .public)"+ "增量拉取已降级: detail=\(error.localizedDescription, privacy: .public); action=fullRebuild")try await rebuildCacheFromRemote()}@@ -721,7 +798,7 @@ private extension WorkflowSyncService {} catch {// 丢掉游标, 下次同步会从头拉一遍AppLog.sync.notice(- "建立游标基线失败, 已丢弃游标: detail=\(error.localizedDescription, privacy: .public)"+ "游标基线已降级: detail=\(error.localizedDescription, privacy: .public); action=dropCursor")try? fileManager.removeItem(at: cursorURL)}@@ -753,13 +830,14 @@ private extension WorkflowSyncService {}}+ @discardableResultfunc pruneCurrentDeviceRecordsIfNeeded(deviceId: String,state: inout WorkflowSyncState- ) async throws {+ ) async throws -> Int {let today = WorkflowStorage.dateKey(for: Date())guard state.lastPrunedDate != today else {- return+ return 0}let cutoffKey = WorkflowStorage.dateKey(for: WorkflowStorage.retentionCutoffDate())@@ -793,6 +871,7 @@ private extension WorkflowSyncService {state.hashByDate.removeValue(forKey: date)}state.lastPrunedDate = today+ return recordIDs.count}func resolveCurrentDeviceId() async throws -> String {diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swiftindex 4880f13..6794c47 100644--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift@@ -58,7 +58,7 @@ private extension CodexStatusMenuView {isEmail: snapshot.account.hasEmail,plan: snapshot.planLabel,isRefreshing: viewModel.isRefreshing,- onRefresh: viewModel.refresh+ onRefresh: { viewModel.refresh(trigger: .manual) })activityCard@@ -69,7 +69,7 @@ private extension CodexStatusMenuView {StatusAccountCard(loadState: viewModel.loadState,isRefreshing: viewModel.isRefreshing,- onRefresh: viewModel.refresh+ onRefresh: { viewModel.refresh(trigger: .manual) })activityCardEmptyDataPanel()diff --git a/CodexBarHelper/main.swift b/CodexBarHelper/main.swiftindex d18595a..f4ef447 100644--- a/CodexBarHelper/main.swift+++ b/CodexBarHelper/main.swift@@ -14,7 +14,9 @@ private enum CodexBarHelperStorage {for: .applicationSupportDirectory,in: .localDomainMask).first else {- preconditionFailure("无法获取 Application Support 目录")+ // launchd 会立刻重新拉起来, 不留痕就成了查不出原因的崩溃循环+ helperLog.error("Helper 启动失败: reason=applicationSupportMissing")+ exit(EXIT_FAILURE)}return applicationSupportURL.appending(path: "CodexBar", directoryHint: .isDirectory)@@ -38,14 +40,24 @@ private enum SentinelState {case absentcase present(previouslyDisabled: Bool)case unreadable(Error)++ /// 读取失败也必须进入恢复流程: 记录损坏时无法排除「休眠正被我们禁用着」+ var needsRestore: Bool {+ switch self {+ case .absent:+ false+ case .present, .unreadable:+ true+ }+ }}private enum SleepRestoreTrigger: String {- case appRequest = "CodexBar 主动请求"- case connectionWatchdog = "CodexBar 连接断开"- case helperStartup = "Helper 启动恢复"- case sentinelCheck = "Helper 定时恢复"- case helperTermination = "Helper 退出恢复"+ case appRequest+ case connectionWatchdog+ case helperStartup+ case sentinelCheck+ case helperTermination}private enum PmsetRunner {@@ -113,7 +125,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Codefunc run() {guard geteuid() == 0 else {- helperLog.error("Helper 启动失败: 需要 root 身份")+ helperLog.error("Helper 启动失败: reason=notRoot")exit(EXIT_FAILURE)}@@ -122,12 +134,23 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code} catch {let sentinelDirectoryPath = sentinelURL.deletingLastPathComponent().pathhelperLog.error(- "Helper 启动失败: 无法访问休眠设置目录; path=\(sentinelDirectoryPath, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"+ "Helper 启动失败: reason=sentinelDirectory; path=\(sentinelDirectoryPath, privacy: .public); detail=\(error.localizedDescription, privacy: .public)")exit(EXIT_FAILURE)}- if sentinelNeedsRestore() {+ // 启动时哨兵还在说明上次异常退出, 这条是判断有没有残留过的起点+ // 读一次就够, 恢复判断也用这同一份结果+ let startupSentinel = sentinelState()+ let sentinelName = switch startupSentinel {+ case .absent: "absent"+ case .present: "present"+ case .unreadable: "unreadable"+ }+ helperLog.notice("Helper 已启动: sentinel=\(sentinelName, privacy: .public)")++ // 读取失败也必须进入恢复流程: 记录损坏时无法排除「休眠正被我们禁用着」+ if startupSentinel.needsRestore {_ = restoreSleep(trigger: .helperStartup)}@@ -139,7 +162,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, CodeclientCodeSigningRequirement = try Self.makeClientCodeSigningRequirement()} catch {helperLog.error(- "Helper 启动失败: \(error.localizedDescription, privacy: .public)"+ "Helper 启动失败: reason=listener; detail=\(error.localizedDescription, privacy: .public)")exit(EXIT_FAILURE)}@@ -219,22 +242,24 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Codeprivate func disableSleep() -> Int32 {var didCreateSentinel = false+ // 哨兵记的是接管前系统原本的 SleepDisabled, 恢复要还原到它而不是无脑写 0+ var sentinelValue = "-"switch sentinelState() {- case .present:- break+ case let .present(previouslyDisabled):+ sentinelValue = previouslyDisabled ? "1" : "0"case let .unreadable(error):// 不能用当前的 SleepDisabled 覆写损坏的记录: 当前值可能正是我们自己禁用的结果// 那会把「原本允许休眠」错记成「原本已禁用」让后续恢复永久跳过let sentinelPath = sentinelURL.pathhelperLog.error(- "休眠记录损坏: path=\(sentinelPath, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"+ "休眠哨兵损坏: path=\(sentinelPath, privacy: .public); detail=\(error.localizedDescription, privacy: .public)")return -1case .absent:let current = PmsetRunner.currentSleepDisabled()guard current.result.exitCode == 0, let wasDisabled = current.value else {helperLog.error(- "读取休眠设置失败: error=\(current.result.exitCode); detail=\(current.result.output, privacy: .public)"+ "pmset 读取失败: exit=\(current.result.exitCode); detail=\(current.result.output, privacy: .public)")return current.result.exitCode == 0 ? -1 : current.result.exitCode}@@ -242,10 +267,11 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Codedo {try writeSentinel(previouslyDisabled: wasDisabled)didCreateSentinel = true+ sentinelValue = wasDisabled ? "1" : "0"} catch {let sentinelPath = sentinelURL.pathhelperLog.error(- "保存休眠设置失败: path=\(sentinelPath, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"+ "休眠哨兵写入失败: path=\(sentinelPath, privacy: .public); detail=\(error.localizedDescription, privacy: .public)")return -1}@@ -257,12 +283,12 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Codetry? FileManager.default.removeItem(at: sentinelURL)}helperLog.error(- "关闭系统休眠失败: error=\(result.exitCode); detail=\(result.output, privacy: .public)"+ "系统休眠关闭失败: exit=\(result.exitCode); detail=\(result.output, privacy: .public)")return result.exitCode}- helperLog.notice("系统休眠已关闭: 任务正在运行")+ helperLog.notice("系统休眠已关闭: sentinel=\(sentinelValue, privacy: .public)")return 0}@@ -280,7 +306,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code// 读不出原值时按系统默认的「允许休眠」恢复// 宁可多恢复一次(pmset 幂等), 也不能把 SleepDisabled=1 永久留给用户helperLog.error(- "读取休眠记录失败: reason=\(trigger.rawValue, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"+ "休眠哨兵读取失败: trigger=\(trigger.rawValue, privacy: .public); detail=\(error.localizedDescription, privacy: .public); action=forceRestore")previouslyDisabled = false}@@ -289,7 +315,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Codelet result = PmsetRunner.setSleepDisabled(previouslyDisabled)guard result.exitCode == 0 else {helperLog.error(- "恢复系统休眠失败: reason=\(trigger.rawValue, privacy: .public); SleepDisabled=\(previousValue); error=\(result.exitCode); detail=\(result.output, privacy: .public)"+ "系统休眠恢复失败: trigger=\(trigger.rawValue, privacy: .public); sleepDisabled=\(previousValue); exit=\(result.exitCode); detail=\(result.output, privacy: .public)")return SleepRestoreResult(exitCode: result.exitCode,@@ -299,7 +325,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Codetry? FileManager.default.removeItem(at: sentinelURL)helperLog.notice(- "系统休眠已恢复: reason=\(trigger.rawValue, privacy: .public); SleepDisabled=\(previousValue)"+ "系统休眠已恢复: trigger=\(trigger.rawValue, privacy: .public); sleepDisabled=\(previousValue)")return SleepRestoreResult(exitCode: 0,@@ -410,14 +436,8 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code}}- /// 读取失败也必须进入恢复流程: 记录损坏时无法排除「休眠正被我们禁用着」private func sentinelNeedsRestore() -> Bool {- switch sentinelState() {- case .absent:- false- case .present, .unreadable:- true- }+ sentinelState().needsRestore}private func readSentinelPreviousState() throws -> Bool? {diff --git a/appcast.xml b/appcast.xmlindex 9bd997b..68f3ba3 100644--- a/appcast.xml+++ b/appcast.xml@@ -7,6 +7,15 @@<link>https://codexbar.zabrian.app/appcast.xml</link><description>CodexBar appcast feed</description><language>zh-CN</language>+ <item>+ <title>CodexBar.app 3.5.6</title>+ <sparkle:version>60</sparkle:version>+ <sparkle:shortVersionString>3.5.6</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.5.6</sparkle:releaseNotesLink>+ <pubDate>Wed, 29 Jul 2026 11:41:16 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.5.6.dmg" sparkle:edSignature="WNs2hQy/XsKr7YVt5oVBFy0Dw/iTP5RHt/jQBB1mWeho7Bh511e5aAWIf7tE1ql47Y5x10NhqpEwX/zKieQjBg==" length="5944501" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 3.5.5</title><sparkle:version>59</sparkle:version>