Skip to content

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

fix: 修复隐藏窗口持续动画造成的资源占用

Bob369f2837ec01
diff --git a/AGENTS.md b/AGENTS.md
index f1ce0f5..07be3ba 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -76,6 +76,12 @@ CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用,使用 Swift 6,
不要主动 push,不要回滚、覆盖或丢弃他人的未提交修改。用户只要求提交时,不要顺带格式化或修改文件。
+提交信息应从完整代码差异中提炼变更的核心用途和目的,说明解决了什么问题、带来了什么行为或能力变化,而不是逐项罗列代码改动:
+
+- 标题概括本次提交最主要的问题或目标,不用次要交互细节或局部实现代替核心目的
+- body 围绕核心目的解释必要的原因、关键行为变化和影响;实现细节仅在有助于理解目的或评估影响时保留
+- 不把文件清单、函数改动清单或开发过程直接作为提交说明,也不为覆盖每一处 diff 而堆砌条目
+
提交标题使用 `<type>: <中文描述>` 格式:
- 常用 type 包括 `feat` `fix` `chore` `refactor` `docs`
diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swift
index b1d63d7..f5fafe1 100644
--- a/CodexBar/Controllers/SettingsWindowController.swift
+++ b/CodexBar/Controllers/SettingsWindowController.swift
@@ -21,12 +21,13 @@ final class SettingsWindowController: HostingWindowController {
private let onSyncChanged: (Bool) -> Void
private let onRebuildWorkflowData: WorkflowSyncScheduler.RebuildHandler
private let mainPanelUndoManager = UndoManager()
+ private let animationState = SettingsWindowAnimationState()
private var windowFocusObserver: AnyCancellable?
+ private var windowVisibilityObserver: AnyCancellable?
/// 只在真的要展开时构造: hosting controller 与动态面板订阅会常驻到 App 结束, 而用户可能一次子面板都没开过
private var optionsPanelControllers: [SettingsOptionsPanel: SettingsOptionsPanelController] = [:]
private var optionsDismissEventMonitor: Any?
private var optionsDismissFocusObserver: AnyCancellable?
- private var optionsDismissWindowObserver: NSObjectProtocol?
private var optionsDismissedByClick: (panel: SettingsOptionsPanel, event: NSEvent)?
/// 首次构造窗口时 SwiftUI 可能先于 window 赋值上报高度 因此必须保留最近一次测量
private var preferredContentHeight: CGFloat?
@@ -70,6 +71,9 @@ final class SettingsWindowController: HostingWindowController {
override func open() {
refreshSettingsState()
super.open()
+ if let window {
+ animationState.update(for: window)
+ }
installOptionsDismissMonitor()
NotificationCenter.default.post(name: .settingsWindowDidOpen, object: nil)
}
@@ -97,6 +101,7 @@ final class SettingsWindowController: HostingWindowController {
)
.environmentObject(viewModel)
.environmentObject(appUpdater)
+ .environmentObject(animationState)
)
hostingController.sizingOptions = []
@@ -112,6 +117,21 @@ final class SettingsWindowController: HostingWindowController {
.sink { [weak notificationSettings] _ in
notificationSettings?.refreshAuthorizationStatus()
}
+ // 关闭后 hosting controller 仍然保留, 必须按窗口可见性停止持续动画
+ windowVisibilityObserver = Publishers.MergeMany([
+ NSWindow.didChangeOcclusionStateNotification,
+ NSWindow.didMiniaturizeNotification,
+ NSWindow.didDeminiaturizeNotification,
+ NSWindow.willCloseNotification
+ ].map { NotificationCenter.default.publisher(for: $0, object: window) })
+ .sink { [weak self, weak window] notification in
+ guard let self, let window else { return }
+ let isClosing = notification.name == NSWindow.willCloseNotification
+ animationState.update(for: window, isClosing: isClosing)
+ if isClosing {
+ removeOptionsDismissMonitor()
+ }
+ }
return window
}
@@ -299,15 +319,6 @@ final class SettingsWindowController: HostingWindowController {
handleOptionsAction(.closeAll)
}
}
- optionsDismissWindowObserver = NotificationCenter.default.addObserver(
- forName: NSWindow.willCloseNotification,
- object: window,
- queue: .main
- ) { [weak self] _ in
- MainActor.assumeIsolated {
- self?.removeOptionsDismissMonitor()
- }
- }
}
private func removeOptionsDismissMonitor() {
@@ -317,12 +328,8 @@ final class SettingsWindowController: HostingWindowController {
if let optionsDismissEventMonitor {
NSEvent.removeMonitor(optionsDismissEventMonitor)
}
- if let optionsDismissWindowObserver {
- NotificationCenter.default.removeObserver(optionsDismissWindowObserver)
- }
optionsDismissEventMonitor = nil
optionsDismissFocusObserver = nil
- optionsDismissWindowObserver = nil
optionsDismissedByClick = nil
}
@@ -471,6 +478,18 @@ final class SettingsWindowController: HostingWindowController {
}
}
+@MainActor
+final class SettingsWindowAnimationState: ObservableObject {
+ @Published private(set) var allowsAnimations = false
+
+ func update(for window: NSWindow, isClosing: Bool = false) {
+ let isVisible = !isClosing && window.isVisible && !window.isMiniaturized
+ && window.occlusionState.contains(.visible)
+ guard allowsAnimations != isVisible else { return }
+ allowsAnimations = isVisible
+ }
+}
+
nonisolated extension Notification.Name {
static let settingsWindowDidOpen = Notification.Name("CodexBar.settingsWindowDidOpen")
}
diff --git a/CodexBar/Views/Menu/CodexActivityCard.swift b/CodexBar/Views/Menu/CodexActivityCard.swift
index 5f3cfa4..f88a393 100644
--- a/CodexBar/Views/Menu/CodexActivityCard.swift
+++ b/CodexBar/Views/Menu/CodexActivityCard.swift
@@ -9,6 +9,7 @@ struct CodexActivityCard: View {
@ObservedObject var keepAliveController: KeepAliveController
let showsUnavailableState: Bool
let onTaskCenterTap: (ScreenFrameProvider) -> Void
+ @Environment(\.mainPanelAnimationsEnabled) private var allowsAnimations
@State private var frameProvider = ScreenFrameProvider()
@State private var isHovered = false
@@ -90,14 +91,20 @@ struct CodexActivityCard: View {
.transition(.opacity)
}
+ // 防睡眠只在任务运行期间生效, 所以状态挂在活动卡片上而不是单独占一行
if showsKeepAliveBadge {
- // 防睡眠只在任务运行期间生效, 所以状态挂在活动卡片上而不是单独占一行
- Image(systemName: "sun.max.fill")
- .font(.system(size: 11, weight: .semibold))
- .foregroundStyle(Color.teal)
- .symbolEffect(.rotate.byLayer, options: .repeat(.continuous))
- .transition(.opacity)
- .help(keepAliveHelp)
+ // 隐藏或关闭动画效果时移除整个旋转视图, 避免保留持续渲染调度
+ Group {
+ if allowsAnimations {
+ RotatingKeepAliveSun()
+ } else {
+ Image(systemName: "sun.max.fill")
+ }
+ }
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(Color.teal)
+ .transition(.opacity)
+ .help(keepAliveHelp)
}
if content.otherTaskCount > 0 {
@@ -268,6 +275,17 @@ struct CodexActivityCard: View {
}
}
+private struct RotatingKeepAliveSun: View {
+ @State private var isRotating = false
+
+ var body: some View {
+ Image(systemName: "sun.max.fill")
+ .rotationEffect(.degrees(isRotating ? 360 : 0))
+ .animation(.linear(duration: 2).repeatForever(autoreverses: false), value: isRotating)
+ .onAppear { isRotating = true }
+ }
+}
+
/// 卡片自行处理 hover/选中描边, 按钮样式不再修改 label 的前景色或透明度
private struct ActivityCardButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swift
index 7cff1b1..bb63f0e 100644
--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift
+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift
@@ -2,6 +2,8 @@ import Combine
import SwiftUI
extension EnvironmentValues {
+ // 持续动画需要显式停用, 不能只依赖 transaction 的动画禁用
+ @Entry var mainPanelAnimationsEnabled: Bool = false
@Entry var mainPanelEntranceAnimationsEnabled: Bool = true
}
@@ -52,6 +54,10 @@ struct CodexStatusMenuView: View {
VStack(alignment: .leading, spacing: Metrics.verticalSpacing) {
content
}
+ .environment(
+ \.mainPanelAnimationsEnabled,
+ animationState.allowsAnimations && mainPanelSettings.areEntranceAnimationsEnabled
+ )
.environment(
\.mainPanelEntranceAnimationsEnabled,
mainPanelSettings.areEntranceAnimationsEnabled
diff --git a/CodexBar/Views/Settings/CodexVersionSection.swift b/CodexBar/Views/Settings/CodexVersionSection.swift
index c593f84..a08fdaa 100644
--- a/CodexBar/Views/Settings/CodexVersionSection.swift
+++ b/CodexBar/Views/Settings/CodexVersionSection.swift
@@ -3,6 +3,7 @@ import SwiftUI
/// Codex CLI/APP 版本区, 同时展示磁盘版本和当前 app-server 运行版本
struct CodexVersionSection: View {
+ @EnvironmentObject private var animationState: SettingsWindowAnimationState
let snapshot: CodexCLIVersionSnapshot
let connectionInfo: CodexCLIConnectionInfo?
let sourceSelection: CodexCLISourceSelection
@@ -77,7 +78,10 @@ struct CodexVersionSection: View {
} label: {
let icon = Image(systemName: "cable.coaxial")
Group {
- if #available(macOS 26.0, *), isWorking {
+ if !animationState.allowsAnimations || !isWorking {
+ // 隐藏时移除动画分支, 同时停止 phaseAnimator 和持续符号效果
+ icon
+ } else if #available(macOS 26.0, *) {
// DrawOn 保持激活会停在隐藏状态, 交替阶段才能持续重复绘制
icon.phaseAnimator([true, false]) { content, isHidden in
content.symbolEffect(.drawOn.byLayer, options: .repeat(.continuous), isActive: isHidden)
@@ -85,7 +89,7 @@ struct CodexVersionSection: View {
.linear(duration: 0.5)
}
} else {
- icon.symbolEffect(.wiggle.clockwise.byLayer, options: .repeat(.continuous), isActive: isWorking)
+ icon.symbolEffect(.wiggle.clockwise.byLayer, options: .repeat(.continuous))
}
}
.frame(width: SettingsRowMetrics.optionsButtonSize, height: SettingsRowMetrics.optionsButtonSize)
diff --git a/Config/Version.xcconfig b/Config/Version.xcconfig
index 244163e..51544fb 100644
--- a/Config/Version.xcconfig
+++ b/Config/Version.xcconfig
@@ -1,2 +1,2 @@
-MARKETING_VERSION = 3.7.3
-CURRENT_PROJECT_VERSION = 87
+MARKETING_VERSION = 3.7.4
+CURRENT_PROJECT_VERSION = 88
diff --git a/Docs/DeveloperGuide/ui-and-lifecycle.md b/Docs/DeveloperGuide/ui-and-lifecycle.md
index dec7d41..234bdb3 100644
--- a/Docs/DeveloperGuide/ui-and-lifecycle.md
+++ b/Docs/DeveloperGuide/ui-and-lifecycle.md
@@ -127,13 +127,13 @@ hidden -> opening -> shown -> closing -> hidden
popover 和备用面板分别持有 `MenuSurfaceAnimationState`。展示前将 `allowsAnimations` 设为 `true`,淡出期间保持开启,实际关闭后设为 `false`
-`CodexStatusMenuView` 在动画许可关闭时,将根视图事务的 `animation` 设为 `nil`、`disablesAnimations` 设为 `true`。后台数据刷新继续执行。
+`CodexStatusMenuView` 在宿主动画许可关闭时,将根视图事务的 `animation` 设为 `nil`、`disablesAnimations` 设为 `true`。持续动画使用 `mainPanelAnimationsEnabled` 环境值,同时要求宿主动画许可和设置中的“动画效果”开关开启。宿主隐藏或用户关闭动画效果时必须移除持续动画视图,不能只依赖事务禁用。后台数据刷新继续执行。
`MenuSurfaceVisibilityState` 在面板展示后开启,在关闭开始时结束。每次展示递增 `presentationGeneration`,额度和用量区域以该值作为视图身份,重新执行入场动画。
### 活动卡片
-`CodexActivityCard` 使用 `primaryActivity`,优先级为等待批准、运行中、最近完成、最近终止。`isActivelyPreventingSleep` 为 `true` 且卡片数据可用时显示青绿色 `sun.max.fill`,通过 `.symbolEffect(.rotate.byLayer, options: .repeat(.continuous))` 持续旋转。tooltip 按 `sleepPreventionSource` 显示来源。
+`CodexActivityCard` 使用 `primaryActivity`,优先级为等待批准、运行中、最近完成、最近终止。`isActivelyPreventingSleep` 为 `true` 且卡片数据可用时显示青绿色 `sun.max.fill`。所属宿主的 `mainPanelAnimationsEnabled` 开启时创建独立的旋转视图,以线性动画每 2 秒顺时针旋转一圈,不使用系统符号效果的启动加速阶段。关闭许可后移除旋转视图并切回静态图标;重新展示时仅在“动画效果”开启的情况下恢复旋转。popover 与 fallback 宿主各自控制,不互相激活动画。tooltip 按 `sleepPreventionSource` 显示来源。
## Fallback panel
@@ -229,6 +229,8 @@ SwiftUI 可能在窗口创建完成前上报高度。`SettingsWindowController`
关于页面的重连按钮紧邻 `Codex 版本` 标题,来源选择器位于行尾。重连及刷新期间两者禁用;没有可用来源时重连按钮禁用。
+重连按钮的持续绘制或摆动动画只在设置窗口可见且正在重连或刷新时创建。`SettingsWindowController` 根据窗口遮挡、最小化和关闭通知更新动画许可;窗口隐藏时移除整个动画分支,恢复可见后按当前忙碌状态重新创建。切离关于页时,现有分页分支会移除版本区。窗口是否获得键盘焦点不参与动画许可判断。
+
## 全局快捷键
[`GlobalHotKeyController.swift`](../../CodexBar/Controllers/GlobalHotKeyController.swift) 使用 Carbon Hot Key API。
@@ -283,7 +285,7 @@ app-server 状态默认每 60 秒检查刷新。主面板打开后约 160 ms 调
- 左键打开主面板,右键和 Control 点击打开上下文菜单
- 菜单栏符号随任务状态切换,最新终态在结束 30 秒后恢复空闲,跨睡眠唤醒后按当前时间显示
- 切换额度圆弧显隐时动画完整,零额度保留底轨,缓存额度变淡
-- 防睡眠生效时太阳徽标持续旋转,结束后消失,重开面板后状态正确
+- 防睡眠生效时太阳徽标仅在“动画效果”开启且所属面板展示期间旋转;关闭动画效果后保留静态太阳,再次开启后仅可见宿主恢复旋转;冷启动后不打开面板、关闭后继续运行任务时均无持续旋转开销;重开、快速开关和 popover 与 fallback 切换后均保持每 2 秒一圈的匀速旋转,任务结束后徽标消失
- 代理密码显隐切换时淡化正常,输入内容、选区和焦点保留
- 点击主面板外部正确关闭,点击侧边面板不误关闭
- 热力图、Reset Credits 和活动中心保持互斥
@@ -291,6 +293,7 @@ app-server 状态默认每 60 秒检查刷新。主面板打开后约 160 ms 调
- 全局快捷键在状态栏锚点有效和无效场景都能打开面板
- 从通知点击激活 App 并打开面板
- 设置窗口首次打开、关闭和再次打开时焦点正确
+- 关于页刷新或重连期间,关闭、最小化、完全遮挡设置窗口或切离关于页后,重连图标不再持续绘制或摆动;恢复展示后仅在仍忙碌时恢复动画,窗口失焦但仍可见时行为正常
- 冷启动后首次打开设置时通用页直接使用完整内容高度;切换三个 tab 时窗口高度自适应,屏幕空间充足时均不显示滚动条
- 主面板布局、通知、自动重置和防睡眠子面板互斥,顶边对齐对应设置行,内容变化后高度正确
- 设置子面板展开时从菜单栏打开主面板,主面板保持打开,设置子面板收起且不把焦点抢回设置窗口
diff --git a/Docs/en/DeveloperGuide/ui-and-lifecycle.md b/Docs/en/DeveloperGuide/ui-and-lifecycle.md
index f239c17..ae956a5 100644
--- a/Docs/en/DeveloperGuide/ui-and-lifecycle.md
+++ b/Docs/en/DeveloperGuide/ui-and-lifecycle.md
@@ -127,13 +127,13 @@ Settings and log windows temporarily reject `makeKey()` during closing and regai
The popover and fallback panel each hold a separate `MenuSurfaceAnimationState`. `allowsAnimations` is set to `true` before presentation, remains enabled during fade-out, and becomes `false` after the surface closes.
-When animations are disabled, `CodexStatusMenuView` sets the root transaction's `animation` to `nil` and `disablesAnimations` to `true`. Background data refresh continues.
+When host animation permission is disabled, `CodexStatusMenuView` sets the root transaction's `animation` to `nil` and `disablesAnimations` to `true`. Continuous animations use the `mainPanelAnimationsEnabled` environment value, which requires both host permission and the Animation Effects setting. Hiding the host or disabling Animation Effects must remove the continuously animated view; disabling transaction animations alone is insufficient. Background data refresh continues.
`MenuSurfaceVisibilityState` begins after the panel is shown and ends when closing starts. Each presentation increments `presentationGeneration`; the rate-limit and usage sections use that value as their view identity and run their entrance animations again.
### Activity Card
-`CodexActivityCard` uses `primaryActivity`, prioritizing waiting for approval, running, recently completed, and recently terminated tasks. When `isActivelyPreventingSleep` is `true` and card data is available, it shows a teal `sun.max.fill` with continuous `.symbolEffect(.rotate.byLayer, options: .repeat(.continuous))` animation. The tooltip identifies `sleepPreventionSource`.
+`CodexActivityCard` uses `primaryActivity`, prioritizing waiting for approval, running, recently completed, and recently terminated tasks. When `isActivelyPreventingSleep` is `true` and card data is available, it shows a teal `sun.max.fill`. While the host's `mainPanelAnimationsEnabled` is true, a separate rotating view uses linear animation for one clockwise revolution every 2 seconds, without the system symbol effect's acceleration phase. Disabling permission removes the rotating view and restores a static icon. Reopening restores rotation only when Animation Effects is enabled. Popover and fallback hosts control their animations independently. The tooltip identifies `sleepPreventionSource`.
## Fallback Panel
@@ -229,6 +229,8 @@ Without a configuration, clicking the row or toggle opens the dialog. With one s
In About, the reconnect button sits immediately after the Codex Versions title, with the source picker at the end of the row. Both are disabled during reconnection and refresh; Reconnect is also disabled when no source is available.
+The reconnect button creates its continuous drawing or wiggle animation only while the Settings window is visible and reconnection or refresh is in progress. `SettingsWindowController` updates animation permission from window occlusion, minimization, and close notifications. Hiding the window removes the entire animated branch; becoming visible recreates it according to the current busy state. Switching away from About removes the version section through the existing page branches. Keyboard focus does not determine animation permission.
+
## Global Shortcut
[`GlobalHotKeyController.swift`](../../../CodexBar/Controllers/GlobalHotKeyController.swift) uses the Carbon Hot Key API.
@@ -283,7 +285,7 @@ Release scripts require Developer ID, signing, and notarization credentials and
- Left-click opens the main panel; right-click and Control-click open the context menu
- Menu bar symbols follow task state; terminal feedback expires 30 seconds after the task ends and is recalculated on wake
- Quota-arc visibility animates, zero quota retains the track, and cached quota dims
-- The sun badge rotates while sleep prevention is active, disappears when it ends, and shows the correct state when reopening
+- The sun badge rotates only while sleep prevention is active, Animation Effects is enabled, and its host panel is presented; disabling Animation Effects preserves a static sun, and enabling it again resumes rotation only in the visible host; no continuous rotation work occurs before the first opening or while tasks continue after closing; reopening, rapid toggling, and switching between popover and fallback hosts preserve a constant speed of one revolution every 2 seconds, and the badge disappears when tasks end
- Password reveal transitions preserve text, selection, and focus
- Clicking outside the main panel dismisses it; clicking a side panel does not
- Heatmap, Reset Credits, and Task Center panels remain mutually exclusive
@@ -291,6 +293,7 @@ Release scripts require Developer ID, signing, and notarization credentials and
- The global shortcut opens the panel with both valid and invalid status-bar anchors
- Clicking a notification activates the app and opens the panel
- Focus is correct when opening Settings for the first time, closing it, and reopening it
+- During refresh or reconnection in About, closing, minimizing, fully occluding Settings, or switching away from About stops the reconnect icon's continuous drawing or wiggle; showing it again resumes animation only if still busy, and losing focus while visible preserves normal behavior
- On the first Settings open after a cold launch, General immediately uses its full content height; switching among all three tabs adapts the window height, with no scrollbar when screen space is sufficient
- Main Panel Layout, Notification, Automatic Reset, and sleep-prevention child panels remain mutually exclusive, align their top edges with their setting rows, and resize correctly when content changes
- With a settings child panel open, opening the main panel from the menu bar keeps the main panel open, closes the settings child panel, and does not steal focus back to Settings
diff --git a/appcast.xml b/appcast.xml
index f8a4126..daaeee9 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.7.4</title>
+ <sparkle:version>88</sparkle:version>
+ <sparkle:shortVersionString>3.7.4</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.7.4</sparkle:releaseNotesLink>
+ <pubDate>Fri, 11 Sep 2026 13:39:13 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.7.4.dmg" sparkle:edSignature="SrAqH6oyCF8tQJcUh6yPStv0FxgwWqynGg/CID6/KwutPCius0vK/OZzLkyrmRviv6X3KyRC7MBptdsXwOTuCg==" length="7938933" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.7.3</title>
<sparkle:version>87</sparkle:version>