Skip to content

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

feat: 完善设置和更新交互

Bobccd41bc83742
diff --git a/AGENTS.md b/AGENTS.md
index 6be8f85..5a71a2e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -4,7 +4,7 @@
## 项目概览
-CodexBar 是一个 macOS 菜单栏应用(SwiftUI + MVVM,最低 macOS 15.0),通过本机 Codex app-server 展示当前 Codex 账号的额度和 token 用量。主入口是 `MenuBarExtra`,弹窗使用 `.menuBarExtraStyle(.window)`。唯一外部依赖是 Sparkle(SwiftPM)。
+CodexBar 是一个 macOS 菜单栏应用(SwiftUI + MVVM,最低 macOS 15.0),通过本机 Codex app-server 展示当前 Codex 账号的额度和 token 用量。`LSUIElement` 纯菜单栏应用(无 Dock 图标、无应用菜单),入口经 `NSApplicationDelegateAdaptor`(`CodexBarAppDelegate`)→ `StatusItemController` 手动管理 `NSStatusItem` + `NSPopover`,SwiftUI 内容托管在 popover 中。唯一外部依赖是 Sparkle(SwiftPM)。
## 构建验证
@@ -20,13 +20,15 @@ SourceKit 经常对跨文件类型误报「Cannot find type ... in scope」(索
## 架构
-数据流:`CodexRateLimitService`(JSON-RPC 常驻连接)→ `RateLimitsViewModel`(状态发布)→ `MenuBarStatusView`(菜单栏图标 + 在 `.task` 中驱动每分钟自动刷新)/ `RateLimitsMenuView`(弹窗)。
+数据流:`CodexRateLimitService`(JSON-RPC 常驻连接)→ `RateLimitsViewModel`(状态发布)→ `StatusItemController`(菜单栏图标,经 Combine 订阅 `objectWillChange` 刷新图标)/ `RateLimitsMenuView`(popover 弹窗)。
-- `CodexBarApp.swift`:入口,创建 `RateLimitsViewModel` 和 `@StateObject AppUpdater`,后者以 `environmentObject` 注入弹窗。
+- `CodexBarApp.swift`:`@main`,仅声明一个占位 `Settings { EmptyView() }` Scene(`LSUIElement` 无入口触发它);真实 UI 由 `@NSApplicationDelegateAdaptor` 注入的 `CodexBarAppDelegate` 驱动。同文件含 `nonisolated extension Bundle`(`shortVersionString`、`displayVersionLabel`)。
+- `StatusItemController.swift`:`CodexBarAppDelegate`(持有 `RateLimitsViewModel`、`AppUpdater`)+ `StatusItemController`(私有)。后者 `install()` 时配置 `NSStatusItem`、popover、Combine 订阅,并调 `viewModel.startAutoRefresh()` 启动每分钟刷新;左键开关 popover(手写淡入淡出动画),右键弹 `NSMenu`(设置 / 退出),设置项打开独立 `NSWindow`(`makeSettingsWindow`,内嵌 `AppSettingsView`)。
+- `AppSettingsView.swift`:设置窗口 UI(开机自启开关、自动检查更新开关、当前版本 + 立即更新、检查更新、退出),经 `environmentObject` 注入 `AppUpdater`;`onAppear` 时刷新开机自启与自动检查状态。两个开关行复用 `settingsToggleRow(icon:title:isOn:isEnabled:)`。
- `CodexRateLimitService.swift`:app-server 常驻连接管理 + JSON-RPC 请求/响应。
- `RateLimitModels.swift`:wire 响应模型(纯 Decodable,不含展示逻辑)、业务快照模型(`CodexQuotaSnapshot` → `limits: [CodexQuotaLimitSnapshot]` → `windows: [QuotaWindow]`,支持多 limit 多窗口)、`CodexRateLimitError`(含 `requiresLogin`、`isAuthenticationRequired` 分类属性)。
- `RateLimitsViewModel.swift`:错误状态单一来源——只发布 `lastError: CodexRateLimitError?`,`errorMessage`、`requiresLogin`、`hasError` 都是派生计算属性,**不要再加并列的错误布尔**。
-- `QuotaRow.swift`:额度行和分段进度条;`LoginItemSettings.swift`:`SMAppService.mainApp` 开机自启;`AppUpdater.swift`:Sparkle 封装。
+- `QuotaRow.swift`:额度行和分段进度条;`LoginItemSettings.swift`:`SMAppService.mainApp` 开机自启;`AppUpdater.swift`:Sparkle 封装;`LiquidGlassStyle.swift`:Liquid Glass 视觉(`liquidGlassSurface`/`liquidGlassCapsule` 修饰符、`LiquidGlassDivider`)。
## Codex app-server 连接(核心逻辑)
@@ -67,19 +69,22 @@ Xcode target 已关闭 App Sandbox(需要启动本机 Codex CLI 并读取用户
## UI 与错误展示约定
-- 菜单栏正常图标 `person.fill.checkmark`,错误图标 `person.fill.xmark`,切换用 `.contentTransition(.symbolEffect(.replace))`。菜单栏不展示额度数字,详情只在弹窗中展示。
+- 菜单栏正常图标 `person.fill.checkmark`,错误图标 `person.fill.xmark`,由 `StatusItemController.updateStatusImage()` 直接设置 `NSStatusItem.button.image`。菜单栏不展示额度数字,详情只在 popover 中展示。
- App 图标保持白底黑色 `timelapse`。
- 不要给 symbol API 加低版本 fallback,最低系统版本已是 macOS 15.0。
-- 弹窗按 limit 分节展示(节标题取 `limitName` 回退 `limitId`,首字母大写,节之间 `Divider`)。分段条展示**剩余**额度(`100 - usedPercent`);额度行标签由 `windowDurationMins` 动态生成(如 `300` → `5 小时`,`10080` → `7 天`)。重置时间格式 `MM-dd HH:mm`,更新时间格式 `HH:mm:ss`。
+- 弹窗整体采用 Liquid Glass 风格(`LiquidGlassStyle.swift`):`.liquidGlassSurface(...)` 给各分区/外层加玻璃质感背景,`.liquidGlassCapsule` 给 plan 徽章,分隔线用 `LiquidGlassDivider`。plan 徽章颜色由 `planBadgeTint(for:)` 按计划名子串匹配(有序优先级:enterprise→team/business→pro→plus→edu→free→默认 cyan)。
+- 弹窗按 limit 分节展示(节标题取 `limitName` 回退 `limitId`,首字母大写,节之间 `LiquidGlassDivider`)。分段条展示**剩余**额度(`100 - usedPercent`);额度行标签由 `windowDurationMins` 动态生成(如 `300` → `5 小时`,`10080` → `7 天`)。重置时间格式 `MM-dd HH:mm`,更新时间格式 `HH:mm:ss`(更新时间行不展示版本号)。
- token 贡献墙为 30 列 × 7 行蓝色方块热力图,token 数按 `M`/`B` 紧凑单位展示。
-- 设置区仅在按住 Option 点击菜单栏图标时展示;开机自启状态读取是同步 XPC,也只在设置区可见时刷新。
+- 设置走菜单栏图标**右键(或 Control 点击)菜单**的「设置」项,打开独立的 `AppSettingsView` 窗口;开机自启状态读取是同步 XPC,在设置窗口 `onAppear` 时刷新。
- **错误文案不暴露内部细节**:`serverTimeout` 只携带 JSON-RPC 步骤名;子进程 stderr 由 `PipeDrain` 排空丢弃,不进入任何用户可见文案。
- 登录类错误(`requiresLogin`):弹窗顶部橙色提示「Codex 未登录」,旧快照置灰(opacity 0.4)保留,红色错误行被抑制。其他错误:红色小字展示 `errorDescription`,旧快照保持全亮度。
- 错误文案保持显示直到某次刷新成功(`refresh()` 开始时不清空 `lastError`);旧额度快照永远不清空。
## 自动更新(Sparkle)
-`AppUpdater`(`@MainActor`、`ObservableObject`)初始化时先校验 Info.plist 的 `SUFeedURL`(http/https)和 `SUPublicEDKey`(非空),任一缺失则不创建 `SPUStandardUpdaterController`,双击版本文案显示「未配置更新资源」(Debug/未签名构建静默降级)。`statusMessage` 是唯一发布的 UI 状态,3 秒后由可取消的 `Task` 自动清空。Info.plist 位于 `CodexBar/Resources/Info.plist`(`SUFeedURL = https://codexbar.zabrian.app/appcast.xml`,检查间隔 3600 秒)。
+`AppUpdater`(`@MainActor`、`ObservableObject`)初始化时先校验 Info.plist 的 `SUFeedURL`(http/https)和 `SUPublicEDKey`(非空),任一缺失则不创建 `SPUStandardUpdaterController`,各操作文案显示「未配置更新资源」(Debug/未签名构建静默降级);`canConfigureAutomaticChecks` 是 `updaterController != nil` 的计算属性,设置窗的「自动检查更新」开关据此禁用。
+
+按 UI 表面拆三个 `@Published` 文案,不要合并:`settingsStatusMessage`(设置窗版本行,默认 3 秒后由可取消 `Task` 清空,`autoDismissDelay: nil` 时常驻)、`panelUpdateMessage`(popover 底栏被动提示)、`availableUpdateMessage`(有新版的语义标志,驱动设置窗「立即更新」按钮)。`checkForUpdates()` 是设置窗的手动检查(置 `isManualCheckInProgress`),`startUpdate()` 拉起 Sparkle 安装面板,`setAutomaticallyChecksForUpdates(_:)`/`refreshAutomaticCheckSetting()` 同步开关状态。委托回调据 `isManualCheckInProgress` 路由:手动检查的结果进 `settingsStatusMessage`,自动检查发现新版进 `panelUpdateMessage`。Info.plist 位于 `CodexBar/Resources/Info.plist`(`SUFeedURL = https://codexbar.zabrian.app/appcast.xml`,检查间隔 3600 秒)。
## Git 提交规范
diff --git a/CLAUDE.md b/CLAUDE.md
index 510d16d..4d2979c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## 项目概览
-CodexBar 是一个 macOS 菜单栏应用(SwiftUI + MVVM,最低 macOS 15.0),通过本机 Codex app-server 展示当前 Codex 账号的额度和 token 用量。主入口是 `MenuBarExtra`,弹窗使用 `.menuBarExtraStyle(.window)`。唯一外部依赖是 Sparkle(SwiftPM)。
+CodexBar 是一个 macOS 菜单栏应用(SwiftUI + MVVM,最低 macOS 15.0),通过本机 Codex app-server 展示当前 Codex 账号的额度和 token 用量。`LSUIElement` 纯菜单栏应用(无 Dock 图标、无应用菜单),入口经 `NSApplicationDelegateAdaptor`(`CodexBarAppDelegate`)→ `StatusItemController` 手动管理 `NSStatusItem` + `NSPopover`,SwiftUI 内容托管在 popover 中。唯一外部依赖是 Sparkle(SwiftPM)。
## 构建验证
@@ -20,13 +20,15 @@ SourceKit 经常对跨文件类型误报「Cannot find type ... in scope」(索
## 架构
-数据流:`CodexRateLimitService`(JSON-RPC 常驻连接)→ `RateLimitsViewModel`(状态发布)→ `MenuBarStatusView`(菜单栏图标 + 在 `.task` 中驱动每分钟自动刷新)/ `RateLimitsMenuView`(弹窗)。
+数据流:`CodexRateLimitService`(JSON-RPC 常驻连接)→ `RateLimitsViewModel`(状态发布)→ `StatusItemController`(菜单栏图标,经 Combine 订阅 `objectWillChange` 刷新图标)/ `RateLimitsMenuView`(popover 弹窗)。
-- `CodexBarApp.swift`:入口,创建 `RateLimitsViewModel` 和 `@StateObject AppUpdater`,后者以 `environmentObject` 注入弹窗。
+- `CodexBarApp.swift`:`@main`,仅声明一个占位 `Settings { EmptyView() }` Scene(`LSUIElement` 无入口触发它);真实 UI 由 `@NSApplicationDelegateAdaptor` 注入的 `CodexBarAppDelegate` 驱动。同文件含 `nonisolated extension Bundle`(`shortVersionString`、`displayVersionLabel`)。
+- `StatusItemController.swift`:`CodexBarAppDelegate`(持有 `RateLimitsViewModel`、`AppUpdater`)+ `StatusItemController`(私有)。后者 `install()` 时配置 `NSStatusItem`、popover、Combine 订阅,并调 `viewModel.startAutoRefresh()` 启动每分钟刷新;左键开关 popover(手写淡入淡出动画),右键弹 `NSMenu`(设置 / 退出),设置项打开独立 `NSWindow`(`makeSettingsWindow`,内嵌 `AppSettingsView`)。
+- `AppSettingsView.swift`:设置窗口 UI(开机自启开关、自动检查更新开关、当前版本 + 立即更新、检查更新、退出),经 `environmentObject` 注入 `AppUpdater`;`onAppear` 时刷新开机自启与自动检查状态。两个开关行复用 `settingsToggleRow(icon:title:isOn:isEnabled:)`。
- `CodexRateLimitService.swift`:app-server 常驻连接管理 + JSON-RPC 请求/响应。
- `RateLimitModels.swift`:wire 响应模型(纯 Decodable,不含展示逻辑)、业务快照模型(`CodexQuotaSnapshot` → `limits: [CodexQuotaLimitSnapshot]` → `windows: [QuotaWindow]`,支持多 limit 多窗口)、`CodexRateLimitError`(含 `requiresLogin`、`isAuthenticationRequired` 分类属性)。
- `RateLimitsViewModel.swift`:错误状态单一来源——只发布 `lastError: CodexRateLimitError?`,`errorMessage`、`requiresLogin`、`hasError` 都是派生计算属性,**不要再加并列的错误布尔**。
-- `QuotaRow.swift`:额度行和分段进度条;`LoginItemSettings.swift`:`SMAppService.mainApp` 开机自启;`AppUpdater.swift`:Sparkle 封装。
+- `QuotaRow.swift`:额度行和分段进度条;`LoginItemSettings.swift`:`SMAppService.mainApp` 开机自启;`AppUpdater.swift`:Sparkle 封装;`LiquidGlassStyle.swift`:Liquid Glass 视觉(`liquidGlassSurface`/`liquidGlassCapsule` 修饰符、`LiquidGlassDivider`)。
## Codex app-server 连接(核心逻辑)
@@ -67,19 +69,22 @@ Xcode target 已关闭 App Sandbox(需要启动本机 Codex CLI 并读取用户
## UI 与错误展示约定
-- 菜单栏正常图标 `person.fill.checkmark`,错误图标 `person.fill.xmark`,切换用 `.contentTransition(.symbolEffect(.replace))`。菜单栏不展示额度数字,详情只在弹窗中展示。
+- 菜单栏正常图标 `person.fill.checkmark`,错误图标 `person.fill.xmark`,由 `StatusItemController.updateStatusImage()` 直接设置 `NSStatusItem.button.image`。菜单栏不展示额度数字,详情只在 popover 中展示。
- App 图标保持白底黑色 `timelapse`。
- 不要给 symbol API 加低版本 fallback,最低系统版本已是 macOS 15.0。
-- 弹窗按 limit 分节展示(节标题取 `limitName` 回退 `limitId`,首字母大写,节之间 `Divider`)。分段条展示**剩余**额度(`100 - usedPercent`);额度行标签由 `windowDurationMins` 动态生成(如 `300` → `5 小时`,`10080` → `7 天`)。重置时间格式 `MM-dd HH:mm`,更新时间格式 `HH:mm:ss`。
+- 弹窗整体采用 Liquid Glass 风格(`LiquidGlassStyle.swift`):`.liquidGlassSurface(...)` 给各分区/外层加玻璃质感背景,`.liquidGlassCapsule` 给 plan 徽章,分隔线用 `LiquidGlassDivider`。plan 徽章颜色由 `planBadgeTint(for:)` 按计划名子串匹配(有序优先级:enterprise→team/business→pro→plus→edu→free→默认 cyan)。
+- 弹窗按 limit 分节展示(节标题取 `limitName` 回退 `limitId`,首字母大写,节之间 `LiquidGlassDivider`)。分段条展示**剩余**额度(`100 - usedPercent`);额度行标签由 `windowDurationMins` 动态生成(如 `300` → `5 小时`,`10080` → `7 天`)。重置时间格式 `MM-dd HH:mm`,更新时间格式 `HH:mm:ss`(更新时间行不展示版本号)。
- token 贡献墙为 30 列 × 7 行蓝色方块热力图,token 数按 `M`/`B` 紧凑单位展示。
-- 设置区仅在按住 Option 点击菜单栏图标时展示;开机自启状态读取是同步 XPC,也只在设置区可见时刷新。
+- 设置走菜单栏图标**右键(或 Control 点击)菜单**的「设置」项,打开独立的 `AppSettingsView` 窗口;开机自启状态读取是同步 XPC,在设置窗口 `onAppear` 时刷新。
- **错误文案不暴露内部细节**:`serverTimeout` 只携带 JSON-RPC 步骤名;子进程 stderr 由 `PipeDrain` 排空丢弃,不进入任何用户可见文案。
- 登录类错误(`requiresLogin`):弹窗顶部橙色提示「Codex 未登录」,旧快照置灰(opacity 0.4)保留,红色错误行被抑制。其他错误:红色小字展示 `errorDescription`,旧快照保持全亮度。
- 错误文案保持显示直到某次刷新成功(`refresh()` 开始时不清空 `lastError`);旧额度快照永远不清空。
## 自动更新(Sparkle)
-`AppUpdater`(`@MainActor`、`ObservableObject`)初始化时先校验 Info.plist 的 `SUFeedURL`(http/https)和 `SUPublicEDKey`(非空),任一缺失则不创建 `SPUStandardUpdaterController`,双击版本文案显示「未配置更新资源」(Debug/未签名构建静默降级)。`statusMessage` 是唯一发布的 UI 状态,3 秒后由可取消的 `Task` 自动清空。Info.plist 位于 `CodexBar/Resources/Info.plist`(`SUFeedURL = https://codexbar.zabrian.app/appcast.xml`,检查间隔 3600 秒)。
+`AppUpdater`(`@MainActor`、`ObservableObject`)初始化时先校验 Info.plist 的 `SUFeedURL`(http/https)和 `SUPublicEDKey`(非空),任一缺失则不创建 `SPUStandardUpdaterController`,各操作文案显示「未配置更新资源」(Debug/未签名构建静默降级);`canConfigureAutomaticChecks` 是 `updaterController != nil` 的计算属性,设置窗的「自动检查更新」开关据此禁用。
+
+按 UI 表面拆三个 `@Published` 文案,不要合并:`settingsStatusMessage`(设置窗版本行,默认 3 秒后由可取消 `Task` 清空,`autoDismissDelay: nil` 时常驻)、`panelUpdateMessage`(popover 底栏被动提示)、`availableUpdateMessage`(有新版的语义标志,驱动设置窗「立即更新」按钮)。`checkForUpdates()` 是设置窗的手动检查(置 `isManualCheckInProgress`),`startUpdate()` 拉起 Sparkle 安装面板,`setAutomaticallyChecksForUpdates(_:)`/`refreshAutomaticCheckSetting()` 同步开关状态。委托回调据 `isManualCheckInProgress` 路由:手动检查的结果进 `settingsStatusMessage`,自动检查发现新版进 `panelUpdateMessage`。Info.plist 位于 `CodexBar/Resources/Info.plist`(`SUFeedURL = https://codexbar.zabrian.app/appcast.xml`,检查间隔 3600 秒)。
## Git 提交规范
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxproj
index 7d7084a..9791cef 100644
--- a/CodexBar.xcodeproj/project.pbxproj
+++ b/CodexBar.xcodeproj/project.pbxproj
@@ -15,7 +15,7 @@
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
- C42A52F22FDAD000004A2B53 /* Exceptions for "CodexBar" folder in "CodexBar" target */ = {
+ 9E664A582FDD47540016B96E /* Exceptions for "CodexBar" folder in "CodexBar" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Resources/Info.plist,
@@ -25,10 +25,10 @@
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
- C4A0FD972FD9302E000263A7 /* CodexBar */ = {
+ 9E664A4C2FDD47530016B96E /* CodexBar */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
- C42A52F22FDAD000004A2B53 /* Exceptions for "CodexBar" folder in "CodexBar" target */,
+ 9E664A582FDD47540016B96E /* Exceptions for "CodexBar" folder in "CodexBar" target */,
);
path = CodexBar;
sourceTree = "<group>";
@@ -50,7 +50,7 @@
C4A0FD8C2FD9302E000263A7 = {
isa = PBXGroup;
children = (
- C4A0FD972FD9302E000263A7 /* CodexBar */,
+ 9E664A4C2FDD47530016B96E /* CodexBar */,
C4A0FD962FD9302E000263A7 /* Products */,
);
sourceTree = "<group>";
@@ -79,7 +79,7 @@
dependencies = (
);
fileSystemSynchronizedGroups = (
- C4A0FD972FD9302E000263A7 /* CodexBar */,
+ 9E664A4C2FDD47530016B96E /* CodexBar */,
);
name = CodexBar;
packageProductDependencies = (
@@ -275,7 +275,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 4;
+ CURRENT_PROJECT_VERSION = 5;
DEVELOPMENT_TEAM = 4KJ362VJW5;
ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
ENABLE_APP_SANDBOX = NO;
@@ -290,7 +290,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 1.3.1;
+ MARKETING_VERSION = 1.3.2;
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 = 4;
+ CURRENT_PROJECT_VERSION = 5;
DEVELOPMENT_TEAM = 4KJ362VJW5;
ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
ENABLE_APP_SANDBOX = NO;
@@ -327,7 +327,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 1.3.1;
+ MARKETING_VERSION = 1.3.2;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
diff --git a/CodexBar/AppSettingsView.swift b/CodexBar/AppSettingsView.swift
new file mode 100644
index 0000000..2cdac95
--- /dev/null
+++ b/CodexBar/AppSettingsView.swift
@@ -0,0 +1,179 @@
+//
+// AppSettingsView.swift
+// CodexBar
+//
+// Created by Bob on 2026-06-14.
+//
+
+import AppKit
+import SwiftUI
+
+struct AppSettingsView: View {
+ @EnvironmentObject private var appUpdater: AppUpdater
+ @StateObject private var loginItemSettings = LoginItemSettings()
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {
+ VStack(alignment: .leading, spacing: Metrics.rowSpacing) {
+ launchAtLoginRow
+ LiquidGlassDivider()
+ automaticUpdateCheckRow
+ LiquidGlassDivider()
+ versionRow
+ }
+ .padding(Metrics.panelPadding)
+ .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)
+
+ HStack(alignment: .center, spacing: 12) {
+ quitButton
+ statusText
+ Spacer()
+ checkUpdateButton
+ }
+ .padding(Metrics.panelPadding)
+ .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .red)
+ }
+ .padding(Metrics.padding)
+ .frame(width: Metrics.windowWidth)
+ .liquidGlassSurface(
+ cornerRadii: RectangleCornerRadii(
+ topLeading: 0,
+ bottomLeading: Metrics.surfaceCornerRadius,
+ bottomTrailing: Metrics.surfaceCornerRadius,
+ topTrailing: 0
+ ),
+ tint: .cyan,
+ isOuterSurface: true
+ )
+ .onAppear {
+ loginItemSettings.refresh()
+ appUpdater.refreshAutomaticCheckSetting()
+ }
+ }
+}
+
+private extension AppSettingsView {
+ enum Metrics {
+ static let padding: CGFloat = 20
+ static let windowWidth: CGFloat = 380
+ static let sectionSpacing: CGFloat = 18
+ static let rowSpacing: CGFloat = 14
+ static let panelPadding: CGFloat = 12
+ static let surfaceCornerRadius: CGFloat = 16
+ static let panelCornerRadius: CGFloat = 10
+ static let iconWidth: CGFloat = 18
+ }
+
+ var launchAtLoginRow: some View {
+ settingsToggleRow(
+ icon: "power",
+ title: "开机自动启动",
+ isOn: Binding(
+ get: { loginItemSettings.isEnabled },
+ set: { loginItemSettings.setEnabled($0) }
+ )
+ )
+ }
+
+ var automaticUpdateCheckRow: some View {
+ settingsToggleRow(
+ icon: "arrow.triangle.2.circlepath",
+ title: "自动检查更新",
+ isOn: Binding(
+ get: { appUpdater.automaticallyChecksForUpdates },
+ set: { appUpdater.setAutomaticallyChecksForUpdates($0) }
+ ),
+ isEnabled: appUpdater.canConfigureAutomaticChecks
+ )
+ }
+
+ func settingsToggleRow(
+ icon: String,
+ title: String,
+ isOn: Binding<Bool>,
+ isEnabled: Bool = true
+ ) -> some View {
+ HStack(spacing: 10) {
+ Image(systemName: icon)
+ .frame(width: Metrics.iconWidth)
+ .foregroundStyle(.tint)
+
+ Text(title)
+
+ Spacer()
+
+ Toggle(title, isOn: isOn)
+ .labelsHidden()
+ .toggleStyle(.switch)
+ .controlSize(.small)
+ .disabled(!isEnabled)
+ }
+ }
+
+ var versionRow: some View {
+ HStack(spacing: 10) {
+ Image(systemName: "info.circle")
+ .frame(width: Metrics.iconWidth)
+ .foregroundStyle(.secondary)
+
+ Text("当前 APP 版本")
+
+ Spacer()
+
+ Text(versionStatus.text)
+ .font(versionStatus.isVersionLabel ? .body.monospacedDigit() : .body)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+
+ if appUpdater.availableUpdateMessage != nil {
+ Button {
+ appUpdater.startUpdate()
+ } label: {
+ Image(systemName: "arrow.down.circle.fill")
+ .imageScale(.large)
+ }
+ .controlSize(.small)
+ .buttonStyle(.plain)
+ .foregroundStyle(.tint)
+ .help("立即更新")
+ .accessibilityLabel("立即更新")
+ }
+ }
+ }
+
+ /// 版本行文案;无任何动态消息时回退到版本号(此时用等宽数字)
+ var versionStatus: (text: String, isVersionLabel: Bool) {
+ if let message = appUpdater.settingsStatusMessage ?? appUpdater.availableUpdateMessage {
+ return (message, false)
+ }
+ return (Bundle.main.displayVersionLabel, true)
+ }
+
+ @ViewBuilder
+ var statusText: some View {
+ if let message = loginItemSettings.errorMessage {
+ Text(message)
+ .font(.caption)
+ .foregroundStyle(.red)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+
+ var checkUpdateButton: some View {
+ Button {
+ appUpdater.checkForUpdates()
+ } label: {
+ Label("检查更新", systemImage: "arrow.down.circle")
+ }
+ }
+
+ var quitButton: some View {
+ Button(role: .destructive) {
+ NSApplication.shared.terminate(nil)
+ } label: {
+ Label("退出 CodexBar", systemImage: "power.circle")
+ }
+ .foregroundStyle(.red)
+ .keyboardShortcut("q")
+ }
+}
diff --git a/CodexBar/AppUpdater.swift b/CodexBar/AppUpdater.swift
index 1e53a21..adb8629 100644
--- a/CodexBar/AppUpdater.swift
+++ b/CodexBar/AppUpdater.swift
@@ -12,11 +12,16 @@ import SwiftUI
@MainActor
final class AppUpdater: NSObject, ObservableObject {
- @Published private(set) var statusMessage: String?
-
+ @Published private(set) var settingsStatusMessage: String?
+ @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 clearStatusMessageTask: Task<Void, Never>?
- private var hasAvailableUpdate = false
+ private var clearSettingsStatusMessageTask: Task<Void, Never>?
+ private var isManualCheckInProgress = false
init(bundle: Bundle = .main) {
super.init()
@@ -30,34 +35,60 @@ final class AppUpdater: NSObject, ObservableObject {
updaterDelegate: self,
userDriverDelegate: nil
)
+ refreshAutomaticCheckSetting()
}
func checkForUpdates() {
guard let updaterController else {
- showStatusMessage("未配置更新资源")
+ showSettingsStatusMessage("未配置更新资源")
return
}
- if hasAvailableUpdate {
- NSApplication.shared.activate()
- updaterController.checkForUpdates(nil)
+ if let availableUpdateMessage {
+ showSettingsStatusMessage(availableUpdateMessage, autoDismissDelay: nil)
return
}
- showStatusMessage("正在检查更新")
+ isManualCheckInProgress = true
+ showSettingsStatusMessage("正在检查更新")
updaterController.updater.checkForUpdateInformation()
}
- private func showStatusMessage(_ message: String, autoDismiss: Bool = true) {
- clearStatusMessageTask?.cancel()
- statusMessage = message
+ func startUpdate() {
+ guard let updaterController else {
+ showSettingsStatusMessage("未配置更新资源")
+ return
+ }
- guard autoDismiss else { return }
+ NSApplication.shared.activate()
+ updaterController.checkForUpdates(nil)
+ }
+
+ func setAutomaticallyChecksForUpdates(_ isEnabled: Bool) {
+ guard let updaterController else {
+ automaticallyChecksForUpdates = false
+ showSettingsStatusMessage("未配置更新资源")
+ return
+ }
- clearStatusMessageTask = Task { [weak self] in
- try? await Task.sleep(for: .seconds(3))
+ updaterController.updater.automaticallyChecksForUpdates = isEnabled
+ refreshAutomaticCheckSetting()
+ }
+
+ func refreshAutomaticCheckSetting() {
+ automaticallyChecksForUpdates = updaterController?.updater.automaticallyChecksForUpdates ?? false
+ }
+
+ private func showSettingsStatusMessage(_ message: String, autoDismissDelay: Duration? = .seconds(3)) {
+ clearSettingsStatusMessageTask?.cancel()
+ settingsStatusMessage = message
+
+ guard let autoDismissDelay else { return }
+
+ clearSettingsStatusMessageTask = Task { [weak self] in
+ try? await Task.sleep(for: autoDismissDelay)
guard !Task.isCancelled else { return }
- self?.statusMessage = nil
+ self?.settingsStatusMessage = nil
}
}
@@ -77,12 +108,26 @@ final class AppUpdater: NSObject, ObservableObject {
extension AppUpdater: SPUUpdaterDelegate {
func updater(_ updater: SPUUpdater, didFindValidUpdate item: SUAppcastItem) {
- hasAvailableUpdate = true
- showStatusMessage("发现新版本 v\(item.displayVersionString)", autoDismiss: false)
+ let message = "发现新版本: v\(item.displayVersionString)"
+ availableUpdateMessage = message
+
+ if isManualCheckInProgress {
+ showSettingsStatusMessage(message, autoDismissDelay: nil)
+ } else {
+ panelUpdateMessage = message
+ }
+
+ isManualCheckInProgress = false
}
func updaterDidNotFindUpdate(_ updater: SPUUpdater, error: Error) {
- hasAvailableUpdate = false
- showStatusMessage("已是最新版本")
+ availableUpdateMessage = nil
+ panelUpdateMessage = nil
+
+ if isManualCheckInProgress {
+ showSettingsStatusMessage("已是最新版本", autoDismissDelay: .milliseconds(1500))
+ }
+
+ isManualCheckInProgress = false
}
}
diff --git a/CodexBar/CodexBarApp.swift b/CodexBar/CodexBarApp.swift
index f736801..bbc7c5c 100644
--- a/CodexBar/CodexBarApp.swift
+++ b/CodexBar/CodexBarApp.swift
@@ -5,22 +5,19 @@
// Created by Bob on 2026-06-10.
//
+import AppKit
import SwiftUI
@main
struct CodexBarApp: App {
- @StateObject private var viewModel = RateLimitsViewModel()
- @StateObject private var appUpdater = AppUpdater()
+ @NSApplicationDelegateAdaptor(CodexBarAppDelegate.self) private var appDelegate
var body: some Scene {
- MenuBarExtra {
- RateLimitsMenuView(viewModel: viewModel)
- .frame(width: RateLimitsMenuView.menuWidth)
- .environmentObject(appUpdater)
- } label: {
- MenuBarStatusView(viewModel: viewModel)
+ // 实际 UI 由 CodexBarAppDelegate 的 StatusItemController 驱动
+ // App 仅需声明一个占位 Scene 设置窗口走右键菜单的 makeSettingsWindow
+ Settings {
+ EmptyView()
}
- .menuBarExtraStyle(.window)
}
}
@@ -28,4 +25,10 @@ nonisolated extension Bundle {
var shortVersionString: String? {
object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
}
+
+ /// `v1.2.3` 形式的版本文案,缺失时回退 `--`(不带 v 前缀)
+ var displayVersionLabel: String {
+ guard let version = shortVersionString else { return "--" }
+ return "v\(version)"
+ }
}
diff --git a/CodexBar/LiquidGlassStyle.swift b/CodexBar/LiquidGlassStyle.swift
new file mode 100644
index 0000000..c445467
--- /dev/null
+++ b/CodexBar/LiquidGlassStyle.swift
@@ -0,0 +1,244 @@
+//
+// LiquidGlassStyle.swift
+// CodexBar
+//
+// Created by Bob on 2026-06-14.
+//
+
+import SwiftUI
+
+extension View {
+ func liquidGlassSurface(
+ cornerRadius: CGFloat,
+ tint: Color,
+ isOuterSurface: Bool = false
+ ) -> some View {
+ liquidGlassSurface(
+ cornerRadii: RectangleCornerRadii(
+ topLeading: cornerRadius,
+ bottomLeading: cornerRadius,
+ bottomTrailing: cornerRadius,
+ topTrailing: cornerRadius
+ ),
+ tint: tint,
+ isOuterSurface: isOuterSurface
+ )
+ }
+
+ func liquidGlassSurface(
+ cornerRadii: RectangleCornerRadii,
+ tint: Color,
+ isOuterSurface: Bool = false
+ ) -> some View {
+ background {
+ LiquidGlassSurface(
+ cornerRadii: cornerRadii,
+ tint: tint,
+ isOuterSurface: isOuterSurface
+ )
+ }
+ }
+
+ func liquidGlassCapsule(tint: Color) -> some View {
+ background {
+ LiquidGlassCapsule(tint: tint)
+ }
+ }
+}
+
+struct LiquidGlassDivider: View {
+ var body: some View {
+ Rectangle()
+ .fill(
+ LinearGradient(
+ colors: [
+ .clear,
+ .white.opacity(0.36),
+ .primary.opacity(0.08),
+ .clear
+ ],
+ startPoint: .leading,
+ endPoint: .trailing
+ )
+ )
+ .frame(height: 1)
+ }
+}
+
+private struct LiquidGlassSurface: View {
+ let cornerRadii: RectangleCornerRadii
+ let tint: Color
+ let isOuterSurface: Bool
+ @Environment(\.colorScheme) private var colorScheme
+
+ var body: some View {
+ let shape = UnevenRoundedRectangle(cornerRadii: cornerRadii, style: .continuous)
+
+ ZStack {
+ shape
+ .fill(baseFill)
+
+ shape
+ .fill(
+ LinearGradient(
+ colors: [
+ .white.opacity(isOuterSurface ? 0.18 : 0.24),
+ tint.opacity(isOuterSurface ? 0.08 : 0.12),
+ .clear
+ ],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ )
+ )
+ .blendMode(.plusLighter)
+
+ shape
+ .strokeBorder(
+ LinearGradient(
+ colors: [
+ .white.opacity(isOuterSurface ? 0.44 : 0.36),
+ tint.opacity(0.24),
+ .primary.opacity(0.08)
+ ],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ ),
+ lineWidth: isOuterSurface ? 1.0 : 0.8
+ )
+
+ LiquidGlassSpecular(cornerRadii: cornerRadii)
+ .opacity(isOuterSurface ? 0.82 : 0.64)
+ }
+ .shadow(
+ color: raisedHighlightShadowColor,
+ radius: isOuterSurface ? 0 : 2,
+ x: isOuterSurface ? 0 : -1,
+ y: isOuterSurface ? 0 : -1
+ )
+ .shadow(
+ color: ambientShadowColor,
+ radius: isOuterSurface ? 18 : 12,
+ x: 0,
+ y: isOuterSurface ? 10 : 7
+ )
+ .shadow(
+ color: contactShadowColor,
+ radius: isOuterSurface ? 0 : 3,
+ x: 0,
+ y: isOuterSurface ? 0 : 2
+ )
+ }
+
+ private var baseFill: LinearGradient {
+ LinearGradient(
+ colors: [
+ baseColor.opacity(isOuterSurface ? 1 : 0.94),
+ baseColor.opacity(isOuterSurface ? 0.88 : 0.78)
+ ],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ )
+ }
+
+ 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)
+ }
+}
+
+private struct LiquidGlassCapsule: View {
+ let tint: Color
+ @Environment(\.colorScheme) private var colorScheme
+
+ var body: some View {
+ Capsule(style: .continuous)
+ .fill(baseFill)
+ .overlay {
+ Capsule(style: .continuous)
+ .fill(
+ LinearGradient(
+ colors: [
+ .white.opacity(colorScheme == .dark ? 0.18 : 0.36),
+ tint.opacity(colorScheme == .dark ? 0.16 : 0.12),
+ .clear
+ ],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ )
+ )
+ .blendMode(.plusLighter)
+ }
+ .overlay {
+ Capsule(style: .continuous)
+ .strokeBorder(.white.opacity(colorScheme == .dark ? 0.22 : 0.34), lineWidth: 0.7)
+ }
+ }
+
+ private var baseFill: LinearGradient {
+ LinearGradient(
+ colors: [
+ baseColor.opacity(colorScheme == .dark ? 0.76 : 0.70),
+ baseColor.opacity(colorScheme == .dark ? 0.58 : 0.52)
+ ],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ )
+ }
+
+ private var baseColor: Color {
+ colorScheme == .dark
+ ? Color(red: 0.16, green: 0.18, blue: 0.20)
+ : Color.white
+ }
+}
+
+private struct LiquidGlassSpecular: View {
+ let cornerRadii: RectangleCornerRadii
+
+ var body: some View {
+ UnevenRoundedRectangle(cornerRadii: cornerRadii, style: .continuous)
+ .strokeBorder(
+ AngularGradient(
+ colors: [
+ .white.opacity(0.52),
+ .white.opacity(0.04),
+ .white.opacity(0.18),
+ .clear,
+ .white.opacity(0.42)
+ ],
+ center: .center,
+ startAngle: .degrees(215),
+ endAngle: .degrees(575)
+ ),
+ lineWidth: 1
+ )
+ .blur(radius: 0.15)
+ }
+}
diff --git a/CodexBar/LoginItemSettings.swift b/CodexBar/LoginItemSettings.swift
index 2fde233..848a6ec 100644
--- a/CodexBar/LoginItemSettings.swift
+++ b/CodexBar/LoginItemSettings.swift
@@ -35,7 +35,7 @@ final class LoginItemSettings: ObservableObject {
refresh()
} catch {
refresh()
- errorMessage = "设置开机自动启动失败: \(error.localizedDescription)"
+ errorMessage = "设置开机启动失败: \(error.localizedDescription)"
}
}
}
diff --git a/CodexBar/MenuBarStatusView.swift b/CodexBar/MenuBarStatusView.swift
deleted file mode 100644
index 7450f17..0000000
--- a/CodexBar/MenuBarStatusView.swift
+++ /dev/null
@@ -1,21 +0,0 @@
-//
-// MenuBarStatusView.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-10.
-//
-
-import SwiftUI
-
-struct MenuBarStatusView: View {
- @ObservedObject var viewModel: RateLimitsViewModel
-
- var body: some View {
- Image(systemName: viewModel.hasError ? "person.fill.xmark" : "person.fill.checkmark")
- .contentTransition(.symbolEffect(.replace))
- .animation(.default, value: viewModel.hasError)
- .task {
- viewModel.startAutoRefresh()
- }
- }
-}
diff --git a/CodexBar/RateLimitsMenuView.swift b/CodexBar/RateLimitsMenuView.swift
index 90336cf..125eed1 100644
--- a/CodexBar/RateLimitsMenuView.swift
+++ b/CodexBar/RateLimitsMenuView.swift
@@ -9,12 +9,10 @@ import AppKit
import SwiftUI
struct RateLimitsMenuView: View {
- static let menuWidth: CGFloat = Metrics.padding * 2 + UsageHeatmap.Metrics.totalWidth
+ static let menuWidth: CGFloat = Metrics.padding * 2 + Metrics.panelPadding * 2 + UsageHeatmap.Metrics.totalWidth
@ObservedObject var viewModel: RateLimitsViewModel
@EnvironmentObject private var appUpdater: AppUpdater
- @StateObject private var loginItemSettings = LoginItemSettings()
- @State private var showsControls = false
@State private var isEmailBlurred = false
var body: some View {
@@ -22,19 +20,9 @@ struct RateLimitsMenuView: View {
content
// 未登录已有专属橙色提示, 不再重复显示同文案的红色错误行
errorView(viewModel.requiresLogin ? nil : viewModel.errorMessage)
- errorView(loginItemSettings.errorMessage)
- controls
}
.padding(Metrics.padding)
- .onAppear {
- viewModel.refreshIfNeeded()
- showsControls = NSEvent.modifierFlags.contains(.option)
-
- // 开机自启状态读取是同步 XPC, 仅在设置区可见时刷新
- if showsControls {
- loginItemSettings.refresh()
- }
- }
+ .liquidGlassSurface(cornerRadius: Metrics.surfaceCornerRadius, tint: .cyan, isOuterSurface: true)
.onChange(of: viewModel.snapshot?.account.email) { _, _ in
isEmailBlurred = false
}
@@ -44,6 +32,9 @@ struct RateLimitsMenuView: View {
private extension RateLimitsMenuView {
enum Metrics {
static let padding: CGFloat = 12
+ static let panelPadding: CGFloat = 10
+ static let surfaceCornerRadius: CGFloat = 14
+ static let panelCornerRadius: CGFloat = 8
static let verticalSpacing: CGFloat = 10
static let accountIconSize: CGFloat = 14
static let loadingVerticalPadding: CGFloat = 16
@@ -57,7 +48,7 @@ private extension RateLimitsMenuView {
if let snapshot = viewModel.snapshot {
Group {
- accountRow(
+ accountCard(
title: snapshot.accountLabel,
isEmail: snapshot.account.hasEmail,
plan: snapshot.planLabel
@@ -70,12 +61,17 @@ private extension RateLimitsMenuView {
}
updatedAtRow(for: snapshot)
+ .padding(.horizontal, Metrics.panelPadding)
+ .padding(.vertical, 7)
+ .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .mint)
}
// 未登录时旧数据已过期, 置灰提示不可信
.opacity(viewModel.requiresLogin ? 0.4 : 1)
} else {
- accountRow(title: "")
+ accountCard(title: "")
emptyView
+ .padding(Metrics.panelPadding)
+ .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)
}
}
@@ -93,15 +89,6 @@ private extension RateLimitsMenuView {
}
}
- @ViewBuilder
- var controls: some View {
- if showsControls {
- Divider()
- settingsView
- }
- }
-
-
var emptyView: some View {
Text("暂无数据")
.foregroundStyle(.secondary)
@@ -113,12 +100,14 @@ private extension RateLimitsMenuView {
VStack(alignment: .leading, spacing: 8) {
ForEach(limits) { limit in
if limit.id != limits.first?.id {
- Divider()
+ LiquidGlassDivider()
}
quotaLimitSection(limit)
}
}
+ .padding(Metrics.panelPadding)
+ .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .green)
}
func quotaLimitSection(_ limit: CodexQuotaLimitSnapshot) -> some View {
@@ -137,6 +126,13 @@ private extension RateLimitsMenuView {
}
}
+ func accountCard(title: String, isEmail: Bool = false, plan: String? = nil) -> some View {
+ accountRow(title: title, isEmail: isEmail, plan: plan)
+ .padding(.horizontal, Metrics.panelPadding)
+ .padding(.vertical, 8)
+ .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)
+ }
+
func accountRow(title: String, isEmail: Bool = false, plan: String? = nil) -> some View {
HStack(spacing: 8) {
Image(systemName: "person.fill")
@@ -166,13 +162,15 @@ private extension RateLimitsMenuView {
Spacer()
if let plan {
+ let tint = planBadgeTint(for: plan)
+
Text(plan.uppercased())
.font(.caption2)
- .foregroundStyle(.secondary)
+ .foregroundStyle(tint)
.lineLimit(1)
.padding(.horizontal, 5)
.padding(.vertical, 2)
- .background(.secondary.opacity(0.12), in: Capsule())
+ .liquidGlassCapsule(tint: tint)
}
}
}
@@ -182,39 +180,18 @@ private extension RateLimitsMenuView {
Text("更新时间 \(snapshot.generatedAt, formatter: Self.timeFormatter)")
.font(.caption2)
.foregroundStyle(.secondary)
-
- Spacer()
-
- Text(appUpdater.statusMessage ?? Self.appVersionLabel)
- .font(.caption2.monospacedDigit())
- .foregroundStyle(.secondary)
- .lineLimit(1)
- .onTapGesture(count: 2) {
- appUpdater.checkForUpdates()
- }
- }
- }
-
- var settingsView: some View {
- HStack {
- Toggle(
- "开机自动启动",
- isOn: Binding(
- get: { loginItemSettings.isEnabled },
- set: { loginItemSettings.setEnabled($0) }
- )
- )
- .toggleStyle(.switch)
- .controlSize(.small)
- .font(.caption)
-
+
Spacer()
- Button("退出") {
- NSApplication.shared.terminate(nil)
+ if let message = appUpdater.panelUpdateMessage {
+ Text(message)
+ .font(.caption2.monospacedDigit())
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .onTapGesture(count: 2) {
+ appUpdater.startUpdate()
+ }
}
- .foregroundStyle(.red)
- .keyboardShortcut("q")
}
}
@@ -229,17 +206,42 @@ private extension RateLimitsMenuView {
}
}
+ func planBadgeTint(for plan: String) -> Color {
+ let normalizedPlan = plan.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+
+ if normalizedPlan.contains("enterprise") {
+ return .green
+ }
+
+ if normalizedPlan.contains("team") || normalizedPlan.contains("business") {
+ return .orange
+ }
+
+ if normalizedPlan.contains("pro") {
+ return .purple
+ }
+
+ if normalizedPlan.contains("plus") {
+ return .blue
+ }
+
+ if normalizedPlan.contains("edu") {
+ return .teal
+ }
+
+ if normalizedPlan.contains("free") {
+ return .secondary
+ }
+
+ return .cyan
+ }
+
static let timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "zh_CN")
formatter.dateFormat = "HH:mm:ss"
return formatter
}()
-
- static let appVersionLabel: String = {
- let version = Bundle.main.shortVersionString ?? "--"
- return "App 版本: v\(version)"
- }()
}
private struct UsageSummaryView: View {
@@ -254,8 +256,6 @@ private struct UsageSummaryView: View {
var body: some View {
VStack(alignment: .leading, spacing: 8) {
- Divider()
-
HStack(alignment: .firstTextBaseline) {
metric(label: "单日峰值", value: usage.summary.peakDailyTokens, alignment: .leading)
Spacer()
@@ -264,6 +264,8 @@ private struct UsageSummaryView: View {
UsageHeatmap(days: days, hoveredDay: $hoveredDay)
}
+ .padding(10)
+ .liquidGlassSurface(cornerRadius: 8, tint: .blue)
.onAppear {
hoveredDay = nil
}
@@ -462,12 +464,7 @@ private struct UsageHeatmapTooltip: View {
.padding(.horizontal, 7)
.padding(.vertical, 5)
.frame(width: UsageHeatmap.Metrics.tooltipWidth, alignment: .leading)
- .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 7, style: .continuous))
- .overlay {
- RoundedRectangle(cornerRadius: 7, style: .continuous)
- .stroke(Color.blue.opacity(0.22), lineWidth: 0.8)
- }
- .shadow(color: .black.opacity(0.14), radius: 7, y: 3)
+ .liquidGlassSurface(cornerRadius: 7, tint: .blue)
}
}
diff --git a/CodexBar/StatusItemController.swift b/CodexBar/StatusItemController.swift
new file mode 100644
index 0000000..d11adbe
--- /dev/null
+++ b/CodexBar/StatusItemController.swift
@@ -0,0 +1,468 @@
+//
+// StatusItemController.swift
+// CodexBar
+//
+// Created by Bob on 2026-06-14.
+//
+
+import AppKit
+import Combine
+import SwiftUI
+
+@MainActor
+final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
+ let viewModel = RateLimitsViewModel()
+ let appUpdater = AppUpdater()
+
+ private var statusItemController: StatusItemController?
+
+ func applicationDidFinishLaunching(_ notification: Notification) {
+ let controller = StatusItemController(viewModel: viewModel, appUpdater: appUpdater)
+ controller.install()
+ statusItemController = controller
+ }
+
+ func applicationWillTerminate(_ notification: Notification) {
+ statusItemController?.uninstall()
+ }
+}
+
+@MainActor
+private final class StatusItemController: NSObject {
+ private let viewModel: RateLimitsViewModel
+ private let appUpdater: AppUpdater
+ private let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
+ private let popover = NSPopover()
+
+ private var settingsWindow: NSWindow?
+ private var deferredRefreshTask: Task<Void, Never>?
+ private var popoverOpenTask: Task<Void, Never>?
+ private var popoverCloseTask: Task<Void, Never>?
+ private var popoverState = PopoverState.hidden
+ private var popoverAnimationGeneration = 0
+ private var localMouseEventMonitor: Any?
+ private var globalMouseEventMonitor: Any?
+ private var cancellables = Set<AnyCancellable>()
+ private var lastHasError: Bool?
+
+ private static let normalImage = NSImage(systemSymbolName: "person.fill.checkmark", accessibilityDescription: nil)
+ private static let errorImage = NSImage(systemSymbolName: "person.fill.xmark", accessibilityDescription: nil)
+
+ init(viewModel: RateLimitsViewModel, appUpdater: AppUpdater) {
+ self.viewModel = viewModel
+ self.appUpdater = appUpdater
+ super.init()
+ }
+
+ func install() {
+ configureStatusButton()
+ configurePopover()
+ observeViewModel()
+ updateStatusImage()
+ viewModel.startAutoRefresh()
+ }
+
+ func uninstall() {
+ closePopover(animated: false)
+ cancellables.removeAll()
+ NSStatusBar.system.removeStatusItem(statusItem)
+ }
+
+ private func configureStatusButton() {
+ guard let button = statusItem.button else {
+ return
+ }
+
+ button.target = self
+ button.action = #selector(statusItemClicked(_:))
+ button.imagePosition = .imageOnly
+ button.toolTip = "CodexBar"
+ button.sendAction(on: [.leftMouseUp, .rightMouseUp])
+ }
+
+ private func configurePopover() {
+ let rootView = RateLimitsMenuView(viewModel: viewModel)
+ .environmentObject(appUpdater)
+ .frame(width: RateLimitsMenuView.menuWidth)
+
+ let hostingController = NSHostingController(rootView: rootView)
+ hostingController.sizingOptions = [.preferredContentSize]
+
+ popover.behavior = .applicationDefined
+ popover.animates = false
+ popover.contentViewController = hostingController
+ }
+
+ private func observeViewModel() {
+ viewModel.objectWillChange
+ .sink { [weak self] _ in
+ Task { @MainActor [weak self] in
+ self?.updateStatusImage()
+ }
+ }
+ .store(in: &cancellables)
+ }
+
+ private func updateStatusImage() {
+ let hasError = viewModel.hasError
+ guard hasError != lastHasError else {
+ return
+ }
+
+ lastHasError = hasError
+ statusItem.button?.image = hasError ? Self.errorImage : Self.normalImage
+ }
+
+ @objc private func statusItemClicked(_ sender: NSStatusBarButton) {
+ guard let event = NSApplication.shared.currentEvent else {
+ togglePopover(relativeTo: sender)
+ return
+ }
+
+ if event.type == .rightMouseUp || event.modifierFlags.contains(.control) {
+ showContextMenu(relativeTo: sender)
+ } else {
+ togglePopover(relativeTo: sender)
+ }
+ }
+
+ private func togglePopover(relativeTo button: NSStatusBarButton) {
+ switch popoverState {
+ case .hidden:
+ openPopover(relativeTo: button)
+ case .opening, .shown:
+ closePopover()
+ case .closing:
+ finishPopoverClose()
+ openPopover(relativeTo: button)
+ }
+ }
+
+ private func cancelPopoverTasks() {
+ deferredRefreshTask?.cancel()
+ deferredRefreshTask = nil
+ popoverOpenTask?.cancel()
+ popoverOpenTask = nil
+ popoverCloseTask?.cancel()
+ popoverCloseTask = nil
+ }
+
+ private func openPopover(relativeTo button: NSStatusBarButton) {
+ cancelPopoverTasks()
+
+ popoverAnimationGeneration += 1
+ let generation = popoverAnimationGeneration
+ popoverState = .opening
+
+ preparePopoverForFadeIn()
+ popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
+ stabilizePopoverChromeAppearance()
+ installPopoverDismissMonitors()
+ fadePopover(to: 1, duration: Metrics.fadeInDuration)
+
+ popoverOpenTask = Task { @MainActor [weak self] in
+ try? await Task.sleep(for: .milliseconds(Int(Metrics.fadeInDuration * 1000)))
+ guard let self, !Task.isCancelled, self.popoverAnimationGeneration == generation else {
+ return
+ }
+
+ self.resetPopoverAlpha()
+ self.popoverState = .shown
+ self.popoverOpenTask = nil
+ }
+
+ scheduleDeferredRefresh()
+ }
+
+ private func showContextMenu(relativeTo button: NSStatusBarButton) {
+ closePopover(animated: false)
+
+ let menu = NSMenu()
+
+ let settingsItem = NSMenuItem(
+ title: "设置",
+ action: #selector(openSettings),
+ keyEquivalent: ","
+ )
+ settingsItem.image = NSImage(systemSymbolName: "gearshape", accessibilityDescription: nil)
+ settingsItem.target = self
+ menu.addItem(settingsItem)
+
+ menu.addItem(.separator())
+
+ let quitItem = NSMenuItem(
+ title: "退出",
+ action: #selector(quit),
+ keyEquivalent: "q"
+ )
+ quitItem.image = NSImage(systemSymbolName: "power", accessibilityDescription: nil)
+ quitItem.target = self
+ menu.addItem(quitItem)
+
+ menu.popUp(
+ positioning: nil,
+ at: NSPoint(x: 0, y: button.bounds.minY - 4),
+ in: button
+ )
+ }
+
+ @objc private func openSettings() {
+ if settingsWindow == nil {
+ settingsWindow = makeSettingsWindow()
+ }
+
+ guard let settingsWindow else {
+ return
+ }
+
+ NSApplication.shared.activate()
+ prepareSettingsWindowForDisplay(settingsWindow)
+ settingsWindow.makeKeyAndOrderFront(nil)
+ }
+
+ @objc private func quit() {
+ NSApplication.shared.terminate(nil)
+ }
+
+ private func closePopover(animated: Bool = true) {
+ if popoverState == .closing && animated {
+ return
+ }
+
+ cancelPopoverTasks()
+ removePopoverDismissMonitors()
+
+ guard popover.isShown else {
+ resetPopoverAlpha()
+ popoverState = .hidden
+ return
+ }
+
+ guard animated, let contentView = popover.contentViewController?.view else {
+ finishPopoverClose()
+ return
+ }
+
+ popoverAnimationGeneration += 1
+ let generation = popoverAnimationGeneration
+ popoverState = .closing
+
+ let popoverWindow = contentView.window
+ fadePopover(to: 0, duration: Metrics.fadeOutDuration)
+ popoverCloseTask = Task { @MainActor [weak self, weak contentView, weak popoverWindow] in
+ try? await Task.sleep(for: .milliseconds(Int(Metrics.fadeOutDuration * 1000)))
+ guard let self, !Task.isCancelled, self.popoverAnimationGeneration == generation else {
+ return
+ }
+
+ self.popover.performClose(nil)
+ contentView?.alphaValue = 1
+ popoverWindow?.alphaValue = 1
+ self.popoverState = .hidden
+ self.popoverCloseTask = nil
+ }
+ }
+
+ private func finishPopoverClose() {
+ cancelPopoverTasks()
+ popoverAnimationGeneration += 1
+ removePopoverDismissMonitors()
+
+ if popover.isShown {
+ popover.performClose(nil)
+ }
+
+ resetPopoverAlpha()
+ popoverState = .hidden
+ }
+
+ private func installPopoverDismissMonitors() {
+ removePopoverDismissMonitors()
+
+ localMouseEventMonitor = NSEvent.addLocalMonitorForEvents(matching: Metrics.dismissEventMask) { [weak self] event in
+ self?.closePopoverIfNeeded(for: event)
+ self?.restabilizePopoverChromeAfterEvent()
+ return event
+ }
+
+ globalMouseEventMonitor = NSEvent.addGlobalMonitorForEvents(matching: Metrics.dismissEventMask) { [weak self] _ in
+ self?.closePopover()
+ }
+ }
+
+ private func removePopoverDismissMonitors() {
+ if let localMouseEventMonitor {
+ NSEvent.removeMonitor(localMouseEventMonitor)
+ self.localMouseEventMonitor = nil
+ }
+
+ if let globalMouseEventMonitor {
+ NSEvent.removeMonitor(globalMouseEventMonitor)
+ self.globalMouseEventMonitor = nil
+ }
+ }
+
+ private func restabilizePopoverChromeAfterEvent() {
+ Task { @MainActor [weak self] in
+ await Task.yield()
+ guard let self, self.popover.isShown else {
+ return
+ }
+
+ self.stabilizePopoverChromeAppearance()
+ }
+ }
+
+ private func stabilizePopoverChromeAppearance() {
+ guard let rootView = popover.contentViewController?.view.window?.contentView else {
+ return
+ }
+
+ stabilizeVisualEffectViews(in: rootView)
+ }
+
+ private func stabilizeVisualEffectViews(in view: NSView) {
+ if let visualEffectView = view as? NSVisualEffectView {
+ visualEffectView.state = .inactive
+ visualEffectView.isEmphasized = false
+ }
+
+ for subview in view.subviews {
+ stabilizeVisualEffectViews(in: subview)
+ }
+ }
+
+ private func closePopoverIfNeeded(for event: NSEvent) {
+ guard popover.isShown else {
+ return
+ }
+
+ if isEventInsidePopover(event) || isEventInsideStatusButton(event) {
+ return
+ }
+
+ closePopover()
+ }
+
+ private func isEventInsidePopover(_ event: NSEvent) -> Bool {
+ guard let contentView = popover.contentViewController?.view,
+ event.window == contentView.window else {
+ return false
+ }
+
+ let point = contentView.convert(event.locationInWindow, from: nil)
+ return contentView.bounds.contains(point)
+ }
+
+ private func isEventInsideStatusButton(_ event: NSEvent) -> Bool {
+ guard let button = statusItem.button,
+ let buttonWindow = button.window else {
+ return false
+ }
+
+ let eventScreenPoint = event.window?.convertPoint(toScreen: event.locationInWindow) ?? NSEvent.mouseLocation
+ let buttonRectInWindow = button.convert(button.bounds, to: nil)
+ let buttonScreenRect = buttonWindow.convertToScreen(buttonRectInWindow)
+ return buttonScreenRect.contains(eventScreenPoint)
+ }
+
+ private func preparePopoverForFadeIn() {
+ popover.contentViewController?.view.alphaValue = 0
+ popover.contentViewController?.view.window?.alphaValue = 0
+ }
+
+ private func resetPopoverAlpha() {
+ popover.contentViewController?.view.alphaValue = 1
+ popover.contentViewController?.view.window?.alphaValue = 1
+ }
+
+ private func fadePopover(to alpha: CGFloat, duration: TimeInterval) {
+ guard let contentView = popover.contentViewController?.view else {
+ return
+ }
+
+ let popoverWindow = contentView.window
+ // 淡入前窗口可能刚由 popover.show 懒创建,先把窗口 alpha 归零再动画
+ if alpha == 1 {
+ popoverWindow?.alphaValue = 0
+ }
+
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = duration
+ context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
+ popoverWindow?.animator().alphaValue = alpha
+ contentView.animator().alphaValue = alpha
+ }
+ }
+
+ private func scheduleDeferredRefresh() {
+ deferredRefreshTask?.cancel()
+ deferredRefreshTask = Task { @MainActor [weak self] in
+ try? await Task.sleep(for: .milliseconds(160))
+ guard let self, !Task.isCancelled, self.popover.isShown else {
+ return
+ }
+
+ self.viewModel.refreshIfNeeded()
+ }
+ }
+
+ private func makeSettingsWindow() -> NSWindow {
+ let hostingController = NSHostingController(
+ rootView: AppSettingsView()
+ .environmentObject(appUpdater)
+ )
+ hostingController.sizingOptions = [.preferredContentSize]
+
+ let window = NSWindow(contentViewController: hostingController)
+ window.title = "CodexBar 设置"
+ window.styleMask = [.titled, .closable, .miniaturizable]
+ window.isReleasedWhenClosed = false
+ return window
+ }
+
+ private func prepareSettingsWindowForDisplay(_ window: NSWindow) {
+ window.contentViewController?.view.layoutSubtreeIfNeeded()
+
+ if let fittingSize = window.contentViewController?.view.fittingSize,
+ fittingSize.width > 0,
+ fittingSize.height > 0 {
+ window.setContentSize(fittingSize)
+ }
+
+ centerSettingsWindow(window)
+ }
+
+ private func centerSettingsWindow(_ window: NSWindow) {
+ guard let screen = statusItem.button?.window?.screen ?? window.screen ?? NSScreen.main else {
+ window.center()
+ return
+ }
+
+ let visibleFrame = screen.visibleFrame
+ let windowFrame = window.frame
+ let origin = NSPoint(
+ x: visibleFrame.midX - windowFrame.width / 2,
+ y: visibleFrame.midY - windowFrame.height / 2
+ )
+
+ window.setFrameOrigin(origin)
+ }
+
+ private enum Metrics {
+ static let dismissEventMask: NSEvent.EventTypeMask = [
+ .leftMouseDown,
+ .rightMouseDown,
+ .otherMouseDown
+ ]
+ static let fadeInDuration: TimeInterval = 0.24
+ static let fadeOutDuration: TimeInterval = 0.18
+ }
+
+ private enum PopoverState {
+ case hidden
+ case opening
+ case shown
+ case closing
+ }
+}
diff --git a/Updates/appcast.xml b/Updates/appcast.xml
index 9a37765..cac59a6 100644
--- a/Updates/appcast.xml
+++ b/Updates/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 1.3.2</title>
+ <sparkle:version>5</sparkle:version>
+ <sparkle:shortVersionString>1.3.2</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes/1.3.2.html</sparkle:releaseNotesLink>
+ <pubDate>Sun, 14 Jun 2026 15:12:18 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v1.3.2.dmg" sparkle:edSignature="FWk4PT/QIvq17Z3NzHZD7hao5NEhpLMsoOL3UMHl5l08nFZINtrUj4w4Hapkh8V4rkk6BbxN08kayns5L73wAg==" length="1396203" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 1.3.1</title>
<sparkle:version>4</sparkle:version>