Skip to content

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

fix: 修复 Helper 安装状态与组件异常提示

Bob985591e3a9cc
diff --git a/CLAUDE.md b/CLAUDE.md
index ce18cb6..dd94dfa 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -145,6 +145,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- `hasRunningTasks` 与 `isRefreshingHelper` 都不带 `@Published` 标注,它们变得比结论频繁,各自发信号会把整个设置页拖着一起重算
- helper 只做固定的系统电源操作;不要给 root helper 增加网络、任意命令执行或其他文件访问能力
- helper 注册需求由防睡眠主开关与自动重置请求共同决定;自动重置开启时即使防睡眠关闭也要完成 `SMAppService` 注册和系统批准,设置行复用注册错误并单独展示唤醒计划同步错误
+- 关于页面和功能说明读取派生的 `helperInstallationStatus`;包完整且无注册错误时,`.notRegistered` 与 `.notFound` 均显示未安装;包校验异常优先于已授权状态,后续校验成功后清除,详见 [CodexBarHelper 安装与通信](Docs/DeveloperGuide/sleep-prevention.md#codexbarhelper-安装与通信)
- 自动重置与防睡眠从关闭切换为开启时统一通过 `HelperFeatureConfirmation` 显示确认;`.notRegistered` 与 `.notFound` 提示需要安装并授权后台运行,`.requiresApproval` 提示已安装但仍需授权,`.enabled` 只显示功能说明
- `ensureHelperRegistration()` 只负责注册与刷新 helper;Helper 授权系统设置仅由设置行的 `打开系统设置` 按钮调用 `openSystemSettings()` 打开,两个功能的开启动作不直接切换到系统设置
- `AutoResetWakeScheduler` 与防睡眠租约使用独立 XPC 连接,只同步下一次唤醒时间;距现在不超过 5 秒的时间不交给 helper,由 App 内定时任务直接进入到点执行路径
diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstrings
index 847f2ac..cf707de 100644
--- a/CodexBar/Resources/Localizable.xcstrings
+++ b/CodexBar/Resources/Localizable.xcstrings
@@ -2257,18 +2257,34 @@
}
}
},
+ "keep-alive.error.helper-assets-invalid" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "CodexBar Helper has invalid components or configuration. Please reinstall CodexBar"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "CodexBar Helper 组件或配置异常, 请重新安装 CodexBar"
+ }
+ }
+ }
+ },
"keep-alive.error.helper-assets-missing" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Service unavailable; reinstall CodexBar"
+ "value" : "CodexBar Helper is missing components or configuration. Please reinstall CodexBar"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "服务异常, 请重新安装 CodexBar"
+ "value" : "CodexBar Helper 组件或配置丢失, 请重新安装 CodexBar"
}
}
}
diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swift
index 2b16f44..25eb4b1 100644
--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift
+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift
@@ -46,11 +46,19 @@ final class KeepAliveController: ObservableObject {
/// 注册不成功时操作类错误只是下游噪音, 优先展示注册问题
var errorMessage: String? {
- (isEnabled ? registrationErrorMessage : nil) ?? operationErrorMessage
+ (isEnabled ? helperRegistrationErrorMessage : nil) ?? operationErrorMessage
}
var helperRegistrationErrorMessage: String? {
- registrationErrorMessage
+ helperPackageValidation.issue?.message ?? registrationErrorMessage
+ }
+
+ var helperInstallationStatus: HelperInstallationStatus {
+ HelperInstallationStatus(
+ registration: helperStatus,
+ packageIssue: helperPackageValidation.issue,
+ registrationError: registrationErrorMessage
+ )
}
/// 时长上限的状态转发给 UI, 使调用方不必知道 limiter 的存在
@@ -108,6 +116,7 @@ final class KeepAliveController: ObservableObject {
private let helperRuntimeStatusMonitor = HelperRuntimeStatusMonitor()
private var retryAttempt = 0
private var helperRegistrationTask: Task<Void, Never>?
+ private let helperPackageValidation = HelperPackageValidation()
/// 与 hasRunningTasks 同理: 只经由派生状态影响 UI, 自己不发信号
private var isRefreshingHelper = false
private var isAutoResetRequested = false
@@ -160,6 +169,9 @@ final class KeepAliveController: ObservableObject {
return
}
isStarted = true
+ helperPackageValidation.objectWillChange
+ .sink { [weak self] in self?.objectWillChange.send() }
+ .store(in: &cancellables)
// Hook 是本功能的依赖, 不是用户意图
// 只重新求值当前该不该防止系统睡眠, 绝不改写用户保存的开关
@@ -215,6 +227,7 @@ final class KeepAliveController: ObservableObject {
cancellables.removeAll()
cancelRetryTask()
cancelHelperRegistrationTask()
+ helperPackageValidation.cancel()
autoResetWakeScheduler.stop()
cancelExternalObservation()
startedRunningTaskIDs.removeAll()
@@ -265,6 +278,9 @@ final class KeepAliveController: ObservableObject {
}
private func refreshRegistrationAndSleepState() {
+ if isStarted {
+ helperPackageValidation.refresh()
+ }
guard helperRegistrationTask == nil else {
reconcileSleepState(trigger: .statusRefresh)
return
@@ -552,7 +568,7 @@ final class KeepAliveController: ObservableObject {
return
case .notRegistered, .notFound:
guard KeepAliveHelperConfiguration.assetsArePresent else {
- registrationErrorMessage = KeepAliveLocalizedMessage.helperAssetsMissing
+ helperPackageValidation.reportMissingAssets()
return
}
}
@@ -614,17 +630,24 @@ final class KeepAliveController: ObservableObject {
defer {
autoResetWakeScheduler.resumeAfterHelperInterruption()
}
- let updateResult = await replaceRegisteredHelper(service)
+ let updateError: Error?
+ do {
+ try await replaceRegisteredHelper(service)
+ updateError = nil
+ } catch is CancellationError {
+ return
+ } catch {
+ updateError = error
+ }
- guard !(updateResult.error is CancellationError),
- isStarted,
+ guard isStarted,
!Task.isCancelled else {
return
}
refreshHelperStatus()
var helperWasUpdated = false
- if updateResult.didUnregisterHelper,
+ if updateError == nil,
helperStatus.isRegisteredOrAwaitingApproval {
KeepAliveHelperConfiguration.recordRegistration(
defaults: defaults,
@@ -641,7 +664,7 @@ final class KeepAliveController: ObservableObject {
}
if !helperWasUpdated {
- let detail = updateResult.error?.localizedDescription ?? "readinessFailed"
+ let detail = updateError?.localizedDescription ?? "readinessFailed"
AppLog.keepAlive.error(
"Helper 注册更新失败: detail=\(detail, privacy: .public)"
)
@@ -655,28 +678,6 @@ final class KeepAliveController: ObservableObject {
}
}
- private func registerRefreshedHelper(_ service: SMAppService) async throws {
- await Task.yield()
-
- var retryDelays = KeepAliveHelperConfiguration.registrationRetryDelays.makeIterator()
- while true {
- do {
- try service.register()
- return
- } catch {
- let status = HelperStatus(service.status)
- if status.isRegisteredOrAwaitingApproval {
- return
- }
- guard KeepAliveHelperConfiguration.isTransientRegistrationError(error),
- let retryDelay = retryDelays.next() else {
- throw error
- }
- try await Task.sleep(for: retryDelay)
- }
- }
- }
-
/// @Published 在 willSet 无条件发信号, 不比较新旧值
/// refreshHelperStatus 每次 App 激活跑, releaseSleepPrevention 每条活动快照都会经过
/// 同值赋值会让菜单面板和设置页反复空转, 所以反复求值路径上的写入都走这里
@@ -1510,24 +1511,17 @@ final class KeepAliveController: ObservableObject {
}
extension KeepAliveController {
- private func replaceRegisteredHelper(_ service: SMAppService) async -> (didUnregisterHelper: Bool, error: Error?) {
- do {
- try Task.checkCancellation()
- guard await autoResetWakeScheduler.cancelBeforeHelperInterruption() else {
- throw KeepAliveError.wakeScheduleCancellationFailed
- }
- reconcileAutoResetWakeSchedule()
- try Task.checkCancellation()
- try await service.unregister()
- mayHaveHelperLease = false
- try Task.checkCancellation()
- try await registerRefreshedHelper(service)
- return (true, nil)
- } catch is CancellationError {
- return (false, CancellationError())
- } catch {
- return (false, error)
+ private func replaceRegisteredHelper(_ service: SMAppService) async throws {
+ try Task.checkCancellation()
+ guard await autoResetWakeScheduler.cancelBeforeHelperInterruption() else {
+ throw KeepAliveError.wakeScheduleCancellationFailed
}
+ reconcileAutoResetWakeSchedule()
+ try Task.checkCancellation()
+ try await service.unregister()
+ mayHaveHelperLease = false
+ try Task.checkCancellation()
+ try await KeepAliveHelperConfiguration.registerRefreshedHelper(service)
}
func setAutoResetRequested(_ requested: Bool) {
diff --git a/CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swift b/CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swift
index 168c30b..32e0e8a 100644
--- a/CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swift
+++ b/CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swift
@@ -1,5 +1,7 @@
+import Combine
import CryptoKit
import Foundation
+import Security
import ServiceManagement
@MainActor
@@ -55,6 +57,61 @@ enum KeepAliveHelperConfiguration {
&& FileManager.default.isExecutableFile(atPath: helperExecutableURL.path)
}
+ nonisolated static func validatePackage(appURL: URL, machServiceName: String) -> HelperPackageIssue? {
+ let helperURL = appURL.appending(path: "Contents/Resources/CodexBarHelper")
+ let plistURL = appURL.appending(path: "Contents/Library/LaunchDaemons/\(machServiceName).plist")
+ let fileManager = FileManager.default
+ guard fileManager.fileExists(atPath: plistURL.path),
+ fileManager.isExecutableFile(atPath: helperURL.path) else {
+ return .missing
+ }
+ guard let appIdentifier = Bundle(url: appURL)?.bundleIdentifier,
+ let plistData = try? Data(contentsOf: plistURL),
+ let plist = try? PropertyListSerialization.propertyList(from: plistData, format: nil) as? [String: Any],
+ plist["Label"] as? String == machServiceName,
+ plist["BundleProgram"] as? String == "Contents/Resources/CodexBarHelper",
+ (plist["AssociatedBundleIdentifiers"] as? [String])?.contains(appIdentifier) == true,
+ (plist["MachServices"] as? [String: Any])?[machServiceName] as? Bool == true else {
+ return .invalid
+ }
+ guard helperSignatureIsValid(helperURL: helperURL, appURL: appURL, machServiceName: machServiceName) else {
+ return .invalid
+ }
+ return nil
+ }
+
+ private nonisolated static func helperSignatureIsValid(helperURL: URL, appURL: URL, machServiceName: String) -> Bool {
+ let flags = SecCSFlags(rawValue: kSecCSCheckAllArchitectures | kSecCSStrictValidate).union(.noNetworkAccess)
+ var appCode: SecStaticCode?
+ var signingInformation: CFDictionary?
+ guard SecStaticCodeCreateWithPath(appURL as CFURL, SecCSFlags(), &appCode) == errSecSuccess,
+ let appCode,
+ SecStaticCodeCheckValidity(appCode, flags, nil) == errSecSuccess,
+ SecCodeCopySigningInformation(appCode, SecCSFlags(rawValue: kSecCSSigningInformation), &signingInformation) == errSecSuccess,
+ let values = signingInformation as NSDictionary?,
+ let teamIdentifier = values[kSecCodeInfoTeamIdentifier] as? String,
+ !teamIdentifier.isEmpty,
+ teamIdentifier.unicodeScalars.allSatisfy(CharacterSet.alphanumerics.contains),
+ !machServiceName.isEmpty,
+ machServiceName.unicodeScalars.allSatisfy(CharacterSet.alphanumerics.union(CharacterSet(charactersIn: ".-")).contains) else {
+ return false
+ }
+
+ // App 资源封印覆盖 plist, helper 另按客户端校验使用的签名团队验证全部架构
+ let requirementText = "anchor apple generic"
+ + " and certificate leaf[subject.OU] = \"\(teamIdentifier)\""
+ + " and identifier \"\(machServiceName)\""
+ var requirement: SecRequirement?
+ var helperCode: SecStaticCode?
+ guard SecRequirementCreateWithString(requirementText as CFString, SecCSFlags(), &requirement) == errSecSuccess,
+ let requirement,
+ SecStaticCodeCreateWithPath(helperURL as CFURL, SecCSFlags(), &helperCode) == errSecSuccess,
+ let helperCode else {
+ return false
+ }
+ return SecStaticCodeCheckValidity(helperCode, flags, requirement) == errSecSuccess
+ }
+
static func registrationNeedsRefresh(defaults: UserDefaults) -> Bool {
guard let fingerprint else {
return false
@@ -114,6 +171,28 @@ enum KeepAliveHelperConfiguration {
&& error.code == operationNotPermittedErrorCode
}
+ static func registerRefreshedHelper(_ service: SMAppService) async throws {
+ await Task.yield()
+
+ var retryDelays = registrationRetryDelays.makeIterator()
+ while true {
+ do {
+ try service.register()
+ return
+ } catch {
+ let status = KeepAliveController.HelperStatus(service.status)
+ if status.isRegisteredOrAwaitingApproval {
+ return
+ }
+ guard isTransientRegistrationError(error),
+ let retryDelay = retryDelays.next() else {
+ throw error
+ }
+ try await Task.sleep(for: retryDelay)
+ }
+ }
+ }
+
private static let registrationFingerprintKey = "KeepAlive.helperRegistrationFingerprint"
private static let pendingUpdateIdentifierKey = "KeepAlive.pendingHelperUpdateIdentifier"
private static let operationNotPermittedErrorCode = 1
@@ -151,3 +230,41 @@ enum KeepAliveHelperConfiguration {
.appending(path: CodexBarHelperIPC.daemonPlistName)
}
}
+
+@MainActor
+final class HelperPackageValidation: ObservableObject {
+ /// 包校验与安装前检查共用组件异常, 不写入注册操作错误
+ @Published private(set) var issue: HelperPackageIssue?
+ private var task: Task<Void, Never>?
+
+ func refresh() {
+ guard task == nil else { return }
+ let appURL = Bundle.main.bundleURL
+ let machServiceName = CodexBarHelperIPC.machServiceName
+ task = Task { [weak self] in
+ let worker = Task.detached(priority: .utility) {
+ KeepAliveHelperConfiguration.validatePackage(appURL: appURL, machServiceName: machServiceName)
+ }
+ let result = await worker.value
+ guard let self, !Task.isCancelled else { return }
+ task = nil
+ if issue != result {
+ issue = result
+ }
+ }
+ }
+
+ func reportMissingAssets() {
+ // 丢弃先前校验结果, 避免旧的正常结果覆盖刚确认的缺失
+ cancel()
+ if issue != .missing {
+ issue = .missing
+ }
+ refresh()
+ }
+
+ func cancel() {
+ task?.cancel()
+ task = nil
+ }
+}
diff --git a/CodexBar/Services/KeepAlive/KeepAliveModels.swift b/CodexBar/Services/KeepAlive/KeepAliveModels.swift
index b947a0a..018f58d 100644
--- a/CodexBar/Services/KeepAlive/KeepAliveModels.swift
+++ b/CodexBar/Services/KeepAlive/KeepAliveModels.swift
@@ -89,6 +89,29 @@ extension KeepAliveController {
}
}
+ enum HelperInstallationStatus: Equatable {
+ case notInstalled
+ case authorized
+ case requiresApproval
+ case unavailable(String)
+
+ init(registration: HelperStatus, packageIssue: HelperPackageIssue?, registrationError: String?) {
+ if let packageIssue {
+ self = .unavailable(packageIssue.message)
+ return
+ }
+ switch registration {
+ case .enabled:
+ self = .authorized
+ case .requiresApproval:
+ self = .requiresApproval
+ case .notRegistered, .notFound:
+ // 系统尚无后台注册记录时也会返回 notFound
+ self = registrationError.map(Self.unavailable) ?? .notInstalled
+ }
+ }
+ }
+
/// 防睡眠没生效时缺的是哪一项, 同时充当日志里的 reason= 取值
enum SleepBlockReason: String {
case notStarted
@@ -117,8 +140,23 @@ extension KeepAliveController {
}
}
+nonisolated enum HelperPackageIssue: Equatable, Sendable {
+ case missing
+ case invalid
+
+ var message: String {
+ switch self {
+ case .missing:
+ KeepAliveLocalizedMessage.helperAssetsMissing
+ case .invalid:
+ KeepAliveLocalizedMessage.helperAssetsInvalid
+ }
+ }
+}
+
nonisolated enum KeepAliveLocalizedMessage {
static let helperAssetsMissing = String(localized: "keep-alive.error.helper-assets-missing")
+ static let helperAssetsInvalid = String(localized: "keep-alive.error.helper-assets-invalid")
static let registrationFailed = String(localized: "keep-alive.error.registration-failed")
static let updateFailed = String(localized: "keep-alive.error.update-failed")
static let preventIdleSleepFailed = String(localized: "keep-alive.error.prevent-idle-sleep-failed")
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index 95c22de..5d257eb 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -293,9 +293,9 @@ private extension AppSettingsView {
VStack(alignment: .leading, spacing: Metrics.rowSpacing) {
codexVersionSection
LiquidGlassDivider()
- versionRow
+ HelperInstallationStatusRow(status: keepAliveController.helperInstallationStatus)
LiquidGlassDivider()
- HelperInstallationStatusRow(status: keepAliveController.helperStatus)
+ versionRow
LiquidGlassDivider()
githubProjectRow
}
@@ -489,26 +489,31 @@ private extension AppSettingsView {
guard autoResetSettings.isEnabled else {
return nil
}
- if let errorMessage = keepAliveController.helperRegistrationErrorMessage {
- return SettingsStatusCaption(message: errorMessage, isError: true)
+ if let caption = helperInstallationCaption {
+ return caption
+ }
+ guard let errorMessage = keepAliveController.helperRegistrationErrorMessage
+ ?? keepAliveController.autoResetWakeScheduleErrorMessage else {
+ return nil
}
+ return SettingsStatusCaption(message: errorMessage, isError: true)
+ }
- switch keepAliveController.helperStatus {
+ var helperInstallationCaption: SettingsStatusCaption? {
+ switch keepAliveController.helperInstallationStatus {
case .requiresApproval:
- return SettingsStatusCaption(
+ SettingsStatusCaption(
message: String(localized: "helper.status.authorization-required"),
showsSystemSettingsButton: true
)
- case .notRegistered, .notFound:
- return SettingsStatusCaption(
+ case .notInstalled:
+ SettingsStatusCaption(
message: String(localized: "helper.status.not-registered")
)
- case .enabled:
- guard let errorMessage = keepAliveController
- .autoResetWakeScheduleErrorMessage else {
- return nil
- }
- return SettingsStatusCaption(message: errorMessage, isError: true)
+ case let .unavailable(message):
+ SettingsStatusCaption(message: message, isError: true)
+ case .authorized:
+ nil
}
}
@@ -593,18 +598,12 @@ private extension AppSettingsView {
guard keepAliveController.isEnabled else {
return nil
}
- if keepAliveController.helperStatus == .requiresApproval {
- return SettingsStatusCaption(
- message: String(localized: "helper.status.authorization-required"),
- showsSystemSettingsButton: true
- )
+ if let caption = helperInstallationCaption {
+ return caption
}
if let errorMessage = keepAliveController.errorMessage {
return SettingsStatusCaption(message: errorMessage, isError: true)
}
- guard keepAliveController.helperStatus == .enabled else {
- return SettingsStatusCaption(message: String(localized: "helper.status.not-registered"))
- }
guard codexHookSettings.isVerified else {
return SettingsStatusCaption(message: String(localized: "hook.status.inactive"))
}
diff --git a/CodexBar/Views/Settings/HelperInstallationStatusRow.swift b/CodexBar/Views/Settings/HelperInstallationStatusRow.swift
index f0a1424..bac202e 100644
--- a/CodexBar/Views/Settings/HelperInstallationStatusRow.swift
+++ b/CodexBar/Views/Settings/HelperInstallationStatusRow.swift
@@ -1,7 +1,7 @@
import SwiftUI
struct HelperInstallationStatusRow: View {
- let status: KeepAliveController.HelperStatus
+ let status: KeepAliveController.HelperInstallationStatus
var body: some View {
HStack(spacing: SettingsRowMetrics.spacing) {
@@ -23,13 +23,13 @@ struct HelperInstallationStatusRow: View {
private var statusPresentation: (text: LocalizedStringKey, color: Color) {
switch status {
- case .notRegistered:
+ case .notInstalled:
("settings.about.helper.not-installed", .gray)
- case .enabled:
+ case .authorized:
("settings.about.helper.authorized", .green)
case .requiresApproval:
("settings.about.helper.requires-approval", .orange)
- case .notFound:
+ case .unavailable:
("settings.about.helper.unavailable", .red)
}
}
diff --git a/Docs/DeveloperGuide/sleep-prevention.md b/Docs/DeveloperGuide/sleep-prevention.md
index f009d8a..1c3a977 100644
--- a/Docs/DeveloperGuide/sleep-prevention.md
+++ b/Docs/DeveloperGuide/sleep-prevention.md
@@ -163,6 +163,15 @@ CodexBarHelper 通过 `SMAppService` 注册为 LaunchDaemon。App 和 CodexBarHe
- 防睡眠选项入口读取 `KeepAliveController.canShowOptions`,没有任务、低电量阻断、达到上限或 helper 刷新期间仍允许调整设置
- 自动重置和防睡眠开关关闭时,设置行不显示状态说明
+关于页面和两个功能说明统一读取 `helperInstallationStatus`。系统注册状态、包校验结果与操作错误分别保存:
+
+- `.notRegistered` 和 `.notFound` 在没有已知安装异常时显示“未安装”
+- App 启动和再次激活时,后台校验 Helper 可执行文件、plist 关键配置、App 资源签名及 Helper 的签名团队和标识;签名校验不访问网络
+- 确认组件缺失、配置异常或签名无效时显示“不可用”,即使系统仍返回 `.enabled`;后续包校验成功后清除该异常
+- 安装前发现组件缺失时只更新包异常并发起新校验,不另存一份注册错误;旧校验结果不能覆盖新发现的缺失,关闭功能后修复组件也能通过再次校验恢复显示
+- 待授权和已授权状态不会被历史注册错误覆盖;未注册且安装失败时显示“不可用”
+- 校验结果只保存在内存中,不证明 Helper 的每次运行都成功;XPC 超时和具体电源操作失败仍按原操作错误处理
+
唤醒计划采用系统状态收敛而不是只依赖正常退出清理:
- helper 每次启动都在开放 XPC listener 前清除固定 owner 的遗留事件,App 重连后再按最新目标重新安排
@@ -390,7 +399,7 @@ CodexBar 在确认自己拥有的系统设置已恢复后读取 clamshell 状态
- 连接失效会立即释放 App assertion,避免 UI 已降级但进程仍永久阻止空闲睡眠
- 旧请求通过 generation 失效,不依赖每条取消路径都成功撤回底层消息
-诊断时应区分 registration error 和 operation error。前者表示 helper 未安装、待批准或更新失败,后者表示已安装 helper 的某次切换没有得到可信结果。
+诊断时应区分系统注册状态、包校验异常、注册错误和操作错误。未安装与待批准属于注册状态;组件缺失、配置或签名无效属于包校验异常;注册或更新失败属于注册错误;已安装 helper 的某次切换未得到可信结果属于操作错误。
自动重置唤醒计划使用独立的有界同步策略:
@@ -421,6 +430,9 @@ App 更新可能改变内嵌 CodexBarHelper 的签名或内容。App 会记录 C
- App 强制退出或 XPC 断开后,watchdog 恢复 owned 状态
- 自动重置和防睡眠每次开启都显示确认,取消后保持关闭
- 未注册、等待批准和已批准三种 helper 状态的确认文案与功能说明正确
+- 包完整且没有注册错误时,`.notRegistered` 和 `.notFound` 均显示“未安装”
+- 在测试包中分别移除 Helper、移除或篡改 plist、破坏签名,启动或再次激活后显示“不可用”,已授权状态也不能掩盖包异常
+- 安装前发现缺失后,旧校验结果不覆盖新异常;关闭两个功能并修复完整 App 包后,再次激活能清除异常,关于页面仍显示状态
- 开启操作只触发 helper 注册,Helper 授权系统设置仅由设置行的 `打开系统设置` 按钮打开
- 自动重置选项入口只在开关开启且 helper 已批准时显示,条件失效后已展开面板关闭
- 自动重置开启且防睡眠关闭时仍能完成 helper 注册与批准
@@ -436,6 +448,7 @@ App 更新可能改变内嵌 CodexBarHelper 的签名或内容。App 会记录 C
## 关键源码
- [`KeepAliveController.swift`](../../CodexBar/Services/KeepAlive/KeepAliveController.swift)
+- [`KeepAliveHelperConfiguration.swift`](../../CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swift)
- [`SystemSleepService.swift`](../../CodexBar/Services/KeepAlive/SystemSleepService.swift)
- [`HelperRuntimeStatusMonitor.swift`](../../CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift)
- [`AutoResetWakeScheduler.swift`](../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift)
diff --git a/Docs/UserGuide/settings.md b/Docs/UserGuide/settings.md
index 3fc70d1..b7387c0 100644
--- a/Docs/UserGuide/settings.md
+++ b/Docs/UserGuide/settings.md
@@ -78,11 +78,23 @@ HTTP 代理也能转发 HTTPS 请求。只有代理端口本身支持 TLS 时才
| 重新建立连接 | 使用所选 Codex 来源重新连接,更新 Codex 后可用它立即切换到新版本 |
| Codex CLI / Codex APP | 查看检测到的版本,点击路径可复制 |
| 当前使用 | 当前连接所用的来源和版本 |
-| 不可用 | 之前使用或选择的来源已无法找到 |
+| 不可用(Codex 来源) | 之前使用或选择的来源已无法找到 |
+| CodexBar Helper | 查看后台组件的安装与授权状态 |
| CodexBar 版本 / 检查更新 | 查看版本并检查可用更新 |
| GitHub 项目 | 打开项目页面 |
| 退出 CodexBar | 退出 App |
连接期间暂时不能切换来源。连接失败原因显示在版本区域底部,可据此排查或重新选择来源。
+CodexBar Helper 状态始终显示在关于页面,不受自动重置和防睡眠开关影响:
+
+| 状态 | 含义 |
+| --- | --- |
+| 未安装 | 尚未注册,且未发现组件或安装异常;首次使用时属于正常状态 |
+| 未授权 | 已注册,仍需允许后台运行 |
+| 已授权 | 系统已允许后台运行,当前未发现组件异常;具体操作仍可能失败 |
+| 不可用 | 组件缺失、配置或签名异常,或未注册且安装失败 |
+
+发现组件异常时,即使之前已授权,也会显示“不可用”。处理方式见 [CodexBarHelper 无法注册](troubleshooting.md#codexbarhelper-无法注册)
+
返回 [用户指南](README.md)
diff --git a/Docs/UserGuide/troubleshooting.md b/Docs/UserGuide/troubleshooting.md
index d7640bc..da8d457 100644
--- a/Docs/UserGuide/troubleshooting.md
+++ b/Docs/UserGuide/troubleshooting.md
@@ -91,10 +91,12 @@
## CodexBarHelper 无法注册
-- 确认 `自动重置` 或 `防止系统睡眠` 已开启;关闭状态不显示 Helper 状态说明
-- Helper 等待系统批准时,点击设置行下方的 `打开系统设置` 并允许 CodexBar 后台运行
+- 在关于页面查看 `CodexBar Helper` 状态;功能开关关闭时仅隐藏对应设置行的说明,关于页面仍显示状态
+- 首次使用显示“未安装”属于正常状态;开启 `自动重置` 或 `防止系统睡眠` 并确认后,App 才会尝试安装和注册
+- 显示“未授权”时,点击已开启功能设置行下方的 `打开系统设置` 并允许 CodexBar 后台运行
- 确认 CodexBar 位于 Applications 中且 App 包完整
-- 如果提示服务异常或 CodexBarHelper 文件缺失,重新安装完整 CodexBar App
+- 提示 `CodexBar Helper 组件或配置丢失, 请重新安装 CodexBar` 时,包内缺少必要组件或配置;提示 `CodexBar Helper 组件或配置异常, 请重新安装 CodexBar` 时,配置或签名校验未通过;两种情况都需要重新安装完整 CodexBar App
+- 修复 App 包后,重新启动或再次激活 App 会重新校验;校验成功后自动清除组件异常,无需为了清除提示而开启功能
- 更新后持续失败时退出 CodexBar,重新打开并再次检查授权
## 自动重置没有按时执行
diff --git a/Docs/en/DeveloperGuide/sleep-prevention.md b/Docs/en/DeveloperGuide/sleep-prevention.md
index 7d0b2a5..fb6571e 100644
--- a/Docs/en/DeveloperGuide/sleep-prevention.md
+++ b/Docs/en/DeveloperGuide/sleep-prevention.md
@@ -163,6 +163,15 @@ Settings separates user confirmation, helper registration, and navigation to Hel
- Sleep-prevention options read `KeepAliveController.canShowOptions`; settings remain adjustable with no task, low-battery block, limit reached, or helper refresh
- Automatic Reset and sleep-prevention rows show no status explanation while their switches are off
+The About row and both feature captions use `helperInstallationStatus`. System registration, package validation, and operation errors remain separate facts:
+
+- `.notRegistered` and `.notFound` display Not Installed when there is no known installation failure
+- At startup and when the app becomes active, background validation checks the helper executable, key plist fields, the app resource seal, and the helper's signing team and identifier; signature validation does not access the network
+- Missing components, invalid configuration, or invalid signatures display Unavailable even when macOS still returns `.enabled`; a later successful package check clears the issue
+- Missing components found before registration update only the package issue and start a fresh check, without storing a duplicate registration error; older results cannot overwrite the new issue, and revalidation can restore the display after repairs even with both features off
+- Historical registration errors do not override pending approval or authorization; an unregistered helper with a failed installation displays Unavailable
+- Validation results stay in memory and do not guarantee successful execution; XPC timeouts and individual power-operation failures retain their existing error handling
+
Wake schedules converge from actual system state rather than depending only on normal-exit cleanup:
- Before opening the XPC listener on every startup, the helper removes stale events for its fixed owner; after reconnect, the app reschedules from the latest target
@@ -390,7 +399,7 @@ Sleep prevention uses bounded retries because each attempt reconstructs a privil
- Release the app assertion immediately on connection invalidation so a degraded UI does not coexist with indefinite process-level idle prevention
- Invalidate old requests by generation rather than relying on every cancellation path to retract the underlying message
-Diagnostics distinguish registration from operation errors. Registration means the helper is missing, awaiting approval, or failed to update. Operation error means an installed helper did not produce a trusted result for one transition.
+Diagnostics distinguish system registration status, package validation issues, registration errors, and operation errors. Not installed and awaiting approval are registration states. Missing components or invalid configuration or signatures are package issues. Failed registration or update produces a registration error. An operation error means an installed helper did not produce a trusted result for one transition.
Automatic Reset wake scheduling uses a separate bounded synchronization policy:
@@ -421,6 +430,9 @@ Validation must cover:
- Forced exit or XPC disconnect lets the watchdog restore owned state
- Automatic Reset and sleep prevention show confirmation every time they are enabled and remain off after cancellation
- Confirmation text and feature descriptions are correct for unregistered, awaiting-approval, and approved helper states
+- With a valid package and no registration error, both `.notRegistered` and `.notFound` display Not Installed
+- In a test bundle, separately remove the Helper, remove or alter the plist, and invalidate signatures; launch or reactivate to confirm Unavailable, including when already authorized
+- After detecting missing components before installation, older validation results cannot overwrite the new issue; disable both features, repair the complete app bundle, and reactivate to clear the issue while About continues showing the status
- Enabling only triggers helper registration; authorization settings opens solely from `Open System Settings` on the row
- Automatic Reset options appear only when enabled and approved and close when that condition fails
- Automatic Reset can register and gain approval while sleep prevention remains off
@@ -436,6 +448,7 @@ Validation must cover:
## Key Source Files
- [`KeepAliveController.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveController.swift)
+- [`KeepAliveHelperConfiguration.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swift)
- [`SystemSleepService.swift`](../../../CodexBar/Services/KeepAlive/SystemSleepService.swift)
- [`HelperRuntimeStatusMonitor.swift`](../../../CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift)
- [`AutoResetWakeScheduler.swift`](../../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift)
diff --git a/Docs/en/UserGuide/settings.md b/Docs/en/UserGuide/settings.md
index 4a2ae01..0948ad6 100644
--- a/Docs/en/UserGuide/settings.md
+++ b/Docs/en/UserGuide/settings.md
@@ -78,11 +78,23 @@ Automatic Reset runs independently of notifications. Configure result alerts in
| Reconnect | Reconnect using the selected source; use after upgrading Codex to switch immediately to the new version |
| Codex CLI / Codex APP | View detected versions; click a path to copy it |
| Currently Using | Source and version used by the current connection |
-| Unavailable | A previously used or selected source can no longer be found |
+| Unavailable (Codex source) | A previously used or selected source can no longer be found |
+| CodexBar Helper | View the background component's installation and authorization status |
| CodexBar Version / Check for Updates | View the version and check for updates |
| GitHub Project | Open the project page |
| Quit CodexBar | Exit the app |
Source selection is temporarily disabled while connecting. Connection failure reasons appear below the version area to help you troubleshoot or choose another source.
+CodexBar Helper status always appears in About, regardless of the Automatic Reset and sleep prevention switches:
+
+| Status | Meaning |
+| --- | --- |
+| Not Installed | Not yet registered, with no detected component or installation issue; normal on first use |
+| Not Authorized | Registered, but still needs permission to run in the background |
+| Authorized | Background execution is approved and no component issue is currently detected; individual operations can still fail |
+| Unavailable | Components are missing, configuration or signatures are invalid, or installation failed while unregistered |
+
+A detected component issue displays Unavailable even if authorization was previously granted. See [CodexBarHelper Cannot Be Registered](troubleshooting.md#codexbarhelper-cannot-be-registered).
+
Back to the [User Guide](README.md).
diff --git a/Docs/en/UserGuide/troubleshooting.md b/Docs/en/UserGuide/troubleshooting.md
index 0370d8b..fef9258 100644
--- a/Docs/en/UserGuide/troubleshooting.md
+++ b/Docs/en/UserGuide/troubleshooting.md
@@ -91,10 +91,12 @@ If Settings says `System sleep is disabled by another source`, CodexBar does not
## CodexBarHelper Cannot Be Registered
-- Confirm that `Automatic Reset` or `Prevent System Sleep` is enabled; Helper status is hidden while both are off
-- If the Helper is awaiting approval, click `Open System Settings` below the settings row and allow CodexBar to run in the background
+- Check `CodexBar Helper` in About; turning off a feature hides only its settings-row caption, while About still shows the status
+- Not Installed is normal on first use; the app attempts installation and registration after you enable `Automatic Reset` or `Prevent System Sleep` and confirm
+- For Not Authorized, click `Open System Settings` below an enabled feature's settings row and allow CodexBar to run in the background
- Confirm that CodexBar is in Applications and that the app bundle is complete
-- If the service is reported as unhealthy or the CodexBarHelper file is missing, reinstall the complete CodexBar app
+- `CodexBar Helper is missing components or configuration. Please reinstall CodexBar` means required bundle components or configuration are absent; `CodexBar Helper has invalid components or configuration. Please reinstall CodexBar` means configuration or signature validation failed; reinstall the complete CodexBar app in either case
+- After repairing the app bundle, restart or reactivate the app to recheck it; a successful check automatically clears the component issue without requiring either feature to be enabled
- If failures continue after an update, quit CodexBar, reopen it, and check authorization again
## Automatic Reset Did Not Run on Time