Skip to content

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

feat: 自动信任 Codex Hook

Bob898aea46acbd
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxproj
index a327ccd..2e1567f 100644
--- a/CodexBar.xcodeproj/project.pbxproj
+++ b/CodexBar.xcodeproj/project.pbxproj
@@ -277,7 +277,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 26;
+ CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = 4KJ362VJW5;
ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
ENABLE_APP_SANDBOX = NO;
@@ -292,7 +292,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 3.1.2;
+ MARKETING_VERSION = 3.1.3;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
@@ -314,7 +314,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 26;
+ CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = 4KJ362VJW5;
ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
ENABLE_APP_SANDBOX = NO;
@@ -329,7 +329,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 3.1.2;
+ MARKETING_VERSION = 3.1.3;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
diff --git a/CodexBar/App/CodexBarApp.swift b/CodexBar/App/CodexBarApp.swift
index 5ed4ea4..e4166b6 100644
--- a/CodexBar/App/CodexBarApp.swift
+++ b/CodexBar/App/CodexBarApp.swift
@@ -2,6 +2,7 @@ import AppKit
import Darwin
import SwiftUI
+/// 应用入口; Hook 子进程模式会在初始化阶段记录事件并退出
@main
struct CodexBarApp: App {
@NSApplicationDelegateAdaptor(CodexBarAppDelegate.self) private var appDelegate
@@ -25,7 +26,7 @@ nonisolated extension Bundle {
object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
}
- /// `v1.2.3` 形式的版本文案; 缺失时回退 `--`
+ /// ` v1.2.3` 形式的版本文案; 缺失时回退 `--`
var displayVersionLabel: String {
guard let version = shortVersionString else { return "--" }
return "v\(version)"
diff --git a/CodexBar/Controllers/FallbackPanelController.swift b/CodexBar/Controllers/FallbackPanelController.swift
index 0986066..e07e2a8 100644
--- a/CodexBar/Controllers/FallbackPanelController.swift
+++ b/CodexBar/Controllers/FallbackPanelController.swift
@@ -1,6 +1,7 @@
import AppKit
import SwiftUI
+/// 全局快捷键无法信任 status item 锚点时使用的无箭头菜单面板
@MainActor
final class FallbackPanelController {
private let makeContentController: () -> NSHostingController<AnyView>
diff --git a/CodexBar/Controllers/GlobalHotKeyController.swift b/CodexBar/Controllers/GlobalHotKeyController.swift
index 3974db5..0d73b48 100644
--- a/CodexBar/Controllers/GlobalHotKeyController.swift
+++ b/CodexBar/Controllers/GlobalHotKeyController.swift
@@ -1,6 +1,7 @@
import Carbon.HIToolbox
import Foundation
+/// Carbon 全局快捷键注册器, 将系统回调桥接回 MainActor
final class GlobalHotKeyController {
private let onPressed: @MainActor () -> Void
private var registration: GlobalHotKeyRegistration?
@@ -96,6 +97,7 @@ final class GlobalHotKeyController {
}()
}
+/// 负责在 deinit 或重新注册时释放 Carbon handler 和 hot key
private final nonisolated class GlobalHotKeyRegistration {
private var eventHandler: EventHandlerUPP?
private var eventHandlerRef: EventHandlerRef?
diff --git a/CodexBar/Controllers/HeatmapDetailPanelController.swift b/CodexBar/Controllers/HeatmapDetailPanelController.swift
index 848f728..514e9cb 100644
--- a/CodexBar/Controllers/HeatmapDetailPanelController.swift
+++ b/CodexBar/Controllers/HeatmapDetailPanelController.swift
@@ -2,6 +2,7 @@ import AppKit
import QuartzCore
import SwiftUI
+/// 详情面板不接收焦点, 只作为菜单面板的跟随子窗口
private final class DetailPanel: NSPanel {
override var canBecomeKey: Bool {
false
@@ -12,6 +13,7 @@ private final class DetailPanel: NSPanel {
}
}
+/// 热力图 hover 详情控制器, 负责左右贴边定位和抽屉式切换动画
@MainActor
final class HeatmapDetailPanelController {
private var panel: NSPanel?
@@ -137,6 +139,8 @@ final class HeatmapDetailPanelController {
private func updateVisiblePanel(_ request: PanelRequest, on panel: NSPanel) {
if drawerTransition == .switchingSide {
+ // 切边动画过程中只保留最新请求
+ // 防止连续 hover 造成动画队列堆积
pendingSideSwitchRequest = request
return
}
@@ -367,6 +371,7 @@ final class HeatmapDetailPanelController {
showsWorkflowStats: Bool,
preferredSide: UsageHeatmapDetailSide
) -> PanelPosition {
+ // 优先贴在请求侧, 空间不足时换边, 最后仍夹紧到屏幕可见区域
let menuSurfaceFrame = contentScreenFrame(for: contentView, in: menuSurfaceWindow) ?? menuSurfaceWindow.frame
let visibleFrame = (menuSurfaceWindow.screen ?? NSScreen.main)?.visibleFrame ?? menuSurfaceFrame
let leftX = menuSurfaceFrame.minX - Metrics.panelGap - panelSize.width
diff --git a/CodexBar/Controllers/HostingWindowController.swift b/CodexBar/Controllers/HostingWindowController.swift
index 17a3421..9dc12c2 100644
--- a/CodexBar/Controllers/HostingWindowController.swift
+++ b/CodexBar/Controllers/HostingWindowController.swift
@@ -1,5 +1,6 @@
import AppKit
+/// 可临时禁止成为 key window, 让菜单面板关闭动画期间不被辅助窗口抢焦点
@MainActor
final class AuxiliaryHostingWindow: NSWindow {
var allowsKeyFocus = true
@@ -13,7 +14,7 @@ final class AuxiliaryHostingWindow: NSWindow {
}
}
-/// 承载 SwiftUI 内容的单窗口控制器基类, 统一懒创建、居中与窗口管理逻辑
+/// 承载 SwiftUI 内容的单窗口控制器基类, 统一懒创建, 居中与窗口管理逻辑
@MainActor
class HostingWindowController {
let screenProvider: () -> NSScreen?
@@ -49,6 +50,7 @@ class HostingWindowController {
func applyWindowPresentationPolicy(_ window: NSWindow) {
window.level = .normal
// 重新打开时跟随到当前桌面, 避免把用户切回窗口旧桌面
+
window.collectionBehavior.insert(.moveToActiveSpace)
}
diff --git a/CodexBar/Controllers/LogWindowController.swift b/CodexBar/Controllers/LogWindowController.swift
index 414a24e..2174c9d 100644
--- a/CodexBar/Controllers/LogWindowController.swift
+++ b/CodexBar/Controllers/LogWindowController.swift
@@ -1,6 +1,7 @@
import AppKit
import SwiftUI
+/// 日志窗口控制器, 使用全局 RequestLogStore 保持关闭后日志不丢失
@MainActor
final class LogWindowController: HostingWindowController {
private let store: RequestLogStore
diff --git a/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift b/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift
index beb2b8a..b948d37 100644
--- a/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift
+++ b/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift
@@ -1,5 +1,6 @@
import AppKit
+/// 菜单面板关闭监听器, 汇总本地/全局鼠标, 键盘和应用激活变化
@MainActor
final class MenuSurfaceDismissMonitor {
private let isPresented: () -> Bool
@@ -208,6 +209,8 @@ final class MenuSurfaceDismissMonitor {
}
private func suppressNextActivationDismiss() {
+ // Command-Space 会切换系统搜索焦点
+ // 需要短暂抑制失活关闭避免误关面板
suppressActivationDismissTask?.cancel()
suppressesActivationDismiss = true
suppressActivationDismissTask = Task { @MainActor [weak self] in
@@ -238,6 +241,7 @@ final class MenuSurfaceDismissMonitor {
return
}
+ // 只有真正点到菜单和状态按钮之外才关闭
dismiss()
}
@@ -266,7 +270,8 @@ final class MenuSurfaceDismissMonitor {
return
}
- // AppKit 会在点击后重新强调 NSVisualEffectView, 这里固定为 inactive 避免背景明暗跳变
+ // AppKit 会在点击后重新强调 NSVisualEffectView
+ // 这里固定为 inactive 避免背景明暗跳变
stabilizeVisualEffectViews(in: rootView)
}
diff --git a/CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift b/CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift
index 418353d..9cfdbb8 100644
--- a/CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift
+++ b/CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift
@@ -1,5 +1,6 @@
import AppKit
+/// 菜单面板淡入淡出的集中控制, 用 generation 丢弃过期动画完成回调
@MainActor
final class MenuSurfaceFadeCoordinator {
private let contentViewProvider: () -> NSView?
diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swift
index e54c0dd..e12efc8 100644
--- a/CodexBar/Controllers/SettingsWindowController.swift
+++ b/CodexBar/Controllers/SettingsWindowController.swift
@@ -1,6 +1,7 @@
import AppKit
import SwiftUI
+/// 设置窗口控制器, 打开前刷新 Hook 状态并按内容自适应高度
@MainActor
final class SettingsWindowController: HostingWindowController {
private let viewModel: CodexStatusViewModel
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index 9284f22..d55d45a 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -2,6 +2,7 @@ import AppKit
import Combine
import SwiftUI
+/// 应用级对象装配点, 持有共享服务和 ViewModel 生命周期
@MainActor
final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
private let codexStatusService = CodexStatusService()
@@ -30,6 +31,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
}
}
+/// 菜单栏入口控制器, 统一管理状态图标, 菜单面板, 右键菜单和全局快捷键
@MainActor
private final class StatusItemController: NSObject {
private let viewModel: CodexStatusViewModel
@@ -302,6 +304,8 @@ private final class StatusItemController: NSObject {
_ button: NSStatusBarButton,
on targetScreen: NSScreen?
) -> Bool {
+ // 全局快捷键打开时必须确认 status item 锚点真实可用
+ // 否则使用无箭头 fallback 面板
guard let window = button.window,
let screen = window.screen,
!button.isHidden,
@@ -460,6 +464,8 @@ private final class StatusItemController: NSObject {
}
guard animated else {
+ // 关闭菜单面板时短暂禁止辅助窗口抢回 key
+ // 避免设置/日志窗口闪前
suspendAuxiliaryWindowKeyFocus()
completeMenuSurfaceClose(hidesDetailPanel: false)
return
@@ -530,6 +536,7 @@ private final class StatusItemController: NSObject {
}
private func refreshWorkflowStatsIfHookEnabled(performMaintenance: Bool) {
+ // Hook 开关可能被外部 Codex 配置改动, 每次需要统计前都先读 hooks.json
codexHookSettings.refresh()
if codexHookSettings.isEnabled {
workflowStatsViewModel.refreshIfNeeded(performMaintenance: performMaintenance)
diff --git a/CodexBar/Models/CodexAccountModels.swift b/CodexBar/Models/CodexAccountModels.swift
index 48ebc60..dfdf909 100644
--- a/CodexBar/Models/CodexAccountModels.swift
+++ b/CodexBar/Models/CodexAccountModels.swift
@@ -1,5 +1,6 @@
import Foundation
+/// app-server account/read 的账号信息, 只保留菜单面板需要展示的字段
nonisolated struct CodexAccount: Decodable, Equatable {
let type: String
let email: String?
@@ -27,6 +28,7 @@ nonisolated struct CodexAccount: Decodable, Equatable {
}
}
+/// account/read 允许 account 为空, 由上层转换为`未登录`状态
nonisolated struct AccountReadResponse: Decodable {
let account: CodexAccount?
}
diff --git a/CodexBar/Models/CodexHookEvent.swift b/CodexBar/Models/CodexHookEvent.swift
index 28aa038..3149edc 100644
--- a/CodexBar/Models/CodexHookEvent.swift
+++ b/CodexBar/Models/CodexHookEvent.swift
@@ -1,5 +1,6 @@
import Foundation
+/// Codex Hook 事件名的统一枚举, 负责在 hooks.json 与 app-server 命名间转换
nonisolated enum CodexHookEvent: String, CaseIterable {
case sessionStart = "SessionStart"
case userPromptSubmit = "UserPromptSubmit"
diff --git a/CodexBar/Models/CodexQuotaModels.swift b/CodexBar/Models/CodexQuotaModels.swift
index 6a4f79f..7b2a6fe 100644
--- a/CodexBar/Models/CodexQuotaModels.swift
+++ b/CodexBar/Models/CodexQuotaModels.swift
@@ -1,5 +1,6 @@
import Foundation
+/// 由 account/rateLimits/usage 三路 app-server 响应合成的菜单面板快照
nonisolated struct CodexQuotaSnapshot: Equatable {
let account: CodexAccount
let planType: String?
@@ -30,6 +31,7 @@ nonisolated struct CodexQuotaSnapshot: Equatable {
}
}
+/// 单个额度类型的展示快照, 例如 codex 或其他 limit id
nonisolated struct CodexQuotaLimitSnapshot: Equatable, Identifiable {
let limitId: String
let limitName: String?
@@ -58,6 +60,7 @@ private nonisolated extension String {
}
}
+/// primary/secondary 窗口的 UI 友好表示, 统一计算剩余额度百分比
nonisolated struct QuotaWindow: Equatable, Identifiable {
let id: String
let windowDurationMins: Int?
@@ -86,22 +89,24 @@ nonisolated struct QuotaWindow: Equatable, Identifiable {
}
if minutes.isMultiple(of: 1440) {
- return "\(minutes / 1440)D"
+ return "\(minutes / 1440)d"
}
if minutes.isMultiple(of: 60) {
- return "\(minutes / 60)H"
+ return "\(minutes / 60)h"
}
- return "\(minutes)M"
+ return "\(minutes)m"
}
}
+/// app-server account/rateLimits 原始响应模型
nonisolated struct AccountRateLimitsResponse: Decodable {
let rateLimits: RateLimitSnapshot
let rateLimitsByLimitId: [String: RateLimitSnapshot]?
}
+/// app-server 返回的单个 limit, primary/secondary 可能独立缺失
nonisolated struct RateLimitSnapshot: Decodable {
let limitId: String?
let limitName: String?
@@ -110,6 +115,7 @@ nonisolated struct RateLimitSnapshot: Decodable {
let secondary: RateLimitWindow?
}
+/// resetsAt 是 Unix 时间戳, 在模型层先转成 Date 方便 UI 格式化
nonisolated struct RateLimitWindow: Decodable {
let usedPercent: Int?
let resetsAt: Int?
@@ -144,7 +150,9 @@ nonisolated extension CodexQuotaSnapshot {
CodexUsageSnapshot(summary: $0.summary, dailyBuckets: $0.dailyUsageBuckets)
}
- // rateLimits/usage 可同时为空, 账户有效时仍生成快照给 UI 展示"暂无数据"
+ // rateLimits/usage 可同时为空
+ // 账户有效时仍生成快照给 UI 展示 `暂无数据`
+
self.init(
account: account,
planType: rateLimitsResponse?.rateLimits.planType,
diff --git a/CodexBar/Models/CodexStatusError.swift b/CodexBar/Models/CodexStatusError.swift
index 12691f9..aec77a0 100644
--- a/CodexBar/Models/CodexStatusError.swift
+++ b/CodexBar/Models/CodexStatusError.swift
@@ -1,5 +1,6 @@
import Foundation
+/// UI 和日志共用的 app-server 错误分类, 保留可重试/需重连判断
nonisolated enum CodexStatusError: LocalizedError {
case executableNotFound
case serverTimeout
@@ -14,7 +15,7 @@ nonisolated enum CodexStatusError: LocalizedError {
case .executableNotFound:
"找不到 Codex CLI 或 Codex APP"
case .serverTimeout:
- "等待 Codex app-server 响应超时"
+ "Codex app-server 等待响应超时"
case .serverConnectionClosed:
"Codex app-server 连接已断开"
case .invalidServerResponse:
@@ -51,7 +52,7 @@ nonisolated enum CodexStatusError: LocalizedError {
return !isAuthenticationRequired && !isUnsupportedMethod
}
- /// 连接断开、超时、无法解析都需要重建 app-server 会话
+ /// 连接断开, 超时, 无法解析都需要重建 app-server 会话
var isTransportFailure: Bool {
switch self {
case .serverConnectionClosed, .serverTimeout, .invalidServerResponse:
diff --git a/CodexBar/Models/CodexUsageModels.swift b/CodexBar/Models/CodexUsageModels.swift
index c92efae..55face9 100644
--- a/CodexBar/Models/CodexUsageModels.swift
+++ b/CodexBar/Models/CodexUsageModels.swift
@@ -1,10 +1,12 @@
import Foundation
+/// app-server account/usage 的原始响应, summary 和按日 bucket 分开使用
nonisolated struct AccountUsageResponse: Decodable {
let summary: UsageSummary
let dailyUsageBuckets: [DailyUsageBucket]
}
+/// token 区域展示的汇总指标
nonisolated struct UsageSummary: Decodable, Equatable {
let currentStreakDays: Int?
let lifetimeTokens: Int
@@ -13,6 +15,7 @@ nonisolated struct UsageSummary: Decodable, Equatable {
let peakDailyTokens: Int
}
+/// 单日 token bucket, startDate 使用 yyyy-MM-dd 作为稳定键
nonisolated struct DailyUsageBucket: Decodable, Equatable, Identifiable {
let startDate: String
let tokens: Int
@@ -22,6 +25,7 @@ nonisolated struct DailyUsageBucket: Decodable, Equatable, Identifiable {
}
}
+/// token 热力图使用的只读快照, 负责按日期聚合重复 bucket
nonisolated struct CodexUsageSnapshot: Equatable {
let summary: UsageSummary
let dailyBuckets: [DailyUsageBucket]
diff --git a/CodexBar/Models/CodexWeekGrid.swift b/CodexBar/Models/CodexWeekGrid.swift
index e83c0f9..3aebc7f 100644
--- a/CodexBar/Models/CodexWeekGrid.swift
+++ b/CodexBar/Models/CodexWeekGrid.swift
@@ -1,5 +1,6 @@
import Foundation
+/// 共享的周历网格生成器, 固定按列为周, 行从周日开始排列
nonisolated enum CodexWeekGrid {
static let rowCount = 7
diff --git a/CodexBar/Models/CodexWorkflowStatsModels.swift b/CodexBar/Models/CodexWorkflowStatsModels.swift
index 4a33cf8..20a001c 100644
--- a/CodexBar/Models/CodexWorkflowStatsModels.swift
+++ b/CodexBar/Models/CodexWorkflowStatsModels.swift
@@ -1,5 +1,6 @@
import Foundation
+/// 写入 JSONL 时固定字段顺序, 便于人工排查和 diff
private nonisolated enum WorkflowStatsJSON {
static func lineData(_ fields: [String]) -> Data {
let json = "{\(fields.joined(separator: ","))}"
@@ -32,6 +33,7 @@ private nonisolated enum WorkflowStatsJSON {
}
}
+/// hooks 进程落盘的最小事件模型, 对历史字段缺失保持宽容
nonisolated struct WorkflowHookEvent: Decodable, Equatable {
let timestamp: Date
let name: String
@@ -145,6 +147,7 @@ nonisolated struct WorkflowHookEvent: Decodable, Equatable {
}
}
+/// 热力图详情面板直接消费的每日统计
nonisolated struct WorkflowDailyStats: Equatable, Identifiable {
let startDate: String
let sessionCount: Int
@@ -171,6 +174,7 @@ nonisolated struct WorkflowDailyStats: Equatable, Identifiable {
}
}
+/// WorkflowStatsService 发布给 UI 的近端快照
nonisolated struct WorkflowStatsSnapshot: Equatable {
let generatedAt: Date
let dailyStats: [WorkflowDailyStats]
@@ -208,6 +212,7 @@ nonisolated struct WorkflowStatsSnapshot: Equatable {
}
}
+/// 聚合时保留 Set 缓存, 避免同一会话或轮次重复计数
nonisolated struct WorkflowDailyIdentifierCache {
var sessionIds: Set<String>
var turnIds: Set<String>
@@ -218,6 +223,7 @@ nonisolated struct WorkflowDailyIdentifierCache {
}
}
+/// daily.jsonl 中的持久化聚合行, 同时兼容保留 ID 和只保留计数两种形态
nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
let date: String
var eventCount: Int
@@ -329,7 +335,8 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
turnIds = nil
}
- // 会话/轮次最终值: 优先使用去重/压缩后的数量, 起止事件计数只作为缺失兜底
+ // 会话/轮次最终值: 优先使用去重/压缩后的数量
+ // 起止事件计数只作为缺失兜底
private var resolvedSessionCount: Int {
sessionCount ?? sessionIds?.count ?? sessionStartCount
}
diff --git a/CodexBar/Models/DateFormatter.swift b/CodexBar/Models/DateFormatter.swift
index c830dce..3d8a7e2 100644
--- a/CodexBar/Models/DateFormatter.swift
+++ b/CodexBar/Models/DateFormatter.swift
@@ -1,5 +1,6 @@
import Foundation
+/// 集中管理 CodexBar 数据文件和 app-server 响应里使用的日期格式
nonisolated enum CodexDateFormat {
/// yyyy-MM-dd, 作为热力图与按日聚合统一的稳定日期键
static func dayString(from date: Date) -> String {
@@ -43,7 +44,7 @@ nonisolated enum CodexDateFormat {
return date
}
- /// yyyy-MM-dd HH:mm:ss.SSS, Hook 原始事件写入本机时间字符串
+ /// yyyy-MM-dd HH: mm: ss.SSS, Hook 原始事件写入本机时间字符串
static func localTimestampString(from date: Date) -> String {
localTimestampFormatter().string(from: date)
}
diff --git a/CodexBar/Models/GlobalHotKeyShortcut.swift b/CodexBar/Models/GlobalHotKeyShortcut.swift
index ca40dfc..75d2eab 100644
--- a/CodexBar/Models/GlobalHotKeyShortcut.swift
+++ b/CodexBar/Models/GlobalHotKeyShortcut.swift
@@ -1,6 +1,7 @@
import AppKit
import Carbon.HIToolbox
+/// 可持久化的 Carbon 快捷键模型, 同时负责录制结果的基础校验
nonisolated struct GlobalHotKeyShortcut: Codable, Equatable {
let keyCode: UInt32
let modifiers: UInt32
@@ -63,6 +64,7 @@ nonisolated struct GlobalHotKeyShortcut: Codable, Equatable {
[controlKey, optionKey, shiftKey, cmdKey].filter(hasModifier).count
}
+ /// 避开 Command-Space 和 Command-Tab 等系统级组合
private var isReservedSystemShortcut: Bool {
hasModifier(cmdKey) && Self.reservedSystemKeyCodes.contains(keyCode)
}
diff --git a/CodexBar/Models/UsageHeatmapDay.swift b/CodexBar/Models/UsageHeatmapDay.swift
index 51d6445..4f543d8 100644
--- a/CodexBar/Models/UsageHeatmapDay.swift
+++ b/CodexBar/Models/UsageHeatmapDay.swift
@@ -1,5 +1,6 @@
import Foundation
+/// 热力图单元格模型, 合并 app-server token 数据和本地 Hook 工作流统计
nonisolated struct UsageHeatmapDay: Equatable, Identifiable {
let startDate: String
let tokenCount: Int?
@@ -21,6 +22,8 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {
today: Date
) -> [UsageHeatmapDay?] {
let todayTokenCount = usage.tokenCount(on: today)
+ // Hook 开启时当天工作流统计可见
+ // Hook 关闭时只在 token bucket 已返回时展示今天
let endingDaysAgo = showsWorkflowStats || todayTokenCount != nil ? 0 : 1
let tokenDays = usage.recentWeekGrid(
columnCount: columnCount,
diff --git a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
index f63533b..4c53e63 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
@@ -1,6 +1,7 @@
import Darwin
import Foundation
+/// CodexBar 支持全局 CLI 优先, 找不到时回退 Codex APP 内置 CLI
nonisolated enum CodexCLIExecutableSource: String, Equatable {
case global
case bundled
@@ -13,20 +14,24 @@ nonisolated enum CodexCLIExecutableSource: String, Equatable {
}
}
+/// 启动 app-server 所需的可执行文件和固定 stdio 参数
nonisolated struct AppServerCommand: Equatable {
let source: CodexCLIExecutableSource
let executablePath: String
let arguments = ["app-server", "--listen", "stdio://"]
}
+/// 当前已连接 app-server 的来源信息, 设置页用它标记`当前使用`
nonisolated struct CodexCLIConnectionInfo: Equatable {
let source: CodexCLIExecutableSource
let executablePath: String
// 来自 initialize 握手, 代表当前 app-server 进程真实运行的版本
+
let version: String?
let openedAt: Date
}
+/// 一次 PATH 扫描得到的安装结果, 供启动和版本探测复用
nonisolated struct CodexCLIInstallations: Equatable {
let globalPath: String?
let bundledPath: String?
@@ -46,6 +51,7 @@ nonisolated struct CodexCLIInstallations: Equatable {
}
}
+/// 解析真实用户环境下的 Codex 可执行文件, 避免使用 Xcode/container 的 HOME
nonisolated enum CodexCLIResolver {
static let bundledExecutablePath = "/Applications/Codex.app/Contents/Resources/codex"
static let environment = appServerEnvironment()
@@ -85,6 +91,7 @@ nonisolated enum CodexCLIResolver {
let homeDirectory = realUserHomeDirectory()
let path = environment["PATH"] ?? ""
// 菜单栏应用通常拿不到用户 shell PATH, 需要补上常见 CLI 安装目录
+
let fallbackPaths = [
"/opt/homebrew/bin",
"/usr/local/bin",
diff --git a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
index 67e2b80..585a776 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
@@ -2,6 +2,7 @@ import Combine
import Foundation
import os
+/// 设置页版本区域的完整快照
nonisolated struct CodexCLIVersionSnapshot: Equatable {
let global: CodexCLIVersionItem
let bundled: CodexCLIVersionItem
@@ -15,6 +16,7 @@ nonisolated struct CodexCLIVersionSnapshot: Equatable {
)
}
+/// 单个安装源的磁盘探测结果
nonisolated struct CodexCLIVersionItem: Equatable, Identifiable {
let source: CodexCLIExecutableSource
let path: String?
@@ -53,12 +55,14 @@ nonisolated struct CodexCLIVersionDisplay: Equatable {
let displayVersion: String
let hasVersion: Bool
let path: String?
- /// 当前会话尚未重连到新安装版本时显示的新版本号
+ // 当前会话尚未重连到新安装版本时显示的新版本号
+
let newerInstalledVersion: String?
init(item: CodexCLIVersionItem, connection: CodexCLIConnectionInfo?) {
let isCurrent = connection?.source == item.source
// 当前来源优先显示正在运行的版本, 避免后台升级后误报已生效
+
let runningVersion = isCurrent ? connection?.version : nil
let version = runningVersion ?? item.version
@@ -101,6 +105,7 @@ nonisolated struct CodexCLIVersionDisplay: Equatable {
}
}
+/// 并发探测 Codex CLI 与 Codex APP 内置 CLI 的磁盘版本
actor CodexCLIVersionService {
private let timeout: TimeInterval
private static let pipeDrainTimeout: TimeInterval = 0.25
@@ -244,6 +249,7 @@ actor CodexCLIVersionService {
}
}
+/// 将 Process.terminationHandler 桥接成可超时等待的 async 结果
private final nonisolated class ProcessExitWaiter: Sendable {
private struct State {
var continuation: CheckedContinuation<Bool, Never>?
@@ -302,6 +308,7 @@ private final nonisolated class ProcessExitWaiter: Sendable {
}
}
+/// 从 ` codex --version` 的输出中提取用户可读版本号
nonisolated enum CodexCLIVersionReader {
static func displayVersion(from output: String) -> String {
output
@@ -311,12 +318,14 @@ nonisolated enum CodexCLIVersionReader {
}
}
+/// 设置页持有的版本探测状态, 负责节流和丢弃过期刷新结果
@MainActor
final class CodexCLIVersionViewModel: ObservableObject {
@Published private(set) var snapshot = CodexCLIVersionSnapshot.empty
@Published private(set) var isRefreshing = false
- /// onAppear 和 didBecomeActive 常连发, 版本探测需要节流以避免频繁启动子进程
+ /// onAppear 和 didBecomeActive 常连发
+ /// 版本探测需要节流以避免频繁启动子进程
private static let refreshThrottle: TimeInterval = 60
private let service: CodexCLIVersionService
diff --git a/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift b/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift
index f5a2649..5e86a8e 100644
--- a/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift
+++ b/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift
@@ -1,5 +1,6 @@
import Foundation
+/// app-server stdout 行读取器, 只向会话层暴露完整非空行
final nonisolated class JSONLineReader {
private let buffer: PipeReadBuffer
@@ -20,6 +21,7 @@ final nonisolated class JSONLineReader {
}
}
+/// stderr 只需要及时 drain, 避免子进程因管道填满而阻塞
final nonisolated class PipeDrain {
private let buffer: PipeReadBuffer
@@ -32,8 +34,10 @@ final nonisolated class PipeDrain {
}
}
-/// 底层 pipe 读取桥接了 FileHandle、DispatchSourceRead 和 semaphore 这些非 Sendable 类型
-/// 对外 Sendable 边界只保留在这里, 可变状态全部经由 lock 保护, 读事件固定在 readQueue 上执行
+/// 底层 pipe 读取桥接了 FileHandle, DispatchSourceRead 和 semaphore
+/// 这些非 Sendable 类型
+/// 对外 Sendable 边界只保留在这里
+/// 可变状态全部经由 lock 保护, 读事件固定在 readQueue 上执行
final nonisolated class PipeReadBuffer: @unchecked Sendable {
private let lock = NSLock()
private let lineSemaphore = DispatchSemaphore(value: 0)
diff --git a/CodexBar/Services/CodexStatus/AppServerSession.swift b/CodexBar/Services/CodexStatus/AppServerSession.swift
index 2989d61..9a3b877 100644
--- a/CodexBar/Services/CodexStatus/AppServerSession.swift
+++ b/CodexBar/Services/CodexStatus/AppServerSession.swift
@@ -1,5 +1,7 @@
import Foundation
+/// 对 app-server stdio JSON-RPC 的薄封装
+/// 负责日志记录, 超时和 unsupported 方法缓存
final nonisolated class AppServerSession {
let process: Process
@@ -72,6 +74,7 @@ final nonisolated class AppServerSession {
throw CodexStatusError.unsupportedMethod
}
+ // app-server 偶发业务错误可重试一次; 传输错误由上层重建连接
do {
return try performRequestRememberingUnsupported(method, params: params, as: type)
} catch let error as CodexStatusError where error.isRetriableServerError {
@@ -160,6 +163,7 @@ final nonisolated class AppServerSession {
let deadline = Date().addingTimeInterval(timeout)
let decoder = JSONDecoder()
+ // stdout 可能混有无关日志行, 只消费 id 匹配的 JSON-RPC 响应
while Date() < deadline {
guard let line = try nextResponseLine(
matching: id,
@@ -226,6 +230,7 @@ final nonisolated class AppServerSession {
}
}
+/// 先轻量读取 id, 避免把其他请求或日志行误当成本次响应
private nonisolated struct RPCIDEnvelope: Decodable {
let id: Int?
}
diff --git a/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift b/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift
index 5360945..7a318a4 100644
--- a/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift
+++ b/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift
@@ -1,5 +1,6 @@
import Foundation
+/// config/read 的最小响应模型, 只解出 Hook 开关和信任状态
nonisolated struct CodexConfigReadResponse: Decodable {
let config: CodexAppServerConfig
@@ -10,12 +11,19 @@ nonisolated struct CodexConfigReadResponse: Decodable {
return (features.hooks ?? features.codexHooks) == false
}
+
+ var hookTrustState: [String: String] {
+ config.hooks?.state?.compactMapValues(\.trustedHash) ?? [:]
+ }
}
+/// Codex 用户配置根节点, 字段保持 optional 以兼容不同 Codex 版本
nonisolated struct CodexAppServerConfig: Decodable {
let features: CodexAppServerFeatures?
+ let hooks: CodexAppServerHooks?
}
+/// Codex 新旧配置名可能同时存在, 读取时按 hooks 优先回退 codex_hooks
nonisolated struct CodexAppServerFeatures: Decodable {
let hooks: Bool?
let codexHooks: Bool?
@@ -26,10 +34,42 @@ nonisolated struct CodexAppServerFeatures: Decodable {
}
}
+/// hooks.state 里保存 hook key 到 trusted_hash 的映射
+nonisolated struct CodexAppServerHooks: Decodable {
+ let state: [String: CodexHookTrustState]?
+}
+
+nonisolated struct CodexHookTrustState: Decodable {
+ let trustedHash: String?
+
+ private enum CodingKeys: String, CodingKey {
+ case trustedHash = "trusted_hash"
+ }
+}
+
+/// config/batchWrite 的单条编辑, 直接转成 app-server 期望的 JSON 对象
+nonisolated struct CodexConfigBatchEdit {
+ let keyPath: String
+ let value: [String: [String: String]]
+ let mergeStrategy: String
+
+ var appServerObject: [String: Any] {
+ [
+ "keyPath": keyPath,
+ "value": value,
+ "mergeStrategy": mergeStrategy
+ ]
+ }
+}
+
+nonisolated struct CodexConfigWriteResponse: Decodable {}
+
+/// hooks/list 的响应列表按 cwd 分组
nonisolated struct CodexHooksListResponse: Decodable {
let data: [CodexHooksListEntry]
}
+/// 单个 cwd 下 Codex 解析出的 Hook 状态
nonisolated struct CodexHooksListEntry: Decodable {
let cwd: String
let hooks: [CodexHookMetadata]
@@ -37,12 +77,15 @@ nonisolated struct CodexHooksListEntry: Decodable {
let errors: [CodexHookErrorInfo]
}
+/// hooks/list 返回的单个 Hook 元数据, key/currentHash 用于自动写入信任状态
nonisolated struct CodexHookMetadata: Decodable {
let eventName: String
let command: String?
let enabled: Bool
let sourcePath: String
let trustStatus: String
+ let key: String?
+ let currentHash: String?
}
nonisolated struct CodexHookErrorInfo: Decodable {
diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swift
index 6e322c5..db6a35d 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift
@@ -1,6 +1,6 @@
import Foundation
-/// UI 只关心可展示数据、未登录、初始化失败; 更细的错误保留在交互日志中
+/// UI 只关心可展示数据, 未登录, 初始化失败; 更细的错误保留在交互日志中
nonisolated enum CodexFetchOutcome {
case data(CodexQuotaSnapshot)
case notLoggedIn
@@ -13,7 +13,7 @@ private nonisolated enum ConnectionResolution {
case initializationFailed
}
-// 单接口读取结果按后续动作分类: 跳过、刷新认证、重建连接
+// 单接口读取结果按后续动作分类: 跳过, 刷新认证, 重建连接
private nonisolated enum ReadResult<Value> {
case value(Value)
case skipped(ReadSkipReason)
@@ -36,6 +36,7 @@ private nonisolated struct CachedSupplementalRead<Value> {
let isStale: Bool
}
+/// 只缓存同一账号下的补充数据, 账号变化时整体丢弃避免串号
private nonisolated struct SupplementalDataCache {
var account: CodexAccount?
var rateLimits: AccountRateLimitsResponse?
@@ -62,7 +63,8 @@ private nonisolated extension ReadResult {
return nil
}
- /// 认证刷新后仍是 authRequired/broken 则上抛, 其余原样返回交给调用方按缓存策略处理
+ /// 认证刷新后仍是 authRequired/broken 则上抛
+ /// 其余原样返回交给调用方按缓存策略处理
func resultAfterAuthAttempt() throws -> ReadResult<Value> {
switch self {
case .value, .skipped:
@@ -85,7 +87,8 @@ actor CodexStatusService {
private var connection: AppServerConnection?
private var supplementalDataCache = SupplementalDataCache()
- /// app-server 退出后继续写管道会触发 SIGPIPE; 忽略信号, 让 write 抛错后走重建
+ /// app-server 退出后继续写管道会触发 SIGPIPE
+ /// 忽略信号, 让 write 抛错后走重建
private static let ignoreBrokenPipeSignal: Void = {
signal(SIGPIPE, SIG_IGN)
}()
@@ -120,7 +123,21 @@ actor CodexStatusService {
)
}
- /// 复用连接出现传输故障时只重建重试一次, 避免故障状态下反复拉起进程
+ /// Hook 自动信任和清理统一走批量写入, 让 Codex 负责刷新用户配置
+ func writeCodexConfigBatch(edits: [CodexConfigBatchEdit]) async throws -> CodexConfigWriteResponse {
+ let connection = try readyConnection()
+ return try connection.session.request(
+ "config/batchWrite",
+ params: [
+ "edits": edits.map(\.appServerObject),
+ "reloadUserConfig": true
+ ],
+ as: CodexConfigWriteResponse.self
+ )
+ }
+
+ /// 复用连接出现传输故障时只重建重试一次
+ /// 避免故障状态下反复拉起进程
private func resolveOutcome(allowRebuild: Bool) -> CodexFetchOutcome {
switch ensureConnection() {
case .notLoggedIn:
@@ -200,7 +217,9 @@ actor CodexStatusService {
return connection.commandInfo
}
- /// 额度与用量独立读取; 认证失败全程只刷新一次 token, 传输故障交给外层重建连接
+ /// 额度与用量独立读取
+ /// 认证失败全程只刷新一次 token
+ /// 传输故障交给外层重建连接
private func fetchData(using connection: AppServerConnection, refreshAccountInfo: Bool) throws -> CodexQuotaSnapshot {
var didRefresh = false
@@ -234,6 +253,7 @@ actor CodexStatusService {
}
// 新建连接已读过 account; 复用连接才刷新账户状态
+
if refreshAccountInfo {
let accountResult: ReadResult<AccountReadResponse> = try readResultWithAuthRefresh {
Self.read("account/read", params: ["refreshToken": false], using: connection, as: AccountReadResponse.self)
@@ -263,6 +283,7 @@ actor CodexStatusService {
)
// rateLimits/usage 都可为空, 只要账户有效就让 UI 展示"暂无数据"
+
guard let snapshot = try? CodexQuotaSnapshot(
accountResponse: connection.accountResponse,
rateLimitsResponse: rateLimitsRead.value,
@@ -276,7 +297,9 @@ actor CodexStatusService {
return snapshot
}
- /// 新值更新缓存; 本轮请求失败则回退到缓存并标记陈旧; 方法不支持/认证/断连一律视为无数据
+ /// 新值更新缓存
+ /// 本轮请求失败则回退到缓存并标记陈旧
+ /// 方法不支持/认证/断连一律视为无数据
private func cachedRead<Value>(
_ result: ReadResult<Value>,
cache: inout Value?
@@ -315,6 +338,7 @@ actor CodexStatusService {
return .skipped(.methodUnsupported)
}
// 重试后仍失败的非认证业务错误不阻断整轮刷新
+
return error.isTransportFailure ? .broken : .skipped(.requestFailed)
}
@@ -443,6 +467,7 @@ actor CodexStatusService {
}
}
+/// 持有 stdio 会话及初始化阶段读取到的账号/版本信息
private final nonisolated class AppServerConnection {
let session: AppServerSession
let commandInfo: CodexCLIConnectionInfo
diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
index cf30ca7..18ed99a 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
@@ -16,6 +16,7 @@ nonisolated enum CodexLoadState: Equatable {
}
}
+/// 菜单面板主状态模型, 将服务层结果转换为 SwiftUI 可发布状态
@MainActor
final class CodexStatusViewModel: ObservableObject {
@Published private(set) var snapshot: CodexQuotaSnapshot?
@@ -71,6 +72,7 @@ final class CodexStatusViewModel: ObservableObject {
autoRefreshTask = Task { [weak self] in
self?.refreshIfNeeded()
+ // 每轮按剩余时间休眠, 手动刷新后倒计时会自然重新对齐
while !Task.isCancelled {
let delay = self?.autoRefreshDelay ?? Self.refreshInterval
if await (try? Task.sleep(for: .seconds(delay))) == nil {
@@ -103,6 +105,7 @@ final class CodexStatusViewModel: ObservableObject {
let outcome = await service.fetchOutcome()
let connectionInfo = await service.currentConnectionInfo()
+ // 过期刷新结果直接丢弃, 避免慢请求覆盖后启动的新状态
guard refreshCoordinator.canCommit(generation) else {
return
}
diff --git a/CodexBar/Services/CodexStatus/RequestLog.swift b/CodexBar/Services/CodexStatus/RequestLog.swift
index ef32fec..b22fe0a 100644
--- a/CodexBar/Services/CodexStatus/RequestLog.swift
+++ b/CodexBar/Services/CodexStatus/RequestLog.swift
@@ -2,7 +2,8 @@ import Combine
import Foundation
import os
-/// JSON-RPC 交互日志: 带 id 的请求先记录为进行, 响应或错误到达后回填到同一条
+/// JSON-RPC 交互日志: 带 id 的请求先记录为进行
+/// 响应或错误到达后回填到同一条
/// `initialized` 这类无 id 请求没有响应可等, 单独记录为空响应
nonisolated struct RequestLogEntry: Identifiable, Equatable {
enum Kind {
@@ -166,7 +167,8 @@ final nonisolated class RequestLogStorage: Sendable {
}
}
- /// 合法 JSON 重新序列化为稳定、未转义斜杠的日志文本; 非 JSON 错误消息保持原样
+ /// 合法 JSON 重新序列化为稳定, 未转义斜杠的日志文本
+ /// 非 JSON 错误消息保持原样
private static func normalized(_ text: String) -> String {
jsonNormalized(text) ?? text
}
diff --git a/CodexBar/Services/Process/ProcessTermination.swift b/CodexBar/Services/Process/ProcessTermination.swift
index fe9f10a..dd2b9c2 100644
--- a/CodexBar/Services/Process/ProcessTermination.swift
+++ b/CodexBar/Services/Process/ProcessTermination.swift
@@ -1,6 +1,7 @@
import Darwin
import Foundation
+/// 子进程关闭结果, 让调用方区分正常退出和强杀兜底
nonisolated enum ProcessTerminationResult: Equatable {
case alreadyExited
case terminated
@@ -8,6 +9,7 @@ nonisolated enum ProcessTerminationResult: Equatable {
case stillRunning
}
+/// 先 terminate, 超时后 SIGKILL 的统一收口
nonisolated enum ProcessTermination {
private static let pollInterval: TimeInterval = 0.02
diff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swift
index 5a9b2b5..679de6c 100644
--- a/CodexBar/Services/Settings/CodexHookSettings.swift
+++ b/CodexBar/Services/Settings/CodexHookSettings.swift
@@ -1,6 +1,7 @@
import Combine
import Foundation
+/// 设置页的 Codex Hook 开关状态机, 同时管理 hooks.json 和 Codex 信任状态
@MainActor
final class CodexHookSettings: ObservableObject {
@Published private(set) var isEnabled = false
@@ -64,24 +65,20 @@ final class CodexHookSettings: ObservableObject {
try ensureCurrentUpdate(generation)
}
- var config = try readConfigIfPresent()
- try Self.removeCodexBarHooks(
- from: &config,
- executablePath: currentExecutablePath
- )
-
- if enabled {
- try Self.installCodexBarHooks(
- in: &config,
- executablePath: currentExecutablePath
- )
- }
-
- try write(config)
+ // 关闭前先通过 hooks/list 拿到 key
+ // hooks.json 删除后 app-server 就无法再反查这些 key
+ let cleanupPlan = try await hookTrustCleanupPlan(isDisabling: !enabled, generation: generation)
+ try writeCodexBarHookConfig(enabled: enabled)
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
@@ -184,6 +181,23 @@ private extension CodexHookSettings {
static let hookTimeoutKey = "timeout"
static let hookCommandType = "command"
static let hookTimeout = 5
+ static let configMergeStrategyReplace = "replace"
+ static let configMergeStrategyUpsert = "upsert"
+ static let hookTrustStateKeyPath = "hooks.state"
+ static let trustedHashKey = "trusted_hash"
+
+ struct CodexHookTrustEntry {
+ let key: String
+ let trustedHash: String
+ }
+
+ /// discoveryError 会在 Hook 已关闭后展示, 说明仅信任状态清理未完成
+ struct CodexHookTrustCleanupPlan {
+ let keys: Set<String>
+ let discoveryError: Error?
+
+ static let empty = Self(keys: [], discoveryError: nil)
+ }
enum HookConfigError: LocalizedError {
case invalidFormat
@@ -234,7 +248,18 @@ private extension CodexHookSettings {
}
func validateInstalledHooksWithAppServer() async throws {
- let response = try await codexStatusService.listCodexHooks(cwds: [hooksListWorkingDirectory])
+ var response = try await codexStatusService.listCodexHooks(cwds: [hooksListWorkingDirectory])
+ // 只信任 command/sourcePath/event 都匹配当前 CodexBar 的 Hook
+ let entries = Self.hookTrustEntriesNeedingUpdate(
+ from: response,
+ executablePath: currentExecutablePath,
+ hooksURL: hooksURL
+ )
+ if !entries.isEmpty {
+ try await trustCodexBarHooks(entries)
+ response = try await codexStatusService.listCodexHooks(cwds: [hooksListWorkingDirectory])
+ }
+
if let message = Self.validationMessage(
from: response,
executablePath: currentExecutablePath,
@@ -244,6 +269,120 @@ private extension CodexHookSettings {
}
}
+ func hookTrustCleanupPlan(isDisabling: Bool, generation: Int) async throws -> CodexHookTrustCleanupPlan {
+ guard isDisabling else {
+ return .empty
+ }
+
+ do {
+ let keys = try await codexBarHookTrustKeysFromAppServer()
+ try ensureCurrentUpdate(generation)
+ return .init(keys: keys, discoveryError: nil)
+ } catch is CancellationError {
+ throw CancellationError()
+ } catch {
+ return .init(keys: [], discoveryError: error)
+ }
+ }
+
+ func writeCodexBarHookConfig(enabled: Bool) throws {
+ var config = try readConfigIfPresent()
+ try Self.removeCodexBarHooks(
+ from: &config,
+ executablePath: currentExecutablePath
+ )
+
+ if enabled {
+ try Self.installCodexBarHooks(
+ in: &config,
+ executablePath: currentExecutablePath
+ )
+ }
+
+ try write(config)
+ }
+
+ func codexBarHookTrustKeysFromAppServer() async throws -> Set<String> {
+ let response = try await codexStatusService.listCodexHooks(cwds: [hooksListWorkingDirectory])
+ return Self.codexBarHookTrustKeys(
+ from: response,
+ executablePath: currentExecutablePath,
+ hooksURL: hooksURL
+ )
+ }
+
+ func cleanupCodexHookTrust(
+ removing keys: Set<String>,
+ discoveryError: Error?,
+ generation: Int
+ ) async {
+ do {
+ try ensureCurrentUpdate(generation)
+ if !keys.isEmpty {
+ try await removeCodexBarHookTrust(keys)
+ try ensureCurrentUpdate(generation)
+ }
+
+ if let discoveryError {
+ errorMessage = "已关闭 Codex Hook, 清理信任状态失败: \(discoveryError.localizedDescription)"
+ } else {
+ errorMessage = nil
+ }
+ } catch is CancellationError {
+ return
+ } catch {
+ guard isCurrentUpdate(generation) else {
+ return
+ }
+
+ errorMessage = "已关闭 Codex Hook, 清理信任状态失败: \(error.localizedDescription)"
+ }
+ }
+
+ func trustCodexBarHooks(_ entries: [CodexHookTrustEntry]) async throws {
+ guard !entries.isEmpty else {
+ return
+ }
+
+ try await writeHookTrustState(
+ Self.hookTrustStateValue(from: entries),
+ mergeStrategy: Self.configMergeStrategyUpsert
+ )
+ }
+
+ func removeCodexBarHookTrust(_ keys: Set<String>) async throws {
+ guard !keys.isEmpty else {
+ return
+ }
+
+ let response = try await codexStatusService.readCodexConfig()
+ var state = response.hookTrustState
+ // 先读出现有 state 再 replace, 只删除 CodexBar key, 保留用户自己的信任项
+ for key in keys {
+ state.removeValue(forKey: key)
+ }
+
+ try await writeHookTrustState(
+ Self.hookTrustStateValue(from: state),
+ mergeStrategy: Self.configMergeStrategyReplace
+ )
+ }
+
+ func writeHookTrustState(
+ _ value: [String: [String: String]],
+ mergeStrategy: String
+ ) async throws {
+ _ = try await codexStatusService.writeCodexConfigBatch(
+ edits: [
+ .init(
+ keyPath: Self.hookTrustStateKeyPath,
+ value: value,
+ mergeStrategy: mergeStrategy
+ )
+ ]
+ )
+ }
+
func readConfigIfPresent() throws -> JSONObject {
guard fileManager.fileExists(atPath: hooksURL.path) else {
return [:]
@@ -304,6 +443,7 @@ private extension CodexHookSettings {
static func installCodexBarHooks(in config: inout JSONObject, executablePath: String) throws {
var hooks = try hooksObject(from: config)
+ // 每个事件追加一个独立 group, 避免和用户已有 group 混写
for event in CodexHookEvent.allCases {
var groups = try eventGroups(named: event.configName, from: hooks)
groups.append([
@@ -325,6 +465,7 @@ private extension CodexHookSettings {
var hooks = try hooksObject(from: config)
+ // 仅移除 command 同时匹配当前可执行路径与 --hook-event 的 handler
for (event, value) in hooks {
guard let groups = value as? JSONArray else {
throw HookConfigError.invalidFormat
@@ -379,7 +520,7 @@ private extension CodexHookSettings {
hasDisabledHook = hasDisabledHook || !hook.enabled
hasUnexpectedSource = hasUnexpectedSource || normalizedPath(hook.sourcePath) != expectedSourcePath
- hasUntrustedHook = hasUntrustedHook || hook.trustStatus == "untrusted" || hook.trustStatus == "modified"
+ hasUntrustedHook = hasUntrustedHook || hookNeedsTrustUpdate(hook)
}
if !errors.isEmpty {
@@ -404,6 +545,68 @@ private extension CodexHookSettings {
return nil
}
+ static func hookTrustEntriesNeedingUpdate(
+ from response: CodexHooksListResponse,
+ executablePath: String,
+ hooksURL: URL
+ ) -> [CodexHookTrustEntry] {
+ let hooks = response.data.flatMap(\.hooks)
+ let expectedSourcePath = normalizedPath(hooksURL.path)
+ var entries: [CodexHookTrustEntry] = []
+ var seenKeys = Set<String>()
+
+ for event in CodexHookEvent.allCases {
+ guard let hook = matchingHook(
+ for: event,
+ in: hooks,
+ executablePath: executablePath,
+ expectedSourcePath: expectedSourcePath
+ ),
+ isManagedCodexBarHook(
+ hook,
+ executablePath: executablePath,
+ expectedSourcePath: expectedSourcePath
+ ),
+ hookNeedsTrustUpdate(hook),
+ let key = hook.key,
+ let trustedHash = hook.currentHash,
+ !key.isEmpty,
+ !trustedHash.isEmpty,
+ seenKeys.insert(key).inserted else {
+ continue
+ }
+
+ entries.append(.init(key: key, trustedHash: trustedHash))
+ }
+
+ return entries
+ }
+
+ static func codexBarHookTrustKeys(
+ from response: CodexHooksListResponse,
+ executablePath: String,
+ hooksURL: URL
+ ) -> Set<String> {
+ let expectedSourcePath = normalizedPath(hooksURL.path)
+ return Set(
+ response.data
+ .flatMap(\.hooks)
+ .compactMap { hook in
+ guard isManagedCodexBarHook(
+ hook,
+ executablePath: executablePath,
+ expectedSourcePath: expectedSourcePath
+ ),
+ let key = hook.key,
+ !key.isEmpty else {
+ return nil
+ }
+
+ return key
+ }
+ )
+ }
+
static func matchingHook(
for event: CodexHookEvent,
in hooks: [CodexHookMetadata],
@@ -418,6 +621,51 @@ private extension CodexHookSettings {
?? matchingHooks.first
}
+ static func isManagedCodexBarHook(
+ _ hook: CodexHookMetadata,
+ executablePath: String,
+ expectedSourcePath: String
+ ) -> Bool {
+ guard let command = hook.command else {
+ return false
+ }
+
+ // 自动信任/清理必须同时匹配命令和 sourcePath, 防止误碰用户 Hook
+ return isCodexBarCommand(command, executablePath: executablePath)
+ && normalizedPath(hook.sourcePath) == expectedSourcePath
+ }
+
+ static func hookNeedsTrustUpdate(_ hook: CodexHookMetadata) -> Bool {
+ switch hook.trustStatus.lowercased() {
+ case "untrusted", "modified":
+ true
+ default:
+ false
+ }
+ }
+
+ static func hookTrustStateValue(from state: [String: String]) -> [String: [String: String]] {
+ var value: [String: [String: String]] = [:]
+ for key in state.keys.sorted() {
+ guard let trustedHash = state[key] else {
+ continue
+ }
+
+ value[key] = [trustedHashKey: trustedHash]
+ }
+
+ return value
+ }
+
+ static func hookTrustStateValue(from entries: [CodexHookTrustEntry]) -> [String: [String: String]] {
+ var state: [String: String] = [:]
+ for entry in entries {
+ state[entry.key] = entry.trustedHash
+ }
+
+ return hookTrustStateValue(from: state)
+ }
+
static func hooksObject(from config: JSONObject) throws -> JSONObject {
guard let value = config[hooksKey] else {
return [:]
@@ -514,6 +762,7 @@ private extension CodexHookSettings {
}
static func isCodexBarCommand(_ command: String, executablePath: String) -> Bool {
+ // 使用 shell quoted 路径匹配当前 app, 再要求带有 Hook 子进程参数
command.contains(shellQuoted(executablePath))
&& command.split(whereSeparator: \.isWhitespace)
.contains(Substring(WorkflowHookEventRecorder.hookArgument))
diff --git a/CodexBar/Services/Settings/GlobalHotKeySettings.swift b/CodexBar/Services/Settings/GlobalHotKeySettings.swift
index d2a3cc9..2e12fa3 100644
--- a/CodexBar/Services/Settings/GlobalHotKeySettings.swift
+++ b/CodexBar/Services/Settings/GlobalHotKeySettings.swift
@@ -1,6 +1,7 @@
import Combine
import Foundation
+/// 全局快捷键偏好设置, 负责持久化和注册失败后的 UI 回滚
@MainActor
final class GlobalHotKeySettings: ObservableObject {
@Published private(set) var shortcut: GlobalHotKeyShortcut?
diff --git a/CodexBar/Services/Settings/LoginItemSettings.swift b/CodexBar/Services/Settings/LoginItemSettings.swift
index 07ca099..79aef5e 100644
--- a/CodexBar/Services/Settings/LoginItemSettings.swift
+++ b/CodexBar/Services/Settings/LoginItemSettings.swift
@@ -2,6 +2,7 @@ import Combine
import Foundation
import ServiceManagement
+/// 开机启动设置, 所有 ServiceManagement 错误只展示简短文案
@MainActor
final class LoginItemSettings: ObservableObject {
@Published private(set) var isEnabled = false
diff --git a/CodexBar/Services/Updates/AppUpdater.swift b/CodexBar/Services/Updates/AppUpdater.swift
index e39eff1..c4a5595 100644
--- a/CodexBar/Services/Updates/AppUpdater.swift
+++ b/CodexBar/Services/Updates/AppUpdater.swift
@@ -3,6 +3,7 @@ import Combine
import Sparkle
import SwiftUI
+/// Sparkle 更新状态桥接层, 同时驱动设置窗和菜单面板的更新提示
@MainActor
final class AppUpdater: NSObject, ObservableObject {
@Published private(set) var settingsStatusMessage: String?
@@ -23,7 +24,9 @@ final class AppUpdater: NSObject, ObservableObject {
init(bundle: Bundle = .main) {
super.init()
- // 开发环境可能没有 Sparkle feed 或公钥, 此时保留设置 UI, 但禁用更新能力
+ // 开发环境可能没有 Sparkle feed 或公钥
+ // 此时保留设置 UI, 但禁用更新能力
+
guard Self.hasUsableSparkleConfiguration(in: bundle) else {
return
}
diff --git a/CodexBar/Services/WorkflowStats/JSONLines.swift b/CodexBar/Services/WorkflowStats/JSONLines.swift
index 58e9177..aab1789 100644
--- a/CodexBar/Services/WorkflowStats/JSONLines.swift
+++ b/CodexBar/Services/WorkflowStats/JSONLines.swift
@@ -1,7 +1,8 @@
import Foundation
+/// 简单 JSONL 工具, 读取时跳过坏行以保护历史统计可用性
nonisolated enum JSONLines {
- /// 按行解码 JSONL: 切分换行、trim、跳过空行与解码失败的行
+ /// 按行解码 JSONL: 切分换行, trim, 跳过空行与解码失败的行
static func decode<T: Decodable>(_ type: T.Type = T.self, from data: Data) -> [T] {
decodeWithFailures(type, from: data).values
}
@@ -37,6 +38,7 @@ nonisolated enum JSONLines {
}
}
+/// 解码结果同时返回坏行数量, 维护流程据此触发重建
nonisolated struct JSONLinesDecodeResult<T> {
let values: [T]
let failedLineCount: Int
diff --git a/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift b/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift
index 3c1f02d..991b856 100644
--- a/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift
+++ b/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift
@@ -1,6 +1,7 @@
import Darwin
import Foundation
+/// Hook 子进程入口: 读取 stdin payload, 写入本地 JSONL, 然后立即退出
nonisolated enum WorkflowHookEventRecorder {
static let hookArgument = "--hook-event"
@@ -12,7 +13,9 @@ nonisolated enum WorkflowHookEventRecorder {
let payload = stdinPayload()
guard let eventName = payload.string(for: "hook_event_name") else {
- // 显式 Hook 模式下吞掉无效输入, 避免 Hook 子进程继续启动完整菜单栏 App
+ // 显式 Hook 模式下吞掉无效输入
+ // 避免 Hook 子进程继续启动完整菜单栏 App
+
return true
}
@@ -92,6 +95,7 @@ nonisolated enum WorkflowHookEventRecorder {
}
}
+/// Codex Hook payload 字段存在版本差异, 这里集中做宽松类型归一化
private nonisolated struct WorkflowHookPayload {
let values: [String: Any]
diff --git a/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift b/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift
index 3c4b0ed..ac8e3bf 100644
--- a/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift
+++ b/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift
@@ -2,6 +2,7 @@ import Combine
import Darwin
import Foundation
+/// 从 Hook 原始事件维护每日聚合, 对外只发布 UI 需要的统计快照
actor WorkflowStatsService {
private let eventsDirectoryURL: URL
private let dailyLogURL: URL
@@ -126,6 +127,8 @@ actor WorkflowStatsService {
) -> Bool {
var changed = markDirty(eventDateKeys.filter { state.days[$0] == nil }, in: &state)
+ // 文件变小说明被外部截断, 必须全量重建
+ // 变大则从旧 offset 增量追上
for (dateKey, day) in state.days {
let actualSize = eventLogSize(for: dateKey)
if actualSize < day.offset || day.offset != day.size {
@@ -300,6 +303,7 @@ actor WorkflowStatsService {
var buffer = Data()
var corrupt = 0
+ // 分块读取防止大日志一次性进内存, 但仍按完整 JSONL 行解码
while remainingBytes > 0 {
let readSize = min(Int(remainingBytes), Self.eventReadChunkSize)
guard let chunk = try fileHandle.read(upToCount: readSize), !chunk.isEmpty else {
@@ -351,6 +355,8 @@ actor WorkflowStatsService {
return
}
+ // daily.jsonl 和 maintenance.json 分开写
+ // 每次提交前后都检查事件文件是否被并发追加
try writeDailyAggregate(result.aggregate)
try commitMaintenanceState(result)
}
@@ -461,6 +467,7 @@ actor WorkflowStatsService {
}
}
+/// Hook 统计文件路径, 保留期和跨进程 flock 都集中在这里
nonisolated enum WorkflowStatsStorage {
private static let retentionDayCount = 210
private static let identifierRetentionDayCount = 3
@@ -519,6 +526,7 @@ nonisolated enum WorkflowStatsStorage {
try? lockHandle.close()
}
+ // Hook 子进程和主 App 可能同时写统计文件, 必须使用进程级排他锁
if flock(lockHandle.fileDescriptor, LOCK_EX) != 0 {
throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
}
@@ -587,6 +595,7 @@ nonisolated enum WorkflowStatsStorage {
}
}
+/// 记录单日事件文件已处理到的 offset, 支持后续增量维护
nonisolated struct WorkflowStatsDayMaintenanceState: Codable, Equatable {
var offset: UInt64
var size: UInt64
@@ -599,6 +608,7 @@ nonisolated struct WorkflowStatsDayMaintenanceState: Codable, Equatable {
}
}
+/// maintenance.json 的全局状态, pending 表示可增量, dirty 表示需全量重建
nonisolated struct WorkflowStatsMaintenanceState: Codable, Equatable {
static let currentSchema = 2
@@ -678,6 +688,7 @@ nonisolated struct WorkflowStatsMaintenanceState: Codable, Equatable {
}
}
+// 单次维护任务: 从 startOffset 读到 size, 可基于已有聚合继续追加
private nonisolated struct WorkflowStatsMaintenanceTask {
let dateKey: String
let startOffset: UInt64
@@ -686,6 +697,7 @@ private nonisolated struct WorkflowStatsMaintenanceTask {
let existingCorrupt: Int
}
+/// 维护任务的提交结果, corrupt 统计保留给后续诊断
private nonisolated struct WorkflowStatsMaintenanceResult {
let dateKey: String
let aggregate: WorkflowDailyAggregate
@@ -693,6 +705,7 @@ private nonisolated struct WorkflowStatsMaintenanceResult {
let corrupt: Int
}
+/// UI 层的工作流统计状态, 节流普通刷新但允许维护刷新立即执行
@MainActor
final class WorkflowStatsViewModel: ObservableObject {
@Published private(set) var snapshot = WorkflowStatsSnapshot.empty
diff --git a/CodexBar/Views/Log/LogView.swift b/CodexBar/Views/Log/LogView.swift
index fc9c017..c4c88ff 100644
--- a/CodexBar/Views/Log/LogView.swift
+++ b/CodexBar/Views/Log/LogView.swift
@@ -1,11 +1,13 @@
import AppKit
import SwiftUI
+/// app-server 交互日志窗口根视图
struct LogView: View {
@ObservedObject var store: RequestLogStore
var body: some View {
// 每轮渲染只取一次发布快照复用
+
let entries = store.entries
VStack(spacing: 0) {
header(entries: entries)
@@ -74,6 +76,7 @@ struct LogView: View {
}
}
+/// 单条日志行, 摘要行可展开查看请求和响应预览
private struct LogRow: View {
let entry: RequestLogEntry
@State private var isExpanded = false
@@ -148,7 +151,8 @@ private struct LogRow: View {
.font(.caption.weight(.medium).monospaced())
.foregroundStyle(.primary)
} else if let detail = entry.detail {
- // 无方法名的记录(信息/进程级错误)直接预览正文, 避免标签后留空
+ // 无方法名的记录 (信息/进程级错误) 直接预览正文
+ // 避免标签后留空
Text(RequestLogEntry.singleLinePreview(detail, limit: RequestLogEntry.summaryPreviewLength))
.font(.caption)
.foregroundStyle(.secondary)
@@ -230,12 +234,14 @@ private struct LogRow: View {
}()
}
+/// 预览弹窗数据源
private struct FullLogTextItem: Identifiable {
let id = UUID()
let title: String
let text: String
}
+/// 复制/预览按钮的统一样式入口
private struct LogHeaderActionButton: View {
let title: String
let systemImage: String
@@ -250,6 +256,7 @@ private struct LogHeaderActionButton: View {
}
}
+/// 统一收口剪贴板写入
private enum LogClipboard {
static func copy(_ text: String) {
NSPasteboard.general.clearContents()
@@ -257,6 +264,7 @@ private enum LogClipboard {
}
}
+/// 完整请求/响应预览弹窗
private struct FullLogTextView: View {
let item: FullLogTextItem
@Environment(\.dismiss) private var dismiss
@@ -316,11 +324,13 @@ private struct FullLogTextView: View {
}
}
+/// 日志预览文本, JSON 时会带基础语法高亮
private struct LogCodePreview {
let attributedText: NSAttributedString
let language: String?
}
+/// 将 JSON 格式化并做轻量 token 高亮, 非 JSON 保持纯文本
private enum LogCodePreviewFormatter {
private static let font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)
private static var baseAttributes: [NSAttributedString.Key: Any] {
@@ -441,6 +451,7 @@ private enum LogCodePreviewFormatter {
}
}
+/// AppKit 文本视图承载完整日志, 支持横向滚动
private struct LogCodePreviewView: NSViewRepresentable {
let attributedText: NSAttributedString
diff --git a/CodexBar/Views/Menu/AutoRefreshCountdownView.swift b/CodexBar/Views/Menu/AutoRefreshCountdownView.swift
index 4697dcf..a737d69 100644
--- a/CodexBar/Views/Menu/AutoRefreshCountdownView.swift
+++ b/CodexBar/Views/Menu/AutoRefreshCountdownView.swift
@@ -1,5 +1,6 @@
import SwiftUI
+/// 仅在菜单面板可见时每秒刷新, 隐藏时保持静态圆环
struct AutoRefreshCountdownTimeline: View {
let startedAt: Date
let interval: TimeInterval
diff --git a/CodexBar/Views/Menu/CodexStatusMenuSections.swift b/CodexBar/Views/Menu/CodexStatusMenuSections.swift
index b35e1bf..ea2461d 100644
--- a/CodexBar/Views/Menu/CodexStatusMenuSections.swift
+++ b/CodexBar/Views/Menu/CodexStatusMenuSections.swift
@@ -1,5 +1,6 @@
import SwiftUI
+/// 菜单面板内共享的固定尺寸, 保持各分区对齐
enum MenuMetrics {
static let panelPadding: CGFloat = 10
static let panelCornerRadius: CGFloat = 8
@@ -7,6 +8,7 @@ enum MenuMetrics {
static let loadingVerticalPadding: CGFloat = 16
}
+/// 已登录状态的账号行, 邮箱可双击模糊, 头像可双击刷新
struct AccountCard: View {
let title: String
let isEmail: Bool
@@ -73,6 +75,7 @@ struct AccountCard: View {
]
}
+/// 未登录或初始化失败时的账号行, 不展示底层错误细节
struct StatusAccountCard: View {
let loadState: CodexLoadState
let isRefreshing: Bool
@@ -118,6 +121,7 @@ struct StatusAccountCard: View {
}
}
+/// 额度和用量均无数据时的统一占位面板
struct EmptyDataPanel: View {
var body: some View {
Text("暂无数据")
@@ -129,6 +133,7 @@ struct EmptyDataPanel: View {
}
}
+/// 多个 limit 的额度区, 使用 stale 透明度标记缓存回退数据
struct QuotaLimitsSection: View {
let limits: [CodexQuotaLimitSnapshot]
let isStale: Bool
@@ -165,6 +170,7 @@ struct QuotaLimitsSection: View {
}
}
+/// 底部更新时间行, 同时承载 Sparkle 被动更新提示
struct UpdatedAtRow: View {
let snapshot: CodexQuotaSnapshot
let countdownStartedAt: Date
diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swift
index 718963a..28542c0 100644
--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift
+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift
@@ -1,11 +1,13 @@
import Combine
import SwiftUI
+/// 控制 TimelineView 是否 tick 的轻量状态, 由菜单面板显示/隐藏驱动
@MainActor
final class MenuSurfaceVisibilityState: ObservableObject {
@Published var isVisible = false
}
+/// 菜单栏弹出面板根视图, 只展示账号, 额度, token 和更新时间
struct CodexStatusMenuView: View {
static let menuWidth: CGFloat = Metrics.padding * 2 + MenuMetrics.panelPadding * 2 + UsageHeatmap.Metrics.totalWidth
diff --git a/CodexBar/Views/Menu/QuotaRow.swift b/CodexBar/Views/Menu/QuotaRow.swift
index 7377023..529659b 100644
--- a/CodexBar/Views/Menu/QuotaRow.swift
+++ b/CodexBar/Views/Menu/QuotaRow.swift
@@ -1,5 +1,6 @@
import SwiftUI
+/// 单个额度窗口行, 布局宽度固定以避免不同文案撑宽菜单面板
struct QuotaRow: View {
let window: QuotaWindow
@@ -81,6 +82,7 @@ private extension QuotaRow {
}()
}
+/// 额度颜色按剩余百分比分档, 无数据时使用占位色
private enum QuotaBarPalette {
static func filledColor(for percent: Int?) -> Color {
guard let percent else {
@@ -109,6 +111,7 @@ private enum QuotaBarPalette {
private static let red = Color(hex: 0xEE3F3F)
}
+/// 胶囊条, 与菜单面板宽度联动
private struct SegmentedQuotaBar: View {
let percent: Int?
diff --git a/CodexBar/Views/Menu/TokenCountText.swift b/CodexBar/Views/Menu/TokenCountText.swift
index 2b5df2e..421e41c 100644
--- a/CodexBar/Views/Menu/TokenCountText.swift
+++ b/CodexBar/Views/Menu/TokenCountText.swift
@@ -1,5 +1,6 @@
import SwiftUI
+/// token 数字展示组件, 负责 K/M/B 缩写和可选等宽保留
struct TokenCountText: View {
let tokens: Int
var font: Font = .caption.monospacedDigit().weight(.semibold)
@@ -34,6 +35,7 @@ struct TokenCountText: View {
}
}
+/// 根据新旧数值方向选择 numericText 的滚动方向
private struct NumericRollTransition: ViewModifier {
let value: Double
@State private var previous: Double?
@@ -60,6 +62,7 @@ extension View {
}
}
+/// 1K 以下显示完整整数, 1K 起使用 K/M/B
private enum TokenCountFormatter {
static func parts(from tokens: Int) -> TokenCountParts {
switch tokens {
diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swift
index 5cdc35b..547f30c 100644
--- a/CodexBar/Views/Menu/UsageHeatmap.swift
+++ b/CodexBar/Views/Menu/UsageHeatmap.swift
@@ -1,6 +1,7 @@
import AppKit
import SwiftUI
+/// hover 详情面板需要的完整上下文, 包括屏幕坐标和峰值 token
nonisolated struct UsageHeatmapHoverContext: Equatable {
let day: UsageHeatmapDay
let showsWorkflowStats: Bool
@@ -15,12 +16,14 @@ nonisolated enum UsageHeatmapDetailSide: Equatable {
case right
}
+/// hover 单元格在热力图中的列/行位置, 用于吸附和详情定位
nonisolated struct UsageHeatmapSelection: Equatable {
let day: UsageHeatmapDay
let column: Int
let row: Int
}
+/// token 摘要和近 30 周热力图的组合区
struct UsageSummaryView: View {
let usage: CodexUsageSnapshot
let isStale: Bool
@@ -168,6 +171,7 @@ struct UsageSummaryView: View {
}
private var hoverContext: UsageHeatmapHoverContext? {
+ // 详情面板由控制器显示, SwiftUI 这里只负责传递屏幕坐标和数据
hoverSelection.map {
UsageHeatmapHoverContext(
day: $0.day,
@@ -229,6 +233,7 @@ struct UsageSummaryView: View {
}
}
+/// 近 30 周 token 热力图, hover 时把指针吸附到最近的有效日期格
struct UsageHeatmap: View {
let days: [UsageHeatmapDay?]
let onScreenFrameChange: (CGRect?) -> Void
@@ -345,6 +350,7 @@ struct UsageHeatmap: View {
}
private func snappedSelection(at point: CGPoint) -> UsageHeatmapSelection? {
+ // 以格子中心为准吸附, 指针离中心过远时视为离开格子
let column = Int(((point.x - Metrics.squareSize / 2) / Metrics.squarePitch).rounded())
let row = Int(((point.y - Metrics.squareSize / 2) / Metrics.squarePitch).rounded())
@@ -428,6 +434,7 @@ extension UsageHeatmap {
}
}
+/// 单个热力图方块, 蓝色透明度表示当天 token 强度
private struct UsageHeatmapSquare: View {
let day: UsageHeatmapDay
let percent: Double
@@ -470,6 +477,7 @@ private struct UsageHeatmapSquare: View {
}
}
+/// 通过 NSView 桥接读取热力图在屏幕坐标系中的 frame
private struct HeatmapScreenFrameReader: NSViewRepresentable {
let onChange: (CGRect?) -> Void
@@ -485,6 +493,7 @@ private struct HeatmapScreenFrameReader: NSViewRepresentable {
}
}
+/// 只在布局稳定后上报 frame, 避免 hover 期间反复触发无效定位
@MainActor
private final class HeatmapScreenFrameReportingView: NSView {
var onChange: ((CGRect?) -> Void)?
@@ -502,7 +511,9 @@ private final class HeatmapScreenFrameReportingView: NSView {
}
func scheduleReport() {
- // updateNSView 每次 hover 重渲染都会调到这里, 合并掉重复的待执行 report, 至多保留一个
+ // updateNSView 每次 hover 重渲染都会调到这里
+ // 合并掉重复的待执行 report, 至多保留一个
+
guard !reportScheduled else {
return
}
@@ -537,6 +548,7 @@ private final class HeatmapScreenFrameReportingView: NSView {
}
}
+/// 热力图 hover 详情内容, Hook 开启时额外展示工作流统计
struct UsageHeatmapDayDetailView: View {
let context: UsageHeatmapHoverContext
@Environment(\.colorScheme) private var colorScheme
@@ -839,6 +851,7 @@ struct UsageHeatmapDayDetailView: View {
}
}
+/// 日期拆成三段以获得更自然的数字滚动过渡
private struct AnimatedDateText: View {
let startDate: String
let font: Font
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index b48035a..b678f93 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -1,6 +1,7 @@
import AppKit
import SwiftUI
+/// 设置窗口根视图, 汇总启动项, 更新, Hook, 快捷键和版本信息
struct AppSettingsView: View {
@EnvironmentObject private var statusViewModel: CodexStatusViewModel
@EnvironmentObject private var appUpdater: AppUpdater
diff --git a/CodexBar/Views/Settings/CodexVersionSection.swift b/CodexBar/Views/Settings/CodexVersionSection.swift
index d2888ff..75a83f6 100644
--- a/CodexBar/Views/Settings/CodexVersionSection.swift
+++ b/CodexBar/Views/Settings/CodexVersionSection.swift
@@ -1,6 +1,7 @@
import AppKit
import SwiftUI
+/// Codex CLI/APP 版本区, 同时展示磁盘版本和当前 app-server 运行版本
struct CodexVersionSection: View {
let snapshot: CodexCLIVersionSnapshot
let connectionInfo: CodexCLIConnectionInfo?
@@ -114,6 +115,7 @@ struct CodexVersionSection: View {
}
}
+/// 路径复制后保持同一布局宽度, 避免 `已复制` 状态造成跳动
private struct CopyablePathText: View {
let path: String
let isCopied: Bool
diff --git a/CodexBar/Views/Settings/HotKeyRecorderRow.swift b/CodexBar/Views/Settings/HotKeyRecorderRow.swift
index 295bbfd..9ffcc26 100644
--- a/CodexBar/Views/Settings/HotKeyRecorderRow.swift
+++ b/CodexBar/Views/Settings/HotKeyRecorderRow.swift
@@ -2,6 +2,7 @@ import AppKit
import Carbon.HIToolbox
import SwiftUI
+/// 快捷键录制行, 隐藏 NSView 负责真正捕获 keyDown
struct HotKeyRecorderRow: View {
@ObservedObject var settings: GlobalHotKeySettings
@State private var isRecording = false
@@ -160,6 +161,7 @@ struct HotKeyRecorderRow: View {
}
}
+/// SwiftUI 到 AppKit first responder 的桥接层
private struct HotKeyCaptureView: NSViewRepresentable {
@Binding var isRecording: Bool
let onCapture: (NSEvent) -> Void
@@ -189,6 +191,7 @@ private struct HotKeyCaptureView: NSViewRepresentable {
}
}
+/// 捕获下一次按键并监听窗口关闭, 关闭时清理录制态
private final class HotKeyCaptureNSView: NSView {
var onCapture: ((NSEvent) -> Void)?
var onCancel: (() -> Void)?
diff --git a/CodexBar/Views/Settings/SettingsToggleRow.swift b/CodexBar/Views/Settings/SettingsToggleRow.swift
index 2349a2b..d22e25b 100644
--- a/CodexBar/Views/Settings/SettingsToggleRow.swift
+++ b/CodexBar/Views/Settings/SettingsToggleRow.swift
@@ -1,5 +1,6 @@
import SwiftUI
+/// 设置页通用开关行
struct SettingsToggleRow: View {
let icon: String
let title: String
diff --git a/CodexBar/Views/Shared/LiquidGlassStyle.swift b/CodexBar/Views/Shared/LiquidGlassStyle.swift
index 13f0c7c..924ee99 100644
--- a/CodexBar/Views/Shared/LiquidGlassStyle.swift
+++ b/CodexBar/Views/Shared/LiquidGlassStyle.swift
@@ -1,11 +1,14 @@
import SwiftUI
+/// CodexBar 统一的短状态动画
extension Animation {
static let codexStatus = Animation.easeInOut(duration: 0.20)
}
+/// 共享颜色和十六进制便捷初始化
extension Color {
- // 某些自定义 View 需要具体 Color, 不能直接使用 .primary/.secondary 这类 ShapeStyle
+ // 某些自定义 View 需要具体 Color
+ // 不能直接使用 .primary/.secondary 这类 ShapeStyle
static let codexLabel = Color(nsColor: .labelColor)
static let codexSecondaryLabel = Color(nsColor: .secondaryLabelColor)
@@ -18,6 +21,7 @@ extension Color {
}
}
+/// 自绘 Liquid Glass 背景和 stale 状态修饰
extension View {
func liquidGlassSurface(
cornerRadius: CGFloat,
@@ -52,12 +56,13 @@ extension View {
}
}
- /// 数据为缓存回退(本轮刷新失败)时弱化显示
+ /// 数据为缓存回退 (本轮刷新失败) 时弱化显示
func markStale(_ isStale: Bool) -> some View {
opacity(isStale ? 0.55 : 1)
}
}
+/// 分区之间的细分隔线, 与玻璃背景保持低对比
struct LiquidGlassDivider: View {
var body: some View {
Rectangle()
@@ -77,6 +82,7 @@ struct LiquidGlassDivider: View {
}
}
+/// 自绘玻璃面板, 由底色, 高光, 纹理, 描边和阴影叠加组成
private struct LiquidGlassSurface: View {
let cornerRadii: RectangleCornerRadii
let isOuterSurface: Bool
@@ -201,6 +207,7 @@ private struct LiquidGlassSurface: View {
}
}
+/// 稳定伪随机纹理, 不依赖运行时随机数以避免重绘闪烁
private struct LiquidGlassFrostedTexture: View {
let isOuterSurface: Bool
@Environment(\.colorScheme) private var colorScheme
@@ -250,6 +257,7 @@ private struct LiquidGlassFrostedTexture: View {
}
}
+/// 小徽章背景, 用于计划名和当前运行状态
private struct LiquidGlassCapsule: View {
let tint: Color
@Environment(\.colorScheme) private var colorScheme
@@ -300,6 +308,7 @@ private struct LiquidGlassCapsule: View {
}
}
+/// 面板边缘的高光描边
private struct LiquidGlassSpecular: View {
let cornerRadii: RectangleCornerRadii
diff --git a/Docs/AppServer.md b/Docs/AppServer.md
index 3cd550f..964b63e 100644
--- a/Docs/AppServer.md
+++ b/Docs/AppServer.md
@@ -51,8 +51,9 @@ codex app-server --listen stdio://
- `account/read` 每轮复用连接时用 `refreshToken: false` 更新账户状态。
- `account/rateLimits/read` 读取额度。
- `account/usage/read` 读取 `summary.lifetimeTokens`、`summary.peakDailyTokens`、`dailyUsageBuckets`。
-- `config/read` 在开启 Codex Hook 前读取有效配置,用于判断 `[features] hooks = false` 或兼容旧名 `codex_hooks = false` 是否禁用了 Hook。
-- `hooks/list` 在写入 Hook 后或设置页刷新时验证 Codex 实际识别到的 Hook,检查 `command`、`eventName`、`enabled`、`sourcePath`、`trustStatus`、`warnings` 和 `errors`。
+- `config/read` 在开启 Codex Hook 前读取有效配置,用于判断 `[features] hooks = false` 或兼容旧名 `codex_hooks = false` 是否禁用了 Hook;关闭清理时也读取 `hooks.state` 以保留其他 Hook 的信任状态。
+- `hooks/list` 在写入 Hook 后或设置页刷新时验证 Codex 实际识别到的 Hook,检查 `command`、`eventName`、`enabled`、`sourcePath`、`trustStatus`、`key`、`currentHash`、`warnings` 和 `errors`。
+- `config/batchWrite` 只用于写回 `hooks.state`:开启后把 CodexBar Hook 的 `key/currentHash` upsert 成 `trusted_hash`,关闭时移除对应 key。
认证失败时,同会话最多调用一次 `account/read(refreshToken:true)` 后重试原读取。
diff --git a/Docs/CodexHook.md b/Docs/CodexHook.md
index a71c5f8..39aae78 100644
--- a/Docs/CodexHook.md
+++ b/Docs/CodexHook.md
@@ -23,20 +23,22 @@ CodexBar 处理器的识别条件:
检测是否已开启时,只要任意 CodexBar 事件存在当前 App 路径对应的处理器,开关就保持开启;如果缺少部分事件,`hooks/list` 验证会在 Hook 选项下方显示 `CodexBar Hook 已不完整`。
+关闭时会先通过 `hooks/list` 找出 `command` 属于当前 CodexBar 且来源为全局 `hooks.json` 的 Hook key;移除 `hooks.json` 中的处理器后,再通过 `config/read` + `config/batchWrite` 从 `hooks.state` 删除这些 key。清理失败不恢复已经关闭的 Hook,只在 Hook 选项下方提示清理信任状态失败。
+
开启写入成功后会复用同一条 app-server 会话调用 `hooks/list` 做有效性检查:
- `command`: 必须包含 CodexBar 当前可执行文件路径生成的命令和 `--hook-event` 参数。
- `eventName`: 必须覆盖全部 CodexBar 事件;`hooks/list` 返回值使用 `sessionStart` 这类 lower camel 名称,CodexBar 会与写入的 `SessionStart` 配置名做映射。
- `enabled`: 必须为 `true`,否则提示 Codex 已禁用这些 Hook。
- `sourcePath`: 必须指向全局 `~/.codex/hooks.json`。
-- `trustStatus`: `untrusted` 或 `modified` 时提示用户在 Codex 中执行 `/hooks` 并信任 CodexBar。
+- `trustStatus`: `untrusted` 或 `modified` 时,仅对 `sourcePath` 指向全局 `~/.codex/hooks.json` 且 command 属于当前 CodexBar 的 Hook 读取 `key` 和 `currentHash`,通过 `config/batchWrite` upsert 到 `hooks.state` 的 `trusted_hash`,再重新 `hooks/list` 验证。
- `warnings` / `errors`: 参与验证优先级判断;设置页只显示最高优先级问题,完整返回内容进入日志窗口。
-`config/read` 和 `hooks/list` 都通过 `AppServerSession.request` 调用,请求和响应会进入 CodexBar 日志窗口。
+`config/read`、`hooks/list` 和 `config/batchWrite` 都通过 `AppServerSession.request` 调用,请求和响应会进入 CodexBar 日志窗口。
`config/read` 请求失败时,CodexBar 不写入 `hooks.json`,调用 `refresh()` 恢复本地实际状态,并在 Hook 选项下方显示 `设置 Codex Hook 失败: <错误>`。只有请求成功且明确读到全局禁用 Hook 时,才显示 `Codex 配置已禁用 Hook`。
-`hooks/list` 请求失败或验证发现问题时,CodexBar 不回滚已经写入的 Hook。请求失败时显示 `无法验证 Codex Hook: <错误>`;请求成功但验证未通过时只显示最高优先级的一条摘要。当前优先级为: 无返回结果、Codex 返回错误、Hook 被禁用、Hook 未被信任、事件不完整、来源异常、Codex 返回警告。
+`hooks/list`、自动信任写入或二次验证失败时,CodexBar 不回滚已经写入的 Hook。请求失败时显示 `无法验证 Codex Hook: <错误>`;请求成功但验证未通过时只显示最高优先级的一条摘要。当前优先级为: 无返回结果、Codex 返回错误、Hook 被禁用、Hook 未被信任、事件不完整、来源异常、Codex 返回警告。
Hook 事件定义集中在 `CodexHookEvent`。`configName` 用于写入 `hooks.json`, `appServerName` 用于匹配 `hooks/list` 返回的 lower camel 事件名, `init(eventName:)` 用于把 events 中的 `hook_event_name` 归一化到同一组事件。
diff --git a/Docs/DevelopmentGuide.md b/Docs/DevelopmentGuide.md
index eda7224..4259b05 100644
--- a/Docs/DevelopmentGuide.md
+++ b/Docs/DevelopmentGuide.md
@@ -406,25 +406,26 @@ app-server 与状态刷新错误:
设置, Hook 和更新错误:
-| 错误来源 | 检测位置 | 用户可见状态 | 重试或降级 |
-| -------------------------------- | ------------------------------------------------------------------ | -------------------------------------------- | ------------------------------------------------ |
-| 登录项注册或取消失败 | `LoginItemSettings.setEnabled` | 设置窗口中部错误组显示"设置开机启动失败" | 调用 `refresh()` 恢复实际状态 |
-| `config/read` 请求失败 | `CodexHookSettings.setEnabled` / app-server `config/read` | Hook 选项下方显示"设置 Codex Hook 失败" | 不写 `hooks.json`, 调用 `refresh()` 恢复实际状态 |
-| Codex 全局配置禁用 Hook | `CodexHookSettings.setEnabled` / app-server `config/read` | Hook 开关保持关闭, Hook 选项下方显示禁用说明 | 不写 `hooks.json` |
-| `hooks.json` 读取失败或结构非法 | `CodexHookSettings.refresh` | Hook 开关视为关闭, Hook 选项下方显示错误 | 不写配置 |
-| Hook 开关写入失败 | `CodexHookSettings.setEnabled` | Hook 选项下方显示"设置 Codex Hook 失败" | 调用 `refresh()` 恢复实际状态 |
-| `hooks/list` 请求失败 | `CodexHookSettings.verifyInstalledHooks` / app-server `hooks/list` | Hook 选项下方显示"无法验证 Codex Hook" | 保留已写入 Hook, 详细错误进入日志 |
-| Hook 写入后验证发现问题 | `CodexHookSettings.verifyInstalledHooks` / app-server `hooks/list` | Hook 选项下方显示最高优先级验证摘要 | 保留已写入 Hook, 详细响应进入日志 |
-| 快捷键无法识别或不符合规则 | `HotKeyRecorderRow` / `GlobalHotKeySettings.setShortcut` | 快捷键行内显示红色错误 | 用户清除后重新录制 |
-| 快捷键注册冲突 | `StatusItemController.applyGlobalHotKey` | 快捷键行内显示占用提示 | 恢复上一个已注册快捷键 |
-| Hook 子进程 payload 不是 JSON | `WorkflowHookEventRecorder.stdinPayload` | 无 UI 提示 | 吞掉本次 Hook, 避免启动完整菜单栏 App |
-| Hook 子进程写入失败 | `WorkflowHookEventRecorder.handleIfRequested` | 无 UI 提示 | `try? record` 吞掉错误并正常退出, 避免阻断 Codex |
-| `daily.jsonl` 缺失, 空文件或坏行 | `WorkflowStatsService.prepareMaintenanceTasks` | 热力图详情面板可能暂时显示 0 | 标记 dirty, 后续从 events 文件重建 |
-| events 文件变小或 offset 不一致 | `WorkflowStatsService.reconcileEventFiles` | 热力图详情面板可能暂时显示旧聚合 | 标记 dirty, 从头重建当天聚合 |
-| 单个维护任务失败 | `WorkflowStatsService.performMaintenanceIfNeeded` | 使用已有 daily 或空 snapshot | 对应日期标记 dirty |
-| Sparkle 配置缺失 | `AppUpdater.init` | 更新开关禁用, 操作显示"未配置更新资源" | 不创建 updater controller |
-| 手动检查没有更新 | `updaterDidNotFindUpdate` | 显示"没有可用更新" | 1 秒后自动清理状态 |
-| 手动检查失败 | `didAbortWithError` | 显示"检查更新失败" | 不展示底层错误细节 |
+| 错误来源 | 检测位置 | 用户可见状态 | 重试或降级 |
+| -------------------------------- | ------------------------------------------------------------------------- | -------------------------------------------- | ------------------------------------------------ |
+| 登录项注册或取消失败 | `LoginItemSettings.setEnabled` | 设置窗口中部错误组显示"设置开机启动失败" | 调用 `refresh()` 恢复实际状态 |
+| `config/read` 请求失败 | `CodexHookSettings.setEnabled` / app-server `config/read` | Hook 选项下方显示"设置 Codex Hook 失败" | 不写 `hooks.json`, 调用 `refresh()` 恢复实际状态 |
+| Codex 全局配置禁用 Hook | `CodexHookSettings.setEnabled` / app-server `config/read` | Hook 开关保持关闭, Hook 选项下方显示禁用说明 | 不写 `hooks.json` |
+| `hooks.json` 读取失败或结构非法 | `CodexHookSettings.refresh` | Hook 开关视为关闭, Hook 选项下方显示错误 | 不写配置 |
+| Hook 开关写入失败 | `CodexHookSettings.setEnabled` | Hook 选项下方显示"设置 Codex Hook 失败" | 调用 `refresh()` 恢复实际状态 |
+| `hooks/list` 请求失败 | `CodexHookSettings.verifyInstalledHooks` / app-server `hooks/list` | Hook 选项下方显示"无法验证 Codex Hook" | 保留已写入 Hook, 详细错误进入日志 |
+| Hook 自动信任写入失败 | `CodexHookSettings.updateCodexHookTrust` / app-server `config/batchWrite` | Hook 选项下方显示"无法验证 Codex Hook" | 保留已写入 Hook, 详细错误进入日志 |
+| Hook 写入后验证发现问题 | `CodexHookSettings.verifyInstalledHooks` / app-server `hooks/list` | Hook 选项下方显示最高优先级验证摘要 | 保留已写入 Hook, 详细响应进入日志 |
+| 快捷键无法识别或不符合规则 | `HotKeyRecorderRow` / `GlobalHotKeySettings.setShortcut` | 快捷键行内显示红色错误 | 用户清除后重新录制 |
+| 快捷键注册冲突 | `StatusItemController.applyGlobalHotKey` | 快捷键行内显示占用提示 | 恢复上一个已注册快捷键 |
+| Hook 子进程 payload 不是 JSON | `WorkflowHookEventRecorder.stdinPayload` | 无 UI 提示 | 吞掉本次 Hook, 避免启动完整菜单栏 App |
+| Hook 子进程写入失败 | `WorkflowHookEventRecorder.handleIfRequested` | 无 UI 提示 | `try? record` 吞掉错误并正常退出, 避免阻断 Codex |
+| `daily.jsonl` 缺失, 空文件或坏行 | `WorkflowStatsService.prepareMaintenanceTasks` | 热力图详情面板可能暂时显示 0 | 标记 dirty, 后续从 events 文件重建 |
+| events 文件变小或 offset 不一致 | `WorkflowStatsService.reconcileEventFiles` | 热力图详情面板可能暂时显示旧聚合 | 标记 dirty, 从头重建当天聚合 |
+| 单个维护任务失败 | `WorkflowStatsService.performMaintenanceIfNeeded` | 使用已有 daily 或空 snapshot | 对应日期标记 dirty |
+| Sparkle 配置缺失 | `AppUpdater.init` | 更新开关禁用, 操作显示"未配置更新资源" | 不创建 updater controller |
+| 手动检查没有更新 | `updaterDidNotFindUpdate` | 显示"没有可用更新" | 1 秒后自动清理状态 |
+| 手动检查失败 | `didAbortWithError` | 显示"检查更新失败" | 不展示底层错误细节 |
Codex 版本探测错误:
@@ -563,7 +564,7 @@ Hook 开启且当天没有 token bucket 时, 今天的 token 数显示 `--`。
~/.codex/hooks.json
```
-开启前会复用 App 当前的 `CodexStatusService` app-server 会话调用 `config/read`, 如果有效配置中 `[features] hooks = false` 或兼容旧名 `codex_hooks = false`, 则不写入 Hook, 并在 Hook 选项下方提示。`config/read` 请求失败时同样不写入 Hook, 并显示"设置 Codex Hook 失败"。开启写入后会继续调用 `hooks/list`, 检查 Codex 实际识别到的 `command`, `eventName`, `enabled`, `sourcePath`, `trustStatus`, `warnings` 和 `errors`。`hooks/list` 请求失败或验证未通过不会回滚已写入 Hook, 只在 Hook 选项下方显示验证摘要。这些 app-server 请求和响应都会进入日志窗口。
+开启前会复用 App 当前的 `CodexStatusService` app-server 会话调用 `config/read`, 如果有效配置中 `[features] hooks = false` 或兼容旧名 `codex_hooks = false`, 则不写入 Hook, 并在 Hook 选项下方提示。`config/read` 请求失败时同样不写入 Hook, 并显示"设置 Codex Hook 失败"。开启写入后会继续调用 `hooks/list`, 检查 Codex 实际识别到的 `command`, `eventName`, `enabled`, `sourcePath`, `trustStatus`, `key`, `currentHash`, `warnings` 和 `errors`。如果 `trustStatus` 是 `untrusted` 或 `modified`, CodexBar 只对 `sourcePath` 指向全局 `~/.codex/hooks.json` 且 command 属于当前 CodexBar 的 Hook, 用 `config/batchWrite` 把对应 `trusted_hash` upsert 到 `hooks.state` 并重新 `hooks/list` 验证。`hooks/list`、自动信任写入或验证未通过不会回滚已写入 Hook, 只在 Hook 选项下方显示验证摘要。这些 app-server 请求和响应都会进入日志窗口。
下面的时序图展示开启 Hook, Codex 触发事件, 本机写入, 后台维护, 以及常见错误后的处理
@@ -605,6 +606,9 @@ sequenceDiagram
Settings->>Server: hooks/list 验证 Codex 实际识别结果
alt hooks/list 请求失败
Server-->>Settings: 保留已写入 Hook, 显示无法验证
+ else Hook 未信任或已修改
+ Settings->>Server: config/batchWrite upsert trusted_hash
+ Settings->>Server: hooks/list 二次验证
else command, eventName, enabled, sourcePath, trustStatus, warnings 或 errors 异常
Server-->>Settings: Hook 选项下方显示验证说明
else 验证通过
@@ -833,19 +837,19 @@ App 再次成为 active 时, 也会刷新 Codex 版本区, 并在已安装 Hook
设置项:
-| 设置项 | 状态源 | 写入行为 |
-| --------------- | -------------------------------------------------------------- | -------------------------------------------------------- |
-| 开机自动启动 | `SMAppService.mainApp.status` | `register()` / `unregister()` |
-| 自动检查更新 | Sparkle updater | 设置 `automaticallyChecksForUpdates` |
-| 使用快捷键 | `GlobalHotKeySettings.shortcut` | 写入 `UserDefaults` 并注册 hot key |
-| 启用 Codex Hook | app-server `config/read` / `hooks/list`, `~/.codex/hooks.json` | 检查全局 Hook 开关后追加或移除当前 CodexBar command hook |
-| Codex 版本 | `CodexCLIVersionSnapshot` + 当前 app-server 握手信息 | 路径点击复制到剪贴板 |
-| CodexBar 版本 | Bundle + AppUpdater 状态 | 有更新状态时优先显示动态消息 |
+| 设置项 | 状态源 | 写入行为 |
+| --------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------- |
+| 开机自动启动 | `SMAppService.mainApp.status` | `register()` / `unregister()` |
+| 自动检查更新 | Sparkle updater | 设置 `automaticallyChecksForUpdates` |
+| 使用快捷键 | `GlobalHotKeySettings.shortcut` | 写入 `UserDefaults` 并注册 hot key |
+| 启用 Codex Hook | app-server `config/read` / `hooks/list` / `config/batchWrite`, `~/.codex/hooks.json` | 检查全局 Hook 开关后追加或移除当前 CodexBar command hook, 并维护对应 `hooks.state` 信任状态 |
+| Codex 版本 | `CodexCLIVersionSnapshot` + 当前 app-server 握手信息 | 路径点击复制到剪贴板 |
+| CodexBar 版本 | Bundle + AppUpdater 状态 | 有更新状态时优先显示动态消息 |
错误显示:
- 开机启动失败显示在设置组与底部按钮组之间的独立错误组
-- Hook 设置失败, 全局禁用, `hooks/list` 未信任或验证异常显示在 Hook 选项下方
+- Hook 设置失败, 全局禁用, 自动信任写入失败或验证异常显示在 Hook 选项下方
- 没有登录项错误时不渲染错误组
- 快捷键无法识别, 规则不合法或注册冲突显示在快捷键行内
- 更新检查状态显示在 CodexBar 版本行
@@ -978,7 +982,7 @@ App 再次成为 active 时, 也会刷新 Codex 版本区, 并在已安装 Hook
- Hook 子进程只在锁内追加当天 `events/YYYY-MM-DD.jsonl` 并更新 `maintenance.json`
- 主 App 维护 `daily.jsonl` 时, 先锁外原子写 daily, 再短暂持锁提交维护状态, 减少阻塞 Hook 写入
- `maintenance.json` 和 `daily.jsonl` 使用 atomic write
-- 设置 Hook 时通过当前 app-server 会话先读 `config/read`, 未全局禁用时 pretty printed 写回 `~/.codex/hooks.json`, 只移除 command 同时包含当前 App 可执行路径和 `--hook-event` 参数的 handler, 写入后再用 `hooks/list` 验证有效状态
+- 设置 Hook 时通过当前 app-server 会话先读 `config/read`, 未全局禁用时 pretty printed 写回 `~/.codex/hooks.json`, 只移除 command 同时包含当前 App 可执行路径和 `--hook-event` 参数的 handler, 写入后再用 `hooks/list` 验证有效状态;未信任或已修改时, 仅把当前 CodexBar command 且来源为全局 `hooks.json` 的 `key/currentHash` 通过 `config/batchWrite` 写入 `hooks.state`
隐私和敏感信息边界:
diff --git a/README.md b/README.md
index 762c9d3..98fbf22 100644
--- a/README.md
+++ b/README.md
@@ -39,7 +39,7 @@ CodexBar 可以在设置中开启「启用 Codex Hook」
开启后会在全局 `~/.codex/hooks.json` 中增加以下 Hook,用于接收 Codex 的会话、工具调用、权限请求、上下文压缩和子智能体事件。
-开启前会通过本机 Codex app-server 检查全局 `config.toml` 是否禁用了 Hook;如果已禁用,CodexBar 不会写入配置,并会在 Hook 选项下方提示。写入后还会用 `hooks/list` 确认 CodexBar 自己的 Hook 命令、事件、来源、启用状态、信任状态以及 Codex 返回的警告或错误。
+开启前会通过本机 Codex app-server 检查全局 `config.toml` 是否禁用了 Hook;如果已禁用,CodexBar 不会写入配置,并会在 Hook 选项下方提示。写入后还会用 `hooks/list` 确认 CodexBar 自己的 Hook 命令、事件、来源、启用状态、信任状态以及 Codex 返回的警告或错误;未信任或已修改时只会把当前 CodexBar Hook 的 key/hash 写入 `hooks.state` 后再次验证。
- `SessionStart`: 记录一次 Codex 会话开始,用于统计会话总数
- `UserPromptSubmit`: 记录用户提交提示词事件,保留为原始活动事件
diff --git a/appcast.xml b/appcast.xml
index 48b6e9a..24b2da4 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.1.3</title>
+ <sparkle:version>27</sparkle:version>
+ <sparkle:shortVersionString>3.1.3</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.1.3</sparkle:releaseNotesLink>
+ <pubDate>Thu, 25 Jun 2026 12:03:41 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.1.3.dmg" sparkle:edSignature="RRlH9tMTga4XjHhRiRQS3g5GA9BIQHkKfcFMaQP8wYbmJxXqE/PJ6METPSB9enHh8DSZMJq4qGlhnLvR1bM9Bg==" length="3158065" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.1.2</title>
<sparkle:version>26</sparkle:version>