Skip to content

CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息

feat: 补齐系统日志并收敛防休眠状态文案

Bobd17b0e21fe0f
diff --git a/.swiftlint.yml b/.swiftlint.yml
index d9a97e0..de2cea2 100644
--- a/.swiftlint.yml
+++ b/.swiftlint.yml
@@ -2,8 +2,8 @@ included:
- CodexBar
line_length:
- warning: 140
- error: 180
+ warning: 180
+ error: 220
ignores_comments: true
ignores_urls: true
ignores_function_declarations: true
@@ -15,8 +15,8 @@ file_length:
ignore_comment_only_lines: true
type_body_length:
- warning: 550
- error: 700
+ warning: 800
+ error: 1200
function_body_length:
warning: 80
diff --git a/AGENTS.md b/AGENTS.md
index 426acb1..abe3ab4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -2,17 +2,16 @@
## 项目结构与模块组织
-CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用, 使用 Swift 6, SwiftUI, AppKit 和 MVVM. 工程只有 `CodexBar` scheme, 包含主 App 与 `CodexBarHelper` 两个 target
+CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用, 使用 Swift 6, SwiftUI, AppKit 和 MVVM; 工程只有 `CodexBar` scheme, 包含主 App 与 `CodexBarHelper` 两个 target
-`CodexBar/` 按 `App/` `Views/` `Controllers/` `Models/` `Services/` 和 `Resources/` 分层. root LaunchDaemon 位于 `CodexBarHelper/` 目录, 跨 target XPC 接口位于 `Shared/` 目录. `Scripts/` 提供发布和 helper 清理工具, `Images/` 存放 README 资源
+`CodexBar/` 按 `App/` `Views/` `Controllers/` `Models/` `Services/` 和 `Resources/` 分层; root LaunchDaemon 位于 `CodexBarHelper/` 目录, 跨 target XPC 接口位于 `Shared/` 目录. `Scripts/` 提供发布和 helper 清理工具, `Images/` 存放 README 资源
## 构建, 测试与开发命令
-- `open CodexBar.xcodeproj` 在 Xcode 中运行 Debug scheme
-- `xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build` 执行日常构建验证
+- `xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build` 执行代码变更后的构建验证
- `swiftformat .` 按 `.swiftformat` 格式化全部 Swift, 使用 Swift 6 和 4 空格缩进
-- `swiftlint` 按 `.swiftlint.yml` 检查 `CodexBar/`
-- `Scripts/cleanup.swift --help` 查看 KeepAlive helper 清理选项
+- `swiftlint` 按 `.swiftlint.yml` 检查
+- `/usr/bin/log stream --predicate 'subsystem == "app.zabrian.codexbar"' --style compact` 查看系统日志, Debug 版 subsystem 带 `.debug` 后缀
`Scripts/build.sh` `dmg.sh` 和 `appcast.sh` 需要 Developer ID 与公证凭据, 不用于日常验证
diff --git a/CLAUDE.md b/CLAUDE.md
index 16ab6f3..d225d3b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -35,6 +35,12 @@ swiftformat .
# 即 Shared/ CodexBarHelper/ Scripts/ 不在 lint 范围内
swiftlint
+# 查看系统日志; zsh 里 log 会和 shell 冲突, 必须写完整路径
+# Debug 版把 subsystem 换成 app.zabrian.codexbar.debug, helper 进程另带 .helper 后缀
+# BEGINSWITH 会同时命中 Debug 与 Release, 要分版本得用 == 或 IN
+/usr/bin/log stream --predicate 'subsystem == "app.zabrian.codexbar"' --style compact
+/usr/bin/log show --predicate 'subsystem == "app.zabrian.codexbar"' --last 30m --style compact
+
# 发布流程 (需要 Developer ID 凭据, 不要当普通本地验证跑)
Scripts/build.sh # Release archive + Developer ID 导出 + notarize + staple + Gatekeeper 校验
Scripts/dmg.sh # 打包 DMG
@@ -70,7 +76,7 @@ Commit message: Conventional Commits 前缀 + 中文标题, 需要 body 时空
```text
fix: 修复 Codex 状态刷新
- - 合并设置页 onAppear 和 didBecomeActive 的重复版本探测
+ - 合并设置页 onAppear 和 didBecomeActive 的重复版本检测
- 保留当前运行版本与磁盘安装版本不一致时的更新提示
```
@@ -127,7 +133,9 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 调用方校验由 XPC 层强制; helper 启动时用 `SecCodeCopySelf` 读自身签名, 拼出形如 `anchor apple generic and certificate leaf[subject.OU] = "<team>" and identifier "<主 App identifier>"` 的 requirement 字符串, 交给 `NSXPCListener.setConnectionCodeSigningRequirement` 生效; 没有逐次连接的 audit token 检查, 改签名或改 bundle ID 会直接连不上
- 恢复哨兵放在 `/Library/Application Support/CodexBar/<machService>.state` 这个路径, **必须保持 `absent` `present` `unreadable` 三态**, 把读取失败折叠成 nil 会让恢复流程以为无需恢复, 使 `SleepDisabled=1` 永久残留; watchdog 宽限 15 秒, 哨兵自检 60 秒一次
- 切换失败按 2/4/8...256 秒重试, 列表耗尽 (约 8.5 分钟) 即放弃, 瞬时抖动能自愈, 权限类故障不该无限重试
-- 状态只呈现在主面板活动卡片右侧的咖啡杯标记, 由 `KeepAliveController.isActivelyPreventingSleep` 驱动, 卡片折叠成"暂无数据"时标记要跟着一起收
+- helper 回传的 `restoredSleepDisabled` 只有 `.present` 分支是实测值, `.absent` (本轮没接管过) 与 pmset 失败时都是占位的 `true`; App 侧靠 `canTrustRestoreResult` (接管到恢复之间连接未断) 判断可不可信, 这是从未接管的一轮里不误发 `IOPMSleepSystem` 的唯一屏障, 不要把 `.absent` 改成回实测值
+- 状态只呈现在主面板活动卡片右侧的咖啡杯标记 (带 tooltip), 由 `KeepAliveController.isActivelyPreventingSleep` 驱动, 卡片折叠成"暂无数据"时标记要跟着一起收
+- 设置页那一行说明只在异常或达到上限时出现, 正常运行时整行收起, `keepAliveCaption` 返回 nil 即代表收起
- **菜单栏图标不承载防休眠状态**, 它要保持模板渲染让系统按菜单栏外观着色, 自行着色在深浅和带染色的菜单栏下都会失控
### 通知
@@ -150,6 +158,12 @@ 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 两侧保持同一套格式
+- 成对的操作要留成对的日志, 例如 XPC 的发送与回复各记一条并带同一个 `generation`, 缺一条就说明请求丢在途中
+- `Logger` 的插值是 autoclosure, 里面直接访问属性会被要求显式 `self`, 而 `.swiftformat` 配了 `--self remove`, 两边会打架; 把属性先取到局部常量再插值即可, 不需要 lint 豁免
- 账号有效时 rate limits 和 usage 允许单独失败, 复用同账号旧缓存并标记 stale, UI 显示为半透明, 无缓存则该区域不显示; 账号变化时整体丢弃缓存避免串号
- 各 Settings 类把读取类错误与操作类错误分开存储, 定时 refresh 不能抹掉用户操作或校验的结论, 参见 `CodexHookSettings` 与 `KeepAliveController`
- Hook 子进程任何失败都静默退出, 优先保证不拖慢 Codex
@@ -179,12 +193,14 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 只读查询打到 `https://chatgpt.com/backend-api/wham/rate-limit-reset-credits` 这一个地址, 也是全仓库唯一的 `URLSession` 调用点, 位于 `CodexResetCreditsService` 内; Sparkle 更新走 `https://codexbar.zabrian.app/appcast.xml` 这个 feed
- 不展示 app-server stderr; 不展示或记录 Codex OAuth token 与 `auth.json` 内容; 不把原始敏感 RPC 响应写进文档
- CloudKit 只同步去掉 `sessionIds` 与 `turnIds` 的 daily 聚合, 不同步原始 Hook events, 账号, 额度或 Token 用量
+- 系统日志不写用户数据: 额度与 Token 用量只记 `state=` 这类结果分类, 任务内容, 项目名, 会话与轮次标识一律不记; 可执行文件路径含用户名, 用 `source=global|bundled` 之类的标识代替
+- 事件数, 任务数, 日期这类聚合数字可以记, 它们是判断重建是否正确和定位哪天出问题的依据, 不含任何内容
## 代码修改原则
- 优先贴合现有文件结构和类型职责, 不为小改动新建抽象
- 改 shared controller, shared service, 模型解析或持久化 key 时, 要考虑旧数据和降级路径; 用户设置要保持默认值; 持久化 key 和旧版本迁移兼容
-- **任何兼容性问题都必须主动询问用户, 不要自行拍板**; 只要改动会影响新旧共存就适用, 不限于旧数据迁移或丢弃, 持久化 key 改名或改结构, 老版本升上来的降级路径, 最低系统版本与 API 可用性取舍, 云端记录格式变更; 先说清影响面和几种做法的代价, 等用户选定再动手
+- **任何兼容性问题都必须主动询问用户, 不要自行决定**; 只要改动会影响新旧共存就适用, 不限于旧数据迁移或丢弃, 持久化 key 改名或改结构, 老版本升上来的降级路径, 最低系统版本与 API 可用性取舍, 云端记录格式变更; 先说清影响面和几种做法的代价, 等用户选定再动手
- 处理窗口, 菜单, 快捷键, App 激活或事件监听时, 特别注意 `LSUIElement` 应用特有的焦点行为
- 注释保持克制, 只解释非显然的生命周期, 焦点, actor 或系统 API 约束; 现有注释多为解释为什么的类型, 沿用同样风格
- 改动涉及菜单面板, 窗口焦点, Hook, 同步, 通知或防休眠时, 构建通过之外还要说明应手动覆盖的交互场景; 防休眠额外要验证 App 包内 helper 与 plist 位置, 签名, 首次系统授权, 运行/等待切换和异常退出后的恢复
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxproj
index ce7a156..c88f924 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 = 58;
+ CURRENT_PROJECT_VERSION = 59;
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.4;
+ MARKETING_VERSION = 3.5.5;
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 = 58;
+ CURRENT_PROJECT_VERSION = 59;
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.4;
+ MARKETING_VERSION = 3.5.5;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
diff --git a/CodexBar/Controllers/GlobalHotKeyController.swift b/CodexBar/Controllers/GlobalHotKeyController.swift
index 0fa0b2c..f50cbb1 100644
--- a/CodexBar/Controllers/GlobalHotKeyController.swift
+++ b/CodexBar/Controllers/GlobalHotKeyController.swift
@@ -1,5 +1,6 @@
import Carbon.HIToolbox
import Foundation
+import os
/// Carbon 全局快捷键注册器, 将系统回调桥接回 MainActor
final class GlobalHotKeyController {
@@ -28,6 +29,7 @@ final class GlobalHotKeyController {
userData,
&installedHandlerRef
) == noErr else {
+ AppLog.settings.error("全局快捷键事件处理器安装失败")
return false
}
@@ -43,10 +45,13 @@ final class GlobalHotKeyController {
)
guard status == noErr else {
+ // 最常见的原因是快捷键已被其他 App 占用, 用户只会看到"按了没反应"
+ AppLog.settings.error("全局快捷键注册失败: error=\(status)")
GlobalHotKeyRegistration.remove(hotKeyRef: nil, eventHandlerRef: installedHandlerRef)
return false
}
+ AppLog.settings.notice("全局快捷键已注册")
clearCurrentRegistration()
registration = GlobalHotKeyRegistration(
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index 341a024..a76bcb9 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -1,5 +1,6 @@
import AppKit
import Combine
+import os
import SwiftUI
/// 应用级对象装配点, 持有共享服务和 ViewModel 生命周期
@@ -56,14 +57,35 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
self.notificationService = notificationService
activityMonitor.start()
keepAliveController.start()
+ logLaunchState()
}
func applicationWillTerminate(_: Notification) {
+ AppLog.app.notice("APP 即将退出")
statusItemController?.uninstall()
keepAliveController.stop()
activityMonitor.stop()
}
+ /// 启动时把各开关的初始值记成一条基线, 之后的变更日志都是相对这条基线的增量
+ /// 排查时先看这条就知道当时的配置, 不必让用户逐项回忆
+ private func logLaunchState() {
+ // 全部先落到局部量再插值: Logger 的插值是 autoclosure, 直接写属性会与 --self remove 打架
+ let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "-"
+ let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "-"
+ let hook = codexHookSettings.isEnabled ? 1 : 0
+ let keepAlive = keepAliveController.isEnabled ? 1 : 0
+ let keepAliveLimit = keepAliveController.maximumDuration.title
+ let sync = syncSettings.isEnabled ? 1 : 0
+ let notification = notificationSettings.isEnabled ? 1 : 0
+ let menuBarQuota = menuBarQuotaSettings.selection.rawValue
+ let taskCenter = mainPanelSettings.showsTaskCenter ? 1 : 0
+ let hotKey = globalHotKeySettings.shortcut == nil ? 0 : 1
+ AppLog.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)"
+ )
+ }
+
func openSettingsFromCommand() {
statusItemController?.openSettingsFromCommand()
}
diff --git a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
index 9c5dc29..a902372 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
@@ -30,7 +30,7 @@ nonisolated struct CodexCLIConnectionInfo: Equatable {
let openedAt: Date
}
-/// 一次 PATH 扫描得到的安装结果, 供启动和版本探测复用
+/// 一次 PATH 扫描得到的安装结果, 供启动和版本检测复用
nonisolated struct CodexCLIInstallations: Equatable {
let globalPath: String?
let bundledPath: String?
diff --git a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
index 41aa7eb..8d7bad8 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
@@ -16,7 +16,7 @@ nonisolated struct CodexCLIVersionSnapshot: Equatable {
)
}
-/// 单个安装源的磁盘探测结果
+/// 单个安装源的磁盘检测结果
nonisolated struct CodexCLIVersionItem: Equatable, Identifiable {
let source: CodexCLIExecutableSource
let path: String?
@@ -48,7 +48,7 @@ nonisolated struct CodexCLIVersionItem: Equatable, Identifiable {
}
}
-/// 合并磁盘探测版本和当前 app-server 握手版本
+/// 合并磁盘检测版本和当前 app-server 握手版本
nonisolated struct CodexCLIVersionDisplay: Equatable {
let source: CodexCLIExecutableSource
let isCurrent: Bool
@@ -103,7 +103,7 @@ nonisolated struct CodexCLIVersionDisplay: Equatable {
}
}
-/// 并发探测 Codex CLI 与 Codex APP 内置 CLI 的磁盘版本
+/// 并发检测 Codex CLI 与 Codex APP 内置 CLI 的磁盘版本
actor CodexCLIVersionService {
private let timeout: TimeInterval
private static let pipeDrainTimeout: TimeInterval = 0.25
@@ -121,7 +121,7 @@ actor CodexCLIVersionService {
let environment = CodexCLIResolver.environment
let installations = CodexCLIResolver.resolveInstallations(environment: environment)
- // 两个安装源互不依赖, 并发探测避免两个超时串行叠加
+ // 两个安装源互不依赖, 并发检测避免两个超时串行叠加
async let global = probeVersion(
source: .global,
path: installations.globalPath,
@@ -182,6 +182,9 @@ actor CodexCLIVersionService {
} catch {
process.terminationHandler = nil
stopCollectors(outputCollector: outputCollector, errorCollector: errorCollector)
+ AppLog.codexCLI.error(
+ "版本检测启动失败: source=\(source.rawValue, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"
+ )
return CodexCLIVersionItem(source: source, path: path, errorMessage: "启动失败")
}
defer {
@@ -194,6 +197,7 @@ actor CodexCLIVersionService {
outputCollector: outputCollector,
errorCollector: errorCollector
)
+ AppLog.codexCLI.error("版本检测超时: source=\(source.rawValue, privacy: .public)")
return CodexCLIVersionItem(source: source, path: path, errorMessage: "读取超时")
}
@@ -201,17 +205,25 @@ actor CodexCLIVersionService {
let errorOutput = collectedText(from: errorCollector, deadline: deadline)
guard process.terminationStatus == 0 else {
+ AppLog.codexCLI.error(
+ "版本检测退出码非零: source=\(source.rawValue, privacy: .public); error=\(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)")
return CodexCLIVersionItem(source: source, path: path, errorMessage: "版本未知")
}
+ let displayVersion = CodexCLIVersionReader.displayVersion(from: version)
+ AppLog.codexCLI.notice(
+ "版本检测完成: source=\(source.rawValue, privacy: .public); version=\(displayVersion, privacy: .public)"
+ )
return CodexCLIVersionItem(
source: source,
path: path,
- version: CodexCLIVersionReader.displayVersion(from: version)
+ version: displayVersion
)
}
@@ -316,14 +328,14 @@ nonisolated enum CodexCLIVersionReader {
}
}
-/// 设置页持有的版本探测状态, 负责节流和丢弃过期刷新结果
+/// 设置页持有的版本检测状态, 负责节流和丢弃过期刷新结果
@MainActor
final class CodexCLIVersionViewModel: ObservableObject {
@Published private(set) var snapshot = CodexCLIVersionSnapshot.empty
@Published private(set) var isRefreshing = false
/// onAppear 和 didBecomeActive 常连发
- /// 版本探测需要节流以避免频繁启动子进程
+ /// 版本检测需要节流以避免频繁启动子进程
private static let refreshThrottle: TimeInterval = 60
private let service: CodexCLIVersionService
diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swift
index 277463e..55b106f 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift
@@ -1,4 +1,5 @@
import Foundation
+import os
/// UI 只关心可展示数据, 未登录, 初始化失败; 更细的错误保留在交互日志中
nonisolated enum CodexFetchOutcome {
@@ -317,11 +318,17 @@ actor CodexStatusService {
do {
try refreshTokenIfNeeded()
} catch {
+ AppLog.app.error(
+ "重置次数查询失败: stage=refreshToken; detail=\(error.localizedDescription, privacy: .public)"
+ )
return nil
}
return try? await fetchExpirationDates()
} catch {
+ AppLog.app.error(
+ "重置次数查询失败: stage=fetch; detail=\(error.localizedDescription, privacy: .public)"
+ )
return nil
}
}
@@ -471,6 +478,10 @@ actor CodexStatusService {
reused: false
)
} catch {
+ // app-server 链路的细节按既有分工进日志窗口, 不重复写系统日志
+ RequestLogStorage.shared.recordFailure(
+ message: "app-server 会话初始化失败: \(error.localizedDescription)"
+ )
session.close()
return .initializationFailed
}
diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
index 8352b16..882739a 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
@@ -1,5 +1,6 @@
import Combine
import Foundation
+import os
/// UI 级状态; 更细的连接和接口错误由服务层归并到日志
nonisolated enum CodexLoadState: Equatable {
@@ -99,6 +100,10 @@ final class CodexStatusViewModel: ObservableObject {
loadState = .initializationFailed
}
+ // 只记结果分类, 额度与用量是用户数据, 不进系统日志
+ // RPC 层面的请求响应细节仍然只进日志窗口
+ let state = loadState
+ AppLog.app.notice("额度信息刷新完成: state=\(String(describing: state), privacy: .public)")
codexConnectionInfo = result.connectionInfo
autoRefreshCountdownStartedAt = Date()
}
diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swift
index fb23e93..1616990 100644
--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift
+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift
@@ -3,6 +3,7 @@ import Combine
import CryptoKit
import Foundation
import IOKit
+import os
import ServiceManagement
@MainActor
@@ -25,7 +26,7 @@ final class KeepAliveController: ObservableObject {
}
/// 用户开关仍开着, 且 helper 已经真的把休眠关掉
- /// isPreventingSleep 在稳态下已隐含 isEnabled (shouldDisableSleep 要求它),
+ /// isPreventingSleep 在稳态下已隐含 isEnabled (shouldDisableSleep 要求它)
/// 叠这一层是为了关开关到 helper 回调之间的异步空窗: 用户意图先落地
var isActivelyPreventingSleep: Bool {
isEnabled && isPreventingSleep
@@ -41,6 +42,10 @@ final class KeepAliveController: ObservableObject {
/// 记录上一份快照中的等待任务, 用于识别等待批准后恢复运行的状态转换
private var waitingTaskIDs = Set<UUID>()
private var connection: NSXPCConnection?
+ /// 本轮接管以来连接没有断过, helper 那边的哨兵必然还在
+ /// 断过就可能是 helper 已经自行恢复并清掉哨兵, 那之后拿到的回复只是占位值, 不是实测状态
+ /// 能这样判断是因为哨兵只由 helper 侧的恢复删除, 而那些路径都要求连接已断
+ private var canTrustRestoreResult = false
private var appliedSleepDisabled: Bool?
private var requestInFlight = false
private var requestGeneration: UInt64 = 0
@@ -134,6 +139,7 @@ final class KeepAliveController: ObservableObject {
return
}
+ AppLog.keepAlive.notice("阻止休眠开关已变更: enabled=\(enabled ? 1 : 0)")
isEnabled = enabled
defaults.set(enabled, forKey: Self.enabledKey)
registrationErrorMessage = nil
@@ -152,6 +158,7 @@ final class KeepAliveController: ObservableObject {
return
}
+ AppLog.keepAlive.notice("最长阻止时间已变更: duration=\(duration.title, privacy: .public)")
maximumDuration = duration
defaults.set(duration.rawValue, forKey: Self.maximumDurationKey)
@@ -227,12 +234,16 @@ final class KeepAliveController: ObservableObject {
}
}
+ AppLog.keepAlive.notice("开始注册服务")
do {
try service.register()
} catch {
refreshHelperStatus()
if !helperStatus.isRegisteredOrAwaitingApproval {
- registrationErrorMessage = "注册服务失败: \(error.localizedDescription)"
+ AppLog.keepAlive.error(
+ "注册服务失败: detail=\(error.localizedDescription, privacy: .public)"
+ )
+ registrationErrorMessage = "注册服务失败"
}
}
@@ -282,7 +293,10 @@ final class KeepAliveController: ObservableObject {
if helperStatus.isRegisteredOrAwaitingApproval {
recordHelperRegistrationIfCurrent()
} else if let registrationError {
- registrationErrorMessage = "更新服务失败: \(registrationError.localizedDescription)"
+ AppLog.keepAlive.error(
+ "更新服务失败: detail=\(registrationError.localizedDescription, privacy: .public)"
+ )
+ registrationErrorMessage = "更新服务失败"
}
isRefreshingHelper = false
@@ -332,7 +346,16 @@ final class KeepAliveController: ObservableObject {
}
private func refreshHelperStatus() {
+ let previousStatus = helperStatus
assign(HelperStatus(Self.helperService.status), to: \.helperStatus)
+ // 每次 App 激活都会跑, 只记真正的迁移, 否则日志会被无变化的求值淹没
+ // 取局部量再插值: Logger 的插值是 autoclosure, 直接写属性会被要求显式 self, 与 --self remove 冲突
+ let currentStatus = helperStatus
+ if currentStatus != previousStatus {
+ AppLog.keepAlive.notice(
+ "服务状态变化: from=\(String(describing: previousStatus), privacy: .public); to=\(String(describing: currentStatus), privacy: .public)"
+ )
+ }
if helperStatus == .enabled {
// 注册已正常, 只撤回注册类抱怨
// 操作类结果 (例如重试耗尽) 必须留到下一次操作有结论为止
@@ -370,7 +393,8 @@ final class KeepAliveController: ObservableObject {
if disabled {
let result = systemSleepService.beginPreventingIdleSleep()
guard result == kIOReturnSuccess else {
- operationErrorMessage = "阻止空闲休眠失败 (\(result))"
+ AppLog.keepAlive.error("阻止空闲休眠失败: error=\(result)")
+ operationErrorMessage = "阻止空闲休眠失败"
scheduleRetryIfNeeded(for: true)
return
}
@@ -381,6 +405,10 @@ final class KeepAliveController: ObservableObject {
requestInFlight = true
requestGeneration &+= 1
let generation = requestGeneration
+ // 与下面的回复日志配成一对, 缺回复即说明请求丢在 XPC 途中或 helper 无响应
+ AppLog.keepAlive.notice(
+ "发送休眠请求: disabled=\(disabled ? 1 : 0); generation=\(generation)"
+ )
let errorHandler: (Error) -> Void = { [weak self] error in
Task { @MainActor in
@@ -402,10 +430,14 @@ final class KeepAliveController: ObservableObject {
return
}
self.requestInFlight = false
+ AppLog.keepAlive.notice(
+ "收到休眠回复: generation=\(generation); error=\(exitCode); sleepDisabled=\(sleepDisabledAfterOperation ? 1 : 0)"
+ )
guard exitCode == 0 else {
// invalidateConnection 会连同 assertion 一起收
self.invalidateConnection()
- self.operationErrorMessage = "切换休眠状态失败 (\(exitCode))"
+ AppLog.keepAlive.error("切换休眠状态失败: error=\(exitCode)")
+ self.operationErrorMessage = "切换休眠状态失败"
self.scheduleRetryIfNeeded(for: disabled)
return
}
@@ -414,6 +446,8 @@ final class KeepAliveController: ObservableObject {
self.isPreventingSleep = disabled
self.operationErrorMessage = nil
if disabled {
+ AppLog.keepAlive.notice("已接管系统休眠")
+ self.canTrustRestoreResult = true
self.beginMaximumDurationCountdownIfNeeded()
} else {
self.finishSleepRestore(
@@ -469,25 +503,51 @@ final class KeepAliveController: ObservableObject {
cancelMaximumDurationTask()
hasReachedMaximumDuration = true
+ let durationTitle = maximumDuration.title
+ AppLog.keepAlive.notice("已到阻止休眠上限: duration=\(durationTitle, privacy: .public)")
reconcileSleepState()
}
private func finishSleepRestore(sleepDisabledAfterOperation: Bool) {
+ // assertion 无论回复可不可信都要释放, 与下面的判断无关
let idleSleepResult = systemSleepService.endPreventingIdleSleep()
if idleSleepResult != kIOReturnSuccess {
- operationErrorMessage = "恢复空闲休眠策略失败 (\(idleSleepResult))"
+ AppLog.keepAlive.error("恢复空闲休眠策略失败: error=\(idleSleepResult)")
+ operationErrorMessage = "恢复空闲休眠策略失败"
+ }
+
+ let sleepDisabled = sleepDisabledAfterOperation ? 1 : 0
+ // 连接断过时 helper 可能已自行恢复并清掉哨兵, 这份回复不带实测状态
+ // 不能据此补发合盖休眠: 本轮可能压根不是我们禁用的休眠
+ guard canTrustRestoreResult else {
+ // 这条判断是防止误发强制休眠的唯一屏障, 生效时必须留痕, 否则误判无从追查
+ AppLog.keepAlive.notice("跳过恢复处理: 接管期间连接断开")
+ return
}
+ AppLog.keepAlive.notice("已恢复系统休眠: SleepDisabled=\(sleepDisabled)")
+
+ let lidStatus = SystemSleepService.currentStatus()
let shouldRequestSystemSleep = !sleepDisabledAfterOperation
- && SystemSleepService.currentStatus()?.shouldSleepForLidClosure == true
+ && lidStatus?.shouldSleepForLidClosure == true
+
+ let lidClosed = lidStatus.map { $0.isLidClosed ? "1" : "0" } ?? "unknown"
+ let lidCausesSleep = lidStatus.map { $0.lidClosureCausesSleep ? "1" : "0" } ?? "unknown"
guard shouldRequestSystemSleep else {
+ AppLog.keepAlive.notice(
+ "不请求系统休眠: sleepDisabled=\(sleepDisabled); lidClosed=\(lidClosed, privacy: .public); lidCausesSleep=\(lidCausesSleep, privacy: .public)"
+ )
return
}
+ AppLog.keepAlive.notice(
+ "请求系统休眠: sleepDisabled=\(sleepDisabled); lidClosed=\(lidClosed, privacy: .public); lidCausesSleep=\(lidCausesSleep, privacy: .public)"
+ )
let result = SystemSleepService.requestSystemSleep()
if result != kIOReturnSuccess {
- operationErrorMessage = "请求系统休眠失败 (\(result))"
+ AppLog.keepAlive.error("请求系统休眠失败: error=\(result)")
+ operationErrorMessage = "请求系统休眠失败"
}
}
@@ -535,6 +595,7 @@ final class KeepAliveController: ObservableObject {
}
connection.resume()
self.connection = connection
+ AppLog.keepAlive.notice("已建立服务连接")
return connection
}
@@ -542,7 +603,10 @@ final class KeepAliveController: ObservableObject {
let shouldRetry = requestInFlight || isPreventingSleep
let desiredSleepDisabled = shouldDisableSleep
invalidateConnection()
- operationErrorMessage = "连接服务失败: \(error.localizedDescription)"
+ AppLog.keepAlive.error(
+ "连接服务失败: detail=\(error.localizedDescription, privacy: .public)"
+ )
+ operationErrorMessage = "连接服务失败"
if shouldRetry {
scheduleRetryIfNeeded(for: desiredSleepDisabled)
}
@@ -555,6 +619,12 @@ final class KeepAliveController: ObservableObject {
connection?.invalidationHandler = nil
connection?.interruptionHandler = nil
connection?.invalidate()
+ // 无连接时也会走到这里, 只记真的断掉了一条, 避免空转刷屏
+ if connection != nil {
+ AppLog.keepAlive.notice("服务连接已失效")
+ }
+ // 所有能让我们在哨兵已删的情况下再发一次恢复请求的路径都汇到这里, 标志清在这里才严密
+ canTrustRestoreResult = false
appliedSleepDisabled = nil
requestInFlight = false
releaseSleepPrevention()
@@ -592,12 +662,19 @@ final class KeepAliveController: ObservableObject {
// 每次重试都会重建特权连接并以 root 拉起 pmset
// 固定 2 秒无上限重试会让持续失败的 helper 变成无限循环
guard retryAttempt < Self.sleepToggleRetryDelays.count else {
+ AppLog.keepAlive.error(
+ "阻止休眠多次失败, 已停止重试: attempts=\(Self.sleepToggleRetryDelays.count)"
+ )
operationErrorMessage = "阻止休眠多次失败, 已停止重试"
return
}
let delay = Self.sleepToggleRetryDelays[retryAttempt]
retryAttempt += 1
+ let attempt = retryAttempt
+ AppLog.keepAlive.notice(
+ "安排重试: attempt=\(attempt); delay=\(delay.components.seconds)s; disabled=\(disabled ? 1 : 0)"
+ )
retryTask = Task { @MainActor [weak self] in
try? await Task.sleep(for: delay)
diff --git a/CodexBar/Services/KeepAlive/SystemSleepService.swift b/CodexBar/Services/KeepAlive/SystemSleepService.swift
index 464edee..62a28e2 100644
--- a/CodexBar/Services/KeepAlive/SystemSleepService.swift
+++ b/CodexBar/Services/KeepAlive/SystemSleepService.swift
@@ -13,38 +13,37 @@ final class SystemSleepService {
}
}
- private static let idleSleepAssertionName = "CodexBar - Codex task running"
+ private static let assertionName = "CodexBar - Codex activity"
- private var idleSleepAssertionID = IOPMAssertionID(kIOPMNullAssertionID)
+ private var assertionID = IOPMAssertionID(kIOPMNullAssertionID)
func beginPreventingIdleSleep() -> IOReturn {
- guard idleSleepAssertionID == IOPMAssertionID(kIOPMNullAssertionID) else {
+ guard assertionID == IOPMAssertionID(kIOPMNullAssertionID) else {
return kIOReturnSuccess
}
- var assertionID = IOPMAssertionID(kIOPMNullAssertionID)
- // 名称必须是 ASCII: 含中文时 pmset -g assertions 会把 named 显示成空串,
- // 这条断言在诊断输出里就失去了标识, 只能靠进程名辨认
+ var createdAssertionID = IOPMAssertionID(kIOPMNullAssertionID)
+ // 名称必须是 ASCII: 含中文时 pmset -g assertions 的 named 会显示成空串, 这条断言就失去了标识
let result = IOPMAssertionCreateWithName(
kIOPMAssertionTypePreventUserIdleSystemSleep as CFString,
IOPMAssertionLevel(kIOPMAssertionLevelOn),
- Self.idleSleepAssertionName as CFString,
- &assertionID
+ Self.assertionName as CFString,
+ &createdAssertionID
)
if result == kIOReturnSuccess {
- idleSleepAssertionID = assertionID
+ assertionID = createdAssertionID
}
return result
}
func endPreventingIdleSleep() -> IOReturn {
- guard idleSleepAssertionID != IOPMAssertionID(kIOPMNullAssertionID) else {
+ guard assertionID != IOPMAssertionID(kIOPMNullAssertionID) else {
return kIOReturnSuccess
}
- let result = IOPMAssertionRelease(idleSleepAssertionID)
+ let result = IOPMAssertionRelease(assertionID)
if result == kIOReturnSuccess || result == kIOReturnNotFound {
- idleSleepAssertionID = IOPMAssertionID(kIOPMNullAssertionID)
+ assertionID = IOPMAssertionID(kIOPMNullAssertionID)
}
return result == kIOReturnNotFound ? kIOReturnSuccess : result
}
diff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swift
index 11a42e1..17eefe8 100644
--- a/CodexBar/Services/Notifications/CodexNotificationService.swift
+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift
@@ -1,6 +1,7 @@
import AppKit
import Combine
import Foundation
+import os
import UserNotifications
/// 集中式提醒服务: 订阅额度与实时活动, 负责触觉反馈; 阈值判定; 去重; 重置识别与本地通知发送
@@ -420,6 +421,7 @@ final class CodexNotificationService: NSObject {
// MARK: - 发送与文案
+ /// 通知的 title 与 body 含项目名和任务信息, 一律不进日志, 只记 kind
private func send(
_ notification: CodexNotificationContent,
sound: NotificationSoundOption,
@@ -428,9 +430,11 @@ final class CodexNotificationService: NSObject {
isStillRelevant: (() -> Bool)? = nil,
onSubmissionFailure: (() -> Void)? = nil
) {
+ let kind = notification.kind
if let dedupKey {
guard !sentDedupKeys.contains(dedupKey),
submittingDedupKeys.insert(dedupKey).inserted else {
+ AppLog.notification.notice("通知已跳过: kind=\(kind, privacy: .public); reason=duplicate")
return
}
}
@@ -458,23 +462,33 @@ final class CodexNotificationService: NSObject {
for _ in 0 ... Self.notificationSubmissionRetryCount {
guard isStillRelevant?() != false else {
+ AppLog.notification.notice(
+ "通知已跳过: kind=\(kind, privacy: .public); reason=obsolete"
+ )
return
}
do {
try await UNUserNotificationCenter.current().add(request)
guard isStillRelevant?() != false else {
+ // 投递后任务状态又变了, 撤回避免用户看到过期提醒
+ AppLog.notification.notice(
+ "通知已撤回: kind=\(kind, privacy: .public); reason=obsolete"
+ )
removeNotifications(withIdentifiers: [identifier])
return
}
if let dedupKey {
rememberSentDedupKey(dedupKey)
}
+ AppLog.notification.notice("通知已发送: kind=\(kind, privacy: .public)")
return
} catch {
continue
}
}
+ // 重试全部用尽才记, 循环内的单次失败会重试
+ AppLog.notification.error("通知发送失败: kind=\(kind, privacy: .public); reason=retryExhausted")
onSubmissionFailure?()
}
}
@@ -547,6 +561,8 @@ final class CodexNotificationService: NSObject {
}
nonisolated struct CodexNotificationContent: Equatable {
+ /// 只用于日志分类, 由各静态工厂带出, 保证与实际内容不会错位
+ let kind: String
let title: String
let body: String
@@ -556,6 +572,7 @@ nonisolated struct CodexNotificationContent: Equatable {
thresholdPercent: Int
) -> CodexNotificationContent {
CodexNotificationContent(
+ kind: "lowQuota",
title: "Codex 额度不足",
body: "\(limitTitle) \(windowLabel) 剩余额度已低于 \(thresholdPercent)%"
)
@@ -566,6 +583,7 @@ nonisolated struct CodexNotificationContent: Equatable {
windowLabel: String
) -> CodexNotificationContent {
CodexNotificationContent(
+ kind: "quotaReset",
title: "额度已重置",
body: "\(limitTitle) \(windowLabel)"
)
@@ -574,6 +592,7 @@ nonisolated struct CodexNotificationContent: Equatable {
static func taskCompleted(project: String?, duration: TimeInterval) -> CodexNotificationContent {
let projectText = project.map { "「\($0)」" } ?? "Codex"
return CodexNotificationContent(
+ kind: "longTask",
title: "Codex 任务完成",
body: "\(projectText) 任务完成, \(CodexActivityDisplayFormat.elapsedDurationFragment(for: duration))"
)
@@ -583,6 +602,7 @@ nonisolated struct CodexNotificationContent: Equatable {
let subject = project.map { "「\($0)」" } ?? "Codex"
let action = toolName.map { "\($0) 操作" } ?? "下一步操作"
return CodexNotificationContent(
+ kind: "taskWaiting",
title: "Codex 等待批准",
body: "\(subject) 正在等待批准 \(action)"
)
@@ -590,6 +610,7 @@ nonisolated struct CodexNotificationContent: Equatable {
static func creditExpiry(count: Int, expirationDate: Date) -> CodexNotificationContent {
CodexNotificationContent(
+ kind: "creditExpiry",
title: "重置即将过期",
body: "有 \(count) 个重置次数将于 \(CodexDateFormat.localDisplayString(from: expirationDate)) 过期"
)
diff --git a/CodexBar/Services/Settings/CodexCLINotificationSettings.swift b/CodexBar/Services/Settings/CodexCLINotificationSettings.swift
index 2c8ee61..62359e1 100644
--- a/CodexBar/Services/Settings/CodexCLINotificationSettings.swift
+++ b/CodexBar/Services/Settings/CodexCLINotificationSettings.swift
@@ -1,5 +1,6 @@
import Combine
import Foundation
+import os
/// Codex TUI 通知设置, 通过 app-server 读写用户级 config.toml
@MainActor
@@ -33,6 +34,7 @@ final class CodexCLINotificationSettings: ObservableObject {
}
func setEnabled(_ enabled: Bool) {
+ AppLog.settings.notice("Codex 通知配置已变更: enabled=\(enabled ? 1 : 0)")
guard enabled != isEnabled else {
return
}
@@ -85,7 +87,10 @@ final class CodexCLINotificationSettings: ObservableObject {
guard isCurrentUpdate(generation) else {
return
}
- errorMessage = "\(errorPrefix): \(error.localizedDescription)"
+ AppLog.settings.error(
+ "\(errorPrefix, privacy: .public): detail=\(error.localizedDescription, privacy: .public)"
+ )
+ errorMessage = errorPrefix
}
finishUpdate(generation)
diff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swift
index f91dd70..7599600 100644
--- a/CodexBar/Services/Settings/CodexHookSettings.swift
+++ b/CodexBar/Services/Settings/CodexHookSettings.swift
@@ -1,5 +1,6 @@
import Combine
import Foundation
+import os
/// 设置页的 Codex Hook 开关状态机, 同时管理 hooks.json 和 Codex 信任状态
@MainActor
@@ -49,11 +50,15 @@ final class CodexHookSettings: ObservableObject {
// 只有 I/O 失败和 JSON 格式错误会走到这里, 它们对「Hook 装没装」不提供信息
// 文件不存在或配置里没有 CodexBar 都由 readConfigIfPresent 正常返回
// 因此保留上次已知值, 不能把读取失败当成用户关闭了 Hook
- readErrorMessage = "读取 Codex Hook 配置失败: \(error.localizedDescription)"
+ AppLog.hooks.error(
+ "读取 Hook 配置失败: detail=\(error.localizedDescription, privacy: .public)"
+ )
+ readErrorMessage = "读取 Codex Hook 配置失败"
}
}
func setEnabled(_ enabled: Bool) {
+ AppLog.hooks.notice("Hook 开关已变更: enabled=\(enabled ? 1 : 0)")
runLatestUpdate(showProgress: true) { settings, generation in
await settings.applyEnabled(enabled, generation: generation)
}
@@ -173,11 +178,17 @@ final class CodexHookSettings: ObservableObject {
if let hookError = error as? HookConfigError,
hookError.isPreflightFailure {
+ AppLog.hooks.error(
+ "前置检查未通过, 未改动配置: detail=\(hookError.localizedDescription, privacy: .public)"
+ )
isEnabled = false
operationErrorMessage = hookError.localizedDescription
} else {
+ AppLog.hooks.error(
+ "设置 Hook 失败: detail=\(error.localizedDescription, privacy: .public)"
+ )
refresh()
- operationErrorMessage = "设置 Codex Hook 失败: \(error.localizedDescription)"
+ operationErrorMessage = "设置 Codex Hook 失败"
}
}
}
@@ -309,6 +320,8 @@ private extension CodexHookSettings {
}
try write(config)
+ // 改的是用户自己的 ~/.codex/hooks.json, 每次写入都要留痕
+ AppLog.hooks.notice("已写入 Hook 配置: enabled=\(enabled ? 1 : 0)")
}
func codexBarHookTrustKeysFromAppServer() async throws -> Set<String> {
@@ -330,10 +343,14 @@ private extension CodexHookSettings {
if !keys.isEmpty {
try await removeCodexBarHookTrust(keys)
try ensureCurrentUpdate(generation)
+ AppLog.hooks.notice("已清理 Hook 信任状态: keys=\(keys.count)")
}
if let discoveryError {
- operationErrorMessage = "已关闭 Codex Hook, 清理信任状态失败: \(discoveryError.localizedDescription)"
+ AppLog.hooks.error(
+ "清理信任状态失败: stage=discovery; detail=\(discoveryError.localizedDescription, privacy: .public)"
+ )
+ operationErrorMessage = "已关闭 Codex Hook, 清理信任状态失败"
} else {
operationErrorMessage = nil
}
@@ -344,7 +361,10 @@ private extension CodexHookSettings {
return
}
- operationErrorMessage = "已关闭 Codex Hook, 清理信任状态失败: \(error.localizedDescription)"
+ AppLog.hooks.error(
+ "清理信任状态失败: stage=remove; detail=\(error.localizedDescription, privacy: .public)"
+ )
+ operationErrorMessage = "已关闭 Codex Hook, 清理信任状态失败"
}
}
diff --git a/CodexBar/Services/Settings/GlobalHotKeySettings.swift b/CodexBar/Services/Settings/GlobalHotKeySettings.swift
index a642fd5..caf3230 100644
--- a/CodexBar/Services/Settings/GlobalHotKeySettings.swift
+++ b/CodexBar/Services/Settings/GlobalHotKeySettings.swift
@@ -1,5 +1,6 @@
import Combine
import Foundation
+import os
/// 全局快捷键偏好设置, 负责持久化和注册失败后的 UI 回滚
@MainActor
@@ -21,12 +22,14 @@ final class GlobalHotKeySettings: ObservableObject {
return
}
+ AppLog.settings.notice("全局快捷键已设置")
self.shortcut = shortcut
saveShortcut(shortcut)
errorMessage = nil
}
func clearShortcut() {
+ AppLog.settings.notice("全局快捷键已清除")
shortcut = nil
saveShortcut(nil)
errorMessage = nil
@@ -37,12 +40,14 @@ final class GlobalHotKeySettings: ObservableObject {
}
func setRegistrationError(_ message: String) {
+ AppLog.settings.error("全局快捷键注册失败: detail=\(message, privacy: .public)")
errorMessage = message
}
/// 参数不可为空: 传 nil 会经 saveShortcut 清空用户保存的配置
/// 没有可回退的快捷键时应改用 setRegistrationError
func restoreShortcut(_ shortcut: GlobalHotKeyShortcut, message: String) {
+ AppLog.settings.notice("全局快捷键已回退: detail=\(message, privacy: .public)")
self.shortcut = shortcut
saveShortcut(shortcut)
errorMessage = message
diff --git a/CodexBar/Services/Settings/LoginItemSettings.swift b/CodexBar/Services/Settings/LoginItemSettings.swift
index 79aef5e..a3beb07 100644
--- a/CodexBar/Services/Settings/LoginItemSettings.swift
+++ b/CodexBar/Services/Settings/LoginItemSettings.swift
@@ -1,5 +1,6 @@
import Combine
import Foundation
+import os
import ServiceManagement
/// 开机启动设置, 所有 ServiceManagement 错误只展示简短文案
@@ -15,6 +16,7 @@ final class LoginItemSettings: ObservableObject {
func setEnabled(_ enabled: Bool) {
errorMessage = nil
+ AppLog.settings.notice("开机启动已变更: enabled=\(enabled ? 1 : 0)")
do {
if enabled {
try SMAppService.mainApp.register()
@@ -24,8 +26,11 @@ final class LoginItemSettings: ObservableObject {
refresh()
} catch {
+ AppLog.settings.error(
+ "设置开机启动失败: enabled=\(enabled ? 1 : 0); detail=\(error.localizedDescription, privacy: .public)"
+ )
refresh()
- errorMessage = "设置开机启动失败: \(error.localizedDescription)"
+ errorMessage = "设置开机启动失败"
}
}
}
diff --git a/CodexBar/Services/Settings/MainPanelSettings.swift b/CodexBar/Services/Settings/MainPanelSettings.swift
index c68042f..45ae3ff 100644
--- a/CodexBar/Services/Settings/MainPanelSettings.swift
+++ b/CodexBar/Services/Settings/MainPanelSettings.swift
@@ -1,5 +1,6 @@
import Combine
import Foundation
+import os
/// 主面板内容偏好
@MainActor
@@ -27,6 +28,7 @@ final class MainPanelSettings: ObservableObject {
return
}
+ 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.swift
index ec30851..d022bdb 100644
--- a/CodexBar/Services/Settings/MenuBarQuotaSettings.swift
+++ b/CodexBar/Services/Settings/MenuBarQuotaSettings.swift
@@ -1,5 +1,6 @@
import Combine
import Foundation
+import os
/// 菜单栏额度指示偏好
@MainActor
@@ -35,6 +36,9 @@ final class MenuBarQuotaSettings: ObservableObject {
return
}
+ AppLog.settings.notice(
+ "菜单栏额度显示已变更: selection=\(selection.rawValue, privacy: .public)"
+ )
saveSelection(selection)
publishSelection(selection)
}
diff --git a/CodexBar/Services/Settings/NotificationSettings.swift b/CodexBar/Services/Settings/NotificationSettings.swift
index 682483d..3fc9dd1 100644
--- a/CodexBar/Services/Settings/NotificationSettings.swift
+++ b/CodexBar/Services/Settings/NotificationSettings.swift
@@ -1,6 +1,7 @@
import AppKit
import Combine
import Foundation
+import os
import UserNotifications
/// 通知偏好: 总开关; 五类通知子开关及声音; 任务触觉开关; 两个阈值和系统授权状态镜像
@@ -95,6 +96,7 @@ final class NotificationSettings: ObservableObject {
return
}
+ AppLog.notification.notice("通知总开关已变更: enabled=\(enabled ? 1 : 0)")
isEnabled = enabled
defaults.set(enabled, forKey: Self.enabledKey)
if enabled {
@@ -182,6 +184,12 @@ final class NotificationSettings: ObservableObject {
return
}
+ let previousStatus = authorizationStatus
+ if status != previousStatus {
+ AppLog.notification.notice(
+ "通知授权状态变化: from=\(String(describing: previousStatus), privacy: .public); to=\(String(describing: status), privacy: .public)"
+ )
+ }
authorizationStatus = status
}
}
@@ -210,6 +218,10 @@ final class NotificationSettings: ObservableObject {
return
}
+ // 被拒时通知会静默不发, 这是最常见的"设置开了却收不到"来源, 必须留痕
+ AppLog.notification.notice(
+ "通知授权请求结果: status=\(String(describing: status), privacy: .public)"
+ )
authorizationStatus = status
}
}
@@ -219,6 +231,10 @@ final class NotificationSettings: ObservableObject {
return
}
+ // 六个通知细项都走这里, 用持久化 key 区分是哪一项, 不必逐个 setter 铺日志
+ AppLog.notification.notice(
+ "通知选项已变更: key=\(key, privacy: .public); enabled=\(value ? 1 : 0)"
+ )
current = value
defaults.set(value, forKey: key)
}
diff --git a/CodexBar/Services/Settings/WorkflowSyncSettings.swift b/CodexBar/Services/Settings/WorkflowSyncSettings.swift
index 9527a5f..91a5fc0 100644
--- a/CodexBar/Services/Settings/WorkflowSyncSettings.swift
+++ b/CodexBar/Services/Settings/WorkflowSyncSettings.swift
@@ -1,6 +1,7 @@
import CloudKit
import Combine
import Foundation
+import os
/// 设置页的工作流同步状态
@MainActor
@@ -45,6 +46,9 @@ final class WorkflowSyncSettings: ObservableObject {
}
let previousValue = isEnabled
+ if previousValue != enabled {
+ AppLog.sync.notice("同步开关已变更: enabled=\(enabled ? 1 : 0)")
+ }
defaults.set(enabled, forKey: Self.enabledKey)
if enabled {
defaults.set(true, forKey: Self.needsBackfillKey)
diff --git a/CodexBar/Services/Support/AppLog.swift b/CodexBar/Services/Support/AppLog.swift
new file mode 100644
index 0000000..cdcade5
--- /dev/null
+++ b/CodexBar/Services/Support/AppLog.swift
@@ -0,0 +1,27 @@
+import Foundation
+import os
+
+/// App 侧统一的系统日志出口, 与 app-server 链路的日志窗口分工明确
+/// 用户可见的错误文案只留步骤名, 定位问题需要的细节写到这里
+/// subsystem 取 bundle identifier, Debug 与 Release 两套装置的日志因此天然分开
+nonisolated enum AppLog {
+ /// App 生命周期, Sparkle 更新, 额度刷新结果与重置次数查询
+ static let app = Logger(subsystem: subsystem, category: "app")
+ static let keepAlive = Logger(subsystem: subsystem, category: "keepalive")
+ /// 本地 Hook 事件聚合与维护
+ static let workflow = Logger(subsystem: subsystem, category: "workflow")
+ /// CloudKit 同步
+ static let sync = Logger(subsystem: subsystem, category: "sync")
+ /// 改写用户 ~/.codex 下的 Hook 配置与信任状态
+ static let hooks = Logger(subsystem: subsystem, category: "hooks")
+ /// 实时任务监控, 只记低频的生命周期节点, 逐事件与逐快照的路径一律不记
+ static let activity = Logger(subsystem: subsystem, category: "activity")
+ /// 开机启动, 全局快捷键, Codex 自身通知配置这类用户设置
+ static let settings = Logger(subsystem: subsystem, category: "settings")
+ /// codex 可执行文件检测与版本读取
+ static let codexCLI = Logger(subsystem: subsystem, category: "codexcli")
+ /// 本地通知投递
+ static let notification = Logger(subsystem: subsystem, category: "notification")
+
+ private static let subsystem = Bundle.main.bundleIdentifier ?? "app.zabrian.codexbar"
+}
diff --git a/CodexBar/Services/Updates/AppUpdater.swift b/CodexBar/Services/Updates/AppUpdater.swift
index 5978be8..45504b7 100644
--- a/CodexBar/Services/Updates/AppUpdater.swift
+++ b/CodexBar/Services/Updates/AppUpdater.swift
@@ -1,5 +1,6 @@
import AppKit
import Combine
+import os
import Sparkle
import SwiftUI
@@ -54,6 +55,7 @@ final class AppUpdater: NSObject, ObservableObject {
return
}
+ AppLog.app.notice("开始检查更新")
beginManualCheck()
showSettingsStatusMessage("正在检查更新")
updaterController.updater.checkForUpdateInformation()
@@ -76,6 +78,7 @@ final class AppUpdater: NSObject, ObservableObject {
return
}
+ AppLog.app.notice("自动检查更新已变更: enabled=\(isEnabled ? 1 : 0)")
updaterController.updater.automaticallyChecksForUpdates = isEnabled
refreshAutomaticCheckSetting()
}
diff --git a/CodexBar/Services/Workflow/CodexActivityMonitor.swift b/CodexBar/Services/Workflow/CodexActivityMonitor.swift
index 13d640a..41a3c9a 100644
--- a/CodexBar/Services/Workflow/CodexActivityMonitor.swift
+++ b/CodexBar/Services/Workflow/CodexActivityMonitor.swift
@@ -1,6 +1,7 @@
import AppKit
import Combine
import Foundation
+import os
/// 从本机 Hook JSONL 维护进程内实时任务状态, 是菜单栏; 活动卡片; 通知和触觉反馈的唯一任务状态来源
@MainActor
@@ -55,6 +56,7 @@ final class CodexActivityMonitor: ObservableObject {
guard let self else {
return
}
+ AppLog.activity.notice("系统唤醒, 立即重新读取")
if let reader = tailReader {
Task {
await reader.drainNow()
@@ -76,6 +78,7 @@ final class CodexActivityMonitor: ObservableObject {
private func setMonitoringEnabled(_ enabled: Bool) {
guard enabled else {
+ AppLog.activity.notice("已停止监控")
stopReaderAndClearState()
return
}
@@ -84,6 +87,8 @@ final class CodexActivityMonitor: ObservableObject {
return
}
+ AppLog.activity.notice("已开始监控")
+
tailReaderGeneration &+= 1
let generation = tailReaderGeneration
let reader = HookEventTailReader(
@@ -281,8 +286,11 @@ final class CodexActivityMonitor: ObservableObject {
refreshSnapshot(now: Date())
refreshSessionLifecycleNow()
backfillPromptStartTimesFromHistory()
+ let activeCount = snapshot.activeCount
+ AppLog.activity.notice("历史回放完成: activeTasks=\(activeCount)")
case let .live(events):
let pendingKeysBefore = Set(pendingTerminalTasks.keys)
+ let activeCountBefore = snapshot.activeCount
var transitions: [CodexActivityLiveTransition] = []
for event in events {
if let transition = apply(event) {
@@ -291,6 +299,14 @@ final class CodexActivityMonitor: ObservableObject {
}
refreshSnapshot(now: Date())
+ // 活跃数变化覆盖任务起止, transitions 覆盖等待批准
+ // 只看活跃数会漏掉 running 转 waitingApproval, 那一进一出恒抵消为零
+ let activeCountAfter = snapshot.activeCount
+ if activeCountAfter != activeCountBefore || !transitions.isEmpty {
+ AppLog.activity.notice(
+ "任务状态变化: from=\(activeCountBefore); to=\(activeCountAfter); transitions=\(transitions.count)"
+ )
+ }
publishLiveTransitions(transitions)
if !pendingTerminalTasks.isEmpty {
// 只有刚进入终态确认窗口的任务需要重置解析缓存重试定位 rollout
diff --git a/CodexBar/Services/Workflow/WorkflowService.swift b/CodexBar/Services/Workflow/WorkflowService.swift
index 235aa8a..9bad80b 100644
--- a/CodexBar/Services/Workflow/WorkflowService.swift
+++ b/CodexBar/Services/Workflow/WorkflowService.swift
@@ -2,6 +2,7 @@ import Combine
import CryptoKit
import Darwin
import Foundation
+import os
/// 从 Hook 原始事件维护每日聚合, 对外只发布 UI 需要的统计快照
actor WorkflowService {
@@ -76,6 +77,10 @@ actor WorkflowService {
do {
try rebuildResults.append(rebuildLocalData(for: dateKey))
} catch {
+ // 整批成功时这个原因不会往上抛, 摘要只带得走日期
+ AppLog.workflow.error(
+ "重建失败: date=\(dateKey, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"
+ )
failedDateKeys.append(dateKey)
if firstFailure == nil {
firstFailure = error
@@ -90,6 +95,9 @@ actor WorkflowService {
do {
try await syncService.markReplacementNeeded(for: normalizedDateKeys)
} catch {
+ AppLog.workflow.error(
+ "登记待替换记录失败: dates=\(normalizedDateKeys.count); detail=\(error.localizedDescription, privacy: .public)"
+ )
didFailReplacementMarking = true
}
@@ -110,6 +118,9 @@ actor WorkflowService {
failedDateKeys: failedDateKeys,
didFailSyncReplacementMarking: didFailReplacementMarking
)
+ AppLog.workflow.notice(
+ "重建完成: dates=\(summary.rebuiltDateCount); events=\(summary.eventCount); corruptLines=\(summary.corruptLineCount); failedDates=\(failedDateKeys.count)"
+ )
return WorkflowDataRebuildOutcome(snapshot: snapshot, summary: summary)
}
@@ -197,6 +208,9 @@ actor WorkflowService {
}
try pruneExpiredEventFiles()
} catch {
+ AppLog.workflow.error(
+ "维护未完成: detail=\(error.localizedDescription, privacy: .public)"
+ )
return
}
}
@@ -214,6 +228,9 @@ actor WorkflowService {
let result = try buildDailyAggregate(for: task)
didWrite = try commit(result, aggregates: &aggregates) || didWrite
} catch {
+ AppLog.workflow.error(
+ "聚合失败, 已标记待重建: date=\(task.dateKey, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"
+ )
markDirty(task.dateKey)
}
}
@@ -766,6 +783,10 @@ actor WorkflowService {
try WorkflowStorage.saveMaintenanceState(state)
}
+ // 保留期到点会真的删掉原始事件文件, 数据对不上时要能查到哪些日期被清掉了
+ AppLog.workflow.notice(
+ "已清理过期事件文件: dates=\(expiredDateKeys.count); oldest=\(expiredDateKeys.first ?? "-", privacy: .public)"
+ )
}
private func keepsIdentifiers(for dateKey: String) -> Bool {
diff --git a/CodexBar/Services/Workflow/WorkflowSyncScheduler.swift b/CodexBar/Services/Workflow/WorkflowSyncScheduler.swift
index 6b5af17..6143635 100644
--- a/CodexBar/Services/Workflow/WorkflowSyncScheduler.swift
+++ b/CodexBar/Services/Workflow/WorkflowSyncScheduler.swift
@@ -1,4 +1,5 @@
import Foundation
+import os
/// 合并工作流维护刷新中的同步请求, 避免频繁开关产生重复同步
@MainActor
@@ -109,6 +110,7 @@ final class WorkflowSyncScheduler {
}
private func startMaintenance(synchronize: Bool) {
+ AppLog.workflow.notice("开始维护: synchronize=\(synchronize ? 1 : 0)")
isRunning = true
pendingLocalMaintenance = false
@@ -128,6 +130,7 @@ final class WorkflowSyncScheduler {
}
private func finishMaintenance(synchronize: Bool) {
+ AppLog.workflow.notice("维护结束: synchronize=\(synchronize ? 1 : 0)")
isRunning = false
if synchronize {
@@ -161,6 +164,9 @@ final class WorkflowSyncScheduler {
)
)
} catch {
+ AppLog.workflow.error(
+ "重建请求失败: dates=\(request.dateKeys.count); detail=\(error.localizedDescription, privacy: .public)"
+ )
result = .failure(error)
}
diff --git a/CodexBar/Services/Workflow/WorkflowSyncService.swift b/CodexBar/Services/Workflow/WorkflowSyncService.swift
index 9010902..e94e63f 100644
--- a/CodexBar/Services/Workflow/WorkflowSyncService.swift
+++ b/CodexBar/Services/Workflow/WorkflowSyncService.swift
@@ -2,6 +2,7 @@ import CloudKit
import CryptoKit
import Foundation
import IOKit
+import os
import Security
nonisolated enum WorkflowSyncCloudKit {
@@ -124,9 +125,14 @@ actor WorkflowSyncService {
try await pruneCurrentDeviceRecordsIfNeeded(deviceId: deviceId, state: &state)
try saveState(state)
didSucceed = true
+ AppLog.sync.notice("同步完成")
} catch {
+ let reason = WorkflowSyncFailureReason.classify(error)
+ AppLog.sync.error(
+ "同步失败: reason=\(reason.rawValue, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"
+ )
invalidateAccountScopedCaches()
- failureMessage = WorkflowSyncFailureReason.classify(error).message
+ failureMessage = reason.message
try? saveState(state)
}
@@ -587,6 +593,10 @@ private extension WorkflowSyncService {
cachedRecords: loadCachedRecords()
)
} catch {
+ // 增量拉取退化成全量重建, 代价高得多, 反复出现说明游标或缓存有问题
+ AppLog.sync.notice(
+ "增量拉取失败, 改为全量重建: detail=\(error.localizedDescription, privacy: .public)"
+ )
try await rebuildCacheFromRemote()
}
}
@@ -709,6 +719,10 @@ private extension WorkflowSyncService {
cachedRecords: cachedRecords
)
} catch {
+ // 丢掉游标, 下次同步会从头拉一遍
+ AppLog.sync.notice(
+ "建立游标基线失败, 已丢弃游标: detail=\(error.localizedDescription, privacy: .public)"
+ )
try? fileManager.removeItem(at: cursorURL)
}
}
diff --git a/CodexBar/Views/Menu/CodexActivityCard.swift b/CodexBar/Views/Menu/CodexActivityCard.swift
index 7d8d0ba..9662117 100644
--- a/CodexBar/Views/Menu/CodexActivityCard.swift
+++ b/CodexBar/Views/Menu/CodexActivityCard.swift
@@ -82,6 +82,7 @@ struct CodexActivityCard: View {
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(Color.teal)
.transition(.opacity)
+ .help("已阻止系统休眠")
}
if content.otherTaskCount > 0 {
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index ee73c96..04ae4c3 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -435,30 +435,35 @@ private extension AppSettingsView {
}
}
- SettingsIndentedRow(alignment: .top) {
- Text(caption.message)
- .font(.caption)
- .foregroundStyle(caption.isError ? .red : .secondary)
- .fixedSize(horizontal: false, vertical: true)
- .contentTransition(.opacity)
-
- Spacer(minLength: 8)
-
- if caption.showsSystemSettingsButton {
- Button("打开系统设置") {
- keepAliveController.openSystemSettings()
+ if let caption {
+ SettingsIndentedRow(alignment: .top) {
+ Text(caption.message)
+ .font(.caption)
+ .foregroundStyle(caption.isError ? .red : .secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ .contentTransition(.opacity)
+
+ Spacer(minLength: 8)
+
+ if caption.showsSystemSettingsButton {
+ Button("打开系统设置") {
+ keepAliveController.openSystemSettings()
+ }
+ .controlSize(.small)
+ .fixedSize()
+ .transition(.opacity.combined(with: .move(edge: .trailing)))
}
- .controlSize(.small)
- .fixedSize()
- .transition(.opacity.combined(with: .move(edge: .trailing)))
}
+ .transition(.opacity)
}
}
.animation(Metrics.statusAnimation, value: caption)
.animation(Metrics.statusAnimation, value: keepAliveController.isEnabled)
}
- var keepAliveCaption: KeepAliveCaption {
+ /// 返回 nil 表示这一行整个收起
+ /// 正常运行时不必占一行说"一切正常", 是否正在阻止由主面板的咖啡杯标记呈现
+ var keepAliveCaption: KeepAliveCaption? {
if let errorMessage = keepAliveController.errorMessage {
return KeepAliveCaption(message: errorMessage, isError: true)
}
@@ -478,18 +483,13 @@ private extension AppSettingsView {
case .notRegistered, .notFound:
return KeepAliveCaption(message: "CodexBarHelper 尚未注册")
case .enabled:
- if keepAliveController.hasReachedMaximumDuration {
- let action = keepAliveController.isPreventingSleep
- ? "正恢复系统休眠"
- : "已允许系统休眠"
- return KeepAliveCaption(
- message: "已达到阻止休眠上限 (\(keepAliveController.maximumDuration.title)); \(action)"
- )
+ // 上限之外的运行态都收起; 达到上限要留一句, 否则开关开着却没生效无从解释
+ guard keepAliveController.hasReachedMaximumDuration else {
+ return nil
}
- if keepAliveController.isPreventingSleep {
- return KeepAliveCaption(message: "当前阻止系统休眠")
- }
- return KeepAliveCaption(message: "当前允许系统休眠")
+ return KeepAliveCaption(
+ message: "已到阻止休眠上限 (\(keepAliveController.maximumDuration.title))"
+ )
}
}
@@ -861,7 +861,7 @@ private extension AppSettingsView {
}
func refreshCodexVersionSection() {
- // 版本探测较慢且内部会合并并发请求; 连接信息只是缓存读取
+ // 版本检测较慢且内部会合并并发请求; 连接信息只是缓存读取
codexVersions.refresh()
statusViewModel.refreshCodexConnectionInfo()
}
diff --git a/CodexBarHelper/main.swift b/CodexBarHelper/main.swift
index b78675f..d18595a 100644
--- a/CodexBarHelper/main.swift
+++ b/CodexBarHelper/main.swift
@@ -122,7 +122,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
} catch {
let sentinelDirectoryPath = sentinelURL.deletingLastPathComponent().path
helperLog.error(
- "Helper 启动失败: 无法访问休眠设置目录; path=\(sentinelDirectoryPath, privacy: .public), detail=\(error.localizedDescription, privacy: .public)"
+ "Helper 启动失败: 无法访问休眠设置目录; path=\(sentinelDirectoryPath, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"
)
exit(EXIT_FAILURE)
}
@@ -224,17 +224,17 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
break
case let .unreadable(error):
// 不能用当前的 SleepDisabled 覆写损坏的记录: 当前值可能正是我们自己禁用的结果
- // 那会把「原本允许休眠」错记成「原本已禁用」, 让后续恢复永久跳过
+ // 那会把「原本允许休眠」错记成「原本已禁用」让后续恢复永久跳过
let sentinelPath = sentinelURL.path
helperLog.error(
- "休眠记录损坏, 拒绝覆写: path=\(sentinelPath, privacy: .public), detail=\(error.localizedDescription, privacy: .public)"
+ "休眠记录损坏: path=\(sentinelPath, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"
)
return -1
case .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)"
+ "读取休眠设置失败: error=\(current.result.exitCode); detail=\(current.result.output, privacy: .public)"
)
return current.result.exitCode == 0 ? -1 : current.result.exitCode
}
@@ -245,7 +245,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
} catch {
let sentinelPath = sentinelURL.path
helperLog.error(
- "保存休眠设置失败: path=\(sentinelPath, privacy: .public), detail=\(error.localizedDescription, privacy: .public)"
+ "保存休眠设置失败: path=\(sentinelPath, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"
)
return -1
}
@@ -257,7 +257,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
try? FileManager.default.removeItem(at: sentinelURL)
}
helperLog.error(
- "关闭系统休眠失败: error=\(result.exitCode), detail=\(result.output, privacy: .public)"
+ "关闭系统休眠失败: error=\(result.exitCode); detail=\(result.output, privacy: .public)"
)
return result.exitCode
}
@@ -271,6 +271,8 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
let previouslyDisabled: Bool
switch sentinelState() {
case .absent:
+ // 没接管过就没有要恢复的东西, 这个值只是占位, 不代表系统真实状态
+ // 必须保持 true: App 用它抑制补发合盖休眠, 换成实测值会让从未接管的这一轮把机器按睡
return SleepRestoreResult(exitCode: 0, restoredSleepDisabled: true)
case let .present(value):
previouslyDisabled = value
@@ -278,7 +280,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
// 读不出原值时按系统默认的「允许休眠」恢复
// 宁可多恢复一次(pmset 幂等), 也不能把 SleepDisabled=1 永久留给用户
helperLog.error(
- "读取休眠记录失败, 按允许休眠恢复: reason=\(trigger.rawValue, privacy: .public), detail=\(error.localizedDescription, privacy: .public)"
+ "读取休眠记录失败: reason=\(trigger.rawValue, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"
)
previouslyDisabled = false
}
@@ -287,7 +289,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
let 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)"
+ "恢复系统休眠失败: reason=\(trigger.rawValue, privacy: .public); SleepDisabled=\(previousValue); error=\(result.exitCode); detail=\(result.output, privacy: .public)"
)
return SleepRestoreResult(
exitCode: result.exitCode,
@@ -297,7 +299,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
try? FileManager.default.removeItem(at: sentinelURL)
helperLog.notice(
- "系统休眠已恢复: reason=\(trigger.rawValue, privacy: .public), SleepDisabled=\(previousValue)"
+ "系统休眠已恢复: reason=\(trigger.rawValue, privacy: .public); SleepDisabled=\(previousValue)"
)
return SleepRestoreResult(
exitCode: 0,
@@ -333,7 +335,10 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
guard let self else {
exit(EXIT_SUCCESS)
}
- _ = restoreSleep(trigger: .helperTermination)
+ // 和另外三个触发源一样先判断: 空闲态退出没有东西要恢复, 不必再 fork 一次 pmset
+ if sentinelNeedsRestore() {
+ _ = restoreSleep(trigger: .helperTermination)
+ }
exit(EXIT_SUCCESS)
}
source.resume()
@@ -365,17 +370,17 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
private func validateSentinelDirectory(_ info: stat) throws {
guard info.st_mode & S_IFMT == S_IFDIR else {
throw CodexBarHelperError.insecureSentinelDirectory(
- "目录类型错误: actual=\(fileTypeName(info.st_mode)), expected=directory"
+ "目录类型错误: actual=\(fileTypeName(info.st_mode)); expected=directory"
)
}
guard info.st_uid == 0 else {
throw CodexBarHelperError.insecureSentinelDirectory(
- "所有者错误: actual=\(info.st_uid), expected=0"
+ "所有者错误: actual=\(info.st_uid); expected=0"
)
}
guard info.st_mode & 0o022 == 0 else {
throw CodexBarHelperError.insecureSentinelDirectory(
- "目录权限错误: actual=\(permissionString(info.st_mode)), forbidden=0022"
+ "目录权限错误: actual=\(permissionString(info.st_mode)); forbidden=0022"
)
}
}
@@ -427,17 +432,17 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
}
guard info.st_mode & S_IFMT == S_IFREG else {
throw CodexBarHelperError.invalidSentinel(
- "文件类型错误: actual=\(fileTypeName(info.st_mode)), expected=file"
+ "文件类型错误: actual=\(fileTypeName(info.st_mode)); expected=file"
)
}
guard info.st_uid == 0 else {
throw CodexBarHelperError.invalidSentinel(
- "所有者错误: actual=\(info.st_uid), expected=0"
+ "所有者错误: actual=\(info.st_uid); expected=0"
)
}
guard info.st_mode & 0o022 == 0 else {
throw CodexBarHelperError.invalidSentinel(
- "文件权限错误: actual=\(permissionString(info.st_mode)), forbidden=0022"
+ "文件权限错误: actual=\(permissionString(info.st_mode)); forbidden=0022"
)
}
@@ -451,7 +456,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
}
guard let value = String(data: data, encoding: .utf8) else {
throw CodexBarHelperError.invalidSentinel(
- "文件编码错误: actual=unknown, expected=UTF-8"
+ "文件编码错误: actual=unknown; expected=UTF-8"
)
}
@@ -462,7 +467,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
return true
default:
throw CodexBarHelperError.invalidSentinel(
- "文件内容错误: actual=\(data.count), expected=0|1"
+ "文件内容错误: actual=\(data.count); expected=0|1"
)
}
}
@@ -490,7 +495,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
var status = SecCodeCopySelf(SecCSFlags(), &runningCode)
guard status == errSecSuccess, let runningCode else {
throw CodexBarHelperError.codeSigningValidationFailed(
- "读取运行签名失败: Operation=SecCodeCopySelf, Status=\(status)"
+ "读取运行签名失败: Operation=SecCodeCopySelf; Status=\(status)"
)
}
@@ -498,7 +503,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
status = SecCodeCopyStaticCode(runningCode, SecCSFlags(), &staticCode)
guard status == errSecSuccess, let staticCode else {
throw CodexBarHelperError.codeSigningValidationFailed(
- "读取静态签名失败: Operation=SecCodeCopyStaticCode, Status=\(status)"
+ "读取静态签名失败: Operation=SecCodeCopyStaticCode; Status=\(status)"
)
}
@@ -510,7 +515,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
)
guard status == errSecSuccess, let signingInformation else {
throw CodexBarHelperError.codeSigningValidationFailed(
- "读取签名信息失败: Operation=SecCodeCopySigningInformation, Status=\(status)"
+ "读取签名信息失败: Operation=SecCodeCopySigningInformation; Status=\(status)"
)
}
@@ -525,7 +530,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code
let helperSuffix = CodexBarHelperIPC.helperBundleIdentifierSuffix
guard helperIdentifier.hasSuffix(helperSuffix) else {
throw CodexBarHelperError.codeSigningValidationFailed(
- "Helper 标识符错误: actual=\(helperIdentifier), expected=*\(helperSuffix)"
+ "Helper 标识符错误: actual=\(helperIdentifier); expected=*\(helperSuffix)"
)
}
diff --git a/Shared/CodexBarHelperXPC.swift b/Shared/CodexBarHelperXPC.swift
index 8d5e907..cd5d6bc 100644
--- a/Shared/CodexBarHelperXPC.swift
+++ b/Shared/CodexBarHelperXPC.swift
@@ -18,6 +18,10 @@ nonisolated enum CodexBarHelperIPC {
}
@objc nonisolated protocol CodexBarHelperProtocol: AnyObject {
+ /// reply 的两个参数是 pmset 退出码, 与恢复写回的 SleepDisabled 值
+ /// 写回的是接管前的原值, 所以第二个参数不等于请求值: 系统原本就禁用休眠时恢复后仍是禁用
+ /// 但 helper 本轮没接管过或 pmset 操作失败时它只是占位的 true, 并非实测状态
+ /// 调用方要先确认退出码为 0, 且自己的接管过程没有被连接中断打断, 才能把它当成实测值
func setSleepDisabled(
_ disabled: Bool,
reply: @escaping @Sendable (Int32, Bool) -> Void
diff --git a/appcast.xml b/appcast.xml
index a55a849..9bd997b 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.5</title>
+ <sparkle:version>59</sparkle:version>
+ <sparkle:shortVersionString>3.5.5</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.5.5</sparkle:releaseNotesLink>
+ <pubDate>Mon, 27 Jul 2026 16:29:01 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.5.5.dmg" sparkle:edSignature="7SsxaIRyGOmmLK+x4v7hgRqd8EAUbFcD3/4InMLJBMY4YG5gBHj2/WPt7yW/Gh+k6aiw5u/bWBVN07NJVe07DQ==" length="5914638" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.5.4</title>
<sparkle:version>58</sparkle:version>