CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
refactor: 精简内部状态与重复逻辑
Bob0ac2a901b666
diff --git a/CLAUDE.md b/CLAUDE.mdindex cdf8dea..25abeeb 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -34,7 +34,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co## 项目概述-CodexBar 是一个 macOS 菜单栏应用,以 `LSUIElement` 方式运行,没有 Dock 图标,展示本机 Codex 的账号状态、额度、Token 用量、实时任务和工作流统计。技术栈为 Swift 6 + SwiftUI + AppKit + MVVM,唯一外部依赖是 Sparkle `2.9.5+`(SwiftPM)。最低系统版本为 macOS `15.0`+CodexBar 是一个 macOS 菜单栏应用,以 `LSUIElement` 方式运行,没有 Dock 图标,展示本机 Codex 的账号状态、额度、Token 用量、实时任务和工作流统计。技术栈为 Swift 6 + SwiftUI + AppKit + MVVM,唯一外部依赖是 Sparkle `2.9.6+`(SwiftPM)。最低系统版本为 macOS `15.0`Xcode 工程有两个 target:主 App `CodexBar` 和随 App 嵌入的 root helper `CodexBarHelper`(command-line tool + LaunchDaemon)。**没有测试 target**,验证依靠构建通过和实际运行。diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex 856ab9b..b5afafc 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -261,17 +261,13 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;CREATE_INFOPLIST_SECTION_IN_BINARY = YES;- DEAD_CODE_STRIPPING = YES;- DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_SANDBOX = NO;ENABLE_HARDENED_RUNTIME = YES;GENERATE_INFOPLIST_FILE = YES;- MACOSX_DEPLOYMENT_TARGET = 15.0;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.debug.helper;PRODUCT_NAME = "$(TARGET_NAME)";SKIP_INSTALL = YES;SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;- SWIFT_VERSION = 6.0;};name = Debug;};@@ -281,17 +277,13 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;CREATE_INFOPLIST_SECTION_IN_BINARY = YES;- DEAD_CODE_STRIPPING = YES;- DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_SANDBOX = NO;ENABLE_HARDENED_RUNTIME = YES;GENERATE_INFOPLIST_FILE = YES;- MACOSX_DEPLOYMENT_TARGET = 15.0;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.helper;PRODUCT_NAME = "$(TARGET_NAME)";SKIP_INSTALL = YES;SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;- SWIFT_VERSION = 6.0;};name = Release;};@@ -433,8 +425,6 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- DEAD_CODE_STRIPPING = YES;- DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;ENABLE_APP_SANDBOX = NO;ENABLE_HARDENED_RUNTIME = YES;@@ -444,7 +434,6 @@GENERATE_INFOPLIST_FILE = NO;INFOPLIST_FILE = CodexBar/Resources/Info.plist;INFOPLIST_KEY_CFBundleDisplayName = "CodexBar Debug";- INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/../Frameworks",@@ -452,12 +441,10 @@PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.debug;PRODUCT_NAME = "$(TARGET_NAME)";REGISTER_APP_GROUPS = YES;- STRING_CATALOG_GENERATE_SYMBOLS = YES;SWIFT_APPROACHABLE_CONCURRENCY = YES;SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;SWIFT_EMIT_LOC_STRINGS = YES;SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;- SWIFT_VERSION = 6.0;};name = Debug;};@@ -470,8 +457,6 @@CODE_SIGN_IDENTITY = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- DEAD_CODE_STRIPPING = YES;- DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;ENABLE_APP_SANDBOX = NO;ENABLE_HARDENED_RUNTIME = YES;@@ -481,7 +466,6 @@GENERATE_INFOPLIST_FILE = NO;INFOPLIST_FILE = CodexBar/Resources/Info.plist;INFOPLIST_KEY_CFBundleDisplayName = CodexBar;- INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/../Frameworks",@@ -490,12 +474,10 @@PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "$(CODEXBAR_PROVISIONING_PROFILE_SPECIFIER)";REGISTER_APP_GROUPS = YES;- STRING_CATALOG_GENERATE_SYMBOLS = YES;SWIFT_APPROACHABLE_CONCURRENCY = YES;SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;SWIFT_EMIT_LOC_STRINGS = YES;SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;- SWIFT_VERSION = 6.0;};name = Release;};@@ -534,7 +516,7 @@repositoryURL = "https://github.com/sparkle-project/Sparkle";requirement = {kind = upToNextMajorVersion;- minimumVersion = 2.9.5;+ minimumVersion = 2.9.6;};};/* End XCRemoteSwiftPackageReference section */diff --git a/CodexBar/Controllers/ResetCreditsPanelController.swift b/CodexBar/Controllers/ResetCreditsPanelController.swiftindex 209aa4c..10d9dd7 100644--- a/CodexBar/Controllers/ResetCreditsPanelController.swift+++ b/CodexBar/Controllers/ResetCreditsPanelController.swift@@ -70,10 +70,11 @@ final class ResetCreditsPanelController {))let panelSize = ResetCreditsPanelView.panelSize(for: resolvedContext)- let position = panelPosition(- for: panelSize,+ let position = SidePanelSupport.anchoredPosition(+ panelSize: panelSize,menuSurfaceFrame: menuSurfaceFrame,visibleFrame: (menuSurfaceWindow.screen ?? NSScreen.main)?.visibleFrame ?? menuSurfaceFrame,+ screenFrame: nil,alignmentScreenFrame: resolvedContext.alignmentScreenFrame,preferredSide: resolvedContext.preferredSide)@@ -87,26 +88,6 @@ final class ResetCreditsPanelController {presenter.present(panel, at: position, relativeTo: menuSurfaceWindow)}- private func panelPosition(- for panelSize: CGSize,- menuSurfaceFrame: CGRect,- visibleFrame: CGRect,- alignmentScreenFrame: CGRect?,- preferredSide: UsageHeatmapDetailSide- ) -> SidePanelPosition {- SidePanelSupport.position(- panelSize: panelSize,- menuSurfaceFrame: menuSurfaceFrame,- visibleFrame: visibleFrame,- preferredSide: preferredSide,- proposedY: SidePanelSupport.alignedProposedY(- panelSize: panelSize,- menuSurfaceFrame: menuSurfaceFrame,- alignmentScreenFrame: alignmentScreenFrame- )- )- }-private func panelMaximumHeight(menuSurfaceFrame: CGRect,alignmentScreenFrame: CGRect?diff --git a/CodexBar/Controllers/SidePanelSupport.swift b/CodexBar/Controllers/SidePanelSupport.swiftindex 0a74b8f..c7e8de6 100644--- a/CodexBar/Controllers/SidePanelSupport.swift+++ b/CodexBar/Controllers/SidePanelSupport.swift@@ -506,7 +506,7 @@ enum SidePanelSupport {}/// 面板顶边对齐锚点行顶边, 锚点无效时回退宿主内容区垂直居中- static func alignedProposedY(+ private static func alignedProposedY(panelSize: CGSize,menuSurfaceFrame: CGRect,alignmentScreenFrame: CGRect?diff --git a/CodexBar/Models/CodexUsageModels.swift b/CodexBar/Models/CodexUsageModels.swiftindex c20068e..6f407da 100644--- a/CodexBar/Models/CodexUsageModels.swift+++ b/CodexBar/Models/CodexUsageModels.swift@@ -16,13 +16,9 @@ nonisolated struct UsageSummary: Decodable, Equatable {}/// 单日 token bucket, startDate 使用 yyyy-MM-dd 作为稳定键-nonisolated struct DailyUsageBucket: Decodable, Equatable, Identifiable {+nonisolated struct DailyUsageBucket: Decodable, Equatable {let startDate: Stringlet tokens: Int-- var id: String {- startDate- }}/// token 热力图使用的只读快照, 负责按日期聚合重复 bucket@@ -48,22 +44,4 @@ nonisolated struct CodexUsageSnapshot: Equatable {let startDate = CodexDateFormat.dayString(from: date)return tokensByDate[startDate]}-- /// 给热力图生成按周排列的最近日期网格, 每列从周日开始- func recentWeekGrid(columnCount: Int, endingDaysAgo: Int = 0, today: Date = Date()) -> [DailyUsageBucket?] {- CodexWeekGrid.dates(- columnCount: columnCount,- endingDaysAgo: endingDaysAgo,- today: today- )- .map { date in- date.map {- let startDate = CodexDateFormat.dayString(from: $0)- return DailyUsageBucket(- startDate: startDate,- tokens: tokensByDate[startDate] ?? 0- )- }- }- }}diff --git a/CodexBar/Models/CodexWorkflowModels.swift b/CodexBar/Models/CodexWorkflowModels.swiftindex 0487319..c2290e0 100644--- a/CodexBar/Models/CodexWorkflowModels.swift+++ b/CodexBar/Models/CodexWorkflowModels.swift@@ -203,7 +203,7 @@ nonisolated struct WorkflowHookEvent: Decodable, Equatable {// MARK: - 每日聚合指标/// 热力图详情面板直接消费的每日统计-nonisolated struct WorkflowDailyMetrics: Equatable, Identifiable {+nonisolated struct WorkflowDailyMetrics: Equatable {let startDate: Stringlet sessionCount: Intlet turnCount: Int@@ -213,10 +213,6 @@ nonisolated struct WorkflowDailyMetrics: Equatable, Identifiable {let subagentCount: Intlet modelCounts: [String: Int]- var id: String {- startDate- }-var mostUsedModel: String? {modelCounts.filter { $0.value > 0 }@@ -374,24 +370,6 @@ nonisolated struct WorkflowSnapshot: Equatable {}}- func recentWeekGrid(columnCount: Int, endingDaysAgo: Int = 0, today: Date = Date()) -> [WorkflowDailyMetrics?] {- let metricsByDate = dailyMetrics.reduce(into: [String: WorkflowDailyMetrics]()) { result, metrics in- result[metrics.startDate] = metrics- }-- return CodexWeekGrid.dates(- columnCount: columnCount,- endingDaysAgo: endingDaysAgo,- today: today- )- .map { date in- date.map {- let startDate = CodexDateFormat.dayString(from: $0)- return metricsByDate[startDate] ?? WorkflowDailyMetrics.empty(startDate: startDate)- }- }- }-private static func merge(_ records: [WorkflowSyncedDailyRecord],into metricsByDate: inout [String: WorkflowDailyMetrics]@@ -549,7 +527,7 @@ nonisolated struct WorkflowHookCountAvailability {}/// daily.jsonl 中的持久化聚合行, 同时兼容保留 ID 和只保留计数两种形态-nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {+nonisolated struct WorkflowDailyAggregate: Codable, Equatable {let date: Stringvar sourceGeneration: String?var sourceIsFresh: Bool@@ -572,10 +550,6 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {var sessionIds: [String]?var turnIds: [String]?- var id: String {- date- }-/// 增量路径只有在完整 ID 集合仍然存在时才能继续安全去重var supportsIncrementalAggregation: Bool {sessionCount == nil && turnCount == nil@@ -843,7 +817,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {}/// 同步存储中保存的脱敏每日聚合行: 对应 daily.jsonl 但不包含 sessionIds / turnIds-nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable, Identifiable {+nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable {let date: Stringvar sourceGeneration: String?var eventCount: Int?@@ -863,10 +837,6 @@ nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable, Identifiablvar projectCounts: [String: Int]var modelCounts: [String: Int]- var id: String {- date- }-var metrics: WorkflowDailyMetrics {WorkflowDailyMetrics(startDate: date,diff --git a/CodexBar/Models/UsageHeatmapDay.swift b/CodexBar/Models/UsageHeatmapDay.swiftindex 9d8a4c8..ec607f8 100644--- a/CodexBar/Models/UsageHeatmapDay.swift+++ b/CodexBar/Models/UsageHeatmapDay.swift@@ -25,40 +25,28 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {// Hook 开启时当天工作流统计可见// Hook 关闭时只在 token bucket 已返回时展示今天let endingDaysAgo = showsWorkflow || todayTokenCount != nil ? 0 : 1- let tokenDays = usage.recentWeekGrid(- columnCount: columnCount,- endingDaysAgo: endingDaysAgo,- today: today- )- let workflowDays = workflow.recentWeekGrid(+ let workflowByDate = workflow.dailyMetrics.reduce(into: [String: WorkflowDailyMetrics]()) { result, metrics in+ result[metrics.startDate] = metrics+ }+ let todayString = CodexDateFormat.dayString(from: today)++ return CodexWeekGrid.dates(columnCount: columnCount,endingDaysAgo: endingDaysAgo,today: today)-- return merge(- tokenDays: tokenDays,- workflowDays: workflowDays,- todayString: CodexDateFormat.dayString(from: today),- todayTokenCount: todayTokenCount- )- }-- private static func merge(- tokenDays: [DailyUsageBucket?],- workflowDays: [WorkflowDailyMetrics?],- todayString: String,- todayTokenCount: Int?- ) -> [UsageHeatmapDay?] {- zip(tokenDays, workflowDays).map { tokenDay, workflowDay in- guard let startDate = tokenDay?.startDate ?? workflowDay?.startDate else {+ .map { date in+ guard let date else {return nil}+ let startDate = CodexDateFormat.dayString(from: date)return UsageHeatmapDay(startDate: startDate,- tokenCount: startDate == todayString ? todayTokenCount : tokenDay?.tokens ?? 0,- workflow: workflowDay ?? .empty(startDate: startDate)+ tokenCount: startDate == todayString+ ? todayTokenCount+ : usage.tokenCount(on: date) ?? 0,+ workflow: workflowByDate[startDate] ?? .empty(startDate: startDate))}}diff --git a/CodexBar/Services/Settings/CodexCLINotificationSettings.swift b/CodexBar/Services/Settings/CodexCLINotificationSettings.swiftindex 6f3839d..c0c6277 100644--- a/CodexBar/Services/Settings/CodexCLINotificationSettings.swift+++ b/CodexBar/Services/Settings/CodexCLINotificationSettings.swift@@ -10,17 +10,12 @@ final class CodexCLINotificationSettings: ObservableObject {@Published private(set) var errorMessage: String?private let codexStatusService: CodexStatusService- private var updateTask: Task<Void, Never>?- private var updateGeneration = 0+ private let updateCoordinator = RefreshTaskCoordinator()init(codexStatusService: CodexStatusService) {self.codexStatusService = codexStatusService}- deinit {- updateTask?.cancel()- }-func refresh() {guard !isUpdating else {return@@ -83,29 +78,25 @@ final class CodexCLINotificationSettings: ObservableObject {private func runLatestUpdate(operation: ConfigOperation,- body: @escaping @MainActor (CodexCLINotificationSettings, Int) async throws -> Bool+ body: @escaping @MainActor @Sendable (CodexCLINotificationSettings, Int) async throws -> Bool) {- updateTask?.cancel()- updateGeneration += 1- let generation = updateGeneration-isUpdating = trueerrorMessage = nil- updateTask = Task { [weak self] in+ updateCoordinator.start { [weak self] generation inguard let self else {return}do {let isEnabled = try await body(self, generation)- guard isCurrentUpdate(generation) else {+ guard updateCoordinator.canCommit(generation) else {return}self.isEnabled = isEnabled} catch is CancellationError {return} catch {- guard isCurrentUpdate(generation) else {+ guard updateCoordinator.canCommit(generation) else {return}let logStage = operation.logStage@@ -117,30 +108,19 @@ final class CodexCLINotificationSettings: ObservableObject {errorMessage = operation.errorPrefix}- finishUpdate(generation)- }- }-- private func finishUpdate(_ generation: Int) {- guard isCurrentUpdate(generation) else {- return+ updateCoordinator.finish(generation) {+ isUpdating = false+ }}-- isUpdating = false- updateTask = nil}private func ensureCurrentUpdate(_ generation: Int) throws {try Task.checkCancellation()- guard isCurrentUpdate(generation) else {+ guard updateCoordinator.canCommit(generation) else {throw CancellationError()}}- private func isCurrentUpdate(_ generation: Int) -> Bool {- generation == updateGeneration- }-private enum SettingsError: LocalizedError {case verificationFaileddiff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swiftindex 80c3f6f..43460f0 100644--- a/CodexBar/Services/Settings/CodexHookSettings.swift+++ b/CodexBar/Services/Settings/CodexHookSettings.swift@@ -35,8 +35,7 @@ final class CodexHookSettings: ObservableObject {private let hooksURL: URLprivate let fileManager: FileManagerprivate let codexStatusService: CodexStatusService- private var updateTask: Task<Void, Never>?- private var updateGeneration = 0+ private let updateCoordinator = RefreshTaskCoordinator()/// refresh() 上次读到的安装结论, 首次读取前为 nil/// 不能用 isEnabled 代替: 它的初始值是 false, 会把首次读取当成一次配置变化private var lastKnownInstalled: Bool?@@ -51,10 +50,6 @@ final class CodexHookSettings: ObservableObject {self.codexStatusService = codexStatusService}- deinit {- updateTask?.cancel()- }-// MARK: - 对外入口func refresh() {@@ -158,7 +153,7 @@ final class CodexHookSettings: ObservableObject {} catch is CancellationError {return} catch let error as HookConfigError {- guard isCurrentUpdate(generation) else {+ guard updateCoordinator.canCommit(generation) else {return}@@ -166,7 +161,7 @@ final class CodexHookSettings: ObservableObject {assignVerified(false, reason: .validationFailed)operationErrorMessage = error.localizedDescription} catch {- guard isCurrentUpdate(generation) else {+ guard updateCoordinator.canCommit(generation) else {return}@@ -194,52 +189,37 @@ final class CodexHookSettings: ObservableObject {private func runLatestUpdate(showProgress: Bool,- _ operation: @escaping @MainActor (CodexHookSettings, Int) async -> Void+ _ operation: @escaping @MainActor @Sendable (CodexHookSettings, Int) async -> Void) {- updateTask?.cancel()- updateGeneration += 1- let generation = updateGeneration-if showProgress {isUpdating = trueoperationErrorMessage = nil}- updateTask = Task { [weak self] in+ updateCoordinator.start { [weak self] generation inguard let self else {return}await operation(self, generation)- finishUpdate(generation, showProgress: showProgress)- }- }-- private func finishUpdate(_ generation: Int, showProgress: Bool) {- guard isCurrentUpdate(generation) else {- return- }-- if showProgress {- isUpdating = false+ updateCoordinator.finish(generation) {+ if showProgress {+ isUpdating = false+ }+ }}- updateTask = nil- }-- private func isCurrentUpdate(_ generation: Int) -> Bool {- generation == updateGeneration}private func ensureCurrentUpdate(_ generation: Int) throws {try Task.checkCancellation()- guard isCurrentUpdate(generation) else {+ guard updateCoordinator.canCommit(generation) else {throw CancellationError()}}private func handleApplyError(_ error: Error, generation: Int) {- guard isCurrentUpdate(generation) else {+ guard updateCoordinator.canCommit(generation) else {return}@@ -479,7 +459,7 @@ private extension CodexHookSettings {} catch is CancellationError {return} catch {- guard isCurrentUpdate(generation) else {+ guard updateCoordinator.canCommit(generation) else {return}diff --git a/CodexBar/Services/Settings/WorkflowSyncSettings.swift b/CodexBar/Services/Settings/WorkflowSyncSettings.swiftindex 412926d..5dd1798 100644--- a/CodexBar/Services/Settings/WorkflowSyncSettings.swift+++ b/CodexBar/Services/Settings/WorkflowSyncSettings.swift@@ -15,8 +15,7 @@ final class WorkflowSyncSettings: ObservableObject {private let defaults: UserDefaultsprivate var cancellables = Set<AnyCancellable>()- private var accountStatusTask: Task<Void, Never>?- private var accountStatusGeneration = 0+ private let accountStatusCoordinator = RefreshTaskCoordinator()init(defaults: UserDefaults = .standard) {self.defaults = defaults@@ -26,10 +25,6 @@ final class WorkflowSyncSettings: ObservableObject {refreshSyncAvailability()}- deinit {- accountStatusTask?.cancel()- }-func refresh() {isEnabled = Self.isEnabled(defaults: defaults)if !isEnabled {@@ -138,19 +133,15 @@ final class WorkflowSyncSettings: ObservableObject {}private func refreshSyncAvailability() {- accountStatusGeneration += 1- let generation = accountStatusGeneration-- accountStatusTask?.cancel()- accountStatusTask = Task { @MainActor [weak self] in+ accountStatusCoordinator.start { [weak self] generation inlet result = await Self.querySyncAvailability()guard let self,- !Task.isCancelled,- generation == accountStatusGeneration else {+ accountStatusCoordinator.canCommit(generation) else {return}applyAvailabilityResult(result)+ accountStatusCoordinator.finish(generation) {}}}diff --git a/CodexBar/Services/Workflow/CodexActivityMonitor.swift b/CodexBar/Services/Workflow/CodexActivityMonitor.swiftindex 0d41aa2..8c1b807 100644--- a/CodexBar/Services/Workflow/CodexActivityMonitor.swift+++ b/CodexBar/Services/Workflow/CodexActivityMonitor.swift@@ -832,11 +832,7 @@ final class CodexActivityMonitor: ObservableObject {task.recordSubagentActivity(agentId: event.agentId,isStarting: isStarting,- at: event.timestamp,- hasReliableTaskAssociation: hasReliableSubagentAssociation(- eventSessionId: event.sessionId,- matchedKey: key- )+ at: event.timestamp)if event.timestamp >= task.lastActivityAt {@@ -860,27 +856,6 @@ final class CodexActivityMonitor: ObservableObject {tasks[key] = task}- /// Subagent Hook 的 turn 属于子 Agent 自己; 父任务只能通过共享 session 关联- private func hasReliableSubagentAssociation(- eventSessionId: String?,- matchedKey: CodexActivityTaskKey- ) -> Bool {- guard let eventSessionId,- matchedKey.sessionId == eventSessionId else {- return false- }-- let activeTaskCount = tasks.values.reduce(into: 0) { count, task in- if task.key.sessionId == eventSessionId {- count += 1- }- }- let hasPendingTask = pendingTerminalTasks.values.contains {- $0.task.key.sessionId == eventSessionId- }- return activeTaskCount == 1 && !hasPendingTask- }-private func waitForApproval(from event: WorkflowHookEvent,source: CodexActivityEventSourcediff --git a/CodexBar/Services/Workflow/CodexActivityTask.swift b/CodexBar/Services/Workflow/CodexActivityTask.swiftindex ddcf018..906863b 100644--- a/CodexBar/Services/Workflow/CodexActivityTask.swift+++ b/CodexBar/Services/Workflow/CodexActivityTask.swift@@ -237,10 +237,9 @@ struct CodexActivityTask {mutating func recordSubagentActivity(agentId: String?,isStarting: Bool,- at timestamp: Date,- hasReliableTaskAssociation: Bool+ at timestamp: Date) {- guard hasReliableTaskAssociation, let agentId else {+ guard let agentId else {isSubagentCountReliable = falsereturn}diff --git a/CodexBar/Services/Workflow/HookEventTailReader.swift b/CodexBar/Services/Workflow/HookEventTailReader.swiftindex 22454a5..729b8a7 100644--- a/CodexBar/Services/Workflow/HookEventTailReader.swift+++ b/CodexBar/Services/Workflow/HookEventTailReader.swift@@ -31,12 +31,7 @@ actor HookEventTailReader {private var activeFileIdentifier: UInt64?private var lastReportedSourceHealth: Bool?private var requestedDrainGeneration: UInt64 = 0- private var drainWaiters: [- UUID: (- generation: UInt64,- continuation: CheckedContinuation<HookEventDrainResult, Never>- )- ] = [:]+ private var drainWaiters: [UInt64: CheckedContinuation<HookEventDrainResult, Never>] = [:]init(onBatch: @escaping @MainActor @Sendable (HookEventBatch) -> Void) {self.onBatch = onBatch@@ -87,17 +82,16 @@ actor HookEventTailReader {requestedDrainGeneration &+= 1let generation = requestedDrainGeneration- let waiterID = UUID()hasPendingDrain = truereturn await withTaskCancellationHandler {await withCheckedContinuation { continuation in- drainWaiters[waiterID] = (generation, continuation)+ drainWaiters[generation] = continuationstartPendingReadIfNeeded()}} onCancel: {Task {- await self.cancelDrainWaiter(waiterID)+ await self.cancelDrainWaiter(generation)}}}@@ -140,11 +134,9 @@ actor HookEventTailReader {through generation: UInt64,with result: HookEventDrainResult) {- let completedWaiterIDs = drainWaiters.compactMap { waiterID, waiter in- waiter.generation <= generation ? waiterID : nil- }- for waiterID in completedWaiterIDs {- drainWaiters.removeValue(forKey: waiterID)?.continuation.resume(returning: result)+ let completedGenerations = drainWaiters.keys.filter { $0 <= generation }+ for completedGeneration in completedGenerations {+ drainWaiters.removeValue(forKey: completedGeneration)?.resume(returning: result)}}@@ -152,12 +144,12 @@ actor HookEventTailReader {let waiters = Array(drainWaiters.values)drainWaiters.removeAll()for waiter in waiters {- waiter.continuation.resume(returning: result)+ waiter.resume(returning: result)}}- private func cancelDrainWaiter(_ waiterID: UUID) {- drainWaiters.removeValue(forKey: waiterID)?.continuation.resume(returning: .cancelled)+ private func cancelDrainWaiter(_ generation: UInt64) {+ drainWaiters.removeValue(forKey: generation)?.resume(returning: .cancelled)}private var activeFileURL: URL {diff --git a/CodexBarHelper/main.swift b/CodexBarHelper/main.swiftindex f6d4423..9378d62 100644--- a/CodexBarHelper/main.swift+++ b/CodexBarHelper/main.swift@@ -304,6 +304,11 @@ private final class CodexBarHelperConnectionSession: NSObject, CodexBarHelperPro}private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unchecked Sendable {+ private struct Watchdog {+ let token: UUID+ let workItem: DispatchWorkItem+ }+private let queue = DispatchQueue(label: CodexBarHelperIPC.machServiceName + ".state")private let ownershipURL = CodexBarHelperStorage.ownershipURLprivate var ownership = SleepOwnership.idle@@ -311,8 +316,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @uncprivate var lastCompletedUpdateIdentifier: String?private var connections = Set<UUID>()private var clients = [UUID: ClientLease]()- private var watchdogs = [UUID: DispatchWorkItem]()- private var watchdogTokens = [UUID: UUID]()+ private var watchdogs = [UUID: Watchdog]()private var lastKnownSleepDisabled: Bool?private var ownershipTimer: DispatchSourceTimer?private var scheduledOwnershipCheckInterval: TimeInterval?@@ -622,11 +626,10 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unclet token = UUID()let workItem = DispatchWorkItem { [weak self] in- guard let self, watchdogTokens[clientIdentifier] == token else {+ guard let self, watchdogs[clientIdentifier]?.token == token else {return}watchdogs[clientIdentifier] = nil- watchdogTokens[clientIdentifier] = nilguard let lease = clients[clientIdentifier],lease.generation == generation,lease.isRequesting,@@ -639,8 +642,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unc_ = reconcileReleasedSleep(source: source, trigger: .connectionWatchdog)scheduleOwnershipTimerIfNeeded()}- watchdogs[clientIdentifier] = workItem- watchdogTokens[clientIdentifier] = token+ watchdogs[clientIdentifier] = Watchdog(token: token, workItem: workItem)queue.asyncAfter(deadline: .now() + CodexBarHelperIPC.watchdogGraceSeconds,execute: workItem@@ -648,8 +650,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unc}private func cancelWatchdog(for clientIdentifier: UUID) {- watchdogs.removeValue(forKey: clientIdentifier)?.cancel()- watchdogTokens[clientIdentifier] = nil+ watchdogs.removeValue(forKey: clientIdentifier)?.workItem.cancel()}// MARK: - 所有权与睡眠切换