Skip to content

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

feat: 完善日志预览与 Hook 记录

Bobb0371907af6c
diff --git a/.swiftformat b/.swiftformat
index eb8f268..80fdc0e 100644
--- a/.swiftformat
+++ b/.swiftformat
@@ -49,8 +49,5 @@
--void-type Void
--some-any true
-# 保持格式化结果可预期, 不自动重排源码结构
---disable markTypes,organizeDeclarations,sortDeclarations,trailingClosures,enumNamespaces,preferForLoop
-
-# 多行 guard 大括号不换行
+# 大括号不换行
--disable wrapMultilineStatementBraces
diff --git a/AGENTS.md b/AGENTS.md
index 6489897..a5cb545 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -64,7 +64,7 @@ git status --short
- 平台: SwiftUI + AppKit + MVVM, 最低 macOS 15.0。
- 应用形态: `LSUIElement` 菜单栏应用, 无 Dock 图标、无主窗口。
- 外部依赖: Sparkle(SwiftPM)。
-- 当前 build settings: `MACOSX_DEPLOYMENT_TARGET = 15.0`, `MARKETING_VERSION = 2.4.5`, `CURRENT_PROJECT_VERSION = 21`, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`。
+- 当前 build settings: `MACOSX_DEPLOYMENT_TARGET = 15.0`, `MARKETING_VERSION = 3.1.1`, `CURRENT_PROJECT_VERSION = 25`, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`, `SWIFT_VERSION = 6.0`。
- App Sandbox 必须保持关闭(`ENABLE_APP_SANDBOX = NO`), 因为应用要启动本机 Codex CLI/APP 内置 CLI, 并读取真实 macOS 用户的 Codex 登录状态。
- 工程使用 `PBXFileSystemSynchronizedRootGroup`; 新增或删除 `CodexBar/` 下 Swift 文件通常无需改 `project.pbxproj`。只有依赖、target/build settings 或资源归属变更才改 Xcode 工程文件。
- Swift 源码按目录组织: `App/`、`Controllers/`、`Models/`、`Services/`、`Views/`。不要把新 Swift 文件直接放回 `CodexBar/` 根层。
@@ -81,7 +81,7 @@ CodexStatusService(JSON-RPC app-server)
-> CodexStatusMenuView / AppSettingsView / LogView
Codex Hook
- -> WorkflowHookEventRecorder(stdin hook_event_name)
+ -> WorkflowHookEventRecorder(--hook-event 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)。
-- 设置开关只能追加或移除 command 包含当前 CodexBar 可执行路径的 Hook 处理器, 不能破坏其他用户 Hook。
-- Hook 命令写入当前 CodexBar 可执行文件路径; Hook 事件名来自 Codex 传入的 stdin payload 顶层 `hook_event_name`。
+- 设置开关只能追加或移除 command 同时包含当前 CodexBar 可执行路径和 `--hook-event` 参数的 Hook 处理器, 不能破坏其他用户 Hook。
+- Hook 命令写入当前 CodexBar 可执行文件路径和 `--hook-event` 参数; Hook 事件名来自 Codex 传入的 stdin payload 顶层 `hook_event_name`。
- Hook 数据只保存在 `~/Library/Application Support/CodexBar/HookEvents/`。
- Hook 写入可能并发触发, 追加 `events/YYYY-MM-DD.jsonl` 并更新 `maintenance.json` 时必须通过 `stats.lock` 加锁。
@@ -150,12 +150,13 @@ Hook 统计的配置、存储、保留策略和统计口径见 [Docs/CodexHook.m
工程开启 `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; 未显式标注的类型会推断为 MainActor 隔离。
- UI 层保持 `@MainActor`: app delegate、status item controller、window controllers、view models、settings/updater。
-- 服务层对外暴露 async API, 内部用串行 queue 管理 `Process`、`Pipe` 和连接状态。
+- 服务层对外暴露 async API, 共享可变状态优先由 actor 隔离。
- 非 UI 类型、DTO、模型、服务辅助类型和静态工具需要显式 `nonisolated`, 避免 main actor 隔离泄漏到同步服务代码。
-- `CodexStatusService` 使用 `CodexBar.app-server` 队列。
-- `CodexCLIVersionService` 使用 `CodexBar.codex-version` 队列, 全局和内置版本探测先并发启动再收集。
-- `RequestLogStore` 可从后台队列写入, storage 用锁保护, SwiftUI 通知切回主线程发送。
-- `WorkflowStatsService` 使用 `CodexBar.workflow-stats` 队列读取快照。
+- `CodexStatusService` 是 actor, 负责 app-server 连接、缓存和重建。
+- `CodexCLIVersionService` 是 actor, 全局和内置版本探测用 `async let` 并发启动; 子进程输出通过 `PipeReadBuffer` 收集。
+- `WorkflowStatsService` 是 actor, 串行维护和读取 workflow stats 快照。
+- `RequestLogStorage` 可从后台同步写入, 用 `OSAllocatedUnfairLock` 保护; `@MainActor RequestLogStore` 只负责发布 SwiftUI 快照。
+- `PipeReadBuffer` 是底层 `FileHandle`、`DispatchSourceRead` 和 semaphore 的唯一 `@unchecked Sendable` 边界, 读队列 `CodexBar.pipe-read` 使用 `.userInitiated` QoS。
- Hook 写入可能由多个 Codex 进程并发触发, 必须通过 `stats.lock` 和 `flock` 保护 `events/YYYY-MM-DD.jsonl` 和 `maintenance.json` 的一致性; `daily.jsonl` 由主 App 刷新维护流程写回。
## UI 约束
@@ -210,8 +211,8 @@ Hook 统计的配置、存储、保留策略和统计口径见 [Docs/CodexHook.m
日志窗口:
- 通过右键菜单「日志」打开。
-- 日志窗口应持续显示全局 `RequestLogStore.shared` 中的记录, 不因窗口关闭丢失。
-- 详情文本必须可选择; 请求 payload 预览由存储层截断到 4000 字符, 响应和错误详情不按长度截断。
+- 日志窗口应持续显示全局 `RequestLogStorage.shared` 中的记录, 通过 `@MainActor RequestLogStore.shared` 发布到 SwiftUI, 不因窗口关闭丢失。
+- `RequestLogEntry` 保存完整 request/detail; 列表摘要和行内展开只显示单行短预览, 非空请求/响应标题行提供预览和复制完整内容; 预览视图对 JSON 做格式化和高亮。
## Sparkle 更新
@@ -263,8 +264,8 @@ fix: 修复 Codex 状态刷新
Tag:
-- tag 名格式 `v{MARKETING_VERSION}`, 例如 `v2.4.5`。
-- 使用附注 tag: `git tag -a v2.4.5 -m "Release v2.4.5"`。
+- tag 名格式 `v{MARKETING_VERSION}`, 例如 `v3.1.1`。
+- 使用附注 tag: `git tag -a v3.1.1 -m "Release v3.1.1"`。
## 最终检查
diff --git a/CLAUDE.md b/CLAUDE.md
index 4d32772..2e1d8a5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -24,12 +24,12 @@ xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination generic/pla
- app-server 与版本探测**必须使用真实用户 `HOME`/`USER`/`LOGNAME`**,不能回退到 Xcode sandbox/container 的 home。
- 工程使用 `PBXFileSystemSynchronizedRootGroup`:新增/删除 `CodexBar/` 下的 Swift 文件**通常无需改 `project.pbxproj`**;只有依赖、target/build settings、资源归属变更才动工程文件。仅 `Resources/Info.plist` 在同步组里被排除。
- 源码按目录分层:`App/` `Controllers/` `Models/` `Services/` `Views/`。新文件放入对应子目录,不要丢回 `CodexBar/` 根层。
-- `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`:未标注的类型会被推断为 MainActor 隔离。UI 层保持 `@MainActor`;**DTO、模型、服务辅助类型、静态工具必须显式 `nonisolated`**,否则 main actor 隔离会泄漏进同步的服务代码。
+- `SWIFT_VERSION = 6.0`,并开启 `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`:未标注的类型会被推断为 MainActor 隔离。UI 层保持 `@MainActor`;**DTO、模型、服务辅助类型、静态工具必须显式 `nonisolated`**,否则 main actor 隔离会泄漏进同步的服务代码。
- 最低 macOS 15.0;不要为 15 以下添加 SF Symbols 或 SwiftUI API 的 fallback。
## 架构(两条独立数据流)
-应用是 `LSUIElement` 菜单栏程序(无 Dock 图标、无主窗口),入口 `CodexBarApp` 在启动时先分流:若标准输入中有 Codex Hook payload 且顶层 `hook_event_name` 有效,则走 `WorkflowHookEventRecorder` 记录一条 Hook 事件并立即退出,否则正常起 UI。
+应用是 `LSUIElement` 菜单栏程序(无 Dock 图标、无主窗口),入口 `CodexBarApp` 在启动时先分流:若启动参数包含 `--hook-event`,则走 `WorkflowHookEventRecorder` 尝试记录 Hook 事件并立即退出;否则正常起 UI。
**1. 状态/额度流**(实时数据)
@@ -42,27 +42,27 @@ 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、请求 payload 预览 4000 字符、响应和错误详情不截断),不直接展示子进程 stderr。
+- 错误处理哲学:UI 只暴露 `notLoggedIn` / `initializationFailed` 两类特殊状态;所有具体请求/启动/超时/解析错误进 `RequestLogStorage.shared`(容量 500,完整保存 request/detail),日志窗口通过 `@MainActor RequestLogStore.shared` 订阅快照,列表/行内只展示单行短预览,非空请求/响应标题行提供完整预览和复制,预览视图会格式化并高亮 JSON,不直接展示子进程 stderr。
**2. Codex Hook 工作流统计流**(本机统计)
```
-WorkflowHookEventRecorder (stdin hook_event_name 子进程)
+WorkflowHookEventRecorder (--hook-event stdin hook_event_name 子进程)
→ WorkflowStatsStorage (events/YYYY-MM-DD.jsonl / daily.jsonl,~/Library/Application Support/CodexBar/HookEvents/)
→ WorkflowStatsService → WorkflowStatsViewModel
→ UsageSummaryView / UsageHeatmap (统计只在热力图侧边详情面板中展示)
```
-- Hook 命令只写入当前 CodexBar 可执行文件路径,事件名来自 Codex 传入的 stdin payload 顶层 `hook_event_name`。
+- Hook 命令写入当前 CodexBar 可执行文件路径和 `--hook-event` 参数,事件名来自 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 处理器。
+- 设置开关只能追加/移除 `command` 同时包含当前 CodexBar 可执行路径和 `--hook-event` 参数的 Hook 处理器,绝不破坏其他用户 Hook。若用户自定义 Hook 命令也同时包含当前可执行路径和 `--hook-event` 参数,会被视为当前 CodexBar 处理器。
- Hook 写入可能由多个 Codex 进程并发触发,追加 `events/YYYY-MM-DD.jsonl` 并更新 `maintenance.json` 必须经 `stats.lock` + `flock` 加锁;`daily.jsonl` 由主 App 刷新维护流程写回。
- 字段兼容、保留策略、统计口径见 `Docs/CodexHook.md`。
## 并发分工
-服务层对外暴露 async API,内部各用串行 `DispatchQueue` 管理 `Process`/`Pipe`/连接:`CodexBar.app-server`、`CodexBar.codex-version`(全局+内置版本并发探测后收集)、`CodexBar.workflow-stats`。`RequestLogStore` 可后台写入、用锁保护、通知切回主线程。
+服务层对外暴露 async API,主要共享状态由 actor 隔离:`CodexStatusService` 管理 app-server 连接和缓存,`CodexCLIVersionService` 用 `async let` 并发探测全局/内置版本,`WorkflowStatsService` 串行维护本机统计。`RequestLogStorage` 可后台同步写入并用 `OSAllocatedUnfairLock` 保护,`RequestLogStore` 只在 MainActor 发布 SwiftUI 快照。`PipeReadBuffer` 是底层 `FileHandle` / `DispatchSourceRead` / semaphore 的唯一 `@unchecked Sendable` 边界。
## 外部依赖与更新
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxproj
index 9fe8449..98a2434 100644
--- a/CodexBar.xcodeproj/project.pbxproj
+++ b/CodexBar.xcodeproj/project.pbxproj
@@ -277,7 +277,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 24;
+ CURRENT_PROJECT_VERSION = 25;
DEVELOPMENT_TEAM = 4KJ362VJW5;
ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
ENABLE_APP_SANDBOX = NO;
@@ -292,7 +292,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 3.1.0;
+ MARKETING_VERSION = 3.1.1;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
@@ -314,7 +314,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 24;
+ CURRENT_PROJECT_VERSION = 25;
DEVELOPMENT_TEAM = 4KJ362VJW5;
ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
ENABLE_APP_SANDBOX = NO;
@@ -329,7 +329,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 3.1.0;
+ MARKETING_VERSION = 3.1.1;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
diff --git a/CodexBar/Controllers/GlobalHotKeyController.swift b/CodexBar/Controllers/GlobalHotKeyController.swift
index 50edd78..3974db5 100644
--- a/CodexBar/Controllers/GlobalHotKeyController.swift
+++ b/CodexBar/Controllers/GlobalHotKeyController.swift
@@ -3,19 +3,13 @@ import Foundation
final class GlobalHotKeyController {
private let onPressed: @MainActor () -> Void
- private var eventHandler: EventHandlerUPP?
- private nonisolated(unsafe) var eventHandlerRef: EventHandlerRef?
- private nonisolated(unsafe) var hotKeyRef: EventHotKeyRef?
+ private var registration: GlobalHotKeyRegistration?
private var nextHotKeyID: UInt32 = 1
init(onPressed: @escaping @MainActor () -> Void) {
self.onPressed = onPressed
}
- deinit {
- Self.removeRegistration(hotKeyRef: hotKeyRef, eventHandlerRef: eventHandlerRef)
- }
-
func install(shortcut: GlobalHotKeyShortcut) -> Bool {
let newEventHandler = Self.makeEventHandler()
var eventType = EventTypeSpec(
@@ -49,16 +43,18 @@ final class GlobalHotKeyController {
guard status == noErr else {
if let installedHandlerRef {
- RemoveEventHandler(installedHandlerRef)
+ GlobalHotKeyRegistration.remove(hotKeyRef: nil, eventHandlerRef: installedHandlerRef)
}
return false
}
clearCurrentRegistration()
- eventHandler = newEventHandler
- eventHandlerRef = installedHandlerRef
- hotKeyRef = registeredHotKeyRef
+ registration = GlobalHotKeyRegistration(
+ eventHandler: newEventHandler,
+ eventHandlerRef: installedHandlerRef,
+ hotKeyRef: registeredHotKeyRef
+ )
nextHotKeyID &+= 1
return true
}
@@ -68,10 +64,8 @@ final class GlobalHotKeyController {
}
private func clearCurrentRegistration() {
- Self.removeRegistration(hotKeyRef: hotKeyRef, eventHandlerRef: eventHandlerRef)
- hotKeyRef = nil
- eventHandlerRef = nil
- eventHandler = nil
+ registration?.invalidate()
+ registration = nil
}
private func handleHotKeyPressed() {
@@ -94,7 +88,41 @@ final class GlobalHotKeyController {
}
}
- private nonisolated static func removeRegistration(
+ private static let hotKeySignature: OSType = {
+ let scalars = Array("CDBR".unicodeScalars)
+ return scalars.reduce(UInt32(0)) { result, scalar in
+ (result << 8) + scalar.value
+ }
+ }()
+}
+
+private final nonisolated class GlobalHotKeyRegistration {
+ private var eventHandler: EventHandlerUPP?
+ private var eventHandlerRef: EventHandlerRef?
+ private var hotKeyRef: EventHotKeyRef?
+
+ init(
+ eventHandler: EventHandlerUPP,
+ eventHandlerRef: EventHandlerRef?,
+ hotKeyRef: EventHotKeyRef?
+ ) {
+ self.eventHandler = eventHandler
+ self.eventHandlerRef = eventHandlerRef
+ self.hotKeyRef = hotKeyRef
+ }
+
+ deinit {
+ invalidate()
+ }
+
+ func invalidate() {
+ Self.remove(hotKeyRef: hotKeyRef, eventHandlerRef: eventHandlerRef)
+ hotKeyRef = nil
+ eventHandlerRef = nil
+ eventHandler = nil
+ }
+
+ static func remove(
hotKeyRef: EventHotKeyRef?,
eventHandlerRef: EventHandlerRef?
) {
@@ -106,11 +134,4 @@ final class GlobalHotKeyController {
RemoveEventHandler(eventHandlerRef)
}
}
-
- private static let hotKeySignature: OSType = {
- let scalars = Array("CDBR".unicodeScalars)
- return scalars.reduce(UInt32(0)) { result, scalar in
- (result << 8) + scalar.value
- }
- }()
}
diff --git a/CodexBar/Models/CodexUsageModels.swift b/CodexBar/Models/CodexUsageModels.swift
index 7d8acc8..c92efae 100644
--- a/CodexBar/Models/CodexUsageModels.swift
+++ b/CodexBar/Models/CodexUsageModels.swift
@@ -27,7 +27,7 @@ nonisolated struct CodexUsageSnapshot: Equatable {
let dailyBuckets: [DailyUsageBucket]
func tokenCount(on date: Date) -> Int? {
- let startDate = DateFormatter.codexDay.string(from: date)
+ let startDate = CodexDateFormat.dayString(from: date)
return tokensByDate[startDate]
}
@@ -41,7 +41,7 @@ nonisolated struct CodexUsageSnapshot: Equatable {
)
.map { date in
date.map {
- let startDate = DateFormatter.codexDay.string(from: $0)
+ let startDate = CodexDateFormat.dayString(from: $0)
return DailyUsageBucket(
startDate: startDate,
tokens: tokenCountsByDate[startDate] ?? 0
diff --git a/CodexBar/Models/CodexWorkflowStatsModels.swift b/CodexBar/Models/CodexWorkflowStatsModels.swift
index ce7fd87..4a33cf8 100644
--- a/CodexBar/Models/CodexWorkflowStatsModels.swift
+++ b/CodexBar/Models/CodexWorkflowStatsModels.swift
@@ -115,12 +115,12 @@ nonisolated struct WorkflowHookEvent: Decodable, Equatable {
}
private static func date(from string: String) -> Date? {
- DateFormatter.codexLocalTimestamp.date(from: string)
+ CodexDateFormat.localTimestampDate(from: string)
}
func jsonLineData() throws -> Data {
let fields = try [
- WorkflowStatsJSON.field("timestamp", DateFormatter.codexLocalTimestamp.string(from: timestamp)),
+ WorkflowStatsJSON.field("timestamp", CodexDateFormat.localTimestampString(from: timestamp)),
WorkflowStatsJSON.field("event", name),
WorkflowStatsJSON.field("model", modelName),
WorkflowStatsJSON.field("permission", permissionMode),
@@ -201,7 +201,7 @@ nonisolated struct WorkflowStatsSnapshot: Equatable {
)
.map { date in
date.map {
- let startDate = DateFormatter.codexDay.string(from: $0)
+ let startDate = CodexDateFormat.dayString(from: $0)
return statsByDate[startDate] ?? WorkflowDailyStats.empty(startDate: startDate)
}
}
@@ -429,7 +429,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
}
private static func date(from string: String) -> Date? {
- DateFormatter.codexDay.date(from: string)
+ CodexDateFormat.dayDate(from: string)
}
private enum CodingKeys: String, CodingKey {
diff --git a/CodexBar/Models/DateFormatter.swift b/CodexBar/Models/DateFormatter.swift
index 93a6afd..c830dce 100644
--- a/CodexBar/Models/DateFormatter.swift
+++ b/CodexBar/Models/DateFormatter.swift
@@ -1,40 +1,96 @@
import Foundation
-extension DateFormatter {
+nonisolated enum CodexDateFormat {
/// 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
+ static func dayString(from date: Date) -> String {
+ let components = localGregorianCalendar.dateComponents([.year, .month, .day], from: date)
+ guard let year = components.year,
+ let month = components.month,
+ let day = components.day else {
+ return ""
+ }
+
+ return "\(padded(year, toLength: 4))-\(padded(month, toLength: 2))-\(padded(day, toLength: 2))"
+ }
+
+ static func dayDate(from string: String) -> Date? {
+ let parts = string.split(separator: "-", omittingEmptySubsequences: false)
+ guard parts.count == 3,
+ parts[0].count == 4,
+ parts[1].count == 2,
+ parts[2].count == 2,
+ let year = Int(parts[0]),
+ let month = Int(parts[1]),
+ let day = Int(parts[2]),
+ (1 ... 9999).contains(year),
+ (1 ... 12).contains(month),
+ (1 ... 31).contains(day) else {
+ return nil
+ }
+
+ var components = DateComponents()
+ components.calendar = localGregorianCalendar
+ components.timeZone = .autoupdatingCurrent
+ components.year = year
+ components.month = month
+ components.day = day
+
+ guard let date = components.date,
+ dayString(from: date) == string else {
+ return nil
+ }
+
+ return date
}
/// yyyy-MM-dd HH:mm:ss.SSS, Hook 原始事件写入本机时间字符串
- /// DateFormatter 不是线程安全类型, 这里每次返回新实例以避免跨线程共享
- nonisolated static var codexLocalTimestamp: DateFormatter {
+ static func localTimestampString(from date: Date) -> String {
+ localTimestampFormatter().string(from: date)
+ }
+
+ static func localTimestampDate(from string: String) -> Date? {
+ localTimestampFormatter().date(from: string)
+ }
+
+ /// 带小数秒的 ISO8601, 用于读取 Hook payload 中的原始时间戳
+ static func iso8601FractionalDate(from string: String) -> Date? {
+ iso8601FractionalFormatter().date(from: string)
+ }
+
+ /// 不带小数秒的 ISO8601 兜底解析器
+ static func iso8601InternetDateTimeDate(from string: String) -> Date? {
+ iso8601InternetDateTimeFormatter().date(from: string)
+ }
+
+ private static var localGregorianCalendar: Calendar {
+ var calendar = Calendar(identifier: .gregorian)
+ calendar.locale = Locale(identifier: "en_US_POSIX")
+ calendar.timeZone = .autoupdatingCurrent
+ return calendar
+ }
+
+ private static func localTimestampFormatter() -> 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 中的原始时间戳
- /// ISO8601DateFormatter 不是 Sendable, 这里每次返回新实例以避免跨线程共享
- nonisolated static var codexFractional: ISO8601DateFormatter {
+ private static func iso8601FractionalFormatter() -> ISO8601DateFormatter {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return formatter
}
- /// 不带小数秒的 ISO8601 兜底解析器
- nonisolated static var codexInternetDateTime: ISO8601DateFormatter {
+ private static func iso8601InternetDateTimeFormatter() -> ISO8601DateFormatter {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime]
return formatter
}
+
+ private static func padded(_ value: Int, toLength length: Int) -> String {
+ let text = String(value)
+ return String(repeating: "0", count: max(0, length - text.count)) + text
+ }
}
diff --git a/CodexBar/Models/UsageHeatmapDay.swift b/CodexBar/Models/UsageHeatmapDay.swift
index 210832a..51d6445 100644
--- a/CodexBar/Models/UsageHeatmapDay.swift
+++ b/CodexBar/Models/UsageHeatmapDay.swift
@@ -36,7 +36,7 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {
return merge(
tokenDays: tokenDays,
workflowDays: workflowDays,
- todayString: DateFormatter.codexDay.string(from: today),
+ todayString: CodexDateFormat.dayString(from: today),
todayTokenCount: todayTokenCount
)
}
diff --git a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
index 6d20e15..67e2b80 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
@@ -1,5 +1,6 @@
import Combine
import Foundation
+import os
nonisolated struct CodexCLIVersionSnapshot: Equatable {
let global: CodexCLIVersionItem
@@ -100,8 +101,7 @@ nonisolated struct CodexCLIVersionDisplay: Equatable {
}
}
-final nonisolated class CodexCLIVersionService: @unchecked Sendable {
- private let queue = DispatchQueue(label: "CodexBar.codex-version", qos: .utility)
+actor CodexCLIVersionService {
private let timeout: TimeInterval
private static let pipeDrainTimeout: TimeInterval = 0.25
private static let maxPipeOutputBytes = 64 * 1024
@@ -111,63 +111,46 @@ final nonisolated class CodexCLIVersionService: @unchecked Sendable {
}
func fetchSnapshot() async -> CodexCLIVersionSnapshot {
- await withCheckedContinuation { continuation in
- queue.async {
- continuation.resume(returning: Self.fetchSnapshotOnQueue(timeout: self.timeout))
- }
- }
+ await Self.fetchSnapshot(timeout: timeout)
}
- private static func fetchSnapshotOnQueue(timeout: TimeInterval) -> CodexCLIVersionSnapshot {
+ private static func fetchSnapshot(timeout: TimeInterval) async -> CodexCLIVersionSnapshot {
let environment = CodexCLIResolver.environment
let installations = CodexCLIResolver.resolveInstallations(environment: environment)
- // 两个安装源互不依赖, 先并发启动再收集, 避免两个超时串行叠加
- let globalProbe = startProbe(
+ // 两个安装源互不依赖, 并发探测避免两个超时串行叠加
+ async let global = probeVersion(
source: .global,
path: installations.globalPath,
environment: environment,
timeout: timeout
)
- let bundledProbe = startProbe(
+ async let bundled = probeVersion(
source: .bundled,
path: installations.bundledPath,
environment: environment,
timeout: timeout
)
+ let (globalItem, bundledItem) = await (global, bundled)
return CodexCLIVersionSnapshot(
- global: finishProbe(globalProbe),
- bundled: finishProbe(bundledProbe),
+ global: globalItem,
+ bundled: bundledItem,
refreshedAt: Date()
)
}
- private struct RunningProbe {
- let source: CodexCLIExecutableSource
- let path: String
- let process: Process
- let outputCollector: PipeCollector
- let errorCollector: PipeCollector
- let finished: DispatchSemaphore
- let deadline: Date
- }
-
- private enum ProbeOutcome {
- case resolved(CodexCLIVersionItem)
- case running(RunningProbe)
- }
-
- private static func startProbe(
+ private static func probeVersion(
source: CodexCLIExecutableSource,
path: String?,
environment: [String: String],
timeout: TimeInterval
- ) -> ProbeOutcome {
+ ) async -> CodexCLIVersionItem {
guard let path else {
- return .resolved(CodexCLIVersionItem(source: source))
+ return CodexCLIVersionItem(source: source)
}
+ let deadline = Date().addingTimeInterval(timeout)
let process = Process()
process.executableURL = URL(fileURLWithPath: path)
process.arguments = ["--version"]
@@ -175,81 +158,79 @@ final nonisolated class CodexCLIVersionService: @unchecked Sendable {
let standardOutput = Pipe()
let standardError = Pipe()
- let outputCollector = PipeCollector(
+ let outputCollector = PipeReadBuffer(
fileHandle: standardOutput.fileHandleForReading,
maxBytes: Self.maxPipeOutputBytes
)
- let errorCollector = PipeCollector(
+ let errorCollector = PipeReadBuffer(
fileHandle: standardError.fileHandleForReading,
maxBytes: Self.maxPipeOutputBytes
)
- let finished = DispatchSemaphore(value: 0)
+ let exitWaiter = ProcessExitWaiter()
process.standardOutput = standardOutput
process.standardError = standardError
- process.terminationHandler = { _ in finished.signal() }
+ process.terminationHandler = { _ in
+ exitWaiter.finish(true)
+ }
do {
try process.run()
} catch {
- return .resolved(CodexCLIVersionItem(source: source, path: path, errorMessage: "启动失败"))
+ process.terminationHandler = nil
+ stopCollectors(outputCollector: outputCollector, errorCollector: errorCollector)
+ return CodexCLIVersionItem(source: source, path: path, errorMessage: "启动失败")
+ }
+ defer {
+ process.terminationHandler = nil
}
- return .running(RunningProbe(
- source: source,
- path: path,
- process: process,
- outputCollector: outputCollector,
- errorCollector: errorCollector,
- finished: finished,
- deadline: Date().addingTimeInterval(timeout)
- ))
- }
-
- private static func finishProbe(_ outcome: ProbeOutcome) -> CodexCLIVersionItem {
- switch outcome {
- case let .resolved(item):
- return item
- 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: "读取超时")
- }
-
- let output = collectedText(from: probe.outputCollector, deadline: probe.deadline)
- let errorOutput = collectedText(from: probe.errorCollector, deadline: probe.deadline)
+ guard await exitWaiter.wait(timeout: max(0, deadline.timeIntervalSinceNow)) else {
+ terminateTimedOutProbe(
+ process: process,
+ outputCollector: outputCollector,
+ errorCollector: errorCollector
+ )
+ return CodexCLIVersionItem(source: source, path: path, errorMessage: "读取超时")
+ }
- guard probe.process.terminationStatus == 0 else {
- return CodexCLIVersionItem(source: probe.source, path: probe.path, errorMessage: "读取失败")
- }
+ let output = collectedText(from: outputCollector, deadline: deadline)
+ let errorOutput = collectedText(from: errorCollector, deadline: deadline)
- guard let version = firstLine(in: output) ?? firstLine(in: errorOutput) else {
- return CodexCLIVersionItem(source: probe.source, path: probe.path, errorMessage: "版本未知")
- }
+ guard process.terminationStatus == 0 else {
+ return CodexCLIVersionItem(source: source, path: path, errorMessage: "读取失败")
+ }
- return CodexCLIVersionItem(
- source: probe.source,
- path: probe.path,
- version: CodexCLIVersionReader.displayVersion(from: version)
- )
+ guard let version = firstLine(in: output) ?? firstLine(in: errorOutput) else {
+ return CodexCLIVersionItem(source: source, path: path, errorMessage: "版本未知")
}
+
+ return CodexCLIVersionItem(
+ source: source,
+ path: path,
+ version: CodexCLIVersionReader.displayVersion(from: version)
+ )
}
- private static func terminateTimedOutProbe(_ probe: RunningProbe) {
+ private static func terminateTimedOutProbe(
+ process: Process,
+ outputCollector: PipeReadBuffer,
+ errorCollector: PipeReadBuffer
+ ) {
_ = ProcessTermination.terminate(
- probe.process,
+ process,
gracefulTimeout: 0.2,
killTimeout: 0.2
)
- stopCollectors(for: probe)
+ stopCollectors(outputCollector: outputCollector, errorCollector: errorCollector)
}
- private static func stopCollectors(for probe: RunningProbe) {
- _ = probe.outputCollector.stopAndRead()
- _ = probe.errorCollector.stopAndRead()
+ private static func stopCollectors(outputCollector: PipeReadBuffer, errorCollector: PipeReadBuffer) {
+ _ = outputCollector.stopAndRead()
+ _ = errorCollector.stopAndRead()
}
- private static func collectedText(from collector: PipeCollector, deadline: Date) -> String {
+ private static func collectedText(from collector: PipeReadBuffer, deadline: Date) -> String {
let drainTimeout = min(Self.pipeDrainTimeout, max(0, deadline.timeIntervalSinceNow))
_ = collector.waitUntilClosed(timeout: drainTimeout)
return String(bytes: collector.stopAndRead(), encoding: .utf8) ?? ""
@@ -263,70 +244,61 @@ final nonisolated class CodexCLIVersionService: @unchecked Sendable {
}
}
-private final nonisolated class PipeCollector: @unchecked Sendable {
- private let lock = NSLock()
- private let closedSemaphore = DispatchSemaphore(value: 0)
- private let fileHandle: FileHandle
- private let maxBytes: Int
- private var data = Data()
- private var isClosed = false
-
- init(fileHandle: FileHandle, maxBytes: Int) {
- self.fileHandle = fileHandle
- self.maxBytes = max(maxBytes, 0)
- fileHandle.readabilityHandler = { [weak self] handle in
- let availableData = handle.availableData
- guard !availableData.isEmpty else {
- handle.readabilityHandler = nil
- self?.markClosed()
- return
- }
-
- self?.append(availableData)
- }
+private final nonisolated class ProcessExitWaiter: Sendable {
+ private struct State {
+ var continuation: CheckedContinuation<Bool, Never>?
+ var result: Bool?
}
- func waitUntilClosed(timeout: TimeInterval) -> Bool {
- lock.lock()
- let closed = isClosed
- lock.unlock()
+ private let state = OSAllocatedUnfairLock(initialState: State())
- guard !closed else {
- return true
- }
+ func wait(timeout: TimeInterval) async -> Bool {
+ await withTaskCancellationHandler {
+ let timeoutTask = Task { [weak self] in
+ do {
+ try await Task.sleep(for: .seconds(max(0, timeout)))
+ } catch {
+ return
+ }
- return closedSemaphore.wait(timeout: .now() + max(0, timeout)) == .success
- }
+ self?.finish(false)
+ }
+ defer {
+ timeoutTask.cancel()
+ }
- func stopAndRead() -> Data {
- fileHandle.readabilityHandler = nil
- try? fileHandle.close()
+ return await withCheckedContinuation { continuation in
+ let immediateResult: Bool? = state.withLock {
+ if let result = $0.result {
+ return result
+ }
- lock.lock()
- let snapshot = data
- isClosed = true
- lock.unlock()
- closedSemaphore.signal()
+ $0.continuation = continuation
+ return nil
+ }
- return snapshot
+ if let immediateResult {
+ continuation.resume(returning: immediateResult)
+ }
+ }
+ } onCancel: {
+ finish(false)
+ }
}
- private func append(_ chunk: Data) {
- lock.lock()
- defer { lock.unlock() }
+ func finish(_ result: Bool) {
+ let continuation: CheckedContinuation<Bool, Never>? = state.withLock {
+ guard $0.result == nil else {
+ return nil
+ }
- guard data.count < maxBytes else {
- return
+ $0.result = result
+ let continuation = $0.continuation
+ $0.continuation = nil
+ return continuation
}
- data.append(chunk.prefix(maxBytes - data.count))
- }
-
- private func markClosed() {
- lock.lock()
- isClosed = true
- lock.unlock()
- closedSemaphore.signal()
+ continuation?.resume(returning: result)
}
}
@@ -348,14 +320,14 @@ final class CodexCLIVersionViewModel: ObservableObject {
private static let refreshThrottle: TimeInterval = 60
private let service: CodexCLIVersionService
- private var refreshTask: Task<Void, Never>?
+ private let refreshCoordinator = RefreshTaskCoordinator()
init(service: CodexCLIVersionService = CodexCLIVersionService()) {
self.service = service
}
deinit {
- refreshTask?.cancel()
+ refreshCoordinator.cancel()
}
func refresh() {
@@ -365,13 +337,24 @@ final class CodexCLIVersionViewModel: ObservableObject {
}
isRefreshing = true
- refreshTask = Task {
+ refreshCoordinator.start { [weak self] generation in
+ guard let self else {
+ return
+ }
+
+ defer {
+ self.refreshCoordinator.finish(generation) {
+ self.isRefreshing = false
+ }
+ }
+
let snapshot = await service.fetchSnapshot()
- guard !Task.isCancelled else { return }
+ guard refreshCoordinator.canCommit(generation) else {
+ return
+ }
self.snapshot = snapshot
- self.isRefreshing = false
}
}
}
diff --git a/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift b/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift
index 4166710..f5a2649 100644
--- a/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift
+++ b/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift
@@ -1,24 +1,70 @@
import Foundation
-final nonisolated class JSONLineReader: @unchecked Sendable {
+final nonisolated class JSONLineReader {
+ private let buffer: PipeReadBuffer
+
+ init(fileHandle: FileHandle) {
+ buffer = PipeReadBuffer(fileHandle: fileHandle, parsesLines: true)
+ }
+
+ func nextLine(timeout: TimeInterval) -> String? {
+ buffer.nextLine(timeout: timeout)
+ }
+
+ func stop() {
+ buffer.stop()
+ }
+
+ var isClosed: Bool {
+ buffer.hasNoMoreLines
+ }
+}
+
+final nonisolated class PipeDrain {
+ private let buffer: PipeReadBuffer
+
+ init(fileHandle: FileHandle) {
+ buffer = PipeReadBuffer(fileHandle: fileHandle)
+ }
+
+ func stop() {
+ buffer.stop()
+ }
+}
+
+/// 底层 pipe 读取桥接了 FileHandle、DispatchSourceRead 和 semaphore 这些非 Sendable 类型
+/// 对外 Sendable 边界只保留在这里, 可变状态全部经由 lock 保护, 读事件固定在 readQueue 上执行
+final nonisolated class PipeReadBuffer: @unchecked Sendable {
private let lock = NSLock()
- private let semaphore = DispatchSemaphore(value: 0)
+ private let lineSemaphore = DispatchSemaphore(value: 0)
+ private let closedSemaphore = DispatchSemaphore(value: 0)
private let fileHandle: FileHandle
- private var buffer = Data()
+ private let readQueue: DispatchQueue
+ private let readQueueKey = DispatchSpecificKey<Void>()
+ private let readSource: DispatchSourceRead
+ private let maxBytes: Int
+ private let parsesLines: Bool
+ private var collectedData = Data()
+ private var lineBuffer = Data()
private var lines: [String] = []
private var closed = false
+ private var readSourceCancelled = false
- init(fileHandle: FileHandle) {
+ init(fileHandle: FileHandle, maxBytes: Int = 0, parsesLines: Bool = false) {
self.fileHandle = fileHandle
- fileHandle.readabilityHandler = { [weak self] handle in
- let data = handle.availableData
- guard !data.isEmpty else {
- handle.readabilityHandler = nil
- self?.markClosed()
- return
- }
- self?.append(data)
+ self.maxBytes = max(maxBytes, 0)
+ self.parsesLines = parsesLines
+ readQueue = DispatchQueue(label: "CodexBar.pipe-read", qos: .userInitiated)
+ readSource = DispatchSource.makeReadSource(
+ fileDescriptor: fileHandle.fileDescriptor,
+ queue: readQueue
+ )
+
+ readQueue.setSpecific(key: readQueueKey, value: ())
+ readSource.setEventHandler { [weak self] in
+ self?.readAvailableData()
}
+ readSource.resume()
}
func nextLine(timeout: TimeInterval) -> String? {
@@ -26,11 +72,11 @@ final nonisolated class JSONLineReader: @unchecked Sendable {
return line
}
- if isClosed {
+ if hasNoMoreLines {
return nil
}
- let result = semaphore.wait(timeout: .now() + timeout)
+ let result = lineSemaphore.wait(timeout: .now() + max(0, timeout))
guard result == .success else {
return nil
}
@@ -38,82 +84,138 @@ final nonisolated class JSONLineReader: @unchecked Sendable {
return popLine()
}
- func stop() {
- fileHandle.readabilityHandler = nil
- markClosed()
- }
-
- var isClosed: Bool {
- lock.lock()
- defer { lock.unlock() }
+ private func readAvailableData() {
+ let data = fileHandle.availableData
+ guard !data.isEmpty else {
+ cancelReadSourceIfNeeded()
+ markClosed()
+ return
+ }
- return closed && lines.isEmpty
+ append(data)
}
private func append(_ data: Data) {
- lock.lock()
- defer { lock.unlock() }
+ withLock {
+ if maxBytes > 0, collectedData.count < maxBytes {
+ collectedData.append(data.prefix(maxBytes - collectedData.count))
+ }
- buffer.append(data)
+ guard parsesLines else {
+ return
+ }
- while let newlineRange = buffer.firstRange(of: Data([0x0A])) {
- let lineData = buffer[..<newlineRange.lowerBound]
- buffer.removeSubrange(...newlineRange.lowerBound)
+ lineBuffer.append(data)
- if let line = String(bytes: lineData, encoding: .utf8)?
- .trimmingCharacters(in: .whitespacesAndNewlines),
- !line.isEmpty {
- lines.append(line)
- semaphore.signal()
+ while let newlineRange = lineBuffer.firstRange(of: Data([0x0A])) {
+ let lineData = lineBuffer[..<newlineRange.lowerBound]
+ lineBuffer.removeSubrange(...newlineRange.lowerBound)
+ appendLineIfPresent(lineData, signal: true)
}
}
}
- private func markClosed() {
- lock.lock()
- defer {
- lock.unlock()
- semaphore.signal()
+ func waitUntilClosed(timeout: TimeInterval) -> Bool {
+ let isClosed = withLock { closed }
+
+ guard !isClosed else {
+ return true
}
- if !buffer.isEmpty {
- if let line = String(bytes: buffer, encoding: .utf8)?
- .trimmingCharacters(in: .whitespacesAndNewlines),
- !line.isEmpty {
- lines.append(line)
+ return closedSemaphore.wait(timeout: .now() + max(0, timeout)) == .success
+ }
+
+ func stopAndRead() -> Data {
+ cancelReadSourceIfNeeded()
+ waitForReadQueueToDrain()
+ try? fileHandle.close()
+
+ let snapshot = withLock {
+ appendRemainingLineIfNeeded()
+ closed = true
+ return collectedData
+ }
+ closedSemaphore.signal()
+ lineSemaphore.signal()
+
+ return snapshot
+ }
+
+ func stop() {
+ _ = stopAndRead()
+ }
+
+ var hasNoMoreLines: Bool {
+ withLock { closed && lines.isEmpty }
+ }
+
+ private func cancelReadSourceIfNeeded() {
+ let shouldCancel = withLock {
+ guard !readSourceCancelled else {
+ return false
}
- buffer.removeAll()
+
+ readSourceCancelled = true
+ return true
}
- closed = true
+ if shouldCancel {
+ readSource.cancel()
+ }
}
- private func popLine() -> String? {
- lock.lock()
- defer { lock.unlock() }
+ private func waitForReadQueueToDrain() {
+ guard DispatchQueue.getSpecific(key: readQueueKey) == nil else {
+ return
+ }
- guard !lines.isEmpty else {
- return nil
+ readQueue.sync {}
+ }
+
+ private func markClosed() {
+ withLock {
+ appendRemainingLineIfNeeded()
+ closed = true
+ }
+ closedSemaphore.signal()
+ lineSemaphore.signal()
+ }
+
+ private func appendRemainingLineIfNeeded() {
+ guard parsesLines, !lineBuffer.isEmpty else {
+ return
}
- return lines.removeFirst()
+ appendLineIfPresent(lineBuffer, signal: false)
+ lineBuffer.removeAll()
}
-}
-final nonisolated class PipeDrain: @unchecked Sendable {
- private let fileHandle: FileHandle
+ private func appendLineIfPresent(_ data: Data, signal: Bool) {
+ guard let line = String(bytes: data, encoding: .utf8)?
+ .trimmingCharacters(in: .whitespacesAndNewlines),
+ !line.isEmpty else {
+ return
+ }
- init(fileHandle: FileHandle) {
- self.fileHandle = fileHandle
- fileHandle.readabilityHandler = { handle in
- guard !handle.availableData.isEmpty else {
- handle.readabilityHandler = nil
- return
+ lines.append(line)
+ if signal {
+ lineSemaphore.signal()
+ }
+ }
+
+ private func popLine() -> String? {
+ withLock {
+ guard !lines.isEmpty else {
+ return nil
}
+
+ return lines.removeFirst()
}
}
- func stop() {
- fileHandle.readabilityHandler = nil
+ private func withLock<T>(_ work: () -> T) -> T {
+ lock.lock()
+ defer { lock.unlock() }
+ return work()
}
}
diff --git a/CodexBar/Services/CodexStatus/AppServerSession.swift b/CodexBar/Services/CodexStatus/AppServerSession.swift
index 5ea77d5..2989d61 100644
--- a/CodexBar/Services/CodexStatus/AppServerSession.swift
+++ b/CodexBar/Services/CodexStatus/AppServerSession.swift
@@ -47,9 +47,9 @@ final nonisolated class AppServerSession {
case .alreadyExited, .terminated:
break
case .killed:
- RequestLogStore.shared.recordFailure(message: "app-server 退出超时, 已强制结束")
+ RequestLogStorage.shared.recordFailure(message: "app-server 退出超时, 已强制结束")
case .stillRunning:
- RequestLogStore.shared.recordFailure(message: "app-server 退出超时, 可能仍在后台运行")
+ RequestLogStorage.shared.recordFailure(message: "app-server 退出超时, 可能仍在后台运行")
}
}
}
@@ -58,9 +58,9 @@ final nonisolated class AppServerSession {
let encoded = try encodeMessage(method: method, id: nil, params: params)
try writeEncoded(encoded) {
- RequestLogStore.shared.recordFailure(method: method, message: Self.writeFailureMessage)
+ RequestLogStorage.shared.recordFailure(method: method, message: Self.writeFailureMessage)
}
- RequestLogStore.shared.recordRequestWithEmptyResponse(method: method, payload: encoded.text)
+ RequestLogStorage.shared.recordRequestWithEmptyResponse(method: method, payload: encoded.text)
}
func request<Response: Decodable>(
@@ -102,10 +102,10 @@ final nonisolated class AppServerSession {
let id = nextId
nextId += 1
let encoded = try encodeMessage(method: method, id: id, params: params)
- let token = RequestLogStore.shared.beginRequest(method: method, payload: encoded.text)
+ let token = RequestLogStorage.shared.beginRequest(method: method, payload: encoded.text)
try writeEncoded(encoded) {
- RequestLogStore.shared.failRequest(token, message: Self.writeFailureMessage)
+ RequestLogStorage.shared.failRequest(token, message: Self.writeFailureMessage)
}
return try waitForResponse(id: id, token: token, decode: type)
@@ -171,7 +171,7 @@ final nonisolated class AppServerSession {
}
let result = try decodeResponse(line, as: type, token: token, decoder: decoder)
- RequestLogStore.shared.finishRequest(token, response: line.text)
+ RequestLogStorage.shared.finishRequest(token, response: line.text)
return result
}
@@ -221,7 +221,7 @@ final nonisolated class AppServerSession {
}
private func failRequest(_ token: UUID, message: String, error: CodexStatusError) throws -> Never {
- RequestLogStore.shared.failRequest(token, message: message)
+ RequestLogStorage.shared.failRequest(token, message: message)
throw error
}
}
diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swift
index 8b31bc8..6e322c5 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift
@@ -7,26 +7,26 @@ nonisolated enum CodexFetchOutcome {
case initializationFailed
}
-private enum ConnectionResolution {
+private nonisolated enum ConnectionResolution {
case ready(connection: AppServerConnection, reused: Bool)
case notLoggedIn
case initializationFailed
}
// 单接口读取结果按后续动作分类: 跳过、刷新认证、重建连接
-private enum ReadResult<Value> {
+private nonisolated enum ReadResult<Value> {
case value(Value)
case skipped(ReadSkipReason)
case authRequired
case broken
}
-private enum ReadSkipReason {
+private nonisolated enum ReadSkipReason {
case requestFailed
case methodUnsupported
}
-private enum FetchFailure: Error {
+private nonisolated enum FetchFailure: Error {
case notLoggedIn
case needsRebuild
}
@@ -76,14 +76,12 @@ private nonisolated extension ReadResult {
}
/// 维持一条 codex app-server stdio 会话, 复用失败后按需重建
-final nonisolated class CodexStatusService: @unchecked Sendable {
+actor CodexStatusService {
private static let requestTimeout: TimeInterval = 20
// 定期回收连接, 让后台升级后的 codex 二进制有机会生效
private static let connectionMaxAge: TimeInterval = 1 * 60 * 60
private static let environment = CodexCLIResolver.environment
- // connection 只在这个队列上访问
- private let queue = DispatchQueue(label: "CodexBar.app-server", qos: .utility)
private var connection: AppServerConnection?
private var supplementalDataCache = SupplementalDataCache()
@@ -96,64 +94,34 @@ final nonisolated class CodexStatusService: @unchecked Sendable {
_ = Self.ignoreBrokenPipeSignal
}
- deinit {
- connection?.session.close()
- }
-
func fetchOutcome() async -> CodexFetchOutcome {
- await withCheckedContinuation { continuation in
- queue.async {
- continuation.resume(returning: self.resolveOutcomeOnQueue(allowRebuild: true))
- }
- }
+ resolveOutcome(allowRebuild: true)
}
func currentConnectionInfo() async -> CodexCLIConnectionInfo? {
- await withCheckedContinuation { continuation in
- queue.async {
- continuation.resume(returning: self.currentConnectionInfoOnQueue())
- }
- }
+ currentConnectionInfoSnapshot()
}
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)
- }
- }
- }
+ let connection = try readyConnection()
+ return try connection.session.request(
+ "config/read",
+ params: ["includeLayers": false],
+ as: CodexConfigReadResponse.self
+ )
}
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)
- }
- }
- }
+ let connection = try readyConnection()
+ return try connection.session.request(
+ "hooks/list",
+ params: ["cwds": cwds],
+ as: CodexHooksListResponse.self
+ )
}
/// 复用连接出现传输故障时只重建重试一次, 避免故障状态下反复拉起进程
- private func resolveOutcomeOnQueue(allowRebuild: Bool) -> CodexFetchOutcome {
+ private func resolveOutcome(allowRebuild: Bool) -> CodexFetchOutcome {
switch ensureConnection() {
case .notLoggedIn:
return .notLoggedIn
@@ -170,7 +138,7 @@ final nonisolated class CodexStatusService: @unchecked Sendable {
} catch FetchFailure.needsRebuild {
teardownConnection()
if reused, allowRebuild {
- return resolveOutcomeOnQueue(allowRebuild: false)
+ return resolveOutcome(allowRebuild: false)
}
return .initializationFailed
} catch {
@@ -180,7 +148,7 @@ final nonisolated class CodexStatusService: @unchecked Sendable {
}
}
- private func readyConnectionOnQueue() throws -> AppServerConnection {
+ private func readyConnection() throws -> AppServerConnection {
switch ensureConnection() {
case let .ready(connection, _):
return connection
@@ -203,7 +171,7 @@ final nonisolated class CodexStatusService: @unchecked Sendable {
do {
command = try CodexCLIResolver.resolveAppServerCommand(environment: Self.environment)
} catch {
- RequestLogStore.shared.recordFailure(message: error.localizedDescription)
+ RequestLogStorage.shared.recordFailure(message: error.localizedDescription)
return .initializationFailed
}
@@ -220,11 +188,11 @@ final nonisolated class CodexStatusService: @unchecked Sendable {
}
private func teardownConnection() {
- connection?.session.close()
+ connection?.close()
connection = nil
}
- private func currentConnectionInfoOnQueue() -> CodexCLIConnectionInfo? {
+ private func currentConnectionInfoSnapshot() -> CodexCLIConnectionInfo? {
guard let connection, connection.session.process.isRunning else {
return nil
}
@@ -395,7 +363,7 @@ final nonisolated class CodexStatusService: @unchecked Sendable {
do {
try process.run()
} catch {
- RequestLogStore.shared.recordFailure(message: "app-server 启动失败: \(error.localizedDescription)")
+ RequestLogStorage.shared.recordFailure(message: "app-server 启动失败: \(error.localizedDescription)")
return .initializationFailed
}
let openedAt = Date()
@@ -479,6 +447,7 @@ private final nonisolated class AppServerConnection {
let session: AppServerSession
let commandInfo: CodexCLIConnectionInfo
var accountResponse: AccountReadResponse
+ private var isClosed = false
var openedAt: Date {
commandInfo.openedAt
@@ -493,6 +462,19 @@ private final nonisolated class AppServerConnection {
self.accountResponse = accountResponse
self.commandInfo = commandInfo
}
+
+ deinit {
+ close()
+ }
+
+ func close() {
+ guard !isClosed else {
+ return
+ }
+
+ isClosed = true
+ session.close()
+ }
}
private nonisolated struct InitializeResult: Decodable {
diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
index a850be3..cf30ca7 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
@@ -44,6 +44,7 @@ final class CodexStatusViewModel: ObservableObject {
private let service: CodexStatusService
private var autoRefreshTask: Task<Void, Never>?
+ private let refreshCoordinator = RefreshTaskCoordinator()
init(service: CodexStatusService = CodexStatusService()) {
self.service = service
@@ -51,6 +52,7 @@ final class CodexStatusViewModel: ObservableObject {
deinit {
autoRefreshTask?.cancel()
+ refreshCoordinator.cancel()
}
func refreshIfNeeded() {
@@ -87,22 +89,38 @@ final class CodexStatusViewModel: ObservableObject {
isRefreshing = true
- Task {
- switch await service.fetchOutcome() {
+ refreshCoordinator.start { [weak self] generation in
+ guard let self else {
+ return
+ }
+
+ defer {
+ self.refreshCoordinator.finish(generation) {
+ self.isRefreshing = false
+ }
+ }
+
+ let outcome = await service.fetchOutcome()
+ let connectionInfo = await service.currentConnectionInfo()
+
+ guard refreshCoordinator.canCommit(generation) else {
+ return
+ }
+
+ switch outcome {
case let .data(snapshot):
self.snapshot = snapshot
- self.loadState = .loaded
+ loadState = .loaded
case .notLoggedIn:
- self.snapshot = nil
- self.loadState = .notLoggedIn
+ snapshot = nil
+ loadState = .notLoggedIn
case .initializationFailed:
- self.snapshot = nil
- self.loadState = .initializationFailed
+ snapshot = nil
+ loadState = .initializationFailed
}
- self.codexConnectionInfo = await service.currentConnectionInfo()
- self.autoRefreshCountdownStartedAt = Date()
- self.isRefreshing = false
+ codexConnectionInfo = connectionInfo
+ autoRefreshCountdownStartedAt = Date()
}
}
diff --git a/CodexBar/Services/CodexStatus/RequestLog.swift b/CodexBar/Services/CodexStatus/RequestLog.swift
index 0003466..ef32fec 100644
--- a/CodexBar/Services/CodexStatus/RequestLog.swift
+++ b/CodexBar/Services/CodexStatus/RequestLog.swift
@@ -1,5 +1,6 @@
import Combine
import Foundation
+import os
/// JSON-RPC 交互日志: 带 id 的请求先记录为进行, 响应或错误到达后回填到同一条
/// `initialized` 这类无 id 请求没有响应可等, 单独记录为空响应
@@ -18,25 +19,48 @@ nonisolated struct RequestLogEntry: Identifiable, Equatable {
let method: String?
let request: String?
var detail: String?
-}
-/// 常驻日志存储, 写入来自后台队列, storage 用锁保护, SwiftUI 通知切回主线程发送
-final nonisolated class RequestLogStore: ObservableObject, @unchecked Sendable {
- static let shared = RequestLogStore()
+ static let summaryPreviewLength = 160
+ static let expandedInlinePreviewLength = 260
+
+ static func preview(_ text: String, limit: Int) -> String {
+ guard limit > 0,
+ let endIndex = text.index(text.startIndex, offsetBy: limit, limitedBy: text.endIndex),
+ endIndex < text.endIndex else {
+ return text
+ }
+
+ return String(text[..<endIndex]) + "..."
+ }
+
+ static func singleLinePreview(_ text: String, limit: Int) -> String {
+ let firstLine = text.components(separatedBy: .newlines).first ?? ""
+ let normalizedText = firstLine
+ .components(separatedBy: .whitespaces)
+ .filter { !$0.isEmpty }
+ .joined(separator: " ")
+ let displayText = preview(normalizedText, limit: limit)
+
+ guard firstLine != text, !displayText.hasSuffix("...") else {
+ return displayText
+ }
+
+ return displayText + "..."
+ }
+}
- /// nonisolated 存储不能用 @Published 包装可变数组, 这里手动发送变更
- let objectWillChange = ObservableObjectPublisher()
+/// 常驻日志存储, 允许后台请求路径同步写入并立即拿到请求 token
+final nonisolated class RequestLogStorage: Sendable {
+ static let shared = RequestLogStorage()
- // 环形上限避免长时间运行后日志无限增长
+ /// 环形上限避免长时间运行后日志无限增长
private static let capacity = 500
- private static let maxRequestLength = 4000
- private let lock = NSLock()
/// 最新在前, 既方便渲染也让刚发出的请求更快被回填
- private var storage: [RequestLogEntry] = []
+ private let storage = OSAllocatedUnfairLock(initialState: [RequestLogEntry]())
var entries: [RequestLogEntry] {
- withLock { storage }
+ storage.withLock { $0 }
}
private init() {}
@@ -50,7 +74,7 @@ final nonisolated class RequestLogStore: ObservableObject, @unchecked Sendable {
respondedAt: nil,
kind: .pending,
method: method,
- request: Self.normalizedPreview(payload),
+ request: Self.normalized(payload),
detail: nil
)
)
@@ -81,7 +105,7 @@ final nonisolated class RequestLogStore: ObservableObject, @unchecked Sendable {
respondedAt: nil,
kind: .emptyResponse,
method: method,
- request: Self.normalizedPreview(payload),
+ request: Self.normalized(payload),
detail: ""
)
)
@@ -102,30 +126,30 @@ final nonisolated class RequestLogStore: ObservableObject, @unchecked Sendable {
}
func clear() {
- withLock {
- storage.removeAll()
+ storage.withLock {
+ $0.removeAll()
}
notifyChange()
}
private func append(_ entry: RequestLogEntry) {
- withLock {
- storage.insert(entry, at: 0)
- if storage.count > Self.capacity {
- storage.removeLast(storage.count - Self.capacity)
+ storage.withLock {
+ $0.insert(entry, at: 0)
+ if $0.count > Self.capacity {
+ $0.removeLast($0.count - Self.capacity)
}
}
notifyChange()
}
- private func update(_ id: UUID, _ mutate: (inout RequestLogEntry) -> Void) {
- let didUpdate = withLock {
- guard let index = storage.firstIndex(where: { $0.id == id }) else {
+ private func update(_ id: UUID, _ mutate: @Sendable (inout RequestLogEntry) -> Void) {
+ let didUpdate = storage.withLock {
+ guard let index = $0.firstIndex(where: { $0.id == id }) else {
return false
}
- mutate(&storage[index])
+ mutate(&$0[index])
return true
}
@@ -136,19 +160,9 @@ final nonisolated class RequestLogStore: ObservableObject, @unchecked Sendable {
notifyChange()
}
- private func withLock<T>(_ work: () -> T) -> T {
- lock.lock()
- defer { lock.unlock() }
- return work()
- }
-
private func notifyChange() {
- if Thread.isMainThread {
- objectWillChange.send()
- } else {
- DispatchQueue.main.async { [weak self] in
- self?.objectWillChange.send()
- }
+ Task { @MainActor in
+ RequestLogStore.shared.reloadFromStorage()
}
}
@@ -157,15 +171,6 @@ final nonisolated class RequestLogStore: ObservableObject, @unchecked Sendable {
jsonNormalized(text) ?? text
}
- private static func normalizedPreview(_ text: String) -> String {
- let readableText = jsonNormalized(text) ?? text
- guard readableText.count > maxRequestLength else {
- return readableText
- }
-
- return String(readableText.prefix(maxRequestLength)) + "…"
- }
-
private static func jsonNormalized(_ text: String) -> String? {
guard let data = text.data(using: .utf8),
let object = try? JSONSerialization.jsonObject(with: data),
@@ -180,3 +185,26 @@ final nonisolated class RequestLogStore: ObservableObject, @unchecked Sendable {
return String(bytes: output, encoding: .utf8)
}
}
+
+/// SwiftUI 观察层只负责在主线程发布 storage 快照
+@MainActor
+final class RequestLogStore: ObservableObject {
+ static let shared = RequestLogStore()
+
+ @Published private(set) var entries: [RequestLogEntry]
+
+ private let storage: RequestLogStorage
+
+ init(storage: RequestLogStorage = .shared) {
+ self.storage = storage
+ entries = storage.entries
+ }
+
+ func clear() {
+ storage.clear()
+ }
+
+ fileprivate func reloadFromStorage() {
+ entries = storage.entries
+ }
+}
diff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swift
index 0017243..5a9b2b5 100644
--- a/CodexBar/Services/Settings/CodexHookSettings.swift
+++ b/CodexBar/Services/Settings/CodexHookSettings.swift
@@ -178,6 +178,13 @@ private extension CodexHookSettings {
typealias JSONObject = [String: Any]
typealias JSONArray = [Any]
+ static let hooksKey = "hooks"
+ static let hookTypeKey = "type"
+ static let hookCommandKey = "command"
+ static let hookTimeoutKey = "timeout"
+ static let hookCommandType = "command"
+ static let hookTimeout = 5
+
enum HookConfigError: LocalizedError {
case invalidFormat
case hooksGloballyDisabled
@@ -279,7 +286,7 @@ private extension CodexHookSettings {
}
static func containsAnyCodexBarHook(in config: JSONObject, executablePath: String) -> Bool {
- guard let hooks = config["hooks"] as? JSONObject else {
+ guard let hooks = config[hooksKey] as? JSONObject else {
return false
}
@@ -300,25 +307,19 @@ private extension CodexHookSettings {
for event in CodexHookEvent.allCases {
var groups = try eventGroups(named: event.configName, from: hooks)
groups.append([
- "hooks": [
- [
- "type": "command",
- "command": hookCommand(executablePath: executablePath),
- "timeout": 5
- ]
- ]
+ hooksKey: [codexBarHookHandler(executablePath: executablePath)]
])
hooks[event.configName] = groups
}
- config["hooks"] = hooks
+ config[hooksKey] = hooks
}
static func removeCodexBarHooks(
from config: inout JSONObject,
executablePath: String
) throws {
- guard config["hooks"] != nil else {
+ guard config[hooksKey] != nil else {
return
}
@@ -343,7 +344,7 @@ private extension CodexHookSettings {
}
}
- config["hooks"] = hooks
+ config[hooksKey] = hooks
}
static func validationMessage(
@@ -352,7 +353,7 @@ private extension CodexHookSettings {
hooksURL: URL
) -> String? {
guard !response.data.isEmpty else {
- return "hooks/list 没有返回任何结果"
+ return "Codex 没有返回任何结果"
}
let entries = response.data
@@ -418,7 +419,7 @@ private extension CodexHookSettings {
}
static func hooksObject(from config: JSONObject) throws -> JSONObject {
- guard let value = config["hooks"] else {
+ guard let value = config[hooksKey] else {
return [:]
}
@@ -445,13 +446,9 @@ private extension CodexHookSettings {
_ group: Any,
executablePath: String
) -> Bool {
- guard let handlers = handlers(from: group) else {
- return false
- }
-
- return handlers.contains {
+ handlers(from: group)?.contains {
isCurrentCodexBarHandler($0, executablePath: executablePath)
- }
+ } ?? false
}
static func groupRemovingCodexBarHandlers(
@@ -470,7 +467,7 @@ private extension CodexHookSettings {
return nil
}
- groupObject["hooks"] = filteredHandlers
+ groupObject[hooksKey] = filteredHandlers
return groupObject
}
@@ -479,7 +476,7 @@ private extension CodexHookSettings {
return nil
}
- return group["hooks"] as? JSONArray
+ return group[hooksKey] as? JSONArray
}
static func isCurrentCodexBarHandler(
@@ -496,20 +493,30 @@ private extension CodexHookSettings {
/// 仅当 handler 是 type == "command" 时返回其 command 字符串, 否则 nil
private static func commandIfCommandHandler(_ handler: Any) -> String? {
guard let handler = handler as? JSONObject,
- handler["type"] as? String == "command",
- let command = handler["command"] as? String else {
+ handler[hookTypeKey] as? String == hookCommandType,
+ let command = handler[hookCommandKey] as? String else {
return nil
}
return command
}
+ static func codexBarHookHandler(executablePath: String) -> JSONObject {
+ [
+ hookTypeKey: hookCommandType,
+ hookCommandKey: hookCommand(executablePath: executablePath),
+ hookTimeoutKey: hookTimeout
+ ]
+ }
+
static func hookCommand(executablePath: String) -> String {
- shellQuoted(executablePath)
+ "\(shellQuoted(executablePath)) \(WorkflowHookEventRecorder.hookArgument)"
}
static func isCodexBarCommand(_ command: String, executablePath: String) -> Bool {
- command.contains(hookCommand(executablePath: executablePath))
+ command.contains(shellQuoted(executablePath))
+ && command.split(whereSeparator: \.isWhitespace)
+ .contains(Substring(WorkflowHookEventRecorder.hookArgument))
}
static func shellQuoted(_ value: String) -> String {
diff --git a/CodexBar/Services/Support/RefreshTaskCoordinator.swift b/CodexBar/Services/Support/RefreshTaskCoordinator.swift
new file mode 100644
index 0000000..9febbd1
--- /dev/null
+++ b/CodexBar/Services/Support/RefreshTaskCoordinator.swift
@@ -0,0 +1,81 @@
+import Foundation
+import os
+
+/// 小型刷新任务状态机, 由 MainActor ViewModel 持有和调用
+final nonisolated class RefreshTaskCoordinator: Sendable {
+ private struct State {
+ var task: Task<Void, Never>?
+ var generation = 0
+ }
+
+ private let state = OSAllocatedUnfairLock(initialState: State())
+
+ deinit {
+ cancel()
+ }
+
+ @MainActor
+ @discardableResult
+ func start(_ operation: @escaping @MainActor @Sendable (_ generation: Int) async -> Void) -> Int {
+ let generation = begin()
+ store(Task { @MainActor in
+ await operation(generation)
+ })
+ return generation
+ }
+
+ private func begin() -> Int {
+ let (task, generation) = state.withLock {
+ let task = $0.task
+ $0.task = nil
+ $0.generation += 1
+ return (task, $0.generation)
+ }
+ task?.cancel()
+ return generation
+ }
+
+ private func store(_ task: Task<Void, Never>) {
+ state.withLock {
+ $0.task = task
+ }
+ }
+
+ func canCommit(_ generation: Int) -> Bool {
+ !Task.isCancelled && state.withLock {
+ generation == $0.generation
+ }
+ }
+
+ @discardableResult
+ private func finish(_ generation: Int) -> Bool {
+ state.withLock {
+ guard generation == $0.generation else {
+ return false
+ }
+
+ $0.task = nil
+ return true
+ }
+ }
+
+ @MainActor
+ @discardableResult
+ func finish(_ generation: Int, onCurrentGeneration: () -> Void) -> Bool {
+ let didFinish = finish(generation)
+ if didFinish {
+ onCurrentGeneration()
+ }
+ return didFinish
+ }
+
+ func cancel() {
+ let task = state.withLock {
+ let task = $0.task
+ $0.task = nil
+ $0.generation += 1
+ return task
+ }
+ task?.cancel()
+ }
+}
diff --git a/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift b/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift
index d462038..3c1f02d 100644
--- a/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift
+++ b/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift
@@ -2,13 +2,18 @@ import Darwin
import Foundation
nonisolated enum WorkflowHookEventRecorder {
+ static let hookArgument = "--hook-event"
+
static func handleIfRequested() -> Bool {
+ guard CommandLine.arguments.contains(hookArgument) else {
+ return false
+ }
+
let payload = stdinPayload()
guard let eventName = payload.string(for: "hook_event_name") else {
- // 如果 Codex 已经通过 stdin 传了内容但事件名缺失, 吞掉本次 Hook
- // 避免 Hook 子进程继续启动完整菜单栏 App
- return payload.hasInput
+ // 显式 Hook 模式下吞掉无效输入, 避免 Hook 子进程继续启动完整菜单栏 App
+ return true
}
try? record(payload: payload, eventName: eventName)
@@ -70,26 +75,25 @@ nonisolated enum WorkflowHookEventRecorder {
private static func stdinPayload() -> WorkflowHookPayload {
guard isatty(STDIN_FILENO) == 0 else {
- return WorkflowHookPayload(values: [:], hasInput: false)
+ return WorkflowHookPayload(values: [:])
}
let data = FileHandle.standardInput.readDataToEndOfFile()
guard !data.isEmpty else {
- return WorkflowHookPayload(values: [:], hasInput: false)
+ return WorkflowHookPayload(values: [:])
}
guard let object = try? JSONSerialization.jsonObject(with: data),
let values = object as? [String: Any] else {
- return WorkflowHookPayload(values: [:], hasInput: true)
+ return WorkflowHookPayload(values: [:])
}
- return WorkflowHookPayload(values: values, hasInput: true)
+ return WorkflowHookPayload(values: values)
}
}
private nonisolated struct WorkflowHookPayload {
let values: [String: Any]
- let hasInput: Bool
func string(for key: String) -> String? {
Self.normalizedString(values[key])
@@ -130,14 +134,14 @@ private nonisolated struct WorkflowHookPayload {
return nil
}
- if let date = ISO8601DateFormatter.codexFractional.date(from: trimmedString) {
+ if let date = CodexDateFormat.iso8601FractionalDate(from: trimmedString) {
return date
}
- if let date = DateFormatter.codexLocalTimestamp.date(from: trimmedString) {
+ if let date = CodexDateFormat.localTimestampDate(from: trimmedString) {
return date
}
- return ISO8601DateFormatter.codexInternetDateTime.date(from: trimmedString)
+ return CodexDateFormat.iso8601InternetDateTimeDate(from: trimmedString)
}
}
diff --git a/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift b/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift
index 72abbbf..cbe6b15 100644
--- a/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift
+++ b/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift
@@ -2,8 +2,7 @@ import Combine
import Darwin
import Foundation
-final nonisolated class WorkflowStatsService: @unchecked Sendable {
- private let queue = DispatchQueue(label: "CodexBar.workflow-stats", qos: .utility)
+actor WorkflowStatsService {
private let eventsDirectoryURL: URL
private let dailyLogURL: URL
private static let eventReadChunkSize = 64 * 1024
@@ -16,27 +15,19 @@ final nonisolated class WorkflowStatsService: @unchecked Sendable {
self.dailyLogURL = dailyLogURL
}
- func loadSnapshot(performMaintenance: Bool = false) async -> WorkflowStatsSnapshot {
- await withCheckedContinuation { continuation in
- queue.async {
- continuation.resume(returning: self.loadSnapshotOnQueue(performMaintenance: performMaintenance))
- }
- }
- }
-
- private func loadSnapshotOnQueue(performMaintenance: Bool) -> WorkflowStatsSnapshot {
+ func loadSnapshot(performMaintenance: Bool = false) -> WorkflowStatsSnapshot {
if performMaintenance {
- performMaintenanceIfNeededOnQueue()
+ performMaintenanceIfNeeded()
}
- if let aggregates = loadDailyAggregatesOnQueue(), !aggregates.isEmpty {
+ if let aggregates = loadDailyAggregates(), !aggregates.isEmpty {
return WorkflowStatsSnapshot(dailyAggregates: aggregates)
}
return .empty
}
- private func loadDailyAggregatesOnQueue() -> [WorkflowDailyAggregate]? {
+ private func loadDailyAggregates() -> [WorkflowDailyAggregate]? {
guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {
return nil
}
@@ -49,9 +40,9 @@ final nonisolated class WorkflowStatsService: @unchecked Sendable {
return WorkflowDailyAggregate.normalized(aggregates: aggregates)
}
- private func performMaintenanceIfNeededOnQueue() {
+ private func performMaintenanceIfNeeded() {
do {
- let tasks = try prepareMaintenanceTasksOnQueue()
+ let tasks = try prepareMaintenanceTasks()
guard !tasks.isEmpty else {
return
}
@@ -61,19 +52,19 @@ final nonisolated class WorkflowStatsService: @unchecked Sendable {
let result = try buildDailyAggregate(for: task)
try commit(result)
} catch {
- markDirtyOnQueue(task.dateKey)
+ markDirty(task.dateKey)
}
}
- try pruneExpiredEventFilesOnQueue()
+ try pruneExpiredEventFiles()
} catch {
return
}
}
- private func prepareMaintenanceTasksOnQueue() throws -> [WorkflowStatsMaintenanceTask] {
- let eventDateKeys = eventDateKeysOnQueue()
- let dailyDecodeResult = loadDailyAggregatesWithFailuresOnQueue()
+ private func prepareMaintenanceTasks() throws -> [WorkflowStatsMaintenanceTask] {
+ let eventDateKeys = eventDateKeys()
+ let dailyDecodeResult = loadDailyAggregatesWithFailures()
return try WorkflowStatsStorage.withExclusiveLock {
var state = WorkflowStatsStorage.loadMaintenanceState()
@@ -235,7 +226,7 @@ final nonisolated class WorkflowStatsService: @unchecked Sendable {
WorkflowStatsStorage.fileSize(at: eventLogURL(for: dateKey))
}
- private func loadDailyAggregatesWithFailuresOnQueue() -> JSONLinesDecodeResult<WorkflowDailyAggregate> {
+ private func loadDailyAggregatesWithFailures() -> JSONLinesDecodeResult<WorkflowDailyAggregate> {
guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {
return JSONLinesDecodeResult(values: [], failedLineCount: 0)
}
@@ -243,7 +234,7 @@ final nonisolated class WorkflowStatsService: @unchecked Sendable {
return JSONLines.decodeWithFailures(from: data)
}
- private func eventDateKeysOnQueue() -> [String] {
+ private func eventDateKeys() -> [String] {
guard let contents = try? FileManager.default.contentsOfDirectory(
at: eventsDirectoryURL,
includingPropertiesForKeys: nil
@@ -385,7 +376,7 @@ final nonisolated class WorkflowStatsService: @unchecked Sendable {
withIntermediateDirectories: true
)
- var aggregates = loadDailyAggregatesOnQueue() ?? []
+ var aggregates = loadDailyAggregates() ?? []
upsert(aggregate, into: &aggregates)
aggregates = WorkflowDailyAggregate.normalized(aggregates: aggregates)
let data = try WorkflowDailyAggregate.encodeJSONLines(aggregates)
@@ -428,7 +419,7 @@ final nonisolated class WorkflowStatsService: @unchecked Sendable {
}
}
- private func markDirtyOnQueue(_ dateKey: String) {
+ private func markDirty(_ dateKey: String) {
try? WorkflowStatsStorage.withExclusiveLock {
var state = WorkflowStatsStorage.loadMaintenanceState()
state.markDirty(dateKey)
@@ -436,10 +427,10 @@ final nonisolated class WorkflowStatsService: @unchecked Sendable {
}
}
- private func pruneExpiredEventFilesOnQueue() throws {
+ private func pruneExpiredEventFiles() throws {
let cutoffDate = WorkflowStatsStorage.retentionCutoffDate()
- let expiredDateKeys = eventDateKeysOnQueue().filter { dateKey in
- guard let date = DateFormatter.codexDay.date(from: dateKey) else {
+ let expiredDateKeys = eventDateKeys().filter { dateKey in
+ guard let date = CodexDateFormat.dayDate(from: dateKey) else {
return false
}
@@ -462,7 +453,7 @@ final nonisolated class WorkflowStatsService: @unchecked Sendable {
}
private func keepsIdentifiers(for dateKey: String) -> Bool {
- guard let date = DateFormatter.codexDay.date(from: dateKey) else {
+ guard let date = CodexDateFormat.dayDate(from: dateKey) else {
return true
}
@@ -588,11 +579,11 @@ nonisolated enum WorkflowStatsStorage {
}
static func dateKey(for date: Date) -> String {
- DateFormatter.codexDay.string(from: date)
+ CodexDateFormat.dayString(from: date)
}
static func isValidDateKey(_ dateKey: String) -> Bool {
- DateFormatter.codexDay.date(from: dateKey) != nil
+ CodexDateFormat.dayDate(from: dateKey) != nil
}
}
@@ -710,12 +701,17 @@ final class WorkflowStatsViewModel: ObservableObject {
private let service: WorkflowStatsService
private var isRefreshing = false
+ private let refreshCoordinator = RefreshTaskCoordinator()
private var lastRefreshedAt: Date?
init(service: WorkflowStatsService = WorkflowStatsService()) {
self.service = service
}
+ deinit {
+ refreshCoordinator.cancel()
+ }
+
func refreshIfNeeded(performMaintenance: Bool = false) {
guard performMaintenance || Date().timeIntervalSince(lastRefreshedAt ?? .distantPast) > Self.minimumRefreshInterval else {
return
@@ -725,16 +721,31 @@ final class WorkflowStatsViewModel: ObservableObject {
}
func refresh(performMaintenance: Bool = false) {
- guard !isRefreshing else {
+ if isRefreshing, !performMaintenance {
return
}
isRefreshing = true
- Task {
- snapshot = await service.loadSnapshot(performMaintenance: performMaintenance)
+ refreshCoordinator.start { [weak self] generation in
+ guard let self else {
+ return
+ }
+
+ defer {
+ self.refreshCoordinator.finish(generation) {
+ self.isRefreshing = false
+ }
+ }
+
+ let snapshot = await service.loadSnapshot(performMaintenance: performMaintenance)
+
+ guard refreshCoordinator.canCommit(generation) else {
+ return
+ }
+
+ self.snapshot = snapshot
lastRefreshedAt = Date()
- isRefreshing = false
}
}
}
diff --git a/CodexBar/Views/Log/LogView.swift b/CodexBar/Views/Log/LogView.swift
index 13e33d3..5e81f4e 100644
--- a/CodexBar/Views/Log/LogView.swift
+++ b/CodexBar/Views/Log/LogView.swift
@@ -1,10 +1,11 @@
+import AppKit
import SwiftUI
struct LogView: View {
@ObservedObject var store: RequestLogStore
var body: some View {
- // 整表是锁内拷贝, 每轮渲染只取一次复用
+ // 每轮渲染只取一次发布快照复用
let entries = store.entries
VStack(spacing: 0) {
header(entries: entries)
@@ -76,6 +77,7 @@ struct LogView: View {
private struct LogRow: View {
let entry: RequestLogEntry
@State private var isExpanded = false
+ @State private var fullTextItem: FullLogTextItem?
var body: some View {
VStack(alignment: .leading, spacing: 0) {
@@ -114,6 +116,9 @@ private struct LogRow: View {
}
.padding(.horizontal, 16)
.padding(.vertical, 8)
+ .sheet(item: $fullTextItem) { item in
+ FullLogTextView(item: item)
+ }
}
private var summary: some View {
@@ -144,7 +149,7 @@ private struct LogRow: View {
.foregroundStyle(.primary)
} else if let detail = entry.detail {
// 无方法名的记录(信息/进程级错误)直接预览正文, 避免标签后留空
- Text(detail)
+ Text(RequestLogEntry.singleLinePreview(detail, limit: RequestLogEntry.summaryPreviewLength))
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
@@ -157,7 +162,13 @@ private struct LogRow: View {
}
private func payloadBlock(caption: String, time: Date?, text: String, color: Color) -> some View {
- VStack(alignment: .leading, spacing: 2) {
+ let hasText = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ let displayText = RequestLogEntry.singleLinePreview(
+ text,
+ limit: RequestLogEntry.expandedInlinePreviewLength
+ )
+
+ return VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 6) {
Text(caption)
.font(.caption2.weight(.semibold))
@@ -168,13 +179,34 @@ private struct LogRow: View {
.font(.caption2.monospaced())
.foregroundStyle(.tertiary)
}
+
+ if hasText {
+ LogHeaderActionButton(
+ title: "预览",
+ systemImage: "doc.text.magnifyingglass",
+ help: "预览完整\(caption)"
+ ) {
+ fullTextItem = FullLogTextItem(title: caption, text: text)
+ }
+
+ LogHeaderActionButton(
+ title: "复制",
+ systemImage: "doc.on.doc",
+ help: "复制完整\(caption)"
+ ) {
+ LogClipboard.copy(text)
+ }
+ }
}
+ .buttonStyle(.borderless)
+ .controlSize(.small)
+ .font(.caption)
- Text(text)
+ Text(verbatim: displayText)
.font(.caption.monospaced())
.foregroundStyle(color)
- .textSelection(.enabled)
- .fixedSize(horizontal: false, vertical: true)
+ .lineLimit(1)
+ .truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
@@ -198,6 +230,262 @@ private struct LogRow: View {
}()
}
+private struct FullLogTextItem: Identifiable {
+ let id = UUID()
+ let title: String
+ let text: String
+}
+
+private struct LogHeaderActionButton: View {
+ let title: String
+ let systemImage: String
+ let help: String
+ let action: () -> Void
+
+ var body: some View {
+ Button(action: action) {
+ Label(title, systemImage: systemImage)
+ }
+ .help(help)
+ }
+}
+
+private enum LogClipboard {
+ static func copy(_ text: String) {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(text, forType: .string)
+ }
+}
+
+private struct FullLogTextView: View {
+ let item: FullLogTextItem
+ @Environment(\.dismiss) private var dismiss
+ private let preview: LogCodePreview
+
+ init(item: FullLogTextItem) {
+ self.item = item
+ preview = LogCodePreviewFormatter.preview(for: item.text)
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ HStack(spacing: 10) {
+ Text(item.title)
+ .font(.headline)
+
+ Text("\(item.text.count)")
+ .font(.caption.monospacedDigit())
+ .foregroundStyle(.secondary)
+
+ if let language = preview.language {
+ Text(language)
+ .font(.caption2.weight(.semibold))
+ .foregroundStyle(.secondary)
+ .padding(.horizontal, 6)
+ .padding(.vertical, 2)
+ .background(
+ RoundedRectangle(cornerRadius: 4, style: .continuous)
+ .fill(.quaternary)
+ )
+ }
+
+ Spacer()
+
+ Button {
+ LogClipboard.copy(item.text)
+ } label: {
+ Label("复制", systemImage: "doc.on.doc")
+ }
+ .controlSize(.small)
+
+ Button {
+ dismiss()
+ } label: {
+ Label("关闭", systemImage: "xmark")
+ }
+ .controlSize(.small)
+ }
+ .padding(.horizontal, 14)
+ .padding(.vertical, 10)
+
+ Divider()
+
+ LogCodePreviewView(attributedText: preview.attributedText)
+ .frame(minWidth: 760, minHeight: 520)
+ }
+ }
+}
+
+private struct LogCodePreview {
+ let attributedText: NSAttributedString
+ let language: String?
+}
+
+private enum LogCodePreviewFormatter {
+ private static let font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)
+ private static var baseAttributes: [NSAttributedString.Key: Any] {
+ [
+ .font: font,
+ .foregroundColor: NSColor.labelColor
+ ]
+ }
+
+ private static let jsonReadingOptions: JSONSerialization.ReadingOptions = [.fragmentsAllowed]
+ private static let jsonWritingOptions: JSONSerialization.WritingOptions = [
+ .fragmentsAllowed,
+ .prettyPrinted,
+ .sortedKeys,
+ .withoutEscapingSlashes
+ ]
+ private static let tokenRegex = try? NSRegularExpression(
+ pattern: #""(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b|\b(?:true|false|null)\b|[{}\[\]:,]"#
+ )
+
+ static func preview(for text: String) -> LogCodePreview {
+ if let formattedJSON = formattedJSON(text) {
+ return LogCodePreview(
+ attributedText: highlightedJSON(formattedJSON),
+ language: "JSON"
+ )
+ }
+
+ return LogCodePreview(
+ attributedText: attributedPlainText(text),
+ language: nil
+ )
+ }
+
+ private static func formattedJSON(_ text: String) -> String? {
+ guard let data = text.data(using: .utf8),
+ let object = try? JSONSerialization.jsonObject(with: data, options: jsonReadingOptions),
+ let output = try? JSONSerialization.data(
+ withJSONObject: object,
+ options: jsonWritingOptions
+ ) else {
+ return nil
+ }
+
+ return String(bytes: output, encoding: .utf8)
+ }
+
+ private static func attributedPlainText(_ text: String) -> NSAttributedString {
+ NSAttributedString(
+ string: text,
+ attributes: baseAttributes
+ )
+ }
+
+ private static func highlightedJSON(_ text: String) -> NSAttributedString {
+ let attributedText = NSMutableAttributedString(
+ string: text,
+ attributes: baseAttributes
+ )
+
+ guard let tokenRegex else {
+ return attributedText
+ }
+
+ let nsText = text as NSString
+ let fullRange = NSRange(location: 0, length: nsText.length)
+ tokenRegex.enumerateMatches(in: text, range: fullRange) { match, _, _ in
+ guard let range = match?.range else {
+ return
+ }
+
+ let token = nsText.substring(with: range)
+ attributedText.addAttribute(
+ .foregroundColor,
+ value: color(for: token, in: nsText, range: range),
+ range: range
+ )
+ }
+
+ return attributedText
+ }
+
+ private static func color(for token: String, in text: NSString, range: NSRange) -> NSColor {
+ if token.hasPrefix("\"") {
+ return isJSONKey(in: text, after: range) ? .systemBlue : .systemGreen
+ }
+
+ if token == "true" || token == "false" {
+ return .systemOrange
+ }
+
+ if token == "null" {
+ return .secondaryLabelColor
+ }
+
+ if token.first?.isNumber == true || token.hasPrefix("-") {
+ return .systemPurple
+ }
+
+ return .tertiaryLabelColor
+ }
+
+ private static func isJSONKey(in text: NSString, after range: NSRange) -> Bool {
+ var cursor = range.location + range.length
+ while cursor < text.length {
+ guard let scalar = UnicodeScalar(Int(text.character(at: cursor))),
+ CharacterSet.whitespacesAndNewlines.contains(scalar) else {
+ break
+ }
+ cursor += 1
+ }
+
+ guard cursor < text.length else {
+ return false
+ }
+
+ return text.character(at: cursor) == 58
+ }
+}
+
+private struct LogCodePreviewView: NSViewRepresentable {
+ let attributedText: NSAttributedString
+
+ func makeNSView(context _: Context) -> NSScrollView {
+ let scrollView = NSScrollView()
+ scrollView.hasVerticalScroller = true
+ scrollView.hasHorizontalScroller = true
+ scrollView.autohidesScrollers = false
+ scrollView.drawsBackground = true
+ scrollView.backgroundColor = .textBackgroundColor
+
+ let textView = NSTextView()
+ textView.isEditable = false
+ textView.isSelectable = true
+ textView.isRichText = true
+ textView.drawsBackground = true
+ textView.backgroundColor = .textBackgroundColor
+ textView.textContainerInset = NSSize(width: 12, height: 12)
+ textView.minSize = NSSize(width: 0, height: scrollView.contentSize.height)
+ textView.maxSize = NSSize(
+ width: CGFloat.greatestFiniteMagnitude,
+ height: CGFloat.greatestFiniteMagnitude
+ )
+ textView.isVerticallyResizable = true
+ textView.isHorizontallyResizable = true
+ textView.autoresizingMask = [.width]
+ textView.textContainer?.containerSize = NSSize(
+ width: CGFloat.greatestFiniteMagnitude,
+ height: CGFloat.greatestFiniteMagnitude
+ )
+ textView.textContainer?.widthTracksTextView = false
+
+ scrollView.documentView = textView
+ return scrollView
+ }
+
+ func updateNSView(_ scrollView: NSScrollView, context _: Context) {
+ guard let textView = scrollView.documentView as? NSTextView else {
+ return
+ }
+
+ textView.textStorage?.setAttributedString(attributedText)
+ }
+}
+
private extension RequestLogEntry.Kind {
var label: String {
switch self {
diff --git a/Docs/AppServer.md b/Docs/AppServer.md
index 71ca481..3cd550f 100644
--- a/Docs/AppServer.md
+++ b/Docs/AppServer.md
@@ -89,6 +89,8 @@ Invalid request: unknown variant
- 全新连接初始化失败直接返回「初始化失败」,不重复完整握手。
- 关闭会话时先停止 stdout/stderr reader 并关闭 stdin,然后对 app-server 进程执行有界退出: 先 `terminate()` 等待 1 秒,仍未退出再 `SIGKILL` 并等待 0.5 秒;被强制结束或仍未退出时写入请求日志。
+`CodexStatusService` 是 actor,app-server 连接、补充数据缓存和重建策略都在 actor 隔离内串行访问。stdout 的 `JSONLineReader` 和 stderr 的 `PipeDrain` 共用底层 `PipeReadBuffer`,把 `FileHandle`、`DispatchSourceRead` 和 semaphore 这些非 Sendable IO 细节集中在唯一的受控边界内;读事件运行在 `CodexBar.pipe-read` 的 `.userInitiated` 队列上。
+
## UI 状态
`CodexLoadState` 只有四种:
@@ -111,9 +113,10 @@ UI 只展示「未登录」和「初始化失败」两类特殊状态;具体
日志规则:
+- 后台请求路径写入 `RequestLogStorage.shared`,日志窗口通过 `@MainActor RequestLogStore.shared` 订阅 storage 快照。
- 带 id 的 JSON-RPC 请求先记录为进行,响应或错误到达后回填到同一条。
- `initialized` 这类无 id 请求记录为空响应。
-- 日志容量上限 500 条,请求 payload 预览上限 4000 字符;响应和错误详情不按长度截断。
+- 日志容量上限 500 条,`RequestLogEntry` 完整保存 request/detail;日志窗口列表和行内展开只渲染单行短预览,非空请求/响应标题行提供完整预览和复制,预览视图对 JSON 做格式化和高亮。
- 合法 JSON 通过 `JSONSerialization` 重新序列化,使用 `.sortedKeys` 和 `.withoutEscapingSlashes`。
- 非 JSON 错误消息保持原样。
- 不要把子进程 stderr 直接展示给用户。
diff --git a/Docs/CodexHook.md b/Docs/CodexHook.md
index ae1cbcf..9ca1fb0 100644
--- a/Docs/CodexHook.md
+++ b/Docs/CodexHook.md
@@ -17,15 +17,15 @@
CodexBar 处理器的识别条件:
- `type` 是 `command`
-- `command` 必须包含当前 App 可执行文件路径生成的 shell 命令, 例如 `'<当前 CodexBar 可执行文件路径>'`
+- `command` 必须包含当前 App 可执行文件路径生成的 shell 命令和 `--hook-event` 参数, 例如 `'<当前 CodexBar 可执行文件路径>' --hook-event`
-也就是说,如果用户手写的 Hook 命令同样包含当前 CodexBar 可执行文件路径,也会被当作当前 CodexBar 处理器移除;不包含当前路径的用户 Hook 会保留。
+也就是说,如果用户手写的 Hook 命令同样包含当前 CodexBar 可执行文件路径和 `--hook-event` 参数,也会被当作当前 CodexBar 处理器移除;不同时包含当前路径和 `--hook-event` 的用户 Hook 会保留。
检测是否已开启时,只要任意 CodexBar 事件存在当前 App 路径对应的处理器,开关就保持开启;如果缺少部分事件,`hooks/list` 验证会在 Hook 选项下方显示 `CodexBar Hook 已不完整`。
开启写入成功后会复用同一条 app-server 会话调用 `hooks/list` 做有效性检查:
-- `command`: 必须包含 CodexBar 当前可执行文件路径生成的命令。
+- `command`: 必须包含 CodexBar 当前可执行文件路径生成的命令和 `--hook-event` 参数。
- `eventName`: 必须覆盖全部 CodexBar 事件;`hooks/list` 返回值使用 `sessionStart` 这类 lower camel 名称,CodexBar 会与写入的 `SessionStart` 配置名做映射。
- `enabled`: 必须为 `true`,否则提示 Codex 已禁用这些 Hook。
- `sourcePath`: 必须指向全局 `~/.codex/hooks.json`。
@@ -60,12 +60,12 @@ SubagentStop
命令格式:
```bash
-'/Applications/CodexBar.app/Contents/MacOS/CodexBar'
+'/Applications/CodexBar.app/Contents/MacOS/CodexBar' --hook-event
```
-Hook timeout 为 5 秒。App 启动最早阶段会调用 `WorkflowHookEventRecorder.handleIfRequested()`,如果识别到 Hook 输入,只记录数据并立即退出正常 App 启动流程。
+Hook timeout 为 5 秒。App 启动最早阶段会调用 `WorkflowHookEventRecorder.handleIfRequested()`,只有启动参数包含 `--hook-event` 时才读取 stdin;如果识别到 Hook 输入,只记录数据并立即退出正常 App 启动流程。
-Hook 子进程通过 stdin payload 顶层 `hook_event_name` 判断事件名。
+Hook 子进程通过 `--hook-event` 参数进入记录模式, 再通过 stdin payload 顶层 `hook_event_name` 判断事件名。
## Payload 解析
@@ -81,7 +81,7 @@ Hook stdin 会尝试解析为 Codex 官方 JSON 对象,只读取顶层字段
- 会话: `session_id`
- 轮次: `turn_id`
-事件名来自 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`。
+事件名来自 payload 顶层 `hook_event_name`。没有 `--hook-event` 参数时按普通 App 启动;有 `--hook-event` 参数但 stdin 为空、不是 JSON 或事件名缺失时吞掉本次 Hook,避免 Hook 子进程继续启动完整菜单栏 App。事件时间优先读取 payload 顶层 `timestamp`,解析后按本机时区写成 `yyyy-MM-dd HH:mm:ss.SSS`;如果 `timestamp` 缺失或无法解析,记录当前时间作为兜底。同一个事件时间也会按本机时区格式化为 `yyyy-MM-dd` 的 date key,用于选择 `events/YYYY-MM-DD.jsonl` 文件。日期和时间解析统一走 `CodexDateFormat`,其中高频的 `yyyy-MM-dd` key 由本机 Gregorian 日历组件生成和校验,不暴露可变 `DateFormatter` 实例。每行按固定顺序写入 `timestamp`、`event`、`model`、`permission`、`session`、`turn`、`tool`、`cwd`;缺失值写为 `null`。
事件名统计时会去掉 `_` 和 `-` 并转小写,因此 `PreToolUse`、`pre_tool_use`、`pre-tool-use` 会归为同一个事件。
@@ -135,7 +135,7 @@ Hook 可能由多个 Codex 进程并发触发。`WorkflowHookEventRecorder` 会
Hook 写入路径不更新 `daily.jsonl`,也不执行重建或清理旧文件,避免在 Hook timeout 内持锁执行重活。
-`WorkflowStatsService` 只在现有自动刷新或手动刷新触发工作流统计刷新时检查 `maintenance.json`。打开菜单面板时只读取现有 `daily.jsonl`。如果没有 `pending` 或 `dirty`,服务不会执行维护。
+`WorkflowStatsService` 是 actor,只在现有自动刷新或手动刷新触发工作流统计刷新时检查 `maintenance.json`。打开菜单面板时只读取现有 `daily.jsonl`。如果没有 `pending` 或 `dirty`,服务不会执行维护。
维护时优先处理 `dirty`,从对应日期文件第一行开始流式重建当天聚合;再处理 `pending`,从 `days[date].offset` 开始流式读取新增事件并合并到已有当天聚合。每条坏行会被跳过并计入 `days[date].corrupt`。处理完成后先在 `stats.lock` 外原子写回 `daily.jsonl`,再短暂持有 `stats.lock` 更新 `maintenance.json`,避免主 App 写 daily 时阻塞 Hook 追加事件。
diff --git a/Docs/DevelopmentGuide.md b/Docs/DevelopmentGuide.md
index 672d93c..eda7224 100644
--- a/Docs/DevelopmentGuide.md
+++ b/Docs/DevelopmentGuide.md
@@ -17,7 +17,7 @@ App 通过本机 Codex app-server 读取账号, 额度和 token 用量, 通过 C
- App Sandbox 保持关闭, 因为需要启动本机 `codex`, 读取真实用户 Codex 登录状态, 并写入用户级 Hook 配置
- 除 Sparkle 检查和下载更新外, App 自身不发起网络请求
- 账号, 额度, token 用量和 Hook 工作流统计都只在本机处理, 不发送给第三方
-- Swift 工程开启 `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`, 服务和模型中需要被后台队列同步访问的类型显式使用 `nonisolated`
+- Swift 工程使用 Swift 6 并开启 `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`, UI 默认 MainActor 隔离;服务共享状态优先用 actor 管理, DTO、模型、同步辅助类型和静态工具需要显式使用 `nonisolated`
源码目录职责:
@@ -36,13 +36,13 @@ App 通过本机 Codex app-server 读取账号, 额度和 token 用量, 通过 C
两条主数据链路:
- Codex app-server 链路: `CodexStatusService` 启动或复用本机 app-server, 生成 `CodexQuotaSnapshot`, 由 `CodexStatusViewModel` 发布给菜单栏 UI
-- Codex Hook 链路: Codex 进程触发 Hook 命令, CodexBar 从 stdin payload 读取 `hook_event_name` 并快速写入 JSONL; 主 App 后续维护聚合并生成 `WorkflowStatsSnapshot`
+- Codex Hook 链路: Codex 进程触发带 `--hook-event` 参数的 Hook 命令, CodexBar 从 stdin payload 读取 `hook_event_name` 并快速写入 JSONL; 主 App 后续维护聚合并生成 `WorkflowStatsSnapshot`
## 3. 启动流程
入口在 `CodexBar/App/CodexBarApp.swift`
-`CodexBarApp.init()` 最先调用 `WorkflowHookEventRecorder.handleIfRequested()`, 用于区分普通 App 启动和 Hook 子进程启动
+`CodexBarApp.init()` 最先调用 `WorkflowHookEventRecorder.handleIfRequested()`, 用 `--hook-event` 参数区分普通 App 启动和 Hook 子进程启动
```mermaid
sequenceDiagram
@@ -153,6 +153,7 @@ Command-Space 不直接关闭菜单面板, 只短暂抑制 600 ms 内的 active
- 刷新间隔是 60 秒
- `refreshIfNeeded()` 会比较 `autoRefreshCountdownStartedAt`, 避免菜单面板打开和自动刷新同时触发重复请求
- `refresh()` 通过 `isRefreshing` 防重入
+- 刷新任务通过 `RefreshTaskCoordinator` 管理, 保证只有最后一次有效刷新能回写 UI 状态
下面的时序图展示刷新, app-server 握手, 额度与用量读取, 以及常见错误后的重试或降级
@@ -167,7 +168,7 @@ sequenceDiagram
participant Log as 请求日志
UI->>State: 请求刷新账号, 额度和用量
- State->>State: 进入串行队列并检查连接是否可复用
+ State->>State: 进入 actor 隔离区并检查连接是否可复用
alt 没有可复用连接
State->>Finder: 查找全局 Codex 或 App 内置 Codex
@@ -277,7 +278,7 @@ sequenceDiagram
`CodexStatusService` 的连接策略:
-- 所有连接状态只在 `CodexBar.app-server` 串行队列上访问
+- `CodexStatusService` 是 actor, app-server 连接、缓存和重建状态都在 actor 隔离内访问
- 请求超时是 20 秒
- 连接最大复用时间是 1 小时, 超过后重建, 便于后台升级后的 `codex` 二进制生效
- 忽略 `SIGPIPE`, 断管由 `write` 抛错后走连接重建
@@ -319,7 +320,7 @@ codex app-server --listen stdio://
`AppServerSession` 负责 JSON-RPC 读写:
-- 每个带 id 的请求先写入 `RequestLogStore.beginRequest`
+- 每个带 id 的请求先写入 `RequestLogStorage.beginRequest`
- 请求 JSON 使用 sorted keys 和不转义斜杠序列化
- 写入 stdin 时追加换行
- `JSONLineReader` 从 stdout 读取按行 JSON, 只处理 id 匹配的响应, 其他行忽略
@@ -327,6 +328,7 @@ codex app-server --listen stdio://
- 响应不能解析成期望类型时归为 `.invalidServerResponse`
- `initialized` 是无 id 通知, 不等待响应, 但记录为"请求"
- `PipeDrain` 只 drain stderr, 不把子进程 stderr 展示给用户
+- `JSONLineReader` 和 `PipeDrain` 底层都使用 `PipeReadBuffer`, 把 `FileHandle`、`DispatchSourceRead` 和 semaphore 的非 Sendable IO 边界集中管理
请求错误分类:
@@ -337,15 +339,19 @@ codex app-server --listen stdio://
| 非认证业务错误 | `AppServerSession` 先重试同请求一次, 仍失败后不阻断整轮刷新 |
| 连接断开, 超时, 响应解析失败 | 视为传输故障, 外层重建连接 |
-`RequestLogStore` 是常驻全局日志:
+`RequestLogStorage` 是常驻全局日志存储:
- 容量上限 500 条
-- 请求 payload 预览上限 4000 字符
-- 响应和错误详情不按长度截断
+- `RequestLogEntry` 完整保存 request/detail
+- 列表摘要和行内展开只使用 `RequestLogEntry` 生成的单行短预览
+- 非空请求和响应标题行提供完整预览和复制; 预览视图对 JSON 做格式化和高亮
- 合法 JSON 会稳定化显示, 非 JSON 错误消息保持原样
-- storage 用 `NSLock` 保护, SwiftUI 通知切回主线程发送
+- storage 用 `OSAllocatedUnfairLock` 保护, 后台请求路径可以同步写入并立即拿到请求 token
+- 写入后通过 `Task { @MainActor ... }` 刷新 `RequestLogStore.shared`
- 日志窗口关闭不会清空日志
+`RequestLogStore` 是 `@MainActor ObservableObject` 外壳, 只负责把 storage 快照发布给 SwiftUI, 清空操作也委托给 `RequestLogStorage`
+
日志状态标签:
| Kind | UI 标签 |
@@ -368,22 +374,22 @@ codex app-server --listen stdio://
app-server 与状态刷新错误:
-| 错误来源 | 检测位置 | 用户可见状态 | 日志或存储 | 重试或降级 |
-| -------------------------------------------- | -------------------------------------------- | ---------------------------------------- | -------------------------------------------- | ----------------------------------------------------------------- |
-| 找不到全局 Codex CLI 和 Codex APP 内置 CLI | `CodexCLIResolver.resolveAppServerCommand()` | `初始化失败` | `RequestLogStore.recordFailure` 记录可读错误 | 不启动 app-server, 下轮刷新重新解析 |
-| app-server 进程启动失败 | `Process.run()` | `初始化失败` | 记录"app-server 启动失败" | 不复用本次进程, 下轮刷新重试 |
-| `initialize` 或首次 `account/read` 失败 | `CodexStatusService.openConnection` | `初始化失败` | 对应 JSON-RPC 请求进入日志 | 关闭本次 session, 不重复完整握手 |
-| 首次 `account/read` 返回 `account == nil` | `CodexStatusService.openConnection` | `未登录` | 请求响应进入日志 | 关闭本次 session, 不生成 snapshot |
-| 复用连接刷新 account 后返回 `account == nil` | `CodexStatusService.fetchData` | `未登录` | 请求响应进入日志 | 清空 supplemental cache, teardown connection |
-| JSON-RPC 认证失败 | `CodexStatusError.isAuthenticationRequired` | 取决于刷新后结果 | 失败响应进入日志 | 同一轮最多 `account/read(refreshToken:true)` 一次, 然后重试原读取 |
-| refresh token 后仍认证失败 | `ReadResult.resultAfterAuthAttempt` | `未登录` | 失败响应进入日志 | 清空 cache, teardown connection |
-| unsupported method | `CodexStatusError.isUnsupportedMethod` | 对应区域可能显示无数据 | 失败响应进入日志 | 当前 session 记住 method, 后续跳过, 不复用旧缓存 |
-| 非认证业务错误 | `CodexStatusError.isRetriableServerError` | 通常不改变整体状态 | 失败响应进入日志 | 同请求立即重试一次, 仍失败则 supplemental 读取按失败处理 |
-| rate limits 读取失败 | `CodexStatusService.cachedRead` | 有旧缓存时区域半透明, 无旧缓存时无额度区 | 失败进入日志 | 同账号旧缓存复用并标记 `isRateLimitsStale` |
-| usage 读取失败 | `CodexStatusService.cachedRead` | 有旧缓存时区域半透明, 无旧缓存时无用量区 | 失败进入日志 | 同账号旧缓存复用并标记 `isUsageStale` |
-| 连接断开, 请求超时, 响应解析失败 | `CodexStatusError.isTransportFailure` | 复用连接重建失败后为 `初始化失败` | 请求标记为错误 | 复用连接只重建重试一次, 新连接失败不再重试 |
-| app-server 关闭超时 | `AppServerSession.close()` | 不直接改变 UI | 记录强制结束或仍在后台运行 | 先 terminate 等 1 秒, 再 SIGKILL 等 0.5 秒 |
-| snapshot 无可信 quota 和 usage | `CodexQuotaSnapshot.hasTrustedData` | 菜单栏切换错误图标 | 不新增日志 | 仍可展示 stale 数据或无数据面板 |
+| 错误来源 | 检测位置 | 用户可见状态 | 日志或存储 | 重试或降级 |
+| -------------------------------------------- | -------------------------------------------- | ---------------------------------------- | ---------------------------------------------- | ----------------------------------------------------------------- |
+| 找不到全局 Codex CLI 和 Codex APP 内置 CLI | `CodexCLIResolver.resolveAppServerCommand()` | `初始化失败` | `RequestLogStorage.recordFailure` 记录可读错误 | 不启动 app-server, 下轮刷新重新解析 |
+| app-server 进程启动失败 | `Process.run()` | `初始化失败` | 记录"app-server 启动失败" | 不复用本次进程, 下轮刷新重试 |
+| `initialize` 或首次 `account/read` 失败 | `CodexStatusService.openConnection` | `初始化失败` | 对应 JSON-RPC 请求进入日志 | 关闭本次 session, 不重复完整握手 |
+| 首次 `account/read` 返回 `account == nil` | `CodexStatusService.openConnection` | `未登录` | 请求响应进入日志 | 关闭本次 session, 不生成 snapshot |
+| 复用连接刷新 account 后返回 `account == nil` | `CodexStatusService.fetchData` | `未登录` | 请求响应进入日志 | 清空 supplemental cache, teardown connection |
+| JSON-RPC 认证失败 | `CodexStatusError.isAuthenticationRequired` | 取决于刷新后结果 | 失败响应进入日志 | 同一轮最多 `account/read(refreshToken:true)` 一次, 然后重试原读取 |
+| refresh token 后仍认证失败 | `ReadResult.resultAfterAuthAttempt` | `未登录` | 失败响应进入日志 | 清空 cache, teardown connection |
+| unsupported method | `CodexStatusError.isUnsupportedMethod` | 对应区域可能显示无数据 | 失败响应进入日志 | 当前 session 记住 method, 后续跳过, 不复用旧缓存 |
+| 非认证业务错误 | `CodexStatusError.isRetriableServerError` | 通常不改变整体状态 | 失败响应进入日志 | 同请求立即重试一次, 仍失败则 supplemental 读取按失败处理 |
+| rate limits 读取失败 | `CodexStatusService.cachedRead` | 有旧缓存时区域半透明, 无旧缓存时无额度区 | 失败进入日志 | 同账号旧缓存复用并标记 `isRateLimitsStale` |
+| usage 读取失败 | `CodexStatusService.cachedRead` | 有旧缓存时区域半透明, 无旧缓存时无用量区 | 失败进入日志 | 同账号旧缓存复用并标记 `isUsageStale` |
+| 连接断开, 请求超时, 响应解析失败 | `CodexStatusError.isTransportFailure` | 复用连接重建失败后为 `初始化失败` | 请求标记为错误 | 复用连接只重建重试一次, 新连接失败不再重试 |
+| app-server 关闭超时 | `AppServerSession.close()` | 不直接改变 UI | 记录强制结束或仍在后台运行 | 先 terminate 等 1 秒, 再 SIGKILL 等 0.5 秒 |
+| snapshot 无可信 quota 和 usage | `CodexQuotaSnapshot.hasTrustedData` | 菜单栏切换错误图标 | 不新增日志 | 仍可展示 stale 数据或无数据面板 |
日志错误处理:
@@ -395,8 +401,8 @@ app-server 与状态刷新错误:
| `initialized` 无 id 通知 | 记录为"请求", 不等待响应 |
| 进程级错误没有 method | 日志行直接预览错误文本 |
| 合法 JSON 内容 | 重新序列化为稳定顺序并保留未转义斜杠 |
-| 超长请求 payload | 请求预览截断到 4000 字符 |
-| 超长响应或错误详情 | 不按长度截断 |
+| 请求 payload | 存完整内容, UI 行内只渲染单行短预览 |
+| 响应或错误详情 | 存完整内容, 通过预览视图查看或复制 |
设置, Hook 和更新错误:
@@ -413,9 +419,9 @@ app-server 与状态刷新错误:
| 快捷键注册冲突 | `StatusItemController.applyGlobalHotKey` | 快捷键行内显示占用提示 | 恢复上一个已注册快捷键 |
| Hook 子进程 payload 不是 JSON | `WorkflowHookEventRecorder.stdinPayload` | 无 UI 提示 | 吞掉本次 Hook, 避免启动完整菜单栏 App |
| Hook 子进程写入失败 | `WorkflowHookEventRecorder.handleIfRequested` | 无 UI 提示 | `try? record` 吞掉错误并正常退出, 避免阻断 Codex |
-| `daily.jsonl` 缺失, 空文件或坏行 | `WorkflowStatsService.prepareMaintenanceTasksOnQueue` | 热力图详情面板可能暂时显示 0 | 标记 dirty, 后续从 events 文件重建 |
+| `daily.jsonl` 缺失, 空文件或坏行 | `WorkflowStatsService.prepareMaintenanceTasks` | 热力图详情面板可能暂时显示 0 | 标记 dirty, 后续从 events 文件重建 |
| events 文件变小或 offset 不一致 | `WorkflowStatsService.reconcileEventFiles` | 热力图详情面板可能暂时显示旧聚合 | 标记 dirty, 从头重建当天聚合 |
-| 单个维护任务失败 | `WorkflowStatsService.performMaintenanceIfNeededOnQueue` | 使用已有 daily 或空 snapshot | 对应日期标记 dirty |
+| 单个维护任务失败 | `WorkflowStatsService.performMaintenanceIfNeeded` | 使用已有 daily 或空 snapshot | 对应日期标记 dirty |
| Sparkle 配置缺失 | `AppUpdater.init` | 更新开关禁用, 操作显示"未配置更新资源" | 不创建 updater controller |
| 手动检查没有更新 | `updaterDidNotFindUpdate` | 显示"没有可用更新" | 1 秒后自动清理状态 |
| 手动检查失败 | `didAbortWithError` | 显示"检查更新失败" | 不展示底层错误细节 |
@@ -664,7 +670,7 @@ sequenceDiagram
每个处理器形如:
```bash
-'<当前 CodexBar 可执行文件路径>'
+'<当前 CodexBar 可执行文件路径>' --hook-event
```
Hook 事件定义集中在 `CodexHookEvent`:
@@ -677,14 +683,14 @@ Hook 事件定义集中在 `CodexHookEvent`:
- handler 是 JSON 对象
- `type == "command"`
-- `command` 包含当前 App 可执行路径生成的 shell 命令
+- `command` 同时包含当前 App 可执行路径生成的 shell 命令和 `--hook-event` 参数
这意味着:
- 用户已有 Hook 会被保留
- 其他 App Hook 会被保留
- 同一事件下其他处理器会被保留
-- 如果用户自定义 Hook 命令中也包含当前 CodexBar 可执行路径, 会被当作当前 CodexBar 处理器删除
+- 如果用户自定义 Hook 命令中也同时包含当前 CodexBar 可执行路径和 `--hook-event` 参数, 会被当作当前 CodexBar 处理器删除
检测是否已开启时, 只要任意 CodexBar 事件存在当前 App 路径对应的 handler, 开关就保持开启。缺少部分事件时, `hooks/list` 验证会在 Hook 选项下方显示"CodexBar Hook 已不完整"。
@@ -753,10 +759,11 @@ Hook 数据目录:
- `refreshIfNeeded(performMaintenance: false)` 至少间隔 5 秒
- `performMaintenance: true` 时跳过 5 秒节流, 直接刷新
+- 如果普通读取尚未结束, 带维护的刷新会通过 `RefreshTaskCoordinator` 取消旧任务, 确保旧结果不会回写
- 打开菜单面板时如果 Hook 开启, 只读取现有 `daily.jsonl`, 不维护
- app-server 自动刷新倒计时重置时, 如果 Hook 开启, 触发一次带维护的 workflow stats 刷新
-维护流程在 `WorkflowStatsService` 的 `CodexBar.workflow-stats` 串行队列执行
+维护流程在 `WorkflowStatsService` actor 内串行执行
```mermaid
flowchart TD
@@ -857,11 +864,12 @@ App 再次成为 active 时, 也会刷新 Codex 版本区, 并在已安装 Hook
`CodexCLIVersionService` 的版本探测:
-- 在 `CodexBar.codex-version` 串行队列执行
+- `CodexCLIVersionService` 是 actor, 对外提供 async 快照 API
- 先解析安装源
-- 全局和内置版本探测先并发启动, 再收集结果, 避免两个 5 秒超时串行叠加
+- 全局和内置版本探测用 `async let` 并发启动, 再收集结果, 避免两个 5 秒超时串行叠加
- 每个探测运行 `codex --version`
-- stdout 和 stderr 都收集, 最多各 64 KiB
+- stdout 和 stderr 都通过 `PipeReadBuffer` 收集, 最多各 64 KiB
+- 进程结束由 `ProcessExitWaiter` 用 continuation 异步等待, Task 取消或超时都会恢复等待方
- 进程超时时先 terminate, 再 SIGKILL
- 第一行中第一个以数字开头的 token 作为显示版本
@@ -918,12 +926,13 @@ App 再次成为 active 时, 也会刷新 Codex 版本区, 并在已安装 Hook
- 空状态显示"暂无日志"
- 有日志时使用 `ScrollView + LazyVStack`, 最新日志在前
- 每行默认显示时间, 状态标签, method 或无 method 记录的详情预览
-- 点击行展开请求和响应或错误详情
+- 点击行展开请求和响应或错误详情; 展开正文限制为单行预览, 非空内容通过标题行的预览和复制查看或复制完整内容
+- 预览视图使用可滚动代码视图, 对 JSON 做格式化和高亮
- 详情文本开启 `.textSelection(.enabled)`
-日志只记录经过 `RequestLogStore` 的请求和错误
+日志只记录经过 `RequestLogStorage` 的请求和错误;`RequestLogStore` 只负责把这些记录发布给 SwiftUI
-为了保护隐私, 不直接展示 app-server stderr 或 Codex auth 文件内容。app-server 响应和错误详情会完整保留在日志窗口中, 不按长度截断。
+为了保护隐私, 不直接展示 app-server stderr 或 Codex auth 文件内容。app-server 请求、响应和错误详情会完整保留在 `RequestLogEntry` 中, UI 默认只渲染预览以避免大文本拖慢日志窗口。
## 17. 发布脚本流程
@@ -952,28 +961,29 @@ App 再次成为 active 时, 也会刷新 Codex 版本区, 并在已安装 Hook
主要并发边界:
-| 模块 | 并发策略 |
-| --------------------------------- | ------------------------------------------------- |
-| UI, 控制器, ViewModel, 设置, 更新 | `@MainActor` |
-| `CodexStatusService` | `DispatchQueue(label: "CodexBar.app-server")` |
-| `CodexCLIVersionService` | `DispatchQueue(label: "CodexBar.codex-version")` |
-| `WorkflowStatsService` | `DispatchQueue(label: "CodexBar.workflow-stats")` |
-| `RequestLogStore` | `NSLock` 保护 storage, 主线程发送 SwiftUI 通知 |
-| Hook 写入 | `stats.lock` + `flock(LOCK_EX)` |
-| app-server stdout | `JSONLineReader` 使用锁和 semaphore |
-| 版本探测输出 | `PipeCollector` 使用锁和 semaphore |
+| 模块 | 并发策略 |
+| --------------------------------- | ------------------------------------------------------------------------ |
+| UI, 控制器, ViewModel, 设置, 更新 | `@MainActor` |
+| `CodexStatusService` | actor 隔离 app-server 连接、缓存和重建状态 |
+| `CodexCLIVersionService` | actor + `async let` 并发探测版本 |
+| `WorkflowStatsService` | actor 串行维护 daily 聚合和快照读取 |
+| `RequestLogStorage` | `OSAllocatedUnfairLock` 保护后台同步写入 |
+| `RequestLogStore` | `@MainActor ObservableObject` 发布日志快照 |
+| Hook 写入 | `stats.lock` + `flock(LOCK_EX)` |
+| app-server stdout/stderr | `JSONLineReader` / `PipeDrain` 复用 `PipeReadBuffer` |
+| 版本探测输出 | `PipeReadBuffer` 收集 stdout/stderr, 进程退出由 `ProcessExitWaiter` 等待 |
文件写入安全:
- Hook 子进程只在锁内追加当天 `events/YYYY-MM-DD.jsonl` 并更新 `maintenance.json`
- 主 App 维护 `daily.jsonl` 时, 先锁外原子写 daily, 再短暂持锁提交维护状态, 减少阻塞 Hook 写入
- `maintenance.json` 和 `daily.jsonl` 使用 atomic write
-- 设置 Hook 时通过当前 app-server 会话先读 `config/read`, 未全局禁用时 pretty printed 写回 `~/.codex/hooks.json`, 只移除 command 包含当前 App 可执行路径的 handler, 写入后再用 `hooks/list` 验证有效状态
+- 设置 Hook 时通过当前 app-server 会话先读 `config/read`, 未全局禁用时 pretty printed 写回 `~/.codex/hooks.json`, 只移除 command 同时包含当前 App 可执行路径和 `--hook-event` 参数的 handler, 写入后再用 `hooks/list` 验证有效状态
隐私和敏感信息边界:
- 不展示 app-server stderr
- 不读取或展示 Codex auth 文件内容
- 不把原始敏感 RPC 响应写入文档或测试夹具
-- 日志请求 payload 预览截断到 4000 字符; 响应和错误详情不按长度截断
+- 日志完整保存 request/detail, UI 默认只渲染单行预览; 完整内容通过标题行预览或复制查看
- Hook 统计只保存在用户 Application Support 的 CodexBar 目录
diff --git a/README.md b/README.md
index e8a4c69..0b71114 100644
--- a/README.md
+++ b/README.md
@@ -55,7 +55,7 @@ CodexBar 可以在设置中开启「启用 Codex Hook」
每个事件都会追加一个 `command` 类型的 Hook,命令形如:
```bash
-'/Applications/CodexBar.app/Contents/MacOS/CodexBar'
+'/Applications/CodexBar.app/Contents/MacOS/CodexBar' --hook-event
```
开启后,用量热力图会包含今天;鼠标悬停到任意一天时,弹窗会在 token 数之外展示当天的会话总数、对话轮次、子智能体、工具调用、权限请求和上下文压缩次数。关闭 Hook 时,弹窗只展示日期和 token 数;如果 app-server 尚未返回当天 token 数据,热力图不会额外占位展示今天。
@@ -66,13 +66,15 @@ CodexBar 只会追加或移除 command 中包含当前 CodexBar 可执行路径
## 从源码构建
+项目使用 Swift 6、SwiftUI + AppKit + MVVM,依赖 Sparkle (SwiftPM)。
+
```bash
git clone [email protected]:bob-zebedy/CodexBar.git
cd CodexBar
xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build
```
-也可以直接用 Xcode 打开 `CodexBar.xcodeproj` 运行。项目使用 SwiftUI + MVVM 依赖 Sparkle (SwiftPM)
+也可以直接用 Xcode 打开 `CodexBar.xcodeproj` 运行。
## 源码结构
@@ -81,7 +83,7 @@ Swift 源码按职责放在 `CodexBar/` 下的子目录中:
- `App/`: 应用入口
- `Controllers/`: 菜单栏、菜单面板和独立窗口控制器
- `Models/`: account、quota、usage、工作流统计、共享日期网格和错误分类模型
-- `Services/`: app-server 会话、Codex CLI 解析、版本探测、Hook 设置、工作流统计、开机自启和 Sparkle 更新
+- `Services/`: actor 隔离的 app-server 会话、Codex CLI 解析、版本探测、Hook 设置、工作流统计、日志存储、开机自启和 Sparkle 更新
- `Views/`: 菜单面板、设置窗口、日志窗口和共享 Liquid Glass 样式
更详细的启动、刷新、Hook 统计、设置、日志、更新和发布流程见 [开发文档](Docs/DevelopmentGuide.md)。
diff --git a/appcast.xml b/appcast.xml
index 89459fa..637448d 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.1</title>
+ <sparkle:version>25</sparkle:version>
+ <sparkle:shortVersionString>3.1.1</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.1.1</sparkle:releaseNotesLink>
+ <pubDate>Wed, 24 Jun 2026 23:38:10 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.1.1.dmg" sparkle:edSignature="ZAqYx2b6FLAS3Qy1hKM8GAcBQr3vHQkd9TEzPYrkBepYl8FrwKBM9FVjhVuTO4kc7DeCipofmjFGfO3Jytk6Dw==" length="3134760" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.1.0</title>
<sparkle:version>24</sparkle:version>