Skip to content

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

fix: 适配 Swift 6 并完善 Hook 设置

Bob1cb133850f87
diff --git a/.swiftformat b/.swiftformat
new file mode 100644
index 0000000..eb8f268
--- /dev/null
+++ b/.swiftformat
@@ -0,0 +1,56 @@
+# CodexBar SwiftFormat 配置
+
+# 项目语言设置
+--swift-version 6.0
+--language-mode 6
+
+# 文件范围
+--exclude .build,DerivedData,Pods,Carthage,Generated
+--linebreaks lf
+--trim-whitespace always
+--header ignore
+
+# 基础布局
+--indent 4
+--allman false
+--else-position same-line
+--guard-else same-line
+--indent-case false
+--empty-braces no-space
+--max-width none
+
+# 换行规则
+--allow-partial-wrapping true
+--closing-paren balanced
+--wrap-arguments before-first
+--wrap-parameters before-first
+--wrap-collections before-first
+--wrap-conditions preserve
+--wrap-effects preserve
+--wrap-return-type preserve
+
+# 导入与字面量
+--import-grouping alpha,access-control
+--hex-literal-case uppercase
+--decimal-grouping none
+--binary-grouping none
+--hex-grouping none
+--octal-grouping none
+
+# Swift 风格
+--acronyms ID,URL,UUID
+--self remove
+--semicolons never
+--trailing-commas never
+--ranges spaced
+--operator-func spaced
+--pattern-let hoist
+--nil-init remove
+--void-type Void
+--some-any true
+
+# 保持格式化结果可预期, 不自动重排源码结构
+--disable markTypes,organizeDeclarations,sortDeclarations,trailingClosures,enumNamespaces,preferForLoop
+
+# 多行 guard 大括号不换行
+--disable wrapMultilineStatementBraces
diff --git a/.swiftlint.yml b/.swiftlint.yml
index 0101d52..4174cd9 100644
--- a/.swiftlint.yml
+++ b/.swiftlint.yml
@@ -1,12 +1,6 @@
included:
- CodexBar
-excluded:
- - .build
- - DerivedData
- - /tmp
- - CodexBar/Resources
-
line_length:
warning: 140
error: 180
diff --git a/AGENTS.md b/AGENTS.md
index 0c7fc78..6489897 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -81,7 +81,7 @@ CodexStatusService(JSON-RPC app-server)
-> CodexStatusMenuView / AppSettingsView / LogView
Codex Hook
- -> WorkflowHookEventRecorder(--hook-event)
+ -> WorkflowHookEventRecorder(stdin hook_event_name)
-> WorkflowStatsStorage(events/YYYY-MM-DD.jsonl / daily.jsonl)
-> WorkflowStatsService
-> WorkflowStatsViewModel
@@ -109,8 +109,8 @@ Hook 统计的配置、存储、保留策略和统计口径见 [Docs/CodexHook.m
## Codex Hook 合约
- 详细设计见 [Docs/CodexHook.md](Docs/CodexHook.md)。
-- 设置开关只能追加或移除 CodexBar 自己的 Hook 处理器, 不能破坏用户已有 Hook。
-- Hook 命令只支持 `--hook-event`。
+- 设置开关只能追加或移除 command 包含当前 CodexBar 可执行路径的 Hook 处理器, 不能破坏其他用户 Hook。
+- Hook 命令写入当前 CodexBar 可执行文件路径; Hook 事件名来自 Codex 传入的 stdin payload 顶层 `hook_event_name`。
- Hook 数据只保存在 `~/Library/Application Support/CodexBar/HookEvents/`。
- Hook 写入可能并发触发, 追加 `events/YYYY-MM-DD.jsonl` 并更新 `maintenance.json` 时必须通过 `stats.lock` 加锁。
@@ -202,14 +202,16 @@ Hook 统计的配置、存储、保留策略和统计口径见 [Docs/CodexHook.m
- 路径点击复制到剪贴板, 对应来源显示「已复制」1.5 秒; 保留路径文本布局宽度避免跳动。
- 默认全局快捷键是 `⌘⇧W`; 快捷键录制至少需要两个修饰键, 不允许 Command-Space 或 Command-Tab; 注册冲突、无法识别和校验错误显示在快捷键行内。
- 设置页包含「启用 Codex Hook」开关; 开启后会写入全局 Codex Hook 配置, 用于近 30 周数据展示更多本机统计数据。
-- Codex Hook 开关下方说明文案为小号辅助文字; 不展示启用/关闭状态文案。
-- 开机启动和 Codex Hook 错误显示在设置组与底部按钮组之间的独立错误组; 无错误时不展示该组, 退出和检查更新按钮之间不展示错误文案。
+- 开启 Codex Hook 前必须通过当前 `CodexStatusService` app-server 会话调用 `config/read`, 如果 Codex 全局配置禁用了 Hook, 则不写入 `hooks.json`, 开启失败并在 Hook 选项下方提示。
+- 开启 Codex Hook 写入 `hooks.json` 后必须通过当前 app-server 会话调用 `hooks/list` 验证 `command`、`eventName`、`enabled`、`sourcePath`、`trustStatus`、`warnings` 和 `errors`; 未信任时提示用户去 Codex `/hooks` 信任。
+- Codex Hook 开关下方只在必要时显示 Hook 相关错误; 不展示固定说明文案、启用状态或关闭状态文案。
+- 开机启动错误显示在设置组与底部按钮组之间的独立错误组; 无错误时不展示该组, 退出和检查更新按钮之间不展示错误文案。
日志窗口:
- 通过右键菜单「日志」打开。
- 日志窗口应持续显示全局 `RequestLogStore.shared` 中的记录, 不因窗口关闭丢失。
-- 详情文本必须可选择, 长内容由存储层截断。
+- 详情文本必须可选择; 请求 payload 预览由存储层截断到 4000 字符, 响应和错误详情不按长度截断。
## Sparkle 更新
diff --git a/CLAUDE.md b/CLAUDE.md
index f5d14ae..4d32772 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -29,7 +29,7 @@ xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination generic/pla
## 架构(两条独立数据流)
-应用是 `LSUIElement` 菜单栏程序(无 Dock 图标、无主窗口),入口 `CodexBarApp` 在启动时先分流:若带 `--hook-event` 参数则走 `WorkflowHookEventRecorder` 记录一条 Hook 事件并立即退出,否则正常起 UI。
+应用是 `LSUIElement` 菜单栏程序(无 Dock 图标、无主窗口),入口 `CodexBarApp` 在启动时先分流:若标准输入中有 Codex Hook payload 且顶层 `hook_event_name` 有效,则走 `WorkflowHookEventRecorder` 记录一条 Hook 事件并立即退出,否则正常起 UI。
**1. 状态/额度流**(实时数据)
@@ -42,18 +42,21 @@ CodexStatusService (JSON-RPC over `codex app-server --listen stdio://`)
- app-server 启动命令统一由 `CodexCLIResolver.resolveAppServerCommand()` 解析(优先全局 `codex`,否则回退 Codex.app 内置 CLI),**不要绕过 resolver**。
- 握手与读取顺序、超时/重连、token 刷新、stale 缓存等约束见 `Docs/AppServer.md` 与 `AGENTS.md` 的「app-server 合约」。
-- 错误处理哲学:UI 只暴露 `notLoggedIn` / `initializationFailed` 两类特殊状态;所有具体请求/启动/超时/解析错误进 `RequestLogStore.shared`(容量 500、单条 4000 字符),不直接展示子进程 stderr。
+- 错误处理哲学:UI 只暴露 `notLoggedIn` / `initializationFailed` 两类特殊状态;所有具体请求/启动/超时/解析错误进 `RequestLogStore.shared`(容量 500、请求 payload 预览 4000 字符、响应和错误详情不截断),不直接展示子进程 stderr。
**2. Codex Hook 工作流统计流**(本机统计)
```
-WorkflowHookEventRecorder (--hook-event 子进程)
+WorkflowHookEventRecorder (stdin hook_event_name 子进程)
→ WorkflowStatsStorage (events/YYYY-MM-DD.jsonl / daily.jsonl,~/Library/Application Support/CodexBar/HookEvents/)
→ WorkflowStatsService → WorkflowStatsViewModel
→ UsageSummaryView / UsageHeatmap (统计只在热力图侧边详情面板中展示)
```
-- 设置开关只能追加/移除 CodexBar 自己的 Hook 处理器,绝不破坏用户已有 Hook。
+- Hook 命令只写入当前 CodexBar 可执行文件路径,事件名来自 Codex 传入的 stdin payload 顶层 `hook_event_name`。
+- 开启 Hook 前必须通过当前 app-server 会话调用 `config/read`,如果全局配置禁用了 Hook,则不写入 `hooks.json`,并在 Hook 选项下方提示。
+- 开启 Hook 写入后必须通过当前 app-server 会话调用 `hooks/list` 验证 `command`、`eventName`、`enabled`、`sourcePath`、`trustStatus`、`warnings` 和 `errors`;未信任时提示用户去 Codex `/hooks` 信任。
+- 设置开关只能追加/移除 `command` 包含当前 CodexBar 可执行路径的 Hook 处理器,绝不破坏其他用户 Hook。若用户自定义 Hook 命令也包含当前可执行路径,会被视为当前 CodexBar 处理器。
- Hook 写入可能由多个 Codex 进程并发触发,追加 `events/YYYY-MM-DD.jsonl` 并更新 `maintenance.json` 必须经 `stats.lock` + `flock` 加锁;`daily.jsonl` 由主 App 刷新维护流程写回。
- 字段兼容、保留策略、统计口径见 `Docs/CodexHook.md`。
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxproj
index 5f04c44..9fe8449 100644
--- a/CodexBar.xcodeproj/project.pbxproj
+++ b/CodexBar.xcodeproj/project.pbxproj
@@ -208,6 +208,7 @@
SDKROOT = macosx;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 6.0;
};
name = Debug;
};
@@ -264,6 +265,7 @@
MTL_FAST_MATH = YES;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
+ SWIFT_VERSION = 6.0;
};
name = Release;
};
@@ -275,7 +277,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 23;
+ CURRENT_PROJECT_VERSION = 24;
DEVELOPMENT_TEAM = 4KJ362VJW5;
ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
ENABLE_APP_SANDBOX = NO;
@@ -290,7 +292,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 3.0.0;
+ MARKETING_VERSION = 3.1.0;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
@@ -299,7 +301,7 @@
SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
- SWIFT_VERSION = 5.0;
+ SWIFT_VERSION = 6.0;
};
name = Debug;
};
@@ -312,7 +314,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 23;
+ CURRENT_PROJECT_VERSION = 24;
DEVELOPMENT_TEAM = 4KJ362VJW5;
ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
ENABLE_APP_SANDBOX = NO;
@@ -327,7 +329,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 3.0.0;
+ MARKETING_VERSION = 3.1.0;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
@@ -337,7 +339,7 @@
SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
- SWIFT_VERSION = 5.0;
+ SWIFT_VERSION = 6.0;
};
name = Release;
};
diff --git a/CodexBar/App/CodexBarApp.swift b/CodexBar/App/CodexBarApp.swift
index f4c14de..5ed4ea4 100644
--- a/CodexBar/App/CodexBarApp.swift
+++ b/CodexBar/App/CodexBarApp.swift
@@ -25,7 +25,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/GlobalHotKeyController.swift b/CodexBar/Controllers/GlobalHotKeyController.swift
index b5785eb..50edd78 100644
--- a/CodexBar/Controllers/GlobalHotKeyController.swift
+++ b/CodexBar/Controllers/GlobalHotKeyController.swift
@@ -4,8 +4,8 @@ import Foundation
final class GlobalHotKeyController {
private let onPressed: @MainActor () -> Void
private var eventHandler: EventHandlerUPP?
- private var eventHandlerRef: EventHandlerRef?
- private var hotKeyRef: EventHotKeyRef?
+ private nonisolated(unsafe) var eventHandlerRef: EventHandlerRef?
+ private nonisolated(unsafe) var hotKeyRef: EventHotKeyRef?
private var nextHotKeyID: UInt32 = 1
init(onPressed: @escaping @MainActor () -> Void) {
@@ -13,7 +13,7 @@ final class GlobalHotKeyController {
}
deinit {
- uninstall()
+ Self.removeRegistration(hotKeyRef: hotKeyRef, eventHandlerRef: eventHandlerRef)
}
func install(shortcut: GlobalHotKeyShortcut) -> Bool {
@@ -68,16 +68,9 @@ final class GlobalHotKeyController {
}
private func clearCurrentRegistration() {
- if let hotKeyRef {
- UnregisterEventHotKey(hotKeyRef)
- self.hotKeyRef = nil
- }
-
- if let eventHandlerRef {
- RemoveEventHandler(eventHandlerRef)
- self.eventHandlerRef = nil
- }
-
+ Self.removeRegistration(hotKeyRef: hotKeyRef, eventHandlerRef: eventHandlerRef)
+ hotKeyRef = nil
+ eventHandlerRef = nil
eventHandler = nil
}
@@ -101,6 +94,19 @@ final class GlobalHotKeyController {
}
}
+ private nonisolated static func removeRegistration(
+ hotKeyRef: EventHotKeyRef?,
+ eventHandlerRef: EventHandlerRef?
+ ) {
+ if let hotKeyRef {
+ UnregisterEventHotKey(hotKeyRef)
+ }
+
+ if let eventHandlerRef {
+ RemoveEventHandler(eventHandlerRef)
+ }
+ }
+
private static let hotKeySignature: OSType = {
let scalars = Array("CDBR".unicodeScalars)
return scalars.reduce(UInt32(0)) { result, scalar in
diff --git a/CodexBar/Controllers/HeatmapDetailPanelController.swift b/CodexBar/Controllers/HeatmapDetailPanelController.swift
index b8b1ce1..848f728 100644
--- a/CodexBar/Controllers/HeatmapDetailPanelController.swift
+++ b/CodexBar/Controllers/HeatmapDetailPanelController.swift
@@ -67,29 +67,29 @@ final class HeatmapDetailPanelController {
guard let self,
!Task.isCancelled,
- generation == self.visibilityGeneration,
+ generation == visibilityGeneration,
let panel = self.panel,
panel.isVisible else {
return
}
- self.drawerTransition = .exiting
- let hidden = self.drawerHiddenTranslation(for: side, panelWidth: panel.frame.width)
- self.animateContentTranslation(
+ drawerTransition = .exiting
+ let hidden = drawerHiddenTranslation(for: side, panelWidth: panel.frame.width)
+ animateContentTranslation(
to: hidden,
duration: Metrics.drawerExitDuration,
timing: .easeIn
) {
Task { @MainActor [weak self] in
guard let self,
- generation == self.visibilityGeneration else {
+ generation == visibilityGeneration else {
return
}
- self.orderOut(panel)
- self.setContentTranslation(0)
- self.drawerTransition = .idle
- self.hideTask = nil
+ orderOut(panel)
+ setContentTranslation(0)
+ drawerTransition = .idle
+ hideTask = nil
}
}
}
@@ -197,14 +197,14 @@ final class HeatmapDetailPanelController {
) {
Task { @MainActor [weak self] in
guard let self,
- generation == self.visibilityGeneration,
- self.drawerTransition == .switchingSide,
+ generation == visibilityGeneration,
+ drawerTransition == .switchingSide,
panel.isVisible else {
return
}
- self.showHiddenSideSwitchRequest(
- self.nextSideSwitchRequest(fallback: request),
+ showHiddenSideSwitchRequest(
+ nextSideSwitchRequest(fallback: request),
on: panel,
generation: generation
)
@@ -227,14 +227,14 @@ final class HeatmapDetailPanelController {
) {
Task { @MainActor [weak self] in
guard let self,
- generation == self.visibilityGeneration,
+ generation == visibilityGeneration,
panel.isVisible else {
return
}
- self.drawerTransition = .idle
- self.setContentTranslation(0)
- self.handlePendingSideSwitchRequest(on: panel)
+ drawerTransition = .idle
+ setContentTranslation(0)
+ handlePendingSideSwitchRequest(on: panel)
}
}
}
@@ -423,15 +423,14 @@ final class HeatmapDetailPanelController {
heatmapScreenFrame: CGRect?,
showsWorkflowStats: Bool
) -> CGFloat {
- let proposedY: CGFloat
- if showsWorkflowStats {
- proposedY = menuSurfaceFrame.minY
+ let proposedY: CGFloat = if showsWorkflowStats {
+ menuSurfaceFrame.minY
} else if let heatmapScreenFrame {
- proposedY = heatmapScreenFrame.maxY - panelSize.height
+ heatmapScreenFrame.maxY - panelSize.height
} else if let anchorScreenFrame {
- proposedY = anchorScreenFrame.maxY - panelSize.height
+ anchorScreenFrame.maxY - panelSize.height
} else {
- proposedY = menuSurfaceFrame.midY - panelSize.height / 2
+ menuSurfaceFrame.midY - panelSize.height / 2
}
return clamped(
@@ -515,8 +514,8 @@ final class HeatmapDetailPanelController {
let animation = CABasicAnimation(keyPath: "transform")
animation.fromValue = fromTranslationX.map { CATransform3DMakeTranslation($0, 0, 0) }
- ?? layer.presentation()?.transform
- ?? layer.transform
+ ?? layer.presentation()?.transform
+ ?? layer.transform
animation.toValue = targetTransform
animation.duration = duration
animation.timingFunction = CAMediaTimingFunction(name: timing)
@@ -540,16 +539,16 @@ final class HeatmapDetailPanelController {
guard let self,
let panel,
panel.isVisible,
- generation == self.visibilityGeneration else {
+ generation == visibilityGeneration else {
return
}
- self.setContentTranslation(hiddenTranslationX)
+ setContentTranslation(hiddenTranslationX)
panel.contentView?.layoutSubtreeIfNeeded()
panel.displayIfNeeded()
CATransaction.flush()
panel.alphaValue = 1
- self.animateContentTranslation(
+ animateContentTranslation(
from: hiddenTranslationX,
to: 0,
duration: Metrics.drawerEnterDuration,
@@ -557,12 +556,12 @@ final class HeatmapDetailPanelController {
) {
Task { @MainActor [weak self] in
guard let self,
- generation == self.visibilityGeneration else {
+ generation == visibilityGeneration else {
return
}
- self.drawerTransition = .idle
- self.setContentTranslation(0)
+ drawerTransition = .idle
+ setContentTranslation(0)
}
}
}
diff --git a/CodexBar/Controllers/HostingWindowController.swift b/CodexBar/Controllers/HostingWindowController.swift
index 99f068f..17a3421 100644
--- a/CodexBar/Controllers/HostingWindowController.swift
+++ b/CodexBar/Controllers/HostingWindowController.swift
@@ -13,7 +13,7 @@ final class AuxiliaryHostingWindow: NSWindow {
}
}
-// 承载 SwiftUI 内容的单窗口控制器基类, 统一懒创建、居中与窗口管理逻辑
+/// 承载 SwiftUI 内容的单窗口控制器基类, 统一懒创建、居中与窗口管理逻辑
@MainActor
class HostingWindowController {
let screenProvider: () -> NSScreen?
diff --git a/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift b/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift
index 88cc623..beb2b8a 100644
--- a/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift
+++ b/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift
@@ -34,12 +34,12 @@ final class MenuSurfaceDismissMonitor {
return event
}
- if self.handleKeyEvent(event) {
+ if handleKeyEvent(event) {
return nil
}
- self.dismissIfNeeded(for: event)
- self.restabilizeActiveMenuSurfaceChromeAfterEvent()
+ dismissIfNeeded(for: event)
+ restabilizeActiveMenuSurfaceChromeAfterEvent()
return event
}
@@ -77,11 +77,11 @@ final class MenuSurfaceDismissMonitor {
installActiveMenuSurfaceWindowObserverAndFocus()
deferredWindowFocusTask = Task { @MainActor [weak self] in
await Task.yield()
- guard let self, !Task.isCancelled, self.isPresented() else {
+ guard let self, !Task.isCancelled, isPresented() else {
return
}
- self.installActiveMenuSurfaceWindowObserverAndFocus()
+ installActiveMenuSurfaceWindowObserverAndFocus()
}
}
@@ -216,8 +216,8 @@ final class MenuSurfaceDismissMonitor {
return
}
- self.suppressesActivationDismiss = false
- self.suppressActivationDismissTask = nil
+ suppressesActivationDismiss = false
+ suppressActivationDismissTask = nil
}
}
@@ -244,20 +244,20 @@ final class MenuSurfaceDismissMonitor {
private func isMouseDismissEvent(_ event: NSEvent) -> Bool {
switch event.type {
case .leftMouseDown, .rightMouseDown, .otherMouseDown:
- return true
+ true
default:
- return false
+ false
}
}
private func restabilizeActiveMenuSurfaceChromeAfterEvent() {
Task { @MainActor [weak self] in
await Task.yield()
- guard let self, self.isPresented() else {
+ guard let self, isPresented() else {
return
}
- self.stabilizeActiveMenuSurfaceChromeAppearance()
+ stabilizeActiveMenuSurfaceChromeAppearance()
}
}
diff --git a/CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift b/CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift
index b811548..418353d 100644
--- a/CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift
+++ b/CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift
@@ -39,12 +39,12 @@ final class MenuSurfaceFadeCoordinator {
fadeInCompletionTask = Task { @MainActor [weak self] in
try? await Task.sleep(for: .milliseconds(Int(duration * 1000)))
- guard let self, !Task.isCancelled, self.fadeGeneration == operationGeneration else {
+ guard let self, !Task.isCancelled, fadeGeneration == operationGeneration else {
return
}
- self.resetAlpha()
- self.fadeInCompletionTask = nil
+ resetAlpha()
+ fadeInCompletionTask = nil
completion()
}
}
@@ -60,14 +60,14 @@ final class MenuSurfaceFadeCoordinator {
fadeOutCompletionTask = Task { @MainActor [weak self, weak contentView, weak activeMenuSurfaceWindow] in
try? await Task.sleep(for: .milliseconds(Int(duration * 1000)))
- guard let self, !Task.isCancelled, self.fadeGeneration == operationGeneration else {
+ guard let self, !Task.isCancelled, fadeGeneration == operationGeneration else {
return
}
- self.closeActiveMenuSurface()
+ closeActiveMenuSurface()
contentView?.alphaValue = 1
activeMenuSurfaceWindow?.alphaValue = 1
- self.fadeOutCompletionTask = nil
+ fadeOutCompletionTask = nil
completion()
}
diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swift
index b96f398..e54c0dd 100644
--- a/CodexBar/Controllers/SettingsWindowController.swift
+++ b/CodexBar/Controllers/SettingsWindowController.swift
@@ -22,6 +22,11 @@ final class SettingsWindowController: HostingWindowController {
super.init(screenProvider: screenProvider)
}
+ override func open() {
+ refreshHookStatus()
+ super.open()
+ }
+
override func makeWindow() -> NSWindow {
let hostingController = NSHostingController(
rootView: AppSettingsView(
@@ -60,4 +65,9 @@ final class SettingsWindowController: HostingWindowController {
private enum Metrics {
static let minimumContentSize = NSSize(width: 420, height: 240)
}
+
+ private func refreshHookStatus() {
+ codexHookSettings.refresh()
+ codexHookSettings.verifyInstalledHooks()
+ }
}
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index 0c7f8a2..9284f22 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -4,15 +4,16 @@ import SwiftUI
@MainActor
final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
- let viewModel = CodexStatusViewModel()
+ private let codexStatusService = CodexStatusService()
+ lazy var viewModel = CodexStatusViewModel(service: codexStatusService)
let workflowStatsViewModel = WorkflowStatsViewModel()
- let codexHookSettings = CodexHookSettings()
+ lazy var codexHookSettings = CodexHookSettings(codexStatusService: codexStatusService)
let globalHotKeySettings = GlobalHotKeySettings()
let appUpdater = AppUpdater()
private var statusItemController: StatusItemController?
- func applicationDidFinishLaunching(_ notification: Notification) {
+ func applicationDidFinishLaunching(_: Notification) {
let controller = StatusItemController(
viewModel: viewModel,
workflowStatsViewModel: workflowStatsViewModel,
@@ -24,7 +25,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
statusItemController = controller
}
- func applicationWillTerminate(_ notification: Notification) {
+ func applicationWillTerminate(_: Notification) {
statusItemController?.uninstall()
}
}
@@ -44,8 +45,9 @@ private final class StatusItemController: NSObject {
private lazy var globalHotKeyController = GlobalHotKeyController { [weak self] in
self?.toggleMenuSurfaceFromHotKey()
}
+
private lazy var fallbackPanelController = FallbackPanelController { [unowned self] in
- self.makeMenuHostingController(usesPreferredContentSize: false)
+ makeMenuHostingController(usesPreferredContentSize: false)
}
private lazy var settingsWindowController = SettingsWindowController(
@@ -56,9 +58,11 @@ private final class StatusItemController: NSObject {
) { [weak self] in
self?.statusItem.button?.window?.screen
}
+
private lazy var logWindowController = LogWindowController { [weak self] in
self?.statusItem.button?.window?.screen
}
+
private lazy var menuSurfaceFadeCoordinator = MenuSurfaceFadeCoordinator(
contentViewProvider: { [weak self] in
self?.activeMenuSurfaceContentView
@@ -163,8 +167,8 @@ private final class StatusItemController: NSObject {
self?.updateHeatmapDetailPanel(context)
}
)
- .environmentObject(appUpdater)
- .frame(width: CodexStatusMenuView.menuWidth)
+ .environmentObject(appUpdater)
+ .frame(width: CodexStatusMenuView.menuWidth)
let hostingController = NSHostingController(rootView: AnyView(rootView))
if usesPreferredContentSize {
@@ -185,12 +189,12 @@ private final class StatusItemController: NSObject {
.store(in: &cancellables)
viewModel.$autoRefreshCountdownStartedAt
- .compactMap { $0 }
+ .compactMap(\.self)
.sink { [weak self] _ in
guard let self else {
return
}
- self.refreshWorkflowStatsIfHookEnabled(performMaintenance: true)
+ refreshWorkflowStatsIfHookEnabled(performMaintenance: true)
}
.store(in: &cancellables)
}
@@ -439,7 +443,7 @@ private final class StatusItemController: NSObject {
}
private func closeMenuSurface(animated: Bool = true) {
- if menuSurfaceState == .closing && animated {
+ if menuSurfaceState == .closing, animated {
return
}
@@ -503,8 +507,8 @@ private final class StatusItemController: NSObject {
return
}
- self.setAuxiliaryWindowKeyFocus(true)
- self.auxiliaryWindowFocusRestoreTask = nil
+ setAuxiliaryWindowKeyFocus(true)
+ auxiliaryWindowFocusRestoreTask = nil
}
}
@@ -517,11 +521,11 @@ private final class StatusItemController: NSObject {
delayedStatusRefreshTask?.cancel()
delayedStatusRefreshTask = Task { @MainActor [weak self] in
try? await Task.sleep(for: .milliseconds(160))
- guard let self, !Task.isCancelled, self.isActiveMenuSurfaceVisible else {
+ guard let self, !Task.isCancelled, isActiveMenuSurfaceVisible else {
return
}
- self.viewModel.refreshIfNeeded()
+ viewModel.refreshIfNeeded()
}
}
@@ -550,33 +554,33 @@ private final class StatusItemController: NSObject {
private var isActiveMenuSurfaceVisible: Bool {
switch activeMenuSurface {
case .none:
- return false
+ false
case .popover:
- return popover.isShown
+ popover.isShown
case .fallbackPanel:
- return fallbackPanelController.isVisible
+ fallbackPanelController.isVisible
}
}
private var activeMenuSurfaceContentView: NSView? {
switch activeMenuSurface {
case .none:
- return nil
+ nil
case .popover:
- return popover.contentViewController?.view
+ popover.contentViewController?.view
case .fallbackPanel:
- return fallbackPanelController.contentView
+ fallbackPanelController.contentView
}
}
private var activeMenuSurfaceWindow: NSWindow? {
switch activeMenuSurface {
case .none:
- return nil
+ nil
case .popover:
- return popover.contentViewController?.view.window
+ popover.contentViewController?.view.window
case .fallbackPanel:
- return fallbackPanelController.window
+ fallbackPanelController.window
}
}
@@ -615,8 +619,8 @@ private final class StatusItemController: NSObject {
private extension CGRect {
var hasFiniteGeometry: Bool {
origin.x.isFinite &&
- origin.y.isFinite &&
- size.width.isFinite &&
- size.height.isFinite
+ origin.y.isFinite &&
+ size.width.isFinite &&
+ size.height.isFinite
}
}
diff --git a/CodexBar/Models/CodexHookEvent.swift b/CodexBar/Models/CodexHookEvent.swift
new file mode 100644
index 0000000..28aa038
--- /dev/null
+++ b/CodexBar/Models/CodexHookEvent.swift
@@ -0,0 +1,41 @@
+import Foundation
+
+nonisolated enum CodexHookEvent: String, CaseIterable {
+ case sessionStart = "SessionStart"
+ case userPromptSubmit = "UserPromptSubmit"
+ case preToolUse = "PreToolUse"
+ case postToolUse = "PostToolUse"
+ case permissionRequest = "PermissionRequest"
+ case preCompact = "PreCompact"
+ case postCompact = "PostCompact"
+ case stop = "Stop"
+ case subagentStart = "SubagentStart"
+ case subagentStop = "SubagentStop"
+
+ init?(eventName: String) {
+ let normalizedName = Self.normalizedName(eventName)
+ guard let event = Self.allCases.first(where: { $0.normalizedName == normalizedName }) else {
+ return nil
+ }
+ self = event
+ }
+
+ var configName: String {
+ rawValue
+ }
+
+ var appServerName: String {
+ rawValue.prefix(1).lowercased() + rawValue.dropFirst()
+ }
+
+ private var normalizedName: String {
+ Self.normalizedName(rawValue)
+ }
+
+ private static func normalizedName(_ eventName: String) -> String {
+ eventName
+ .replacingOccurrences(of: "_", with: "")
+ .replacingOccurrences(of: "-", with: "")
+ .lowercased()
+ }
+}
diff --git a/CodexBar/Models/CodexQuotaModels.swift b/CodexBar/Models/CodexQuotaModels.swift
index 15cd796..6a4f79f 100644
--- a/CodexBar/Models/CodexQuotaModels.swift
+++ b/CodexBar/Models/CodexQuotaModels.swift
@@ -35,7 +35,9 @@ nonisolated struct CodexQuotaLimitSnapshot: Equatable, Identifiable {
let limitName: String?
let windows: [QuotaWindow]
- var id: String { limitId }
+ var id: String {
+ limitId
+ }
var title: String {
if let limitName, !limitName.isEmpty {
@@ -46,7 +48,7 @@ nonisolated struct CodexQuotaLimitSnapshot: Equatable, Identifiable {
}
}
-nonisolated private extension String {
+private nonisolated extension String {
func capitalizingFirstLetter() -> String {
guard let first else {
return self
@@ -83,8 +85,8 @@ nonisolated struct QuotaWindow: Equatable, Identifiable {
return "额度"
}
- if minutes.isMultiple(of: 1_440) {
- return "\(minutes / 1_440)D"
+ if minutes.isMultiple(of: 1440) {
+ return "\(minutes / 1440)D"
}
if minutes.isMultiple(of: 60) {
diff --git a/CodexBar/Models/CodexStatusError.swift b/CodexBar/Models/CodexStatusError.swift
index 5148b9b..12691f9 100644
--- a/CodexBar/Models/CodexStatusError.swift
+++ b/CodexBar/Models/CodexStatusError.swift
@@ -12,24 +12,34 @@ nonisolated enum CodexStatusError: LocalizedError {
var errorDescription: String? {
switch self {
case .executableNotFound:
- return "找不到 Codex CLI 或 Codex APP"
- default:
- return nil
+ "找不到 Codex CLI 或 Codex APP"
+ case .serverTimeout:
+ "等待 Codex app-server 响应超时"
+ case .serverConnectionClosed:
+ "Codex app-server 连接已断开"
+ case .invalidServerResponse:
+ "Codex app-server 返回无法解析"
+ case let .serverError(message):
+ message
+ case .unsupportedMethod:
+ "Codex app-server 不支持该接口"
+ case .notLoggedIn:
+ "Codex 未登录"
}
}
- // codex app-server 未登录
+ /// codex app-server 未登录
var isAuthenticationRequired: Bool {
serverErrorMessageContains("codex account authentication required")
}
- // codex app-server 不支持的方法
+ /// codex app-server 不支持的方法
var isUnsupportedMethod: Bool {
switch self {
case .unsupportedMethod:
- return true
+ true
default:
- return serverErrorMessageContains("Invalid request: unknown variant")
+ serverErrorMessageContains("Invalid request: unknown variant")
}
}
@@ -41,18 +51,18 @@ nonisolated enum CodexStatusError: LocalizedError {
return !isAuthenticationRequired && !isUnsupportedMethod
}
- // 连接断开、超时、无法解析都需要重建 app-server 会话
+ /// 连接断开、超时、无法解析都需要重建 app-server 会话
var isTransportFailure: Bool {
switch self {
case .serverConnectionClosed, .serverTimeout, .invalidServerResponse:
- return true
+ true
default:
- return false
+ false
}
}
private func serverErrorMessageContains(_ keyword: String) -> Bool {
- guard case .serverError(let message) = self else {
+ guard case let .serverError(message) = self else {
return false
}
diff --git a/CodexBar/Models/CodexUsageModels.swift b/CodexBar/Models/CodexUsageModels.swift
index 44e9efe..7d8acc8 100644
--- a/CodexBar/Models/CodexUsageModels.swift
+++ b/CodexBar/Models/CodexUsageModels.swift
@@ -17,7 +17,9 @@ nonisolated struct DailyUsageBucket: Decodable, Equatable, Identifiable {
let startDate: String
let tokens: Int
- var id: String { startDate }
+ var id: String {
+ startDate
+ }
}
nonisolated struct CodexUsageSnapshot: Equatable {
@@ -29,7 +31,7 @@ nonisolated struct CodexUsageSnapshot: Equatable {
return tokensByDate[startDate]
}
- // 给热力图生成按周排列的最近日期网格, 每列从周日开始
+ /// 给热力图生成按周排列的最近日期网格, 每列从周日开始
func recentWeekGrid(columnCount: Int, endingDaysAgo: Int = 0, today: Date = Date()) -> [DailyUsageBucket?] {
let tokenCountsByDate = tokensByDate
return CodexWeekGrid.dates(
diff --git a/CodexBar/Models/CodexWeekGrid.swift b/CodexBar/Models/CodexWeekGrid.swift
index 9cdf174..e83c0f9 100644
--- a/CodexBar/Models/CodexWeekGrid.swift
+++ b/CodexBar/Models/CodexWeekGrid.swift
@@ -28,12 +28,12 @@ nonisolated enum CodexWeekGrid {
return []
}
- return (0..<columnCount).flatMap { column -> [Date?] in
+ return (0 ..< columnCount).flatMap { column -> [Date?] in
guard let weekStart = calendar.date(byAdding: .weekOfYear, value: column, to: firstWeekStart) else {
return Array(repeating: nil, count: rowCount)
}
- return (0..<rowCount).map { weekdayOffset -> Date? in
+ return (0 ..< rowCount).map { weekdayOffset -> Date? in
guard let date = calendar.date(byAdding: .day, value: weekdayOffset, to: weekStart),
date <= lastVisibleDate else {
return nil
diff --git a/CodexBar/Models/CodexWorkflowStatsModels.swift b/CodexBar/Models/CodexWorkflowStatsModels.swift
index 014fff9..ce7fd87 100644
--- a/CodexBar/Models/CodexWorkflowStatsModels.swift
+++ b/CodexBar/Models/CodexWorkflowStatsModels.swift
@@ -1,33 +1,16 @@
import Foundation
-// Hook 事件类型: 由归一化后的事件名 (去除 _/-、小写) 映射, 是名称到聚合计数的唯一映射来源
-nonisolated enum WorkflowEventKind: String {
- case sessionStart = "sessionstart"
- case stop = "stop"
- case preToolUse = "pretooluse"
- case postToolUse = "posttooluse"
- case permissionRequest = "permissionrequest"
- case preCompact = "precompact"
- case postCompact = "postcompact"
- case subagentStart = "subagentstart"
- case subagentStop = "subagentstop"
-
- init?(normalizedName: String) {
- self.init(rawValue: normalizedName)
- }
-}
-
private nonisolated enum WorkflowStatsJSON {
static func lineData(_ fields: [String]) -> Data {
let json = "{\(fields.joined(separator: ","))}"
return Data(json.utf8) + Data([0x0A])
}
- static func field<T: Encodable>(_ name: String, _ value: T?) throws -> String {
- "\"\(name)\":\(try Self.value(value))"
+ static func field(_ name: String, _ value: (some Encodable)?) throws -> String {
+ try "\"\(name)\":\(Self.value(value))"
}
- static func value<T: Encodable>(_ value: T?) throws -> String {
+ static func value(_ value: (some Encodable)?) throws -> String {
guard let value else {
return "null"
}
@@ -35,7 +18,7 @@ private nonisolated enum WorkflowStatsJSON {
return try Self.value(value)
}
- static func value<T: Encodable>(_ value: T) throws -> String {
+ static func value(_ value: some Encodable) throws -> String {
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
let data = try encoder.encode(value)
@@ -95,16 +78,16 @@ nonisolated struct WorkflowHookEvent: Decodable, Equatable {
self.timestamp = timestamp
self.name = name
- self.directoryPath = Self.string(from: container, key: .cwd)
- self.toolName = Self.string(from: container, key: .toolName)
- self.modelName = Self.string(from: container, key: .modelName)
- self.permissionMode = Self.string(from: container, key: .permissionMode)
- self.sessionId = Self.string(from: container, key: .sessionId)
- self.turnId = Self.string(from: container, key: .turnId)
+ directoryPath = Self.string(from: container, key: .cwd)
+ toolName = Self.string(from: container, key: .toolName)
+ modelName = Self.string(from: container, key: .modelName)
+ permissionMode = Self.string(from: container, key: .permissionMode)
+ sessionId = Self.string(from: container, key: .sessionId)
+ turnId = Self.string(from: container, key: .turnId)
}
- var kind: WorkflowEventKind? {
- WorkflowEventKind(normalizedName: normalizedName)
+ var hookEvent: CodexHookEvent? {
+ CodexHookEvent(eventName: name)
}
var projectDisplayName: String? {
@@ -117,13 +100,6 @@ nonisolated struct WorkflowHookEvent: Decodable, Equatable {
return lastComponent.isEmpty ? directoryPath : lastComponent
}
- private var normalizedName: String {
- name
- .replacingOccurrences(of: "_", with: "")
- .replacingOccurrences(of: "-", with: "")
- .lowercased()
- }
-
private static func string(
from container: KeyedDecodingContainer<CodingKeys>,
key: CodingKeys
@@ -143,15 +119,15 @@ nonisolated struct WorkflowHookEvent: Decodable, Equatable {
}
func jsonLineData() throws -> Data {
- let fields = [
- try WorkflowStatsJSON.field("timestamp", DateFormatter.codexLocalTimestamp.string(from: timestamp)),
- try WorkflowStatsJSON.field("event", name),
- try WorkflowStatsJSON.field("model", modelName),
- try WorkflowStatsJSON.field("permission", permissionMode),
- try WorkflowStatsJSON.field("session", sessionId),
- try WorkflowStatsJSON.field("turn", turnId),
- try WorkflowStatsJSON.field("tool", toolName),
- try WorkflowStatsJSON.field("cwd", directoryPath)
+ let fields = try [
+ WorkflowStatsJSON.field("timestamp", DateFormatter.codexLocalTimestamp.string(from: timestamp)),
+ WorkflowStatsJSON.field("event", name),
+ WorkflowStatsJSON.field("model", modelName),
+ WorkflowStatsJSON.field("permission", permissionMode),
+ WorkflowStatsJSON.field("session", sessionId),
+ WorkflowStatsJSON.field("turn", turnId),
+ WorkflowStatsJSON.field("tool", toolName),
+ WorkflowStatsJSON.field("cwd", directoryPath)
]
return WorkflowStatsJSON.lineData(fields)
@@ -175,12 +151,12 @@ nonisolated struct WorkflowDailyStats: Equatable, Identifiable {
let turnCount: Int
let toolCallCount: Int
let permissionRequestCount: Int
- let mostActiveProject: String?
let contextCompactionCount: Int
let subagentCount: Int
- let eventCount: Int
- var id: String { startDate }
+ var id: String {
+ startDate
+ }
static func empty(startDate: String) -> WorkflowDailyStats {
WorkflowDailyStats(
@@ -189,10 +165,8 @@ nonisolated struct WorkflowDailyStats: Equatable, Identifiable {
turnCount: 0,
toolCallCount: 0,
permissionRequestCount: 0,
- mostActiveProject: nil,
contextCompactionCount: 0,
- subagentCount: 0,
- eventCount: 0
+ subagentCount: 0
)
}
}
@@ -210,7 +184,7 @@ nonisolated struct WorkflowStatsSnapshot: Equatable {
init(dailyAggregates: [WorkflowDailyAggregate], generatedAt: Date = Date()) {
self.generatedAt = generatedAt
- self.dailyStats = dailyAggregates
+ dailyStats = dailyAggregates
.map(\.stats)
.sorted { $0.startDate < $1.startDate }
}
@@ -239,8 +213,8 @@ nonisolated struct WorkflowDailyIdentifierCache {
var turnIds: Set<String>
init(aggregate: WorkflowDailyAggregate) {
- self.sessionIds = Set(aggregate.sessionIds ?? [])
- self.turnIds = Set(aggregate.turnIds ?? [])
+ sessionIds = Set(aggregate.sessionIds ?? [])
+ turnIds = Set(aggregate.turnIds ?? [])
}
}
@@ -262,45 +236,47 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
var sessionIds: [String]?
var turnIds: [String]?
- var id: String { date }
+ var id: String {
+ date
+ }
init(date: String) {
self.date = date
- self.eventCount = 0
- self.sessionStartCount = 0
- self.stopCount = 0
- self.preToolUseCount = 0
- self.postToolUseCount = 0
- self.permissionRequestCount = 0
- self.preCompactCount = 0
- self.postCompactCount = 0
- self.subagentStartCount = 0
- self.subagentStopCount = 0
- self.sessionCount = nil
- self.turnCount = nil
- self.projectCounts = [:]
- self.sessionIds = []
- self.turnIds = []
+ eventCount = 0
+ sessionStartCount = 0
+ stopCount = 0
+ preToolUseCount = 0
+ postToolUseCount = 0
+ permissionRequestCount = 0
+ preCompactCount = 0
+ postCompactCount = 0
+ subagentStartCount = 0
+ subagentStopCount = 0
+ sessionCount = nil
+ turnCount = nil
+ projectCounts = [:]
+ sessionIds = []
+ turnIds = []
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
- self.date = try container.decode(String.self, forKey: .date)
- self.eventCount = try container.decodeIfPresent(Int.self, forKey: .eventCount) ?? 0
- self.sessionStartCount = try container.decodeIfPresent(Int.self, forKey: .sessionStartCount) ?? 0
- self.stopCount = try container.decodeIfPresent(Int.self, forKey: .stopCount) ?? 0
- self.preToolUseCount = try container.decodeIfPresent(Int.self, forKey: .preToolUseCount) ?? 0
- self.postToolUseCount = try container.decodeIfPresent(Int.self, forKey: .postToolUseCount) ?? 0
- self.permissionRequestCount = try container.decodeIfPresent(Int.self, forKey: .permissionRequestCount) ?? 0
- self.preCompactCount = try container.decodeIfPresent(Int.self, forKey: .preCompactCount) ?? 0
- self.postCompactCount = try container.decodeIfPresent(Int.self, forKey: .postCompactCount) ?? 0
- self.subagentStartCount = try container.decodeIfPresent(Int.self, forKey: .subagentStartCount) ?? 0
- self.subagentStopCount = try container.decodeIfPresent(Int.self, forKey: .subagentStopCount) ?? 0
- self.sessionCount = try container.decodeIfPresent(Int.self, forKey: .sessionCount)
- self.turnCount = try container.decodeIfPresent(Int.self, forKey: .turnCount)
- self.projectCounts = try container.decodeIfPresent([String: Int].self, forKey: .projectCounts) ?? [:]
- self.sessionIds = try container.decodeIfPresent([String].self, forKey: .sessionIds)
- self.turnIds = try container.decodeIfPresent([String].self, forKey: .turnIds)
+ date = try container.decode(String.self, forKey: .date)
+ eventCount = try container.decodeIfPresent(Int.self, forKey: .eventCount) ?? 0
+ sessionStartCount = try container.decodeIfPresent(Int.self, forKey: .sessionStartCount) ?? 0
+ stopCount = try container.decodeIfPresent(Int.self, forKey: .stopCount) ?? 0
+ preToolUseCount = try container.decodeIfPresent(Int.self, forKey: .preToolUseCount) ?? 0
+ postToolUseCount = try container.decodeIfPresent(Int.self, forKey: .postToolUseCount) ?? 0
+ permissionRequestCount = try container.decodeIfPresent(Int.self, forKey: .permissionRequestCount) ?? 0
+ preCompactCount = try container.decodeIfPresent(Int.self, forKey: .preCompactCount) ?? 0
+ postCompactCount = try container.decodeIfPresent(Int.self, forKey: .postCompactCount) ?? 0
+ subagentStartCount = try container.decodeIfPresent(Int.self, forKey: .subagentStartCount) ?? 0
+ subagentStopCount = try container.decodeIfPresent(Int.self, forKey: .subagentStopCount) ?? 0
+ sessionCount = try container.decodeIfPresent(Int.self, forKey: .sessionCount)
+ turnCount = try container.decodeIfPresent(Int.self, forKey: .turnCount)
+ projectCounts = try container.decodeIfPresent([String: Int].self, forKey: .projectCounts) ?? [:]
+ sessionIds = try container.decodeIfPresent([String].self, forKey: .sessionIds)
+ turnIds = try container.decodeIfPresent([String].self, forKey: .turnIds)
}
mutating func record(
@@ -310,7 +286,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
) {
eventCount += 1
- switch event.kind {
+ switch event.hookEvent {
case .sessionStart: sessionStartCount += 1
case .stop: stopCount += 1
case .preToolUse: preToolUseCount += 1
@@ -320,6 +296,8 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
case .postCompact: postCompactCount += 1
case .subagentStart: subagentStartCount += 1
case .subagentStop: subagentStopCount += 1
+ case .userPromptSubmit:
+ break
case .none: break
}
@@ -373,10 +351,8 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
turnCount: turnTotal,
toolCallCount: toolCallCount,
permissionRequestCount: permissionRequestCount,
- mostActiveProject: mostActiveProject,
contextCompactionCount: contextCompactionCount,
- subagentCount: subagentCount,
- eventCount: eventCount
+ subagentCount: subagentCount
)
}
@@ -406,28 +382,28 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
static func encodeJSONLines(_ aggregates: [WorkflowDailyAggregate]) throws -> Data {
try aggregates.reduce(into: Data()) { result, aggregate in
- result.append(try aggregate.jsonLineData())
+ try result.append(aggregate.jsonLineData())
}
}
func jsonLineData() throws -> Data {
- let fields = [
- try WorkflowStatsJSON.field("date", date),
- try WorkflowStatsJSON.field("eventCount", eventCount),
- try WorkflowStatsJSON.field("sessionStartCount", sessionStartCount),
- try WorkflowStatsJSON.field("stopCount", stopCount),
- try WorkflowStatsJSON.field("preToolUseCount", preToolUseCount),
- try WorkflowStatsJSON.field("postToolUseCount", postToolUseCount),
- try WorkflowStatsJSON.field("permissionRequestCount", permissionRequestCount),
- try WorkflowStatsJSON.field("preCompactCount", preCompactCount),
- try WorkflowStatsJSON.field("postCompactCount", postCompactCount),
- try WorkflowStatsJSON.field("subagentStartCount", subagentStartCount),
- try WorkflowStatsJSON.field("subagentStopCount", subagentStopCount),
- try WorkflowStatsJSON.field("sessionCount", sessionCount),
- try WorkflowStatsJSON.field("turnCount", turnCount),
- try WorkflowStatsJSON.field("projectCounts", projectCounts),
- try WorkflowStatsJSON.field("sessionIds", sessionIds),
- try WorkflowStatsJSON.field("turnIds", turnIds)
+ let fields = try [
+ WorkflowStatsJSON.field("date", date),
+ WorkflowStatsJSON.field("eventCount", eventCount),
+ WorkflowStatsJSON.field("sessionStartCount", sessionStartCount),
+ WorkflowStatsJSON.field("stopCount", stopCount),
+ WorkflowStatsJSON.field("preToolUseCount", preToolUseCount),
+ WorkflowStatsJSON.field("postToolUseCount", postToolUseCount),
+ WorkflowStatsJSON.field("permissionRequestCount", permissionRequestCount),
+ WorkflowStatsJSON.field("preCompactCount", preCompactCount),
+ WorkflowStatsJSON.field("postCompactCount", postCompactCount),
+ WorkflowStatsJSON.field("subagentStartCount", subagentStartCount),
+ WorkflowStatsJSON.field("subagentStopCount", subagentStopCount),
+ WorkflowStatsJSON.field("sessionCount", sessionCount),
+ WorkflowStatsJSON.field("turnCount", turnCount),
+ WorkflowStatsJSON.field("projectCounts", projectCounts),
+ WorkflowStatsJSON.field("sessionIds", sessionIds),
+ WorkflowStatsJSON.field("turnIds", turnIds)
]
return WorkflowStatsJSON.lineData(fields)
@@ -452,19 +428,6 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
Set(identifiers ?? []).sorted()
}
- private var mostActiveProject: String? {
- projectCounts
- .sorted { lhs, rhs in
- if lhs.value != rhs.value {
- return lhs.value > rhs.value
- }
-
- return lhs.key.localizedStandardCompare(rhs.key) == .orderedAscending
- }
- .first?
- .key
- }
-
private static func date(from string: String) -> Date? {
DateFormatter.codexDay.date(from: string)
}
diff --git a/CodexBar/Models/DateFormatter.swift b/CodexBar/Models/DateFormatter.swift
index 049cd15..93a6afd 100644
--- a/CodexBar/Models/DateFormatter.swift
+++ b/CodexBar/Models/DateFormatter.swift
@@ -1,30 +1,40 @@
import Foundation
extension DateFormatter {
- // yyyy-MM-dd, 作为热力图与按日聚合统一的稳定日期键
- nonisolated static let codexDay: DateFormatter = {
+ /// yyyy-MM-dd, 作为热力图与按日聚合统一的稳定日期键
+ /// DateFormatter 不是线程安全类型, 这里每次返回新实例以避免跨线程共享
+ nonisolated static var codexDay: DateFormatter {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = .autoupdatingCurrent
formatter.dateFormat = "yyyy-MM-dd"
return formatter
- }()
+ }
- // yyyy-MM-dd HH:mm:ss.SSS, Hook 原始事件写入本机时间字符串
- nonisolated static let codexLocalTimestamp: DateFormatter = {
+ /// yyyy-MM-dd HH:mm:ss.SSS, Hook 原始事件写入本机时间字符串
+ /// DateFormatter 不是线程安全类型, 这里每次返回新实例以避免跨线程共享
+ nonisolated static var codexLocalTimestamp: DateFormatter {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = .autoupdatingCurrent
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
return formatter
- }()
+ }
}
extension ISO8601DateFormatter {
- // 带小数秒的 ISO8601, 用于读取 Hook payload 中的原始时间戳
- nonisolated static let codexFractional: ISO8601DateFormatter = {
+ /// 带小数秒的 ISO8601, 用于读取 Hook payload 中的原始时间戳
+ /// ISO8601DateFormatter 不是 Sendable, 这里每次返回新实例以避免跨线程共享
+ nonisolated static var codexFractional: ISO8601DateFormatter {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return formatter
- }()
+ }
+
+ /// 不带小数秒的 ISO8601 兜底解析器
+ nonisolated static var codexInternetDateTime: ISO8601DateFormatter {
+ let formatter = ISO8601DateFormatter()
+ formatter.formatOptions = [.withInternetDateTime]
+ return formatter
+ }
}
diff --git a/CodexBar/Models/GlobalHotKeyShortcut.swift b/CodexBar/Models/GlobalHotKeyShortcut.swift
index b3c3da8..ca40dfc 100644
--- a/CodexBar/Models/GlobalHotKeyShortcut.swift
+++ b/CodexBar/Models/GlobalHotKeyShortcut.swift
@@ -1,7 +1,7 @@
import AppKit
import Carbon.HIToolbox
-nonisolated struct GlobalHotKeyShortcut: Codable, Equatable, Sendable {
+nonisolated struct GlobalHotKeyShortcut: Codable, Equatable {
let keyCode: UInt32
let modifiers: UInt32
let keyLabel: String
@@ -55,8 +55,8 @@ nonisolated struct GlobalHotKeyShortcut: Codable, Equatable, Sendable {
hasModifier(shiftKey) ? "⇧" : nil,
hasModifier(cmdKey) ? "⌘" : nil
]
- .compactMap { $0 }
- .joined()
+ .compactMap(\.self)
+ .joined()
}
private var modifierCount: Int {
diff --git a/CodexBar/Models/UsageHeatmapDay.swift b/CodexBar/Models/UsageHeatmapDay.swift
index a02fadd..210832a 100644
--- a/CodexBar/Models/UsageHeatmapDay.swift
+++ b/CodexBar/Models/UsageHeatmapDay.swift
@@ -5,7 +5,9 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {
let tokenCount: Int?
let workflowStats: WorkflowDailyStats
- var id: String { startDate }
+ var id: String {
+ startDate
+ }
var tokensForHeatmap: Int {
tokenCount ?? 0
diff --git a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
index 21d7f7b..f63533b 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
@@ -1,25 +1,25 @@
import Darwin
import Foundation
-nonisolated enum CodexCLIExecutableSource: String, Sendable, Equatable {
+nonisolated enum CodexCLIExecutableSource: String, Equatable {
case global
case bundled
var displayName: String {
switch self {
- case .global: return "Codex CLI"
- case .bundled: return "Codex APP"
+ case .global: "Codex CLI"
+ case .bundled: "Codex APP"
}
}
}
-nonisolated struct AppServerCommand: Sendable, Equatable {
+nonisolated struct AppServerCommand: Equatable {
let source: CodexCLIExecutableSource
let executablePath: String
let arguments = ["app-server", "--listen", "stdio://"]
}
-nonisolated struct CodexCLIConnectionInfo: Sendable, Equatable {
+nonisolated struct CodexCLIConnectionInfo: Equatable {
let source: CodexCLIExecutableSource
let executablePath: String
// 来自 initialize 握手, 代表当前 app-server 进程真实运行的版本
@@ -27,7 +27,7 @@ nonisolated struct CodexCLIConnectionInfo: Sendable, Equatable {
let openedAt: Date
}
-nonisolated struct CodexCLIInstallations: Sendable, Equatable {
+nonisolated struct CodexCLIInstallations: Equatable {
let globalPath: String?
let bundledPath: String?
@@ -40,8 +40,8 @@ nonisolated struct CodexCLIInstallations: Sendable, Equatable {
func path(for source: CodexCLIExecutableSource) -> String? {
switch source {
- case .global: return globalPath
- case .bundled: return bundledPath
+ case .global: globalPath
+ case .bundled: bundledPath
}
}
}
@@ -54,7 +54,7 @@ nonisolated enum CodexCLIResolver {
try command(from: resolveInstallations(environment: environment))
}
- // 从已解析的安装信息派生命令, 避免重复扫描 PATH
+ /// 从已解析的安装信息派生命令, 避免重复扫描 PATH
static func command(from installations: CodexCLIInstallations) throws -> AppServerCommand {
guard let source = installations.activeSource,
let path = installations.path(for: source) else {
@@ -68,11 +68,10 @@ nonisolated enum CodexCLIResolver {
let cliPath = findExecutable(named: "codex", environment: environment)
let cliIsBundled = cliPath.map { pathsAreEquivalent($0, bundledExecutablePath) } ?? false
- let bundledPath: String?
- if FileManager.default.isExecutableFile(atPath: bundledExecutablePath) {
- bundledPath = bundledExecutablePath
+ let bundledPath: String? = if FileManager.default.isExecutableFile(atPath: bundledExecutablePath) {
+ bundledExecutablePath
} else {
- bundledPath = cliIsBundled ? cliPath : nil
+ cliIsBundled ? cliPath : nil
}
return CodexCLIInstallations(
diff --git a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
index 60803ad..6d20e15 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
@@ -1,12 +1,12 @@
import Combine
import Foundation
-nonisolated struct CodexCLIVersionSnapshot: Equatable, Sendable {
+nonisolated struct CodexCLIVersionSnapshot: Equatable {
let global: CodexCLIVersionItem
let bundled: CodexCLIVersionItem
let refreshedAt: Date
- // 让首次 refresh 不受节流限制
+ /// 让首次 refresh 不受节流限制
static let empty = CodexCLIVersionSnapshot(
global: CodexCLIVersionItem(source: .global),
bundled: CodexCLIVersionItem(source: .bundled),
@@ -14,13 +14,15 @@ nonisolated struct CodexCLIVersionSnapshot: Equatable, Sendable {
)
}
-nonisolated struct CodexCLIVersionItem: Equatable, Identifiable, Sendable {
+nonisolated struct CodexCLIVersionItem: Equatable, Identifiable {
let source: CodexCLIExecutableSource
let path: String?
let version: String?
let errorMessage: String?
- var id: CodexCLIExecutableSource { source }
+ var id: CodexCLIExecutableSource {
+ source
+ }
init(
source: CodexCLIExecutableSource,
@@ -43,14 +45,14 @@ nonisolated struct CodexCLIVersionItem: Equatable, Identifiable, Sendable {
}
}
-// 合并磁盘探测版本和当前 app-server 握手版本
+/// 合并磁盘探测版本和当前 app-server 握手版本
nonisolated struct CodexCLIVersionDisplay: Equatable {
let source: CodexCLIExecutableSource
let isCurrent: Bool
let displayVersion: String
let hasVersion: Bool
let path: String?
- // 当前会话尚未重连到新安装版本时显示的新版本号
+ /// 当前会话尚未重连到新安装版本时显示的新版本号
let newerInstalledVersion: String?
init(item: CodexCLIVersionItem, connection: CodexCLIConnectionInfo?) {
@@ -59,18 +61,18 @@ nonisolated struct CodexCLIVersionDisplay: Equatable {
let runningVersion = isCurrent ? connection?.version : nil
let version = runningVersion ?? item.version
- self.source = item.source
+ source = item.source
self.isCurrent = isCurrent
- self.hasVersion = version != nil
- self.displayVersion = version ?? item.displayVersion
- self.path = (isCurrent ? connection?.executablePath : nil) ?? item.path
+ hasVersion = version != nil
+ displayVersion = version ?? item.displayVersion
+ path = (isCurrent ? connection?.executablePath : nil) ?? item.path
if let runningVersion,
let installed = item.version,
Self.isInstalledVersionNewer(installed, than: runningVersion) {
- self.newerInstalledVersion = installed
+ newerInstalledVersion = installed
} else {
- self.newerInstalledVersion = nil
+ newerInstalledVersion = nil
}
}
@@ -98,7 +100,7 @@ nonisolated struct CodexCLIVersionDisplay: Equatable {
}
}
-nonisolated final class CodexCLIVersionService: @unchecked Sendable {
+final nonisolated class CodexCLIVersionService: @unchecked Sendable {
private let queue = DispatchQueue(label: "CodexBar.codex-version", qos: .utility)
private let timeout: TimeInterval
private static let pipeDrainTimeout: TimeInterval = 0.25
@@ -206,9 +208,9 @@ nonisolated final class CodexCLIVersionService: @unchecked Sendable {
private static func finishProbe(_ outcome: ProbeOutcome) -> CodexCLIVersionItem {
switch outcome {
- case .resolved(let item):
+ case let .resolved(item):
return item
- case .running(let probe):
+ case let .running(probe):
guard probe.finished.wait(timeout: .now() + max(0, probe.deadline.timeIntervalSinceNow)) == .success else {
terminateTimedOutProbe(probe)
return CodexCLIVersionItem(source: probe.source, path: probe.path, errorMessage: "读取超时")
@@ -259,10 +261,9 @@ nonisolated final class CodexCLIVersionService: @unchecked Sendable {
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.first { !$0.isEmpty }
}
-
}
-private nonisolated final class PipeCollector: @unchecked Sendable {
+private final nonisolated class PipeCollector: @unchecked Sendable {
private let lock = NSLock()
private let closedSemaphore = DispatchSemaphore(value: 0)
private let fileHandle: FileHandle
@@ -343,7 +344,7 @@ 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 9097593..4166710 100644
--- a/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift
+++ b/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift
@@ -1,6 +1,6 @@
import Foundation
-nonisolated final class JSONLineReader: @unchecked Sendable {
+final nonisolated class JSONLineReader: @unchecked Sendable {
private let lock = NSLock()
private let semaphore = DispatchSemaphore(value: 0)
private let fileHandle: FileHandle
@@ -62,7 +62,7 @@ nonisolated final class JSONLineReader: @unchecked Sendable {
if let line = String(bytes: lineData, encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines),
- !line.isEmpty {
+ !line.isEmpty {
lines.append(line)
semaphore.signal()
}
@@ -79,7 +79,7 @@ nonisolated final class JSONLineReader: @unchecked Sendable {
if !buffer.isEmpty {
if let line = String(bytes: buffer, encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines),
- !line.isEmpty {
+ !line.isEmpty {
lines.append(line)
}
buffer.removeAll()
@@ -100,7 +100,7 @@ nonisolated final class JSONLineReader: @unchecked Sendable {
}
}
-nonisolated final class PipeDrain: @unchecked Sendable {
+final nonisolated class PipeDrain: @unchecked Sendable {
private let fileHandle: FileHandle
init(fileHandle: FileHandle) {
diff --git a/CodexBar/Services/CodexStatus/AppServerSession.swift b/CodexBar/Services/CodexStatus/AppServerSession.swift
index 4b790c7..5ea77d5 100644
--- a/CodexBar/Services/CodexStatus/AppServerSession.swift
+++ b/CodexBar/Services/CodexStatus/AppServerSession.swift
@@ -1,6 +1,6 @@
import Foundation
-nonisolated final class AppServerSession {
+final nonisolated class AppServerSession {
let process: Process
private typealias EncodedMessage = (data: Data, text: String)
@@ -203,7 +203,7 @@ nonisolated final class AppServerSession {
private func decodeResponse<Response: Decodable>(
_ line: ResponseLine,
- as type: Response.Type,
+ as _: Response.Type,
token: UUID,
decoder: JSONDecoder
) throws -> Response {
diff --git a/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift b/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift
new file mode 100644
index 0000000..5360945
--- /dev/null
+++ b/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift
@@ -0,0 +1,51 @@
+import Foundation
+
+nonisolated struct CodexConfigReadResponse: Decodable {
+ let config: CodexAppServerConfig
+
+ var hooksGloballyDisabled: Bool {
+ guard let features = config.features else {
+ return false
+ }
+
+ return (features.hooks ?? features.codexHooks) == false
+ }
+}
+
+nonisolated struct CodexAppServerConfig: Decodable {
+ let features: CodexAppServerFeatures?
+}
+
+nonisolated struct CodexAppServerFeatures: Decodable {
+ let hooks: Bool?
+ let codexHooks: Bool?
+
+ private enum CodingKeys: String, CodingKey {
+ case hooks
+ case codexHooks = "codex_hooks"
+ }
+}
+
+nonisolated struct CodexHooksListResponse: Decodable {
+ let data: [CodexHooksListEntry]
+}
+
+nonisolated struct CodexHooksListEntry: Decodable {
+ let cwd: String
+ let hooks: [CodexHookMetadata]
+ let warnings: [String]
+ let errors: [CodexHookErrorInfo]
+}
+
+nonisolated struct CodexHookMetadata: Decodable {
+ let eventName: String
+ let command: String?
+ let enabled: Bool
+ let sourcePath: String
+ let trustStatus: String
+}
+
+nonisolated struct CodexHookErrorInfo: Decodable {
+ let path: String
+ let message: String
+}
diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swift
index 1566844..8b31bc8 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
@@ -31,12 +31,12 @@ private enum FetchFailure: Error {
case needsRebuild
}
-nonisolated private struct CachedSupplementalRead<Value> {
+private nonisolated struct CachedSupplementalRead<Value> {
let value: Value?
let isStale: Bool
}
-nonisolated private struct SupplementalDataCache {
+private nonisolated struct SupplementalDataCache {
var account: CodexAccount?
var rateLimits: AccountRateLimitsResponse?
var usage: AccountUsageResponse?
@@ -47,7 +47,7 @@ nonisolated private struct SupplementalDataCache {
}
}
-nonisolated private extension ReadResult {
+private nonisolated extension ReadResult {
var isAuthenticationRequired: Bool {
if case .authRequired = self {
return true
@@ -56,13 +56,13 @@ nonisolated private extension ReadResult {
}
var value: Value? {
- if case .value(let value) = self {
+ if case let .value(value) = self {
return value
}
return nil
}
- // 认证刷新后仍是 authRequired/broken 则上抛, 其余原样返回交给调用方按缓存策略处理
+ /// 认证刷新后仍是 authRequired/broken 则上抛, 其余原样返回交给调用方按缓存策略处理
func resultAfterAuthAttempt() throws -> ReadResult<Value> {
switch self {
case .value, .skipped:
@@ -75,8 +75,8 @@ nonisolated private extension ReadResult {
}
}
-// 维持一条 codex app-server stdio 会话, 复用失败后按需重建
-nonisolated final class CodexStatusService: @unchecked Sendable {
+/// 维持一条 codex app-server stdio 会话, 复用失败后按需重建
+final nonisolated class CodexStatusService: @unchecked Sendable {
private static let requestTimeout: TimeInterval = 20
// 定期回收连接, 让后台升级后的 codex 二进制有机会生效
private static let connectionMaxAge: TimeInterval = 1 * 60 * 60
@@ -87,7 +87,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
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)
}()
@@ -116,14 +116,50 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
}
}
- // 复用连接出现传输故障时只重建重试一次, 避免故障状态下反复拉起进程
+ func readCodexConfig() async throws -> CodexConfigReadResponse {
+ try await withCheckedThrowingContinuation { continuation in
+ queue.async {
+ do {
+ let connection = try self.readyConnectionOnQueue()
+ let response = try connection.session.request(
+ "config/read",
+ params: ["includeLayers": false],
+ as: CodexConfigReadResponse.self
+ )
+ continuation.resume(returning: response)
+ } catch {
+ continuation.resume(throwing: error)
+ }
+ }
+ }
+ }
+
+ func listCodexHooks(cwds: [String]) async throws -> CodexHooksListResponse {
+ try await withCheckedThrowingContinuation { continuation in
+ queue.async {
+ do {
+ let connection = try self.readyConnectionOnQueue()
+ let response = try connection.session.request(
+ "hooks/list",
+ params: ["cwds": cwds],
+ as: CodexHooksListResponse.self
+ )
+ continuation.resume(returning: response)
+ } catch {
+ continuation.resume(throwing: error)
+ }
+ }
+ }
+ }
+
+ /// 复用连接出现传输故障时只重建重试一次, 避免故障状态下反复拉起进程
private func resolveOutcomeOnQueue(allowRebuild: Bool) -> CodexFetchOutcome {
switch ensureConnection() {
case .notLoggedIn:
return .notLoggedIn
case .initializationFailed:
return .initializationFailed
- case .ready(let connection, let reused):
+ case let .ready(connection, reused):
do {
let snapshot = try fetchData(using: connection, refreshAccountInfo: reused)
return .data(snapshot)
@@ -133,7 +169,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
return .notLoggedIn
} catch FetchFailure.needsRebuild {
teardownConnection()
- if reused && allowRebuild {
+ if reused, allowRebuild {
return resolveOutcomeOnQueue(allowRebuild: false)
}
return .initializationFailed
@@ -144,6 +180,17 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
}
}
+ private func readyConnectionOnQueue() throws -> AppServerConnection {
+ switch ensureConnection() {
+ case let .ready(connection, _):
+ return connection
+ case .notLoggedIn:
+ throw CodexStatusError.notLoggedIn
+ case .initializationFailed:
+ throw CodexStatusError.serverConnectionClosed
+ }
+ }
+
private func ensureConnection() -> ConnectionResolution {
if let connection, connection.session.process.isRunning,
Date().timeIntervalSince(connection.openedAt) < Self.connectionMaxAge {
@@ -166,7 +213,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
clientVersion: Self.clientVersion(),
timeout: Self.requestTimeout
)
- if case .ready(let newConnection, _) = resolution {
+ if case let .ready(newConnection, _) = resolution {
connection = newConnection
}
return resolution
@@ -185,7 +232,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
return connection.commandInfo
}
- // 额度与用量独立读取; 认证失败全程只刷新一次 token, 传输故障交给外层重建连接
+ /// 额度与用量独立读取; 认证失败全程只刷新一次 token, 传输故障交给外层重建连接
private func fetchData(using connection: AppServerConnection, refreshAccountInfo: Bool) throws -> CodexQuotaSnapshot {
var didRefresh = false
@@ -261,13 +308,13 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
return snapshot
}
- // 新值更新缓存; 本轮请求失败则回退到缓存并标记陈旧; 方法不支持/认证/断连一律视为无数据
+ /// 新值更新缓存; 本轮请求失败则回退到缓存并标记陈旧; 方法不支持/认证/断连一律视为无数据
private func cachedRead<Value>(
_ result: ReadResult<Value>,
cache: inout Value?
) -> CachedSupplementalRead<Value> {
switch result {
- case .value(let value):
+ case let .value(value):
cache = value
return CachedSupplementalRead(value: value, isStale: false)
case .skipped(.requestFailed):
@@ -284,7 +331,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
as type: Value.Type
) -> ReadResult<Value> {
do {
- return .value(try connection.session.request(method, params: params, as: type))
+ return try .value(connection.session.request(method, params: params, as: type))
} catch let error as CodexStatusError {
return classify(error)
} catch {
@@ -323,7 +370,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
}
}
- // 初始化失败与未登录在这里分流; 两者都不复用本次新建的进程
+ /// 初始化失败与未登录在这里分流; 两者都不复用本次新建的进程
private static func openConnection(
command: AppServerCommand,
environment: [String: String],
@@ -416,7 +463,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
return version
}
- // userAgent 形如 "codex_bar/0.139.0 (...)"; 取首个 token 中 "/" 之后的运行版本号
+ /// userAgent 形如 "codex_bar/0.139.0 (...)"; 取首个 token 中 "/" 之后的运行版本号
private nonisolated static func serverVersion(fromUserAgent userAgent: String?) -> String? {
guard let firstToken = userAgent?.split(separator: " ").first,
let slashIndex = firstToken.firstIndex(of: "/") else {
@@ -428,12 +475,14 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
}
}
-private nonisolated final class AppServerConnection {
+private final nonisolated class AppServerConnection {
let session: AppServerSession
let commandInfo: CodexCLIConnectionInfo
var accountResponse: AccountReadResponse
- var openedAt: Date { commandInfo.openedAt }
+ var openedAt: Date {
+ commandInfo.openedAt
+ }
init(
session: AppServerSession,
diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
index b02e959..a850be3 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
@@ -1,7 +1,7 @@
import Combine
import Foundation
-// UI 级状态; 更细的连接和接口错误由服务层归并到日志
+/// UI 级状态; 更细的连接和接口错误由服务层归并到日志
nonisolated enum CodexLoadState: Equatable {
case loading
case loaded
@@ -24,12 +24,21 @@ final class CodexStatusViewModel: ObservableObject {
@Published private(set) var codexConnectionInfo: CodexCLIConnectionInfo?
@Published private(set) var autoRefreshCountdownStartedAt: Date?
- var hasError: Bool { loadState.isError }
+ var hasError: Bool {
+ loadState.isError
+ }
+
var hasUntrustedData: Bool {
snapshot?.hasTrustedData == false
}
- var usesErrorImage: Bool { hasError || hasUntrustedData }
- var autoRefreshInterval: TimeInterval { Self.refreshInterval }
+
+ var usesErrorImage: Bool {
+ hasError || hasUntrustedData
+ }
+
+ var autoRefreshInterval: TimeInterval {
+ Self.refreshInterval
+ }
private static let refreshInterval: TimeInterval = 60
@@ -62,7 +71,7 @@ final class CodexStatusViewModel: ObservableObject {
while !Task.isCancelled {
let delay = self?.autoRefreshDelay ?? Self.refreshInterval
- if (try? await Task.sleep(for: .seconds(delay))) == nil {
+ if await (try? Task.sleep(for: .seconds(delay))) == nil {
break
}
@@ -80,7 +89,7 @@ final class CodexStatusViewModel: ObservableObject {
Task {
switch await service.fetchOutcome() {
- case .data(let snapshot):
+ case let .data(snapshot):
self.snapshot = snapshot
self.loadState = .loaded
case .notLoggedIn:
diff --git a/CodexBar/Services/CodexStatus/RequestLog.swift b/CodexBar/Services/CodexStatus/RequestLog.swift
index c5a60d3..0003466 100644
--- a/CodexBar/Services/CodexStatus/RequestLog.swift
+++ b/CodexBar/Services/CodexStatus/RequestLog.swift
@@ -1,8 +1,8 @@
import Combine
import Foundation
-// JSON-RPC 交互日志: 带 id 的请求先记录为进行, 响应或错误到达后回填到同一条
-// `initialized` 这类无 id 请求没有响应可等, 单独记录为空响应
+/// JSON-RPC 交互日志: 带 id 的请求先记录为进行, 响应或错误到达后回填到同一条
+/// `initialized` 这类无 id 请求没有响应可等, 单独记录为空响应
nonisolated struct RequestLogEntry: Identifiable, Equatable {
enum Kind {
case pending
@@ -20,19 +20,19 @@ nonisolated struct RequestLogEntry: Identifiable, Equatable {
var detail: String?
}
-// 常驻日志存储, 写入来自后台队列, storage 用锁保护, SwiftUI 通知切回主线程发送
-nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {
+/// 常驻日志存储, 写入来自后台队列, storage 用锁保护, SwiftUI 通知切回主线程发送
+final nonisolated class RequestLogStore: ObservableObject, @unchecked Sendable {
static let shared = RequestLogStore()
- // nonisolated 存储不能用 @Published 包装可变数组, 这里手动发送变更
+ /// nonisolated 存储不能用 @Published 包装可变数组, 这里手动发送变更
let objectWillChange = ObservableObjectPublisher()
// 环形上限避免长时间运行后日志无限增长
private static let capacity = 500
- private static let maxDetailLength = 4000
+ private static let maxRequestLength = 4000
private let lock = NSLock()
- // 最新在前, 既方便渲染也让刚发出的请求更快被回填
+ /// 最新在前, 既方便渲染也让刚发出的请求更快被回填
private var storage: [RequestLogEntry] = []
var entries: [RequestLogEntry] {
@@ -50,7 +50,7 @@ nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {
respondedAt: nil,
kind: .pending,
method: method,
- request: Self.normalized(payload),
+ request: Self.normalizedPreview(payload),
detail: nil
)
)
@@ -81,7 +81,7 @@ nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {
respondedAt: nil,
kind: .emptyResponse,
method: method,
- request: Self.normalized(payload),
+ request: Self.normalizedPreview(payload),
detail: ""
)
)
@@ -152,14 +152,18 @@ nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {
}
}
- // 合法 JSON 重新序列化为稳定、未转义斜杠的日志文本; 非 JSON 错误消息保持原样
+ /// 合法 JSON 重新序列化为稳定、未转义斜杠的日志文本; 非 JSON 错误消息保持原样
private static func normalized(_ text: String) -> String {
+ jsonNormalized(text) ?? text
+ }
+
+ private static func normalizedPreview(_ text: String) -> String {
let readableText = jsonNormalized(text) ?? text
- guard readableText.count > maxDetailLength else {
+ guard readableText.count > maxRequestLength else {
return readableText
}
- return String(readableText.prefix(maxDetailLength)) + "…"
+ return String(readableText.prefix(maxRequestLength)) + "…"
}
private static func jsonNormalized(_ text: String) -> String? {
@@ -167,8 +171,8 @@ nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {
let object = try? JSONSerialization.jsonObject(with: data),
JSONSerialization.isValidJSONObject(object),
let output = try? JSONSerialization.data(
- withJSONObject: object,
- options: [.sortedKeys, .withoutEscapingSlashes]
+ withJSONObject: object,
+ options: [.sortedKeys, .withoutEscapingSlashes]
) else {
return nil
}
diff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swift
index 767b3e4..0017243 100644
--- a/CodexBar/Services/Settings/CodexHookSettings.swift
+++ b/CodexBar/Services/Settings/CodexHookSettings.swift
@@ -4,23 +4,33 @@ import Foundation
@MainActor
final class CodexHookSettings: ObservableObject {
@Published private(set) var isEnabled = false
+ @Published private(set) var isUpdating = false
@Published private(set) var errorMessage: String?
private let hooksURL: URL
private let fileManager: FileManager
+ private let codexStatusService: CodexStatusService
+ private var updateTask: Task<Void, Never>?
+ private var updateGeneration = 0
init(
hooksURL: URL = CodexHookSettings.defaultHooksURL(),
- fileManager: FileManager = .default
+ fileManager: FileManager = .default,
+ codexStatusService: CodexStatusService
) {
self.hooksURL = hooksURL
self.fileManager = fileManager
+ self.codexStatusService = codexStatusService
+ }
+
+ deinit {
+ updateTask?.cancel()
}
func refresh() {
do {
let config = try readConfigIfPresent()
- isEnabled = Self.containsCodexBarHooks(
+ isEnabled = Self.containsAnyCodexBarHook(
in: config,
executablePath: currentExecutablePath
)
@@ -32,9 +42,28 @@ final class CodexHookSettings: ObservableObject {
}
func setEnabled(_ enabled: Bool) {
- errorMessage = nil
+ runLatestUpdate(showProgress: true) { settings, generation in
+ await settings.applyEnabled(enabled, generation: generation)
+ }
+ }
+
+ func verifyInstalledHooks() {
+ guard isEnabled, !isUpdating else {
+ return
+ }
+
+ runLatestUpdate(showProgress: false) { settings, generation in
+ await settings.verifyInstalledHooksWithAppServer(generation: generation)
+ }
+ }
+ private func applyEnabled(_ enabled: Bool, generation: Int) async {
do {
+ if enabled {
+ try await ensureCodexHooksGloballyEnabled()
+ try ensureCurrentUpdate(generation)
+ }
+
var config = try readConfigIfPresent()
try Self.removeCodexBarHooks(
from: &config,
@@ -49,8 +78,96 @@ final class CodexHookSettings: ObservableObject {
}
try write(config)
+ try ensureCurrentUpdate(generation)
isEnabled = enabled
+ if enabled {
+ await verifyInstalledHooksWithAppServer(generation: generation)
+ }
+ } catch is CancellationError {
+ return
} catch {
+ handleApplyError(error, generation: generation)
+ }
+ }
+
+ private func verifyInstalledHooksWithAppServer(generation: Int) async {
+ do {
+ try await validateInstalledHooksWithAppServer()
+ try ensureCurrentUpdate(generation)
+ errorMessage = nil
+ } catch is CancellationError {
+ return
+ } catch let error as HookConfigError {
+ guard isCurrentUpdate(generation) else {
+ return
+ }
+
+ errorMessage = error.localizedDescription
+ } catch {
+ guard isCurrentUpdate(generation) else {
+ return
+ }
+
+ errorMessage = "无法验证 Codex Hook: \(error.localizedDescription)"
+ }
+ }
+
+ private func runLatestUpdate(
+ showProgress: Bool,
+ _ operation: @escaping @MainActor (CodexHookSettings, Int) async -> Void
+ ) {
+ updateTask?.cancel()
+ updateGeneration += 1
+ let generation = updateGeneration
+
+ if showProgress {
+ isUpdating = true
+ errorMessage = nil
+ }
+
+ updateTask = Task { [weak self] in
+ guard let self else {
+ return
+ }
+
+ await operation(self, generation)
+ finishUpdate(generation, showProgress: showProgress)
+ }
+ }
+
+ private func finishUpdate(_ generation: Int, showProgress: Bool) {
+ guard isCurrentUpdate(generation) else {
+ return
+ }
+
+ if showProgress {
+ isUpdating = false
+ }
+ updateTask = nil
+ }
+
+ private func isCurrentUpdate(_ generation: Int) -> Bool {
+ generation == updateGeneration
+ }
+
+ private func ensureCurrentUpdate(_ generation: Int) throws {
+ try Task.checkCancellation()
+
+ guard isCurrentUpdate(generation) else {
+ throw CancellationError()
+ }
+ }
+
+ private func handleApplyError(_ error: Error, generation: Int) {
+ guard isCurrentUpdate(generation) else {
+ return
+ }
+
+ if let hookError = error as? HookConfigError,
+ hookError.isPreflightFailure {
+ isEnabled = false
+ errorMessage = hookError.localizedDescription
+ } else {
refresh()
errorMessage = "设置 Codex Hook 失败: \(error.localizedDescription)"
}
@@ -62,34 +179,28 @@ private extension CodexHookSettings {
typealias JSONArray = [Any]
enum HookConfigError: LocalizedError {
- case invalidRoot
- case invalidHooks
- case invalidEvent(String)
+ case invalidFormat
+ case hooksGloballyDisabled
+ case hookValidationFailed(String)
var errorDescription: String? {
switch self {
- case .invalidRoot:
- return "hooks.json 顶层必须是 JSON 对象"
- case .invalidHooks:
- return "hooks 字段必须是 JSON 对象"
- case .invalidEvent(let event):
- return "\(event) 配置必须是数组"
+ case .invalidFormat:
+ "hooks.json 文件格式错误"
+ case .hooksGloballyDisabled:
+ "Codex 配置已禁用 Hook"
+ case let .hookValidationFailed(message):
+ message
}
}
- }
- static let codexBarEvents = [
- "SessionStart",
- "UserPromptSubmit",
- "PreToolUse",
- "PostToolUse",
- "PermissionRequest",
- "PreCompact",
- "PostCompact",
- "Stop",
- "SubagentStart",
- "SubagentStop"
- ]
+ var isPreflightFailure: Bool {
+ if case .hooksGloballyDisabled = self {
+ return true
+ }
+ return false
+ }
+ }
nonisolated static func defaultHooksURL() -> URL {
FileManager.default
@@ -100,8 +211,30 @@ private extension CodexHookSettings {
var currentExecutablePath: String {
Bundle.main.executableURL?.path
- ?? CommandLine.arguments.first
- ?? "/Applications/CodexBar.app/Contents/MacOS/CodexBar"
+ ?? CommandLine.arguments.first
+ ?? "/Applications/CodexBar.app/Contents/MacOS/CodexBar"
+ }
+
+ var hooksListWorkingDirectory: String {
+ fileManager.homeDirectoryForCurrentUser.path
+ }
+
+ func ensureCodexHooksGloballyEnabled() async throws {
+ let response = try await codexStatusService.readCodexConfig()
+ if response.hooksGloballyDisabled {
+ throw HookConfigError.hooksGloballyDisabled
+ }
+ }
+
+ func validateInstalledHooksWithAppServer() async throws {
+ let response = try await codexStatusService.listCodexHooks(cwds: [hooksListWorkingDirectory])
+ if let message = Self.validationMessage(
+ from: response,
+ executablePath: currentExecutablePath,
+ hooksURL: hooksURL
+ ) {
+ throw HookConfigError.hookValidationFailed(message)
+ }
}
func readConfigIfPresent() throws -> JSONObject {
@@ -118,9 +251,15 @@ private extension CodexHookSettings {
return [:]
}
- let object = try JSONSerialization.jsonObject(with: data)
+ let object: Any
+ do {
+ object = try JSONSerialization.jsonObject(with: data)
+ } catch {
+ throw HookConfigError.invalidFormat
+ }
+
guard let config = object as? JSONObject else {
- throw HookConfigError.invalidRoot
+ throw HookConfigError.invalidFormat
}
return config
@@ -139,25 +278,18 @@ private extension CodexHookSettings {
try data.write(to: hooksURL, options: .atomic)
}
- static func containsCodexBarHooks(in config: JSONObject, executablePath: String) -> Bool {
+ static func containsAnyCodexBarHook(in config: JSONObject, executablePath: String) -> Bool {
guard let hooks = config["hooks"] as? JSONObject else {
return false
}
- return codexBarEvents.allSatisfy { event in
- guard let groups = hooks[event] as? JSONArray else {
+ return CodexHookEvent.allCases.contains { event in
+ guard let groups = hooks[event.configName] as? JSONArray else {
return false
}
- return groups.contains { group in
- guard let group = group as? JSONObject,
- let handlers = group["hooks"] as? JSONArray else {
- return false
- }
-
- return handlers.contains {
- isCurrentCodexBarHandler($0, event: event, executablePath: executablePath)
- }
+ return groups.contains {
+ groupContainsCodexBarHandler($0, executablePath: executablePath)
}
}
}
@@ -165,18 +297,18 @@ private extension CodexHookSettings {
static func installCodexBarHooks(in config: inout JSONObject, executablePath: String) throws {
var hooks = try hooksObject(from: config)
- for event in codexBarEvents {
- var groups = try eventGroups(named: event, from: hooks)
+ for event in CodexHookEvent.allCases {
+ var groups = try eventGroups(named: event.configName, from: hooks)
groups.append([
"hooks": [
[
"type": "command",
- "command": hookCommand(for: event, executablePath: executablePath),
+ "command": hookCommand(executablePath: executablePath),
"timeout": 5
]
]
])
- hooks[event] = groups
+ hooks[event.configName] = groups
}
config["hooks"] = hooks
@@ -194,28 +326,14 @@ private extension CodexHookSettings {
for (event, value) in hooks {
guard let groups = value as? JSONArray else {
- throw HookConfigError.invalidEvent(event)
+ throw HookConfigError.invalidFormat
}
- let filteredGroups = groups.compactMap { group -> Any? in
- guard var groupObject = group as? JSONObject,
- let handlers = groupObject["hooks"] as? JSONArray else {
- return group
- }
-
- let filteredHandlers = handlers.filter {
- !isCurrentCodexBarHandler(
- $0,
- event: event,
- executablePath: executablePath
- )
- }
- guard !filteredHandlers.isEmpty else {
- return nil
- }
-
- groupObject["hooks"] = filteredHandlers
- return groupObject
+ let filteredGroups = groups.compactMap {
+ groupRemovingCodexBarHandlers(
+ from: $0,
+ executablePath: executablePath
+ )
}
if filteredGroups.isEmpty {
@@ -228,13 +346,84 @@ private extension CodexHookSettings {
config["hooks"] = hooks
}
+ static func validationMessage(
+ from response: CodexHooksListResponse,
+ executablePath: String,
+ hooksURL: URL
+ ) -> String? {
+ guard !response.data.isEmpty else {
+ return "hooks/list 没有返回任何结果"
+ }
+
+ let entries = response.data
+ let hooks = entries.flatMap(\.hooks)
+ let warnings = entries.flatMap(\.warnings)
+ let errors = entries.flatMap(\.errors)
+ let expectedSourcePath = normalizedPath(hooksURL.path)
+ var hasMissingEvent = false
+ var hasDisabledHook = false
+ var hasUnexpectedSource = false
+ var hasUntrustedHook = false
+
+ for event in CodexHookEvent.allCases {
+ guard let hook = matchingHook(
+ for: event,
+ in: hooks,
+ executablePath: executablePath,
+ expectedSourcePath: expectedSourcePath
+ ) else {
+ hasMissingEvent = true
+ continue
+ }
+
+ hasDisabledHook = hasDisabledHook || !hook.enabled
+ hasUnexpectedSource = hasUnexpectedSource || normalizedPath(hook.sourcePath) != expectedSourcePath
+ hasUntrustedHook = hasUntrustedHook || hook.trustStatus == "untrusted" || hook.trustStatus == "modified"
+ }
+
+ if !errors.isEmpty {
+ return "Codex 返回错误"
+ }
+ if hasDisabledHook {
+ return "CodexBar Hook 已被禁用"
+ }
+ if hasUntrustedHook {
+ return "CodexBar Hook 未被信任"
+ }
+ if hasMissingEvent {
+ return "CodexBar Hook 已不完整"
+ }
+ if hasUnexpectedSource {
+ return "CodexBar Hook 意外来源"
+ }
+ if !warnings.isEmpty {
+ return "Codex 返回警告"
+ }
+
+ return nil
+ }
+
+ static func matchingHook(
+ for event: CodexHookEvent,
+ in hooks: [CodexHookMetadata],
+ executablePath: String,
+ expectedSourcePath: String
+ ) -> CodexHookMetadata? {
+ let matchingHooks = hooks.filter {
+ ($0.command.map { isCodexBarCommand($0, executablePath: executablePath) } ?? false)
+ && $0.eventName == event.appServerName
+ }
+ return matchingHooks.first { normalizedPath($0.sourcePath) == expectedSourcePath }
+ ?? matchingHooks.first
+ }
+
static func hooksObject(from config: JSONObject) throws -> JSONObject {
guard let value = config["hooks"] else {
return [:]
}
guard let hooks = value as? JSONObject else {
- throw HookConfigError.invalidHooks
+ throw HookConfigError.invalidFormat
}
return hooks
@@ -246,21 +435,65 @@ private extension CodexHookSettings {
}
guard let groups = value as? JSONArray else {
- throw HookConfigError.invalidEvent(event)
+ throw HookConfigError.invalidFormat
}
return groups
}
+ static func groupContainsCodexBarHandler(
+ _ group: Any,
+ executablePath: String
+ ) -> Bool {
+ guard let handlers = handlers(from: group) else {
+ return false
+ }
+
+ return handlers.contains {
+ isCurrentCodexBarHandler($0, executablePath: executablePath)
+ }
+ }
+
+ static func groupRemovingCodexBarHandlers(
+ from group: Any,
+ executablePath: String
+ ) -> Any? {
+ guard var groupObject = group as? JSONObject,
+ let handlers = handlers(from: group) else {
+ return group
+ }
+
+ let filteredHandlers = handlers.filter {
+ !isCurrentCodexBarHandler($0, executablePath: executablePath)
+ }
+ guard !filteredHandlers.isEmpty else {
+ return nil
+ }
+
+ groupObject["hooks"] = filteredHandlers
+ return groupObject
+ }
+
+ static func handlers(from group: Any) -> JSONArray? {
+ guard let group = group as? JSONObject else {
+ return nil
+ }
+
+ return group["hooks"] as? JSONArray
+ }
+
static func isCurrentCodexBarHandler(
_ handler: Any,
- event: String,
executablePath: String
) -> Bool {
- commandIfCommandHandler(handler) == hookCommand(for: event, executablePath: executablePath)
+ guard let command = commandIfCommandHandler(handler) else {
+ return false
+ }
+
+ return isCodexBarCommand(command, executablePath: executablePath)
}
- // 仅当 handler 是 type == "command" 时返回其 command 字符串, 否则 nil
+ /// 仅当 handler 是 type == "command" 时返回其 command 字符串, 否则 nil
private static func commandIfCommandHandler(_ handler: Any) -> String? {
guard let handler = handler as? JSONObject,
handler["type"] as? String == "command",
@@ -271,11 +504,22 @@ private extension CodexHookSettings {
return command
}
- static func hookCommand(for event: String, executablePath: String) -> String {
- "\(shellQuoted(executablePath)) --hook-event \(event)"
+ static func hookCommand(executablePath: String) -> String {
+ shellQuoted(executablePath)
+ }
+
+ static func isCodexBarCommand(_ command: String, executablePath: String) -> Bool {
+ command.contains(hookCommand(executablePath: executablePath))
}
static func shellQuoted(_ value: String) -> String {
"'\(value.replacingOccurrences(of: "'", with: "'\\''"))'"
}
+
+ static func normalizedPath(_ path: String) -> String {
+ URL(fileURLWithPath: (path as NSString).expandingTildeInPath)
+ .standardizedFileURL
+ .resolvingSymlinksInPath()
+ .path
+ }
}
diff --git a/CodexBar/Services/Settings/GlobalHotKeySettings.swift b/CodexBar/Services/Settings/GlobalHotKeySettings.swift
index d777b74..d2a3cc9 100644
--- a/CodexBar/Services/Settings/GlobalHotKeySettings.swift
+++ b/CodexBar/Services/Settings/GlobalHotKeySettings.swift
@@ -11,7 +11,7 @@ final class GlobalHotKeySettings: ObservableObject {
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
- self.shortcut = Self.loadShortcut(from: defaults)
+ shortcut = Self.loadShortcut(from: defaults)
}
func setShortcut(_ shortcut: GlobalHotKeyShortcut) {
diff --git a/CodexBar/Services/Updates/AppUpdater.swift b/CodexBar/Services/Updates/AppUpdater.swift
index c5b829d..e39eff1 100644
--- a/CodexBar/Services/Updates/AppUpdater.swift
+++ b/CodexBar/Services/Updates/AppUpdater.swift
@@ -10,7 +10,9 @@ final class AppUpdater: NSObject, ObservableObject {
@Published private(set) var availableUpdateMessage: String?
@Published private(set) var automaticallyChecksForUpdates = false
- var canConfigureAutomaticChecks: Bool { updaterController != nil }
+ var canConfigureAutomaticChecks: Bool {
+ updaterController != nil
+ }
private var updaterController: SPUStandardUpdaterController?
private var clearSettingsStatusMessageTask: Task<Void, Never>?
@@ -96,8 +98,7 @@ final class AppUpdater: NSObject, ObservableObject {
let feedURLString = bundle.object(forInfoDictionaryKey: "SUFeedURL") as? String,
let scheme = URL(string: feedURLString)?.scheme?.lowercased(),
scheme == "https" || scheme == "http",
- let publicKey = bundle.object(forInfoDictionaryKey: "SUPublicEDKey") as? String
- else {
+ let publicKey = bundle.object(forInfoDictionaryKey: "SUPublicEDKey") as? String else {
return false
}
diff --git a/CodexBar/Services/WorkflowStats/JSONLines.swift b/CodexBar/Services/WorkflowStats/JSONLines.swift
index 208af89..58e9177 100644
--- a/CodexBar/Services/WorkflowStats/JSONLines.swift
+++ b/CodexBar/Services/WorkflowStats/JSONLines.swift
@@ -1,13 +1,13 @@
import Foundation
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
}
static func decodeWithFailures<T: Decodable>(
- _ type: T.Type = T.self,
+ _: T.Type = T.self,
from data: Data
) -> JSONLinesDecodeResult<T> {
guard let text = String(bytes: data, encoding: .utf8) else {
diff --git a/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift b/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift
index 699ca10..d462038 100644
--- a/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift
+++ b/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift
@@ -2,37 +2,20 @@ import Darwin
import Foundation
nonisolated enum WorkflowHookEventRecorder {
- static func handleIfRequested(arguments: [String] = CommandLine.arguments) -> Bool {
- guard let fallbackEventName = hookEventName(from: arguments) else {
- return false
- }
-
- try? record(fallbackEventName: fallbackEventName)
- return true
- }
-
- private static func hookEventName(from arguments: [String]) -> String? {
- for argument in arguments.dropFirst() where argument.hasPrefix("--hook-event=") {
- return normalizedHookEventName(String(argument.dropFirst("--hook-event=".count)))
- }
+ static func handleIfRequested() -> Bool {
+ let payload = stdinPayload()
- if let optionIndex = arguments.firstIndex(of: "--hook-event"),
- arguments.indices.contains(arguments.index(after: optionIndex)) {
- return normalizedHookEventName(arguments[arguments.index(after: optionIndex)])
+ guard let eventName = payload.string(for: "hook_event_name") else {
+ // 如果 Codex 已经通过 stdin 传了内容但事件名缺失, 吞掉本次 Hook
+ // 避免 Hook 子进程继续启动完整菜单栏 App
+ return payload.hasInput
}
- return nil
- }
-
- private static func normalizedHookEventName(_ value: String) -> String? {
- let trimmedValue = value.trimmingCharacters(in: .whitespacesAndNewlines)
- return trimmedValue.isEmpty ? nil : trimmedValue
+ try? record(payload: payload, eventName: eventName)
+ return true
}
- private static func record(fallbackEventName: String) throws {
- let payload = stdinPayload()
- let eventName = payload.string(for: "hook_event_name")
- .flatMap(normalizedHookEventName) ?? fallbackEventName
+ private static func record(payload: WorkflowHookPayload, eventName: String) throws {
let timestamp = payload.date(for: "timestamp") ?? Date()
let cwd = payload.string(for: "cwd") ?? FileManager.default.currentDirectoryPath
let tool = payload.string(for: "tool_name")
@@ -87,22 +70,26 @@ nonisolated enum WorkflowHookEventRecorder {
private static func stdinPayload() -> WorkflowHookPayload {
guard isatty(STDIN_FILENO) == 0 else {
- return WorkflowHookPayload(values: [:])
+ return WorkflowHookPayload(values: [:], hasInput: false)
}
let data = FileHandle.standardInput.readDataToEndOfFile()
- guard !data.isEmpty,
- let object = try? JSONSerialization.jsonObject(with: data),
+ guard !data.isEmpty else {
+ return WorkflowHookPayload(values: [:], hasInput: false)
+ }
+
+ guard let object = try? JSONSerialization.jsonObject(with: data),
let values = object as? [String: Any] else {
- return WorkflowHookPayload(values: [:])
+ return WorkflowHookPayload(values: [:], hasInput: true)
}
- return WorkflowHookPayload(values: values)
+ return WorkflowHookPayload(values: values, hasInput: true)
}
}
private nonisolated struct WorkflowHookPayload {
let values: [String: Any]
+ let hasInput: Bool
func string(for key: String) -> String? {
Self.normalizedString(values[key])
@@ -130,7 +117,7 @@ private nonisolated struct WorkflowHookPayload {
return date(from: string)
case let number as NSNumber:
let rawValue = number.doubleValue
- let seconds = rawValue > 10_000_000_000 ? rawValue / 1000 : rawValue
+ let seconds = rawValue > 10000000000 ? rawValue / 1000 : rawValue
return Date(timeIntervalSince1970: seconds)
default:
return nil
@@ -151,12 +138,6 @@ private nonisolated struct WorkflowHookPayload {
return date
}
- return iso8601Formatter.date(from: trimmedString)
+ return ISO8601DateFormatter.codexInternetDateTime.date(from: trimmedString)
}
-
- private static let iso8601Formatter: ISO8601DateFormatter = {
- let formatter = ISO8601DateFormatter()
- formatter.formatOptions = [.withInternetDateTime]
- return formatter
- }()
}
diff --git a/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift b/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift
index aad0ec0..72abbbf 100644
--- a/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift
+++ b/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift
@@ -2,7 +2,7 @@ import Combine
import Darwin
import Foundation
-nonisolated final class WorkflowStatsService: @unchecked Sendable {
+final nonisolated class WorkflowStatsService: @unchecked Sendable {
private let queue = DispatchQueue(label: "CodexBar.workflow-stats", qos: .utility)
private let eventsDirectoryURL: URL
private let dailyLogURL: URL
@@ -338,8 +338,7 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {
record: (WorkflowHookEvent) -> Void
) -> Int {
guard let line = String(bytes: lineData, encoding: .utf8)?
- .trimmingCharacters(in: .whitespacesAndNewlines)
- else {
+ .trimmingCharacters(in: .whitespacesAndNewlines) else {
return 1
}
@@ -469,7 +468,6 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {
return date >= WorkflowStatsStorage.identifierRetentionCutoffDate()
}
-
}
nonisolated enum WorkflowStatsStorage {
@@ -632,10 +630,10 @@ nonisolated struct WorkflowStatsMaintenanceState: Codable, Equatable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
- self.schema = try container.decodeIfPresent(Int.self, forKey: .schema) ?? Self.currentSchema
- self.pending = Self.normalizedDates(try container.decodeIfPresent([String].self, forKey: .pending) ?? [])
- self.dirty = Self.normalizedDates(try container.decodeIfPresent([String].self, forKey: .dirty) ?? [])
- self.days = try container.decodeIfPresent([String: WorkflowStatsDayMaintenanceState].self, forKey: .days) ?? [:]
+ schema = try container.decodeIfPresent(Int.self, forKey: .schema) ?? Self.currentSchema
+ pending = try Self.normalizedDates(container.decodeIfPresent([String].self, forKey: .pending) ?? [])
+ dirty = try Self.normalizedDates(container.decodeIfPresent([String].self, forKey: .dirty) ?? [])
+ days = try container.decodeIfPresent([String: WorkflowStatsDayMaintenanceState].self, forKey: .days) ?? [:]
}
mutating func markPending(_ dateKey: String) {
diff --git a/CodexBar/Views/Log/LogView.swift b/CodexBar/Views/Log/LogView.swift
index b583662..13e33d3 100644
--- a/CodexBar/Views/Log/LogView.swift
+++ b/CodexBar/Views/Log/LogView.swift
@@ -182,11 +182,11 @@ private struct LogRow: View {
private var detailCaption: String {
switch entry.kind {
case .response, .emptyResponse:
- return "响应"
+ "响应"
case .failure:
- return "错误"
+ "错误"
default:
- return "详情"
+ "详情"
}
}
@@ -202,26 +202,26 @@ private extension RequestLogEntry.Kind {
var label: String {
switch self {
case .pending:
- return "进行"
+ "进行"
case .response:
- return "完成"
+ "完成"
case .failure:
- return "错误"
+ "错误"
case .emptyResponse:
- return "请求"
+ "请求"
}
}
var tint: Color {
switch self {
case .pending:
- return .orange
+ .orange
case .response:
- return .green
+ .green
case .failure:
- return .red
+ .red
case .emptyResponse:
- return .blue
+ .blue
}
}
}
diff --git a/CodexBar/Views/Menu/CodexStatusMenuSections.swift b/CodexBar/Views/Menu/CodexStatusMenuSections.swift
index e8ddee9..b35e1bf 100644
--- a/CodexBar/Views/Menu/CodexStatusMenuSections.swift
+++ b/CodexBar/Views/Menu/CodexStatusMenuSections.swift
@@ -109,11 +109,11 @@ struct StatusAccountCard: View {
private var statusDisplay: (text: String?, color: Color) {
switch loadState {
case .notLoggedIn:
- return ("未登录", .orange)
+ ("未登录", .orange)
case .initializationFailed:
- return ("初始化失败", .red)
+ ("初始化失败", .red)
case .loading, .loaded:
- return (nil, .accentColor)
+ (nil, .accentColor)
}
}
}
diff --git a/CodexBar/Views/Menu/QuotaRow.swift b/CodexBar/Views/Menu/QuotaRow.swift
index c879198..7377023 100644
--- a/CodexBar/Views/Menu/QuotaRow.swift
+++ b/CodexBar/Views/Menu/QuotaRow.swift
@@ -90,11 +90,11 @@ private enum QuotaBarPalette {
switch percent {
case 80...:
return green
- case 60..<80:
+ case 60 ..< 80:
return teal
- case 40..<60:
+ case 40 ..< 60:
return yellow
- case 20..<40:
+ case 20 ..< 40:
return orange
default:
return red
@@ -116,7 +116,7 @@ private struct SegmentedQuotaBar: View {
let filledColor = QuotaBarPalette.filledColor(for: percent)
HStack(spacing: Metrics.segmentSpacing) {
- ForEach(0..<Metrics.segmentCount, id: \.self) { index in
+ ForEach(0 ..< Metrics.segmentCount, id: \.self) { index in
Capsule(style: .continuous)
.fill(index < filledSegments ? filledColor : QuotaBarPalette.placeholderColor)
.frame(width: Metrics.segmentWidth, height: Metrics.segmentHeight)
diff --git a/CodexBar/Views/Menu/TokenCountText.swift b/CodexBar/Views/Menu/TokenCountText.swift
index 0e16ff7..2b5df2e 100644
--- a/CodexBar/Views/Menu/TokenCountText.swift
+++ b/CodexBar/Views/Menu/TokenCountText.swift
@@ -63,14 +63,14 @@ extension View {
private enum TokenCountFormatter {
static func parts(from tokens: Int) -> TokenCountParts {
switch tokens {
- case 1_000_000_000...:
- return TokenCountParts(number: decimal(Double(tokens) / 1_000_000_000), unit: "B")
- case 1_000_000...:
- return TokenCountParts(number: decimal(Double(tokens) / 1_000_000), unit: "M")
- case 1_000...:
- return TokenCountParts(number: decimal(Double(tokens) / 1_000), unit: "K")
+ case 1000000000...:
+ TokenCountParts(number: decimal(Double(tokens) / 1000000000), unit: "B")
+ case 1000000...:
+ TokenCountParts(number: decimal(Double(tokens) / 1000000), unit: "M")
+ case 1000...:
+ TokenCountParts(number: decimal(Double(tokens) / 1000), unit: "K")
default:
- return TokenCountParts(number: String(tokens), unit: nil)
+ TokenCountParts(number: String(tokens), unit: nil)
}
}
diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swift
index f5bf09f..5cdc35b 100644
--- a/CodexBar/Views/Menu/UsageHeatmap.swift
+++ b/CodexBar/Views/Menu/UsageHeatmap.swift
@@ -51,7 +51,7 @@ struct UsageSummaryView: View {
today: Date()
)
self.days = days
- self.peakTokens = max(days.lazy.compactMap { $0?.tokensForHeatmap }.max() ?? 0, 1)
+ peakTokens = max(days.lazy.compactMap { $0?.tokensForHeatmap }.max() ?? 0, 1)
}
var body: some View {
@@ -111,10 +111,10 @@ struct UsageSummaryView: View {
}
}
- private func metric<Content: View>(
+ private func metric(
label: String,
alignment: Alignment,
- @ViewBuilder value: () -> Content
+ @ViewBuilder value: () -> some View
) -> some View {
VStack(alignment: .leading, spacing: 2) {
Text(label)
@@ -142,9 +142,9 @@ struct UsageSummaryView: View {
}
let duration = max(seconds, 0)
- let days = duration / 86_400
- let hours = duration % 86_400 / 3_600
- let minutes = duration % 3_600 / 60
+ let days = duration / 86400
+ let hours = duration % 86400 / 3600
+ let minutes = duration % 3600 / 60
let remainingSeconds = duration % 60
if days > 0 {
@@ -187,8 +187,8 @@ struct UsageSummaryView: View {
let x = heatmapGridScreenFrame.minX + CGFloat(selection.column) * UsageHeatmap.Metrics.squarePitch
let y = heatmapGridScreenFrame.maxY
- - CGFloat(selection.row) * UsageHeatmap.Metrics.squarePitch
- - UsageHeatmap.Metrics.squareSize
+ - CGFloat(selection.row) * UsageHeatmap.Metrics.squarePitch
+ - UsageHeatmap.Metrics.squareSize
return CGRect(
x: x,
@@ -203,7 +203,7 @@ struct UsageSummaryView: View {
return
}
- guard let updatedDay = days.compactMap({ $0 }).first(where: { $0.id == hoverSelection.day.id }) else {
+ guard let updatedDay = days.compactMap(\.self).first(where: { $0.id == hoverSelection.day.id }) else {
withAnimation(Metrics.statusAnimation) {
self.hoverSelection = nil
}
@@ -245,7 +245,7 @@ struct UsageHeatmap: View {
) {
self.days = days
self.onScreenFrameChange = onScreenFrameChange
- self._selection = selection
+ _selection = selection
self.peakTokens = peakTokens
}
@@ -276,9 +276,9 @@ struct UsageHeatmap: View {
}
HStack(alignment: .top, spacing: Metrics.squareSpacing) {
- ForEach(0..<Metrics.columnCount, id: \.self) { column in
+ ForEach(0 ..< Metrics.columnCount, id: \.self) { column in
VStack(spacing: Metrics.squareSpacing) {
- ForEach(0..<Metrics.rowCount, id: \.self) { row in
+ ForEach(0 ..< Metrics.rowCount, id: \.self) { row in
let index = column * Metrics.rowCount + row
if days.indices.contains(index), let day = days[index] {
@@ -299,7 +299,7 @@ struct UsageHeatmap: View {
.contentShape(Rectangle())
.onContinuousHover(coordinateSpace: .local) { phase in
switch phase {
- case .active(let point):
+ case let .active(point):
updatePointerLocation(point)
case .ended:
scheduleDeactivate()
@@ -313,7 +313,7 @@ struct UsageHeatmap: View {
}
private var visibleDays: [UsageHeatmapDay] {
- days.compactMap { $0 }
+ days.compactMap(\.self)
}
private var dateRangeText: String? {
@@ -348,8 +348,8 @@ struct UsageHeatmap: View {
let column = Int(((point.x - Metrics.squareSize / 2) / Metrics.squarePitch).rounded())
let row = Int(((point.y - Metrics.squareSize / 2) / Metrics.squarePitch).rounded())
- guard (0..<Metrics.columnCount).contains(column),
- (0..<Metrics.rowCount).contains(row) else {
+ guard (0 ..< Metrics.columnCount).contains(column),
+ (0 ..< Metrics.rowCount).contains(row) else {
return nil
}
@@ -473,13 +473,13 @@ private struct UsageHeatmapSquare: View {
private struct HeatmapScreenFrameReader: NSViewRepresentable {
let onChange: (CGRect?) -> Void
- func makeNSView(context: Context) -> HeatmapScreenFrameReportingView {
+ func makeNSView(context _: Context) -> HeatmapScreenFrameReportingView {
let view = HeatmapScreenFrameReportingView()
view.onChange = onChange
return view
}
- func updateNSView(_ nsView: HeatmapScreenFrameReportingView, context: Context) {
+ func updateNSView(_ nsView: HeatmapScreenFrameReportingView, context _: Context) {
nsView.onChange = onChange
nsView.scheduleReport()
}
@@ -502,7 +502,7 @@ private final class HeatmapScreenFrameReportingView: NSView {
}
func scheduleReport() {
- // updateNSView 每次 hover 重渲染都会调到这里, 合并掉重复的待执行 report, 至多保留一个。
+ // updateNSView 每次 hover 重渲染都会调到这里, 合并掉重复的待执行 report, 至多保留一个
guard !reportScheduled else {
return
}
@@ -512,8 +512,8 @@ private final class HeatmapScreenFrameReportingView: NSView {
guard let self else {
return
}
- self.reportScheduled = false
- self.reportFrame()
+ reportScheduled = false
+ reportFrame()
}
}
@@ -573,8 +573,8 @@ struct UsageHeatmapDayDetailView: View {
static func panelSize(showsWorkflowStats: Bool) -> CGSize {
showsWorkflowStats
- ? CGSize(width: Metrics.workflowPanelWidth, height: Metrics.workflowPanelHeight)
- : CGSize(width: Metrics.tokenPanelWidth, height: Metrics.tokenPanelHeight)
+ ? CGSize(width: Metrics.workflowPanelWidth, height: Metrics.workflowPanelHeight)
+ : CGSize(width: Metrics.tokenPanelWidth, height: Metrics.tokenPanelHeight)
}
@ViewBuilder
@@ -660,7 +660,7 @@ struct UsageHeatmapDayDetailView: View {
metricDot(tint: .blue, darkOpacity: 0.88, lightOpacity: 0.76)
}
- private func metricRowLayout<Content: View>(@ViewBuilder content: () -> Content) -> some View {
+ private func metricRowLayout(@ViewBuilder content: () -> some View) -> some View {
HStack(spacing: Metrics.metricRowSpacing, content: content)
.font(.system(size: Metrics.workflowFontSize))
.frame(height: Metrics.metricRowHeight)
@@ -674,7 +674,7 @@ struct UsageHeatmapDayDetailView: View {
private var tokenIntensityStrip: some View {
HStack(spacing: Metrics.tokenIntensitySegmentSpacing) {
- ForEach(0..<Metrics.tokenIntensitySegmentCount, id: \.self) { index in
+ ForEach(0 ..< Metrics.tokenIntensitySegmentCount, id: \.self) { index in
RoundedRectangle(cornerRadius: 2, style: .continuous)
.fill(tokenIntensityFill(for: index))
.frame(maxWidth: .infinity)
@@ -797,8 +797,8 @@ struct UsageHeatmapDayDetailView: View {
private var panelBoundaryColor: Color {
colorScheme == .dark
- ? .white.opacity(0.18)
- : .black.opacity(0.14)
+ ? .white.opacity(0.18)
+ : .black.opacity(0.14)
}
private struct WorkflowMetricRow: Identifiable {
@@ -806,7 +806,9 @@ struct UsageHeatmapDayDetailView: View {
let value: Int
let tint: Color
- var id: String { label }
+ var id: String {
+ label
+ }
}
private enum Metrics {
@@ -865,7 +867,7 @@ private struct AnimatedDateText: View {
let day = Int(components.day) else {
return 0
}
- return Double(year * 10_000 + month * 100 + day)
+ return Double(year * 10000 + month * 100 + day)
}
private var components: DateTextComponents? {
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index 7bba4a9..b48035a 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -16,13 +16,13 @@ struct AppSettingsView: View {
LiquidGlassDivider()
automaticUpdateCheckRow
LiquidGlassDivider()
- hotKeyRow
- LiquidGlassDivider()
codexHookRow
LiquidGlassDivider()
- versionRow
+ hotKeyRow
LiquidGlassDivider()
codexVersionSection
+ LiquidGlassDivider()
+ versionRow
}
.padding(Metrics.panelPadding)
.liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius)
@@ -39,6 +39,7 @@ struct AppSettingsView: View {
}
.animation(Metrics.statusAnimation, value: loginItemSettings.errorMessage)
.animation(Metrics.statusAnimation, value: codexHookSettings.errorMessage)
+ .animation(Metrics.statusAnimation, value: codexHookSettings.isUpdating)
.padding(Metrics.padding)
.frame(width: Metrics.windowWidth)
.liquidGlassSurface(
@@ -52,11 +53,12 @@ struct AppSettingsView: View {
)
.onAppear {
loginItemSettings.refresh()
- codexHookSettings.refresh()
appUpdater.refreshAutomaticCheckSetting()
refreshCodexVersionSection()
}
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
+ codexHookSettings.refresh()
+ codexHookSettings.verifyInstalledHooks()
refreshCodexVersionSection()
}
}
@@ -110,17 +112,21 @@ private extension AppSettingsView {
isOn: Binding(
get: { codexHookSettings.isEnabled },
set: { codexHookSettings.setEnabled($0) }
- )
+ ),
+ isEnabled: !codexHookSettings.isUpdating
)
- HStack(alignment: .top, spacing: 10) {
- Color.clear
- .frame(width: Metrics.iconWidth)
+ if let message = codexHookSettings.errorMessage {
+ HStack(alignment: .top, spacing: 10) {
+ Color.clear
+ .frame(width: Metrics.iconWidth)
- Text("开启后将会写入全局 Codex Hook 配置\n用于近 30 周数据中展示更多统计数据\n该数据仅保存在本机")
- .font(.caption)
- .foregroundStyle(.secondary)
- .fixedSize(horizontal: false, vertical: true)
+ Text(message)
+ .font(.caption)
+ .foregroundStyle(.red)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .transition(.opacity)
}
}
}
@@ -161,7 +167,7 @@ private extension AppSettingsView {
.animation(Metrics.statusAnimation, value: appUpdater.availableUpdateMessage != nil)
}
- // 版本行优先显示更新状态, 没有动态消息时回退到当前版本号
+ /// 版本行优先显示更新状态, 没有动态消息时回退到当前版本号
var versionStatus: (text: String, isVersionLabel: Bool) {
if let message = appUpdater.settingsStatusMessage ?? appUpdater.availableUpdateMessage {
return (message, false)
@@ -215,6 +221,6 @@ private extension AppSettingsView {
}
var settingsErrorMessage: String? {
- loginItemSettings.errorMessage ?? codexHookSettings.errorMessage
+ loginItemSettings.errorMessage
}
}
diff --git a/CodexBar/Views/Settings/HotKeyRecorderRow.swift b/CodexBar/Views/Settings/HotKeyRecorderRow.swift
index f95e6b0..295bbfd 100644
--- a/CodexBar/Views/Settings/HotKeyRecorderRow.swift
+++ b/CodexBar/Views/Settings/HotKeyRecorderRow.swift
@@ -166,7 +166,7 @@ private struct HotKeyCaptureView: NSViewRepresentable {
let onCancel: () -> Void
let onWindowClose: () -> Void
- func makeNSView(context: Context) -> HotKeyCaptureNSView {
+ func makeNSView(context _: Context) -> HotKeyCaptureNSView {
let view = HotKeyCaptureNSView()
view.onCapture = onCapture
view.onCancel = onCancel
@@ -174,7 +174,7 @@ private struct HotKeyCaptureView: NSViewRepresentable {
return view
}
- func updateNSView(_ nsView: HotKeyCaptureNSView, context: Context) {
+ func updateNSView(_ nsView: HotKeyCaptureNSView, context _: Context) {
nsView.onCapture = onCapture
nsView.onCancel = onCancel
nsView.onWindowClose = onWindowClose
@@ -193,16 +193,11 @@ private final class HotKeyCaptureNSView: NSView {
var onCapture: ((NSEvent) -> Void)?
var onCancel: (() -> Void)?
var onWindowClose: (() -> Void)?
- private var windowCloseObserver: NSObjectProtocol?
override var acceptsFirstResponder: Bool {
true
}
- deinit {
- removeWindowCloseObserver()
- }
-
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
updateWindowCloseObserver()
@@ -223,19 +218,23 @@ private final class HotKeyCaptureNSView: NSView {
return
}
- windowCloseObserver = NotificationCenter.default.addObserver(
- forName: NSWindow.willCloseNotification,
- object: window,
- queue: .main
- ) { [weak self] _ in
- self?.onWindowClose?()
- }
+ NotificationCenter.default.addObserver(
+ self,
+ selector: #selector(windowWillClose(_:)),
+ name: NSWindow.willCloseNotification,
+ object: window
+ )
+ }
+
+ @objc private func windowWillClose(_: Notification) {
+ onWindowClose?()
}
private func removeWindowCloseObserver() {
- if let windowCloseObserver {
- NotificationCenter.default.removeObserver(windowCloseObserver)
- self.windowCloseObserver = nil
- }
+ NotificationCenter.default.removeObserver(
+ self,
+ name: NSWindow.willCloseNotification,
+ object: nil
+ )
}
}
diff --git a/CodexBar/Views/Shared/LiquidGlassStyle.swift b/CodexBar/Views/Shared/LiquidGlassStyle.swift
index dd5f63d..13f0c7c 100644
--- a/CodexBar/Views/Shared/LiquidGlassStyle.swift
+++ b/CodexBar/Views/Shared/LiquidGlassStyle.swift
@@ -52,7 +52,7 @@ extension View {
}
}
- // 数据为缓存回退(本轮刷新失败)时弱化显示
+ /// 数据为缓存回退(本轮刷新失败)时弱化显示
func markStale(_ isStale: Bool) -> some View {
opacity(isStale ? 0.55 : 1)
}
@@ -171,13 +171,13 @@ private struct LiquidGlassSurface: View {
private var baseColor: Color {
if colorScheme == .dark {
return isOuterSurface
- ? Color(red: 0.07, green: 0.08, blue: 0.095)
- : Color(red: 0.16, green: 0.18, blue: 0.20)
+ ? Color(red: 0.07, green: 0.08, blue: 0.095)
+ : Color(red: 0.16, green: 0.18, blue: 0.20)
}
return isOuterSurface
- ? Color(red: 0.97, green: 0.985, blue: 1.0)
- : Color.white
+ ? Color(red: 0.97, green: 0.985, blue: 1.0)
+ : Color.white
}
private var raisedHighlightShadowColor: Color {
@@ -213,17 +213,16 @@ private struct LiquidGlassFrostedTexture: View {
let baseOpacity = colorScheme == .dark ? 0.035 : 0.045
let outerScale = isOuterSurface ? 0.75 : 1
- for row in 0..<rows {
- for column in 0..<columns {
+ for row in 0 ..< rows {
+ for column in 0 ..< columns {
let sample = Self.noise(column: column, row: row)
let isHighlight = sample >= 0.5
let strength = isHighlight ? (sample - 0.5) * 2 : (0.5 - sample) * 2
let opacity = baseOpacity * strength * outerScale
- let color: Color
- if isHighlight {
- color = Color.white.opacity(opacity)
+ let color = if isHighlight {
+ Color.white.opacity(opacity)
} else {
- color = Color.black.opacity(opacity * (colorScheme == .dark ? 0.24 : 0.16))
+ Color.black.opacity(opacity * (colorScheme == .dark ? 0.24 : 0.16))
}
let rect = CGRect(
x: CGFloat(column) * step,
@@ -296,8 +295,8 @@ private struct LiquidGlassCapsule: View {
private var baseColor: Color {
colorScheme == .dark
- ? Color(red: 0.16, green: 0.18, blue: 0.20)
- : Color.white
+ ? Color(red: 0.16, green: 0.18, blue: 0.20)
+ : Color.white
}
}
diff --git a/Docs/AppServer.md b/Docs/AppServer.md
index 0d5bc64..71ca481 100644
--- a/Docs/AppServer.md
+++ b/Docs/AppServer.md
@@ -51,6 +51,8 @@ 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`。
认证失败时,同会话最多调用一次 `account/read(refreshToken:true)` 后重试原读取。
@@ -111,7 +113,7 @@ UI 只展示「未登录」和「初始化失败」两类特殊状态;具体
- 带 id 的 JSON-RPC 请求先记录为进行,响应或错误到达后回填到同一条。
- `initialized` 这类无 id 请求记录为空响应。
-- 日志容量上限 500 条,单条详情上限 4000 字符。
+- 日志容量上限 500 条,请求 payload 预览上限 4000 字符;响应和错误详情不按长度截断。
- 合法 JSON 通过 `JSONSerialization` 重新序列化,使用 `.sortedKeys` 和 `.withoutEscapingSlashes`。
- 非 JSON 错误消息保持原样。
- 不要把子进程 stderr 直接展示给用户。
diff --git a/Docs/CodexHook.md b/Docs/CodexHook.md
index c898cbd..ae1cbcf 100644
--- a/Docs/CodexHook.md
+++ b/Docs/CodexHook.md
@@ -10,14 +10,35 @@
~/.codex/hooks.json
```
-开启和关闭都会先移除当前 App 可执行文件路径对应的 CodexBar hook。开启时随后按当前 App 路径安装 hook。用户自定义 Hook、其他 App Hook、其他路径的 CodexBar Hook 和同事件下的其他处理器必须保留。
+开启前会先复用 App 当前的 Codex app-server 会话调用 `config/read`。如果有效配置中 `[features] hooks = false`,或兼容旧名 `codex_hooks = false`,CodexBar 不写入 `hooks.json`,并在 Hook 选项下方显示全局禁用说明。
+
+开启和关闭都会先移除 `command` 包含当前 App 可执行文件路径的 CodexBar hook。开启时随后按当前 App 路径安装 hook。用户自定义 Hook、其他 App Hook 和同事件下的其他处理器必须保留。
CodexBar 处理器的识别条件:
- `type` 是 `command`
-- `command` 必须等于当前 App 可执行文件路径生成的命令, 例如 `'<当前 CodexBar 可执行文件路径>' --hook-event SessionStart`
+- `command` 必须包含当前 App 可执行文件路径生成的 shell 命令, 例如 `'<当前 CodexBar 可执行文件路径>'`
+
+也就是说,如果用户手写的 Hook 命令同样包含当前 CodexBar 可执行文件路径,也会被当作当前 CodexBar 处理器移除;不包含当前路径的用户 Hook 会保留。
+
+检测是否已开启时,只要任意 CodexBar 事件存在当前 App 路径对应的处理器,开关就保持开启;如果缺少部分事件,`hooks/list` 验证会在 Hook 选项下方显示 `CodexBar Hook 已不完整`。
+
+开启写入成功后会复用同一条 app-server 会话调用 `hooks/list` 做有效性检查:
+
+- `command`: 必须包含 CodexBar 当前可执行文件路径生成的命令。
+- `eventName`: 必须覆盖全部 CodexBar 事件;`hooks/list` 返回值使用 `sessionStart` 这类 lower camel 名称,CodexBar 会与写入的 `SessionStart` 配置名做映射。
+- `enabled`: 必须为 `true`,否则提示 Codex 已禁用这些 Hook。
+- `sourcePath`: 必须指向全局 `~/.codex/hooks.json`。
+- `trustStatus`: `untrusted` 或 `modified` 时提示用户在 Codex 中执行 `/hooks` 并信任 CodexBar。
+- `warnings` / `errors`: 参与验证优先级判断;设置页只显示最高优先级问题,完整返回内容进入日志窗口。
+
+`config/read` 和 `hooks/list` 都通过 `AppServerSession.request` 调用,请求和响应会进入 CodexBar 日志窗口。
-检测是否已开启时,要求全部 CodexBar 事件都存在当前 App 路径对应的处理器。
+`config/read` 请求失败时,CodexBar 不写入 `hooks.json`,调用 `refresh()` 恢复本地实际状态,并在 Hook 选项下方显示 `设置 Codex Hook 失败: <错误>`。只有请求成功且明确读到全局禁用 Hook 时,才显示 `Codex 配置已禁用 Hook`。
+
+`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` 归一化到同一组事件。
## Hook 事件
@@ -39,25 +60,20 @@ SubagentStop
命令格式:
```bash
-'/Applications/CodexBar.app/Contents/MacOS/CodexBar' --hook-event SessionStart
+'/Applications/CodexBar.app/Contents/MacOS/CodexBar'
```
-Hook timeout 为 5 秒。App 启动最早阶段会调用 `WorkflowHookEventRecorder.handleIfRequested()`,如果命中 Hook 参数,只记录数据并立即退出正常 App 启动流程。
-
-支持的参数形式:
+Hook timeout 为 5 秒。App 启动最早阶段会调用 `WorkflowHookEventRecorder.handleIfRequested()`,如果识别到 Hook 输入,只记录数据并立即退出正常 App 启动流程。
-```bash
---hook-event SessionStart
---hook-event=SessionStart
-```
+Hook 子进程通过 stdin payload 顶层 `hook_event_name` 判断事件名。
## Payload 解析
-Hook stdin 会尝试解析为 Codex 官方 JSON 对象,只读取顶层字段。缺少字段时尽量兜底,不阻断记录。
+Hook stdin 会尝试解析为 Codex 官方 JSON 对象,只读取顶层字段。`hook_event_name` 是记录事件的必需字段;其他字段缺失时尽量兜底,不阻断记录。
读取字段:
-- 事件: `hook_event_name`,缺失时回退 Hook 命令参数 `--hook-event`
+- 事件: `hook_event_name`
- 目录: `cwd`
- 工具: `tool_name`
- 模型: `model`
@@ -65,7 +81,7 @@ Hook stdin 会尝试解析为 Codex 官方 JSON 对象,只读取顶层字段
- 会话: `session_id`
- 轮次: `turn_id`
-事件名优先来自 payload 顶层 `hook_event_name`;缺失时回退 Hook 命令参数 `--hook-event`。`--hook-event` 仍用于识别当前进程是否是 Hook 子进程,避免普通 App 启动时读取 stdin。事件时间优先读取 payload 顶层 `timestamp`,解析后按本机时区写成 `yyyy-MM-dd HH:mm:ss.SSS`;如果 payload 缺失或无法解析,记录当前时间作为兜底。同一个事件时间也会按本机时区格式化为 `yyyy-MM-dd` 的 date key,用于选择 `events/YYYY-MM-DD.jsonl` 文件。每行按固定顺序写入 `timestamp`、`event`、`model`、`permission`、`session`、`turn`、`tool`、`cwd`;缺失值写为 `null`。
+事件名来自 payload 顶层 `hook_event_name`。没有事件名且 stdin 没有输入时按普通 App 启动;stdin 有输入但事件名缺失时吞掉本次 Hook,避免 Hook 子进程继续启动完整菜单栏 App。事件时间优先读取 payload 顶层 `timestamp`,解析后按本机时区写成 `yyyy-MM-dd HH:mm:ss.SSS`;如果 `timestamp` 缺失或无法解析,记录当前时间作为兜底。同一个事件时间也会按本机时区格式化为 `yyyy-MM-dd` 的 date key,用于选择 `events/YYYY-MM-DD.jsonl` 文件。每行按固定顺序写入 `timestamp`、`event`、`model`、`permission`、`session`、`turn`、`tool`、`cwd`;缺失值写为 `null`。
事件名统计时会去掉 `_` 和 `-` 并转小写,因此 `PreToolUse`、`pre_tool_use`、`pre-tool-use` 会归为同一个事件。
diff --git a/Docs/DevelopmentGuide.md b/Docs/DevelopmentGuide.md
index 0520e3f..672d93c 100644
--- a/Docs/DevelopmentGuide.md
+++ b/Docs/DevelopmentGuide.md
@@ -24,10 +24,10 @@ App 通过本机 Codex app-server 读取账号, 额度和 token 用量, 通过 C
| 目录 | 职责 |
| ----------------------- | ----------------------------------------------------------------------- |
| `CodexBar/App/` | SwiftUI 入口和 AppDelegate 启动分支 |
-| `CodexBar/Controllers/` | 菜单栏, 菜单面板, 设置窗口, 日志窗口和窗口行为 |
+| `CodexBar/Controllers/` | 菜单栏, 菜单面板, 设置窗口, 日志窗口和窗口行为 |
| `CodexBar/Models/` | account, quota, usage, workflow stats, 日期网格和错误模型 |
| `CodexBar/Services/` | app-server, Codex CLI 解析, 版本探测, Hook 设置, 统计维护, 更新, 登录项 |
-| `CodexBar/Views/` | 菜单面板, 设置窗口, 日志窗口和共享 Liquid Glass 样式 |
+| `CodexBar/Views/` | 菜单面板, 设置窗口, 日志窗口和共享 Liquid Glass 样式 |
| `Docs/` | app-server, Hook 和开发文档 |
| `Scripts/` | DMG 和 appcast 发布脚本 |
@@ -36,7 +36,7 @@ App 通过本机 Codex app-server 读取账号, 额度和 token 用量, 通过 C
两条主数据链路:
- Codex app-server 链路: `CodexStatusService` 启动或复用本机 app-server, 生成 `CodexQuotaSnapshot`, 由 `CodexStatusViewModel` 发布给菜单栏 UI
-- Codex Hook 链路: Codex 进程触发 Hook 命令, CodexBar 以 `--hook-event` 模式快速写入 JSONL; 主 App 后续维护聚合并生成 `WorkflowStatsSnapshot`
+- Codex Hook 链路: Codex 进程触发 Hook 命令, CodexBar 从 stdin payload 读取 `hook_event_name` 并快速写入 JSONL; 主 App 后续维护聚合并生成 `WorkflowStatsSnapshot`
## 3. 启动流程
@@ -340,7 +340,8 @@ codex app-server --listen stdio://
`RequestLogStore` 是常驻全局日志:
- 容量上限 500 条
-- 单条详情上限 4000 字符
+- 请求 payload 预览上限 4000 字符
+- 响应和错误详情不按长度截断
- 合法 JSON 会稳定化显示, 非 JSON 错误消息保持原样
- storage 用 `NSLock` 保护, SwiftUI 通知切回主线程发送
- 日志窗口关闭不会清空日志
@@ -394,25 +395,30 @@ app-server 与状态刷新错误:
| `initialized` 无 id 通知 | 记录为"请求", 不等待响应 |
| 进程级错误没有 method | 日志行直接预览错误文本 |
| 合法 JSON 内容 | 重新序列化为稳定顺序并保留未转义斜杠 |
-| 超长详情 | 截断到 4000 字符 |
+| 超长请求 payload | 请求预览截断到 4000 字符 |
+| 超长响应或错误详情 | 不按长度截断 |
设置, Hook 和更新错误:
-| 错误来源 | 检测位置 | 用户可见状态 | 重试或降级 |
-| -------------------------------- | -------------------------------------------------------- | ----------------------------------------- | ------------------------------------------------ |
-| 登录项注册或取消失败 | `LoginItemSettings.setEnabled` | 设置窗口中部错误组显示"设置开机启动失败" | 调用 `refresh()` 恢复实际状态 |
-| `hooks.json` 读取失败或结构非法 | `CodexHookSettings.refresh` | Hook 开关视为关闭, 中部错误组显示读取失败 | 不写配置 |
-| Hook 开关写入失败 | `CodexHookSettings.setEnabled` | 中部错误组显示"设置 Codex Hook 失败" | 调用 `refresh()` 恢复实际状态 |
-| 快捷键无法识别或不符合规则 | `HotKeyRecorderRow` / `GlobalHotKeySettings.setShortcut` | 快捷键行内显示红色错误 | 用户清除后重新录制 |
-| 快捷键注册冲突 | `StatusItemController.applyGlobalHotKey` | 快捷键行内显示占用提示 | 恢复上一个已注册快捷键 |
-| Hook 子进程 payload 不是 JSON | `WorkflowHookEventRecorder.stdinPayload` | 无 UI 提示 | 使用空 payload 和 fallback 字段继续记录 |
-| Hook 子进程写入失败 | `WorkflowHookEventRecorder.handleIfRequested` | 无 UI 提示 | `try? record` 吞掉错误并正常退出, 避免阻断 Codex |
-| `daily.jsonl` 缺失, 空文件或坏行 | `WorkflowStatsService.prepareMaintenanceTasksOnQueue` | 热力图详情面板可能暂时显示 0 | 标记 dirty, 后续从 events 文件重建 |
-| events 文件变小或 offset 不一致 | `WorkflowStatsService.reconcileEventFiles` | 热力图详情面板可能暂时显示旧聚合 | 标记 dirty, 从头重建当天聚合 |
-| 单个维护任务失败 | `WorkflowStatsService.performMaintenanceIfNeededOnQueue` | 使用已有 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.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.prepareMaintenanceTasksOnQueue` | 热力图详情面板可能暂时显示 0 | 标记 dirty, 后续从 events 文件重建 |
+| events 文件变小或 offset 不一致 | `WorkflowStatsService.reconcileEventFiles` | 热力图详情面板可能暂时显示旧聚合 | 标记 dirty, 从头重建当天聚合 |
+| 单个维护任务失败 | `WorkflowStatsService.performMaintenanceIfNeededOnQueue` | 使用已有 daily 或空 snapshot | 对应日期标记 dirty |
+| Sparkle 配置缺失 | `AppUpdater.init` | 更新开关禁用, 操作显示"未配置更新资源" | 不创建 updater controller |
+| 手动检查没有更新 | `updaterDidNotFindUpdate` | 显示"没有可用更新" | 1 秒后自动清理状态 |
+| 手动检查失败 | `didAbortWithError` | 显示"检查更新失败" | 不展示底层错误细节 |
Codex 版本探测错误:
@@ -545,18 +551,21 @@ Hook 开启且当天没有 token bucket 时, 今天的 token 数显示 `--`。
## 10. Codex Hook 开启后完整流程
-设置页"启用 Codex Hook"由 `CodexHookSettings` 管理, 配置文件是:
+设置页"启用 Codex Hook"由 `CodexHookSettings` 管理, Hook 写入文件是:
```text
~/.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 请求和响应都会进入日志窗口。
+
下面的时序图展示开启 Hook, Codex 触发事件, 本机写入, 后台维护, 以及常见错误后的处理
```mermaid
sequenceDiagram
participant User as 用户
participant Settings as 设置界面
+ participant Server as app-server
participant Config as Hook 配置读写
participant File as 全局 Hook 配置
participant Codex as Codex 运行过程
@@ -566,21 +575,36 @@ sequenceDiagram
participant Detail as 热力图详情面板
User->>Settings: 打开启用 Hook
- Settings->>Config: 请求写入 Hook 配置
- Config->>File: 读取现有配置
-
- alt 配置结构非法或读取失败
- Config-->>Settings: 开关恢复实际状态并显示错误
- else 文件不存在或读取成功
- Config->>Config: 使用空配置或现有配置
- Config->>Config: 移除当前 App 路径的旧处理器
- Config->>Config: 保留用户已有处理器和其他 App 处理器
- Config->>Config: 为 10 个事件追加命令处理器
- Config->>File: 原子写回配置
- alt 写入失败
- Config-->>Settings: 刷新实际状态并显示设置失败
- else 写入成功
- Config-->>Settings: 开关显示已启用
+ Settings->>Server: config/read 检查全局 Hook 开关
+ alt config/read 请求失败
+ Server-->>Settings: 不写配置, 刷新本地状态并显示设置失败
+ else Codex 全局禁用 Hook
+ Server-->>Settings: Hook 选项下方显示禁用说明
+ else Hook 未被全局禁用
+ Settings->>Config: 请求写入 Hook 配置
+ Config->>File: 读取现有配置
+
+ alt 配置结构非法或读取失败
+ Config-->>Settings: 开关恢复实际状态并显示错误
+ else 文件不存在或读取成功
+ Config->>Config: 使用空配置或现有配置
+ Config->>Config: 移除 command 包含当前 App 路径的旧处理器
+ Config->>Config: 保留用户已有处理器和其他 App 处理器
+ Config->>Config: 为 10 个事件追加命令处理器
+ Config->>File: 原子写回配置
+ alt 写入失败
+ Config-->>Settings: 刷新实际状态并显示设置失败
+ else 写入成功
+ Config-->>Settings: 开关显示已启用
+ Settings->>Server: hooks/list 验证 Codex 实际识别结果
+ alt hooks/list 请求失败
+ Server-->>Settings: 保留已写入 Hook, 显示无法验证
+ else command, eventName, enabled, sourcePath, trustStatus, warnings 或 errors 异常
+ Server-->>Settings: Hook 选项下方显示验证说明
+ else 验证通过
+ Server-->>Settings: 清空 Hook 错误提示
+ end
+ end
end
end
@@ -640,23 +664,29 @@ sequenceDiagram
每个处理器形如:
```bash
-'<当前 CodexBar 可执行文件路径>' --hook-event SessionStart
+'<当前 CodexBar 可执行文件路径>'
```
-识别和移除 CodexBar 自己的 Hook 时必须同时满足:
+Hook 事件定义集中在 `CodexHookEvent`:
+
+- `configName`: 写入 `hooks.json` 使用, 例如 `SessionStart`
+- `appServerName`: 验证 `hooks/list` 使用, 例如 `sessionStart`
+- `init(eventName:)`: 统计 events 使用, 会把 `PreToolUse`, `pre_tool_use`, `pre-tool-use` 归一化到同一事件
+
+识别和移除当前 CodexBar 处理器时必须同时满足:
- handler 是 JSON 对象
- `type == "command"`
-- `command` 等于当前 App 可执行路径生成的命令
+- `command` 包含当前 App 可执行路径生成的 shell 命令
这意味着:
- 用户已有 Hook 会被保留
- 其他 App Hook 会被保留
-- 其他路径的 CodexBar Hook 不会被当作当前 App Hook 删除
- 同一事件下其他处理器会被保留
+- 如果用户自定义 Hook 命令中也包含当前 CodexBar 可执行路径, 会被当作当前 CodexBar 处理器删除
-检测是否已开启时, 要求全部 CodexBar 事件都存在当前 App 路径对应的 handler
+检测是否已开启时, 只要任意 CodexBar 事件存在当前 App 路径对应的 handler, 开关就保持开启。缺少部分事件时, `hooks/list` 验证会在 Hook 选项下方显示"CodexBar Hook 已不完整"。
## 11. Hook 事件写入流程
@@ -694,9 +724,9 @@ sequenceDiagram
| `session_id` | `session` |
| `turn_id` | `turn` |
-`hook_event_name` 缺失时回退命令参数 `--hook-event`;`--hook-event` 仍用于识别当前进程是否是 Hook 子进程。
+`hook_event_name` 是 Hook 事件来源。如果 stdin 有输入但缺失事件名, 记录器会吞掉本次 Hook, 避免 Hook 子进程启动完整菜单栏 App。
-缺失字段不阻断写入:
+除 `hook_event_name` 外, 缺失字段不阻断写入:
- `timestamp` 缺失或无法解析时使用当前时间
- `cwd` 缺失时使用当前工作目录
@@ -778,36 +808,41 @@ UI 展示指标来自 `WorkflowDailyAggregate.stats`:
设置窗口由 `SettingsWindowController` 打开, 内容是 `AppSettingsView`
-`onAppear` 时刷新:
+`SettingsWindowController.open()` 每次打开设置窗口时刷新:
-- `LoginItemSettings.refresh()`
- `CodexHookSettings.refresh()`
+- `CodexHookSettings.verifyInstalledHooks()`
+
+`AppSettingsView.onAppear` 时刷新:
+
+- `LoginItemSettings.refresh()`
- `AppUpdater.refreshAutomaticCheckSetting()`
- `CodexCLIVersionViewModel.refresh()`
- `CodexStatusViewModel.refreshCodexConnectionInfo()`
-App 再次成为 active 时, 也会刷新 Codex 版本区
+App 再次成为 active 时, 也会刷新 Codex 版本区, 并在已安装 Hook 时重新运行 `hooks/list` 验证。
版本探测内部有 60 秒节流, 避免 `onAppear` 和 `didBecomeActive` 连续触发时重复启动子进程
设置项:
-| 设置项 | 状态源 | 写入行为 |
-| --------------- | ---------------------------------------------------- | ------------------------------------ |
-| 开机自动启动 | `SMAppService.mainApp.status` | `register()` / `unregister()` |
-| 自动检查更新 | Sparkle updater | 设置 `automaticallyChecksForUpdates` |
-| 使用快捷键 | `GlobalHotKeySettings.shortcut` | 写入 `UserDefaults` 并注册 hot key |
-| 启用 Codex Hook | `~/.codex/hooks.json` | 追加或移除当前 CodexBar command hook |
-| CodexBar 版本 | Bundle + AppUpdater 状态 | 有更新状态时优先显示动态消息 |
-| Codex 版本 | `CodexCLIVersionSnapshot` + 当前 app-server 握手信息 | 路径点击复制到剪贴板 |
+| 设置项 | 状态源 | 写入行为 |
+| --------------- | -------------------------------------------------------------- | -------------------------------------------------------- |
+| 开机自动启动 | `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 状态 | 有更新状态时优先显示动态消息 |
错误显示:
-- 开机启动失败和 Hook 设置失败显示在设置组与底部按钮组之间的独立错误组
-- 没有登录项或 Hook 错误时不渲染错误组
+- 开机启动失败显示在设置组与底部按钮组之间的独立错误组
+- Hook 设置失败, 全局禁用, `hooks/list` 未信任或验证异常显示在 Hook 选项下方
+- 没有登录项错误时不渲染错误组
- 快捷键无法识别, 规则不合法或注册冲突显示在快捷键行内
- 更新检查状态显示在 CodexBar 版本行
-- Hook 开关说明只展示辅助说明, 不展示启用或关闭状态文案
+- Hook 开关下方只在必要时展示错误, 不展示辅助说明、启用或关闭状态文案
## 14. Codex CLI 解析与版本探测
@@ -888,7 +923,7 @@ App 再次成为 active 时, 也会刷新 Codex 版本区
日志只记录经过 `RequestLogStore` 的请求和错误
-为了保护隐私, 不直接展示 app-server stderr, Codex auth 文件内容或未截断的长响应
+为了保护隐私, 不直接展示 app-server stderr 或 Codex auth 文件内容。app-server 响应和错误详情会完整保留在日志窗口中, 不按长度截断。
## 17. 发布脚本流程
@@ -933,12 +968,12 @@ App 再次成为 active 时, 也会刷新 Codex 版本区
- Hook 子进程只在锁内追加当天 `events/YYYY-MM-DD.jsonl` 并更新 `maintenance.json`
- 主 App 维护 `daily.jsonl` 时, 先锁外原子写 daily, 再短暂持锁提交维护状态, 减少阻塞 Hook 写入
- `maintenance.json` 和 `daily.jsonl` 使用 atomic write
-- 设置 Hook 时 pretty printed 写回 `~/.codex/hooks.json`, 但只移除当前 App 可执行路径对应的 handler
+- 设置 Hook 时通过当前 app-server 会话先读 `config/read`, 未全局禁用时 pretty printed 写回 `~/.codex/hooks.json`, 只移除 command 包含当前 App 可执行路径的 handler, 写入后再用 `hooks/list` 验证有效状态
隐私和敏感信息边界:
- 不展示 app-server stderr
- 不读取或展示 Codex auth 文件内容
- 不把原始敏感 RPC 响应写入文档或测试夹具
-- 日志详情截断到 4000 字符
+- 日志请求 payload 预览截断到 4000 字符; 响应和错误详情不按长度截断
- Hook 统计只保存在用户 Application Support 的 CodexBar 目录
diff --git a/README.md b/README.md
index ed1a3ec..e8a4c69 100644
--- a/README.md
+++ b/README.md
@@ -39,6 +39,8 @@ CodexBar 可以在设置中开启「启用 Codex Hook」
开启后会在全局 `~/.codex/hooks.json` 中增加以下 Hook,用于接收 Codex 的会话、工具调用、权限请求、上下文压缩和子智能体事件。
+开启前会通过本机 Codex app-server 检查全局 `config.toml` 是否禁用了 Hook;如果已禁用,CodexBar 不会写入配置,并会在 Hook 选项下方提示。写入后还会用 `hooks/list` 确认 CodexBar 自己的 Hook 命令、事件、来源、启用状态、信任状态以及 Codex 返回的警告或错误。
+
- `SessionStart`: 记录一次 Codex 会话开始,用于统计会话总数
- `UserPromptSubmit`: 记录用户提交提示词事件,保留为原始活动事件
- `PreToolUse`: 记录工具调用开始
@@ -53,12 +55,12 @@ CodexBar 可以在设置中开启「启用 Codex Hook」
每个事件都会追加一个 `command` 类型的 Hook,命令形如:
```bash
-'/Applications/CodexBar.app/Contents/MacOS/CodexBar' --hook-event SessionStart
+'/Applications/CodexBar.app/Contents/MacOS/CodexBar'
```
开启后,用量热力图会包含今天;鼠标悬停到任意一天时,弹窗会在 token 数之外展示当天的会话总数、对话轮次、子智能体、工具调用、权限请求和上下文压缩次数。关闭 Hook 时,弹窗只展示日期和 token 数;如果 app-server 尚未返回当天 token 数据,热力图不会额外占位展示今天。
-CodexBar 只会追加或移除自己安装的 Hook,不会删除你已有的其他 Codex Hook。
+CodexBar 只会追加或移除 command 中包含当前 CodexBar 可执行路径的 Hook,不会删除其他 Codex Hook。
统计数据只保存在本机 `~/Library/Application Support/CodexBar/HookEvents/`,不会发送给任何个人或第三方服务。
diff --git a/appcast.xml b/appcast.xml
index 2698719..89459fa 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.0</title>
+ <sparkle:version>24</sparkle:version>
+ <sparkle:shortVersionString>3.1.0</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.1.0</sparkle:releaseNotesLink>
+ <pubDate>Wed, 24 Jun 2026 20:18:38 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.1.0.dmg" sparkle:edSignature="FppmuKHgGue1IKo9TCjzm7hmoE2YjPKPnXKHNIh4mbhn9fkHs5qcSsjCq9pygIwr3ZqkJbQ+3u49bBcvPAexBA==" length="3084556" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.0.0</title>
<sparkle:version>23</sparkle:version>