Skip to content

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

fix: 完善任务通知与任务中心交互

Bobbfaa2117c717
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxproj
index 6876f25..fc769fc 100644
--- a/CodexBar.xcodeproj/project.pbxproj
+++ b/CodexBar.xcodeproj/project.pbxproj
@@ -282,7 +282,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 42;
+ CURRENT_PROJECT_VERSION = 43;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 4KJ362VJW5;
ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
@@ -298,7 +298,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 3.3.4;
+ MARKETING_VERSION = 3.3.5;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
@@ -321,7 +321,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 42;
+ CURRENT_PROJECT_VERSION = 43;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 4KJ362VJW5;
ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
@@ -337,7 +337,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 3.3.4;
+ MARKETING_VERSION = 3.3.5;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
diff --git a/CodexBar/App/CodexBarApp.swift b/CodexBar/App/CodexBarApp.swift
index a464cb6..ab4f49d 100644
--- a/CodexBar/App/CodexBarApp.swift
+++ b/CodexBar/App/CodexBarApp.swift
@@ -37,7 +37,7 @@ nonisolated extension Bundle {
object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
}
- /// ` v1.2.3` 形式的版本文案; 缺失时回退 `--`
+ /// `v1.2.3` 形式的版本文案; 缺失时回退 `--`
var displayVersionLabel: String {
guard let version = shortVersionString else { return "--" }
return "v\(version)"
diff --git a/CodexBar/Controllers/ActivityCenterPanelController.swift b/CodexBar/Controllers/ActivityCenterPanelController.swift
index e6ec8da..d1c74b9 100644
--- a/CodexBar/Controllers/ActivityCenterPanelController.swift
+++ b/CodexBar/Controllers/ActivityCenterPanelController.swift
@@ -13,6 +13,9 @@ final class ActivityCenterPanelController {
private weak var menuSurfaceWindow: NSWindow?
private weak var menuContentView: NSView?
private var cancellables = Set<AnyCancellable>()
+ private var presentationTask: Task<Void, Never>?
+ private var panelUpdateTask: Task<Void, Never>?
+ private var panelUpdateGeneration = 0
private lazy var presenter = SidePanelDrawerPresenter(
animationKey: Metrics.drawerTransformAnimationKey,
contentViewProvider: { [weak self] in
@@ -33,11 +36,7 @@ final class ActivityCenterPanelController {
guard let self, presentationState.isPresented else {
return
}
- if snapshot.hasTaskCenterContent {
- updateVisibleLayout(for: snapshot)
- } else {
- hide()
- }
+ schedulePanelUpdate(hasContent: snapshot.hasTaskCenterContent)
}
.store(in: &cancellables)
}
@@ -58,12 +57,12 @@ final class ActivityCenterPanelController {
relativeTo menuSurfaceWindow: NSWindow?,
contentView: NSView?
) {
- if isVisible {
+ if isVisible || presentationTask != nil {
hide()
return
}
- show(
+ schedulePresentation(
context: context,
relativeTo: menuSurfaceWindow,
contentView: contentView
@@ -71,26 +70,66 @@ final class ActivityCenterPanelController {
}
func hide(immediate: Bool = false) {
+ cancelScheduledPresentation()
// 热力图 hover 等高频路径会盲调 hide;已隐藏时跳过 @Published 写入,避免整个菜单重算。
guard presentationState.isPresented || presenter.isVisible else {
return
}
+ cancelScheduledPanelUpdate()
presentationState.isPresented = false
presenter.hide(immediate: immediate)
}
+ private func schedulePresentation(
+ context: CodexActivityCenterPanelContext,
+ relativeTo menuSurfaceWindow: NSWindow?,
+ contentView: NSView?
+ ) {
+ presentationTask = Task { @MainActor [weak self] in
+ guard let self else {
+ return
+ }
+
+ contentView?.layoutSubtreeIfNeeded()
+ if let menuSurfaceWindow,
+ context.anchorProvider.currentScreenFrame(
+ in: menuSurfaceWindow,
+ allowingCachedFrame: false
+ ) == nil {
+ await Task.yield()
+ }
+
+ guard !Task.isCancelled else {
+ return
+ }
+ presentationTask = nil
+ show(
+ context: context,
+ relativeTo: menuSurfaceWindow,
+ contentView: contentView
+ )
+ }
+ }
+
+ private func cancelScheduledPresentation() {
+ presentationTask?.cancel()
+ presentationTask = nil
+ }
+
private func show(
context: CodexActivityCenterPanelContext,
relativeTo menuSurfaceWindow: NSWindow?,
contentView: NSView?
) {
- guard activityMonitor.snapshot.hasTaskCenterContent,
+ let snapshot = activityMonitor.snapshot
+ guard snapshot.hasTaskCenterContent,
let menuSurfaceWindow else {
hide(immediate: true)
return
}
let panel = ensurePanel()
+ cancelScheduledPanelUpdate()
currentContext = context
self.menuSurfaceWindow = menuSurfaceWindow
menuContentView = contentView
@@ -98,7 +137,8 @@ final class ActivityCenterPanelController {
context: context,
menuSurfaceWindow: menuSurfaceWindow,
contentView: contentView,
- snapshot: activityMonitor.snapshot
+ snapshot: snapshot,
+ allowsCachedAnchor: false
)
updateContent(panelSize: layout.size)
@@ -114,7 +154,8 @@ final class ActivityCenterPanelController {
context: CodexActivityCenterPanelContext,
menuSurfaceWindow: NSWindow,
contentView: NSView?,
- snapshot: CodexActivitySnapshot
+ snapshot: CodexActivitySnapshot,
+ allowsCachedAnchor: Bool = true
) -> (size: CGSize, position: SidePanelPosition) {
let menuSurfaceFrame = SidePanelSupport.contentScreenFrame(
for: contentView,
@@ -123,7 +164,10 @@ final class ActivityCenterPanelController {
let screen = menuSurfaceWindow.screen ?? NSScreen.main
let visibleFrame = screen?.visibleFrame ?? menuSurfaceFrame
let alignmentScreenFrame = SidePanelSupport.validatedAlignmentScreenFrame(
- context.alignmentScreenFrame,
+ context.anchorProvider.currentScreenFrame(
+ in: menuSurfaceWindow,
+ allowingCachedFrame: allowsCachedAnchor
+ ),
menuSurfaceFrame: menuSurfaceFrame
)
let screenMaximumHeight = visibleFrame.height - SidePanelSupport.Metrics.screenPadding * 2
@@ -168,14 +212,48 @@ final class ActivityCenterPanelController {
contentView: menuContentView,
snapshot: snapshot
)
- // 内容更新由 @ObservedObject 原地驱动;只有尺寸或位置变化才需要重建 rootView 和重设 frame。
guard panel.frame != layout.position.frame else {
return
}
- if panel.frame.size != layout.size {
- updateContent(panelSize: layout.size)
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = Metrics.contentUpdateDuration
+ context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
+ panel.animator().setFrame(layout.position.frame, display: true)
}
- panel.setFrame(layout.position.frame, display: true)
+ }
+
+ private func schedulePanelUpdate(hasContent: Bool) {
+ cancelScheduledPanelUpdate()
+ let generation = panelUpdateGeneration
+ panelUpdateTask = Task { @MainActor [weak self] in
+ if hasContent {
+ await Task.yield()
+ } else {
+ try? await Task.sleep(for: .seconds(Metrics.contentUpdateDuration))
+ }
+
+ guard let self, !Task.isCancelled,
+ generation == panelUpdateGeneration else {
+ return
+ }
+ let snapshot = activityMonitor.snapshot
+ guard snapshot.hasTaskCenterContent == hasContent else {
+ return
+ }
+
+ panelUpdateTask = nil
+ if hasContent {
+ updateVisibleLayout(for: snapshot)
+ } else {
+ hide()
+ }
+ }
+ }
+
+ private func cancelScheduledPanelUpdate() {
+ panelUpdateGeneration += 1
+ panelUpdateTask?.cancel()
+ panelUpdateTask = nil
}
private func ensurePanel() -> NSPanel {
@@ -194,15 +272,14 @@ final class ActivityCenterPanelController {
private func updateContent(panelSize: CGSize) {
let rootView = CodexActivityCenterView(
activityMonitor: activityMonitor,
- presentationState: presentationState,
- panelSize: panelSize
+ presentationState: presentationState
)
if let hostingController {
hostingController.rootView = rootView
} else {
let hostingController = NSHostingController(rootView: rootView)
- hostingController.sizingOptions = [.preferredContentSize]
+ hostingController.sizingOptions = []
panel?.contentViewController = hostingController
self.hostingController = hostingController
}
@@ -217,5 +294,6 @@ final class ActivityCenterPanelController {
private enum Metrics {
static let drawerTransformAnimationKey = "CodexBar.activityCenterDrawerTransform"
+ static let contentUpdateDuration: TimeInterval = 0.20
}
}
diff --git a/CodexBar/Controllers/GlobalHotKeyController.swift b/CodexBar/Controllers/GlobalHotKeyController.swift
index 0d73b48..0fa0b2c 100644
--- a/CodexBar/Controllers/GlobalHotKeyController.swift
+++ b/CodexBar/Controllers/GlobalHotKeyController.swift
@@ -43,9 +43,7 @@ final class GlobalHotKeyController {
)
guard status == noErr else {
- if let installedHandlerRef {
- GlobalHotKeyRegistration.remove(hotKeyRef: nil, eventHandlerRef: installedHandlerRef)
- }
+ GlobalHotKeyRegistration.remove(hotKeyRef: nil, eventHandlerRef: installedHandlerRef)
return false
}
diff --git a/CodexBar/Controllers/HeatmapDetailPanelController.swift b/CodexBar/Controllers/HeatmapDetailPanelController.swift
index 66087c9..c33a19b 100644
--- a/CodexBar/Controllers/HeatmapDetailPanelController.swift
+++ b/CodexBar/Controllers/HeatmapDetailPanelController.swift
@@ -59,7 +59,6 @@ final class HeatmapDetailPanelController {
guard !immediate else {
drawerAnimator.resetVisualState(for: panel)
- drawerTransition = .idle
orderOut(panel)
return
}
diff --git a/CodexBar/Controllers/ResetCreditsPanelController.swift b/CodexBar/Controllers/ResetCreditsPanelController.swift
index cb17f97..e63bd69 100644
--- a/CodexBar/Controllers/ResetCreditsPanelController.swift
+++ b/CodexBar/Controllers/ResetCreditsPanelController.swift
@@ -1,7 +1,7 @@
import AppKit
import SwiftUI
-/// 重置次数详情控制器, 复用热力图详情的侧边抽屉动效
+/// 重置次数详情控制器, 复用共享侧边抽屉定位和动画
@MainActor
final class ResetCreditsPanelController {
private var panel: NSPanel?
diff --git a/CodexBar/Controllers/SidePanelSupport.swift b/CodexBar/Controllers/SidePanelSupport.swift
index 6b2e631..aeec1c4 100644
--- a/CodexBar/Controllers/SidePanelSupport.swift
+++ b/CodexBar/Controllers/SidePanelSupport.swift
@@ -141,7 +141,7 @@ final class SidePanelDrawerAnimator {
}
}
-/// 重置次数 / 通知子选项两类「一次性展开」抽屉面板共用的显隐状态机:
+/// 重置次数、通知子选项和并发任务中心三类「一次性展开」抽屉面板共用的显隐状态机:
/// 负责 generation 竞态防护、入退场动画和 child window 挂载/卸载
/// (热力图详情面板因带切边与延迟隐藏, 状态机不同, 不走这里)
@MainActor
@@ -503,7 +503,7 @@ enum SidePanelSupport {
}
}
-nonisolated struct SidePanelHorizontalPlacement {
+private nonisolated struct SidePanelHorizontalPlacement {
let x: CGFloat
let side: UsageHeatmapDetailSide
let isAvailable: Bool
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index 9afc0db..cf09267 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -528,6 +528,24 @@ private final class StatusItemController: NSObject, NSMenuDelegate {
}
private func observeViewModel() {
+ let hasQuotaSnapshot = viewModel.$snapshot
+ .map { $0 != nil }
+ .removeDuplicates()
+
+ Publishers.CombineLatest3(
+ menuSurfaceVisibility.$isVisible,
+ hasQuotaSnapshot,
+ activityMonitor.$snapshot.map(\.hasTaskCenterContent)
+ )
+ .map { isMenuVisible, hasQuotaSnapshot, hasActivity in
+ isMenuVisible && hasQuotaSnapshot && hasActivity
+ }
+ .removeDuplicates()
+ .sink { [weak self] isActive in
+ self?.activityCenterPresentationState.setTimelineActive(isActive)
+ }
+ .store(in: &cancellables)
+
Publishers.CombineLatest4(
viewModel.$loadState,
viewModel.$snapshot,
@@ -538,7 +556,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {
StatusIconState(
usesErrorImage: loadState.isError || snapshot?.hasTrustedData == false,
progress: StatusIconProgress(snapshot: snapshot, selection: selection),
- activity: activity
+ activity: snapshot == nil ? .empty : activity
)
}
.removeDuplicates()
@@ -557,9 +575,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {
}
.store(in: &cancellables)
- viewModel.$snapshot
- .map { $0 != nil }
- .removeDuplicates()
+ hasQuotaSnapshot
.sink { [weak self] isAvailable in
guard let self, !isAvailable else {
return
@@ -589,15 +605,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {
syncSettings.$syncAvailability
.removeDuplicates()
.sink { [weak self] availability in
- guard let self else {
- return
- }
-
- if availability.isAvailable {
- workflowSyncScheduler.requestSync()
- } else {
- workflowSyncScheduler.clearPendingSync()
- }
+ self?.handleSyncChanged(availability.isAvailable)
}
.store(in: &cancellables)
}
diff --git a/CodexBar/Models/CodexAccountModels.swift b/CodexBar/Models/CodexAccountModels.swift
index dfdf909..b1c1883 100644
--- a/CodexBar/Models/CodexAccountModels.swift
+++ b/CodexBar/Models/CodexAccountModels.swift
@@ -11,7 +11,7 @@ nonisolated struct CodexAccount: Decodable, Equatable {
}
var displayName: String {
- if let email, hasEmail {
+ if let email, !email.isEmpty {
return email
}
diff --git a/CodexBar/Models/CodexWorkflowModels.swift b/CodexBar/Models/CodexWorkflowModels.swift
index df83a18..c9e7233 100644
--- a/CodexBar/Models/CodexWorkflowModels.swift
+++ b/CodexBar/Models/CodexWorkflowModels.swift
@@ -104,14 +104,12 @@ nonisolated struct WorkflowHookEvent: Decodable, Equatable, Sendable {
from container: KeyedDecodingContainer<CodingKeys>,
key: CodingKeys
) -> String? {
- if let value = try? container.decode(String.self, forKey: key) {
- let trimmedValue = value.trimmingCharacters(in: .whitespacesAndNewlines)
- if !trimmedValue.isEmpty {
- return trimmedValue
- }
+ guard let value = try? container.decode(String.self, forKey: key) else {
+ return nil
}
- return nil
+ let trimmedValue = value.trimmingCharacters(in: .whitespacesAndNewlines)
+ return trimmedValue.isEmpty ? nil : trimmedValue
}
private static func date(from string: String) -> Date? {
@@ -263,14 +261,13 @@ nonisolated struct WorkflowSnapshot: Equatable {
currentDeviceId: String?
) {
var metricsByDate = [String: WorkflowDailyMetrics]()
- localAggregates
- .map(\.metrics)
- .forEach { Self.merge($0, into: &metricsByDate) }
-
- syncedRecords
- .filter { $0.deviceId != currentDeviceId }
- .map(\.daily.metrics)
- .forEach { Self.merge($0, into: &metricsByDate) }
+ for aggregate in localAggregates {
+ Self.merge(aggregate.metrics, into: &metricsByDate)
+ }
+
+ for record in syncedRecords where record.deviceId != currentDeviceId {
+ Self.merge(record.daily.metrics, into: &metricsByDate)
+ }
dailyMetrics = metricsByDate.values.sorted { $0.startDate < $1.startDate }
}
diff --git a/CodexBar/Models/DateFormatter.swift b/CodexBar/Models/DateFormatter.swift
index 749c690..28bc05f 100644
--- a/CodexBar/Models/DateFormatter.swift
+++ b/CodexBar/Models/DateFormatter.swift
@@ -44,7 +44,7 @@ nonisolated enum CodexDateFormat {
return date
}
- /// yyyy-MM-dd HH: mm: ss.SSS, Hook 原始事件写入本机时间字符串
+ /// yyyy-MM-dd HH:mm:ss.SSS, Hook 原始事件写入本机时间字符串
static func localTimestampString(from date: Date) -> String {
localTimestampFormatter.string(from: date)
}
@@ -53,7 +53,7 @@ nonisolated enum CodexDateFormat {
localTimestampFormatter.date(from: string)
}
- /// yyyy-MM-dd HH: mm: ss, 设置页与重置次数详情统一的本地时间展示
+ /// yyyy-MM-dd HH:mm:ss, 设置页与重置次数详情统一的本地时间展示
static func localDisplayString(from date: Date) -> String {
localDisplayFormatter.string(from: date)
}
diff --git a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
index 20a4150..3e60f9f 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
@@ -25,8 +25,7 @@ nonisolated struct AppServerCommand: Equatable {
nonisolated struct CodexCLIConnectionInfo: Equatable {
let source: CodexCLIExecutableSource
let executablePath: String
- // 来自 initialize 握手, 代表当前 app-server 进程真实运行的版本
-
+ /// 来自 initialize 握手, 代表当前 app-server 进程真实运行的版本
let version: String?
let openedAt: Date
}
@@ -163,12 +162,11 @@ nonisolated enum CodexCLIResolver {
var seen = Set<String>()
for component in path.split(separator: ":").map(String.init) + fallbackPaths {
- guard !component.isEmpty, !seen.contains(component) else {
+ guard !component.isEmpty, seen.insert(component).inserted else {
continue
}
components.append(component)
- seen.insert(component)
}
return components.joined(separator: ":")
diff --git a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
index 585a776..bf3f7f6 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
@@ -55,14 +55,12 @@ nonisolated struct CodexCLIVersionDisplay: Equatable {
let displayVersion: String
let hasVersion: Bool
let path: String?
- // 当前会话尚未重连到新安装版本时显示的新版本号
-
+ /// 当前会话尚未重连到新安装版本时显示的新版本号
let newerInstalledVersion: String?
init(item: CodexCLIVersionItem, connection: CodexCLIConnectionInfo?) {
let isCurrent = connection?.source == item.source
// 当前来源优先显示正在运行的版本, 避免后台升级后误报已生效
-
let runningVersion = isCurrent ? connection?.version : nil
let version = runningVersion ?? item.version
diff --git a/CodexBar/Services/CodexStatus/AppServerSession.swift b/CodexBar/Services/CodexStatus/AppServerSession.swift
index 9a3b877..9332227 100644
--- a/CodexBar/Services/CodexStatus/AppServerSession.swift
+++ b/CodexBar/Services/CodexStatus/AppServerSession.swift
@@ -236,12 +236,10 @@ private nonisolated struct RPCIDEnvelope: Decodable {
}
private nonisolated struct RPCResponseEnvelope<Response: Decodable>: Decodable {
- let id: Int?
let result: Response?
}
private nonisolated struct RPCErrorEnvelope: Decodable {
- let id: Int?
let error: RPCError?
}
diff --git a/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift b/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift
index 7a318a4..0998e7e 100644
--- a/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift
+++ b/CodexBar/Services/CodexStatus/CodexHookAppServerModels.swift
@@ -5,11 +5,7 @@ nonisolated struct CodexConfigReadResponse: Decodable {
let config: CodexAppServerConfig
var hooksGloballyDisabled: Bool {
- guard let features = config.features else {
- return false
- }
-
- return (features.hooks ?? features.codexHooks) == false
+ (config.features?.hooks ?? config.features?.codexHooks) == false
}
var hookTrustState: [String: String] {
diff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swift
index cfad12b..b9d6909 100644
--- a/CodexBar/Services/Notifications/CodexNotificationService.swift
+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift
@@ -14,6 +14,7 @@ final class CodexNotificationService: NSObject {
private var cancellables = Set<AnyCancellable>()
private var taskHapticFeedbackTask: Task<Void, Never>?
+ private var taskWaitingNotificationIdentifiers = Set<String>()
private let creditExpiryReminderScheduler = ReminderCheckScheduler()
private var latestQuotaSnapshot: CodexQuotaSnapshot?
@@ -82,6 +83,12 @@ final class CodexNotificationService: NSObject {
self?.handleActivityTransition(transition)
}
.store(in: &cancellables)
+
+ activityMonitor.$snapshot
+ .sink { [weak self] snapshot in
+ self?.reconcileTaskWaitingNotifications(with: snapshot)
+ }
+ .store(in: &cancellables)
}
// MARK: - Hook 任务提醒
@@ -98,7 +105,22 @@ final class CodexNotificationService: NSObject {
guard settings.isTaskWaitingEnabled else {
return
}
- send(.taskWaiting(project: task.projectName, toolName: task.toolName))
+ let taskID = task.id
+ let identifier = Self.taskWaitingNotificationIdentifier(for: taskID)
+ taskWaitingNotificationIdentifiers.insert(identifier)
+ send(
+ .taskWaiting(project: task.projectName, toolName: task.toolName),
+ identifier: identifier,
+ isStillRelevant: { [weak self] in
+ self?.isTaskStillWaiting(
+ taskID,
+ notificationIdentifier: identifier
+ ) ?? false
+ },
+ onSubmissionFailure: { [weak self] in
+ self?.taskWaitingNotificationIdentifiers.remove(identifier)
+ }
+ )
case let .completed(completion):
guard settings.isLongTaskEnabled,
let duration = completion.duration,
@@ -109,6 +131,33 @@ final class CodexNotificationService: NSObject {
}
}
+ private func isTaskStillWaiting(
+ _ taskID: UUID,
+ notificationIdentifier: String
+ ) -> Bool {
+ let isStillWaiting = activityMonitor.snapshot.waitingTasks.contains {
+ $0.id == taskID
+ }
+ if !isStillWaiting {
+ taskWaitingNotificationIdentifiers.remove(notificationIdentifier)
+ }
+ return isStillWaiting
+ }
+
+ private func reconcileTaskWaitingNotifications(with snapshot: CodexActivitySnapshot) {
+ let activeIdentifiers = Set(snapshot.waitingTasks.map {
+ Self.taskWaitingNotificationIdentifier(for: $0.id)
+ })
+ let obsoleteIdentifiers = taskWaitingNotificationIdentifiers.subtracting(activeIdentifiers)
+ guard !obsoleteIdentifiers.isEmpty else {
+ return
+ }
+
+ let identifiers = Array(obsoleteIdentifiers)
+ removeNotifications(withIdentifiers: identifiers)
+ taskWaitingNotificationIdentifiers.subtract(obsoleteIdentifiers)
+ }
+
private func performTaskHapticFeedbackIfEnabled() {
guard settings.canPerformTaskHapticFeedback else {
return
@@ -251,10 +300,11 @@ final class CodexNotificationService: NSObject {
windowLabel: window.label,
thresholdPercent: settings.lowQuotaThresholdPercent
),
- dedupKey: dedupKey
- ) { [weak self] in
- self?.lastRemainingPercents.removeValue(forKey: stateKey)
- }
+ dedupKey: dedupKey,
+ onSubmissionFailure: { [weak self] in
+ self?.lastRemainingPercents.removeValue(forKey: stateKey)
+ }
+ )
}
// MARK: - 额度重置提醒
@@ -277,19 +327,24 @@ final class CodexNotificationService: NSObject {
return
}
+ let dedupKey = window.resetsAt.map { resetsAt in
+ "quotaReset|\(stateKey)|\(Self.epoch(resetsAt))"
+ }
send(
.quotaReset(
limitTitle: limit.title,
windowLabel: window.label
- )
- ) { [weak self] in
- guard let self,
- quotaWindowResetObservations[stateKey]?.lifecycleToken == lifecycleToken else {
- return
- }
+ ),
+ dedupKey: dedupKey,
+ onSubmissionFailure: { [weak self] in
+ guard let self,
+ quotaWindowResetObservations[stateKey]?.lifecycleToken == lifecycleToken else {
+ return
+ }
- quotaWindowResetObservations[stateKey]?.hasObservedConsumption = true
- }
+ quotaWindowResetObservations[stateKey]?.hasObservedConsumption = true
+ }
+ )
}
}
@@ -360,8 +415,10 @@ final class CodexNotificationService: NSObject {
private func send(
_ notification: CodexNotificationContent,
+ identifier: String = UUID().uuidString,
dedupKey: String? = nil,
- onFailure: (() -> Void)? = nil
+ isStillRelevant: (() -> Bool)? = nil,
+ onSubmissionFailure: (() -> Void)? = nil
) {
if let dedupKey {
guard !sentDedupKeys.contains(dedupKey),
@@ -376,7 +433,7 @@ final class CodexNotificationService: NSObject {
content.sound = .default
let request = UNNotificationRequest(
- identifier: UUID().uuidString,
+ identifier: identifier,
content: content,
trigger: nil
)
@@ -392,8 +449,15 @@ final class CodexNotificationService: NSObject {
}
for _ in 0 ... Self.notificationSubmissionRetryCount {
+ guard isStillRelevant?() != false else {
+ return
+ }
do {
try await UNUserNotificationCenter.current().add(request)
+ guard isStillRelevant?() != false else {
+ removeNotifications(withIdentifiers: [identifier])
+ return
+ }
if let dedupKey {
rememberSentDedupKey(dedupKey)
}
@@ -403,10 +467,16 @@ final class CodexNotificationService: NSObject {
}
}
- onFailure?()
+ onSubmissionFailure?()
}
}
+ private func removeNotifications(withIdentifiers identifiers: [String]) {
+ let center = UNUserNotificationCenter.current()
+ center.removeDeliveredNotifications(withIdentifiers: identifiers)
+ center.removePendingNotificationRequests(withIdentifiers: identifiers)
+ }
+
private nonisolated static func accountKey(for snapshot: CodexQuotaSnapshot) -> String {
snapshot.account.email ?? snapshot.account.type
}
@@ -415,6 +485,10 @@ final class CodexNotificationService: NSObject {
Int(date.timeIntervalSince1970)
}
+ private nonisolated static func taskWaitingNotificationIdentifier(for taskID: UUID) -> String {
+ "taskWaiting|\(taskID.uuidString)"
+ }
+
private nonisolated static func quotaWindowStateKey(
accountKey: String,
limitId: String,
diff --git a/CodexBar/Services/Workflow/WorkflowService.swift b/CodexBar/Services/Workflow/WorkflowService.swift
index 8a023de..addc8eb 100644
--- a/CodexBar/Services/Workflow/WorkflowService.swift
+++ b/CodexBar/Services/Workflow/WorkflowService.swift
@@ -631,12 +631,7 @@ nonisolated enum WorkflowStorage {
}
static func fileSize(at url: URL) -> UInt64 {
- guard let attributes = try? FileManager.default.attributesOfItem(atPath: url.path),
- let fileSize = attributes[.size] as? NSNumber else {
- return 0
- }
-
- return fileSize.uint64Value
+ fileStat(at: url)?.size ?? 0
}
/// 单次 stat 同时返回大小与 inode 标识, 文件缺失或不可读时为 nil
diff --git a/CodexBar/Services/Workflow/WorkflowSyncService.swift b/CodexBar/Services/Workflow/WorkflowSyncService.swift
index 7cf1117..80bf5c5 100644
--- a/CodexBar/Services/Workflow/WorkflowSyncService.swift
+++ b/CodexBar/Services/Workflow/WorkflowSyncService.swift
@@ -128,7 +128,12 @@ actor WorkflowSyncService {
}
private extension WorkflowSyncService {
- typealias PendingUpload = (date: String, aggregate: WorkflowSyncedDailyAggregate, hash: String)
+ struct PendingUpload {
+ let date: String
+ let aggregate: WorkflowSyncedDailyAggregate
+ let hash: String
+ }
+
typealias PendingRecord = (upload: PendingUpload, recordID: CKRecord.ID)
typealias UploadedHash = (date: String, hash: String)
@@ -277,7 +282,7 @@ private extension WorkflowSyncService {
return nil
}
- return (date: date, aggregate: aggregate, hash: hash)
+ return PendingUpload(date: date, aggregate: aggregate, hash: hash)
}
.sorted { $0.date < $1.date }
}
@@ -292,7 +297,6 @@ private extension WorkflowSyncService {
let recordIDs = pendingRecords.map(\.recordID)
let existingRecords = try await database.records(for: recordIDs)
let records = pendingRecords.map { pendingRecord in
- let (_, aggregate, _) = pendingRecord.upload
let existingRecord: CKRecord? = if case let .success(record) = existingRecords[pendingRecord.recordID] {
record
} else {
@@ -303,7 +307,7 @@ private extension WorkflowSyncService {
recordType: RecordTypes.dailyAggregate,
recordID: pendingRecord.recordID
)
- apply(aggregate, deviceId: deviceId, to: record)
+ apply(pendingRecord.upload.aggregate, deviceId: deviceId, to: record)
return record
}
@@ -315,9 +319,8 @@ private extension WorkflowSyncService {
)
return pendingRecords.compactMap { pendingRecord in
- let (date, _, hash) = pendingRecord.upload
if case .success = result.saveResults[pendingRecord.recordID] {
- return (date: date, hash: hash)
+ return (date: pendingRecord.upload.date, hash: pendingRecord.upload.hash)
}
return nil
}
@@ -350,7 +353,6 @@ private extension WorkflowSyncService {
excluding: currentDeviceId
)
var token: CKServerChangeToken? = initialToken
- var latestToken: CKServerChangeToken?
var moreComing = true
while moreComing {
@@ -369,7 +371,6 @@ private extension WorkflowSyncService {
removeDeletedRecords(result.deletions, from: &cacheByID)
token = result.changeToken
- latestToken = result.changeToken
moreComing = result.moreComing
}
@@ -379,8 +380,8 @@ private extension WorkflowSyncService {
excluding: currentDeviceId
)
)
- if let latestToken {
- try saveCursor(latestToken)
+ if let token {
+ try saveCursor(token)
}
}
@@ -392,9 +393,6 @@ private extension WorkflowSyncService {
}
func fetchAllRemoteDailyRecords() async throws -> [WorkflowSyncedDailyRecord] {
- var records = [WorkflowSyncedDailyRecord]()
- var queryCursor: CKQueryOperation.Cursor?
-
let query = CKQuery(
recordType: RecordTypes.dailyAggregate,
predicate: NSPredicate(format: "TRUEPREDICATE")
@@ -410,8 +408,8 @@ private extension WorkflowSyncService {
desiredKeys: nil,
resultsLimit: Metrics.queryFetchLimit
)
- records.append(contentsOf: Self.remoteDailyRecords(from: firstPage.matchResults))
- queryCursor = firstPage.queryCursor
+ var records = Self.remoteDailyRecords(from: firstPage.matchResults)
+ var queryCursor = firstPage.queryCursor
while let cursor = queryCursor {
let page = try await database.records(
@@ -699,7 +697,7 @@ private extension WorkflowSyncService {
}
func saveState(_ state: WorkflowSyncState) throws {
- try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
+ try ensureSyncDirectoryExists()
let data = try JSONLines.stableEncoder.encode(state)
try data.write(to: stateURL, options: .atomic)
}
@@ -713,7 +711,7 @@ private extension WorkflowSyncService {
}
func saveCachedRecords(_ records: [WorkflowSyncedDailyRecord]) throws {
- try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
+ try ensureSyncDirectoryExists()
let encoder = JSONLines.stableEncoder
let data = try records
@@ -742,13 +740,17 @@ private extension WorkflowSyncService {
}
func saveCursor(_ token: CKServerChangeToken) throws {
- try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
+ try ensureSyncDirectoryExists()
let data = try NSKeyedArchiver.archivedData(
withRootObject: token,
requiringSecureCoding: true
)
try data.write(to: cursorURL, options: .atomic)
}
+
+ func ensureSyncDirectoryExists() throws {
+ try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
+ }
}
private extension WorkflowSyncService {
@@ -948,15 +950,6 @@ private nonisolated struct WorkflowSyncState: Codable, Equatable {
lastPrunedDate = try container.decodeIfPresent(String.self, forKey: .lastPrunedDate)
}
- func encode(to encoder: Encoder) throws {
- var container = encoder.container(keyedBy: CodingKeys.self)
- try container.encode(schema, forKey: .schema)
- try container.encodeIfPresent(deviceId, forKey: .deviceId)
- try container.encode(hashByDate, forKey: .hashByDate)
- try container.encodeIfPresent(lastUploadAt, forKey: .lastUploadAt)
- try container.encodeIfPresent(lastPrunedDate, forKey: .lastPrunedDate)
- }
-
private enum CodingKeys: String, CodingKey {
case schema
case deviceId
diff --git a/CodexBar/Views/Log/LogView.swift b/CodexBar/Views/Log/LogView.swift
index c4c88ff..abb2aa4 100644
--- a/CodexBar/Views/Log/LogView.swift
+++ b/CodexBar/Views/Log/LogView.swift
@@ -7,7 +7,6 @@ struct LogView: View {
var body: some View {
// 每轮渲染只取一次发布快照复用
-
let entries = store.entries
VStack(spacing: 0) {
header(entries: entries)
diff --git a/CodexBar/Views/Menu/CodexActivityCard.swift b/CodexBar/Views/Menu/CodexActivityCard.swift
index 1e2efa5..8862825 100644
--- a/CodexBar/Views/Menu/CodexActivityCard.swift
+++ b/CodexBar/Views/Menu/CodexActivityCard.swift
@@ -1,27 +1,31 @@
import SwiftUI
-/// Hook 开启时常驻的固定高度活动摘要,只在菜单面板可见时逐秒更新时间。
+/// Hook 开启时常驻的固定高度活动摘要,使用菜单面板共享的逐秒时间。
struct CodexActivityCard: View {
- let snapshot: CodexActivitySnapshot
- let isTimelineActive: Bool
+ @ObservedObject var activityMonitor: CodexActivityMonitor
+ let timelineDate: Date
let showsUnavailableState: Bool
let isTaskCenterPresented: Bool
- let onTaskCenterTap: (CGRect?) -> Void
+ let onTaskCenterTap: (ScreenFrameProvider) -> Void
@State private var frameProvider = ScreenFrameProvider()
@State private var isHovered = false
+ private var snapshot: CodexActivitySnapshot {
+ showsUnavailableState ? .empty : activityMonitor.snapshot
+ }
+
var body: some View {
Group {
if snapshot.hasTaskCenterContent {
Button {
- onTaskCenterTap(frameProvider.currentScreenFrame())
+ onTaskCenterTap(frameProvider)
} label: {
- timelineContent
+ card(now: timelineDate)
}
.buttonStyle(ActivityCardButtonStyle())
.contentShape(Rectangle())
} else {
- timelineContent
+ card(now: timelineDate)
}
}
.background {
@@ -30,22 +34,6 @@ struct CodexActivityCard: View {
.onHover { isHovered = $0 }
}
- @ViewBuilder
- private var timelineContent: some View {
- if isTimelineActive, needsPerSecondUpdates {
- TimelineView(.periodic(from: .now, by: 1)) { timeline in
- card(now: timeline.date)
- }
- } else {
- card(now: Date())
- }
- }
-
- /// 空闲文案不随时间变化,不需要逐秒重算。
- private var needsPerSecondUpdates: Bool {
- snapshot.primaryActivity != .idle
- }
-
private func card(now: Date) -> some View {
let content = content(at: now)
return HStack(spacing: 10) {
diff --git a/CodexBar/Views/Menu/CodexActivityCenterView.swift b/CodexBar/Views/Menu/CodexActivityCenterView.swift
index 1bc6ee8..155236c 100644
--- a/CodexBar/Views/Menu/CodexActivityCenterView.swift
+++ b/CodexBar/Views/Menu/CodexActivityCenterView.swift
@@ -1,15 +1,43 @@
import Combine
import SwiftUI
-/// 活动卡片与任务中心共享的显隐状态,控制选中外观和逐秒时间更新。
+/// 活动卡片与任务中心共享的显隐和逐秒时间状态。
@MainActor
final class CodexActivityCenterPresentationState: ObservableObject {
@Published var isPresented = false
+ @Published private(set) var timelineDate = Date()
+ private var timelineTask: Task<Void, Never>?
+
+ func setTimelineActive(_ isActive: Bool) {
+ guard isActive else {
+ timelineTask?.cancel()
+ timelineTask = nil
+ return
+ }
+ guard timelineTask == nil else {
+ return
+ }
+
+ timelineDate = Date()
+ timelineTask = Task { @MainActor [weak self] in
+ while !Task.isCancelled {
+ let now = Date()
+ let fraction = now.timeIntervalSinceReferenceDate
+ .truncatingRemainder(dividingBy: 1)
+ try? await Task.sleep(for: .seconds(max(0.01, 1 - fraction)))
+ guard let self, !Task.isCancelled else {
+ return
+ }
+ timelineDate = Date()
+ }
+ }
+ }
}
/// 点击活动卡片时传给 AppKit 控制器的定位信息。
-nonisolated struct CodexActivityCenterPanelContext: Equatable {
- let alignmentScreenFrame: CGRect?
+@MainActor
+struct CodexActivityCenterPanelContext {
+ let anchorProvider: ScreenFrameProvider
let preferredSide: UsageHeatmapDetailSide
}
@@ -17,21 +45,15 @@ nonisolated struct CodexActivityCenterPanelContext: Equatable {
struct CodexActivityCenterView: View {
@ObservedObject var activityMonitor: CodexActivityMonitor
@ObservedObject var presentationState: CodexActivityCenterPresentationState
- let panelSize: CGSize
var body: some View {
- Group {
- if presentationState.isPresented, needsPerSecondUpdates {
- TimelineView(.periodic(from: .now, by: 1)) { timeline in
- content(now: timeline.date)
- }
- } else {
- content(now: Date())
- }
- }
- .frame(width: panelSize.width, height: panelSize.height, alignment: .topLeading)
- .sidePanelChrome(cornerRadius: Metrics.cornerRadius)
- .animation(.codexStatus, value: activityMonitor.snapshot)
+ content(now: presentationState.timelineDate)
+ .frame(
+ maxWidth: .infinity,
+ maxHeight: .infinity,
+ alignment: .topLeading
+ )
+ .sidePanelChrome(cornerRadius: Metrics.cornerRadius)
}
static var initialPanelSize: CGSize {
@@ -46,30 +68,26 @@ struct CodexActivityCenterView: View {
maximumHeight: CGFloat,
snapshot: CodexActivitySnapshot
) -> CGSize {
- let sectionCounts = [
+ let visibleSectionCounts = [
snapshot.waitingTasks.count,
snapshot.runningTasks.count,
snapshot.recentCompletions.count,
snapshot.recentTerminations.count
].filter { $0 > 0 }
+ let rowCount = visibleSectionCounts.reduce(0, +)
let contentHeight = Metrics.headerHeight
+ Metrics.dividerHeight
+ Metrics.verticalPadding * 2
- + CGFloat(sectionCounts.count) * Metrics.sectionHeaderHeight
- + CGFloat(sectionCounts.reduce(0, +)) * (Metrics.rowHeight + Metrics.rowSpacing)
- + CGFloat(max(0, sectionCounts.count - 1)) * Metrics.sectionSpacing
- let desiredHeight = max(Metrics.minimumPanelHeight, contentHeight)
+ + CGFloat(visibleSectionCounts.count) * Metrics.sectionHeaderHeight
+ + CGFloat(rowCount) * (Metrics.rowHeight + Metrics.rowSpacing)
+ + CGFloat(max(0, visibleSectionCounts.count - 1)) * Metrics.sectionSpacing
return CGSize(
width: Metrics.panelWidth,
- height: min(maximumHeight, desiredHeight)
+ height: min(maximumHeight, contentHeight)
)
}
- private var needsPerSecondUpdates: Bool {
- activityMonitor.snapshot.hasTaskCenterContent
- }
-
private func content(now: Date) -> some View {
VStack(alignment: .leading, spacing: 0) {
header
@@ -77,7 +95,7 @@ struct CodexActivityCenterView: View {
LiquidGlassDivider()
ScrollView(.vertical) {
- LazyVStack(alignment: .leading, spacing: Metrics.sectionSpacing) {
+ VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {
if !activityMonitor.snapshot.waitingTasks.isEmpty {
taskSection(
title: "等待确认",
@@ -108,6 +126,7 @@ struct CodexActivityCenterView: View {
terminationSection(now: now)
}
}
+ .animation(.codexStatus, value: activityMonitor.snapshot)
.padding(.horizontal, Metrics.horizontalPadding)
.padding(.vertical, Metrics.verticalPadding)
}
@@ -203,6 +222,7 @@ struct CodexActivityCenterView: View {
.font(.caption2.monospacedDigit())
.foregroundStyle(.tertiary)
}
+ .frame(height: Metrics.sectionHeaderHeight)
content()
}
@@ -280,6 +300,8 @@ struct CodexActivityCenterView: View {
}
}
.frame(maxWidth: .infinity, alignment: .leading)
+ .frame(height: Metrics.rowHeight, alignment: .top)
+ .transition(Metrics.contentTransition)
}
private func titleLine(projectName: String?, modelName: String?) -> some View {
@@ -323,7 +345,6 @@ struct CodexActivityCenterView: View {
private enum Metrics {
static let panelWidth: CGFloat = 312
static let preferredPanelHeight: CGFloat = 360
- static let minimumPanelHeight: CGFloat = 180
static let headerHeight: CGFloat = 42
static let dividerHeight: CGFloat = 1
static let horizontalPadding: CGFloat = 12
@@ -335,5 +356,9 @@ struct CodexActivityCenterView: View {
static let symbolWidth: CGFloat = 16
static let titleLineHeight: CGFloat = 16
static let cornerRadius: CGFloat = 12
+ static let contentTransition = AnyTransition.asymmetric(
+ insertion: .opacity.combined(with: .scale(scale: 0.98, anchor: .top)),
+ removal: .opacity.combined(with: .scale(scale: 0.96, anchor: .top))
+ )
}
}
diff --git a/CodexBar/Views/Menu/CodexStatusMenuSections.swift b/CodexBar/Views/Menu/CodexStatusMenuSections.swift
index 1d0b478..f88fad8 100644
--- a/CodexBar/Views/Menu/CodexStatusMenuSections.swift
+++ b/CodexBar/Views/Menu/CodexStatusMenuSections.swift
@@ -82,16 +82,17 @@ struct StatusAccountCard: View {
let onRefresh: () -> Void
var body: some View {
+ let display = statusDisplay
HStack(spacing: 8) {
Image(systemName: "person.fill")
.font(.system(size: MenuMetrics.accountIconSize, weight: .medium))
- .foregroundStyle(statusDisplay.color)
+ .foregroundStyle(display.color)
.onTapGesture(count: 2, perform: onRefresh)
- if let text = statusDisplay.text {
+ if let text = display.text {
Text(text)
.font(.caption.weight(.semibold))
- .foregroundStyle(statusDisplay.color)
+ .foregroundStyle(display.color)
.lineLimit(1)
.truncationMode(.middle)
}
@@ -145,11 +146,12 @@ struct QuotaLimitsSection: View {
var body: some View {
VStack(alignment: .leading, spacing: 8) {
ForEach(limits) { limit in
- if !isPrimaryLimit(limit) {
+ let isPrimary = limit.id == limits.first?.id
+ if !isPrimary {
LiquidGlassDivider()
}
- quotaLimitSection(limit, showsResetCredits: isPrimaryLimit(limit))
+ quotaLimitSection(limit, showsResetCredits: isPrimary)
}
}
.markStale(isStale)
@@ -184,10 +186,6 @@ struct QuotaLimitsSection: View {
}
}
- private var primaryLimitId: CodexQuotaLimitSnapshot.ID? {
- limits.first?.id
- }
-
private func resetCreditsButton(count: Int) -> some View {
Button {
onResetCreditsTap(
@@ -209,10 +207,6 @@ struct QuotaLimitsSection: View {
}
.buttonStyle(.plain)
}
-
- private func isPrimaryLimit(_ limit: CodexQuotaLimitSnapshot) -> Bool {
- limit.id == primaryLimitId
- }
}
/// 底部更新时间行, 同时承载 Sparkle 被动更新提示
diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swift
index adfc9cd..aa5482a 100644
--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift
+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift
@@ -1,13 +1,13 @@
import Combine
import SwiftUI
-/// 控制 TimelineView 是否 tick 的轻量状态, 由菜单面板显示/隐藏驱动
+/// 菜单面板可见状态,用于控制逐秒时间更新。
@MainActor
final class MenuSurfaceVisibilityState: ObservableObject {
@Published var isVisible = false
}
-/// 菜单栏弹出面板根视图, 只展示账号, 额度, token 和更新时间
+/// 菜单栏弹出面板根视图, 汇总账号、实时活动、额度、token、同步状态和更新时间
struct CodexStatusMenuView: View {
static let menuWidth: CGFloat = Metrics.padding * 2 + MenuMetrics.panelPadding * 2 + UsageHeatmap.Metrics.totalWidth
@@ -40,9 +40,7 @@ struct CodexStatusMenuView: View {
private extension CodexStatusMenuView {
enum Metrics {
static let padding: CGFloat = 12
- static let panelPadding: CGFloat = 10
static let surfaceCornerRadius: CGFloat = 14
- static let panelCornerRadius: CGFloat = 8
static let verticalSpacing: CGFloat = 10
static let statusAnimation = Animation.codexStatus
}
@@ -78,14 +76,14 @@ private extension CodexStatusMenuView {
if codexHookSettings.isEnabled {
let hasQuotaSnapshot = viewModel.snapshot != nil
CodexActivityCard(
- snapshot: hasQuotaSnapshot ? activityMonitor.snapshot : .empty,
- isTimelineActive: menuSurfaceVisibility.isVisible,
+ activityMonitor: activityMonitor,
+ timelineDate: activityCenterPresentationState.timelineDate,
showsUnavailableState: !hasQuotaSnapshot,
isTaskCenterPresented: activityCenterPresentationState.isPresented,
- onTaskCenterTap: { alignmentScreenFrame in
+ onTaskCenterTap: { anchorProvider in
onActivityCenterTap(
CodexActivityCenterPanelContext(
- alignmentScreenFrame: alignmentScreenFrame,
+ anchorProvider: anchorProvider,
preferredSide: .right
)
)
@@ -121,9 +119,9 @@ private extension CodexStatusMenuView {
}
updatedAtRow(for: snapshot)
- .padding(.horizontal, Metrics.panelPadding)
+ .padding(.horizontal, MenuMetrics.panelPadding)
.padding(.vertical, 7)
- .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius)
+ .liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)
}
func updatedAtRow(for snapshot: CodexQuotaSnapshot) -> some View {
diff --git a/CodexBar/Views/Menu/QuotaRow.swift b/CodexBar/Views/Menu/QuotaRow.swift
index 331f986..2646bf7 100644
--- a/CodexBar/Views/Menu/QuotaRow.swift
+++ b/CodexBar/Views/Menu/QuotaRow.swift
@@ -13,7 +13,7 @@ struct QuotaRow: View {
.allowsTightening(true)
.frame(width: Metrics.labelWidth, alignment: .center)
- SegmentedQuotaBar(percent: displayPercent)
+ SegmentedQuotaBar(percent: remainingPercent)
.padding(.leading, Metrics.labelBarSpacing)
Text(percentText)
@@ -55,23 +55,23 @@ private extension QuotaRow {
}
var percentText: String {
- guard window.hasData else {
+ guard let remainingPercent else {
return "--"
}
- return "\(window.remainingPercent)%"
+ return "\(remainingPercent)%"
}
- var displayPercent: Int? {
+ var remainingPercent: Int? {
window.hasData ? window.remainingPercent : nil
}
var percentColor: Color {
- guard window.hasData else {
+ guard let remainingPercent else {
return .secondary
}
- return QuotaBarPalette.filledColor(for: window.remainingPercent)
+ return QuotaBarPalette.filledColor(for: remainingPercent)
}
static let resetFormatter: DateFormatter = {
diff --git a/CodexBar/Views/Menu/ScreenFrameReader.swift b/CodexBar/Views/Menu/ScreenFrameReader.swift
index bdd686a..fbf1961 100644
--- a/CodexBar/Views/Menu/ScreenFrameReader.swift
+++ b/CodexBar/Views/Menu/ScreenFrameReader.swift
@@ -26,32 +26,76 @@ struct ScreenFrameReader: NSViewRepresentable {
nsView.onChange = onChange
nsView.scheduleReport()
}
+
+ static func dismantleNSView(_ nsView: ScreenFrameReportingView, coordinator _: ()) {
+ nsView.frameProvider?.unbind(from: nsView)
+ nsView.frameProvider = nil
+ nsView.onChange = nil
+ }
+
+ func sizeThatFits(
+ _ proposal: ProposedViewSize,
+ nsView _: ScreenFrameReportingView,
+ context _: Context
+ ) -> CGSize? {
+ guard let width = proposal.width, let height = proposal.height else {
+ return nil
+ }
+ return CGSize(width: width, height: height)
+ }
}
/// 在交互发生时同步读取最新 screen frame, 避免只依赖异步 SwiftUI 状态
@MainActor
final class ScreenFrameProvider {
private weak var view: NSView?
+ private weak var lastValidWindow: NSWindow?
private var lastValidFrame: CGRect?
func bind(to view: NSView) {
self.view = view
}
+ func unbind(from view: NSView) {
+ guard self.view === view else {
+ return
+ }
+ self.view = nil
+ lastValidWindow = nil
+ lastValidFrame = nil
+ }
+
func currentScreenFrame() -> CGRect? {
if let currentFrame = Self.screenFrame(for: view) {
- lastValidFrame = currentFrame
+ updateLastValidFrame(currentFrame, in: view?.window)
return currentFrame
}
return lastValidFrame
}
- func updateLastValidFrame(_ frame: CGRect?) {
- guard let frame else {
+ func currentScreenFrame(
+ in expectedWindow: NSWindow,
+ allowingCachedFrame: Bool = true
+ ) -> CGRect? {
+ if view?.window === expectedWindow,
+ let currentFrame = Self.screenFrame(for: view) {
+ updateLastValidFrame(currentFrame, in: expectedWindow)
+ return currentFrame
+ }
+
+ guard allowingCachedFrame, lastValidWindow === expectedWindow else {
+ return nil
+ }
+ return lastValidFrame
+ }
+
+ func updateLastValidFrame(_ frame: CGRect?, in window: NSWindow?) {
+ guard let frame, let window else {
return
}
+ lastValidWindow = window
lastValidFrame = frame
}
@@ -113,7 +157,7 @@ final class ScreenFrameReportingView: NSView {
private func reportFrame() {
let screenFrame = ScreenFrameProvider.screenFrame(for: self)
- frameProvider?.updateLastValidFrame(screenFrame)
+ frameProvider?.updateLastValidFrame(screenFrame, in: window)
updateFrame(screenFrame)
}
diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swift
index e310d7a..5416bef 100644
--- a/CodexBar/Views/Menu/UsageHeatmap.swift
+++ b/CodexBar/Views/Menu/UsageHeatmap.swift
@@ -71,8 +71,8 @@ struct UsageSummaryView: View {
)
}
.markStale(isStale)
- .padding(10)
- .liquidGlassSurface(cornerRadius: 8)
+ .padding(MenuMetrics.panelPadding)
+ .liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)
.onAppear {
clearHover()
}
@@ -317,11 +317,8 @@ struct UsageHeatmap: View {
.frame(maxWidth: .infinity, alignment: .leading)
}
- private var visibleDays: [UsageHeatmapDay] {
- days.compactMap(\.self)
- }
-
private var dateRangeText: String? {
+ let visibleDays = days.compactMap(\.self)
guard let firstDate = visibleDays.first?.startDate,
let lastDate = visibleDays.last?.startDate else {
return nil
@@ -501,9 +498,10 @@ struct UsageHeatmapDayDetailView: View {
}
static func panelSize(showsWorkflow: Bool) -> CGSize {
- showsWorkflow
- ? CGSize(width: Metrics.workflowPanelWidth, height: Metrics.workflowPanelHeight)
- : CGSize(width: Metrics.tokenPanelWidth, height: Metrics.tokenPanelHeight)
+ CGSize(
+ width: Metrics.panelWidth,
+ height: showsWorkflow ? Metrics.workflowPanelHeight : Metrics.tokenPanelHeight
+ )
}
@ViewBuilder
@@ -741,9 +739,8 @@ struct UsageHeatmapDayDetailView: View {
}
private enum Metrics {
- static let workflowPanelWidth: CGFloat = 212
+ static let panelWidth: CGFloat = 212
static let workflowPanelHeight: CGFloat = 208
- static let tokenPanelWidth: CGFloat = 212
static let tokenPanelHeight: CGFloat = 84
static let sectionSpacing: CGFloat = 8
static let headerSpacing: CGFloat = 10
diff --git a/Docs/DevelopmentGuide.md b/Docs/DevelopmentGuide.md
index d477c0c..38045f9 100644
--- a/Docs/DevelopmentGuide.md
+++ b/Docs/DevelopmentGuide.md
@@ -25,11 +25,11 @@ App 通过本机 Codex app-server 读取账号, 额度和 token 用量, 通过 C
| ----------------------- | ----------------------------------------------------------------------- |
| `CodexBar/App/` | SwiftUI 入口和 AppDelegate 启动分支 |
| `CodexBar/Controllers/` | 菜单栏, 菜单面板, 侧边 child panel, 设置窗口, 日志窗口和窗口行为 |
-| `CodexBar/Models/` | account, quota, usage, workflow, 日期网格和错误模型 |
+| `CodexBar/Models/` | account, quota, usage, workflow, activity, 日期网格、快捷键和错误模型 |
| `CodexBar/Services/` | app-server, Codex CLI 解析, 版本探测, Hook 设置, 统计维护, 更新, 登录项 |
| `CodexBar/Views/` | 菜单面板, 设置窗口, 日志窗口和共享 Liquid Glass 样式 |
| `Docs/` | app-server, Hook 和开发文档 |
-| `Scripts/` | DMG 和 appcast 发布脚本 |
+| `Scripts/` | Release 构建、公证、DMG 和 appcast 发布脚本 |
## 2. 总体架构
@@ -98,11 +98,13 @@ App 退出时, `applicationWillTerminate` 调用 `StatusItemController.uninstall
正常图标是 `person.fill.checkmark`, 错误图标是 `person.fill.xmark`
-小人右下角的状态点只表达 Hook 任务状态,按 `等待批准 > 运行中 > 刚完成 > 暂无活动` 取最高优先级:等待批准使用系统橙色,运行中使用系统蓝色,确认 turn 完成后 30 秒内使用系统绿色,空闲时不显示。小人本体始终使用系统前景色,账号异常继续由 `person.fill.xmark` 表达,不改变状态点颜色;空闲且没有额度竖条时保持 template 图像,有状态点或显示额度竖条时使用非 template 合成图。状态点与额度竖条分别绘制,颜色互不影响。
+小人右下角的状态点只表达 Hook 任务状态,并以 `CodexQuotaSnapshot` 可用作为展示条件。快照可用时按 `等待批准 > 运行中 > 刚完成 > 暂无活动` 取最高优先级:等待批准使用系统橙色,运行中使用系统蓝色,确认 turn 完成后 30 秒内使用系统绿色,空闲时不显示;快照为 `nil` 时不绘制状态点。小人本体始终使用系统前景色,账号异常由 `person.fill.xmark` 表达;状态点与额度竖条分别绘制,颜色互不影响。空闲且没有额度竖条时使用 template 图像,存在状态点或额度竖条时使用非 template 合成图。
设置页「菜单栏额度指示」默认开启, 使用独立开关控制启用状态; 缺失持久化选择时默认使用 `.primary`, 关闭时显式持久化 `.off`。开启后在同一行显示额度窗口菜单, 可选择当前账号 Codex limit 返回的额度窗口, 当前保留选择不在返回窗口中时用 fallback 标题追加到菜单。最后一次非关闭的窗口选择由 `MenuBarQuotaSettings` 以 `MenuBarQuota.lastWindowSelection` 键随偏好持久化: 关闭开关时它继续参与菜单淡出避免过渡期间回退, 重新开启时(含重开设置窗口或重启应用后)恢复该选择, 无记录时回退 `.primary`。开启后 `StatusItemController` 会把所选 Codex 窗口的剩余额度进度条绘制在图标左侧, 以竖条形式与 `person.fill.checkmark` / `person.fill.xmark` 合成为单个 `NSImage`, 并随 `CodexStatusViewModel` 自动刷新。合成图尺寸为 `27 x 17`, 图标本体保持原始 `24 x 17`, 左侧竖条轨道为 `2 x 15`, 状态点位于小人右下角。额度显隐或状态点变化时, `StatusItemController` 合并为同一个逐帧重绘任务,在 0.18 秒内同时插值竖条与状态点的透明度以及状态点颜色,避免两个动画任务竞争;过渡期间合成图宽度和绘制坐标保持固定。活动期间 tooltip 每分钟更新一次耗时并合并并发数量与额度,活动结束后取消刷新任务。
-Hook 开启时,账号卡片下方始终显示固定高度 `CodexActivityCard`。主面板 `CodexQuotaSnapshot` 为 `nil` 时,卡片消费空活动快照并显示「暂无数据」,不开放任务中心;Monitor 仍在后台维护状态,主快照恢复后直接发布最新活动。卡片按等待、运行、最近完成、最近终止、空闲的顺序展示项目最后一级名称、模型或工具、耗时及其他任务数量;只有终止历史时使用灰色终止状态展示最近一项。存在活动任务、最近完成或最近终止记录时整张卡片成为无系统 label 状态变化的自定义 button:只有存在其他活动任务时才在右侧显示 `+N`,单任务不显示尾部附件,hover/选中反馈只作用于卡片描边。点击后由 `ActivityCenterPanelController` 展开并发任务中心,按等待、运行、最近完成和最近终止展示 `CodexActivitySnapshot` 的完整有序列表;等待和运行按最后活动时间倒序,完成和终止分别按结束时间倒序。任务及两类最近记录使用进程内 opaque UUID 供 SwiftUI diff,不向 UI 暴露 session/turn ID。最近完成和最近终止均保留 10 分钟,卡片与任务中心的耗时只在各自可见时逐秒 tick;已打开期间主快照变为 `nil` 时会立即收回任务中心。
+Hook 开启时,账号卡片下方始终显示固定高度 `CodexActivityCard`。`CodexQuotaSnapshot` 为 `nil` 时,卡片显示「暂无数据」且不开放任务中心;Monitor 继续维护实时状态。快照可用时,卡片按等待、运行、最近完成、最近终止、空闲的顺序展示项目最后一级名称、模型或工具、耗时及其他活动任务数量;只有终止历史时显示最近一项灰色终止状态。存在任务中心内容时,卡片可点击,其他活动任务数量使用右侧 `+N` 徽标,hover 和选中反馈作用于卡片描边。
+
+`ActivityCenterPanelController` 展示 `CodexActivitySnapshot` 的完整等待、运行、最近完成和最近终止列表。等待和运行按最后活动时间倒序,完成和终止按各自结束时间倒序;列表身份使用进程内 opaque UUID,不向 UI 暴露 session/turn ID。最近完成和最近终止保留 10 分钟。卡片与任务中心直接观察同一个 Monitor,并在菜单可见、额度快照可用且存在任务中心内容时使用 `CodexActivityCenterPresentationState` 的共享逐秒时间。任务中心打开期间额度快照变为 `nil` 时立即关闭。
错误图标触发条件:
@@ -147,7 +149,7 @@ Hook 开启时,账号卡片下方始终显示固定高度 `CodexActivityCard`
- 立即隐藏热力图详情面板、重置次数详情面板和并发任务中心
- 移除本地和全局事件监听
-- 将 `isVisible` 设为 `false`, 让倒计时停止 `TimelineView` 每秒 tick
+- 将 `isVisible` 设为 `false`, 停止活动卡片与任务中心共享的逐秒时间任务
- 临时禁止设置窗口和日志窗口成为 key window, 避免关闭菜单面板时 AppKit 把这些辅助窗口提到前面
- 默认执行 0.18 秒淡出, 无法淡出时直接关闭
- 菜单面板关闭后延迟 120 ms 恢复设置窗口和日志窗口的 key window 能力
@@ -165,7 +167,11 @@ Command-Space 不直接关闭菜单面板, 只短暂抑制 600 ms 内的 active
热力图详情面板、重置次数详情面板和并发任务中心都会通过 `containsScreenPoint(_:)` 告诉关闭监听器自己的屏幕区域, 因此点击这些 child panel 内部不会触发主菜单面板关闭。重置次数详情面板和并发任务中心可接收鼠标事件用于滚动; 热力图详情面板不接收鼠标事件。并发任务中心是点击后保持打开的面板;出现有效的热力图方块 hover context 时会自动收回任务中心并展示当天详情,点击重置次数也会显式切换并关闭任务中心。
-侧边面板的共同行为集中在 `CodexBar/Controllers/SidePanelSupport.swift`: `NonactivatingSidePanel` 固定不能成为 key/main window, `KeyableBorderlessPanel` 供需要键盘焦点的无边框面板(通知子选项面板、fallback 面板)共用, `SidePanelDrawerAnimator` 管理内容 view 的横向抽屉 transform, `SidePanelDrawerPresenter` 承载重置次数、并发任务中心和通知子选项三类「一次性展开」面板共用的显隐状态机(generation 竞态防护、入退场动画、child window 挂载/卸载、可选 makeKey), `SidePanelSupport` 提供 panel 工厂(`makePanel`, 由 `ignoresMouseEvents`、初始尺寸与 `keyable` 决定)、完整定位入口(`position`, 内含左右侧选择、坐标夹紧与 `SidePanelPosition` 组装, 纵向由调用方传入期望位置)、锚点行对齐与校验(`alignedProposedY` / `validatedAlignmentScreenFrame`, 容差 6 pt)、锚点感知的定位边界放宽(`anchorAwareVisibleFrame`, 宿主进入系统菜单栏保留区时只向上放宽到锚点行顶边)、共享几何/抽屉动画常量(`SidePanelSupport.Metrics`), 以及 child window 挂载/移除、菜单面板 key window 恢复、圆角 layer 配置和屏幕 frame 换算。`HeatmapDetailPanelController` 保留 hover 请求、Y 轴策略、侧边切换队列和 token/workflow 内容更新, 其切边/延迟隐藏状态机不走共享 presenter; `ResetCreditsPanelController` 主要保留重置次数内容、最大高度和点击切换状态;`ActivityCenterPanelController` 使用常驻 Monitor 快照原地更新任务列表,只有显隐时播放抽屉动画,并在主面板进入系统菜单栏保留区时只向上放宽定位边界到活动卡片顶边。任务中心先按当前分区和条目数扩展高度,并在打开期间随快照变化重新布局;高度同时受屏幕可见高度和活动卡片顶边到主面板底边的距离限制,只有达到该上限后列表才内部滚动,因此顶边保持对齐且底边不会越过主面板。三个面板视图的玻璃底/背板/描边/圆角裁剪皮肤共用 `LiquidGlassStyle.swift` 的 `sidePanelChrome(cornerRadius:)`。
+侧边面板的共同行为集中在 `CodexBar/Controllers/SidePanelSupport.swift`。`NonactivatingSidePanel` 不能成为 key/main window;`KeyableBorderlessPanel` 用于需要键盘焦点的通知子选项面板和 fallback 面板;`SidePanelDrawerAnimator` 管理横向抽屉 transform;`SidePanelDrawerPresenter` 管理重置次数、并发任务中心和通知子选项面板的显隐状态、generation、入退场动画及 child window 挂载。`SidePanelSupport` 统一提供 panel 创建、左右侧选择、屏幕边界夹紧、锚点行校验与对齐、菜单面板 key window 恢复、圆角 layer 配置和屏幕坐标换算。侧边面板视图的玻璃底、背板、描边和圆角裁剪共用 `LiquidGlassStyle.swift` 的 `sidePanelChrome(cornerRadius:)`。
+
+`HeatmapDetailPanelController` 管理 hover 请求、Y 轴策略、侧边切换队列和 token/workflow 内容更新;`ResetCreditsPanelController` 管理重置次数内容、最大高度和点击切换;`ActivityCenterPanelController` 观察常驻 Monitor 快照并更新列表与窗口布局。任务中心宽度固定,高度由标题、分区、固定行高、间距和底部留白计算,并受屏幕可见高度及活动卡片顶边到主面板底边的范围限制。活动卡片把 `ScreenFrameProvider` 作为锚点交给控制器,控制器每次布局都只读取属于当前菜单窗口的实时 frame;首次读取失败时等待一个 MainActor 调度点重试,仍无有效锚点才回退主面板垂直居中。锚点有效时,面板顶边与卡片顶边对齐,底边最低与主面板底边齐平;达到高度上限后列表内部滚动。
+
+任务中心列表使用普通 `VStack` 和单层条目 transition。快照变化后,SwiftUI 提交列表布局,AppKit 在下一个 MainActor 调度点用 0.20 秒 ease-in-ease-out 曲线更新 panel frame;新的快照会取消尚未执行的布局更新。任务中心内容变空时等待 0.20 秒再执行抽屉收起,期间出现新内容会取消收起。
设置窗口和日志窗口都继承 `HostingWindowController` 的行为: 懒创建, 关闭后不释放, 重新打开复用, 按当前屏幕居中, 重新打开对应入口时只移动和置前对应窗口。窗口 level 保持 `.normal`; 置前时先恢复 `AuxiliaryHostingWindow.allowsKeyFocus`, 再 `orderFrontRegardless()`, `NSRunningApplication.current.activate(options: [])` 和 `makeKeyAndOrderFront(nil)`, 只做一次性置前, 不持续置顶。CodexBar 是 `LSUIElement` 菜单栏 App, 首次懒创建辅助窗口时需要通过当前运行中应用激活, 避免设置或日志窗口第一次打开时没有稳定拉到最前。
@@ -472,7 +478,7 @@ Codex 版本探测错误:
| 脚本 | 失败条件 | 行为 |
| -------------------- | --------------------------------------------------------------- | -------------------------------------- |
| `Scripts/build.sh` | 找不到 Xcode 工程、签名命令、notary 凭据或导出 App | `set -euo pipefail` 直接退出并打印错误 |
-| `Scripts/build.sh` | archive、Developer ID 导出、notary、staple 或签名校验失败 | 退出, 不替换 build 中最终 App |
+| `Scripts/build.sh` | archive、Developer ID 导出、notary、staple 或签名校验失败 | 退出;默认不产出最终 App,保留中间产物 |
| `Scripts/dmg.sh` | 找不到唯一 App, 版本号缺失, DMG 挂载失败, 缺少必要命令 | `set -euo pipefail` 直接退出并打印错误 |
| `Scripts/appcast.sh` | 找不到 DMG, appcast, Xcode 工程, build setting 或 `sign_update` | 直接退出并打印错误 |
| `Scripts/appcast.sh` | 无法解析 `sparkle:edSignature` | 打印 sign_update 原始输出并退出 |
@@ -564,7 +570,7 @@ flowchart TD
- 无数据时百分比和重置时间显示 `--`, 电量条用占位色
- stale 数据通过 `.markStale(true)` 降低透明度到 0.55
-`QuotaLimitsSection` 通过 `ScreenFrameProvider` 持有额度区桥接 `NSView`, 点击「重置次数」时同步读取额度区在屏幕坐标系中的最新 frame, 作为重置次数详情面板顶部对齐锚点。`ScreenFrameReader` 是通用 `NSViewRepresentable`, 同时服务额度区和热力图, 会在 SwiftUI 布局稳定后上报 frame 并去重; `ScreenFrameProvider` 会记录最后有效 frame 兜底, 避免只依赖异步 SwiftUI 状态更新导致点击瞬间没有锚点。
+`QuotaLimitsSection` 通过 `ScreenFrameProvider` 持有额度区桥接 `NSView`, 点击「重置次数」时同步读取额度区在屏幕坐标系中的最新 frame, 作为重置次数详情面板顶部对齐锚点。`ScreenFrameReader` 是通用 `NSViewRepresentable`, 同时服务额度区、活动卡片和热力图;它接受父布局提出的尺寸,在 SwiftUI 布局稳定后上报 frame 并去重,视图拆除时解除与 provider 的绑定。`ScreenFrameProvider` 弱持有当前桥接视图,并同时记录最后有效 frame 及其所属 window。任务中心首次展示只接受当前菜单窗口中的实时 frame,失败时等待一个 MainActor 调度点后重试;后续布局也只允许同一窗口的缓存 frame 兜底,避免复用旧菜单窗口坐标导致顶部错位。额度区和热力图继续按各自控制器的锚点校验与降级策略读取坐标。
重置次数详情面板由 `ResetCreditsPanelController` 管理:
@@ -1025,7 +1031,7 @@ App 再次成为 active 时, 也会刷新 Codex 版本区、同步可用性, 并
- notary 凭据优先使用 `--notary-profile`; 未设置时使用 `--apple-id`、`--notary-password` 和 `--team-id`; 如果两组参数同时提供, `--notary-profile` 生效, Apple ID 三件套会被忽略
- 将导出的 App 压缩后提交 `xcrun notarytool submit --wait`, 成功后对 App 执行 `stapler staple` 和 `stapler validate`
- 通过 `codesign --verify --deep --strict` 校验导出 App 和最终 App; 默认额外执行 `spctl --assess`
-- 成功后把最终 App 写入 `build/CodexBar.app` 或传入的 `Output.app`; notary 失败时不替换最终 App
+- 成功后把最终 App 写入 `build/CodexBar.app` 或传入的 `Output.app`; 失败时默认不产出最终 App,自定义 build 外输出路径不替换既有 App
- 最终 App 校验通过后清理 `build/` 下的 archive、DerivedData 等中间产物, 默认只保留 `build/CodexBar.app`; 如果构建或 notary 失败, 保留中间产物便于排查
- 可用 `--skip-notarization` 只执行 archive/export/signature verify, 便于本地调试脚本
@@ -1096,15 +1102,15 @@ App 再次成为 active 时, 也会刷新 Codex 版本区、同步可用性, 并
五类通知的触发与去重:
-| 通知 | 触发 | 去重键 |
-| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
-| 额度低阈值 | 非 stale 快照中窗口剩余比例穿越到 ≤ 阈值; 阈值或子开关变化时用当前快照立即重评估 | `low\|账号\|limitId\|windowId\|resetsAt` |
-| 额度已重置 | 同一账号下每个 limit 的 primary/secondary 窗口独立观察;可信快照中消耗曾大于 0%,之后更新为 0% 时立即发送以面板 `limit.title` 和窗口周期命名的通知 | 进程内按 `账号\|limitId\|windowId` 状态转换 |
-| 长任务完成 | monitor 的 live Hook `Stop` 或 rollout `task_complete` transition 具有精确耗时且耗时 ≥ 阈值 | 状态机按精确任务键对两种完成信号去重 |
-| 任务等待批准 | monitor 的 live 批次结束后任务最终仍处于 `waitingApproval` | 同批次按任务键合并,最终快照只发布一次 |
-| 重置机会临期 | 过期时间距今 ≤ 7 天, 并在过期前 7/6/5/4/3/2/1 天各提醒一次; 正文使用本地时间 `yyyy-MM-dd HH:mm:ss` | `credit\|账号\|过期时间\|提醒档位` |
+| 通知 | 触发 | 去重键 |
+| ------------ | --------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
+| 额度低阈值 | 非 stale 快照中窗口剩余比例穿越到 ≤ 阈值; 阈值或子开关变化时用当前快照立即重评估 | `low\|账号\|limitId\|windowId\|resetsAt` |
+| 额度已重置 | 同一账号下每个 limit 的 primary/secondary 窗口独立观察;可信快照中消耗从大于 0% 变为 0% 时立即发送以 `limit.title` 和窗口周期命名的通知 | 进程内按 `账号\|limitId\|windowId` 观察状态转换;成功发送后使用 `quotaReset\|账号\|limitId\|windowId\|resetsAt` 持久化去重 |
+| 长任务完成 | monitor 的 live Hook `Stop` 或 rollout `task_complete` transition 具有精确耗时且耗时 ≥ 阈值 | 状态机按精确任务键对两种完成信号去重 |
+| 任务等待批准 | monitor 的 live 批次结束后任务处于 `waitingApproval`;当前进程内任务离开等待状态后移除对应的 delivered/pending 通知 | 同批次按任务键合并,通知使用 `taskWaiting\|taskUUID` 任务级 identifier |
+| 重置机会临期 | 过期时间距今 ≤ 7 天, 并在过期前 7/6/5/4/3/2/1 天各提醒一次; 正文使用本地时间 `yyyy-MM-dd HH:mm:ss` | `credit\|账号\|过期时间\|提醒档位` |
-额度低阈值和重置机会通知只在系统成功接收后才把已发送去重键持久化到 UserDefaults (`Notification.sentKeys`, 上限 300 条滚动淘汰), 账号维度包含在键中, 切换账号自动隔离。通知服务初始化时会移除旧版预测式额度重置留下的 `reset|` 去重键和 pending reminder 数据,保留有效的 `low|` / `credit|` 键。额度重置与任务等待状态只保留在当前进程内,不按预测时间调度或补发;可信额度快照即使在总开关关闭或授权不可用时也会继续消费重置状态转换但不发送,并移除当前快照中已经消失的窗口,整个快照变为空时清空全部待重置窗口。bootstrap 会恢复 App 启动前滚动 24 小时内的任务状态,但永远不发布 transition,因此不会补发历史权限通知、完成通知或触觉反馈;重新开启通知也不会回放旧事件。
+额度低阈值、额度重置和重置机会通知只在系统成功接收后把去重键写入 UserDefaults (`Notification.sentKeys`),最多保留 300 条。键包含账号维度;额度重置窗口提供 `resetsAt` 时,去重键还包含该时间,缺失时仍发送通知但不生成周期去重键。额度重置观察状态和等待通知跟踪集合保存在当前进程内;通知不按预测时间调度,也不补发已错过的状态转换。可信额度快照持续推进重置观察状态,stale 快照不参与判定;窗口消失时移除对应观察状态,快照为 `nil` 时清空全部观察状态。Hook bootstrap 只恢复任务状态,不发布 transition,因此不产生历史任务通知或触觉反馈。
「任务触觉反馈」使用 `Notification.taskHapticEnabled` 持久化,缺失时默认开启。等待批准和任意任务完成 transition 都启动一段触觉反馈任务:每 100 ms 请求一次 `.levelChange`,连续 10 次;新 transition 会取消并重启当前序列,开关关闭后会在下一脉冲前停止。触觉反馈不受长任务阈值与系统通知授权影响;App 内「系统通知」总开关关闭时不触发。`NSHapticFeedbackManager.defaultPerformer` 会按当前输入设备、辅助功能与系统偏好决定是否实际反馈及震感强弱。
diff --git a/Docs/UserGuide.md b/Docs/UserGuide.md
index b0e1324..919d458 100644
--- a/Docs/UserGuide.md
+++ b/Docs/UserGuide.md
@@ -95,6 +95,8 @@ CodexBar 是菜单栏 App,不显示 Dock 图标,也没有传统的主窗口
- 绿色:任务刚刚完成,绿色状态保留约 30 秒。
- 无状态点:当前没有等待或运行任务,也没有处于绿色高亮期的完成任务。
+状态点只在主面板额度快照可用时按上述任务状态绘制;活动卡片显示「暂无数据」时不显示状态点。
+
当多个状态同时存在时,显示优先级为:等待批准、运行中、刚完成、空闲。
## 4. 使用菜单面板
@@ -128,7 +130,7 @@ CodexBar 默认每 60 秒自动刷新一次。菜单面板底部「数据更新
「完成」只表示 Codex 已确认该轮结束,不代表任务结果一定成功。「终止」表示任务没有按正常完成路径结束,也不会触发绿色状态或完成通知。
-最近完成和最近终止记录保留约 10 分钟。任务中心会在菜单侧面展开,右侧空间不足时自动改到左侧;内容较多时可以在任务中心内滚动。
+最近完成和最近终止记录保留约 10 分钟。任务中心会在菜单侧面展开,右侧空间不足时自动改到左侧,顶边优先与活动卡片对齐。点击时如果卡片布局尚未稳定,任务中心会等待一次布局更新后重试;仍然无法取得有效位置时,才在主面板旁垂直居中。面板高度随列表内容变化,底部与最后一个项目保持固定留白且不会低于主面板底边;内容达到可用高度上限后改为内部滚动。
### 额度和重置时间
@@ -313,10 +315,10 @@ Hook 命令包含 CodexBar 当前可执行文件的完整路径。如果准备
### 可用通知
-| 选项 | 触发条件 | 可配置项 |
+| 选项 | 触发条件 | 配置或频率 |
| ---------------- | ---------------------------------- | -------------------------------- |
| 额度预警通知 | 可信额度从阈值上方跌到阈值或以下 | 5%、10%、25%,默认 10% |
-| 额度重置通知 | 已发生消耗的额度窗口恢复到 100% | 无 |
+| 额度重置通知 | 已发生消耗的额度窗口恢复到 100% | 提供重置时间时,同周期提醒一次 |
| 任务完成通知 | Hook 任务确认完成且耗时达到阈值 | 30 秒、1、2、5 分钟,默认 1 分钟 |
| 任务等待通知 | 任务在一批事件处理结束后仍等待批准 | 无 |
| 任务触觉反馈 | 任务进入等待批准或确认结束 | 需要 Hook;服从通知总开关 |
@@ -324,6 +326,8 @@ Hook 命令包含 CodexBar 当前可执行文件的完整路径。如果准备
任务完成、任务等待和任务触觉选项需要 Hook。Hook 关闭时,这些选项会显示为关闭并置灰,但不会丢失用户原来的偏好。
+当前 App 进程发出的等待批准通知会跟随 Monitor 中的任务状态;任务恢复运行、完成、终止或以其他方式离开等待状态后,通知会自动从通知中心移除,不影响其他仍在等待的并发任务。
+
触觉反馈是否真的发生、震感强弱和形式由 Mac、触控板、辅助功能及系统偏好决定。CodexBar 请求了触觉,不代表所有设备都能产生明显反馈。
点击 CodexBar 发出的系统通知会尝试打开主菜单面板,方便继续查看当前状态。
diff --git a/README.md b/README.md
index 24ef63c..9a8ae2c 100644
--- a/README.md
+++ b/README.md
@@ -39,9 +39,9 @@ CodexBar 是一个无 Dock 图标的 macOS 菜单栏应用。
「菜单栏额度指示」默认开启,菜单栏图标左侧会以一条细竖向进度条显示当前账号 Codex 额度中所选窗口的剩余比例;关闭后菜单栏图标保持纯图标显示。
-开启 Codex Hook 后,菜单栏小人右下角的状态点会反映实时任务状态:运行中为蓝色、等待批准为橙色、刚完成为绿色,暂无活动时不显示。状态优先级依次为等待批准、运行中、刚完成和暂无活动;小人保持系统前景色,账号异常仍使用带叉图标表示,额度竖条也保持自己的颜色。
+开启 Codex Hook 后,菜单栏小人右下角的状态点会反映实时任务状态:运行中为蓝色、等待批准为橙色、刚完成为绿色,暂无活动时不显示。主面板额度快照不可用时也不显示状态点,与活动卡片的「暂无数据」状态保持一致。状态优先级依次为等待批准、运行中、刚完成和暂无活动;小人保持系统前景色,账号异常仍使用带叉图标表示,额度竖条也保持自己的颜色。
-菜单面板账号卡片下方会固定显示活动卡片,汇总当前项目、模型、工具、耗时和其他并发任务数量。主面板快照尚未加载时,活动卡片同步显示「暂无数据」且不开放任务中心;快照可用且存在活动任务、最近完成或最近终止记录时,点击卡片会打开并发任务中心,按等待确认、运行中、最近完成和最近终止分组展示全部任务。只有终止历史时,卡片会用灰色终止状态展示最近一项,不再显示「暂无 Codex 活动」。面板优先在菜单右侧展开,空间不足时自动切换到左侧。绿色完成状态保留 30 秒,最近完成和最近终止记录会保留 10 分钟;终止记录不触发完成提醒。
+菜单面板账号卡片下方会固定显示活动卡片,汇总当前项目、模型、工具、耗时和其他并发任务数量。主面板快照不可用时,活动卡片显示「暂无数据」且不开放任务中心;快照可用并存在活动任务、最近完成或最近终止记录时,点击卡片会打开并发任务中心,按等待确认、运行中、最近完成和最近终止分组展示全部任务。只有终止历史时,卡片显示最近一项灰色终止状态。面板优先在菜单右侧展开,空间不足时自动切换到左侧,并优先与活动卡片顶边对齐;暂时无法取得有效位置时会等待布局更新后重试,仍然失败才在主面板旁垂直居中。绿色完成状态保留 30 秒,最近完成和最近终止记录保留 10 分钟;终止记录不触发完成提醒。
### 额度与重置时间一眼可见
@@ -61,7 +61,7 @@ CodexBar 是一个无 Dock 图标的 macOS 菜单栏应用。
统计结果会汇总到热力图详情面板中,不打断正常的 Codex 使用流程。
-主 App 还会在后台只读 Hook JSONL:启动时按块恢复最近 24 小时的活动,之后 tail 当天新增事件,并在内存中维护并发任务状态。跨日任务缺少起点时会按精确 session + turn 定向查找更早的 Prompt;对于仍处于运行、等待终态确认或等待批准状态的精确 turn,CodexBar 会每秒增量读取对应本机 Codex session rollout,仅用 `task_started` 回填缺失起点、用 `task_complete` 补齐缺失的结束、用 `turn_aborted` 清理中断任务并生成短暂的最近终止记录。同 session 新 Prompt 会让旧 turn 立即退出活动列表,但先保留 5 秒终态确认窗口,优先接受 rollout 或迟到 Hook 的完成/终止信号,仍无终态才记为终止。不读取提示词、回复、推理或工具内容。该实时状态用于菜单栏状态点、活动卡片、并发任务中心、可选任务通知和触觉反馈,不新增历史状态文件,也不参与跨设备同步。
+主 App 还会在后台只读 Hook JSONL:启动时按块恢复最近 24 小时的活动,之后 tail 当天新增事件,并在内存中维护并发任务状态。跨日任务缺少起点时会按精确 session + turn 定向查找更早的 Prompt;对于仍处于运行、等待终态确认或等待批准状态的精确 turn,CodexBar 会每秒增量读取对应本机 Codex session rollout,仅用 `task_started` 回填缺失起点、用 `task_complete` 补齐缺失的结束、用 `turn_aborted` 清理中断任务并生成最近终止记录。同 session 新 Prompt 会让旧 turn 立即退出活动列表,但先保留 5 秒终态确认窗口,优先接受 rollout 或迟到 Hook 的完成/终止信号,仍无终态才记为终止。不读取提示词、回复、推理或工具内容。该实时状态用于菜单栏状态点、活动卡片、并发任务中心、可选任务通知和触觉反馈,不新增历史状态文件,也不参与跨设备同步。
CodexBar 只会追加或移除属于当前 CodexBar 可执行文件的 Hook,不会删除用户已有的其他 Codex Hook。
@@ -82,9 +82,9 @@ CodexBar 会把该设备的使用详情数据同步到当前 iCloud 账号的 Cl
在设置中开启「系统通知」后,CodexBar 会在关键状态变化时发送本地通知:
- 额度剩余比例跌破所选阈值 (5% / 10% / 25%)
-- 每个额度类型和时间窗口产生消耗后恢复至 100% 时提示额度已重置
+- 每个额度类型和时间窗口产生消耗后恢复至 100% 时提示额度已重置;窗口提供重置时间时,同一周期只提醒一次
- Codex 完成一轮超过所选时长的任务 (需开启 Codex Hook)
-- Codex 请求批准工具操作并等待用户处理 (需开启 Codex Hook)
+- Codex 请求批准工具操作并等待用户处理;当前 App 运行期间任务离开等待状态后自动撤回对应通知 (需开启 Codex Hook)
- 手动重置机会将在 7 天内过期,并按 24 小时间隔提醒
五类通知可以单独开关;全部为本地通知,不新增网络请求。
diff --git a/appcast.xml b/appcast.xml
index dd7b38a..b6395e9 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.3.5</title>
+ <sparkle:version>43</sparkle:version>
+ <sparkle:shortVersionString>3.3.5</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.3.5</sparkle:releaseNotesLink>
+ <pubDate>Sun, 12 Jul 2026 21:26:55 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.3.5.dmg" sparkle:edSignature="uRaQAj2G+Ru+oaxcYckQXTKkIHc9h2NtJdjusTe7Xr+c9q4LwP36M2oc2jk+ftWpppsU5jyx7EDTQWSzLF4KAA==" length="3986637" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.3.4</title>
<sparkle:version>42</sparkle:version>