CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
docs: 校准代码注释并明确关键运行边界
Bob1595fd6fcff2
diff --git a/CodexBar/App/CodexBarAppDelegate.swift b/CodexBar/App/CodexBarAppDelegate.swiftindex 4394eb6..e93736c 100644--- a/CodexBar/App/CodexBarAppDelegate.swift+++ b/CodexBar/App/CodexBarAppDelegate.swift@@ -78,7 +78,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {)autoResetController.start()self.autoResetController = autoResetController- // 低电量触发会中断正在跑的任务, 得让用户知道是谁干的+ // 低电量保护会解除防睡眠, 通知说明恢复系统睡眠策略的原因keepAliveController.onLowBatteryTriggered = { [weak notificationService] percent inawait notificationService?.notifyLowBatteryProtection(percent: percent) ?? false}diff --git a/CodexBar/Controllers/SidePanelPresenter.swift b/CodexBar/Controllers/SidePanelPresenter.swiftindex 69759a1..0f05bce 100644--- a/CodexBar/Controllers/SidePanelPresenter.swift+++ b/CodexBar/Controllers/SidePanelPresenter.swift@@ -237,8 +237,8 @@ final class SidePanelDrawerPresenter {// MARK: - 内容宿主-/// 侧边面板的内容宿主: 懒建 panel + hostingController, 统一"替换 rootView → configureLayers → setContentSize"的更新序列-/// ⚠️ 每次更新都整树替换 rootView 是刻意行为 (见 CLAUDE.md 热力图详情面板的说明), 不要改成常驻状态推送+/// 侧边面板按展示快照替换 rootView, 内容与面板尺寸在同一次更新中同步+/// 替换内容后重新配置图层, 保持圆角裁剪与透明背景一致@MainActorfinal class SidePanelContentHost<Root: View> {private(set) var panel: NSPanel?diff --git a/CodexBar/Controllers/SidePanelSupport.swift b/CodexBar/Controllers/SidePanelSupport.swiftindex d4ebb2e..dc46f1e 100644--- a/CodexBar/Controllers/SidePanelSupport.swift+++ b/CodexBar/Controllers/SidePanelSupport.swift@@ -148,8 +148,7 @@ enum SidePanelSupport {)}- /// 锚点对齐的完整定位: 先按锚点收窄可见区域, 再算出对齐锚点顶边的 y, 最后交给 position 夹紧- /// 三步顺序固定且必须一致, 拆开写过一次就会出现第二份, 加参数时也只会改到其中一份+ /// 先按锚点调整可见区域, 再对齐锚点顶边并限制面板位置, 避免定位结果受菜单栏保留区域干扰static func anchoredPosition(panelSize: CGSize,menuSurfaceFrame: CGRect,diff --git a/CodexBar/Models/AppServerEventRecord.swift b/CodexBar/Models/AppServerEventRecord.swiftindex a09126a..7589190 100644--- a/CodexBar/Models/AppServerEventRecord.swift+++ b/CodexBar/Models/AppServerEventRecord.swift@@ -1,11 +1,12 @@import Foundation-/// 数据库仅保存活动事实和 Token 原始观测, 派生快照不能作为重建来源+/// 事件记录保存活动事实和 Token 原始观测, 聚合重建以这些记录为来源nonisolated struct AppServerEventRecord: Codable, Equatable {enum Kind: String, Codable { case activityData, tokenUsage }static let schemaVersion = 1let schemaVersion: Int+ /// 采集记录的时间, 历史回填时可能晚于业务事件时间let recordedAt: Datelet context: ActivityDataContext?private let storedActivityData: ActivityDataRecord?diff --git a/CodexBar/Services/Activity/ActivityMonitor.swift b/CodexBar/Services/Activity/ActivityMonitor.swiftindex cae93d6..b3131e7 100644--- a/CodexBar/Services/Activity/ActivityMonitor.swift+++ b/CodexBar/Services/Activity/ActivityMonitor.swift@@ -484,7 +484,7 @@ final class ActivityMonitor: ObservableObject {.sorted(by: Self.recentFirst(\.lastActivityAt, \.displayID))}- /// 时间相同再按 UUID 字符串排序(Swift sort 不稳定), 保证快照对 SwiftUI diff 稳定+ /// 时间相同时按 UUID 排序, 避免字典遍历顺序变化导致快照重排private static func recentFirst<Element>(_ date: KeyPath<Element, Date>,_ id: KeyPath<Element, UUID>diff --git a/CodexBar/Services/Activity/AppServerActivityBackfill.swift b/CodexBar/Services/Activity/AppServerActivityBackfill.swiftindex 408f8d3..8426310 100644--- a/CodexBar/Services/Activity/AppServerActivityBackfill.swift+++ b/CodexBar/Services/Activity/AppServerActivityBackfill.swift@@ -19,6 +19,7 @@ actor AppServerActivityBackfill {}func readPage(reference: ActivityTurnReference, cursor: String?, limit: Int, timeout: TimeInterval) throws -> Page {+ // 缩小分页后的重试共用本次截止时间, 避免重连反复延长读取上限let budget = AppServerRequestBudget(deadline: Date().addingTimeInterval(timeout))return try AppServerRequestBudget.$current.withValue(budget) {var connection: AppServerSession?@@ -47,6 +48,7 @@ actor AppServerActivityBackfill {return Page(items: page.data, nextCursor: page.nextCursor, limit: pageLimit)} catch let error as CodexStatusError {guard case .messageTooLarge = error else { throw error }+ // 超大消息会关闭连接, 清除旧会话后缩小分页并重新握手connection?.close()connection = nilif pageLimit > 1 {diff --git a/CodexBar/Services/AppServer/AppServerSession.swift b/CodexBar/Services/AppServer/AppServerSession.swiftindex 36c3c6f..3016d1c 100644--- a/CodexBar/Services/AppServer/AppServerSession.swift+++ b/CodexBar/Services/AppServer/AppServerSession.swift@@ -103,6 +103,8 @@ final nonisolated class AppServerSession {logStorage?.recordConnection(method: "connection/closed", detail: socketPath, connection: connectionName, status: .information)}+ /// 按服务端 userAgent 校验当前连接的实际版本, 安装版本不能代替运行中的服务版本+ /// 版本缺失或无法解析时也拒绝完成握手, 防止绕过最低版本要求@discardableResultfunc initialize(clientName: String, minimumVersion: String, timeout: TimeInterval = 10, title: String? = nil) throws -> String {var clientInfo = ["name": clientName, "version": Bundle.main.shortVersionString.flatMap { $0.isEmpty ? nil : $0 } ?? "1.0.0"]diff --git a/CodexBar/Services/Codex/CodexVersionService.swift b/CodexBar/Services/Codex/CodexVersionService.swiftindex ccae9c4..98dff62 100644--- a/CodexBar/Services/Codex/CodexVersionService.swift+++ b/CodexBar/Services/Codex/CodexVersionService.swift@@ -202,10 +202,12 @@ actor CodexVersionService {}}-/// 从 ` codex --version` 的输出中提取用户可读版本号+/// Codex 版本号的提取与语义版本比较nonisolated enum CodexVersionReader {+ /// 账户, 活动和历史回填连接共用的最低服务版本, 启动候选也按此筛选static let minimumAppServerVersion = "0.162.0"+ /// 从 `codex --version` 的输出中提取用户可读版本号static func displayVersion(from output: String) -> String {output.split(whereSeparator: \.isWhitespace)@@ -312,5 +314,3 @@ nonisolated enum CodexVersionReader {}}}--// 设置页持有的版本检测状态, 负责节流和丢弃过期刷新结果diff --git a/CodexBar/Services/Codex/CodexVersionViewModel.swift b/CodexBar/Services/Codex/CodexVersionViewModel.swiftindex d4a0c70..18f6bc7 100644--- a/CodexBar/Services/Codex/CodexVersionViewModel.swift+++ b/CodexBar/Services/Codex/CodexVersionViewModel.swift@@ -1,6 +1,7 @@import Combineimport Foundation+/// 设置页的安装版本状态, 对刷新请求节流并通过协调器丢弃过期结果@MainActorfinal class CodexVersionViewModel: ObservableObject {@Published private(set) var snapshot = CodexVersionSnapshot.emptydiff --git a/CodexBar/Services/History/HistoryDatabase.swift b/CodexBar/Services/History/HistoryDatabase.swiftindex 1929de0..b037168 100644--- a/CodexBar/Services/History/HistoryDatabase.swift+++ b/CodexBar/Services/History/HistoryDatabase.swift@@ -36,6 +36,7 @@ final nonisolated class HistoryDatabase {}struct Entry {+ /// 数据库分配的写入序号, 用于增量读取, 不表示业务事件发生顺序let position: Int64let record: AppServerEventRecord}diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swiftindex f70d57a..2fef0ba 100644--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift@@ -14,26 +14,21 @@ final class KeepAliveController: ObservableObject {@Published private(set) var lowBatteryThreshold: LowBatteryThreshold/// 是否将审批等待和明确阻塞的提问计入防睡眠@Published private(set) var keepsAwakeWhileWaiting: Bool- /// 防睡眠生效期间是否连屏幕一起留住, 顺带压住屏保与闲置锁屏+ /// 防睡眠生效期间保持屏幕常亮, 同时阻止屏保与闲置锁屏@Published private(set) var keepsDisplayAwake: Bool- /// 确认没有内置电池时为 false, 设置页据此隐藏低电量那一行+ /// 确认没有内置电池时为 false, 设置页据此隐藏低电量选项@Published private(set) var hasBattery = true- /// 当前是否因低电量而停止防睡眠, 带滞回所以不等于"电量低于阈值"- /// 会随电量自己翻转, 不需要外部清除, 与 hasReachedMaximumDuration 那种粘滞标志不是一回事+ /// 带滞回的低电量阻断状态, 随供电方式和电量恢复而解除@Published private(set) var isLowBatteryActive = false- /// 低电量保护是不是真的在起作用: 防睡眠本身可用, 阈值开着, 且这台机器确实有电池- /// 规则收在这里而不是各视图各写一遍: 通知面板要据此置灰那一行, 防睡眠面板据此决定显不显示阈值+ /// 汇总防睡眠可用性, 阈值开关和电池状态, 供设置面板统一判断低电量选项是否可用@Published private(set) var isLowBatteryProtectionEnabled = false- /// 时长上限是不是真的会到点: 防睡眠本身可用, 且没选无限制- /// 与 isLowBatteryProtectionEnabled 同一个用法, 视图只读结论, 不各自再判一次 unlimited- /// 只在功能可用性变化时发信号, 单纯调整时长不需要通知面板重算高度+ /// 防睡眠可用且已设置时长上限时为 true+ /// 只在可用性变化时发布, 避免单纯调整时长触发通知面板重算高度@Published private(set) var isMaximumDurationEnabled = false- /// 低电量是不是当下唯一拦住防睡眠的那一项- /// 由 reconcileSleepState 从 sleepBlockReason 派生, 见那里的说明+ /// 由 sleepBlockReason 派生, 表示当前优先处理的阻断原因是否为低电量@Published private(set) var isLowBatteryBlocking = false- /// 子面板入口该不该出现: 用户开关开着且依赖已就绪- /// 同样从 sleepBlockReason 派生, 于是新增阻断条件时必然要在那个 switch 里表态, 不会漏配+ /// 从 sleepBlockReason 派生子面板入口是否可用, 与防睡眠阻断规则保持一致@Published private(set) var canShowOptions = false/// 只供自动重置设置行展示, 不与防睡眠操作错误混在一起@Published private(set) var autoResetWakeScheduleErrorMessage: String?@@ -70,19 +65,16 @@ final class KeepAliveController: ObservableObject {durationLimiter.hasReached}- /// 低电量导致睡眠恢复之后回调一次, 参数是触及阈值时的电量; 由 AppDelegate 接到通知服务- /// 用事件回调而不是 @Published: 触发是一次性动作, 电量回升到解除门槛以上后再次跌破要能重新发一次+ /// 低电量导致系统睡眠策略恢复后提交通知, 参数为触及阈值时的电量+ /// 电量回升到解除门槛后才允许下一轮提醒/// 通知提交完成前保留空闲断言, 避免恢复系统策略后先进入空闲睡眠- /// 返回值是通知有没有真的发出去, 决定这一轮算不算已通知+ /// 返回值表示通知是否提交成功, 用于本轮去重var onLowBatteryTriggered: ((Int) async -> Bool)?- /// 达到防睡眠时长上限且睡眠恢复成功之后回调一次- /// 时长上限本身是粘滞状态, 每个计时周期天然只会进入一次+ /// 达到防睡眠时长上限且系统睡眠策略恢复后回调, 每个计时周期触发一次var onKeepAliveLimitTriggered: ((MaximumDuration) async -> Bool)?- /// 用户开关仍开着, 且 Power Helper 已经真的把睡眠关掉- /// isPreventingSleep 在稳态下已隐含 isEnabled (shouldDisableSleep 要求它)- /// 叠这一层是为了关开关到 Power Helper 回调之间的异步空窗: 用户意图先落地+ /// 同时检查用户开关和实际状态, 覆盖关开关后等待 Power Helper 回复的异步窗口var isActivelyPreventingSleep: Bool {isEnabled && isPreventingSleep}@@ -355,22 +347,15 @@ final class KeepAliveController: ObservableObject {reconcileSleepState(trigger: .battery)}- /// 纯条件判定: 只看当下, 不记"低过电"这笔账, 所以充上电会自动恢复- /// 滞回让解除门槛比触发门槛高一截, 否则电量在阈值附近抖动会反复切换睡眠状态- /// 读不到电量时维持上一次的判定, 两种情形各有各的理由- /// 从没读到过时保持不触发: 误触发会当场断掉用户任务, 漏触发最坏也有系统强制睡眠兜底- /// 已经在保护中时不清零: 一次瞬时失败不该让防睡眠反复开关, 那还会绕过滞回并重发通知+ /// 供电恢复或电量达到解除门槛时解除阻断, 滞回避免阈值附近反复切换+ /// 读数失败时保留上次判定, 避免无依据地解除防睡眠或绕过滞回private func updateBatteryState() {let reading = powerSourceMonitor.reading- // 读失败时维持上一次的判定, 与下面 isLowBatteryActive 同一条规则- // unreadable.hasBattery 是 true (从没读到过时按"可能有"处理), 无条件赋值会让一次- // IOKit 缺口把已确认没有电池的台式机翻回有电池, 低电量那一行跟着闪进闪出+ // unreadable 将电池视为可能存在, 不能用它覆盖已确认的无电池状态if reading != .unreadable {assign(reading.hasBattery, to: \.hasBattery)}- // 阈值与 hasBattery 都只在这条路径上变, 派生值跟着一起收在这里- // 走这里而不是等 reconcileSleepState: handlePowerSourceChange 在低电量结论没变时就返回了,- // 而 hasBattery 可能在同一次读数里刚变过+ // 电池状态可能单独变化, 不能等到低电量阻断状态变化后才刷新派生值publishNotificationDependencies()// 保护关掉了就没有可维持的状态, 这一条要排在读数判断之前@@ -391,8 +376,7 @@ final class KeepAliveController: ObservableObject {return}- // 这一轮结束的标志是电量真的回来了, 不是接上了电源- // 排在供电状态之前: 充电期间也要能收口, 否则下一次拔线还算同一轮+ // 通知周期按电量恢复结束, 在供电判断前处理, 确保充电期间也能重置去重状态if status.percent >= threshold + Self.lowBatteryHysteresis {clearPendingLowBatteryNotification()}@@ -411,8 +395,7 @@ final class KeepAliveController: ObservableObject {return}- // 百分比只在这里记录, 避免电量每次变化都触发 SleepConditions 日志- // 本来就没在挡睡眠时这一跌不改变任何事, 但仍要记: 这是排查"为什么在这个电量断的"的唯一依据+ // 仅在进入低电量状态时记录百分比, 保留触发依据并避免每次读数都产生日志let wasPreventingSleep = isActivelyPreventingSleep&& sleepPreventionSource == .codexBarlet details = LogFields.joined(@@ -422,17 +405,16 @@ final class KeepAliveController: ObservableObject {)AppLog.keepAlive.notice("KeepAlive 电量已触及阈值: \(details, privacy: .public)")- // 没挡过就不通知: "已恢复系统睡眠"会变成一句空话, 启动时电量本就偏低的机器首当其冲+ // 只有本次低电量会解除 CodexBar 的防睡眠时才通知guard wasPreventingSleep, !hasNotifiedLowBattery else {return}- // 这里只排队不发: 睡眠还没真的恢复, 恢复请求可能失败并耗尽重试+ // 等系统睡眠策略恢复成功后再通知, 此时恢复请求仍可能失败pendingLowBatteryPercent = status.percent}- /// 排队的低电量通知在睡眠真的恢复之后才发- /// 途中接上电源时拦下防睡眠的已经不是低电量, 那条通知随即作废+ /// 系统睡眠策略恢复后, 仅在低电量仍是当前阻断原因时发送排队的通知private func flushPendingLowBatteryNotification() async {guard let percent = pendingLowBatteryPercent else {return@@ -443,15 +425,12 @@ final class KeepAliveController: ObservableObject {return}- // 锁存要等通知真的发出去才打: 打在入队处或提交前, 都会让没送达的那一条吃掉整轮配额- // 使这一轮之后真正触发的低电量再也提醒不了+ // 提交成功后才标记已通知, 失败不能消耗本轮提醒机会hasNotifiedLowBattery = await onLowBatteryTriggered?(percent) ?? false}- /// 恢复睡眠成功之后按当下的拦截原因发对应的那一条, 顺带把另一条作废- /// 作废低电量只写 pendingLowBatteryPercent, 不能改走 clearPendingLowBatteryNotification:- /// 那个方法会连 hasNotifiedLowBattery 一起清, 而这一轮低电量还没结束 (电量没回到解除门槛),- /// 清了会让下一次跌破阈值重发第二条, 也就是供电状态反复翻转时每翻一次一条+ /// 系统睡眠策略恢复后按当前阻断原因发送通知, 清除另一种原因的待发通知+ /// 作废低电量通知时保留本轮去重状态, 避免供电反复切换导致重复提醒private func flushPendingSleepRestoreNotification() async {switch sleepBlockReason {case .lowBattery:@@ -1181,14 +1160,12 @@ final class KeepAliveController: ObservableObject {}}- /// Power Helper 起不来时 XPC 方法既不回复也不触发 errorHandler, 请求就那么挂着- /// 没有这道超时, 界面会显示防睡眠开着而实际没生效, 日志里只剩一条没有配对回复的请求已发送+ /// XPC 请求可能没有回复或错误回调, 用独立超时结束等待并进入失败恢复private func scheduleRequestTimeout(for requested: Bool, generation: UInt64) {requestTimeoutTask?.cancel()requestTimeoutTask = Task { @MainActor [weak self] intry? await Task.sleep(for: PowerHelperConfiguration.requestTimeout)- // 认状态而不是认取消位: 每条取消路径都同时推进了 generation 或清了 in-flight,- // 认状态就不必依赖将来每个新路径都记得 cancel+ // 取消等待后仍可能执行到这里, 仅处理代次匹配且仍在途的请求guard let self, generation == requestGeneration, requestInFlight else {return}@@ -1231,17 +1208,14 @@ final class KeepAliveController: ObservableObject {releaseSleepPrevention()}- /// assertion 与 isPreventingSleep 同进同退的唯一出口- /// 两者必须一起收: 只清标志会让菜单栏图标显示成未防睡眠, 而这条 assertion 仍在防止空闲睡眠,- /// 且没有任何后续路径会释放它; 仍需要防睡眠时由重试重建+ /// 释放空闲断言并清除防睡眠展示状态, 避免界面已关闭而断言仍生效+ /// 同时停止屏幕常亮和时长累计, 仍需防睡眠时由重试重新建立private func releaseSleepPrevention() {_ = systemSleepService.endPreventingIdleSleep()cancelExternalObservation()assign(false, to: \.isPreventingSleep)assign(.none, to: \.sleepPreventionSource)- // 空闲断言与屏幕成对: 这里之后睡眠不再被挡, 屏幕也没有留住的理由reconcileDisplayAwake()- // 收表跟着实际效果走: 这里之后睡眠不再被挡, 那段时间不该占用户的上限durationLimiter.pause()}@@ -1301,10 +1275,8 @@ final class KeepAliveController: ObservableObject {// MARK: - 屏幕常亮- /// 用户开关与防睡眠实际效果的汇合点, 两边任意一个变了都要过这里- /// 跟 isActivelyPreventingSleep 走, 于是低电量拦下, 达到上限, 任务结束时屏幕都会跟着放开- /// 失败只记日志不占 operationErrorMessage: 那个字段是睡眠切换的结论, 会顶到设置页最前面,- /// 让一个附加效果的失败显示成防睡眠本身出错+ /// 屏幕常亮同时取决于用户设置和防睡眠实际状态+ /// 屏幕操作失败仅记日志, 避免覆盖系统睡眠切换的错误结论private func reconcileDisplayAwake() {let shouldKeepAwake = keepsDisplayAwake && isActivelyPreventingSleepif shouldKeepAwake {diff --git a/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift b/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swiftindex d7e35c1..c98b247 100644--- a/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift@@ -2,12 +2,9 @@ import Combineimport Foundationimport os-/// 防睡眠的时长上限计时-/// 累计的是真正挡住睡眠的那段时间: begin 起表, pause 收表, 收表之后机器睡着或被低电量拦下都不算-/// 时钟用 SuspendingClock 而不是 Date: 后者受系统时间调整影响, 且系统睡眠期间照走-/// hasReached 是粘滞标志: 累计只增不减, 到期之后每一秒都还成立-/// 只有重新开始计时的入口能清除它, 这些清除全部收在 clearReached 里-/// 低电量那条是纯条件判定, 不要照抄这里的粘滞写法+/// 累计防睡眠生效时长, 暂停期间不计入上限+/// 使用 SuspendingClock 排除系统时间调整和睡眠时长的影响+/// 达到上限后保留 hasReached 状态, 由新计时周期或上限调整解除@MainActorfinal class KeepAliveDurationLimiter: ObservableObject {typealias Duration = KeepAliveController.MaximumDurationdiff --git a/CodexBar/Services/Notifications/NotificationService.swift b/CodexBar/Services/Notifications/NotificationService.swiftindex 916f9e5..e22bc98 100644--- a/CodexBar/Services/Notifications/NotificationService.swift+++ b/CodexBar/Services/Notifications/NotificationService.swift@@ -10,7 +10,7 @@ nonisolated enum AutoResetFailureNotice: String, Sendable {case permanent}-/// 集中式提醒服务: 订阅额度与实时活动, 负责触觉反馈; 阈值判定; 去重; 重置识别与本地通知发送+/// 订阅额度与实时活动, 统一处理提醒条件, 去重, 触觉反馈与本地通知发送@MainActorfinal class NotificationService: NSObject {private let settings: NotificationSettingsdiff --git a/CodexBar/Services/Notifications/NotificationSoundOption.swift b/CodexBar/Services/Notifications/NotificationSoundOption.swiftindex 715dd0a..53cbd2b 100644--- a/CodexBar/Services/Notifications/NotificationSoundOption.swift+++ b/CodexBar/Services/Notifications/NotificationSoundOption.swift@@ -3,8 +3,8 @@ import Foundationimport osimport UserNotifications-/// CodexBar 可用于系统通知的声音, 系统提示音按本机声音目录实时枚举, 其余随 App 打包-/// `id` 是落在 UserDefaults 里的持久化值, 系统提示音取文件名小写形式, 与旧版本的枚举值天然对齐+/// 系统提示音首次使用时从本机声音目录加载并缓存, 其余声音随 App 打包+/// id 用于持久化, 系统提示音取不含扩展名的文件名小写形式struct NotificationSoundOption: Identifiable, Hashable {let id: Stringlet localizedTitle: String@@ -21,7 +21,7 @@ struct NotificationSoundOption: Identifiable, Hashable {source: .systemDefault)- /// 分组的唯一登记点, 菜单渲染与 id 解析都从这里派生, 新增一组声音只改这一处+ /// 菜单分组与持久化 id 的解析共用同一份声音列表static let categories: [Category] = [Category(title: "System", sounds: systemSounds),Category(title: "Modern", sounds: modernSounds),@@ -41,8 +41,7 @@ struct NotificationSoundOption: Identifiable, Hashable {return categories.lazy.flatMap(\.sounds).first { $0.id == id }}- /// 通知中心解析不到声音文件时是静音而不是回落默认音, 用户只会发现通知不响却查不出原因- /// 所以这里先确认文件在位, 缺失就主动降级, 宁可换个声音也不要静默失声+ /// 声音列表会缓存, 文件可能在加载后被删除, 发送通知前检查并显式回退默认音var notificationSound: UNNotificationSound? {switch source {case .silent:@@ -66,8 +65,7 @@ struct NotificationSoundOption: Identifiable, Hashable {}}- /// 降级本身没有用户可见的痕迹, 通知照常弹出只是换了个声音, 这条日志是事后唯一的线索- /// 记 id 是定位所需, 它是选项标识而不是文件路径, 用户自定义音也只会暴露文件名本身+ /// 记录回退原因以便排查声音变化, 仅记录选项 id 和来源, 不记录完整文件路径private static func degraded(id: String, source: String) -> UNNotificationSound {let details = LogFields.joined("id=\(id)",@@ -79,8 +77,7 @@ struct NotificationSoundOption: Identifiable, Hashable {return .default}- /// 静音本就没有声音, 默认音由通知中心内部决定且不暴露文件, 两者都没有可试听的对象- /// 拿系统警告声冒充默认音会误导, 它和通知中心默认音是两个独立设置+ /// 默认音由通知中心决定, 没有对应的试听资源, 不使用系统警告声代替var isPreviewable: Bool {switch source {case .silent, .systemDefault:@@ -119,8 +116,8 @@ struct NotificationSoundOption: Identifiable, Hashable {}}- /// 系统提示音由声音目录提供, 枚举时就定下具体文件, 通知与预览都用它而不再重新搜索- /// 打包的声音出自私有框架或第三方资源包, 不在系统声音搜索路径内, 只能按 bundle 资源名解析+ /// 系统提示音保留文件 URL 供校验和试听, 发送通知时只将文件名交给系统解析+ /// 打包声音按 bundle 资源名定位, 不依赖本机声音目录private enum SoundSource: Hashable {case silentcase systemDefault@@ -187,7 +184,7 @@ struct NotificationSoundOption: Identifiable, Hashable {)}- /// 同名文件以靠前的目录为准, 与系统解析声音的顺序一致+ /// 同名选项按目录优先级去重, 保留最先找到的文件private static func loadSystemSounds() -> [NotificationSoundOption] {var seen = reservedIDsvar sounds: [NotificationSoundOption] = []diff --git a/CodexBar/Services/Support/AppLog.swift b/CodexBar/Services/Support/AppLog.swiftindex 87c5919..0a3a72c 100644--- a/CodexBar/Services/Support/AppLog.swift+++ b/CodexBar/Services/Support/AppLog.swift@@ -34,8 +34,7 @@ nonisolated enum LogFields {}}-/// 一次操作的触发来源, 作为日志里的 trigger 字段-/// 同一条链路可能被用户动作 定时轮询 系统事件分别踢起来, 事后只有这个字段能区分+/// 记录操作触发来源, 区分同一链路的用户动作, 定时轮询和系统事件nonisolated enum LogTrigger: String {case manualcase panelOpen@@ -63,19 +62,17 @@ nonisolated struct LogDuration {Self.seconds(startedAt.duration(to: .now))}- /// 已经算好的秒数走这里, 保证和 elapsed 同一种写法+ /// 秒数与 elapsed 使用相同的日志格式static func seconds(_ value: TimeInterval) -> String {String(format: "%.2fs", max(0, value))}- /// 重试间隔这类 Duration 走这里, 不必在调用点各写一遍换算static func seconds(_ duration: Duration) -> String {seconds(TimeInterval(duration))}}nonisolated extension TimeInterval {- /// Duration 的 attosecond 分量换算成秒, 全仓库只留这一份init(_ duration: Duration) {self = Double(duration.components.seconds)+ Double(duration.components.attoseconds) / 1e18diff --git a/CodexBar/Views/Menu/ActivityCard.swift b/CodexBar/Views/Menu/ActivityCard.swiftindex 3d86d8d..b3b256e 100644--- a/CodexBar/Views/Menu/ActivityCard.swift+++ b/CodexBar/Views/Menu/ActivityCard.swift@@ -186,7 +186,7 @@ struct ActivityCard: View {.transition(.opacity).help(String(localized: "activity.summary.other-task-count", defaultValue: "\(content.otherTaskCount, specifier: "%lld")"))}- // 防睡眠只在任务运行期间生效, 所以状态挂在活动卡片上而不是单独占一行+ // 防睡眠由任务状态驱动, 徽标跟随活动卡片展示if showsKeepAliveBadge {// 隐藏或关闭动画效果时移除整个旋转视图, 避免保留持续渲染调度Group {diff --git a/CodexBar/Views/Menu/ActivityCenterView.swift b/CodexBar/Views/Menu/ActivityCenterView.swiftindex 158e9b3..6e09034 100644--- a/CodexBar/Views/Menu/ActivityCenterView.swift+++ b/CodexBar/Views/Menu/ActivityCenterView.swift@@ -43,7 +43,7 @@ struct ActivityCenterPanelContext {// MARK: - 任务中心面板-/// 并发任务中心, 实时展示全部等待; 运行; 最近完成和最近终止任务+/// 并发任务中心, 展示等待, 运行, 最近完成和最近终止的任务struct ActivityCenterView: View {@ObservedObject var activityMonitor: ActivityMonitor@ObservedObject var presentationState: ActivityCenterPresentationStatediff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swiftindex 2411cb1..1e905e2 100644--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift@@ -29,7 +29,7 @@ final class MenuSurfaceAnimationState: ObservableObject {@Published var allowsAnimations = false}-/// 菜单栏弹出面板根视图, 汇总账号; 实时活动; 额度; token; 同步状态和更新时间+/// 菜单栏弹出面板根视图, 汇总账号, 实时活动, 额度, Token 用量, 同步状态和更新时间struct CodexStatusMenuView: View {static let menuWidth: CGFloat = Metrics.padding * 2 + MenuMetrics.panelPadding * 2 + UsageHeatmap.Metrics.totalWidthdiff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex 8a99928..0236fec 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -2,7 +2,7 @@ import AppKitimport ServiceManagementimport SwiftUI-/// 设置窗口根视图, 按通用、高级和关于分页汇总设置与版本信息+/// 设置窗口根视图, 按通用, 高级和关于分页汇总设置与版本信息struct AppSettingsView: View {@EnvironmentObject private var statusViewModel: CodexStatusViewModel@EnvironmentObject private var appUpdater: AppUpdater@@ -980,7 +980,7 @@ private extension AppSettingsView {}func refreshCodexVersionSection() {- // 版本检测较慢且内部会合并并发请求; 连接信息只是缓存读取+ // 安装版本查询会节流并跳过重复刷新, 连接信息直接读取缓存codexVersions.refresh()statusViewModel.refreshCodexConnectionInfo()}diff --git a/CodexBarHelper/Power/Shared/CodexBarPowerHelperXPC.swift b/CodexBarHelper/Power/Shared/CodexBarPowerHelperXPC.swiftindex f376fee..6b0647f 100644--- a/CodexBarHelper/Power/Shared/CodexBarPowerHelperXPC.swift+++ b/CodexBarHelper/Power/Shared/CodexBarPowerHelperXPC.swift@@ -15,8 +15,7 @@ nonisolated enum CodexBarPowerHelperIPC {static let ownedCheckIntervalSeconds: TimeInterval = 5static let recoveryCheckIntervalSeconds: TimeInterval = 60static let checkLeewaySeconds: TimeInterval = 1- /// App 侧等回复的上限, 与 watchdog 宽限是一对: 必须更小, 这样 App 先放手 Power Helper 再自行兜底- /// Power Helper 冷启动加一次 pmset 通常一秒内完成, 留这么宽只为排除偶发的调度抖动+ /// App 等待 XPC 回复的上限, 超时后断开连接并进入失败恢复static let requestTimeoutSeconds: TimeInterval = 10}@@ -33,7 +32,8 @@ nonisolated enum CodexBarSleepOwnershipState: Int, Sendable {}@objc nonisolated protocol CodexBarPowerHelperProtocol: AnyObject {- /// reply 依次返回 pmset 退出码, 本轮防睡眠来源与操作后实测的 SleepDisabled+ /// clientSessionID 跨重连保持租约身份, generation 防止旧请求覆盖新状态+ /// reply 依次返回操作状态码, 防睡眠来源和 SleepDisabled 状态, 后两项可能来自缓存func setSleepPreventionRequested(_ requested: Bool,clientSessionID: String,diff --git a/Scripts/appcast.sh b/Scripts/appcast.shindex 5557386..dd12b41 100755--- a/Scripts/appcast.sh+++ b/Scripts/appcast.sh@@ -68,11 +68,11 @@ read_build_setting() {'}-# Print the single entry matching a glob in a directory, or fail:+# Print the single entry matching a glob in a directory, or fail# $1 noun for "no X found" $2 find -type $3 -name glob# $4 noun for "multiple X found" $5 hint appended to the multiple-match error# $6 directory to search. Exits 1 when nothing matches, 2 when more than one-# matches (printing the list).+# matches (printing the list)find_single() {local search_dir="$6"local items=()@@ -230,7 +230,7 @@ APPCAST_ITEM=" <item></item>"echo "==> Updating appcast"-# Write through a temp file so a perl die leaves appcast.xml untouched.+# Write through a temp file so a perl die leaves appcast.xml untouchedAPPCAST_TMP="$(mktemp)"trap 'rm -f "${APPCAST_TMP}"' EXITAPPCAST_ITEM="${APPCAST_ITEM}" APPCAST_VERSION="${BUILD_VERSION}" perl -0p -e '@@ -239,7 +239,7 @@ APPCAST_ITEM="${APPCAST_ITEM}" APPCAST_VERSION="${BUILD_VERSION}" perl -0p -e 'my $before = () = /<item>/g;# Keep the (?!<\/item>) guards: a plain .*? spans item boundaries and would- # also delete every entry above the one being replaced.+ # also delete every entry above the one being replaceds/\n\s*<item>(?:(?!<\/item>).)*?<sparkle:version>\Q$version\E<\/sparkle:version>(?:(?!<\/item>).)*?<\/item>//sg;if (!s/(<language>.*?<\/language>)/$1\n$item/s) {diff --git a/Scripts/build.sh b/Scripts/build.shindex b34e1f3..df7b27a 100755--- a/Scripts/build.sh+++ b/Scripts/build.sh@@ -15,7 +15,7 @@ ALLOW_PROVISIONING_UPDATES="1"SKIP_NOTARIZATION="0"SPCTL_ASSESS="1"-# Configure the keychain profile once before release builds:+# Configure the keychain profile once before release builds# xcrun notarytool store-credentials "codexbar-notary" --apple-id "<Apple ID>" --team-id "<Team ID>"NOTARYTOOL_PROFILE=""APPLE_ID=""diff --git a/Scripts/cleanup.swift b/Scripts/cleanup.swiftindex f5a4991..67ad278 100755--- a/Scripts/cleanup.swift+++ b/Scripts/cleanup.swift@@ -230,8 +230,7 @@ private final class KeepAliveCleanupCommand {}}- /// 候选按可信度排序, 命中的唯一标准是 Info.plist 里的 CFBundleIdentifier 对得上- /// 这里就是唯一的 App 校验点: 读到 Info.plist 即说明是个目录, 标识符对上即说明是这个 App+ /// 按候选顺序查找, 通过 Info.plist 中的 CFBundleIdentifier 确认目标 Appprivate func resolveAppURL(configuration: CleanupBuildConfiguration) throws -> URL? {let bundleIdentifier = configuration.bundleIdentifiervar candidates: [URL] = []@@ -260,9 +259,8 @@ private final class KeepAliveCleanupCommand {return try appBundleIdentifier(at: builtAppURL) == bundleIdentifier ? builtAppURL : nil}- /// 返回 nil 只代表这个路径下没有 App, 属于正常跳过- /// 读到了却解析不了必须抛出去: 用 try? 折叠成 nil 会把损坏的安装当成"不是这个 App",- /// 于是一次什么都没清理的运行照样打印完成并以 0 退出+ /// 缺少 Info.plist 或字符串类型的 CFBundleIdentifier 时返回 nil+ /// 文件读取或解析失败时抛出错误, 避免将损坏的安装静默跳过private func appBundleIdentifier(at appURL: URL) throws -> String? {let infoURL = appURL.appending(path: "Contents/Info.plist")guard fileManager.fileExists(atPath: infoURL.path) else {