CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
refactor: 整理菜单面板并发布 3.0.0
Bob9e9f9fd64dea
diff --git a/.swiftlint.yml b/.swiftlint.ymlnew file mode 100644index 0000000..0101d52--- /dev/null+++ b/.swiftlint.yml@@ -0,0 +1,45 @@+included:+ - CodexBar++excluded:+ - .build+ - DerivedData+ - /tmp+ - CodexBar/Resources++line_length:+ warning: 140+ error: 180+ ignores_comments: true+ ignores_urls: true+ ignores_function_declarations: true+ ignores_interpolated_strings: true++file_length:+ warning: 900+ error: 1200+ ignore_comment_only_lines: true++type_body_length:+ warning: 550+ error: 700++function_body_length:+ warning: 80+ error: 120++function_parameter_count:+ warning: 7+ error: 9++cyclomatic_complexity:+ warning: 15+ error: 25+ ignores_case_statements: true++identifier_name:+ min_length:+ warning: 1+ max_length:+ warning: 60+ error: 80diff --git a/AGENTS.md b/AGENTS.mdindex 15b68b2..0c7fc78 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -77,7 +77,7 @@ git status --short```textCodexStatusService(JSON-RPC app-server)-> CodexStatusViewModel(@MainActor 状态发布)- -> StatusItemController(菜单栏图标、popover、窗口入口)+ -> StatusItemController(菜单栏图标、菜单面板、窗口入口)-> CodexStatusMenuView / AppSettingsView / LogViewCodex Hook@@ -91,10 +91,10 @@ Codex Hook目录职责:- `App/`: 入口和全局启动分支。-- `Controllers/`: 菜单栏、popover、设置窗口和日志窗口控制。+- `Controllers/`: 菜单栏、菜单面板、设置窗口和日志窗口控制。- `Models/`: account、quota、usage、workflow stats、共享日期网格和错误模型。- `Services/`: app-server、Codex CLI、设置、Hook 统计、更新和日志服务。-- `Views/`: popover、设置、日志和共享 Liquid Glass 样式。+- `Views/`: 菜单面板、设置、日志和共享 Liquid Glass 样式。Hook 统计的配置、存储、保留策略和统计口径见 [Docs/CodexHook.md](Docs/CodexHook.md)。@@ -163,10 +163,11 @@ Hook 统计的配置、存储、保留策略和统计口径见 [Docs/CodexHook.m菜单栏:- 正常图标是 `person.fill.checkmark`, 错误图标是 `person.fill.xmark`。-- 菜单栏不展示额度数字; 详情只在 popover 中展示。-- 左键或全局快捷键切换 popover; 右键或 Control 点击显示「设置 / 日志 / 退出」。+- 菜单栏不展示额度数字; 详情只在菜单面板中展示。+- 左键或全局快捷键切换菜单面板; 右键或 Control 点击显示「设置 / 日志 / 退出」。+- 全局快捷键打开菜单面板前必须校验当前 status item 锚点可信; 锚点无 window、无有效 screen、按钮隐藏、bounds 为空、屏幕矩形异常, 或屏幕矩形没有落在目标屏幕范围内时, 使用无箭头 fallback `NSPanel` 在目标屏幕顶部居中打开。目标屏幕优先取鼠标所在屏幕, 找不到时取主屏幕。快捷键关闭已打开的菜单面板不受此校验影响。-Popover:+菜单面板:- `CodexStatusMenuView.menuWidth` 由热力图宽度和 padding 推导; 改热力图尺寸时同步检查弹窗宽度。- 外层和分区使用 `.liquidGlassSurface(...)`; 分隔线使用 `LiquidGlassDivider`; 小徽章可用 `.liquidGlassCapsule(...)`。@@ -174,16 +175,16 @@ Popover:- 账号图标双击触发刷新。邮箱文本双击切换模糊。- 计划名是右侧加粗纯文字; `planBadgeTint(for:)` 优先级: enterprise -> team/business -> pro -> plus -> edu -> free -> 默认 cyan。- 额度条展示剩余百分比, 固定为 50 个胶囊, 每个胶囊宽 `3.5`, 间距 `2`, 高 `12`; 颜色按 20% 一档: 红、橙、黄、薄荷、绿。-- 额度行标签列宽 `34`, 居中显示, 标签允许最小缩放到 `0.75`, 标签到额度条间距 `12`, 额度条到百分比间距 `8`, 百分比列宽 `37`, 百分比到重置时间最小间距 `6`, 重置时间列宽 `75`; 不通过加宽 popover 解决额度行溢出。+- 额度行标签列宽 `34`, 居中显示, 标签允许最小缩放到 `0.75`, 标签到额度条间距 `12`, 额度条到百分比间距 `8`, 百分比列宽 `37`, 百分比到重置时间最小间距 `6`, 重置时间列宽 `75`; 不通过加宽菜单面板解决额度行溢出。- 无 quota 数据时显示 `--` / `暂无数据`, 并使用占位色。- `rateLimits` 或 `usage` 使用旧缓存时, 对应区域通过 `.markStale(true)` 降低透明度到 0.55, 不降低饱和度; 下一轮对应接口成功后恢复正常透明度。- 重置时间格式是 `MM-dd HH:mm`, 使用等宽数字, 在额度行最右侧对齐。- 更新时间行显示倒计时圆环、「数据更新时间」和 `HH:mm:ss`。-- 倒计时只在 popover 可见时用 `TimelineView` 每秒 tick; 普通 tick 不做连续动画, 仅刷新起点变化时播放恢复动画。+- 倒计时只在菜单面板可见时用 `TimelineView` 每秒 tick; 普通 tick 不做连续动画, 仅刷新起点变化时播放恢复动画。- token 区域显示「单日峰值」和「全时累计」; `TokenCountText` 对 1K 以下显示完整整数, 1K 起显示 K/M/B。- token 区域还显示「当前连胜」、「最长连胜」和「最长任务」。- 热力图是近 30 周、30 列 x 7 行、周日到周六排列; Codex Hook 开启时包含今天, Hook 关闭时仅在 app-server 已返回当天 token bucket 时包含今天。-- 热力图 hover 使用 `HeatmapDetailPanelController` 展示侧边详情面板, 不是 popover 内 tooltip; 面板作为 popover child window, 不接收鼠标事件, 左右贴边展示并在屏幕可见区域内夹紧。+- 热力图 hover 使用 `HeatmapDetailPanelController` 展示侧边详情面板, 不是菜单面板内 tooltip; 面板作为菜单面板 child window, 不接收鼠标事件, 左右贴边展示并在屏幕可见区域内夹紧。- Hook 关闭时详情面板显示日期、token 数和「用量强度」分段条, 尺寸 `212 x 84`。- Hook 开启时详情面板首行左侧显示日期、右侧显示 token 数, 当天 token 数显示 `--`; 后续显示「用量强度」、「会话总数」、「对话轮次」、「子智能体」、「工具调用」、「权限请求」、「上下文压缩」, 尺寸 `212 x 189`。- 「用量强度」前置圆点固定为蓝色, 不随用量强度变化。@@ -192,7 +193,7 @@ Popover:设置窗口:- 通过右键菜单「设置」打开独立 `AppSettingsView` 窗口。-- 不要恢复为 Option 点击或 popover 内设置区。+- 不要恢复为 Option 点击或菜单面板内设置区。- 设置页包含「使用快捷键」行、「CodexBar 版本」和「Codex 版本」区域。- `Codex CLI` 行图标用 `terminal`; `Codex APP` 行图标用 `app.badge`。- 当前运行来源显示「当前使用」。@@ -217,7 +218,7 @@ Popover:- 任一缺失时不创建 `SPUStandardUpdaterController`, 更新操作显示「未配置更新资源」。- `canConfigureAutomaticChecks` 是 `updaterController != nil`。- `settingsStatusMessage` 用于设置窗版本行, 默认 3 秒后清空。-- `panelUpdateMessage` 用于 popover 底栏被动提示, 双击触发 `startUpdate()`。+- `panelUpdateMessage` 用于菜单面板底栏被动提示, 双击触发 `startUpdate()`。- `availableUpdateMessage` 驱动设置窗版本行和「立即更新」按钮。- 手动检查结果进 `settingsStatusMessage`; 自动发现新版进 `panelUpdateMessage`。- 当前 `SUFeedURL = https://codexbar.zabrian.app/appcast.xml`, `SUScheduledCheckInterval = 3600`。@@ -233,7 +234,7 @@ Popover:## 发布脚本-- `Scripts/dmg.sh [App.app] [Output.dmg]` 创建带 `/Applications` 链接的 DMG, 会尝试写 Finder 布局。+- `Scripts/dmg.sh [App.app] [Output.dmg]` 创建带 `/Applications` Finder alias 的 DMG, 会尝试写 Finder 布局。- `Scripts/appcast.sh [CodexBar-vX.Y.Z.dmg]` 更新 `appcast.xml`, 需要 Sparkle `sign_update`。- 改发布脚本后至少运行 `bash -n Scripts/dmg.sh` 和 `bash -n Scripts/appcast.sh`。- 更新 appcast、tag、push、上传 DMG 都必须先得到用户明确同意。diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex b310826..5f04c44 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -275,7 +275,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 22;+ CURRENT_PROJECT_VERSION = 23;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;ENABLE_APP_SANDBOX = NO;@@ -290,7 +290,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 2.4.6;+ MARKETING_VERSION = 3.0.0;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";REGISTER_APP_GROUPS = YES;@@ -312,7 +312,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 22;+ CURRENT_PROJECT_VERSION = 23;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;ENABLE_APP_SANDBOX = NO;@@ -327,7 +327,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 2.4.6;+ MARKETING_VERSION = 3.0.0;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";diff --git a/CodexBar/App/CodexBarApp.swift b/CodexBar/App/CodexBarApp.swiftindex 1cbc0f7..f4c14de 100644--- a/CodexBar/App/CodexBarApp.swift+++ b/CodexBar/App/CodexBarApp.swift@@ -5,13 +5,13 @@ import SwiftUI@mainstruct CodexBarApp: App {@NSApplicationDelegateAdaptor(CodexBarAppDelegate.self) private var appDelegate-+init() {if WorkflowHookEventRecorder.handleIfRequested() {exit(EXIT_SUCCESS)}}-+var body: some Scene {// 菜单栏 UI 由 AppDelegate 驱动; 空 Settings scene 仅用于保留系统设置入口Settings {@@ -24,7 +24,7 @@ nonisolated extension Bundle {var shortVersionString: String? {object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String}-+// `v1.2.3` 形式的版本文案; 缺失时回退 `--`var displayVersionLabel: String {guard let version = shortVersionString else { return "--" }diff --git a/CodexBar/Controllers/FallbackPanelController.swift b/CodexBar/Controllers/FallbackPanelController.swiftnew file mode 100644index 0000000..0986066--- /dev/null+++ b/CodexBar/Controllers/FallbackPanelController.swift@@ -0,0 +1,127 @@+import AppKit+import SwiftUI++@MainActor+final class FallbackPanelController {+ private let makeContentController: () -> NSHostingController<AnyView>+ private var panel: FallbackStatusPanel?++ init(makeContentController: @escaping () -> NSHostingController<AnyView>) {+ self.makeContentController = makeContentController+ }++ var isVisible: Bool {+ panel?.isVisible == true+ }++ var window: NSWindow? {+ panel+ }++ var contentView: NSView? {+ panel?.contentViewController?.view+ }++ func prepareForDisplay(on screen: NSScreen?) {+ let panel = makePanelIfNeeded()+ let contentSize = contentSize(for: panel)+ panel.setFrame(frame(for: contentSize, on: screen), display: false)+ }++ func show() {+ guard let panel else {+ return+ }++ panel.orderFrontRegardless()+ NSRunningApplication.current.activate(options: [])+ panel.makeKeyAndOrderFront(nil)+ }++ func orderOut() {+ panel?.orderOut(nil)+ }++ private func makePanelIfNeeded() -> FallbackStatusPanel {+ if let panel {+ return panel+ }++ let panel = FallbackStatusPanel(+ contentRect: NSRect(origin: .zero, size: Metrics.fallbackSize),+ styleMask: [.borderless, .fullSizeContentView],+ backing: .buffered,+ defer: false+ )+ panel.contentViewController = makeContentController()+ panel.isReleasedWhenClosed = false+ panel.isOpaque = false+ panel.backgroundColor = .clear+ panel.hasShadow = true+ panel.level = .popUpMenu+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]+ panel.hidesOnDeactivate = false++ self.panel = panel+ return panel+ }++ private func contentSize(for panel: NSPanel) -> NSSize {+ guard let contentView = panel.contentViewController?.view else {+ return Metrics.fallbackSize+ }++ contentView.layoutSubtreeIfNeeded()+ let fittingSize = contentView.fittingSize+ guard fittingSize.width.isFinite,+ fittingSize.height.isFinite,+ fittingSize.width > 0,+ fittingSize.height > 0 else {+ return Metrics.fallbackSize+ }++ return NSSize(+ width: CodexStatusMenuView.menuWidth,+ height: fittingSize.height+ )+ }++ private func frame(for panelSize: NSSize, on preferredScreen: NSScreen?) -> NSRect {+ guard let screen = preferredScreen ?? mouseScreen() ?? NSScreen.main else {+ return NSRect(origin: .zero, size: panelSize)+ }++ let visibleFrame = screen.visibleFrame+ return NSRect(+ x: visibleFrame.midX - panelSize.width / 2,+ y: visibleFrame.maxY - panelSize.height - Metrics.topInset,+ width: panelSize.width,+ height: panelSize.height+ )+ }++ private func mouseScreen() -> NSScreen? {+ let mouseLocation = NSEvent.mouseLocation+ return NSScreen.screens.first { screen in+ screen.frame.contains(mouseLocation)+ }+ }++ private enum Metrics {+ static let fallbackSize = NSSize(+ width: CodexStatusMenuView.menuWidth,+ height: 420+ )+ 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/GlobalHotKeyController.swift b/CodexBar/Controllers/GlobalHotKeyController.swiftindex 792d377..b5785eb 100644--- a/CodexBar/Controllers/GlobalHotKeyController.swift+++ b/CodexBar/Controllers/GlobalHotKeyController.swift@@ -7,15 +7,15 @@ final class GlobalHotKeyController {private var eventHandlerRef: EventHandlerRef?private var hotKeyRef: EventHotKeyRef?private var nextHotKeyID: UInt32 = 1-+init(onPressed: @escaping @MainActor () -> Void) {self.onPressed = onPressed}-+deinit {uninstall()}-+func install(shortcut: GlobalHotKeyShortcut) -> Bool {let newEventHandler = Self.makeEventHandler()var eventType = EventTypeSpec(@@ -24,7 +24,7 @@ final class GlobalHotKeyController {)let userData = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())var installedHandlerRef: EventHandlerRef?-+guard InstallEventHandler(GetApplicationEventTarget(),newEventHandler,@@ -35,7 +35,7 @@ final class GlobalHotKeyController {) == noErr else {return false}-+let hotKeyID = EventHotKeyID(signature: Self.hotKeySignature, id: nextHotKeyID)var registeredHotKeyRef: EventHotKeyRef?let status = RegisterEventHotKey(@@ -46,53 +46,53 @@ final class GlobalHotKeyController {0,®isteredHotKeyRef)-+guard status == noErr else {if let installedHandlerRef {RemoveEventHandler(installedHandlerRef)}return false}-+clearCurrentRegistration()-+eventHandler = newEventHandlereventHandlerRef = installedHandlerRefhotKeyRef = registeredHotKeyRefnextHotKeyID &+= 1return true}-+func uninstall() {clearCurrentRegistration()}-+private func clearCurrentRegistration() {if let hotKeyRef {UnregisterEventHotKey(hotKeyRef)self.hotKeyRef = nil}-+if let eventHandlerRef {RemoveEventHandler(eventHandlerRef)self.eventHandlerRef = nil}-+eventHandler = nil}-+private func handleHotKeyPressed() {Task { @MainActor [onPressed] inonPressed()}}-+private static func makeEventHandler() -> EventHandlerUPP {{ _, _, userData inguard let userData else {return noErr}-+let controller = Unmanaged<GlobalHotKeyController>.fromOpaque(userData).takeUnretainedValue()@@ -100,7 +100,7 @@ final class GlobalHotKeyController {return noErr}}-+private static let hotKeySignature: OSType = {let scalars = Array("CDBR".unicodeScalars)return scalars.reduce(UInt32(0)) { result, scalar indiff --git a/CodexBar/Controllers/HeatmapDetailPanelController.swift b/CodexBar/Controllers/HeatmapDetailPanelController.swiftindex 10a3723..b8b1ce1 100644--- a/CodexBar/Controllers/HeatmapDetailPanelController.swift+++ b/CodexBar/Controllers/HeatmapDetailPanelController.swift@@ -6,7 +6,7 @@ private final class DetailPanel: NSPanel {override var canBecomeKey: Bool {false}-+override var canBecomeMain: Bool {false}@@ -21,50 +21,50 @@ final class HeatmapDetailPanelController {private var visibilityGeneration = 0private var drawerTransition = DrawerTransition.idleprivate var pendingSideSwitchRequest: PanelRequest?- private weak var popoverWindow: NSWindow?-+ private weak var menuSurfaceWindow: NSWindow?+func update(context: UsageHeatmapHoverContext?,- relativeTo popoverWindow: NSWindow?,+ relativeTo menuSurfaceWindow: NSWindow?,contentView: NSView?) {guard let context else {hide()return}-- guard let popoverWindow else {++ guard let menuSurfaceWindow else {hide(immediate: true)return}-- show(context: context, relativeTo: popoverWindow, contentView: contentView)++ show(context: context, relativeTo: menuSurfaceWindow, contentView: contentView)}-+func hide(immediate: Bool = false, delayed: Bool = true) {cancelHideTask()visibilityGeneration += 1drawerTransition = .idlependingSideSwitchRequest = nil-+guard let panel, panel.isVisible else {return}-+guard !immediate else {resetDrawerVisualState(for: panel)drawerTransition = .idleorderOut(panel)return}-+let generation = visibilityGenerationlet side = currentSidehideTask = Task { @MainActor [weak self] inif delayed {try? await Task.sleep(for: .milliseconds(Metrics.hideDelayMilliseconds))}-+guard let self,!Task.isCancelled,generation == self.visibilityGeneration,@@ -72,7 +72,7 @@ final class HeatmapDetailPanelController {panel.isVisible else {return}-+self.drawerTransition = .exitinglet hidden = self.drawerHiddenTranslation(for: side, panelWidth: panel.frame.width)self.animateContentTranslation(@@ -85,7 +85,7 @@ final class HeatmapDetailPanelController {generation == self.visibilityGeneration else {return}-+self.orderOut(panel)self.setContentTranslation(0)self.drawerTransition = .idle@@ -94,24 +94,24 @@ final class HeatmapDetailPanelController {}}}-+private func show(context: UsageHeatmapHoverContext,- relativeTo popoverWindow: NSWindow,+ relativeTo menuSurfaceWindow: NSWindow,contentView: NSView?) {cancelHideTask()-+let panel = ensurePanel()let wasVisible = panel.isVisibleif wasVisible {- attach(panel, to: popoverWindow)+ attach(panel, to: menuSurfaceWindow)}-+let panelSize = UsageHeatmapDayDetailView.panelSize(showsWorkflowStats: context.showsWorkflowStats)let position = panelPosition(for: panelSize,- relativeTo: popoverWindow,+ relativeTo: menuSurfaceWindow,contentView: contentView,anchorScreenFrame: context.anchorScreenFrame,heatmapScreenFrame: context.heatmapScreenFrame,@@ -119,39 +119,39 @@ final class HeatmapDetailPanelController {preferredSide: context.preferredSide)let request = PanelRequest(context: context, position: position)-- panel.level = popoverWindow.level++ panel.level = menuSurfaceWindow.leveldefer {- restorePopoverKeyWindow(popoverWindow)+ restoreMenuSurfaceKeyWindow(menuSurfaceWindow)}-+if wasVisible {updateVisiblePanel(request, on: panel)return}-+visibilityGeneration += 1apply(request, to: panel)- showPanelWithDrawerAnimation(panel, relativeTo: popoverWindow)+ showPanelWithDrawerAnimation(panel, relativeTo: menuSurfaceWindow)}-+private func updateVisiblePanel(_ request: PanelRequest, on panel: NSPanel) {if drawerTransition == .switchingSide {pendingSideSwitchRequest = requestreturn}-+if currentSide != request.position.side {beginSideSwitch(on: panel, from: currentSide, to: request)return}-+let activeTransition = drawerTransitionif activeTransition != .entering {visibilityGeneration += 1}apply(request, to: panel)-+switch activeTransition {case .entering:return@@ -163,14 +163,14 @@ final class HeatmapDetailPanelController {resetDrawerVisualState(for: panel)}}-- private func showPanelWithDrawerAnimation(_ panel: NSPanel, relativeTo popoverWindow: NSWindow) {++ private func showPanelWithDrawerAnimation(_ panel: NSPanel, relativeTo menuSurfaceWindow: NSWindow) {let generation = visibilityGenerationlet hidden = drawerHiddenTranslation(for: currentSide, panelWidth: panel.frame.width)setContentTranslation(hidden)panel.alphaValue = 0- attach(panel, to: popoverWindow)- panel.order(.above, relativeTo: popoverWindow.windowNumber)+ attach(panel, to: menuSurfaceWindow)+ panel.order(.above, relativeTo: menuSurfaceWindow.windowNumber)drawerTransition = .enteringanimateContentTranslationAfterInitialLayout(from: hidden,@@ -178,7 +178,7 @@ final class HeatmapDetailPanelController {generation: generation)}-+private func beginSideSwitch(on panel: NSPanel,from sourceSide: UsageHeatmapDetailSide,@@ -188,7 +188,7 @@ final class HeatmapDetailPanelController {let generation = visibilityGenerationdrawerTransition = .switchingSidependingSideSwitchRequest = nil-+let hidden = drawerHiddenTranslation(for: sourceSide, panelWidth: panel.frame.width)animateContentTranslation(to: hidden,@@ -202,7 +202,7 @@ final class HeatmapDetailPanelController {panel.isVisible else {return}-+self.showHiddenSideSwitchRequest(self.nextSideSwitchRequest(fallback: request),on: panel,@@ -211,14 +211,14 @@ final class HeatmapDetailPanelController {}}}-+private func showHiddenSideSwitchRequest(_ request: PanelRequest, on panel: NSPanel, generation: Int) {let side = request.position.sidelet hidden = drawerHiddenTranslation(for: side, panelWidth: request.position.frame.width)setContentTranslation(hidden)apply(request, to: panel)setContentTranslation(hidden)-+animateContentTranslation(from: hidden,to: 0,@@ -231,31 +231,31 @@ final class HeatmapDetailPanelController {panel.isVisible else {return}-+self.drawerTransition = .idleself.setContentTranslation(0)self.handlePendingSideSwitchRequest(on: panel)}}}-+private func nextSideSwitchRequest(fallback request: PanelRequest) -> PanelRequest {guard let pendingSideSwitchRequest,pendingSideSwitchRequest.position.side == request.position.side else {return request}-+self.pendingSideSwitchRequest = nilreturn pendingSideSwitchRequest}-+private func handlePendingSideSwitchRequest(on panel: NSPanel) {guard let pendingSideSwitchRequest else {return}-+self.pendingSideSwitchRequest = nil-+if pendingSideSwitchRequest.position.side != currentSide {beginSideSwitch(on: panel, from: currentSide, to: pendingSideSwitchRequest)} else {@@ -263,12 +263,12 @@ final class HeatmapDetailPanelController {resetDrawerVisualState(for: panel)}}-+private func ensurePanel() -> NSPanel {if let panel {return panel}-+let panel = DetailPanel(contentRect: NSRect(origin: .zero, size: UsageHeatmapDayDetailView.panelSize(showsWorkflowStats: true)),styleMask: [.borderless, .nonactivatingPanel],@@ -287,36 +287,36 @@ final class HeatmapDetailPanelController {self.panel = panelreturn panel}-+private func attach(_ panel: NSPanel, to parentWindow: NSWindow) {- popoverWindow = parentWindow+ menuSurfaceWindow = parentWindowguard panel.parent !== parentWindow else {return}-+panel.parent?.removeChildWindow(panel)parentWindow.addChildWindow(panel, ordered: .above)}-+private func orderOut(_ panel: NSPanel) {- let parentWindow = panel.parent ?? popoverWindow+ let parentWindow = panel.parent ?? menuSurfaceWindowpanel.orderOut(nil)parentWindow?.removeChildWindow(panel)- restorePopoverKeyWindow(parentWindow)+ restoreMenuSurfaceKeyWindow(parentWindow)}-- private func restorePopoverKeyWindow(_ popoverWindow: NSWindow?) {++ private func restoreMenuSurfaceKeyWindow(_ menuSurfaceWindow: NSWindow?) {guard NSApplication.shared.isActive else {return}-- popoverWindow?.makeKey()++ menuSurfaceWindow?.makeKey()}-+private func updateContent(_ context: UsageHeatmapHoverContext) {let rootView = UsageHeatmapDayDetailView(context: context)let size = UsageHeatmapDayDetailView.panelSize(showsWorkflowStats: context.showsWorkflowStats)-+if let hostingController {hostingController.rootView = rootView} else {@@ -325,16 +325,16 @@ final class HeatmapDetailPanelController {panel?.contentViewController = hostingControllerself.hostingController = hostingController}-+configurePanelLayers()panel?.setContentSize(size)}-+private func configurePanelLayers() {if let hostingView = hostingController?.view {configurePanelLayer(for: hostingView)}-+if let contentView = panel?.contentView {configurePanelLayer(for: contentView)if let frameView = contentView.superview {@@ -342,14 +342,14 @@ final class HeatmapDetailPanelController {}}}-+private func apply(_ request: PanelRequest, to panel: NSPanel) {updateContent(request.context)panel.setFrame(request.position.frame, display: true)panel.alphaValue = 1currentSide = request.position.side}-+private func configurePanelLayer(for view: NSView) {view.wantsLayer = trueview.layer?.backgroundColor = NSColor.clear.cgColor@@ -357,20 +357,20 @@ final class HeatmapDetailPanelController {view.layer?.cornerRadius = UsageHeatmapDayDetailView.panelCornerRadiusview.layer?.cornerCurve = .continuous}-+private func panelPosition(for panelSize: CGSize,- relativeTo popoverWindow: NSWindow,+ relativeTo menuSurfaceWindow: NSWindow,contentView: NSView?,anchorScreenFrame: CGRect?,heatmapScreenFrame: CGRect?,showsWorkflowStats: Bool,preferredSide: UsageHeatmapDetailSide) -> PanelPosition {- let popoverFrame = contentScreenFrame(for: contentView, in: popoverWindow) ?? popoverWindow.frame- let visibleFrame = (popoverWindow.screen ?? NSScreen.main)?.visibleFrame ?? popoverFrame- let leftX = popoverFrame.minX - Metrics.panelGap - panelSize.width- let rightX = popoverFrame.maxX + Metrics.panelGap+ let menuSurfaceFrame = contentScreenFrame(for: contentView, in: menuSurfaceWindow) ?? menuSurfaceWindow.frame+ let visibleFrame = (menuSurfaceWindow.screen ?? NSScreen.main)?.visibleFrame ?? menuSurfaceFrame+ let leftX = menuSurfaceFrame.minX - Metrics.panelGap - panelSize.width+ let rightX = menuSurfaceFrame.maxX + Metrics.panelGaplet horizontal = horizontalPlacement(preferredSide: preferredSide,left: HorizontalPlacement(@@ -384,7 +384,7 @@ final class HeatmapDetailPanelController {isAvailable: rightX + panelSize.width <= visibleFrame.maxX - Metrics.screenPadding))-+let x = clamped(horizontal.x,lower: visibleFrame.minX + Metrics.screenPadding,@@ -394,7 +394,7 @@ final class HeatmapDetailPanelController {x: x,y: panelY(for: panelSize,- popoverFrame: popoverFrame,+ menuSurfaceFrame: menuSurfaceFrame,visibleFrame: visibleFrame,anchorScreenFrame: anchorScreenFrame,heatmapScreenFrame: heatmapScreenFrame,@@ -403,21 +403,21 @@ final class HeatmapDetailPanelController {width: panelSize.width,height: panelSize.height)-+return PanelPosition(frame: frame,side: actualSide(forX: x,panelWidth: panelSize.width,- popoverFrame: popoverFrame,+ menuSurfaceFrame: menuSurfaceFrame,fallback: horizontal.side))}-+private func panelY(for panelSize: CGSize,- popoverFrame: CGRect,+ menuSurfaceFrame: CGRect,visibleFrame: CGRect,anchorScreenFrame: CGRect?,heatmapScreenFrame: CGRect?,@@ -425,22 +425,22 @@ final class HeatmapDetailPanelController {) -> CGFloat {let proposedY: CGFloatif showsWorkflowStats {- proposedY = popoverFrame.minY+ proposedY = menuSurfaceFrame.minY} else if let heatmapScreenFrame {proposedY = heatmapScreenFrame.maxY - panelSize.height} else if let anchorScreenFrame {proposedY = anchorScreenFrame.maxY - panelSize.height} else {- proposedY = popoverFrame.midY - panelSize.height / 2+ proposedY = menuSurfaceFrame.midY - panelSize.height / 2}-+return clamped(proposedY,- lower: max(visibleFrame.minY + Metrics.screenPadding, popoverFrame.minY),+ lower: max(visibleFrame.minY + Metrics.screenPadding, menuSurfaceFrame.minY),upper: visibleFrame.maxY - panelSize.height - Metrics.screenPadding)}-+private func horizontalPlacement(preferredSide: UsageHeatmapDetailSide,left: HorizontalPlacement,@@ -448,33 +448,33 @@ final class HeatmapDetailPanelController {) -> HorizontalPlacement {let primary = preferredSide == .left ? left : rightlet fallback = preferredSide == .left ? right : left-+if primary.isAvailable {return primary}return fallback.isAvailable ? fallback : primary}-+private func actualSide(forX x: CGFloat,panelWidth: CGFloat,- popoverFrame: CGRect,+ menuSurfaceFrame: CGRect,fallback: UsageHeatmapDetailSide) -> UsageHeatmapDetailSide {- if x + panelWidth <= popoverFrame.minX {+ if x + panelWidth <= menuSurfaceFrame.minX {return .left}- if x >= popoverFrame.maxX {+ if x >= menuSurfaceFrame.maxX {return .right}return fallback}-+private func cancelHideTask() {hideTask?.cancel()hideTask = nil}-+private func drawerHiddenTranslation(for side: UsageHeatmapDetailSide, panelWidth: CGFloat) -> CGFloat {let distance = panelWidth + Metrics.drawerOverscanswitch side {@@ -484,19 +484,19 @@ final class HeatmapDetailPanelController {return -distance}}-+private func setContentTranslation(_ translationX: CGFloat) {guard let layer = hostingController?.view.layer else {return}-+CATransaction.begin()CATransaction.setDisableActions(true)layer.removeAnimation(forKey: Metrics.drawerTransformAnimationKey)layer.transform = CATransform3DMakeTranslation(translationX, 0, 0)CATransaction.commit()}-+private func animateContentTranslation(from fromTranslationX: CGFloat? = nil,to translationX: CGFloat,@@ -508,11 +508,11 @@ final class HeatmapDetailPanelController {completion?()return}-+let targetTransform = CATransform3DMakeTranslation(translationX, 0, 0)CATransaction.begin()CATransaction.setCompletionBlock(completion)-+let animation = CABasicAnimation(keyPath: "transform")animation.fromValue = fromTranslationX.map { CATransform3DMakeTranslation($0, 0, 0) }?? layer.presentation()?.transform@@ -522,10 +522,10 @@ final class HeatmapDetailPanelController {animation.timingFunction = CAMediaTimingFunction(name: timing)layer.add(animation, forKey: Metrics.drawerTransformAnimationKey)layer.transform = targetTransform-+CATransaction.commit()}-+private func animateContentTranslationAfterInitialLayout(from hiddenTranslationX: CGFloat,panel: NSPanel,@@ -534,7 +534,7 @@ final class HeatmapDetailPanelController {panel.contentView?.layoutSubtreeIfNeeded()panel.displayIfNeeded()CATransaction.flush()-+Task { @MainActor [weak self, weak panel] inawait Task.yield()guard let self,@@ -543,7 +543,7 @@ final class HeatmapDetailPanelController {generation == self.visibilityGeneration else {return}-+self.setContentTranslation(hiddenTranslationX)panel.contentView?.layoutSubtreeIfNeeded()panel.displayIfNeeded()@@ -560,42 +560,42 @@ final class HeatmapDetailPanelController {generation == self.visibilityGeneration else {return}-+self.drawerTransition = .idleself.setContentTranslation(0)}}}}-+private func resetDrawerVisualState(for panel: NSPanel) {setContentTranslation(0)panel.alphaValue = 1}-+private func contentScreenFrame(for contentView: NSView?, in window: NSWindow) -> CGRect? {guard let contentView else {return nil}-+contentView.layoutSubtreeIfNeeded()let frameInWindow = contentView.convert(contentView.bounds, to: nil)let screenFrame = window.convertToScreen(frameInWindow)guard screenFrame.width > 0, screenFrame.height > 0 else {return nil}-+return screenFrame}-+private func clamped(_ value: CGFloat, lower: CGFloat, upper: CGFloat) -> CGFloat {guard lower <= upper else {return lower}-+return min(max(value, lower), upper)}-+private enum Metrics {static let panelGap: CGFloat = 4static let screenPadding: CGFloat = 8@@ -605,25 +605,25 @@ final class HeatmapDetailPanelController {static let drawerOverscan: CGFloat = 1static let drawerTransformAnimationKey = "CodexBar.heatmapDetailDrawerTransform"}-+private enum DrawerTransition {case idlecase enteringcase exitingcase switchingSide}-+private struct PanelPosition {let frame: NSRectlet side: UsageHeatmapDetailSide}-+private struct HorizontalPlacement {let x: CGFloatlet side: UsageHeatmapDetailSidelet isAvailable: Bool}-+private struct PanelRequest {let context: UsageHeatmapHoverContextlet position: PanelPositiondiff --git a/CodexBar/Controllers/HostingWindowController.swift b/CodexBar/Controllers/HostingWindowController.swiftindex e986ab4..99f068f 100644--- a/CodexBar/Controllers/HostingWindowController.swift+++ b/CodexBar/Controllers/HostingWindowController.swift@@ -3,11 +3,11 @@ import AppKit@MainActorfinal class AuxiliaryHostingWindow: NSWindow {var allowsKeyFocus = true-+override var canBecomeKey: Bool {allowsKeyFocus}-+override var canBecomeMain: Bool {false}@@ -18,11 +18,11 @@ final class AuxiliaryHostingWindow: NSWindow {class HostingWindowController {let screenProvider: () -> NSScreen?private(set) var window: NSWindow?-+init(screenProvider: @escaping () -> NSScreen?) {self.screenProvider = screenProvider}-+func open() {let target: NSWindowif let window {@@ -32,51 +32,51 @@ class HostingWindowController {target.isReleasedWhenClosed = falsewindow = target}-+applyWindowPresentationPolicy(target)-+if !target.isVisible {prepareForDisplay(target)}-+bringToFront(target)}-+func makeWindow() -> NSWindow {fatalError("subclass must override makeWindow()")}-+func applyWindowPresentationPolicy(_ window: NSWindow) {window.level = .normal// 重新打开时跟随到当前桌面, 避免把用户切回窗口旧桌面window.collectionBehavior.insert(.moveToActiveSpace)}-+func prepareForDisplay(_ window: NSWindow) {center(window)}-+func bringToFront(_ window: NSWindow) {if window.isMiniaturized {window.deminiaturize(nil)}-+(window as? AuxiliaryHostingWindow)?.allowsKeyFocus = truewindow.orderFrontRegardless()NSRunningApplication.current.activate(options: [])window.makeKeyAndOrderFront(nil)}-+func setAllowsKeyFocus(_ allowsKeyFocus: Bool) {(window as? AuxiliaryHostingWindow)?.allowsKeyFocus = allowsKeyFocus}-+func center(_ window: NSWindow) {guard let screen = screenProvider() ?? window.screen ?? NSScreen.main else {window.center()return}-+let visibleFrame = screen.visibleFramelet windowFrame = window.framewindow.setFrameOrigin(diff --git a/CodexBar/Controllers/LogWindowController.swift b/CodexBar/Controllers/LogWindowController.swiftindex 206583a..414a24e 100644--- a/CodexBar/Controllers/LogWindowController.swift+++ b/CodexBar/Controllers/LogWindowController.swift@@ -4,7 +4,7 @@ import SwiftUI@MainActorfinal class LogWindowController: HostingWindowController {private let store: RequestLogStore-+init(store: RequestLogStore = .shared,screenProvider: @escaping () -> NSScreen?@@ -12,10 +12,10 @@ final class LogWindowController: HostingWindowController {self.store = storesuper.init(screenProvider: screenProvider)}-+override func makeWindow() -> NSWindow {let hostingController = NSHostingController(rootView: LogView(store: store))-+let window = AuxiliaryHostingWindow(contentViewController: hostingController)window.title = "CodexBar 日志"window.styleMask = [.titled, .closable, .miniaturizable, .resizable]@@ -23,7 +23,7 @@ final class LogWindowController: HostingWindowController {window.setContentSize(Metrics.defaultContentSize)return window}-+private enum Metrics {static let minimumContentSize = NSSize(width: 640, height: 480)static let defaultContentSize = NSSize(width: 900, height: 680)diff --git a/CodexBar/Controllers/PopoverDismissMonitor.swift b/CodexBar/Controllers/MenuSurfaceDismissMonitor.swiftsimilarity index 76%rename from CodexBar/Controllers/PopoverDismissMonitor.swiftrename to CodexBar/Controllers/MenuSurfaceDismissMonitor.swiftindex 7eda210..88cc623 100644--- a/CodexBar/Controllers/PopoverDismissMonitor.swift+++ b/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift@@ -1,52 +1,55 @@import AppKit@MainActor-final class PopoverDismissMonitor {- private let popover: NSPopover+final class MenuSurfaceDismissMonitor {+ private let isPresented: () -> Bool+ private let windowProvider: () -> NSWindow?private let statusButtonProvider: () -> NSStatusBarButton?private var localEventMonitor: Any?private var globalMouseEventMonitor: Any?private var appResignActiveObserver: NSObjectProtocol?private var workspaceActivateObserver: NSObjectProtocol?- private var popoverWindowResignKeyObserver: NSObjectProtocol?+ private var activeMenuSurfaceWindowResignKeyObserver: NSObjectProtocol?private var deferredWindowFocusTask: Task<Void, Never>?private var suppressActivationDismissTask: Task<Void, Never>?private var suppressesActivationDismiss = falseprivate var onDismiss: (() -> Void)?-+init(- popover: NSPopover,+ isPresented: @escaping () -> Bool,+ windowProvider: @escaping () -> NSWindow?,statusButtonProvider: @escaping () -> NSStatusBarButton?) {- self.popover = popover+ self.isPresented = isPresented+ self.windowProvider = windowProviderself.statusButtonProvider = statusButtonProvider}-+func install(onDismiss: @escaping () -> Void) {remove()self.onDismiss = onDismiss-+localEventMonitor = NSEvent.addLocalMonitorForEvents(matching: Metrics.dismissEventMask) { [weak self] event inguard let self else {return event}-+if self.handleKeyEvent(event) {return nil}-+self.dismissIfNeeded(for: event)- self.restabilizePopoverChromeAfterEvent()+ self.restabilizeActiveMenuSurfaceChromeAfterEvent()return event}-+globalMouseEventMonitor = NSEvent.addGlobalMonitorForEvents(matching: Metrics.mouseDismissEventMask) { [weak self] _ inlet screenPoint = NSEvent.mouseLocationTask { @MainActor [weak self, screenPoint] inself?.dismissIfNeeded(at: screenPoint)}}-+appResignActiveObserver = NotificationCenter.default.addObserver(forName: NSApplication.willResignActiveNotification,object: NSApplication.shared,@@ -56,7 +59,7 @@ final class PopoverDismissMonitor {self?.scheduleDismissForActivationChange()}}-+workspaceActivateObserver = NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.didActivateApplicationNotification,object: nil,@@ -65,23 +68,23 @@ final class PopoverDismissMonitor {let activatedProcessIdentifier = (notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication)?.processIdentifier-+Task { @MainActor [weak self, activatedProcessIdentifier] inself?.dismissIfDifferentApplication(processIdentifier: activatedProcessIdentifier)}}-- installPopoverWindowObserverAndFocus()++ installActiveMenuSurfaceWindowObserverAndFocus()deferredWindowFocusTask = Task { @MainActor [weak self] inawait Task.yield()- guard let self, !Task.isCancelled, self.popover.isShown else {+ guard let self, !Task.isCancelled, self.isPresented() else {return}-- self.installPopoverWindowObserverAndFocus()++ self.installActiveMenuSurfaceWindowObserverAndFocus()}}-+func remove() {onDismiss = nildeferredWindowFocusTask?.cancel()@@ -93,23 +96,23 @@ final class PopoverDismissMonitor {removeEventMonitor(&globalMouseEventMonitor)removeObserver(&appResignActiveObserver)removeObserver(&workspaceActivateObserver, center: NSWorkspace.shared.notificationCenter)- removeObserver(&popoverWindowResignKeyObserver)+ removeObserver(&activeMenuSurfaceWindowResignKeyObserver)}-- private func installPopoverWindowObserverAndFocus() {- installPopoverWindowObserver()- focusPopoverWindow()++ private func installActiveMenuSurfaceWindowObserverAndFocus() {+ installActiveMenuSurfaceWindowObserver()+ focusActiveMenuSurfaceWindow()}-- private func installPopoverWindowObserver() {- removeObserver(&popoverWindowResignKeyObserver)- guard let popoverWindow = popover.contentViewController?.view.window else {++ private func installActiveMenuSurfaceWindowObserver() {+ removeObserver(&activeMenuSurfaceWindowResignKeyObserver)+ guard let activeMenuSurfaceWindow = windowProvider() else {return}-- popoverWindowResignKeyObserver = NotificationCenter.default.addObserver(++ activeMenuSurfaceWindowResignKeyObserver = NotificationCenter.default.addObserver(forName: NSWindow.didResignKeyNotification,- object: popoverWindow,+ object: activeMenuSurfaceWindow,queue: .main) { [weak self] _ inTask { @MainActor [weak self] in@@ -117,59 +120,59 @@ final class PopoverDismissMonitor {}}}-+private nonisolated func scheduleDismiss() {Task { @MainActor [weak self] inself?.dismiss()}}-+private func scheduleDismissForActivationChange() {guard !suppressesActivationDismiss else {return}-+scheduleDismiss()}-+private func dismiss() {- guard popover.isShown else {+ guard isPresented() else {return}-+onDismiss?()}-+private func dismissIfDifferentApplication(processIdentifier: pid_t?) {guard !suppressesActivationDismiss else {return}-+if let processIdentifier, processIdentifier == NSRunningApplication.current.processIdentifier {return}-+dismiss()}-- private func focusPopoverWindow() {- guard popover.isShown,- let popoverWindow = popover.contentViewController?.view.window else {++ private func focusActiveMenuSurfaceWindow() {+ guard isPresented(),+ let activeMenuSurfaceWindow = windowProvider() else {return}-- popoverWindow.orderFrontRegardless()++ activeMenuSurfaceWindow.orderFrontRegardless()NSRunningApplication.current.activate(options: [])- popoverWindow.makeKeyAndOrderFront(nil)+ activeMenuSurfaceWindow.makeKeyAndOrderFront(nil)}-+private func removeEventMonitor(_ monitor: inout Any?) {if let currentMonitor = monitor {NSEvent.removeMonitor(currentMonitor)monitor = nil}}-+private func removeObserver(_ observer: inout NSObjectProtocol?,center: NotificationCenter = .default@@ -179,31 +182,31 @@ final class PopoverDismissMonitor {observer = nil}}-+private func handleKeyEvent(_ event: NSEvent) -> Bool {- guard popover.isShown, event.type == .keyDown else {+ guard isPresented(), event.type == .keyDown else {return false}-+if event.keyCode == Metrics.escapeKeyCode {dismiss()return true}-+if isCommandShortcut(event, keyCode: Metrics.tabKeyCode) {dismiss()} else if isCommandShortcut(event, keyCode: Metrics.spaceKeyCode) {suppressNextActivationDismiss()}-+return false}-+private func isCommandShortcut(_ event: NSEvent, keyCode: UInt16) -> Bool {let modifierFlags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)return modifierFlags.contains(.command) && event.keyCode == keyCode}-+private func suppressNextActivationDismiss() {suppressActivationDismissTask?.cancel()suppressesActivationDismiss = true@@ -212,32 +215,32 @@ final class PopoverDismissMonitor {guard let self, !Task.isCancelled else {return}-+self.suppressesActivationDismiss = falseself.suppressActivationDismissTask = nil}}-+private func dismissIfNeeded(for event: NSEvent) {- guard popover.isShown, isMouseDismissEvent(event) else {+ guard isPresented(), isMouseDismissEvent(event) else {return}-+dismissIfNeeded(at: screenPoint(for: event))}-+private func dismissIfNeeded(at screenPoint: NSPoint) {- guard popover.isShown else {+ guard isPresented() else {return}-- if isScreenPointInsidePopover(screenPoint) || isScreenPointInsideStatusButton(screenPoint) {++ if isScreenPointInsideActiveMenuSurface(screenPoint) || isScreenPointInsideStatusButton(screenPoint) {return}-+dismiss()}-+private func isMouseDismissEvent(_ event: NSEvent) -> Bool {switch event.type {case .leftMouseDown, .rightMouseDown, .otherMouseDown:@@ -246,61 +249,61 @@ final class PopoverDismissMonitor {return false}}-- private func restabilizePopoverChromeAfterEvent() {++ private func restabilizeActiveMenuSurfaceChromeAfterEvent() {Task { @MainActor [weak self] inawait Task.yield()- guard let self, self.popover.isShown else {+ guard let self, self.isPresented() else {return}-- self.stabilizePopoverChromeAppearance()++ self.stabilizeActiveMenuSurfaceChromeAppearance()}}-- private func stabilizePopoverChromeAppearance() {- guard let rootView = popover.contentViewController?.view.window?.contentView else {++ private func stabilizeActiveMenuSurfaceChromeAppearance() {+ guard let rootView = windowProvider()?.contentView else {return}-- // NSPopover 会在点击后重新强调 NSVisualEffectView, 这里固定为 inactive 避免背景明暗跳变++ // AppKit 会在点击后重新强调 NSVisualEffectView, 这里固定为 inactive 避免背景明暗跳变stabilizeVisualEffectViews(in: rootView)}-+private func stabilizeVisualEffectViews(in view: NSView) {if let visualEffectView = view as? NSVisualEffectView {visualEffectView.state = .inactivevisualEffectView.isEmphasized = false}-+for subview in view.subviews {stabilizeVisualEffectViews(in: subview)}}-+private func screenPoint(for event: NSEvent) -> NSPoint {event.window?.convertPoint(toScreen: event.locationInWindow) ?? NSEvent.mouseLocation}-- private func isScreenPointInsidePopover(_ screenPoint: NSPoint) -> Bool {- guard let popoverWindow = popover.contentViewController?.view.window else {++ private func isScreenPointInsideActiveMenuSurface(_ screenPoint: NSPoint) -> Bool {+ guard let activeMenuSurfaceWindow = windowProvider() else {return false}-- return popoverWindow.frame.contains(screenPoint)++ return activeMenuSurfaceWindow.frame.contains(screenPoint)}-+private func isScreenPointInsideStatusButton(_ screenPoint: NSPoint) -> Bool {guard let button = statusButtonProvider(),let buttonWindow = button.window else {return false}-+let buttonRectInWindow = button.convert(button.bounds, to: nil)let buttonScreenRect = buttonWindow.convertToScreen(buttonRectInWindow)return buttonScreenRect.contains(screenPoint)}-+private enum Metrics {static let mouseDismissEventMask: NSEvent.EventTypeMask = [.leftMouseDown,diff --git a/CodexBar/Controllers/PopoverFadeCoordinator.swift b/CodexBar/Controllers/MenuSurfaceFadeCoordinator.swiftsimilarity index 50%rename from CodexBar/Controllers/PopoverFadeCoordinator.swiftrename to CodexBar/Controllers/MenuSurfaceFadeCoordinator.swiftindex c4ea85f..b811548 100644--- a/CodexBar/Controllers/PopoverFadeCoordinator.swift+++ b/CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift@@ -1,97 +1,102 @@import AppKit@MainActor-final class PopoverFadeCoordinator {- private let popover: NSPopover- private var openTask: Task<Void, Never>?- private var closeTask: Task<Void, Never>?- private var generation = 0-- init(popover: NSPopover) {- self.popover = popover+final class MenuSurfaceFadeCoordinator {+ private let contentViewProvider: () -> NSView?+ private let closeActiveMenuSurface: () -> Void+ private var fadeInCompletionTask: Task<Void, Never>?+ private var fadeOutCompletionTask: Task<Void, Never>?+ private var fadeGeneration = 0++ init(+ contentViewProvider: @escaping () -> NSView?,+ closeActiveMenuSurface: @escaping () -> Void+ ) {+ self.contentViewProvider = contentViewProvider+ self.closeActiveMenuSurface = closeActiveMenuSurface}-+func cancel() {- openTask?.cancel()- openTask = nil- closeTask?.cancel()- closeTask = nil+ fadeInCompletionTask?.cancel()+ fadeInCompletionTask = nil+ fadeOutCompletionTask?.cancel()+ fadeOutCompletionTask = nil}-+func prepareForFadeIn() {contentView?.alphaValue = 0contentView?.window?.alphaValue = 0}-+func resetAlpha() {contentView?.alphaValue = 1contentView?.window?.alphaValue = 1}-+func fadeIn(duration: TimeInterval, completion: @escaping () -> Void) {let operationGeneration = nextGeneration()fade(to: 1, duration: duration)-- openTask = Task { @MainActor [weak self] in++ fadeInCompletionTask = Task { @MainActor [weak self] intry? await Task.sleep(for: .milliseconds(Int(duration * 1000)))- guard let self, !Task.isCancelled, self.generation == operationGeneration else {+ guard let self, !Task.isCancelled, self.fadeGeneration == operationGeneration else {return}-+self.resetAlpha()- self.openTask = nil+ self.fadeInCompletionTask = nilcompletion()}}-+func fadeOut(duration: TimeInterval, completion: @escaping () -> Void) -> Bool {guard let contentView else {return false}-+let operationGeneration = nextGeneration()- let popoverWindow = contentView.window+ let activeMenuSurfaceWindow = contentView.windowfade(to: 0, duration: duration)-- closeTask = Task { @MainActor [weak self, weak contentView, weak popoverWindow] in++ fadeOutCompletionTask = Task { @MainActor [weak self, weak contentView, weak activeMenuSurfaceWindow] intry? await Task.sleep(for: .milliseconds(Int(duration * 1000)))- guard let self, !Task.isCancelled, self.generation == operationGeneration else {+ guard let self, !Task.isCancelled, self.fadeGeneration == operationGeneration else {return}-- self.popover.performClose(nil)++ self.closeActiveMenuSurface()contentView?.alphaValue = 1- popoverWindow?.alphaValue = 1- self.closeTask = nil+ activeMenuSurfaceWindow?.alphaValue = 1+ self.fadeOutCompletionTask = nilcompletion()}-+return true}-+private var contentView: NSView? {- popover.contentViewController?.view+ contentViewProvider()}-+private func nextGeneration() -> Int {- generation += 1- return generation+ fadeGeneration += 1+ return fadeGeneration}-+private func fade(to alpha: CGFloat, duration: TimeInterval) {guard let contentView else {return}-- let popoverWindow = contentView.window++ let activeMenuSurfaceWindow = contentView.windowif alpha == 1 {- popoverWindow?.alphaValue = 0+ activeMenuSurfaceWindow?.alphaValue = 0}-+NSAnimationContext.runAnimationGroup { context incontext.duration = durationcontext.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)- popoverWindow?.animator().alphaValue = alpha+ activeMenuSurfaceWindow?.animator().alphaValue = alphacontentView.animator().alphaValue = alpha}}diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftindex 7eda423..b96f398 100644--- a/CodexBar/Controllers/SettingsWindowController.swift+++ b/CodexBar/Controllers/SettingsWindowController.swift@@ -7,7 +7,7 @@ final class SettingsWindowController: HostingWindowController {private let appUpdater: AppUpdaterprivate let codexHookSettings: CodexHookSettingsprivate let globalHotKeySettings: GlobalHotKeySettings-+init(viewModel: CodexStatusViewModel,appUpdater: AppUpdater,@@ -21,7 +21,7 @@ final class SettingsWindowController: HostingWindowController {self.globalHotKeySettings = globalHotKeySettingssuper.init(screenProvider: screenProvider)}-+override func makeWindow() -> NSWindow {let hostingController = NSHostingController(rootView: AppSettingsView(@@ -32,17 +32,17 @@ final class SettingsWindowController: HostingWindowController {.environmentObject(appUpdater))hostingController.sizingOptions = [.preferredContentSize]-+let window = AuxiliaryHostingWindow(contentViewController: hostingController)window.title = "CodexBar 设置"window.styleMask = [.titled, .closable, .miniaturizable]window.contentMinSize = Metrics.minimumContentSizereturn window}-+override func prepareForDisplay(_ window: NSWindow) {window.contentViewController?.view.layoutSubtreeIfNeeded()-+if let fittingSize = window.contentViewController?.view.fittingSize,fittingSize.width > 0,fittingSize.height > 0 {@@ -53,10 +53,10 @@ final class SettingsWindowController: HostingWindowController {))}-+super.prepareForDisplay(window)}-+private enum Metrics {static let minimumContentSize = NSSize(width: 420, height: 240)}diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex 5bc1bd5..0c7f8a2 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -9,9 +9,9 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {let codexHookSettings = CodexHookSettings()let globalHotKeySettings = GlobalHotKeySettings()let appUpdater = AppUpdater()-+private var statusItemController: StatusItemController?-+func applicationDidFinishLaunching(_ notification: Notification) {let controller = StatusItemController(viewModel: viewModel,@@ -23,7 +23,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {controller.install()statusItemController = controller}-+func applicationWillTerminate(_ notification: Notification) {statusItemController?.uninstall()}@@ -38,12 +38,16 @@ private final class StatusItemController: NSObject {private let appUpdater: AppUpdaterprivate let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)private let popover = NSPopover()- private let popoverVisibility = PopoverVisibilityState()+ private let menuSurfaceVisibility = MenuSurfaceVisibilityState()private let heatmapDetailPanelController = HeatmapDetailPanelController()+ private var activeMenuSurface = ActiveMenuSurface.noneprivate lazy var globalHotKeyController = GlobalHotKeyController { [weak self] in- self?.togglePopoverFromHotKey()+ self?.toggleMenuSurfaceFromHotKey()}-+ private lazy var fallbackPanelController = FallbackPanelController { [unowned self] in+ self.makeMenuHostingController(usesPreferredContentSize: false)+ }+private lazy var settingsWindowController = SettingsWindowController(viewModel: viewModel,appUpdater: appUpdater,@@ -55,20 +59,35 @@ private final class StatusItemController: NSObject {private lazy var logWindowController = LogWindowController { [weak self] inself?.statusItem.button?.window?.screen}- private lazy var popoverFadeCoordinator = PopoverFadeCoordinator(popover: popover)- private lazy var popoverDismissMonitor = PopoverDismissMonitor(popover: popover) { [weak self] in- self?.statusItem.button- }- private var deferredRefreshTask: Task<Void, Never>?- private var popoverState = PopoverState.hidden+ private lazy var menuSurfaceFadeCoordinator = MenuSurfaceFadeCoordinator(+ contentViewProvider: { [weak self] in+ self?.activeMenuSurfaceContentView+ },+ closeActiveMenuSurface: { [weak self] in+ self?.closeActiveMenuSurface()+ }+ )+ private lazy var menuSurfaceDismissMonitor = MenuSurfaceDismissMonitor(+ isPresented: { [weak self] in+ self?.isActiveMenuSurfaceVisible == true+ },+ windowProvider: { [weak self] in+ self?.activeMenuSurfaceWindow+ },+ statusButtonProvider: { [weak self] in+ self?.statusItem.button+ }+ )+ private var delayedStatusRefreshTask: Task<Void, Never>?+ private var menuSurfaceState = MenuSurfaceState.hiddenprivate var cancellables = Set<AnyCancellable>()private var isShowingErrorImage: Bool?private var registeredHotKeyShortcut: GlobalHotKeyShortcut?private var auxiliaryWindowFocusRestoreTask: Task<Void, Never>?-+private static let normalImage = makeStatusImage("person.fill.checkmark")private static let errorImage = makeStatusImage("person.fill.xmark")-+init(viewModel: CodexStatusViewModel,workflowStatsViewModel: WorkflowStatsViewModel,@@ -83,7 +102,7 @@ private final class StatusItemController: NSObject {self.appUpdater = appUpdatersuper.init()}-+private static func makeStatusImage(_ symbolName: String) -> NSImage? {let configuration = NSImage.SymbolConfiguration(pointSize: 16,@@ -95,7 +114,7 @@ private final class StatusItemController: NSObject {image?.isTemplate = truereturn image}-+func install() {configureStatusButton()configurePopover()@@ -104,49 +123,56 @@ private final class StatusItemController: NSObject {updateStatusImage()viewModel.startAutoRefresh()}-+func uninstall() {- closePopover(animated: false)+ closeMenuSurface(animated: false)auxiliaryWindowFocusRestoreTask?.cancel()setAuxiliaryWindowKeyFocus(true)globalHotKeyController.uninstall()cancellables.removeAll()NSStatusBar.system.removeStatusItem(statusItem)}-+private func configureStatusButton() {guard let button = statusItem.button else {return}-+button.target = selfbutton.action = #selector(statusItemClicked(_:))button.imagePosition = .imageOnlybutton.toolTip = "CodexBar"button.sendAction(on: [.leftMouseUp, .rightMouseUp])}-+private func configurePopover() {+ let hostingController = makeMenuHostingController(usesPreferredContentSize: true)++ popover.behavior = .applicationDefined+ popover.animates = false+ popover.contentViewController = hostingController+ }++ private func makeMenuHostingController(usesPreferredContentSize: Bool) -> NSHostingController<AnyView> {let rootView = CodexStatusMenuView(viewModel: viewModel,workflowStatsViewModel: workflowStatsViewModel,codexHookSettings: codexHookSettings,- popoverVisibility: popoverVisibility,+ menuSurfaceVisibility: menuSurfaceVisibility,onUsageHeatmapHoverChange: { [weak self] context inself?.updateHeatmapDetailPanel(context)}).environmentObject(appUpdater).frame(width: CodexStatusMenuView.menuWidth)-- let hostingController = NSHostingController(rootView: rootView)- hostingController.sizingOptions = [.preferredContentSize]-- popover.behavior = .applicationDefined- popover.animates = false- popover.contentViewController = hostingController++ let hostingController = NSHostingController(rootView: AnyView(rootView))+ if usesPreferredContentSize {+ hostingController.sizingOptions = [.preferredContentSize]+ }+ return hostingController}-+private func observeViewModel() {Publishers.CombineLatest(viewModel.$loadState, viewModel.$snapshot).map { loadState, snapshot in@@ -157,7 +183,7 @@ private final class StatusItemController: NSObject {self?.updateStatusImage(usesErrorImage: usesErrorImage)}.store(in: &cancellables)-+viewModel.$autoRefreshCountdownStartedAt.compactMap { $0 }.sink { [weak self] _ in@@ -168,7 +194,7 @@ private final class StatusItemController: NSObject {}.store(in: &cancellables)}-+private func observeGlobalHotKeySettings() {globalHotKeySettings.$shortcut.removeDuplicates()@@ -177,143 +203,213 @@ private final class StatusItemController: NSObject {}.store(in: &cancellables)}-+private func applyGlobalHotKey(_ shortcut: GlobalHotKeyShortcut?) {guard shortcut != registeredHotKeyShortcut else {return}-+guard let shortcut else {globalHotKeyController.uninstall()registeredHotKeyShortcut = nilreturn}-+if globalHotKeyController.install(shortcut: shortcut) {registeredHotKeyShortcut = shortcutglobalHotKeySettings.clearError()return}-+let message = hotKeyConflictMessage(for: shortcut)globalHotKeySettings.restoreShortcut(registeredHotKeyShortcut, message: message)}-+private func hotKeyConflictMessage(for shortcut: GlobalHotKeyShortcut) -> String {if shortcut == .default {return "默认快捷键 \(shortcut.label) 已被占用,请重新设置"}-+return "快捷键已被占用,请重新设置"}-+private func updateStatusImage() {updateStatusImage(usesErrorImage: viewModel.usesErrorImage)}-+private func updateStatusImage(usesErrorImage: Bool) {guard usesErrorImage != isShowingErrorImage else {return}-+isShowingErrorImage = usesErrorImagestatusItem.button?.image = usesErrorImage ? Self.errorImage : Self.normalImage}-+@objc private func statusItemClicked(_ sender: NSStatusBarButton) {guard let event = NSApplication.shared.currentEvent else {- togglePopover(relativeTo: sender)+ toggleMenuSurface(relativeTo: sender)return}-+if event.type == .rightMouseUp || event.modifierFlags.contains(.control) {showContextMenu(relativeTo: sender)} else {- togglePopover(relativeTo: sender)+ toggleMenuSurface(relativeTo: sender)}}-- private func togglePopover(relativeTo button: NSStatusBarButton) {- switch popoverState {- case .hidden:++ private func toggleMenuSurface(relativeTo button: NSStatusBarButton) {+ toggleMenuSurface {openPopover(relativeTo: button)+ }+ }++ private func toggleMenuSurface(open: () -> Void) {+ switch menuSurfaceState {+ case .hidden:+ open()case .opening, .shown:- closePopover()+ closeMenuSurface()case .closing:- finishPopoverClose()- openPopover(relativeTo: button)+ completeMenuSurfaceClose()+ open()}}-- private func togglePopoverFromHotKey() {- guard let button = statusItem.button else {++ private func toggleMenuSurfaceFromHotKey() {+ let targetScreen = screenContainingMouse() ?? NSScreen.main+ toggleMenuSurface {+ openMenuSurfaceFromHotKey(on: targetScreen)+ }+ }++ private func openMenuSurfaceFromHotKey(on targetScreen: NSScreen?) {+ guard let button = statusItem.button,+ isTrustedStatusItemAnchor(button, on: targetScreen) else {+ openFallbackPanel(on: targetScreen)return}-- togglePopover(relativeTo: button)++ openPopover(relativeTo: button)}-- private func cancelPopoverTasks() {- deferredRefreshTask?.cancel()- deferredRefreshTask = nil- popoverFadeCoordinator.cancel()++ private func isTrustedStatusItemAnchor(+ _ button: NSStatusBarButton,+ on targetScreen: NSScreen?+ ) -> Bool {+ guard let window = button.window,+ let screen = window.screen,+ !button.isHidden,+ !button.bounds.isEmpty else {+ return false+ }++ let buttonRectInWindow = button.convert(button.bounds, to: nil)+ let buttonScreenRect = window.convertToScreen(buttonRectInWindow)+ guard buttonScreenRect.hasFiniteGeometry,+ buttonScreenRect.width >= Metrics.minimumTrustedAnchorLength,+ buttonScreenRect.height >= Metrics.minimumTrustedAnchorLength else {+ return false+ }++ let trustedScreenFrame = (targetScreen ?? screen).frame.insetBy(+ dx: -Metrics.anchorScreenTolerance,+ dy: -Metrics.anchorScreenTolerance+ )+ return trustedScreenFrame.intersects(buttonScreenRect)}-++ private func screenContainingMouse() -> NSScreen? {+ let mouseLocation = NSEvent.mouseLocation+ return NSScreen.screens.first { screen in+ screen.frame.contains(mouseLocation)+ }+ }++ private func cancelMenuSurfaceTasks() {+ delayedStatusRefreshTask?.cancel()+ delayedStatusRefreshTask = nil+ menuSurfaceFadeCoordinator.cancel()+ }+private func openPopover(relativeTo button: NSStatusBarButton) {- cancelPopoverTasks()-- popoverState = .opening-- popoverFadeCoordinator.prepareForFadeIn()+ cancelMenuSurfaceTasks()++ menuSurfaceState = .opening+ activeMenuSurface = .popover++ menuSurfaceFadeCoordinator.prepareForFadeIn()popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)- popoverVisibility.isVisible = true+ completeMenuSurfaceOpen()+ }++ private func openFallbackPanel(on screen: NSScreen?) {+ cancelMenuSurfaceTasks()++ fallbackPanelController.prepareForDisplay(on: screen)+ menuSurfaceState = .opening+ activeMenuSurface = .fallbackPanel++ menuSurfaceFadeCoordinator.prepareForFadeIn()+ fallbackPanelController.show()+ completeMenuSurfaceOpen()+ }++ private func completeMenuSurfaceOpen() {+ menuSurfaceVisibility.isVisible = truerefreshWorkflowStatsIfHookEnabled(performMaintenance: false)- popoverDismissMonitor.install { [weak self] in- self?.closePopover()+ menuSurfaceDismissMonitor.install { [weak self] in+ self?.closeMenuSurface()}-- popoverFadeCoordinator.fadeIn(duration: Metrics.fadeInDuration) { [weak self] in- self?.popoverState = .shown++ menuSurfaceFadeCoordinator.fadeIn(duration: Metrics.fadeInDuration) { [weak self] in+ self?.menuSurfaceState = .shown}-- scheduleDeferredRefresh()++ scheduleDelayedStatusRefresh()}-+private func showContextMenu(relativeTo button: NSStatusBarButton) {- closePopover(animated: false)-+ closeMenuSurface(animated: false)+ presentStatusItemMenu(makeContextMenu(), relativeTo: button)+ }++ private func presentStatusItemMenu(_ menu: NSMenu, relativeTo button: NSStatusBarButton) {+ statusItem.menu = menu+ defer { statusItem.menu = nil }+ button.performClick(nil)+ }++ private func makeContextMenu() -> NSMenu {let menu = NSMenu()-+menu.addItem(menuItem(title: "设置",action: #selector(openSettings),keyEquivalent: ",",symbolName: "gearshape"))-+menu.addItem(menuItem(title: "日志",action: #selector(openLog),keyEquivalent: "l",symbolName: "doc.text.magnifyingglass"))-+menu.addItem(.separator())-+menu.addItem(menuItem(title: "退出",action: #selector(quit),keyEquivalent: "q",symbolName: "power"))-- menu.popUp(- positioning: nil,- at: NSPoint(x: 0, y: button.bounds.minY - 4),- in: button- )++ return menu}-+private func menuItem(title: String,action: Selector,@@ -329,76 +425,76 @@ private final class StatusItemController: NSObject {item.target = selfreturn item}-+@objc private func openSettings() {settingsWindowController.open()}-+@objc private func openLog() {logWindowController.open()}-+@objc private func quit() {NSApplication.shared.terminate(nil)}-- private func closePopover(animated: Bool = true) {- if popoverState == .closing && animated {++ private func closeMenuSurface(animated: Bool = true) {+ if menuSurfaceState == .closing && animated {return}-- cancelPopoverTasks()++ cancelMenuSurfaceTasks()heatmapDetailPanelController.hide(immediate: true, delayed: false)- popoverDismissMonitor.remove()- popoverVisibility.isVisible = false-- guard popover.isShown else {- popoverFadeCoordinator.resetAlpha()- popoverState = .hidden+ menuSurfaceDismissMonitor.remove()+ menuSurfaceVisibility.isVisible = false++ guard isActiveMenuSurfaceVisible else {+ menuSurfaceFadeCoordinator.resetAlpha()+ menuSurfaceState = .hidden+ activeMenuSurface = .nonereturn}-+guard animated else {suspendAuxiliaryWindowKeyFocus()- finishPopoverClose(hidesDetailPanel: false)+ completeMenuSurfaceClose(hidesDetailPanel: false)return}-+suspendAuxiliaryWindowKeyFocus()- popoverState = .closing- let didStartFadeOut = popoverFadeCoordinator.fadeOut(duration: Metrics.fadeOutDuration) { [weak self] in- self?.popoverState = .hidden+ menuSurfaceState = .closing+ let didStartFadeOut = menuSurfaceFadeCoordinator.fadeOut(duration: Metrics.fadeOutDuration) { [weak self] in+ self?.menuSurfaceState = .hiddenself?.scheduleAuxiliaryWindowKeyFocusRestore()}-+if !didStartFadeOut {- finishPopoverClose()+ completeMenuSurfaceClose()}}-- private func finishPopoverClose(hidesDetailPanel: Bool = true) {- cancelPopoverTasks()++ private func completeMenuSurfaceClose(hidesDetailPanel: Bool = true) {+ cancelMenuSurfaceTasks()if hidesDetailPanel {heatmapDetailPanelController.hide(immediate: true)}- popoverDismissMonitor.remove()-- if popover.isShown {- popover.performClose(nil)- }-- popoverVisibility.isVisible = false- popoverFadeCoordinator.resetAlpha()- popoverState = .hidden+ menuSurfaceDismissMonitor.remove()++ closeActiveMenuSurface()++ menuSurfaceVisibility.isVisible = false+ menuSurfaceFadeCoordinator.resetAlpha()+ menuSurfaceState = .hidden+ activeMenuSurface = .nonescheduleAuxiliaryWindowKeyFocusRestore()}-+private func suspendAuxiliaryWindowKeyFocus() {auxiliaryWindowFocusRestoreTask?.cancel()auxiliaryWindowFocusRestoreTask = nilsetAuxiliaryWindowKeyFocus(false)}-+private func scheduleAuxiliaryWindowKeyFocusRestore() {auxiliaryWindowFocusRestoreTask?.cancel()auxiliaryWindowFocusRestoreTask = Task { @MainActor [weak self] in@@ -406,61 +502,121 @@ private final class StatusItemController: NSObject {guard let self, !Task.isCancelled else {return}-+self.setAuxiliaryWindowKeyFocus(true)self.auxiliaryWindowFocusRestoreTask = nil}}-+private func setAuxiliaryWindowKeyFocus(_ allowsKeyFocus: Bool) {settingsWindowController.setAllowsKeyFocus(allowsKeyFocus)logWindowController.setAllowsKeyFocus(allowsKeyFocus)}-- private func scheduleDeferredRefresh() {- deferredRefreshTask?.cancel()- deferredRefreshTask = Task { @MainActor [weak self] in++ private func scheduleDelayedStatusRefresh() {+ delayedStatusRefreshTask?.cancel()+ delayedStatusRefreshTask = Task { @MainActor [weak self] intry? await Task.sleep(for: .milliseconds(160))- guard let self, !Task.isCancelled, self.popover.isShown else {+ guard let self, !Task.isCancelled, self.isActiveMenuSurfaceVisible else {return}-+self.viewModel.refreshIfNeeded()}}-+private func refreshWorkflowStatsIfHookEnabled(performMaintenance: Bool) {codexHookSettings.refresh()if codexHookSettings.isEnabled {workflowStatsViewModel.refreshIfNeeded(performMaintenance: performMaintenance)}}-+private func updateHeatmapDetailPanel(_ context: UsageHeatmapHoverContext?) {- guard popover.isShown,- let popoverContentView = popover.contentViewController?.view,- let popoverWindow = popoverContentView.window else {+ guard isActiveMenuSurfaceVisible,+ let menuSurfaceContentView = activeMenuSurfaceContentView,+ let menuSurfaceWindow = activeMenuSurfaceWindow else {heatmapDetailPanelController.hide(immediate: true)return}-+heatmapDetailPanelController.update(context: context,- relativeTo: popoverWindow,- contentView: popoverContentView+ relativeTo: menuSurfaceWindow,+ contentView: menuSurfaceContentView)}-++ private var isActiveMenuSurfaceVisible: Bool {+ switch activeMenuSurface {+ case .none:+ return false+ case .popover:+ return popover.isShown+ case .fallbackPanel:+ return fallbackPanelController.isVisible+ }+ }++ private var activeMenuSurfaceContentView: NSView? {+ switch activeMenuSurface {+ case .none:+ return nil+ case .popover:+ return popover.contentViewController?.view+ case .fallbackPanel:+ return fallbackPanelController.contentView+ }+ }++ private var activeMenuSurfaceWindow: NSWindow? {+ switch activeMenuSurface {+ case .none:+ return nil+ case .popover:+ return popover.contentViewController?.view.window+ case .fallbackPanel:+ return fallbackPanelController.window+ }+ }++ private func closeActiveMenuSurface() {+ if popover.isShown {+ popover.performClose(nil)+ }++ fallbackPanelController.orderOut()++ activeMenuSurface = .none+ }+private enum Metrics {static let fadeInDuration: TimeInterval = 0.24static let fadeOutDuration: TimeInterval = 0.18static let auxiliaryWindowKeyFocusRestoreDelayMilliseconds: UInt64 = 120+ static let minimumTrustedAnchorLength: CGFloat = 1+ static let anchorScreenTolerance: CGFloat = 1}-- private enum PopoverState {++ private enum MenuSurfaceState {case hiddencase openingcase showncase closing}++ private enum ActiveMenuSurface {+ case none+ case popover+ case fallbackPanel+ }+}++private extension CGRect {+ var hasFiniteGeometry: Bool {+ origin.x.isFinite &&+ origin.y.isFinite &&+ size.width.isFinite &&+ size.height.isFinite+ }}diff --git a/CodexBar/Models/CodexAccountModels.swift b/CodexBar/Models/CodexAccountModels.swiftindex 42c5019..48ebc60 100644--- a/CodexBar/Models/CodexAccountModels.swift+++ b/CodexBar/Models/CodexAccountModels.swift@@ -4,16 +4,16 @@ nonisolated struct CodexAccount: Decodable, Equatable {let type: Stringlet email: String?let planType: String?-+var hasEmail: Bool {email?.isEmpty == false}-+var displayName: String {if let email, hasEmail {return email}-+switch type {case "apiKey":return "API Key"diff --git a/CodexBar/Models/CodexQuotaModels.swift b/CodexBar/Models/CodexQuotaModels.swiftindex eb3b14c..15cd796 100644--- a/CodexBar/Models/CodexQuotaModels.swift+++ b/CodexBar/Models/CodexQuotaModels.swift@@ -8,23 +8,23 @@ nonisolated struct CodexQuotaSnapshot: Equatable {let usage: CodexUsageSnapshot?let isRateLimitsStale: Boollet isUsageStale: Bool-+var accountLabel: String {account.displayName}-+var planLabel: String? {account.planType ?? planType}-+var hasTrustedData: Bool {hasTrustedRateLimitsData || hasTrustedUsageData}-+private var hasTrustedRateLimitsData: Bool {!limits.isEmpty && !isRateLimitsStale}-+private var hasTrustedUsageData: Bool {usage != nil && !isUsageStale}@@ -34,14 +34,14 @@ nonisolated struct CodexQuotaLimitSnapshot: Equatable, Identifiable {let limitId: Stringlet limitName: String?let windows: [QuotaWindow]-+var id: String { limitId }-+var title: String {if let limitName, !limitName.isEmpty {return limitName.capitalizingFirstLetter()}-+return limitId.capitalizingFirstLetter()}}@@ -51,7 +51,7 @@ nonisolated private extension String {guard let first else {return self}-+return first.uppercased() + dropFirst()}}@@ -61,36 +61,36 @@ nonisolated struct QuotaWindow: Equatable, Identifiable {let windowDurationMins: Int?let usedPercent: Int?let resetsAt: Date?-+var label: String {Self.windowLabel(for: windowDurationMins)}-+var remainingPercent: Int {guard let usedPercent else {return 0}-+return max(0, min(100, 100 - usedPercent))}-+var hasData: Bool {usedPercent != nil}-+private static func windowLabel(for minutes: Int?) -> String {guard let minutes, minutes > 0 else {return "额度"}-+if minutes.isMultiple(of: 1_440) {return "\(minutes / 1_440)D"}-+if minutes.isMultiple(of: 60) {return "\(minutes / 60)H"}-+return "\(minutes)M"}}@@ -112,7 +112,7 @@ nonisolated struct RateLimitWindow: Decodable {let usedPercent: Int?let resetsAt: Int?let windowDurationMins: Int?-+var resetDate: Date? {guard let resetsAt else { return nil }return Date(timeIntervalSince1970: TimeInterval(resetsAt))@@ -131,17 +131,17 @@ nonisolated extension CodexQuotaSnapshot {guard let account = accountResponse.account else {throw CodexStatusError.notLoggedIn}-+let limits = rateLimitsResponse.map { response inSelf.orderedSnapshots(from: response).compactMap { entry inCodexQuotaLimitSnapshot(limitId: entry.limitId, snapshot: entry.snapshot)}} ?? []-+let usage = usageResponse.map {CodexUsageSnapshot(summary: $0.summary, dailyBuckets: $0.dailyUsageBuckets)}-+// rateLimits/usage 可同时为空, 账户有效时仍生成快照给 UI 展示"暂无数据"self.init(account: account,@@ -153,31 +153,31 @@ nonisolated extension CodexQuotaSnapshot {isUsageStale: isUsageStale)}-+// 展示顺序: 顶层 rateLimits 指向的主 limit 置顶, 其余按名称排序private static func orderedSnapshots(from response: AccountRateLimitsResponse) -> [(limitId: String, snapshot: RateLimitSnapshot)] {let primaryLimitId = response.rateLimits.limitId ?? "codex"-+guard let byLimitId = response.rateLimitsByLimitId, !byLimitId.isEmpty else {return [(primaryLimitId, response.rateLimits)]}-+return byLimitId.map { (limitId: $0.key, snapshot: $0.value) }.sorted { lhs, rhs inif (lhs.limitId == primaryLimitId) != (rhs.limitId == primaryLimitId) {return lhs.limitId == primaryLimitId}-+let lhsName = lhs.snapshot.limitName ?? lhs.limitIdlet rhsName = rhs.snapshot.limitName ?? rhs.limitIdlet nameOrder = lhsName.localizedStandardCompare(rhsName)if nameOrder != .orderedSame {return nameOrder == .orderedAscending}-+return lhs.limitId.localizedStandardCompare(rhs.limitId) == .orderedAscending}}@@ -189,11 +189,11 @@ nonisolated extension CodexQuotaLimitSnapshot {.compactMap { id, window inwindow.map { QuotaWindow(id: id, window: $0) }}-+guard !windows.isEmpty else {return nil}-+self.init(limitId: limitId,limitName: snapshot.limitName,diff --git a/CodexBar/Models/CodexStatusError.swift b/CodexBar/Models/CodexStatusError.swiftindex e820b3b..5148b9b 100644--- a/CodexBar/Models/CodexStatusError.swift+++ b/CodexBar/Models/CodexStatusError.swift@@ -8,7 +8,7 @@ nonisolated enum CodexStatusError: LocalizedError {case serverError(String)case unsupportedMethodcase notLoggedIn-+var errorDescription: String? {switch self {case .executableNotFound:@@ -17,12 +17,12 @@ nonisolated enum CodexStatusError: LocalizedError {return nil}}-+// codex app-server 未登录var isAuthenticationRequired: Bool {serverErrorMessageContains("codex account authentication required")}-+// codex app-server 不支持的方法var isUnsupportedMethod: Bool {switch self {@@ -32,15 +32,15 @@ nonisolated enum CodexStatusError: LocalizedError {return serverErrorMessageContains("Invalid request: unknown variant")}}-+var isRetriableServerError: Bool {guard case .serverError = self else {return false}-+return !isAuthenticationRequired && !isUnsupportedMethod}-+// 连接断开、超时、无法解析都需要重建 app-server 会话var isTransportFailure: Bool {switch self {@@ -50,12 +50,12 @@ nonisolated enum CodexStatusError: LocalizedError {return false}}-+private func serverErrorMessageContains(_ keyword: String) -> Bool {guard case .serverError(let message) = self else {return false}-+return message.range(of: keyword, options: .caseInsensitive) != nil}}diff --git a/CodexBar/Models/CodexUsageModels.swift b/CodexBar/Models/CodexUsageModels.swiftindex 1b3a455..44e9efe 100644--- a/CodexBar/Models/CodexUsageModels.swift+++ b/CodexBar/Models/CodexUsageModels.swift@@ -16,19 +16,19 @@ nonisolated struct UsageSummary: Decodable, Equatable {nonisolated struct DailyUsageBucket: Decodable, Equatable, Identifiable {let startDate: Stringlet tokens: Int-+var id: String { startDate }}nonisolated struct CodexUsageSnapshot: Equatable {let summary: UsageSummarylet dailyBuckets: [DailyUsageBucket]-+func tokenCount(on date: Date) -> Int? {let startDate = DateFormatter.codexDay.string(from: date)return tokensByDate[startDate]}-+// 给热力图生成按周排列的最近日期网格, 每列从周日开始func recentWeekGrid(columnCount: Int, endingDaysAgo: Int = 0, today: Date = Date()) -> [DailyUsageBucket?] {let tokenCountsByDate = tokensByDate@@ -47,7 +47,7 @@ nonisolated struct CodexUsageSnapshot: Equatable {}}}-+private var tokensByDate: [String: Int] {dailyBuckets.reduce(into: [String: Int]()) { result, bucket inresult[bucket.startDate, default: 0] += bucket.tokensdiff --git a/CodexBar/Models/CodexWeekGrid.swift b/CodexBar/Models/CodexWeekGrid.swiftindex 3fa2a4b..9cdf174 100644--- a/CodexBar/Models/CodexWeekGrid.swift+++ b/CodexBar/Models/CodexWeekGrid.swift@@ -2,7 +2,7 @@ import Foundationnonisolated enum CodexWeekGrid {static let rowCount = 7-+static func dates(columnCount: Int,endingDaysAgo: Int = 0,@@ -12,7 +12,7 @@ nonisolated enum CodexWeekGrid {guard columnCount > 0 else {return []}-+let todayStart = calendar.startOfDay(for: today)let lastVisibleDate = calendar.date(byAdding: .day,@@ -27,23 +27,23 @@ nonisolated enum CodexWeekGrid {) else {return []}-+return (0..<columnCount).flatMap { column -> [Date?] inguard let weekStart = calendar.date(byAdding: .weekOfYear, value: column, to: firstWeekStart) else {return Array(repeating: nil, count: rowCount)}-+return (0..<rowCount).map { weekdayOffset -> Date? inguard let date = calendar.date(byAdding: .day, value: weekdayOffset, to: weekStart),date <= lastVisibleDate else {return nil}-+return date}}}-+private static func sundayStartOfWeek(containing date: Date, calendar: Calendar) -> Date {let weekday = calendar.component(.weekday, from: date)let daysSinceSunday = weekday - 1diff --git a/CodexBar/Models/CodexWorkflowStatsModels.swift b/CodexBar/Models/CodexWorkflowStatsModels.swiftindex e337475..014fff9 100644--- a/CodexBar/Models/CodexWorkflowStatsModels.swift+++ b/CodexBar/Models/CodexWorkflowStatsModels.swift@@ -11,7 +11,7 @@ nonisolated enum WorkflowEventKind: String {case postCompact = "postcompact"case subagentStart = "subagentstart"case subagentStop = "subagentstop"-+init?(normalizedName: String) {self.init(rawValue: normalizedName)}@@ -22,24 +22,30 @@ private nonisolated enum WorkflowStatsJSON {let json = "{\(fields.joined(separator: ","))}"return Data(json.utf8) + Data([0x0A])}-+static func field<T: Encodable>(_ name: String, _ value: T?) throws -> String {"\"\(name)\":\(try Self.value(value))"}-+static func value<T: Encodable>(_ value: T?) throws -> String {guard let value else {return "null"}-+return try Self.value(value)}-+static func value<T: Encodable>(_ value: T) throws -> String {let encoder = JSONEncoder()encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]let data = try encoder.encode(value)- return String(decoding: data, as: UTF8.self)+ guard let text = String(bytes: data, encoding: .utf8) else {+ throw EncodingError.invalidValue(+ value,+ .init(codingPath: [], debugDescription: "Encoded workflow stats JSON was not UTF-8")+ )+ }+ return text}}@@ -52,7 +58,7 @@ nonisolated struct WorkflowHookEvent: Decodable, Equatable {let permissionMode: String?let sessionId: String?let turnId: String?-+init(timestamp: Date,name: String,@@ -72,7 +78,7 @@ nonisolated struct WorkflowHookEvent: Decodable, Equatable {self.sessionId = sessionIdself.turnId = turnId}-+init(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self)guard let timestampString = Self.string(from: container, key: .timestamp),@@ -86,7 +92,7 @@ nonisolated struct WorkflowHookEvent: Decodable, Equatable {.init(codingPath: decoder.codingPath, debugDescription: "Missing hook event name"))}-+self.timestamp = timestampself.name = nameself.directoryPath = Self.string(from: container, key: .cwd)@@ -96,28 +102,28 @@ nonisolated struct WorkflowHookEvent: Decodable, Equatable {self.sessionId = Self.string(from: container, key: .sessionId)self.turnId = Self.string(from: container, key: .turnId)}-+var kind: WorkflowEventKind? {WorkflowEventKind(normalizedName: normalizedName)}-+var projectDisplayName: String? {guard let directoryPath, !directoryPath.isEmpty else {return nil}-+let url = URL(fileURLWithPath: directoryPath).standardizedFileURLlet lastComponent = url.lastPathComponentreturn lastComponent.isEmpty ? directoryPath : lastComponent}-+private var normalizedName: String {name.replacingOccurrences(of: "_", with: "").replacingOccurrences(of: "-", with: "").lowercased()}-+private static func string(from container: KeyedDecodingContainer<CodingKeys>,key: CodingKeys@@ -128,14 +134,14 @@ nonisolated struct WorkflowHookEvent: Decodable, Equatable {return trimmedValue}}-+return nil}-+private static func date(from string: String) -> Date? {DateFormatter.codexLocalTimestamp.date(from: string)}-+func jsonLineData() throws -> Data {let fields = [try WorkflowStatsJSON.field("timestamp", DateFormatter.codexLocalTimestamp.string(from: timestamp)),@@ -147,10 +153,10 @@ nonisolated struct WorkflowHookEvent: Decodable, Equatable {try WorkflowStatsJSON.field("tool", toolName),try WorkflowStatsJSON.field("cwd", directoryPath)]-+return WorkflowStatsJSON.lineData(fields)}-+private enum CodingKeys: String, CodingKey {case timestampcase event@@ -173,9 +179,9 @@ nonisolated struct WorkflowDailyStats: Equatable, Identifiable {let contextCompactionCount: Intlet subagentCount: Intlet eventCount: Int-+var id: String { startDate }-+static func empty(startDate: String) -> WorkflowDailyStats {WorkflowDailyStats(startDate: startDate,@@ -194,26 +200,26 @@ nonisolated struct WorkflowDailyStats: Equatable, Identifiable {nonisolated struct WorkflowStatsSnapshot: Equatable {let generatedAt: Datelet dailyStats: [WorkflowDailyStats]-+static let empty = WorkflowStatsSnapshot(generatedAt: Date(), dailyStats: [])-+init(generatedAt: Date = Date(), dailyStats: [WorkflowDailyStats]) {self.generatedAt = generatedAtself.dailyStats = dailyStats}-+init(dailyAggregates: [WorkflowDailyAggregate], generatedAt: Date = Date()) {self.generatedAt = generatedAtself.dailyStats = dailyAggregates.map(\.stats).sorted { $0.startDate < $1.startDate }}-+func recentWeekGrid(columnCount: Int, endingDaysAgo: Int = 0, today: Date = Date()) -> [WorkflowDailyStats?] {let statsByDate = dailyStats.reduce(into: [String: WorkflowDailyStats]()) { result, stats inresult[stats.startDate] = stats}-+return CodexWeekGrid.dates(columnCount: columnCount,endingDaysAgo: endingDaysAgo,@@ -231,7 +237,7 @@ nonisolated struct WorkflowStatsSnapshot: Equatable {nonisolated struct WorkflowDailyIdentifierCache {var sessionIds: Set<String>var turnIds: Set<String>-+init(aggregate: WorkflowDailyAggregate) {self.sessionIds = Set(aggregate.sessionIds ?? [])self.turnIds = Set(aggregate.turnIds ?? [])@@ -255,9 +261,9 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {var projectCounts: [String: Int]var sessionIds: [String]?var turnIds: [String]?-+var id: String { date }-+init(date: String) {self.date = dateself.eventCount = 0@@ -276,7 +282,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {self.sessionIds = []self.turnIds = []}-+init(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self)self.date = try container.decode(String.self, forKey: .date)@@ -296,14 +302,14 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {self.sessionIds = try container.decodeIfPresent([String].self, forKey: .sessionIds)self.turnIds = try container.decodeIfPresent([String].self, forKey: .turnIds)}-+mutating func record(_ event: WorkflowHookEvent,keepsIdentifiers: Bool,identifierCache: inout WorkflowDailyIdentifierCache) {eventCount += 1-+switch event.kind {case .sessionStart: sessionStartCount += 1case .stop: stopCount += 1@@ -316,51 +322,51 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {case .subagentStop: subagentStopCount += 1case .none: break}-+if keepsIdentifiers {if let sessionId = event.sessionId {Self.append(sessionId, to: &sessionIds, using: &identifierCache.sessionIds)}-+if let turnId = event.turnId {Self.append(turnId, to: &turnIds, using: &identifierCache.turnIds)}}-+if let projectDisplayName = event.projectDisplayName {projectCounts[projectDisplayName, default: 0] += 1}}-+mutating func compactIdentifiersIfNeeded(keepsIdentifiers: Bool) {guard !keepsIdentifiers else {sessionIds = Self.normalizedIdentifiers(sessionIds)turnIds = Self.normalizedIdentifiers(turnIds)return}-+sessionCount = resolvedSessionCountturnCount = resolvedTurnCountsessionIds = nilturnIds = nil}-+// 会话/轮次最终值: 优先使用去重/压缩后的数量, 起止事件计数只作为缺失兜底private var resolvedSessionCount: Int {sessionCount ?? sessionIds?.count ?? sessionStartCount}-+private var resolvedTurnCount: Int {turnCount ?? turnIds?.count ?? stopCount}-+var stats: WorkflowDailyStats {let sessionTotal = resolvedSessionCountlet turnTotal = resolvedTurnCountlet toolCallCount = max(preToolUseCount, postToolUseCount)let contextCompactionCount = max(preCompactCount, postCompactCount)let subagentCount = max(subagentStartCount, subagentStopCount)-+return WorkflowDailyStats(startDate: date,sessionCount: sessionTotal,@@ -373,7 +379,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {eventCount: eventCount)}-+static func normalized(aggregates: [WorkflowDailyAggregate],today: Date = Date(),@@ -381,29 +387,29 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {) -> [WorkflowDailyAggregate] {let retentionCutoffDate = WorkflowStatsStorage.retentionCutoffDate(today: today, calendar: calendar)let identifierCutoffDate = WorkflowStatsStorage.identifierRetentionCutoffDate(today: today, calendar: calendar)-+return aggregates.compactMap { aggregate inguard let date = Self.date(from: aggregate.date), date >= retentionCutoffDate else {return nil}-+var mutableAggregate = aggregatemutableAggregate.compactIdentifiersIfNeeded(keepsIdentifiers: date >= identifierCutoffDate)return mutableAggregate}.sorted { $0.date < $1.date }}-+static func decodeJSONLines(from data: Data) -> [WorkflowDailyAggregate] {JSONLines.decode(from: data)}-+static func encodeJSONLines(_ aggregates: [WorkflowDailyAggregate]) throws -> Data {try aggregates.reduce(into: Data()) { result, aggregate inresult.append(try aggregate.jsonLineData())}}-+func jsonLineData() throws -> Data {let fields = [try WorkflowStatsJSON.field("date", date),@@ -423,10 +429,10 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {try WorkflowStatsJSON.field("sessionIds", sessionIds),try WorkflowStatsJSON.field("turnIds", turnIds)]-+return WorkflowStatsJSON.lineData(fields)}-+private static func append(_ identifier: String,to identifiers: inout [String]?,@@ -435,34 +441,34 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {guard identifierSet.insert(identifier).inserted else {return}-+if identifiers == nil {identifiers = []}identifiers?.append(identifier)}-+private static func normalizedIdentifiers(_ identifiers: [String]?) -> [String] {Set(identifiers ?? []).sorted()}-+private var mostActiveProject: String? {projectCounts.sorted { lhs, rhs inif lhs.value != rhs.value {return lhs.value > rhs.value}-+return lhs.key.localizedStandardCompare(rhs.key) == .orderedAscending}.first?.key}-+private static func date(from string: String) -> Date? {DateFormatter.codexDay.date(from: string)}-+private enum CodingKeys: String, CodingKey {case datecase eventCountdiff --git a/CodexBar/Models/DateFormatter.swift b/CodexBar/Models/DateFormatter.swiftindex 5f40f2d..049cd15 100644--- a/CodexBar/Models/DateFormatter.swift+++ b/CodexBar/Models/DateFormatter.swift@@ -9,7 +9,7 @@ extension DateFormatter {formatter.dateFormat = "yyyy-MM-dd"return formatter}()-+// yyyy-MM-dd HH:mm:ss.SSS, Hook 原始事件写入本机时间字符串nonisolated static let codexLocalTimestamp: DateFormatter = {let formatter = DateFormatter()diff --git a/CodexBar/Models/GlobalHotKeyShortcut.swift b/CodexBar/Models/GlobalHotKeyShortcut.swiftindex 7414eea..b3c3da8 100644--- a/CodexBar/Models/GlobalHotKeyShortcut.swift+++ b/CodexBar/Models/GlobalHotKeyShortcut.swift@@ -5,49 +5,49 @@ nonisolated struct GlobalHotKeyShortcut: Codable, Equatable, Sendable {let keyCode: UInt32let modifiers: UInt32let keyLabel: String-+static let `default` = GlobalHotKeyShortcut(keyCode: UInt32(kVK_ANSI_W),modifiers: UInt32(cmdKey | shiftKey),keyLabel: "W")-+init(keyCode: UInt32, modifiers: UInt32, keyLabel: String) {self.keyCode = keyCodeself.modifiers = modifiersself.keyLabel = keyLabel}-+init?(event: NSEvent) {let modifiers = Self.carbonModifiers(from: event.modifierFlags)let keyLabel = Self.keyLabel(for: event)guard !keyLabel.isEmpty else {return nil}-+self.init(keyCode: UInt32(event.keyCode),modifiers: modifiers,keyLabel: keyLabel)}-+var label: String {modifierSymbols + keyLabel}-+var validationError: String? {if modifierCount < 2 {return "至少需要两个修饰键"}-+if isReservedSystemShortcut {return "不可使用系统快捷键"}-+return nil}-+private var modifierSymbols: String {[hasModifier(controlKey) ? "⌃" : nil,@@ -58,22 +58,22 @@ nonisolated struct GlobalHotKeyShortcut: Codable, Equatable, Sendable {.compactMap { $0 }.joined()}-+private var modifierCount: Int {[controlKey, optionKey, shiftKey, cmdKey].filter(hasModifier).count}-+private var isReservedSystemShortcut: Bool {hasModifier(cmdKey) && Self.reservedSystemKeyCodes.contains(keyCode)}-+private func hasModifier(_ modifier: Int) -> Bool {modifiers & UInt32(modifier) != 0}-+private static func carbonModifiers(from flags: NSEvent.ModifierFlags) -> UInt32 {var modifiers: UInt32 = 0-+if flags.contains(.control) {modifiers |= UInt32(controlKey)}@@ -86,20 +86,20 @@ nonisolated struct GlobalHotKeyShortcut: Codable, Equatable, Sendable {if flags.contains(.command) {modifiers |= UInt32(cmdKey)}-+return modifiers}-+private static func keyLabel(for event: NSEvent) -> String {if let specialLabel = specialKeyLabels[UInt32(event.keyCode)] {return specialLabel}-+return (event.charactersIgnoringModifiers ?? "").uppercased().trimmingCharacters(in: .whitespacesAndNewlines)}-+private static let specialKeyLabels: [UInt32: String] = [UInt32(kVK_Space): "Space",UInt32(kVK_Tab): "Tab",@@ -116,7 +116,7 @@ nonisolated struct GlobalHotKeyShortcut: Codable, Equatable, Sendable {UInt32(kVK_UpArrow): "↑",UInt32(kVK_DownArrow): "↓"]-+private static let reservedSystemKeyCodes: Set<UInt32> = [UInt32(kVK_Space),UInt32(kVK_Tab)diff --git a/CodexBar/Models/UsageHeatmapDay.swift b/CodexBar/Models/UsageHeatmapDay.swiftindex b4a255e..a02fadd 100644--- a/CodexBar/Models/UsageHeatmapDay.swift+++ b/CodexBar/Models/UsageHeatmapDay.swift@@ -4,13 +4,13 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {let startDate: Stringlet tokenCount: Int?let workflowStats: WorkflowDailyStats-+var id: String { startDate }-+var tokensForHeatmap: Int {tokenCount ?? 0}-+static func grid(usage: CodexUsageSnapshot,workflowStats: WorkflowStatsSnapshot,@@ -30,7 +30,7 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {endingDaysAgo: endingDaysAgo,today: today)-+return merge(tokenDays: tokenDays,workflowDays: workflowDays,@@ -38,7 +38,7 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {todayTokenCount: todayTokenCount)}-+private static func merge(tokenDays: [DailyUsageBucket?],workflowDays: [WorkflowDailyStats?],@@ -49,7 +49,7 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {guard let startDate = tokenDay?.startDate ?? workflowDay?.startDate else {return nil}-+return UsageHeatmapDay(startDate: startDate,tokenCount: startDate == todayString ? todayTokenCount : tokenDay?.tokens ?? 0,diff --git a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift b/CodexBar/Services/CodexCLI/CodexCLIResolver.swiftindex 764e292..21d7f7b 100644--- a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift+++ b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift@@ -4,7 +4,7 @@ import Foundationnonisolated enum CodexCLIExecutableSource: String, Sendable, Equatable {case globalcase bundled-+var displayName: String {switch self {case .global: return "Codex CLI"@@ -30,14 +30,14 @@ nonisolated struct CodexCLIConnectionInfo: Sendable, Equatable {nonisolated struct CodexCLIInstallations: Sendable, Equatable {let globalPath: String?let bundledPath: String?-+// 与启动优先级一致: 全局优先, 回退内置var activeSource: CodexCLIExecutableSource? {if globalPath != nil { return .global }if bundledPath != nil { return .bundled }return nil}-+func path(for source: CodexCLIExecutableSource) -> String? {switch source {case .global: return globalPath@@ -49,38 +49,38 @@ nonisolated struct CodexCLIInstallations: Sendable, Equatable {nonisolated enum CodexCLIResolver {static let bundledExecutablePath = "/Applications/Codex.app/Contents/Resources/codex"static let environment = appServerEnvironment()-+static func resolveAppServerCommand(environment: [String: String] = environment) throws -> AppServerCommand {try command(from: resolveInstallations(environment: environment))}-+// 从已解析的安装信息派生命令, 避免重复扫描 PATHstatic func command(from installations: CodexCLIInstallations) throws -> AppServerCommand {guard let source = installations.activeSource,let path = installations.path(for: source) else {throw CodexStatusError.executableNotFound}-+return AppServerCommand(source: source, executablePath: path)}-+static func resolveInstallations(environment: [String: String] = environment) -> CodexCLIInstallations {let cliPath = findExecutable(named: "codex", environment: environment)let cliIsBundled = cliPath.map { pathsAreEquivalent($0, bundledExecutablePath) } ?? false-+let bundledPath: String?if FileManager.default.isExecutableFile(atPath: bundledExecutablePath) {bundledPath = bundledExecutablePath} else {bundledPath = cliIsBundled ? cliPath : nil}-+return CodexCLIInstallations(globalPath: cliIsBundled ? nil : cliPath,bundledPath: bundledPath)}-+private static func appServerEnvironment() -> [String: String] {var environment = ProcessInfo.processInfo.environmentlet homeDirectory = realUserHomeDirectory()@@ -97,16 +97,16 @@ nonisolated enum CodexCLIResolver {"/usr/sbin","/sbin"]-+environment["HOME"] = homeDirectoryenvironment["USER"] = NSUserName()environment["LOGNAME"] = NSUserName()environment["PATH"] = mergedPath(path, fallbackPaths: fallbackPaths)environment["TERM"] = environment["TERM"] ?? "xterm-256color"-+return environment}-+private static func findExecutable(named executableName: String,environment: [String: String]@@ -114,50 +114,50 @@ nonisolated enum CodexCLIResolver {guard let path = environment["PATH"] else {return nil}-+for directory in path.split(separator: ":") {let executablePath = "\(directory)/\(executableName)"if FileManager.default.isExecutableFile(atPath: executablePath) {return executablePath}}-+return nil}-+private static func mergedPath(_ path: String, fallbackPaths: [String]) -> String {var components: [String] = []var seen = Set<String>()-+for component in path.split(separator: ":").map(String.init) + fallbackPaths {guard !component.isEmpty, !seen.contains(component) else {continue}-+components.append(component)seen.insert(component)}-+return components.joined(separator: ":")}-+private static func pathsAreEquivalent(_ lhs: String, _ rhs: String) -> Bool {canonicalPath(lhs) == canonicalPath(rhs)}-+private static func canonicalPath(_ path: String) -> String {URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.path}-+private static func realUserHomeDirectory() -> String {guard let passwd = getpwuid(getuid()),let home = passwd.pointee.pw_dir else {return NSHomeDirectory()}-+return String(cString: home)}}diff --git a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swiftindex a75fb36..60803ad 100644--- a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift+++ b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift@@ -5,7 +5,7 @@ nonisolated struct CodexCLIVersionSnapshot: Equatable, Sendable {let global: CodexCLIVersionItemlet bundled: CodexCLIVersionItemlet refreshedAt: Date-+// 让首次 refresh 不受节流限制static let empty = CodexCLIVersionSnapshot(global: CodexCLIVersionItem(source: .global),@@ -19,9 +19,9 @@ nonisolated struct CodexCLIVersionItem: Equatable, Identifiable, Sendable {let path: String?let version: String?let errorMessage: String?-+var id: CodexCLIExecutableSource { source }-+init(source: CodexCLIExecutableSource,path: String? = nil,@@ -33,12 +33,12 @@ nonisolated struct CodexCLIVersionItem: Equatable, Identifiable, Sendable {self.version = versionself.errorMessage = errorMessage}-+var displayVersion: String {if path == nil {return "未找到 \(source.displayName)"}-+return version ?? errorMessage ?? "未知版本"}}@@ -52,19 +52,19 @@ nonisolated struct CodexCLIVersionDisplay: Equatable {let path: String?// 当前会话尚未重连到新安装版本时显示的新版本号let newerInstalledVersion: String?-+init(item: CodexCLIVersionItem, connection: CodexCLIConnectionInfo?) {let isCurrent = connection?.source == item.source// 当前来源优先显示正在运行的版本, 避免后台升级后误报已生效let runningVersion = isCurrent ? connection?.version : nillet version = runningVersion ?? item.version-+self.source = item.sourceself.isCurrent = isCurrentself.hasVersion = version != nilself.displayVersion = version ?? item.displayVersionself.path = (isCurrent ? connection?.executablePath : nil) ?? item.path-+if let runningVersion,let installed = item.version,Self.isInstalledVersionNewer(installed, than: runningVersion) {@@ -73,7 +73,7 @@ nonisolated struct CodexCLIVersionDisplay: Equatable {self.newerInstalledVersion = nil}}-+private static func isInstalledVersionNewer(_ installedVersion: String,than runningVersion: String@@ -82,10 +82,10 @@ nonisolated struct CodexCLIVersionDisplay: Equatable {let runningComponents = normalizedVersionComponents(from: runningVersion) else {return false}-+return runningComponents.lexicographicallyPrecedes(installedComponents)}-+private static func normalizedVersionComponents(from version: String) -> [Int]? {let components = version.components(separatedBy: CharacterSet.decimalDigits.inverted)@@ -93,7 +93,7 @@ nonisolated struct CodexCLIVersionDisplay: Equatable {guard !components.isEmpty else {return nil}-+return Array(components.reversed().drop(while: { $0 == 0 }).reversed())}}@@ -103,11 +103,11 @@ nonisolated final class CodexCLIVersionService: @unchecked Sendable {private let timeout: TimeIntervalprivate static let pipeDrainTimeout: TimeInterval = 0.25private static let maxPipeOutputBytes = 64 * 1024-+init(timeout: TimeInterval = 5) {self.timeout = timeout}-+func fetchSnapshot() async -> CodexCLIVersionSnapshot {await withCheckedContinuation { continuation inqueue.async {@@ -115,11 +115,11 @@ nonisolated final class CodexCLIVersionService: @unchecked Sendable {}}}-+private static func fetchSnapshotOnQueue(timeout: TimeInterval) -> CodexCLIVersionSnapshot {let environment = CodexCLIResolver.environmentlet installations = CodexCLIResolver.resolveInstallations(environment: environment)-+// 两个安装源互不依赖, 先并发启动再收集, 避免两个超时串行叠加let globalProbe = startProbe(source: .global,@@ -133,14 +133,14 @@ nonisolated final class CodexCLIVersionService: @unchecked Sendable {environment: environment,timeout: timeout)-+return CodexCLIVersionSnapshot(global: finishProbe(globalProbe),bundled: finishProbe(bundledProbe),refreshedAt: Date())}-+private struct RunningProbe {let source: CodexCLIExecutableSourcelet path: String@@ -150,12 +150,12 @@ nonisolated final class CodexCLIVersionService: @unchecked Sendable {let finished: DispatchSemaphorelet deadline: Date}-+private enum ProbeOutcome {case resolved(CodexCLIVersionItem)case running(RunningProbe)}-+private static func startProbe(source: CodexCLIExecutableSource,path: String?,@@ -165,12 +165,12 @@ nonisolated final class CodexCLIVersionService: @unchecked Sendable {guard let path else {return .resolved(CodexCLIVersionItem(source: source))}-+let process = Process()process.executableURL = URL(fileURLWithPath: path)process.arguments = ["--version"]process.environment = environment-+let standardOutput = Pipe()let standardError = Pipe()let outputCollector = PipeCollector(@@ -182,17 +182,17 @@ nonisolated final class CodexCLIVersionService: @unchecked Sendable {maxBytes: Self.maxPipeOutputBytes)let finished = DispatchSemaphore(value: 0)-+process.standardOutput = standardOutputprocess.standardError = standardErrorprocess.terminationHandler = { _ in finished.signal() }-+do {try process.run()} catch {return .resolved(CodexCLIVersionItem(source: source, path: path, errorMessage: "启动失败"))}-+return .running(RunningProbe(source: source,path: path,@@ -203,7 +203,7 @@ nonisolated final class CodexCLIVersionService: @unchecked Sendable {deadline: Date().addingTimeInterval(timeout)))}-+private static func finishProbe(_ outcome: ProbeOutcome) -> CodexCLIVersionItem {switch outcome {case .resolved(let item):@@ -213,18 +213,18 @@ nonisolated final class CodexCLIVersionService: @unchecked Sendable {terminateTimedOutProbe(probe)return CodexCLIVersionItem(source: probe.source, path: probe.path, errorMessage: "读取超时")}-+let output = collectedText(from: probe.outputCollector, deadline: probe.deadline)let errorOutput = collectedText(from: probe.errorCollector, deadline: probe.deadline)-+guard probe.process.terminationStatus == 0 else {return CodexCLIVersionItem(source: probe.source, path: probe.path, errorMessage: "读取失败")}-+guard let version = firstLine(in: output) ?? firstLine(in: errorOutput) else {return CodexCLIVersionItem(source: probe.source, path: probe.path, errorMessage: "版本未知")}-+return CodexCLIVersionItem(source: probe.source,path: probe.path,@@ -232,7 +232,7 @@ nonisolated final class CodexCLIVersionService: @unchecked Sendable {)}}-+private static func terminateTimedOutProbe(_ probe: RunningProbe) {_ = ProcessTermination.terminate(probe.process,@@ -241,25 +241,25 @@ nonisolated final class CodexCLIVersionService: @unchecked Sendable {)stopCollectors(for: probe)}-+private static func stopCollectors(for probe: RunningProbe) {_ = probe.outputCollector.stopAndRead()_ = probe.errorCollector.stopAndRead()}-+private static func collectedText(from collector: PipeCollector, deadline: Date) -> String {let drainTimeout = min(Self.pipeDrainTimeout, max(0, deadline.timeIntervalSinceNow))_ = collector.waitUntilClosed(timeout: drainTimeout)- return String(data: collector.stopAndRead(), encoding: .utf8) ?? ""+ return String(bytes: collector.stopAndRead(), encoding: .utf8) ?? ""}-+private static func firstLine(in text: String) -> String? {text.split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.first { !$0.isEmpty }}-+}private nonisolated final class PipeCollector: @unchecked Sendable {@@ -269,7 +269,7 @@ private nonisolated final class PipeCollector: @unchecked Sendable {private let maxBytes: Intprivate var data = Data()private var isClosed = false-+init(fileHandle: FileHandle, maxBytes: Int) {self.fileHandle = fileHandleself.maxBytes = max(maxBytes, 0)@@ -280,47 +280,47 @@ private nonisolated final class PipeCollector: @unchecked Sendable {self?.markClosed()return}-+self?.append(availableData)}}-+func waitUntilClosed(timeout: TimeInterval) -> Bool {lock.lock()let closed = isClosedlock.unlock()-+guard !closed else {return true}-+return closedSemaphore.wait(timeout: .now() + max(0, timeout)) == .success}-+func stopAndRead() -> Data {fileHandle.readabilityHandler = niltry? fileHandle.close()-+lock.lock()let snapshot = dataisClosed = truelock.unlock()closedSemaphore.signal()-+return snapshot}-+private func append(_ chunk: Data) {lock.lock()defer { lock.unlock() }-+guard data.count < maxBytes else {return}-+data.append(chunk.prefix(maxBytes - data.count))}-+private func markClosed() {lock.lock()isClosed = true@@ -342,33 +342,33 @@ nonisolated enum CodexCLIVersionReader {final class CodexCLIVersionViewModel: ObservableObject {@Published private(set) var snapshot = CodexCLIVersionSnapshot.empty@Published private(set) var isRefreshing = false-+// onAppear 和 didBecomeActive 常连发, 版本探测需要节流以避免频繁启动子进程private static let refreshThrottle: TimeInterval = 60-+private let service: CodexCLIVersionServiceprivate var refreshTask: Task<Void, Never>?-+init(service: CodexCLIVersionService = CodexCLIVersionService()) {self.service = service}-+deinit {refreshTask?.cancel()}-+func refresh() {guard !isRefreshing,Date().timeIntervalSince(snapshot.refreshedAt) > Self.refreshThrottle else {return}isRefreshing = true-+refreshTask = Task {let snapshot = await service.fetchSnapshot()-+guard !Task.isCancelled else { return }-+self.snapshot = snapshotself.isRefreshing = false}diff --git a/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift b/CodexBar/Services/CodexStatus/AppServerPipeReaders.swiftindex d1db7e1..9097593 100644--- a/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift+++ b/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift@@ -7,7 +7,7 @@ nonisolated final class JSONLineReader: @unchecked Sendable {private var buffer = Data()private var lines: [String] = []private var closed = false-+init(fileHandle: FileHandle) {self.fileHandle = fileHandlefileHandle.readabilityHandler = { [weak self] handle in@@ -20,47 +20,47 @@ nonisolated final class JSONLineReader: @unchecked Sendable {self?.append(data)}}-+func nextLine(timeout: TimeInterval) -> String? {if let line = popLine() {return line}-+if isClosed {return nil}-+let result = semaphore.wait(timeout: .now() + timeout)guard result == .success else {return nil}-+return popLine()}-+func stop() {fileHandle.readabilityHandler = nilmarkClosed()}-+var isClosed: Bool {lock.lock()defer { lock.unlock() }-+return closed && lines.isEmpty}-+private func append(_ data: Data) {lock.lock()defer { lock.unlock() }-+buffer.append(data)-+while let newlineRange = buffer.firstRange(of: Data([0x0A])) {let lineData = buffer[..<newlineRange.lowerBound]buffer.removeSubrange(...newlineRange.lowerBound)-- if let line = String(data: lineData, encoding: .utf8)?++ if let line = String(bytes: lineData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines),!line.isEmpty {lines.append(line)@@ -68,41 +68,41 @@ nonisolated final class JSONLineReader: @unchecked Sendable {}}}-+private func markClosed() {lock.lock()defer {lock.unlock()semaphore.signal()}-+if !buffer.isEmpty {- if let line = String(data: buffer, encoding: .utf8)?+ if let line = String(bytes: buffer, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines),!line.isEmpty {lines.append(line)}buffer.removeAll()}-+closed = true}-+private func popLine() -> String? {lock.lock()defer { lock.unlock() }-+guard !lines.isEmpty else {return nil}-+return lines.removeFirst()}}nonisolated final class PipeDrain: @unchecked Sendable {private let fileHandle: FileHandle-+init(fileHandle: FileHandle) {self.fileHandle = fileHandlefileHandle.readabilityHandler = { handle in@@ -112,7 +112,7 @@ nonisolated final class PipeDrain: @unchecked Sendable {}}}-+func stop() {fileHandle.readabilityHandler = nil}diff --git a/CodexBar/Services/CodexStatus/AppServerSession.swift b/CodexBar/Services/CodexStatus/AppServerSession.swiftindex 27a6604..4b790c7 100644--- a/CodexBar/Services/CodexStatus/AppServerSession.swift+++ b/CodexBar/Services/CodexStatus/AppServerSession.swift@@ -2,23 +2,23 @@ import Foundationnonisolated final class AppServerSession {let process: Process-+private typealias EncodedMessage = (data: Data, text: String)private typealias ResponseLine = (text: String, data: Data)-+private static let writeFailureMessage = "连接已断开, 无法发送请求"private static let responseConnectionClosedMessage = "连接已断开, 等待响应失败"private static let responseTimeoutMessage = "等待响应超时"private static let closeGracefulTimeout: TimeInterval = 1.0private static let closeKillTimeout: TimeInterval = 0.5-+private let input: Pipeprivate let lineReader: JSONLineReaderprivate let errorReader: PipeDrainprivate let timeout: TimeIntervalprivate var nextId = 1private var unsupportedMethods: Set<String> = []-+init(process: Process,input: Pipe,@@ -32,12 +32,12 @@ nonisolated final class AppServerSession {self.errorReader = errorReaderself.timeout = timeout}-+func close() {lineReader.stop()errorReader.stop()try? input.fileHandleForWriting.close()-+if process.isRunning {switch ProcessTermination.terminate(process,@@ -53,16 +53,16 @@ nonisolated final class AppServerSession {}}}-+func notify(_ method: String, params: [String: Any]? = nil) throws {let encoded = try encodeMessage(method: method, id: nil, params: params)-+try writeEncoded(encoded) {RequestLogStore.shared.recordFailure(method: method, message: Self.writeFailureMessage)}RequestLogStore.shared.recordRequestWithEmptyResponse(method: method, payload: encoded.text)}-+func request<Response: Decodable>(_ method: String,params: [String: Any]? = nil,@@ -71,14 +71,14 @@ nonisolated final class AppServerSession {guard !unsupportedMethods.contains(method) else {throw CodexStatusError.unsupportedMethod}-+do {return try performRequestRememberingUnsupported(method, params: params, as: type)} catch let error as CodexStatusError where error.isRetriableServerError {return try performRequestRememberingUnsupported(method, params: params, as: type)}}-+private func performRequestRememberingUnsupported<Response: Decodable>(_ method: String,params: [String: Any]? = nil,@@ -93,7 +93,7 @@ nonisolated final class AppServerSession {throw error}}-+private func performRequest<Response: Decodable>(_ method: String,params: [String: Any]? = nil,@@ -103,18 +103,18 @@ nonisolated final class AppServerSession {nextId += 1let encoded = try encodeMessage(method: method, id: id, params: params)let token = RequestLogStore.shared.beginRequest(method: method, payload: encoded.text)-+try writeEncoded(encoded) {RequestLogStore.shared.failRequest(token, message: Self.writeFailureMessage)}-+return try waitForResponse(id: id, token: token, decode: type)}-+private func encodeMessage(method: String, id: Int?, params: [String: Any]?) throws -> EncodedMessage {try encode(message(method: method, id: id, params: params))}-+private func message(method: String, id: Int?, params: [String: Any]?) -> [String: Any] {var object: [String: Any] = ["method": method]if let id {@@ -125,12 +125,18 @@ nonisolated final class AppServerSession {}return object}-+private func encode(_ object: [String: Any]) throws -> EncodedMessage {let data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes])- return (data, String(decoding: data, as: UTF8.self))+ guard let text = String(bytes: data, encoding: .utf8) else {+ throw EncodingError.invalidValue(+ object,+ .init(codingPath: [], debugDescription: "Encoded app-server JSON was not UTF-8")+ )+ }+ return (data, text)}-+private func writeEncoded(_ encoded: EncodedMessage, onFailure: () -> Void) throws {do {try writeData(encoded.data)@@ -139,13 +145,13 @@ nonisolated final class AppServerSession {throw CodexStatusError.serverConnectionClosed}}-+private func writeData(_ data: Data) throws {var payload = datapayload.append(0x0A)try input.fileHandleForWriting.write(contentsOf: payload)}-+private func waitForResponse<Response: Decodable>(id: Int,token: UUID,@@ -153,7 +159,7 @@ nonisolated final class AppServerSession {) throws -> Response {let deadline = Date().addingTimeInterval(timeout)let decoder = JSONDecoder()-+while Date() < deadline {guard let line = try nextResponseLine(matching: id,@@ -163,15 +169,15 @@ nonisolated final class AppServerSession {) else {continue}-+let result = try decodeResponse(line, as: type, token: token, decoder: decoder)RequestLogStore.shared.finishRequest(token, response: line.text)return result}-+try failRequest(token, message: Self.responseTimeoutMessage, error: .serverTimeout)}-+private func nextResponseLine(matching id: Int,before deadline: Date,@@ -182,19 +188,19 @@ nonisolated final class AppServerSession {if lineReader.isClosed {try failRequest(token, message: Self.responseConnectionClosedMessage, error: .serverConnectionClosed)}-+return nil}-+guard let data = text.data(using: .utf8),let idEnvelope = try? decoder.decode(RPCIDEnvelope.self, from: data),idEnvelope.id == id else {return nil}-+return (text, data)}-+private func decodeResponse<Response: Decodable>(_ line: ResponseLine,as type: Response.Type,@@ -205,15 +211,15 @@ nonisolated final class AppServerSession {let error = errorEnvelope.error {try failRequest(token, message: line.text, error: .serverError(error.message))}-+guard let envelope = try? decoder.decode(RPCResponseEnvelope<Response>.self, from: line.data),let result = envelope.result else {try failRequest(token, message: line.text, error: .invalidServerResponse)}-+return result}-+private func failRequest(_ token: UUID, message: String, error: CodexStatusError) throws -> Never {RequestLogStore.shared.failRequest(token, message: message)throw errordiff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swiftindex d276362..1566844 100644--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift@@ -40,7 +40,7 @@ nonisolated private struct SupplementalDataCache {var account: CodexAccount?var rateLimits: AccountRateLimitsResponse?var usage: AccountUsageResponse?-+mutating func useAccount(_ account: CodexAccount) {guard self.account != account else { return }self = Self(account: account)@@ -54,14 +54,14 @@ nonisolated private extension ReadResult {}return false}-+var value: Value? {if case .value(let value) = self {return value}return nil}-+// 认证刷新后仍是 authRequired/broken 则上抛, 其余原样返回交给调用方按缓存策略处理func resultAfterAuthAttempt() throws -> ReadResult<Value> {switch self {@@ -81,25 +81,25 @@ nonisolated final class CodexStatusService: @unchecked Sendable {// 定期回收连接, 让后台升级后的 codex 二进制有机会生效private static let connectionMaxAge: TimeInterval = 1 * 60 * 60private static let environment = CodexCLIResolver.environment-+// connection 只在这个队列上访问private let queue = DispatchQueue(label: "CodexBar.app-server", qos: .utility)private var connection: AppServerConnection?private var supplementalDataCache = SupplementalDataCache()-+// app-server 退出后继续写管道会触发 SIGPIPE; 忽略信号, 让 write 抛错后走重建private static let ignoreBrokenPipeSignal: Void = {signal(SIGPIPE, SIG_IGN)}()-+init() {_ = Self.ignoreBrokenPipeSignal}-+deinit {connection?.session.close()}-+func fetchOutcome() async -> CodexFetchOutcome {await withCheckedContinuation { continuation inqueue.async {@@ -107,7 +107,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {}}}-+func currentConnectionInfo() async -> CodexCLIConnectionInfo? {await withCheckedContinuation { continuation inqueue.async {@@ -115,7 +115,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {}}}-+// 复用连接出现传输故障时只重建重试一次, 避免故障状态下反复拉起进程private func resolveOutcomeOnQueue(allowRebuild: Bool) -> CodexFetchOutcome {switch ensureConnection() {@@ -143,15 +143,15 @@ nonisolated final class CodexStatusService: @unchecked Sendable {}}}-+private func ensureConnection() -> ConnectionResolution {if let connection, connection.session.process.isRunning,Date().timeIntervalSince(connection.openedAt) < Self.connectionMaxAge {return .ready(connection: connection, reused: true)}-+teardownConnection()-+let command: AppServerCommanddo {command = try CodexCLIResolver.resolveAppServerCommand(environment: Self.environment)@@ -159,7 +159,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {RequestLogStore.shared.recordFailure(message: error.localizedDescription)return .initializationFailed}-+let resolution = Self.openConnection(command: command,environment: Self.environment,@@ -171,40 +171,40 @@ nonisolated final class CodexStatusService: @unchecked Sendable {}return resolution}-+private func teardownConnection() {connection?.session.close()connection = nil}-+private func currentConnectionInfoOnQueue() -> CodexCLIConnectionInfo? {guard let connection, connection.session.process.isRunning else {return nil}-+return connection.commandInfo}-+// 额度与用量独立读取; 认证失败全程只刷新一次 token, 传输故障交给外层重建连接private func fetchData(using connection: AppServerConnection, refreshAccountInfo: Bool) throws -> CodexQuotaSnapshot {var didRefresh = false-+func refreshTokenIfNeeded() throws {guard !didRefresh else { throw FetchFailure.notLoggedIn }didRefresh = truetry Self.refreshAccount(using: connection)}-+func readResultWithAuthRefresh<Value>(_ read: () -> ReadResult<Value>) throws -> ReadResult<Value> {let firstAttempt = read()guard firstAttempt.isAuthenticationRequired else {return try firstAttempt.resultAfterAuthAttempt()}-+try refreshTokenIfNeeded()return try read().resultAfterAuthAttempt()}-+func readSupplemental<Value: Decodable>(_ method: String,as type: Value.Type,@@ -217,7 +217,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {cache: &cache)}-+// 新建连接已读过 account; 复用连接才刷新账户状态if refreshAccountInfo {let accountResult: ReadResult<AccountReadResponse> = try readResultWithAuthRefresh {@@ -228,25 +228,25 @@ nonisolated final class CodexStatusService: @unchecked Sendable {connection.accountResponse = response}}-+guard let account = connection.accountResponse.account else {throw FetchFailure.notLoggedIn}-+supplementalDataCache.useAccount(account)-+let rateLimitsRead = try readSupplemental("account/rateLimits/read",as: AccountRateLimitsResponse.self,cache: &supplementalDataCache.rateLimits)-+let usageRead = try readSupplemental("account/usage/read",as: AccountUsageResponse.self,cache: &supplementalDataCache.usage)-+// rateLimits/usage 都可为空, 只要账户有效就让 UI 展示"暂无数据"guard let snapshot = try? CodexQuotaSnapshot(accountResponse: connection.accountResponse,@@ -257,10 +257,10 @@ nonisolated final class CodexStatusService: @unchecked Sendable {) else {throw FetchFailure.notLoggedIn}-+return snapshot}-+// 新值更新缓存; 本轮请求失败则回退到缓存并标记陈旧; 方法不支持/认证/断连一律视为无数据private func cachedRead<Value>(_ result: ReadResult<Value>,@@ -276,7 +276,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {return CachedSupplementalRead(value: nil, isStale: false)}}-+private static func read<Value: Decodable>(_ method: String,params: [String: Any]? = nil,@@ -291,7 +291,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {return .broken}}-+private static func classify<Value>(_ error: CodexStatusError) -> ReadResult<Value> {if error.isAuthenticationRequired {return .authRequired@@ -302,7 +302,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {// 重试后仍失败的非认证业务错误不阻断整轮刷新return error.isTransportFailure ? .broken : .skipped(.requestFailed)}-+private static func refreshAccount(using connection: AppServerConnection) throws {let response: AccountReadResponsedo {@@ -316,13 +316,13 @@ nonisolated final class CodexStatusService: @unchecked Sendable {} catch {throw FetchFailure.needsRebuild}-+connection.accountResponse = responseif response.account == nil {throw FetchFailure.notLoggedIn}}-+// 初始化失败与未登录在这里分流; 两者都不复用本次新建的进程private static func openConnection(command: AppServerCommand,@@ -334,17 +334,17 @@ nonisolated final class CodexStatusService: @unchecked Sendable {process.executableURL = URL(fileURLWithPath: command.executablePath)process.arguments = command.argumentsprocess.environment = environment-+let standardInput = Pipe()let standardOutput = Pipe()let standardError = Pipe()let lineReader = JSONLineReader(fileHandle: standardOutput.fileHandleForReading)let errorReader = PipeDrain(fileHandle: standardError.fileHandleForReading)-+process.standardInput = standardInputprocess.standardOutput = standardOutputprocess.standardError = standardError-+do {try process.run()} catch {@@ -352,7 +352,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {return .initializationFailed}let openedAt = Date()-+let session = AppServerSession(process: process,input: standardInput,@@ -360,7 +360,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {errorReader: errorReader,timeout: timeout)-+do {let initializeResult = try session.request("initialize",@@ -373,27 +373,27 @@ nonisolated final class CodexStatusService: @unchecked Sendable {],as: InitializeResult.self)-+try session.notify("initialized")-+let accountResponse = try session.request("account/read",params: ["refreshToken": false],as: AccountReadResponse.self)-+guard accountResponse.account != nil else {session.close()return .notLoggedIn}-+let commandInfo = CodexCLIConnectionInfo(source: command.source,executablePath: command.executablePath,version: Self.serverVersion(fromUserAgent: initializeResult.userAgent),openedAt: openedAt)-+return .ready(connection: AppServerConnection(session: session,@@ -407,22 +407,22 @@ nonisolated final class CodexStatusService: @unchecked Sendable {return .initializationFailed}}-+private nonisolated static func clientVersion() -> String {guard let version = Bundle.main.shortVersionString, !version.isEmpty else {return "1.0.0"}-+return version}-+// userAgent 形如 "codex_bar/0.139.0 (...)"; 取首个 token 中 "/" 之后的运行版本号private nonisolated static func serverVersion(fromUserAgent userAgent: String?) -> String? {guard let firstToken = userAgent?.split(separator: " ").first,let slashIndex = firstToken.firstIndex(of: "/") else {return nil}-+let version = firstToken[firstToken.index(after: slashIndex)...]return version.isEmpty ? nil : String(version)}@@ -432,9 +432,9 @@ private nonisolated final class AppServerConnection {let session: AppServerSessionlet commandInfo: CodexCLIConnectionInfovar accountResponse: AccountReadResponse-+var openedAt: Date { commandInfo.openedAt }-+init(session: AppServerSession,accountResponse: AccountReadResponse,diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swiftindex 63c6645..b02e959 100644--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift@@ -7,7 +7,7 @@ nonisolated enum CodexLoadState: Equatable {case loadedcase notLoggedIncase initializationFailed-+var isError: Bool {switch self {case .notLoggedIn, .initializationFailed: true@@ -23,61 +23,61 @@ final class CodexStatusViewModel: ObservableObject {@Published private(set) var loadState: CodexLoadState = .loading@Published private(set) var codexConnectionInfo: CodexCLIConnectionInfo?@Published private(set) var autoRefreshCountdownStartedAt: Date?-+var hasError: Bool { loadState.isError }var hasUntrustedData: Bool {snapshot?.hasTrustedData == false}var usesErrorImage: Bool { hasError || hasUntrustedData }var autoRefreshInterval: TimeInterval { Self.refreshInterval }-+private static let refreshInterval: TimeInterval = 60-+private let service: CodexStatusServiceprivate var autoRefreshTask: Task<Void, Never>?-+init(service: CodexStatusService = CodexStatusService()) {self.service = service}-+deinit {autoRefreshTask?.cancel()}-+func refreshIfNeeded() {guard Date().timeIntervalSince(autoRefreshCountdownStartedAt ?? .distantPast) > Self.refreshInterval else {return}-+refresh()}-+func startAutoRefresh() {guard autoRefreshTask == nil else {return}-+autoRefreshTask = Task { [weak self] inself?.refreshIfNeeded()-+while !Task.isCancelled {let delay = self?.autoRefreshDelay ?? Self.refreshIntervalif (try? await Task.sleep(for: .seconds(delay))) == nil {break}-+self?.refreshIfNeeded()}}}-+func refresh() {guard !isRefreshing else {return}-+isRefreshing = true-+Task {switch await service.fetchOutcome() {case .data(let snapshot):@@ -90,24 +90,24 @@ final class CodexStatusViewModel: ObservableObject {self.snapshot = nilself.loadState = .initializationFailed}-+self.codexConnectionInfo = await service.currentConnectionInfo()self.autoRefreshCountdownStartedAt = Date()self.isRefreshing = false}}-+func refreshCodexConnectionInfo() {Task {self.codexConnectionInfo = await service.currentConnectionInfo()}}-+private var autoRefreshDelay: TimeInterval {guard let autoRefreshCountdownStartedAt else {return Self.refreshInterval}-+let remaining = Self.refreshInterval - Date().timeIntervalSince(autoRefreshCountdownStartedAt)return max(1, remaining)}diff --git a/CodexBar/Services/CodexStatus/RequestLog.swift b/CodexBar/Services/CodexStatus/RequestLog.swiftindex 1ee946d..c5a60d3 100644--- a/CodexBar/Services/CodexStatus/RequestLog.swift+++ b/CodexBar/Services/CodexStatus/RequestLog.swift@@ -10,7 +10,7 @@ nonisolated struct RequestLogEntry: Identifiable, Equatable {case failurecase emptyResponse}-+let id: UUIDlet requestedAt: Datevar respondedAt: Date?@@ -23,24 +23,24 @@ nonisolated struct RequestLogEntry: Identifiable, Equatable {// 常驻日志存储, 写入来自后台队列, storage 用锁保护, SwiftUI 通知切回主线程发送nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {static let shared = RequestLogStore()-+// nonisolated 存储不能用 @Published 包装可变数组, 这里手动发送变更let objectWillChange = ObservableObjectPublisher()-+// 环形上限避免长时间运行后日志无限增长private static let capacity = 500private static let maxDetailLength = 4000-+private let lock = NSLock()// 最新在前, 既方便渲染也让刚发出的请求更快被回填private var storage: [RequestLogEntry] = []-+var entries: [RequestLogEntry] {withLock { storage }}-+private init() {}-+func beginRequest(method: String, payload: String) -> UUID {let id = UUID()append(@@ -56,7 +56,7 @@ nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {)return id}-+func finishRequest(_ id: UUID, response: String) {update(id) { entry inentry.kind = .response@@ -64,7 +64,7 @@ nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {entry.respondedAt = Date()}}-+func failRequest(_ id: UUID, message: String) {update(id) { entry inentry.kind = .failure@@ -72,7 +72,7 @@ nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {entry.respondedAt = Date()}}-+func recordRequestWithEmptyResponse(method: String, payload: String) {append(RequestLogEntry(@@ -86,7 +86,7 @@ nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {))}-+func recordFailure(method: String? = nil, message: String) {append(RequestLogEntry(@@ -100,15 +100,15 @@ nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {))}-+func clear() {withLock {storage.removeAll()}-+notifyChange()}-+private func append(_ entry: RequestLogEntry) {withLock {storage.insert(entry, at: 0)@@ -116,10 +116,10 @@ nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {storage.removeLast(storage.count - Self.capacity)}}-+notifyChange()}-+private func update(_ id: UUID, _ mutate: (inout RequestLogEntry) -> Void) {let didUpdate = withLock {guard let index = storage.firstIndex(where: { $0.id == id }) else {@@ -128,20 +128,20 @@ nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {mutate(&storage[index])return true}-+guard didUpdate else {return}-+notifyChange()}-+private func withLock<T>(_ work: () -> T) -> T {lock.lock()defer { lock.unlock() }return work()}-+private func notifyChange() {if Thread.isMainThread {objectWillChange.send()@@ -151,17 +151,17 @@ nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {}}}-+// 合法 JSON 重新序列化为稳定、未转义斜杠的日志文本; 非 JSON 错误消息保持原样private static func normalized(_ text: String) -> String {let readableText = jsonNormalized(text) ?? textguard readableText.count > maxDetailLength else {return readableText}-+return String(readableText.prefix(maxDetailLength)) + "…"}-+private static func jsonNormalized(_ text: String) -> String? {guard let data = text.data(using: .utf8),let object = try? JSONSerialization.jsonObject(with: data),@@ -172,7 +172,7 @@ nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {) else {return nil}-- return String(decoding: output, as: UTF8.self)++ return String(bytes: output, encoding: .utf8)}}diff --git a/CodexBar/Services/Process/ProcessTermination.swift b/CodexBar/Services/Process/ProcessTermination.swiftindex ba925cb..fe9f10a 100644--- a/CodexBar/Services/Process/ProcessTermination.swift+++ b/CodexBar/Services/Process/ProcessTermination.swift@@ -10,7 +10,7 @@ nonisolated enum ProcessTerminationResult: Equatable {nonisolated enum ProcessTermination {private static let pollInterval: TimeInterval = 0.02-+static func terminate(_ process: Process,gracefulTimeout: TimeInterval,@@ -19,26 +19,26 @@ nonisolated enum ProcessTermination {guard process.isRunning else {return .alreadyExited}-+process.terminate()if waitUntilExit(process, timeout: gracefulTimeout) {return .terminated}-+kill(process.processIdentifier, SIGKILL)if waitUntilExit(process, timeout: killTimeout) {return .killed}-+return .stillRunning}-+private static func waitUntilExit(_ process: Process, timeout: TimeInterval) -> Bool {let deadline = Date().addingTimeInterval(max(timeout, 0))while process.isRunning, Date() < deadline {Thread.sleep(forTimeInterval: pollInterval)}-+return !process.isRunning}}diff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swiftindex ad843cc..767b3e4 100644--- a/CodexBar/Services/Settings/CodexHookSettings.swift+++ b/CodexBar/Services/Settings/CodexHookSettings.swift@@ -5,10 +5,10 @@ import Foundationfinal class CodexHookSettings: ObservableObject {@Published private(set) var isEnabled = false@Published private(set) var errorMessage: String?-+private let hooksURL: URLprivate let fileManager: FileManager-+init(hooksURL: URL = CodexHookSettings.defaultHooksURL(),fileManager: FileManager = .default@@ -16,7 +16,7 @@ final class CodexHookSettings: ObservableObject {self.hooksURL = hooksURLself.fileManager = fileManager}-+func refresh() {do {let config = try readConfigIfPresent()@@ -30,24 +30,24 @@ final class CodexHookSettings: ObservableObject {errorMessage = "读取 Codex Hook 配置失败: \(error.localizedDescription)"}}-+func setEnabled(_ enabled: Bool) {errorMessage = nil-+do {var config = try readConfigIfPresent()try Self.removeCodexBarHooks(from: &config,executablePath: currentExecutablePath)-+if enabled {try Self.installCodexBarHooks(in: &config,executablePath: currentExecutablePath)}-+try write(config)isEnabled = enabled} catch {@@ -60,12 +60,12 @@ final class CodexHookSettings: ObservableObject {private extension CodexHookSettings {typealias JSONObject = [String: Any]typealias JSONArray = [Any]-+enum HookConfigError: LocalizedError {case invalidRootcase invalidHookscase invalidEvent(String)-+var errorDescription: String? {switch self {case .invalidRoot:@@ -77,7 +77,7 @@ private extension CodexHookSettings {}}}-+static let codexBarEvents = ["SessionStart","UserPromptSubmit",@@ -90,81 +90,81 @@ private extension CodexHookSettings {"SubagentStart","SubagentStop"]-+nonisolated static func defaultHooksURL() -> URL {FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".codex", isDirectory: true).appendingPathComponent("hooks.json")}-+var currentExecutablePath: String {Bundle.main.executableURL?.path?? CommandLine.arguments.first?? "/Applications/CodexBar.app/Contents/MacOS/CodexBar"}-+func readConfigIfPresent() throws -> JSONObject {guard fileManager.fileExists(atPath: hooksURL.path) else {return [:]}-+return try readConfig()}-+func readConfig() throws -> JSONObject {let data = try Data(contentsOf: hooksURL)guard !data.isEmpty else {return [:]}-+let object = try JSONSerialization.jsonObject(with: data)guard let config = object as? JSONObject else {throw HookConfigError.invalidRoot}-+return config}-+func write(_ config: JSONObject) throws {try fileManager.createDirectory(at: hooksURL.deletingLastPathComponent(),withIntermediateDirectories: true)-+let data = try JSONSerialization.data(withJSONObject: config,options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])try data.write(to: hooksURL, options: .atomic)}-+static func containsCodexBarHooks(in config: JSONObject, executablePath: String) -> Bool {guard let hooks = config["hooks"] as? JSONObject else {return false}-+return codexBarEvents.allSatisfy { event inguard let groups = hooks[event] as? JSONArray else {return false}-+return groups.contains { group inguard let group = group as? JSONObject,let handlers = group["hooks"] as? JSONArray else {return false}-+return handlers.contains {isCurrentCodexBarHandler($0, event: event, executablePath: executablePath)}}}}-+static func installCodexBarHooks(in config: inout JSONObject, executablePath: String) throws {var hooks = try hooksObject(from: config)-+for event in codexBarEvents {var groups = try eventGroups(named: event, from: hooks)groups.append([@@ -178,10 +178,10 @@ private extension CodexHookSettings {])hooks[event] = groups}-+config["hooks"] = hooks}-+static func removeCodexBarHooks(from config: inout JSONObject,executablePath: String@@ -189,20 +189,20 @@ private extension CodexHookSettings {guard config["hooks"] != nil else {return}-+var hooks = try hooksObject(from: config)-+for (event, value) in hooks {guard let groups = value as? JSONArray else {throw HookConfigError.invalidEvent(event)}-+let filteredGroups = groups.compactMap { group -> Any? inguard var groupObject = group as? JSONObject,let handlers = groupObject["hooks"] as? JSONArray else {return group}-+let filteredHandlers = handlers.filter {!isCurrentCodexBarHandler($0,@@ -213,45 +213,45 @@ private extension CodexHookSettings {guard !filteredHandlers.isEmpty else {return nil}-+groupObject["hooks"] = filteredHandlersreturn groupObject}-+if filteredGroups.isEmpty {hooks.removeValue(forKey: event)} else {hooks[event] = filteredGroups}}-+config["hooks"] = hooks}-+static func hooksObject(from config: JSONObject) throws -> JSONObject {guard let value = config["hooks"] else {return [:]}-+guard let hooks = value as? JSONObject else {throw HookConfigError.invalidHooks}-+return hooks}-+static func eventGroups(named event: String, from hooks: JSONObject) throws -> JSONArray {guard let value = hooks[event] else {return []}-+guard let groups = value as? JSONArray else {throw HookConfigError.invalidEvent(event)}-+return groups}-+static func isCurrentCodexBarHandler(_ handler: Any,event: String,@@ -259,7 +259,7 @@ private extension CodexHookSettings {) -> Bool {commandIfCommandHandler(handler) == hookCommand(for: event, executablePath: executablePath)}-+// 仅当 handler 是 type == "command" 时返回其 command 字符串, 否则 nilprivate static func commandIfCommandHandler(_ handler: Any) -> String? {guard let handler = handler as? JSONObject,@@ -267,14 +267,14 @@ private extension CodexHookSettings {let command = handler["command"] as? String else {return nil}-+return command}-+static func hookCommand(for event: String, executablePath: String) -> String {"\(shellQuoted(executablePath)) --hook-event \(event)"}-+static func shellQuoted(_ value: String) -> String {"'\(value.replacingOccurrences(of: "'", with: "'\\''"))'"}diff --git a/CodexBar/Services/Settings/GlobalHotKeySettings.swift b/CodexBar/Services/Settings/GlobalHotKeySettings.swiftindex 6f9fd60..d777b74 100644--- a/CodexBar/Services/Settings/GlobalHotKeySettings.swift+++ b/CodexBar/Services/Settings/GlobalHotKeySettings.swift@@ -5,50 +5,50 @@ import Foundationfinal class GlobalHotKeySettings: ObservableObject {@Published private(set) var shortcut: GlobalHotKeyShortcut?@Published private(set) var errorMessage: String?-+private let defaults: UserDefaultsprivate let encoder = JSONEncoder()-+init(defaults: UserDefaults = .standard) {self.defaults = defaultsself.shortcut = Self.loadShortcut(from: defaults)}-+func setShortcut(_ shortcut: GlobalHotKeyShortcut) {if let validationError = shortcut.validationError {errorMessage = validationErrorreturn}-+self.shortcut = shortcutsaveShortcut(shortcut)errorMessage = nil}-+func clearShortcut() {shortcut = nilsaveShortcut(nil)errorMessage = nil}-+func restoreDefaultShortcut() {setShortcut(.default)}-+func setRegistrationError(_ message: String) {errorMessage = message}-+func restoreShortcut(_ shortcut: GlobalHotKeyShortcut?, message: String) {self.shortcut = shortcutsaveShortcut(shortcut)errorMessage = message}-+func clearError() {errorMessage = nil}-+private func saveShortcut(_ shortcut: GlobalHotKeyShortcut?) {if let shortcut, let data = try? encoder.encode(shortcut) {defaults.set(true, forKey: Keys.isEnabled)@@ -58,21 +58,21 @@ final class GlobalHotKeySettings: ObservableObject {defaults.removeObject(forKey: Keys.shortcut)}}-+private static func loadShortcut(from defaults: UserDefaults) -> GlobalHotKeyShortcut? {let hasEnabledValue = defaults.object(forKey: Keys.isEnabled) != nilguard !hasEnabledValue || defaults.bool(forKey: Keys.isEnabled) else {return nil}-+if let data = defaults.data(forKey: Keys.shortcut),let shortcut = try? JSONDecoder().decode(GlobalHotKeyShortcut.self, from: data) {return shortcut}-+return .default}-+private enum Keys {static let isEnabled = "GlobalHotKey.isEnabled"static let shortcut = "GlobalHotKey.shortcut"diff --git a/CodexBar/Services/Settings/LoginItemSettings.swift b/CodexBar/Services/Settings/LoginItemSettings.swiftindex a03dce0..07ca099 100644--- a/CodexBar/Services/Settings/LoginItemSettings.swift+++ b/CodexBar/Services/Settings/LoginItemSettings.swift@@ -6,21 +6,21 @@ import ServiceManagementfinal class LoginItemSettings: ObservableObject {@Published private(set) var isEnabled = false@Published private(set) var errorMessage: String?-+func refresh() {isEnabled = SMAppService.mainApp.status == .enabled}-+func setEnabled(_ enabled: Bool) {errorMessage = nil-+do {if enabled {try SMAppService.mainApp.register()} else {try SMAppService.mainApp.unregister()}-+refresh()} catch {refresh()diff --git a/CodexBar/Services/Updates/AppUpdater.swift b/CodexBar/Services/Updates/AppUpdater.swiftindex ebb695a..c5b829d 100644--- a/CodexBar/Services/Updates/AppUpdater.swift+++ b/CodexBar/Services/Updates/AppUpdater.swift@@ -9,23 +9,23 @@ final class AppUpdater: NSObject, ObservableObject {@Published private(set) var panelUpdateMessage: String?@Published private(set) var availableUpdateMessage: String?@Published private(set) var automaticallyChecksForUpdates = false-+var canConfigureAutomaticChecks: Bool { updaterController != nil }-+private var updaterController: SPUStandardUpdaterController?private var clearSettingsStatusMessageTask: Task<Void, Never>?private var isManualCheckInProgress = false-+private static let missingUpdateConfigurationMessage = "未配置更新资源"-+init(bundle: Bundle = .main) {super.init()-+// 开发环境可能没有 Sparkle feed 或公钥, 此时保留设置 UI, 但禁用更新能力guard Self.hasUsableSparkleConfiguration(in: bundle) else {return}-+updaterController = SPUStandardUpdaterController(startingUpdater: true,updaterDelegate: self,@@ -33,64 +33,64 @@ final class AppUpdater: NSObject, ObservableObject {)refreshAutomaticCheckSetting()}-+func checkForUpdates() {guard let updaterController else {showSettingsStatusMessage(Self.missingUpdateConfigurationMessage)return}-+if let availableUpdateMessage {showSettingsStatusMessage(availableUpdateMessage, autoDismissDelay: nil)return}-+isManualCheckInProgress = trueshowSettingsStatusMessage("正在检查更新")updaterController.updater.checkForUpdateInformation()}-+func startUpdate() {guard let updaterController else {showSettingsStatusMessage(Self.missingUpdateConfigurationMessage)return}-+NSApplication.shared.activate()updaterController.checkForUpdates(nil)}-+func setAutomaticallyChecksForUpdates(_ isEnabled: Bool) {guard let updaterController else {automaticallyChecksForUpdates = falseshowSettingsStatusMessage(Self.missingUpdateConfigurationMessage)return}-+updaterController.updater.automaticallyChecksForUpdates = isEnabledrefreshAutomaticCheckSetting()}-+func refreshAutomaticCheckSetting() {automaticallyChecksForUpdates = updaterController?.updater.automaticallyChecksForUpdates ?? false}-+private func showSettingsStatusMessage(_ message: String, autoDismissDelay: Duration? = .seconds(3)) {clearSettingsStatusMessageTask?.cancel()settingsStatusMessage = message-+guard let autoDismissDelay else {clearSettingsStatusMessageTask = nilreturn}-+clearSettingsStatusMessageTask = Task { [weak self] intry? await Task.sleep(for: autoDismissDelay)guard !Task.isCancelled else { return }self?.settingsStatusMessage = nil}}-+private static func hasUsableSparkleConfiguration(in bundle: Bundle) -> Bool {guardlet feedURLString = bundle.object(forInfoDictionaryKey: "SUFeedURL") as? String,@@ -100,7 +100,7 @@ final class AppUpdater: NSObject, ObservableObject {else {return false}-+return !publicKey.isEmpty}}@@ -109,32 +109,32 @@ extension AppUpdater: SPUUpdaterDelegate {func updater(_: SPUUpdater, didFindValidUpdate item: SUAppcastItem) {let message = "发现新版本: v\(item.displayVersionString)"availableUpdateMessage = message-+if isManualCheckInProgress {showSettingsStatusMessage(message, autoDismissDelay: nil)} else {panelUpdateMessage = message}-+isManualCheckInProgress = false}-+func updaterDidNotFindUpdate(_: SPUUpdater, error _: Error) {availableUpdateMessage = nilpanelUpdateMessage = nil-+if isManualCheckInProgress {showSettingsStatusMessage("没有可用更新", autoDismissDelay: .milliseconds(1000))}-+isManualCheckInProgress = false}-+func updater(_: SPUUpdater, didAbortWithError _: Error) {guard isManualCheckInProgress else {return}-+showSettingsStatusMessage("检查更新失败")isManualCheckInProgress = false}diff --git a/CodexBar/Services/WorkflowStats/JSONLines.swift b/CodexBar/Services/WorkflowStats/JSONLines.swiftindex 767787b..208af89 100644--- a/CodexBar/Services/WorkflowStats/JSONLines.swift+++ b/CodexBar/Services/WorkflowStats/JSONLines.swift@@ -5,15 +5,18 @@ nonisolated enum JSONLines {static func decode<T: Decodable>(_ type: T.Type = T.self, from data: Data) -> [T] {decodeWithFailures(type, from: data).values}-+static func decodeWithFailures<T: Decodable>(_ type: T.Type = T.self,from data: Data) -> JSONLinesDecodeResult<T> {- let text = String(decoding: data, as: UTF8.self)+ guard let text = String(bytes: data, encoding: .utf8) else {+ return JSONLinesDecodeResult(values: [], failedLineCount: data.isEmpty ? 0 : 1)+ }+let decoder = JSONDecoder()var failedLineCount = 0-+let values = text.split(whereSeparator: \.isNewline).compactMap { line -> T? in@@ -21,15 +24,15 @@ nonisolated enum JSONLines {guard !trimmedLine.isEmpty, let lineData = trimmedLine.data(using: .utf8) else {return nil}-+if let value = try? decoder.decode(T.self, from: lineData) {return value}-+failedLineCount += 1return nil}-+return JSONLinesDecodeResult(values: values, failedLineCount: failedLineCount)}}diff --git a/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift b/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swiftindex d6b9f83..699ca10 100644--- a/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift+++ b/CodexBar/Services/WorkflowStats/WorkflowHookEventRecorder.swift@@ -6,31 +6,29 @@ nonisolated enum WorkflowHookEventRecorder {guard let fallbackEventName = hookEventName(from: arguments) else {return false}-+try? record(fallbackEventName: fallbackEventName)return true}-+private static func hookEventName(from arguments: [String]) -> String? {- for argument in arguments.dropFirst() {- if argument.hasPrefix("--hook-event=") {- return normalizedHookEventName(String(argument.dropFirst("--hook-event=".count)))- }+ for argument in arguments.dropFirst() where argument.hasPrefix("--hook-event=") {+ return normalizedHookEventName(String(argument.dropFirst("--hook-event=".count)))}-+if let optionIndex = arguments.firstIndex(of: "--hook-event"),arguments.indices.contains(arguments.index(after: optionIndex)) {return normalizedHookEventName(arguments[arguments.index(after: optionIndex)])}-+return nil}-+private static func normalizedHookEventName(_ value: String) -> String? {let trimmedValue = value.trimmingCharacters(in: .whitespacesAndNewlines)return trimmedValue.isEmpty ? nil : trimmedValue}-+private static func record(fallbackEventName: String) throws {let payload = stdinPayload()let eventName = payload.string(for: "hook_event_name")@@ -52,68 +50,68 @@ nonisolated enum WorkflowHookEventRecorder {sessionId: sessionId,turnId: turnId)-+try recordStatsTransaction(event: event)}-+private static func recordStatsTransaction(event: WorkflowHookEvent) throws {try WorkflowStatsStorage.withExclusiveLock {let dateKey = WorkflowStatsStorage.dateKey(for: event.timestamp)let eventLogURL = WorkflowStatsStorage.eventLogURL(for: dateKey)var maintenanceState = WorkflowStatsStorage.loadMaintenanceState()-+try append(event.jsonLineData(), to: eventLogURL)maintenanceState.markPending(dateKey)try WorkflowStatsStorage.saveMaintenanceState(maintenanceState)}}-+private static func append(_ data: Data, to url: URL) throws {try FileManager.default.createDirectory(at: url.deletingLastPathComponent(),withIntermediateDirectories: true)-+if !FileManager.default.fileExists(atPath: url.path) {FileManager.default.createFile(atPath: url.path, contents: nil)}-+let fileHandle = try FileHandle(forWritingTo: url)defer {try? fileHandle.close()}-+try fileHandle.seekToEnd()try fileHandle.write(contentsOf: data)}-+private static func stdinPayload() -> WorkflowHookPayload {guard isatty(STDIN_FILENO) == 0 else {return WorkflowHookPayload(values: [:])}-+let data = FileHandle.standardInput.readDataToEndOfFile()guard !data.isEmpty,let object = try? JSONSerialization.jsonObject(with: data),let values = object as? [String: Any] else {return WorkflowHookPayload(values: [:])}-+return WorkflowHookPayload(values: values)}}private nonisolated struct WorkflowHookPayload {let values: [String: Any]-+func string(for key: String) -> String? {Self.normalizedString(values[key])}-+func date(for key: String) -> Date? {Self.normalizedDate(values[key])}-+private static func normalizedString(_ value: Any?) -> String? {switch value {case let string as String:@@ -125,7 +123,7 @@ private nonisolated struct WorkflowHookPayload {return nil}}-+private static func normalizedDate(_ value: Any?) -> Date? {switch value {case let string as String:@@ -138,24 +136,24 @@ private nonisolated struct WorkflowHookPayload {return nil}}-+private static func date(from string: String) -> Date? {let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)guard !trimmedString.isEmpty else {return nil}-+if let date = ISO8601DateFormatter.codexFractional.date(from: trimmedString) {return date}-+if let date = DateFormatter.codexLocalTimestamp.date(from: trimmedString) {return date}-+return iso8601Formatter.date(from: trimmedString)}-+private static let iso8601Formatter: ISO8601DateFormatter = {let formatter = ISO8601DateFormatter()formatter.formatOptions = [.withInternetDateTime]diff --git a/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift b/CodexBar/Services/WorkflowStats/WorkflowStatsService.swiftindex 7adc3c6..aad0ec0 100644--- a/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift+++ b/CodexBar/Services/WorkflowStats/WorkflowStatsService.swift@@ -7,7 +7,7 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {private let eventsDirectoryURL: URLprivate let dailyLogURL: URLprivate static let eventReadChunkSize = 64 * 1024-+init(eventsDirectoryURL: URL = WorkflowStatsStorage.eventsDirectoryURL(),dailyLogURL: URL = WorkflowStatsStorage.dailyURL()@@ -15,7 +15,7 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {self.eventsDirectoryURL = eventsDirectoryURLself.dailyLogURL = dailyLogURL}-+func loadSnapshot(performMaintenance: Bool = false) async -> WorkflowStatsSnapshot {await withCheckedContinuation { continuation inqueue.async {@@ -23,39 +23,39 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {}}}-+private func loadSnapshotOnQueue(performMaintenance: Bool) -> WorkflowStatsSnapshot {if performMaintenance {performMaintenanceIfNeededOnQueue()}-+if let aggregates = loadDailyAggregatesOnQueue(), !aggregates.isEmpty {return WorkflowStatsSnapshot(dailyAggregates: aggregates)}-+return .empty}-+private func loadDailyAggregatesOnQueue() -> [WorkflowDailyAggregate]? {guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {return nil}-+let aggregates = WorkflowDailyAggregate.decodeJSONLines(from: data)guard !aggregates.isEmpty else {return nil}-+return WorkflowDailyAggregate.normalized(aggregates: aggregates)}-+private func performMaintenanceIfNeededOnQueue() {do {let tasks = try prepareMaintenanceTasksOnQueue()guard !tasks.isEmpty else {return}-+for task in tasks {do {let result = try buildDailyAggregate(for: task)@@ -64,24 +64,24 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {markDirtyOnQueue(task.dateKey)}}-+try pruneExpiredEventFilesOnQueue()} catch {return}}-+private func prepareMaintenanceTasksOnQueue() throws -> [WorkflowStatsMaintenanceTask] {let eventDateKeys = eventDateKeysOnQueue()let dailyDecodeResult = loadDailyAggregatesWithFailuresOnQueue()-+return try WorkflowStatsStorage.withExclusiveLock {var state = WorkflowStatsStorage.loadMaintenanceState()var changedState = state.normalize()let dailyByDate = dailyDecodeResult.values.reduce(into: [String: WorkflowDailyAggregate]()) { result, aggregate inresult[aggregate.date] = aggregate}-+let changedByRebuild = markRebuildDates(eventDateKeys: eventDateKeys,dailyDecodeResult: dailyDecodeResult,@@ -90,21 +90,21 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {)let changedByReconcile = reconcileEventFiles(eventDateKeys: eventDateKeys, state: &state)changedState = changedState || changedByRebuild || changedByReconcile-+let tasks = makeMaintenanceTasks(state: &state,dailyByDate: dailyByDate,changedState: &changedState)-+if changedState {try WorkflowStatsStorage.saveMaintenanceState(state)}-+return tasks}}-+private func markRebuildDates(eventDateKeys: [String],dailyDecodeResult: JSONLinesDecodeResult<WorkflowDailyAggregate>,@@ -112,29 +112,29 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {state: inout WorkflowStatsMaintenanceState) -> Bool {var changed = false-+if state.schema != WorkflowStatsMaintenanceState.currentSchema {changed = markDirty(eventDateKeys, in: &state) || changedstate.schema = WorkflowStatsMaintenanceState.currentSchemachanged = true}-+if dailyDecodeResult.failedLineCount > 0 || (dailyDecodeResult.values.isEmpty && !eventDateKeys.isEmpty) {changed = markDirty(eventDateKeys, in: &state) || changed}-+changed = markDirty(eventDateKeys.filter { dailyByDate[$0] == nil }, in: &state) || changedchanged = markDirty(state.pending.filter { dailyByDate[$0] == nil }, in: &state) || changed-+return changed}-+private func reconcileEventFiles(eventDateKeys: [String],state: inout WorkflowStatsMaintenanceState) -> Bool {var changed = markDirty(eventDateKeys.filter { state.days[$0] == nil }, in: &state)-+for (dateKey, day) in state.days {let actualSize = eventLogSize(for: dateKey)if actualSize < day.offset || day.offset != day.size {@@ -147,10 +147,10 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {changed = true}}-+return changed}-+private func makeMaintenanceTasks(state: inout WorkflowStatsMaintenanceState,dailyByDate: [String: WorkflowDailyAggregate],@@ -158,7 +158,7 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {) -> [WorkflowStatsMaintenanceTask] {let dirty = Set(state.dirty)var tasks = state.dirty.map { dirtyTask(for: $0) }-+for dateKey in state.pending where !dirty.contains(dateKey) {let day = state.days[dateKey] ?? WorkflowStatsDayMaintenanceState()let size = eventLogSize(for: dateKey)@@ -167,14 +167,14 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {changedState = truecontinue}-+guard let baseAggregate = dailyByDate[dateKey] else {state.markDirty(dateKey)changedState = truetasks.append(dirtyTask(for: dateKey, size: size))continue}-+tasks.append(pendingTask(for: dateKey,@@ -184,24 +184,24 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {))}-+return tasks}-+private func markDirty(_ dateKeys: [String],in state: inout WorkflowStatsMaintenanceState) -> Bool {let previousDirty = state.dirtylet previousDays = state.days-+for dateKey in dateKeys {state.markDirty(dateKey)}-+return previousDirty != state.dirty || previousDays != state.days}-+private func dirtyTask(for dateKey: String, size: UInt64? = nil) -> WorkflowStatsMaintenanceTask {WorkflowStatsMaintenanceTask(dateKey: dateKey,@@ -211,7 +211,7 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {existingCorrupt: 0)}-+private func pendingTask(for dateKey: String,day: WorkflowStatsDayMaintenanceState,@@ -226,23 +226,23 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {existingCorrupt: day.corrupt)}-+private func eventLogURL(for dateKey: String) -> URL {eventsDirectoryURL.appendingPathComponent("\(dateKey).jsonl", isDirectory: false)}-+private func eventLogSize(for dateKey: String) -> UInt64 {WorkflowStatsStorage.fileSize(at: eventLogURL(for: dateKey))}-+private func loadDailyAggregatesWithFailuresOnQueue() -> JSONLinesDecodeResult<WorkflowDailyAggregate> {guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {return JSONLinesDecodeResult(values: [], failedLineCount: 0)}-+return JSONLines.decodeWithFailures(from: data)}-+private func eventDateKeysOnQueue() -> [String] {guard let contents = try? FileManager.default.contentsOfDirectory(at: eventsDirectoryURL,@@ -250,14 +250,14 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {) else {return []}-+return contents.filter { $0.pathExtension == "jsonl" }.map { $0.deletingPathExtension().lastPathComponent }.filter { WorkflowStatsStorage.isValidDateKey($0) }.sorted()}-+private func buildDailyAggregate(for task: WorkflowStatsMaintenanceTask) throws -> WorkflowStatsMaintenanceResult {@@ -265,7 +265,7 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {var corrupt = task.existingCorruptvar identifierCache = WorkflowDailyIdentifierCache(aggregate: aggregate)let keepsIdentifiers = keepsIdentifiers(for: task.dateKey)-+corrupt += try readEvents(at: eventLogURL(for: task.dateKey),from: task.startOffset,@@ -277,7 +277,7 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {identifierCache: &identifierCache)}-+aggregate.compactIdentifiersIfNeeded(keepsIdentifiers: keepsIdentifiers)return WorkflowStatsMaintenanceResult(dateKey: task.dateKey,@@ -286,7 +286,7 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {corrupt: corrupt)}-+private func readEvents(at url: URL,from startOffset: UInt64,@@ -296,127 +296,131 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {guard size > startOffset else {return 0}-+let fileHandle = try FileHandle(forReadingFrom: url)defer {try? fileHandle.close()}-+try fileHandle.seek(toOffset: startOffset)-+let decoder = JSONDecoder()var remainingBytes = size - startOffsetvar buffer = Data()var corrupt = 0-+while remainingBytes > 0 {let readSize = min(Int(remainingBytes), Self.eventReadChunkSize)guard let chunk = try fileHandle.read(upToCount: readSize), !chunk.isEmpty else {break}-+remainingBytes -= UInt64(chunk.count)buffer.append(chunk)-+while let newlineIndex = buffer.firstIndex(of: 0x0A) {let lineData = buffer[..<newlineIndex]corrupt += decode(lineData, using: decoder, record: record)buffer.removeSubrange(...newlineIndex)}}-+if !buffer.isEmpty {corrupt += decode(buffer, using: decoder, record: record)}-+return corrupt}-+private func decode(_ lineData: Data.SubSequence,using decoder: JSONDecoder,record: (WorkflowHookEvent) -> Void) -> Int {- let line = String(decoding: lineData, as: UTF8.self)+ guard let line = String(bytes: lineData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)+ else {+ return 1+ }+guard !line.isEmpty else {return 0}-+guard let data = line.data(using: .utf8),let event = try? decoder.decode(WorkflowHookEvent.self, from: data) else {return 1}-+record(event)return 0}-+private func commit(_ result: WorkflowStatsMaintenanceResult) throws {guard try eventLogHasNotShrunk(for: result) else {return}-+try writeDailyAggregate(result.aggregate)try commitMaintenanceState(result)}-+private func eventLogHasNotShrunk(for result: WorkflowStatsMaintenanceResult) throws -> Bool {try WorkflowStatsStorage.withExclusiveLock {let currentSize = WorkflowStatsStorage.fileSize(at: eventLogURL(for: result.dateKey))var state = WorkflowStatsStorage.loadMaintenanceState()-+guard currentSize >= result.size else {state.markDirty(result.dateKey)try WorkflowStatsStorage.saveMaintenanceState(state)return false}-+return true}}-+private func writeDailyAggregate(_ aggregate: WorkflowDailyAggregate) throws {try FileManager.default.createDirectory(at: dailyLogURL.deletingLastPathComponent(),withIntermediateDirectories: true)-+var aggregates = loadDailyAggregatesOnQueue() ?? []upsert(aggregate, into: &aggregates)aggregates = WorkflowDailyAggregate.normalized(aggregates: aggregates)let data = try WorkflowDailyAggregate.encodeJSONLines(aggregates)try data.write(to: dailyLogURL, options: .atomic)}-+private func commitMaintenanceState(_ result: WorkflowStatsMaintenanceResult) throws {try WorkflowStatsStorage.withExclusiveLock {let currentSize = WorkflowStatsStorage.fileSize(at: eventLogURL(for: result.dateKey))var state = WorkflowStatsStorage.loadMaintenanceState()-+guard currentSize >= result.size else {state.markDirty(result.dateKey)try WorkflowStatsStorage.saveMaintenanceState(state)return}-+state.days[result.dateKey] = WorkflowStatsDayMaintenanceState(offset: result.size,size: result.size,corrupt: result.corrupt)state.removeDirty(result.dateKey)-+if currentSize == result.size {state.removePending(result.dateKey)} else {state.markPending(result.dateKey)}-+try WorkflowStatsStorage.saveMaintenanceState(state)}}-+private func upsert(_ aggregate: WorkflowDailyAggregate, into aggregates: inout [WorkflowDailyAggregate]) {if let index = aggregates.firstIndex(where: { $0.date == aggregate.date }) {aggregates[index] = aggregate@@ -424,7 +428,7 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {aggregates.append(aggregate)}}-+private func markDirtyOnQueue(_ dateKey: String) {try? WorkflowStatsStorage.withExclusiveLock {var state = WorkflowStatsStorage.loadMaintenanceState()@@ -432,71 +436,71 @@ nonisolated final class WorkflowStatsService: @unchecked Sendable {try WorkflowStatsStorage.saveMaintenanceState(state)}}-+private func pruneExpiredEventFilesOnQueue() throws {let cutoffDate = WorkflowStatsStorage.retentionCutoffDate()let expiredDateKeys = eventDateKeysOnQueue().filter { dateKey inguard let date = DateFormatter.codexDay.date(from: dateKey) else {return false}-+return date < cutoffDate}-+guard !expiredDateKeys.isEmpty else {return}-+try WorkflowStatsStorage.withExclusiveLock {var state = WorkflowStatsStorage.loadMaintenanceState()for dateKey in expiredDateKeys {try? FileManager.default.removeItem(at: eventLogURL(for: dateKey))state.remove(dateKey)}-+try WorkflowStatsStorage.saveMaintenanceState(state)}}-+private func keepsIdentifiers(for dateKey: String) -> Bool {guard let date = DateFormatter.codexDay.date(from: dateKey) else {return true}-+return date >= WorkflowStatsStorage.identifierRetentionCutoffDate()}-+}nonisolated enum WorkflowStatsStorage {private static let retentionDayCount = 210private static let identifierRetentionDayCount = 7-+static func eventsDirectoryURL() -> URL {directoryURL().appendingPathComponent("events", isDirectory: true)}-+static func eventLogURL(for dateKey: String) -> URL {eventsDirectoryURL().appendingPathComponent("\(dateKey).jsonl", isDirectory: false)}-+static func dailyURL() -> URL {directoryURL().appendingPathComponent("daily.jsonl", isDirectory: false)}-+static func lockURL() -> URL {directoryURL().appendingPathComponent("stats.lock", isDirectory: false)}-+static func maintenanceURL() -> URL {directoryURL().appendingPathComponent("maintenance.json", isDirectory: false)}-+static func directoryURL() -> URL {let applicationSupportURL = FileManager.default.urls(for: .applicationSupportDirectory,@@ -504,78 +508,78 @@ nonisolated enum WorkflowStatsStorage {).first ?? URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library", isDirectory: true).appendingPathComponent("Application Support", isDirectory: true)-+return applicationSupportURL.appendingPathComponent("CodexBar", isDirectory: true).appendingPathComponent("HookEvents", isDirectory: true)}-+static func withExclusiveLock<T>(_ work: () throws -> T) throws -> T {try FileManager.default.createDirectory(at: directoryURL(),withIntermediateDirectories: true)-+let lockURL = lockURL()if !FileManager.default.fileExists(atPath: lockURL.path) {FileManager.default.createFile(atPath: lockURL.path, contents: nil)}-+let lockHandle = try FileHandle(forUpdating: lockURL)defer {try? lockHandle.close()}-+if flock(lockHandle.fileDescriptor, LOCK_EX) != 0 {throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)}-+defer {flock(lockHandle.fileDescriptor, LOCK_UN)}-+return try work()}-+static func loadMaintenanceState() -> WorkflowStatsMaintenanceState {let url = maintenanceURL()guard let data = try? Data(contentsOf: url), !data.isEmpty,let state = try? JSONDecoder().decode(WorkflowStatsMaintenanceState.self, from: data) else {return WorkflowStatsMaintenanceState()}-+return state}-+static func saveMaintenanceState(_ state: WorkflowStatsMaintenanceState) throws {try FileManager.default.createDirectory(at: directoryURL(),withIntermediateDirectories: true)-+let encoder = JSONEncoder()encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]let data = try encoder.encode(state)try data.write(to: maintenanceURL(), options: .atomic)}-+static func fileSize(at url: URL) -> UInt64 {guard let attributes = try? FileManager.default.attributesOfItem(atPath: url.path),let fileSize = attributes[.size] as? NSNumber else {return 0}-+return fileSize.uint64Value}-+static func retentionCutoffDate(today: Date = Date(), calendar: Calendar = .current) -> Date {cutoffDate(dayCount: retentionDayCount, today: today, calendar: calendar)}-+static func identifierRetentionCutoffDate(today: Date = Date(), calendar: Calendar = .current) -> Date {cutoffDate(dayCount: identifierRetentionDayCount, today: today, calendar: calendar)}-+private static func cutoffDate(dayCount: Int, today: Date, calendar: Calendar) -> Date {let todayStart = calendar.startOfDay(for: today)return calendar.date(@@ -584,11 +588,11 @@ nonisolated enum WorkflowStatsStorage {to: todayStart) ?? todayStart}-+static func dateKey(for date: Date) -> String {DateFormatter.codexDay.string(from: date)}-+static func isValidDateKey(_ dateKey: String) -> Bool {DateFormatter.codexDay.date(from: dateKey) != nil}@@ -598,7 +602,7 @@ nonisolated struct WorkflowStatsDayMaintenanceState: Codable, Equatable {var offset: UInt64var size: UInt64var corrupt: Int-+init(offset: UInt64 = 0, size: UInt64 = 0, corrupt: Int = 0) {self.offset = offsetself.size = size@@ -608,12 +612,12 @@ nonisolated struct WorkflowStatsDayMaintenanceState: Codable, Equatable {nonisolated struct WorkflowStatsMaintenanceState: Codable, Equatable {static let currentSchema = 2-+var schema: Intvar pending: [String]var dirty: [String]var days: [String: WorkflowStatsDayMaintenanceState]-+init(schema: Int = Self.currentSchema,pending: [String] = [],@@ -625,7 +629,7 @@ nonisolated struct WorkflowStatsMaintenanceState: Codable, Equatable {self.dirty = Self.normalizedDates(dirty)self.days = days}-+init(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self)self.schema = try container.decodeIfPresent(Int.self, forKey: .schema) ?? Self.currentSchema@@ -633,53 +637,53 @@ nonisolated struct WorkflowStatsMaintenanceState: Codable, Equatable {self.dirty = Self.normalizedDates(try container.decodeIfPresent([String].self, forKey: .dirty) ?? [])self.days = try container.decodeIfPresent([String: WorkflowStatsDayMaintenanceState].self, forKey: .days) ?? [:]}-+mutating func markPending(_ dateKey: String) {pending = Self.inserting(dateKey, into: pending)ensureDayState(for: dateKey)}-+mutating func markDirty(_ dateKey: String) {dirty = Self.inserting(dateKey, into: dirty)ensureDayState(for: dateKey)}-+mutating func removePending(_ dateKey: String) {pending.removeAll { $0 == dateKey }}-+mutating func removeDirty(_ dateKey: String) {dirty.removeAll { $0 == dateKey }}-+mutating func remove(_ dateKey: String) {removePending(dateKey)removeDirty(dateKey)days.removeValue(forKey: dateKey)}-+mutating func normalize() -> Bool {let previousPending = pendinglet previousDirty = dirtylet previousDays = days-+pending = Self.normalizedDates(pending)dirty = Self.normalizedDates(dirty)days = days.filter { WorkflowStatsStorage.isValidDateKey($0.key) }-+return previousPending != pending || previousDirty != dirty || previousDays != days}-+private mutating func ensureDayState(for dateKey: String) {if days[dateKey] == nil {days[dateKey] = WorkflowStatsDayMaintenanceState()}}-+private static func inserting(_ dateKey: String, into dates: [String]) -> [String] {normalizedDates(dates + [dateKey])}-+private static func normalizedDates(_ dates: [String]) -> [String] {Array(Set(dates.filter { WorkflowStatsStorage.isValidDateKey($0) })).sorted()}@@ -703,32 +707,32 @@ private nonisolated struct WorkflowStatsMaintenanceResult {@MainActorfinal class WorkflowStatsViewModel: ObservableObject {@Published private(set) var snapshot = WorkflowStatsSnapshot.empty-+private static let minimumRefreshInterval: TimeInterval = 5-+private let service: WorkflowStatsServiceprivate var isRefreshing = falseprivate var lastRefreshedAt: Date?-+init(service: WorkflowStatsService = WorkflowStatsService()) {self.service = service}-+func refreshIfNeeded(performMaintenance: Bool = false) {guard performMaintenance || Date().timeIntervalSince(lastRefreshedAt ?? .distantPast) > Self.minimumRefreshInterval else {return}-+refresh(performMaintenance: performMaintenance)}-+func refresh(performMaintenance: Bool = false) {guard !isRefreshing else {return}-+isRefreshing = true-+Task {snapshot = await service.loadSnapshot(performMaintenance: performMaintenance)lastRefreshedAt = Date()diff --git a/CodexBar/Views/Log/LogView.swift b/CodexBar/Views/Log/LogView.swiftindex 72710a5..b583662 100644--- a/CodexBar/Views/Log/LogView.swift+++ b/CodexBar/Views/Log/LogView.swift@@ -2,14 +2,14 @@ import SwiftUIstruct LogView: View {@ObservedObject var store: RequestLogStore-+var body: some View {// 整表是锁内拷贝, 每轮渲染只取一次复用let entries = store.entriesVStack(spacing: 0) {header(entries: entries)Divider()-+if entries.isEmpty {emptyState} else {@@ -18,24 +18,24 @@ struct LogView: View {}.frame(minWidth: 640, minHeight: 480)}-+private func header(entries: [RequestLogEntry]) -> some View {HStack(spacing: 10) {Image(systemName: "doc.text.magnifyingglass").foregroundStyle(.tint)-+Text("Codex app-server 日志").font(.headline)-+Text("\(entries.count)").font(.caption.monospacedDigit()).foregroundStyle(.secondary).padding(.horizontal, 7).padding(.vertical, 2).background(Capsule().fill(.quaternary))-+Spacer()-+Button {store.clear()} label: {@@ -47,19 +47,19 @@ struct LogView: View {.padding(.horizontal, 16).padding(.vertical, 10)}-+private var emptyState: some View {VStack(spacing: 8) {Image(systemName: "tray").font(.largeTitle).foregroundStyle(.tertiary)-+Text("暂无日志").foregroundStyle(.secondary)}.frame(maxWidth: .infinity, maxHeight: .infinity)}-+private func logList(entries: [RequestLogEntry]) -> some View {ScrollView {LazyVStack(alignment: .leading, spacing: 0) {@@ -76,7 +76,7 @@ struct LogView: View {private struct LogRow: View {let entry: RequestLogEntry@State private var isExpanded = false-+var body: some View {VStack(alignment: .leading, spacing: 0) {Button {@@ -87,13 +87,13 @@ private struct LogRow: View {summary}.buttonStyle(.plain)-+if isExpanded {VStack(alignment: .leading, spacing: 8) {if let request = entry.request {payloadBlock(caption: "请求", time: entry.requestedAt, text: request, color: .primary)}-+if let detail = entry.detail {payloadBlock(caption: detailCaption,@@ -115,7 +115,7 @@ private struct LogRow: View {.padding(.horizontal, 16).padding(.vertical, 8)}-+private var summary: some View {HStack(spacing: 8) {Image(systemName: "chevron.right")@@ -123,11 +123,11 @@ private struct LogRow: View {.foregroundStyle(.secondary).rotationEffect(.degrees(isExpanded ? 90 : 0)).frame(width: 12)-+Text(Self.timeFormatter.string(from: entry.requestedAt)).font(.caption.monospaced()).foregroundStyle(.secondary)-+Text(entry.kind.label).font(.caption2.weight(.semibold)).foregroundStyle(entry.kind.tint)@@ -137,7 +137,7 @@ private struct LogRow: View {RoundedRectangle(cornerRadius: 4, style: .continuous).fill(entry.kind.tint.opacity(0.14)))-+if let method = entry.method {Text(method).font(.caption.weight(.medium).monospaced())@@ -150,26 +150,26 @@ private struct LogRow: View {.lineLimit(1).truncationMode(.tail)}-+Spacer(minLength: 0)}.contentShape(Rectangle())}-+private func payloadBlock(caption: String, time: Date?, text: String, color: Color) -> some View {VStack(alignment: .leading, spacing: 2) {HStack(spacing: 6) {Text(caption).font(.caption2.weight(.semibold)).foregroundStyle(.tertiary)-+if let time {Text(Self.timeFormatter.string(from: time)).font(.caption2.monospaced()).foregroundStyle(.tertiary)}}-+Text(text).font(.caption.monospaced()).foregroundStyle(color)@@ -178,7 +178,7 @@ private struct LogRow: View {.frame(maxWidth: .infinity, alignment: .leading)}}-+private var detailCaption: String {switch entry.kind {case .response, .emptyResponse:@@ -189,7 +189,7 @@ private struct LogRow: View {return "详情"}}-+private static let timeFormatter: DateFormatter = {let formatter = DateFormatter()formatter.locale = Locale(identifier: "en_US_POSIX")@@ -211,7 +211,7 @@ private extension RequestLogEntry.Kind {return "请求"}}-+var tint: Color {switch self {case .pending:diff --git a/CodexBar/Views/Menu/AutoRefreshCountdownView.swift b/CodexBar/Views/Menu/AutoRefreshCountdownView.swiftindex 94a78c9..4697dcf 100644--- a/CodexBar/Views/Menu/AutoRefreshCountdownView.swift+++ b/CodexBar/Views/Menu/AutoRefreshCountdownView.swift@@ -5,7 +5,7 @@ struct AutoRefreshCountdownTimeline: View {let interval: TimeIntervallet isActive: Boollet color: Color-+var body: some View {if isActive {TimelineView(.periodic(from: .now, by: 1)) { timeline in@@ -15,7 +15,7 @@ struct AutoRefreshCountdownTimeline: View {circle(now: Date())}}-+private func circle(now: Date) -> AutoRefreshCountdownCircle {AutoRefreshCountdownCircle(startedAt: startedAt,@@ -33,21 +33,21 @@ private struct AutoRefreshCountdownCircle: View {let now: Datelet isActive: Boollet color: Color-+private var progress: Double {guard interval > 0 else {return 0}-+let elapsed = max(0, now.timeIntervalSince(startedAt))return max(0, 1 - elapsed / interval)}-+var body: some View {ZStack {Circle().stroke(color.opacity(0.15), lineWidth: 1.4)-+Circle().trim(from: 1 - progress, to: 1).stroke(@@ -60,7 +60,7 @@ private struct AutoRefreshCountdownCircle: View {// 只让刷新起点变化触发动画, 避免每秒 tick 被补间.animation(isActive ? .linear(duration: Metrics.resetAnimationDuration) : nil, value: startedAt)}-+private enum Metrics {static let resetAnimationDuration: TimeInterval = 0.50}diff --git a/CodexBar/Views/Menu/CodexStatusMenuSections.swift b/CodexBar/Views/Menu/CodexStatusMenuSections.swiftindex db3821e..e8ddee9 100644--- a/CodexBar/Views/Menu/CodexStatusMenuSections.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuSections.swift@@ -14,14 +14,14 @@ struct AccountCard: View {let isRefreshing: Boollet onRefresh: () -> Void@State private var isEmailBlurred = false-+var body: some View {HStack(spacing: 8) {Image(systemName: "person.fill").font(.system(size: MenuMetrics.accountIconSize, weight: .medium)).foregroundStyle(.tint).onTapGesture(count: 2, perform: onRefresh)-+Text(title).font(.caption.weight(.semibold)).lineLimit(1)@@ -32,15 +32,15 @@ struct AccountCard: View {guard isEmail else { return }isEmailBlurred.toggle()}-+if isRefreshing {ProgressView().controlSize(.mini).padding(.leading, 2)}-+Spacer()-+if let plan {Text(plan.uppercased()).font(.caption2.weight(.bold))@@ -55,14 +55,14 @@ struct AccountCard: View {isEmailBlurred = false}}-+private static func planBadgeTint(for plan: String) -> Color {let normalizedPlan = plan.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()return planTintRules.first { rule inrule.keywords.contains { normalizedPlan.contains($0) }}?.tint ?? .cyan}-+private static let planTintRules: [(keywords: [String], tint: Color)] = [(["enterprise"], Color(hex: 0x15803D)),(["team", "business"], Color(hex: 0xD97706)),@@ -77,14 +77,14 @@ struct StatusAccountCard: View {let loadState: CodexLoadStatelet isRefreshing: Boollet onRefresh: () -> Void-+var body: some View {HStack(spacing: 8) {Image(systemName: "person.fill").font(.system(size: MenuMetrics.accountIconSize, weight: .medium)).foregroundStyle(statusDisplay.color).onTapGesture(count: 2, perform: onRefresh)-+if let text = statusDisplay.text {Text(text).font(.caption.weight(.semibold))@@ -92,20 +92,20 @@ struct StatusAccountCard: View {.lineLimit(1).truncationMode(.middle)}-+if isRefreshing {ProgressView().controlSize(.mini).padding(.leading, 2)}-+Spacer()}.padding(.horizontal, MenuMetrics.panelPadding).padding(.vertical, 8).liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)}-+private var statusDisplay: (text: String?, color: Color) {switch loadState {case .notLoggedIn:@@ -132,14 +132,14 @@ struct EmptyDataPanel: View {struct QuotaLimitsSection: View {let limits: [CodexQuotaLimitSnapshot]let isStale: Bool-+var body: some View {VStack(alignment: .leading, spacing: 8) {ForEach(limits) { limit inif limit.id != limits.first?.id {LiquidGlassDivider()}-+quotaLimitSection(limit)}}@@ -147,7 +147,7 @@ struct QuotaLimitsSection: View {.padding(MenuMetrics.panelPadding).liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)}-+private func quotaLimitSection(_ limit: CodexQuotaLimitSnapshot) -> some View {VStack(alignment: .leading, spacing: 6) {Text(limit.title)@@ -155,7 +155,7 @@ struct QuotaLimitsSection: View {.foregroundStyle(.primary).lineLimit(1).truncationMode(.middle)-+VStack(spacing: 8) {ForEach(limit.windows) { window inQuotaRow(window: window)@@ -172,7 +172,7 @@ struct UpdatedAtRow: View {let isCountdownActive: Boollet updateMessage: String?let startUpdate: () -> Void-+var body: some View {HStack {HStack(spacing: 5) {@@ -182,10 +182,10 @@ struct UpdatedAtRow: View {isActive: isCountdownActive,color: .blue)-+Text("数据更新时间").foregroundStyle(Self.secondaryTextColor)-+Text(Self.timeFormatter.string(from: snapshot.generatedAt)).monospacedDigit().contentTransition(.numericText())@@ -193,9 +193,9 @@ struct UpdatedAtRow: View {}.font(.caption2).animation(Metrics.statusAnimation, value: snapshot.generatedAt)-+Spacer()-+if let updateMessage {Text(updateMessage).font(.caption2.monospacedDigit())@@ -208,16 +208,16 @@ struct UpdatedAtRow: View {}.animation(Metrics.statusAnimation, value: updateMessage)}-+private static let timeFormatter: DateFormatter = {let formatter = DateFormatter()formatter.locale = Locale(identifier: "zh_CN")formatter.dateFormat = "HH:mm:ss"return formatter}()-+private static let secondaryTextColor = Color.codexSecondaryLabel-+private enum Metrics {static let statusAnimation = Animation.codexStatus}diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swiftindex 9bef567..718963a 100644--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift@@ -2,20 +2,20 @@ import Combineimport SwiftUI@MainActor-final class PopoverVisibilityState: ObservableObject {+final class MenuSurfaceVisibilityState: ObservableObject {@Published var isVisible = false}struct CodexStatusMenuView: View {static let menuWidth: CGFloat = Metrics.padding * 2 + MenuMetrics.panelPadding * 2 + UsageHeatmap.Metrics.totalWidth-+@ObservedObject var viewModel: CodexStatusViewModel@ObservedObject var workflowStatsViewModel: WorkflowStatsViewModel@ObservedObject var codexHookSettings: CodexHookSettings- @ObservedObject var popoverVisibility: PopoverVisibilityState+ @ObservedObject var menuSurfaceVisibility: MenuSurfaceVisibilityStatelet onUsageHeatmapHoverChange: (UsageHeatmapHoverContext?) -> Void@EnvironmentObject private var appUpdater: AppUpdater-+var body: some View {VStack(alignment: .leading, spacing: Metrics.verticalSpacing) {content@@ -36,7 +36,7 @@ private extension CodexStatusMenuView {static let verticalSpacing: CGFloat = 10static let statusAnimation = Animation.codexStatus}-+@ViewBuildervar content: some View {if let snapshot = viewModel.snapshot {@@ -47,7 +47,7 @@ private extension CodexStatusMenuView {isRefreshing: viewModel.isRefreshing,onRefresh: viewModel.refresh)-+dataSection(snapshot)} else {// 仅展示未登录 / 初始化失败两种特殊状态, 其余错误只进日志@@ -59,7 +59,7 @@ private extension CodexStatusMenuView {EmptyDataPanel()}}-+@ViewBuilderfunc dataSection(_ snapshot: CodexQuotaSnapshot) -> some View {if snapshot.limits.isEmpty, snapshot.usage == nil {@@ -68,7 +68,7 @@ private extension CodexStatusMenuView {if !snapshot.limits.isEmpty {QuotaLimitsSection(limits: snapshot.limits, isStale: snapshot.isRateLimitsStale)}-+if let usage = snapshot.usage {UsageSummaryView(usage: usage,@@ -79,19 +79,19 @@ private extension CodexStatusMenuView {)}}-+updatedAtRow(for: snapshot).padding(.horizontal, Metrics.panelPadding).padding(.vertical, 7).liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius)}-+func updatedAtRow(for snapshot: CodexQuotaSnapshot) -> some View {UpdatedAtRow(snapshot: snapshot,countdownStartedAt: viewModel.autoRefreshCountdownStartedAt ?? snapshot.generatedAt,countdownInterval: viewModel.autoRefreshInterval,- isCountdownActive: popoverVisibility.isVisible,+ isCountdownActive: menuSurfaceVisibility.isVisible,updateMessage: appUpdater.panelUpdateMessage,startUpdate: appUpdater.startUpdate)diff --git a/CodexBar/Views/Menu/QuotaRow.swift b/CodexBar/Views/Menu/QuotaRow.swiftindex 23a1539..c879198 100644--- a/CodexBar/Views/Menu/QuotaRow.swift+++ b/CodexBar/Views/Menu/QuotaRow.swift@@ -2,7 +2,7 @@ import SwiftUIstruct QuotaRow: View {let window: QuotaWindow-+var body: some View {HStack(alignment: .center, spacing: 0) {Text(window.label)@@ -11,19 +11,19 @@ struct QuotaRow: View {.minimumScaleFactor(Metrics.labelMinimumScaleFactor).allowsTightening(true).frame(width: Metrics.labelWidth, alignment: .center)-+SegmentedQuotaBar(percent: displayPercent).padding(.leading, Metrics.labelBarSpacing)-+Text(percentText).font(.caption.monospacedDigit().weight(.semibold)).foregroundStyle(percentColor).lineLimit(1).frame(width: Metrics.percentWidth, alignment: .leading).padding(.leading, Metrics.barPercentSpacing)-+Spacer(minLength: Metrics.percentResetSpacing)-+Text(resetText).font(.caption2.monospacedDigit()).foregroundStyle(.secondary)@@ -44,35 +44,35 @@ private extension QuotaRow {static let percentResetSpacing: CGFloat = 6static let resetWidth: CGFloat = 75}-+var resetText: String {guard window.hasData, let resetsAt = window.resetsAt else {return "--"}-+return Self.resetFormatter.string(from: resetsAt)}-+var percentText: String {guard window.hasData else {return "--"}-+return "\(window.remainingPercent)%"}-+var displayPercent: Int? {window.hasData ? window.remainingPercent : nil}-+var percentColor: Color {guard window.hasData else {return .secondary}-+return QuotaBarPalette.filledColor(for: window.remainingPercent)}-+static let resetFormatter: DateFormatter = {let formatter = DateFormatter()formatter.locale = Locale(identifier: "zh_CN")@@ -86,7 +86,7 @@ private enum QuotaBarPalette {guard let percent else {return placeholderColor}-+switch percent {case 80...:return green@@ -100,7 +100,7 @@ private enum QuotaBarPalette {return red}}-+static let placeholderColor = Color(hex: 0xE5E7EB)private static let green = Color(hex: 0x16A085)private static let teal = Color(hex: 0x5DADE2)@@ -111,10 +111,10 @@ private enum QuotaBarPalette {private struct SegmentedQuotaBar: View {let percent: Int?-+var body: some View {let filledColor = QuotaBarPalette.filledColor(for: percent)-+HStack(spacing: Metrics.segmentSpacing) {ForEach(0..<Metrics.segmentCount, id: \.self) { index inCapsule(style: .continuous)@@ -132,17 +132,17 @@ private extension SegmentedQuotaBar {static let segmentWidth: CGFloat = 3.5static let segmentSpacing: CGFloat = 2static let segmentHeight: CGFloat = 12-+static var totalWidth: CGFloat {CGFloat(segmentCount) * segmentWidth + CGFloat(segmentCount - 1) * segmentSpacing}}-+var filledSegments: Int {guard let percent else {return 0}-+return Int((Double(percent) / 100.0 * Double(Metrics.segmentCount)).rounded())}}diff --git a/CodexBar/Views/Menu/TokenCountText.swift b/CodexBar/Views/Menu/TokenCountText.swiftindex 63e74e2..0e16ff7 100644--- a/CodexBar/Views/Menu/TokenCountText.swift+++ b/CodexBar/Views/Menu/TokenCountText.swift@@ -5,24 +5,24 @@ struct TokenCountText: View {var font: Font = .caption.monospacedDigit().weight(.semibold)var reservedNumericWidth: CGFloat?var reservedUnitWidth: CGFloat?-+var body: some View {content.font(font).lineLimit(1).minimumScaleFactor(0.8)}-+@ViewBuilderprivate var content: some View {let parts = TokenCountFormatter.parts(from: tokens)-+if let reservedNumericWidth {HStack(spacing: 0) {Text(parts.number).numericRollTransition(value: Double(tokens)).frame(minWidth: reservedNumericWidth, alignment: .trailing)-+if let unit = parts.unit {Text(unit).frame(width: reservedUnitWidth, alignment: .trailing)@@ -37,7 +37,7 @@ struct TokenCountText: View {private struct NumericRollTransition: ViewModifier {let value: Double@State private var previous: Double?-+func body(content: Content) -> some View {content.contentTransition(.numericText(countsDown: countsDown))@@ -45,7 +45,7 @@ private struct NumericRollTransition: ViewModifier {previous = newValue}}-+private var countsDown: Bool {guard let previous else {return false@@ -73,13 +73,13 @@ private enum TokenCountFormatter {return TokenCountParts(number: String(tokens), unit: nil)}}-+private static func decimal(_ value: Double) -> String {let roundingScale: Double = value >= 0.1 ? 10 : 100let rounded = (value * roundingScale).rounded() / roundingScalereturn formatter.string(from: NSNumber(value: rounded)) ?? String(format: "%.1f", rounded)}-+private static let formatter: NumberFormatter = {let formatter = NumberFormatter()formatter.numberStyle = .decimal@@ -88,11 +88,11 @@ private enum TokenCountFormatter {formatter.maximumFractionDigits = 2return formatter}()-+struct TokenCountParts {let number: Stringlet unit: String?-+var text: String {number + (unit ?? "")}diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swiftindex 1bf639a..f5bf09f 100644--- a/CodexBar/Views/Menu/UsageHeatmap.swift+++ b/CodexBar/Views/Menu/UsageHeatmap.swift@@ -30,7 +30,7 @@ struct UsageSummaryView: View {private let peakTokens: Int@State private var hoverSelection: UsageHeatmapSelection?@State private var heatmapGridScreenFrame: CGRect?-+init(usage: CodexUsageSnapshot,workflowStats: WorkflowStatsSnapshot,@@ -42,7 +42,7 @@ struct UsageSummaryView: View {self.isStale = isStaleself.showsWorkflowStats = showsWorkflowStatsself.onHoverContextChange = onHoverContextChange-+let days = UsageHeatmapDay.grid(usage: usage,workflowStats: workflowStats,@@ -53,11 +53,11 @@ struct UsageSummaryView: View {self.days = daysself.peakTokens = max(days.lazy.compactMap { $0?.tokensForHeatmap }.max() ?? 0, 1)}-+var body: some View {VStack(alignment: .leading, spacing: 8) {metricsGrid-+UsageHeatmap(days: days,selection: $hoverSelection,@@ -85,7 +85,7 @@ struct UsageSummaryView: View {.animation(Metrics.statusAnimation, value: usage).animation(Metrics.statusAnimation, value: days)}-+private var metricsGrid: some View {HStack(alignment: .firstTextBaseline, spacing: Metrics.metricSpacing) {tokenMetric(label: "全时累计", value: usage.summary.lifetimeTokens)@@ -95,13 +95,13 @@ struct UsageSummaryView: View {textMetric(label: "最长任务", value: Self.durationText(seconds: usage.summary.longestRunningTurnSec))}}-+private func tokenMetric(label: String, value: Int) -> some View {metric(label: label, alignment: .center) {TokenCountText(tokens: value)}}-+private func textMetric(label: String, value: String) -> some View {metric(label: label, alignment: .center) {Text(value)@@ -110,7 +110,7 @@ struct UsageSummaryView: View {.minimumScaleFactor(0.8)}}-+private func metric<Content: View>(label: String,alignment: Alignment,@@ -121,52 +121,52 @@ struct UsageSummaryView: View {.font(.caption2).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: alignment)-+value().frame(maxWidth: .infinity, alignment: alignment)}.frame(maxWidth: .infinity)}-+private static func dayText(_ days: Int?) -> String {guard let days else {return "--"}-+return "\(max(days, 0))天"}-+private static func durationText(seconds: Int?) -> String {guard let seconds else {return "--"}-+let duration = max(seconds, 0)let days = duration / 86_400let hours = duration % 86_400 / 3_600let minutes = duration % 3_600 / 60let remainingSeconds = duration % 60-+if days > 0 {return "\(days) 天 \(hours) 时 \(minutes) 分 \(remainingSeconds) 秒"}-+if hours > 0 {return "\(hours) 时 \(minutes) 分 \(remainingSeconds) 秒"}-+if minutes > 0 {return "\(minutes) 分 \(remainingSeconds) 秒"}-+return "\(remainingSeconds) 秒"}-+private enum Metrics {static let metricSpacing: CGFloat = 8static let statusAnimation = Animation.codexStatus}-+private var hoverContext: UsageHeatmapHoverContext? {hoverSelection.map {UsageHeatmapHoverContext(@@ -179,17 +179,17 @@ struct UsageSummaryView: View {)}}-+private func hoveredSquareScreenFrame(for selection: UsageHeatmapSelection) -> CGRect? {guard let heatmapGridScreenFrame else {return nil}-+let x = heatmapGridScreenFrame.minX + CGFloat(selection.column) * UsageHeatmap.Metrics.squarePitchlet y = heatmapGridScreenFrame.maxY- CGFloat(selection.row) * UsageHeatmap.Metrics.squarePitch- UsageHeatmap.Metrics.squareSize-+return CGRect(x: x,y: y,@@ -197,23 +197,23 @@ struct UsageSummaryView: View {height: UsageHeatmap.Metrics.squareSize)}-+private func refreshHoveredDay(from days: [UsageHeatmapDay?]) {guard let hoverSelection else {return}-+guard let updatedDay = days.compactMap({ $0 }).first(where: { $0.id == hoverSelection.day.id }) else {withAnimation(Metrics.statusAnimation) {self.hoverSelection = nil}return}-+guard updatedDay != hoverSelection.day else {return}-+withAnimation(Metrics.statusAnimation) {self.hoverSelection = UsageHeatmapSelection(day: updatedDay,@@ -222,7 +222,7 @@ struct UsageSummaryView: View {)}}-+private func clearHover() {hoverSelection = nilonHoverContextChange(nil)@@ -236,7 +236,7 @@ struct UsageHeatmap: View {@State private var snapSelection: UsageHeatmapSelection?@State private var hoverClearTask: Task<Void, Never>?private let peakTokens: Int-+init(days: [UsageHeatmapDay?],selection: Binding<UsageHeatmapSelection?>,@@ -248,7 +248,7 @@ struct UsageHeatmap: View {self._selection = selectionself.peakTokens = peakTokens}-+var body: some View {heatmapGrid.frame(height: Metrics.height)@@ -257,16 +257,16 @@ struct UsageHeatmap: View {onScreenFrameChange(nil)}}-+private var heatmapGrid: some View {VStack(alignment: .leading, spacing: 6) {HStack(alignment: .firstTextBaseline) {Text("近 \(Metrics.columnCount) 周").font(.caption2.weight(.medium)).foregroundStyle(.secondary)-+Spacer()-+if let dateRangeText {Text(dateRangeText).font(.caption2.monospacedDigit())@@ -274,13 +274,13 @@ struct UsageHeatmap: View {.lineLimit(1)}}-+HStack(alignment: .top, spacing: Metrics.squareSpacing) {ForEach(0..<Metrics.columnCount, id: \.self) { column inVStack(spacing: Metrics.squareSpacing) {ForEach(0..<Metrics.rowCount, id: \.self) { row inlet index = column * Metrics.rowCount + row-+if days.indices.contains(index), let day = days[index] {UsageHeatmapSquare(day: day,@@ -311,48 +311,48 @@ struct UsageHeatmap: View {}.frame(maxWidth: .infinity, alignment: .leading)}-+private var visibleDays: [UsageHeatmapDay] {days.compactMap { $0 }}-+private var dateRangeText: String? {guard let firstDate = visibleDays.first?.startDate,let lastDate = visibleDays.last?.startDate else {return nil}-+return "\(firstDate) ~ \(lastDate)"}-+private func updatePointerLocation(_ point: CGPoint) {guard let target = snappedSelection(at: point) else {scheduleDeactivate()return}-+cancelHoverClearTask()-+if !matches(snapSelection, target) {withAnimation(.snappy(duration: Metrics.snapAnimationDuration)) {snapSelection = target}}-+if !matches(selection, target) {activate(target)}}-+private func snappedSelection(at point: CGPoint) -> UsageHeatmapSelection? {let column = Int(((point.x - Metrics.squareSize / 2) / Metrics.squarePitch).rounded())let row = Int(((point.y - Metrics.squareSize / 2) / Metrics.squarePitch).rounded())-+guard (0..<Metrics.columnCount).contains(column),(0..<Metrics.rowCount).contains(row) else {return nil}-+let center = CGPoint(x: CGFloat(column) * Metrics.squarePitch + Metrics.squareSize / 2,y: CGFloat(row) * Metrics.squarePitch + Metrics.squareSize / 2@@ -361,21 +361,21 @@ struct UsageHeatmap: View {abs(point.y - center.y) <= Metrics.snapHalfExtent else {return nil}-+let index = column * Metrics.rowCount + rowguard days.indices.contains(index), let day = days[index] else {return nil}-+return UsageHeatmapSelection(day: day, column: column, row: row)}-+private func activate(_ target: UsageHeatmapSelection) {withAnimation(.easeInOut(duration: Metrics.hoverFadeDuration)) {selection = target}}-+private func scheduleDeactivate() {cancelHoverClearTask()hoverClearTask = Task { @MainActor in@@ -383,19 +383,19 @@ struct UsageHeatmap: View {guard !Task.isCancelled else {return}-+withAnimation(.easeInOut(duration: Metrics.hoverFadeDuration)) {snapSelection = nilselection = nil}}}-+private func cancelHoverClearTask() {hoverClearTask?.cancel()hoverClearTask = nil}-+private func matches(_ lhs: UsageHeatmapSelection?, _ rhs: UsageHeatmapSelection) -> Bool {lhs?.day.id == rhs.day.id && lhs?.column == rhs.column && lhs?.row == rhs.row}@@ -413,15 +413,15 @@ extension UsageHeatmap {static let hoverFadeDuration: TimeInterval = 0.15static let hoverExitGraceMilliseconds: UInt64 = 160static let snapHalfExtent: CGFloat = squareSize / 2 + squareSpacing-+static var totalWidth: CGFloat {CGFloat(columnCount) * squareSize + CGFloat(columnCount - 1) * squareSpacing}-+static var gridHeight: CGFloat {CGFloat(rowCount) * squareSize + CGFloat(rowCount - 1) * squareSpacing}-+static func preferredDetailSide(for column: Int) -> UsageHeatmapDetailSide {column < columnCount / 2 ? .left : .right}@@ -432,7 +432,7 @@ private struct UsageHeatmapSquare: View {let day: UsageHeatmapDaylet percent: Doublelet isHovered: Bool-+var body: some View {RoundedRectangle(cornerRadius: 4, style: .continuous).fill(fillColor)@@ -446,39 +446,39 @@ private struct UsageHeatmapSquare: View {.contentShape(RoundedRectangle(cornerRadius: 4, style: .continuous)).animation(.snappy(duration: 0.14), value: isHovered)}-+private var clampedPercent: Double {min(max(percent, 0), 1)}-+private var fillColor: Color {guard day.tokensForHeatmap > 0 else {return Color.blue.opacity(isHovered ? 0.16 : 0.08)}-+let intensity = pow(clampedPercent, 0.62)let opacity = 0.18 + intensity * 0.68return Color.blue.opacity(isHovered ? min(opacity + 0.10, 1.0) : opacity)}-+private var borderColor: Color {if isHovered {return Color.blue.opacity(0.78)}-+return Color.blue.opacity(day.tokensForHeatmap > 0 ? 0.18 : 0.10)}}private struct HeatmapScreenFrameReader: NSViewRepresentable {let onChange: (CGRect?) -> Void-+func makeNSView(context: Context) -> HeatmapScreenFrameReportingView {let view = HeatmapScreenFrameReportingView()view.onChange = onChangereturn view}-+func updateNSView(_ nsView: HeatmapScreenFrameReportingView, context: Context) {nsView.onChange = onChangensView.scheduleReport()@@ -490,17 +490,17 @@ private final class HeatmapScreenFrameReportingView: NSView {var onChange: ((CGRect?) -> Void)?private var lastReportedFrame: CGRect?private var reportScheduled = false-+override func viewDidMoveToWindow() {super.viewDidMoveToWindow()scheduleReport()}-+override func layout() {super.layout()reportFrame()}-+func scheduleReport() {// updateNSView 每次 hover 重渲染都会调到这里, 合并掉重复的待执行 report, 至多保留一个。guard !reportScheduled else {@@ -516,22 +516,22 @@ private final class HeatmapScreenFrameReportingView: NSView {self.reportFrame()}}-+private func reportFrame() {guard let window else {updateFrame(nil)return}-+let frameInWindow = convert(bounds, to: nil)updateFrame(window.convertToScreen(frameInWindow))}-+private func updateFrame(_ frame: CGRect?) {guard frame != lastReportedFrame else {return}-+lastReportedFrame = frameonChange?(frame)}@@ -540,10 +540,10 @@ private final class HeatmapScreenFrameReportingView: NSView {struct UsageHeatmapDayDetailView: View {let context: UsageHeatmapHoverContext@Environment(\.colorScheme) private var colorScheme-+var body: some View {let panelSize = Self.panelSize(showsWorkflowStats: context.showsWorkflowStats)-+VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {detailContent}@@ -566,17 +566,17 @@ struct UsageHeatmapDayDetailView: View {.clipShape(RoundedRectangle(cornerRadius: Metrics.cornerRadius, style: .continuous)).animation(Metrics.statusAnimation, value: context)}-+static var panelCornerRadius: CGFloat {Metrics.cornerRadius}-+static func panelSize(showsWorkflowStats: Bool) -> CGSize {showsWorkflowStats? CGSize(width: Metrics.workflowPanelWidth, height: Metrics.workflowPanelHeight): CGSize(width: Metrics.tokenPanelWidth, height: Metrics.tokenPanelHeight)}-+@ViewBuilderprivate var detailContent: some View {if context.showsWorkflowStats {@@ -585,7 +585,7 @@ struct UsageHeatmapDayDetailView: View {tokenOnlyContent}}-+private var header: some View {HStack(alignment: .center, spacing: Metrics.headerSpacing) {VStack(alignment: .leading, spacing: 4) {@@ -594,84 +594,84 @@ struct UsageHeatmapDayDetailView: View {.padding(.vertical, 3).liquidGlassCapsule(tint: .accentColor)}-+Spacer(minLength: 8)-+tokenText.frame(minWidth: Metrics.tokenMinimumWidth, alignment: .trailing)}}-+private var workflowContent: some View {VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {header-+LiquidGlassDivider().opacity(0.72)-+VStack(alignment: .leading, spacing: Metrics.metricSpacing) {tokenIntensityMetricRow-+ForEach(workflowMetricRows) { row inmetricRow(row)}}}}-+private var tokenOnlyContent: some View {VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {header-+LiquidGlassDivider().opacity(0.62)-+tokenOnlyFooter}}-+private var tokenOnlyFooter: some View {metricRowLayout {tokenIntensityDotText("用量强度").foregroundStyle(.secondary)-+Spacer(minLength: 8)-+tokenIntensityStrip.frame(width: Metrics.tokenIntensityStripWidth)}}-+private var tokenIntensityMetricRow: some View {metricRowLayout {tokenIntensityDotText("用量强度").foregroundStyle(.secondary).frame(width: Metrics.metricLabelWidth, alignment: .leading)-+tokenIntensityStrip.frame(width: Metrics.tokenIntensityStripWidth).frame(maxWidth: .infinity, alignment: .trailing)}}-+private var tokenIntensityDot: some View {metricDot(tint: .blue, darkOpacity: 0.88, lightOpacity: 0.76)}-+private func metricRowLayout<Content: View>(@ViewBuilder content: () -> Content) -> some View {HStack(spacing: Metrics.metricRowSpacing, content: content).font(.system(size: Metrics.workflowFontSize)).frame(height: Metrics.metricRowHeight)}-+private func metricDot(tint: Color, darkOpacity: Double = 0.86, lightOpacity: Double = 0.72) -> some View {Circle().fill(tint.opacity(colorScheme == .dark ? darkOpacity : lightOpacity)).frame(width: Metrics.metricDotSize, height: Metrics.metricDotSize)}-+private var tokenIntensityStrip: some View {HStack(spacing: Metrics.tokenIntensitySegmentSpacing) {ForEach(0..<Metrics.tokenIntensitySegmentCount, id: \.self) { index in@@ -682,7 +682,7 @@ struct UsageHeatmapDayDetailView: View {}.frame(height: Metrics.tokenIntensityStripHeight)}-+private var workflowMetricRows: [WorkflowMetricRow] {[WorkflowMetricRow(label: "会话总数", value: context.day.workflowStats.sessionCount, tint: .green),@@ -693,7 +693,7 @@ struct UsageHeatmapDayDetailView: View {WorkflowMetricRow(label: "上下文压缩", value: context.day.workflowStats.contextCompactionCount, tint: .purple)]}-+private var dateText: some View {AnimatedDateText(startDate: context.day.startDate, font: dateFont).foregroundStyle(Color.codexSecondaryLabel)@@ -701,7 +701,7 @@ struct UsageHeatmapDayDetailView: View {.fixedSize(horizontal: true, vertical: false).layoutPriority(1)}-+@ViewBuilderprivate var tokenText: some View {if let tokenCount = context.day.tokenCount {@@ -719,60 +719,60 @@ struct UsageHeatmapDayDetailView: View {.contentTransition(.opacity)}}-+private var dateFont: Font {.caption2.monospacedDigit()}-+private var tokenFont: Font {.system(size: 14).monospacedDigit().weight(.semibold)}-+private var tokenIntensityLevel: Int {guard context.day.tokensForHeatmap > 0 else {return 0}-+let percent = tokenIntensityPercentreturn min(Metrics.tokenIntensitySegmentCount,max(1, Int(ceil(percent * Double(Metrics.tokenIntensitySegmentCount)))))}-+private var tokenIntensityPercent: Double {guard context.peakTokens > 0 else {return 0}-+return min(max(Double(context.day.tokensForHeatmap) / Double(context.peakTokens), 0), 1)}-+private func tokenIntensityFill(for index: Int) -> Color {guard index < tokenIntensityLevel else {return Color.blue.opacity(colorScheme == .dark ? 0.14 : 0.10)}-+let opacity = colorScheme == .dark ? 0.42 + Double(index) * 0.10 : 0.34 + Double(index) * 0.09return Color.blue.opacity(min(opacity, 0.88))}-+private func metricRow(_ row: WorkflowMetricRow) -> some View {metricRowLayout {metricDot(tint: row.tint)Text(row.label).foregroundStyle(.secondary).frame(width: Metrics.metricLabelWidth, alignment: .leading)-+fittingMetricValue("\(row.value)", comparison: Double(row.value))}}-+private func fittingMetricValue(_ value: String, comparison: Double) -> some View {ViewThatFits(in: .horizontal) {metricValueText(value).fixedSize(horizontal: true, vertical: false)-+metricValueText(value).minimumScaleFactor(Metrics.metricValueMinimumScale).allowsTightening(true)@@ -781,7 +781,7 @@ struct UsageHeatmapDayDetailView: View {.layoutPriority(1).frame(maxWidth: .infinity, alignment: .trailing)}-+private func metricValueText(_ value: String) -> some View {Text(value).foregroundStyle(Color.codexLabel)@@ -789,26 +789,26 @@ struct UsageHeatmapDayDetailView: View {.monospacedDigit().lineLimit(1)}-+private var panelBackingFill: Color {Color(nsColor: .windowBackgroundColor).opacity(colorScheme == .dark ? 0.90 : 0.86)}-+private var panelBoundaryColor: Color {colorScheme == .dark? .white.opacity(0.18): .black.opacity(0.14)}-+private struct WorkflowMetricRow: Identifiable {let label: Stringlet value: Intlet tint: Color-+var id: String { label }}-+private enum Metrics {static let workflowPanelWidth: CGFloat = 212static let workflowPanelHeight: CGFloat = 189@@ -840,7 +840,7 @@ struct UsageHeatmapDayDetailView: View {private struct AnimatedDateText: View {let startDate: Stringlet font: Font-+var body: some View {if let components {HStack(spacing: 0) {@@ -858,7 +858,7 @@ private struct AnimatedDateText: View {.contentTransition(.numericText())}}-+private func dateValue(_ components: DateTextComponents) -> Double {guard let year = Int(components.year),let month = Int(components.month),@@ -867,17 +867,17 @@ private struct AnimatedDateText: View {}return Double(year * 10_000 + month * 100 + day)}-+private var components: DateTextComponents? {let parts = startDate.split(separator: "-", omittingEmptySubsequences: false).map(String.init)guard parts.count == 3,parts.allSatisfy({ !$0.isEmpty && $0.allSatisfy(\.isNumber) }) else {return nil}-+return DateTextComponents(year: parts[0], month: parts[1], day: parts[2])}-+private struct DateTextComponents {let year: Stringlet month: Stringdiff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex 4b9975b..7bba4a9 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -8,7 +8,7 @@ struct AppSettingsView: View {@StateObject private var codexVersions = CodexCLIVersionViewModel()@ObservedObject var codexHookSettings: CodexHookSettings@ObservedObject var globalHotKeySettings: GlobalHotKeySettings-+var body: some View {VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {VStack(alignment: .leading, spacing: Metrics.rowSpacing) {@@ -26,9 +26,9 @@ struct AppSettingsView: View {}.padding(Metrics.panelPadding).liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius)-+settingsErrorPanel-+HStack(alignment: .center, spacing: 12) {quitButtonSpacer()@@ -74,7 +74,7 @@ private extension AppSettingsView {static let iconWidth: CGFloat = 18static let statusAnimation = Animation.codexStatus}-+var launchAtLoginRow: some View {SettingsToggleRow(icon: "power",@@ -85,7 +85,7 @@ private extension AppSettingsView {))}-+var automaticUpdateCheckRow: some View {SettingsToggleRow(icon: "arrow.triangle.2.circlepath",@@ -97,11 +97,11 @@ private extension AppSettingsView {isEnabled: appUpdater.canConfigureAutomaticChecks)}-+var hotKeyRow: some View {HotKeyRecorderRow(settings: globalHotKeySettings)}-+var codexHookRow: some View {VStack(alignment: .leading, spacing: 4) {SettingsToggleRow(@@ -112,11 +112,11 @@ private extension AppSettingsView {set: { codexHookSettings.setEnabled($0) }))-+HStack(alignment: .top, spacing: 10) {Color.clear.frame(width: Metrics.iconWidth)-+Text("开启后将会写入全局 Codex Hook 配置\n用于近 30 周数据中展示更多统计数据\n该数据仅保存在本机").font(.caption).foregroundStyle(.secondary)@@ -124,26 +124,26 @@ private extension AppSettingsView {}}}-+var versionRow: some View {let status = versionStatus-+return HStack(spacing: 10) {Image(systemName: "info.circle").frame(width: Metrics.iconWidth).foregroundStyle(.secondary)-+Text("CodexBar 版本")-+Spacer()-+Text(status.text).font(status.isVersionLabel ? .body.monospacedDigit() : .body).foregroundStyle(.secondary).lineLimit(1).contentTransition(.opacity).animation(Metrics.statusAnimation, value: status.text)-+if appUpdater.availableUpdateMessage != nil {Button {appUpdater.startUpdate()@@ -160,7 +160,7 @@ private extension AppSettingsView {}.animation(Metrics.statusAnimation, value: appUpdater.availableUpdateMessage != nil)}-+// 版本行优先显示更新状态, 没有动态消息时回退到当前版本号var versionStatus: (text: String, isVersionLabel: Bool) {if let message = appUpdater.settingsStatusMessage ?? appUpdater.availableUpdateMessage {@@ -168,20 +168,20 @@ private extension AppSettingsView {}return (Bundle.main.displayVersionLabel, true)}-+var codexVersionSection: some View {CodexVersionSection(snapshot: codexVersions.snapshot,connectionInfo: statusViewModel.codexConnectionInfo)}-+func refreshCodexVersionSection() {// 版本探测较慢且内部会合并并发请求; 连接信息只是缓存读取codexVersions.refresh()statusViewModel.refreshCodexConnectionInfo()}-+@ViewBuildervar settingsErrorPanel: some View {if let message = settingsErrorMessage {@@ -195,7 +195,7 @@ private extension AppSettingsView {.transition(.opacity)}}-+var checkUpdateButton: some View {Button {appUpdater.checkForUpdates()@@ -203,7 +203,7 @@ private extension AppSettingsView {Label("检查更新", systemImage: "arrow.down.circle")}}-+var quitButton: some View {Button(role: .destructive) {NSApplication.shared.terminate(nil)@@ -213,7 +213,7 @@ private extension AppSettingsView {.foregroundStyle(.red).keyboardShortcut("q")}-+var settingsErrorMessage: String? {loginItemSettings.errorMessage ?? codexHookSettings.errorMessage}diff --git a/CodexBar/Views/Settings/CodexVersionSection.swift b/CodexBar/Views/Settings/CodexVersionSection.swiftindex d7ba481..d2888ff 100644--- a/CodexBar/Views/Settings/CodexVersionSection.swift+++ b/CodexBar/Views/Settings/CodexVersionSection.swift@@ -5,25 +5,25 @@ struct CodexVersionSection: View {let snapshot: CodexCLIVersionSnapshotlet connectionInfo: CodexCLIConnectionInfo?@State private var copiedPathResetTasks: [CodexCLIExecutableSource: Task<Void, Never>] = [:]-+var body: some View {VStack(alignment: .leading, spacing: Metrics.rowSpacing) {HStack(spacing: 10) {Image(systemName: "number.circle").frame(width: Metrics.iconWidth).foregroundStyle(.secondary)-+Text("Codex 版本")-+Spacer()}-+LiquidGlassDivider().padding(.leading, Metrics.iconWidth + 10)-+VStack(alignment: .leading, spacing: Metrics.rowSpacing) {codexVersionRow(icon: "terminal", item: snapshot.global)-+codexVersionRow(icon: "app.badge", item: snapshot.bundled)}.padding(.leading, Metrics.childIndent)@@ -32,21 +32,21 @@ struct CodexVersionSection: View {copiedPathResetTasks.values.forEach { $0.cancel() }}}-+private func codexVersionRow(icon: String, item: CodexCLIVersionItem) -> some View {let row = CodexCLIVersionDisplay(item: item, connection: connectionInfo)let isPathCopied = copiedPathResetTasks[item.source] != nil-+return HStack(alignment: .top, spacing: 10) {Image(systemName: icon).frame(width: Metrics.iconWidth).foregroundStyle(.tertiary)-+Text(item.source.displayName).foregroundStyle(.secondary)-+Spacer(minLength: 28)-+VStack(alignment: .trailing, spacing: 3) {HStack(spacing: 12) {if row.isCurrent {@@ -58,7 +58,7 @@ struct CodexVersionSection: View {.liquidGlassCapsule(tint: .green).transition(.opacity)}-+Text(row.displayVersion).font(row.hasVersion ? .body.monospacedDigit() : .body).foregroundStyle(row.hasVersion ? .secondary : .tertiary)@@ -67,7 +67,7 @@ struct CodexVersionSection: View {.animation(Metrics.statusAnimation, value: row.displayVersion)}.animation(Metrics.statusAnimation, value: row.isCurrent)-+if let newerInstalledVersion = row.newerInstalledVersion {Text("已更新至 \(newerInstalledVersion)").font(.caption2.monospacedDigit())@@ -75,7 +75,7 @@ struct CodexVersionSection: View {.lineLimit(1).transition(.opacity)}-+if let path = row.path {CopyablePathText(path: path, isCopied: isPathCopied).animation(Metrics.statusAnimation, value: isPathCopied)@@ -91,20 +91,20 @@ struct CodexVersionSection: View {.animation(Metrics.statusAnimation, value: row.path)}}-+private func copyPathToPasteboard(_ path: String, source: CodexCLIExecutableSource) {NSPasteboard.general.clearContents()NSPasteboard.general.setString(path, forType: .string)-+copiedPathResetTasks[source]?.cancel()copiedPathResetTasks[source] = Task { @MainActor intry? await Task.sleep(for: .milliseconds(1500))guard !Task.isCancelled else { return }-+copiedPathResetTasks[source] = nil}}-+private enum Metrics {static let rowSpacing: CGFloat = 14static let iconWidth: CGFloat = 18@@ -117,7 +117,7 @@ struct CodexVersionSection: View {private struct CopyablePathText: View {let path: Stringlet isCopied: Bool-+var body: some View {ZStack(alignment: .trailing) {Text(path)@@ -126,7 +126,7 @@ private struct CopyablePathText: View {.lineLimit(1).truncationMode(.middle).opacity(isCopied ? 0 : 1)-+Text("已复制").font(.caption2).foregroundStyle(.green)diff --git a/CodexBar/Views/Settings/HotKeyRecorderRow.swift b/CodexBar/Views/Settings/HotKeyRecorderRow.swiftindex 4dfc938..f95e6b0 100644--- a/CodexBar/Views/Settings/HotKeyRecorderRow.swift+++ b/CodexBar/Views/Settings/HotKeyRecorderRow.swift@@ -5,18 +5,18 @@ import SwiftUIstruct HotKeyRecorderRow: View {@ObservedObject var settings: GlobalHotKeySettings@State private var isRecording = false-+var body: some View {VStack(alignment: .leading, spacing: 4) {HStack(spacing: 10) {Image(systemName: "keyboard").frame(width: Metrics.iconWidth).foregroundStyle(.tint)-+Text("使用快捷键")-+Spacer()-+Button {startRecording()} label: {@@ -41,7 +41,7 @@ struct HotKeyRecorderRow: View {).frame(width: 0, height: 0)}-+iconButton(systemName: "arrow.counterclockwise.circle",help: "恢复默认快捷键",@@ -50,7 +50,7 @@ struct HotKeyRecorderRow: View {settings.restoreDefaultShortcut()stopRecording()}-+iconButton(systemName: "xmark.circle",help: "清除设置快捷键",@@ -60,7 +60,7 @@ struct HotKeyRecorderRow: View {stopRecording()}}-+if let message = settings.errorMessage {errorMessageRow(message)}@@ -69,76 +69,76 @@ struct HotKeyRecorderRow: View {resetTransientState()}}-+private var shortcutLabel: String {if isRecording {return "请输入快捷键"}-+return settings.shortcut?.label ?? "未设置"}-+private var canStartRecording: Bool {!hasShortcut || isRecording}-+private var canRestoreDefaultShortcut: Bool {!hasShortcut}-+private var canClearShortcut: Bool {hasShortcut || isRecording}-+private var hasShortcut: Bool {settings.shortcut != nil}-+private func startRecording() {guard settings.shortcut == nil else {return}-+isRecording = true}-+private func stopRecording() {isRecording = false}-+private func resetTransientState() {stopRecording()settings.clearError()}-+private func captureShortcut(_ event: NSEvent) {guard event.keyCode != UInt16(kVK_Escape) else {stopRecording()return}-+guard let shortcut = GlobalHotKeyShortcut(event: event) else {settings.setRegistrationError("无法识别该快捷键")stopRecording()return}-+settings.setShortcut(shortcut)stopRecording()}-+private func errorMessageRow(_ message: String) -> some View {HStack(alignment: .top, spacing: 10) {Color.clear.frame(width: Metrics.iconWidth)-+Text(message).font(.caption).foregroundStyle(.red).fixedSize(horizontal: false, vertical: true)}}-+private func iconButton(systemName: String,help: String,@@ -153,7 +153,7 @@ struct HotKeyRecorderRow: View {.help(help).disabled(isDisabled)}-+private enum Metrics {static let iconWidth: CGFloat = 18static let shortcutButtonMinWidth: CGFloat = 78@@ -165,7 +165,7 @@ private struct HotKeyCaptureView: NSViewRepresentable {let onCapture: (NSEvent) -> Voidlet onCancel: () -> Voidlet onWindowClose: () -> Void-+func makeNSView(context: Context) -> HotKeyCaptureNSView {let view = HotKeyCaptureNSView()view.onCapture = onCapture@@ -173,12 +173,12 @@ private struct HotKeyCaptureView: NSViewRepresentable {view.onWindowClose = onWindowClosereturn view}-+func updateNSView(_ nsView: HotKeyCaptureNSView, context: Context) {nsView.onCapture = onCapturensView.onCancel = onCancelnsView.onWindowClose = onWindowClose-+if isRecording {Task { @MainActor [weak nsView] innsView?.window?.makeFirstResponder(nsView)@@ -194,20 +194,20 @@ private final class HotKeyCaptureNSView: NSView {var onCancel: (() -> Void)?var onWindowClose: (() -> Void)?private var windowCloseObserver: NSObjectProtocol?-+override var acceptsFirstResponder: Bool {true}-+deinit {removeWindowCloseObserver()}-+override func viewDidMoveToWindow() {super.viewDidMoveToWindow()updateWindowCloseObserver()}-+override func keyDown(with event: NSEvent) {if event.keyCode == UInt16(kVK_Escape) {onCancel?()@@ -215,14 +215,14 @@ private final class HotKeyCaptureNSView: NSView {onCapture?(event)}}-+private func updateWindowCloseObserver() {removeWindowCloseObserver()-+guard let window else {return}-+windowCloseObserver = NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification,object: window,@@ -231,7 +231,7 @@ private final class HotKeyCaptureNSView: NSView {self?.onWindowClose?()}}-+private func removeWindowCloseObserver() {if let windowCloseObserver {NotificationCenter.default.removeObserver(windowCloseObserver)diff --git a/CodexBar/Views/Settings/SettingsToggleRow.swift b/CodexBar/Views/Settings/SettingsToggleRow.swiftindex c1c301c..2349a2b 100644--- a/CodexBar/Views/Settings/SettingsToggleRow.swift+++ b/CodexBar/Views/Settings/SettingsToggleRow.swift@@ -5,17 +5,17 @@ struct SettingsToggleRow: View {let title: Stringlet isOn: Binding<Bool>var isEnabled = true-+var body: some View {HStack(spacing: 10) {Image(systemName: icon).frame(width: Metrics.iconWidth).foregroundStyle(.tint)-+Text(title)-+Spacer()-+Toggle(title, isOn: isOn).labelsHidden().toggleStyle(.switch)@@ -23,7 +23,7 @@ struct SettingsToggleRow: View {.disabled(!isEnabled)}}-+private enum Metrics {static let iconWidth: CGFloat = 18}diff --git a/CodexBar/Views/Shared/LiquidGlassStyle.swift b/CodexBar/Views/Shared/LiquidGlassStyle.swiftindex e60d07b..dd5f63d 100644--- a/CodexBar/Views/Shared/LiquidGlassStyle.swift+++ b/CodexBar/Views/Shared/LiquidGlassStyle.swift@@ -8,7 +8,7 @@ extension Color {// 某些自定义 View 需要具体 Color, 不能直接使用 .primary/.secondary 这类 ShapeStylestatic let codexLabel = Color(nsColor: .labelColor)static let codexSecondaryLabel = Color(nsColor: .secondaryLabelColor)-+init(hex: Int) {self.init(red: Double((hex >> 16) & 0xFF) / 255.0,@@ -33,7 +33,7 @@ extension View {isOuterSurface: isOuterSurface)}-+func liquidGlassSurface(cornerRadii: RectangleCornerRadii,isOuterSurface: Bool = false@@ -45,13 +45,13 @@ extension View {)}}-+func liquidGlassCapsule(tint: Color) -> some View {background {LiquidGlassCapsule(tint: tint)}}-+// 数据为缓存回退(本轮刷新失败)时弱化显示func markStale(_ isStale: Bool) -> some View {opacity(isStale ? 0.55 : 1)@@ -81,27 +81,27 @@ private struct LiquidGlassSurface: View {let cornerRadii: RectangleCornerRadiilet isOuterSurface: Bool@Environment(\.colorScheme) private var colorScheme-+var body: some View {let shape = UnevenRoundedRectangle(cornerRadii: cornerRadii, style: .continuous)-+ZStack {shape.fill(baseFill)-+shape.fill(highlightFill).blendMode(.plusLighter)-+LiquidGlassFrostedTexture(isOuterSurface: isOuterSurface).clipShape(shape)-+shape.strokeBorder(borderColor,lineWidth: isOuterSurface ? 1.0 : 0.8)-+shape.strokeBorder(rimHighlightColor, lineWidth: rimLineWidth).shadow(@@ -116,7 +116,7 @@ private struct LiquidGlassSurface: View {x: 0,y: isOuterSurface ? 0.6 : 1.0)-+LiquidGlassSpecular(cornerRadii: cornerRadii).opacity(isOuterSurface ? 0.82 : 0.64)}@@ -139,63 +139,63 @@ private struct LiquidGlassSurface: View {y: isOuterSurface ? 0 : 2)}-+private var baseFill: Color {baseColor.opacity(0.6)}-+private var highlightFill: Color {.white.opacity(isOuterSurface ? 0.12 : 0.14)}-+private var borderColor: Color {.white.opacity(isOuterSurface ? 0.34 : 0.28)}-+private var rimHighlightColor: Color {.white.opacity(isOuterSurface ? 0.36 : 0.50)}-+private var rimLightShadowColor: Color {.white.opacity(colorScheme == .dark ? 0.05 : 0.20)}-+private var rimDarkShadowColor: Color {.black.opacity(colorScheme == .dark ? 0.28 : 0.12)}-+private var rimLineWidth: CGFloat {isOuterSurface ? 0.8 : 1.1}-+private var baseColor: Color {if colorScheme == .dark {return isOuterSurface? Color(red: 0.07, green: 0.08, blue: 0.095): Color(red: 0.16, green: 0.18, blue: 0.20)}-+return isOuterSurface? Color(red: 0.97, green: 0.985, blue: 1.0): Color.white}-+private var raisedHighlightShadowColor: Color {if colorScheme == .dark {return .white.opacity(0.08)}-+return .white.opacity(0.46)}-+private var ambientShadowColor: Color {if isOuterSurface {return .black.opacity(0.16)}-+return .black.opacity(colorScheme == .dark ? 0.34 : 0.18)}-+private var contactShadowColor: Color {.black.opacity(colorScheme == .dark ? 0.20 : 0.08)}@@ -204,7 +204,7 @@ private struct LiquidGlassSurface: View {private struct LiquidGlassFrostedTexture: View {let isOuterSurface: Bool@Environment(\.colorScheme) private var colorScheme-+var body: some View {Canvas(opaque: false, rendersAsynchronously: true) { context, size inlet step: CGFloat = isOuterSurface ? 4 : 3@@ -212,7 +212,7 @@ private struct LiquidGlassFrostedTexture: View {let rows = max(Int((size.height / step).rounded(.up)), 0)let baseOpacity = colorScheme == .dark ? 0.035 : 0.045let outerScale = isOuterSurface ? 0.75 : 1-+for row in 0..<rows {for column in 0..<columns {let sample = Self.noise(column: column, row: row)@@ -231,14 +231,14 @@ private struct LiquidGlassFrostedTexture: View {width: 1,height: 1)-+context.fill(Path(rect), with: .color(color))}}}.allowsHitTesting(false)}-+private nonisolated static func noise(column: Int, row: Int) -> Double {var value = UInt64(column) &* 0x9E3779B185EBCA87value ^= UInt64(row) &* 0xC2B2AE3D27D4EB4F@@ -254,7 +254,7 @@ private struct LiquidGlassFrostedTexture: View {private struct LiquidGlassCapsule: View {let tint: Color@Environment(\.colorScheme) private var colorScheme-+var body: some View {Capsule(style: .continuous).fill(baseFill)@@ -282,7 +282,7 @@ private struct LiquidGlassCapsule: View {.clipShape(Capsule(style: .continuous))}}-+private var baseFill: LinearGradient {LinearGradient(colors: [@@ -293,7 +293,7 @@ private struct LiquidGlassCapsule: View {endPoint: .bottomTrailing)}-+private var baseColor: Color {colorScheme == .dark? Color(red: 0.16, green: 0.18, blue: 0.20)@@ -303,7 +303,7 @@ private struct LiquidGlassCapsule: View {private struct LiquidGlassSpecular: View {let cornerRadii: RectangleCornerRadii-+var body: some View {UnevenRoundedRectangle(cornerRadii: cornerRadii, style: .continuous).strokeBorder(diff --git a/Docs/CodexHook.md b/Docs/CodexHook.mdindex 54375bf..c898cbd 100644--- a/Docs/CodexHook.md+++ b/Docs/CodexHook.md@@ -119,7 +119,7 @@ Hook 可能由多个 Codex 进程并发触发。`WorkflowHookEventRecorder` 会Hook 写入路径不更新 `daily.jsonl`,也不执行重建或清理旧文件,避免在 Hook timeout 内持锁执行重活。-`WorkflowStatsService` 只在现有自动刷新或手动刷新触发工作流统计刷新时检查 `maintenance.json`。打开 popover 时只读取现有 `daily.jsonl`。如果没有 `pending` 或 `dirty`,服务不会执行维护。+`WorkflowStatsService` 只在现有自动刷新或手动刷新触发工作流统计刷新时检查 `maintenance.json`。打开菜单面板时只读取现有 `daily.jsonl`。如果没有 `pending` 或 `dirty`,服务不会执行维护。维护时优先处理 `dirty`,从对应日期文件第一行开始流式重建当天聚合;再处理 `pending`,从 `days[date].offset` 开始流式读取新增事件并合并到已有当天聚合。每条坏行会被跳过并计入 `days[date].corrupt`。处理完成后先在 `stats.lock` 外原子写回 `daily.jsonl`,再短暂持有 `stats.lock` 更新 `maintenance.json`,避免主 App 写 daily 时阻塞 Hook 追加事件。@@ -203,14 +203,14 @@ UI 不直接展示所有原始字段,而是先生成 `WorkflowDailyStats`:用量热力图固定为近 30 周、30 列 x 7 行、周日到周六排列。`account/usage/read` 返回当天 `dailyUsageBuckets` 时, 热力图展示今天的小方块和对应 token 数; 没有当天 bucket 时再按 Hook 开关决定是否包含今天。-热力图 hover 时不在 popover 内绘制旧式 tooltip, 而是通过 `UsageHeatmapHoverContext` 通知 `HeatmapDetailPanelController` 展示侧边详情面板。指针会吸附到最近方块, 离开热力图后延迟 160 ms 清除选中状态。+热力图 hover 时不在菜单面板内绘制旧式 tooltip, 而是通过 `UsageHeatmapHoverContext` 通知 `HeatmapDetailPanelController` 展示侧边详情面板。指针会吸附到最近方块, 离开热力图后延迟 160 ms 清除选中状态。-详情面板是 popover 的 borderless nonactivating child panel:+详情面板是菜单面板的 borderless nonactivating child panel:-- 不接收鼠标事件, 不抢走 popover key window-- 按悬停列优先显示在 popover 左侧或右侧, 左右空间不足时尝试另一侧+- 不接收鼠标事件, 不抢走菜单面板 key window+- 按悬停列优先显示在菜单面板左侧或右侧, 左右空间不足时尝试另一侧- 最终位置会被夹在当前屏幕可见区域内, 屏幕边缘保留 `8` px-- 与 popover 之间保留 `4` px gap+- 与菜单面板之间保留 `4` px gap- 侧边切换使用抽屉动画: 收起 `0.12` 秒, 展开 `0.18` 秒Codex Hook 关闭时:diff --git a/Docs/DevelopmentGuide.md b/Docs/DevelopmentGuide.mdindex 595d531..0520e3f 100644--- a/Docs/DevelopmentGuide.md+++ b/Docs/DevelopmentGuide.md@@ -8,7 +8,7 @@CodexBar 是一个 macOS 菜单栏应用, 使用 SwiftUI + AppKit + MVVM-App 通过本机 Codex app-server 读取账号, 额度和 token 用量, 通过 Codex Hook 记录本机工作流事件, 并把这些数据展示在菜单栏 popover, 设置窗口和日志窗口中+App 通过本机 Codex app-server 读取账号, 额度和 token 用量, 通过 Codex Hook 记录本机工作流事件, 并把这些数据展示在菜单面板, 设置窗口和日志窗口中关键边界:@@ -24,10 +24,10 @@ App 通过本机 Codex app-server 读取账号, 额度和 token 用量, 通过 C| 目录 | 职责 || ----------------------- | ----------------------------------------------------------------------- || `CodexBar/App/` | SwiftUI 入口和 AppDelegate 启动分支 |-| `CodexBar/Controllers/` | 菜单栏, popover, 设置窗口, 日志窗口和窗口行为 |+| `CodexBar/Controllers/` | 菜单栏, 菜单面板, 设置窗口, 日志窗口和窗口行为 || `CodexBar/Models/` | account, quota, usage, workflow stats, 日期网格和错误模型 || `CodexBar/Services/` | app-server, Codex CLI 解析, 版本探测, Hook 设置, 统计维护, 更新, 登录项 |-| `CodexBar/Views/` | popover, 设置窗口, 日志窗口和共享 Liquid Glass 样式 |+| `CodexBar/Views/` | 菜单面板, 设置窗口, 日志窗口和共享 Liquid Glass 样式 || `Docs/` | app-server, Hook 和开发文档 || `Scripts/` | DMG 和 appcast 发布脚本 |@@ -61,7 +61,7 @@ sequenceDiagramelse 普通菜单栏启动App->>Delegate: 进入 App 启动流程Delegate->>Controller: 创建菜单栏控制器- Controller->>Controller: 安装菜单栏按钮和 popover+ Controller->>Controller: 安装菜单栏按钮和菜单面板Controller->>VM: 启动自动刷新end```@@ -77,14 +77,14 @@ sequenceDiagram`StatusItemController.install()` 负责:- 配置菜单栏按钮图标, tooltip 和点击事件-- 配置 popover 的 SwiftUI 根视图+- 配置菜单面板的 SwiftUI 根视图- 订阅状态变化并切换菜单栏图标- 订阅全局快捷键配置并安装或移除 Carbon hot key- 开始每 60 秒自动刷新-App 退出时, `applicationWillTerminate` 调用 `StatusItemController.uninstall()`, 关闭 popover, 注销全局快捷键, 移除订阅并从系统状态栏移除 status item+App 退出时, `applicationWillTerminate` 调用 `StatusItemController.uninstall()`, 关闭菜单面板, 注销全局快捷键, 移除订阅并从系统状态栏移除 status item-## 4. 菜单栏, Popover 与窗口流程+## 4. 菜单栏, 菜单面板与窗口流程菜单栏按钮由 `NSStatusBar.system.statusItem(withLength:)` 创建@@ -99,48 +99,51 @@ App 退出时, `applicationWillTerminate` 调用 `StatusItemController.uninstall| 操作 | 行为 || ---------------- | ---------------- |-| 左键点击 | 切换 popover |+| 左键点击 | 切换菜单面板 || 右键点击 | 打开上下文菜单 || Control + 点击 | 打开上下文菜单 |-| 全局快捷键 | 切换 popover |+| 全局快捷键 | 切换菜单面板 || 上下文菜单"设置" | 打开独立设置窗口 || 上下文菜单"日志" | 打开独立日志窗口 || 上下文菜单"退出" | 终止 App |全局快捷键由 `GlobalHotKeySettings` 和 `GlobalHotKeyController` 管理。没有用户设置时默认注册 `⌘⇧W`; 用户清除后不注册快捷键。注册冲突时恢复到上一个已注册快捷键, 并把错误显示在设置窗口的快捷键行内。-打开 popover 的顺序:+通过全局快捷键打开菜单面板前, `StatusItemController` 会先用鼠标所在屏幕作为目标屏幕, 找不到时回退主屏幕, 再校验当前 `NSStatusBarButton` 锚点是否可信: 按钮必须有 window 和有效 screen、未隐藏且 bounds 非空, 换算后的屏幕矩形必须是有限尺寸, 宽高至少 1 px, 并且与目标屏幕范围相交。锚点可信时使用 `NSPopover` 挂在 status item 下方; 锚点不可信时使用无箭头 fallback `NSPanel`, 放在目标屏幕顶部居中位置。已打开时仍允许快捷键关闭当前面板。鼠标点击路径不做这层 fallback, 因为点击 sender 本身就是当前锚点。++打开菜单面板的顺序:- 取消正在等待的延迟刷新和淡入淡出任务+- 如果来自全局快捷键且当前状态需要打开菜单面板, 先用目标屏幕确认 status item 锚点可信; 不可信时改用同一屏幕顶部居中的 fallback `NSPanel`- 设置状态为 `opening`, 准备透明度淡入-- 显示 `NSPopover`, 把 `PopoverVisibilityState.isVisible` 设为 `true`+- 显示 `NSPopover` 或 fallback `NSPanel`, 把 `MenuSurfaceVisibilityState.isVisible` 设为 `true`- 调用 `refreshWorkflowStatsIfHookEnabled(performMaintenance: false)`, 只读取已有 `daily.jsonl`, 不做重维护-- 安装 `PopoverDismissMonitor`, 监听 popover window 并只将 popover window 置前和设为 key window+- 安装 `MenuSurfaceDismissMonitor`, 监听当前菜单面板 window 并只将当前菜单面板 window 置前和设为 key window- 执行 0.24 秒淡入- 延迟 160 ms 后调用 `viewModel.refreshIfNeeded()`-关闭 popover 的顺序:+关闭菜单面板的顺序:- 移除本地和全局事件监听- 将 `isVisible` 设为 `false`, 让倒计时停止 `TimelineView` 每秒 tick-- 临时禁止设置窗口和日志窗口成为 key window, 避免关闭 popover 时 AppKit 把这些辅助窗口提到前面+- 临时禁止设置窗口和日志窗口成为 key window, 避免关闭菜单面板时 AppKit 把这些辅助窗口提到前面- 默认执行 0.18 秒淡出, 无法淡出时直接关闭-- popover 关闭后延迟 120 ms 恢复设置窗口和日志窗口的 key window 能力+- 菜单面板关闭后延迟 120 ms 恢复设置窗口和日志窗口的 key window 能力-`PopoverDismissMonitor` 监听这些 dismiss 条件:+`MenuSurfaceDismissMonitor` 监听这些 dismiss 条件:-- popover 外部鼠标点击+- 菜单面板外部鼠标点击- Escape- Command-Tab- App 失去 active- 其他应用被激活-- popover window 失去 key+- 菜单面板 window 失去 key-Command-Space 不直接关闭 popover, 只短暂抑制 600 ms 内的 active 变化关闭逻辑, 避免 Spotlight 或系统搜索抢焦点时误关弹窗。+Command-Space 不直接关闭菜单面板, 只短暂抑制 600 ms 内的 active 变化关闭逻辑, 避免 Spotlight 或系统搜索抢焦点时误关弹窗。设置窗口和日志窗口都继承 `HostingWindowController` 的行为: 懒创建, 关闭后不释放, 重新打开复用, 按当前屏幕居中, 重新打开对应入口时只移动和置前对应窗口。-设置窗口和日志窗口使用 `AuxiliaryHostingWindow`; 窗口可以成为 key window, 但不能成为 main window。通过快捷键打开或关闭 popover 时, 只激活并置前 popover, 不主动置前已有的设置窗口或日志窗口。+设置窗口和日志窗口使用 `AuxiliaryHostingWindow`; 窗口可以成为 key window, 但不能成为 main window。通过快捷键打开或关闭菜单面板时, 只激活并置前当前面板, 不主动置前已有的设置窗口或日志窗口。## 5. Codex 状态刷新流程@@ -148,7 +151,7 @@ Command-Space 不直接关闭 popover, 只短暂抑制 600 ms 内的 active 变- `startAutoRefresh()` 先尝试一次 `refreshIfNeeded()`, 之后按 `autoRefreshDelay` 循环- 刷新间隔是 60 秒-- `refreshIfNeeded()` 会比较 `autoRefreshCountdownStartedAt`, 避免 popover 打开和自动刷新同时触发重复请求+- `refreshIfNeeded()` 会比较 `autoRefreshCountdownStartedAt`, 避免菜单面板打开和自动刷新同时触发重复请求- `refresh()` 通过 `isRefreshing` 防重入下面的时序图展示刷新, app-server 握手, 额度与用量读取, 以及常见错误后的重试或降级@@ -355,7 +358,7 @@ codex app-server --listen stdio://错误处理的基本原则:-- Popover 只展示"未登录"和"初始化失败"两类特殊状态+- 菜单面板只展示"未登录"和"初始化失败"两类特殊状态- 具体启动失败, 请求失败, 超时, 断连, 解析失败和业务错误进入日志窗口- 账户有效时, rate limits 和 usage 可以单独失败, 失败区域按缓存或无数据处理- 登录项和 Hook 写入错误显示在设置窗口中部的独立错误组@@ -432,7 +435,7 @@ Codex 版本探测错误:## 8. Snapshot 合成流程-`CodexQuotaSnapshot` 是 popover 展示 app-server 数据的唯一入口+`CodexQuotaSnapshot` 是菜单面板展示 app-server 数据的唯一入口它由 `AccountReadResponse`, 可选的 `AccountRateLimitsResponse` 和可选的 `AccountUsageResponse` 合成@@ -469,7 +472,7 @@ Codex 版本探测错误:- `nil` 表示未来日期或无法生成日期, UI 不绘制方块, 也不参与峰值计算- 今天没有 token bucket 但 Hook 开启时, 今天 token 显示 `--`-## 9. Popover UI 展示流程+## 9. 菜单面板 UI 展示流程`CodexStatusMenuView.menuWidth` 由热力图宽度和 padding 推导:@@ -481,7 +484,7 @@ UI 状态分支:```mermaidflowchart TD- Start["渲染菜单栏弹窗"] --> HasSnapshot{"是否有账号快照"}+ Start["渲染菜单面板"] --> HasSnapshot{"是否有账号快照"}HasSnapshot -- "否" --> StatusCard["显示未登录或初始化失败"]StatusCard --> Empty["显示暂无数据面板"]HasSnapshot -- "是" --> Account["显示账号和计划"]@@ -520,7 +523,7 @@ flowchart TD- hover 时通过 `UsageHeatmapHoverContext` 通知 `HeatmapDetailPanelController` 展示侧边详情面板- 指针会吸附到最近方块, 吸附动画 0.12 秒; 离开热力图后延迟 160 ms 清除选中状态-热力图详情面板是 popover 的 borderless nonactivating child panel, 不接收鼠标事件, 按悬停列优先显示在 popover 左侧或右侧; 左右空间不足时尝试另一侧, 最终在当前屏幕可见区域内保留 8 px 边距。侧边切换时先以 0.12 秒抽屉动画收起, 再以 0.18 秒展开。+热力图详情面板是菜单面板的 borderless nonactivating child panel, 不接收鼠标事件, 按悬停列优先显示在菜单面板左侧或右侧; 左右空间不足时尝试另一侧, 最终在当前屏幕可见区域内保留 8 px 边距。侧边切换时先以 0.12 秒抽屉动画收起, 再以 0.18 秒展开。详情面板分两种:@@ -535,8 +538,8 @@ Hook 开启且当天没有 token bucket 时, 今天的 token 数显示 `--`。更新时间行:- 显示倒计时圆环, "数据更新时间"和 `HH:mm:ss`-- popover 可见时使用 `TimelineView(.periodic(..., by: 1))` 每秒 tick-- popover 不可见时只渲染一次静态圆环+- 菜单面板可见时使用 `TimelineView(.periodic(..., by: 1))` 每秒 tick+- 菜单面板不可见时只渲染一次静态圆环- 普通 tick 不做连续动画, 只有刷新起点变化时播放 0.5 秒恢复动画- 如果 Sparkle 自动发现新版, 右侧显示 `panelUpdateMessage`, 双击该文本调用 `startUpdate()`@@ -720,7 +723,7 @@ Hook 数据目录:- `refreshIfNeeded(performMaintenance: false)` 至少间隔 5 秒- `performMaintenance: true` 时跳过 5 秒节流, 直接刷新-- 打开 popover 时如果 Hook 开启, 只读取现有 `daily.jsonl`, 不维护+- 打开菜单面板时如果 Hook 开启, 只读取现有 `daily.jsonl`, 不维护- app-server 自动刷新倒计时重置时, 如果 Hook 开启, 触发一次带维护的 workflow stats 刷新维护流程在 `WorkflowStatsService` 的 `CodexBar.workflow-stats` 串行队列执行@@ -866,7 +869,7 @@ App 再次成为 active 时, 也会刷新 Codex 版本区被动发现新版:- 自动检查发现新版时设置 `panelUpdateMessage`-- popover 底部更新时间行显示该消息+- 菜单面板底部更新时间行显示该消息- 双击消息调用 `startUpdate()`, 激活 App 并打开 Sparkle 更新流程## 16. 日志窗口流程@@ -895,7 +898,7 @@ App 再次成为 active 时, 也会刷新 Codex 版本区- 解析 App 路径, 未指定时从项目根查找唯一 `.app`- 读取 `MARKETING_VERSION`, 优先从 Xcode build settings 读取, 失败后回退 `project.pbxproj` 和 App `Info.plist`-- 准备临时 staging 目录, 复制 `.app` 并创建 `/Applications` 符号链接+- 准备临时 staging 目录, 复制 `.app`, 挂载后通过 Finder 创建 `/Applications` alias- 创建可写 DMG- 挂载 DMG 并用 AppleScript 写 Finder icon view 布局- 压缩为最终 UDZO DMGdiff --git a/README.md b/README.mdindex 167dee6..ed1a3ec 100644--- a/README.md+++ b/README.md@@ -77,10 +77,10 @@ xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/plSwift 源码按职责放在 `CodexBar/` 下的子目录中:- `App/`: 应用入口-- `Controllers/`: 菜单栏、popover 和独立窗口控制器+- `Controllers/`: 菜单栏、菜单面板和独立窗口控制器- `Models/`: account、quota、usage、工作流统计、共享日期网格和错误分类模型- `Services/`: app-server 会话、Codex CLI 解析、版本探测、Hook 设置、工作流统计、开机自启和 Sparkle 更新-- `Views/`: 菜单栏弹窗、设置窗口、日志窗口和共享 Liquid Glass 样式+- `Views/`: 菜单面板、设置窗口、日志窗口和共享 Liquid Glass 样式更详细的启动、刷新、Hook 统计、设置、日志、更新和发布流程见 [开发文档](Docs/DevelopmentGuide.md)。diff --git a/Scripts/dmg.sh b/Scripts/dmg.shindex fcb1da2..84df30f 100755--- a/Scripts/dmg.sh+++ b/Scripts/dmg.sh@@ -123,7 +123,6 @@ rm -f "${RW_DMG}" "${TEMP_OUTPUT_PATH}"echo "==> Preparing DMG contents"ditto "${APP_PATH}" "${STAGING_DIR}/${APP_NAME}.app"-ln -sfn /Applications "${STAGING_DIR}/Applications"echo "==> Creating writable DMG"hdiutil create \@@ -146,10 +145,15 @@ fiecho "==> Writing Finder layout"osascript <<APPLESCRIPTset mountFolder to POSIX file "${MOUNT_POINT}" as alias+set applicationsFolder to POSIX file "/Applications" as aliastell application "Finder"open mountFolderdelay 1+ if exists item "Applications" of mountFolder then+ delete item "Applications" of mountFolder+ end if+ make new alias file to applicationsFolder at mountFolder with properties {name:"Applications"}set targetWindow to front Finder windowset current view of targetWindow to icon viewset toolbar visible of targetWindow to falsediff --git a/appcast.xml b/appcast.xmlindex 861f649..2698719 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.0.0</title>+ <sparkle:version>23</sparkle:version>+ <sparkle:shortVersionString>3.0.0</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.0.0</sparkle:releaseNotesLink>+ <pubDate>Wed, 24 Jun 2026 14:32:55 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.0.0.dmg" sparkle:edSignature="i0pBg41pJVgmZCUctggIWCZmjcTI6ZMPnpPj2CAsgv9UmrnB7grm9eE0no/Ja6by1v/cx0A0CEKmOHFxkWSmDA==" length="3030047" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 2.4.6</title><sparkle:version>22</sparkle:version>