Skip to content

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

feat: 添加系统通知与模型统计

Bob731e56bb7a30
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxproj
index 2e4c12f..cad1190 100644
--- a/CodexBar.xcodeproj/project.pbxproj
+++ b/CodexBar.xcodeproj/project.pbxproj
@@ -298,7 +298,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 3.2.10;
+ MARKETING_VERSION = 3.3.0;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
@@ -337,7 +337,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 3.2.10;
+ MARKETING_VERSION = 3.3.0;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
diff --git a/CodexBar/Controllers/FallbackPanelController.swift b/CodexBar/Controllers/FallbackPanelController.swift
index 11153c7..c965d65 100644
--- a/CodexBar/Controllers/FallbackPanelController.swift
+++ b/CodexBar/Controllers/FallbackPanelController.swift
@@ -5,7 +5,7 @@ import SwiftUI
@MainActor
final class FallbackPanelController {
private let makeContentController: () -> NSHostingController<AnyView>
- private var panel: FallbackStatusPanel?
+ private var panel: KeyableBorderlessPanel?
init(makeContentController: @escaping () -> NSHostingController<AnyView>) {
self.makeContentController = makeContentController
@@ -43,12 +43,12 @@ final class FallbackPanelController {
panel?.orderOut(nil)
}
- private func makePanelIfNeeded() -> FallbackStatusPanel {
+ private func makePanelIfNeeded() -> KeyableBorderlessPanel {
if let panel {
return panel
}
- let panel = FallbackStatusPanel(
+ let panel = KeyableBorderlessPanel(
contentRect: NSRect(origin: .zero, size: Metrics.fallbackSize),
styleMask: [.borderless, .fullSizeContentView],
backing: .buffered,
@@ -109,13 +109,3 @@ final class FallbackPanelController {
static let topInset: CGFloat = 8
}
}
-
-private final class FallbackStatusPanel: NSPanel {
- override var canBecomeKey: Bool {
- true
- }
-
- override var canBecomeMain: Bool {
- false
- }
-}
diff --git a/CodexBar/Controllers/NotificationOptionsPanelController.swift b/CodexBar/Controllers/NotificationOptionsPanelController.swift
new file mode 100644
index 0000000..37549e3
--- /dev/null
+++ b/CodexBar/Controllers/NotificationOptionsPanelController.swift
@@ -0,0 +1,204 @@
+import AppKit
+import SwiftUI
+
+/// 通知子选项面板动作, 由 AppSettingsView 发出并在 SettingsWindowController 中路由
+nonisolated enum NotificationOptionsPanelAction: Equatable {
+ case toggle(alignmentScreenFrame: CGRect?)
+ case open(alignmentScreenFrame: CGRect?)
+ case close
+}
+
+/// 通知子选项面板控制器, 挂在设置窗口右侧, 复用侧边抽屉动效
+/// 与重置次数面板不同: 内容是交互控件, 用常驻 hosting controller + ObservableObject 驱动更新, 不替换 rootView
+@MainActor
+final class NotificationOptionsPanelController {
+ private let notificationSettings: NotificationSettings
+ private let codexHookSettings: CodexHookSettings
+ private var panel: NSPanel?
+ private var hostingController: NSHostingController<NotificationOptionsView>?
+ private lazy var presenter = SidePanelDrawerPresenter(
+ animationKey: Metrics.drawerTransformAnimationKey,
+ makesKey: true,
+ contentViewProvider: { [weak self] in
+ self?.hostingController?.view
+ }
+ )
+ private weak var settingsWindow: NSWindow?
+ private var panelDismissObserver: NSObjectProtocol?
+ private var settingsWindowDismissObservers: [NSObjectProtocol] = []
+
+ init(
+ notificationSettings: NotificationSettings,
+ codexHookSettings: CodexHookSettings
+ ) {
+ self.notificationSettings = notificationSettings
+ self.codexHookSettings = codexHookSettings
+ }
+
+ var isVisible: Bool {
+ presenter.isVisible
+ }
+
+ func owns(_ window: NSWindow?) -> Bool {
+ window === panel
+ }
+
+ func toggle(
+ alignmentScreenFrame: CGRect?,
+ relativeTo window: NSWindow?,
+ contentView: NSView?
+ ) {
+ if isVisible {
+ hide()
+ return
+ }
+
+ show(
+ alignmentScreenFrame: alignmentScreenFrame,
+ relativeTo: window,
+ contentView: contentView
+ )
+ }
+
+ func show(
+ alignmentScreenFrame: CGRect?,
+ relativeTo window: NSWindow?,
+ contentView: NSView?
+ ) {
+ guard let window else {
+ hide(immediate: true)
+ return
+ }
+
+ let panel = ensurePanel()
+ let windowSurfaceFrame = SidePanelSupport.contentScreenFrame(for: contentView, in: window) ?? window.frame
+ let panelSize = measuredPanelSize()
+ let validatedAlignmentFrame = SidePanelSupport.validatedAlignmentScreenFrame(
+ alignmentScreenFrame,
+ menuSurfaceFrame: windowSurfaceFrame
+ )
+ let position = SidePanelSupport.position(
+ panelSize: panelSize,
+ menuSurfaceFrame: windowSurfaceFrame,
+ visibleFrame: (window.screen ?? NSScreen.main)?.visibleFrame ?? windowSurfaceFrame,
+ preferredSide: .right,
+ proposedY: SidePanelSupport.alignedProposedY(
+ panelSize: panelSize,
+ menuSurfaceFrame: windowSurfaceFrame,
+ alignmentScreenFrame: validatedAlignmentFrame
+ )
+ )
+
+ panel.level = window.level
+ installSettingsWindowDismissObservers(for: window)
+ presenter.present(panel, at: position, relativeTo: window)
+ }
+
+ func hide(immediate: Bool = false) {
+ presenter.hide(immediate: immediate)
+ }
+
+ private func ensurePanel() -> NSPanel {
+ if let panel {
+ return panel
+ }
+
+ let panel = SidePanelSupport.makePanel(
+ initialSize: NotificationOptionsView.initialPanelSize,
+ ignoresMouseEvents: false,
+ keyable: true
+ )
+ let hostingController = NSHostingController(
+ rootView: NotificationOptionsView(
+ notificationSettings: notificationSettings,
+ codexHookSettings: codexHookSettings
+ )
+ )
+ hostingController.sizingOptions = [.preferredContentSize]
+ panel.contentViewController = hostingController
+ SidePanelSupport.configureLayers(
+ hostingView: hostingController.view,
+ contentView: panel.contentView,
+ cornerRadius: NotificationOptionsView.panelCornerRadius
+ )
+ panelDismissObserver = makeResignKeyDismissObserver(observing: panel) { [weak self] keyWindow in
+ self?.owns(keyWindow) != true
+ }
+ self.hostingController = hostingController
+ self.panel = panel
+ return panel
+ }
+
+ /// 设置窗口和面板之间切换 key 不收起; 焦点离开这个窗口组或设置窗口关闭时收起
+ private func installSettingsWindowDismissObservers(for window: NSWindow) {
+ guard settingsWindow !== window || settingsWindowDismissObservers.isEmpty else {
+ return
+ }
+
+ settingsWindow = window
+ for observer in settingsWindowDismissObservers {
+ NotificationCenter.default.removeObserver(observer)
+ }
+
+ settingsWindowDismissObservers = [
+ makeResignKeyDismissObserver(observing: window) { [weak self, weak window] keyWindow in
+ keyWindow !== window && self?.owns(keyWindow) != true
+ },
+ NotificationCenter.default.addObserver(
+ forName: NSWindow.willCloseNotification,
+ object: window,
+ queue: .main
+ ) { [weak self] _ in
+ Task { @MainActor [weak self] in
+ self?.hide(immediate: true)
+ }
+ }
+ ]
+ }
+
+ /// resignKey 后让出一轮 runloop, 等新 keyWindow 生效再判定
+ private func makeResignKeyDismissObserver(
+ observing window: NSWindow,
+ shouldDismiss: @escaping @MainActor (NSWindow?) -> Bool
+ ) -> NSObjectProtocol {
+ NotificationCenter.default.addObserver(
+ forName: NSWindow.didResignKeyNotification,
+ object: window,
+ queue: .main
+ ) { [weak self] _ in
+ Task { @MainActor [weak self] in
+ guard let self else {
+ return
+ }
+
+ await Task.yield()
+ guard isVisible, shouldDismiss(NSApplication.shared.keyWindow) else {
+ return
+ }
+
+ hide()
+ }
+ }
+ }
+
+ private func measuredPanelSize() -> CGSize {
+ guard let hostingView = hostingController?.view else {
+ return NotificationOptionsView.initialPanelSize
+ }
+
+ hostingView.layoutSubtreeIfNeeded()
+ let fittingSize = hostingView.fittingSize
+ guard fittingSize.width.isFinite,
+ fittingSize.height.isFinite,
+ fittingSize.width > 0,
+ fittingSize.height > 0 else {
+ return NotificationOptionsView.initialPanelSize
+ }
+
+ return fittingSize
+ }
+
+ private enum Metrics {
+ static let drawerTransformAnimationKey = "CodexBar.notificationOptionsDrawerTransform"
+ }
+}
diff --git a/CodexBar/Controllers/ResetCreditsPanelController.swift b/CodexBar/Controllers/ResetCreditsPanelController.swift
index 603eb32..cb17f97 100644
--- a/CodexBar/Controllers/ResetCreditsPanelController.swift
+++ b/CodexBar/Controllers/ResetCreditsPanelController.swift
@@ -1,5 +1,4 @@
import AppKit
-import QuartzCore
import SwiftUI
/// 重置次数详情控制器, 复用热力图详情的侧边抽屉动效
@@ -7,20 +6,15 @@ import SwiftUI
final class ResetCreditsPanelController {
private var panel: NSPanel?
private var hostingController: NSHostingController<ResetCreditsPanelView>?
- private lazy var drawerAnimator = SidePanelDrawerAnimator(
+ private lazy var presenter = SidePanelDrawerPresenter(
+ animationKey: Metrics.drawerTransformAnimationKey,
contentViewProvider: { [weak self] in
self?.hostingController?.view
- },
- animationKey: Metrics.drawerTransformAnimationKey,
- overscan: SidePanelSupport.Metrics.drawerOverscan
+ }
)
- private var visibilityGeneration = 0
- private var isExitAnimationRunning = false
- private var currentSide = UsageHeatmapDetailSide.right
- private weak var menuSurfaceWindow: NSWindow?
var isVisible: Bool {
- panel?.isVisible == true
+ presenter.isVisible
}
func containsScreenPoint(_ screenPoint: NSPoint) -> Bool {
@@ -49,51 +43,7 @@ final class ResetCreditsPanelController {
}
func hide(immediate: Bool = false) {
- guard let panel, panel.isVisible else {
- return
- }
-
- if immediate {
- visibilityGeneration += 1
- hideImmediately(panel)
- return
- }
-
- guard !isExitAnimationRunning else {
- return
- }
-
- hideWithAnimation(panel)
- }
-
- private func hideImmediately(_ panel: NSPanel) {
- drawerAnimator.resetVisualState(for: panel)
- isExitAnimationRunning = false
- orderOut(panel)
- }
-
- private func hideWithAnimation(_ panel: NSPanel) {
- visibilityGeneration += 1
- let generation = visibilityGeneration
- let side = currentSide
- isExitAnimationRunning = true
- let hidden = drawerAnimator.hiddenTranslation(for: side, panelWidth: panel.frame.width)
- drawerAnimator.animateTranslation(
- to: hidden,
- duration: SidePanelSupport.Metrics.drawerExitDuration,
- timing: .easeIn
- ) {
- Task { @MainActor [weak self] in
- guard let self,
- generation == visibilityGeneration else {
- return
- }
-
- orderOut(panel)
- drawerAnimator.setTranslation(0)
- isExitAnimationRunning = false
- }
- }
+ presenter.hide(immediate: immediate)
}
private func show(
@@ -108,7 +58,7 @@ final class ResetCreditsPanelController {
let panel = ensurePanel()
let menuSurfaceFrame = SidePanelSupport.contentScreenFrame(for: contentView, in: menuSurfaceWindow) ?? menuSurfaceWindow.frame
- let alignmentScreenFrame = validAlignmentScreenFrame(
+ let alignmentScreenFrame = SidePanelSupport.validatedAlignmentScreenFrame(
context.alignmentScreenFrame,
menuSurfaceFrame: menuSurfaceFrame
)
@@ -133,10 +83,8 @@ final class ResetCreditsPanelController {
SidePanelSupport.restoreMenuSurfaceKeyWindow(menuSurfaceWindow)
}
- visibilityGeneration += 1
- isExitAnimationRunning = false
- apply(context: resolvedContext, panelSize: panelSize, position: position, to: panel)
- showPanelWithDrawerAnimation(panel, relativeTo: menuSurfaceWindow)
+ updateContent(resolvedContext, size: panelSize)
+ presenter.present(panel, at: position, relativeTo: menuSurfaceWindow)
}
private func ensurePanel() -> NSPanel {
@@ -172,47 +120,6 @@ final class ResetCreditsPanelController {
panel?.setContentSize(size)
}
- private func apply(
- context: ResetCreditsPanelContext,
- panelSize: CGSize,
- position: SidePanelPosition,
- to panel: NSPanel
- ) {
- updateContent(context, size: panelSize)
- panel.setFrame(position.frame, display: true)
- panel.alphaValue = 1
- currentSide = position.side
- }
-
- private func showPanelWithDrawerAnimation(_ panel: NSPanel, relativeTo menuSurfaceWindow: NSWindow) {
- let generation = visibilityGeneration
- let hidden = drawerAnimator.hiddenTranslation(for: currentSide, panelWidth: panel.frame.width)
- drawerAnimator.setTranslation(hidden)
- panel.alphaValue = 0
- attach(panel, to: menuSurfaceWindow)
- panel.order(.above, relativeTo: menuSurfaceWindow.windowNumber)
- drawerAnimator.animateEntryAfterInitialLayout(
- from: hidden,
- panel: panel,
- duration: SidePanelSupport.Metrics.drawerEnterDuration,
- isCurrent: { [weak self] in
- self?.visibilityGeneration == generation
- },
- completion: { [weak self] in
- self?.drawerAnimator.setTranslation(0)
- }
- )
- }
-
- private func attach(_ panel: NSPanel, to parentWindow: NSWindow) {
- menuSurfaceWindow = parentWindow
- SidePanelSupport.attach(panel, to: parentWindow)
- }
-
- private func orderOut(_ panel: NSPanel) {
- SidePanelSupport.orderOut(panel, menuSurfaceWindow: menuSurfaceWindow)
- }
-
private func panelPosition(
for panelSize: CGSize,
menuSurfaceFrame: CGRect,
@@ -225,26 +132,14 @@ final class ResetCreditsPanelController {
menuSurfaceFrame: menuSurfaceFrame,
visibleFrame: visibleFrame,
preferredSide: preferredSide,
- proposedY: proposedY(
- for: panelSize,
+ proposedY: SidePanelSupport.alignedProposedY(
+ panelSize: panelSize,
menuSurfaceFrame: menuSurfaceFrame,
alignmentScreenFrame: alignmentScreenFrame
)
)
}
- private func proposedY(
- for panelSize: CGSize,
- menuSurfaceFrame: CGRect,
- alignmentScreenFrame: CGRect?
- ) -> CGFloat {
- if let alignmentScreenFrame {
- return alignmentScreenFrame.maxY - panelSize.height
- }
-
- return menuSurfaceFrame.midY - panelSize.height / 2
- }
-
private func panelMaximumHeight(
menuSurfaceFrame: CGRect,
alignmentScreenFrame: CGRect?
@@ -260,30 +155,7 @@ final class ResetCreditsPanelController {
return maximumHeight
}
- private func validAlignmentScreenFrame(
- _ alignmentScreenFrame: CGRect?,
- menuSurfaceFrame: CGRect
- ) -> CGRect? {
- guard let alignmentScreenFrame = alignmentScreenFrame?.standardized,
- alignmentScreenFrame.isValidScreenRect else {
- return nil
- }
-
- let validationFrame = menuSurfaceFrame
- .standardized
- .insetBy(
- dx: -Metrics.anchorValidationTolerance,
- dy: -Metrics.anchorValidationTolerance
- )
- guard validationFrame.intersects(alignmentScreenFrame) else {
- return nil
- }
-
- return alignmentScreenFrame
- }
-
private enum Metrics {
- static let anchorValidationTolerance: CGFloat = 6
static let drawerTransformAnimationKey = "CodexBar.resetCreditsDrawerTransform"
}
}
diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swift
index 952de40..9a8feca 100644
--- a/CodexBar/Controllers/SettingsWindowController.swift
+++ b/CodexBar/Controllers/SettingsWindowController.swift
@@ -10,7 +10,12 @@ final class SettingsWindowController: HostingWindowController {
private let syncSettings: WorkflowSyncSettings
private let globalHotKeySettings: GlobalHotKeySettings
private let menuBarQuotaSettings: MenuBarQuotaSettings
+ private let notificationSettings: NotificationSettings
private let onSyncChanged: (Bool) -> Void
+ private lazy var notificationOptionsPanelController = NotificationOptionsPanelController(
+ notificationSettings: notificationSettings,
+ codexHookSettings: codexHookSettings
+ )
init(
viewModel: CodexStatusViewModel,
@@ -19,6 +24,7 @@ final class SettingsWindowController: HostingWindowController {
syncSettings: WorkflowSyncSettings,
globalHotKeySettings: GlobalHotKeySettings,
menuBarQuotaSettings: MenuBarQuotaSettings,
+ notificationSettings: NotificationSettings,
screenProvider: @escaping () -> NSScreen?,
onSyncChanged: @escaping (Bool) -> Void
) {
@@ -28,6 +34,7 @@ final class SettingsWindowController: HostingWindowController {
self.syncSettings = syncSettings
self.globalHotKeySettings = globalHotKeySettings
self.menuBarQuotaSettings = menuBarQuotaSettings
+ self.notificationSettings = notificationSettings
self.onSyncChanged = onSyncChanged
super.init(screenProvider: screenProvider)
}
@@ -44,7 +51,11 @@ final class SettingsWindowController: HostingWindowController {
syncSettings: syncSettings,
globalHotKeySettings: globalHotKeySettings,
menuBarQuotaSettings: menuBarQuotaSettings,
- onSyncChanged: onSyncChanged
+ notificationSettings: notificationSettings,
+ onSyncChanged: onSyncChanged,
+ onNotificationOptionsAction: { [weak self] action in
+ self?.handleNotificationOptionsAction(action)
+ }
)
.environmentObject(viewModel)
.environmentObject(appUpdater)
@@ -82,6 +93,25 @@ final class SettingsWindowController: HostingWindowController {
menuBarQuotaSettings.refresh()
}
+ private func handleNotificationOptionsAction(_ action: NotificationOptionsPanelAction) {
+ switch action {
+ case let .toggle(alignmentFrame):
+ notificationOptionsPanelController.toggle(
+ alignmentScreenFrame: alignmentFrame,
+ relativeTo: window,
+ contentView: window?.contentViewController?.view
+ )
+ case let .open(alignmentFrame):
+ notificationOptionsPanelController.show(
+ alignmentScreenFrame: alignmentFrame,
+ relativeTo: window,
+ contentView: window?.contentViewController?.view
+ )
+ case .close:
+ notificationOptionsPanelController.hide()
+ }
+ }
+
private func maximumContentSize(for window: NSWindow) -> NSSize {
guard let screen = screenProvider() ?? window.screen ?? NSScreen.main else {
return Metrics.maximumFallbackContentSize
diff --git a/CodexBar/Controllers/SidePanelSupport.swift b/CodexBar/Controllers/SidePanelSupport.swift
index 2dd1aef..54051d2 100644
--- a/CodexBar/Controllers/SidePanelSupport.swift
+++ b/CodexBar/Controllers/SidePanelSupport.swift
@@ -13,6 +13,18 @@ final class NonactivatingSidePanel: NSPanel {
}
}
+/// 可获得键盘焦点的无边框面板, 用于含交互控件的子面板和 fallback 面板
+@MainActor
+final class KeyableBorderlessPanel: NSPanel {
+ override var canBecomeKey: Bool {
+ true
+ }
+
+ override var canBecomeMain: Bool {
+ false
+ }
+}
+
@MainActor
final class SidePanelDrawerAnimator {
private let contentViewProvider: @MainActor () -> NSView?
@@ -129,24 +141,145 @@ final class SidePanelDrawerAnimator {
}
}
+/// 重置次数 / 通知子选项两类「一次性展开」抽屉面板共用的显隐状态机:
+/// 负责 generation 竞态防护、入退场动画和 child window 挂载/卸载
+/// (热力图详情面板因带切边与延迟隐藏, 状态机不同, 不走这里)
+@MainActor
+final class SidePanelDrawerPresenter {
+ private let makesKey: Bool
+ private let drawerAnimator: SidePanelDrawerAnimator
+ private weak var panel: NSPanel?
+ private var visibilityGeneration = 0
+ private var isExitAnimationRunning = false
+ private var currentSide = UsageHeatmapDetailSide.right
+ private weak var parentWindow: NSWindow?
+
+ init(
+ animationKey: String,
+ makesKey: Bool = false,
+ contentViewProvider: @escaping @MainActor () -> NSView?
+ ) {
+ self.makesKey = makesKey
+ drawerAnimator = SidePanelDrawerAnimator(
+ contentViewProvider: contentViewProvider,
+ animationKey: animationKey,
+ overscan: SidePanelSupport.Metrics.drawerOverscan
+ )
+ }
+
+ var isVisible: Bool {
+ panel?.isVisible == true
+ }
+
+ /// 内容更新由调用方在 present 之前完成
+ func present(_ panel: NSPanel, at position: SidePanelPosition, relativeTo parentWindow: NSWindow) {
+ self.panel = panel
+ visibilityGeneration += 1
+ isExitAnimationRunning = false
+ panel.setFrame(position.frame, display: true)
+ panel.alphaValue = 1
+ currentSide = position.side
+
+ let generation = visibilityGeneration
+ let hidden = drawerAnimator.hiddenTranslation(for: currentSide, panelWidth: panel.frame.width)
+ drawerAnimator.setTranslation(hidden)
+ panel.alphaValue = 0
+ self.parentWindow = parentWindow
+ SidePanelSupport.attach(panel, to: parentWindow)
+ panel.order(.above, relativeTo: parentWindow.windowNumber)
+ if makesKey {
+ panel.makeKey()
+ }
+ drawerAnimator.animateEntryAfterInitialLayout(
+ from: hidden,
+ panel: panel,
+ duration: SidePanelSupport.Metrics.drawerEnterDuration,
+ isCurrent: { [weak self] in
+ self?.visibilityGeneration == generation
+ },
+ completion: { [weak self] in
+ self?.drawerAnimator.setTranslation(0)
+ }
+ )
+ }
+
+ func hide(immediate: Bool = false) {
+ guard let panel, panel.isVisible else {
+ return
+ }
+
+ if immediate {
+ visibilityGeneration += 1
+ drawerAnimator.resetVisualState(for: panel)
+ isExitAnimationRunning = false
+ orderOut(panel)
+ return
+ }
+
+ guard !isExitAnimationRunning else {
+ return
+ }
+
+ visibilityGeneration += 1
+ let generation = visibilityGeneration
+ let side = currentSide
+ isExitAnimationRunning = true
+ let hidden = drawerAnimator.hiddenTranslation(for: side, panelWidth: panel.frame.width)
+ drawerAnimator.animateTranslation(
+ to: hidden,
+ duration: SidePanelSupport.Metrics.drawerExitDuration,
+ timing: .easeIn
+ ) {
+ Task { @MainActor [weak self] in
+ guard let self,
+ generation == visibilityGeneration else {
+ return
+ }
+
+ orderOut(panel)
+ drawerAnimator.setTranslation(0)
+ isExitAnimationRunning = false
+ }
+ }
+ }
+
+ private func orderOut(_ panel: NSPanel) {
+ SidePanelSupport.orderOut(panel, menuSurfaceWindow: parentWindow)
+ }
+}
+
@MainActor
enum SidePanelSupport {
- /// 两个侧边详情面板共用的几何与抽屉动画常量
+ /// 侧边面板共用的几何与抽屉动画常量
enum Metrics {
static let panelGap: CGFloat = 4
static let screenPadding: CGFloat = 8
static let drawerEnterDuration: TimeInterval = 0.18
static let drawerExitDuration: TimeInterval = 0.12
static let drawerOverscan: CGFloat = 1
+ static let anchorValidationTolerance: CGFloat = 6
}
- static func makePanel(initialSize: CGSize, ignoresMouseEvents: Bool) -> NSPanel {
- let panel = NonactivatingSidePanel(
- contentRect: NSRect(origin: .zero, size: initialSize),
- styleMask: [.borderless, .nonactivatingPanel],
- backing: .buffered,
- defer: false
- )
+ /// keyable 决定面板能否成为 key window: 交互面板需要焦点, 详情面板保持 nonactivating
+ static func makePanel(
+ initialSize: CGSize,
+ ignoresMouseEvents: Bool,
+ keyable: Bool = false
+ ) -> NSPanel {
+ let contentRect = NSRect(origin: .zero, size: initialSize)
+ let panel: NSPanel = keyable
+ ? KeyableBorderlessPanel(
+ contentRect: contentRect,
+ styleMask: [.borderless],
+ backing: .buffered,
+ defer: false
+ )
+ : NonactivatingSidePanel(
+ contentRect: contentRect,
+ styleMask: [.borderless, .nonactivatingPanel],
+ backing: .buffered,
+ defer: false
+ )
panel.backgroundColor = .clear
panel.collectionBehavior = [.transient, .canJoinAllSpaces, .fullScreenAuxiliary]
panel.hasShadow = true
@@ -247,6 +380,42 @@ enum SidePanelSupport {
}
}
+ /// 面板顶边对齐锚点行顶边, 锚点无效时回退宿主内容区垂直居中
+ static func alignedProposedY(
+ panelSize: CGSize,
+ menuSurfaceFrame: CGRect,
+ alignmentScreenFrame: CGRect?
+ ) -> CGFloat {
+ guard let alignmentScreenFrame else {
+ return menuSurfaceFrame.midY - panelSize.height / 2
+ }
+
+ return alignmentScreenFrame.maxY - panelSize.height
+ }
+
+ /// 锚点必须落在宿主内容区容差范围内才可信, 否则丢弃并走回退定位
+ static func validatedAlignmentScreenFrame(
+ _ alignmentScreenFrame: CGRect?,
+ menuSurfaceFrame: CGRect
+ ) -> CGRect? {
+ guard let alignmentScreenFrame = alignmentScreenFrame?.standardized,
+ alignmentScreenFrame.isValidScreenRect else {
+ return nil
+ }
+
+ let validationFrame = menuSurfaceFrame
+ .standardized
+ .insetBy(
+ dx: -Metrics.anchorValidationTolerance,
+ dy: -Metrics.anchorValidationTolerance
+ )
+ guard validationFrame.intersects(alignmentScreenFrame) else {
+ return nil
+ }
+
+ return alignmentScreenFrame
+ }
+
static func contentScreenFrame(for contentView: NSView?, in window: NSWindow) -> CGRect? {
guard let contentView else {
return nil
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index 9f3664c..00f98de 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -12,9 +12,11 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
let syncSettings = WorkflowSyncSettings()
let globalHotKeySettings = GlobalHotKeySettings()
let menuBarQuotaSettings = MenuBarQuotaSettings()
+ let notificationSettings = NotificationSettings()
let appUpdater = AppUpdater()
private var statusItemController: StatusItemController?
+ private var notificationService: CodexNotificationService?
func applicationDidFinishLaunching(_: Notification) {
let controller = StatusItemController(
@@ -24,10 +26,21 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
syncSettings: syncSettings,
globalHotKeySettings: globalHotKeySettings,
menuBarQuotaSettings: menuBarQuotaSettings,
+ notificationSettings: notificationSettings,
appUpdater: appUpdater
)
controller.install()
statusItemController = controller
+
+ let notificationService = CodexNotificationService(
+ settings: notificationSettings,
+ statusViewModel: viewModel,
+ codexHookSettings: codexHookSettings
+ ) { [weak controller] in
+ controller?.openMenuSurfaceFromNotification()
+ }
+ notificationService.start()
+ self.notificationService = notificationService
}
func applicationWillTerminate(_: Notification) {
@@ -48,6 +61,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {
private let syncSettings: WorkflowSyncSettings
private let globalHotKeySettings: GlobalHotKeySettings
private let menuBarQuotaSettings: MenuBarQuotaSettings
+ private let notificationSettings: NotificationSettings
private let appUpdater: AppUpdater
private let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
private let popover = NSPopover()
@@ -69,7 +83,8 @@ private final class StatusItemController: NSObject, NSMenuDelegate {
codexHookSettings: codexHookSettings,
syncSettings: syncSettings,
globalHotKeySettings: globalHotKeySettings,
- menuBarQuotaSettings: menuBarQuotaSettings
+ menuBarQuotaSettings: menuBarQuotaSettings,
+ notificationSettings: notificationSettings
) { [weak self] in
self?.statusItem.button?.window?.screen
} onSyncChanged: { [weak self] enabled in
@@ -126,6 +141,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {
syncSettings: WorkflowSyncSettings,
globalHotKeySettings: GlobalHotKeySettings,
menuBarQuotaSettings: MenuBarQuotaSettings,
+ notificationSettings: NotificationSettings,
appUpdater: AppUpdater
) {
self.viewModel = viewModel
@@ -134,6 +150,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {
self.syncSettings = syncSettings
self.globalHotKeySettings = globalHotKeySettings
self.menuBarQuotaSettings = menuBarQuotaSettings
+ self.notificationSettings = notificationSettings
self.appUpdater = appUpdater
super.init()
}
@@ -324,6 +341,15 @@ private final class StatusItemController: NSObject, NSMenuDelegate {
openSettings()
}
+ /// 通知点击回调: 面板未展示时按快捷键路径打开(含 fallback 面板兜底)
+ func openMenuSurfaceFromNotification() {
+ guard menuSurfaceWillOpenOnToggle else {
+ return
+ }
+
+ toggleMenuSurfaceFromHotKey()
+ }
+
private func configureStatusButton() {
guard let button = statusItem.button else {
return
@@ -587,9 +613,14 @@ private final class StatusItemController: NSObject, NSMenuDelegate {
}
}
+ /// toggle 将走「打开」分支的状态谓词, 与 toggleMenuSurface 的分支口径一致
+ private var menuSurfaceWillOpenOnToggle: Bool {
+ menuSurfaceState == .hidden || menuSurfaceState == .closing
+ }
+
private func toggleMenuSurfaceFromHotKey() {
let targetScreen = NSScreen.containingMouse() ?? NSScreen.main
- let opensMenuSurface = menuSurfaceState == .hidden || menuSurfaceState == .closing
+ let opensMenuSurface = menuSurfaceWillOpenOnToggle
if opensMenuSurface {
suspendAuxiliaryWindowKeyFocus()
}
diff --git a/CodexBar/Models/CodexWorkflowModels.swift b/CodexBar/Models/CodexWorkflowModels.swift
index c23efd1..3f8325f 100644
--- a/CodexBar/Models/CodexWorkflowModels.swift
+++ b/CodexBar/Models/CodexWorkflowModels.swift
@@ -154,11 +154,21 @@ nonisolated struct WorkflowDailyMetrics: Equatable, Identifiable {
let permissionRequestCount: Int
let contextCompactionCount: Int
let subagentCount: Int
+ let modelCounts: [String: Int]
var id: String {
startDate
}
+ var mostUsedModel: String? {
+ modelCounts
+ .filter { $0.value > 0 }
+ .sorted { lhs, rhs in
+ lhs.value == rhs.value ? lhs.key < rhs.key : lhs.value > rhs.value
+ }
+ .first?.key
+ }
+
init(
startDate: String,
sessionCount: Int,
@@ -166,7 +176,8 @@ nonisolated struct WorkflowDailyMetrics: Equatable, Identifiable {
toolCallCount: Int,
permissionRequestCount: Int,
contextCompactionCount: Int,
- subagentCount: Int
+ subagentCount: Int,
+ modelCounts: [String: Int] = [:]
) {
self.startDate = startDate
self.sessionCount = sessionCount
@@ -175,6 +186,7 @@ nonisolated struct WorkflowDailyMetrics: Equatable, Identifiable {
self.permissionRequestCount = permissionRequestCount
self.contextCompactionCount = contextCompactionCount
self.subagentCount = subagentCount
+ self.modelCounts = modelCounts
}
static func empty(startDate: String) -> WorkflowDailyMetrics {
@@ -199,7 +211,8 @@ nonisolated struct WorkflowDailyMetrics: Equatable, Identifiable {
preCompactCount: Int,
postCompactCount: Int,
subagentStartCount: Int,
- subagentStopCount: Int
+ subagentStopCount: Int,
+ modelCounts: [String: Int]
) {
self.startDate = startDate
self.sessionCount = sessionCount
@@ -208,6 +221,7 @@ nonisolated struct WorkflowDailyMetrics: Equatable, Identifiable {
self.permissionRequestCount = permissionRequestCount
contextCompactionCount = max(preCompactCount, postCompactCount)
subagentCount = max(subagentStartCount, subagentStopCount)
+ self.modelCounts = modelCounts
}
func adding(_ other: WorkflowDailyMetrics) -> WorkflowDailyMetrics {
@@ -218,9 +232,19 @@ nonisolated struct WorkflowDailyMetrics: Equatable, Identifiable {
toolCallCount: toolCallCount + other.toolCallCount,
permissionRequestCount: permissionRequestCount + other.permissionRequestCount,
contextCompactionCount: contextCompactionCount + other.contextCompactionCount,
- subagentCount: subagentCount + other.subagentCount
+ subagentCount: subagentCount + other.subagentCount,
+ modelCounts: Self.mergedCounts(modelCounts, other.modelCounts)
)
}
+
+ private static func mergedCounts(
+ _ lhs: [String: Int],
+ _ rhs: [String: Int]
+ ) -> [String: Int] {
+ rhs.reduce(into: lhs) { result, item in
+ result[item.key, default: 0] += item.value
+ }
+ }
}
/// WorkflowService 发布给 UI 的近端快照
@@ -308,6 +332,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
var sessionCount: Int?
var turnCount: Int?
var projectCounts: [String: Int]
+ var modelCounts: [String: Int]
var sessionIds: [String]?
var turnIds: [String]?
@@ -330,6 +355,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
sessionCount = nil
turnCount = nil
projectCounts = [:]
+ modelCounts = [:]
sessionIds = []
turnIds = []
}
@@ -350,6 +376,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
sessionCount = try container.decodeIfPresent(Int.self, forKey: .sessionCount)
turnCount = try container.decodeIfPresent(Int.self, forKey: .turnCount)
projectCounts = try container.decodeIfPresent([String: Int].self, forKey: .projectCounts) ?? [:]
+ modelCounts = try container.decodeIfPresent([String: Int].self, forKey: .modelCounts) ?? [:]
sessionIds = try container.decodeIfPresent([String].self, forKey: .sessionIds)
turnIds = try container.decodeIfPresent([String].self, forKey: .turnIds)
}
@@ -389,6 +416,10 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
if let projectDisplayName = event.projectDisplayName {
projectCounts[projectDisplayName, default: 0] += 1
}
+
+ if let modelName = event.modelName {
+ modelCounts[modelName, default: 0] += 1
+ }
}
mutating func compactIdentifiersIfNeeded(keepsIdentifiers: Bool) {
@@ -425,7 +456,8 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
preCompactCount: preCompactCount,
postCompactCount: postCompactCount,
subagentStartCount: subagentStartCount,
- subagentStopCount: subagentStopCount
+ subagentStopCount: subagentStopCount,
+ modelCounts: modelCounts
)
}
@@ -475,6 +507,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
WorkflowJSON.field("sessionCount", sessionCount),
WorkflowJSON.field("turnCount", turnCount),
WorkflowJSON.field("projectCounts", projectCounts),
+ WorkflowJSON.field("modelCounts", modelCounts),
WorkflowJSON.field("sessionIds", sessionIds),
WorkflowJSON.field("turnIds", turnIds)
]
@@ -497,7 +530,8 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
subagentStopCount: subagentStopCount,
sessionCount: syncedSessionCount,
turnCount: syncedTurnCount,
- projectCounts: projectCounts
+ projectCounts: projectCounts,
+ modelCounts: modelCounts
)
}
@@ -555,6 +589,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
case sessionCount
case turnCount
case projectCounts
+ case modelCounts
case sessionIds
case turnIds
}
@@ -576,6 +611,7 @@ nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable, Identifiabl
var sessionCount: Int?
var turnCount: Int?
var projectCounts: [String: Int]
+ var modelCounts: [String: Int]?
var id: String {
date
@@ -592,7 +628,8 @@ nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable, Identifiabl
preCompactCount: preCompactCount,
postCompactCount: postCompactCount,
subagentStartCount: subagentStartCount,
- subagentStopCount: subagentStopCount
+ subagentStopCount: subagentStopCount,
+ modelCounts: modelCounts ?? [:]
)
}
@@ -611,7 +648,8 @@ nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable, Identifiabl
WorkflowJSON.field("subagentStopCount", subagentStopCount),
WorkflowJSON.field("sessionCount", sessionCount),
WorkflowJSON.field("turnCount", turnCount),
- WorkflowJSON.field("projectCounts", projectCounts)
+ WorkflowJSON.field("projectCounts", projectCounts),
+ WorkflowJSON.field("modelCounts", modelCounts)
]
return WorkflowJSON.lineData(fields)
diff --git a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
index 00b83e5..20a4150 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
@@ -57,7 +57,10 @@ nonisolated struct CodexCLIInstallations: Equatable {
/// 解析真实用户环境下的 Codex 可执行文件, 避免使用 Xcode/container 的 HOME
nonisolated enum CodexCLIResolver {
- static let bundledExecutablePath = "/Applications/Codex.app/Contents/Resources/codex"
+ static let bundledExecutablePaths = [
+ "/Applications/ChatGPT.app/Contents/Resources/codex",
+ "/Applications/Codex.app/Contents/Resources/codex"
+ ]
static let environment = appServerEnvironment()
static func resolveAppServerCommand(environment: [String: String] = environment) throws -> AppServerCommand {
@@ -96,13 +99,13 @@ nonisolated enum CodexCLIResolver {
static func resolveInstallations(environment: [String: String] = environment) -> CodexCLIInstallations {
let cliPath = findExecutable(named: "codex", environment: environment)
- let cliIsBundled = cliPath.map { pathsAreEquivalent($0, bundledExecutablePath) } ?? false
+ let cliIsBundled = cliPath.map { path in
+ bundledExecutablePaths.contains { pathsAreEquivalent(path, $0) }
+ } ?? false
- let bundledPath: String? = if FileManager.default.isExecutableFile(atPath: bundledExecutablePath) {
- bundledExecutablePath
- } else {
- cliIsBundled ? cliPath : nil
- }
+ let bundledPath = bundledExecutablePaths.first {
+ FileManager.default.isExecutableFile(atPath: $0)
+ } ?? (cliIsBundled ? cliPath : nil)
return CodexCLIInstallations(
globalPath: cliIsBundled ? nil : cliPath,
diff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swift
new file mode 100644
index 0000000..dd43cc5
--- /dev/null
+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift
@@ -0,0 +1,696 @@
+import AppKit
+import Combine
+import Foundation
+import UserNotifications
+
+/// 集中式通知服务: 订阅额度快照, 负责阈值判定、去重、重置调度与本地通知发送
+/// 任务完成和等待批准通知的 Hook 事件接入见 handleHookEvents
+@MainActor
+final class CodexNotificationService: NSObject {
+ private let settings: NotificationSettings
+ private let statusViewModel: CodexStatusViewModel
+ private let codexHookSettings: CodexHookSettings
+ private let defaults: UserDefaults
+ private nonisolated let openMenuSurface: @MainActor @Sendable () -> Void
+
+ private var cancellables = Set<AnyCancellable>()
+ private let resetReminderScheduler = ReminderCheckScheduler()
+ private let creditExpiryReminderScheduler = ReminderCheckScheduler()
+ private var latestQuotaSnapshot: CodexQuotaSnapshot?
+
+ /// 待发送的重置完成提醒与已发送去重键的内存镜像, 变更时才写回 UserDefaults
+ private var pendingResetReminders: [PendingQuotaResetReminder]
+ private var sentDedupKeys: [String]
+
+ /// 阈值穿越判定的会话内上一帧剩余比例, key 为 account|limitId|windowId
+ private var lastRemainingPercents: [String: Int] = [:]
+
+ private var tailReader: HookEventTailReader?
+
+ /// 起点事件配对表: 优先 session|turn 精确配对, 回退 session 最近一条
+ private var promptTimesByTurn: [String: Date] = [:]
+ private var promptTimesBySession: [String: Date] = [:]
+ private var taskWaitingNotificationTimesByKey: [String: Date] = [:]
+
+ init(
+ settings: NotificationSettings,
+ statusViewModel: CodexStatusViewModel,
+ codexHookSettings: CodexHookSettings,
+ defaults: UserDefaults = .standard,
+ openMenuSurface: @escaping @MainActor @Sendable () -> Void
+ ) {
+ self.settings = settings
+ self.statusViewModel = statusViewModel
+ self.codexHookSettings = codexHookSettings
+ self.defaults = defaults
+ self.openMenuSurface = openMenuSurface
+ pendingResetReminders = Self.loadPendingResetReminders(from: defaults)
+ sentDedupKeys = defaults.stringArray(forKey: Self.sentKeysKey) ?? []
+ super.init()
+ }
+
+ func start() {
+ UNUserNotificationCenter.current().delegate = self
+ settings.refreshAuthorizationStatus()
+
+ statusViewModel.$snapshot
+ .sink { [weak self] snapshot in
+ self?.handleSnapshot(snapshot)
+ }
+ .store(in: &cancellables)
+
+ Publishers.CombineLatest(
+ settings.$isLowQuotaEnabled,
+ settings.$lowQuotaThresholdPercent
+ )
+ .dropFirst()
+ .sink { [weak self] _, _ in
+ self?.reevaluateLowQuotaSettings()
+ }
+ .store(in: &cancellables)
+
+ // 休眠可能错过 resetsAt, 唤醒时补检
+ NSWorkspace.shared.notificationCenter
+ .publisher(for: NSWorkspace.didWakeNotification)
+ .receive(on: DispatchQueue.main)
+ .sink { [weak self] _ in
+ self?.deliverDueResetReminders()
+ self?.deliverDueCreditExpiryReminders()
+ }
+ .store(in: &cancellables)
+
+ // 两类 Hook 通知任一开启, 且总开关、授权和 Hook 状态满足时运行 tail
+ Publishers.CombineLatest(
+ Publishers.CombineLatest4(
+ settings.$isEnabled,
+ settings.$isLongTaskEnabled,
+ settings.$isTaskWaitingEnabled,
+ settings.$authorizationStatus
+ ),
+ codexHookSettings.$isEnabled
+ )
+ .map { notificationState, hook in
+ let (enabled, longTask, taskWaiting, authorizationStatus) = notificationState
+ return enabled
+ && (longTask || taskWaiting)
+ && authorizationStatus != .denied
+ && hook
+ }
+ .removeDuplicates()
+ .sink { [weak self] shouldRun in
+ self?.setTailReaderActive(shouldRun)
+ }
+ .store(in: &cancellables)
+
+ // 等待批准通知仍在运行 tail 时, 关闭任务完成通知也要立即丢弃未完成的计时配对
+ settings.$isLongTaskEnabled
+ .removeDuplicates()
+ .sink { [weak self] enabled in
+ guard !enabled else {
+ return
+ }
+ self?.promptTimesByTurn.removeAll()
+ self?.promptTimesBySession.removeAll()
+ }
+ .store(in: &cancellables)
+ }
+
+ // MARK: - Hook 任务通知
+
+ private func setTailReaderActive(_ active: Bool) {
+ if active {
+ guard tailReader == nil else {
+ return
+ }
+
+ let reader = HookEventTailReader { [weak self] events in
+ self?.handleHookEvents(events)
+ }
+ reader.start()
+ tailReader = reader
+ return
+ }
+
+ tailReader?.stop()
+ tailReader = nil
+ promptTimesByTurn.removeAll()
+ promptTimesBySession.removeAll()
+ taskWaitingNotificationTimesByKey.removeAll()
+ }
+
+ private func handleHookEvents(_ events: [WorkflowHookEvent]) {
+ for event in events {
+ switch event.hookEvent {
+ case .userPromptSubmit:
+ guard settings.isLongTaskEnabled,
+ let sessionId = event.sessionId else {
+ continue
+ }
+ promptTimesBySession[sessionId] = event.timestamp
+ if let turnId = event.turnId {
+ promptTimesByTurn[Self.hookTurnKey(sessionId: sessionId, turnId: turnId)] = event.timestamp
+ }
+ case .stop:
+ guard settings.isLongTaskEnabled,
+ let sessionId = event.sessionId else {
+ continue
+ }
+ notifyLongTaskIfNeeded(stopEvent: event, sessionId: sessionId)
+ case .permissionRequest:
+ notifyTaskWaitingIfNeeded(event)
+ default:
+ continue
+ }
+ }
+
+ pruneHookNotificationState()
+ }
+
+ private func notifyTaskWaitingIfNeeded(_ event: WorkflowHookEvent) {
+ guard settings.isTaskWaitingEnabled else {
+ return
+ }
+
+ let key = Self.taskWaitingNotificationKey(for: event)
+ guard taskWaitingNotificationTimesByKey[key] == nil else {
+ return
+ }
+ taskWaitingNotificationTimesByKey[key] = event.timestamp
+
+ send(.taskWaiting(project: event.projectDisplayName, toolName: event.toolName))
+ }
+
+ private func notifyLongTaskIfNeeded(stopEvent event: WorkflowHookEvent, sessionId: String) {
+ let turnStart = event.turnId.flatMap {
+ promptTimesByTurn.removeValue(
+ forKey: Self.hookTurnKey(sessionId: sessionId, turnId: $0)
+ )
+ }
+ let start = turnStart ?? promptTimesBySession[sessionId]
+
+ // 一条 Stop 只配对一次, 防止后续无提交的 Stop 重复计时
+ promptTimesBySession.removeValue(forKey: sessionId)
+
+ guard let start else {
+ return
+ }
+
+ let duration = event.timestamp.timeIntervalSince(start)
+ guard duration >= TimeInterval(settings.longTaskThresholdSeconds) else {
+ return
+ }
+
+ send(.taskCompleted(project: event.projectDisplayName, duration: duration))
+ }
+
+ private func pruneHookNotificationState() {
+ let cutoff = Date().addingTimeInterval(-Self.promptRetention)
+ promptTimesBySession = promptTimesBySession.filter { $0.value > cutoff }
+ promptTimesByTurn = promptTimesByTurn.filter { $0.value > cutoff }
+ taskWaitingNotificationTimesByKey = taskWaitingNotificationTimesByKey.filter {
+ $0.value > cutoff
+ }
+ }
+
+ // MARK: - 快照处理
+
+ private func handleSnapshot(_ snapshot: CodexQuotaSnapshot?) {
+ guard let snapshot else {
+ latestQuotaSnapshot = nil
+ scheduleNextCreditExpiryCheck(dates: [])
+ return
+ }
+
+ latestQuotaSnapshot = snapshot
+
+ guard settings.canDeliver else {
+ scheduleNextCreditExpiryCheck(dates: [])
+ return
+ }
+
+ // stale 快照是旧缓存, 不参与额度判定, 避免误报
+ if !snapshot.isRateLimitsStale {
+ processQuotaWindows(snapshot)
+ }
+
+ processCreditExpirations(snapshot)
+ deliverDueResetReminders()
+ }
+
+ private func processQuotaWindows(_ snapshot: CodexQuotaSnapshot) {
+ let accountKey = Self.accountKey(for: snapshot)
+ for limit in snapshot.limits {
+ for window in limit.windows where window.hasData {
+ processQuotaWindow(
+ window,
+ limit: limit,
+ accountKey: accountKey
+ )
+ }
+ }
+ }
+
+ private func reevaluateLowQuotaSettings() {
+ guard settings.canDeliver,
+ settings.isLowQuotaEnabled,
+ let snapshot = latestQuotaSnapshot,
+ !snapshot.isRateLimitsStale else {
+ return
+ }
+
+ resetQuotaObservation(for: snapshot)
+ processQuotaWindows(snapshot)
+ }
+
+ private func resetQuotaObservation(for snapshot: CodexQuotaSnapshot) {
+ let accountKey = Self.accountKey(for: snapshot)
+ for limit in snapshot.limits {
+ for window in limit.windows where window.hasData {
+ let stateKey = Self.quotaWindowStateKey(
+ accountKey: accountKey,
+ limitId: limit.limitId,
+ windowId: window.id
+ )
+ lastRemainingPercents.removeValue(forKey: stateKey)
+ }
+ }
+ }
+
+ private func processQuotaWindow(
+ _ window: QuotaWindow,
+ limit: CodexQuotaLimitSnapshot,
+ accountKey: String
+ ) {
+ let stateKey = Self.quotaWindowStateKey(
+ accountKey: accountKey,
+ limitId: limit.limitId,
+ windowId: window.id
+ )
+ let previous = lastRemainingPercents[stateKey]
+ lastRemainingPercents[stateKey] = window.remainingPercent
+
+ guard let resetsAt = window.resetsAt,
+ window.remainingPercent <= settings.lowQuotaThresholdPercent else {
+ return
+ }
+
+ // 记录本周期曾跌破阈值, 供重置完成提醒做门槛; 与低阈值子开关无关
+ rememberPendingResetReminder(
+ accountKey: accountKey,
+ limitId: limit.limitId,
+ window: window,
+ resetsAt: resetsAt
+ )
+
+ guard settings.isLowQuotaEnabled else {
+ return
+ }
+
+ // 穿越判定: 上一帧高于阈值才提醒; 会话内首次观察即低于也视为穿越
+ // (App 可能在跌破后才启动), 持久化去重键保证每周期只发一次
+ if let previous, previous <= settings.lowQuotaThresholdPercent {
+ return
+ }
+
+ let dedupKey = "low|\(accountKey)|\(limit.limitId)|\(window.id)|\(Self.epoch(resetsAt))"
+ guard consumeDedupKey(dedupKey) else {
+ return
+ }
+
+ send(
+ .lowQuota(
+ limitTitle: limit.title,
+ windowLabel: window.label,
+ thresholdPercent: settings.lowQuotaThresholdPercent
+ )
+ )
+ }
+
+ // MARK: - 重置完成提醒
+
+ private func rememberPendingResetReminder(
+ accountKey: String,
+ limitId: String,
+ window: QuotaWindow,
+ resetsAt: Date
+ ) {
+ let reminder = PendingQuotaResetReminder(
+ accountKey: accountKey,
+ limitId: limitId,
+ windowId: window.id,
+ windowLabel: window.label,
+ resetsAt: resetsAt,
+ windowDurationMins: window.windowDurationMins
+ )
+
+ guard !pendingResetReminders.contains(reminder), !hasSent(reminder.dedupKey) else {
+ return
+ }
+
+ pendingResetReminders.append(reminder)
+ persistPendingResetReminders()
+ }
+
+ private func deliverDueResetReminders() {
+ let now = Date()
+ var remaining: [PendingQuotaResetReminder] = []
+
+ for reminder in pendingResetReminders {
+ if reminder.resetsAt > now {
+ remaining.append(reminder)
+ continue
+ }
+
+ // 已到重置时刻: 超时效或已发过的直接丢弃
+ guard now < reminder.validUntil, !hasSent(reminder.dedupKey) else {
+ continue
+ }
+
+ // 开关或授权此刻关闭时保留, 时效内等下一次快照/唤醒重试
+ guard settings.canDeliver,
+ settings.isQuotaResetEnabled,
+ consumeDedupKey(reminder.dedupKey) else {
+ remaining.append(reminder)
+ continue
+ }
+
+ send(.quotaReset(windowLabel: reminder.windowLabel))
+ }
+
+ if remaining != pendingResetReminders {
+ pendingResetReminders = remaining
+ persistPendingResetReminders()
+ }
+ scheduleNextResetCheck()
+ }
+
+ private func scheduleNextResetCheck() {
+ let now = Date()
+ let nextDate = pendingResetReminders.map(\.resetsAt).filter { $0 > now }.min()
+ resetReminderScheduler.schedule(at: nextDate) { [weak self] in
+ self?.deliverDueResetReminders()
+ }
+ }
+
+ // MARK: - 重置次数临期提醒
+
+ private func processCreditExpirations(_ snapshot: CodexQuotaSnapshot) {
+ guard settings.isCreditExpiryEnabled,
+ let dates = snapshot.resetCreditExpirationDates else {
+ scheduleNextCreditExpiryCheck(dates: [])
+ return
+ }
+
+ let accountKey = Self.accountKey(for: snapshot)
+ let now = Date()
+ let dueDates = dates.filter {
+ Self.creditExpiryReminderDay(expirationDate: $0, now: now) != nil
+ }
+
+ // 相同过期时间的机会合并成一条通知; 按秒分组与去重键口径保持一致
+ for (epochSecond, groupedDates) in Dictionary(grouping: dueDates, by: { Self.epoch($0) }) {
+ guard let date = groupedDates.first,
+ let reminderDay = Self.creditExpiryReminderDay(expirationDate: date, now: now) else {
+ continue
+ }
+
+ let dedupKey = "credit|\(accountKey)|\(epochSecond)|\(reminderDay)d"
+ guard consumeDedupKey(dedupKey) else {
+ continue
+ }
+
+ send(.creditExpiry(count: groupedDates.count, expirationDate: date))
+ }
+
+ scheduleNextCreditExpiryCheck(dates: dates)
+ }
+
+ private func deliverDueCreditExpiryReminders() {
+ guard let latestQuotaSnapshot, settings.canDeliver else {
+ scheduleNextCreditExpiryCheck(dates: [])
+ return
+ }
+
+ processCreditExpirations(latestQuotaSnapshot)
+ }
+
+ private func scheduleNextCreditExpiryCheck(dates: [Date]) {
+ let now = Date()
+ let nextDate = dates
+ .flatMap(Self.creditExpiryReminderDates)
+ .filter { $0 > now }
+ .min()
+ creditExpiryReminderScheduler.schedule(at: nextDate) { [weak self] in
+ self?.deliverDueCreditExpiryReminders()
+ }
+ }
+
+ // MARK: - 去重与持久化
+
+ /// 未发过则记录并返回 true; 已发过返回 false
+ private func consumeDedupKey(_ key: String) -> Bool {
+ guard !sentDedupKeys.contains(key) else {
+ return false
+ }
+
+ sentDedupKeys.append(key)
+ if sentDedupKeys.count > Self.sentKeysLimit {
+ sentDedupKeys.removeFirst(sentDedupKeys.count - Self.sentKeysLimit)
+ }
+
+ defaults.set(sentDedupKeys, forKey: Self.sentKeysKey)
+ return true
+ }
+
+ private func hasSent(_ key: String) -> Bool {
+ sentDedupKeys.contains(key)
+ }
+
+ private static func loadPendingResetReminders(from defaults: UserDefaults) -> [PendingQuotaResetReminder] {
+ guard let data = defaults.data(forKey: pendingResetRemindersKey),
+ let reminders = try? JSONDecoder().decode(
+ [PendingQuotaResetReminder].self,
+ from: data
+ ) else {
+ return []
+ }
+
+ return reminders
+ }
+
+ private func persistPendingResetReminders() {
+ guard let data = try? JSONEncoder().encode(pendingResetReminders) else {
+ return
+ }
+
+ defaults.set(data, forKey: Self.pendingResetRemindersKey)
+ }
+
+ // MARK: - 发送与文案
+
+ private func send(_ notification: CodexNotificationContent) {
+ let content = UNMutableNotificationContent()
+ content.title = notification.title
+ content.body = notification.body
+ content.sound = .default
+
+ let request = UNNotificationRequest(
+ identifier: UUID().uuidString,
+ content: content,
+ trigger: nil
+ )
+ UNUserNotificationCenter.current().add(request)
+ }
+
+ private nonisolated static func accountKey(for snapshot: CodexQuotaSnapshot) -> String {
+ snapshot.account.email ?? snapshot.account.type
+ }
+
+ private nonisolated static func epoch(_ date: Date) -> Int {
+ Int(date.timeIntervalSince1970)
+ }
+
+ private nonisolated static func hookTurnKey(sessionId: String, turnId: String) -> String {
+ "\(sessionId)|\(turnId)"
+ }
+
+ private nonisolated static func quotaWindowStateKey(
+ accountKey: String,
+ limitId: String,
+ windowId: String
+ ) -> String {
+ "\(accountKey)|\(limitId)|\(windowId)"
+ }
+
+ private nonisolated static func taskWaitingNotificationKey(for event: WorkflowHookEvent) -> String {
+ let milliseconds = Int64((event.timestamp.timeIntervalSince1970 * 1000).rounded())
+ return [
+ String(milliseconds),
+ event.sessionId ?? "",
+ event.turnId ?? "",
+ event.toolName ?? ""
+ ].joined(separator: "|")
+ }
+
+ private nonisolated static func creditExpiryReminderDates(for expirationDate: Date) -> [Date] {
+ creditExpiryReminderDays.map {
+ expirationDate.addingTimeInterval(-TimeInterval($0) * day)
+ }
+ }
+
+ private nonisolated static func creditExpiryReminderDay(
+ expirationDate: Date,
+ now: Date
+ ) -> Int? {
+ let remaining = expirationDate.timeIntervalSince(now)
+ guard remaining > 0, remaining <= creditExpiryLeadTime else {
+ return nil
+ }
+
+ for reminderDay in creditExpiryReminderDays where remaining > TimeInterval(reminderDay - 1) * day {
+ return reminderDay
+ }
+
+ return 1
+ }
+
+ private nonisolated static let day: TimeInterval = 24 * 3600
+ private nonisolated static let creditExpiryReminderDays = [7, 6, 5, 4, 3, 2, 1]
+ private nonisolated static let creditExpiryLeadTime: TimeInterval = 7 * day
+ private static let promptRetention: TimeInterval = 24 * 3600
+ private static let sentKeysLimit = 300
+ private static let sentKeysKey = "Notification.sentKeys"
+ private static let pendingResetRemindersKey = "Notification.pendingResetReminders"
+}
+
+nonisolated struct CodexNotificationContent: Equatable {
+ let title: String
+ let body: String
+
+ static func lowQuota(
+ limitTitle: String,
+ windowLabel: String,
+ thresholdPercent: Int
+ ) -> CodexNotificationContent {
+ CodexNotificationContent(
+ title: "Codex 额度不足",
+ body: "\(limitTitle) \(windowLabel) 剩余额度已低于 \(thresholdPercent)%"
+ )
+ }
+
+ static func quotaReset(windowLabel: String) -> CodexNotificationContent {
+ CodexNotificationContent(
+ title: "Codex 额度重置",
+ body: "\(windowLabel) 窗口额度已重置"
+ )
+ }
+
+ static func taskCompleted(project: String?, duration: TimeInterval) -> CodexNotificationContent {
+ let projectText = project.map { "「\($0)」" } ?? "Codex"
+ return CodexNotificationContent(
+ title: "Codex 任务完成",
+ body: "\(projectText) 任务完成, 耗时 \(durationText(duration))"
+ )
+ }
+
+ static func taskWaiting(project: String?, toolName: String?) -> CodexNotificationContent {
+ let subject = project.map { "「\($0)」" } ?? "Codex"
+ let action = toolName.map { "\($0) 操作" } ?? "下一步操作"
+ return CodexNotificationContent(
+ title: "Codex 等待批准",
+ body: "\(subject) 正在等待批准 \(action)"
+ )
+ }
+
+ static func creditExpiry(count: Int, expirationDate: Date) -> CodexNotificationContent {
+ CodexNotificationContent(
+ title: "重置次数即将过期",
+ body: "有 \(count) 个重置次数将于 \(CodexDateFormat.localDisplayString(from: expirationDate)) 过期"
+ )
+ }
+
+ private static func durationText(_ interval: TimeInterval) -> String {
+ let totalSeconds = Int(interval.rounded())
+ let minutes = totalSeconds / 60
+ let seconds = totalSeconds % 60
+ if minutes >= 60 {
+ return "\(minutes / 60) 小时 \(minutes % 60) 分"
+ }
+
+ if minutes > 0 {
+ return "\(minutes) 分 \(seconds) 秒"
+ }
+
+ return "\(seconds) 秒"
+ }
+}
+
+// MARK: - UNUserNotificationCenterDelegate
+
+extension CodexNotificationService: UNUserNotificationCenterDelegate {
+ /// 菜单栏常驻应用处于前台时也要展示横幅
+ nonisolated func userNotificationCenter(
+ _: UNUserNotificationCenter,
+ willPresent _: UNNotification
+ ) async -> UNNotificationPresentationOptions {
+ [.banner, .list]
+ }
+
+ nonisolated func userNotificationCenter(
+ _: UNUserNotificationCenter,
+ didReceive _: UNNotificationResponse
+ ) async {
+ await openMenuSurface()
+ }
+}
+
+/// 单一待办时刻的重检调度: 目标时刻未变化时不重建 Task, 避免每个快照 tick 都 cancel/respawn
+@MainActor
+private final class ReminderCheckScheduler {
+ private var task: Task<Void, Never>?
+ private var armedDate: Date?
+
+ /// date 为 nil 时取消当前调度
+ func schedule(at date: Date?, action: @escaping @MainActor () -> Void) {
+ if let date, date == armedDate, task != nil {
+ return
+ }
+
+ task?.cancel()
+ task = nil
+ armedDate = date
+ guard let date else {
+ return
+ }
+
+ task = Task { @MainActor [weak self] in
+ try? await Task.sleep(for: .seconds(date.timeIntervalSinceNow + 1))
+ guard !Task.isCancelled else {
+ return
+ }
+
+ self?.task = nil
+ self?.armedDate = nil
+ action()
+ }
+ }
+}
+
+/// 本周期曾跌破阈值的窗口, 等待 resetsAt 到达后发送恢复提醒
+private nonisolated struct PendingQuotaResetReminder: Codable, Equatable {
+ let accountKey: String
+ let limitId: String
+ let windowId: String
+ let windowLabel: String
+ let resetsAt: Date
+ let windowDurationMins: Int?
+
+ var dedupKey: String {
+ "reset|\(accountKey)|\(limitId)|\(windowId)|\(Int(resetsAt.timeIntervalSince1970))"
+ }
+
+ /// 补发时效: 超过一个窗口周期不再提醒, 周期未知按 24h
+ var validUntil: Date {
+ resetsAt.addingTimeInterval(TimeInterval((windowDurationMins ?? 1440) * 60))
+ }
+}
diff --git a/CodexBar/Services/Notifications/HookEventTailReader.swift b/CodexBar/Services/Notifications/HookEventTailReader.swift
new file mode 100644
index 0000000..524050a
--- /dev/null
+++ b/CodexBar/Services/Notifications/HookEventTailReader.swift
@@ -0,0 +1,100 @@
+import Foundation
+
+/// 只读 tail 读取 HookEvents/events 目录: 轮询当日 JSONL 文件大小,
+/// 增量解码新追加的完整事件行后回调
+/// 仅服务于通知判定, 不参与统计维护; 任何读取失败都静默跳过本轮
+@MainActor
+final class HookEventTailReader {
+ private let onEvents: ([WorkflowHookEvent]) -> Void
+ private var pollTask: Task<Void, Never>?
+ private var activeDateKey = ""
+ private var activeFileOffset: UInt64 = 0
+
+ init(onEvents: @escaping ([WorkflowHookEvent]) -> Void) {
+ self.onEvents = onEvents
+ }
+
+ func start() {
+ guard pollTask == nil else {
+ return
+ }
+
+ // 初始位点取当天文件当前大小: 只处理启动之后写入的事件, 不回放历史
+ activeDateKey = WorkflowStorage.dateKey(for: Date())
+ activeFileOffset = WorkflowStorage.fileSize(at: activeFileURL)
+
+ pollTask = Task { @MainActor [weak self] in
+ while !Task.isCancelled {
+ try? await Task.sleep(for: .seconds(Self.pollInterval))
+ guard let self, !Task.isCancelled else {
+ return
+ }
+
+ drainNewLines()
+ }
+ }
+ }
+
+ func stop() {
+ pollTask?.cancel()
+ pollTask = nil
+ }
+
+ private var activeFileURL: URL {
+ WorkflowStorage.eventLogURL(for: activeDateKey)
+ }
+
+ private func drainNewLines() {
+ let todayKey = WorkflowStorage.dateKey(for: Date())
+ if todayKey != activeDateKey {
+ // 跨零点: 先清掉旧文件尾部, 再从新文件头开始
+ readAppendedLines()
+ activeDateKey = todayKey
+ activeFileOffset = 0
+ }
+
+ readAppendedLines()
+ }
+
+ private func readAppendedLines() {
+ let url = activeFileURL
+ let size = WorkflowStorage.fileSize(at: url)
+ if size < activeFileOffset {
+ // 文件被截断或替换, 从当前头部重新开始
+ activeFileOffset = 0
+ }
+
+ guard size > activeFileOffset,
+ let handle = try? FileHandle(forReadingFrom: url) else {
+ return
+ }
+
+ defer {
+ try? handle.close()
+ }
+
+ guard (try? handle.seek(toOffset: activeFileOffset)) != nil,
+ let data = try? handle.readToEnd(),
+ !data.isEmpty else {
+ return
+ }
+
+ // 只消费到最后一个完整行, 半行留待下一轮
+ guard let lastNewlineIndex = data.lastIndex(of: Self.newlineByte) else {
+ return
+ }
+
+ let completeData = data[...lastNewlineIndex]
+ activeFileOffset += UInt64(completeData.count)
+
+ let events = JSONLines.decode(WorkflowHookEvent.self, from: completeData)
+ guard !events.isEmpty else {
+ return
+ }
+
+ onEvents(events)
+ }
+
+ private static let pollInterval: TimeInterval = 2
+ private static let newlineByte: UInt8 = 0x0A
+}
diff --git a/CodexBar/Services/Settings/NotificationSettings.swift b/CodexBar/Services/Settings/NotificationSettings.swift
new file mode 100644
index 0000000..972c892
--- /dev/null
+++ b/CodexBar/Services/Settings/NotificationSettings.swift
@@ -0,0 +1,198 @@
+import AppKit
+import Combine
+import Foundation
+import UserNotifications
+
+/// 通知偏好: 总开关、五类子开关、两个阈值和系统授权状态镜像
+/// 授权请求/查询集中在这里, 判定与发送在 CodexNotificationService
+@MainActor
+final class NotificationSettings: ObservableObject {
+ @Published private(set) var isEnabled: Bool
+ @Published private(set) var isLowQuotaEnabled: Bool
+ @Published private(set) var isQuotaResetEnabled: Bool
+ @Published private(set) var isLongTaskEnabled: Bool
+ @Published private(set) var isTaskWaitingEnabled: Bool
+ @Published private(set) var isCreditExpiryEnabled: Bool
+ @Published private(set) var lowQuotaThresholdPercent: Int
+ @Published private(set) var longTaskThresholdSeconds: Int
+ @Published private(set) var authorizationStatus: UNAuthorizationStatus = .notDetermined
+
+ /// 系统授权被拒时设置页展示引导, 通知服务停发
+ var isAuthorizationDenied: Bool {
+ authorizationStatus == .denied
+ }
+
+ /// 总开关开启且授权未被拒时才允许发送
+ var canDeliver: Bool {
+ isEnabled && !isAuthorizationDenied
+ }
+
+ /// 子选项面板仅在总开关开启且授权已明确通过时可展示
+ var canShowOptions: Bool {
+ isEnabled && authorizationStatus != .notDetermined && authorizationStatus != .denied
+ }
+
+ static let lowQuotaThresholdOptions = [5, 10, 25]
+ static let longTaskThresholdOptions = [30, 60, 120, 300]
+
+ private let defaults: UserDefaults
+ private var authorizationTask: Task<Void, Never>?
+
+ init(defaults: UserDefaults = .standard) {
+ self.defaults = defaults
+ isEnabled = defaults.bool(forKey: Self.enabledKey)
+ isLowQuotaEnabled = Self.bool(from: defaults, key: Self.lowQuotaEnabledKey, defaultValue: true)
+ isQuotaResetEnabled = Self.bool(from: defaults, key: Self.quotaResetEnabledKey, defaultValue: true)
+ isLongTaskEnabled = Self.bool(from: defaults, key: Self.longTaskEnabledKey, defaultValue: true)
+ isTaskWaitingEnabled = Self.bool(from: defaults, key: Self.taskWaitingEnabledKey, defaultValue: true)
+ isCreditExpiryEnabled = Self.bool(from: defaults, key: Self.creditExpiryEnabledKey, defaultValue: true)
+ lowQuotaThresholdPercent = Self.option(
+ defaults.object(forKey: Self.lowQuotaThresholdKey) as? Int,
+ in: Self.lowQuotaThresholdOptions,
+ defaultValue: 10
+ )
+ longTaskThresholdSeconds = Self.option(
+ defaults.object(forKey: Self.longTaskThresholdKey) as? Int,
+ in: Self.longTaskThresholdOptions,
+ defaultValue: 60
+ )
+ }
+
+ deinit {
+ authorizationTask?.cancel()
+ }
+
+ func setEnabled(_ enabled: Bool) {
+ guard enabled != isEnabled else {
+ return
+ }
+
+ isEnabled = enabled
+ defaults.set(enabled, forKey: Self.enabledKey)
+ if enabled {
+ requestAuthorization()
+ }
+ }
+
+ func setLowQuotaEnabled(_ enabled: Bool) {
+ setBool(enabled, current: &isLowQuotaEnabled, key: Self.lowQuotaEnabledKey)
+ }
+
+ func setQuotaResetEnabled(_ enabled: Bool) {
+ setBool(enabled, current: &isQuotaResetEnabled, key: Self.quotaResetEnabledKey)
+ }
+
+ func setLongTaskEnabled(_ enabled: Bool) {
+ setBool(enabled, current: &isLongTaskEnabled, key: Self.longTaskEnabledKey)
+ }
+
+ func setTaskWaitingEnabled(_ enabled: Bool) {
+ setBool(enabled, current: &isTaskWaitingEnabled, key: Self.taskWaitingEnabledKey)
+ }
+
+ func setCreditExpiryEnabled(_ enabled: Bool) {
+ setBool(enabled, current: &isCreditExpiryEnabled, key: Self.creditExpiryEnabledKey)
+ }
+
+ func setLowQuotaThresholdPercent(_ percent: Int) {
+ guard Self.lowQuotaThresholdOptions.contains(percent),
+ percent != lowQuotaThresholdPercent else {
+ return
+ }
+
+ lowQuotaThresholdPercent = percent
+ defaults.set(percent, forKey: Self.lowQuotaThresholdKey)
+ }
+
+ func setLongTaskThresholdSeconds(_ seconds: Int) {
+ guard Self.longTaskThresholdOptions.contains(seconds),
+ seconds != longTaskThresholdSeconds else {
+ return
+ }
+
+ longTaskThresholdSeconds = seconds
+ defaults.set(seconds, forKey: Self.longTaskThresholdKey)
+ }
+
+ /// 用户可能在系统设置里改过权限, 回到 App 时需要重新读取
+ func refreshAuthorizationStatus() {
+ authorizationTask?.cancel()
+ authorizationTask = Task { @MainActor [weak self] in
+ let status = await UNUserNotificationCenter.current()
+ .notificationSettings().authorizationStatus
+ guard let self, !Task.isCancelled else {
+ return
+ }
+
+ // 开关已开但用户从未回应过系统弹窗 (如开启后立即退出): 补一次请求, 避免静默丢通知
+ if status == .notDetermined, isEnabled {
+ requestAuthorization()
+ return
+ }
+
+ authorizationStatus = status
+ }
+ }
+
+ /// 引导用户到系统设置的 CodexBar 通知面板
+ func openSystemNotificationSettings() {
+ let candidates = [
+ Bundle.main.bundleIdentifier.flatMap {
+ URL(string: "x-apple.systempreferences:com.apple.Notifications-Settings.extension?id=\($0)")
+ },
+ URL(string: "x-apple.systempreferences:com.apple.Notifications-Settings.extension")
+ ]
+ for url in candidates.compactMap(\.self) where NSWorkspace.shared.open(url) {
+ return
+ }
+ }
+
+ private func requestAuthorization() {
+ authorizationTask?.cancel()
+ authorizationTask = Task { @MainActor [weak self] in
+ _ = try? await UNUserNotificationCenter.current()
+ .requestAuthorization(options: [.alert, .sound])
+ let status = await UNUserNotificationCenter.current()
+ .notificationSettings().authorizationStatus
+ guard let self, !Task.isCancelled else {
+ return
+ }
+
+ authorizationStatus = status
+ }
+ }
+
+ private func setBool(_ value: Bool, current: inout Bool, key: String) {
+ guard value != current else {
+ return
+ }
+
+ current = value
+ defaults.set(value, forKey: key)
+ }
+
+ private static func bool(from defaults: UserDefaults, key: String, defaultValue: Bool) -> Bool {
+ guard defaults.object(forKey: key) != nil else {
+ return defaultValue
+ }
+
+ return defaults.bool(forKey: key)
+ }
+
+ private static func option(_ value: Int?, in options: [Int], defaultValue: Int) -> Int {
+ guard let value, options.contains(value) else {
+ return defaultValue
+ }
+
+ return value
+ }
+
+ private static let enabledKey = "Notification.enabled"
+ private static let lowQuotaEnabledKey = "Notification.lowQuotaEnabled"
+ private static let quotaResetEnabledKey = "Notification.quotaResetEnabled"
+ private static let longTaskEnabledKey = "Notification.longTaskEnabled"
+ private static let taskWaitingEnabledKey = "Notification.taskWaitingEnabled"
+ private static let creditExpiryEnabledKey = "Notification.creditExpiryEnabled"
+ private static let lowQuotaThresholdKey = "Notification.lowQuotaThresholdPercent"
+ private static let longTaskThresholdKey = "Notification.longTaskThresholdSeconds"
+}
diff --git a/CodexBar/Services/Workflow/WorkflowService.swift b/CodexBar/Services/Workflow/WorkflowService.swift
index 27551dc..5f6d402 100644
--- a/CodexBar/Services/Workflow/WorkflowService.swift
+++ b/CodexBar/Services/Workflow/WorkflowService.swift
@@ -691,7 +691,7 @@ nonisolated struct WorkflowDayMaintenanceState: Codable, Equatable {
/// maintenance.json 的全局状态, pending 表示可增量, dirty 表示需全量重建
nonisolated struct WorkflowMaintenanceState: Codable, Equatable {
- static let currentSchema = 2
+ static let currentSchema = 3
var schema: Int
var pending: [String]
diff --git a/CodexBar/Services/Workflow/WorkflowSyncService.swift b/CodexBar/Services/Workflow/WorkflowSyncService.swift
index ee526d0..7cf1117 100644
--- a/CodexBar/Services/Workflow/WorkflowSyncService.swift
+++ b/CodexBar/Services/Workflow/WorkflowSyncService.swift
@@ -133,7 +133,7 @@ private extension WorkflowSyncService {
typealias UploadedHash = (date: String, hash: String)
enum Metrics {
- static let syncSchemaVersion = 1
+ static let syncSchemaVersion = 2
static let syncZoneName = "CodexBarZone"
static let saltByteCount = 32
static let recordFetchLimit = 200
@@ -165,6 +165,7 @@ private extension WorkflowSyncService {
static let sessionCount = "sessionCount"
static let turnCount = "turnCount"
static let projectCounts = "projectCounts"
+ static let modelCounts = "modelCounts"
static let updatedAt = "updatedAt"
}
@@ -617,7 +618,8 @@ private extension WorkflowSyncService {
record[FieldKeys.subagentStopCount] = aggregate.subagentStopCount as CKRecordValue
record[FieldKeys.sessionCount] = aggregate.sessionCount as CKRecordValue?
record[FieldKeys.turnCount] = aggregate.turnCount as CKRecordValue?
- record[FieldKeys.projectCounts] = Self.projectCountsData(aggregate.projectCounts) as CKRecordValue
+ record[FieldKeys.projectCounts] = Self.countsData(aggregate.projectCounts) as CKRecordValue
+ record[FieldKeys.modelCounts] = Self.countsData(aggregate.modelCounts ?? [:]) as CKRecordValue
record[FieldKeys.updatedAt] = Date() as CKRecordValue
}
@@ -784,7 +786,8 @@ private extension WorkflowSyncService {
subagentStopCount: intValue(record[FieldKeys.subagentStopCount]),
sessionCount: optionalIntValue(record[FieldKeys.sessionCount]),
turnCount: optionalIntValue(record[FieldKeys.turnCount]),
- projectCounts: projectCounts(from: record[FieldKeys.projectCounts])
+ projectCounts: counts(from: record[FieldKeys.projectCounts]),
+ modelCounts: counts(from: record[FieldKeys.modelCounts])
)
return WorkflowSyncedDailyRecord(
@@ -853,7 +856,7 @@ private extension WorkflowSyncService {
return nil
}
- static func projectCounts(from value: CKRecordValue?) -> [String: Int] {
+ static func counts(from value: CKRecordValue?) -> [String: Int] {
guard let data = value as? Data,
let counts = try? JSONDecoder().decode([String: Int].self, from: data) else {
return [:]
@@ -861,7 +864,7 @@ private extension WorkflowSyncService {
return counts
}
- static func projectCountsData(_ counts: [String: Int]) -> Data {
+ static func countsData(_ counts: [String: Int]) -> Data {
(try? JSONLines.stableEncoder.encode(counts)) ?? Data("{}".utf8)
}
@@ -912,7 +915,7 @@ nonisolated struct WorkflowSyncSnapshot: Equatable {
}
private nonisolated struct WorkflowSyncState: Codable, Equatable {
- static let currentSchema = 1
+ static let currentSchema = 2
var schema: Int
var deviceId: String?
diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swift
index d7bb355..553a330 100644
--- a/CodexBar/Views/Menu/UsageHeatmap.swift
+++ b/CodexBar/Views/Menu/UsageHeatmap.swift
@@ -538,6 +538,7 @@ struct UsageHeatmapDayDetailView: View {
VStack(alignment: .leading, spacing: Metrics.metricSpacing) {
tokenIntensityMetricRow
+ mostUsedModelMetricRow
ForEach(workflowMetricRows) { row in
metricRow(row)
@@ -583,6 +584,17 @@ struct UsageHeatmapDayDetailView: View {
}
}
+ private var mostUsedModelMetricRow: some View {
+ metricRowLayout {
+ metricDot(tint: .cyan)
+ Text("最热模型")
+ .foregroundStyle(.secondary)
+ .frame(width: Metrics.metricLabelWidth, alignment: .leading)
+
+ fittingModelValue(context.day.workflow.mostUsedModel ?? "--")
+ }
+ }
+
private var tokenIntensityDot: some View {
metricDot(tint: .blue, darkOpacity: 0.88, lightOpacity: 0.76)
}
@@ -687,6 +699,19 @@ struct UsageHeatmapDayDetailView: View {
}
private func fittingMetricValue(_ value: String, comparison: Double) -> some View {
+ fittingValueContent(value)
+ .numericRollTransition(value: comparison)
+ .layoutPriority(1)
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ }
+
+ private func fittingModelValue(_ value: String) -> some View {
+ fittingValueContent(value)
+ .layoutPriority(1)
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ }
+
+ private func fittingValueContent(_ value: String) -> some View {
ViewThatFits(in: .horizontal) {
metricValueText(value)
.fixedSize(horizontal: true, vertical: false)
@@ -695,9 +720,6 @@ struct UsageHeatmapDayDetailView: View {
.minimumScaleFactor(Metrics.metricValueMinimumScale)
.allowsTightening(true)
}
- .numericRollTransition(value: comparison)
- .layoutPriority(1)
- .frame(maxWidth: .infinity, alignment: .trailing)
}
private func metricValueText(_ value: String) -> some View {
@@ -720,7 +742,7 @@ struct UsageHeatmapDayDetailView: View {
private enum Metrics {
static let workflowPanelWidth: CGFloat = 212
- static let workflowPanelHeight: CGFloat = 189
+ static let workflowPanelHeight: CGFloat = 208
static let tokenPanelWidth: CGFloat = 212
static let tokenPanelHeight: CGFloat = 84
static let sectionSpacing: CGFloat = 8
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index 7567fd0..3bf197e 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -11,7 +11,11 @@ struct AppSettingsView: View {
@ObservedObject var syncSettings: WorkflowSyncSettings
@ObservedObject var globalHotKeySettings: GlobalHotKeySettings
@ObservedObject var menuBarQuotaSettings: MenuBarQuotaSettings
+ @ObservedObject var notificationSettings: NotificationSettings
let onSyncChanged: (Bool) -> Void
+ let onNotificationOptionsAction: (NotificationOptionsPanelAction) -> Void
+ @State private var notificationRowFrame: CGRect?
+ @State private var shouldOpenNotificationOptionsAfterAuthorization = false
var body: some View {
VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {
@@ -26,6 +30,8 @@ struct AppSettingsView: View {
LiquidGlassDivider()
syncRow
LiquidGlassDivider()
+ notificationRow
+ LiquidGlassDivider()
hotKeyRow
LiquidGlassDivider()
codexVersionSection
@@ -62,6 +68,7 @@ struct AppSettingsView: View {
menuBarQuotaSettings.refresh()
appUpdater.refreshAutomaticCheckSetting()
refreshCodexVersionSection()
+ notificationSettings.refreshAuthorizationStatus()
}
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
codexHookSettings.refresh()
@@ -69,6 +76,7 @@ struct AppSettingsView: View {
menuBarQuotaSettings.refresh()
codexHookSettings.verifyInstalledHooks()
refreshCodexVersionSection()
+ notificationSettings.refreshAuthorizationStatus()
}
}
}
@@ -83,6 +91,7 @@ private extension AppSettingsView {
static let surfaceCornerRadius: CGFloat = 16
static let panelCornerRadius: CGFloat = 10
static let iconWidth: CGFloat = 18
+ static let notificationOptionsButtonSize: CGFloat = 22
static let menuBarQuotaPickerWidth: CGFloat = 72
static let statusAnimation = Animation.codexStatus
}
@@ -261,6 +270,103 @@ private extension AppSettingsView {
)
}
+ /// 主开关行保留在设置窗口内, 子选项在右侧子面板中展开
+ var notificationRow: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(spacing: 10) {
+ Image(systemName: "bell.badge")
+ .frame(width: Metrics.iconWidth)
+ .foregroundStyle(.tint)
+
+ Text("系统通知")
+
+ Spacer()
+
+ Button {
+ onNotificationOptionsAction(.toggle(alignmentScreenFrame: notificationRowFrame))
+ } label: {
+ Image(systemName: "slider.horizontal.3")
+ }
+ .buttonStyle(.plain)
+ .controlSize(.small)
+ .foregroundStyle(.tint)
+ .frame(
+ width: Metrics.notificationOptionsButtonSize,
+ height: Metrics.notificationOptionsButtonSize
+ )
+ .opacity(notificationSettings.canShowOptions ? 1 : 0)
+ .disabled(!notificationSettings.canShowOptions)
+ .accessibilityHidden(!notificationSettings.canShowOptions)
+ .help("通知选项")
+ .animation(Metrics.statusAnimation, value: notificationSettings.canShowOptions)
+
+ Toggle(
+ "系统通知",
+ isOn: Binding(
+ get: { notificationSettings.isEnabled },
+ set: { setNotificationsEnabled($0) }
+ )
+ )
+ .labelsHidden()
+ .toggleStyle(.switch)
+ .controlSize(.small)
+ }
+ .background(
+ ScreenFrameReader { frame in
+ notificationRowFrame = frame
+ }
+ )
+
+ if notificationSettings.isEnabled, notificationSettings.isAuthorizationDenied {
+ notificationDeniedRows
+ .transition(.identity)
+ .transaction { transaction in
+ transaction.animation = nil
+ }
+ }
+ }
+ .onChange(of: notificationSettings.canShowOptions) { _, canShowOptions in
+ guard canShowOptions else {
+ onNotificationOptionsAction(.close)
+ return
+ }
+
+ if shouldOpenNotificationOptionsAfterAuthorization {
+ shouldOpenNotificationOptionsAfterAuthorization = false
+ onNotificationOptionsAction(.open(alignmentScreenFrame: notificationRowFrame))
+ }
+ }
+ .onChange(of: notificationSettings.isAuthorizationDenied) { _, isDenied in
+ if isDenied {
+ shouldOpenNotificationOptionsAfterAuthorization = false
+ onNotificationOptionsAction(.close)
+ }
+ }
+ }
+
+ func setNotificationsEnabled(_ enabled: Bool) {
+ notificationSettings.setEnabled(enabled)
+ if enabled, notificationSettings.canShowOptions {
+ shouldOpenNotificationOptionsAfterAuthorization = false
+ onNotificationOptionsAction(.open(alignmentScreenFrame: notificationRowFrame))
+ } else {
+ shouldOpenNotificationOptionsAfterAuthorization = enabled
+ && !notificationSettings.isAuthorizationDenied
+ onNotificationOptionsAction(.close)
+ }
+ }
+
+ @ViewBuilder
+ var notificationDeniedRows: some View {
+ SettingsCaptionMessageRow(message: "系统通知权限未开启, 请在系统设置中允许 CodexBar 发送通知")
+ SettingsIndentedRow {
+ Button("打开系统设置") {
+ notificationSettings.openSystemNotificationSettings()
+ }
+ .controlSize(.small)
+ }
+ }
+
var versionRow: some View {
let status = versionStatus
diff --git a/CodexBar/Views/Settings/NotificationOptionsView.swift b/CodexBar/Views/Settings/NotificationOptionsView.swift
new file mode 100644
index 0000000..96d1e21
--- /dev/null
+++ b/CodexBar/Views/Settings/NotificationOptionsView.swift
@@ -0,0 +1,187 @@
+import SwiftUI
+
+/// 通知子选项面板, 挂在设置窗口「系统通知」行右侧展开
+/// 面板尺寸在 Hook 开/关两种状态下保持不变: 行高固定, Picker 行内显隐不改行高
+struct NotificationOptionsView: View {
+ @ObservedObject var notificationSettings: NotificationSettings
+ @ObservedObject var codexHookSettings: CodexHookSettings
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: Metrics.rowSpacing) {
+ lowQuotaRow
+ quotaResetRow
+ longTaskRow
+ taskWaitingRow
+ creditExpiryRow
+ }
+ .padding(.horizontal, Metrics.horizontalPadding)
+ .padding(.vertical, Metrics.verticalPadding)
+ .frame(width: Metrics.panelWidth, alignment: .topLeading)
+ .sidePanelChrome(cornerRadius: Metrics.cornerRadius)
+ }
+
+ static var panelCornerRadius: CGFloat {
+ Metrics.cornerRadius
+ }
+
+ static var initialPanelSize: CGSize {
+ CGSize(
+ width: Metrics.panelWidth,
+ height: Metrics.verticalPadding * 2
+ + Metrics.rowHeight * 5
+ + Metrics.rowSpacing * 4
+ )
+ }
+
+ private var lowQuotaRow: some View {
+ optionRow(
+ title: "额度预警通知",
+ isOn: Binding(
+ get: { notificationSettings.isLowQuotaEnabled },
+ set: { notificationSettings.setLowQuotaEnabled($0) }
+ )
+ ) {
+ if notificationSettings.isLowQuotaEnabled {
+ optionPicker(
+ title: "低额度阈值",
+ selection: Binding(
+ get: { notificationSettings.lowQuotaThresholdPercent },
+ set: { notificationSettings.setLowQuotaThresholdPercent($0) }
+ ),
+ options: NotificationSettings.lowQuotaThresholdOptions,
+ label: { "\($0)%" }
+ )
+ .transition(.opacity.combined(with: .move(edge: .trailing)))
+ }
+ }
+ .animation(Metrics.statusAnimation, value: notificationSettings.isLowQuotaEnabled)
+ }
+
+ private var quotaResetRow: some View {
+ optionRow(
+ title: "额度重置通知",
+ isOn: Binding(
+ get: { notificationSettings.isQuotaResetEnabled },
+ set: { notificationSettings.setQuotaResetEnabled($0) }
+ )
+ )
+ }
+
+ /// Hook 未开启时显示为关闭并置灰, 不修改持久化的 isLongTaskEnabled
+ private var longTaskRow: some View {
+ let isDisplayedOn = codexHookSettings.isEnabled && notificationSettings.isLongTaskEnabled
+
+ return optionRow(
+ title: "任务完成通知",
+ isOn: Binding(
+ get: { isDisplayedOn },
+ set: { notificationSettings.setLongTaskEnabled($0) }
+ ),
+ isEnabled: codexHookSettings.isEnabled
+ ) {
+ if isDisplayedOn {
+ optionPicker(
+ title: "任务时长",
+ selection: Binding(
+ get: { notificationSettings.longTaskThresholdSeconds },
+ set: { notificationSettings.setLongTaskThresholdSeconds($0) }
+ ),
+ options: NotificationSettings.longTaskThresholdOptions,
+ label: { Self.longTaskOptionLabel($0) }
+ )
+ .transition(.opacity.combined(with: .move(edge: .trailing)))
+ }
+ }
+ .animation(Metrics.statusAnimation, value: isDisplayedOn)
+ }
+
+ /// Hook 未开启时显示为关闭并置灰, 不修改持久化的 isTaskWaitingEnabled
+ private var taskWaitingRow: some View {
+ let isDisplayedOn = codexHookSettings.isEnabled && notificationSettings.isTaskWaitingEnabled
+
+ return optionRow(
+ title: "任务等待通知",
+ isOn: Binding(
+ get: { isDisplayedOn },
+ set: { notificationSettings.setTaskWaitingEnabled($0) }
+ ),
+ isEnabled: codexHookSettings.isEnabled
+ )
+ }
+
+ private var creditExpiryRow: some View {
+ optionRow(
+ title: "重置次数临期通知",
+ isOn: Binding(
+ get: { notificationSettings.isCreditExpiryEnabled },
+ set: { notificationSettings.setCreditExpiryEnabled($0) }
+ )
+ )
+ }
+
+ private func optionRow(
+ title: String,
+ isOn: Binding<Bool>,
+ isEnabled: Bool = true
+ ) -> some View {
+ optionRow(title: title, isOn: isOn, isEnabled: isEnabled) {
+ EmptyView()
+ }
+ }
+
+ private func optionRow(
+ title: String,
+ isOn: Binding<Bool>,
+ isEnabled: Bool = true,
+ @ViewBuilder accessory: () -> some View
+ ) -> some View {
+ HStack(spacing: 10) {
+ Text(title)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+
+ Spacer(minLength: 8)
+
+ accessory()
+
+ Toggle(title, isOn: isOn)
+ .labelsHidden()
+ .toggleStyle(.switch)
+ .controlSize(.mini)
+ .disabled(!isEnabled)
+ }
+ .frame(height: Metrics.rowHeight)
+ }
+
+ private func optionPicker(
+ title: String,
+ selection: Binding<Int>,
+ options: [Int],
+ label: @escaping (Int) -> String
+ ) -> some View {
+ Picker(title, selection: selection) {
+ ForEach(options, id: \.self) { option in
+ Text(label(option)).tag(option)
+ }
+ }
+ .labelsHidden()
+ .pickerStyle(.menu)
+ .controlSize(.small)
+ .frame(width: Metrics.pickerWidth)
+ }
+
+ private static func longTaskOptionLabel(_ seconds: Int) -> String {
+ seconds < 60 ? "\(seconds) 秒" : "\(seconds / 60) 分钟"
+ }
+
+ private enum Metrics {
+ static let panelWidth: CGFloat = 300
+ static let horizontalPadding: CGFloat = 12
+ static let verticalPadding: CGFloat = 10
+ static let rowSpacing: CGFloat = 7
+ static let rowHeight: CGFloat = 22
+ static let pickerWidth: CGFloat = 72
+ static let cornerRadius: CGFloat = 12
+ static let statusAnimation = Animation.codexStatus
+ }
+}
diff --git a/Docs/AppServer.md b/Docs/AppServer.md
index 5a00fba..248f053 100644
--- a/Docs/AppServer.md
+++ b/Docs/AppServer.md
@@ -13,8 +13,8 @@ codex app-server --listen stdio://
必须通过 `CodexCLIResolver.resolveAppServerCommand()` 解析:
- 优先 PATH 中的全局 `codex`。
-- 如果 PATH 中的 `codex` 等价于 `/Applications/Codex.app/Contents/Resources/codex`,当作内置 Codex APP CLI,不当作全局 CLI。
-- 全局 CLI 不存在时回退 Codex APP 内置 CLI。
+- 如果 PATH 中的 `codex` 等价于 APP 内置路径,当作内置 CLI,不当作全局 CLI。
+- 全局 CLI 不存在时依次检查 `/Applications/ChatGPT.app/Contents/Resources/codex` 和 `/Applications/Codex.app/Contents/Resources/codex`。
- 两者都不存在时返回 `CodexStatusError.executableNotFound`,UI 归为「初始化失败」,日志记录具体错误。
不要绕过 `CodexCLIResolver` 直接启动 app-server。
diff --git a/Docs/CodexHook.md b/Docs/CodexHook.md
index 72a3d3f..4d31871 100644
--- a/Docs/CodexHook.md
+++ b/Docs/CodexHook.md
@@ -101,7 +101,7 @@ Hook 数据目录:
文件职责:
-- `events/YYYY-MM-DD.jsonl`: 按本机日期拆分的原始 Hook 事件日志
+- `events/YYYY-MM-DD.jsonl`: 按本机日期拆分的原始 Hook 事件日志;开启「系统通知」的任务完成或任务等待提醒后,主 App 会以只读方式轮询 tail 当日 events 文件的新增行,用 `UserPromptSubmit` / `Stop` 判定长任务完成、用 `PermissionRequest` 判定等待批准;该读取不修改文件、不参与统计维护,统计口径不变。
- `daily.jsonl`: 每日聚合结果,UI 优先读取它
- `stats.lock`: 并发写入锁文件,只用于 `flock`
- `maintenance.json`: 记录待整理日期、需要重建日期和每个日期的处理进度
@@ -110,7 +110,7 @@ Hook 数据目录:
```json
{
- "schema": 2,
+ "schema": 3,
"pending": ["2026-06-21"],
"dirty": [],
"days": {
@@ -180,7 +180,7 @@ CodexBar 不上传原始 `IOPlatformUUID`。同一台 Mac 在同一 iCloud 账
sessionIds, turnIds
```
-其余字段保持原值同步,包括 `projectCounts`。如果本地仍保留 `sessionIds` / `turnIds`,上传副本会把去重后的 `sessionIds.count` / `turnIds.count` 写入 `sessionCount` / `turnCount`,但不会上传 ID 本身;只有既没有压缩后的 count、也没有本地 ID 时,这两个字段才可能为 `null`。脱敏只发生在上传副本上,不会写回本地 `daily.jsonl`,因此最近 3 天本地仍保留 `sessionIds` / `turnIds` 用于本机精确去重。
+其余字段保持原值同步,包括 `projectCounts` 和 `modelCounts`。如果本地仍保留 `sessionIds` / `turnIds`,上传副本会把去重后的 `sessionIds.count` / `turnIds.count` 写入 `sessionCount` / `turnCount`,但不会上传 ID 本身;只有既没有压缩后的 count、也没有本地 ID 时,这两个字段才可能为 `null`。脱敏只发生在上传副本上,不会写回本地 `daily.jsonl`,因此最近 3 天本地仍保留 `sessionIds` / `turnIds` 用于本机精确去重。
每台设备每天一条记录:
@@ -214,7 +214,7 @@ Hook 子进程不访问网络。主 App 在工作流统计维护刷新后对本
最终展示 = 本机 daily.jsonl + 同步缓存中的其他设备记录
```
-`cache.jsonl` 写入前必须过滤本机自己的 CloudKit 记录,否则本机会把本地 daily 和自己上传的云端副本重复相加。本机数据永远以本地 `daily.jsonl` 为准;同步缓存只补其他设备。热力图详情的 6 个工作流指标按每台设备各自 daily 口径先生成展示值,再按日期相加;`projectCounts` 按项目名逐项相加。
+`cache.jsonl` 写入前必须过滤本机自己的 CloudKit 记录,否则本机会把本地 daily 和自己上传的云端副本重复相加。本机数据永远以本地 `daily.jsonl` 为准;同步缓存只补其他设备。热力图详情的 6 个计数指标按每台设备各自 daily 口径先生成展示值,再按日期相加;`projectCounts` 和 `modelCounts` 分别按项目名、模型名逐项相加,最后从合并后的模型计数中选出「最热模型」。
CloudKit 也按最近 210 天保留。每天第一次工作流刷新时,当前设备会删除 `deviceId == 本机 deviceId` 且早于保留窗口的 CloudKit 记录;其他设备记录不由本机清理。展示侧始终忽略最近 210 天外的缓存记录。
@@ -231,10 +231,10 @@ CloudKit 也按最近 210 天保留。每天第一次工作流刷新时,当前
```text
date, eventCount, sessionStartCount, stopCount, preToolUseCount, postToolUseCount,
permissionRequestCount, preCompactCount, postCompactCount, subagentStartCount,
-subagentStopCount, sessionCount, turnCount, projectCounts, sessionIds, turnIds
+subagentStopCount, sessionCount, turnCount, projectCounts, modelCounts, sessionIds, turnIds
```
-其中 `sessionIds` / `turnIds` / `sessionCount` / `turnCount` 没有值时写为 `null`,`projectCounts` 内部项目名按稳定顺序写出。
+其中 `sessionIds` / `turnIds` / `sessionCount` / `turnCount` 没有值时写为 `null`,`projectCounts` 和 `modelCounts` 内部键按稳定顺序写出。
能参与统计的事件行必须至少满足:
@@ -253,6 +253,7 @@ subagentStopCount, sessionCount, turnCount, projectCounts, sessionIds, turnIds
| 工具调用 | `event` 归一化为 `pretooluse` 的行会增加 `preToolUseCount`;归一化为 `posttooluse` 的行会增加 `postToolUseCount`。`tool` 可以是具体工具名,也可以是 `null`。 | `SessionStart` 这类非工具事件,即使 `tool` 是 `null` 或存在也不会计入;坏行。 | `max(preToolUseCount, postToolUseCount)` |
| 权限请求 | `event` 归一化为 `permissionrequest` 的行。 | `permission` 字段本身不会触发计数;只有事件名是 `PermissionRequest` 才计入。 | `permissionRequestCount` |
| 上下文压缩 | `event` 归一化为 `precompact` 或 `postcompact` 的行。 | 其他事件名;坏行。 | `max(preCompactCount, postCompactCount)` |
+| 最热模型 | 任意带非空 `model` 的有效事件行。 | `model` 为 `null` 或空字符串;坏行。 | 按模型名累计事件数,取最高值;并列时按模型名升序取第一个 |
逐字段统计口径如下:
@@ -274,8 +275,9 @@ subagentStopCount, sessionCount, turnCount, projectCounts, sessionIds, turnIds
| `sessionCount` | `sessionIds`、旧 `sessionCount`、`sessionStartCount` | 最近 3 天通常为 `null`;日期进入 3 天外窗口后,归一化时优先沿用已有 `sessionCount`,否则使用 `sessionIds.count`,再否则使用 `sessionStartCount`,然后移除 `sessionIds`。这样旧日期不用继续保存完整 ID,也能保留会话总数。 | 参与「会话总数」。 |
| `turnCount` | `turnIds`、旧 `turnCount`、`stopCount` | 最近 3 天通常为 `null`;日期进入 3 天外窗口后,归一化时优先沿用已有 `turnCount`,否则使用 `turnIds.count`,再否则使用 `stopCount`,然后移除 `turnIds`。这样旧日期不用继续保存完整 ID,也能保留轮次总数。 | 参与「对话轮次」。 |
| `projectCounts` | `cwd` | 任意事件行只要 `cwd` 非空,就取标准化路径的最后一层目录名作为项目名并 `+1`;如果最后一层为空,回退使用完整路径字符串。统计的是事件数,不是会话数或工具调用数。未知事件也会计入。 | 用于计算 `mostActiveProject`,当前页面不展示。 |
+| `modelCounts` | `model` | 任意事件行只要 `model` 非空,就按原始模型名 `+1`。统计的是带模型字段的事件数,不是 token 数;未知事件也会计入。 | 合并后用于计算并展示「最热模型」。 |
-读取旧 `daily.jsonl` 时,缺失的数字字段按 `0` 处理,缺失的 `projectCounts` 按空字典处理,缺失的 `sessionIds` / `turnIds` / `sessionCount` / `turnCount` 保持为 `nil`。后续归一化会按当前保留策略补齐或压缩这些字段。
+读取旧 `daily.jsonl` 时,缺失的数字字段按 `0` 处理,缺失的 `projectCounts` / `modelCounts` 按空字典处理,缺失的 `sessionIds` / `turnIds` / `sessionCount` / `turnCount` 保持为 `nil`。维护 schema 升级到 `3` 后会把保留窗口内已有事件日期标记为 dirty,从原始事件重建模型计数;后续归一化仍按当前保留策略补齐或压缩 ID 字段。
UI 不直接展示所有原始字段,而是先生成 `WorkflowDailyMetrics`:
@@ -287,8 +289,9 @@ UI 不直接展示所有原始字段,而是先生成 `WorkflowDailyMetrics`:
| 工具调用 | `max(preToolUseCount, postToolUseCount)` |
| 权限请求 | `permissionRequestCount` |
| 上下文压缩 | `max(preCompactCount, postCompactCount)` |
+| 最热模型 | 合并 `modelCounts` 后取计数最高的模型;并列时按名称升序 |
-`mostActiveProject` 和 `eventCount` 会进入 `WorkflowDailyMetrics`,但当前页面没有展示。`UserPromptSubmit` 和未知事件不会增加上述 6 个页面指标,只会进入 `eventCount`,有 `cwd` 时也会进入 `projectCounts`。
+`eventCount` 和 `projectCounts` 保留在 daily 聚合中,但当前页面不展示。`UserPromptSubmit` 和未知事件不会增加上述 6 个计数指标,只会进入 `eventCount`;有 `cwd` 时进入 `projectCounts`,有 `model` 时进入 `modelCounts`。
## UI 展示
@@ -324,8 +327,8 @@ Codex Hook 开启时:
- 没有当天 token bucket 时, 今天的 token 数显示为 `--`
- 详情面板首行左侧显示日期、右侧显示 token 数
- 第二行显示「用量强度」分段条
-- 后续逐行显示「会话总数」、「对话轮次」、「子智能体」、「工具调用」、「权限请求」、「上下文压缩」
-- 详情面板固定为 `212 x 189`
+- 后续逐行显示「最热模型」、「会话总数」、「对话轮次」、「子智能体」、「工具调用」、「权限请求」、「上下文压缩」
+- 详情面板固定为 `212 x 208`
- 详情面板横向 padding 为 `12`, 纵向 padding 为 `10`, 圆角为 `12`
- 日期使用 `.caption2.monospacedDigit()`, token 数使用 `14pt` 等宽数字并加粗
- 工作流统计行整体使用 `11pt`; 左侧标签固定宽度 `72`, 标签和值之间 spacing 为 `6`
diff --git a/Docs/CrossDeviceSync.md b/Docs/CrossDeviceSync.md
index 4c546f7..02d3400 100644
--- a/Docs/CrossDeviceSync.md
+++ b/Docs/CrossDeviceSync.md
@@ -8,7 +8,7 @@
- `daily.jsonl` 中每一天的工作流统计聚合副本
- 会话总数、对话轮次、子智能体、工具调用、权限请求、上下文压缩等计数字段
-- `eventCount` 和 `projectCounts`
+- `eventCount`、`projectCounts` 和 `modelCounts`
不会同步:
@@ -65,7 +65,7 @@ Sync/cursor.data
```json
{
- "schema": 1,
+ "schema": 2,
"deviceId": "<当前设备在当前 iCloud 账号下的匿名设备 ID>",
"hashByDate": {
"2026-06-25": "<脱敏 daily 聚合的 SHA256>"
@@ -121,11 +121,14 @@ fields:
sessionCount: Int?
turnCount: Int?
projectCounts: Data(JSON object)
+ modelCounts: Data(JSON object)
updatedAt: Date
```
`projectCounts` 会保留本机聚合中的项目显示名。项目显示名通常是 `cwd` 的最后一层目录名;如果路径最后一层为空,代码会回退到完整路径字符串。
+`modelCounts` 会保留 Hook 事件中的模型名及其当天事件计数,用于跨设备合并后计算热力图详情的「最热模型」;不会包含 prompt、response 或原始事件内容。
+
## 设备标识
设备标识不直接上传 `IOPlatformUUID`。同步服务会先在当前 iCloud private database 中读取或创建 32 字节账号级 salt,然后计算:
@@ -140,7 +143,7 @@ deviceId = HMAC_SHA256(accountSalt, IOPlatformUUID)
- 同一台 Mac 切换 iCloud 账号后会得到不同的 `deviceId`
- CloudKit 中不会保存原始 `IOPlatformUUID`
-如果本地 `state.json` 的 `schema` 和当前代码不一致,服务会丢弃旧同步状态。下一轮同步会按当前设备重新写入 `state.json`,清空旧 `cache.jsonl` / `cursor.data`,再从 `CodexBarZone` 重建缓存。当前调试阶段 iCloud sync state schema 保持为 `1`。
+如果本地 `state.json` 的 `schema` 和当前代码不一致,服务会丢弃旧同步状态。下一轮同步会按当前设备重新写入 `state.json`,清空旧 `cache.jsonl` / `cursor.data`,再从 `CodexBarZone` 重建缓存。当前 iCloud sync state schema 为 `2`。
如果本地 `state.json` 中的 `deviceId` 和当前解析出的 `deviceId` 不一致,说明 iCloud 账号或账号级 salt 已变化。此时同步服务会重置本地同步状态,清空 `cache.jsonl`,并删除 `cursor.data`,然后按新账号重新同步。
@@ -270,6 +273,7 @@ CodexBar.workflowSyncDidFinish
- 保留各类计数字段
- 保留 `projectCounts`
+- 保留 `modelCounts`
- 不包含 `sessionIds`
- 不包含 `turnIds`
- 如果本机还有 `sessionIds`,会把去重数量写入 `sessionCount`
diff --git a/Docs/DevelopmentGuide.md b/Docs/DevelopmentGuide.md
index c0588f7..90ba791 100644
--- a/Docs/DevelopmentGuide.md
+++ b/Docs/DevelopmentGuide.md
@@ -157,7 +157,7 @@ Command-Space 不直接关闭菜单面板, 只短暂抑制 600 ms 内的 active
热力图详情面板和重置次数详情面板都会通过 `containsScreenPoint(_:)` 告诉关闭监听器自己的屏幕区域, 因此点击这些 child panel 内部不会触发主菜单面板关闭。重置次数详情面板可接收鼠标事件用于滚动; 热力图详情面板不接收鼠标事件。
-两个侧边详情面板的共同行为集中在 `CodexBar/Controllers/SidePanelSupport.swift`: `NonactivatingSidePanel` 固定不能成为 key/main window, `SidePanelDrawerAnimator` 管理内容 view 的横向抽屉 transform, `SidePanelSupport` 提供 panel 工厂(`makePanel`, 仅 `ignoresMouseEvents` 与初始尺寸由调用方决定)、完整定位入口(`position`, 内含左右侧选择、坐标夹紧与 `SidePanelPosition` 组装, 纵向由调用方传入期望位置)、共享几何/抽屉动画常量(`SidePanelSupport.Metrics`), 以及 child window 挂载/移除、菜单面板 key window 恢复、圆角 layer 配置和屏幕 frame 换算。`HeatmapDetailPanelController` 主要保留 hover 请求、Y 轴策略、侧边切换队列和 token/workflow 内容更新; `ResetCreditsPanelController` 主要保留重置次数内容、额度区锚点校验、最大高度和点击切换状态。两个面板视图的玻璃底/背板/描边/圆角裁剪皮肤共用 `LiquidGlassStyle.swift` 的 `sidePanelChrome(cornerRadius:)`。
+侧边面板的共同行为集中在 `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)、共享几何/抽屉动画常量(`SidePanelSupport.Metrics`), 以及 child window 挂载/移除、菜单面板 key window 恢复、圆角 layer 配置和屏幕 frame 换算。`HeatmapDetailPanelController` 保留 hover 请求、Y 轴策略、侧边切换队列和 token/workflow 内容更新, 其切边/延迟隐藏状态机不走共享 presenter; `ResetCreditsPanelController` 主要保留重置次数内容、最大高度和点击切换状态。两个面板视图的玻璃底/背板/描边/圆角裁剪皮肤共用 `LiquidGlassStyle.swift` 的 `sidePanelChrome(cornerRadius:)`。
设置窗口和日志窗口都继承 `HostingWindowController` 的行为: 懒创建, 关闭后不释放, 重新打开复用, 按当前屏幕居中, 重新打开对应入口时只移动和置前对应窗口。窗口 level 保持 `.normal`; 置前时先恢复 `AuxiliaryHostingWindow.allowsKeyFocus`, 再 `orderFrontRegardless()`, `NSRunningApplication.current.activate(options: [])` 和 `makeKeyAndOrderFront(nil)`, 只做一次性置前, 不持续置顶。CodexBar 是 `LSUIElement` 菜单栏 App, 首次懒创建辅助窗口时需要通过当前运行中应用激活, 避免设置或日志窗口第一次打开时没有稳定拉到最前。
@@ -324,8 +324,8 @@ codex app-server --listen stdio://
解析优先级:
- PATH 中的全局 `codex`
-- 如果 PATH 中的 `codex` 等价于 `/Applications/Codex.app/Contents/Resources/codex`, 它被视为 Codex APP 内置 CLI, 不算全局 CLI
-- 全局 CLI 不存在时回退 Codex APP 内置 CLI
+- 如果 PATH 中的 `codex` 等价于 APP 内置路径, 它被视为内置 CLI, 不算全局 CLI
+- 全局 CLI 不存在时依次检查 `/Applications/ChatGPT.app/Contents/Resources/codex` 和 `/Applications/Codex.app/Contents/Resources/codex`
- 两者都不存在时抛出 `CodexStatusError.executableNotFound`
环境变量由 `CodexCLIResolver.environment` 构造:
@@ -389,6 +389,7 @@ codex app-server --listen stdio://
- 登录项错误显示在设置组与底部按钮组之间的独立错误组; Hook 写入/验证错误显示在 Hook 开关下方; 同步账号不可用显示在「跨设备同步」开关下方; 同步运行失败显示在主面板更新时间行同步图标 tooltip 中
- 全局快捷键录制, 校验和注册错误显示在快捷键行内
- Hook 子进程尽量快速退出, 事件记录失败不会阻断 Codex 自身流程
+- 通知发送与 Hook 事件 tail 的失败全部静默降级, 不进入请求日志窗口, 详见第 19 节
app-server 与状态刷新错误:
@@ -577,14 +578,14 @@ flowchart TD
热力图详情面板是菜单面板的 borderless nonactivating child panel, 不接收鼠标事件, 按悬停列优先显示在菜单面板左侧或右侧; 左右空间不足时尝试另一侧, 最终在当前屏幕可见区域内保留 8 px 边距。侧边切换时先以 0.12 秒抽屉动画收起, 再以 0.18 秒展开。热力图详情面板和重置次数详情面板互斥, hover 热力图会立即隐藏重置次数详情面板。nonactivating panel、抽屉 transform、child window 挂载和圆角 layer 配置复用 `SidePanelSupport.swift`。
-`HeatmapDetailPanelController` 会复用同一个 `NSPanel` 和 `NSHostingController`, 但每次 hover 内容变化时必须替换 `hostingController.rootView` 并同步 `setContentSize`。不要用常驻 `ObservableObject` model 持续推送 `UsageHeatmapHoverContext`; Hook 开关会让详情面板在 `212 x 84` 和 `212 x 189` 两种布局之间切换, 复用同一棵 SwiftUI 布局树容易触发 AppKit constraint/layout 递归。相关回归路径是: 先 hover 出详情面板, 打开设置切换 Hook, 再回到主面板 hover 热力图。
+`HeatmapDetailPanelController` 会复用同一个 `NSPanel` 和 `NSHostingController`, 但每次 hover 内容变化时必须替换 `hostingController.rootView` 并同步 `setContentSize`。不要用常驻 `ObservableObject` model 持续推送 `UsageHeatmapHoverContext`; Hook 开关会让详情面板在 `212 x 84` 和 `212 x 208` 两种布局之间切换, 复用同一棵 SwiftUI 布局树容易触发 AppKit constraint/layout 递归。相关回归路径是: 先 hover 出详情面板, 打开设置切换 Hook, 再回到主面板 hover 热力图。
详情面板分两种:
| Hook 状态 | 内容 | 尺寸 |
| --------- | ---------------------------------------------------------------------------------------------- | ----------- |
| 关闭 | 日期, token 数和"用量强度"分段条 | `212 x 84` |
-| 开启 | 日期, token 数, "用量强度"分段条, 会话总数, 对话轮次, 子智能体, 工具调用, 权限请求, 上下文压缩 | `212 x 189` |
+| 开启 | 日期, token 数, "用量强度"分段条, 最热模型, 会话总数, 对话轮次, 子智能体, 工具调用, 权限请求, 上下文压缩 | `212 x 208` |
Hook 开启且当天没有 token bucket 时, 今天的 token 数显示 `--`。日期使用 `AnimatedDateText` 做数字滚动, token 数使用 `TokenCountText` 并保留数字和单位宽度。
「用量强度」前置圆点固定为蓝色, 不随用量强度变化。
@@ -847,6 +848,7 @@ flowchart TD
- 事件名先去掉 `_` 和 `-`, 再转小写
- `sessionStartCount`, `stopCount`, `preToolUseCount` 等按归一化事件名增加
+- 任意有效事件中的非空 `model` 按模型名累加到 `modelCounts`
- 最近 3 个本地自然日保留 `sessionIds` 和 `turnIds`, 用于继续去重
- 3 天前把 ID 集合压缩为 `sessionCount` 和 `turnCount`, 随后移除 ID 列表
- 最多保留最近 210 天数据
@@ -863,8 +865,9 @@ UI 展示指标来自 `WorkflowDailyAggregate.metrics`:
| 工具调用 | `max(preToolUseCount, postToolUseCount)` |
| 权限请求 | `permissionRequestCount` |
| 上下文压缩 | `max(preCompactCount, postCompactCount)` |
+| 最热模型 | 合并 `modelCounts` 后取计数最高的模型, 并列时按名称升序 |
-跨设备同步只在 `performMaintenance: true, synchronize: true` 的刷新中执行。`WorkflowSyncScheduler` 会合并同步开关、Hook 重新开启、同步账号恢复可用和自动刷新产生的同步请求;同步中不取消重启, 冷却窗口内只保留一次待补跑请求, 补跑前重新校验 Hook 开启、跨设备同步偏好为 true 且同步账号可用。`WorkflowSyncService` 先用本机 daily 聚合生成脱敏 `WorkflowSyncedDailyAggregate`, 再按日期稳定排序候选项, 每批最多上传 25 天, 每轮最多使用 20 秒。zone 存在性确认和 account salt 首次成功后在 actor 内跨轮缓存, 任一轮同步失败时作废, 下一轮重新确认(覆盖 iCloud 账号切换)。每批成功后立即保存 `state.hashByDate` 和 `lastUploadAt`, 未完成的 backfill 留给后续自动刷新继续。没有 `cursor.data` 时先 query 全量 `CodexBarDailyAggregate` 回填 `cache.jsonl`; 有游标时优先拉 CloudKit 增量, 游标失效或增量失败时不写入日志窗口, 直接全量重建缓存。写入 `cache.jsonl` 前会过滤当前设备自己的记录, 只保留其他设备记录。增量路径先写 `cache.jsonl`, 成功后再写 `cursor.data`, 避免游标提前推进导致未落盘记录被跳过。同步失败会通过 `CodexBar.workflowSyncDidFinish` 通知发送 `didSucceed=false` 和归类后的 `failureMessage`, 主面板同步图标进入失败态。
+跨设备同步只在 `performMaintenance: true, synchronize: true` 的刷新中执行。`WorkflowSyncScheduler` 会合并同步开关、Hook 重新开启、同步账号恢复可用和自动刷新产生的同步请求;同步中不取消重启, 冷却窗口内只保留一次待补跑请求, 补跑前重新校验 Hook 开启、跨设备同步偏好为 true 且同步账号可用。`WorkflowSyncService` 先用本机 daily 聚合生成脱敏 `WorkflowSyncedDailyAggregate`, 保留 `projectCounts` 和 `modelCounts`, 再按日期稳定排序候选项, 每批最多上传 25 天, 每轮最多使用 20 秒。zone 存在性确认和 account salt 首次成功后在 actor 内跨轮缓存, 任一轮同步失败时作废, 下一轮重新确认(覆盖 iCloud 账号切换)。每批成功后立即保存 `state.hashByDate` 和 `lastUploadAt`, 未完成的 backfill 留给后续自动刷新继续。没有 `cursor.data` 时先 query 全量 `CodexBarDailyAggregate` 回填 `cache.jsonl`; 有游标时优先拉 CloudKit 增量, 游标失效或增量失败时不写入日志窗口, 直接全量重建缓存。写入 `cache.jsonl` 前会过滤当前设备自己的记录, 只保留其他设备记录。增量路径先写 `cache.jsonl`, 成功后再写 `cursor.data`, 避免游标提前推进导致未落盘记录被跳过。同步失败会通过 `CodexBar.workflowSyncDidFinish` 通知发送 `didSucceed=false` 和归类后的 `failureMessage`, 主面板同步图标进入失败态。
## 13. 设置窗口流程
@@ -894,16 +897,17 @@ App 再次成为 active 时, 也会刷新 Codex 版本区、同步可用性, 并
设置项:
-| 设置项 | 状态源 | 写入行为 |
-| --------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
-| 开机自动启动 | `SMAppService.mainApp.status` | `register()` / `unregister()` |
-| 自动检查更新 | Sparkle updater | 设置 `automaticallyChecksForUpdates` |
+| 设置项 | 状态源 | 写入行为 |
+| --------------- | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 开机自动启动 | `SMAppService.mainApp.status` | `register()` / `unregister()` |
+| 自动检查更新 | Sparkle updater | 设置 `automaticallyChecksForUpdates` |
| 菜单栏额度指示 | `MenuBarQuotaSettings.selection` / `MenuBarQuota.lastWindowSelection` | 开关写入 `.off` 或恢复持久化的上次窗口选择, 窗口菜单写入所选窗口并同步记住; 标签优先来自当前账号 Codex limit 返回的额度窗口, 缺失时使用 fallback 标题 |
-| 使用快捷键 | `GlobalHotKeySettings.shortcut` | 写入 `UserDefaults` 并注册 hot key |
-| 启用 Codex Hook | app-server `config/read` / `hooks/list` / `config/batchWrite`, `~/.codex/hooks.json` | 检查全局 Hook 开关后追加或移除当前 CodexBar command hook, 并维护对应 `hooks.state` 信任状态 |
-| 跨设备同步 | `WorkflowSyncSettings` + CloudKit account status + `WorkflowSyncScheduler` | Hook 开启且同步账号可用时写入 `UserDefaults`; 开启时标记 `needsBackfill` 并请求调度同步 |
-| Codex 版本 | `CodexCLIVersionSnapshot` + 当前 app-server 握手信息 | 路径点击复制到剪贴板 |
-| CodexBar 版本 | Bundle + AppUpdater 状态 | 有更新状态时优先显示动态消息 |
+| 系统通知 | `NotificationSettings` + `UNUserNotificationCenter` | 总开关与五类子开关、阈值写入 `UserDefaults`; 首次开启时请求系统通知授权 |
+| 使用快捷键 | `GlobalHotKeySettings.shortcut` | 写入 `UserDefaults` 并注册 hot key |
+| 启用 Codex Hook | app-server `config/read` / `hooks/list` / `config/batchWrite`, `~/.codex/hooks.json` | 检查全局 Hook 开关后追加或移除当前 CodexBar command hook, 并维护对应 `hooks.state` 信任状态 |
+| 跨设备同步 | `WorkflowSyncSettings` + CloudKit account status + `WorkflowSyncScheduler` | Hook 开启且同步账号可用时写入 `UserDefaults`; 开启时标记 `needsBackfill` 并请求调度同步 |
+| Codex 版本 | `CodexCLIVersionSnapshot` + 当前 app-server 握手信息 | 路径点击复制到剪贴板 |
+| CodexBar 版本 | Bundle + AppUpdater 状态 | 有更新状态时优先显示动态消息 |
错误显示:
@@ -923,7 +927,7 @@ App 再次成为 active 时, 也会刷新 Codex 版本区、同步可用性, 并
安装源模型:
- `.global`: PATH 中真实全局 `codex`
-- `.bundled`: `/Applications/Codex.app/Contents/Resources/codex` 或等价路径
+- `.bundled`: `/Applications/ChatGPT.app/Contents/Resources/codex`、`/Applications/Codex.app/Contents/Resources/codex` 或等价路径, ChatGPT.app 优先
`CodexCLIInstallations.activeSource` 与启动优先级一致: 全局优先, 内置回退
@@ -1066,3 +1070,36 @@ App 再次成为 active 时, 也会刷新 Codex 版本区、同步可用性, 并
- 不把原始敏感 RPC 响应写入文档或测试夹具
- 日志完整保存 request/detail, UI 默认只渲染单行预览; 完整内容通过标题行预览或复制查看
- Hook 统计默认只保存在用户 Application Support 的 CodexBar 目录;开启「跨设备同步」后, CloudKit 只保存去掉 `sessionIds` / `turnIds` 的 daily 聚合副本, 不保存原始 Hook events
+
+## 19. 通知提醒链路
+
+通知判定与发送在 `CodexBar/Services/Notifications/`, 偏好类随其他设置类放在 `CodexBar/Services/Settings/`:
+
+- `NotificationSettings` (`Services/Settings/`): 总开关、五类子开关、低额度阈值 (5%/10%/25%, 默认 10%) 和长任务时长 (30s/1m/2m/5m, 默认 1m), 持久化到 UserDefaults; 负责系统授权请求、被拒状态镜像和设置页选项面板可展示状态
+- `CodexNotificationService`: 集中判定、去重、调度与发送; 由 `CodexBarAppDelegate` 创建, 订阅 `CodexStatusViewModel.$snapshot` 与 `NSWorkspace.didWakeNotification`; 五类正式通知共用 `CodexNotificationContent` 文案工厂
+- `HookEventTailReader`: 2 秒轮询当日 `events/YYYY-MM-DD.jsonl` 大小, 只读增量解码新追加的完整行; 仅在总开关开启、系统授权未拒绝、Hook 启用, 且任务完成/任务等待任一子开关开启时运行
+
+设置页交互: 「系统通知」主开关行保留在设置窗口内, 子选项 (五类子开关与两个阈值 Picker) 在主选项右侧的子面板中展开 (`NotificationOptionsPanelController`, 复用 SidePanelSupport 抽屉机制挂在设置窗口上, 内容用常驻 hosting controller + ObservableObject 驱动, 面板尺寸在 Hook 开/关两种状态下保持不变)。「任务等待通知」紧跟在「任务完成通知」下方。主开关开启后仅在系统授权允许时展开, 首次授权场景会等待授权结果; 点击行内滑杆按钮可手动展开; 设置窗口 resign key/关闭、主开关关闭或授权变为被拒时自动收起。任务完成与任务等待子项在 Hook 未开启时显示为关闭并置灰, 不修改各自持久化偏好, Hook 重新开启后恢复用户原选择。授权被拒的引导文案与"打开系统设置"按钮仍内联显示在主开关行下方, 插入提示时不触发设置项纵向动画。
+
+五类通知的触发与去重:
+
+| 通知 | 触发 | 去重键 |
+| ------------ | -------------------------------------------------------------------------------- | ------------------------------------------ |
+| 额度低阈值 | 非 stale 快照中窗口剩余比例穿越到 ≤ 阈值; 阈值或子开关变化时用当前快照立即重评估 | `low\|账号\|limitId\|windowId\|resetsAt` |
+| 额度重置完成 | 本周期曾跌破阈值 (与低阈值子开关无关) 且到达 resetsAt; 补发时效为一个窗口周期 | `reset\|账号\|limitId\|windowId\|resetsAt` |
+| 长任务完成 | Stop 事件按 session+turn (回退 session) 配对 UserPromptSubmit, 耗时 ≥ 阈值 | 每条 Stop 只配对一次 |
+| 任务等待批准 | 实时读取到 `PermissionRequest` 事件 | 进程内按 timestamp+session+turn+tool 去重 |
+| 重置机会临期 | 过期时间距今 ≤ 7 天, 并在过期前 7/6/5/4/3/2/1 天各提醒一次; 正文使用本地时间 `yyyy-MM-dd HH:mm:ss` | `credit\|账号\|过期时间\|提醒档位` |
+
+额度和重置机会通知的已发送去重键持久化在 UserDefaults (`Notification.sentKeys`, 上限 300 条滚动淘汰), 账号维度包含在键中, 切换账号自动隔离。任务等待去重只保留在当前进程内, tail 启动时从当日文件末尾开始, 不回放 App 启动前的历史权限事件。
+
+通知错误处理 (延续"细节不打扰用户"原则, 不写入请求日志窗口):
+
+| 场景 | 行为 |
+| --------------------- | ------------------------------------------------ |
+| 系统授权被拒 | 服务静默不发, 设置页显示引导与"打开系统设置"按钮 |
+| 事件文件读取/解析失败 | 静默跳过本轮 tail, 其余通知不受影响 |
+| 休眠错过 resetsAt | 唤醒时补检, 超过一个窗口周期的恢复提醒直接丢弃 |
+| Hook 关闭或两个 Hook 通知子开关都关闭 | tail 停止并清空配对表 |
+
+通知点击通过 `UNUserNotificationCenterDelegate` 回调 `StatusItemController.openMenuSurfaceFromNotification()`, 复用全局快捷键的打开路径 (含 fallback 面板兜底)。
diff --git a/README.md b/README.md
index 2caafc6..19ad46d 100644
--- a/README.md
+++ b/README.md
@@ -15,8 +15,9 @@ Codex 的额度、Token 用量和使用情况通常分散在终端、App 或 Ses
- 查看当前账号是否已登录,以及 Codex CLI / Codex.app 的运行版本
- 跟踪不同时间窗口的额度剩余比例和下一次重置时间
- 用 30 周热力图回顾每日 Token 用量
-- 在开启 Codex Hook 后在 30 周热力图中可查看会话、对话轮次、工具调用、权限请求、上下文压缩和子智能体统计 (仅在开启后可记录查看,无法查看到历史数据)
+- 在开启 Codex Hook 后在 30 周热力图中可查看当天最热模型,以及会话、对话轮次、工具调用、权限请求、上下文压缩和子智能体统计 (仅在开启后可记录查看,无法查看到历史数据)
- 通过可选 iCloud 私有数据库同步实现跨设备数据合并
+- 额度告急、额度恢复、任务等待批准、长任务完成时收到系统通知(可选开启)
## 有什么功能
@@ -66,6 +67,18 @@ CodexBar 会把该设备的使用详情数据同步到当前 iCloud 账号的 Cl
完整同步范围见 [跨设备同步文档](Docs/CrossDeviceSync.md)
+### 系统通知提醒
+
+在设置中开启「系统通知」后,CodexBar 会在关键状态变化时发送本地通知:
+
+- 额度剩余比例跌破所选阈值 (5% / 10% / 25%)
+- 曾跌破阈值的额度窗口完成重置
+- Codex 完成一轮超过所选时长的任务 (需开启 Codex Hook)
+- Codex 请求批准工具操作并等待用户处理 (需开启 Codex Hook)
+- 手动重置机会将在 7 天内过期,并按 24 小时间隔提醒
+
+五类通知可以单独开关;全部为本地通知,不新增网络请求。
+
### 日志与版本信息
CodexBar 内置请求日志窗口,用于查看 app-server 请求状态和排查刷新问题。设置页会展示 CodexBar 版本、当前 Codex CLI / Codex.app 版本、运行来源和本地安装路径,路径点击即可复制。
@@ -106,7 +119,7 @@ Codex Hook 工作流数据默认只保存在本机:
~/Library/Application Support/CodexBar/HookEvents/
```
-只有在用户开启「跨设备同步」后,CodexBar 才会通过 `CloudKit private database` 同步每日使用详情数据; 同步的数据副本只包含各个事件数量,不包含事件具体的数据。
+只有在用户开启「跨设备同步」后,CodexBar 才会通过 `CloudKit private database` 同步每日使用详情数据; 同步的数据副本只包含各个事件数量、项目聚合和模型名使用次数,不包含事件具体的数据。
除上述重置机会过期时间查询、Sparkle appcast / DMG 下载,以及用户开启跨设备同步后的 CloudKit 请求外,CodexBar 自身不发起其他网络请求。
diff --git a/appcast.xml b/appcast.xml
index 5e04821..7d06aa9 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.0</title>
+ <sparkle:version>38</sparkle:version>
+ <sparkle:shortVersionString>3.3.0</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.3.0</sparkle:releaseNotesLink>
+ <pubDate>Fri, 10 Jul 2026 10:30:19 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.3.0.dmg" sparkle:edSignature="u5Qwjjj8I7QHEE+wtsyjZ8mOlafk+L5a1AE9xRo0NnF28nz6ExB5Gk8ZMmtc5XhqwCvoG9/Kli+g5cZ7tYFOCw==" length="3608469" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.2.9</title>
<sparkle:version>37</sparkle:version>