Skip to content

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

fix: 自动修复已开启的 Hook

Bob64212587764d
diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swift
index a8025c8..a6cd097 100644
--- a/CodexBar/Controllers/SettingsWindowController.swift
+++ b/CodexBar/Controllers/SettingsWindowController.swift
@@ -116,8 +116,7 @@ final class SettingsWindowController: HostingWindowController {
}
private func refreshSettingsState() {
- codexHookSettings.refresh()
- codexHookSettings.verifyInstalledHooks()
+ codexHookSettings.reconcileInstalledHooks()
codexCLINotificationSettings.refresh()
syncSettings.refresh()
menuBarQuotaSettings.refresh()
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index 24d7686..abaa0ca 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -444,7 +444,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
// 订阅时 CombineLatest 会同步发出当前值, 初始图标由订阅路径统一渲染
observeViewModel()
observeWorkflowSyncState()
- codexHookSettings.refresh()
+ codexHookSettings.reconcileInstalledHooks()
observeMainPanelHookState()
viewModel.startAutoRefresh()
}
@@ -1211,8 +1211,8 @@ final class StatusItemController: NSObject, NSMenuDelegate {
}
private func refreshWorkflowIfHookEnabled(performMaintenance: Bool) {
- // Hook 开关可能被外部 Codex 配置改动, 每次需要统计前都先读 hooks.json
- codexHookSettings.refresh()
+ // Hook 与额度使用同一刷新节奏, 配置和信任状态损坏后都能自动收敛
+ codexHookSettings.reconcileInstalledHooks()
guard codexHookSettings.isEnabled else {
workflowSyncScheduler.clearPendingMaintenance()
return
diff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swift
index 43460f0..270d8be 100644
--- a/CodexBar/Services/Settings/CodexHookSettings.swift
+++ b/CodexBar/Services/Settings/CodexHookSettings.swift
@@ -5,27 +5,27 @@ import os
/// 设置页的 Codex Hook 开关状态机, 同时管理 hooks.json 和 Codex 信任状态
@MainActor
final class CodexHookSettings: ObservableObject {
- static let minimumSupportedCodexVersion = CodexCLIMinimumVersion.hook
-
+ /// 当前进程中的 Hook 开启状态, 首次从现有配置恢复
+ /// 开启后配置缺失视为需要自愈, 只有显式关闭或明确的低版本会置为 false
@Published private(set) var isEnabled = false
@Published private(set) var isUpdating = false
/// 最近一次校验的明确结论: Codex 会不会真的执行 CodexBar 的 Hook
- /// 乐观默认: 校验只在设置窗口打开时跑, 没有反证之前不能把依赖 Hook 的功能关掉
+ /// 乐观默认: 启动对账开始前没有反证, 不能提前把依赖 Hook 的功能关掉
/// 只由明确结论写入两个方向, RPC 失败或被取消时保留上次的值:
/// 连不上 app-server 不说明 Hook 坏了, 那时置灰会把好用的功能关掉
@Published private(set) var isVerified = true
- /// Hook 链路真的通不通: hooks.json 里装着, 且最近一次校验没有明确失败
+ /// Hook 链路真的通不通: 当前进程中开启, 且最近一次校验没有明确失败
/// 依赖 Hook 的下游 (防睡眠, 任务类通知) 一律看这个
- /// isEnabled 只说明装了, Codex 那边全局关掉 hooks 或者不信任我们的 handler 时它照样是 true
+ /// Codex 那边全局关掉 hooks 或者不信任我们的 handler 时 isEnabled 照样是 true
var isOperable: Bool {
isEnabled && isVerified
}
- /// 读取 hooks.json 失败, 由 refresh() 独立维护
+ /// 读取 hooks.json 失败, 由 refreshInstallationState() 独立维护
@Published private var readErrorMessage: String?
/// 开关操作与 Hook 校验的结果, 只能由下一次操作或校验覆盖
- /// 与读取类错误分开存储: refresh() 每 60 秒被调用一次, 不能抹掉校验告警
+ /// 与读取类错误分开存储: 每轮对账都会读取配置, 不能抹掉校验告警
@Published private var operationErrorMessage: String?
var errorMessage: String? {
@@ -36,8 +36,8 @@ final class CodexHookSettings: ObservableObject {
private let fileManager: FileManager
private let codexStatusService: CodexStatusService
private let updateCoordinator = RefreshTaskCoordinator()
- /// refresh() 上次读到的安装结论, 首次读取前为 nil
- /// 不能用 isEnabled 代替: 它的初始值是 false, 会把首次读取当成一次配置变化
+ /// refreshInstallationState() 上次读到的安装结论, 首次读取前为 nil
+ /// 不能用 isEnabled 代替: 开启后它会刻意不跟随外部配置丢失
private var lastKnownInstalled: Bool?
init(
@@ -52,21 +52,30 @@ final class CodexHookSettings: ObservableObject {
// MARK: - 对外入口
- func refresh() {
+ private func refreshInstallationState() {
do {
let config = try readConfigIfPresent()
let installed = Self.containsAnyCodexBarHook(
in: config,
executablePath: currentExecutablePath
)
+ if installed {
+ isEnabled = true
+ }
+ let isComplete = Self.containsAllCodexBarHooks(
+ in: config,
+ executablePath: currentExecutablePath
+ )
// 每次开面板都会读一遍, 无条件记会刷屏
// 只在结论变了才记, 外部改动 ~/.codex/hooks.json 就是从这条看出来的
// 首次读取没有可比的上次值; 拿 isEnabled 的初始 false 去比, 会让装了 Hook 的用户每次启动误报一条
if let lastKnownInstalled, lastKnownInstalled != installed {
- AppLog.hooks.notice("Hook 配置变化: enabled=\(installed ? 1 : 0)")
+ AppLog.hooks.notice("Hook 配置变化: installed=\(installed ? 1 : 0)")
}
lastKnownInstalled = installed
- isEnabled = installed
+ if isEnabled, !isComplete {
+ assignVerified(false, reason: .configurationDamaged)
+ }
readErrorMessage = nil
} catch {
// 只有 I/O 失败和 JSON 格式错误会走到这里, 它们对「Hook 装没装」不提供信息
@@ -88,13 +97,14 @@ final class CodexHookSettings: ObservableObject {
}
}
- func verifyInstalledHooks() {
+ func reconcileInstalledHooks() {
+ refreshInstallationState()
guard isEnabled, !isUpdating else {
return
}
runLatestUpdate(showProgress: false) { settings, generation in
- await settings.verifyInstalledHooksWithAppServer(generation: generation)
+ await settings.reconcileInstalledHooks(generation: generation)
}
}
@@ -107,23 +117,88 @@ final class CodexHookSettings: ObservableObject {
try ensureCurrentUpdate(generation)
try await ensureCodexHooksGloballyEnabled()
try ensureCurrentUpdate(generation)
+ try writeCodexBarHookConfig(enabled: true)
+ try ensureCurrentUpdate(generation)
+ isEnabled = true
+ await verifyInstalledHooksWithAppServer(generation: generation)
+ } else {
+ try await disableCodexBarHooks(generation: generation)
}
+ } catch is CancellationError {
+ return
+ } catch {
+ handleApplyError(error, generation: generation)
+ }
+ }
- // 关闭前先通过 hooks/list 拿到 key
- // hooks.json 删除后 app-server 就无法再反查这些 key
- let cleanupPlan = try await hookTrustCleanupPlan(isDisabling: !enabled, generation: generation)
- try writeCodexBarHookConfig(enabled: enabled)
+ /// 与手动关闭共用同一事务, 自动关闭也不会遗留另一套清理语义
+ private func disableCodexBarHooks(generation: Int) async throws {
+ // 关闭前先通过 hooks/list 拿到 key
+ // hooks.json 删除后 app-server 就无法再反查这些 key
+ let cleanupPlan = try await hookTrustCleanupPlan(generation: generation)
+ try writeCodexBarHookConfig(enabled: false)
+ try ensureCurrentUpdate(generation)
+ isEnabled = false
+ await cleanupCodexHookTrust(
+ removing: cleanupPlan.keys,
+ discoveryError: cleanupPlan.discoveryError,
+ generation: generation
+ )
+ }
+
+ private func reconcileInstalledHooks(generation: Int) async {
+ do {
+ try await ensureCodexHookVersionSupported()
try ensureCurrentUpdate(generation)
- isEnabled = enabled
- if enabled {
- await verifyInstalledHooksWithAppServer(generation: generation)
- } else {
- await cleanupCodexHookTrust(
- removing: cleanupPlan.keys,
- discoveryError: cleanupPlan.discoveryError,
- generation: generation
- )
+ } catch is CancellationError {
+ return
+ } catch let error as HookConfigError {
+ guard case .unsupportedCodexVersion = error else {
+ handleVerificationError(error, generation: generation)
+ return
}
+
+ await disableUnsupportedCodexBarHooks(error: error, generation: generation)
+ return
+ } catch {
+ handleVerificationError(error, generation: generation)
+ return
+ }
+
+ do {
+ // 全局开关关闭时不写用户文件, 等 Codex 恢复后再补齐
+ let globallyDisabled = try await readGlobalHookDisabled()
+ try ensureCurrentUpdate(generation)
+ guard !globallyDisabled else {
+ assignVerified(false, reason: .globallyDisabled)
+ operationErrorMessage = HookConfigError.hooksGloballyDisabled.localizedDescription
+ return
+ }
+
+ try reconcileCodexBarHookConfig()
+ try ensureCurrentUpdate(generation)
+
+ try await validateInstalledHooksWithAppServer()
+ try ensureCurrentUpdate(generation)
+ assignVerified(true, reason: .verified)
+ operationErrorMessage = nil
+ } catch is CancellationError {
+ return
+ } catch {
+ handleVerificationError(error, generation: generation)
+ }
+ }
+
+ private func disableUnsupportedCodexBarHooks(error: HookConfigError, generation: Int) async {
+ assignVerified(false, reason: .unsupportedVersion)
+
+ do {
+ try await disableCodexBarHooks(generation: generation)
+ try ensureCurrentUpdate(generation)
+ if operationErrorMessage == nil {
+ operationErrorMessage = error.localizedDescription
+ }
+ AppLog.hooks.notice("Hook 已自动关闭: reason=unsupportedVersion")
} catch is CancellationError {
return
} catch {
@@ -152,21 +227,26 @@ final class CodexHookSettings: ObservableObject {
operationErrorMessage = nil
} catch is CancellationError {
return
- } catch let error as HookConfigError {
- guard updateCoordinator.canCommit(generation) else {
- return
- }
+ } catch {
+ handleVerificationError(error, generation: generation)
+ }
+ }
+ private func handleVerificationError(_ error: Error, generation: Int) {
+ guard updateCoordinator.canCommit(generation) else {
+ return
+ }
+
+ if let error = error as? HookConfigError {
// HookConfigError 是明确结论: Codex 答复了, 只是答复说这条链路不通
assignVerified(false, reason: .validationFailed)
operationErrorMessage = error.localizedDescription
- } catch {
- guard updateCoordinator.canCommit(generation) else {
- return
- }
-
+ } else {
// 这一支是"验不了"而不是"确认不通", isVerified 保留上次的值
- operationErrorMessage = String(localized: "hook.error.verification-failed", defaultValue: "\(error.localizedDescription)")
+ operationErrorMessage = String(
+ localized: "hook.error.verification-failed",
+ defaultValue: "\(error.localizedDescription)"
+ )
}
}
@@ -235,7 +315,7 @@ final class CodexHookSettings: ObservableObject {
AppLog.hooks.error(
"Hook 写入失败: detail=\(error.localizedDescription, privacy: .public)"
)
- refresh()
+ refreshInstallationState()
operationErrorMessage = String(localized: "hook.error.configuration-failed")
}
}
@@ -264,19 +344,20 @@ private extension CodexHookSettings {
struct CodexHookTrustCleanupPlan {
let keys: Set<String>
let discoveryError: Error?
-
- static let empty = Self(keys: [], discoveryError: nil)
}
/// Hook 链路校验结论的变化理由, 只用于日志的 reason= 取值
enum HookVerificationReason: String {
+ case configurationDamaged
case globallyDisabled
+ case unsupportedVersion
case validationFailed
case verified
}
enum HookConfigError: LocalizedError {
case invalidFormat
+ case configurationFailed
case hooksGloballyDisabled
case codexVersionUnavailable(minimum: String)
case unsupportedCodexVersion(minimum: String)
@@ -286,6 +367,8 @@ private extension CodexHookSettings {
switch self {
case .invalidFormat:
String(localized: "hook.error.invalid-config-format")
+ case .configurationFailed:
+ String(localized: "hook.error.configuration-failed")
case .hooksGloballyDisabled:
String(localized: "hook.status.disabled-by-codex")
case let .codexVersionUnavailable(minimum):
@@ -307,7 +390,7 @@ private extension CodexHookSettings {
switch self {
case .hooksGloballyDisabled, .codexVersionUnavailable, .unsupportedCodexVersion:
true
- case .invalidFormat, .hookValidationFailed:
+ case .invalidFormat, .configurationFailed, .hookValidationFailed:
false
}
}
@@ -343,7 +426,7 @@ private extension CodexHookSettings {
/// 检查实际用于 hooks/list 的 app-server 握手版本
/// 不能只看磁盘版本, 否则升级后尚未重连的旧进程会被误判为可用
func ensureCodexHookVersionSupported() async throws {
- let minimumVersion = Self.minimumSupportedCodexVersion
+ let minimumVersion = CodexCLIMinimumVersion.hook
let connectionInfo = try await codexStatusService.readyConnectionInfo()
guard let currentVersion = connectionInfo.version,
let isSupported = CodexCLIVersionReader.isVersion(
@@ -372,7 +455,17 @@ private extension CodexHookSettings {
hooksURL: hooksURL
)
if !entries.isEmpty {
- try await trustCodexBarHooks(entries)
+ do {
+ try await trustCodexBarHooks(entries)
+ } catch {
+ AppLog.hooks.error(
+ "Hook 信任自愈失败: detail=\(error.localizedDescription, privacy: .public)"
+ )
+ throw HookConfigError.hookValidationFailed(
+ String(localized: "hook.status.untrusted")
+ )
+ }
+ AppLog.hooks.notice("Hook 信任状态已自愈: keys=\(entries.count)")
response = try await codexStatusService.listCodexHooks(cwds: [hooksListWorkingDirectory])
}
@@ -385,11 +478,7 @@ private extension CodexHookSettings {
}
}
- func hookTrustCleanupPlan(isDisabling: Bool, generation: Int) async throws -> CodexHookTrustCleanupPlan {
- guard isDisabling else {
- return .empty
- }
-
+ func hookTrustCleanupPlan(generation: Int) async throws -> CodexHookTrustCleanupPlan {
do {
let keys = try await codexBarHookTrustKeysFromAppServer()
try ensureCurrentUpdate(generation)
@@ -411,7 +500,7 @@ private extension CodexHookSettings {
)
if enabled {
- try Self.installCodexBarHooks(
+ _ = try Self.reconcileCodexBarHooks(
in: &config,
executablePath: currentExecutablePath
)
@@ -422,6 +511,32 @@ private extension CodexHookSettings {
AppLog.hooks.notice("Hook 配置已写入: enabled=\(enabled ? 1 : 0)")
}
+ func reconcileCodexBarHookConfig() throws {
+ var config = try readConfigIfPresent()
+ let repairedEvents = try Self.reconcileCodexBarHooks(
+ in: &config,
+ executablePath: currentExecutablePath
+ )
+ guard !repairedEvents.isEmpty else {
+ return
+ }
+
+ do {
+ try write(config)
+ } catch {
+ AppLog.hooks.error(
+ "Hook 补齐写入失败: detail=\(error.localizedDescription, privacy: .public)"
+ )
+ throw HookConfigError.configurationFailed
+ }
+ let events = repairedEvents.map(\.rawValue).joined(separator: ",")
+ let details = LogFields.joined(
+ "count=\(repairedEvents.count)",
+ "events=\(events)"
+ )
+ AppLog.hooks.notice("Hook 配置已自愈: \(details, privacy: .public)")
+ }
+
func codexBarHookTrustKeysFromAppServer() async throws -> Set<String> {
let response = try await codexStatusService.listCodexHooks(cwds: [hooksListWorkingDirectory])
return Self.codexBarHookTrustKeys(
@@ -573,19 +688,57 @@ private extension CodexHookSettings {
}
}
- static func installCodexBarHooks(in config: inout JSONObject, executablePath: String) throws {
+ static func containsAllCodexBarHooks(in config: JSONObject, executablePath: String) -> Bool {
+ guard let hooks = config[hooksKey] as? JSONObject else {
+ return false
+ }
+
+ return CodexHookEvent.allCases.allSatisfy { event in
+ guard let groups = hooks[event.configName] as? JSONArray else {
+ return false
+ }
+
+ return isCanonicalCodexBarEvent(
+ groups,
+ event: event,
+ executablePath: executablePath
+ )
+ }
+ }
+
+ static func reconcileCodexBarHooks(
+ in config: inout JSONObject,
+ executablePath: String
+ ) throws -> [CodexHookEvent] {
var hooks = try hooksObject(from: config)
+ var repairedEvents: [CodexHookEvent] = []
- // 每个事件追加一个独立 group, 避免和用户已有 group 混写
+ // 每个事件只保留一个标准独立 group, 不和用户已有 group 混写
for event in CodexHookEvent.allCases {
var groups = try eventGroups(named: event.configName, from: hooks)
+ guard !isCanonicalCodexBarEvent(
+ groups,
+ event: event,
+ executablePath: executablePath
+ ) else {
+ continue
+ }
+
+ groups = groups.compactMap {
+ groupRemovingCodexBarHandlers(
+ from: $0,
+ executablePath: executablePath
+ )
+ }
groups.append([
hooksKey: [codexBarHookHandler(for: event, executablePath: executablePath)]
])
hooks[event.configName] = groups
+ repairedEvents.append(event)
}
config[hooksKey] = hooks
+ return repairedEvents
}
static func removeCodexBarHooks(
@@ -822,6 +975,51 @@ private extension CodexHookSettings {
} ?? false
}
+ static func isCanonicalCodexBarEvent(
+ _ groups: JSONArray,
+ event: CodexHookEvent,
+ executablePath: String
+ ) -> Bool {
+ let managedHandlerCount = groups.reduce(into: 0) { count, group in
+ count += handlers(from: group)?.count(where: {
+ isCurrentCodexBarHandler($0, executablePath: executablePath)
+ }) ?? 0
+ }
+ guard managedHandlerCount == 1 else {
+ return false
+ }
+
+ return groups.contains {
+ isCanonicalCodexBarGroup(
+ $0,
+ event: event,
+ executablePath: executablePath
+ )
+ }
+ }
+
+ static func isCanonicalCodexBarGroup(
+ _ group: Any,
+ event: CodexHookEvent,
+ executablePath: String
+ ) -> Bool {
+ guard let group = group as? JSONObject,
+ group.count == 1,
+ let handlers = handlers(from: group),
+ handlers.count == 1,
+ let handler = handlers.first as? JSONObject,
+ handler.count == 3,
+ handler[hookTypeKey] as? String == hookCommandType,
+ handler[hookCommandKey] as? String == hookCommand(executablePath: executablePath),
+ let timeout = handler[hookTimeoutKey] as? NSNumber else {
+ return false
+ }
+
+ return timeout.doubleValue == Double(
+ WorkflowHookEventRecorder.hookTimeoutSeconds(for: event)
+ )
+ }
+
static func groupRemovingCodexBarHandlers(
from group: Any,
executablePath: String
@@ -850,26 +1048,18 @@ private extension CodexHookSettings {
return group[hooksKey] as? JSONArray
}
+ /// 管理项身份只由当前可执行路径和 --hook-event 确定
+ /// type 本身可能损坏, 不能用它决定是否允许自愈或清理
static func isCurrentCodexBarHandler(
_ handler: Any,
executablePath: String
) -> Bool {
- guard let command = commandIfCommandHandler(handler) else {
- return false
- }
-
- return isCodexBarCommand(command, executablePath: executablePath)
- }
-
- /// 仅当 handler 是 type == "command" 时返回其 command 字符串, 否则 nil
- private static func commandIfCommandHandler(_ handler: Any) -> String? {
guard let handler = handler as? JSONObject,
- handler[hookTypeKey] as? String == hookCommandType,
let command = handler[hookCommandKey] as? String else {
- return nil
+ return false
}
- return command
+ return isCodexBarCommand(command, executablePath: executablePath)
}
static func codexBarHookHandler(
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index 1aabefa..abe2817 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -81,12 +81,11 @@ struct AppSettingsView: View {
refreshStatusRows()
}
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
- codexHookSettings.refresh()
+ codexHookSettings.reconcileInstalledHooks()
syncSettings.refresh()
menuBarQuotaSettings.refresh()
mainPanelSettings.refresh()
autoResetSettings.refresh()
- codexHookSettings.verifyInstalledHooks()
refreshStatusRows()
}
.onReceive(NotificationCenter.default.publisher(for: .settingsWindowDidOpen)) { _ in
diff --git a/Config/Version.xcconfig b/Config/Version.xcconfig
index 87e76ed..850aed7 100644
--- a/Config/Version.xcconfig
+++ b/Config/Version.xcconfig
@@ -1,2 +1,2 @@
-MARKETING_VERSION = 3.6.11
-CURRENT_PROJECT_VERSION = 78
+MARKETING_VERSION = 3.6.12
+CURRENT_PROJECT_VERSION = 79
diff --git a/Docs/DeveloperGuide/hook-and-aggregation.md b/Docs/DeveloperGuide/hook-and-aggregation.md
index 44cc93b..80ff15f 100644
--- a/Docs/DeveloperGuide/hook-and-aggregation.md
+++ b/Docs/DeveloperGuide/hook-and-aggregation.md
@@ -70,7 +70,7 @@ Codex Hook
- 禁用时只移除精确匹配的 CodexBar handler
- 无法识别的配置保持原样
-`isEnabled` 只表示 handler 存在,`isVerified` 表示最近一次 app-server 校验通过。UI 只有在 `isOperable` 成立时把 Hook 当作可工作数据源。
+`isEnabled` 表示当前进程中的 Hook 开启状态,首次从现有 CodexBar handler 恢复。`isVerified` 表示最近一次 app-server 校验通过。UI 只有在 `isOperable` 成立时把 Hook 当作可工作数据源。
### 为什么安装和验证是两件事
@@ -84,10 +84,23 @@ Codex Hook
- app-server 解析到其他来源文件
- handler 处于 untrusted 或 modified
-因此 `isEnabled` 是本地配置事实,`isVerified` 是 Codex 对当前来源的最近明确结论。防睡眠和任务通知只依赖两者合成的 `isOperable`
+因此 `isEnabled` 是当前进程的开关状态,`isVerified` 是 Codex 对当前来源的最近明确结论。防睡眠和任务通知只依赖两者合成的 `isOperable`
临时 RPC 失败只代表本轮无法验证,不能反推 handler 已失效。此时保留上一次明确结论,同时展示操作错误供用户排查。
+### 已开启 Hook 的对账
+
+App 启动、设置状态刷新、菜单面板打开以及每轮额度刷新完成后,都会对账已开启的 CodexBar Hook。额度自动刷新正常每 60 秒完成一轮,因此配置和信任数据通常会在 60 秒内自动收敛:
+
+- 只有已确认的实际 app-server 版本低于当前 Hook 最低版本时,才按手动关闭流程移除 CodexBar handler 和对应信任项
+- 版本无法确认或 RPC 临时失败时保留用户配置
+- 配置在当前进程中丢失不会关闭开关,而是标记配置损坏并触发自愈
+- 版本受支持时遍历 `CodexHookEvent.allCases`,为缺失或非标准事件重建独立 group,然后复用信任和完整性校验
+- 信任项缺失或哈希变化时,只修复 `command`、`sourcePath` 和 `event` 都属于当前 CodexBar 的条目
+- 必需事件全部存在时不写 `hooks.json`
+
+对账以当前必需事件集合和文件实际内容为依据,不保存一次性迁移标记。因此未来新增事件或用户手动删除必需 handler 时都会走同一条自愈路径。如果 App 启动前已经没有可识别的 CodexBar handler,首次读取无法恢复开启状态,Hook 保持关闭。
+
### 启用事务的顺序
```text
diff --git a/Docs/UserGuide/activity-and-hook.md b/Docs/UserGuide/activity-and-hook.md
index b92fc14..d6a2be0 100644
--- a/Docs/UserGuide/activity-and-hook.md
+++ b/Docs/UserGuide/activity-and-hook.md
@@ -38,7 +38,7 @@ CodexBar Hook 会在 Codex 的关键事件发生时记录少量结构化字段
4. 开启 `CodexBar Hook`
5. 等待开关完成配置和校验
-CodexBar 会在每次打开设置窗口或 App 重新激活时重新检查已安装 Hook。
+CodexBar 会在启动、打开菜单、每次打开设置窗口、App 重新激活以及每轮额度刷新完成后检查已开启 Hook。额度自动刷新正常每 60 秒完成一轮,必要事件配置或信任项缺失时会自动修复。
## 配置文件会发生什么变化
diff --git a/Docs/UserGuide/troubleshooting.md b/Docs/UserGuide/troubleshooting.md
index b3eea48..94355cc 100644
--- a/Docs/UserGuide/troubleshooting.md
+++ b/Docs/UserGuide/troubleshooting.md
@@ -43,7 +43,7 @@ CodexBar 优先使用全局 Codex CLI,关于页面的 `当前使用` 标记可
| --- | --- | --- |
| 需要更高 Codex 版本 | 当前 app-server 版本不足 | 更新 Codex 后重启 CodexBar |
| Codex Hook 已全局关闭 | `features.hooks` 已禁用 | 在 Codex 配置中重新启用 Hooks |
-| CodexBar Hook 已不完整 | 至少一个必要事件缺少当前 handler | 关闭后重新开启 CodexBar Hook |
+| CodexBar Hook 已不完整 | 至少一个必要事件缺少当前 handler | 重新打开设置触发自动补齐,仍未恢复时关闭后重新开启 Hook |
| CodexBar Hook 未被信任 | Codex 仍把 handler 判定为未信任或已修改 | 重新开启 Hook 并检查 Codex 配置 |
| CodexBar Hook 意外来源 | app-server 返回的来源不是当前配置文件 | 检查 `CODEX_HOME` 和当前 Codex 来源 |
| `hooks.json` 文件格式错误 | 顶层或 `hooks` 结构不是有效 JSON | 修复 JSON 后重新操作 |
@@ -51,7 +51,7 @@ CodexBar 优先使用全局 Codex CLI,关于页面的 `当前使用` 标记可
Hook 配置位于 `$CODEX_HOME/hooks.json`,未设置 `CODEX_HOME` 时位于 `~/.codex/hooks.json`
-升级 CodexBar 后出现 Hook 不完整提示时,关闭并重新开启 Hook 会补齐当前版本要求的事件。
+CodexBar 会在启动、打开菜单和每轮额度刷新完成后自动补齐已开启 Hook 所缺少的必要事件与信任数据。如果临时错误阻止了自动补齐,关闭并重新开启 Hook 仍会重建完整配置。
## 实时任务没有出现
diff --git a/Docs/en/DeveloperGuide/hook-and-aggregation.md b/Docs/en/DeveloperGuide/hook-and-aggregation.md
index bb2af00..9fcae2f 100644
--- a/Docs/en/DeveloperGuide/hook-and-aggregation.md
+++ b/Docs/en/DeveloperGuide/hook-and-aggregation.md
@@ -70,7 +70,7 @@ Installation adds the CodexBar handler as a separate command within the existing
- On disable, remove only an exact CodexBar handler match
- Preserve unrecognized configuration unchanged
-`isEnabled` means only that a handler exists; `isVerified` means the most recent app-server validation passed. The UI treats Hook as a working source only when `isOperable` is true.
+`isEnabled` is the Hook's enabled state for the current process and is initially restored from an existing CodexBar handler. `isVerified` means the most recent app-server validation passed. The UI treats Hook as a working source only when `isOperable` is true.
### Why Installation and Validation Are Separate
@@ -84,10 +84,23 @@ Execution may still be blocked when:
- app-server resolves another source file
- The handler is untrusted or modified
-`isEnabled` is therefore a local configuration fact, while `isVerified` is Codex's most recent explicit conclusion for the current source. Sleep prevention and task notifications depend only on their combined `isOperable` state.
+`isEnabled` is therefore the switch state for the current process, while `isVerified` is Codex's most recent explicit conclusion for the current source. Sleep prevention and task notifications depend only on their combined `isOperable` state.
A transient RPC failure means validation could not run this cycle, not that the handler became invalid. CodexBar preserves the last explicit conclusion while exposing the operation error for diagnosis.
+### Reconciliation of an Enabled Hook
+
+CodexBar reconciles an enabled Hook at app launch, when Settings refreshes, whenever the menu panel opens, and after each quota refresh. Automatic quota refresh normally completes every 60 seconds, so configuration and trust state usually converge within 60 seconds:
+
+- Only a confirmed running app-server version below the current Hook minimum triggers the normal disable flow, which removes CodexBar handlers and their matching trust entries
+- An unknown version or transient RPC failure preserves the user's configuration
+- Configuration lost during the current process does not turn off the switch; CodexBar marks it damaged and starts repair
+- A supported version traverses `CodexHookEvent.allCases`, rebuilds a separate group for every missing or noncanonical event, then reuses trust and completeness validation
+- Missing trust entries or changed hashes are repaired only for entries whose command, `sourcePath`, and event belong to the current CodexBar
+- A complete required event set leaves `hooks.json` unchanged
+
+Reconciliation derives its work from the current required event set and actual file contents; it stores no one-time migration marker. Future required events and manually removed handlers therefore use the same repair path. If no recognizable CodexBar handler remains before app launch, the initial read cannot restore the enabled state, so Hook remains off.
+
### Enable Transaction Order
```text
diff --git a/Docs/en/UserGuide/activity-and-hook.md b/Docs/en/UserGuide/activity-and-hook.md
index 4939da3..64f1b1e 100644
--- a/Docs/en/UserGuide/activity-and-hook.md
+++ b/Docs/en/UserGuide/activity-and-hook.md
@@ -38,7 +38,7 @@ If CodexBar still reports an older version after you update Codex, quit and reop
4. Enable `CodexBar Hook`
5. Wait for configuration and validation to finish
-CodexBar checks the installed Hook again whenever you open Settings or reactivate the app.
+CodexBar checks an enabled Hook at launch, when you open the menu or Settings, when the app becomes active again, and after each quota refresh. Automatic quota refresh normally completes every 60 seconds, and missing required event configuration or trust entries are repaired automatically.
## Configuration Changes
diff --git a/Docs/en/UserGuide/troubleshooting.md b/Docs/en/UserGuide/troubleshooting.md
index 9214db6..d5b2f39 100644
--- a/Docs/en/UserGuide/troubleshooting.md
+++ b/Docs/en/UserGuide/troubleshooting.md
@@ -43,7 +43,7 @@ Double-click the account icon to retry. If the values remain dimmed, check `acco
| --- | --- | --- |
| A newer Codex version is required | The current app-server version is too old | Update Codex, then restart CodexBar |
| Codex Hook is disabled globally | `features.hooks` is disabled | Re-enable Hooks in the Codex configuration |
-| CodexBar Hook is incomplete | At least one required event is missing the current handler | Turn CodexBar Hook off, then on again |
+| CodexBar Hook is incomplete | At least one required event is missing the current handler | Reopen Settings to trigger automatic repair; if it still fails, turn Hook off and on again |
| CodexBar Hook is not trusted | Codex still considers the handler untrusted or modified | Re-enable the Hook and inspect the Codex configuration |
| Unexpected CodexBar Hook source | app-server reported a source other than the active configuration file | Check `CODEX_HOME` and the active Codex source |
| Invalid `hooks.json` format | The top-level value or `hooks` structure is not valid JSON | Repair the JSON, then try again |
@@ -51,7 +51,7 @@ Double-click the account icon to retry. If the values remain dimmed, check `acco
The Hook configuration is at `$CODEX_HOME/hooks.json`, or `~/.codex/hooks.json` when `CODEX_HOME` is unset.
-If CodexBar reports an incomplete Hook after an upgrade, turn the Hook off and on again to add events required by the current version.
+CodexBar automatically restores required events and trust data missing from an enabled Hook at launch, when the menu opens, and after each quota refresh. If a transient error prevents automatic repair, turning Hook off and on still rebuilds the complete configuration.
## Live Tasks Do Not Appear
diff --git a/appcast.xml b/appcast.xml
index 2eb1be2..6c0f7ed 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.6.12</title>
+ <sparkle:version>79</sparkle:version>
+ <sparkle:shortVersionString>3.6.12</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.6.12</sparkle:releaseNotesLink>
+ <pubDate>Wed, 02 Sep 2026 19:30:41 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.6.12.dmg" sparkle:edSignature="rSbh8AMNrijzntjCPvjJepRRb1Cu7oRESYjBiQVQm5sbtw9GPxGV0nUnM6XFdG3rbm3lGKNOPt2XFczGfwj0Cw==" length="7624724" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.6.11</title>
<sparkle:version>78</sparkle:version>