CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
feat: 支持主任务卡片轮播与会话固定
Bob7bcd334be304
diff --git a/.gitignore b/.gitignoreindex f33d444..b3db115 100644--- a/.gitignore+++ b/.gitignore@@ -38,6 +38,9 @@ codesign2# Logs*.log+# Lock files+*.lock+# Performance reports/Performance/diff --git a/AGENTS.md b/AGENTS.mdindex 8f843fb..971d937 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -61,7 +61,9 @@ CodexBar 是面向 macOS 的 `LSUIElement` 菜单栏应用,使用 Swift 6, Swi## 构建、测试与开发命令- `xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build` 执行代码变更后的构建验证-- `env -u CC -u CXX xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'platform=macOS' -testPlan Standard test` 执行日常无宿主单元测试+- `env -u CC -u CXX xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'platform=macOS' -testPlan Unit test` 执行日常快速单元测试,也是 scheme 的默认测试计划+- `env -u CC -u CXX xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'platform=macOS' -testPlan Integration test` 执行协议、存储、进程及跨模块生命周期集成测试+- `env -u CC -u CXX xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'platform=macOS' -testPlan Standard test` 执行全部单元测试和集成测试- `env -u CC -u CXX xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'platform=macOS' -testPlan Sanitizers test` 分别运行 TSan 和 ASan 诊断;使用 `-only-test-configuration ThreadSanitizer` 或 `-only-test-configuration AddressSanitizer` 可单独运行对应配置- `swiftformat .` 按 `.swiftformat` 格式化全部 Swift,使用 Swift 6 和 4 空格缩进- `swiftlint` 按 `.swiftlint.yml` 检查@@ -150,8 +152,10 @@ CodexBar 是面向 macOS 的 `LSUIElement` 菜单栏应用,使用 Swift 6, Swi- 测试围绕可观察行为、关键边界和失败恢复设计,优先复用现有测试;新增测试应能发现实际回归,避免只重复实现或为简单改名机械补测- 单元测试使用独立临时数据和可控依赖,测试结束后清理资源;不得读写真实用户数据、调用真实外部服务、启动特权服务或修改系统设置+- 单元测试不得显示窗口、面板或 popover,也不得激活 App 或抢占焦点,透明窗口和屏幕外窗口同样不允许显示;布局使用离屏宿主验证,依赖真实窗口显示的交互另行手动验证- 代码改动需完成受影响目标的构建、相关自动化测试及项目配置的格式和静态检查;涉及共享逻辑、构建配置或跨模块行为时,扩大验证范围;纯文档改动检查内容和格式即可-- 日常代码改动默认运行 `Standard` 测试计划,按影响范围选择相关测试+- 日常代码改动默认运行 `Unit` 测试计划,并按影响范围补充相关 `Integration` 用例;涉及共享逻辑、构建配置或交付前运行完整 `Standard` 计划+- 集成测试通过 `.tags(.integration)` 标记,按测试的主要依赖和职责归类,混合测试套件可以只标记对应函数;`Unit` 排除该标签,`Integration` 仅包含该标签,`Standard` 和 `Sanitizers` 均保留完整覆盖- 修改共享可变状态、锁或跨线程访问时,追加运行 `Sanitizers` 中的 `ThreadSanitizer` 配置;修改 SQLite、Darwin、C 接口或指针相关的内存访问与资源生命周期时,追加运行 `AddressSanitizer` 配置;同时涉及两类风险时,分别运行两种配置- 测试完成后同时检查失败用例和运行期警告,定位并处理新增的 Sanitizer、Main Thread Checker 和 Thread Performance Checker 报告- 自动化测试无法覆盖的交互、系统集成和生命周期行为,补充手动验证;验证前确认运行产物、构建配置和测试环境,避免混用不同版本@@ -165,6 +169,7 @@ CodexBar 是面向 macOS 的 `LSUIElement` 菜单栏应用,使用 Swift 6, Swi- 标题概括本次提交最主要的问题或目标,不用次要交互细节或局部实现代替核心目的- body 围绕核心目的解释必要的原因、关键行为变化和影响;实现细节仅在有助于理解目的或评估影响时保留+- 只保留代码最终的行为以及状态,不要把代码变化的中间的状态作为变更记录- 不把文件清单、函数改动清单或开发过程直接作为提交说明,也不为覆盖每一处 diff 而堆砌条目提交标题使用 `<type>: <中文描述>` 格式:diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex 4371b45..fbd4d9e 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -66,8 +66,11 @@/* Begin PBXFileReference section */A82000000000000000000001 /* Standard.xctestplan */ = {isa = PBXFileReference; lastKnownFileType = text; path = Standard.xctestplan; sourceTree = "<group>"; };A82000000000000000000002 /* Sanitizers.xctestplan */ = {isa = PBXFileReference; lastKnownFileType = text; path = Sanitizers.xctestplan; sourceTree = "<group>"; };+ A82000000000000000000003 /* Unit.xctestplan */ = {isa = PBXFileReference; lastKnownFileType = text; path = Unit.xctestplan; sourceTree = "<group>"; };+ A82000000000000000000004 /* Integration.xctestplan */ = {isa = PBXFileReference; lastKnownFileType = text; path = Integration.xctestplan; sourceTree = "<group>"; };B10000000000000000000014 /* CodexBarPowerHelper */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = CodexBarPowerHelper; sourceTree = BUILT_PRODUCTS_DIR; };C449FB5030203E0000ED2123 /* Version.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Version.xcconfig; sourceTree = "<group>"; };+ C449FB5030203E0000ED2124 /* BuildNumber.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = BuildNumber.xcconfig; sourceTree = "<group>"; };C4A0FD952FD9302E000263A7 /* CodexBar Debug.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "CodexBar Debug.app"; sourceTree = BUILT_PRODUCTS_DIR; };D10000000000000000000002 /* CodexBarTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CodexBarTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };E10000000000000000000002 /* CodexBarPowerHelperTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CodexBarPowerHelperTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };@@ -252,6 +255,9 @@isa = PBXGroup;children = (C449FB5030203E0000ED2123 /* Version.xcconfig */,+ C449FB5030203E0000ED2124 /* BuildNumber.xcconfig */,+ A82000000000000000000003 /* Unit.xctestplan */,+ A82000000000000000000004 /* Integration.xctestplan */,A82000000000000000000001 /* Standard.xctestplan */,A82000000000000000000002 /* Sanitizers.xctestplan */,);@@ -503,6 +509,180 @@/* End PBXTargetDependency section *//* Begin XCBuildConfiguration section */+ A82900000000000000000001 /* DebugTest configuration for PBXNativeTarget "CodexBarPowerHelper" */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";+ CODE_SIGN_STYLE = Automatic;+ CREATE_INFOPLIST_SECTION_IN_BINARY = YES;+ ENABLE_APP_SANDBOX = NO;+ ENABLE_HARDENED_RUNTIME = YES;+ GENERATE_INFOPLIST_FILE = YES;+ PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.helper.power.debug;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SKIP_INSTALL = YES;+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;+ };+ name = DebugTest;+ };+ A82900000000000000000002 /* DebugTest configuration for PBXProject "CodexBar" */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = C449FB5030203E0000ED2123 /* Version.xcconfig */;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_ENABLE_OBJC_WEAK = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ CODEXBAR_AUTO_INCREMENT_BUILD_NUMBER = NO;+ CODEXBAR_POWER_HELPER_MANAGER_WRAPPER_NAME = "CodexBar Power Helper Debug.app";+ COMPILATION_CACHE_ENABLE_CACHING = YES;+ COPY_PHASE_STRIP = NO;+ DEAD_CODE_STRIPPING = YES;+ DEBUG_INFORMATION_FORMAT = dwarf;+ DEVELOPMENT_TEAM = 4KJ362VJW5;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_TESTABILITY = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = YES;+ GCC_C_LANGUAGE_STANDARD = gnu17;+ GCC_DYNAMIC_NO_PIC = NO;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_OPTIMIZATION_LEVEL = 0;+ GCC_PREPROCESSOR_DEFINITIONS = (+ "DEBUG=1",+ "$(inherited)",+ );+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;+ MACOSX_DEPLOYMENT_TARGET = 15.0;+ MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;+ MTL_FAST_MATH = YES;+ ONLY_ACTIVE_ARCH = YES;+ SDKROOT = macosx;+ STRING_CATALOG_GENERATE_SYMBOLS = YES;+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";+ SWIFT_VERSION = 6.0;+ };+ name = DebugTest;+ };+ A82900000000000000000003 /* DebugTest configuration for PBXNativeTarget "CodexBar" */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_ENTITLEMENTS = CodexBar/Resources/CodexBar.entitlements;+ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";+ CODE_SIGN_STYLE = Automatic;+ COMBINE_HIDPI_IMAGES = YES;+ ENABLE_APP_SANDBOX = NO;+ ENABLE_HARDENED_RUNTIME = YES;+ ENABLE_PREVIEWS = YES;+ ENABLE_USER_SELECTED_FILES = NO;+ EXCLUDED_SOURCE_FILE_NAMES = CodexBarPowerHelper.plist;+ GENERATE_INFOPLIST_FILE = NO;+ INFOPLIST_FILE = CodexBar/Resources/Info.plist;+ INFOPLIST_KEY_CFBundleDisplayName = "CodexBar Debug";+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/../Frameworks",+ );+ PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.debug;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_APPROACHABLE_CONCURRENCY = YES;+ SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;+ SWIFT_EMIT_LOC_STRINGS = YES;+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;+ WRAPPER_NAME = "CodexBar Debug.app";+ };+ name = DebugTest;+ };+ A82900000000000000000004 /* DebugTest configuration for PBXNativeTarget "CodexBarTests" */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ CODE_SIGN_STYLE = Automatic;+ ENABLE_APP_SANDBOX = NO;+ GENERATE_INFOPLIST_FILE = YES;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@loader_path/../Frameworks",+ "@executable_path/../Frameworks",+ );+ PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.tests;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SKIP_INSTALL = YES;+ SWIFT_APPROACHABLE_CONCURRENCY = YES;+ SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;+ SWIFT_EMIT_LOC_STRINGS = NO;+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;+ };+ name = DebugTest;+ };+ A82900000000000000000005 /* DebugTest configuration for PBXNativeTarget "CodexBarPowerHelperTests" */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ CODE_SIGN_STYLE = Automatic;+ ENABLE_APP_SANDBOX = NO;+ GENERATE_INFOPLIST_FILE = YES;+ PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.helper.power.tests;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SKIP_INSTALL = YES;+ SWIFT_EMIT_LOC_STRINGS = NO;+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;+ };+ name = DebugTest;+ };+ A82900000000000000000006 /* DebugTest configuration for PBXNativeTarget "CodexBarPowerHelperManager" */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ CODE_SIGN_IDENTITY = "Apple Development";+ CODE_SIGN_STYLE = Automatic;+ ENABLE_APP_SANDBOX = NO;+ ENABLE_HARDENED_RUNTIME = YES;+ EXCLUDED_SOURCE_FILE_NAMES = CodexBarPowerHelper.plist;+ GENERATE_INFOPLIST_FILE = YES;+ INFOPLIST_KEY_CFBundleDisplayName = "CodexBar Power Helper Debug";+ INFOPLIST_KEY_LSUIElement = YES;+ PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.helper.power.manager.debug;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SKIP_INSTALL = YES;+ SWIFT_EMIT_LOC_STRINGS = NO;+ WRAPPER_NAME = "$(CODEXBAR_POWER_HELPER_MANAGER_WRAPPER_NAME)";+ };+ name = DebugTest;+ };B10000000000000000000033 /* Debug configuration for PBXNativeTarget "CodexBarPowerHelper" */ = {isa = XCBuildConfiguration;buildSettings = {@@ -849,6 +1029,7 @@isa = XCConfigurationList;buildConfigurations = (B10000000000000000000033 /* Debug configuration for PBXNativeTarget "CodexBarPowerHelper" */,+ A82900000000000000000001 /* DebugTest configuration for PBXNativeTarget "CodexBarPowerHelper" */,B10000000000000000000034 /* Release configuration for PBXNativeTarget "CodexBarPowerHelper" */,);defaultConfigurationName = Release;@@ -857,6 +1038,7 @@isa = XCConfigurationList;buildConfigurations = (C4A0FD9E2FD9302E000263A7 /* Debug configuration for PBXProject "CodexBar" */,+ A82900000000000000000002 /* DebugTest configuration for PBXProject "CodexBar" */,C4A0FD9F2FD9302E000263A7 /* Release configuration for PBXProject "CodexBar" */,);defaultConfigurationName = Release;@@ -865,6 +1047,7 @@isa = XCConfigurationList;buildConfigurations = (C4A0FDA12FD9302E000263A7 /* Debug configuration for PBXNativeTarget "CodexBar" */,+ A82900000000000000000003 /* DebugTest configuration for PBXNativeTarget "CodexBar" */,C4A0FDA22FD9302E000263A7 /* Release configuration for PBXNativeTarget "CodexBar" */,);defaultConfigurationName = Release;@@ -873,6 +1056,7 @@isa = XCConfigurationList;buildConfigurations = (D10000000000000000000012 /* Debug configuration for PBXNativeTarget "CodexBarTests" */,+ A82900000000000000000004 /* DebugTest configuration for PBXNativeTarget "CodexBarTests" */,D10000000000000000000013 /* Release configuration for PBXNativeTarget "CodexBarTests" */,);defaultConfigurationName = Release;@@ -881,6 +1065,7 @@isa = XCConfigurationList;buildConfigurations = (E10000000000000000000012 /* Debug configuration for PBXNativeTarget "CodexBarPowerHelperTests" */,+ A82900000000000000000005 /* DebugTest configuration for PBXNativeTarget "CodexBarPowerHelperTests" */,E10000000000000000000013 /* Release configuration for PBXNativeTarget "CodexBarPowerHelperTests" */,);defaultConfigurationName = Release;@@ -889,6 +1074,7 @@isa = XCConfigurationList;buildConfigurations = (F10000000000000000000012 /* Debug configuration for PBXNativeTarget "CodexBarPowerHelperManager" */,+ A82900000000000000000006 /* DebugTest configuration for PBXNativeTarget "CodexBarPowerHelperManager" */,F10000000000000000000013 /* Release configuration for PBXNativeTarget "CodexBarPowerHelperManager" */,);defaultConfigurationName = Release;diff --git a/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme b/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcschemeindex 6d08d84..7259bfe 100644--- a/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme+++ b/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme@@ -6,6 +6,24 @@parallelizeBuildables = "YES"buildImplicitDependencies = "YES"buildArchitectures = "Automatic">+ <PreActions>+ <ExecutionAction+ ActionType = "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction">+ <ActionContent+ title = "Increment Build Number"+ scriptText = '/usr/bin/perl "${PROJECT_DIR}/Scripts/build-number.pl" "${PROJECT_DIR}/Config/BuildNumber.xcconfig"'>+ <EnvironmentBuildable>+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "C4A0FD942FD9302E000263A7"+ BuildableName = "CodexBar.app"+ BlueprintName = "CodexBar"+ ReferencedContainer = "container:CodexBar.xcodeproj">+ </BuildableReference>+ </EnvironmentBuildable>+ </ActionContent>+ </ExecutionAction>+ </PreActions><BuildActionEntries><BuildActionEntrybuildForTesting = "NO"@@ -24,15 +42,21 @@</BuildActionEntries></BuildAction><TestAction- buildConfiguration = "Debug"+ buildConfiguration = "DebugTest"selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"shouldUseLaunchSchemeArgsEnv = "YES"><TestPlans><TestPlanReference- reference = "container:Config/Standard.xctestplan"+ reference = "container:Config/Unit.xctestplan"default = "YES"></TestPlanReference>+ <TestPlanReference+ reference = "container:Config/Integration.xctestplan">+ </TestPlanReference>+ <TestPlanReference+ reference = "container:Config/Standard.xctestplan">+ </TestPlanReference><TestPlanReferencereference = "container:Config/Sanitizers.xctestplan"></TestPlanReference>diff --git a/CodexBar/App/CodexBarApp.swift b/CodexBar/App/CodexBarApp.swiftindex 2ef8afd..d064d6b 100644--- a/CodexBar/App/CodexBarApp.swift+++ b/CodexBar/App/CodexBarApp.swift@@ -30,9 +30,11 @@ nonisolated extension Bundle {object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String}- /// `v1.2.3` 形式的版本文案; 缺失时回退 `--`+ /// 版本文案包含构建号; 版本缺失时回退 `--`var displayVersionLabel: String {guard let version = shortVersionString else { return "--" }- return "v\(version)"+ let label = "v\(version)"+ guard let build = object(forInfoDictionaryKey: "CFBundleVersion") as? String, !build.isEmpty else { return label }+ return "\(label) (Build \(build))"}}diff --git a/CodexBar/Controllers/ActivityCardPresentationState.swift b/CodexBar/Controllers/ActivityCardPresentationState.swiftnew file mode 100644index 0000000..5fc7632--- /dev/null+++ b/CodexBar/Controllers/ActivityCardPresentationState.swift@@ -0,0 +1,83 @@+import Combine+import Foundation++/// 生命周期由菜单控制器持有, 两种面板宿主共享同一份内存选择+@MainActor+final class ActivityCardPresentationState: ObservableObject {+ @Published private(set) var selection = ActivityCardSelection()+ private var subscription: AnyCancellable?+ private var returnTask: Task<Void, Never>?+ private var scheduledDeadline: Date?+ private var gestureOwner: UUID?++ init(activityMonitor: ActivityMonitor) {+ selection.update(snapshot: activityMonitor.snapshot, isHealthy: activityMonitor.isActivitySourceHealthy, now: Date())+ // 发布事务结束后再读取健康状态, 避免恢复时把旧的空快照当作完整结果+ subscription = activityMonitor.presentationPublisher+ .sink { [weak self, weak activityMonitor] update in+ guard let activityMonitor else { return }+ self?.change { $0.update(snapshot: update.snapshot, isHealthy: activityMonitor.isActivitySourceHealthy, now: Date()) }+ }+ }++ deinit {+ returnTask?.cancel()+ }++ func setVisible(_ visible: Bool) {+ if !visible {+ gestureOwner = nil+ }+ change { $0.setVisible(visible, now: Date()) }+ }++ func swipe(_ step: Int) {+ change { $0.swipe(step, now: Date()) }+ }++ func selectAfterSwipe(_ id: String, owner: UUID) {+ guard gestureOwner == owner else { return }+ change { $0.selectAfterSwipe(id, now: Date()) }+ }++ func togglePin() {+ change { $0.togglePin(now: Date()) }+ }++ func setGestureActive(_ active: Bool, owner: UUID) {+ if active {+ guard selection.isVisible else { return }+ gestureOwner = owner+ } else {+ // 关闭的宿主可能晚于新宿主完成清理, 只能释放自己持有的手势+ guard gestureOwner == owner else { return }+ gestureOwner = nil+ }+ change { $0.setGestureActive(active, now: Date()) }+ }++ private func change(_ operation: (inout ActivityCardSelection) -> Void) {+ var updated = selection+ operation(&updated)+ if updated != selection {+ selection = updated+ }+ scheduleReturn()+ }++ private func scheduleReturn() {+ let deadline = selection.returnDeadline+ guard deadline != scheduledDeadline else { return }+ returnTask?.cancel()+ returnTask = nil+ scheduledDeadline = deadline+ guard let deadline else { return }+ returnTask = Task { @MainActor [weak self] in+ try? await Task.sleep(for: .seconds(max(0, deadline.timeIntervalSinceNow)))+ guard let self, !Task.isCancelled else { return }+ scheduledDeadline = nil+ returnTask = nil+ change { $0.reconcile(at: Date()) }+ }+ }+}diff --git a/CodexBar/Controllers/ActivityPanelController.swift b/CodexBar/Controllers/ActivityPanelController.swiftindex d611606..78d6323 100644--- a/CodexBar/Controllers/ActivityPanelController.swift+++ b/CodexBar/Controllers/ActivityPanelController.swift@@ -13,10 +13,10 @@ final class ActivityPanelController {sizingOptions: [],cornerRadius: ActivityCenterView.panelCornerRadius)- private var currentContext: ActivityCenterPanelContext?+ private var currentAnchor: ActivityCenterPanelAnchor?private weak var menuSurfaceWindow: NSWindow?- private weak var menuContentView: NSView?private var cancellables = Set<AnyCancellable>()+ private var layoutSubscriptions = Set<AnyCancellable>()private var presentationTask: Task<Void, Never>?private var panelUpdateTask: Task<Void, Never>?private lazy var presenter = SidePanelDrawerPresenter(@@ -36,12 +36,17 @@ final class ActivityPanelController {self.mainPanelSettings = mainPanelSettingsactivityMonitor.$snapshot+ .map { snapshot -> CGSize? in+ guard snapshot.hasTaskCenterContent else { return nil }+ return ActivityCenterView.panelSize(maximumHeight: .greatestFiniteMagnitude, snapshot: snapshot)+ }+ .removeDuplicates().dropFirst()- .sink { [weak self] snapshot in+ .sink { [weak self] size inguard let self, presentationState.isPresented else {return}- schedulePanelUpdate(hasContent: snapshot.hasTaskCenterContent)+ schedulePanelUpdate(hasContent: size != nil)}.store(in: &cancellables)}@@ -55,7 +60,7 @@ final class ActivityPanelController {}func toggle(- context: ActivityCenterPanelContext,+ anchor: ActivityCenterPanelAnchor,relativeTo menuSurfaceWindow: NSWindow?,contentView: NSView?) {@@ -65,7 +70,7 @@ final class ActivityPanelController {}schedulePresentation(- context: context,+ anchor: anchor,relativeTo: menuSurfaceWindow,contentView: contentView)@@ -73,6 +78,9 @@ final class ActivityPanelController {func hide(immediate: Bool = false) {cancelScheduledPresentation()+ layoutSubscriptions.removeAll()+ currentAnchor = nil+ menuSurfaceWindow = nil// 热力图 hover 等高频路径会反复调用 hide, 已隐藏时跳过 @Published 写入以免整个菜单重算if presentationState.isPresented || presenter.isVisible {cancelScheduledPanelUpdate()@@ -84,7 +92,7 @@ final class ActivityPanelController {}private func schedulePresentation(- context: ActivityCenterPanelContext,+ anchor: ActivityCenterPanelAnchor,relativeTo menuSurfaceWindow: NSWindow?,contentView: NSView?) {@@ -95,10 +103,7 @@ final class ActivityPanelController {contentView?.layoutSubtreeIfNeeded()if let menuSurfaceWindow,- context.anchorProvider.currentScreenFrame(- in: menuSurfaceWindow,- allowingCachedFrame: false- ) == nil {+ anchor.screenFrame(in: menuSurfaceWindow) == nil {await Task.yield()}@@ -107,7 +112,7 @@ final class ActivityPanelController {}presentationTask = nilshow(- context: context,+ anchor: anchor,relativeTo: menuSurfaceWindow,contentView: contentView)@@ -120,7 +125,7 @@ final class ActivityPanelController {}private func show(- context: ActivityCenterPanelContext,+ anchor: ActivityCenterPanelAnchor,relativeTo menuSurfaceWindow: NSWindow?,contentView: NSView?) {@@ -133,16 +138,17 @@ final class ActivityPanelController {let panel = contentHost.ensurePanel()cancelScheduledPanelUpdate()- currentContext = context+ currentAnchor = anchorself.menuSurfaceWindow = menuSurfaceWindow- menuContentView = contentView- let layout = panelLayout(- context: context,+ contentView?.layoutSubtreeIfNeeded()+ guard let layout = panelLayout(+ anchor: anchor,menuSurfaceWindow: menuSurfaceWindow,- contentView: contentView,- snapshot: snapshot,- allowsCachedAnchor: false- )+ snapshot: snapshot+ ) else {+ hide(immediate: true)+ return+ }updateContent(panelSize: layout.size)panel.level = menuSurfaceWindow.level@@ -151,32 +157,24 @@ final class ActivityPanelController {SidePanelSupport.restoreMenuSurfaceKeyWindow(menuSurfaceWindow)}presenter.present(panel, at: layout.position, relativeTo: menuSurfaceWindow)+ observeLayout(anchor: anchor, window: menuSurfaceWindow)}private func panelLayout(- context: ActivityCenterPanelContext,+ anchor: ActivityCenterPanelAnchor,menuSurfaceWindow: NSWindow,- contentView: NSView?,- snapshot: ActivitySnapshot,- allowsCachedAnchor: Bool = true- ) -> (size: CGSize, position: SidePanelPosition) {- let menuSurfaceFrame = SidePanelSupport.contentScreenFrame(- for: contentView,- in: menuSurfaceWindow- ) ?? menuSurfaceWindow.frame+ snapshot: ActivitySnapshot+ ) -> (size: CGSize, position: SidePanelPosition)? {+ let menuSurfaceFrame = menuSurfaceWindow.contentRect(forFrameRect: menuSurfaceWindow.frame)let screen = menuSurfaceWindow.screen ?? NSScreen.mainlet visibleFrame = screen?.visibleFrame ?? menuSurfaceFrame- let alignmentScreenFrame = SidePanelSupport.validatedAlignmentScreenFrame(- context.anchorProvider.currentScreenFrame(- in: menuSurfaceWindow,- allowingCachedFrame: allowsCachedAnchor- ),+ guard let alignmentScreenFrame = SidePanelSupport.validatedAlignmentScreenFrame(+ anchor.screenFrame(in: menuSurfaceWindow),menuSurfaceFrame: menuSurfaceFrame- )+ ) else { return nil }let screenMaximumHeight = visibleFrame.height - SidePanelSupport.Metrics.screenPadding * 2- let menuMaximumHeight = alignmentScreenFrame.map {- $0.maxY - menuSurfaceFrame.minY- } ?? screenMaximumHeight+ let menuMaximumHeight = alignmentScreenFrame.maxY - menuSurfaceFrame.minY+ guard min(screenMaximumHeight, menuMaximumHeight) > 0 else { return nil }let panelSize = ActivityCenterView.panelSize(maximumHeight: min(screenMaximumHeight, menuMaximumHeight),snapshot: snapshot@@ -187,7 +185,7 @@ final class ActivityPanelController {visibleFrame: visibleFrame,screenFrame: screen?.frame,alignmentScreenFrame: alignmentScreenFrame,- preferredSide: context.preferredSide+ preferredSide: .right)return (panelSize, position)@@ -196,27 +194,44 @@ final class ActivityPanelController {private func updateVisibleLayout(for snapshot: ActivitySnapshot) {guard let panel = contentHost.panel,panel.isVisible,- let currentContext,+ let currentAnchor,let menuSurfaceWindow else {return}- let layout = panelLayout(- context: currentContext,+ guard let layout = panelLayout(+ anchor: currentAnchor,menuSurfaceWindow: menuSurfaceWindow,- contentView: menuContentView,snapshot: snapshot- )+ ) else {+ hide()+ return+ }guard panel.frame != layout.position.frame else {return}- NSAnimationContext.runAnimationGroup { context in- context.duration = Metrics.contentUpdateDuration- context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)- panel.animator().setFrame(layout.position.frame, display: true)+ // 宿主随 SwiftUI 布局逐帧伸缩, 窗口位置同步更新, 避免叠加动画+ panel.setFrame(layout.position.frame, display: true)+ }++ private func observeLayout(anchor: ActivityCenterPanelAnchor, window: NSWindow) {+ layoutSubscriptions.removeAll()+ anchor.$topOffset+ .dropFirst()+ .sink { [weak self] _ in self?.scheduleGeometryUpdate() }+ .store(in: &layoutSubscriptions)+ for name in [NSWindow.didMoveNotification, NSWindow.didResizeNotification, NSWindow.didChangeScreenNotification] {+ NotificationCenter.default.publisher(for: name, object: window)+ .sink { [weak self] _ in self?.scheduleGeometryUpdate() }+ .store(in: &layoutSubscriptions)}}+ private func scheduleGeometryUpdate() {+ guard presentationState.isPresented, activityMonitor.snapshot.hasTaskCenterContent else { return }+ schedulePanelUpdate(hasContent: true)+ }+private func schedulePanelUpdate(hasContent: Bool) {cancelScheduledPanelUpdate()panelUpdateTask = Task { @MainActor [weak self] indiff --git a/CodexBar/Controllers/FallbackPanelController.swift b/CodexBar/Controllers/FallbackPanelController.swiftindex 9f81779..a4f8772 100644--- a/CodexBar/Controllers/FallbackPanelController.swift+++ b/CodexBar/Controllers/FallbackPanelController.swift@@ -1,11 +1,12 @@import AppKitimport SwiftUI-/// 全局快捷键无法信任 status item 锚点时使用的无箭头菜单面板+/// 全局快捷键无法通过 status item 锚点可靠定位时使用的无箭头菜单面板@MainActorfinal class FallbackPanelController {private let makeContentController: () -> NSHostingController<AnyView>private var panel: KeyableBorderlessPanel?+ private var resizeTask: Task<Void, Never>?init(makeContentController: @escaping () -> NSHostingController<AnyView>) {self.makeContentController = makeContentController@@ -24,6 +25,7 @@ final class FallbackPanelController {}func prepareForDisplay(on screen: NSScreen?) {+ cancelPendingResize()let panel = makePanelIfNeeded()let contentSize = contentSize(for: panel)panel.setFrame(frame(for: contentSize, on: screen), display: false)@@ -38,19 +40,32 @@ final class FallbackPanelController {}func orderOut() {+ cancelPendingResize()panel?.orderOut(nil)AppearanceTransition.dismissSnapshots(in: panel)}func resizeIfVisible(contentHeight: CGFloat) {guard let panel, panel.isVisible,- contentHeight.isFinite, contentHeight > 0,- panel.frame.height != contentHeight else { return }- var frame = panel.frame- frame.origin.y = frame.maxY - contentHeight- frame.size.height = contentHeight- // 高度已由 SwiftUI 逐帧插值, 再启动窗口动画会让宿主滞后于内容- panel.setFrame(frame, display: true)+ contentHeight.isFinite, contentHeight > 0 else { return }+ cancelPendingResize()+ guard panel.frame.height != contentHeight else { return }+ resizeTask = Task { @MainActor [weak self] in+ // 几何回调可能仍在 NSHostingView.layout 中, 等本轮布局退出后再调整窗口+ await Task.yield()+ guard let self, !Task.isCancelled, let panel = self.panel, panel.isVisible else { return }+ resizeTask = nil+ var frame = panel.frame+ frame.origin.y = frame.maxY - contentHeight+ frame.size.height = contentHeight+ // 高度由 SwiftUI 逐帧插值, 窗口直接跟随, 避免叠加动画+ panel.setFrame(frame, display: true)+ }+ }++ private func cancelPendingResize() {+ resizeTask?.cancel()+ resizeTask = nil}private func makePanelIfNeeded() -> KeyableBorderlessPanel {diff --git a/CodexBar/Controllers/GlobalHotKeyController.swift b/CodexBar/Controllers/GlobalHotKeyController.swiftindex 1186c86..35c97a2 100644--- a/CodexBar/Controllers/GlobalHotKeyController.swift+++ b/CodexBar/Controllers/GlobalHotKeyController.swift@@ -44,7 +44,7 @@ final class GlobalHotKeyController {)guard status == noErr else {- // 注册失败最常见的原因是快捷键被其他 App 占用, 此时按键不会触发操作+ // 新快捷键注册失败时清理本次 handler, 保留已有注册let details = LogFields.joined("stage=register","code=\(status)"diff --git a/CodexBar/Controllers/HostingWindowController.swift b/CodexBar/Controllers/HostingWindowController.swiftindex d6840a4..c54106c 100644--- a/CodexBar/Controllers/HostingWindowController.swift+++ b/CodexBar/Controllers/HostingWindowController.swift@@ -43,7 +43,7 @@ final class AuxiliaryHostingWindow: NSWindow {}}-/// 承载 SwiftUI 内容的单窗口控制器基类, 统一懒创建, 居中与窗口管理逻辑+/// 承载 SwiftUI 内容的单窗口控制器基类, 按需创建窗口并统一处理居中和窗口管理@MainActorclass HostingWindowController {let screenProvider: () -> NSScreen?diff --git a/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift b/CodexBar/Controllers/MenuSurfaceDismissMonitor.swiftindex 53bcabc..9163c54 100644--- a/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift+++ b/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift@@ -275,7 +275,7 @@ final class MenuSurfaceDismissMonitor {return}- // 只有真正点到菜单和状态按钮之外才关闭+ // 点击位置在菜单和状态按钮之外时才关闭dismiss()}diff --git a/CodexBar/Controllers/SettingsHelpPresenter.swift b/CodexBar/Controllers/SettingsHelpPresenter.swiftindex 6a8a03d..c5f9686 100644--- a/CodexBar/Controllers/SettingsHelpPresenter.swift+++ b/CodexBar/Controllers/SettingsHelpPresenter.swift@@ -51,7 +51,7 @@ final class SettingsHelpPresenter {hostingView.frame = contentFramehostingView.autoresizingMask = [.width, .height]- // 普通容器拥有窗口尺寸, SwiftUI 只绘制已测量的固定区域, 不反向更新窗口约束+ // 普通容器控制窗口尺寸, SwiftUI 只绘制已测量的固定区域, 不反向更新窗口约束let container = NSView(frame: contentFrame)container.addSubview(hostingView)panel.contentView = containerdiff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftindex 4b1aab5..5efe5d9 100644--- a/CodexBar/Controllers/SettingsWindowController.swift+++ b/CodexBar/Controllers/SettingsWindowController.swift@@ -29,7 +29,7 @@ final class SettingsWindowController: HostingWindowController {private var optionsDismissEventMonitor: Any?private var optionsDismissFocusObserver: AnyCancellable?private var optionsDismissedByClick: (panel: SettingsOptionsPanel, event: NSEvent)?- /// 首次构造窗口时 SwiftUI 可能先于 window 赋值上报高度 因此必须保留最近一次测量+ /// 首次构造窗口时, SwiftUI 可能在 window 赋值前上报高度, 因此必须保留最近一次测量结果private var preferredContentHeight: CGFloat?init(@@ -146,7 +146,7 @@ final class SettingsWindowController: HostingWindowController {static let minimumContentSize = NSSize(width: 420, height: 240)static let initialContentSize = NSSize(width: AppSettingsView.preferredContentWidth, height: 270)static let maximumFallbackContentSize = NSSize(width: 560, height: 720)- /// 只用于首次定位的稳定顶边基准 不限制页面自适应高度+ /// 顶边基准只用于首次定位, 不限制页面自适应高度static let topEdgeReferenceContentHeight: CGFloat = 500static let screenInset: CGFloat = 80}@@ -345,7 +345,6 @@ final class SettingsWindowController: HostingWindowController {}/// 子面板共用设置窗口右侧的位置, 展开前用 immediate 收起其他面板, 避免出入场动画交叠- /// 所有子面板共用此互斥规则private func handleOptionsAction(_ action: SettingsOptionsPanelAction) {switch action {case let .toggle(panel, anchorProvider):diff --git a/CodexBar/Controllers/SidePanelPresenter.swift b/CodexBar/Controllers/SidePanelPresenter.swiftindex cb1abf0..c18e179 100644--- a/CodexBar/Controllers/SidePanelPresenter.swift+++ b/CodexBar/Controllers/SidePanelPresenter.swift@@ -123,9 +123,9 @@ final class SidePanelDrawerAnimator {// MARK: - 展开与收起-/// 抽屉面板共用的显隐状态机, 用于重置次数 设置子选项和任务中心-/// 负责 generation 竞态防护 入退场动画和 child window 挂载与卸载-/// 热力图详情面板带切边与延迟隐藏 状态机不同 因此不走这里+/// 重置次数, 设置子选项和任务中心共用的抽屉面板显隐状态机+/// 负责 generation 竞态防护, 入退场动画和 child window 挂载与卸载+/// 热力图详情面板需要切边和延迟隐藏, 使用独立的状态机@MainActorfinal class SidePanelDrawerPresenter {private let usesUntranslatedInitialLayout: Booldiff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex 6c8f710..122ad58 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -26,6 +26,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {private let popoverAnimationState = MenuSurfaceAnimationState()private let fallbackPanelAnimationState = MenuSurfaceAnimationState()private let activityCenterPresentationState = ActivityCenterPresentationState()+ private lazy var activityCardPresentationState = ActivityCardPresentationState(activityMonitor: activityMonitor)private lazy var heatmapDetailPanelController = HeatmapPanelController(mainPanelSettings: mainPanelSettings)private lazy var resetCreditsPanelController = ResetCreditsPanelController(mainPanelSettings: mainPanelSettings)private lazy var activityCenterPanelController = ActivityPanelController(@@ -254,14 +255,15 @@ final class StatusItemController: NSObject, NSMenuDelegate {menuSurfaceVisibility: menuSurfaceVisibility,animationState: animationState,activityCenterPresentationState: activityCenterPresentationState,+ activityCardPresentationState: activityCardPresentationState,onUsageHeatmapHoverChange: { [weak self] context inself?.updateHeatmapDetailPanel(context)},onResetCreditsTap: { [weak self] context inself?.toggleResetCreditsPanel(context)},- onActivityCenterTap: { [weak self] context in- self?.toggleActivityCenterPanel(context)+ onActivityCenterTap: { [weak self] anchor in+ self?.toggleActivityCenterPanel(anchor)}).environmentObject(appUpdater)@@ -269,6 +271,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {.fixedSize(horizontal: false, vertical: true)let rootView = MenuPanelLayout { menuContent }+ .coordinateSpace(name: ActivityCenterPanelAnchor.coordinateSpace).onGeometryChange(for: CGFloat.self) { geometry ingeometry.size.height} action: { [weak self] height in@@ -302,21 +305,22 @@ final class StatusItemController: NSObject, NSMenuDelegate {.map(\.hasTaskCenterContent).removeDuplicates()- let isTaskCenterVisible = mainPanelSettings.$layout+ let isActivitySectionEnabled = mainPanelSettings.$layout.map { $0.isVisible(.activity) }.removeDuplicates()Publishers.CombineLatest3(menuSurfaceVisibility.$isVisible,hasTaskCenterContent,- isTaskCenterVisible+ isActivitySectionEnabled)- .map { isMenuVisible, hasActivity, isTaskCenterVisible in- isMenuVisible && hasActivity && isTaskCenterVisible+ .map { isMenuVisible, hasActivity, isActivitySectionEnabled in+ isMenuVisible && hasActivity && isActivitySectionEnabled}.removeDuplicates().sink { [weak self] isActive inself?.activityCenterPresentationState.setTimelineActive(isActive)+ self?.activityCardPresentationState.setVisible(isActive)}.store(in: &cancellables)@@ -486,7 +490,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {}}- /// toggle 将走"打开"分支的状态谓词, 与 toggleMenuSurface 的分支口径一致+ /// 判断 toggle 是否会打开面板, 条件与 toggleMenuSurface 一致private var menuSurfaceWillOpenOnToggle: Bool {menuSurfaceState == .hidden || menuSurfaceState == .closing}@@ -826,7 +830,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {private func refreshHistory(performMaintenance: Bool) {if performMaintenance {syncSettings.refreshAvailabilityIfNeeded()- // 统计维护挂在额度刷新完成事件上, 触发来源继承那一次刷新+ // 额度刷新完成后触发统计维护, 沿用本次刷新的触发来源syncScheduler.requestMaintenance(allowsSync: true,trigger: viewModel.lastRefreshTrigger@@ -878,7 +882,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {)}- private func toggleActivityCenterPanel(_ context: ActivityCenterPanelContext) {+ private func toggleActivityCenterPanel(_ anchor: ActivityCenterPanelAnchor) {guard isActiveMenuSurfaceVisible,let menuSurfaceContentView = activeMenuSurfaceContentView,let menuSurfaceWindow = activeMenuSurfaceWindow else {@@ -888,7 +892,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {hideSideDetailPanels(except: activityCenterPanelController)activityCenterPanelController.toggle(- context: context,+ anchor: anchor,relativeTo: menuSurfaceWindow,contentView: menuSurfaceContentView)diff --git a/CodexBar/Models/ActivityCardSelection.swift b/CodexBar/Models/ActivityCardSelection.swiftnew file mode 100644index 0000000..8d4c1ca--- /dev/null+++ b/CodexBar/Models/ActivityCardSelection.swift@@ -0,0 +1,205 @@+import Foundation++/// 只管理主卡片选择, 不改变采集, 通知或任务中心的排序+nonisolated struct ActivityCardSelection: Equatable {+ private(set) var activities: [CodexPrimaryActivity] = []+ private(set) var selectedID: String?+ private(set) var pinnedID: String?+ private(set) var manualViewingDeadline: Date?+ private(set) var transitionDirection: Int?+ private(set) var isVisible = false+ private var orderedIDs: [String] = []+ private var automaticID: String?+ private var gestureBeganAt: Date?+ private var gestureActivities: [CodexPrimaryActivity]?++ var carouselActivities: [CodexPrimaryActivity] {+ gestureActivities ?? activities+ }++ var isGestureActive: Bool {+ gestureBeganAt != nil+ }++ var current: CodexPrimaryActivity? {+ carouselActivities.first { $0.cardSelectionID == selectedID }+ }++ func positionText(for id: String?) -> String? {+ let carousel = carouselActivities+ guard carousel.count > 1,+ let index = carousel.firstIndex(where: { $0.cardSelectionID == id }) else { return nil }+ return "\(index + 1)/\(carousel.count)"+ }++ var returnDeadline: Date? {+ isVisible && gestureBeganAt == nil ? manualViewingDeadline : nil+ }++ var waitingSides: WaitingSides {+ let carousel = carouselActivities+ guard let origin = carousel.firstIndex(where: { $0.cardSelectionID == selectedID }) else { return WaitingSides() }+ var sides = WaitingSides()+ for (index, activity) in carousel.enumerated() where activity.isCardWaiting && index != origin {+ let forward = (index - origin + carousel.count) % carousel.count+ let backward = carousel.count - forward+ // 高亮对应等待卡片所在侧, 下一项从右侧进入+ sides.left = sides.left || backward <= forward+ sides.right = sides.right || forward <= backward+ }+ return sides+ }++ mutating func update(snapshot: ActivitySnapshot, isHealthy: Bool, now: Date) {+ guard isHealthy else {+ activities = []+ automaticID = nil+ manualViewingDeadline = nil+ gestureBeganAt = nil+ gestureActivities = nil+ transitionDirection = nil+ // 断连期间保留会话顺序和固定关系, 恢复后再根据完整快照裁剪+ return+ }+ let terminals = (snapshot.recentCompletions.map(CodexPrimaryActivity.completed)+ + snapshot.recentTerminations.map(CodexPrimaryActivity.terminated))+ .filter { $0.cardEndedAt.map { now.timeIntervalSince($0) < ActivityRetention.terminalDisplayWindow } == true }+ .sorted { ($0.cardEndedAt ?? .distantPast) > ($1.cardEndedAt ?? .distantPast) }+ let candidates = snapshot.panelWaitingTasks.map(CodexPrimaryActivity.waiting)+ + snapshot.panelRunningTasks.map(CodexPrimaryActivity.running) + terminals+ var latest: [String: CodexPrimaryActivity] = [:]+ var incomingIDs: [String] = []+ for activity in candidates {+ guard let id = activity.cardSelectionID, latest[id] == nil else { continue }+ latest[id] = activity+ incomingIDs.append(id)+ }+ orderedIDs.removeAll { latest[$0] == nil }+ let retainedIDs = Set(orderedIDs)+ orderedIDs += incomingIDs.filter { !retainedIDs.contains($0) }+ activities = orderedIDs.compactMap { latest[$0] }+ if snapshot.hasActiveTasks {+ automaticID = incomingIDs.first+ } else {+ automaticID = snapshot.primaryActivity.cardSelectionID+ }+ if let gestureActivities,+ !Set(gestureActivities.compactMap(\.cardSelectionID)).isSubset(of: Set(incomingIDs)) {+ // 消失的卡片不能继续提交, 让视图取消这轮手势+ setGestureActive(false, now: now)+ } else {+ reconcile(at: now)+ }+ }++ mutating func setVisible(_ visible: Bool, now: Date) {+ guard visible != isVisible else { return }+ isVisible = visible+ manualViewingDeadline = nil+ gestureBeganAt = nil+ gestureActivities = nil+ transitionDirection = nil+ if visible {+ reconcile(at: now)+ }+ }++ mutating func swipe(_ step: Int, now: Date) {+ let carousel = carouselActivities+ guard isVisible, carousel.count > 1,+ let index = carousel.firstIndex(where: { $0.cardSelectionID == selectedID }) else { return }+ let direction = step < 0 ? -1 : 1+ transitionDirection = direction+ selectedID = carousel[(index + direction + carousel.count) % carousel.count].cardSelectionID+ beginManualViewing(at: now)+ }++ mutating func selectAfterSwipe(_ id: String, now: Date) {+ guard isVisible, activities.contains(where: { $0.cardSelectionID == id }) else { return }+ selectedID = id+ transitionDirection = nil+ beginManualViewing(at: now)+ }++ mutating func togglePin(now: Date) {+ guard isVisible, let current, let id = current.cardSelectionID else { return }+ if pinnedID == id {+ pinnedID = nil+ beginManualViewing(at: now)+ } else {+ pinnedID = id+ manualViewingDeadline = nil+ }+ }++ mutating func setGestureActive(_ active: Bool, now: Date) {+ guard isVisible else { return }+ if active {+ if gestureBeganAt == nil {+ gestureBeganAt = now+ // 连续手势接管收尾动画时沿用同一快照, 保持卡片, 位置数字和高亮一致+ gestureActivities = activities+ }+ } else if let began = gestureBeganAt {+ manualViewingDeadline = manualViewingDeadline?.addingTimeInterval(max(0, now.timeIntervalSince(began)))+ gestureBeganAt = nil+ gestureActivities = nil+ reconcile(at: now)+ }+ }++ mutating func reconcile(at now: Date) {+ if current != nil, gestureBeganAt != nil || manualViewingDeadline.map({ $0 > now }) == true {+ return+ }+ manualViewingDeadline = nil+ let available = Set(activities.compactMap(\.cardSelectionID))+ let next = pinnedID.flatMap { available.contains($0) ? $0 : nil }+ ?? automaticID.flatMap { available.contains($0) ? $0 : nil }+ ?? activities.first?.cardSelectionID+ guard next != selectedID else { return }+ transitionDirection = nil+ selectedID = next+ }++ private mutating func beginManualViewing(at now: Date) {+ // 停留期限按最新等待状态计算, 不沿用手势开始时的展示状态+ let activity = activities.first { $0.cardSelectionID == selectedID }+ manualViewingDeadline = now.addingTimeInterval(activity?.isCardWaiting == true ? 15 : 10)+ if gestureBeganAt != nil {+ gestureBeganAt = now+ }+ }++ struct WaitingSides: Equatable {+ var left = false+ var right = false+ }+}++extension CodexPrimaryActivity {+ nonisolated var cardSelectionID: String? {+ switch self {+ case let .waiting(task), let .running(task): task.threadID+ case let .completed(task): task.threadID+ case let .terminated(task): task.threadID+ case .idle: nil+ }+ }++ nonisolated var isCardWaiting: Bool {+ if case .waiting = self {+ true+ } else {+ false+ }+ }++ nonisolated var cardEndedAt: Date? {+ switch self {+ case let .completed(task): task.completedAt+ case let .terminated(task): task.terminatedAt+ default: nil+ }+ }+}diff --git a/CodexBar/Models/ActivityModels.swift b/CodexBar/Models/ActivityModels.swiftindex 11f45f4..d1b557b 100644--- a/CodexBar/Models/ActivityModels.swift+++ b/CodexBar/Models/ActivityModels.swift@@ -1,11 +1,13 @@import Foundation-/// 活动状态, 任务历史和子 Agent 关联共用的保留窗口nonisolated enum ActivityRetention {+ /// 活动状态, 任务历史和子 Agent 关联共用的保留窗口static let window: TimeInterval = 24 * 60 * 60+ /// 已结束任务在快照和界面中的展示保留窗口+ static let terminalDisplayWindow: TimeInterval = 10 * 60}-/// 正在运行或等待回应的任务摘要, 不对 UI 暴露原始会话 ID+/// 正在运行或等待回应的任务摘要nonisolated struct ActivityTaskSnapshot: Equatable, Identifiable {let id: UUIDlet projectName: String?@@ -18,6 +20,7 @@ nonisolated struct ActivityTaskSnapshot: Equatable, Identifiable {var tokenUsage: TokenUsage?var approvalActionText: String?var presentation: ActivityLiveSummary?+ let threadID: String}/// 最近确认结束的任务; 完成只表示一轮任务结束, 不代表执行成功@@ -31,6 +34,7 @@ nonisolated struct ActivityCompletion: Equatable, Identifiable {let completedAt: Datelet duration: TimeInterval?var tokenUsage: TokenUsage?+ let threadID: String}/// 本轮确认的终态和快照一起发布, 历史恢复只发布快照@@ -69,6 +73,7 @@ nonisolated struct ActivityTermination: Equatable, Identifiable {let duration: TimeInterval?var tokenUsage: TokenUsage?var isFailure = false+ let threadID: String}/// 实时越过静默阈值时交给通知服务的最小信息, 不包含原始 thread 或 turn ID@@ -79,7 +84,7 @@ nonisolated struct ProtectionNotice: Equatable, Sendable {let inactivityDurationText: String}-/// UI 只消费该快照, 不直接读取或解释 活动事件+/// UI 只读取该快照, 不直接读取或解释活动事件nonisolated struct ActivitySnapshot: Equatable {/// 仅包含审批等待, 其他交互等待由 panelWaitingTasks 合并展示let waitingTasks: [ActivityTaskSnapshot]@@ -114,16 +119,6 @@ nonisolated struct ActivitySnapshot: Equatable {return (Set(runningTasks.map(\.id)).subtracting(waiting), waiting)}- var panelPrimaryActivity: CodexPrimaryActivity {- if let task = panelWaitingTasks.first {- return .waiting(task)- }- if let task = panelRunningTasks.first {- return .running(task)- }- return primaryActivity- }-var primaryWaitingTask: ActivityTaskSnapshot? {waitingTasks.first}diff --git a/CodexBar/Models/AppServerLogEntry.swift b/CodexBar/Models/AppServerLogEntry.swiftindex aef4830..f3ef6a0 100644--- a/CodexBar/Models/AppServerLogEntry.swift+++ b/CodexBar/Models/AppServerLogEntry.swift@@ -1,6 +1,6 @@import Foundation-/// JSON-RPC 交互日志: 带 id 的请求先记录为进行+/// JSON-RPC 交互日志: 带 id 的请求先记录为进行中/// 响应或错误到达后回填到同一条/// 无需配对的消息单独记录, request 和 detail 分别保留发送与接收内容nonisolated struct AppServerLogEntry: Identifiable, Equatable, Codable, Sendable {diff --git a/CodexBar/Models/CodexAccountModels.swift b/CodexBar/Models/CodexAccountModels.swiftindex 19094db..f420920 100644--- a/CodexBar/Models/CodexAccountModels.swift+++ b/CodexBar/Models/CodexAccountModels.swift@@ -26,7 +26,7 @@ nonisolated struct CodexAccount: Decodable, Equatable {}}-/// account/read 允许 account 为空, 由上层转换为`未登录`状态+/// account/read 允许 account 为空, 上层将其转换为 `未登录` 状态nonisolated struct AccountReadResponse: Decodable {let account: CodexAccount?diff --git a/CodexBar/Models/CodexDateFormat.swift b/CodexBar/Models/CodexDateFormat.swiftindex cfa159d..6432b96 100644--- a/CodexBar/Models/CodexDateFormat.swift+++ b/CodexBar/Models/CodexDateFormat.swift@@ -63,8 +63,8 @@ nonisolated enum CodexDateFormat {return calendar}()- /// 以下格式器配置后不再修改; DateFormatter- /// 在 macOS 10.9+ 线程安全, 可跨并发域缓存共享+ /// DateFormatter 在 macOS 10.9+ 线程安全+ /// 此实例配置后不再修改, 可跨并发域缓存共享private static let localDisplayFormatter: DateFormatter = {let formatter = DateFormatter()formatter.locale = Locale(identifier: "en_US_POSIX")diff --git a/CodexBar/Models/CodexQuotaModels.swift b/CodexBar/Models/CodexQuotaModels.swiftindex 5846b34..712a146 100644--- a/CodexBar/Models/CodexQuotaModels.swift+++ b/CodexBar/Models/CodexQuotaModels.swift@@ -92,7 +92,7 @@ nonisolated enum QuotaWindowKind: String, Equatable {case secondary}-/// primary/secondary 窗口的 UI 友好表示, 统一计算剩余额度百分比+/// 供 UI 使用的 primary/secondary 窗口模型, 统一计算剩余额度百分比nonisolated struct QuotaWindow: Equatable, Identifiable {let kind: QuotaWindowKindlet windowDurationMins: Int?diff --git a/CodexBar/Models/UsageHeatmapDay.swift b/CodexBar/Models/UsageHeatmapDay.swiftindex c61a3c4..a3be358 100644--- a/CodexBar/Models/UsageHeatmapDay.swift+++ b/CodexBar/Models/UsageHeatmapDay.swift@@ -14,7 +14,7 @@ nonisolated enum UsageHeatmapTokenState: Equatable {}}-/// 热力图单元格模型, 合并 app-server token 数据和本地 活动统计+/// 热力图单元格模型, 合并 app-server token 数据和本地活动统计nonisolated struct UsageHeatmapDay: Equatable, Identifiable {let startDate: Stringlet tokenState: UsageHeatmapTokenStatediff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstringsindex 2341fca..41dfa45 100644--- a/CodexBar/Resources/Localizable.xcstrings+++ b/CodexBar/Resources/Localizable.xcstrings@@ -2274,22 +2274,6 @@}}},- "activity.summary.other-task-count" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Other tasks: %lld"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "另有 %lld 个任务"- }- }- }- },"app.action.quit" : {"localizations" : {"en" : {diff --git a/CodexBar/Resources/ThirdPartyLicenses.txt b/CodexBar/Resources/ThirdPartyLicenses.txtindex be4573b..9e4f610 100644--- a/CodexBar/Resources/ThirdPartyLicenses.txt+++ b/CodexBar/Resources/ThirdPartyLicenses.txt@@ -1,6 +1,10 @@SwiftTreeSitter===============+Version: 0.25.0+Source: https://github.com/tree-sitter/swift-tree-sitter+License: https://github.com/tree-sitter/swift-tree-sitter/blob/08ef81eb8620617b55b08868126707ad72bf754f/LICENSE+BSD 3-Clause LicenseCopyright (c) 2021, Chime@@ -35,6 +39,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.Tree-sitter===========+Version: 0.25.10+Source: https://github.com/tree-sitter/tree-sitter+License: https://github.com/tree-sitter/tree-sitter/blob/da6fe9beb4f7f67beb75914ca8e0d48ae48d6406/LICENSE+The MIT License (MIT)Copyright (c) 2018-2024 Max Brunsfeld@@ -61,6 +69,10 @@ SOFTWARE.tree-sitter-bash================+Version: 0.25.1+Source: https://github.com/tree-sitter/tree-sitter-bash+License: https://github.com/tree-sitter/tree-sitter-bash/blob/a06c2e4415e9bc0346c6b86d401879ffb44058f7/LICENSE+The MIT License (MIT)Copyright (c) 2017 Max Brunsfeld@@ -85,7 +97,11 @@ SOFTWARE.Unicode data used by Tree-sitter-===============================+================================++Version: Bundled with Tree-sitter 0.25.10+Source: https://github.com/tree-sitter/tree-sitter+License: https://github.com/tree-sitter/tree-sitter/blob/da6fe9beb4f7f67beb75914ca8e0d48ae48d6406/lib/src/unicode/LICENSECOPYRIGHT AND PERMISSION NOTICE (ICU 58 and later)@@ -501,3 +517,146 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANYTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+++Sparkle+========++Version: 2.10.1+Source: https://github.com/sparkle-project/Sparkle+License: https://github.com/sparkle-project/Sparkle/blob/ab7d71291238df6e0492143b120c9b696a35f603/LICENSE++Copyright (c) 2006-2013 Andy Matuschak.+Copyright (c) 2009-2013 Elgato Systems GmbH.+Copyright (c) 2011-2014 Kornel Lesiński.+Copyright (c) 2015-2017 Mayur Pawashe.+Copyright (c) 2014 C.W. Betts.+Copyright (c) 2014 Petroules Corporation.+Copyright (c) 2014 Big Nerd Ranch.+All rights reserved.++Permission is hereby granted, free of charge, to any person obtaining a copy of+this software and associated documentation files (the "Software"), to deal in+the Software without restriction, including without limitation the rights to+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of+the Software, and to permit persons to whom the Software is furnished to do so,+subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.++=================+EXTERNAL LICENSES+=================++bspatch.c and bsdiff.c, from bsdiff 4.3 <http://www.daemonology.net/bsdiff/>:++Copyright 2003-2005 Colin Percival+All rights reserved++Redistribution and use in source and binary forms, with or without+modification, are permitted providing that the following conditions+are met:+1. Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.+2. Redistributions in binary form must reproduce the above copyright+ notice, this list of conditions and the following disclaimer in the+ documentation and/or other materials provided with the distribution.++THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE+ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,+STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING+IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE+POSSIBILITY OF SUCH DAMAGE.++--++sais.c and sais.h, from sais-lite (2010/08/07) <https://sites.google.com/site/yuta256/sais>:++The sais-lite copyright is as follows:++Copyright (c) 2008-2010 Yuta Mori All Rights Reserved.++Permission is hereby granted, free of charge, to any person+obtaining a copy of this software and associated documentation+files (the "Software"), to deal in the Software without+restriction, including without limitation the rights to use,+copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the+Software is furnished to do so, subject to the following+conditions:++The above copyright notice and this permission notice shall be+included in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR+OTHER DEALINGS IN THE SOFTWARE.++--++Portable C implementation of Ed25519, from https://github.com/orlp/ed25519++Copyright (c) 2015 Orson Peters <[email protected]>++This software is provided 'as-is', without any express or implied warranty. In no event will the+authors be held liable for any damages arising from the use of this software.++Permission is granted to anyone to use this software for any purpose, including commercial+applications, and to alter it and redistribute it freely, subject to the following restrictions:++1. The origin of this software must not be misrepresented; you must not claim that you wrote the+ original software. If you use this software in a product, an acknowledgment in the product+ documentation would be appreciated but is not required.++2. Altered source versions must be plainly marked as such, and must not be misrepresented as+ being the original software.++3. This notice may not be removed or altered from any source distribution.++--++SUSignatureVerifier.m:++Copyright (c) 2011 Mark Hamlin.++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted providing that the following conditions+are met:+1. Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.+2. Redistributions in binary form must reproduce the above copyright+ notice, this list of conditions and the following disclaimer in the+ documentation and/or other materials provided with the distribution.++THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE+ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,+STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING+IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE+POSSIBILITY OF SUCH DAMAGE.diff --git a/CodexBar/Services/Activity/ActivityLivePresentation.swift b/CodexBar/Services/Activity/ActivityLivePresentation.swiftindex 0d6676e..8b7a742 100644--- a/CodexBar/Services/Activity/ActivityLivePresentation.swift+++ b/CodexBar/Services/Activity/ActivityLivePresentation.swift@@ -278,7 +278,7 @@ nonisolated struct ActivityLivePresentation {}private mutating func boundStorage() {- // 异常服务端不能通过无限未结束的 item 或 request 扩大内存+ // 限制未结束的 item 和 request 数量, 避免异常服务端使内存持续增长if items.count > 128 {items = Dictionary(uniqueKeysWithValues: items.sorted { $0.value.at > $1.value.at }.prefix(128).map { ($0.key, $0.value) })inventoryKnown = falsediff --git a/CodexBar/Services/Activity/ActivityMonitor.swift b/CodexBar/Services/Activity/ActivityMonitor.swiftindex 579cd24..c58f535 100644--- a/CodexBar/Services/Activity/ActivityMonitor.swift+++ b/CodexBar/Services/Activity/ActivityMonitor.swift@@ -327,7 +327,7 @@ final class ActivityMonitor: ObservableObject {}}- /// 恢复结果携带屏障之后发布的同一份快照, 不再跨 actor 查询第二份状态+ /// 恢复结果携带屏障之后发布的快照, 避免跨 actor 查询时读到另一份状态func requestActivityRecovery() {guard !isSystemSleeping, let reader = activityReader, !isBootstrapping, let recoveryGeneration = activeRecoveryID else { return }recoveryTask?.cancel()@@ -509,10 +509,10 @@ final class ActivityMonitor: ObservableObject {private func scheduleNextCleanup(now: Date) {var deadlines = completions.map {- $0.completedAt.addingTimeInterval(Self.recentHistoryRetention)+ $0.completedAt.addingTimeInterval(ActivityRetention.terminalDisplayWindow)}deadlines.append(contentsOf: terminations.map {- $0.terminatedAt.addingTimeInterval(Self.recentHistoryRetention)+ $0.terminatedAt.addingTimeInterval(ActivityRetention.terminalDisplayWindow)})deadlines.append(contentsOf: pendingTerminalTasks.values.map(\.expiresAt))deadlines.append(contentsOf: recentlyEndedTaskAt.values.map {@@ -543,7 +543,6 @@ final class ActivityMonitor: ObservableObject {}}- private static let recentHistoryRetention: TimeInterval = 10 * 60static let endedTaskRetention: TimeInterval = 24 * 60 * 60static let protectionNotificationSubmissionGrace: Duration = .seconds(3)private static let recoveryRetryInterval: TimeInterval = 1diff --git a/CodexBar/Services/Activity/ActivityTask.swift b/CodexBar/Services/Activity/ActivityTask.swiftindex 3618661..1cd7d78 100644--- a/CodexBar/Services/Activity/ActivityTask.swift+++ b/CodexBar/Services/Activity/ActivityTask.swift@@ -125,7 +125,8 @@ nonisolated struct ActivityTask {activeSubagentCount: activeSubagentCount,tokenUsage: tokenUsage,approvalActionText: displayedApproval?.actionText,- presentation: livePresentation+ presentation: livePresentation,+ threadID: key.threadID)}@@ -172,7 +173,7 @@ nonisolated struct ActivityTask {lastProgressAt}- /// 隐藏还要求 Codex 后台服务提供的新鲜生命周期覆盖+ /// 隐藏任务前需从 Codex 后台服务完整读取生命周期, 且读取结果仍在有效期内func protectionDeadline(at now: Date, inactivityDuration: TimeInterval) -> Date? {guard hasFreshLifecycle(at: now) else { return nil }return protectionReferenceAt.addingTimeInterval(inactivityDuration)diff --git a/CodexBar/Services/Activity/ActivityTaskGraph+Subagents.swift b/CodexBar/Services/Activity/ActivityTaskGraph+Subagents.swiftindex 20df039..866f67a 100644--- a/CodexBar/Services/Activity/ActivityTaskGraph+Subagents.swift+++ b/CodexBar/Services/Activity/ActivityTaskGraph+Subagents.swift@@ -6,7 +6,7 @@ nonisolated struct PendingSubagentEvent {}nonisolated extension ActivityTaskGraph {- /// 生命周期和工具事件 都携带子轮次, 已结束或未确认的归属不回退到当前根任务+ /// 生命周期和工具事件都携带子轮次, 已结束或未确认的归属不回退到当前根任务func matchingSubagentParentTaskKey(for event: ActivityDataRecord) -> ActivityTaskKey? {diff --git a/CodexBar/Services/Activity/ActivityTaskGraph.swift b/CodexBar/Services/Activity/ActivityTaskGraph.swiftindex 7ca84b5..c9cf183 100644--- a/CodexBar/Services/Activity/ActivityTaskGraph.swift+++ b/CodexBar/Services/Activity/ActivityTaskGraph.swift@@ -1,6 +1,6 @@import Foundation-/// reader 独占任务事实, 发布值快照后 UI 不再消费原始事件或补查另一份缓存+/// reader 独占任务状态, UI 只读取发布的值快照, 不处理原始事件或补查其他缓存nonisolated struct ActivityTaskGraph {var tasks: [ActivityTaskKey: ActivityTask] = [:]var pendingTerminalTasks: [ActivityTaskKey: PendingTerminalTask] = [:]@@ -84,7 +84,7 @@ nonisolated struct ActivityTaskGraph {mutating func prune(now: Date) {pendingTerminalTasks = pendingTerminalTasks.filter { $0.value.expiresAt > now }- let cutoff = now.addingTimeInterval(-600)+ let cutoff = now.addingTimeInterval(-ActivityRetention.terminalDisplayWindow)completions.removeAll { $0.completedAt <= cutoff }terminations.removeAll { $0.terminatedAt <= cutoff }let retained = Set(completions.map(\.id)).union(terminations.map(\.id))@@ -302,7 +302,8 @@ nonisolated struct ActivityTaskGraph {modelName: task.modelName,effort: task.effort,completedAt: completedAt,- duration: duration ?? at.flatMap { task.preciseDuration(until: $0) }+ duration: duration ?? at.flatMap { task.preciseDuration(until: $0) },+ threadID: task.key.threadID)completions.append(completion)registerTerminalTokenUsage(id: completion.id, task: task)@@ -321,7 +322,8 @@ nonisolated struct ActivityTaskGraph {effort: task.effort,terminatedAt: terminatedAt,duration: duration ?? at.flatMap { task.preciseDuration(until: $0) },- isFailure: task.terminalFailed+ isFailure: task.terminalFailed,+ threadID: task.key.threadID)terminations.append(termination)registerTerminalTokenUsage(id: termination.id, task: task)diff --git a/CodexBar/Services/Activity/AppServerActivityReader.swift b/CodexBar/Services/Activity/AppServerActivityReader.swiftindex a1d5a0d..68a9d21 100644--- a/CodexBar/Services/Activity/AppServerActivityReader.swift+++ b/CodexBar/Services/Activity/AppServerActivityReader.swift@@ -81,7 +81,7 @@ actor AppServerActivityReader {private var backfillEpoch = UUID()private var backfillScans: [ActivityTurnReference: BackfillScan] = [:]private var backfillRoots = Set<ActivityTurnReference>()- private var backfillThreads = Set<String>()+ private var backfillThreads: [String: Date] = [:]private var liveStartedTurns = Set<ActivityTurnReference>()private var tokenUsageRestorations: [String: Task<Void, Never>] = [:]@@ -142,6 +142,7 @@ actor AppServerActivityReader {private struct BackfillScan {var completed = false+ let createdAt = Date()var cursor: String?var limit = 20var visitedCursors = Set<String>()@@ -161,6 +162,7 @@ actor AppServerActivityReader {private let maximumPendingBytes: Intprivate let maximumLoadedPages: Intprivate let reconciliationTimeout: TimeInterval+ private let discoveryInterval: TimeIntervalprivate let reconciliationClock: @Sendable () -> ContinuousClock.Instantinit(@@ -172,6 +174,7 @@ actor AppServerActivityReader {maximumPendingBytes: Int = 8 * 1024 * 1024,maximumLoadedPages: Int = 100,reconciliationTimeout: TimeInterval = 30,+ discoveryInterval: TimeInterval = 2,reconciliationClock: @escaping @Sendable () -> ContinuousClock.Instant = { .now },onAccountChange: @escaping @MainActor @Sendable (AccountChange) -> Void = { _ in },onBatch: @escaping @MainActor @Sendable (ActivityUpdate) -> Void@@ -185,6 +188,7 @@ actor AppServerActivityReader {self.maximumPendingBytes = maximumPendingBytesself.maximumLoadedPages = maximumLoadedPagesself.reconciliationTimeout = reconciliationTimeout+ self.discoveryInterval = discoveryIntervalself.reconciliationClock = reconciliationClockself.onAccountChange = onAccountChangeself.onBatch = onBatch@@ -266,7 +270,7 @@ actor AppServerActivityReader {try await connect(generation: current)}try await consumeAvailable(generation: current)- if !drainWaiters.isEmpty || Date().timeIntervalSince(reconciledAt) >= 2 {+ if !drainWaiters.isEmpty || Date().timeIntervalSince(reconciledAt) >= discoveryInterval {let waiters = drainWaitersdrainWaiters.removeAll()let requestedRecovery = waiters.last?.recoveryID@@ -410,13 +414,14 @@ actor AppServerActivityReader {private func reconcileWithinBudget(bootstrap: Bool, forced: Bool, recovering: Bool, generation current: Int) async throws {let loaded = try await loadThreads(generation: current)+ pruneBackfill(now: Date())ignoredThreads.formIntersection(loaded)let knownActive = Set(reducer.states.keys.filter {reducer.states[$0]?.terminal == nil && reducer.threads[$0.threadID]?.status?.type != .notLoaded}.map(\.threadID))let now = reconciliationClock()let dependencies = Set(reducer.missingRootTurns(liveOnly: forced || recovering).keys)- .union(reducer.missingSubagentParents(liveOnly: forced || recovering)).union(backfillThreads)+ .union(reducer.missingSubagentParents(liveOnly: forced || recovering)).union(backfillThreads.keys)// 历史关联保留补读资格, 只有实时依赖需要快速核对let liveDependencies = Set(reducer.missingRootTurns(liveOnly: true).keys).union(reducer.missingSubagentParents(liveOnly: true))@@ -451,6 +456,7 @@ actor AppServerActivityReader {}}reducer.maintain(loadedThreads: loaded.subtracting(ignoredThreads), now: Date())+ pruneBackfill(now: Date())subscribed.formIntersection(loaded)let retained = loaded.union(knownActive).union(dependencies).subtracting(ignoredThreads)threadChecks = threadChecks.filter { retained.contains($0.key) }@@ -458,7 +464,6 @@ actor AppServerActivityReader {verifiedTurns = verifiedTurns.filter { reducer.states[$0.key] != nil && retained.contains($0.key.threadID) }turnScans = turnScans.filter { retained.contains($0.key) }turnRevisions = turnRevisions.filter { reducer.states[$0.key] != nil && retained.contains($0.key.threadID) }- backfillScans = backfillScans.filter { !$0.value.completed || reducer.states[$0.key] != nil }liveStartedTurns = liveStartedTurns.filter { reducer.states[$0] != nil }invalidThreads.formIntersection(retained)reconciledAt = Date()@@ -509,7 +514,7 @@ actor AppServerActivityReader {let first = try await request(ActivityRequests.turns(id, limit: 10), generation: current)await applySnapshot(thread: thread, turns: first.data, checkpoint: checkpoint, bootstrap: bootstrap || newSubscription)remaining.subtract(first.data.map(\.id))- // 首个小页建立轮次身份后立即处理通知, 深页查询不再延迟实时事件+ // 首个小页建立轮次身份后立即处理通知, 避免后续分页查询延迟实时事件preparingThread = nilconsumeDeferred(for: id)if newSubscription {@@ -531,6 +536,7 @@ actor AppServerActivityReader {let unchanged = checkpoint.threadRevision == revisions[id, default: 0]if unchanged {invalidThreads.remove(id)+ finishBackfillDiscovery(threadID: id, turns: first.data, remaining: remaining)}if invalidThreads.contains(id) {reducer.invalidateThread(id)@@ -618,6 +624,23 @@ actor AppServerActivityReader {}}+ private func finishBackfillDiscovery(threadID: String, turns: [ActivityTurn], remaining: Set<String>) {+ guard !turns.isEmpty, remaining.isEmpty, turns.allSatisfy({+ reducer.states[ActivityTurnReference(threadID: threadID, turnID: $0.id)]?.readStatus == .complete+ }) else { return }+ // 轮次身份已交给 reducer 和补查队列, 不再为历史发现单独轮询会话+ backfillThreads[threadID] = nil+ }++ private func pruneBackfill(now: Date) {+ let cutoff = now.addingTimeInterval(-ActivityRetention.window)+ backfillScans = backfillScans.filter {+ reducer.states[$0.key] != nil || (!$0.value.completed && $0.value.createdAt > cutoff)+ }+ backfillRoots = backfillRoots.filter { reducer.states[$0] != nil || backfillScans[$0] != nil }+ backfillThreads = backfillThreads.filter { $0.value > cutoff }+ }+private func cancelBackfill() {backfillEpoch = UUID()backfillTask?.cancel()@@ -706,23 +729,23 @@ actor AppServerActivityReader {}private func finishBackfill(_ result: Result<AppServerActivityBackfill.Page, Error>, reference: ActivityTurnReference, epoch: UUID, generation current: Int) async {- guard isRunning, generation == current, backfillEpoch == epoch, !Task.isCancelled,- var scan = backfillScans[reference] else { return }+ guard isRunning, generation == current, backfillEpoch == epoch else { return }defer {if backfillEpoch == epoch {backfillTask = nil}}+ guard !Task.isCancelled, var scan = backfillScans[reference] else { return }do {let page = try result.get()guard page.nextCursor.map({ !scan.visitedCursors.contains($0) }) ?? true else { throw CodexStatusError.invalidServerResponse }let events = reducer.historicalEvents(page.items, reference: reference, now: Date())+ reducer.historicalTurnEvents(reference)try await activityDataRecorder.record(events: events)- guard isRunning, generation == current, backfillEpoch == epoch, !Task.isCancelled else { return }+ guard isRunning, generation == current, backfillEpoch == epoch, !Task.isCancelled, backfillScans[reference] != nil else { return }for entry in page.items where entry.item.type == .subAgentActivity && entry.item.kind == "started" {if let child = entry.item.agentThreadId, backfillThreads.count < 10000 {- backfillThreads.insert(child)+ backfillThreads[child] = backfillThreads[child] ?? Date()}}scan.limit = page.limit@@ -732,10 +755,10 @@ actor AppServerActivityReader {scan.cursor = page.nextCursorscan.failures = 0scan.completed = page.nextCursor == nil- backfillScans[reference] = scan+ backfillScans[reference] = scan.completed ? BackfillScan(completed: true) : scanawait publish(.lifecycleChanged)} catch {- guard isRunning, generation == current, backfillEpoch == epoch, !Task.isCancelled else { return }+ guard isRunning, generation == current, backfillEpoch == epoch, !Task.isCancelled, backfillScans[reference] != nil else { return }scan.failures += 1scan.retryAfter = Date().addingTimeInterval(scan.failures == 1 ? 5 : 15)let status = error as? CodexStatusError@@ -745,7 +768,7 @@ actor AppServerActivityReader {false}scan.completed = scan.failures >= 3 || status?.isProtocolOrParameterFailure == true || oversized- backfillScans[reference] = scan+ backfillScans[reference] = scan.completed ? BackfillScan(completed: true) : scanlogStorage?.recordFailure(method: "activity/backfill", message: error.localizedDescription, connection: "activity/backfill")}}diff --git a/CodexBar/Services/AppServer/AppServerLogStore.swift b/CodexBar/Services/AppServer/AppServerLogStore.swiftindex 6ae2187..d228ae9 100644--- a/CodexBar/Services/AppServer/AppServerLogStore.swift+++ b/CodexBar/Services/AppServer/AppServerLogStore.swift@@ -393,7 +393,7 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {private func pruneIfNeeded() throws {let cutoff = HistoryStorage.retentionCutoffDate(today: now())if lastRetentionCutoff != cutoff {- // 复用正文中的时间, 保持现有数据库结构; 损坏正文仍由条数和容量限制兜底+ // 按正文中的时间清理过期日志, 正文损坏时仍受条数和容量限制try execute("""DELETE FROM entries WHERE CASE WHEN json_valid(CAST(payload AS TEXT))THEN json_extract(CAST(payload AS TEXT), '$.requestedAt') END < \(cutoff.timeIntervalSinceReferenceDate)diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swiftindex abafd4a..414c9c1 100644--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift@@ -537,7 +537,7 @@ actor CodexStatusService {session.close()throw CodexStatusError.unsupportedVersion(minimum: minimum)} catch {- // app-server 链路的细节按既有分工进日志窗口, 不重复写系统日志+ // app-server 交互细节写入日志窗口, 不重复写入系统日志logStorage?.recordFailure(message: String(localized: "log.app-server.error.initialization-failed",diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swiftindex 60586bc..26546f4 100644--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift@@ -52,7 +52,7 @@ final class CodexStatusViewModel: ObservableObject {@Published private(set) var autoRefreshCountdownStartedAt: Date?@Published private(set) var dataUpdateInterval: DataUpdateInterval- /// 统计维护挂在额度刷新完成事件上, 由它继承本次刷新的触发来源+ /// 额度刷新完成后触发统计维护, 沿用本次刷新的触发来源private(set) var lastRefreshTrigger: LogTrigger = .launch@Published private(set) var isReconnecting = falsediff --git a/CodexBar/Services/History/HistoryDatabase.swift b/CodexBar/Services/History/HistoryDatabase.swiftindex ca852a3..c10faf2 100644--- a/CodexBar/Services/History/HistoryDatabase.swift+++ b/CodexBar/Services/History/HistoryDatabase.swift@@ -216,7 +216,7 @@ final nonisolated class HistoryDatabase {func tokenUsageSnapshot(threadID: String) throws -> TokenUsageThreadSnapshot {let result = try tokenUsageSnapshot(threadSnapshots[threadID]?.snapshot ?? TokenUsageThreadSnapshot(threadID: threadID))threadSnapshots[threadID] = CachedThreadSnapshot(snapshot: result, accessedAt: Date())- if threadSnapshots.count > 128, let oldest = threadSnapshots.min(by: { $0.value.accessedAt < $1.value.accessedAt })?.key {+ if threadSnapshots.count > 256, let oldest = threadSnapshots.min(by: { $0.value.accessedAt < $1.value.accessedAt })?.key {threadSnapshots[oldest] = nil}return result@@ -428,7 +428,7 @@ final nonisolated class HistoryDatabase {func prune(now: Date) throws -> Int {let cutoff = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate(today: now))- return try transaction {+ let removed = try transaction {try execute("DELETE FROM days WHERE date < ?", [.text(cutoff)])let removed = Int(sqlite3_changes(connection))for aggregate in try activityDataAggregates() {@@ -438,6 +438,9 @@ final nonisolated class HistoryDatabase {}return removed}+ // 其他进程也可能已清理旧记录, 每轮保留期维护后都从剩余数据重建缓存+ threadSnapshots.removeAll()+ return removed}func execute(_ sql: String, _ values: [Value] = []) throws {diff --git a/CodexBar/Services/History/HistoryService.swift b/CodexBar/Services/History/HistoryService.swiftindex 0c07848..39f89d4 100644--- a/CodexBar/Services/History/HistoryService.swift+++ b/CodexBar/Services/History/HistoryService.swift@@ -14,7 +14,7 @@ nonisolated struct HistoryMaintenanceCounts {written + failed}- /// 本轮是否改变了状态+ /// 本轮是否有聚合处理结果或过期清理, 包括处理失败的情况var hasWork: Bool {dates > 0 || pruned > 0}diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swiftindex 39564df..f34cf63 100644--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift@@ -215,7 +215,7 @@ final class KeepAliveController: ObservableObject {}/// App 退出时先等 root 侧取消唤醒计划并把已取得的睡眠所有权恢复为 0- /// 如果本轮没有对应所有权, 两条清理请求都会收敛成无操作成功+ /// 本轮没有对应所有权时, 两条清理请求均返回成功, 不执行实际清理func prepareForTermination() async -> Bool {guard isStarted else {return true@@ -237,7 +237,7 @@ final class KeepAliveController: ObservableObject {return true}- // 退出被取消时恢复正常状态, 不能让一次失败把运行中的任务永久放开+ // 退出被取消时恢复正常状态, 避免因退出失败而停止为运行中的任务防睡眠autoResetWakeScheduler.resumeAfterTerminationCancellation()isPreparingForTermination = falsereconcileSleepState(trigger: .termination, force: true)@@ -287,12 +287,11 @@ final class KeepAliveController: ObservableObject {func setMaximumDuration(_ duration: MaximumDuration) {durationLimiter.setDuration(duration)- // limiter 只在这一轮累计过时才回调, 所以派生值不能等 reconcileSleepState 来带+ // limiter 只在本轮累计过时长时回调, 因此必须在这里更新派生值, 不能等待 reconcileSleepStatepublishNotificationDependencies()}- /// 仅决定等待任务是否计入防睡眠, 不新增 sleepBlockReason- /// 关闭时, 只有等待任务与没有任务均返回 noTasks+ /// 开关关闭时, 等待任务不计入活动任务数, 沿用 noTasks 判定func setKeepsAwakeWhileWaiting(_ enabled: Bool) {guard enabled != keepsAwakeWhileWaiting else {return@@ -1127,7 +1126,7 @@ final class KeepAliveController: ObservableObject {)}- /// 断连和超时统一先复核授权, retrying 为 nil 时只收敛状态, 不重试租约+ /// 断连和超时后先断开连接并复核授权, retrying 为 nil 时只更新状态, 不重试租约private func handlePowerHelperFailure(_ message: String?, retrying requested: Bool?) {invalidateConnection()guard powerHelperFailureTask == nil else { return }diff --git a/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift b/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swiftindex 46bae42..6742df3 100644--- a/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift@@ -13,7 +13,7 @@ final class KeepAliveDurationLimiter: ObservableObject {@Published private(set) var hasReached = false/// 状态变化后需要重新求值一次防睡眠条件, 参数是这次变化的来源- /// begin pause restart reset 不走这里: 它们的调用方本来就会紧接着求值+ /// begin pause restart reset 的调用方会立即重新求值, 无需触发此回调var onStateChanged: ((LogTrigger) -> Void)?private let defaults: UserDefaultsdiff --git a/CodexBar/Services/KeepAlive/PowerHelperManagerClient.swift b/CodexBar/Services/KeepAlive/PowerHelperManagerClient.swiftindex 0491516..3cfbc05 100644--- a/CodexBar/Services/KeepAlive/PowerHelperManagerClient.swift+++ b/CodexBar/Services/KeepAlive/PowerHelperManagerClient.swift@@ -1,7 +1,7 @@import Foundationimport ServiceManagement-/// 管理进程只在查询或变更注册时启动, 输出与执行时间由共用进程内核约束+/// 管理进程只在查询或变更注册时启动, 输出与执行时间由 BoundedProcess 限制actor PowerHelperManagerClient {private let executeCommand: @Sendable (PowerHelperManagement.Command) async throws -> SMAppService.Statusprivate let retryDelay: Durationdiff --git a/CodexBar/Services/KeepAlive/PowerSourceMonitor.swift b/CodexBar/Services/KeepAlive/PowerSourceMonitor.swiftindex 739c2ff..5a790c5 100644--- a/CodexBar/Services/KeepAlive/PowerSourceMonitor.swift+++ b/CodexBar/Services/KeepAlive/PowerSourceMonitor.swift@@ -36,7 +36,7 @@ nonisolated enum BatteryReading: Equatable {nonisolated struct BatteryStatus: Equatable {let percent: Int- /// 正在靠电池供电; 接着电源时为 false, 此时电量不会被耗干+ /// 系统报告当前由电池供电时为 truelet isOnBattery: Bool}@@ -52,8 +52,7 @@ final class PowerSourceMonitor {private var pollTask: Task<Void, Never>?/// 独立记录启动状态, 注册失败时 runLoopSource 为 nil, 但唤醒观察者已安装private var isMonitoring = false- /// 这台机器确认装着内置电池- /// 硬件不会中途消失, 所以见过之后再读到空列表只能是枚举缺口, 不能当成台式机+ /// 曾检测到内置电池后, 空列表按读取失败处理, 避免暂时枚举不到电池时解除保护private var hasSeenBattery = false/// 回调里持有的是 unretained 指针, 停止监听必须显式做, 由持有者在 stop 时调用diff --git a/CodexBar/Services/Notifications/NotificationService.swift b/CodexBar/Services/Notifications/NotificationService.swiftindex 5d207ee..a4adae0 100644--- a/CodexBar/Services/Notifications/NotificationService.swift+++ b/CodexBar/Services/Notifications/NotificationService.swift@@ -46,9 +46,6 @@ final class NotificationService: NSObject {private var sentDedupKeys: [String]private var submittingDedupKeys = Set<String>()- /// 阈值观察随额度周期重置, key 为 account|limitId|windowId- private var lowQuotaObservations: [String: LowQuotaObservation] = [:]-/// 低额度判定依据的两个设置项/// @Published 在 willSet 中回调, settings 属性尚未更新, 需使用调用方传入的回调参数private struct LowQuotaConditions {@@ -64,8 +61,8 @@ final class NotificationService: NSObject {)}- /// 可信快照中每个额度窗口的重置观察状态; 窗口消失后重现会获得新的生命周期标记- private var quotaWindowResetObservations: [String: QuotaWindowResetObservation] = [:]+ /// 可信快照中每个额度窗口的观察状态; 窗口消失后重现会获得新的生命周期标记+ private var quotaWindowObservations: [String: QuotaWindowObservation] = [:]init(settings: NotificationSettings,@@ -256,7 +253,7 @@ final class NotificationService: NSObject {private func handleSnapshot(_ snapshot: CodexQuotaSnapshot?) {guard let snapshot else {latestQuotaSnapshot = nil- quotaWindowResetObservations.removeAll()+ quotaWindowObservations.removeAll()scheduleNextCreditExpiryCheck(dates: [])return}@@ -283,17 +280,17 @@ final class NotificationService: NSObject {var observedWindowKeys = Set<String>()forEachQuotaWindowWithData(in: snapshot) { window, limit, stateKey inobservedWindowKeys.insert(stateKey)- if quotaWindowResetObservations[stateKey] == nil {- quotaWindowResetObservations[stateKey] = QuotaWindowResetObservation()+ if quotaWindowObservations[stateKey] == nil {+ quotaWindowObservations[stateKey] = QuotaWindowObservation()}processQuotaWindow(window, limit: limit, stateKey: stateKey, lowQuota: lowQuota)}- quotaWindowResetObservations = quotaWindowResetObservations.filter {+ quotaWindowObservations = quotaWindowObservations.filter {observedWindowKeys.contains($0.key)}}- /// 枚举可信快照中有数据的额度窗口, 窗口过滤与 stateKey 口径的唯一定义处+ /// 枚举可信快照中有数据的额度窗口, 在此统一定义窗口过滤和 stateKey 生成规则private func forEachQuotaWindowWithData(in snapshot: CodexQuotaSnapshot,_ body: (QuotaWindow, CodexQuotaLimitSnapshot, String) -> Void@@ -327,7 +324,7 @@ final class NotificationService: NSObject {private func resetLowQuotaObservation(for snapshot: CodexQuotaSnapshot) {forEachQuotaWindowWithData(in: snapshot) { _, _, stateKey in- lowQuotaObservations.removeValue(forKey: stateKey)+ quotaWindowObservations[stateKey]?.lowQuota = LowQuotaObservation()}}@@ -352,14 +349,14 @@ final class NotificationService: NSObject {return}- let crossedThreshold = lowQuotaObservations[stateKey, default: LowQuotaObservation()].observe(+ let crossedThreshold = quotaWindowObservations[stateKey]?.lowQuota.observe(remainingPercent: window.remainingPercent,resetsAt: window.resetsAt,thresholdPercent: lowQuota.thresholdPercent)guard let resetsAt = window.resetsAt,- crossedThreshold,+ crossedThreshold == true,lowQuota.isEnabled else {return}@@ -374,6 +371,7 @@ final class NotificationService: NSObject {AppLog.notification.notice("阈值已穿越: \(details, privacy: .public)")let dedupKey = lowQuotaDedupKey(stateKey: stateKey, resetsAt: resetsAt)+ let lifecycleToken = quotaWindowObservations[stateKey]?.lifecycleTokensend(.lowQuota(limitTitle: limit.title,@@ -383,7 +381,8 @@ final class NotificationService: NSObject {sound: settings.lowQuotaSound,dedupKey: dedupKey,onSubmissionFailure: { [weak self] in- self?.lowQuotaObservations.removeValue(forKey: stateKey)+ guard let self, quotaWindowObservations[stateKey]?.lifecycleToken == lifecycleToken else { return }+ quotaWindowObservations[stateKey]?.lowQuota = LowQuotaObservation()})}@@ -397,14 +396,14 @@ final class NotificationService: NSObject {window: QuotaWindow) {if usedPercent > 0 {- quotaWindowResetObservations[stateKey]?.hasObservedConsumption = true+ quotaWindowObservations[stateKey]?.hasObservedConsumption = true} else if usedPercent == 0,- quotaWindowResetObservations[stateKey]?.hasObservedConsumption == true {+ quotaWindowObservations[stateKey]?.hasObservedConsumption == true {// 归零即消费待重置状态; 开关或授权此刻不可用时不保留补发- quotaWindowResetObservations[stateKey]?.hasObservedConsumption = false+ quotaWindowObservations[stateKey]?.hasObservedConsumption = falseguard settings.canDeliver,settings.isQuotaResetEnabled,- let lifecycleToken = quotaWindowResetObservations[stateKey]?.lifecycleToken else {+ let lifecycleToken = quotaWindowObservations[stateKey]?.lifecycleToken else {return}@@ -422,11 +421,11 @@ final class NotificationService: NSObject {dedupKey: dedupKey,onSubmissionFailure: { [weak self] inguard let self,- quotaWindowResetObservations[stateKey]?.lifecycleToken == lifecycleToken else {+ quotaWindowObservations[stateKey]?.lifecycleToken == lifecycleToken else {return}- quotaWindowResetObservations[stateKey]?.hasObservedConsumption = true+ quotaWindowObservations[stateKey]?.hasObservedConsumption = true})}@@ -512,7 +511,7 @@ final class NotificationService: NSObject {Self.creditExpiryReminderDay(expirationDate: $0, now: now) != nil}- // 相同过期时间的机会合并成一条通知; 按秒分组与去重键口径保持一致+ // 将过期时间相同的机会合并成一条通知, 分组和去重键均精确到秒for (epochSecond, groupedDates) in Dictionary(grouping: dueDates, by: { Self.epoch($0) }) {guard let date = groupedDates.first,let reminderDay = Self.creditExpiryReminderDay(expirationDate: date, now: now) else {@@ -683,7 +682,7 @@ final class NotificationService: NSObject {}}- // 重试全部用尽才记, 循环内的单次失败会重试+ // 重试耗尽后才记录失败日志, 单次失败继续重试let details = LogFields.joined("kind=\(kind)","reason=retryExhausted"@@ -781,10 +780,10 @@ final class NotificationService: NSObject {}}- /// 单个额度窗口的重置观察状态: 记录大于 0 的消耗, 归零时消费并发送- private struct QuotaWindowResetObservation {+ private struct QuotaWindowObservation {/// 窗口生命周期标记, 迟到的发送失败回调据此丢弃let lifecycleToken = UUID()+ var lowQuota = LowQuotaObservation()var hasObservedConsumption = false}}diff --git a/CodexBar/Services/Settings/NotificationSettings.swift b/CodexBar/Services/Settings/NotificationSettings.swiftindex 9ba8ff5..3a528da 100644--- a/CodexBar/Services/Settings/NotificationSettings.swift+++ b/CodexBar/Services/Settings/NotificationSettings.swift@@ -346,7 +346,7 @@ final class NotificationSettings: ObservableObject {return value}- /// 存量值可能指向已移除或不再支持的声音, 这时回落默认音+ /// 已保存的选项可能指向已移除或不再支持的声音, 此时回退到默认音private static func sound(from defaults: UserDefaults, key: String) -> NotificationSoundOption {guard let id = defaults.string(forKey: key),let sound = NotificationSoundOption.option(forID: id) else {diff --git a/CodexBar/Services/Support/AppLog.swift b/CodexBar/Services/Support/AppLog.swiftindex 09ce8a4..7743d46 100644--- a/CodexBar/Services/Support/AppLog.swift+++ b/CodexBar/Services/Support/AppLog.swift@@ -8,7 +8,7 @@ nonisolated enum AppLog {/// App 生命周期, Sparkle 更新, 额度刷新结果与重置次数查询static let app = Logger(subsystem: subsystem, category: "app")static let keepAlive = Logger(subsystem: subsystem, category: "keepalive")- /// 本地 活动事件聚合与维护+ /// 本地活动事件聚合与维护static let history = Logger(subsystem: subsystem, category: "history")/// CloudKit 同步static let sync = Logger(subsystem: subsystem, category: "sync")diff --git a/CodexBar/Services/Support/RefreshTaskCoordinator.swift b/CodexBar/Services/Support/RefreshTaskCoordinator.swiftindex 4189fa3..457b1d1 100644--- a/CodexBar/Services/Support/RefreshTaskCoordinator.swift+++ b/CodexBar/Services/Support/RefreshTaskCoordinator.swift@@ -23,7 +23,7 @@ final nonisolated class RefreshTaskCoordinator: Sendable {return generation}- /// ViewModel 共用的刷新流程: 设置刷新标记后取数, 仅在代际未过期时提交+ /// ViewModel 共用的刷新流程: 设置刷新标记后读取数据, 仅在当前代次仍有效时提交/// 过期刷新结果直接丢弃, 避免慢请求覆盖后启动的新状态@MainActorfunc run<Value>(diff --git a/CodexBar/Services/Sync/SyncCancellation.swift b/CodexBar/Services/Sync/SyncCancellation.swiftindex a4ee3cf..b450cb2 100644--- a/CodexBar/Services/Sync/SyncCancellation.swift+++ b/CodexBar/Services/Sync/SyncCancellation.swift@@ -1,5 +1,5 @@nonisolated enum SyncCancellation {- /// Task 的取消标记不会随开关重新启用而复活+ /// 重新开启同步不会清除 Task 已有的取消标记static func check(isEnabled: () -> Bool) throws {try Task.checkCancellation()guard isEnabled() else { throw CancellationError() }diff --git a/CodexBar/Services/Sync/SyncRecovery.swift b/CodexBar/Services/Sync/SyncRecovery.swiftindex e74e3d7..fcf67ef 100644--- a/CodexBar/Services/Sync/SyncRecovery.swift+++ b/CodexBar/Services/Sync/SyncRecovery.swift@@ -1,7 +1,7 @@import CloudKitimport Foundation-/// 只有已确认的局部错误允许继续, 未识别的云端错误保持停止当前轮次+/// 遇到已确认的局部错误时可以继续, 遇到未识别的云端错误时停止当前轮次nonisolated enum SyncRecovery {enum Failure: Error {case invalidCursordiff --git a/CodexBar/Services/Sync/SyncService.swift b/CodexBar/Services/Sync/SyncService.swiftindex c0519ae..6f58419 100644--- a/CodexBar/Services/Sync/SyncService.swift+++ b/CodexBar/Services/Sync/SyncService.swift@@ -817,7 +817,7 @@ private extension SyncService {}extension SyncService {- /// 设置页读取最近上传时间, 与内部 loadState 使用同一 schemaVersion 校验口径+ /// 设置页读取最近上传时间时, 与内部 loadState 使用相同的 schemaVersion 校验规则nonisolated static func loadLastUploadAt() -> Date? {ActivityDataSyncStore(directoryURL: AppStorage.directoryURL()).loadState().lastUploadAt}diff --git a/CodexBar/Views/Menu/ActivityCard.swift b/CodexBar/Views/Menu/ActivityCard.swiftindex d5782a3..361005e 100644--- a/CodexBar/Views/Menu/ActivityCard.swift+++ b/CodexBar/Views/Menu/ActivityCard.swift@@ -4,15 +4,33 @@ import SwiftUI/// 活动和防睡眠状态由卡片自行观察, 避免刷新整个菜单树struct ActivityCard: View {@ObservedObject var activityMonitor: ActivityMonitor- @ObservedObject var presentationState: ActivityCenterPresentationState+ @ObservedObject var centerPresentation: ActivityCenterPresentationState+ @ObservedObject var cardPresentation: ActivityCardPresentationState@ObservedObject var keepAliveController: KeepAliveController- let onTaskCenterTap: (ScreenFrameProvider) -> Void+ let onTaskCenterTap: (ActivityCenterPanelAnchor) -> Void@Environment(\.contentAnimationsEnabled) private var allowsAnimations- @State private var frameProvider = ScreenFrameProvider()+ @State private var frameProvider = ActivityCenterPanelAnchor()@State private var isHovered = false- @State private var wrappedHeaderTaskIDs: Set<UUID> = []+ @State private var wrappedHeaderKeys: Set<HeaderWrappingKey> = []@State private var retainedContent: ActivityCardContent?@State private var outgoingContent: ActivityCardContent?+ @State private var cardSize = CGSize.zero+ @State private var swipe = ActivityCardSwipe()+ @State private var swipeContent: ActivityCardSwipeContent?+ @State private var gestureOwner = UUID()+ @State private var incomingOffset: CGFloat = 0+ @State private var outgoingOffset: CGFloat = 0+ @State private var incomingOpacity = 1.0+ @State private var outgoingOpacity = 1.0+ @State private var animationGeneration = 0++ private var selection: ActivityCardSelection {+ cardPresentation.selection+ }++ private var cardWidth: CGFloat {+ cardSize.width+ }private var snapshot: ActivitySnapshot {activityMonitor.snapshot@@ -23,11 +41,11 @@ struct ActivityCard: View {}private var timelineDate: Date {- presentationState.timelineDate+ centerPresentation.timelineDate}private var isTaskCenterPresented: Bool {- presentationState.isPresented+ centerPresentation.isPresented}/// 活动源不可用时隐藏防睡眠徽标, 保持状态一致@@ -36,9 +54,17 @@ struct ActivityCard: View {}private var currentContent: ActivityCardContent? {- guard snapshot.hasTaskCenterContent || showsUnavailableState else { return nil }- var value = content(at: timelineDate)+ guard selection.current != nil || showsUnavailableState else { return nil }+ return displayContent(for: showsUnavailableState ? .idle : (selection.current ?? .idle))+ }++ private func displayContent(for activity: CodexPrimaryActivity) -> ActivityCardContent {+ var value = content(for: activity, at: timelineDate)+ value.selectionID = activity.cardSelectionIDvalue.showsKeepAliveBadge = showsKeepAliveBadge+ value.positionText = selection.positionText(for: value.selectionID)+ value.hasPin = selection.pinnedID != nil && selection.current != nil+ value.isPinned = selection.pinnedID != nil && selection.pinnedID == value.selectionIDreturn value}@@ -49,7 +75,7 @@ struct ActivityCard: View {Button {onTaskCenterTap(frameProvider)} label: {- if let content = currentContent ?? retainedContent {+ if let content = retainedContent ?? currentContent {card(content)}}@@ -57,46 +83,212 @@ struct ActivityCard: View {.disabled(!snapshot.hasTaskCenterContent).contentShape(Rectangle()).background {- ScreenFrameReader(provider: frameProvider)+ ActivityCenterPanelAnchorReader(anchor: frameProvider)+ ActivityCardEvents(+ isEnabled: selection.isVisible && selection.current != nil && !showsUnavailableState,+ onSwipe: handleSwipe,+ onTogglePin: {+ cancelSwipe()+ cardPresentation.togglePin()+ }+ )}+ .onGeometryChange(for: CGFloat.self) { geometry in+ geometry.frame(in: .named(ActivityCenterPanelAnchor.coordinateSpace)).minY+ } action: { frameProvider.updateTopOffset($0) }.onHover { isHovered = $0 }- .onChange(of: currentContent, initial: true) { _, content in- // 退场期间保留最后一份展示内容, 不把正在收回的任务替换成空状态- if let content {- if allowsAnimations, let previous = retainedContent, content.requiresCrossfade(from: previous) {- outgoingContent = previous- }- retainedContent = content+ .onChange(of: currentContent, initial: true) { _, content in updateContent(content) }+ .onChange(of: allowsAnimations) { _, enabled in+ if !enabled {+ completeSwipe()+ settleTransition()+ cardPresentation.setGestureActive(false, owner: gestureOwner)+ retainedContent = currentContent}}- .task(id: outgoingContent) {- guard outgoingContent != nil else { return }- // 先保留旧内容的完整一帧, 下一次更新只交接透明度, 不参与自然高度测量- await Task.yield()- guard !Task.isCancelled else { return }- withAnimation(allowsAnimations ? .easeInOut(duration: 0.2) : nil) {- outgoingContent = nil+ .onChange(of: selection.isVisible) { _, visible in+ if !visible {+ cancelSwipe()+ }+ }+ .onChange(of: selection.isGestureActive) { _, active in+ if !active {+ cancelSwipe()}}+ .onDisappear { cancelSwipe() }+ .task(id: swipe.settlement) {+ guard let settlement = swipe.settlement else { return }+ do {+ try await Task.sleep(for: .seconds(max(0, settlement.duration - Date().timeIntervalSince(settlement.startedAt))))+ } catch { return }+ guard swipe.settlement == settlement else { return }+ completeSwipe()+ }.onChange(of: retainedHeaderTaskIDs) { _, retainedIDs in- wrappedHeaderTaskIDs.formIntersection(retainedIDs)+ wrappedHeaderKeys = wrappedHeaderKeys.filter { retainedIDs.contains($0.taskID) }+ }+ }++ // MARK: - 交互翻页++ private func handleSwipe(_ event: ActivityCardEvents.SwipeEvent) {+ switch event {+ case .began:+ beginSwipe()+ case let .changed(delta):+ swipe.move(by: delta, width: cardWidth)+ case let .ended(velocity):+ swipe.end(velocity: velocity, width: cardWidth, cancelled: false, now: Date())+ if !allowsAnimations {+ completeSwipe()+ }+ case .cancelled:+ swipe.end(velocity: 0, width: cardWidth, cancelled: true, now: Date())+ if !allowsAnimations {+ completeSwipe()+ }+ case let .step(direction):+ completeSwipe()+ guard selection.carouselActivities.count > 1 else { return }+ cardPresentation.setGestureActive(true, owner: gestureOwner)+ cardPresentation.swipe(direction)+ updateContent(currentContent)+ }+ }++ private func beginSwipe() {+ guard selection.isVisible, selection.carouselActivities.count > 1, cardWidth > 0, cardSize.height > 0 else { return }+ cardPresentation.setGestureActive(true, owner: gestureOwner)+ let previous = swipeContent+ let step = swipe.begin(width: cardWidth, now: Date())+ if step != 0, let id = previous?.content(at: step).selectionID {+ cardPresentation.selectAfterSwipe(id, owner: gestureOwner)+ }+ let carousel = selection.carouselActivities+ guard let index = carousel.firstIndex(where: { $0.cardSelectionID == selection.selectedID }) else {+ cancelSwipe()+ return+ }+ func page(_ step: Int) -> ActivityCardContent {+ let activity = carousel[(index + step + carousel.count) % carousel.count]+ return previous?.matching(activity.cardSelectionID) ?? displayContent(for: activity)+ }+ swipeContent = ActivityCardSwipeContent(+ previous: page(-1), current: page(0), next: page(1)+ )+ settleTransition()+ }++ private func completeSwipe() {+ guard let pages = swipeContent else { return }+ let step = swipe.settlement?.step ?? 0+ if step != 0, let id = pages.content(at: step).selectionID {+ cardPresentation.selectAfterSwipe(id, owner: gestureOwner)+ }+ clearSwipe()+ cardPresentation.setGestureActive(false, owner: gestureOwner)+ retainedContent = currentContent+ }++ private func cancelSwipe() {+ guard swipe.isActive || swipeContent != nil || outgoingContent != nil || selection.isGestureActive else { return }+ clearSwipe()+ settleTransition()+ cardPresentation.setGestureActive(false, owner: gestureOwner)+ }++ private func clearSwipe() {+ swipe = ActivityCardSwipe()+ swipeContent = nil+ }++ private func settleTransition() {+ animationGeneration += 1+ var transaction = Transaction()+ transaction.disablesAnimations = true+ withTransaction(transaction) {+ outgoingContent = nil+ incomingOffset = 0+ outgoingOffset = 0+ incomingOpacity = 1+ outgoingOpacity = 1+ }+ }++ private func updateContent(_ content: ActivityCardContent?) {+ if let pages = swipeContent {+ let available = Set(selection.activities.compactMap(\.cardSelectionID))+ if selection.isGestureActive, !showsUnavailableState, selection.selectedID == pages.current.selectionID,+ [pages.previous, pages.current, pages.next].allSatisfy({ $0.selectionID.map(available.contains) == true }) {+ return+ }+ cancelSwipe()+ }+ // 退场期间保留最后一份内容, 避免正在收回的区域变为空卡片+ guard let content else { return }+ guard let previous = retainedContent, content.requiresContentTransition(from: previous) else {+ retainedContent = content+ if outgoingContent == nil {+ cardPresentation.setGestureActive(false, owner: gestureOwner)+ }+ return+ }+ settleTransition()+ guard allowsAnimations, cardWidth > 0 else {+ retainedContent = content+ cardPresentation.setGestureActive(false, owner: gestureOwner)+ return+ }+ let generation = animationGeneration+ // 手动切换的方向只用于不同轮播项之间, 同一 thread 的新 turn 仍沿用淡入淡出+ let slides = selection.transitionDirection != nil+ && content.selectionID != nil && previous.selectionID != nil && content.selectionID != previous.selectionID+ let distance = CGFloat(selection.transitionDirection ?? 0) * cardWidth+ var transaction = Transaction()+ transaction.disablesAnimations = true+ withTransaction(transaction) {+ outgoingContent = previous+ retainedContent = content+ incomingOffset = slides ? distance : 0+ incomingOpacity = slides ? 1 : 0+ }+ Task { @MainActor in+ await Task.yield()+ guard generation == animationGeneration else { return }+ let animation = slides+ ? Animation.timingCurve(0.2, 0.8, 0.2, 1, duration: 0.3)+ : .easeInOut(duration: 0.2)+ withAnimation(animation, completionCriteria: .removed) {+ incomingOffset = 0+ incomingOpacity = 1+ outgoingOffset = slides ? -distance : 0+ outgoingOpacity = slides ? 1 : 0+ } completion: {+ guard generation == animationGeneration else { return }+ outgoingContent = nil+ if slides {+ cardPresentation.setGestureActive(false, owner: gestureOwner)+ }+ }}}private func card(_ content: ActivityCardContent) -> some View {- cardContent(content)+ cardPages(content).background {GeometryReader { geometry in- Color.clear.preference(key: ActivityCardNaturalHeightKey.self, value: geometry.size.height)+ Color.clear.preference(+ key: ActivityCardNaturalHeightKey.self,+ value: .init(height: geometry.size.height, isInteractive: swipeContent != nil)+ )}}- .opacity(outgoingContent == nil ? 1 : 0)- .overlay(alignment: .topLeading) {- if let outgoingContent {- cardContent(outgoingContent)- .transition(.opacity)- .allowsHitTesting(false)+ .onGeometryChange(for: CGSize.self) { $0.size } action: { size in+ if cardWidth != size.width {+ cancelSwipe()}+ cardSize = size}// 外层可以收起整个区域, 内部文字始终按自然高度排版.frame(minHeight: 0, maxHeight: .infinity, alignment: .topLeading)@@ -114,12 +306,43 @@ struct ActivityCard: View {.animation(.codexStatus, value: isHovered).animation(.codexStatus, value: isTaskCenterPresented)}+ .overlay {+ ActivityCardWaitingEdges(+ left: selection.waitingSides.left,+ right: selection.waitingSides.right,+ animates: allowsAnimations+ )+ .clipShape(RoundedRectangle(cornerRadius: MenuMetrics.panelCornerRadius))+ .allowsHitTesting(false)+ }+ }++ @ViewBuilder+ private func cardPages(_ content: ActivityCardContent) -> some View {+ if let pages = swipeContent {+ ActivityCardSwipePages(swipe: swipe, width: cardWidth) { step in+ cardContent(pages.content(at: step))+ }+ } else {+ cardContent(content)+ .offset(x: incomingOffset)+ .opacity(incomingOpacity)+ .overlay(alignment: .topLeading) {+ if let outgoingContent {+ cardContent(outgoingContent)+ .frame(width: cardWidth)+ .offset(x: outgoingOffset)+ .opacity(outgoingOpacity)+ .allowsHitTesting(false)+ }+ }+ }}private func cardContent(_ content: ActivityCardContent) -> some View {VStack(alignment: .leading, spacing: 8) {statusRow(content)- // 切换任务时重新建立文本状态, 不让前一个任务的数字过渡穿过新布局+ // 切换任务时重建文本状态, 避免前一个任务的数字动画影响新布局.id(content.taskID).transition(.identity)if let tokenUsage = content.tokenUsage {@@ -132,8 +355,10 @@ struct ActivityCard: View {.padding(.vertical, 12).frame(maxWidth: .infinity).fixedSize(horizontal: false, vertical: true)- // 内容只上报自然高度, 显示和尺寸变化都由区域容器统一驱动+ // 文字保持自然排版, 页间位移和可见高度由外层控制.transaction { $0.animation = nil }+ // 在内容事务之外统一处理位移, 避免内部文字动画覆盖整张卡片的推入推出+ .geometryGroup()}private func statusRow(_ content: ActivityCardContent) -> some View {@@ -179,28 +404,15 @@ struct ActivityCard: View {}private func statusHeader(_ content: ActivityCardContent) -> some View {- HStack(alignment: .firstTextBaseline, spacing: 10) {- ActivitySummaryText(- components: content.headerLines,- primaryLineLimit: 1,- primaryTruncationMode: .middle,- supplementaryLineLimit: 1,- singleLineWidthReserve: Metrics.headerWidthReserve,- wrappedLayout: wrappedHeaderLayout(for: content.taskID)- )- .font(MenuMetrics.titleFont)- // 标题与数量徽标预留相同的上下空间, 显隐徽标时保持首行基线稳定- .padding(.vertical, Metrics.headerVerticalPadding)- .foregroundStyle(Color.codexLabel)- .numericTransition(value: content.header)- .fixedSize(horizontal: false, vertical: true)- .clipped()- .frame(maxWidth: .infinity, alignment: .leading)- if content.otherTaskCount > 0 || content.showsKeepAliveBadge {- statusBadges(content)- .fixedSize()- }- }+ ActivityCardHeader(+ components: content.headerLines,+ projectName: content.projectName,+ positionText: content.positionText,+ hasPin: content.hasPin,+ isPinned: content.isPinned,+ showsKeepAliveBadge: content.showsKeepAliveBadge,+ usesWrappedLayout: wrappedHeaderLayout(for: content)+ )}private var retainedHeaderTaskIDs: Set<UUID> {@@ -211,51 +423,32 @@ struct ActivityCard: View {.union([retainedContent?.taskID].compactMap(\.self))}- private func wrappedHeaderLayout(for taskID: UUID?) -> Binding<Bool>? {- guard let taskID else { return nil }+ /// 徽标组合变化会改变剩余宽度, 相同组合仍保留任务的换行状态+ private struct HeaderWrappingKey: Hashable {+ let taskID: UUID+ let hasPin: Bool+ let positionLength: Int+ let showsKeepAliveBadge: Bool+ }++ private func wrappedHeaderLayout(for content: ActivityCardContent) -> Binding<Bool>? {+ guard let taskID = content.taskID else { return nil }+ let key = HeaderWrappingKey(+ taskID: taskID,+ hasPin: content.hasPin,+ positionLength: content.positionText?.count ?? 0,+ showsKeepAliveBadge: content.showsKeepAliveBadge+ )return Binding(- get: { wrappedHeaderTaskIDs.contains(taskID) },+ get: { wrappedHeaderKeys.contains(key) },set: { isWrapped inif isWrapped {- wrappedHeaderTaskIDs.insert(taskID)+ wrappedHeaderKeys.insert(key)}})}- private func statusBadges(_ content: ActivityCardContent) -> some View {- HStack(alignment: .firstTextBaseline, spacing: 10) {- if content.otherTaskCount > 0 {- Text(verbatim: "+\(content.otherTaskCount)")- .font(MenuMetrics.badgeFont)- // 必须是具体 Color, 层级样式在 numericText 的过渡层里会被重新解析成别的层级- .foregroundStyle(Color.codexSecondaryLabel)- .numericTransition(value: content.otherTaskCount, comparison: Double(content.otherTaskCount))- .padding(.horizontal, 6)- .padding(.vertical, Metrics.headerVerticalPadding)- .background(.secondary.opacity(0.12), in: Capsule())- .transition(.opacity)- .help(String(localized: "activity.summary.other-task-count", defaultValue: "\(content.otherTaskCount, specifier: "%lld")"))- }- // 防睡眠由任务状态驱动, 徽标跟随活动卡片展示- if content.showsKeepAliveBadge {- // 隐藏或关闭动画效果时移除整个旋转视图, 避免保留持续渲染调度- Group {- if allowsAnimations {- RotatingKeepAliveSun()- } else {- Image(systemName: "sun.max.fill")- }- }- .font(.system(size: 11, weight: .semibold))- .foregroundStyle(Color.teal)- .transition(.opacity)- }- }- .animation(.codexStatus, value: content.showsKeepAliveBadge)- .animation(.codexStatus, value: content.otherTaskCount)- }-private func tokenUsageMetrics(_ tokenUsage: TokenUsage) -> some View {ActivityTokenRowLayout {HStack(alignment: .top, spacing: 0) {@@ -296,8 +489,8 @@ struct ActivityCard: View {// MARK: - 展示内容- private func content(at now: Date) -> ActivityCardContent {- switch snapshot.panelPrimaryActivity {+ private func content(for activity: CodexPrimaryActivity, at now: Date) -> ActivityCardContent {+ switch activity {case let .waiting(task):return activeContent(for: task,@@ -319,10 +512,10 @@ struct ActivityCard: View {)return ActivityCardContent(taskID: completion.taskID ?? completion.id,+ projectName: completion.projectName,symbolName: "checkmark.circle.fill",tint: .green,detail: nil,- otherTaskCount: 0,tokenUsage: completion.tokenUsage,header: [completion.projectName ?? String(localized: "common.codex"),@@ -336,10 +529,10 @@ struct ActivityCard: View {)return ActivityCardContent(taskID: termination.taskID ?? termination.id,+ projectName: termination.projectName,symbolName: "xmark.circle.fill",tint: .red,detail: ActivityLiveLabel(termination.isFailure ? "failed" : "interrupted").text,- otherTaskCount: 0,tokenUsage: termination.tokenUsage,header: [termination.projectName ?? String(localized: "common.codex"),@@ -351,7 +544,6 @@ struct ActivityCard: View {symbolName: "bubble.left.and.exclamationmark.bubble.right",tint: .red,detail: activityMonitor.sourcePresentation?.text,- otherTaskCount: 0,header: [String(localized: "common.codex")])}@@ -366,10 +558,10 @@ struct ActivityCard: View {let summary = ActivityDisplayFormat.liveSummaryComponents(for: task, now: timelineDate, waiting: waiting)return ActivityCardContent(taskID: task.id,+ projectName: task.projectName,symbolName: symbolName,tint: tint,detail: ActivityDisplayFormat.liveStatus(for: task, waiting: waiting),- otherTaskCount: otherTaskCount,tokenUsage: task.tokenUsage,header: [task.projectName ?? String(localized: "common.codex"),@@ -381,29 +573,6 @@ struct ActivityCard: View {statusTextEffect: allowsAnimations ? (waiting ? .ionizing(taskID: task.id) : .shimmer) : .none)}-- private var otherTaskCount: Int {- max(0, snapshot.activeCount - 1)- }-- private enum Metrics {- static let headerVerticalPadding: CGFloat = 3- /// 单行排版为时间文案增长预留宽度- static let headerWidthReserve: CGFloat = 32- }-}--// MARK: - 动画--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 }- }}// MARK: - 辅助视图与展示模型@@ -432,21 +601,39 @@ private struct ActivityCardButtonStyle: ButtonStyle {}}+private struct ActivityCardSwipeContent {+ let previous: ActivityCardContent+ let current: ActivityCardContent+ let next: ActivityCardContent++ func content(at step: Int) -> ActivityCardContent {+ step == 0 ? current : (step < 0 ? previous : next)+ }++ func matching(_ id: String?) -> ActivityCardContent? {+ [current, previous, next].first { $0.selectionID == id }+ }+}+private struct ActivityCardContent: Equatable {var taskID: UUID?+ var selectionID: String?+ var projectName: String?let symbolName: Stringlet tint: Colorlet detail: String?- let otherTaskCount: Intvar tokenUsage: TokenUsage?let header: [String]var recent: String?var detailSupplement: String?var showsCurrentEvent = falsevar showsKeepAliveBadge = false+ var positionText: String?+ var hasPin = false+ var isPinned = falsevar statusTextEffect = ActivityStatusText.Effect.none- func requiresCrossfade(from previous: Self) -> Bool {+ func requiresContentTransition(from previous: Self) -> Bool {taskID != previous.taskID || symbolName != previous.symbolName|| (tokenUsage == nil) != (previous.tokenUsage == nil)|| (detail == nil) != (previous.detail == nil)diff --git a/CodexBar/Views/Menu/ActivityCardEvents.swift b/CodexBar/Views/Menu/ActivityCardEvents.swiftnew file mode 100644index 0000000..fc8fad7--- /dev/null+++ b/CodexBar/Views/Menu/ActivityCardEvents.swift@@ -0,0 +1,190 @@+import AppKit+import SwiftUI++struct ActivityCardEvents: NSViewRepresentable {+ let isEnabled: Bool+ let onSwipe: (SwipeEvent) -> Void+ let onTogglePin: () -> Void++ enum SwipeEvent: Equatable {+ case began+ case changed(CGFloat)+ case ended(velocity: CGFloat)+ case cancelled+ case step(Int)+ }++ func makeNSView(context _: Context) -> EventRegion {+ EventRegion()+ }++ func updateNSView(_ view: EventRegion, context _: Context) {+ view.onSwipe = onSwipe+ view.onTogglePin = onTogglePin+ view.isEnabled = isEnabled+ }++ static func dismantleNSView(_ view: EventRegion, coordinator _: ()) {+ view.removeMonitor()+ }++ final class EventRegion: NSView {+ var isEnabled = false {+ didSet {+ if !isEnabled {+ resetInteraction()+ }+ }+ }++ var onSwipe: ((SwipeEvent) -> Void)?+ var onTogglePin: (() -> Void)?+ private var ownsGesture = false+ private var rightMouseBeganInside = false+ private var monitor: Any?+ private var lastTimestamp: TimeInterval?+ private var velocity: CGFloat = 0+ private var unphasedEndTask: Task<Void, Never>?+ private var cancellationTask: Task<Void, Never>?++ override func hitTest(_: NSPoint) -> NSView? {+ nil+ }++ override func viewDidMoveToWindow() {+ super.viewDidMoveToWindow()+ removeMonitor()+ guard window != nil else { return }+ monitor = NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel, .rightMouseDown, .rightMouseUp]) { [weak self] event in+ let consumed = MainActor.assumeIsolated {+ guard let self else { return false }+ return self.handle(event) == nil+ }+ return consumed ? nil : event+ }+ }++ func removeMonitor() {+ if let monitor {+ NSEvent.removeMonitor(monitor)+ }+ monitor = nil+ resetInteraction()+ }++ private func resetInteraction() {+ rightMouseBeganInside = false+ finish(.cancelled, deferringNotification: true)+ }++ private func finish(_ event: SwipeEvent, deferringNotification: Bool = false) {+ unphasedEndTask?.cancel()+ unphasedEndTask = nil+ lastTimestamp = nil+ velocity = 0+ // 隐藏宿主的清理不能取消另一个宿主正在进行的手势+ guard ownsGesture else { return }+ ownsGesture = false+ if deferringNotification {+ let callback = onSwipe+ // updateNSView 和 dismantleNSView 仍在 SwiftUI 更新内, 退出后再通知视图清理状态+ cancellationTask = Task { @MainActor [weak self] in+ await Task.yield()+ guard !Task.isCancelled else { return }+ self?.cancellationTask = nil+ callback?(event)+ }+ } else {+ onSwipe?(event)+ }+ }++ private func handle(_ event: NSEvent) -> NSEvent? {+ guard isEnabled, let window, window.isVisible, event.window === window else {+ resetInteraction()+ return event+ }+ let point = convert(event.locationInWindow, from: nil)+ let inside = !isHiddenOrHasHiddenAncestor && visibleRect.contains(point)+ if event.type == .rightMouseDown {+ rightMouseBeganInside = inside+ return inside ? nil : event+ }+ if event.type == .rightMouseUp {+ let beganInside = rightMouseBeganInside+ rightMouseBeganInside = false+ guard beganInside, inside else { return event }+ onTogglePin?()+ return nil+ }++ let shiftsVertical = event.modifierFlags.contains(.shift) && abs(event.scrollingDeltaY) > abs(event.scrollingDeltaX)+ let delta = shiftsVertical ? event.scrollingDeltaY : event.scrollingDeltaX+ // 一旦取得横向手势, 后续斜向位移仍沿横轴处理, 直到结束或取消+ guard ownsGesture || shiftsVertical || abs(delta) > abs(event.scrollingDeltaY) else { return event }+ let consumed = scroll(+ delta: delta, timestamp: event.timestamp, phase: event.phase,+ momentum: event.momentumPhase, precise: event.hasPreciseScrollingDeltas, inside: inside+ )+ return consumed ? nil : event+ }++ @discardableResult+ func scroll(delta: CGFloat, timestamp: TimeInterval, phase: NSEvent.Phase, momentum: NSEvent.Phase = [], precise: Bool = true, inside: Bool = true) -> Bool {+ guard isEnabled else { return false }+ if phase.contains(.cancelled) || !inside {+ finish(.cancelled)+ return inside+ }+ if phase.contains(.ended) {+ if ownsGesture, delta.isFinite, delta != 0, timestamp.isFinite {+ move(by: delta, timestamp: timestamp)+ }+ let recentVelocity = lastTimestamp.map { timestamp - $0 < 0.1 ? velocity : 0 } ?? 0+ finish(.ended(velocity: recentVelocity))+ return inside+ }+ // 先结束手指拖动阶段, 惯性不能开启新手势, 也不能触发第二次翻页+ guard momentum.isEmpty, delta.isFinite, timestamp.isFinite, delta != 0 else { return inside }+ if !precise, phase.isEmpty {+ finish(.cancelled)+ if abs(delta) >= 0.5 {+ onSwipe?(.step(delta < 0 ? 1 : -1))+ }+ return true+ }+ if !ownsGesture {+ cancellationTask?.cancel()+ cancellationTask = nil+ ownsGesture = true+ onSwipe?(.began)+ }+ move(by: delta, timestamp: timestamp)+ unphasedEndTask?.cancel()+ unphasedEndTask = nil+ if phase.isEmpty {+ scheduleUnphasedEnd()+ }+ return true+ }++ private func move(by delta: CGFloat, timestamp: TimeInterval) {+ if let previous = lastTimestamp, timestamp > previous {+ let interval = timestamp - previous+ velocity = interval <= 0.1 ? 0.65 * delta / max(1.0 / 240, interval) + 0.35 * velocity : 0+ }+ lastTimestamp = timestamp+ onSwipe?(.changed(delta))+ }++ private func scheduleUnphasedEnd() {+ // 精确滚轮若没有阶段事件, 用输入序列结束代替抬手, 不保留惯性速度+ unphasedEndTask = Task { @MainActor [weak self] in+ do {+ try await Task.sleep(for: .milliseconds(160))+ } catch { return }+ self?.finish(.ended(velocity: 0))+ }+ }+ }+}diff --git a/CodexBar/Views/Menu/ActivityCardHeader.swift b/CodexBar/Views/Menu/ActivityCardHeader.swiftnew file mode 100644index 0000000..7d34507--- /dev/null+++ b/CodexBar/Views/Menu/ActivityCardHeader.swift@@ -0,0 +1,106 @@+import SwiftUI++struct ActivityCardHeader: View {+ let components: [String]+ let projectName: String?+ let positionText: String?+ let hasPin: Bool+ let isPinned: Bool+ let showsKeepAliveBadge: Bool+ var usesWrappedLayout: Binding<Bool>?+ @Environment(\.contentAnimationsEnabled) private var allowsAnimations++ var body: some View {+ HStack(alignment: .firstTextBaseline, spacing: 10) {+ ActivitySummaryText(+ components: components,+ primaryLineLimit: 1,+ primaryTruncationMode: .middle,+ supplementaryLineLimit: 1,+ singleLineWidthReserve: 32,+ usesWrappedLayout: usesWrappedLayout,+ primaryHelp: projectName+ )+ .font(MenuMetrics.titleFont)+ .padding(.vertical, 3)+ .foregroundStyle(Color.codexLabel)+ .numericTransition(value: components)+ .fixedSize(horizontal: false, vertical: true)+ .clipped()+ .frame(maxWidth: .infinity, alignment: .leading)+ if hasPin || positionText != nil || showsKeepAliveBadge {+ badges.fixedSize()+ .transition(.opacity)+ }+ }+ .animation(allowsAnimations ? .easeInOut(duration: 0.25) : nil, value: hasPin)+ }++ private var badges: some View {+ HStack(alignment: .firstTextBaseline, spacing: 10) {+ if hasPin {+ // 保留数字徽标的行高和基线, 无位置数字时图标也不改变对齐位置+ Text(verbatim: "0")+ .font(MenuMetrics.badgeFont)+ .hidden()+ .frame(width: 10)+ .overlay {+ Image(systemName: isPinned ? "pin.fill" : "pin")+ .resizable()+ .scaledToFit()+ .font(.system(size: 10, weight: .semibold))+ .foregroundStyle(isPinned ? Color.accentColor : Color.codexSecondaryLabel)+ .frame(width: 10, height: 10)+ }+ .padding(.vertical, 3)+ .transition(.opacity)+ }+ if let positionText {+ Text(verbatim: positionText)+ .font(MenuMetrics.badgeFont.monospacedDigit())+ .foregroundStyle(Color.codexSecondaryLabel)+ .numericTransition(value: positionText)+ .padding(.horizontal, 6)+ .padding(.vertical, 3)+ .background(.secondary.opacity(0.12), in: Capsule())+ }+ if showsKeepAliveBadge {+ Text(verbatim: "0")+ .font(MenuMetrics.badgeFont)+ .hidden()+ .frame(width: 10)+ .overlay {+ Group {+ if allowsAnimations {+ RotatingKeepAliveSun()+ } else {+ Image(systemName: "sun.max.fill")+ .resizable()+ .scaledToFit()+ }+ }+ .font(.system(size: 10, weight: .semibold))+ .foregroundStyle(Color.teal)+ .frame(width: 10, height: 10)+ }+ .padding(.vertical, 3)+ .transition(.opacity)+ }+ }+ .animation(allowsAnimations ? .codexStatus : nil, value: showsKeepAliveBadge)+ .allowsHitTesting(false)+ }+}++private struct RotatingKeepAliveSun: View {+ @State private var isRotating = false++ var body: some View {+ Image(systemName: "sun.max.fill")+ .resizable()+ .scaledToFit()+ .rotationEffect(.degrees(isRotating ? 360 : 0))+ .animation(.linear(duration: 2).repeatForever(autoreverses: false), value: isRotating)+ .onAppear { isRotating = true }+ }+}diff --git a/CodexBar/Views/Menu/ActivityCardSwipe.swift b/CodexBar/Views/Menu/ActivityCardSwipe.swiftnew file mode 100644index 0000000..7e0dc1b--- /dev/null+++ b/CodexBar/Views/Menu/ActivityCardSwipe.swift@@ -0,0 +1,100 @@+import SwiftUI++/// 拖动和收尾共用位移, 新手势可以在收尾途中接管当前画面+nonisolated struct ActivityCardSwipe: Equatable {+ private(set) var isDragging = false+ private(set) var settlement: Settlement?+ private var dragOffset: CGFloat = 0++ var isActive: Bool {+ isDragging || settlement != nil+ }++ func offset(at now: Date) -> CGFloat {+ guard let settlement else { return dragOffset }+ let progress = min(1, max(0, now.timeIntervalSince(settlement.startedAt) / settlement.duration))+ let remaining = 1 - progress+ return settlement.target + (settlement.origin - settlement.target) * remaining * remaining * remaining+ }++ /// 已确认的翻页在下一次拖动开始时换基准, 两侧内容的屏幕位置保持不变+ mutating func begin(width: CGFloat, now: Date) -> Int {+ let step = settlement?.step ?? 0+ dragOffset = offset(at: now) + CGFloat(step) * width+ settlement = nil+ isDragging = true+ return step+ }++ mutating func move(by delta: CGFloat, width: CGFloat) {+ guard isDragging, delta.isFinite, width.isFinite, width > 0 else { return }+ dragOffset = min(width, max(-width, dragOffset + delta))+ }++ mutating func end(velocity: CGFloat, width: CGFloat, cancelled: Bool, now: Date) {+ guard isDragging, width.isFinite, width > 0 else { return }+ let velocity = velocity.isFinite ? min(width * 5, max(-width * 5, velocity)) : 0+ let projected = dragOffset + velocity * 0.15+ let commits = !cancelled && abs(dragOffset) >= min(8, width * 0.03)+ && projected * dragOffset > 0 && abs(projected) >= width * 0.25+ let step = commits ? (dragOffset < 0 ? 1 : -1) : 0+ let target = -CGFloat(step) * width+ settlement = Settlement(+ origin: dragOffset, target: target, step: step, startedAt: now,+ duration: max(0.08, min(0.24, Double(abs(target - dragOffset) / width) * 0.3))+ )+ isDragging = false+ }++ struct Settlement: Hashable {+ let origin: CGFloat+ let target: CGFloat+ let step: Int+ let startedAt: Date+ let duration: TimeInterval+ }+}++/// 横向位移和容器高度共用进度, 拖动结束后沿用同一高度计算方式完成收尾+struct ActivityCardSwipePages<Content: View>: View {+ let swipe: ActivityCardSwipe+ let width: CGFloat+ @ViewBuilder let content: (Int) -> Content++ var body: some View {+ TimelineView(.animation(paused: swipe.settlement == nil)) { timeline in+ ActivityCardSwipeLayout(width: width, offset: swipe.offset(at: timeline.date)) {+ content(-1)+ content(0)+ content(1)+ }+ }+ .transaction { $0.animation = nil }+ }+}++private struct ActivityCardSwipeLayout: Layout {+ let width: CGFloat+ let offset: CGFloat++ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache _: inout ()) -> CGSize {+ let pageWidth = proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? width+ guard subviews.count == 3, pageWidth > 0 else { return .zero }+ let proposal = ProposedViewSize(width: pageWidth, height: nil)+ let currentHeight = subviews[1].sizeThatFits(proposal).height+ let adjacentHeight = subviews[offset < 0 ? 2 : 0].sizeThatFits(proposal).height+ let progress = min(1, abs(offset) / pageWidth)+ return CGSize(width: pageWidth, height: currentHeight + (adjacentHeight - currentHeight) * progress)+ }++ func placeSubviews(in bounds: CGRect, proposal _: ProposedViewSize, subviews: Subviews, cache _: inout ()) {+ for (index, subview) in subviews.enumerated() {+ // 每页按自然高度排版, 容器只改变可见范围, 避免文字随高度压缩或居中移动+ subview.place(+ at: CGPoint(x: bounds.minX + CGFloat(index - 1) * bounds.width + offset, y: bounds.minY),+ anchor: .topLeading,+ proposal: ProposedViewSize(width: bounds.width, height: nil)+ )+ }+ }+}diff --git a/CodexBar/Views/Menu/ActivityCardWaitingEdges.swift b/CodexBar/Views/Menu/ActivityCardWaitingEdges.swiftnew file mode 100644index 0000000..f3f0d7f--- /dev/null+++ b/CodexBar/Views/Menu/ActivityCardWaitingEdges.swift@@ -0,0 +1,85 @@+import SwiftUI++struct ActivityCardWaitingEdges: View {+ let left: Bool+ let right: Bool+ let animates: Bool+ @State private var startedAt = Date()++ var body: some View {+ // 两侧共用呼吸相位, 改变方向时只交接透明度+ TimelineView(.animation(minimumInterval: 1.0 / 30, paused: !animates || (!left && !right))) { timeline in+ let elapsed = animates ? timeline.date.timeIntervalSince(startedAt) : 0+ HStack(spacing: 0) {+ ActivityCardWaitingEdge(isLeading: true, elapsed: elapsed)+ .frame(width: 10)+ .opacity(left ? 1 : 0)+ Spacer(minLength: 0)+ ActivityCardWaitingEdge(isLeading: false, elapsed: elapsed)+ .frame(width: 10)+ .opacity(right ? 1 : 0)+ }+ }+ .animation(animates ? .easeInOut(duration: 0.25) : nil, value: left)+ .animation(animates ? .easeInOut(duration: 0.25) : nil, value: right)+ }+}++private struct ActivityCardWaitingEdge: View {+ let isLeading: Bool+ let elapsed: TimeInterval+ @Environment(\.colorScheme) private var colorScheme++ /// 按 Apple HIG 的 Pulse 示例视频近似明暗曲线, 不包含额外停顿+ private static let breathCurve = UnitCurve.bezier(+ startControlPoint: UnitPoint(x: 0.31, y: 0),+ endControlPoint: UnitPoint(x: 0.69, y: 1)+ )++ private var amber: Color {+ colorScheme == .dark+ ? Color(red: 1, green: 0.76, blue: 0.40)+ : Color(red: 0.95, green: 0.58, blue: 0.18)+ }++ private var breathIntensity: Double {+ // 从峰值开始, 关闭动画时也保持完整亮度+ let phase = max(0, elapsed).truncatingRemainder(dividingBy: 2)+ return Self.breathCurve.value(at: abs(phase - 1))+ }++ var body: some View {+ Canvas { context, size in+ var mist = context+ mist.opacity = (colorScheme == .dark ? 0.96 : 0.72) * breathIntensity+ mist.addFilter(.blur(radius: 2))+ // 雾光延伸到卡片外再裁切, 让最亮处贴住侧边而不在内部形成亮线+ mist.fill(+ Path(CGRect(x: isLeading ? -6 : 0, y: -6, width: size.width + 6, height: size.height + 12)),+ with: .linearGradient(+ Gradient(stops: [+ .init(color: amber, location: 0),+ .init(color: amber.opacity(0.65), location: 0.20),+ .init(color: amber.opacity(0.25), location: 0.50),+ .init(color: amber.opacity(0.05), location: 0.78),+ .init(color: .clear, location: 1)+ ]),+ startPoint: CGPoint(x: isLeading ? 0 : size.width, y: 0),+ endPoint: CGPoint(x: isLeading ? size.width : 0, y: 0)+ )+ )+ }+ // 遮罩将模糊限制在侧边留白内, 避免扩散到图标和文字区域+ .mask {+ LinearGradient(+ stops: [+ .init(color: .black, location: 0),+ .init(color: .black, location: 0.5),+ .init(color: .clear, location: 1)+ ],+ startPoint: isLeading ? .leading : .trailing,+ endPoint: isLeading ? .trailing : .leading+ )+ }+ }+}diff --git a/CodexBar/Views/Menu/ActivityCenterView.swift b/CodexBar/Views/Menu/ActivityCenterView.swiftindex eebf49f..5952414 100644--- a/CodexBar/Views/Menu/ActivityCenterView.swift+++ b/CodexBar/Views/Menu/ActivityCenterView.swift@@ -34,11 +34,59 @@ final class ActivityCenterPresentationState: ObservableObject {}}-/// 点击活动卡片时传给 AppKit 控制器的定位信息+/// 卡片只报告主面板内的顶部位置, 屏幕坐标由窗口的实际内容区计算@MainActor-struct ActivityCenterPanelContext {- let anchorProvider: ScreenFrameProvider- let preferredSide: UsageHeatmapDetailSide+final class ActivityCenterPanelAnchor {+ nonisolated static let coordinateSpace = "CodexBar.activityCenterAnchor"+ @Published private(set) var topOffset: CGFloat?+ private weak var view: NSView?++ func bind(to view: NSView) {+ self.view = view+ }++ func unbind(from view: NSView) {+ guard self.view === view else { return }+ self.view = nil+ updateTopOffset(nil)+ }++ func updateTopOffset(_ offset: CGFloat?) {+ let offset = offset.flatMap { $0.isFinite && $0 >= 0 ? $0 : nil }+ guard offset != topOffset else { return }+ topOffset = offset+ }++ func screenFrame(in window: NSWindow) -> CGRect? {+ guard view?.window === window, let topOffset else { return nil }+ // Popover 的 hosting view 会先于窗口更新尺寸, 不从该视图转换屏幕坐标+ let contentFrame = window.contentRect(forFrameRect: window.frame)+ guard contentFrame.isValidScreenRect, topOffset < contentFrame.height else { return nil }+ return CGRect(x: contentFrame.minX, y: contentFrame.maxY - topOffset - 1, width: contentFrame.width, height: 1)+ }+}++/// 只绑定宿主身份, 不在 AppKit 布局回调中重复测量屏幕坐标+struct ActivityCenterPanelAnchorReader: NSViewRepresentable {+ let anchor: ActivityCenterPanelAnchor++ func makeCoordinator() -> ActivityCenterPanelAnchor {+ anchor+ }++ func makeNSView(context _: Context) -> NSView {+ let view = NSView()+ anchor.bind(to: view)+ return view+ }++ func updateNSView(_ nsView: NSView, context _: Context) {+ anchor.bind(to: nsView)+ }++ static func dismantleNSView(_ nsView: NSView, coordinator: ActivityCenterPanelAnchor) {+ coordinator.unbind(from: nsView)+ }}// MARK: - 任务中心面板diff --git a/CodexBar/Views/Menu/ActivitySectionReveal.swift b/CodexBar/Views/Menu/ActivitySection.swiftsimilarity index 75%rename from CodexBar/Views/Menu/ActivitySectionReveal.swiftrename to CodexBar/Views/Menu/ActivitySection.swiftindex 5a80510..ac1d877 100644--- a/CodexBar/Views/Menu/ActivitySectionReveal.swift+++ b/CodexBar/Views/Menu/ActivitySection.swift@@ -1,10 +1,18 @@import SwiftUInonisolated struct ActivityCardNaturalHeightKey: PreferenceKey {- static let defaultValue: CGFloat = 0+ struct Value: Equatable {+ var height: CGFloat+ var isInteractive = false+ }++ static let defaultValue = Value(height: 0)- static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {- value = max(value, nextValue())+ static func reduce(value: inout Value, nextValue: () -> Value) {+ let next = nextValue()+ if next.height >= value.height {+ value = next+ }}}@@ -13,7 +21,7 @@ struct ActivitySection<Content: View>: View {@ViewBuilder let content: () -> Content@Environment(\.contentAnimationsEnabled) private var allowsAnimations@State private var retainsContent: Bool- @State private var naturalHeight: CGFloat = 0+ @State private var measurement = ActivityCardNaturalHeightKey.defaultValue@State private var height: CGFloat@State private var progress: CGFloat@State private var transitionGeneration = 0@@ -38,13 +46,14 @@ struct ActivitySection<Content: View>: View {}.modifier(ActivitySectionReveal(height: height, progress: progress)).allowsHitTesting(isVisible)- .onPreferenceChange(ActivityCardNaturalHeightKey.self) { measuredHeight in- guard measuredHeight > 0 else { return }- naturalHeight = measuredHeight+ .onPreferenceChange(ActivityCardNaturalHeightKey.self) { next in+ guard next.height > 0 else { return }+ let followsGesture = measurement.isInteractive || next.isInteractive+ measurement = nextguard isVisible else { return }- // 初次打开直接采用自然高度, 后续变化统一从当前可见高度继续- withAnimation(height < 0 ? nil : animation) {- height = measuredHeight+ // 手势已逐帧计算高度, 结束时直接采用最终自然高度, 避免额外的收尾动画+ withAnimation(height < 0 || followsGesture ? nil : animation) {+ height = next.heightprogress = 1}}@@ -57,7 +66,7 @@ struct ActivitySection<Content: View>: View {return}withAnimation(animation, completionCriteria: .removed) {- height = visible ? naturalHeight : 0+ height = visible ? measurement.height : 0progress = visible ? 1 : 0} completion: {if transitionGeneration == generation, !isVisible {@@ -68,7 +77,7 @@ struct ActivitySection<Content: View>: View {}}-struct ActivitySectionReveal: ViewModifier, Animatable {+private struct ActivitySectionReveal: ViewModifier, Animatable {var height: CGFloatvar progress: CGFloatdiff --git a/CodexBar/Views/Menu/ActivityStatusText.swift b/CodexBar/Views/Menu/ActivityStatusText.swiftindex 5c2d856..fdb1a56 100644--- a/CodexBar/Views/Menu/ActivityStatusText.swift+++ b/CodexBar/Views/Menu/ActivityStatusText.swift@@ -174,29 +174,51 @@ struct ActivitySummaryText: View {var primaryTruncationMode: Text.TruncationMode = .tailvar supplementaryLineLimit: Int?var singleLineWidthReserve: CGFloat = 0- var wrappedLayout: Binding<Bool>?+ var usesWrappedLayout: Binding<Bool>?+ var primaryHelp: String?var body: some View {- if wrappedLayout?.wrappedValue == true {+ if usesWrappedLayout?.wrappedValue == true {wrappedContent} else {ViewThatFits(in: .horizontal) {- Text(components.joined(separator: " • "))+ singleLineContent.fixedSize().padding(.trailing, singleLineWidthReserve)wrappedContent// 只在换行布局被选中后锁定, 不让候选布局的预先测量改变状态.onAppear {- wrappedLayout?.wrappedValue = true+ usesWrappedLayout?.wrappedValue = true}}}}+ @ViewBuilder private var singleLineContent: some View {+ if let primaryHelp, let primary = components.first {+ HStack(spacing: 0) {+ Text(primary).help(primaryHelp)+ if components.count > 1 {+ Text(" • " + components.dropFirst().joined(separator: " • "))+ }+ }+ } else {+ Text(components.joined(separator: " • "))+ }+ }++ @ViewBuilder private func componentText(_ component: String, index: Int) -> some View {+ if index == 0, let primaryHelp {+ Text(component).help(primaryHelp)+ } else {+ Text(component)+ }+ }+private var wrappedContent: some View {VStack(alignment: .leading, spacing: 2) {ForEach(Array(components.enumerated()), id: \.offset) { index, component in- Text(component)+ componentText(component, index: index).lineLimit(index == 0 ? primaryLineLimit : supplementaryLineLimit).truncationMode(index == 0 ? primaryTruncationMode : .tail).fixedSize(horizontal: false, vertical: true)diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swiftindex 4d03649..7462934 100644--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift@@ -43,9 +43,10 @@ struct CodexStatusMenuView: View {@ObservedObject var menuSurfaceVisibility: MenuSurfaceVisibilityState@ObservedObject var animationState: MenuSurfaceAnimationStatelet activityCenterPresentationState: ActivityCenterPresentationState+ let activityCardPresentationState: ActivityCardPresentationStatelet onUsageHeatmapHoverChange: (UsageHeatmapHoverContext?) -> Voidlet onResetCreditsTap: (ResetCreditsPanelContext) -> Void- let onActivityCenterTap: (ActivityCenterPanelContext) -> Void+ let onActivityCenterTap: (ActivityCenterPanelAnchor) -> Void@EnvironmentObject private var appUpdater: AppUpdater@State private var activitySectionVisibility: Bool?@@ -158,16 +159,10 @@ private extension CodexStatusMenuView {var activitySection: some View {ActivityCard(activityMonitor: activityMonitor,- presentationState: activityCenterPresentationState,+ centerPresentation: activityCenterPresentationState,+ cardPresentation: activityCardPresentationState,keepAliveController: keepAliveController,- onTaskCenterTap: { anchorProvider in- onActivityCenterTap(- ActivityCenterPanelContext(- anchorProvider: anchorProvider,- preferredSide: .right- )- )- }+ onTaskCenterTap: onActivityCenterTap)}diff --git a/CodexBar/Views/Menu/MenuPanelLayout.swift b/CodexBar/Views/Menu/MenuPanelLayout.swiftindex a8032eb..594f9c8 100644--- a/CodexBar/Views/Menu/MenuPanelLayout.swift+++ b/CodexBar/Views/Menu/MenuPanelLayout.swift@@ -4,7 +4,7 @@ nonisolated struct MenuSectionVisibilityKey: LayoutValueKey {static let defaultValue: CGFloat = 1}-/// 区域高度和相邻间距使用同一展开进度, 移除零高度区域时不再改变总高度+/// 区域高度和相邻间距使用同一展开进度, 移除零高度区域时总高度保持不变struct MenuSectionLayout: Layout {var spacing: CGFloatdiff --git a/CodexBar/Views/Settings/KeepAliveOptionsView.swift b/CodexBar/Views/Settings/KeepAliveOptionsView.swiftindex feaded4..b88f738 100644--- a/CodexBar/Views/Settings/KeepAliveOptionsView.swift+++ b/CodexBar/Views/Settings/KeepAliveOptionsView.swift@@ -149,7 +149,7 @@ struct KeepAliveOptionsView: View {private enum Metrics {static let panelWidth: CGFloat = 280- /// 有内置电池的设备时行数, 无内置电池设备少一行低电量保护+ /// 有内置电池设备的行数, 无内置电池时少一行低电量保护static let maximumRowCount = 5static let horizontalPadding = SettingsOptionsPanelMetrics.horizontalPaddingstatic let verticalPadding = SettingsOptionsPanelMetrics.verticalPaddingdiff --git a/CodexBar/Views/Settings/TaskGlowOptionsView.swift b/CodexBar/Views/Settings/TaskGlowOptionsView.swiftindex c69851a..fc2067e 100644--- a/CodexBar/Views/Settings/TaskGlowOptionsView.swift+++ b/CodexBar/Views/Settings/TaskGlowOptionsView.swift@@ -306,7 +306,7 @@ private struct TaskGlowHexInput: NSViewRepresentable {}private func setText(_ value: String, in field: NSTextField) {- // 结束编辑通知发出时 field editor 可能仍存在, 与控件及绑定一起收敛+ // 结束编辑通知发出时 field editor 可能仍存在, 需与控件和绑定同步更新文本field.currentEditor()?.string = valuefield.stringValue = valueparent.text = valuediff --git a/CodexBar/Views/Shared/PasteboardWriter.swift b/CodexBar/Views/Shared/PasteboardWriter.swiftindex 000d474..abf2857 100644--- a/CodexBar/Views/Shared/PasteboardWriter.swift+++ b/CodexBar/Views/Shared/PasteboardWriter.swift@@ -1,6 +1,5 @@import AppKit-/// 共用的剪贴板写入方法enum PasteboardWriter {static func copy(_ text: String) {NSPasteboard.general.clearContents()diff --git a/CodexBarHelper/Power/Daemon/PowerHelperRuntime.swift b/CodexBarHelper/Power/Daemon/PowerHelperRuntime.swiftindex 0c5f7e9..935ff4f 100644--- a/CodexBarHelper/Power/Daemon/PowerHelperRuntime.swift+++ b/CodexBarHelper/Power/Daemon/PowerHelperRuntime.swift@@ -745,7 +745,7 @@ final class PowerHelperRuntime: NSObject, NSXPCListenerDelegate, @unchecked Send_ = restoreOwnedSleep(trigger: .powerHelperStartup)}case let .unreadable(error):- // 损坏记录无法证明所有权, 启动时按最安全的默认值 0 收敛+ // 损坏记录无法证明所有权, 启动时将睡眠控制恢复为默认值 0let details = LogFields.joined("detail=\(error.localizedDescription)","action=forceRestore"diff --git a/Config/BuildNumber.xcconfig b/Config/BuildNumber.xcconfignew file mode 100644index 0000000..7b51dc2--- /dev/null+++ b/Config/BuildNumber.xcconfig@@ -0,0 +1,3 @@+// 请勿手动修改+// Do not modify manually+CURRENT_PROJECT_VERSION = 257\ No newline at end of filediff --git a/Config/Integration.xctestplan b/Config/Integration.xctestplannew file mode 100644index 0000000..eecc845--- /dev/null+++ b/Config/Integration.xctestplan@@ -0,0 +1,52 @@+{+ "configurations" : [+ {+ "id" : "23BD616F-0C2D-488E-8585-CFA6A53B126B",+ "name" : "Integration",+ "options" : {++ }+ }+ ],+ "defaultOptions" : {+ "codeCoverage" : true,+ "language" : "zh-Hans",+ "mainThreadCheckerDetectionPolicy" : {+ "severity" : "warning"+ },+ "region" : "CN",+ "testTimeoutsEnabled" : true,+ "threadPerformanceCheckerRuntimeIssueDetection" : {+ "severity" : "warning"+ }+ },+ "testTargets" : [+ {+ "parallelizable" : false,+ "selectedTags" : {+ "tags" : [+ "integration"+ ]+ },+ "target" : {+ "containerPath" : "container:CodexBar.xcodeproj",+ "identifier" : "D10000000000000000000010",+ "name" : "CodexBarTests"+ }+ },+ {+ "parallelizable" : false,+ "selectedTags" : {+ "tags" : [+ "integration"+ ]+ },+ "target" : {+ "containerPath" : "container:CodexBar.xcodeproj",+ "identifier" : "E10000000000000000000010",+ "name" : "CodexBarPowerHelperTests"+ }+ }+ ],+ "version" : 1+}diff --git a/Config/Sanitizers.xctestplan b/Config/Sanitizers.xctestplanindex 65b0d0f..ad47283 100644--- a/Config/Sanitizers.xctestplan+++ b/Config/Sanitizers.xctestplan@@ -21,13 +21,11 @@"codeCoverage" : false,"language" : "zh-Hans","mainThreadCheckerDetectionPolicy" : {- "enabled" : true,"severity" : "warning"},"region" : "CN","testTimeoutsEnabled" : true,"threadPerformanceCheckerRuntimeIssueDetection" : {- "enabled" : true,"severity" : "warning"}},diff --git a/Config/Unit.xctestplan b/Config/Unit.xctestplannew file mode 100644index 0000000..6784ae8--- /dev/null+++ b/Config/Unit.xctestplan@@ -0,0 +1,52 @@+{+ "configurations" : [+ {+ "id" : "413EC0D7-5F78-4C9D-954C-3FCDCAADDE6D",+ "name" : "Unit",+ "options" : {++ }+ }+ ],+ "defaultOptions" : {+ "codeCoverage" : true,+ "language" : "zh-Hans",+ "mainThreadCheckerDetectionPolicy" : {+ "severity" : "warning"+ },+ "region" : "CN",+ "testTimeoutsEnabled" : true,+ "threadPerformanceCheckerRuntimeIssueDetection" : {+ "severity" : "warning"+ }+ },+ "testTargets" : [+ {+ "parallelizable" : false,+ "skippedTags" : {+ "tags" : [+ "integration"+ ]+ },+ "target" : {+ "containerPath" : "container:CodexBar.xcodeproj",+ "identifier" : "D10000000000000000000010",+ "name" : "CodexBarTests"+ }+ },+ {+ "parallelizable" : false,+ "skippedTags" : {+ "tags" : [+ "integration"+ ]+ },+ "target" : {+ "containerPath" : "container:CodexBar.xcodeproj",+ "identifier" : "E10000000000000000000010",+ "name" : "CodexBarPowerHelperTests"+ }+ }+ ],+ "version" : 1+}diff --git a/Config/Version.xcconfig b/Config/Version.xcconfigindex cb75d7f..cf764ce 100644--- a/Config/Version.xcconfig+++ b/Config/Version.xcconfig@@ -1,2 +1,2 @@-MARKETING_VERSION = 5.1.1-CURRENT_PROJECT_VERSION = 210+#include "BuildNumber.xcconfig"+MARKETING_VERSION = 5.2.0diff --git a/Protocol.en.md b/Protocol.en.mdindex cec7cbe..1734f1a 100644--- a/Protocol.en.md+++ b/Protocol.en.md@@ -6,7 +6,7 @@ Codex version: `0.162.0`| API | Purpose || --- | --- |-| `initialize` | Initialize the connection and retrieve the server version |+| `initialize` | Initialize the connection and get the server version || `account/read` | Read account information; `refreshToken` specifies whether to refresh authentication || `account/rateLimits/read` | Read rate limits, credit balance, and reset credits || `account/usage/read` | Read account usage summaries and daily token usage |@@ -16,8 +16,8 @@ Codex version: `0.162.0`| `thread/loaded/list` | List loaded threads || `thread/read` | Read thread information and status; `threadId` identifies the thread, and `includeTurns: false` omits turn content || `thread/resume` | Subscribe to messages from a loaded thread; `threadId` identifies the thread, and `excludeTurns: true` omits turn content |-| `thread/turns/list` | Read paginated turn information for a thread; `threadId` identifies the thread, and `itemsView: "notLoaded"` omits item content |-| `thread/items/list` | Read paginated items for a turn; `threadId` and `turnId` identify the target turn |+| `thread/turns/list` | Read a thread's turn information in pages; `threadId` identifies the thread, and `itemsView: "notLoaded"` omits item content |+| `thread/items/list` | Read a turn's items in pages; `threadId` and `turnId` identify the target turn |## Outgoing notifications@@ -63,12 +63,12 @@ Codex version: `0.162.0`| `turn/diff/updated` | Observe code diff updates || `model/rerouted` | Receive model change information || `model/verification` | Observe model verification requirements |-| `modelProvider/authRecoveryStarted` | Observe the start of authentication recovery |-| `modelProvider/authRecoveryCompleted` | Observe the end of authentication recovery |+| `modelProvider/authRecoveryStarted` | Receive notifications when authentication recovery starts |+| `modelProvider/authRecoveryCompleted` | Receive notifications when authentication recovery ends || `model/safetyBuffering/updated` | Receive safety buffering display status |-| `hook/started` | Observe the start of hook execution |+| `hook/started` | Receive notifications when a hook starts || `hook/completed` | Receive hook execution results |-| `serverRequest/resolved` | Receive notifications that server requests, such as approvals or questions, have ended |+| `serverRequest/resolved` | Receive notifications when server requests, such as approvals or questions, end || `error` | Receive error notifications || `warning` | Log server warnings |diff --git a/Protocol.md b/Protocol.mdindex fb84ca6..d5f43e0 100644--- a/Protocol.md+++ b/Protocol.md@@ -50,23 +50,23 @@ Codex 版本:`0.162.0`| 接口 | 作用 || --- | --- |-| `item/agentMessage/delta` | 感知回答输出进展 |-| `item/reasoning/textDelta` | 感知思考文本输出进展 |-| `item/reasoning/summaryTextDelta` | 感知思考摘要输出进展 |-| `item/commandExecution/outputDelta` | 感知命令输出进展 |+| `item/agentMessage/delta` | 跟踪回答输出进展 |+| `item/reasoning/textDelta` | 跟踪思考文本输出进展 |+| `item/reasoning/summaryTextDelta` | 跟踪思考摘要输出进展 |+| `item/commandExecution/outputDelta` | 跟踪命令输出进展 |### 状态与展示通知| 接口 | 作用 || --- | --- || `turn/plan/updated` | 接收计划进度更新 |-| `turn/diff/updated` | 感知代码差异更新 |+| `turn/diff/updated` | 跟踪代码差异更新 || `model/rerouted` | 接收模型切换信息 |-| `model/verification` | 感知模型验证需求 |-| `modelProvider/authRecoveryStarted` | 感知认证恢复开始 |-| `modelProvider/authRecoveryCompleted` | 感知认证恢复结束 |+| `model/verification` | 接收模型验证需求 |+| `modelProvider/authRecoveryStarted` | 接收认证恢复开始通知 |+| `modelProvider/authRecoveryCompleted` | 接收认证恢复结束通知 || `model/safetyBuffering/updated` | 接收安全缓冲展示状态 |-| `hook/started` | 感知 hook 执行开始 |+| `hook/started` | 接收 hook 执行开始通知 || `hook/completed` | 接收 hook 执行结果 || `serverRequest/resolved` | 接收审批、提问等服务端请求的结束通知 || `error` | 接收错误通知 |diff --git a/README.en.md b/README.en.mdindex e90396a..b454da6 100644--- a/README.en.md+++ b/README.en.md@@ -15,7 +15,7 @@ View Codex status in your macOS menu bar[](https://github.com/bob-zebedy/CodexBar/releases)[](LICENSE)-[Features](#features) | [Installation](#installation) | [Privacy](#privacy) | [Runtime architecture](https://codexbar.zabrian.app/architecture) | [Performance report](https://codexbar.zabrian.app/performance) | [Protocol](Protocol.en.md)+[Features](#features) | [Installation](#installation) | [Privacy](#privacy) | [Runtime architecture](https://codexbar.zabrian.app/architecture) | [Protocol](Protocol.en.md)<img src="Images/preview.gif" width="640" alt="CodexBar preview">@@ -29,13 +29,13 @@ CodexBar is a macOS menu bar app for viewing your Codex account, rate limits, to- View your account, plan, credits, and the remaining percentage and reset time for each rate-limit window- Show your preferred allowance directly in the menu bar-- Track banked resets and their expiry dates, with automatic use before they expire+- View banked resets and their expiry dates, and have CodexBar use them automatically before they expire### Task progress- See each task's project, model, reasoning effort, duration, and token usage- Track execution states, tasks awaiting a response, task progress, and recent events-- Review concurrent tasks and recent completions, failures, and interruptions in Task Center+- Use Task Center to view concurrent tasks and tasks that recently completed, failed, or were interrupted### Usage statistics@@ -47,13 +47,13 @@ CodexBar is a macOS menu bar app for viewing your Codex account, rate limits, to- Receive alerts for task completions, tasks awaiting a response, allowance changes, and protection events- Choose notification types, sounds, and task haptic feedback-- Follow status changes through customizable task glow at the top of your displays+- See status changes in the task glow at the top of your displays, and customize its appearance### Keep awake- Keep your Mac awake while tasks run, then allow normal sleep when they finish-- Optionally stay awake while awaiting a response or keep the display on as well-- Set a keep-awake time limit, low-battery protection, and stalled task protection+- Choose whether to keep your Mac awake while tasks await a response and whether to keep the display on+- Set a keep-awake time limit and enable low-battery and stalled task protection## Installation@@ -70,9 +70,9 @@ Download the latest version from [GitHub Releases](https://github.com/bob-zebedy## Requirements- macOS 15.0 or later-- [Codex CLI](https://github.com/openai/codex) installed and signed in, or ChatGPT App or Codex App with bundled Codex installed+- [Codex CLI](https://github.com/openai/codex) version 0.162.0 or later installed and signed in- Codex background service version `0.162.0` or later-- Cross-device sync requires an available iCloud account signed in on the Mac+- For cross-device sync, the Mac must be signed in to an available iCloud account## Privacydiff --git a/README.md b/README.mdindex b1c435d..ae89708 100644--- a/README.md+++ b/README.md@@ -15,7 +15,7 @@[](https://github.com/bob-zebedy/CodexBar/releases)[](LICENSE)-[功能](#功能) | [安装](#安装) | [隐私](#隐私) | [运行架构](https://codexbar.zabrian.app/architecture) | [性能报告](https://codexbar.zabrian.app/performance) | [协议](Protocol.md)+[功能](#功能) | [安装](#安装) | [隐私](#隐私) | [运行架构](https://codexbar.zabrian.app/architecture) | [协议](Protocol.md)<img src="Images/preview.gif" width="640" alt="CodexBar 预览">@@ -29,13 +29,13 @@ CodexBar 是 macOS 菜单栏 App,可查看 Codex 账户、额度、Token 用- 查看账户、套餐、积分,以及各额度窗口的剩余比例和重置时间- 在菜单栏直接显示关注的额度-- 查看留存重置及到期时间,支持到期前自动使用+- 查看留存重置和到期时间,可在到期前自动使用### 任务进展- 查看项目、模型、推理强度、任务耗时和 Token 用量- 实时显示执行状态、等待回应、任务进度和最近事件-- 在任务中心集中查看并发任务及最近完成、失败和中断的记录+- 在任务中心查看并发任务,以及最近完成、失败或中断的任务### 使用统计@@ -46,7 +46,7 @@ CodexBar 是 macOS 菜单栏 App,可查看 Codex 账户、额度、Token 用### 通知与任务流光- 接收任务完成、等待回应、额度变化和保护提醒-- 按需选择通知类型、音效和任务触觉反馈+- 选择需要的通知类型、音效和任务触觉反馈- 用屏幕顶部的任务流光显示状态变化,支持自定义外观### 防睡眠@@ -65,18 +65,18 @@ brew install --cask bob-zebedy/tap/codexbar@5### DMG-从 [GitHub Releases](https://github.com/bob-zebedy/CodexBar/releases) 下载最新版本并拖入 Applications。+从 [GitHub Releases](https://github.com/bob-zebedy/CodexBar/releases) 下载最新版本,将 CodexBar 拖入 Applications。## 运行要求- macOS 15.0 或更高版本-- 已安装并登录 [Codex CLI](https://github.com/openai/codex) 或安装了内置 Codex 的 ChatGPT App 或 Codex App+- 已安装 [Codex CLI](https://github.com/openai/codex) 0.162.0+ 版本并登录- Codex 后台服务版本为 `0.162.0` 或更高版本-- 使用跨设备同步时,需要登录可用的 iCloud 账户+- 跨设备同步需要登录可用的 iCloud 账户## 隐私-活动原始事件和实时任务在本机处理。开启跨设备同步后,日级活动聚合和 Token 用量记录会上传到 iCloud private database。+CodexBar 在本机处理活动原始事件和实时任务。开启跨设备同步后,会将按天汇总的活动数据和 Token 用量记录上传到 iCloud 私有数据库。## 反馈diff --git a/Scripts/appcast.sh b/Scripts/appcast.shindex 8952139..86c7df0 100755--- a/Scripts/appcast.sh+++ b/Scripts/appcast.sh@@ -1,8 +1,11 @@#!/usr/bin/env bashset -euo pipefail-# 低于此构建号时优先提供旧分支补丁, 无可用补丁时提示手动升级-# 发布不兼容更新时同步调整构建号和升级指南版本, 后续兼容更新保持不变+# For builds below this threshold, provide patches from older branches when available+# Otherwise, prompt users to upgrade manually+#+# For incompatible releases, update both the build threshold and upgrade guide version+# Keep both values unchanged for subsequent compatible releasesreadonly MINIMUM_COMPATIBLE_BUILD=200readonly UPGRADE_GUIDE_VERSION=5.0.0@@ -17,8 +20,6 @@ RELEASE_NOTES_BASE_URL="${RELEASE_NOTES_BASE_URL:-https://codexbar.zabrian.app/nMINIMUM_SYSTEM_VERSION="${MINIMUM_SYSTEM_VERSION:-15.0}"INCLUDE_RELEASE_NOTES="${INCLUDE_RELEASE_NOTES:-1}"SIGN_UPDATE="${SIGN_UPDATE:-}"-XCODE_PROJECT="${XCODE_PROJECT:-}"-XCODE_SCHEME="${XCODE_SCHEME:-CodexBar}"if [[ "${BUILD_DIR}" != /* ]]; thenBUILD_DIR="${PROJECT_DIR}/${BUILD_DIR}"@@ -42,8 +43,6 @@ Environment:INCLUDE_RELEASE_NOTES Set to 0 to omit sparkle:releaseNotesLink.MINIMUM_SYSTEM_VERSION Defaults to 15.0.SIGN_UPDATE Optional path to Sparkle's sign_update tool.- XCODE_PROJECT Optional .xcodeproj path.- XCODE_SCHEME Defaults to CodexBar.USAGE}@@ -62,23 +61,10 @@ xml_escape() {-e 's/"/\"/g'}-read_build_setting() {- local name="$1"- printf '%s\n' "${BUILD_SETTINGS}" |- awk -F= -v key="${name}" '- $1 ~ key {- value = $2- gsub(/^[[:space:]]+|[[:space:]]+$/, "", value)- print value- exit- }- '-}-# Print the single entry matching a glob in a directory, or fail# $1 noun for "no X found" $2 find -type $3 -name glob# $4 noun for "multiple X found" $5 hint appended to the multiple-match error-# $6 directory to search. Exits 1 when nothing matches, 2 when more than one+# $6 directory to search. Returns 1 when nothing matches, 2 when more than one# matches (printing the list)find_single() {local search_dir="$6"@@ -135,40 +121,53 @@ if [[ ! -f "${APPCAST_PATH}" ]]; thenexit 1fi-if [[ -z "${XCODE_PROJECT}" ]]; then- XCODE_PROJECT="$(find_single .xcodeproj d '*.xcodeproj' '.xcodeproj files' 'set XCODE_PROJECT' "${PROJECT_DIR}")" || exit 1-elif [[ "${XCODE_PROJECT}" != /* ]]; then- XCODE_PROJECT="${PROJECT_DIR}/${XCODE_PROJECT}"-fi--require_command xcodebuild+require_command diskutilrequire_command perlrequire_command stat-BUILD_SETTINGS="$(- xcodebuild \- -project "${XCODE_PROJECT}" \- -scheme "${XCODE_SCHEME}" \- -configuration Release \- -showBuildSettings 2>/dev/null-)"--SHORT_VERSION="$(read_build_setting MARKETING_VERSION)"-BUILD_VERSION="$(read_build_setting CURRENT_PROJECT_VERSION)"-PRODUCT_NAME="$(read_build_setting PRODUCT_NAME)"+WORK_DIR="$(mktemp -d)"+MOUNT_POINT="${WORK_DIR}/volume"+APPCAST_TMP="${WORK_DIR}/appcast.xml"+DMG_MOUNTED=0++cleanup() {+ if [[ "${DMG_MOUNTED}" == "1" ]]; then+ if ! diskutil eject "${MOUNT_POINT}" >/dev/null; then+ echo "error: unable to unmount ${MOUNT_POINT}" >&2+ return+ fi+ fi+ rm -f "${APPCAST_TMP}"+ if [[ -d "${MOUNT_POINT}" ]]; then+ rmdir "${MOUNT_POINT}"+ fi+ rmdir "${WORK_DIR}"+}+trap cleanup EXIT++mkdir "${MOUNT_POINT}"+diskutil image attach --readOnly --mountOptions nobrowse --mountPoint "${MOUNT_POINT}" "${DMG_PATH}" >/dev/null+DMG_MOUNTED=1+APP_PATH="$(find_single App d '*.app' Apps 'package a single App:' "${MOUNT_POINT}")" || exit 1+INFO_PLIST="${APP_PATH}/Contents/Info.plist"+SHORT_VERSION="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "${INFO_PLIST}" 2>/dev/null || true)"+BUILD_VERSION="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleVersion' "${INFO_PLIST}" 2>/dev/null || true)"+PRODUCT_NAME="$(basename "${APP_PATH}" .app)"+diskutil eject "${MOUNT_POINT}" >/dev/null+DMG_MOUNTED=0if [[ -z "${SHORT_VERSION}" || -z "${BUILD_VERSION}" ]]; then- echo "error: unable to read MARKETING_VERSION or CURRENT_PROJECT_VERSION" >&2+ echo "error: unable to read CFBundleShortVersionString or CFBundleVersion" >&2exit 1fiif [[ ! "${BUILD_VERSION}" =~ ^[1-9][0-9]*$ || ! "${MINIMUM_COMPATIBLE_BUILD}" =~ ^[1-9][0-9]*$ ]]; then- echo "error: CURRENT_PROJECT_VERSION and MINIMUM_COMPATIBLE_BUILD must be positive integer build numbers" >&2+ echo "error: CFBundleVersion and MINIMUM_COMPATIBLE_BUILD must be positive integer build numbers" >&2echo " configure MINIMUM_COMPATIBLE_BUILD in Scripts/appcast.sh" >&2exit 1fiif ! perl -e 'exit($ARGV[0] > $ARGV[1] ? 1 : 0)' "${MINIMUM_COMPATIBLE_BUILD}" "${BUILD_VERSION}"; then- echo "error: MINIMUM_COMPATIBLE_BUILD must not exceed CURRENT_PROJECT_VERSION" >&2+ echo "error: MINIMUM_COMPATIBLE_BUILD must not exceed CFBundleVersion" >&2exit 1fi@@ -183,12 +182,6 @@ elseRELEASE_NOTES_URL_PREFIX+="?lang="fi-if [[ -z "${PRODUCT_NAME}" || "${PRODUCT_NAME}" == '$(TARGET_NAME)' ]]; then- PRODUCT_NAME="$(basename "${DMG_PATH}")"- PRODUCT_NAME="${PRODUCT_NAME%%-v*}"- PRODUCT_NAME="${PRODUCT_NAME%.dmg}"-fi-if [[ -z "${SIGN_UPDATE}" ]]; thenif command -v sign_update >/dev/null 2>&1; thenSIGN_UPDATE="$(command -v sign_update)"@@ -267,8 +260,6 @@ APPCAST_ITEM=" <item>echo "==> Updating appcast"# Write through a temp file so a perl die leaves appcast.xml untouched-APPCAST_TMP="$(mktemp)"-trap 'rm -f "${APPCAST_TMP}"' EXITAPPCAST_ITEM="${APPCAST_ITEM}" APPCAST_VERSION="${BUILD_VERSION}" perl -0p -e 'my $item = $ENV{"APPCAST_ITEM"};my $version = $ENV{"APPCAST_VERSION"};diff --git a/Scripts/build-number.pl b/Scripts/build-number.plnew file mode 100644index 0000000..ccd8ee7--- /dev/null+++ b/Scripts/build-number.pl@@ -0,0 +1,65 @@+#!/usr/bin/perl+use strict;+use warnings;+use Fcntl qw(:flock);+use File::Basename qw(dirname);+use File::Temp qw(tempfile);++exit 0 if ( $ENV{ACTION} // '' ) =~ /^(?:clean|analyze|indexbuild)$/;++# Increment the build number only for builds+exit 0 if ( $ENV{CODEXBAR_AUTO_INCREMENT_BUILD_NUMBER} // 'YES' ) eq 'NO';++@ARGV == 1+ or die "error: Usage: build-number.pl BuildNumber.xcconfig\n";+my ($config_path) = @ARGV;++# Keep the lock at a stable path so increments stay serialized across atomic replacements+open my $lock, '>>', "$config_path.lock"+ or die "error: Cannot open build number lock: $!\n";+flock $lock, LOCK_EX+ or die "error: Cannot lock build number: $!\n";++open my $config, '<', $config_path+ or die "error: Cannot read $config_path: $!\n";+my $mode = ( stat $config )[2] & 0777;+my $contents = do {+ local $/;+ <$config>;+ }+ // '';+close $config+ or die "error: Cannot close $config_path: $!\n";++my @definitions = $contents =~ /^[ \t]*CURRENT_PROJECT_VERSION\b[^\r\n]*/mg;+@definitions == 1+ or die "error: Expected one CURRENT_PROJECT_VERSION in $config_path\n";++my $next_build;+my $replacements = $contents =~ s{+ ^([\t ]*CURRENT_PROJECT_VERSION[\t ]*=[\t ]*)+ ([1-9][0-9]*)+ ([\t ]*(?:;[\t ]*)?(?://[^\r\n]*)?\r?)$+}{+ $next_build = $2 + 1;+ "$1$next_build$3"+}mex;+$replacements == 1+ or die+ "error: CURRENT_PROJECT_VERSION must be a positive integer in $config_path\n";++my ( $temporary, $temporary_path ) = tempfile(+ '.BuildNumber.xcconfig.XXXXXX',+ DIR => dirname($config_path),+ UNLINK => 1+);+chmod $mode, $temporary_path+ or die "error: Cannot preserve version configuration permissions: $!\n";+print {$temporary} $contents+ or die "error: Cannot write version configuration: $!\n";+close $temporary+ or die "error: Cannot close version configuration: $!\n";+rename $temporary_path, $config_path+ or die "error: Cannot replace $config_path: $!\n";++print "note: CURRENT_PROJECT_VERSION = $next_build\n";diff --git a/Scripts/build.sh b/Scripts/build.shindex caa7e6f..772eb55 100755--- a/Scripts/build.sh+++ b/Scripts/build.sh@@ -1,7 +1,7 @@#!/usr/bin/env bashset -euo pipefail-# 避免外部编译器干扰 Xcode 工具链+# Use the Xcode toolchain without compiler overrides from the environmentunset CC CXXSCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"@@ -611,7 +611,8 @@ configure_archive_signing() {exit 1fi- # exportArchive 不会下载缺失的手动 profile, 在 archive 阶段解析才能触发 Xcode 账户同步+ # exportArchive does not download missing manual profiles+ # Resolve the profile during archive to trigger Xcode account syncARCHIVE_SIGNING_FLAGS=("CODE_SIGN_STYLE=Manual""CODEXBAR_PROVISIONING_PROFILE_SPECIFIER=${provisioning_profile}"diff --git a/Scripts/cleanup.swift b/Scripts/cleanup.swiftindex e93cdbf..dc2261d 100755--- a/Scripts/cleanup.swift+++ b/Scripts/cleanup.swift@@ -106,9 +106,9 @@ private enum CleanupError: LocalizedError {case let .message(message):messagecase let .commandFailed(executable, arguments, status, output):- "命令执行失败, status=\(status), command=\(([executable] + arguments).joined(separator: " "))\n\(output)"+ "Command failed, status=\(status), command=\(([executable] + arguments).joined(separator: " "))\n\(output)"case let .codeSigningValidationFailed(reason):- "签名校验失败, \(reason)"+ "Code signature validation failed, \(reason)"}}}@@ -137,14 +137,14 @@ private final class KeepAliveCleanupCommand {let targets = try makeTargets(options: options)guard !targets.isEmpty else {- print("清理完成: 没有可用目标")+ print("Cleanup complete: no targets found")return}let runningTargets = runningTargets(in: targets)if !options.isCheckOnly, !runningTargets.isEmpty {let bundleIdentifiers = runningTargets.map(\.bundleIdentifier).joined(separator: ", ")- throw CleanupError.message("CodexBar 仍在运行, bundle=\(bundleIdentifiers)")+ throw CleanupError.message("CodexBar is still running, bundle=\(bundleIdentifiers)")}let temporaryRoot = fileManager.temporaryDirectory@@ -184,7 +184,7 @@ private final class KeepAliveCleanupCommand {printUsage()Darwin.exit(EXIT_SUCCESS)default:- throw CleanupError.message("未知选项, value=\(argument)")+ throw CleanupError.message("Unknown option, value=\(argument)")}}@@ -196,17 +196,17 @@ private final class KeepAliveCleanupCommand {"""usage: Scripts/cleanup.swift [options]- 仅注销 CodexBar 的 Release 和 Debug KeepAlive LaunchDaemon+ Unregister only the Release and Debug KeepAlive LaunchDaemons for CodexBarOptions:- --release 只移除 Release Power Helper- --debug 只移除 Debug Power Helper- --check 只检查目标- -h, --help 显示帮助-- 仅支持 Contents/Helpers 中的 Power Helper 管理 App- 不指定 --release 或 --debug 时同时处理两个目标- 实际清理前请先退出待清理的 CodexBar 实例+ --release Remove only the Release Power Helper+ --debug Remove only the Debug Power Helper+ --check Check targets without removing them+ -h, --help Show help++ Requires the Power Helper manager app in Contents/Helpers+ Processes both targets when neither --release nor --debug is specified+ Quit the CodexBar instances you want to clean up before running cleanup""")}@@ -217,11 +217,11 @@ private final class KeepAliveCleanupCommand {.compactMap { configuration inlet bundleIdentifier = configuration.bundleIdentifierguard let appURL = try resolveAppURL(configuration: configuration) else {- print("清理跳过: bundle=\(bundleIdentifier), reason=未找到 App")+ print("Cleanup skipped: bundle=\(bundleIdentifier), reason=App not found")return nil}- print("清理目标: bundle=\(bundleIdentifier), path=\(appURL.path)")+ print("Cleanup target: bundle=\(bundleIdentifier), path=\(appURL.path)")return CleanupTarget(appURL: appURL,bundleIdentifier: bundleIdentifier,@@ -230,7 +230,7 @@ private final class KeepAliveCleanupCommand {}}- /// 按候选顺序查找, 通过 Info.plist 中的 CFBundleIdentifier 确认目标 App+ /// Check candidates in order and verify the App using CFBundleIdentifier in Info.plistprivate func resolveAppURL(configuration: CleanupBuildConfiguration) throws -> URL? {let bundleIdentifier = configuration.bundleIdentifiervar candidates: [URL] = []@@ -250,15 +250,15 @@ private final class KeepAliveCleanupCommand {return candidate}- // xcodebuild 未找到目标不表示数据损坏, 按非致命失败处理+ // Treat an xcodebuild lookup failure as nonfatal since it does not imply a corrupt installationguard let builtAppURL = try? resolveBuiltAppURL(configuration: configuration) else {return nil}return try appBundleIdentifier(at: builtAppURL) == bundleIdentifier ? builtAppURL : nil}- /// 缺少 Info.plist 或字符串类型的 CFBundleIdentifier 时返回 nil- /// 文件读取或解析失败时抛出错误, 避免将损坏的安装静默跳过+ /// Return nil if Info.plist is missing or CFBundleIdentifier is not a string+ /// Throw on read or parse errors so corrupt installations are not silently skippedprivate func appBundleIdentifier(at appURL: URL) throws -> String? {let infoURL = appURL.appending(path: "Contents/Info.plist")guard fileManager.fileExists(atPath: infoURL.path) else {@@ -284,7 +284,7 @@ private final class KeepAliveCleanupCommand {guard let targetBuildDirectory = buildSetting("TARGET_BUILD_DIR", in: output),let wrapperName = buildSetting("WRAPPER_NAME", in: output) else {throw CleanupError.message(- "无法从 Xcode 构建设置定位 App, configuration=\(configuration.rawValue)"+ "Cannot locate App from Xcode build settings, configuration=\(configuration.rawValue)")}return URL(fileURLWithPath: targetBuildDirectory).appending(path: wrapperName)@@ -319,16 +319,16 @@ private final class KeepAliveCleanupCommand {let daemonPlistURL = managerURL.appending(path: "Contents/Library/LaunchDaemons/\(target.plistName)")guard fileManager.isExecutableFile(atPath: managerExecutableURL.path),fileManager.fileExists(atPath: daemonPlistURL.path) else {- throw CleanupError.message("Power Helper 管理 App 缺失或结构无效, path=\(managerURL.path)")+ throw CleanupError.message("Power Helper manager app is missing or has an invalid structure, path=\(managerURL.path)")}let teamIdentifier = try signingTeamIdentifier(for: target.appURL)- try runCodeSigningChecked(["--verify", "--deep", "--strict", managerURL.path], failureReason: "验证管理 App 签名失败")+ try runCodeSigningChecked(["--verify", "--deep", "--strict", managerURL.path], failureReason: "Cannot verify manager app signature")guard try signingTeamIdentifier(for: managerURL) == teamIdentifier else {- throw CleanupError.codeSigningValidationFailed("管理 App 与主 App 的 Team ID 不匹配")+ throw CleanupError.codeSigningValidationFailed("Manager app and main App have different Team IDs")}- // 清理进程必须使用主 App 的签名身份, 才能通过 Power Helper 的 XPC 校验+ // The cleanup process needs the main App's signing identity to pass Power Helper XPC validationlet cleanupAppURL = temporaryRoot.appending(path: "\(target.bundleIdentifier).app", directoryHint: .isDirectory)let contentsURL = cleanupAppURL.appending(path: "Contents", directoryHint: .isDirectory)@@ -352,22 +352,22 @@ private final class KeepAliveCleanupCommand {"--sign", signingIdentity,cleanupAppURL.path],- failureReason: "签名 App 失败"+ failureReason: "Cannot sign App")let cleanupTeamIdentifier = try signingTeamIdentifier(for: cleanupAppURL)guard cleanupTeamIdentifier == teamIdentifier else {throw CleanupError.codeSigningValidationFailed(- "Team ID 不匹配, actual=\(cleanupTeamIdentifier), expected=\(teamIdentifier)"+ "Team ID mismatch, actual=\(cleanupTeamIdentifier), expected=\(teamIdentifier)")}try runCodeSigningChecked(["--verify", "--strict", "--verbose=2", cleanupAppURL.path],- failureReason: "验证 App 签名失败"+ failureReason: "Cannot verify App signature")if isCheckOnly {- print("目标验证完成: bundle=\(target.bundleIdentifier)")+ print("Target verified: bundle=\(target.bundleIdentifier)")return}@@ -393,7 +393,7 @@ private final class KeepAliveCleanupCommand {capturesOutput: true)guard serviceStatus.status != 0 else {- throw CleanupError.message("后台服务仍在运行, service=\(target.serviceIdentifier)")+ throw CleanupError.message("Background service is still running, service=\(target.serviceIdentifier)")}}@@ -401,7 +401,7 @@ private final class KeepAliveCleanupCommand {let data = try Data(contentsOf: url)guard let dictionary = try PropertyListSerialization.propertyList(from: data, format: nil)as? [String: Any] else {- throw CleanupError.message("plist 内容无效, path=\(url.path)")+ throw CleanupError.message("Invalid plist contents, path=\(url.path)")}return dictionary}@@ -418,24 +418,24 @@ private final class KeepAliveCleanupCommand {private func signingTeamIdentifier(for appURL: URL) throws -> String {let output = try runCodeSigningChecked(["-dvv", appURL.path],- failureReason: "读取签名信息失败, path=\(appURL.path)",+ failureReason: "Cannot read code signature, path=\(appURL.path)",capturesOutput: true).textguard let line = output.split(whereSeparator: \.isNewline).first(where: { $0.hasPrefix("TeamIdentifier=") }) else {throw CleanupError.codeSigningValidationFailed(- "Team ID 缺失, path=\(appURL.path)"+ "Missing Team ID, path=\(appURL.path)")}let teamIdentifier = String(line.dropFirst("TeamIdentifier=".count))guard !teamIdentifier.isEmpty else {throw CleanupError.codeSigningValidationFailed(- "Team ID 为空, path=\(appURL.path)"+ "Empty Team ID, path=\(appURL.path)")}guard teamIdentifier.unicodeScalars.allSatisfy(CharacterSet.alphanumerics.contains) else {throw CleanupError.codeSigningValidationFailed(- "Team ID 格式错误, actual=\(teamIdentifier), expected=alphanumeric"+ "Invalid Team ID format, actual=\(teamIdentifier), expected=alphanumeric")}return teamIdentifier@@ -523,17 +523,17 @@ private func runUnregisterChild(serviceIdentifier: String, managerExecutable: Stdo {let initialStatus = try runPowerHelperManager(command: "status", executable: managerExecutable)if initialStatus == .notRegistered || initialStatus == .notFound {- print("后台服务未注册: service=\(serviceIdentifier)")+ print("Background service is not registered: service=\(serviceIdentifier)")Darwin.exit(EXIT_SUCCESS)}let status = try runPowerHelperManager(command: "unregister", executable: managerExecutable)guard status == .notRegistered || status == .notFound else {- throw CleanupError.message("管理 App 未确认 Power Helper 已注销, status=\(status.rawValue)")+ throw CleanupError.message("Manager app did not confirm Power Helper was unregistered, status=\(status.rawValue)")}- print("后台服务已注销: service=\(serviceIdentifier)")+ print("Background service unregistered: service=\(serviceIdentifier)")Darwin.exit(EXIT_SUCCESS)} catch {- FileHandle.standardError.write(Data("Power Helper 注销失败: \(error.localizedDescription)\n".utf8))+ FileHandle.standardError.write(Data("Failed to unregister Power Helper: \(error.localizedDescription)\n".utf8))Darwin.exit(EXIT_FAILURE)}}@@ -548,31 +548,31 @@ private func runPowerHelperManager(command: String, executable: String) throws -let data = pipe.fileHandleForReading.readDataToEndOfFile()process.waitUntilExit()guard process.terminationStatus == 0 else {- throw CleanupError.message("管理 App 进程失败, command=\(command), exit=\(process.terminationStatus)")+ throw CleanupError.message("Manager app process failed, command=\(command), exit=\(process.terminationStatus)")}let reply: PowerHelperManagerReplydo {reply = try JSONDecoder().decode(PowerHelperManagerReply.self, from: data)} catch {- throw CleanupError.message("管理 App 响应无效, command=\(command), detail=\(error.localizedDescription)")+ throw CleanupError.message("Invalid manager app response, command=\(command), detail=\(error.localizedDescription)")}if let domain = reply.errorDomain, let code = reply.errorCode {throw CleanupError.message(- "管理 App 执行失败, command=\(command), status=\(reply.status), domain=\(domain), code=\(code)"+ "Manager app command failed, command=\(command), status=\(reply.status), domain=\(domain), code=\(code)")}guard reply.errorDomain == nil, reply.errorCode == nil else {- throw CleanupError.message("管理 App 错误信息不完整, command=\(command)")+ throw CleanupError.message("Incomplete manager app error details, command=\(command)")}guard let status = SMAppService.Status(rawValue: reply.status) else {- throw CleanupError.message("管理 App 状态无效, command=\(command), status=\(reply.status)")+ throw CleanupError.message("Invalid manager app status, command=\(command), status=\(reply.status)")}switch status {case .notRegistered, .enabled, .requiresApproval, .notFound:return status@unknown default:- throw CleanupError.message("管理 App 状态未知, command=\(command), status=\(reply.status)")+ throw CleanupError.message("Unknown manager app status, command=\(command), status=\(reply.status)")}}@@ -592,10 +592,10 @@ private func cancelAutoResetWakeScheduleBeforeUnregister(serviceIdentifier: Stri}}connection.interruptionHandler = {- finish("连接中断")+ finish("Connection interrupted")}connection.invalidationHandler = {- finish("连接失效")+ finish("Connection invalidated")}connection.resume()@@ -605,7 +605,7 @@ private func cancelAutoResetWakeScheduleBeforeUnregister(serviceIdentifier: Striguard let powerHelper = connection.remoteObjectProxyWithErrorHandler(errorHandler)as? CleanupPowerHelperProtocol else {connection.invalidate()- reportWakeScheduleCancellationFailure(owner: owner, detail: "服务接口无效")+ reportWakeScheduleCancellationFailure(owner: owner, detail: "Invalid service interface")return false}@@ -618,17 +618,17 @@ private func cancelAutoResetWakeScheduleBeforeUnregister(serviceIdentifier: Striconnection.invalidate()let errorMessage = waitResult == .timedOut- ? "请求超时"+ ? "Request timed out": state.completedErrorMessage()guard !hasScheduledWakeEvent(owner: owner) else {reportWakeScheduleCancellationFailure(owner: owner,- detail: errorMessage ?? "系统回读仍存在事件"+ detail: errorMessage ?? "Wake event is still present in the system schedule")return false}- print("自动重置唤醒计划已取消: owner=\(owner)")+ print("Auto-reset wake schedule canceled: owner=\(owner)")return true}@@ -649,7 +649,7 @@ private func hasScheduledWakeEvent(owner: String) -> Bool {private func reportWakeScheduleCancellationFailure(owner: String, detail: String) {FileHandle.standardError.write(Data(- "自动重置唤醒计划取消失败, 已停止注销: owner=\(owner), detail=\(detail)\n".utf8+ "Cannot cancel auto-reset wake schedule; unregister aborted: owner=\(owner), detail=\(detail)\n".utf8))}@@ -658,7 +658,7 @@ let arguments = Array(CommandLine.arguments.dropFirst())if arguments.first == "--unregister-child" {guard arguments.count == 3 else {FileHandle.standardError.write(- Data("内部参数无效: expected=3, actual=\(arguments.count)\n".utf8)+ Data("Invalid internal arguments: expected=3, actual=\(arguments.count)\n".utf8))Darwin.exit(EXIT_FAILURE)}@@ -668,6 +668,6 @@ if arguments.first == "--unregister-child" {do {try KeepAliveCleanupCommand().run(arguments: arguments)} catch {- FileHandle.standardError.write(Data("清理失败: \(error.localizedDescription)\n".utf8))+ FileHandle.standardError.write(Data("Cleanup failed: \(error.localizedDescription)\n".utf8))Darwin.exit(EXIT_FAILURE)}diff --git a/Scripts/dmg.sh b/Scripts/dmg.shindex 1fbb7d1..ece08ba 100755--- a/Scripts/dmg.sh+++ b/Scripts/dmg.sh@@ -4,7 +4,6 @@ set -euo pipefailSCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"BUILD_DIR="${BUILD_DIR:-${PROJECT_DIR}/Build}"-VERSION_CONFIG="${PROJECT_DIR}/Config/Version.xcconfig"APP_PATH="${1:-}"OUTPUT_PATH="${2:-}"@@ -15,7 +14,7 @@ fiif [[ -z "${APP_PATH}" ]]; thenif [[ ! -d "${BUILD_DIR}" ]]; then- echo "error: build 目录不存在: ${BUILD_DIR}" >&2+ echo "error: build directory does not exist: ${BUILD_DIR}" >&2echo "usage: Scripts/dmg.sh [App.app] [Output.dmg]" >&2exit 1fi@@ -26,13 +25,13 @@ if [[ -z "${APP_PATH}" ]]; thendone < <(find "${BUILD_DIR}" -maxdepth 1 -type d -name "*.app" | sort)if [[ "${#apps[@]}" -eq 0 ]]; then- echo "error: build 目录没有找到 .app: ${BUILD_DIR}" >&2+ echo "error: no .app found in build directory: ${BUILD_DIR}" >&2echo "usage: Scripts/dmg.sh [App.app] [Output.dmg]" >&2exit 1fiif [[ "${#apps[@]}" -gt 1 ]]; then- echo "error: build 目录找到多个 .app, 请指定要打包的 app 路径: " >&2+ echo "error: multiple apps found in build directory; specify the app path to package:" >&2printf ' %s\n' "${apps[@]}" >&2exit 1fi@@ -43,34 +42,17 @@ elif [[ "${APP_PATH}" != /* ]]; thenfiif [[ ! -d "${APP_PATH}" || "${APP_PATH}" != *.app ]]; then- echo "error: app 路径无效: ${APP_PATH}" >&2+ echo "error: invalid app path: ${APP_PATH}" >&2exit 1fiAPP_NAME="$(basename "${APP_PATH}" .app)"-VERSION="$(- awk -F= '- $1 ~ /^[[:space:]]*MARKETING_VERSION[[:space:]]*$/ {- value = $2- gsub(/^[[:space:]]+|[[:space:];]+$/, "", value)- print value- exit- }- ' "${VERSION_CONFIG}" 2>/dev/null || true-)"-BUILD="$(- awk -F= '- $1 ~ /^[[:space:]]*CURRENT_PROJECT_VERSION[[:space:]]*$/ {- value = $2- gsub(/^[[:space:]]+|[[:space:];]+$/, "", value)- print value- exit- }- ' "${VERSION_CONFIG}" 2>/dev/null || true-)"+INFO_PLIST="${APP_PATH}/Contents/Info.plist"+VERSION="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "${INFO_PLIST}" 2>/dev/null || true)"+BUILD="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleVersion' "${INFO_PLIST}" 2>/dev/null || true)"if [[ -z "${VERSION}" || -z "${BUILD}" ]]; then- echo "error: 无法从 Config/Version.xcconfig 读取 MARKETING_VERSION 或 CURRENT_PROJECT_VERSION" >&2+ echo "error: cannot read version information" >&2exit 1fi@@ -99,7 +81,7 @@ trap cleanup EXITrequire_command() {if ! command -v "$1" >/dev/null 2>&1; then- echo "error: 缺少命令: $1" >&2+ echo "error: missing command: $1" >&2exit 1fi}@@ -136,7 +118,7 @@ run_quietly diskutil image attach \"${RW_DMG}"if [[ -z "${MOUNT_POINT}" || ! -d "${MOUNT_POINT}" ]]; then- echo "error: 挂载 DMG 失败" >&2+ echo "error: failed to mount DMG" >&2exit 1fi@@ -173,7 +155,7 @@ APPLESCRIPTDS_STORE="${MOUNT_POINT}/.DS_Store"if [[ ! -s "${DS_STORE}" ]]; then- echo "warning: 没有写入 .DS_Store 窗口布局不会生效" >&2+ echo "warning: .DS_Store was not written; the Finder window layout will not take effect" >&2elseecho "==> Finder layout saved"fidiff --git a/Scripts/lib/validate.sh b/Scripts/lib/validate.shindex 11ca4be..7e7a71b 100644--- a/Scripts/lib/validate.sh+++ b/Scripts/lib/validate.sh@@ -44,7 +44,7 @@ validate_power_helper_manager_distribution() {validation_fail "Power Helper manager ${architecture} entitlements" "codesign could not read the entitlements"return 1fi- # 没有 entitlements 的管理 App 同样符合发布要求+ # The manager app can ship without entitlementsif [[ -s "${entitlements}" ]]; thenif ! plutil -lint "${entitlements}" >/dev/null 2>&1; thenvalidation_fail "Power Helper manager ${architecture} entitlements" "Invalid entitlements plist"diff --git a/Scripts/licenses.sh b/Scripts/licenses.shnew file mode 100755index 0000000..1c26a7d--- /dev/null+++ b/Scripts/licenses.sh@@ -0,0 +1,130 @@+#!/usr/bin/env bash+set -euo pipefail++# Download licenses at the commits pinned in Package.resolved and combine them in ThirdPartyLicenses.txt++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"+PACKAGE_RESOLVED="${PROJECT_DIR}/CodexBar.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved"+OUTPUT="${PROJECT_DIR}/CodexBar/Resources/ThirdPartyLicenses.txt"+PACKAGE_IDS=(swift-tree-sitter tree-sitter tree-sitter-bash sparkle)+SOURCES=()+VERSIONS=()+REVISIONS=()++fail() {+ echo "error: $*" >&2+ exit 1+}++read_value() {+ local value+ if ! value="$(plutil -extract "$1" raw -expect "${2:-string}" -o - "${PACKAGE_RESOLVED}" 2>&1)"; then+ fail "Cannot read $1 from Package.resolved: ${value}"+ fi+ printf '%s' "${value}"+}++package_index() {+ local index+ for index in "${!PACKAGE_IDS[@]}"; do+ if [[ "${PACKAGE_IDS[index]}" == "$1" ]]; then+ printf '%s' "${index}"+ return+ fi+ done+ fail "Add license sources for new package '$1' in Scripts/licenses.sh"+}++[[ "$#" -eq 0 ]] || fail "Usage: Scripts/licenses.sh (no arguments)"+[[ "$(read_value version integer)" == "3" ]] || fail "Expected Package.resolved format version 3"+pin_count="$(read_value pins array)"++for ((pin_index = 0; pin_index < pin_count; pin_index++)); do+ identity="$(read_value "pins.${pin_index}.identity")"+ index="$(package_index "${identity}")"+ [[ -z "${SOURCES[index]-}" ]] || fail "Duplicate package: ${identity}"+ [[ "$(read_value "pins.${pin_index}.kind")" == "remoteSourceControl" ]] || fail "Expected a Git source for ${identity}"++ source="$(read_value "pins.${pin_index}.location")"+ source="${source%/}"+ source="${source%.git}"+ version="$(read_value "pins.${pin_index}.state.version")"+ revision="$(read_value "pins.${pin_index}.state.revision")"+ [[ "${source}" =~ ^https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || fail "Expected a public GitHub source for ${identity}"+ [[ -n "${version}" && "${version}" != *$'\n'* && "${version}" != *$'\r'* ]] || fail "Invalid version for ${identity}"+ [[ "${revision}" =~ ^[0-9a-f]{40}$ ]] || fail "Expected a pinned Git revision for ${identity}"+ SOURCES[index]="${source}"+ VERSIONS[index]="${version}"+ REVISIONS[index]="${revision}"+done++for index in "${!PACKAGE_IDS[@]}"; do+ [[ -n "${SOURCES[index]-}" ]] || fail "Remove license sources for missing package '${PACKAGE_IDS[index]}' in Scripts/licenses.sh"+done++# Remove temporary files and directories on failure, keeping the existing license file+WORK_DIR="$(mktemp -d "${OUTPUT%/*}/.third-party-licenses.XXXXXX")"+TEMP_OUTPUT="${WORK_DIR}/licenses"+DOWNLOAD_PATH="${WORK_DIR}/download"+cleanup() {+ rm -f "${TEMP_OUTPUT}" "${DOWNLOAD_PATH}"+ rmdir "${WORK_DIR}"+}+trap cleanup EXIT+trap 'exit 130' INT+trap 'exit 143' TERM++append_license() {+ local identity="$1" title="$2" license_path="$3" version_prefix="${4:-}"+ local index source version revision repository body width+ index="$(package_index "${identity}")"+ source="${SOURCES[index]}"+ version="${VERSIONS[index]}"+ revision="${REVISIONS[index]}"+ repository="${source#https://github.com/}"++ echo "Fetching ${title} (${version})"+ curl --fail --silent --show-error --location \+ --proto '=https' --proto-redir '=https' \+ --connect-timeout 10 --max-time 30 --retry 1 --retry-max-time 65 \+ --output "${DOWNLOAD_PATH}" \+ "https://raw.githubusercontent.com/${repository}/${revision}/${license_path}"+ body="$(sed $'s/[ \t\r]*$//' "${DOWNLOAD_PATH}")"+ [[ -n "${body}" ]] || fail "Empty license for ${title}"++ width="${#title}"+ # Git treats a separator of seven equals signs as a conflict marker+ ((width >= 8)) || width=8+ {+ if [[ -s "${TEMP_OUTPUT}" ]]; then+ printf '\n\n'+ fi+ printf '%s\n' "${title}"+ printf '%*s\n' "${width}" '' | tr ' ' '='+ printf '\nVersion: %s%s\n' "${version_prefix}" "${version}"+ printf 'Source: %s\n' "${source}"+ printf 'License: %s/blob/%s/%s\n\n' "${source}" "${revision}" "${license_path}"+ printf '%s\n' "${body}"+ } >> "${TEMP_OUTPUT}"+}++append_license swift-tree-sitter SwiftTreeSitter LICENSE+append_license tree-sitter Tree-sitter LICENSE+append_license tree-sitter-bash tree-sitter-bash LICENSE+# Include the separate notice for Unicode content bundled with Tree-sitter+append_license tree-sitter 'Unicode data used by Tree-sitter' lib/src/unicode/LICENSE 'Bundled with Tree-sitter '+append_license sparkle Sparkle LICENSE++if [[ -f "${OUTPUT}" ]] && cmp -s "${TEMP_OUTPUT}" "${OUTPUT}"; then+ echo "ThirdPartyLicenses.txt is already up to date"+ exit 0+fi++if [[ -f "${OUTPUT}" ]]; then+ chmod "$(stat -f '%Lp' "${OUTPUT}")" "${TEMP_OUTPUT}"+else+ chmod 644 "${TEMP_OUTPUT}"+fi+mv -f "${TEMP_OUTPUT}" "${OUTPUT}"+echo "Updated CodexBar/Resources/ThirdPartyLicenses.txt"diff --git a/Scripts/performance/.gitignore b/Scripts/performance/.gitignoredeleted file mode 100644index c18dd8d..0000000--- a/Scripts/performance/.gitignore+++ /dev/null@@ -1 +0,0 @@-__pycache__/diff --git a/Scripts/performance/README.md b/Scripts/performance/README.mddeleted file mode 100644index e57d09c..0000000--- a/Scripts/performance/README.md+++ /dev/null@@ -1,130 +0,0 @@-# 性能测试使用说明--## 开始测试--准备 macOS、完整 Xcode 和 Python `3.11+`,启动待测试的 App。`xcode-select -p` 应指向 Xcode 的 `Contents/Developer` 目录,终端需具备 Instruments 采集权限。--在仓库根目录运行:--```sh-python3 -m Scripts.performance --preset quick-```--默认测试 `/Applications/CodexBar.app`。采集期间按测试场景操作 App,用 `--workload` 记录操作内容:--```sh-python3 -m Scripts.performance \- --preset standard \- --workload '反复打开面板、切换页面和滚动列表'-```--完成后打开终端打印的 `performance.html` 路径查看报告。--## 测试时长--| 预设 | 采集时长 | 用途 |-|---|---:|---|-| `quick` | 3 分钟 | 快速检查 |-| `standard` | 10 分钟 | 日常测试,默认预设 |-| `extended` | 30 分钟 | 长时间观察 |--时长是各阶段计划采集时间之和。预热、Instruments 启停和数据导出需要额外时间。--## 参数--| 参数 | 用法 |-|---|---|-| `--app PATH` | App 路径,默认 `/Applications/CodexBar.app` |-| `--pid PID` | 指定待测试进程,存在多个 App 实例时使用 |-| `--preset NAME` | 选择 `quick`、`standard` 或 `extended` |-| `--label TEXT` | 本次测试的标签,会追加到采集目录名末尾 |-| `--output PATH` | 配合 `--render` 指定 HTML 文件路径 |-| `--workload TEXT` | 记录测试场景说明,默认 default |-| `--baseline PATH` | 指定基线 `performance.json` |-| `--cpu-mean-budget NUMBER` | 各阶段平均 CPU 上限,单位为 `%` |-| `--footprint-budget NUMBER` | 各阶段 Footprint 峰值上限,单位为 `MiB` |-| `--render PATH` | 从指定 JSON 重新生成报告 |-| `-h`、`--help` | 查看命令帮助 |--## 输出位置--默认输出到仓库根目录下的 `Performance/{version}({build})-{preset}-YYYYMMDDHHmmss/`,日期和时间取测试启动时的本地时间,精确到秒。版本和构建号分别读取 `Config/Version.xcconfig` 中的 `MARKETING_VERSION` 和 `CURRENT_PROJECT_VERSION`,保留版本号中的点号。--```text-Performance/4.1.1(111)-extended-20261024140000/-├── performance.html-├── performance.json-├── schemas.json-├── tool-source/-├── *.trace-├── *.xml-└── *.log-```--`performance.html` 用于查看报告,`performance.json` 用于基线比较和重新生成报告,`*.trace` 可用 Instruments 打开。目录内同时保存采样 XML、命令日志和工具源码快照。--已有同名目录时,脚本会报错,保留已有结果。用 `--label` 添加测试标签,脚本会在默认目录名后追加 `-{标签}`。标签不能为空或包含 `/`:--```sh-python3 -m Scripts.performance --preset quick --label idle-```--例如,输出目录为 `Performance/4.1.1(111)-quick-20261024140000-idle/`--## 基线比较--先采集基线:--```sh-python3 -m Scripts.performance \- --preset quick \- --label idle-```--再次测试时指定实际生成目录中的基线文件,例如:--```sh-python3 -m Scripts.performance \- --preset quick \- --baseline 'Performance/4.1.1(111)-quick-20261024140000-idle/performance.json'-```--两个报告均完整,且应用标识、格式、测试配置与环境条件匹配时,报告计算各阶段的 CPU 均值和 Footprint 中位数差值;条件不匹配时列出原因。--CPU 使用 Instruments 导出的 `cpu-percent`,均值按同一采样行的 `duration` 加权;报告总均值按各阶段有效 CPU 采样时长加权。P50、P95 和峰值基于有效采样值计算,缺失值不计为零。CPU 采样覆盖率为有效区间总时长除以完整采样区间跨度。--## 性能预算--将平均 CPU 上限设为 `5%`,Footprint 峰值上限设为 `512 MiB`:--```sh-python3 -m Scripts.performance \- --cpu-mean-budget 5 \- --footprint-budget 512-```--预算值须为有限正数。超限阶段会写入报告。--| 退出码 | 含义 |-|---|---|-| `0` | 采集完成且预算检查通过,或重新生成报告成功 |-| `1` | 重新生成报告时,读取、解析 JSON 或生成 HTML 失败 |-| `2` | 参数错误,或采集及结果保存失败 |-| `3` | 采集完成,存在预算超限 |-| `130` | 用户中止采集 |--## 重新生成报告--从已有 JSON 重新生成 HTML 报告:--```sh-python3 -m Scripts.performance --render 'Performance/4.1.1(111)-quick-20261024140000-idle/performance.json'-```--默认更新 JSON 同目录的 `performance.html`。使用 `--output` 指定另一个 HTML 文件:--```sh-python3 -m Scripts.performance \- --render 'Performance/4.1.1(111)-quick-20261024140000-idle/performance.json' \- --output 'Performance/4.1.1(111)-quick-20261024140000-idle/performance-updated.html'-```diff --git a/Scripts/performance/__init__.py b/Scripts/performance/__init__.pydeleted file mode 100644index 1055a1a..0000000--- a/Scripts/performance/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""Instruments performance capture and self-contained reporting"""diff --git a/Scripts/performance/__main__.py b/Scripts/performance/__main__.pydeleted file mode 100644index 422d7cf..0000000--- a/Scripts/performance/__main__.py+++ /dev/null@@ -1,263 +0,0 @@-"""Non-invasive profiling of an already running macOS app, using xctrace"""--import argparse-import datetime as dt-import hashlib-import json-import os-import platform-import re-import signal-import sys-import tempfile-import time-from pathlib import Path-from types import FrameType-from typing import cast--sys.dont_write_bytecode = True--from .capture import capture, inspect_target, load_schemas, now, optional, record_phase, save, status-from .compare import compare-from .report import write_report-from .models import Phase, PhasePlan, Report--VERSION = "1"-ROOT = Path(__file__).resolve().parents[2]-PRESETS = {- "quick": (5, 30, 2, 90, 30),- "standard": (20, 60, 4, 300, 60),- "extended": (30, 120, 5, 900, 300),-}---class Arguments(argparse.Namespace):- app: Path- pid: int | None- preset: str- label: str | None- output: Path | None- workload: str- baseline: Path | None- cpu_mean_budget: float | None- footprint_budget: float | None- render: Path | None---def main() -> int:- parser = argparse.ArgumentParser(- prog="python3 -m Scripts.performance", description=__doc__- )- parser.add_argument("--app", type=Path, default=Path("/Applications/CodexBar.app"))- parser.add_argument("--pid", type=int)- parser.add_argument("--preset", choices=PRESETS, default="standard")- parser.add_argument("--label", help="Label this recording in its directory name")- parser.add_argument("--output", type=Path, help="Set the HTML output path with --render")- parser.add_argument("--workload", default="default")- parser.add_argument("--baseline", type=Path)- parser.add_argument("--cpu-mean-budget", type=float)- parser.add_argument("--footprint-budget", type=float, help="Physical footprint budget in MiB")- parser.add_argument("--render", type=Path, help="Regenerate HTML from an existing performance.json without profiling")- args = parser.parse_args(namespace=Arguments())- if args.render:- if args.label is not None:- parser.error("--label is only available when recording")- render_data = cast(Report, json.loads(args.render.read_text()))- destination = args.output if args.output is not None else args.render.parent / "performance.html"- write_report(render_data, destination)- print(destination)- return 0- if args.output is not None:- parser.error("--output requires --render")- for value in (args.cpu_mean_budget, args.footprint_budget):- if value is not None and (not 0 < value < float("inf")):- parser.error("Budgets must be finite positive numbers")- if args.label is not None and (not args.label or "/" in args.label):- parser.error("--label must be non-empty and must not contain '/'")- version_config = ROOT / "Config/Version.xcconfig"- try:- version_text = version_config.read_text()- except OSError as error:- parser.error(f"Cannot read {version_config}: {error}")- version_match = re.search(r"(?m)^\s*MARKETING_VERSION\s*=\s*(\d+(?:\.\d+)+)\s*$", version_text)- if version_match is None:- parser.error(f"Missing or invalid MARKETING_VERSION in {version_config}")- build_match = re.search(r"(?m)^\s*CURRENT_PROJECT_VERSION\s*=\s*(\d+(?:\.\d+)*)\s*$", version_text)- if build_match is None:- parser.error(f"Missing or invalid CURRENT_PROJECT_VERSION in {version_config}")- version = f"{version_match.group(1)}({build_match.group(1)})"- timestamp = dt.datetime.now().strftime("%Y%m%d%H%M%S")- output_name = f"{version}-{args.preset}-{timestamp}"- if args.label is not None:- output_name += f"-{args.label}"- output = (ROOT / "Performance" / output_name).resolve()- try:- output.mkdir(parents=True, exist_ok=False)- except OSError as error:- parser.error(f"Cannot create a new output directory: {error}")- os.chmod(output, 0o700)- data: Report = {- "format_version": VERSION,- "started": now(),- "state": "running",- "errors": [],- "config": {- "preset": args.preset,- "workload": args.workload,- "cpu_mean_budget": args.cpu_mean_budget,- "footprint_budget": args.footprint_budget,- },- "phases": [],- "environment": {"os": platform.mac_ver()[0], "arch": platform.machine()},- "target": {"name": args.app.stem},- }- exit_code = 0-- def stop(_signum: int, _frame: FrameType | None) -> None:- raise KeyboardInterrupt-- signal.signal(signal.SIGTERM, stop)- try:- if platform.system() != "Darwin":- raise RuntimeError("Recording requires macOS and full Xcode")- data["tool_sha256"] = {}- source_directory = output / "tool-source"- source_directory.mkdir()- for name in (- "__init__.py",- "__main__.py",- "analyze.py",- "models.py",- "capture.py",- "compare.py",- "report.py",- "performance.html",- ):- source = Path(__file__).with_name(name).read_bytes()- (source_directory / name).write_bytes(source)- data["tool_sha256"][name] = hashlib.sha256(source).hexdigest()- status("Preflight: target, Xcode, templates, schemas")- target = inspect_target(args.app.resolve(), args.pid)- data["target"] = target- target_identity = target.get("identity")- if target_identity is None:- raise RuntimeError("Target process identity is unavailable")- env = data["environment"]- env["instruments"] = capture(["/usr/bin/xcrun", "xctrace", "version"])- env["chip"] = optional(["/usr/sbin/sysctl", "-n", "machdep.cpu.brand_string"])- env["cores"] = optional(["/usr/sbin/sysctl", "-n", "hw.logicalcpu"])- env["memory_bytes"] = optional(["/usr/sbin/sysctl", "-n", "hw.memsize"])- env["power"] = optional(["/usr/bin/pmset", "-g", "batt"])- env["power_source"] = (env["power"] or "Unknown").splitlines()[0]- env["load_before"] = list(os.getloadavg())- templates = capture(["/usr/bin/xcrun", "xctrace", "list", "templates"], timeout=60)- for template in ("Time Profiler", "Activity Monitor"):- if template not in templates.splitlines():- raise RuntimeError(f"Missing Instruments template: {template}")- schemas = load_schemas(capture(["/usr/bin/xcode-select", "-p"]))- (output / "schemas.json").write_text(json.dumps(schemas, indent=2))- warmup, sample, repeats, soak, settle = PRESETS[args.preset]- data["config"]["warmup_s"] = warmup- plan: list[PhasePlan] = [- {- "id": f"cpu-{i + 1}",- "label": f"CPU repeat {i + 1}",- "seconds": sample,- "template": "Time Profiler",- }- for i in range(repeats)- ]- plan.extend([- {- "id": "soak",- "label": "Resource observation",- "seconds": soak,- "template": "Activity Monitor",- },- {- "id": "settle",- "label": "Follow-up observation",- "seconds": settle,- "template": "Activity Monitor",- },- ])- data["plan"] = plan- save(data, output)- status(- f"Warm-up {warmup}s; target PID {target_identity['pid']}; output {output}"- )- time.sleep(warmup)- for planned in plan:- phase: Phase = {"id": planned["id"], "label": planned["label"],- "seconds": planned["seconds"], "template": planned["template"]}- data["phases"].append(phase)- status(- f"Recording {phase['id']} ({phase['template']}, {phase['seconds']}s)"- )- record_phase(phase, data, output, schemas)- status(- f"Finished {phase['id']}: {'incomplete' if phase.get('errors') else 'valid'}"- )- save(data, output)- data["state"] = (- "complete"- if all(not p.get("errors") for p in data["phases"])- else "incomplete"- )- data["environment"]["load_after"] = list(os.getloadavg())- if args.baseline:- data["comparison"] = compare(data, args.baseline)- breached: list[str] = []- for phase in data["phases"]:- resource = phase.get("resources", {})- if phase.get("errors"):- continue- if args.cpu_mean_budget is not None:- cpu_mean = resource.get("cpu_mean", 0)- if cpu_mean is None:- raise ValueError("CPU budget requires a valid mean measurement")- if cpu_mean > args.cpu_mean_budget:- breached.append(phase["id"] + ": cpu_mean")- footprint = resource.get("footprint")- footprint_peak = footprint["max"] if footprint is not None else 0- if args.footprint_budget is not None and footprint_peak > args.footprint_budget:- breached.append(phase["id"] + ": footprint_peak")- data["budget_breaches"] = breached- exit_code = 2 if data["state"] != "complete" else 3 if breached else 0- except KeyboardInterrupt:- data["state"] = "interrupted"- data["errors"].append("Interrupted by operator; partial results retained")- exit_code = 130- except Exception as error:- data["state"] = "incomplete"- data["errors"].append(f"{type(error).__name__}: {error}")- exit_code = 2- finally:- data["ended"] = now()- data["exit_code"] = exit_code- report_output: Path | None = output- try:- save(data, output)- except Exception as error:- data["errors"].append(- f"Saving results failed: {type(error).__name__}: {error}"- )- data["state"] = "incomplete"- exit_code = data["exit_code"] = 2- for message in data["errors"]:- status(message)- try:- report_output = Path(tempfile.mkdtemp(prefix="codexbar-performance-recovery-"))- save(data, report_output)- except Exception as recovery_error:- status(- f"Recovery save failed: {type(recovery_error).__name__}: {recovery_error}"- )- report_output = None- if report_output is not None:- status(f"Report: {report_output / 'performance.html'}; exit {exit_code}")- return exit_code---if __name__ == "__main__":- sys.exit(main())diff --git a/Scripts/performance/analyze.py b/Scripts/performance/analyze.pydeleted file mode 100644index 56daf4b..0000000--- a/Scripts/performance/analyze.py+++ /dev/null@@ -1,259 +0,0 @@-"""Decode xctrace XML using the schemas shipped with the recording Xcode"""--import collections-import math-import statistics-import xml.etree.ElementTree as ET-from collections.abc import Iterator, Sequence-from pathlib import Path-from typing import IO, Literal, overload--from .models import Events, MetricKey, Profile, Resources, Sample, SystemSummary---def percentile(values: Sequence[float], fraction: float) -> float | None:- if not values:- return None- values = sorted(values)- position = (len(values) - 1) * fraction- lower = math.floor(position)- upper = math.ceil(position)- return values[lower] + (values[upper] - values[lower]) * (position - lower)---class Table:- def __init__(self, path: Path | IO[str], columns: Sequence[str]) -> None:- self.root = ET.parse(path).getroot()- self.ids = {key: e for e in self.root.iter() if (key := e.get("id"))}- self.columns = columns-- @overload- def resolve(self, element: ET.Element) -> ET.Element:- ...-- @overload- def resolve(self, element: None) -> None:- ...-- def resolve(self, element: ET.Element | None) -> ET.Element | None:- if element is None:- return None- reference = element.get("ref")- return self.ids[reference] if reference else element-- def number(self, element: ET.Element | None) -> float | None:- element = self.resolve(element)- if element is None or element.tag == "sentinel":- return None- text = element.text- if text is None:- return None- try:- value = float(text)- return value if math.isfinite(value) else None- except (ValueError, TypeError):- return None-- def label(self, element: ET.Element | None) -> str:- element = self.resolve(element)- return "" if element is None else element.get("fmt", element.text or "")-- def rows(self) -> Iterator[dict[str, ET.Element]]:- for row in self.root.iter("row"):- if len(row) != len(self.columns):- raise ValueError(f"Schema mismatch: expected {len(self.columns)} columns, got {len(row)}")- yield dict(zip(self.columns, row))---def resource_summary(table: Table, pid: int) -> Resources:- points: list[tuple[float, dict[str, float | None]]] = []- for row in table.rows():- if table.number(row.get("pid")) != pid:- continue- point = {key: table.number(value) for key, value in row.items()}- start = point.get("start")- if start is not None:- points.append((start, point))- points.sort(key=lambda p: p[0])- if len(points) < 3:- raise ValueError("Fewer than 3 target resource samples")- series: list[Sample] = []- errors: list[str] = []- interval_end = points[0][0]- memory_fields: list[tuple[str, MetricKey]] = [- ("memory-physical-footprint", "footprint"),- ("memory-real", "rss"), ("memory-compressed", "compressed"),- ]- for start, point in points:- timestamp = start / 1e9- item: Sample = {"t": timestamp, "cpu": None, "dt": None,- "footprint": None, "rss": None, "compressed": None, "threads": None}- for source, destination in memory_fields:- value = point.get(source)- item[destination] = value / 2 ** 20 if value is not None else None- item["threads"] = point.get("thread-count")- duration, cpu = point.get("duration"), point.get("cpu-percent")- if duration is None or duration <= 0:- errors.append("Resource sample duration is missing or nonpositive")- elif start < interval_end:- errors.append("Resource sample intervals overlap")- else:- interval_end = start + duration- # Instruments pairs each CPU percentage with the duration in the same row- if cpu is not None:- if cpu < 0:- errors.append("CPU percentage is negative")- else:- item["cpu"] = cpu- item["dt"] = duration / 1e9- series.append(item)- span = series[-1]["t"] - series[0]["t"]- if span <= 0:- raise ValueError("Resource sample time did not advance")- cpu_points = [(p["cpu"], p["dt"]) for p in series if p["cpu"] is not None and p["dt"] is not None]- observed_seconds = sum(duration for _, duration in cpu_points)- cpu_span = (max(interval_end, points[-1][0]) - points[0][0]) / 1e9- cpu_values = [value for value, _ in cpu_points]- result: Resources = {- "samples": len(series),- "span_s": span,- "series": series,- "errors": errors,- "max_gap_s": max(b["t"] - a["t"] for a, b in zip(series, series[1:])),- "cpu_coverage": observed_seconds / cpu_span,- "cpu_mean": sum(value * duration for value, duration in cpu_points) / observed_seconds if observed_seconds else None,- "cpu_p50": percentile(cpu_values, .5),- "cpu_p95": percentile(cpu_values, .95),- "cpu_peak": max(cpu_values) if cpu_values else None,- "footprint": None,- "rss": None,- "compressed": None,- "threads": None,- "wakeups": None,- "wakeups_per_s": None,- "read_bytes": None,- "read_bytes_per_s": None,- "written_bytes": None,- "written_bytes_per_s": None- }- metric_keys: tuple[MetricKey, ...] = ("footprint", "rss", "compressed", "threads")- for key in metric_keys:- values = [value for p in series if (value := p[key]) is not None]- result[key] = {- "first": values[0],- "last": values[-1],- "min": min(values),- "max": max(values),- "median": statistics.median(values)- } if values else None- counters: tuple[tuple[str, Literal["wakeups", "read_bytes", "written_bytes"],- Literal["wakeups_per_s", "read_bytes_per_s", "written_bytes_per_s"]], ...] = (- ("idle-wakeups", "wakeups", "wakeups_per_s"),- ("disk-bytes-read", "read_bytes", "read_bytes_per_s"),- ("disk-bytes-written", "written_bytes", "written_bytes_per_s"),- )- for source_key, name, rate_name in counters:- first, last = points[0][1].get(source_key), points[-1][1].get(source_key)- difference = last - first if first is not None and last is not None and last >= first else None- result[name] = difference- result[rate_name] = difference / span if difference is not None else None- footprint = [(p["t"], value) for p in series if (value := p["footprint"]) is not None]- if len(footprint) >= 3:- xs, ys = zip(*footprint)- xmean, ymean = statistics.mean(xs), statistics.mean(ys)- denominator = sum((x - xmean) ** 2 for x in xs)- slope = sum((x - xmean) * (y - ymean) for x, y in footprint) / denominator if denominator else 0- window = min(60, span / 4)- head = [y for x, y in footprint if x <= xs[0] + window]- tail = [y for x, y in footprint if x >= xs[-1] - window]- result["memory_trend"] = {- "slope_mib_min": slope * 60,- "window_s": window,- "head_median": statistics.median(head),- "tail_median": statistics.median(tail),- "delta_mib": statistics.median(tail) - statistics.median(head),- "long_enough": span >= 240- }- return result---def profile_summary(table: Table, pid: int) -> Profile:- total: float = 0- main: float = 0- missing: float = 0- app_weight: float = 0- app_named: float = 0- leaf: collections.defaultdict[str, float] = collections.defaultdict(float)- inclusive: collections.defaultdict[str, float] = collections.defaultdict(float)- binaries: collections.defaultdict[str, float] = collections.defaultdict(float)- seconds: collections.defaultdict[int, float] = collections.defaultdict(float)- for row in table.rows():- process = table.resolve(row.get("process"))- process_pid = table.number(process.find("pid")) if process is not None else None- if process_pid != pid:- continue- weight = table.number(row.get("weight"))- if weight is None:- continue- weight /= 1e6- total += weight- thread = table.label(row.get("thread"))- if "Main Thread" in thread:- main += weight- timestamp = table.number(row.get("time"))- if timestamp is not None:- seconds[int(timestamp / 1e9)] += weight- stack = table.resolve(row.get("stack"))- frames = [table.resolve(f) for f in stack.findall("frame")] if stack is not None else []- if not frames:- missing += weight- continue- names = {f.get("name", "Unknown") for f in frames}- first = frames[0]- leaf[first.get("name", "Unknown")] += weight- for name in names:- inclusive[name] += weight- binary = table.resolve(first.find("binary"))- binaries[binary.get("name", "Unknown") if binary is not None else "Unknown"] += weight- app_frames: list[str] = []- for frame in frames:- binary = table.resolve(frame.find("binary"))- if binary is not None and ".app/Contents/MacOS/" in binary.get("path", ""):- app_frames.append(frame.get("name", ""))- if app_frames:- app_weight += weight- if any(n and not n.startswith("0x") and n != "<deduplicated_symbol>" for n in app_frames):- app_named += weight- return {- "sampled_ms": total,- "main_ms": main,- "missing_stack_ms": missing,- "app_stack_ms": app_weight,- "app_named_stack_ms": app_named,- "leaf": sorted(leaf.items(), key=lambda item: item[1], reverse=True)[:18],- "inclusive": sorted(inclusive.items(), key=lambda item: item[1], reverse=True)[:35],- "binaries": sorted(binaries.items(), key=lambda item: item[1], reverse=True)[:15],- "busiest_seconds": sorted(seconds.items(), key=lambda item: item[1], reverse=True)[:8]- }---def event_summary(table: Table, pid: int | None = None) -> Events:- rows: list[dict[str, str]] = []- for row in table.rows():- if pid is not None and "process" in row:- process = table.resolve(row["process"])- if table.number(process.find("pid")) != pid:- continue- rows.append({key: table.label(value) for key, value in row.items()- if key not in ("backtrace", "process", "thread")})- return {"count": len(rows), "events": rows[:100]}---def system_summary(table: Table) -> SystemSummary:- values: list[float] = []- for row in table.rows():- value = table.number(row.get("cpu-total-load"))- if value is not None:- values.append(value)- return {"samples": len(values), "cpu_load_mean": statistics.mean(values) if values else None,- "cpu_load_peak": max(values) if values else None}diff --git a/Scripts/performance/capture.py b/Scripts/performance/capture.pydeleted file mode 100644index d19e594..0000000--- a/Scripts/performance/capture.py+++ /dev/null@@ -1,345 +0,0 @@-"""Non-invasive profiling of an already running macOS app, using xctrace"""--import ctypes-import datetime as dt-import hashlib-import json-import os-import plistlib-import re-import signal-import subprocess-import time-import xml.etree.ElementTree as ET-from pathlib import Path---from .analyze import (- Table,- event_summary,- profile_summary,- resource_summary,- system_summary,-)-from .report import write_report-from .models import (CommandResult, Phase, ProcessIdentity, Report, SchemaKey, Schemas, Target)--SCHEMAS: tuple[SchemaKey, ...] = (- "activity-monitor-process-live",- "time-profile",- "potential-hangs",- "hang-risks",- "device-thermal-state-intervals",- "activity-monitor-system",-)---def now() -> str:- return dt.datetime.now().astimezone().isoformat(timespec="seconds")---def status(message: str) -> None:- print(f"[{now()}] {message}", flush=True)---def capture(args: list[str], timeout: float = 20) -> str:- result = subprocess.run(args, capture_output=True, timeout=timeout)- if result.returncode:- raise RuntimeError(- f"{args[0]} exited {result.returncode}: {result.stderr.decode(errors='replace')[-1000:]}"- )- return result.stdout.decode(errors="replace").strip()---def optional(args: list[str]) -> str | None:- try:- return capture(args)- except (OSError, RuntimeError, subprocess.TimeoutExpired):- return None---def process_path(pid: int) -> Path | None:- lib = ctypes.CDLL("/usr/lib/libproc.dylib")- lib.proc_pidpath.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32]- lib.proc_pidpath.restype = ctypes.c_int- buffer = ctypes.create_string_buffer(4096)- size = lib.proc_pidpath(pid, buffer, len(buffer))- return Path(os.fsdecode(buffer.value)).resolve() if size > 0 else None---def identity(pid: int) -> ProcessIdentity:- path = process_path(pid)- started = optional(["/bin/ps", "-p", str(pid), "-o", "lstart="])- return {"pid": pid, "path": str(path) if path else None, "started": started}---def inspect_target(app: Path, pid: int | None) -> Target:- info = plistlib.loads((app / "Contents/Info.plist").read_bytes())- executable = (app / "Contents/MacOS" / info["CFBundleExecutable"]).resolve()- if not executable.is_file():- raise ValueError("App executable does not exist")- if pid is None:- candidates = [int(p) for p in capture(["/bin/ps", "-A", "-o", "pid="]).split()]- matches = [p for p in candidates if process_path(p) == executable]- if len(matches) != 1:- raise ValueError(- f"Expected one running instance of {app.name}, found {len(matches)}; specify --pid"- )- pid = matches[0]- original = identity(pid)- if original["path"] != str(executable) or not original["started"]:- raise ValueError("PID does not match the requested app executable")- entitlements = subprocess.run(- ["/usr/bin/codesign", "-d", "--entitlements", ":-", str(app)],- capture_output=True,- timeout=20,- )- ent = None- for stream in (entitlements.stdout, entitlements.stderr):- start = stream.find(b"<?xml")- end = stream.find(b"</plist>")- if 0 <= start <= end:- ent = plistlib.loads(stream[start: end + len(b"</plist>")])- break- uuids = optional(["/usr/bin/xcrun", "dwarfdump", "--uuid", str(executable)])- uuid_list = re.findall(r"UUID: ([A-Fa-f0-9-]+) \(([^)]+)\)", uuids or "")- with executable.open("rb") as file:- binary_hash = hashlib.file_digest(file, "sha256").hexdigest()- return {- "name": app.stem,- "bundle_id": info.get("CFBundleIdentifier"),- "version": info.get("CFBundleShortVersionString"),- "build": info.get("CFBundleVersion"),- "binary_sha256": binary_hash,- "uuids": uuid_list,- "get_task_allow": bool(ent.get("com.apple.security.get-task-allow"))- if ent is not None- else None,- "identity": original,- }---def load_schemas(developer: str) -> Schemas:- base = Path(developer).parent / "Applications/Instruments.app/Contents/Packages"- found: Schemas = {}- for path in base.rglob("schemas.xml"):- for schema in ET.parse(path).getroot().findall("schema"):- name = schema.get("name")- for known_name in SCHEMAS:- if name != known_name:- continue- columns = [c.get("mnemonic") for c in schema.findall("column")]- if any(column is None for column in columns):- raise ValueError(f"Missing column mnemonic in schema: {name}")- found[known_name] = [column for column in columns if column is not None]- if "activity-monitor-process-live" not in found:- raise RuntimeError(- "No Activity Monitor column schema found in the selected Xcode"- )- return found---def run_command(- args: list[str], logfile: Path, timeout: float, expected: ProcessIdentity | None = None,-) -> CommandResult:- began = time.monotonic()- interrupted = False- failure = None- directory = logfile.parent.stat()-- def check_output() -> None:- try:- current = logfile.parent.stat()- if (current.st_dev, current.st_ino) == (directory.st_dev, directory.st_ino):- return- except FileNotFoundError:- pass- raise RuntimeError(- f"Output directory removed or replaced during capture: {logfile.parent}"- )-- with logfile.open("w") as log:- process = subprocess.Popen(- args, stdout=log, stderr=subprocess.STDOUT, start_new_session=True- )- try:- while process.poll() is None:- check_output()- elapsed = time.monotonic() - began- if elapsed >= timeout:- failure = "Command timeout"- break- if expected and identity(expected["pid"]) != expected:- failure = "Target exited or process identity changed"- break- time.sleep(1)- except KeyboardInterrupt:- interrupted = True- finally:- if process.poll() is None:- os.killpg(process.pid, signal.SIGINT)- try:- process.wait(timeout=20)- except subprocess.TimeoutExpired:- os.killpg(process.pid, signal.SIGKILL)- process.wait(timeout=10)- check_output()- result: CommandResult = {- "argv": args,- "exit_code": process.returncode,- "elapsed_s": round(time.monotonic() - began, 2),- "log": logfile.name,- }- if failure:- result["error"] = failure- if interrupted:- raise KeyboardInterrupt- return result---def save(data: Report, output: Path) -> None:- temporary = output / "performance.json.tmp"- temporary.write_text(- json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False) + "\n"- )- temporary.replace(output / "performance.json")- write_report(data, output / "performance.html")---def analyze_phase(phase: Phase, output: Path, schemas: Schemas, pid: int) -> None:- for name, columns in schemas.items():- file = output / f"{phase['id']}-{name}.xml"- if not file.exists() or name not in phase.get("exported", []):- continue- try:- table = Table(file, columns)- if name == "activity-monitor-process-live":- phase["resources"] = resource_summary(table, pid)- elif name == "time-profile":- phase["profile"] = profile_summary(table, pid)- elif name == "activity-monitor-system":- phase["system"] = system_summary(table)- else:- phase[name] = event_summary(- table, pid if name in ("potential-hangs", "hang-risks") else None- )- except (ValueError, KeyError, ET.ParseError, TypeError) as error:- phase.setdefault("errors", []).append(f"{name}: {error}")---def record_phase(phase: Phase, data: Report, output: Path, schemas: Schemas) -> None:- target = data["target"].get("identity")- if target is None:- raise RuntimeError("Target process identity is unavailable")- if identity(target["pid"]) != target:- raise RuntimeError("Target process changed before recording")- phase["started"] = now()- errors: list[str] = []- commands: list[CommandResult] = []- exported: list[SchemaKey] = []- phase["errors"] = errors- phase["commands"] = commands- phase["exported"] = exported- phase["trace"] = phase["id"] + ".trace"- args = [- "/usr/bin/xcrun",- "xctrace",- "record",- "--template",- phase["template"],- "--attach",- str(target["pid"]),- "--time-limit",- f"{phase['seconds']}s",- "--output",- str(output / phase["trace"]),- "--no-prompt",- ]- if phase["template"] == "Time Profiler":- args.extend(["--instrument", "Activity Monitor"])- command = run_command(- args, output / f"{phase['id']}-record.log", phase["seconds"] + 150, target- )- commands.append(command)- if command["exit_code"] or command.get("error"):- errors.append(- command.get("error", "xctrace recording failed; see record log")- )- elif "[Error]" in (output / command["log"]).read_text(errors="replace"):- errors.append("xctrace reported an error despite a zero exit code")- if identity(target["pid"]) != target:- errors.append("Target identity changed during recording")- trace = output / phase["trace"]- if not trace.exists():- errors.append("No trace artifact was created")- return- toc = output / f"{phase['id']}-toc.xml"- cmd = run_command(- [- "/usr/bin/xcrun",- "xctrace",- "export",- "--input",- str(trace),- "--toc",- "--output",- str(toc),- ],- output / f"{phase['id']}-toc.log",- 120,- )- commands.append(cmd)- if cmd["exit_code"] or cmd.get("error"):- errors.append("TOC export failed")- return- root = ET.parse(toc).getroot()- duration = root.findtext(".//summary/duration", "0")- phase["recorded_s"] = float(duration)- phase["trace_started"] = root.findtext(".//summary/start-date")- phase["hang_settings"] = [- e.text for e in root.findall(".//instrument[@name='Hangs']//key")- ]- phase["tables"] = [e.get("schema") for e in root.findall(".//data/table")]- if phase["recorded_s"] < phase["seconds"] * 0.9:- errors.append("Recording duration below 90% of requested duration")- for name in SCHEMAS:- if name not in phase["tables"] or name not in schemas:- continue- xml = output / f"{phase['id']}-{name}.xml"- cmd = run_command(- [- "/usr/bin/xcrun",- "xctrace",- "export",- "--input",- str(trace),- "--xpath",- f'/trace-toc/run[@number="1"]/data/table[@schema="{name}"]',- "--output",- str(xml),- ],- output / f"{phase['id']}-{name}.log",- 120,- )- commands.append(cmd)- if cmd["exit_code"] or cmd.get("error"):- errors.append(f"{name}: export failed")- else:- exported.append(name)- analyze_phase(phase, output, schemas, target["pid"])- if "resources" not in phase:- errors.append("No valid resource measurements")- else:- resource = phase["resources"]- errors.extend(resource["errors"])- if resource["span_s"] < phase["seconds"] * 0.8:- errors.append("Resource coverage below 80% of requested duration")- if resource["max_gap_s"] > 5:- errors.append("Resource sample gap exceeds 5 seconds")- if resource["cpu_coverage"] < 0.95:- errors.append("CPU sample coverage below 95%")- if resource.get("footprint") is None:- errors.append("Physical footprint was not available")- if phase["template"] == "Time Profiler" and "profile" not in phase:- errors.append("No decoded CPU profile")- phase["ended"] = now()diff --git a/Scripts/performance/compare.py b/Scripts/performance/compare.pydeleted file mode 100644index 5992331..0000000--- a/Scripts/performance/compare.py+++ /dev/null@@ -1,59 +0,0 @@-import json-from pathlib import Path-from typing import Literal, cast--from .models import Comparison, Report--def compare(data: Report, path: Path) -> Comparison:- previous = cast(Report, json.loads(path.read_text()))- keys: list[tuple[Literal["target", "environment", "config"], str]] = [- ("target", "bundle_id"),- ("environment", "os"),- ("environment", "chip"),- ("environment", "arch"),- ("environment", "cores"),- ("environment", "memory_bytes"),- ("environment", "power_source"),- ("environment", "instruments"),- ("config", "workload"),- ("config", "preset"),- ("config", "cpu_mean_budget"),- ("config", "footprint_budget"),- ]- differences = [- f"{a}.{b}"- for a, b in keys- if data.get(a, {}).get(b) != previous.get(a, {}).get(b)- ]- if data.get("format_version") != previous.get("format_version"):- differences.append("format_version")- if previous.get("state") != "complete":- differences.append("baseline.state")- if data.get("state") != "complete":- differences.append("current.state")- if [(p["id"], p["seconds"]) for p in data["phases"]] != [- (p["id"], p["seconds"]) for p in previous.get("phases", [])- ]:- differences.append("phase_plan")- result: Comparison = {- "baseline_version": previous.get("target", {}).get("version"),- "compatible": not differences,- "differences": differences,- "deltas": [],- }- if not differences:- for current, old in zip(data["phases"], previous["phases"]):- a, b = current.get("resources"), old.get("resources")- if a and b and not current.get("errors") and not old.get("errors"):- current_cpu, old_cpu = a["cpu_mean"], b["cpu_mean"]- current_memory, old_memory = a["footprint"], b["footprint"]- if current_cpu is None or old_cpu is None or current_memory is None or old_memory is None:- raise ValueError("Complete phases must contain CPU and footprint measurements")- result["deltas"].append(- {- "phase": current["id"],- "cpu_pp": current_cpu - old_cpu,- "footprint_mib": current_memory["median"] - old_memory["median"],- }- )- return resultdiff --git a/Scripts/performance/models.py b/Scripts/performance/models.pydeleted file mode 100644index 09096ac..0000000--- a/Scripts/performance/models.py+++ /dev/null@@ -1,197 +0,0 @@-"""Types for capture and report dictionaries"""--from typing import Literal, NotRequired, TypedDict--MetricKey = Literal["footprint", "rss", "compressed", "threads"]-SeriesKey = Literal["cpu", "footprint", "rss", "compressed", "threads"]-StatisticKey = Literal["first", "last", "min", "max", "median"]-ResourceValueKey = Literal[- "cpu_mean", "cpu_p50", "cpu_p95", "cpu_peak", "wakeups", "wakeups_per_s",- "read_bytes", "read_bytes_per_s", "written_bytes", "written_bytes_per_s",-]-EventKey = Literal["potential-hangs", "hang-risks", "device-thermal-state-intervals"]-SchemaKey = Literal[- "activity-monitor-process-live", "time-profile", "potential-hangs", "hang-risks",- "device-thermal-state-intervals", "activity-monitor-system",-]-Schemas = dict[SchemaKey, list[str]]---class Sample(TypedDict):- t: float- cpu: float | None- dt: float | None- footprint: float | None- rss: float | None- compressed: float | None- threads: float | None---class Statistics(TypedDict):- first: float- last: float- min: float- max: float- median: float---class MemoryTrend(TypedDict):- slope_mib_min: float- window_s: float- head_median: float- tail_median: float- delta_mib: float- long_enough: bool---class Resources(TypedDict):- samples: int- span_s: float- series: list[Sample]- errors: list[str]- max_gap_s: float- cpu_coverage: float- cpu_mean: float | None- cpu_p50: float | None- cpu_p95: float | None- cpu_peak: float | None- footprint: Statistics | None- rss: Statistics | None- compressed: Statistics | None- threads: Statistics | None- wakeups: float | None- wakeups_per_s: float | None- read_bytes: float | None- read_bytes_per_s: float | None- written_bytes: float | None- written_bytes_per_s: float | None- memory_trend: NotRequired[MemoryTrend]---class Profile(TypedDict):- sampled_ms: float- main_ms: float- missing_stack_ms: float- app_stack_ms: float- app_named_stack_ms: float- leaf: list[tuple[str, float]]- inclusive: list[tuple[str, float]]- binaries: list[tuple[str, float]]- busiest_seconds: list[tuple[int, float]]---class Events(TypedDict):- count: int- events: list[dict[str, str]]---class SystemSummary(TypedDict):- samples: int- cpu_load_mean: float | None- cpu_load_peak: float | None---class ProcessIdentity(TypedDict):- pid: int- path: str | None- started: str | None---class Target(TypedDict):- name: str- bundle_id: NotRequired[str | None]- version: NotRequired[str | None]- build: NotRequired[str | None]- binary_sha256: NotRequired[str]- uuids: NotRequired[list[tuple[str, str]]]- get_task_allow: NotRequired[bool | None]- identity: NotRequired[ProcessIdentity]---class CommandResult(TypedDict):- argv: list[str]- exit_code: int | None- elapsed_s: float- log: str- error: NotRequired[str]---class PhasePlan(TypedDict):- id: str- label: str- seconds: int- template: str---PhaseEvents = TypedDict("PhaseEvents", {- "potential-hangs": Events,- "hang-risks": Events,- "device-thermal-state-intervals": Events,-}, total=False)---class Phase(PhasePlan, PhaseEvents):- started: NotRequired[str]- ended: NotRequired[str]- errors: NotRequired[list[str]]- commands: NotRequired[list[CommandResult]]- exported: NotRequired[list[SchemaKey]]- trace: NotRequired[str]- recorded_s: NotRequired[float]- trace_started: NotRequired[str | None]- hang_settings: NotRequired[list[str | None]]- tables: NotRequired[list[str | None]]- resources: NotRequired[Resources]- profile: NotRequired[Profile]- system: NotRequired[SystemSummary]---class Config(TypedDict):- preset: str- workload: str- cpu_mean_budget: float | None- footprint_budget: float | None- warmup_s: NotRequired[int]---class Environment(TypedDict):- os: str- arch: str- instruments: NotRequired[str]- chip: NotRequired[str | None]- cores: NotRequired[str | None]- memory_bytes: NotRequired[str | None]- power: NotRequired[str | None]- power_source: NotRequired[str]- load_before: NotRequired[list[float]]- load_after: NotRequired[list[float]]---class Delta(TypedDict):- phase: str- cpu_pp: float- footprint_mib: float---class Comparison(TypedDict):- baseline_version: str | None- compatible: bool- differences: list[str]- deltas: list[Delta]---class Report(TypedDict):- format_version: str- started: str- state: str- errors: list[str]- config: Config- phases: list[Phase]- environment: Environment- target: Target- ended: NotRequired[str]- exit_code: NotRequired[int]- tool_sha256: NotRequired[dict[str, str]]- plan: NotRequired[list[PhasePlan]]- comparison: NotRequired[Comparison]- budget_breaches: NotRequired[list[str]]diff --git a/Scripts/performance/performance.html b/Scripts/performance/performance.htmldeleted file mode 100644index 5f24b73..0000000--- a/Scripts/performance/performance.html+++ /dev/null@@ -1,1279 +0,0 @@-<!doctype html>-<html lang="zh-CN">- <head>- <meta charset="utf-8" />- <meta name="viewport" content="width=device-width,initial-scale=1" />- <meta name="color-scheme" content="light dark" />- <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; connect-src 'none'; base-uri 'none'; form-action 'none'" />- <title>@@TITLE@@</title>- <style>- @font-face {- font-family: 'Report Latin';- src: local('MesloLGS NF Regular'), local('MesloLGS-NF-Regular');- font-weight: 400;- unicode-range: U+0000-024F, U+1E00-1EFF;- }- @font-face {- font-family: 'Report Latin';- src: local('MesloLGS NF Bold'), local('MesloLGS-NF-Bold');- font-weight: 700;- unicode-range: U+0000-024F, U+1E00-1EFF;- }- :root {- color-scheme: light;- --bg: #eef2f6;- --card: #ffffff;- --surface: #f5f7fa;- --ink: #1b293d;- --muted: #5d6b80;- --line: #d8e0eb;- --teal: #087e83;- --violet: #7055d0;- --warn: #956017;- --rose: #bd4264;- --soft: #e7f3f3;- --nav: #f7f9fc;- --report-font: -apple-system, BlinkMacSystemFont, 'PingFang SC', sans-serif;- --mono: 'Report Latin', 'SFMono-Regular', Consolas, var(--report-font);- }- * {- box-sizing: border-box;- }- html {- scroll-behavior: smooth;- scroll-padding-top: 24px;- }- body {- margin: 0;- background: var(--bg);- color: var(--ink);- font: 13px/1.6 var(--report-font);- -webkit-font-smoothing: antialiased;- }- body.dark {- color-scheme: dark;- --bg: #080d18;- --card: #111a2b;- --surface: #0d1524;- --ink: #e8eef9;- --muted: #9baac1;- --line: #253249;- --teal: #51ddd2;- --violet: #ae9aff;- --warn: #f3be6b;- --rose: #f28da9;- --soft: #152e37;- --nav: #0b1120;- }- a {- color: var(--teal);- text-decoration: none;- }- a:hover {- text-decoration: underline;- }- button,- input {- font: inherit;- }- button {- cursor: pointer;- }- :is(button, a, summary, input):focus-visible {- outline: 2px solid var(--teal);- outline-offset: 4px;- }- [hidden] {- display: none !important;- }- .shell {- display: grid;- grid-template-columns: 190px minmax(0, 1fr);- max-width: 1920px;- margin: auto;- }- .sidebar {- background: var(--nav);- color: var(--muted);- padding: 28px 16px;- position: sticky;- top: 0;- height: 100vh;- overflow-y: auto;- border-right: 1px solid var(--line);- display: flex;- flex-direction: column;- }- .brand {- font: 10px var(--mono);- letter-spacing: 0.16em;- color: var(--teal);- }- .brand::before {- content: '';- display: inline-block;- width: 6px;- height: 6px;- margin-right: 7px;- background: var(--teal);- box-shadow: 0 0 12px var(--teal);- }- .sidebar strong {- font-size: 24px;- letter-spacing: -0.04em;- color: var(--ink);- margin: 8px 0 32px;- }- .sidebar nav a {- display: flex;- align-items: center;- color: var(--muted);- padding: 10px 9px;- margin: 3px 0;- border: 1px solid transparent;- border-radius: 6px;- font-size: 12px;- }- .sidebar nav a:hover,- .sidebar nav a.active {- color: var(--teal);- background: var(--soft);- border-color: var(--line);- text-decoration: none;- }- .sidebar nav span {- width: 27px;- font: 10px var(--mono);- opacity: 0.6;- }- .side-note {- border-top: 1px solid var(--line);- margin-top: auto;- padding-top: 20px;- font: 11px/2 var(--mono);- }- .side-note span {- display: block;- color: var(--muted);- font-size: 9px;- letter-spacing: 0.13em;- }- .main {- padding: 26px 30px 32px;- min-width: 0;- }- .topline,- .section-head {- display: flex;- justify-content: space-between;- align-items: center;- gap: 16px;- }- .eyebrow {- font: 10px var(--mono);- letter-spacing: 0.12em;- text-transform: uppercase;- color: var(--teal);- }- .actions {- display: flex;- gap: 6px;- flex-wrap: wrap;- }- .actions button {- padding: 5px 10px;- border: 1px solid var(--line);- border-radius: 5px;- background: var(--card);- color: var(--muted);- font-size: 11px;- }- .actions button:hover {- border-color: var(--teal);- color: var(--ink);- }- h1 {- font-size: clamp(26px, 3vw, 38px);- line-height: 1.3;- letter-spacing: -0.045em;- margin: 16px 0 8px;- }- h1 span {- color: var(--muted);- font-weight: 400;- font-size: 0.62em;- letter-spacing: 0;- margin-left: 12px;- }- h2 {- font-size: 19px;- letter-spacing: -0.02em;- margin: 0;- }- h3 {- font-size: 13px;- line-height: 1.5;- margin: 0 0 10px;- }- h4 {- font-size: 12px;- margin: 0 0 12px;- }- p {- margin: 8px 0 12px;- }- .muted {- color: var(--muted);- font-size: 11px;- }- .meta {- display: flex;- align-items: center;- gap: 14px;- flex-wrap: wrap;- color: var(--muted);- font-size: 11px;- margin: 10px 0 16px;- }- .badge {- display: inline-flex;- align-items: center;- gap: 6px;- padding: 3px 9px;- border-radius: 4px;- font-size: 10px;- white-space: nowrap;- }- .badge::before {- content: '';- width: 5px;- height: 5px;- border-radius: 50%;- background: currentColor;- }- .badge.ok {- color: var(--teal);- background: var(--soft);- }- .badge.warn {- color: var(--warn);- background: var(--surface);- box-shadow: inset 0 0 0 1px var(--warn);- }- .hero-rule {- height: 1px;- background: linear-gradient(90deg, var(--teal), var(--violet) 45%, var(--line));- margin: 16px 0;- }- .kpis {- display: grid;- grid-template-columns: repeat(4, minmax(0, 1fr));- gap: 10px;- }- .kpi {- position: relative;- overflow: hidden;- background: linear-gradient(125deg, var(--card), var(--surface));- border: 1px solid var(--line);- border-radius: 8px;- padding: 13px 16px 11px;- }- .kpi::before {- content: '';- position: absolute;- top: 0;- left: 16px;- width: 28px;- height: 2px;- background: var(--accent);- box-shadow: 0 0 14px var(--accent);- }- .kpi:nth-child(4n + 1) {- --accent: var(--teal);- }- .kpi:nth-child(4n + 2) {- --accent: var(--violet);- }- .kpi:nth-child(4n + 3) {- --accent: var(--warn);- }- .kpi:nth-child(4n + 4) {- --accent: var(--rose);- }- .kpi .label {- font-size: 11px;- color: var(--muted);- }- .kpi .value {- font: 29px/1.45 var(--mono);- letter-spacing: -0.055em;- margin: 4px 0 0;- }- .kpi .unit {- font-size: 11px;- color: var(--accent);- margin-left: 6px;- letter-spacing: 0;- }- .kpi small {- font-size: 10px;- color: var(--muted);- }- .overview-matrix {- margin-top: 8px;- }- .matrix-head {- display: flex;- justify-content: space-between;- align-items: center;- gap: 10px;- margin-bottom: 8px;- }- .matrix-head h3 {- margin: 0;- }- .phase-buttons {- display: none;- gap: 7px;- flex-wrap: wrap;- margin: 12px 0 0;- }- .js .phase-buttons {- display: flex;- }- .phase-button {- display: flex;- gap: 18px;- justify-content: space-between;- flex: 1 1 130px;- padding: 7px 10px;- border: 1px solid var(--line);- border-left: 2px solid var(--teal);- border-radius: 4px;- background: var(--surface);- color: var(--teal);- text-align: left;- font: 10px var(--mono);- }- .phase-button:hover {- border-color: var(--teal);- background: var(--soft);- }- .phase-button:active {- transform: translateY(1px);- box-shadow: inset 0 1px 3px #0003;- }- .phase-button.warn {- border-left-color: var(--warn);- }- .phase-button b {- font-weight: 400;- color: var(--muted);- }- .section {- margin-top: 28px;- }- .section-head {- margin-bottom: 12px;- }- .section-index {- color: var(--teal);- font: 9px var(--mono);- letter-spacing: 0.13em;- margin-bottom: 3px;- }- .panel,- .phase {- min-width: 0;- background: var(--card);- border: 1px solid var(--line);- border-radius: 8px;- padding: 16px;- }- .phase {- margin-bottom: 14px;- }- .phase .section-head {- margin-bottom: 2px;- }- .phase .section-head h3 {- font: 17px var(--mono);- margin: 5px 0 0;- }- .two,- .chart-grid {- display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));- gap: 12px;- }- #comparison > .two {- grid-template-columns: repeat(3, minmax(0, 1fr));- }- .section > .two {- margin-top: 12px;- }- .panel p {- color: var(--muted);- font-size: 11px;- }- .table-scroll {- overflow-x: auto;- border: 1px solid var(--line);- border-radius: 6px;- background: var(--card);- }- table {- width: 100%;- border-collapse: collapse;- font-size: 11px;- text-align: left;- font-variant-numeric: tabular-nums;- }- th {- font-weight: 500;- color: var(--muted);- background: var(--surface);- padding: 8px 10px;- white-space: nowrap;- }- td {- padding: 8px 10px;- border-top: 1px solid var(--line);- vertical-align: top;- overflow-wrap: anywhere;- }- td:first-child {- font-weight: 600;- }- tr:hover td {- background: var(--soft);- }- .overview-matrix table {- font: 10px/1.6 var(--mono);- }- .overview-matrix td {- white-space: nowrap;- text-align: right;- }- .overview-matrix th {- text-align: right;- }- .overview-matrix :is(td, th):first-child {- text-align: left;- position: sticky;- left: 0;- background: var(--surface);- }- .environment-panel :is(td, th):first-child {- width: 125px;- white-space: nowrap;- }- .notice {- padding: 10px 14px;- border-left: 2px solid var(--teal);- background: var(--soft);- font-size: 12px;- margin: 12px 0;- overflow-wrap: anywhere;- }- .notice.warn {- border-color: var(--warn);- }- svg {- width: 100%;- height: auto;- display: block;- overflow: visible;- }- svg text {- font: 13px var(--mono);- fill: var(--muted);- }- svg .grid {- stroke: var(--line);- stroke-width: 1;- stroke-dasharray: 3 5;- }- svg path {- vector-effect: non-scaling-stroke;- }- details {- border-top: 1px solid var(--line);- padding: 10px 0;- margin-top: 12px;- }- details.panel {- padding: 13px 16px;- }- summary {- font-size: 12px;- font-weight: 600;- cursor: pointer;- overflow-wrap: anywhere;- }- details p {- color: var(--muted);- font-size: 11px;- }- details .table-scroll {- margin-top: 10px;- }- .empty {- padding: 24px 12px;- color: var(--muted);- text-align: center;- font-size: 11px;- }- .footer {- margin-top: 28px;- padding-top: 14px;- border-top: 1px solid var(--line);- display: flex;- justify-content: space-between;- gap: 12px;- font: 9px/1.8 var(--mono);- color: var(--muted);- }- .bar-chart {- margin-top: 12px;- }- .bar-group {- margin-bottom: 10px;- }- .bar-group:last-child {- margin-bottom: 0;- }- .bar-label {- font: 10px/1.6 var(--mono);- overflow-wrap: anywhere;- color: var(--ink);- margin-bottom: 3px;- }- .bar-entry {- display: grid;- grid-template-columns: 34px minmax(20px, 1fr) 90px;- align-items: center;- gap: 6px;- margin: 3px 0;- }- .bar-series {- color: var(--muted);- font-size: 10px;- }- .bar-series:empty {- display: none;- }- .bar-entry:has(.bar-series:empty) {- grid-template-columns: minmax(20px, 1fr) 90px;- }- .bar-track {- position: relative;- height: 8px;- border-radius: 2px;- overflow: hidden;- background: var(--surface);- }- .bar-track i {- position: absolute;- top: 0;- height: 100%;- border-radius: 2px;- }- .bar-track.missing {- background: repeating-linear-gradient(90deg, var(--line) 0 4px, transparent 4px 8px);- height: 2px;- }- .zero {- position: absolute;- top: 0;- height: 100%;- width: 1px;- background: var(--muted);- opacity: 0.5;- }- .bar-value {- font: 10px var(--mono);- text-align: right;- white-space: nowrap;- }- .bar-value small {- font-size: 9px;- color: var(--muted);- }- .hotspot > .two {- margin-top: 14px;- }- .hotspot .panel {- padding: 12px;- background: var(--surface);- }- .hotspot .bar-track {- background: var(--line);- }- .metric-strip {- display: grid;- grid-template-columns: repeat(6, minmax(0, 1fr));- gap: 12px;- margin: 12px 0;- padding: 12px 0;- border-block: 1px solid var(--line);- }- .metric-strip span {- display: block;- color: var(--muted);- font-size: 10px;- }- .metric-strip b {- font: 13px/1.8 var(--mono);- }- .thermal-phase {- display: grid;- grid-template-columns: 55px 1fr;- gap: 7px;- align-items: center;- margin-top: 10px;- font: 10px var(--mono);- }- .thermal-state {- display: flex;- align-items: center;- justify-content: space-between;- flex-wrap: wrap;- gap: 6px;- padding: 7px 9px;- border-radius: 4px;- grid-column: 2;- background: var(--surface);- }- .thermal-phase > b + .thermal-state {- grid-column: auto;- }- .thermal-state span {- font-size: 9px;- color: var(--muted);- }- .thermal-state.nominal {- color: var(--teal);- background: var(--soft);- }- .thermal-state.elevated {- color: var(--warn);- border: 1px solid var(--warn);- }- .trend-chart,- .sample-summary {- min-width: 0;- padding: 12px;- background: var(--surface);- border: 1px solid var(--line);- border-radius: 6px;- }- .trend-stats {- display: flex;- justify-content: space-between;- flex-wrap: wrap;- align-items: baseline;- gap: 4px 10px;- }- .trend-stats b {- font-size: 12px;- }- .trend-stats span {- color: var(--muted);- font: 10px var(--mono);- }- .trend-chart svg {- touch-action: pan-y;- }- .cursor {- stroke: var(--ink);- stroke-width: 1;- stroke-dasharray: 4 4;- pointer-events: none;- }- .chart-control {- display: none;- align-items: center;- gap: 10px;- }- .js .chart-control {- display: flex;- }- .chart-control input {- width: 38%;- min-width: 50px;- accent-color: var(--teal);- cursor: ew-resize;- }- .chart-control output {- font: 10px var(--mono);- white-space: nowrap;- }- .sample-summary {- display: flex;- flex-direction: column;- justify-content: center;- }- .sample-summary p {- margin-bottom: 0;- }- .share-track {- display: flex;- height: 18px;- border-radius: 4px;- overflow: hidden;- margin: 18px 0;- }- .share-track i {- display: block;- height: 100%;- }- .share-values {- display: grid;- grid-template-columns: 1fr 1fr;- gap: 18px;- }- .share-values span,- .share-values small {- display: block;- color: var(--muted);- font-size: 11px;- }- .share-values b {- font: 30px/1.8 var(--mono);- }- .share-values > div {- border-top: 2px solid var(--teal);- padding-top: 8px;- }- .share-values > div + div {- border-color: var(--violet);- }- .interval-axis {- display: flex;- justify-content: space-between;- color: var(--muted);- font: 9px var(--mono);- margin: 12px 0 6px;- }- .interval-row {- padding: 7px 0;- border-bottom: 1px solid var(--line);- }- .interval-row > b {- font: 10px var(--mono);- }- .interval-track {- position: relative;- height: 16px;- margin: 4px 6px;- background: linear-gradient(var(--line), var(--line)) center/100% 1px no-repeat;- }- .interval-line {- position: absolute;- top: 6px;- height: 4px;- background: var(--teal);- opacity: 0.55;- }- .interval-point {- position: absolute;- top: 3px;- transform: translateX(-50%);- width: 10px;- height: 10px;- border: 2px solid var(--teal);- background: var(--teal);- border-radius: 50%;- }- .interval-point.bound {- width: 2px;- border: 0;- border-radius: 0;- top: 2px;- height: 12px;- }- .interval-point.head {- background: var(--card);- }- .interval-point.tail {- background: var(--violet);- border-color: var(--violet);- }- .interval-values,- .interval-key {- display: block;- font: 9px/1.8 var(--mono);- color: var(--muted);- }- .interval-key {- margin-top: 8px;- }- @media (min-width: 1650px) {- .main {- padding-inline: 40px;- }- .kpis {- grid-template-columns: repeat(8, minmax(0, 1fr));- }- .kpi {- padding-inline: 12px;- }- .kpi .value {- font-size: 25px;- }- }- @media (max-width: 1200px) {- .shell {- grid-template-columns: 166px minmax(0, 1fr);- }- .main {- padding: 22px;- }- .sidebar {- padding-inline: 12px;- }- #comparison > .two {- grid-template-columns: repeat(2, minmax(0, 1fr));- }- .metric-strip {- grid-template-columns: repeat(3, minmax(0, 1fr));- }- }- @media (max-width: 850px) {- .shell {- display: block;- }- .sidebar {- position: static;- height: auto;- padding: 12px 18px;- }- .sidebar strong,- .side-note {- display: none;- }- .sidebar nav {- display: flex;- gap: 6px;- overflow-x: auto;- margin-top: 8px;- }- .sidebar nav a {- flex: 0 0 auto;- padding: 6px 8px;- margin: 0;- }- .sidebar nav span {- width: 21px;- }- .main {- padding: 18px;- }- .footer {- flex-wrap: wrap;- }- }- @media (max-width: 600px) {- .main {- padding: 14px;- }- .topline {- align-items: flex-start;- flex-direction: column;- gap: 10px;- }- h1 {- font-size: 29px;- }- h1 span {- display: block;- margin: 4px 0 0;- }- .meta {- gap: 8px 12px;- }- .kpis {- grid-template-columns: repeat(2, minmax(0, 1fr));- gap: 8px;- }- .kpi {- padding: 12px;- }- .kpi .value {- font-size: 26px;- }- .two,- .chart-grid,- #comparison > .two {- grid-template-columns: 1fr;- }- .section-head {- align-items: flex-start;- flex-direction: column;- gap: 5px;- }- .phase .section-head {- flex-direction: row;- }- .panel,- .phase {- padding: 12px;- }- .metric-strip {- gap: 8px;- }- .metric-strip b {- font-size: 11px;- }- .matrix-head {- align-items: flex-start;- flex-direction: column;- gap: 4px;- }- .trend-chart {- padding: 9px;- }- .share-values b {- font-size: 26px;- }- }- @media (prefers-reduced-motion: reduce) {- html {- scroll-behavior: auto;- }- }- @media print {- body,- body.dark {- color-scheme: light;- --bg: #fff;- --card: #fff;- --surface: #f5f7fa;- --ink: #111;- --muted: #505967;- --line: #ccd2da;- --teal: #087e83;- --violet: #7055d0;- --warn: #956017;- --rose: #bd4264;- --soft: #e7f3f3;- background: #fff;- font-size: 10px;- }- .sidebar,- .actions,- .phase-buttons,- .chart-control {- display: none !important;- }- .shell {- display: block;- }- .main {- padding: 0;- }- .kpis {- grid-template-columns: repeat(4, minmax(0, 1fr));- }- .kpi {- padding: 10px;- background: #fff;- }- .kpi::before {- box-shadow: none;- }- .kpi .value {- font-size: 24px;- }- .section {- margin-top: 20px;- }- .table-scroll {- overflow: visible;- }- .overview-matrix table {- font-size: 8px;- }- th,- td {- padding: 5px;- }- .overview-matrix :is(td, th):first-child {- position: static;- }- .two,- .chart-grid,- #comparison > .two {- grid-template-columns: repeat(2, minmax(0, 1fr));- }- .metric-strip {- grid-template-columns: repeat(3, minmax(0, 1fr));- }- .panel,- .trend-chart,- .sample-summary,- .kpi,- .bar-group,- tr {- break-inside: avoid;- }- .phase,- details.panel {- break-inside: auto;- }- .trend-stats span {- font-size: 9px;- }- .bar-track,- .share-track,- .interval-track,- .interval-point,- svg {- print-color-adjust: exact;- -webkit-print-color-adjust: exact;- }- a {- color: inherit;- }- }- </style>- </head>- <body>- <div class="shell">- <aside class="sidebar">- <div class="brand">PERFORMANCE LAB</div>- <strong>@@APP@@</strong>- <nav aria-label="报告章节">- <a href="#overview"><span>01</span>数据总览</a>- <a href="#comparison"><span>02</span>阶段对比</a>- <a href="#io"><span>03</span>唤醒与磁盘</a>- <a href="#measurements"><span>04</span>运行曲线</a>- <a href="#hotspots"><span>05</span>CPU 热点</a>- <a href="#events"><span>06</span>事件与热状态</a>- <a href="#environment"><span>07</span>采集记录</a>- </nav>- <div class="side-note"><span>CAPTURE PROFILE</span>@@PRESET@@<br />@@VERSION@@<br />Instruments</div>- </aside>- <main class="main">- <header id="overview">- <div class="topline">- <span class="eyebrow">Runtime performance / @@PRESET@@</span>- <div class="actions">- <button id="theme" type="button">深色主题</button>- <button id="download" type="button">导出 JSON</button>- <button id="print" type="button">打印报告</button>- </div>- </div>- <h1>@@APP@@<span>性能数据报告</span></h1>- <div class="meta"><span class="badge @@STATE_TONE@@">@@STATE@@</span><span>@@STARTED@@</span></div>- <div class="hero-rule"></div>- <div class="kpis">- <div class="kpi">- <div class="label">记录时间</div>- <div class="value">@@MINUTES@@<span class="unit">min</span></div>- <small>各阶段累计</small>- </div>- <div class="kpi">- <div class="label">平均 CPU</div>- <div class="value">@@CPU@@<span class="unit">%</span></div>- <small>按观测时长加权</small>- </div>- <div class="kpi">- <div class="label">footprint 峰值</div>- <div class="value">@@MEMORY@@<span class="unit">MiB</span></div>- <small>有效阶段最大值</small>- </div>- <div class="kpi">- <div class="label">Hangs 记录</div>- <div class="value">@@HANGS@@<span class="unit">条</span></div>- <small>覆盖 @@HANG_PHASES@@ 个阶段</small>- </div>- @@EXTRA_KPIS@@- </div>- <div class="overview-matrix">- <div class="matrix-head">- <h3>阶段指标</h3>- <span class="muted">FP = Footprint · N/A = 无数据 · CPU 100% = 1 个逻辑核心</span>- </div>- @@MATRIX@@- </div>- <div class="phase-buttons" role="group" aria-label="跳转至阶段曲线">@@PHASE_BUTTONS@@</div>- @@ERRORS@@- </header>- <section id="comparison" class="section">- <div class="section-head">- <div>- <div class="section-index">02 / COMPARISON</div>- <h2>阶段对比</h2>- </div>- <span class="muted">CPU 100% = 1 个逻辑核心</span>- </div>- <div class="two">@@COMPARISONS@@</div>- </section>- <section id="io" class="section">- <div class="section-head">- <div>- <div class="section-index">03 / RESOURCES</div>- <h2>唤醒、磁盘与系统负载</h2>- </div>- </div>- <div class="two">@@IO_CHARTS@@</div>- </section>- <section id="measurements" class="section">- <div class="section-head">- <div>- <div class="section-index">04 / TIME SERIES</div>- <h2>运行曲线</h2>- </div>- <span class="muted">横轴:阶段内秒数 · 同一指标各阶段使用相同纵轴</span>- </div>- @@PHASES@@- </section>- <section id="hotspots" class="section">- <div class="section-head">- <div>- <div class="section-index">05 / CPU PROFILE</div>- <h2>CPU 采样分布与热点</h2>- </div>- <span class="muted">采样权重 / ms</span>- </div>- <div class="two">@@HOT_OVERVIEW@@</div>- @@HOTSPOTS@@- </section>- <section id="events" class="section">- <div class="section-head">- <div>- <div class="section-index">06 / EVENTS</div>- <h2>事件与热状态</h2>- </div>- </div>- <div class="two">@@EVENTS@@</div>- @@EVENT_DETAILS@@- </section>- @@OPTIONAL@@- <section id="environment" class="section">- <div class="section-head">- <div>- <div class="section-index">07 / RECORDS</div>- <h2>采集记录</h2>- </div>- </div>- @@RECORDS@@- <div class="two section">- <article class="panel environment-panel">- <h3>运行环境</h3>- @@METADATA@@- </article>- <article class="panel">- <h3>系统 Load Average</h3>- @@LOAD@@- </article>- </div>- <details>- <summary>App 标识</summary>- @@FINGERPRINT@@- </details>- </section>- <footer class="footer"><span>@@APP@@ · Instruments</span><span>@@STARTED@@ — @@ENDED@@</span></footer>- </main>- </div>- <script id="report-data" type="application/json">- @@PAYLOAD@@- </script>- <script>- const data = JSON.parse(document.getElementById('report-data').textContent);- document.documentElement.classList.add('js');- document.querySelectorAll('.trend-chart').forEach((chart) => {- const points = data.phases[Number(chart.dataset.phase)].resources.series,- key = chart.dataset.key,- unit = chart.dataset.unit;- const svg = chart.querySelector('svg'),- input = chart.querySelector('input');- const plotLeft = Number(svg.dataset.plotLeft),- plotWidth = Number(svg.dataset.plotWidth);- const output = chart.querySelector('output'),- cursor = chart.querySelector('.cursor');- const start = points[0].t,- end = points[points.length - 1].t;-- function select(index) {- const t = points[index].t,- value = points[index][key] ?? null,- x = plotLeft + ((t - start) / Math.max(end - start, 1)) * plotWidth;- cursor.removeAttribute('hidden');- cursor.setAttribute('x1', x);- cursor.setAttribute('x2', x);- output.textContent = `${t.toFixed(2)} s · ${value === null ? 'N/A' : value.toFixed(2) + ' ' + unit}`;- input.value = index;- }-- input.addEventListener('input', () => select(Number(input.value)));- svg.addEventListener('pointermove', (event) => {- const rect = svg.getBoundingClientRect();- const time = start + Math.max(0, Math.min(1, (((event.clientX - rect.left) / rect.width) * svg.viewBox.baseVal.width - plotLeft) / plotWidth)) * (end - start);- let index = 0;- for (let i = 1; i < points.length; i++) if (Math.abs(points[i].t - time) < Math.abs(points[index].t - time)) index = i;- select(index);- });- select(0);- });- document.querySelectorAll('.phase-button').forEach((button) => {- button.addEventListener('click', () => {- const phase = document.getElementById(button.getAttribute('aria-controls'));- phase.focus({ preventScroll: true });- phase.scrollIntoView({ block: 'start' });- });- });- document.getElementById('theme').addEventListener('click', (event) => {- const dark = document.body.classList.toggle('dark');- event.currentTarget.textContent = dark ? '浅色主题' : '深色主题';- });- const navigation = [...document.querySelectorAll('.sidebar nav a')];- const sections = navigation.map((link) => document.querySelector(link.getAttribute('href')));- function updateNavigation() {- let active = 0;- sections.forEach((section, index) => {- if (section.getBoundingClientRect().top <= 100) active = index;- });- navigation.forEach((link, index) => {- link.classList.toggle('active', index === active);- if (index === active) link.setAttribute('aria-current', 'location');- else link.removeAttribute('aria-current');- });- }- let navigationPending = false;- window.addEventListener(- 'scroll',- () => {- if (navigationPending) return;- navigationPending = true;- requestAnimationFrame(() => {- updateNavigation();- navigationPending = false;- });- },- { passive: true },- );- updateNavigation();- document.getElementById('download').addEventListener('click', () => {- const url = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }));- const link = document.createElement('a');- link.href = url;- link.download = 'performance.json';- link.click();- setTimeout(() => URL.revokeObjectURL(url), 1000);- });- document.getElementById('print').addEventListener('click', () => window.print());- let openedForPrint = [];- window.addEventListener('beforeprint', () => {- openedForPrint = [...document.querySelectorAll('details:not([open])')];- openedForPrint.forEach((element) => (element.open = true));- });- window.addEventListener('afterprint', () => {- openedForPrint.forEach((element) => (element.open = false));- openedForPrint = [];- });- </script>- </body>-</html>diff --git a/Scripts/performance/report.py b/Scripts/performance/report.pydeleted file mode 100644index b17dd9b..0000000--- a/Scripts/performance/report.py+++ /dev/null@@ -1,800 +0,0 @@-"""Render a self-contained report with no remote resources or runtime dependencies"""--import html-import json-import math-from collections.abc import Sequence-from pathlib import Path-from typing import cast--from .models import (- EventKey,- MetricKey,- Report,- ResourceValueKey,- Sample,- SeriesKey,- StatisticKey,-)--BarEntry = tuple[str, float | None, str]-BarGroup = tuple[str, Sequence[BarEntry]]---def escape(value: object) -> str:- return html.escape(str(value))---def number(value: float | None, digits: int = 2, suffix: str = "") -> str:- return "N/A" if value is None else f"{value:,.{digits}f}{suffix}"---def table(headers: Sequence[str], rows: Sequence[Sequence[object]]) -> str:- head = "".join(f"<th>{escape(h)}</th>" for h in headers)- body = "".join("<tr>" + "".join(f"<td>{escape(c)}</td>" for c in row) + "</tr>" for row in rows)- if not body:- body = f'<tr><td colspan="{len(headers)}" class="muted">无可用数据</td></tr>'- return f'<div class="table-scroll"><table><thead><tr>{head}</tr></thead><tbody>{body}</tbody></table></div>'---def chart(- series: Sequence[Sample], key: SeriesKey, label: str, color: str, unit: str,- phase_index: int, ceiling: float | None = None, step: bool = False,-) -> str:- width, height, left, right, top, bottom = 640, 240, 60, 24, 32, 40- points = [(p["t"], value) for p in series if (value := p[key]) is not None]- if not points:- return '<div class="empty">无可用采样数据</div>'- start, end = min(p["t"] for p in series), max(p["t"] for p in series)- peak_time, peak_value = max(points, key=lambda p: p[1])- maximum = ceiling or nice_max(peak_value)-- def x(t: float) -> float:- return left + (t - start) / max(end - start, 1) * (width - left - right)-- def y(value: float) -> float:- return top + (1 - value / maximum) * (height - top - bottom)-- parts = [- f'<div class="trend-chart" data-phase="{phase_index}" data-key="{escape(key)}" data-unit="{escape(unit)}">',- f'<div class="trend-stats"><b>{escape(label)}</b><span>最低 {number(min(value for _, value in points))} · 峰值 {number(peak_value)} {escape(unit)}</span></div>',- f'<svg viewBox="0 0 {width} {height}" data-plot-left="{left}" data-plot-width="{width - left - right}" role="img" aria-label="{escape(label)}运行曲线">',- ]- for index in range(5):- value = maximum * index / 4- yy = y(value)- parts.append(f'<line class="grid" x1="{left}" x2="{width - right}" y1="{yy:.2f}" y2="{yy:.2f}"/>')- parts.append(f'<text x="{left - 10}" y="{yy + 4:.2f}" text-anchor="end">{value:g}</text>')- for index in range(6):- t = start + (end - start) * index / 5- parts.append(f'<text x="{x(t):.2f}" y="{height - 10}" text-anchor="middle">{t:.0f}s</text>')- segments: list[list[tuple[float, float]]] = []- current: list[tuple[float, float]] = []- previous = None- for point in series:- value = point[key]- if value is None or (- previous is not None and point["t"] - previous > 5- ):- if current:- segments.append(current)- current = []- if value is not None:- current.append((point["t"], value))- previous = point["t"]- if current:- segments.append(current)- for segment in segments:- path = f"M {x(segment[0][0]):.2f} {y(segment[0][1]):.2f}"- for timestamp, value in segment[1:]:- path += (- f" H {x(timestamp):.2f} V {y(value):.2f}"- if step- else f" L {x(timestamp):.2f} {y(value):.2f}"- )- parts.append(f'<path d="{path} L {x(segment[-1][0]):.2f} {y(0):.2f} L {x(segment[0][0]):.2f} {y(0):.2f} Z" fill="{color}" opacity=".10"/>')- parts.append(f'<path d="{path}" fill="none" stroke="{color}" stroke-width="2"/>')- if len(segment) == 1:- parts.append(f'<circle cx="{x(segment[0][0]):.2f}" cy="{y(segment[0][1]):.2f}" r="3" fill="{color}"/>')- anchor = "end" if x(peak_time) > width / 2 else "start"- parts.append(f'<circle cx="{x(peak_time):.2f}" cy="{y(peak_value):.2f}" r="4" fill="{color}"/>')- parts.append(f'<text x="{x(peak_time):.2f}" y="{y(peak_value) - 10:.2f}" text-anchor="{anchor}">峰值 {peak_value:.2f}</text>')- parts.append(f'<line class="cursor" x1="{left}" x2="{left}" y1="{top}" y2="{height - bottom}" hidden/></svg>')- parts.append(f'<div class="chart-control"><input aria-label="{escape(label)}采样点" type="range" min="0" max="{len(series) - 1}" value="0"><output></output></div></div>')- return "".join(parts)---def nice_max(value: float) -> float:- if value <= 0:- return 1- magnitude: float = 10 ** math.floor(math.log10(value))- step = magnitude / 2- return math.ceil(value * 1.1 / step) * step---COLORS = ["var(--teal)", "var(--violet)", "var(--warn)", "var(--rose)"]---def bars(groups: Sequence[BarGroup], unit: str = "", digits: int = 2) -> str:- values = [- value for _, entries in groups for _, value, _ in entries if value is not None- ]- low, high = min([0] + values), max([0] + values)- extent = high - low or 1- zero = -low / extent * 100- parts = ['<div class="bar-chart">']- for label, entries in groups:- parts.append(f'<div class="bar-group"><div class="bar-label">{escape(label)}</div>')- for name, value, color in entries:- parts.append(f'<div class="bar-entry"><span class="bar-series">{escape(name)}</span>')- if value is None:- parts.append('<div class="bar-track missing"></div><b class="bar-value">N/A</b>')- else:- position = (min(0, value) - low) / extent * 100- width = abs(value) / extent * 100- parts.append(f'<div class="bar-track"><span class="zero" style="left:{zero:.4f}%"></span><i style="left:{position:.4f}%;width:{width:.4f}%;background:{color}" data-value="{value}"></i></div><b class="bar-value">{number(value, digits)} <small>{escape(unit)}</small></b>')- parts.append("</div>")- parts.append("</div>")- return (- "".join(parts)- + ('<div class="empty">无采集数据</div>' if not groups else "")- + "</div>"- )---def ranked(- items: Sequence[tuple[str, float | None]], unit: str = "ms",- color: str = COLORS[0], digits: int = 0,-) -> str:- return bars([(label, [("", value, color)]) for label, value in items], unit, digits)---def panel(title: str, content: str, note: str = "") -> str:- return (- '<article class="panel"><h3>'- + escape(title)- + "</h3>"- + ('<p class="muted">' + escape(note) + "</p>" if note else "")- + content- + "</article>"- )---def distribution(main: float, total: float) -> str:- if not total:- return '<div class="empty">无 CPU 样本</div>'- ratio = main / total * 100- return f"""<div class="share-chart"><div class="share-track"><i style="width:{ratio:.4f}%;background:{COLORS[0]}"></i><i style="width:{100 - ratio:.4f}%;background:{COLORS[1]}"></i></div>-<div class="share-values"><div><span>主线程</span><b>{ratio:.1f}%</b><small>{main:,.0f} ms</small></div><div><span>其他线程</span><b>{100 - ratio:.1f}%</b><small>{total - main:,.0f} ms</small></div></div></div>"""---def interval_chart(- rows: Sequence[tuple[str, Sequence[float | None]]], paired: bool = False,-) -> str:- values = [v for _, entries in rows for v in entries if v is not None]- if not values:- return '<div class="empty">无可用数据</div>'- maximum = nice_max(max(values))-- def x(value: float) -> float:- return 100 * value / maximum-- parts = [- '<div class="interval-chart">',- '<div class="interval-axis"><span>0</span><span>'- + number(maximum, 0)- + " MiB</span></div>",- ]- for label, entries in rows:- parts.append(f'<div class="interval-row"><b>{escape(label)}</b>')- values = [value for value in entries if value is not None]- if len(values) != len(entries):- parts.append('<span class="muted">N/A</span></div>')- continue- first, last = values[0], values[-1]- description = (- f"首段 {first:.1f} → 尾段 {last:.1f} MiB · 变化 {last - first:+.1f} MiB"- if paired- else f"最小 {first:.1f} · 中位 {values[1]:.1f} · 峰值 {last:.1f} MiB"- )- parts.append(f'<div class="interval-track"><i class="interval-line" style="left:{x(min(first, last)):.4f}%;width:{x(abs(last - first)):.4f}%"></i>')- for i, value in enumerate(values):- kind = (- ("head" if i == 0 else "tail")- if paired- else ("median" if i == 1 else "bound")- )- parts.append(f'<i class="interval-point {kind}" style="left:{x(value):.4f}%" title="{value:.2f} MiB"></i>')- parts.append('</div><span class="interval-values">' + description + "</span></div>")- parts.append(- '<div class="interval-key">'- + ("○ 首段 ● 尾段" if paired else "┃ 最小值 / 峰值 ● 中位数")- + "</div></div>"- )- return "".join(parts)---def write_report(data: Report, destination: Path) -> None:- import collections- import re-- phases = data.get("phases", [])- valid = [p for p in phases if p.get("resources") and not p.get("errors")]- target, env = data.get("target", {}), data.get("environment", {})- measured = sum(p.get("recorded_s", 0) for p in phases)- resources = [(p, resource) for p in valid if (resource := p.get("resources")) is not None]- cpu_phases = [(resource, mean) for _, resource in resources if (mean := resource["cpu_mean"]) is not None]- cpu_durations = [- sum(duration for point in resource["series"] if point["cpu"] is not None and (duration := point["dt"]) is not None)- for resource, _ in cpu_phases- ]- span = sum(cpu_durations)- cpu_mean = (- sum(mean * duration for (_, mean), duration in zip(cpu_phases, cpu_durations))- / span- if span- else None- )- footprints = [- footprint["max"] for _, resource in resources- if (footprint := resource["footprint"]) is not None- ]- hang_phases = [p for p in valid if "potential-hangs" in p]- hangs = (- sum(p["potential-hangs"]["count"] for p in hang_phases) if hang_phases else None- )- state = {- "complete": "采集完成",- "incomplete": "采集不完整",- "running": "采集中",- "interrupted": "采集已中断",- }.get(data.get("state"), "状态未知")- tone = "ok" if data.get("state") == "complete" else "warn"- if data.get("budget_breaches"):- state, tone = "超过配置预算", "warn"-- def resource_peak(key: ResourceValueKey) -> float | None:- values = [value for _, resource in resources if (value := resource[key]) is not None]- return max(values, default=None)-- def metric_peak(key: MetricKey) -> float | None:- values = [metric["max"] for _, resource in resources if (metric := resource[key]) is not None]- return max(values, default=None)-- extra_kpis = [- ("CPU 采样峰值", number(resource_peak("cpu_peak")), "%", "有效阶段最高采样值"),- ("RSS 峰值", number(metric_peak("rss"), 1), "MiB", "驻留物理内存"),- (- "线程峰值",- number(metric_peak("threads"), 0),- "个",- "有效阶段最大线程数",- ),- (- "资源采样点",- number(sum(resource["samples"] for _, resource in resources), 0),- "个",- "有效阶段累计样本",- ),- ]- extra_kpis_html = "".join(- f'<div class="kpi"><div class="label">{label}</div><div class="value">{value}<span class="unit">{unit}</span></div><small>{note}</small></div>'- for label, value, unit, note in extra_kpis- )- matrix_rows: list[list[str]] = []- phase_buttons: list[str] = []- for index, phase in enumerate(phases):- r = phase.get("resources", {})- matrix_rows.append(- [- phase["id"],- number(r.get("cpu_mean")),- number(r.get("cpu_p50")),- number(r.get("cpu_p95")),- number(r.get("cpu_peak")),- number(metric["max"] if (metric := r.get("footprint")) is not None else None, 1),- number(metric["max"] if (metric := r.get("rss")) is not None else None, 1),- number(metric["max"] if (metric := r.get("threads")) is not None else None, 0),- number(r.get("wakeups_per_s")),- number(- written_bytes / 1024- if (written_bytes := r.get("written_bytes")) is not None- else None,- 1,- ),- "有效" if phase in valid else "部分数据",- ]- )- phase_buttons.append(- f'<button type="button" class="phase-button {"ok" if phase in valid else "warn"}" aria-controls="phase-{index}"><span>{escape(phase["id"])}</span><b>{number(phase.get("recorded_s"), 1)} s</b></button>'- )- matrix = table(- [- "阶段",- "CPU 均值 %",- "P50 %",- "P95 %",- "峰值 %",- "FP 峰值 MiB",- "RSS 峰值 MiB",- "线程峰值",- "唤醒 /s",- "写入 KiB",- "状态",- ],- matrix_rows,- )-- def resource_groups(- specification: Sequence[tuple[str, ResourceValueKey]], scale: float = 1,- ) -> list[BarGroup]:- groups: list[BarGroup] = []- for phase, r in resources:- entries: list[BarEntry] = []- for index, (label, key) in enumerate(specification):- value = r.get(key)- entries.append(- (label, value / scale if value is not None else None, COLORS[index])- )- groups.append((phase["id"], entries))- return groups-- comparisons = [- panel("平均 CPU", bars(resource_groups([("均值", "cpu_mean")]), "%")),- panel(- "CPU P95 与峰值",- bars(resource_groups([("P95", "cpu_p95"), ("峰值", "cpu_peak")]), "%"),- ),- ]- distribution_keys: tuple[StatisticKey, ...] = ("min", "median", "max")- memory_rows = [- (- p["id"],- [- footprint.get(key) if footprint is not None else None- for key in distribution_keys- ],- )- for p, resource in resources- for footprint in [resource["footprint"]]- ]- comparisons.append(panel("内存 footprint 分布", interval_chart(memory_rows)))- trends = [- (p["id"], trend) for p, resource in resources- if (trend := resource.get("memory_trend"))- ]- comparisons.append(- panel(- "footprint 首尾变化",- interval_chart(- [(name, [t["head_median"], t["tail_median"]]) for name, t in trends],- paired=True,- ),- "窗口长度为 60 秒与阶段跨度四分之一中的较小值",- )- )- comparisons.append(- panel(- "footprint 变化斜率",- ranked(- [(name, t["slope_mib_min"]) for name, t in trends], "MiB/min", digits=2- ),- "按阶段样本作最小二乘拟合",- )- )- comparisons.append(- panel(- "footprint 首尾差值",- ranked([(name, t["delta_mib"]) for name, t in trends], "MiB", digits=2),- "尾段窗口中位数减去首段窗口中位数",- )- )- io_charts = [- panel(- "Idle Wake Ups 速率",- bars(resource_groups([("均值", "wakeups_per_s")]), "次/s"),- ),- panel(- "磁盘读取与写入",- bars(- resource_groups(- [("读取", "read_bytes"), ("写入", "written_bytes")], 1024- ),- "KiB",- 1,- ),- ),- panel(- "磁盘平均吞吐",- bars(- resource_groups(- [("读取", "read_bytes_per_s"), ("写入", "written_bytes_per_s")],- 1024,- ),- "KiB/s",- ),- ),- panel(- "系统 CPU",- bars(- [- (- p["id"],- [- ("均值", system.get("cpu_load_mean"), COLORS[0]),- ("峰值", system.get("cpu_load_peak"), COLORS[1]),- ],- )- for p in valid- if (system := p.get("system"))- ],- "%",- 1,- ),- "各逻辑核心合计",- ),- ]- profiles = [profile for p in valid if (profile := p.get("profile"))]- total = sum(profile["sampled_ms"] for profile in profiles)- main = sum(profile["main_ms"] for profile in profiles)- libraries: collections.defaultdict[str, float] = collections.defaultdict(float)- for profile in profiles:- for name, weight in profile["binaries"]:- libraries[name] += weight- hot_overview = panel("主线程 CPU 样本分布", distribution(main, total)) + panel(- "叶节点所属库 · 已导出 Top 10", ranked(sorted(libraries.items(), key=lambda item: item[1], reverse=True)[:10])- )- phase_html: list[str] = []- hotspot_html: list[str] = []- record_rows: list[list[object]] = []- event_rows: list[list[str]] = []- series_keys: tuple[SeriesKey, ...] = ("cpu", "footprint", "rss", "compressed", "threads")- memory_keys: tuple[MetricKey, ...] = ("footprint", "rss", "compressed")- ceilings = {- key: nice_max(- max(- [- value- for p in phases- for point in p.get("resources", {}).get("series", [])- if (value := point[key]) is not None- ]- or [0]- )- )- for key in series_keys- }- for index, phase in enumerate(phases):- r = phase.get("resources", {})- content = f'<article class="phase" id="phase-{index}" tabindex="-1"><div class="section-head"><div><span class="eyebrow">{escape(phase["template"])}</span><h3>{escape(phase["id"])}</h3></div><span class="badge {"ok" if phase in valid else "warn"}">{"已采集" if phase in valid else "部分数据"}</span></div>'- content += f'<p class="muted">{escape(phase.get("trace_started", phase.get("started", "N/A")))} · {number(phase.get("recorded_s"), 2)} s</p>'- if r:- metrics = [- ("CPU 均值", number(r.get("cpu_mean"), 2, "%")),- (- "CPU P50 / P95",- number(r.get("cpu_p50"), 2)- + " / "- + number(r.get("cpu_p95"), 2, "%"),- ),- ("唤醒次数", number(r.get("wakeups"), 0)),- ("资源样本", number(r.get("samples"), 0)),- (- "CPU 采样覆盖",- number(- coverage * 100- if (coverage := r.get("cpu_coverage")) is not None- else None,- 1,- "%",- ),- ),- ("最大采样间隔", number(r.get("max_gap_s"), 2, " s")),- ]- content += (- '<div class="metric-strip">'- + "".join(- f"<div><span>{escape(label)}</span><b>{escape(value)}</b></div>"- for label, value in metrics- )- + "</div>"- )- content += '<div class="chart-grid">' + chart(- r["series"], "cpu", "CPU", COLORS[0], "%", index, ceilings["cpu"]- )- for key, label, color in zip(- memory_keys,- ["Footprint", "RSS", "压缩内存"],- COLORS,- ):- content += chart(- r["series"], key, label, color, "MiB", index, ceilings[key]- )- content += chart(- r["series"],- "threads",- "线程数",- COLORS[1],- "个",- index,- ceilings["threads"],- step=True,- )- detail_rows: list[list[str]] = []- memory_labels: tuple[tuple[MetricKey, str], ...] = (- ("footprint", "Footprint"),- ("rss", "RSS"),- ("compressed", "压缩内存"),- )- statistic_keys: tuple[StatisticKey, ...] = ("first", "last", "median")- for key, label in memory_labels:- values = r.get(key)- detail_rows.append(- [label]- + [number(values[k] if values is not None else None, 2) for k in statistic_keys]- )- content += (- '<div class="sample-summary"><h4>内存采样明细 <span class="muted">MiB</span></h4>'- + table(["指标", "首值", "尾值", "中位数"], detail_rows)- )- content += '<p class="muted">CPU 为区间使用率. 内存与线程为采样时刻值. 拖动滑块或移动指针查看单点数据</p></div></div>'- if (phase_errors := phase.get("errors")):- content += (- '<div class="notice warn">'- + "<br>".join(escape(e) for e in phase_errors)- + "</div>"- )- phase_html.append(content + "</article>")- profile = phase.get("profile")- if profile:- hot = f'<details class="panel hotspot" {"open" if index == 0 else ""}><summary>{escape(phase["id"])} · CPU 采样权重 {profile["sampled_ms"]:,.0f} ms</summary>'- hot += '<div class="two">' + panel(- "叶节点热点 · Top 12", ranked(profile["leaf"][:12])- )- hot += (- panel(- "调用链热点 · Top 12",- ranked(profile["inclusive"][:12], color=COLORS[1]),- "权重包含子调用",- )- + "</div>"- )- hot += '<div class="two">' + panel(- "高 CPU 采样权重的 1 秒区间",- ranked(- [- (f"{t}–{t + 1} s", value)- for t, value in profile["busiest_seconds"]- ]- ),- )- hot += (- panel(- "调用栈采样记录",- ranked(- [- (- "有调用栈",- profile["sampled_ms"] - profile["missing_stack_ms"],- ),- ("缺失调用栈", profile["missing_stack_ms"]),- ("含 App 帧", profile["app_stack_ms"]),- ("含命名 App 帧", profile["app_named_stack_ms"]),- ],- color=COLORS[2],- ),- )- + "</div>"- )- hot += "<details><summary>全部已导出热点</summary>" + table(- ["叶节点", "权重 / ms"],- [(name, number(weight, 0)) for name, weight in profile["leaf"]],- )- hot += (- table(- ["调用链", "权重 / ms"],- [- (name, number(weight, 0))- for name, weight in profile["inclusive"]- ],- )- + "</details></details>"- )- hotspot_html.append(hot)- record_rows.append(- [- phase["id"],- phase["template"],- number(phase.get("recorded_s"), 2, " s"),- r.get("samples", "N/A"),- number(r.get("max_gap_s"), 2, " s"),- number(- coverage * 100- if (coverage := r.get("cpu_coverage")) is not None- else None,- 1,- "%",- ),- "已采集" if phase in valid else "部分数据",- ]- )- event_labels: tuple[tuple[EventKey, str], ...] = (("potential-hangs", "Hangs"), ("hang-risks", "Hang risks"))- for event_key, label in event_labels:- for event in phase.get(event_key, {}).get("events", []):- event_rows.append(- [- phase["id"],- label,- " · ".join(f"{k}: {v}" for k, v in event.items()),- ]- )- events_chart = bars(- [- (- p["id"],- [- ("Hangs", p.get("potential-hangs", {}).get("count"), COLORS[0]),- ("Hang risks", p.get("hang-risks", {}).get("count"), COLORS[2]),- ],- )- for p in phases- ],- "条",- 0,- )- thermal = '<div class="thermal-grid">'- for p in phases:- events = p.get("device-thermal-state-intervals", {}).get("events", [])- thermal += f'<div class="thermal-phase"><b>{escape(p["id"])}</b>'- if not events:- thermal += '<span class="muted">N/A</span>'- for event in events:- state_name = event.get("thermal-state", "N/A")- thermal += f'<div class="thermal-state {"nominal" if state_name.lower() == "nominal" else "elevated"}"><b>{escape(state_name)}</b><span>{escape(event.get("start", ""))} → {escape(event.get("end", ""))}</span></div>'- thermal += "</div>"- thermal += "</div>"- metadata: list[list[object]] = [- ["App", target.get("name", "N/A")],- ["Bundle ID", target.get("bundle_id", "N/A")],- [- "版本 / 构建",- f"{target.get('version', 'N/A')} / {target.get('build', 'N/A')}",- ],- ["macOS / 架构", f"{env.get('os', 'N/A')} / {env.get('arch', 'N/A')}"],- ["芯片 / 逻辑核心", f"{env.get('chip', 'N/A')} / {env.get('cores', 'N/A')}"],- [- "内存",- number(int(memory_bytes) / 2 ** 30, 0, " GiB")- if (memory_bytes := env.get("memory_bytes"))- else "N/A",- ],- ["Instruments", env.get("instruments", "N/A")],- ["电源", env.get("power", "N/A")],- ["工作负载", data.get("config", {}).get("workload", "N/A")],- ]- fingerprint = [- ["App 文件指纹", target.get("binary_sha256", "N/A")],- [- "Mach-O UUID",- "; ".join(f"{arch}: {uuid}" for uuid, arch in target.get("uuids", [])),- ],- ]- load_groups = [- (- label,- [- ("开始", env.get("load_before", [None] * 3)[i], COLORS[0]),- ("结束", env.get("load_after", [None] * 3)[i], COLORS[1]),- ],- )- for i, label in enumerate(["1 分钟", "5 分钟", "15 分钟"])- ]- optional = ""- comparison = data.get("comparison")- if comparison:- optional += '<section class="section"><h2>历史基线差值</h2>'- if comparison.get("deltas"):- optional += '<div class="two">' + panel(- "平均 CPU 差值",- ranked(- [(r["phase"], r["cpu_pp"]) for r in comparison["deltas"]],- "百分点",- digits=2,- ),- )- optional += (- panel(- "footprint 中位数差值",- ranked(- [- (r["phase"], r["footprint_mib"])- for r in comparison["deltas"]- ],- "MiB",- digits=2,- ),- )- + "</div>"- )- else:- optional += table(- ["比较状态", "字段"],- [["条件不匹配", ", ".join(comparison.get("differences", []))]],- )- optional += "</section>"- budgets = data.get("config", {})- if (- budgets.get("cpu_mean_budget") is not None- or budgets.get("footprint_budget") is not None- ):- optional += (- '<section class="section"><h2>配置预算</h2>'- + table(- ["平均 CPU 上限", "footprint 峰值上限", "超出项"],- [- [- number(budgets.get("cpu_mean_budget"), 2, "%"),- number(budgets.get("footprint_budget"), 1, " MiB"),- ", ".join(data.get("budget_breaches", [])) or "0",- ]- ],- )- + "</section>"- )- portable = cast(Report, json.loads(json.dumps(data)))- portable.get("target", {}).get("identity", {}).pop("path", None)- for phase in portable.get("phases", []):- phase.pop("commands", None)- payload = (- json.dumps(portable, ensure_ascii=False, allow_nan=False)- .replace("&", "\\u0026")- .replace("<", "\\u003c")- .replace(">", "\\u003e")- )- errors = data.get("errors", [])- replacements = {- "TITLE": escape(target.get("name", "App")) + " · 性能数据",- "APP": escape(target.get("name", "App")),- "STATE": state,- "STATE_TONE": tone,- "STARTED": escape(data.get("started", "N/A")),- "ENDED": escape(data.get("ended", "采集中")),- "PRESET": escape(data.get("config", {}).get("preset", "N/A")),- "VERSION": escape(f"{target.get('version', 'N/A')} ({target.get('build', 'N/A')})"),- "MINUTES": number(measured / 60, 1),- "CPU": number(cpu_mean, 2),- "MEMORY": number(max(footprints) if footprints else None, 1),- "HANGS": str(hangs) if hangs is not None else "N/A",- "EXTRA_KPIS": extra_kpis_html,- "MATRIX": matrix,- "PHASE_BUTTONS": "".join(phase_buttons),- "HANG_PHASES": str(len(hang_phases)),- "ERRORS": '<div class="notice warn">' + "<br>".join(escape(e) for e in errors) + "</div>"- if errors- else "",- "COMPARISONS": "".join(comparisons),- "IO_CHARTS": "".join(io_charts),- "PHASES": "".join(phase_html),- "HOT_OVERVIEW": hot_overview,- "HOTSPOTS": "".join(hotspot_html),- "EVENTS": panel("Hangs / Hang risks", events_chart) + panel("热状态", thermal),- "EVENT_DETAILS": table(["阶段", "事件", "记录"], event_rows)- if event_rows- else "",- "RECORDS": table(- ["阶段", "模板", "记录时长", "样本数", "最大间隔", "CPU 采样覆盖", "状态"],- record_rows,- ),- "METADATA": table(["项目", "值"], metadata),- "FINGERPRINT": table(["字段", "值"], fingerprint),- "LOAD": bars(load_groups, "", 2),- "OPTIONAL": optional,- "PAYLOAD": payload,- }- template = Path(__file__).with_name("performance.html").read_text()- document = re.sub(r"@@([A-Z_]+)@@", lambda match: replacements[match[1]], template)- destination = Path(destination)- destination.parent.mkdir(parents=True, exist_ok=True)- temporary = destination.with_suffix(".html.tmp")- temporary.write_text(document)- temporary.replace(destination)diff --git a/Shared/BoundedProcess.swift b/Shared/BoundedProcess.swiftindex b799eb2..fcf1c82 100644--- a/Shared/BoundedProcess.swift+++ b/Shared/BoundedProcess.swift@@ -39,7 +39,7 @@ nonisolated enum BoundedProcess {var standardError = Output(reachedEOF: true)var terminationStatus: Int32?var terminationReason: Process.TerminationReason?- /// 返回后由调用方接管, 内核不再访问该进程+ /// 返回后由调用方接管, BoundedProcess 不再访问该进程var runningProcess: Process?var exitCode: Int32 {diff --git a/Tests/App/Activity/ActivityBackfillTests.swift b/Tests/App/Activity/ActivityBackfillTests.swiftindex 9f593e5..c6b286a 100644--- a/Tests/App/Activity/ActivityBackfillTests.swift+++ b/Tests/App/Activity/ActivityBackfillTests.swift@@ -2,6 +2,7 @@ import Foundationimport Synchronizationimport Testing+@Suite(.tags(.integration))struct ActivityBackfillTests {nonisolated enum BackfillOutcome: CaseIterable { case complete, stop, invalidResponse, liveCreation }@@ -294,6 +295,8 @@ extension ActivityBackfillTests {}let cursors = Mutex<[String?]>([])let queriedThreads = Mutex<Set<String>>([])+ let completedChild = Mutex(false)+ let childReads = Mutex(0)let timestamp = Date().addingTimeInterval(-60).timeIntervalSince1970let server = try SharedServerFixture(connections: 4, concurrentConnections: true) { peer inif try Self.initialize(peer) == "codex_bar_activity_backfill" {@@ -326,7 +329,7 @@ extension ActivityBackfillTests {try peer.reply(to: request, result: ["data": items])}} else {- try Self.serveNewSubagent(peer, timestamp: timestamp, firstPage: firstPage)+ try Self.serveNewSubagent(peer, timestamp: timestamp, firstPage: firstPage, completedChild: completedChild, childReads: childReads)}}defer { server.close() }@@ -352,27 +355,46 @@ extension ActivityBackfillTests {}#expect(await reader.lifecycleSnapshot.lifecycleStates(for: references).allSatisfy { $0.effort == "low" })#expect(cursors.withLock { $0 } == [nil, "older"])+ completedChild.withLock { $0 = true }+ _ = await reader.drainForRecovery(generation: UUID())+ let readsAfterCompletion = childReads.withLock { $0 }+ _ = await reader.drainForRecovery(generation: UUID())+ #expect(childReads.withLock { $0 } == readsAfterCompletion)await reader.stop()try server.finish()#expect(queriedThreads.withLock { $0 } == ["parent", "child"])}- private nonisolated static func serveNewSubagent(_ peer: SharedServerFixture.Peer, timestamp: Double, firstPage: DispatchSemaphore) throws {+ private nonisolated static func serveNewSubagent(+ _ peer: SharedServerFixture.Peer, timestamp: Double, firstPage: DispatchSemaphore,+ completedChild: borrowing Mutex<Bool>, childReads: borrowing Mutex<Int>+ ) throws {var sent = falsewhile let request = try? peer.readMessage() {let id = (request["params"] as? [String: Any])?["threadId"] as? String ?? ""switch request["method"] as? String {- case "thread/loaded/list": try peer.reply(to: request, result: ["data": ["parent", "child"]])+ case "thread/loaded/list": try peer.reply(to: request, result: ["data": completedChild.withLock { $0 } ? ["parent"] : ["parent", "child"]])case "thread/read", "thread/resume":var thread: [String: Any] = ["id": id, "source": "cli", "status": ["type": "active"]]+ if id == "child" {+ childReads.withLock { $0 += 1 }+ if completedChild.withLock({ $0 }) {+ thread["status"] = ["type": "notLoaded"]+ }+ }if id != "parent" {thread["parentThreadId"] = "parent"}try peer.reply(to: request, result: ["thread": thread])case "thread/turns/list":- try peer.reply(to: request, result: ["data": [[+ var turn: [String: Any] = ["id": id == "parent" ? "root" : id + "-turn", "rootTurnId": "root", "status": "inProgress", "startedAt": timestamp- ]]])+ ]+ if id == "child", completedChild.withLock({ $0 }) {+ turn["status"] = "completed"+ turn["completedAt"] = timestamp + 30+ }+ try peer.reply(to: request, result: ["data": [turn]])if id == "parent", !sent {sent = true#expect(firstPage.wait(timeout: .now() + 3) == .success)diff --git a/Tests/App/Activity/ActivityIsolationTests.swift b/Tests/App/Activity/ActivityIsolationTests.swiftindex a46e12e..42a94f4 100644--- a/Tests/App/Activity/ActivityIsolationTests.swift+++ b/Tests/App/Activity/ActivityIsolationTests.swift@@ -2,6 +2,7 @@ import Foundationimport Synchronizationimport Testing+@Suite(.tags(.integration))struct ActivityIsolationTests {@Test func cumulativeTokenNotificationsReachLogsStorageAndLiveTasks() async throws {let directory = try TestDirectory()diff --git a/Tests/App/Activity/ActivityLiveLabelTests.swift b/Tests/App/Activity/ActivityLiveLabelTests.swiftindex c5c5c99..56c0c56 100644--- a/Tests/App/Activity/ActivityLiveLabelTests.swift+++ b/Tests/App/Activity/ActivityLiveLabelTests.swift@@ -49,7 +49,6 @@ struct ActivityLiveLabelTests {@Test(arguments: ["git", "git, ls"])func parsedCommandLabelsAreLocalized(names: String) {- #expect(ActivityLiveLabel("executing-tool", detail: "python3").text == String(localized: "activity.live.executing-named-tool", defaultValue: "\("python3")"))#expect(ActivityLiveLabel("executing-tool", detail: names).text == String(localized: "activity.live.executing-named-tool", defaultValue: "\(names)"))#expect(ActivityLiveLabel("command-completed", detail: names).text == String(localized: "activity.live.named-command-completed", defaultValue: "\(names)"))#expect(ActivityLiveLabel("command-failed", detail: names).text == String(localized: "activity.live.named-command-failed", defaultValue: "\(names)"))@@ -123,7 +122,10 @@ struct ActivityLiveLabelTests {#expect(ActivityDisplayFormat.toolActionText(itemType: type, toolName: " ") == String(localized: action))}- @Test(arguments: ["mcpToolCall", "dynamicToolCall", "future", nil] as [String?], ["search/read", "spawnAgent", "commandExecution"])+ @Test(arguments: [+ ("mcpToolCall", "search/read"), ("dynamicToolCall", "spawnAgent"),+ ("future", "commandExecution"), (nil, "search/read")+ ] as [(String?, String)])func actualToolNamesAreNeverClassifiedByTheirSpelling(type: String?, tool: String) {#expect(ActivityDisplayFormat.toolActionText(itemType: type, toolName: tool) == tool)}diff --git a/Tests/App/Activity/ActivityLivePresentationTests.swift b/Tests/App/Activity/ActivityLivePresentationTests.swiftindex 925fcff..edab5fe 100644--- a/Tests/App/Activity/ActivityLivePresentationTests.swift+++ b/Tests/App/Activity/ActivityLivePresentationTests.swift@@ -607,7 +607,9 @@ struct ActivityLivePresentationTests {#expect(snapshot.panelWaitingTasks.count == 1)#expect(snapshot.panelRunningTasks.isEmpty)#expect(snapshot.primaryActivity == .running(task.snapshot))- #expect(snapshot.panelPrimaryActivity == .waiting(task.snapshot))+ var selection = ActivityCardSelection()+ selection.update(snapshot: snapshot, isHealthy: true, now: now)+ #expect(selection.current == .waiting(task.snapshot))#expect(snapshot.keepAliveTaskIDs.waiting == (isBlocking ? [task.displayID] : []))#expect(snapshot.keepAliveTaskIDs.running == (isBlocking ? [] : [task.displayID]))let summary = ActivityDisplayFormat.liveSummaryComponents(for: task.snapshot, now: now)@@ -640,7 +642,7 @@ struct ActivityLivePresentationTests {let concurrent = ActivityTaskSnapshot(id: UUID(), projectName: nil, modelName: nil, effort: nil,- startedAt: now, stateChangedAt: now, activeSubagentCount: nil+ startedAt: now, stateChangedAt: now, activeSubagentCount: nil, threadID: "concurrent-thread")let mixed = ActivitySnapshot(waitingTasks: [], runningTasks: [waiting, concurrent], recentCompletions: [], recentTerminations: [])#expect(mixed.keepAliveTaskIDs.running == [concurrent.id])diff --git a/Tests/App/Activity/ActivityReaderBoundsTests.swift b/Tests/App/Activity/ActivityReaderBoundsTests.swiftindex 8c4ffc1..046b17e 100644--- a/Tests/App/Activity/ActivityReaderBoundsTests.swift+++ b/Tests/App/Activity/ActivityReaderBoundsTests.swift@@ -1,6 +1,7 @@import Foundationimport Testing+@Suite(.tags(.integration))struct ActivityReaderBoundsTests {@Test(arguments: [["repeat", "repeat"], ["a", "b", "a"], ["a", "b", "c"]])func invalidPaginationCannotCompleteBootstrap(cursors: [String]) async throws {diff --git a/Tests/App/Activity/ActivityReconciliationTests.swift b/Tests/App/Activity/ActivityReconciliationTests.swiftindex 7ab491b..ddb159a 100644--- a/Tests/App/Activity/ActivityReconciliationTests.swift+++ b/Tests/App/Activity/ActivityReconciliationTests.swift@@ -3,6 +3,7 @@ import Synchronizationimport Testing@MainActor+@Suite(.tags(.integration))struct ActivityReconciliationTests {@Test(arguments: [false, true])func bootstrapCannotFinishARecoveryStartedAfterItsBarrier(restarted: Bool) throws {diff --git a/Tests/App/Activity/ActivityRecoveryTests.swift b/Tests/App/Activity/ActivityRecoveryTests.swiftindex cc63f9f..1f075aa 100644--- a/Tests/App/Activity/ActivityRecoveryTests.swift+++ b/Tests/App/Activity/ActivityRecoveryTests.swift@@ -1,6 +1,7 @@import Foundationimport Testing+@Suite(.tags(.integration))struct ActivityRecoveryTests {@Test(arguments: ["item/started", "item/completed"])func reasoningContentDoesNotInvalidateLivePresentation(method: String) async throws {diff --git a/Tests/App/Activity/ActivitySchedulingTests.swift b/Tests/App/Activity/ActivitySchedulingTests.swiftindex d1a2b08..1f5105d 100644--- a/Tests/App/Activity/ActivitySchedulingTests.swift+++ b/Tests/App/Activity/ActivitySchedulingTests.swift@@ -2,6 +2,7 @@ import Foundationimport Synchronizationimport Testing+@Suite(.tags(.integration))struct ActivitySchedulingTests {@Test func slowQueryDoesNotBlockPushOrOverwriteNewerApproval() async throws {let directory = try TestDirectory()@@ -137,6 +138,7 @@ struct ActivitySchedulingTests {socketURL: server.url, logStorage: nil,tokenUsageHistory: TokenUsageHistoryStore(directoryURL: directory.url),activityDataRecorder: ActivityDataRecorder(directoryURL: directory.url),+ discoveryInterval: 0,reconciliationClock: { clock.withLock { $0 } },onBatch: { update inif update.phase == .bootstrapEnd {diff --git a/Tests/App/Activity/ActivityTaskTests.swift b/Tests/App/Activity/ActivityTaskTests.swiftindex 56af751..050c31d 100644--- a/Tests/App/Activity/ActivityTaskTests.swift+++ b/Tests/App/Activity/ActivityTaskTests.swift@@ -2,6 +2,31 @@ import Foundationimport Testingstruct ActivityTaskTests {+ @Test(arguments: [ActivityDataEventKind.turnCompleted, .turnAborted])+ func realTaskSnapshotsPreserveThreadIDAcrossTurnsAndTerminalRecords(terminal: ActivityDataEventKind) throws {+ let now = Date(timeIntervalSince1970: 1800000000)+ var graph = ActivityTaskGraph()+ let start = TestFixtures.event(at: now)+ _ = graph.consume([start], source: .live)+ let first = try #require(graph.tasks[ActivityTaskKey(thread: "thread-a", turn: "turn-a")])+ let threadID = first.snapshot.threadID+ #expect(threadID == "thread-a")+ _ = graph.consume([TestFixtures.event(terminal, at: now.addingTimeInterval(1))], source: .live)+ if terminal == .turnCompleted {+ #expect(graph.completions.first?.threadID == threadID)+ } else {+ #expect(graph.terminations.first?.threadID == threadID)+ }+ _ = graph.consume([TestFixtures.event(at: now.addingTimeInterval(2), turn: "turn-b")], source: .live)+ let next = try #require(graph.tasks[ActivityTaskKey(thread: "thread-a", turn: "turn-b")])+ #expect(next.snapshot.threadID == threadID)+ #expect(next.displayID != first.displayID)+ _ = graph.consume([TestFixtures.event(at: now.addingTimeInterval(3), thread: "another-thread", turn: "turn-b")], source: .live)+ let other = try #require(graph.tasks[ActivityTaskKey(thread: "another-thread", turn: "turn-b")])+ #expect(other.snapshot.threadID == "another-thread")+ #expect(other.snapshot.threadID != threadID)+ }+@Test(arguments: [ActivityDataEventKind.turnCompleted, .turnAborted])func terminalSnapshotPreservesTaskIdentityAcrossTurns(terminal: ActivityDataEventKind) throws {let directory = try TestDirectory()diff --git a/Tests/App/Activity/ActivityThreadFilteringTests.swift b/Tests/App/Activity/ActivityThreadFilteringTests.swiftindex 21685e5..a801833 100644--- a/Tests/App/Activity/ActivityThreadFilteringTests.swift+++ b/Tests/App/Activity/ActivityThreadFilteringTests.swift@@ -2,6 +2,7 @@ import Foundationimport Synchronizationimport Testing+@Suite(.tags(.integration))struct ActivityThreadFilteringTests {@Test(arguments: [false, true])func titleThreadsDoNotBlockRecoveryOrProduceActivity(discoveredByNotification: Bool) async throws {diff --git a/Tests/App/Activity/ActivityTokenUsageTests.swift b/Tests/App/Activity/ActivityTokenUsageTests.swiftindex bbb7ee3..a835bca 100644--- a/Tests/App/Activity/ActivityTokenUsageTests.swift+++ b/Tests/App/Activity/ActivityTokenUsageTests.swift@@ -356,13 +356,17 @@ struct ActivityTokenUsageTests {#expect(monitor.snapshot.activeCount == 1)}- @Test(arguments: [false, true])- func terminalUsageContinuesUntilCardIsRemoved(clearExplicitly: Bool) throws {+ @Test(arguments: [false, true], [false, true])+ func terminalUsageContinuesUntilCardIsRemoved(clearExplicitly: Bool, aborted: Bool) throws {let directory = try TestDirectory()defer { try? directory.remove() }let preferences = try TestPreferences()defer { preferences.remove() }let monitor = try makeMonitor(directory: directory, preferences: preferences)+ defer {+ monitor.clearCollectedActivityState()+ monitor.refreshSnapshot(now: Date())+ }let now = Date()let event = TestFixtures.event(at: now)let key = try #require(ActivityTaskKey(event: event))@@ -371,18 +375,29 @@ struct ActivityTokenUsageTests {startedAt: now, progressGeneration: 1)var transitions: [ActivityTransition] = []- monitor.graph.resolveTerminal(.completed(at: now, duration: 1), task: task, key: key, abortFallback: now, into: &transitions)+ let terminal: TurnTerminalState = aborted ? .aborted(at: now, duration: 1) : .completed(at: now, duration: 1)+ monitor.graph.resolveTerminal(terminal, task: task, key: key, abortFallback: now, into: &transitions)let root = reference("thread-a", "turn-a")#expect(monitor.graph.terminalTokenUsageReferences().contains(root))- #expect(monitor.graph.terminalTokenUsageReferences().contains(root))monitor.graph.applyTerminalTokenUsage([state(root, input: 500)])- #expect(monitor.graph.completions.first?.tokenUsage?.totalTokens == 510)+ monitor.refreshSnapshot(now: now.addingTimeInterval(599))+ #expect(monitor.snapshot.recentCompletions.count == (aborted ? 0 : 1))+ #expect(monitor.snapshot.recentTerminations.count == (aborted ? 1 : 0))+ let tokenUsage = aborted+ ? monitor.snapshot.recentTerminations.first?.tokenUsage+ : monitor.snapshot.recentCompletions.first?.tokenUsage+ #expect(tokenUsage?.totalTokens == 510)+ #expect(monitor.graph.terminalTokenUsageReferences().contains(root))if clearExplicitly {monitor.clearCollectedActivityState()+ monitor.refreshSnapshot(now: now.addingTimeInterval(599))} else {- monitor.refreshSnapshot(now: now.addingTimeInterval(601))+ monitor.refreshSnapshot(now: now.addingTimeInterval(600))}+ #expect(monitor.snapshot.recentCompletions.isEmpty)+ #expect(monitor.snapshot.recentTerminations.isEmpty)#expect(monitor.graph.completions.isEmpty)+ #expect(monitor.graph.terminations.isEmpty)#expect(monitor.graph.terminalTokenUsageRequests.isEmpty)#expect(monitor.graph.terminalTokenUsageReferences().isEmpty)}diff --git a/Tests/App/Activity/ActivityUpdateTests.swift b/Tests/App/Activity/ActivityUpdateTests.swiftindex cc876e2..4a5798d 100644--- a/Tests/App/Activity/ActivityUpdateTests.swift+++ b/Tests/App/Activity/ActivityUpdateTests.swift@@ -3,6 +3,7 @@ import Foundationimport Synchronizationimport Testing+@Suite(.tags(.integration))struct ActivityUpdateTests {@Test(arguments: ["resolved", "pending", "replaced", "unknown", "ended"], [false, true])func approvalPublicationUsesFinalState(scenario: String, deferred: Bool) throws {diff --git a/Tests/App/Activity/ProtectionRecoveryTests.swift b/Tests/App/Activity/ProtectionRecoveryTests.swiftindex 2b203d5..773c896 100644--- a/Tests/App/Activity/ProtectionRecoveryTests.swift+++ b/Tests/App/Activity/ProtectionRecoveryTests.swift@@ -2,6 +2,7 @@ import Foundationimport Testing@MainActor+@Suite(.tags(.integration))struct ProtectionRecoveryTests {@Test func repairedStoreReloadsWhenProtectionIsEnabled() async throws {let directory = try TestDirectory()diff --git a/Tests/App/Activity/ProtectionStoreTests.swift b/Tests/App/Activity/ProtectionStoreTests.swiftindex 3fbf533..d77ebc2 100644--- a/Tests/App/Activity/ProtectionStoreTests.swift+++ b/Tests/App/Activity/ProtectionStoreTests.swift@@ -1,6 +1,7 @@import Foundationimport Testing+@Suite(.tags(.integration))struct ProtectionStoreTests {@Test func expiredRecordsArePrunedAtExactDeadline() async throws {let directory = try TestDirectory()diff --git a/Tests/App/AppServer/AppServerLogTests.swift b/Tests/App/AppServer/AppServerLogTests.swiftindex 1d65f37..8b4f220 100644--- a/Tests/App/AppServer/AppServerLogTests.swift+++ b/Tests/App/AppServer/AppServerLogTests.swift@@ -4,6 +4,7 @@ import osimport SQLite3import Testing+@Suite(.tags(.integration))struct AppServerLogTests {@Test func closeDrainsWritesAndPermanentlyClosesDatabase() async throws {let directory = try TestDirectory()@@ -116,7 +117,7 @@ struct AppServerLogTests {let model = AppServerLogViewModel(storage: storage)defer { model.stop() }- // 确定性复现视图先读取, 窗口随后开始观察的调用顺序+ // 固定调用顺序, 复现视图先读取, 窗口随后开始观察的情况var didStart = falselet subscription = model.$isLoading.sink { isLoading inguard isLoading, !didStart else { return }diff --git a/Tests/App/AppServer/AppServerRequestBudgetTests.swift b/Tests/App/AppServer/AppServerRequestBudgetTests.swiftindex 02c2ffb..24138df 100644--- a/Tests/App/AppServer/AppServerRequestBudgetTests.swift+++ b/Tests/App/AppServer/AppServerRequestBudgetTests.swift@@ -2,7 +2,7 @@ import Darwinimport Foundationimport Testing-@Suite(.timeLimit(.minutes(1)))+@Suite(.tags(.integration), .timeLimit(.minutes(1)))struct AppServerRequestBudgetTests {@Test func expiredBudgetNeverSendsRequest() async throws {let server = try SharedServerFixture { peer indiff --git a/Tests/App/AppServer/AppServerSessionTests.swift b/Tests/App/AppServer/AppServerSessionTests.swiftindex f7a817c..cc9706a 100644--- a/Tests/App/AppServer/AppServerSessionTests.swift+++ b/Tests/App/AppServer/AppServerSessionTests.swift@@ -3,6 +3,7 @@ import Darwinimport Foundationimport Testing+@Suite(.tags(.integration))struct AppServerSessionTests {@Test func acceptsResponseLargerThanSixteenMiB() throws {let server = try SharedServerFixture { peer indiff --git a/Tests/App/AppServer/AppServerStartupTests.swift b/Tests/App/AppServer/AppServerStartupTests.swiftindex 99a33fe..50bd3c8 100644--- a/Tests/App/AppServer/AppServerStartupTests.swift+++ b/Tests/App/AppServer/AppServerStartupTests.swift@@ -3,6 +3,7 @@ import Foundationimport osimport Testing+@Suite(.tags(.integration))struct AppServerStartupTests {@Test func reusesRunningServiceWithoutAnInstalledCLI() async throws {let server = try SharedServerFixture { _ in }diff --git a/Tests/App/Codex/CodexVersionProcessTests.swift b/Tests/App/Codex/CodexVersionProcessTests.swiftindex b6945a7..ebc6305 100644--- a/Tests/App/Codex/CodexVersionProcessTests.swift+++ b/Tests/App/Codex/CodexVersionProcessTests.swift@@ -1,6 +1,7 @@import Foundationimport Testing+@Suite(.tags(.integration))struct CodexVersionProcessTests {@Test(arguments: [("printf 'codex-cli 0.157.0\\nignored'; printf 'codex-cli 0.156.0' >&2", "0.157.0"),diff --git a/Tests/App/CodexStatus/AccountNotificationTests.swift b/Tests/App/CodexStatus/AccountNotificationTests.swiftindex 2e83da0..6a1ec43 100644--- a/Tests/App/CodexStatus/AccountNotificationTests.swift+++ b/Tests/App/CodexStatus/AccountNotificationTests.swift@@ -1,8 +1,9 @@import Foundationimport osimport Testing+import UserNotifications-@Suite(.timeLimit(.minutes(1)))+@Suite(.tags(.integration), .timeLimit(.minutes(1)))struct AccountNotificationTests {@Test func repeatedNotificationsKeepFirstDeadlineAndRespectCooldown() {var schedule = AccountNotificationSchedule()@@ -219,5 +220,149 @@ struct AccountNotificationTests {try server.finish()}+ @Test(arguments: ["window", "account", "logout"])+ func returningQuotaWindowStartsAFreshObservation(disappearance: String) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ preferences.defaults.set(true, forKey: "Notification.isEnabled")+ preferences.defaults.set(false, forKey: "Notification.isLowQuotaEnabled")+ let phase = OSAllocatedUnfairLock(initialState: 0)+ let resetsAt = Int(Date().addingTimeInterval(3600).timeIntervalSince1970)+ let server = try SharedServerFixture { peer in+ while let request = try? peer.readMessage() {+ let phase = phase.withLock { $0 }+ switch request["method"] as? String {+ case "initialize": try peer.reply(to: request, result: ["userAgent": "codex/0.162.0"])+ case "initialized": continue+ case "account/read":+ let account: Any = phase == 1 && disappearance == "logout" ? NSNull() : [+ "type": "chatgpt", "email": phase == 1 && disappearance == "account" ? "[email protected]" : "[email protected]", "planType": "pro"+ ]+ try peer.reply(to: request, result: ["account": account])+ case "account/rateLimits/read":+ let limits: [String: Any] = phase == 1 && disappearance == "window" ? [:] : [+ "primary": ["usedPercent": phase == 1 ? 20 : 95, "resetsAt": resetsAt, "windowDurationMins": 300]+ ]+ try peer.reply(to: request, result: ["rateLimits": limits])+ case "account/usage/read":+ try peer.reply(to: request, result: ["summary": [:]])+ if phase == 2 {+ return+ }+ default: Issue.record("Unexpected request")+ }+ }+ }+ defer { server.close() }+ let settings = NotificationSettings(defaults: preferences.defaults, readAuthorizationStatus: { .authorized })+ let model = CodexStatusViewModel(service: CodexStatusService(socketURL: server.url, logStorage: nil), defaults: preferences.defaults)+ let monitor = ActivityMonitor(+ protectionSettings: ProtectionSettings(defaults: preferences.defaults),+ protectionStore: ProtectionStore(directoryURL: directory.url), activityDataDirectoryURL: directory.url+ )+ var delivered = 0+ let notifications = NotificationService(+ settings: settings, statusViewModel: model, activityMonitor: monitor, defaults: preferences.defaults,+ delivery: .init(setDelegate: { _ in }, add: { _ in delivered += 1 }, remove: { _ in }), openMenuSurface: {}+ )+ notifications.start()+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(5)) { settings.canDeliver })+ for current in 0 ... 2 {+ phase.withLock { $0 = current }+ model.refresh(trigger: .manual)+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(5)) { !model.isRefreshing })+ if current == 0 {+ #expect(model.snapshot?.limits.first?.windows.first?.remainingPercent == 5)+ #expect(delivered == 0)+ } else if current == 1 {+ settings.setLowQuotaEnabled(true)+ }+ }+ #expect(try await waitForCondition(timeout: .seconds(1), pollInterval: .milliseconds(5)) { delivered == 1 })+ withExtendedLifetime(notifications) {}+ try server.finish()+ }++ @Test(arguments: [false, true], [false, true])+ func quotaSubmissionFailureRespectsWindowLifecycle(lowQuota: Bool, reappears: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ preferences.defaults.set(true, forKey: "Notification.isEnabled")+ preferences.defaults.set(10, forKey: "Notification.lowQuotaThresholdPercent")+ let phase = OSAllocatedUnfairLock(initialState: 0)+ let resetsAt = Int(Date().addingTimeInterval(3600).timeIntervalSince1970)+ let server = try SharedServerFixture { peer in+ while let request = try? peer.readMessage() {+ let phase = phase.withLock { $0 }+ switch request["method"] as? String {+ case "initialize": try peer.reply(to: request, result: ["userAgent": "codex/0.162.0"])+ case "initialized": continue+ case "account/read":+ try peer.reply(to: request, result: ["account": ["type": "chatgpt", "email": "[email protected]", "planType": "pro"]])+ case "account/rateLimits/read":+ let limits: [String: Any] = phase == 2 ? [:] : [+ "primary": ["usedPercent": phase == 0 ? 20 : (lowQuota ? 95 : 0), "resetsAt": resetsAt, "windowDurationMins": 300]+ ]+ try peer.reply(to: request, result: ["rateLimits": limits])+ case "account/usage/read":+ try peer.reply(to: request, result: ["summary": [:]])+ if phase == 4 {+ return+ }+ default: Issue.record("Unexpected request")+ }+ }+ }+ defer { server.close() }+ let settings = NotificationSettings(defaults: preferences.defaults, readAuthorizationStatus: { .authorized })+ let model = CodexStatusViewModel(service: CodexStatusService(socketURL: server.url, logStorage: nil), defaults: preferences.defaults)+ let monitor = ActivityMonitor(+ protectionSettings: ProtectionSettings(defaults: preferences.defaults),+ protectionStore: ProtectionStore(directoryURL: directory.url), activityDataDirectoryURL: directory.url+ )+ let release = TestCheckpoint()+ defer { release.signal() }+ var attempts = 0+ var delivered = 0+ let notifications = NotificationService(+ settings: settings, statusViewModel: model, activityMonitor: monitor, defaults: preferences.defaults,+ delivery: .init(setDelegate: { _ in }, add: { _ in+ attempts += 1+ if attempts <= 2 {+ await release.wait()+ throw CocoaError(.fileWriteUnknown)+ }+ delivered += 1+ }, remove: { _ in }), openMenuSurface: {}+ )+ notifications.start()+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(5)) { settings.canDeliver })+ func refresh(_ current: Int) async throws {+ phase.withLock { $0 = current }+ model.refresh(trigger: .manual)+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(5)) { !model.isRefreshing })+ }+ try await refresh(0)+ #expect(attempts == 0)+ try await refresh(1)+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(5)) { attempts == 1 })+ settings.setLowQuotaThresholdPercent(15)+ if reappears {+ try await refresh(2)+ try await refresh(3)+ }+ release.signal()+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(5)) { attempts == 2 })+ try await refresh(4)+ #expect(try await waitForCondition(timeout: .seconds(1), pollInterval: .milliseconds(5)) { delivered == 1 } == !reappears)+ #expect(attempts == (reappears ? 2 : 3))+ withExtendedLifetime(notifications) {}+ try server.finish()+ }+private nonisolated struct Value: Decodable { let value: Int }}diff --git a/Tests/App/CodexStatus/CodexStatusServiceTests.swift b/Tests/App/CodexStatus/CodexStatusServiceTests.swiftindex 3e3ae33..2a59c2f 100644--- a/Tests/App/CodexStatus/CodexStatusServiceTests.swift+++ b/Tests/App/CodexStatus/CodexStatusServiceTests.swift@@ -2,7 +2,7 @@ import Foundationimport osimport Testing-@Suite(.timeLimit(.minutes(1)))+@Suite(.tags(.integration), .timeLimit(.minutes(1)))struct CodexStatusServiceTests {@Test(arguments: ["business", "unsupported", "invalidPayload"], [false, true])func supplementalFailurePreservesCacheAndUnsupportedMethodPolicy(failure: String, hasCache: Bool) async throws {diff --git a/Tests/App/History/AppServerEventStorageTests.swift b/Tests/App/History/AppServerEventStorageTests.swiftindex 88cec32..736f73b 100644--- a/Tests/App/History/AppServerEventStorageTests.swift+++ b/Tests/App/History/AppServerEventStorageTests.swift@@ -1,6 +1,7 @@import Foundationimport Testing+@Suite(.tags(.integration))struct AppServerEventStorageTests {private let now = TestFixtures.nowdiff --git a/Tests/App/History/HistoryDatabaseIndexTests.swift b/Tests/App/History/HistoryDatabaseIndexTests.swiftindex 2098ec7..6bb3e83 100644--- a/Tests/App/History/HistoryDatabaseIndexTests.swift+++ b/Tests/App/History/HistoryDatabaseIndexTests.swift@@ -2,6 +2,7 @@ import Foundationimport SQLite3import Testing+@Suite(.tags(.integration))struct HistoryDatabaseIndexTests {@Test(arguments: [false, true])func existingDatabaseUpdatesIndexesWithoutChangingHistory(newIndexExists: Bool) throws {diff --git a/Tests/App/History/HistoryDatabaseStoreTests.swift b/Tests/App/History/HistoryDatabaseStoreTests.swiftindex 522af63..3ce881b 100644--- a/Tests/App/History/HistoryDatabaseStoreTests.swift+++ b/Tests/App/History/HistoryDatabaseStoreTests.swift@@ -2,6 +2,7 @@ import Foundationimport SQLite3import Testing+@Suite(.tags(.integration))struct HistoryDatabaseStoreTests {@Test func releasingConnectionPreservesCommittedData() async throws {let directory = try TestDirectory()@@ -163,7 +164,7 @@ struct HistoryDatabaseStoreTests {defer { try? directory.remove() }let tokens = TokenUsageHistoryStore(directoryURL: directory.url)let now = Date()- for index in 0 ..< 129 {+ for index in 0 ..< 257 {let threadID = "thread-\(index)"try await tokens.appendObservation(Self.observation(tokens: 5, at: now, threadID: threadID))#expect(try await tokens.snapshot(threadID: threadID).turns["turn"]?.totalTokens == 5)@@ -173,7 +174,7 @@ struct HistoryDatabaseStoreTests {current: Self.observation(tokens: 9, at: now).current))#expect(updated.turns["turn"]?.totalTokens == 9)- for index in 0 ..< 129 {+ for index in 0 ..< 257 {#expect(try await tokens.snapshot(threadID: "thread-\(index)").turns["turn"]?.totalTokens == (index == 0 ? 9 : 5))}}diff --git a/Tests/App/History/HistoryDatabaseTests.swift b/Tests/App/History/HistoryDatabaseTests.swiftindex 9077e8f..b1d8a41 100644--- a/Tests/App/History/HistoryDatabaseTests.swift+++ b/Tests/App/History/HistoryDatabaseTests.swift@@ -2,6 +2,7 @@ import Foundationimport SQLite3import Testing+@Suite(.tags(.integration))struct HistoryDatabaseTests {@Test func storedCommandActionsPreserveDuplicatesAndDoNotCountCompletionTwice() throws {let directory = try TestDirectory()diff --git a/Tests/App/History/HistoryServiceTests.swift b/Tests/App/History/HistoryServiceTests.swiftindex 1b7ecc7..9b906a3 100644--- a/Tests/App/History/HistoryServiceTests.swift+++ b/Tests/App/History/HistoryServiceTests.swift@@ -2,6 +2,7 @@ import CloudKitimport Foundationimport Testing+@Suite(.tags(.integration))struct HistoryServiceTests {@Test func sameSourceRecalculationCanReduceCountsWithoutDeletingRecord() async throws {let fixture = try await HistoryRebuildFixture()diff --git a/Tests/App/History/StorageRetentionTests.swift b/Tests/App/History/StorageRetentionTests.swiftindex fa54900..21e0a35 100644--- a/Tests/App/History/StorageRetentionTests.swift+++ b/Tests/App/History/StorageRetentionTests.swift@@ -2,6 +2,7 @@ import Foundationimport SQLite3import Testing+@Suite(.tags(.integration))struct StorageRetentionTests {@Test func cacheCleanupRunsDailyAndRetriesOnlyFailedStore() async throws {let directory = try TestDirectory()diff --git a/Tests/App/History/TokenUsageHistoryStoreTests.swift b/Tests/App/History/TokenUsageHistoryStoreTests.swiftindex 41dc2d3..b6e4423 100644--- a/Tests/App/History/TokenUsageHistoryStoreTests.swift+++ b/Tests/App/History/TokenUsageHistoryStoreTests.swift@@ -1,6 +1,7 @@import Foundationimport Testing+@Suite(.tags(.integration))struct TokenUsageHistoryStoreTests {@Test func recordingLeaseTransfersWithoutTwoWriters() throws {let directory = try TestDirectory()@@ -194,14 +195,25 @@ struct TokenUsageHistoryStoreTests {let now = Date()let expired = HistoryStorage.retentionCutoffDate(today: now).addingTimeInterval(-86400)let store = TokenUsageHistoryStore(directoryURL: directory.url)- _ = try await store.recordObservations([- TestFixtures.tokenUsageObservation(at: expired, tokenUsage: tokenUsage(20)),- TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(30))- ], now: now)+ let observations = [(expired, "expired", Int64(20)), (now, "current", Int64(30))].map { date, turn, count in+ TokenUsageObservation(+ observedAt: date, threadID: "thread", turnID: turn, previous: .zero,+ current: TokenUsageUpdate(total: tokenUsage(count), last: tokenUsage(count))+ )+ }+ _ = try await store.recordObservations(observations, now: now)let database = try HistoryDatabase(directoryURL: directory.url)+ #expect(try database.tokenUsageSnapshot(threadID: "thread").turns.count == 2)#expect(try database.prune(now: now) == 1)#expect(try database.tokenUsageAggregates().count == 1)#expect(try database.tokenUsageAggregates().first?.tokenUsage == tokenUsage(30))+ let retained = try database.tokenUsageSnapshot(threadID: "thread")+ #expect(retained.turns["expired"] == nil)+ #expect(retained.turns["current"] == tokenUsage(30))+ let future = now.addingTimeInterval(212 * 86400)+ #expect(try HistoryDatabase(directoryURL: directory.url).prune(now: future) == 1)+ #expect(try database.prune(now: future) == 0)+ #expect(try database.tokenUsageSnapshot(threadID: "thread").turns.isEmpty)}private func tokenUsage(_ count: Int64) -> TokenUsage {diff --git a/Tests/App/History/TokenUsageHistoryTests.swift b/Tests/App/History/TokenUsageHistoryTests.swiftindex 00c7d9e..7e85178 100644--- a/Tests/App/History/TokenUsageHistoryTests.swift+++ b/Tests/App/History/TokenUsageHistoryTests.swift@@ -1,6 +1,7 @@import Foundationimport Testing+@Suite(.tags(.integration))struct TokenUsageHistoryTests {private let day = HistoryStorage.dateKey(for: TestFixtures.now)@Test func cachedTokenUsageFileChecksBytesAcrossExternalWritesAndDeletion() throws {diff --git a/Tests/App/Notifications/TaskWaitingNotificationTests.swift b/Tests/App/Notifications/TaskWaitingNotificationTests.swiftindex 36d82ba..633b98d 100644--- a/Tests/App/Notifications/TaskWaitingNotificationTests.swift+++ b/Tests/App/Notifications/TaskWaitingNotificationTests.swift@@ -2,6 +2,7 @@ import Foundationimport Testingimport UserNotifications+@Suite(.tags(.integration))struct TaskWaitingNotificationTests {@Test(arguments: [false, true])func monitorTransitionDeliversAndSnapshotWithdrawsNotification(blockingInput: Bool) async throws {diff --git a/Tests/App/Presentation/ActivityCardEventsTests.swift b/Tests/App/Presentation/ActivityCardEventsTests.swiftnew file mode 100644index 0000000..14118a6--- /dev/null+++ b/Tests/App/Presentation/ActivityCardEventsTests.swift@@ -0,0 +1,114 @@+import AppKit+import Testing++@MainActor+struct ActivityCardEventsTests {+ @Test func inactiveHostCleanupCannotEndAnotherHostsGesture() async throws {+ let active = ActivityCardEvents.EventRegion()+ let inactive = ActivityCardEvents.EventRegion()+ var events: [ActivityCardEvents.SwipeEvent] = []+ active.onSwipe = { events.append($0) }+ inactive.onSwipe = { events.append($0) }+ active.isEnabled = true+ active.scroll(delta: -2, timestamp: 1, phase: .began)+ inactive.removeMonitor()+ #expect(events == [.began, .changed(-2)])+ active.removeMonitor()+ active.removeMonitor()+ try await Task.sleep(for: .milliseconds(10))+ #expect(events == [.began, .changed(-2), .cancelled])+ }++ @Test func disablingRegionReleasesGestureAndAllowsTheNextOne() async throws {+ let region = ActivityCardEvents.EventRegion()+ var events: [ActivityCardEvents.SwipeEvent] = []+ region.onSwipe = { events.append($0) }+ region.isEnabled = true+ region.scroll(delta: -4, timestamp: 1, phase: .began)+ region.isEnabled = false+ try await Task.sleep(for: .milliseconds(10))+ region.isEnabled = true+ region.scroll(delta: 3, timestamp: 2, phase: .began)+ region.scroll(delta: 0, timestamp: 2.2, phase: .ended)+ #expect(events == [.began, .changed(-4), .cancelled, .began, .changed(3), .ended(velocity: 0)])+ }++ @Test func everyDeltaIncludingReversalIsDeliveredBeforeRelease() {+ let region = ActivityCardEvents.EventRegion()+ var events: [ActivityCardEvents.SwipeEvent] = []+ region.onSwipe = { events.append($0) }+ region.isEnabled = true+ region.scroll(delta: -2, timestamp: 1, phase: .began)+ region.scroll(delta: -80, timestamp: 1.02, phase: .changed)+ region.scroll(delta: 25, timestamp: 1.04, phase: .changed)+ #expect(events == [.began, .changed(-2), .changed(-80), .changed(25)])+ region.scroll(delta: 0, timestamp: 1.3, phase: .ended)+ #expect(events.last == .ended(velocity: 0))+ let count = events.count+ region.scroll(delta: -90, timestamp: 1.31, phase: [], momentum: .began)+ region.scroll(delta: -20, timestamp: 1.32, phase: [], momentum: .changed)+ #expect(events.count == count)+ }++ @Test func recentMotionSuppliesReleaseVelocityAndCancellationDoesNotCommit() {+ let region = ActivityCardEvents.EventRegion()+ var events: [ActivityCardEvents.SwipeEvent] = []+ region.onSwipe = { events.append($0) }+ region.isEnabled = true+ region.scroll(delta: -5, timestamp: 1, phase: .began)+ region.scroll(delta: -15, timestamp: 1.02, phase: .changed)+ region.scroll(delta: 0, timestamp: 1.03, phase: .ended)+ guard case let .ended(velocity) = events.last else {+ Issue.record("Missing release velocity")+ return+ }+ #expect(velocity < 0)+ region.scroll(delta: -100, timestamp: 2, phase: .began)+ region.scroll(delta: 0, timestamp: 2.01, phase: .cancelled)+ #expect(events.last == .cancelled)+ }++ @Test func unphasedPreciseInputSettlesOnceAndCleanupCancelsItsTimer() async throws {+ let region = ActivityCardEvents.EventRegion()+ var events: [ActivityCardEvents.SwipeEvent] = []+ region.onSwipe = { events.append($0) }+ region.isEnabled = true+ region.scroll(delta: -10, timestamp: 1, phase: [])+ region.scroll(delta: 4, timestamp: 1.02, phase: [])+ try await Task.sleep(for: .milliseconds(220))+ #expect(events == [.began, .changed(-10), .changed(4), .ended(velocity: 0)])+ region.scroll(delta: -10, timestamp: 2, phase: [])+ region.removeMonitor()+ try await Task.sleep(for: .milliseconds(10))+ let expected = events+ try await Task.sleep(for: .milliseconds(220))+ #expect(events == expected)+ #expect(events.last == .cancelled)+ }++ @Test func ordinaryWheelKeepsDiscreteNavigation() {+ let region = ActivityCardEvents.EventRegion()+ var events: [ActivityCardEvents.SwipeEvent] = []+ region.onSwipe = { events.append($0) }+ region.isEnabled = true+ region.scroll(delta: -1, timestamp: 1, phase: [], precise: false)+ region.scroll(delta: 1, timestamp: 2, phase: [], precise: false)+ #expect(events == [.step(1), .step(-1)])+ }++ @Test func releaseIncludesFinalDeltaAndClosesBeforeMomentum() {+ let region = ActivityCardEvents.EventRegion()+ var events: [ActivityCardEvents.SwipeEvent] = []+ region.onSwipe = { events.append($0) }+ region.isEnabled = true+ region.scroll(delta: -5, timestamp: 1, phase: .began)+ region.scroll(delta: -3, timestamp: 1.02, phase: .ended, momentum: .began)+ #expect(events.prefix(3) == [.began, .changed(-5), .changed(-3)])+ guard case .ended = events.last else {+ Issue.record("Finger phase did not end")+ return+ }+ region.scroll(delta: -40, timestamp: 1.04, phase: [], momentum: .changed)+ #expect(events.count == 4)+ }+}diff --git a/Tests/App/Presentation/ActivityCardHeaderTests.swift b/Tests/App/Presentation/ActivityCardHeaderTests.swiftnew file mode 100644index 0000000..39ced34--- /dev/null+++ b/Tests/App/Presentation/ActivityCardHeaderTests.swift@@ -0,0 +1,43 @@+import AppKit+import SwiftUI+import Testing++@MainActor+struct ActivityCardHeaderTests {+ @Test func everyBadgeParticipatesInTheWrappingWidth() {+ let plain = singleLineThreshold(pin: false, positionText: "1/3", sun: false)+ let pinned = singleLineThreshold(pin: true, positionText: "1/3", sun: false)+ let numbered = singleLineThreshold(pin: true, positionText: "10/12", sun: false)+ let all = singleLineThreshold(pin: true, positionText: "10/12", sun: true)+ #expect(pinned > plain + 10)+ #expect(numbered > pinned + 8)+ #expect(all > numbered + 10)+ #expect(height(width: plain + 1, pin: true, positionText: "10/12", sun: true) > height(width: all + 1, pin: true, positionText: "10/12", sun: true))+ }++ private func singleLineThreshold(pin: Bool, positionText: String, sun: Bool) -> CGFloat {+ let singleLineHeight = height(width: 700, pin: pin, positionText: positionText, sun: sun)+ var lower: CGFloat = 120+ var upper: CGFloat = 700+ while upper - lower > 0.5 {+ let candidate = (lower + upper) / 2+ if height(width: candidate, pin: pin, positionText: positionText, sun: sun) > singleLineHeight + 2 {+ lower = candidate+ } else {+ upper = candidate+ }+ }+ return upper+ }++ private func height(width: CGFloat, pin: Bool, positionText: String, sun: Bool) -> CGFloat {+ let view = ActivityCardHeader(+ components: ["CodexBar", "GPT-5 • High • 10s"], projectName: "CodexBar",+ positionText: positionText, hasPin: pin, isPinned: pin, showsKeepAliveBadge: sun+ )+ .environment(\.contentAnimationsEnabled, false)+ .frame(width: width)+ .fixedSize(horizontal: false, vertical: true)+ return NSHostingView(rootView: view).fittingSize.height+ }+}diff --git a/Tests/App/Presentation/ActivityCardPresentationStateTests.swift b/Tests/App/Presentation/ActivityCardPresentationStateTests.swiftnew file mode 100644index 0000000..e747c6c--- /dev/null+++ b/Tests/App/Presentation/ActivityCardPresentationStateTests.swift@@ -0,0 +1,82 @@+import Foundation+import Testing++struct ActivityCardPresentationStateTests {+ @Test func presentationUsesCommittedReconnectSnapshotWithoutLosingOrder() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = ActivityMonitor(+ protectionSettings: ProtectionSettings(defaults: preferences.defaults),+ protectionStore: ProtectionStore(directoryURL: directory.url), activityDataDirectoryURL: directory.url+ )+ defer { monitor.stop() }+ monitor.isStarted = true+ monitor.protectionLoadState = .available+ monitor.isActivitySourceHealthy = true+ let date = Date()+ monitor.consume(.live([+ TestFixtures.event(at: date.addingTimeInterval(-2), thread: "a"),+ TestFixtures.event(at: date.addingTimeInterval(-1), thread: "b")+ ]))+ let presentation = ActivityCardPresentationState(activityMonitor: monitor)+ presentation.setVisible(true)+ defer { presentation.setVisible(false) }+ presentation.togglePin()+ let pinnedID = presentation.selection.pinnedID+ let order = presentation.selection.activities.compactMap(\.cardSelectionID)+ #expect(order.count == 2)+ presentation.swipe(1)+ presentation.setVisible(false)+ monitor.consume(.sourceUnavailable)+ #expect(presentation.selection.activities.isEmpty)+ #expect(presentation.selection.pinnedID == pinnedID)+ monitor.consume(.bootstrapStart)+ monitor.consume(.snapshotEvents([+ TestFixtures.event(at: date, thread: "a"),+ TestFixtures.event(at: date.addingTimeInterval(-1), thread: "b")+ ]))+ monitor.consume(.bootstrapEnd)+ presentation.setVisible(true)+ #expect(presentation.selection.activities.compactMap(\.cardSelectionID) == order)+ #expect(presentation.selection.selectedID == pinnedID)+ #expect(presentation.selection.returnDeadline == nil)+ }++ @Test func staleHostCannotFinishOrCommitANewHostsGesture() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = ActivityMonitor(+ protectionSettings: ProtectionSettings(defaults: preferences.defaults),+ protectionStore: ProtectionStore(directoryURL: directory.url), activityDataDirectoryURL: directory.url+ )+ defer { monitor.stop() }+ monitor.isActivitySourceHealthy = true+ monitor.protectionLoadState = .available+ monitor.consume(.live([+ TestFixtures.event(at: Date(), thread: "a"),+ TestFixtures.event(at: Date(), thread: "b")+ ]))+ let presentation = ActivityCardPresentationState(activityMonitor: monitor)+ presentation.setVisible(true)+ defer { presentation.setVisible(false) }+ presentation.togglePin()+ let pinnedID = presentation.selection.pinnedID+ let firstHost = UUID(), secondHost = UUID()+ presentation.setGestureActive(true, owner: firstHost)+ presentation.setVisible(false)+ presentation.setVisible(true)+ presentation.setGestureActive(true, owner: secondHost)+ let preview = try #require(presentation.selection.activities.first { $0.cardSelectionID != pinnedID }?.cardSelectionID)+ presentation.selectAfterSwipe(preview, owner: secondHost)+ presentation.setGestureActive(false, owner: firstHost)+ try presentation.selectAfterSwipe(#require(pinnedID), owner: firstHost)+ #expect(presentation.selection.selectedID == preview)+ #expect(presentation.selection.returnDeadline == nil)+ presentation.setGestureActive(false, owner: secondHost)+ #expect(presentation.selection.returnDeadline != nil)+ }+}diff --git a/Tests/App/Presentation/ActivityCardSelectionTests.swift b/Tests/App/Presentation/ActivityCardSelectionTests.swiftnew file mode 100644index 0000000..41404cb--- /dev/null+++ b/Tests/App/Presentation/ActivityCardSelectionTests.swift@@ -0,0 +1,350 @@+import Foundation+import Testing++struct ActivityCardSelectionTests {+ private let now = Date(timeIntervalSince1970: 1800000000)++ @Test func progressReordersAutomaticSelectionButNotCarousel() {+ let a = task("a"), b = task("b"), c = task("c")+ var state = selection(running: [a, b])+ #expect(state.positionText(for: state.selectedID) == "1/2")+ #expect(state.positionText(for: "b") == "2/2")+ #expect(state.positionText(for: nil) == nil)+ #expect(state.positionText(for: "missing") == nil)+ #expect(state.transitionDirection == nil)+ update(&state, running: [b, a, c])+ #expect(state.selectedID == "b")+ #expect(state.transitionDirection == nil)+ #expect(state.activities.compactMap(\.cardSelectionID) == ["a", "b", "c"])+ #expect(state.positionText(for: state.selectedID) == "2/3")+ #expect(state.positionText(for: "a") == "1/3")+ #expect(state.positionText(for: "c") == "3/3")+ state.swipe(1, now: now)+ #expect(state.selectedID == "c")+ #expect(state.transitionDirection == 1)+ state.swipe(1, now: now)+ #expect(state.selectedID == "a")+ state.swipe(-1, now: now)+ #expect(state.positionText(for: state.selectedID) == "3/3")+ #expect(state.transitionDirection == -1)+ }++ @Test func pinFollowsThreadThroughCompletionAndNewTurn() {+ let a = task("a"), b = task("b")+ var state = selection(running: [a, b])+ state.togglePin(now: now)+ let completion = completed(a, at: now)+ update(&state, running: [b], completions: [completion])+ #expect(state.current == .completed(completion))+ let next = task("a")+ update(&state, running: [b, next], completions: [completion])+ #expect(state.current == .running(next))+ #expect(state.pinnedID == "a")+ #expect(state.activities.count == 2)+ #expect(state.positionText(for: state.selectedID) == "1/2")+ }++ @Test(arguments: [false, true], [false, true])+ func manualViewingUsesTenOrFifteenSeconds(pinned: Bool, waiting: Bool) {+ let a = task("a"), b = task("b"), c = task("c")+ var state = selection(running: [a, b])+ if pinned {+ state.togglePin(now: now)+ }+ if waiting {+ update(&state, running: [a], waiting: [b])+ }+ if !pinned, waiting {+ state.swipe(-1, now: now)+ }+ state.swipe(1, now: now)+ #expect(state.selectedID == "b")+ let duration: TimeInterval = waiting ? 15 : 10+ #expect(state.returnDeadline == now.addingTimeInterval(duration))+ update(&state, running: [a, b].filter { !waiting || $0.id != b.id }, waiting: waiting ? [c, b] : [c])+ #expect(state.selectedID == "b")+ #expect(state.transitionDirection == 1)+ state.reconcile(at: now.addingTimeInterval(duration - 0.01))+ #expect(state.selectedID == "b")+ state.reconcile(at: now.addingTimeInterval(duration))+ #expect(state.selectedID == (pinned ? "a" : "c"))+ #expect(state.transitionDirection == nil)+ }++ @Test func pinReplacementAndUnpinKeepCurrentTaskVisible() {+ var state = selection(running: [task("a"), task("b")])+ state.togglePin(now: now)+ state.swipe(1, now: now)+ state.togglePin(now: now)+ #expect(state.pinnedID == "b")+ #expect(state.manualViewingDeadline == nil)+ state.togglePin(now: now)+ #expect(state.pinnedID == nil)+ #expect(state.selectedID == "b")+ state.reconcile(at: now.addingTimeInterval(10))+ #expect(state.selectedID == "a")+ }++ @Test func closedPanelAndDisconnectedSourceRetainPin() {+ let a = task("a"), b = task("b"), c = task("c")+ var state = selection(running: [a, b])+ state.togglePin(now: now)+ state.swipe(1, now: now)+ state.setGestureActive(true, now: now)+ update(&state, running: [a, b, c])+ #expect(state.positionText(for: "b") == "2/2")+ state.setVisible(false, now: now)+ #expect(!state.isGestureActive)+ #expect(state.positionText(for: "b") == "2/3")+ #expect(state.returnDeadline == nil)+ #expect(state.transitionDirection == nil)+ state.setVisible(true, now: now)+ #expect(state.selectedID == "a")+ state.setGestureActive(true, now: now)+ state.update(snapshot: .empty, isHealthy: false, now: now)+ #expect(!state.isGestureActive)+ #expect(state.carouselActivities.isEmpty)+ #expect(state.current == nil)+ #expect(state.pinnedID == "a")+ #expect(state.transitionDirection == nil)+ update(&state, running: [b, a])+ #expect(state.activities.compactMap(\.cardSelectionID) == ["a", "b"])+ #expect(state.current == .running(a))+ }++ @Test(arguments: [false, true])+ func expiredPinAllowsAutomaticPreemptionAndRecoversOnNewTurn(terminated: Bool) {+ let a = task("a"), b = task("b"), c = task("c")+ let completions = terminated ? [] : [completed(a, at: now)]+ let terminations = terminated ? [ActivityTermination(+ id: UUID(), taskID: a.id, projectName: a.projectName, modelName: nil, effort: nil,+ terminatedAt: now, duration: 1, threadID: a.threadID+ )] : []+ var state = selection(running: [a, b])+ state.togglePin(now: now)+ update(&state, running: [b], completions: completions, terminations: terminations, at: now.addingTimeInterval(599))+ #expect(state.current?.cardSelectionID == "a")+ #expect(state.activities.count == 2)+ update(&state, running: [b], completions: completions, terminations: terminations, at: now.addingTimeInterval(600))+ #expect(state.pinnedID == "a")+ #expect(state.selectedID == "b")+ #expect(state.current == .running(b))+ #expect(state.activities.count == 1)+ #expect(state.transitionDirection == nil)+ update(&state, running: [c, b], completions: completions, terminations: terminations, at: now.addingTimeInterval(601))+ #expect(state.selectedID == "c")+ let next = task("a")+ update(&state, running: [c, b, next], at: now.addingTimeInterval(602))+ #expect(state.current == .running(next))+ }++ @Test func newPinnedTurnDoesNotInterruptManualViewing() {+ let a = task("a"), b = task("b"), c = task("c")+ var state = selection(running: [a, b, c])+ state.togglePin(now: now)+ update(&state, running: [b, c])+ state.swipe(1, now: now)+ #expect(state.selectedID == "c")+ let next = task("a")+ update(&state, running: [next, b, c])+ #expect(state.selectedID == "c")+ state.reconcile(at: now.addingTimeInterval(10))+ #expect(state.current == .running(next))+ }++ @Test func waitingDirectionsRecalculateAfterEverySwipeIncludingTies() {+ let tasks = (0 ..< 5).map { task(String($0)) }+ var state = selection(running: tasks)+ state.selectAfterSwipe("0", now: now)+ update(&state, running: [tasks[0], tasks[2], tasks[3]], waiting: [tasks[1], tasks[4]])+ #expect(state.waitingSides == .init(left: true, right: true))+ state.swipe(1, now: now)+ #expect(state.waitingSides == .init(left: true, right: false))+ state.swipe(1, now: now)+ #expect(state.waitingSides == .init(left: true, right: true))+ var tied = selection(running: [tasks[0], tasks[1]])+ tied.togglePin(now: now)+ update(&tied, running: [tasks[0]], waiting: [tasks[1]])+ #expect(tied.waitingSides == .init(left: true, right: true))+ tied.togglePin(now: now)+ #expect(tied.waitingSides == .init(left: true, right: true))+ tied.swipe(1, now: now)+ #expect(tied.waitingSides == .init())+ }++ @Test func gesturesPauseCountdownAndNewSwipesRestartIt() {+ var state = selection(running: [task("a"), task("b"), task("c")])+ state.togglePin(now: now)+ state.setGestureActive(true, now: now)+ state.swipe(1, now: now.addingTimeInterval(1))+ #expect(state.returnDeadline == nil)+ state.reconcile(at: now.addingTimeInterval(20))+ #expect(state.selectedID == "b")+ state.setGestureActive(false, now: now.addingTimeInterval(20))+ #expect(state.returnDeadline == now.addingTimeInterval(30))+ state.swipe(1, now: now.addingTimeInterval(25))+ #expect(state.returnDeadline == now.addingTimeInterval(35))+ state.reconcile(at: now.addingTimeInterval(34))+ #expect(state.selectedID == "c")+ state.reconcile(at: now.addingTimeInterval(35))+ #expect(state.selectedID == "a")+ #expect(state.transitionDirection == nil)+ }++ @Test func disappearingManualTaskFallsBackAndSingleTaskDoesNotStartTimer() {+ let a = task("a"), b = task("b")+ var state = selection(running: [a, b])+ state.togglePin(now: now)+ state.swipe(1, now: now)+ update(&state, running: [a])+ #expect(state.selectedID == "a")+ #expect(state.transitionDirection == nil)+ #expect(state.positionText(for: state.selectedID) == nil)+ #expect(state.returnDeadline == nil)+ state.swipe(1, now: now)+ #expect(state.returnDeadline == nil)+ update(&state, running: [])+ #expect(state.positionText(for: state.selectedID) == nil)+ #expect(state.pinnedID == "a")+ }++ @Test func terminalHistoryKeepsLatestPerThreadAndIncludesFailures() {+ let a = task("a"), b = task("b")+ let old = completed(a, at: now.addingTimeInterval(-10))+ let latest = completed(a, at: now)+ let stopped = ActivityTermination(+ id: UUID(), taskID: b.id, projectName: "same-project", modelName: nil, effort: nil,+ terminatedAt: now, duration: 5, isFailure: true, threadID: "b"+ )+ var state = ActivityCardSelection()+ state.update(snapshot: .init(waitingTasks: [], runningTasks: [], recentCompletions: [latest, old], recentTerminations: [stopped]), isHealthy: true, now: now)+ #expect(state.activities.count == 2)+ #expect(state.activities.contains(.completed(latest)))+ #expect(!state.activities.contains(.completed(old)))+ #expect(state.current == .terminated(stopped))+ }++ @Test func nonblockingQuestionUsesWaitingDirectionAndLongerViewingTime() {+ let a = task("a")+ var b = task("b")+ var state = selection(running: [a, b])+ state.togglePin(now: now)+ b.presentation = ActivityLiveSummary(+ current: ActivityLiveLabel("processing"),+ waiting: ActivityLiveWait(label: ActivityLiveLabel("waiting-input"), since: now, isBlocking: false)+ )+ update(&state, running: [a, b])+ #expect(state.waitingSides == .init(left: true, right: true))+ state.swipe(1, now: now)+ #expect(state.current == .waiting(b))+ #expect(state.returnDeadline == now.addingTimeInterval(15))+ }++ @Test func firstGestureProtectsSelectionBeforeAnyPageWasCommitted() {+ let a = task("a"), b = task("b"), c = task("c")+ var state = selection(running: [a, b])+ state.setGestureActive(true, now: now)+ update(&state, running: [a, b], waiting: [c], at: now.addingTimeInterval(1))+ #expect(state.selectedID == "a")+ #expect(state.manualViewingDeadline == nil)+ state.reconcile(at: now.addingTimeInterval(20))+ #expect(state.selectedID == "a")+ state.setGestureActive(false, now: now.addingTimeInterval(21))+ #expect(state.selectedID == "c")+ }++ @Test func chainedGesturesKeepOrderPositionsAndWaitingEdgesUntilSettlement() {+ let a = task("a"), b = task("b"), c = task("c"), d = task("d"), e = task("e")+ var state = selection(running: [a, b, c])+ state.togglePin(now: now)+ update(&state, running: [a, b], waiting: [c])+ state.setGestureActive(true, now: now)+ update(&state, running: [a, b, d], waiting: [c])+ update(&state, running: [a, b, d, e], waiting: [c])+ #expect(state.activities.count == 5)+ #expect(state.positionText(for: "a") == "1/3")+ #expect(state.positionText(for: "d") == nil)+ #expect(state.waitingSides == .init(left: true, right: false))+ state.swipe(-1, now: now.addingTimeInterval(1))+ #expect(state.selectedID == "c")+ #expect(state.positionText(for: "c") == "3/3")+ state.setGestureActive(true, now: now.addingTimeInterval(2))+ state.swipe(1, now: now.addingTimeInterval(3))+ #expect(state.selectedID == "a")+ #expect(state.positionText(for: "a") == "1/3")+ #expect(state.waitingSides == .init(left: true, right: false))+ state.setGestureActive(false, now: now.addingTimeInterval(4))+ #expect(state.selectedID == "a")+ #expect(state.positionText(for: "a") == "1/5")+ #expect(state.waitingSides == .init(left: false, right: true))+ #expect(state.returnDeadline == now.addingTimeInterval(14))+ }++ @Test(arguments: [false, true])+ func committedPreviewStartsViewingTimeAfterSettlement(waiting: Bool) {+ let a = task("a"), b = task("b"), c = task("c")+ var state = selection(running: [a, b])+ state.setGestureActive(true, now: now)+ update(&state, running: waiting ? [a] : [a, b], waiting: waiting ? [c, b] : [c])+ state.selectAfterSwipe("b", now: now.addingTimeInterval(2))+ #expect(state.selectedID == "b")+ #expect(state.current == .running(b))+ #expect(state.positionText(for: "b") == "2/2")+ #expect(state.returnDeadline == nil)+ #expect(state.transitionDirection == nil)+ state.setGestureActive(false, now: now.addingTimeInterval(3))+ #expect(state.current == (waiting ? .waiting(b) : .running(b)))+ let deadline = now.addingTimeInterval(waiting ? 18 : 13)+ #expect(state.returnDeadline == deadline)+ state.reconcile(at: deadline)+ #expect(state.selectedID == "c")+ }++ @Test func disappearingPreviewCannotBeCommitted() {+ let a = task("a"), b = task("b"), c = task("c")+ var state = selection(running: [a, b])+ state.setGestureActive(true, now: now)+ update(&state, running: [a, c])+ #expect(!state.isGestureActive)+ #expect(state.carouselActivities.compactMap(\.cardSelectionID) == ["a", "c"])+ state.selectAfterSwipe("b", now: now)+ #expect(state.selectedID == "a")+ #expect(state.manualViewingDeadline == nil)+ state.setGestureActive(false, now: now)+ }++ private func task(_ thread: String) -> ActivityTaskSnapshot {+ ActivityTaskSnapshot(+ id: UUID(), projectName: "same-project", modelName: "gpt-5", effort: "high",+ startedAt: now, stateChangedAt: now, activeSubagentCount: 0, threadID: thread+ )+ }++ private func completed(_ task: ActivityTaskSnapshot, at date: Date) -> ActivityCompletion {+ ActivityCompletion(+ id: UUID(), taskID: task.id, projectName: task.projectName, modelName: nil, effort: nil,+ completedAt: date, duration: 1, threadID: task.threadID+ )+ }++ private func selection(running: [ActivityTaskSnapshot]) -> ActivityCardSelection {+ var state = ActivityCardSelection()+ update(&state, running: running)+ state.setVisible(true, now: now)+ return state+ }++ private func update(+ _ state: inout ActivityCardSelection,+ running: [ActivityTaskSnapshot],+ waiting: [ActivityTaskSnapshot] = [],+ completions: [ActivityCompletion] = [],+ terminations: [ActivityTermination] = [],+ at date: Date? = nil+ ) {+ state.update(+ snapshot: .init(waitingTasks: waiting, runningTasks: running, recentCompletions: completions, recentTerminations: terminations),+ isHealthy: true, now: date ?? now+ )+ }+}diff --git a/Tests/App/Presentation/ActivityCardSwipeTests.swift b/Tests/App/Presentation/ActivityCardSwipeTests.swiftnew file mode 100644index 0000000..0c741ac--- /dev/null+++ b/Tests/App/Presentation/ActivityCardSwipeTests.swift@@ -0,0 +1,106 @@+import AppKit+import SwiftUI+import Testing++@MainActor+struct ActivityCardSwipeTests {+ private let now = Date(timeIntervalSince1970: 1800000000)++ @Test func draggingFollowsSmallDeltasAndCanReverseBeforeCommitting() {+ var swipe = ActivityCardSwipe()+ _ = swipe.begin(width: 400, now: now)+ swipe.move(by: -3, width: 400)+ #expect(swipe.offset(at: now) == -3)+ swipe.move(by: -150, width: 400)+ swipe.move(by: 130, width: 400)+ #expect(swipe.offset(at: now) == -23)+ #expect(swipe.settlement == nil)+ swipe.end(velocity: 0, width: 400, cancelled: false, now: now)+ #expect(swipe.settlement?.step == 0)+ #expect(swipe.offset(at: now.addingTimeInterval(1)) == 0)+ }++ @Test(arguments: [-1, 1])+ func releaseUsesDistanceAndVelocityButCancellationAlwaysReturns(direction: Int) {+ let delta = CGFloat(direction)+ var swipe = ActivityCardSwipe()+ _ = swipe.begin(width: 400, now: now)+ swipe.move(by: delta * 120, width: 400)+ swipe.end(velocity: 0, width: 400, cancelled: false, now: now)+ #expect(swipe.settlement?.step == -direction)+ #expect(swipe.offset(at: now.addingTimeInterval(1)) == delta * 400)+ swipe = ActivityCardSwipe()+ _ = swipe.begin(width: 400, now: now)+ swipe.move(by: delta * 20, width: 400)+ swipe.end(velocity: delta * 900, width: 400, cancelled: false, now: now)+ #expect(swipe.settlement?.step == -direction)+ _ = swipe.begin(width: 400, now: now.addingTimeInterval(1))+ swipe.move(by: delta * 300, width: 400)+ swipe.end(velocity: delta * 1200, width: 400, cancelled: true, now: now)+ #expect(swipe.settlement?.step == 0)+ }++ @Test func reversingVelocityCanCancelButCannotChooseAnUnseenOppositePage() {+ var swipe = ActivityCardSwipe()+ _ = swipe.begin(width: 400, now: now)+ swipe.move(by: -140, width: 400)+ swipe.end(velocity: 1800, width: 400, cancelled: false, now: now)+ #expect(swipe.settlement?.step == 0)+ }++ @Test func newGestureRebasesUnfinishedPageWithoutChangingItsVisiblePosition() {+ var swipe = ActivityCardSwipe()+ _ = swipe.begin(width: 400, now: now)+ swipe.move(by: -120, width: 400)+ swipe.end(velocity: 0, width: 400, cancelled: false, now: now)+ let interruptedAt = now.addingTimeInterval(0.06)+ let nextPageBefore = swipe.offset(at: interruptedAt) + 400+ #expect(swipe.begin(width: 400, now: interruptedAt) == 1)+ #expect(abs(swipe.offset(at: interruptedAt) - nextPageBefore) < 0.001)+ swipe.move(by: -10, width: 400)+ #expect(abs(swipe.offset(at: interruptedAt) - (nextPageBefore - 10)) < 0.001)+ #expect(swipe.settlement == nil)+ }++ @Test func offscreenHeightTracksBothDirectionsAndReturnsWithThePages() {+ var swipe = ActivityCardSwipe()+ #expect(renderedHeight(swipe) == 100)+ _ = swipe.begin(width: 400, now: now)+ // 使用整点高度, 避免离屏宿主的 backing scale 影响断言+ swipe.move(by: -40, width: 400)+ #expect(renderedHeight(swipe) == 108)+ swipe.move(by: 20, width: 400)+ #expect(renderedHeight(swipe) == 104)+ swipe.move(by: 220, width: 400)+ #expect(abs(renderedHeight(swipe) - 80) < 0.5)+ swipe.end(velocity: 0, width: 400, cancelled: true, now: now)+ var returned = ActivityCardSwipe()+ _ = returned.begin(width: 400, now: now)+ returned.move(by: swipe.offset(at: now.addingTimeInterval(1)), width: 400)+ #expect(abs(renderedHeight(returned) - 100) < 0.5)+ returned.move(by: -160, width: 320)+ #expect(abs(renderedHeight(returned, width: 320) - 140) < 0.5)+ }++ @Test(arguments: [-1, 1])+ func offscreenRebasingPreservesInterpolatedHeight(direction: Int) {+ var swipe = ActivityCardSwipe()+ _ = swipe.begin(width: 400, now: now)+ swipe.move(by: CGFloat(direction) * 200, width: 400)+ let height = renderedHeight(swipe)+ swipe.end(velocity: 0, width: 400, cancelled: false, now: now)+ let step = swipe.begin(width: 400, now: now)+ let heights: [CGFloat] = step == 1 ? [100, 180, 60] : [180, 60, 100]+ #expect(abs(renderedHeight(swipe, pageHeights: heights) - height) < 0.5)+ swipe.move(by: CGFloat(direction) * 200, width: 400)+ #expect(abs(renderedHeight(swipe, pageHeights: heights) - heights[1]) < 0.5)+ }++ private func renderedHeight(_ swipe: ActivityCardSwipe, pageHeights: [CGFloat] = [60, 100, 180], width: CGFloat = 400) -> CGFloat {+ let root = ActivityCardSwipePages(swipe: swipe, width: 400) { step in+ Color.clear.frame(height: pageHeights[step + 1])+ }+ .frame(width: width)+ return NSHostingView(rootView: root).fittingSize.height+ }+}diff --git a/Tests/App/Presentation/ActivityPanelControllerTests.swift b/Tests/App/Presentation/ActivityPanelControllerTests.swiftnew file mode 100644index 0000000..7c6af51--- /dev/null+++ b/Tests/App/Presentation/ActivityPanelControllerTests.swift@@ -0,0 +1,44 @@+import AppKit+import Testing++@MainActor+struct ActivityPanelControllerTests {+ @Test func anchorIgnoresTransientViewFramesAndRejectsOtherHosts() throws {+ let window = makeWindow()+ defer { window.close() }+ let anchor = makeAnchor(in: window)+ let top = try #require(anchor.screenFrame(in: window)).maxY+ let view = try #require(window.contentView?.subviews.first)++ for offset in [-8.0, 4.0, -2.0, 0.0] {+ view.setFrameOrigin(NSPoint(x: 0, y: offset))+ #expect(anchor.screenFrame(in: window)?.maxY == top)+ }+ anchor.updateTopOffset(150)+ #expect(anchor.screenFrame(in: window)?.maxY == top - 30)+ let other = makeWindow()+ defer { other.close() }+ #expect(anchor.screenFrame(in: other) == nil)+ anchor.updateTopOffset(.nan)+ #expect(anchor.screenFrame(in: window) == nil)+ }++ private func makeWindow() -> NSWindow {+ let window = NSWindow(+ contentRect: NSRect(x: 100, y: 100, width: 467, height: 600),+ styleMask: [.borderless], backing: .buffered, defer: false+ )+ window.isReleasedWhenClosed = false+ #expect(!window.isVisible)+ return window+ }++ private func makeAnchor(in window: NSWindow) -> ActivityCenterPanelAnchor {+ let view = NSView(frame: NSRect(x: 0, y: 0, width: 467, height: 100))+ window.contentView?.addSubview(view)+ let anchor = ActivityCenterPanelAnchor()+ anchor.bind(to: view)+ anchor.updateTopOffset(120)+ return anchor+ }+}diff --git a/Tests/App/Presentation/ActivityPresentationTests.swift b/Tests/App/Presentation/ActivityPresentationTests.swiftindex 2c2a669..ec90c89 100644--- a/Tests/App/Presentation/ActivityPresentationTests.swift+++ b/Tests/App/Presentation/ActivityPresentationTests.swift@@ -104,7 +104,7 @@ struct ActivityPresentationTests {id: UUID(),projectName: hasProject ? "CodexBar" : nil, modelName: nil, effort: nil,startedAt: TestFixtures.now, stateChangedAt: TestFixtures.now,- activeSubagentCount: nil, approvalActionText: approval.actionText+ activeSubagentCount: nil, approvalActionText: approval.actionText, threadID: "waiting-thread")let expected = String(localized: operation.action)let notice = NotificationContent.taskWaiting(project: task.projectName, actionText: task.approvalActionText)@@ -170,7 +170,10 @@ struct ActivityPresentationTests {}@Test func statusItemTerminalExpiresAtTenSecondsWhileCardKeepsHistory() {- let completion = ActivityCompletion(id: UUID(), projectName: nil, modelName: nil, effort: nil, completedAt: TestFixtures.now, duration: 30)+ let completion = ActivityCompletion(+ id: UUID(), projectName: nil, modelName: nil, effort: nil,+ completedAt: TestFixtures.now, duration: 30, threadID: "completed-thread"+ )let snapshot = ActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])#expect(snapshot.statusItemActivity(at: TestFixtures.now.addingTimeInterval(9.999)) == .completed(completion))#expect(snapshot.statusItemActivity(at: TestFixtures.now.addingTimeInterval(10)) == .idle)@@ -180,8 +183,8 @@ struct ActivityPresentationTests {}@Test func waitingTaskTakesPriorityOverRunningTask() {- let waiting = task()- let running = task()+ let waiting = task(thread: "waiting-thread")+ let running = task(thread: "running-thread")let snapshot = ActivitySnapshot(waitingTasks: [waiting], runningTasks: [running], recentCompletions: [], recentTerminations: [])#expect(snapshot.primaryActivity == .waiting(waiting))#expect(snapshot.activeCount == 2)@@ -190,7 +193,7 @@ struct ActivityPresentationTests {@Test(arguments: [false, true])func accountFailureKeepsLiveTaskIcon(waiting: Bool) {- let task = task()+ let task = task(thread: "thread-a")let activity = ActivitySnapshot(waitingTasks: waiting ? [task] : [], runningTasks: waiting ? [] : [task],recentCompletions: [], recentTerminations: []@@ -201,12 +204,12 @@ struct ActivityPresentationTests {#expect(idle.symbolName(at: TestFixtures.now) == "person.slash.fill")}- private func task() -> ActivityTaskSnapshot {+ private func task(thread: String) -> ActivityTaskSnapshot {ActivityTaskSnapshot(id: UUID(),projectName: nil, modelName: nil, effort: nil,startedAt: TestFixtures.now, stateChangedAt: TestFixtures.now,- activeSubagentCount: nil+ activeSubagentCount: nil, threadID: thread)}}diff --git a/Tests/App/Presentation/LogPreviewTests.swift b/Tests/App/Presentation/LogPreviewTests.swiftindex 12635fc..447c8bb 100644--- a/Tests/App/Presentation/LogPreviewTests.swift+++ b/Tests/App/Presentation/LogPreviewTests.swift@@ -1,6 +1,7 @@import AppKitimport Testing+@Suite(.tags(.integration))struct LogPreviewTests {@Test func jsonFormattingAndHighlightingPreserveUnicodeAndOriginalText() async throws {let raw = #"{"z":null,"🙂":"é 汉字","a":true,"n":-1.25,"url":"https://example.com"}"#diff --git a/Tests/App/Presentation/SettingsHelpPresenterTests.swift b/Tests/App/Presentation/SettingsHelpPresenterTests.swiftindex 8c2d987..25395a5 100644--- a/Tests/App/Presentation/SettingsHelpPresenterTests.swift+++ b/Tests/App/Presentation/SettingsHelpPresenterTests.swift@@ -3,82 +3,13 @@ import Testing@MainActorstruct SettingsHelpPresenterTests {- @Test func showsAndHidesSynchronouslyWithoutTakingFocus() throws {- let window = makeWindow()- defer { window.close() }- let anchor = makeAnchor(in: window)- let presenter = SettingsHelpPresenter()- defer { presenter.hide() }- let previousKeyWindow = NSApplication.shared.keyWindow-- presenter.show("settings.sync.title.help", anchorProvider: anchor)-- let panel = try #require(window.childWindows?.first as? NSPanel)- #expect(panel.isVisible)- #expect(!panel.canBecomeKey)- #expect(!panel.canBecomeMain)- #expect(panel.ignoresMouseEvents)- #expect(NSApplication.shared.keyWindow === previousKeyWindow)-- presenter.hide()-- #expect(!panel.isVisible)- #expect(panel.parent == nil)- #expect(window.childWindows?.isEmpty != false)- }-- @Test func repeatedHoverReplacesThePreviousPanel() throws {- let window = makeWindow()- defer { window.close() }- let anchor = makeAnchor(in: window)- let presenter = SettingsHelpPresenter()- defer { presenter.hide() }-- presenter.show("settings.sync.title.help", anchorProvider: anchor)- let previousPanel = try #require(window.childWindows?.first)- presenter.show("settings.keep-alive.title.help", anchorProvider: anchor)-- #expect(!previousPanel.isVisible)- #expect(previousPanel.parent == nil)- #expect(window.childWindows?.count == 1)- #expect(window.childWindows?.first?.isVisible == true)- }-- @Test(arguments: [- NSWindow.willCloseNotification,- NSWindow.willMiniaturizeNotification,- NSWindow.didResignKeyNotification,- NSWindow.willMoveNotification,- NSWindow.didResizeNotification,- NSApplication.didResignActiveNotification- ])- func dismissesWithTheSettingsWindow(_ notification: Notification.Name) throws {- let window = makeWindow()- defer { window.close() }- let options = makeWindow()- defer {- window.removeChildWindow(options)- options.close()- }- window.addChildWindow(options, ordered: .above)- let presenter = SettingsHelpPresenter()- defer { presenter.hide() }- presenter.show("settings.sync.title.help", anchorProvider: makeAnchor(in: options))- let panel = try #require(options.childWindows?.first)-- NotificationCenter.default.post(name: notification, object: window)-- #expect(!panel.isVisible)- #expect(panel.parent == nil)- }-@Test func doesNotShowForHiddenOrDetachedAnchors() {let window = makeWindow()defer { window.close() }let anchor = makeAnchor(in: window)let presenter = SettingsHelpPresenter()defer { presenter.hide() }- window.orderOut(nil)+ #expect(!window.isVisible)presenter.show("settings.sync.title.help", anchorProvider: anchor)#expect(window.childWindows?.isEmpty != false)@@ -87,50 +18,14 @@ struct SettingsHelpPresenterTests {#expect(window.childWindows?.isEmpty != false)}- @Test func keepsInitialLayoutReportAndDismissesWhenAnchorMoves() throws {- let window = makeWindow()- defer { window.close() }- let anchor = makeAnchor(in: window)- let presenter = SettingsHelpPresenter()- defer { presenter.hide() }- presenter.show("settings.sync.title.help", anchorProvider: anchor)- let panel = try #require(window.childWindows?.first)- let frame = try #require(anchor.currentScreenFrame(in: window))-- presenter.updateAnchorFrame(frame)- #expect(panel.isVisible)-- presenter.updateAnchorFrame(frame.offsetBy(dx: 0, dy: 20))- #expect(!panel.isVisible)- #expect(panel.parent == nil)- }-- @Test func hidingTheOwnerRemovesTheTooltipBeforeReopening() throws {- let window = makeWindow()- defer { window.close() }- let presenter = SettingsHelpPresenter()- defer { presenter.hide() }- presenter.show("settings.sync.title.help", anchorProvider: makeAnchor(in: window))- let panel = try #require(window.childWindows?.first)-- window.orderOut(nil)- NotificationCenter.default.post(name: NSWindow.didChangeOcclusionStateNotification, object: window)- window.orderFront(nil)-- #expect(!panel.isVisible)- #expect(panel.parent == nil)- #expect(window.childWindows?.isEmpty != false)- }-private func makeWindow() -> NSWindow {let window = NSWindow(- contentRect: NSRect(x: -10000, y: -10000, width: 470, height: 300),+ contentRect: NSRect(x: 100, y: 100, width: 470, height: 300),styleMask: [.borderless],backing: .buffered,defer: false)window.isReleasedWhenClosed = false- window.orderFront(nil)return window}diff --git a/Tests/App/Presentation/TaskGlowPreviewTests.swift b/Tests/App/Presentation/TaskGlowPreviewTests.swiftindex e19e0e8..f014ebe 100644--- a/Tests/App/Presentation/TaskGlowPreviewTests.swift+++ b/Tests/App/Presentation/TaskGlowPreviewTests.swift@@ -85,7 +85,7 @@ struct TaskGlowPreviewTests {state.suspend(now: time(10.1))let termination = ActivityTermination(id: UUID(), projectName: nil, modelName: nil,- effort: nil, terminatedAt: time(10.2), duration: 60+ effort: nil, terminatedAt: time(10.2), duration: 60, threadID: "terminated-thread")let snapshot = ActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: completed(at: 0).recentCompletions,@@ -222,7 +222,7 @@ struct TaskGlowPreviewTests {private func completed(at seconds: TimeInterval) -> ActivitySnapshot {let completion = ActivityCompletion(id: UUID(), projectName: nil, modelName: nil,- effort: nil, completedAt: time(seconds), duration: 60+ effort: nil, completedAt: time(seconds), duration: 60, threadID: "completed-thread")return ActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])}@@ -231,7 +231,7 @@ struct TaskGlowPreviewTests {let task = ActivityTaskSnapshot(id: UUID(), projectName: nil,modelName: nil, effort: nil, startedAt: now,- stateChangedAt: now, activeSubagentCount: nil+ stateChangedAt: now, activeSubagentCount: nil, threadID: "active-thread")return ActivitySnapshot(waitingTasks: waiting ? [task] : [], runningTasks: waiting ? [] : [task], recentCompletions: [], recentTerminations: []diff --git a/Tests/App/Presentation/TaskGlowTests.swift b/Tests/App/Presentation/TaskGlowTests.swiftindex 4f2299e..f20d9df 100644--- a/Tests/App/Presentation/TaskGlowTests.swift+++ b/Tests/App/Presentation/TaskGlowTests.swift@@ -199,7 +199,7 @@ struct TaskGlowTests {@Test func liveInputWaitMatchesPanelAndReturnsToRunningAfterResponse() {var task = ActivityTaskSnapshot(id: UUID(), projectName: nil, modelName: nil, effort: nil, startedAt: TestFixtures.now,- stateChangedAt: TestFixtures.now, activeSubagentCount: nil+ stateChangedAt: TestFixtures.now, activeSubagentCount: nil, threadID: "input-thread")var presentation = TaskGlowPresentationState()for waiting in [false, true, false] {@@ -223,7 +223,7 @@ struct TaskGlowTests {var running = ActivityTaskSnapshot(id: UUID(), projectName: nil,modelName: nil, effort: nil, startedAt: TestFixtures.now,- stateChangedAt: TestFixtures.now, activeSubagentCount: nil+ stateChangedAt: TestFixtures.now, activeSubagentCount: nil, threadID: "running-thread")if waiting {running.presentation = ActivityLiveSummary(@@ -250,7 +250,7 @@ struct TaskGlowTests {private func completedSnapshot() -> ActivitySnapshot {let completion = ActivityCompletion(id: UUID(), projectName: nil, modelName: nil,- effort: nil, completedAt: TestFixtures.now, duration: 60+ effort: nil, completedAt: TestFixtures.now, duration: 60, threadID: "completed-thread")return ActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])}diff --git a/Tests/App/Support/BoundedProcessTests.swift b/Tests/App/Support/BoundedProcessTests.swiftindex 27ce29c..866d397 100644--- a/Tests/App/Support/BoundedProcessTests.swift+++ b/Tests/App/Support/BoundedProcessTests.swift@@ -2,6 +2,7 @@ import Darwinimport Foundationimport Testing+@Suite(.tags(.integration))struct BoundedProcessTests {@Test nonisolated func preservesArgumentsEnvironmentAndMergedOutput() {let result = BoundedProcess.run(diff --git a/Tests/App/Support/JSONFileStorageTests.swift b/Tests/App/Support/JSONFileStorageTests.swiftindex 6124f4a..514eae1 100644--- a/Tests/App/Support/JSONFileStorageTests.swift+++ b/Tests/App/Support/JSONFileStorageTests.swift@@ -2,6 +2,7 @@ import Darwinimport Foundationimport Testing+@Suite(.tags(.integration))struct JSONFileStorageTests {@Test nonisolated func nonblockingLockRejectsAnotherOwnerAndCanBeReacquired() throws {let directory = try TestDirectory()diff --git a/Tests/App/Support/TestSupport.swift b/Tests/App/Support/TestSupport.swiftindex 97d8685..c049c30 100644--- a/Tests/App/Support/TestSupport.swift+++ b/Tests/App/Support/TestSupport.swift@@ -2,6 +2,10 @@ import Darwinimport Foundationimport Testing+extension Tag {+ @Tag static var integration: Self+}+nonisolated enum TestFixtures {static let now = Date(timeIntervalSince1970: 1789459200)diff --git a/Tests/App/Sync/ActivityDataSyncStoreTests.swift b/Tests/App/Sync/ActivityDataSyncStoreTests.swiftindex 71b9c29..2ba25ae 100644--- a/Tests/App/Sync/ActivityDataSyncStoreTests.swift+++ b/Tests/App/Sync/ActivityDataSyncStoreTests.swift@@ -1,6 +1,7 @@import Foundationimport Testing+@Suite(.tags(.integration))struct ActivityDataSyncStoreTests {@Test func activityDataCacheCommitsRecordsAndCursorTogether() throws {let directory = try TestDirectory()diff --git a/Tests/App/Sync/SyncRecoveryTests.swift b/Tests/App/Sync/SyncRecoveryTests.swiftindex 680a89d..164982b 100644--- a/Tests/App/Sync/SyncRecoveryTests.swift+++ b/Tests/App/Sync/SyncRecoveryTests.swift@@ -2,6 +2,7 @@ import CloudKitimport Foundationimport Testing+@Suite(.tags(.integration))struct SyncRecoveryTests {@Test func expiredTokenUsageCacheStaysBoundedWhenCloudDeletionFailsAndRetries() async throws {let directory = try TestDirectory()diff --git a/Tests/App/Sync/ZoneRecoveryTests.swift b/Tests/App/Sync/ZoneRecoveryTests.swiftindex 4e9f28d..4ba130d 100644--- a/Tests/App/Sync/ZoneRecoveryTests.swift+++ b/Tests/App/Sync/ZoneRecoveryTests.swift@@ -3,6 +3,7 @@ import Foundationimport Synchronizationimport Testing+@Suite(.tags(.integration))struct ZoneRecoveryTests {private static let zone = CKRecordZone.ID(zoneName: SyncCloudKit.zoneName, ownerName: CKCurrentUserDefaultName)diff --git a/appcast.xml b/appcast.xmlindex 237d78b..42ad0c5 100644--- a/appcast.xml+++ b/appcast.xml@@ -5,6 +5,20 @@<link>https://codexbar.zabrian.app/appcast.xml</link><description>CodexBar appcast feed</description><language>zh-CN</language>+ <item>+ <title>CodexBar 5.2.0</title>+ <sparkle:version>257</sparkle:version>+ <sparkle:shortVersionString>5.2.0</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:minimumAutoupdateVersion>200</sparkle:minimumAutoupdateVersion>+ <sparkle:informationalUpdate><sparkle:belowVersion>200</sparkle:belowVersion></sparkle:informationalUpdate>+ <link xml:lang="en-US">https://codexbar.zabrian.app/notes?lang=en-US#5.0.0-Guide</link>+ <link xml:lang="zh-CN">https://codexbar.zabrian.app/notes?lang=zh-CN#5.0.0-Guide</link>+ <sparkle:releaseNotesLink xml:lang="en-US">https://codexbar.zabrian.app/notes?lang=en-US#5.2.0</sparkle:releaseNotesLink>+ <sparkle:releaseNotesLink xml:lang="zh-CN">https://codexbar.zabrian.app/notes?lang=zh-CN#5.2.0</sparkle:releaseNotesLink>+ <pubDate>Sat, 31 Oct 2026 14:02:48 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v5.2.0.dmg" sparkle:edSignature="qYxuVmPPLOcQBN2lBGwhQhXyuwZFeFmohpRvytLWqZ+c6tPUMc1GdnP3tj+s9Vw6emoTTdpUWnwrqBbEJ98dBw==" length="11239424" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 5.1.1</title><sparkle:version>210</sparkle:version>