CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
refactor: 调整重建结果展示并统一 Debug helper 标识
Bob8388a09edc19
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex 78abdd3..1b86f2c 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -72,7 +72,7 @@isa = PBXFileSystemSynchronizedGroupBuildPhaseMembershipExceptionSet;buildPhase = B10000000000000000000024 /* Copy LaunchDaemons */;membershipExceptions = (- app.zabrian.codexbar.debug.helper.plist,+ app.zabrian.codexbar.helper.debug.plist,app.zabrian.codexbar.helper.plist,);};@@ -322,7 +322,7 @@ENABLE_APP_SANDBOX = NO;ENABLE_HARDENED_RUNTIME = YES;GENERATE_INFOPLIST_FILE = YES;- PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.debug.helper;+ PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.helper.debug;PRODUCT_NAME = "$(TARGET_NAME)";SKIP_INSTALL = YES;SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;@@ -523,7 +523,7 @@ENABLE_HARDENED_RUNTIME = YES;ENABLE_PREVIEWS = YES;ENABLE_USER_SELECTED_FILES = NO;- EXCLUDED_SOURCE_FILE_NAMES = app.zabrian.codexbar.debug.helper.plist;+ EXCLUDED_SOURCE_FILE_NAMES = app.zabrian.codexbar.helper.debug.plist;GENERATE_INFOPLIST_FILE = NO;INFOPLIST_FILE = CodexBar/Resources/Info.plist;INFOPLIST_KEY_CFBundleDisplayName = CodexBar;diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstringsindex 29dd75b..0ad890c 100644--- a/CodexBar/Resources/Localizable.xcstrings+++ b/CodexBar/Resources/Localizable.xcstrings@@ -5697,50 +5697,34 @@}}},- "workflow.rebuild.selection.day-count" : {+ "workflow.rebuild.result.completed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Selected days: %lld"+ "value" : "Rebuild Complete"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "已选择 %lld 天"+ "value" : "重建完成"}}}},- "workflow.rebuild.selection.none" : {+ "workflow.rebuild.result.failed" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "No date range selected"+ "value" : "Rebuild Failed"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "未选择重建日期范围"- }- }- }- },- "workflow.rebuild.status.failed" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Rebuild failed: %@"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "重建失败: %@"+ "value" : "重建失败"}}}@@ -5788,7 +5772,7 @@"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "已重建 %1$lld 天, 包含 %2$lld 条数据"+ "value" : "已重建 %1$lld 天, 包含 Hook 数据 %2$lld 条"}}}@@ -5862,29 +5846,13 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "; could not replace cloud data; try rebuilding this data later"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "; 云端替换未能完成, 请稍后重新重建这些数据"- }- }- }- },- "workflow.rebuild.status.running" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Rebuilding activity data and session token data in the background"+ "value" : "; could not replace cloud data, please try again later"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "正在后台重建活动数据和会话 Token 数据"+ "value" : "; 云端替换未能完成, 请稍后重新尝试"}}}diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex bb0f663..94cc1ac 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -31,7 +31,7 @@ struct AppSettingsView: View {@State private var selectedRebuildRange: RebuildDateRange?@State private var isShowingRebuildConfirmation = false@State private var isRebuildingWorkflowData = false- @State private var rebuildStatus: RebuildStatus?+ @State private var rebuildResult: RebuildResult?@State private var helperFeatureConfirmation: HelperFeatureConfirmation?var body: some View {@@ -102,7 +102,7 @@ struct AppSettingsView: View {selectedRebuildRange = nilisShowingRebuildConfirmation = falsehelperFeatureConfirmation = nil- clearRebuildStatus()+ rebuildResult = nil}.onChange(of: selectedTab) { _, _ inonOptionsAction(.closeAll)@@ -139,6 +139,22 @@ struct AppSettingsView: View {} message: {Text(LocalizedStringResource("workflow.rebuild.confirmation.message", defaultValue: "\(selectedRebuildRange?.displayText ?? "")"))}+ .alert(+ rebuildResult?.title ?? LocalizedStringResource("workflow.rebuild.result.completed"),+ isPresented: Binding(+ get: { rebuildResult != nil },+ set: {+ if !$0 {+ rebuildResult = nil+ }+ }+ ),+ presenting: rebuildResult+ ) { _ in+ Button("common.action.close", role: .cancel) {}+ } message: { result in+ Text(verbatim: result.message)+ }.alert(item: $helperFeatureConfirmation) { feature infeature.alert(helperStatus: keepAliveController.helperStatus) {switch feature {@@ -708,75 +724,42 @@ private extension AppSettingsView {// MARK: - 数据重建var rebuildWorkflowDataRow: some View {- VStack(alignment: .leading, spacing: 4) {- HStack(spacing: SettingsRowMetrics.spacing) {- Image(systemName: "arrow.clockwise.circle")- .frame(width: SettingsRowMetrics.iconWidth)- .foregroundStyle(.tint)+ HStack(spacing: SettingsRowMetrics.spacing) {+ Image(systemName: "arrow.clockwise.circle")+ .frame(width: SettingsRowMetrics.iconWidth)+ .foregroundStyle(.tint)- Text("workflow.rebuild.title")- .lineLimit(1)- .fixedSize(horizontal: true, vertical: false)+ Text("workflow.rebuild.title")+ .lineLimit(1)+ .fixedSize(horizontal: true, vertical: false)- Spacer(minLength: 4)+ Spacer(minLength: 4)- RebuildDatePicker(- selection: $selectedRebuildRange,- dataDateKeys: Set(rebuildableDates),- isEnabled: !isRebuildingWorkflowData- )- .frame(- width: RebuildLayoutMetrics.pickerWidth,- height: RebuildLayoutMetrics.controlHeight,- alignment: .leading- )+ RebuildDatePicker(+ selection: $selectedRebuildRange,+ dataDateKeys: Set(rebuildableDates),+ isEnabled: !isRebuildingWorkflowData+ )+ .frame(+ width: RebuildLayoutMetrics.pickerWidth,+ height: RebuildLayoutMetrics.controlHeight,+ alignment: .leading+ )- if isRebuildingWorkflowData {- ProgressView()- .controlSize(.small)- .frame(minWidth: RebuildLayoutMetrics.actionMinimumWidth)- } else {- Button("workflow.rebuild.action") {- isShowingRebuildConfirmation = true- }+ if isRebuildingWorkflowData {+ ProgressView().controlSize(.small).frame(minWidth: RebuildLayoutMetrics.actionMinimumWidth)- .disabled(selectedRebuildDateKeys.isEmpty)+ } else {+ Button("workflow.rebuild.action") {+ isShowingRebuildConfirmation = true}+ .controlSize(.small)+ .frame(minWidth: RebuildLayoutMetrics.actionMinimumWidth)+ .disabled(selectedRebuildDateKeys.isEmpty)}- .frame(height: RebuildLayoutMetrics.controlHeight)-- let caption = rebuildCaption- SettingsCaptionMessageRow(- message: caption.message,- color: caption.isError ? .red : .secondary- )}- }-- var rebuildCaption: RebuildStatus {- if isRebuildingWorkflowData {- return RebuildStatus(message: String(localized: "workflow.rebuild.status.running"), isError: false)- }- if let rebuildStatus {- return rebuildStatus- }- guard let selectedRebuildRange else {- return RebuildStatus(message: String(localized: "workflow.rebuild.selection.none"), isError: false)- }- guard selectedRebuildRange.isComplete else {- return RebuildStatus(message: String(localized: "date-picker.select-end"), isError: false)- }- if selectedRebuildDateKeys.isEmpty {- return RebuildStatus(- message: String(localized: "workflow.rebuild.error.source-unavailable"),- isError: true- )- }- return RebuildStatus(- message: String(localized: "workflow.rebuild.selection.day-count", defaultValue: "\(selectedRebuildRange.dayCount, specifier: "%lld")"),- isError: false- )+ .frame(height: RebuildLayoutMetrics.controlHeight)}var selectedRebuildDateKeys: [String] {@@ -811,14 +794,14 @@ private extension AppSettingsView {}isRebuildingWorkflowData = true- clearRebuildStatus()+ rebuildResult = nilonRebuildWorkflowData(dateKeys) { result inisRebuildingWorkflowData = falserefreshRebuildableDates()switch result {case let .success(summary):- rebuildStatus = RebuildStatus(+ rebuildResult = RebuildResult(message: Self.rebuildSuccessMessage(for: summary,autoRetryAvailable: codexHookSettings.isEnabled@@ -828,12 +811,12 @@ private extension AppSettingsView {case let .failure(error):// 请求被后续请求顶替时工作本身并没有失败, 不该报错guard !(error is CancellationError) else {- clearRebuildStatus()+ rebuildResult = nilreturn}- rebuildStatus = RebuildStatus(- message: String(localized: "workflow.rebuild.status.failed", defaultValue: "\(error.localizedDescription)"),+ rebuildResult = RebuildResult(+ message: error.localizedDescription,isError: true)}@@ -842,7 +825,7 @@ private extension AppSettingsView {static let rebuildFailedDateListLimit = 3- /// 未完成的日期只列前几个, 避免长范围重建时提示挤满整行+ /// 未完成的日期只列前几个, 避免长范围重建时结果过长/// autoRetryAvailable: 常规维护只在 Hook 开启时运行, 关闭时不能承诺自动重试static func rebuildSuccessMessage(for summary: WorkflowDataRebuildSummary,@@ -881,10 +864,6 @@ private extension AppSettingsView {return message}- func clearRebuildStatus() {- rebuildStatus = nil- }-// MARK: - 通知/// 主开关行保留在设置窗口内, 子选项在右侧子面板中展开@@ -1360,9 +1339,13 @@ private struct RebuildDatePicker: View {}}-private struct RebuildStatus {+private struct RebuildResult {let message: Stringlet isError: Bool++ var title: LocalizedStringResource {+ isError ? "workflow.rebuild.result.failed" : "workflow.rebuild.result.completed"+ }}private struct SettingsStatusCaption: Equatable {diff --git a/CodexBarHelper/app.zabrian.codexbar.debug.helper.plist b/CodexBarHelper/app.zabrian.codexbar.helper.debug.plistsimilarity index 85%rename from CodexBarHelper/app.zabrian.codexbar.debug.helper.plistrename to CodexBarHelper/app.zabrian.codexbar.helper.debug.plistindex fd19b4d..e509b3d 100644--- a/CodexBarHelper/app.zabrian.codexbar.debug.helper.plist+++ b/CodexBarHelper/app.zabrian.codexbar.helper.debug.plist@@ -11,10 +11,10 @@<key>KeepAlive</key><true/><key>Label</key>- <string>app.zabrian.codexbar.debug.helper</string>+ <string>app.zabrian.codexbar.helper.debug</string><key>MachServices</key><dict>- <key>app.zabrian.codexbar.debug.helper</key>+ <key>app.zabrian.codexbar.helper.debug</key><true/></dict><key>ProcessType</key>diff --git a/CodexBarHelper/main.swift b/CodexBarHelper/main.swiftindex dfe81b3..b6db361 100644--- a/CodexBarHelper/main.swift+++ b/CodexBarHelper/main.swift@@ -1377,18 +1377,17 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @uncthrow CodexBarHelperError.codeSigningValidationFailed("Helper 标识符缺失")}- let helperSuffix = CodexBarHelperIPC.helperBundleIdentifierSuffix- guard helperIdentifier.hasSuffix(helperSuffix) else {+ guard helperIdentifier == CodexBarHelperIPC.machServiceName else {let details = LogFields.joined("actual=\(helperIdentifier)",- "expected=*\(helperSuffix)"+ "expected=\(CodexBarHelperIPC.machServiceName)")throw CodexBarHelperError.codeSigningValidationFailed("Helper 标识符错误: \(details)")}- let clientIdentifier = String(helperIdentifier.dropLast(helperSuffix.count))+ let clientIdentifier = CodexBarHelperIPC.appBundleIdentifierlet identifierCharacters = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: ".-"))diff --git a/Docs/DeveloperGuide/development.md b/Docs/DeveloperGuide/development.mdindex f94d94d..27addb7 100644--- a/Docs/DeveloperGuide/development.md+++ b/Docs/DeveloperGuide/development.md@@ -104,7 +104,7 @@ CPU、内存、唤醒、磁盘活动与采集环境见[性能报告](https://cod| 配置 | App bundle ID | Helper bundle ID || --- | --- | --- |-| Debug | `app.zabrian.codexbar.debug` | `app.zabrian.codexbar.debug.helper` |+| Debug | `app.zabrian.codexbar.debug` | `app.zabrian.codexbar.helper.debug` || Release | `app.zabrian.codexbar` | `app.zabrian.codexbar.helper` |App 偏好和系统授权按身份隔离,Hook 数据与异常会话保护文件共享。排查时确认正在运行的 App、helper 和已安装 Hook 的可执行路径。diff --git a/Docs/DeveloperGuide/sleep-prevention.md b/Docs/DeveloperGuide/sleep-prevention.mdindex 130da9d..8cde972 100644--- a/Docs/DeveloperGuide/sleep-prevention.md+++ b/Docs/DeveloperGuide/sleep-prevention.md@@ -199,7 +199,7 @@ CodexBarHelper 通过 `SMAppService` 注册为 LaunchDaemon。App 和 CodexBarHe- 不进行网络访问- 不负责判断 Codex 任务状态-CodexBarHelper 从自身签名派生客户端 code-signing requirement,并应用到 XPC listener。未通过签名要求的客户端不能建立控制连接。+CodexBarHelper 使用自身签名中的 Team ID 和当前构建配置对应的 App 标识生成客户端 code-signing requirement,并应用到 XPC listener。## 系统状态所有权diff --git a/Docs/UserGuide/sync-data-privacy.md b/Docs/UserGuide/sync-data-privacy.mdindex c64b773..fc85a16 100644--- a/Docs/UserGuide/sync-data-privacy.md+++ b/Docs/UserGuide/sync-data-privacy.md@@ -60,7 +60,7 @@ App 在历史统计刷新时自动读取本机 Codex 的 rollout,逐步补全重建使用保留的本机 Hook 事件和 rollout,重新计算所选日期的活动统计与 Token 用量。Token 按根轮次开始日期归属,同一轮及其子线程不会重复累计。日期没有 Hook 事件时,也可以重建本机 rollout 中的 Token 数据。-重建在后台运行,可以继续使用主面板或关闭设置窗口。Token 按批读取,扫描完整成功后一次更新;取消或读取失败不会发布部分结果。退出 App 会停止本次重建,未完成的 Token 重建需要重新发起。完成后显示处理日期、活动记录和 Token 轮次数量。+重建在后台运行,可以继续使用主面板或关闭设置窗口。Token 按批读取,扫描完整成功后一次更新;取消或读取失败不会发布部分结果。退出 App 会停止本次重建,未完成的 Token 重建需要重新发起。完成后通过弹窗显示处理天数、Hook 事件数和 Token 轮次数。开启同步时,重建结果会替换当前设备对应日期的活动统计,以及本机重新读到的 Token 轮次记录;其他轮次保留。重建可以降低 Token 计数;重新读到轮次但没有用量记录时,会清除该轮旧计数并同步到云端。本机已经缺失 rollout 的轮次保留已有统计,不会因此删除云端记录。账户信息、额度和 app-server 的账户用量不受影响。diff --git a/Docs/en/DeveloperGuide/development.md b/Docs/en/DeveloperGuide/development.mdindex 30670e2..801108b 100644--- a/Docs/en/DeveloperGuide/development.md+++ b/Docs/en/DeveloperGuide/development.md@@ -104,7 +104,7 @@ For collection, report generation, and baseline comparisons, see the [performanc| Configuration | App bundle ID | Helper bundle ID || --- | --- | --- |-| Debug | `app.zabrian.codexbar.debug` | `app.zabrian.codexbar.debug.helper` |+| Debug | `app.zabrian.codexbar.debug` | `app.zabrian.codexbar.helper.debug` || Release | `app.zabrian.codexbar` | `app.zabrian.codexbar.helper` |Preferences and system approval are isolated by identity; Hook data and Activity Protection files are shared. Identify the running app, helper, and installed Hook executable path when debugging.diff --git a/Docs/en/DeveloperGuide/sleep-prevention.md b/Docs/en/DeveloperGuide/sleep-prevention.mdindex 69e1faa..dc7c7dd 100644--- a/Docs/en/DeveloperGuide/sleep-prevention.md+++ b/Docs/en/DeveloperGuide/sleep-prevention.md@@ -199,7 +199,7 @@ Each app process creates a stable `clientSessionID` that survives XPC reconnecti- It performs no network access- It does not determine Codex task state-CodexBarHelper derives the client code-signing requirement from its own signature and applies it to the XPC listener. A client that fails the signing requirement cannot establish a control connection.+CodexBarHelper builds the client code-signing requirement from the Team ID in its own signature and the app identifier for the current build configuration, then applies it to the XPC listener.## System-State Ownershipdiff --git a/Docs/en/UserGuide/sync-data-privacy.md b/Docs/en/UserGuide/sync-data-privacy.mdindex 64f05e8..41374df 100644--- a/Docs/en/UserGuide/sync-data-privacy.md+++ b/Docs/en/UserGuide/sync-data-privacy.md@@ -60,7 +60,7 @@ If statistics look incorrect, choose a date range in `Settings > Advanced > RebuRebuilding recalculates activity statistics and token usage for the selected dates from local Hook events and rollouts. Tokens belong to the root turn's start date; each thread and turn contributes once. Dates without Hook events can still rebuild token usage from local rollouts.-The work runs in the background. You can keep using the main panel or close Settings. Token files are read in batches and committed only after the complete scan succeeds; cancellation and read errors do not publish partial results. Quitting the app stops the operation, and an unfinished token rebuild must be started again. The result reports days, activity events, and token turns processed.+The work runs in the background. You can keep using the main panel or close Settings. Token files are read in batches and committed only after the complete scan succeeds; cancellation and read errors do not publish partial results. Quitting the app stops the operation, and an unfinished token rebuild must be started again. The result dialog reports the number of days, Hook events, and token turns processed.With sync enabled, rebuilding replaces this device's activity statistics and the token turns reread locally, preserving other turns. Rebuilding can lower token counts. If a turn is reread without usage records, its previous counts are cleared and that correction syncs to iCloud. Turns whose local rollouts are missing retain known statistics; missing files do not delete cloud records. Account details, quota, and app-server account usage are unaffected.diff --git a/Scripts/cleanup.swift b/Scripts/cleanup.swiftindex 3e5fbc0..d2c0360 100755--- a/Scripts/cleanup.swift+++ b/Scripts/cleanup.swift@@ -62,7 +62,12 @@ private struct CleanupTarget {}var serviceLabel: String {- bundleIdentifier + ".helper"+ switch buildConfiguration {+ case .release:+ "app.zabrian.codexbar.helper"+ case .debug:+ "app.zabrian.codexbar.helper.debug"+ }}}diff --git a/Shared/CodexBarHelperXPC.swift b/Shared/CodexBarHelperXPC.swiftindex 909c3ad..16aca52 100644--- a/Shared/CodexBarHelperXPC.swift+++ b/Shared/CodexBarHelperXPC.swift@@ -1,10 +1,13 @@import Foundationnonisolated enum CodexBarHelperIPC {- static let helperBundleIdentifierSuffix = ".helper"- static let machServiceName = bundleIdentifier.hasSuffix(helperBundleIdentifierSuffix)- ? bundleIdentifier- : bundleIdentifier + helperBundleIdentifierSuffix+ #if DEBUG+ static let appBundleIdentifier = "app.zabrian.codexbar.debug"+ static let machServiceName = "app.zabrian.codexbar.helper.debug"+ #else+ static let appBundleIdentifier = "app.zabrian.codexbar"+ static let machServiceName = "app.zabrian.codexbar.helper"+ #endifstatic let daemonPlistName = machServiceName + ".plist"static let watchdogGraceSeconds: TimeInterval = 15static let externalCheckIntervalSeconds: TimeInterval = 5@@ -14,13 +17,6 @@ nonisolated enum CodexBarHelperIPC {/// App 侧等回复的上限, 与 watchdog 宽限是一对: 必须更小, 这样 App 先放手 helper 再自行兜底/// helper 冷启动加一次 pmset 通常一秒内完成, 留这么宽只为排除偶发的调度抖动static let requestTimeoutSeconds: TimeInterval = 10-- private static let bundleIdentifier: String = {- guard let identifier = Bundle.main.bundleIdentifier, !identifier.isEmpty else {- preconditionFailure("CodexBar bundle identifier 缺失")- }- return identifier- }()}nonisolated enum CodexBarSleepPreventionSource: Int, Sendable {