CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 优化 Hook 统计和提示展示
Bobffae90f16a56
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex d48a3f8..eba1a6a 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -275,7 +275,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 13;+ CURRENT_PROJECT_VERSION = 14;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;ENABLE_APP_SANDBOX = NO;@@ -290,7 +290,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 2.3.0;+ MARKETING_VERSION = 2.3.1;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";REGISTER_APP_GROUPS = YES;@@ -312,7 +312,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 13;+ CURRENT_PROJECT_VERSION = 14;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;ENABLE_APP_SANDBOX = NO;@@ -327,7 +327,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 2.3.0;+ MARKETING_VERSION = 2.3.1;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";diff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swiftindex 68e77e0..ad843cc 100644--- a/CodexBar/Services/Settings/CodexHookSettings.swift+++ b/CodexBar/Services/Settings/CodexHookSettings.swift@@ -36,7 +36,10 @@ final class CodexHookSettings: ObservableObject {do {var config = try readConfigIfPresent()- try Self.removeCodexBarHooks(from: &config)+ try Self.removeCodexBarHooks(+ from: &config,+ executablePath: currentExecutablePath+ )if enabled {try Self.installCodexBarHooks(@@ -179,7 +182,10 @@ private extension CodexHookSettings {config["hooks"] = hooks}- static func removeCodexBarHooks(from config: inout JSONObject) throws {+ static func removeCodexBarHooks(+ from config: inout JSONObject,+ executablePath: String+ ) throws {guard config["hooks"] != nil else {return}@@ -197,7 +203,13 @@ private extension CodexHookSettings {return group}- let filteredHandlers = handlers.filter { !isCodexBarHandler($0) }+ let filteredHandlers = handlers.filter {+ !isCurrentCodexBarHandler(+ $0,+ event: event,+ executablePath: executablePath+ )+ }guard !filteredHandlers.isEmpty else {return nil}@@ -248,15 +260,6 @@ private extension CodexHookSettings {commandIfCommandHandler(handler) == hookCommand(for: event, executablePath: executablePath)}- static func isCodexBarHandler(_ handler: Any) -> Bool {- guard let command = commandIfCommandHandler(handler) else {- return false- }-- return command.contains("/Contents/MacOS/CodexBar")- && command.contains("--hook-event")- }-// 仅当 handler 是 type == "command" 时返回其 command 字符串, 否则 nilprivate static func commandIfCommandHandler(_ handler: Any) -> String? {guard let handler = handler as? JSONObject,diff --git a/CodexBar/Services/WorkflowStats/JSONLines.swift b/CodexBar/Services/WorkflowStats/JSONLines.swiftindex f6bd5d1..767787b 100644--- a/CodexBar/Services/WorkflowStats/JSONLines.swift+++ b/CodexBar/Services/WorkflowStats/JSONLines.swift@@ -5,7 +5,7 @@ nonisolated enum JSONLines {static func decode<T: Decodable>(_ type: T.Type = T.self, from data: Data) -> [T] {decodeWithFailures(type, from: data).values}-+static func decodeWithFailures<T: Decodable>(_ type: T.Type = T.self,from data: Data@@ -13,7 +13,7 @@ nonisolated enum JSONLines {let text = String(decoding: data, as: UTF8.self)let decoder = JSONDecoder()var failedLineCount = 0-+let values = text.split(whereSeparator: \.isNewline).compactMap { line -> T? in@@ -21,15 +21,15 @@ nonisolated enum JSONLines {guard !trimmedLine.isEmpty, let lineData = trimmedLine.data(using: .utf8) else {return nil}-+if let value = try? decoder.decode(T.self, from: lineData) {return value}-+failedLineCount += 1return nil}-+return JSONLinesDecodeResult(values: values, failedLineCount: failedLineCount)}}diff --git a/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift b/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swiftindex 28ad1ad..85d4faa 100644--- a/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift+++ b/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift@@ -6,11 +6,11 @@ nonisolated enum WorkflowHookEventRecorder {guard let eventName = hookEventName(from: arguments) else {return false}-+try? record(eventName: eventName)return true}-+private static func hookEventName(from arguments: [String]) -> String? {for argument in arguments.dropFirst() {if argument.hasPrefix("--hook-event=") {@@ -19,17 +19,17 @@ nonisolated enum WorkflowHookEventRecorder {return value.isEmpty ? nil : value}}-+if let optionIndex = arguments.firstIndex(of: "--hook-event"),arguments.indices.contains(arguments.index(after: optionIndex)) {let value = arguments[arguments.index(after: optionIndex)].trimmingCharacters(in: .whitespacesAndNewlines)return value.isEmpty ? nil : value}-+return nil}-+private static func record(eventName: String) throws {let occurredAt = Date()let payload = stdinPayload()@@ -49,10 +49,10 @@ nonisolated enum WorkflowHookEventRecorder {sessionId: sessionId,turnId: turnId)-+try recordStatsTransaction(event: event)}-+private static func recordStatsTransaction(event: WorkflowHookEvent) throws {try WorkflowStatsStorage.withExclusiveLock {let eventLogURL = WorkflowStatsStorage.eventsURL()@@ -65,19 +65,19 @@ nonisolated enum WorkflowHookEventRecorder {)let maintenanceDate = DateFormatter.codexDay.string(from: Calendar.current.startOfDay(for: event.occurredAt))let shouldRunMaintenance = maintenanceState.lastMaintenanceDate != maintenanceDate-+try append(event.jsonLineData(), to: eventLogURL)if shouldRunMaintenance {try pruneExpiredEventsIfNeeded(at: eventLogURL)maintenanceState.lastMaintenanceDate = maintenanceDate}-+guard !needsDailyRebuild else {maintenanceState.markDailyRebuildNeeded()try WorkflowStatsStorage.saveMaintenanceState(maintenanceState)return}-+do {try updateDailyAggregates(with: event,@@ -85,7 +85,7 @@ nonisolated enum WorkflowHookEventRecorder {dailyLogURL: dailyLogURL,runsMaintenance: shouldRunMaintenance)-+maintenanceState.markDailyCacheUpdated(eventLogSize: WorkflowStatsStorage.fileSize(at: eventLogURL))try WorkflowStatsStorage.saveMaintenanceState(maintenanceState)} catch {@@ -95,73 +95,73 @@ nonisolated enum WorkflowHookEventRecorder {}}}-+private static func append(_ data: Data, to url: URL) throws {if !FileManager.default.fileExists(atPath: url.path) {FileManager.default.createFile(atPath: url.path, contents: nil)}-+let fileHandle = try FileHandle(forWritingTo: url)defer {try? fileHandle.close()}-+try fileHandle.seekToEnd()try fileHandle.write(contentsOf: data)}-+private static func pruneExpiredEventsIfNeeded(at url: URL) throws {guard FileManager.default.fileExists(atPath: url.path) else {return}-+let fileHandle = try FileHandle(forUpdating: url)defer {try? fileHandle.close()}-+let cutoffDate = WorkflowStatsStorage.retentionCutoffDate()guard try shouldPruneEvents(in: fileHandle, cutoffDate: cutoffDate) else {return}-+try fileHandle.seek(toOffset: 0)let currentData = try fileHandle.readToEnd() ?? Data()let retainedData = try retainedEventLogData(from: currentData, cutoffDate: cutoffDate)-+try fileHandle.truncate(atOffset: 0)try fileHandle.seek(toOffset: 0)try fileHandle.write(contentsOf: retainedData)}-+private static func shouldPruneEvents(in fileHandle: FileHandle, cutoffDate: Date) throws -> Bool {try fileHandle.seek(toOffset: 0)guard let firstChunk = try fileHandle.read(upToCount: 64 * 1024), !firstChunk.isEmpty else {return false}-+let firstLineEnd = firstChunk.firstIndex(of: 0x0A) ?? firstChunk.endIndexlet firstLine = Data(firstChunk[..<firstLineEnd])guard !firstLine.isEmpty else {return false}-+guard let event = try? JSONDecoder().decode(WorkflowHookEvent.self, from: firstLine) else {return true}-+return event.occurredAt < cutoffDate}-+private static func retainedEventLogData(from data: Data, cutoffDate: Date) throws -> Data {var retainedData = Data()for event in WorkflowHookEvent.decodeJSONLines(from: data) where event.occurredAt >= cutoffDate {retainedData.append(try event.jsonLineData())}-+return retainedData}-+private static func updateDailyAggregates(with event: WorkflowHookEvent,eventLogURL: URL,@@ -169,20 +169,20 @@ nonisolated enum WorkflowHookEventRecorder {runsMaintenance: Bool) throws {var aggregates = loadDailyAggregates(from: dailyLogURL)-+if aggregates.isEmpty {aggregates = rebuildDailyAggregates(from: eventLogURL)} else {aggregates = adding(event, to: aggregates)aggregates = runsMaintenance- ? WorkflowDailyAggregate.normalized(aggregates: aggregates)- : aggregates.sorted { $0.date < $1.date }+ ? WorkflowDailyAggregate.normalized(aggregates: aggregates)+ : aggregates.sorted { $0.date < $1.date }}-+let data = try WorkflowDailyAggregate.encodeJSONLines(aggregates)try data.write(to: dailyLogURL, options: .atomic)}-+private static func adding(_ event: WorkflowHookEvent,to aggregates: [WorkflowDailyAggregate]@@ -192,7 +192,7 @@ nonisolated enum WorkflowHookEventRecorder {guard eventStartDate >= WorkflowStatsStorage.retentionCutoffDate(calendar: calendar) else {return WorkflowDailyAggregate.normalized(aggregates: aggregates, calendar: calendar)}-+let startDate = DateFormatter.codexDay.string(from: eventStartDate)let keepsIdentifiers = eventStartDate >= WorkflowStatsStorage.identifierRetentionCutoffDate(calendar: calendar)var aggregatesByDate = aggregates.reduce(into: [String: WorkflowDailyAggregate]()) { result, aggregate in@@ -200,49 +200,49 @@ nonisolated enum WorkflowHookEventRecorder {}aggregatesByDate[startDate, default: WorkflowDailyAggregate(date: startDate)].record(event, keepsIdentifiers: keepsIdentifiers)-+return Array(aggregatesByDate.values)}-+private static func loadDailyAggregates(from url: URL) -> [WorkflowDailyAggregate] {guard let data = try? Data(contentsOf: url), !data.isEmpty else {return []}-+return WorkflowDailyAggregate.decodeJSONLines(from: data)}-+private static func rebuildDailyAggregates(from url: URL) -> [WorkflowDailyAggregate] {guard let data = try? Data(contentsOf: url), !data.isEmpty else {return []}-+return WorkflowDailyAggregate.aggregates(from: WorkflowHookEvent.decodeJSONLines(from: data))}-+private static func stdinPayload() -> WorkflowHookPayload {guard isatty(STDIN_FILENO) == 0 else {return WorkflowHookPayload(values: [:])}-+let data = FileHandle.standardInput.readDataToEndOfFile()guard !data.isEmpty,let object = try? JSONSerialization.jsonObject(with: data),let values = object as? [String: Any] else {return WorkflowHookPayload(values: [:])}-+return WorkflowHookPayload(values: values)}}private nonisolated struct WorkflowHookPayload {let values: [String: Any]-+func string(for key: String) -> String? {Self.normalizedString(values[key])}-+private static func normalizedString(_ value: Any?) -> String? {switch value {case let string as String:diff --git a/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift b/CodexBar/Services/WorkflowStats/WorkflowStatsService.swiftindex 04709be..73d68c4 100644--- a/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift+++ b/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift@@ -29,45 +29,45 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {if let repairedSnapshot = repairDailyCacheIfNeededOnQueue() {return repairedSnapshot}-+if let aggregates = loadDailyAggregatesOnQueue(), !aggregates.isEmpty {return WorkflowStatsSnapshot(dailyAggregates: aggregates)}-+guard let data = loadEventLogDataOnQueue(), !data.isEmpty else {return .empty}-+return WorkflowStatsSnapshot(events: WorkflowHookEvent.decodeJSONLines(from: data))}-+private func repairDailyCacheIfNeededOnQueue() -> WorkflowStatsSnapshot? {guard dailyCacheNeedsRebuildOnQueue() else {return nil}-+do {let eventLogData = try loadEventLogDataForRebuildOnQueue()let eventLogStateAfterRead = WorkflowStatsStorage.fileState(at: eventLogURL)guard eventLogStateAfterRead.size == UInt64(eventLogData.count) else {throw WorkflowStatsRebuildError.eventsChangedDuringRebuild}-+let decodedEvents = WorkflowHookEvent.decodeJSONLinesWithFailures(from: eventLogData)if eventLogStateAfterRead.size > 0,decodedEvents.values.isEmpty,decodedEvents.failedLineCount > 0 {throw WorkflowStatsRebuildError.noReadableEvents(corruptLineCount: decodedEvents.failedLineCount)}-+let aggregates = WorkflowDailyAggregate.aggregates(from: decodedEvents.values)-+return try WorkflowStatsStorage.withExclusiveLock {let currentEventLogState = WorkflowStatsStorage.fileState(at: eventLogURL)guard currentEventLogState == eventLogStateAfterRead else {throw WorkflowStatsRebuildError.eventsChangedDuringRebuild}-+var state = WorkflowStatsStorage.loadMaintenanceState()guard state.needsDailyRebuild(eventLogSize: currentEventLogState.size,@@ -75,16 +75,16 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {) else {return loadDailyAggregatesOnQueue().map { WorkflowStatsSnapshot(dailyAggregates: $0) } ?? .empty}-+let data = try WorkflowDailyAggregate.encodeJSONLines(aggregates)try data.write(to: dailyLogURL, options: .atomic)-+state.markDailyRebuildSucceeded(eventLogSize: currentEventLogState.size,corruptEventLineCount: decodedEvents.failedLineCount)try WorkflowStatsStorage.saveMaintenanceState(state)-+return WorkflowStatsSnapshot(dailyAggregates: aggregates)}} catch {@@ -92,22 +92,22 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {return nil}}-+private func dailyCacheNeedsRebuildOnQueue() -> Bool {WorkflowStatsStorage.loadMaintenanceState().needsDailyRebuild(eventLogSize: WorkflowStatsStorage.fileSize(at: eventLogURL),dailyLogURL: dailyLogURL)}-+private func loadEventLogDataForRebuildOnQueue() throws -> Data {guard FileManager.default.fileExists(atPath: eventLogURL.path) else {return Data()}-+return try Data(contentsOf: eventLogURL)}-+private func recordDailyRebuildFailureOnQueue(_ error: Error) {try? WorkflowStatsStorage.withExclusiveLock {var state = WorkflowStatsStorage.loadMaintenanceState()@@ -115,17 +115,17 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {try WorkflowStatsStorage.saveMaintenanceState(state)}}-+private func loadDailyAggregatesOnQueue() -> [WorkflowDailyAggregate]? {guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {return nil}-+let aggregates = WorkflowDailyAggregate.decodeJSONLines(from: data)guard !aggregates.isEmpty else {return nil}-+return WorkflowDailyAggregate.normalized(aggregates: aggregates)}@@ -169,27 +169,27 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {nonisolated enum WorkflowStatsStorage {private static let retentionDayCount = 210private static let identifierRetentionDayCount = 7-+static func eventsURL() -> URL {directoryURL().appendingPathComponent("events.jsonl", isDirectory: false)}-+static func dailyURL() -> URL {directoryURL().appendingPathComponent("daily.jsonl", isDirectory: false)}-+static func lockURL() -> URL {directoryURL().appendingPathComponent("stats.lock", isDirectory: false)}-+static func maintenanceURL() -> URL {directoryURL().appendingPathComponent("maintenance.json", isDirectory: false)}-+static func directoryURL() -> URL {let applicationSupportURL = FileManager.default.urls(for: .applicationSupportDirectory,@@ -202,72 +202,72 @@ nonisolated enum WorkflowStatsStorage {.appendingPathComponent("CodexBar", isDirectory: true).appendingPathComponent("HookEvents", isDirectory: true)}-+static func withExclusiveLock<T>(_ work: () throws -> T) throws -> T {try FileManager.default.createDirectory(at: directoryURL(),withIntermediateDirectories: true)-+let lockURL = lockURL()if !FileManager.default.fileExists(atPath: lockURL.path) {FileManager.default.createFile(atPath: lockURL.path, contents: nil)}-+let lockHandle = try FileHandle(forUpdating: lockURL)defer {try? lockHandle.close()}-+if flock(lockHandle.fileDescriptor, LOCK_EX) != 0 {throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)}-+defer {flock(lockHandle.fileDescriptor, LOCK_UN)}-+return try work()}-+static func loadMaintenanceState() -> WorkflowStatsMaintenanceState {let url = maintenanceURL()guard let data = try? Data(contentsOf: url), !data.isEmpty,let state = try? JSONDecoder().decode(WorkflowStatsMaintenanceState.self, from: data) else {return WorkflowStatsMaintenanceState()}-+return state}-+static func saveMaintenanceState(_ state: WorkflowStatsMaintenanceState) throws {try FileManager.default.createDirectory(at: directoryURL(),withIntermediateDirectories: true)-+let encoder = JSONEncoder()encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]let data = try encoder.encode(state)try data.write(to: maintenanceURL(), options: .atomic)}-+static func fileSize(at url: URL) -> UInt64 {fileState(at: url).size}-+static func fileState(at url: URL) -> WorkflowStatsFileState {guard let attributes = try? FileManager.default.attributesOfItem(atPath: url.path),let fileSize = attributes[.size] as? NSNumber else {return WorkflowStatsFileState(size: 0, modifiedAt: nil)}-+return WorkflowStatsFileState(size: fileSize.uint64Value,modifiedAt: attributes[.modificationDate] as? Date)}-+static func retentionCutoffDate(today: Date = Date(), calendar: Calendar = .current) -> Date {let todayStart = calendar.startOfDay(for: today)return calendar.date(@@ -276,7 +276,7 @@ nonisolated enum WorkflowStatsStorage {to: todayStart) ?? todayStart}-+static func identifierRetentionCutoffDate(today: Date = Date(), calendar: Calendar = .current) -> Date {let todayStart = calendar.startOfDay(for: today)return calendar.date(@@ -294,7 +294,7 @@ nonisolated struct WorkflowStatsFileState: Equatable {nonisolated struct WorkflowStatsMaintenanceState: Codable, Equatable {private static let maxErrorSummaryLength = 240-+var lastMaintenanceDate: String?var lastAggregatedEventLogSize: UInt64?var needsDailyRebuild: Bool@@ -302,7 +302,7 @@ nonisolated struct WorkflowStatsMaintenanceState: Codable, Equatable {var lastDailyRebuildFailedAt: String?var lastDailyRebuildError: String?var corruptEventLineCount: Int-+init(lastMaintenanceDate: String? = nil,lastAggregatedEventLogSize: UInt64? = nil,@@ -320,7 +320,7 @@ nonisolated struct WorkflowStatsMaintenanceState: Codable, Equatable {self.lastDailyRebuildError = lastDailyRebuildErrorself.corruptEventLineCount = corruptEventLineCount}-+init(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self)self.lastMaintenanceDate = try container.decodeIfPresent(String.self, forKey: .lastMaintenanceDate)@@ -331,32 +331,32 @@ nonisolated struct WorkflowStatsMaintenanceState: Codable, Equatable {self.lastDailyRebuildError = try container.decodeIfPresent(String.self, forKey: .lastDailyRebuildError)self.corruptEventLineCount = try container.decodeIfPresent(Int.self, forKey: .corruptEventLineCount) ?? 0}-+func needsDailyRebuild(eventLogSize: UInt64, dailyLogURL: URL) -> Bool {if needsDailyRebuild {return true}-+guard eventLogSize > 0 else {return false}-+guard let lastAggregatedEventLogSize else {return true}-+if lastAggregatedEventLogSize != eventLogSize {return true}-+return WorkflowStatsStorage.fileSize(at: dailyLogURL) == 0}-+mutating func markDailyCacheUpdated(eventLogSize: UInt64) {needsDailyRebuild = falselastAggregatedEventLogSize = eventLogSize}-+mutating func markDailyRebuildSucceeded(eventLogSize: UInt64, corruptEventLineCount: Int) {markDailyCacheUpdated(eventLogSize: eventLogSize)lastDailyRebuildAt = Self.timestampString()@@ -364,28 +364,28 @@ nonisolated struct WorkflowStatsMaintenanceState: Codable, Equatable {lastDailyRebuildError = nilself.corruptEventLineCount = corruptEventLineCount}-+mutating func markDailyRebuildNeeded(error: Error? = nil) {needsDailyRebuild = true-+guard let error else {return}-+lastDailyRebuildFailedAt = Self.timestampString()lastDailyRebuildError = Self.errorSummary(error)}-+static func timestampString(from date: Date = Date()) -> String {ISO8601DateFormatter.codexFractional.string(from: date)}-+private static func errorSummary(_ error: Error) -> String {let message = error.localizedDescriptionguard message.count > maxErrorSummaryLength else {return message}-+return String(message.prefix(maxErrorSummaryLength))}}@@ -393,7 +393,7 @@ nonisolated struct WorkflowStatsMaintenanceState: Codable, Equatable {private nonisolated enum WorkflowStatsRebuildError: LocalizedError {case eventsChangedDuringRebuildcase noReadableEvents(corruptLineCount: Int)-+var errorDescription: String? {switch self {case .eventsChangedDuringRebuild:diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swiftindex 43c82ba..6f55293 100644--- a/CodexBar/Views/Menu/UsageHeatmap.swift+++ b/CodexBar/Views/Menu/UsageHeatmap.swift@@ -342,39 +342,47 @@ private struct UsageHeatmapTooltip: View {@Environment(\.colorScheme) private var colorSchemevar body: some View {- VStack(alignment: .leading, spacing: 3) {+ VStack(alignment: .leading, spacing: Metrics.rowSpacing) {if showsWorkflowStats {- HStack(alignment: .firstTextBaseline, spacing: 4) {+ HStack(alignment: .firstTextBaseline, spacing: Metrics.headerSpacing) {dateText- Spacer(minLength: 4)+ Spacer(minLength: Metrics.headerMinimumSpacer)tokenText}- metricRow("会话总数", value: "\(day.workflowStats.sessionCount)")- metricRow("对话轮次", value: "\(day.workflowStats.turnCount)")- metricRow("子智能体", value: "\(day.workflowStats.subagentCount)")- metricRow("工具调用", value: "\(day.workflowStats.toolCallCount)")- metricRow("权限请求", value: "\(day.workflowStats.permissionRequestCount)")- metricRow("上下文压缩", value: "\(day.workflowStats.contextCompactionCount)")+ ForEach(workflowMetricRows, id: \.label) { row in+ metricRow(row.label, value: row.value)+ }} else {dateTexttokenText}}- .padding(.horizontal, 8)- .padding(.vertical, 6)+ .padding(.horizontal, Metrics.horizontalPadding)+ .padding(.vertical, Metrics.verticalPadding).frame(width: tooltipWidth,height: tooltipHeight,alignment: .leading).background {- RoundedRectangle(cornerRadius: 7, style: .continuous)+ RoundedRectangle(cornerRadius: Metrics.cornerRadius, style: .continuous).fill(tooltipFill)}- .liquidGlassSurface(cornerRadius: 7)+ .liquidGlassSurface(cornerRadius: Metrics.cornerRadius)+ }++ private var workflowMetricRows: [(label: String, value: String)] {+ [+ ("会话总数", "\(day.workflowStats.sessionCount)"),+ ("对话轮次", "\(day.workflowStats.turnCount)"),+ ("子智能体", "\(day.workflowStats.subagentCount)"),+ ("工具调用", "\(day.workflowStats.toolCallCount)"),+ ("权限请求", "\(day.workflowStats.permissionRequestCount)"),+ ("上下文压缩", "\(day.workflowStats.contextCompactionCount)")+ ]}private var tooltipHeight: CGFloat {@@ -408,34 +416,49 @@ private struct UsageHeatmapTooltip: View {private var dateFont: Font {showsWorkflowStats- ? .system(size: 10).monospacedDigit()+ ? .system(size: Metrics.workflowFontSize).monospacedDigit(): .caption2.monospacedDigit()}private var tokenFont: Font {showsWorkflowStats- ? .system(size: 10).monospacedDigit().weight(.semibold)+ ? .system(size: Metrics.workflowFontSize).monospacedDigit().weight(.semibold): .caption.monospacedDigit().weight(.semibold)}private func metricRow(_ label: String, value: String) -> some View {- HStack(spacing: 6) {+ HStack(spacing: Metrics.metricRowSpacing) {Text(label).foregroundStyle(.secondary)- .frame(width: 54, alignment: .leading)+ .frame(width: Metrics.metricLabelWidth, alignment: .leading)Text(value).foregroundStyle(Color.codexLabel).monospacedDigit().lineLimit(1)- .truncationMode(.tail)+ .minimumScaleFactor(Metrics.metricValueMinimumScale)+ .allowsTightening(true)+ .layoutPriority(1).frame(maxWidth: .infinity, alignment: .trailing)}- .font(.system(size: 10))+ .font(.system(size: Metrics.workflowFontSize))}private var tooltipFill: Color {Color(nsColor: .windowBackgroundColor).opacity(colorScheme == .dark ? 0.88 : 0.82)}++ private enum Metrics {+ static let rowSpacing: CGFloat = 3+ static let headerSpacing: CGFloat = 4+ static let headerMinimumSpacer: CGFloat = 4+ static let horizontalPadding: CGFloat = 8+ static let verticalPadding: CGFloat = 6+ static let cornerRadius: CGFloat = 7+ static let metricRowSpacing: CGFloat = 6+ static let metricLabelWidth: CGFloat = 54+ static let metricValueMinimumScale: CGFloat = 0.60+ static let workflowFontSize: CGFloat = 10+ }}diff --git a/Docs/CodexHook.md b/Docs/CodexHook.mdindex 567fa27..095e6c4 100644--- a/Docs/CodexHook.md+++ b/Docs/CodexHook.md@@ -10,13 +10,12 @@~/.codex/hooks.json```-写入前会先移除 CodexBar 自己旧的 Hook 处理器,再按当前 App 路径安装新处理器。关闭时只移除 CodexBar 自己的处理器,用户自定义 Hook、其他 App Hook 和同事件下的其他处理器必须保留。+开启和关闭都会先移除当前 App 可执行文件路径对应的 CodexBar hook。开启时随后按当前 App 路径安装 hook。用户自定义 Hook、其他 App Hook、其他路径的 CodexBar Hook 和同事件下的其他处理器必须保留。CodexBar 处理器的识别条件:- `type` 是 `command`-- `command` 包含 `/Contents/MacOS/CodexBar`-- `command` 包含 `--hook-event`+- `command` 必须等于当前 App 可执行文件路径生成的命令, 例如 `'<当前 CodexBar 可执行文件路径>' --hook-event SessionStart`检测是否已开启时,要求全部 CodexBar 事件都存在当前 App 路径对应的处理器。diff --git a/appcast.xml b/appcast.xmlindex 8ba386e..8eba4c8 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 2.3.1</title>+ <sparkle:version>14</sparkle:version>+ <sparkle:shortVersionString>2.3.1</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes/2.3.1.html</sparkle:releaseNotesLink>+ <pubDate>Sun, 21 Jun 2026 14:41:21 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v2.3.1.dmg" sparkle:edSignature="DXxB9AK0MYlB72pLPFx2/0EnBgLcUVsA8P0pcDJzv+YK08SaQDC4JQY8ka5jjxID8kkv6o7MucK+JRjowfeeCA==" length="2848452" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 2.3.0</title><sparkle:version>13</sparkle:version>