CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
refactor: 完善活动数据恢复并分离后台服务授权
Bob49bb0a304775
diff --git a/.swiftlint.yml b/.swiftlint.ymlindex 36a2b09..b462320 100644--- a/.swiftlint.yml+++ b/.swiftlint.yml@@ -2,6 +2,8 @@ included:- CodexBar- CodexBarTests- CodexBarHelperTests+ - CodexBarHelperManager+ - Sharedline_length:warning: 180diff --git a/AGENTS.md b/AGENTS.mdindex 258fa59..984c25f 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -54,9 +54,9 @@## 项目结构与模块组织-CodexBar 是面向 macOS 的 `LSUIElement` 菜单栏应用,使用 Swift 6, SwiftUI, AppKit 和 MVVM。工程只有 `CodexBar` scheme,包含主 App、`CodexBarHelper`、`CodexBarTests` 和 `CodexBarHelperTests` 四个 target。+CodexBar 是面向 macOS 的 `LSUIElement` 菜单栏应用,使用 Swift 6, SwiftUI, AppKit 和 MVVM。工程只有 `CodexBar` scheme,包含主 App、`CodexBarHelperManager`、`CodexBarHelper`、`CodexBarTests` 和 `CodexBarHelperTests` 五个 target。-`CodexBar/` 按 `App/` `Views/` `Controllers/` `Models/` `Services/` 和 `Resources/` 分层。root LaunchDaemon 位于 `CodexBarHelper/` 目录,跨 target XPC 接口位于 `Shared/` 目录。`Scripts/` 提供发布和 helper 清理工具,`Images/` 存放 README 资源。+`CodexBar/` 按 `App/` `Views/` `Controllers/` `Models/` `Services/` 和 `Resources/` 分层。`CodexBarHelperManager/` 提供嵌入主 App 的 Helper 管理 App,拥有 root LaunchDaemon 的注册与授权归属。root LaunchDaemon 位于 `CodexBarHelper/` 目录,主 App 直接与其通信;跨 target 协议位于 `Shared/` 目录。`Scripts/` 提供发布和 helper 清理工具,`Images/` 存放 README 资源。## 构建、测试与开发命令@@ -129,14 +129,14 @@ CodexBar 是面向 macOS 的 `LSUIElement` 菜单栏应用,使用 Swift 6, Swi- 自动重置只处理新鲜响应中明确可用且具备用量和有效期信息的凭证,重试必须有界- helper 只接受有限时间戳,维护单一的系统唤醒计划;目标变化、功能关闭、App 退出、对应连接断开或 helper 启动时必须收敛并清理计划- 修改唤醒事件的归属或类型时,必须考虑旧版本遗留事件的清理兼容性-- 异常会话保护跟随防睡眠开关,只判定非匿名运行中任务,等待批准任务不参与判定+- 异常会话保护跟随防睡眠开关,只判定运行中任务,等待批准任务不参与判定- 活动连接初始化、系统睡眠、唤醒恢复或数据源不可用期间暂停异常会话判定,数据恢复后执行无通知核对- 主动排空活动读取是屏障,每个调用方必须等待一轮在本次请求之后开始的读取;唤醒后只有该轮读取成功,才能执行生命周期核对并恢复保护判定- reader 更换时丢弃旧结果,数据源不可用或任务取消时不得使用旧快照继续判定### 数据语义与兼容性-- 缺少会话标识的任务按匿名任务处理,保留在实时快照和 UI 中,不发布任务通知或触觉反馈,不参与防睡眠和异常会话保护,不生成持久化保护标识+- 实时任务必须具备会话标识和轮次标识,身份不完整的事件不创建任务;子任务归属未确认时等待关联,开始时间缺失时保留未知耗时- 异常会话保护记录只保存哈希任务标识和必要时间戳,保留时间必须有界;Debug 与 Release 共用的数据必须跨进程加锁,修改存储格式或身份计算属于兼容性问题- 聚合算法、输出字段、字段含义或去重规则变化,需要重新计算历史数据时,必须递增聚合 schema,从保留期内的原始事件完整重建,不新增字段级历史迁移- 活动计数字段缺失表示历史来源不可用,不能解释为明确的零值@@ -171,8 +171,9 @@ Tag 名 `v{MARKETING_VERSION}` 里的版本号从 `Config/Version.xcconfig` 读## 代码修改原则- 优先结合现有文件结构和类型职责,不为小改动新建抽象+- **内部逻辑与界面需求分开处理**:修复数据完整性、错误处理、重试或恢复等内部问题时,默认保持现有界面。内部区分成功、失败或部分恢复,不代表需要增加界面标注。未经用户明确要求或同意,不新增提示、标签、状态文案或其他展示内容;确需调整界面时,先说明必要性和具体改动,取得同意后再实施- 改 shared controller、shared service、模型解析或持久化 key 时,要考虑旧数据和降级路径;用户设置要保持默认值;持久化 key 和旧版本迁移兼容-- **任何兼容性问题都必须主动询问用户,不要自行决定**;只要改动会影响新旧共存就适用,不限于旧数据迁移或丢弃、持久化 key 改名或改结构、老版本升上来的降级路径、最低系统版本与 API 可用性取舍、云端记录格式变更;先说清影响面和几种做法的代价,等用户选定再动手+- **任何兼容性问题都必须主动询问用户,不要自行决定**;只要改动会影响新旧共存就适用,不限于旧数据迁移或丢弃、持久化 key 改名或改结构、老版本升上来的降级路径、最低系统版本与 API 可用性取舍、云端记录格式变更、内部版本变化;先说清影响面和几种做法的代价,等用户选定再动手- 处理窗口、菜单、快捷键、App 激活或事件监听时,特别注意 `LSUIElement` 应用特有的焦点行为- 不做辅助功能(Accessibility)适配,不新增辅助功能标签、特征或操作- 注释保持克制,只解释非显然的生命周期、焦点、actor 或系统 API 约束;现有注释多为解释为什么的类型,沿用同样风格diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex 62ed05b..d57e550 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -10,6 +10,7 @@B10000000000000000000005 /* CodexBarHelper in Embed CodexBar Helper */ = {isa = PBXBuildFile; fileRef = B10000000000000000000014 /* CodexBarHelper */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };C42A52F12FDACDEC004A2B53 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = C42A52F02FDACDEC004A2B53 /* Sparkle */; };D10000000000000000000001 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = C42A52F02FDACDEC004A2B53 /* Sparkle */; };+ F10000000000000000000001 /* CodexBar Helper Debug.app in Embed Helper Manager */ = {isa = PBXBuildFile; fileRef = F10000000000000000000002 /* CodexBar Helper Debug.app */; };/* End PBXBuildFile section *//* Begin PBXContainerItemProxy section */@@ -20,6 +21,13 @@remoteGlobalIDString = B10000000000000000000031;remoteInfo = CodexBarHelper;};+ F10000000000000000000007 /* PBXContainerItemProxy */ = {+ isa = PBXContainerItemProxy;+ containerPortal = C4A0FD8D2FD9302E000263A7 /* Project object */;+ proxyType = 1;+ remoteGlobalIDString = F10000000000000000000010;+ remoteInfo = CodexBarHelperManager;+ };/* End PBXContainerItemProxy section *//* Begin PBXCopyFilesBuildPhase section */@@ -40,6 +48,15 @@);name = "Copy LaunchDaemons";};+ F10000000000000000000004 /* Embed Helper Manager */ = {+ isa = PBXCopyFilesBuildPhase;+ dstPath = Contents/Library/LoginItems;+ dstSubfolder = Wrapper;+ files = (+ F10000000000000000000001 /* CodexBar Helper Debug.app in Embed Helper Manager */,+ );+ name = "Embed Helper Manager";+ };/* End PBXCopyFilesBuildPhase section *//* Begin PBXFileReference section */@@ -48,6 +65,7 @@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 /* CodexBarHelperTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CodexBarHelperTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };+ F10000000000000000000002 /* CodexBar Helper Debug.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "CodexBar Helper Debug.app"; sourceTree = BUILT_PRODUCTS_DIR; };/* End PBXFileReference section *//* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */@@ -76,7 +94,7 @@/* End PBXFileSystemSynchronizedBuildFileExceptionSet section *//* Begin PBXFileSystemSynchronizedGroupBuildPhaseMembershipExceptionSet section */- C449FB4C302038A300ED2123 /* Exceptions for "CodexBarHelper" folder in "Copy LaunchDaemons" phase from "CodexBar" target */ = {+ C449FB4C302038A300ED2123 /* Exceptions for "CodexBarHelper" folder in "Copy LaunchDaemons" phase from "CodexBarHelperManager" target */ = {isa = PBXFileSystemSynchronizedGroupBuildPhaseMembershipExceptionSet;buildPhase = B10000000000000000000024 /* Copy LaunchDaemons */;membershipExceptions = (@@ -99,8 +117,8 @@C449FB3A3020367500ED2123 /* CodexBarHelper */ = {isa = PBXFileSystemSynchronizedRootGroup;exceptions = (+ C449FB4C302038A300ED2123 /* Exceptions for "CodexBarHelper" folder in "Copy LaunchDaemons" phase from "CodexBarHelperManager" target */,E10000000000000000000003 /* Exceptions for "CodexBarHelper" folder in "CodexBarHelperTests" target */,- C449FB4C302038A300ED2123 /* Exceptions for "CodexBarHelper" folder in "Copy LaunchDaemons" phase from "CodexBar" target */,);path = CodexBarHelper;sourceTree = "<group>";@@ -120,6 +138,11 @@path = CodexBarHelperTests;sourceTree = "<group>";};+ F10000000000000000000003 /* CodexBarHelperManager */ = {+ isa = PBXFileSystemSynchronizedRootGroup;+ path = CodexBarHelperManager;+ sourceTree = "<group>";+ };/* End PBXFileSystemSynchronizedRootGroup section *//* Begin PBXFrameworksBuildPhase section */@@ -145,6 +168,11 @@files = ();};+ F10000000000000000000006 /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ files = (+ );+ };/* End PBXFrameworksBuildPhase section *//* Begin PBXGroup section */@@ -160,6 +188,7 @@isa = PBXGroup;children = (9E664A4C2FDD47530016B96E /* CodexBar */,+ F10000000000000000000003 /* CodexBarHelperManager */,D10000000000000000000004 /* CodexBarTests */,E10000000000000000000004 /* CodexBarHelperTests */,C449FB4E30203A1100ED2123 /* Shared */,@@ -176,6 +205,7 @@D10000000000000000000002 /* CodexBarTests.xctest */,E10000000000000000000002 /* CodexBarHelperTests.xctest */,B10000000000000000000014 /* CodexBarHelper */,+ F10000000000000000000002 /* CodexBar Helper Debug.app */,);name = Products;sourceTree = "<group>";@@ -208,13 +238,12 @@C4A0FD912FD9302E000263A7 /* Sources */,C4A0FD922FD9302E000263A7 /* Frameworks */,C4A0FD932FD9302E000263A7 /* Resources */,- B10000000000000000000023 /* Embed CodexBar Helper */,- B10000000000000000000024 /* Copy LaunchDaemons */,+ F10000000000000000000004 /* Embed Helper Manager */,);buildRules = ();dependencies = (- B10000000000000000000051 /* PBXTargetDependency */,+ F10000000000000000000008 /* PBXTargetDependency */,);fileSystemSynchronizedGroups = (9E664A4C2FDD47530016B96E /* CodexBar */,@@ -270,6 +299,30 @@productReference = E10000000000000000000002 /* CodexBarHelperTests.xctest */;productType = "com.apple.product-type.bundle.unit-test";};+ F10000000000000000000010 /* CodexBarHelperManager */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = F10000000000000000000011 /* Build configuration list for PBXNativeTarget "CodexBarHelperManager" */;+ buildPhases = (+ F10000000000000000000005 /* Sources */,+ F10000000000000000000006 /* Frameworks */,+ F10000000000000000000009 /* Resources */,+ B10000000000000000000023 /* Embed CodexBar Helper */,+ B10000000000000000000024 /* Copy LaunchDaemons */,+ );+ buildRules = (+ );+ dependencies = (+ B10000000000000000000051 /* PBXTargetDependency */,+ );+ fileSystemSynchronizedGroups = (+ C449FB4E30203A1100ED2123 /* Shared */,+ F10000000000000000000003 /* CodexBarHelperManager */,+ );+ name = CodexBarHelperManager;+ productName = CodexBarHelperManager;+ productReference = F10000000000000000000002 /* CodexBar Helper Debug.app */;+ productType = "com.apple.product-type.application";+ };/* End PBXNativeTarget section *//* Begin PBXProject section */@@ -306,6 +359,7 @@projectDirPath = "";projectRoot = "";targets = (+ F10000000000000000000010 /* CodexBarHelperManager */,E10000000000000000000010 /* CodexBarHelperTests */,D10000000000000000000010 /* CodexBarTests */,C4A0FD942FD9302E000263A7 /* CodexBar */,@@ -315,6 +369,11 @@/* End PBXProject section *//* Begin PBXResourcesBuildPhase section */+ F10000000000000000000009 /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ files = (+ );+ };C4A0FD932FD9302E000263A7 /* Resources */ = {isa = PBXResourcesBuildPhase;files = (@@ -348,6 +407,11 @@files = ();};+ F10000000000000000000005 /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ files = (+ );+ };/* End PBXSourcesBuildPhase section *//* Begin PBXTargetDependency section */@@ -356,6 +420,11 @@target = B10000000000000000000031 /* CodexBarHelper */;targetProxy = B10000000000000000000052 /* PBXContainerItemProxy */;};+ F10000000000000000000008 /* PBXTargetDependency */ = {+ isa = PBXTargetDependency;+ target = F10000000000000000000010 /* CodexBarHelperManager */;+ targetProxy = F10000000000000000000007 /* PBXContainerItemProxy */;+ };/* End PBXTargetDependency section *//* Begin XCBuildConfiguration section */@@ -660,6 +729,46 @@};name = Release;};+ F10000000000000000000012 /* Debug configuration for PBXNativeTarget "CodexBarHelperManager" */ = {+ 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 = app.zabrian.codexbar.helper.plist;+ GENERATE_INFOPLIST_FILE = YES;+ INFOPLIST_KEY_CFBundleDisplayName = "CodexBar Helper Debug";+ INFOPLIST_KEY_LSUIElement = YES;+ PRODUCT_BUNDLE_IDENTIFIER = "app.zabrian.codexbar.helper-manager.debug";+ PRODUCT_NAME = "$(TARGET_NAME)";+ SKIP_INSTALL = YES;+ SWIFT_EMIT_LOC_STRINGS = NO;+ WRAPPER_NAME = "CodexBar Helper Debug.app";+ };+ name = Debug;+ };+ F10000000000000000000013 /* Release configuration for PBXNativeTarget "CodexBarHelperManager" */ = {+ 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 = app.zabrian.codexbar.helper.debug.plist;+ GENERATE_INFOPLIST_FILE = YES;+ INFOPLIST_KEY_CFBundleDisplayName = "CodexBar Helper";+ INFOPLIST_KEY_LSUIElement = YES;+ PRODUCT_BUNDLE_IDENTIFIER = "app.zabrian.codexbar.helper-manager";+ PRODUCT_NAME = "$(TARGET_NAME)";+ SKIP_INSTALL = YES;+ SWIFT_EMIT_LOC_STRINGS = NO;+ WRAPPER_NAME = "CodexBar Helper.app";+ };+ name = Release;+ };/* End XCBuildConfiguration section *//* Begin XCConfigurationList section */@@ -703,6 +812,14 @@);defaultConfigurationName = Release;};+ F10000000000000000000011 /* Build configuration list for PBXNativeTarget "CodexBarHelperManager" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ F10000000000000000000012 /* Debug configuration for PBXNativeTarget "CodexBarHelperManager" */,+ F10000000000000000000013 /* Release configuration for PBXNativeTarget "CodexBarHelperManager" */,+ );+ defaultConfigurationName = Release;+ };/* End XCConfigurationList section *//* Begin XCRemoteSwiftPackageReference section */diff --git a/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plist b/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plistindex bf0b194..d8e6cbe 100644--- a/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plist+++ b/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plist@@ -14,6 +14,11 @@<key>orderHint</key><integer>1</integer></dict>+ <key>CodexBarHelperManager.xcscheme_^#shared#^_</key>+ <dict>+ <key>orderHint</key>+ <integer>2</integer>+ </dict></dict><key>SuppressBuildableAutocreation</key><dict>diff --git a/CodexBar/App/CodexBarAppDelegate.swift b/CodexBar/App/CodexBarAppDelegate.swiftindex 7dc7f6f..6550b3a 100644--- a/CodexBar/App/CodexBarAppDelegate.swift+++ b/CodexBar/App/CodexBarAppDelegate.swift@@ -4,7 +4,7 @@ import os/// 应用级对象装配点, 持有服务和 ViewModel 生命周期@MainActorfinal class CodexBarAppDelegate: NSObject, NSApplicationDelegate {- private let codexStatusService = CodexStatusService()+ private lazy var codexStatusService = CodexStatusService(startup: appServerStartup)private lazy var appServerStartup = AppServerStartup()lazy var viewModel = CodexStatusViewModel(service: codexStatusService)let historyViewModel = HistoryViewModel()@@ -83,6 +83,9 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {keepAliveController.onKeepAliveLimitTriggered = { [weak notificationService] duration inawait notificationService?.notifyKeepAliveLimitReached(durationText: duration.title) ?? false}+ activityMonitor.onAccountChange = { [weak viewModel] change in+ viewModel?.receiveAccountChange(change)+ }activityMonitor.onProtectionTriggered = { [weak notificationService] notice inawait notificationService?.notifyProtection(notice) ?? false}@@ -98,19 +101,17 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {keepAliveController.start()logLaunchState()startupTask = Task { [weak self, startup = appServerStartup] in- var startupError: String?do {try await startup.ensureStarted()} catch is CancellationError {return} catch {- startupError = error.localizedDescriptionAppLog.app.error("Codex 后台服务准备失败")AppServerLogStore.shared.recordFailure(method: "daemon/start", message: error.localizedDescription)}guard let self, !Task.isCancelled else { return }startupTask = nil- viewModel.startAutoRefresh(startupError: startupError)+ viewModel.startAutoRefresh()activityMonitor.start()}}@@ -142,17 +143,23 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {NSApplication.shared.reply(toApplicationShouldTerminate: false)return}+ await startupTask?.valueautoResetController?.prepareForTermination()+ let activitySaved = await activityMonitor.prepareForTermination()+ if !activitySaved {+ AppLog.app.error("退出 App 前数据保存失败")+ }let success = await keepAliveController.prepareForTermination()guard !Task.isCancelled else {return}if success {do { try await AppServerLogStore.shared.finish() } catch {- AppLog.app.error("退出前请求日志写入失败")+ AppLog.app.error("退出 App 前日志写入失败")}}if !success {+ await activityMonitor.resumeAfterTerminationCancellation()autoResetController?.resumeAfterTerminationCancellation()}terminationPreparationTask = nildiff --git a/CodexBar/Controllers/HeatmapPanelController.swift b/CodexBar/Controllers/HeatmapPanelController.swiftindex 4eef041..e36be27 100644--- a/CodexBar/Controllers/HeatmapPanelController.swift+++ b/CodexBar/Controllers/HeatmapPanelController.swift@@ -6,7 +6,7 @@ import SwiftUI@MainActorfinal class HeatmapPanelController {private let contentHost = SidePanelContentHost<HeatmapDetailView>(- initialSize: HeatmapDetailView.panelSize(showsActivity: true),+ initialSize: HeatmapDetailView.panelSize,ignoresMouseEvents: true,sizingOptions: [.preferredContentSize],cornerRadius: HeatmapDetailView.panelCornerRadius@@ -112,7 +112,7 @@ final class HeatmapPanelController {attach(panel, to: menuSurfaceWindow)}- let panelSize = HeatmapDetailView.panelSize(showsActivity: context.showsActivity)+ let panelSize = HeatmapDetailView.panelSizelet position = panelPosition(for: panelSize,relativeTo: menuSurfaceWindow,@@ -291,7 +291,7 @@ final class HeatmapPanelController {private func updateContent(_ context: UsageHeatmapHoverContext) {contentHost.updateContent(HeatmapDetailView(context: context),- size: HeatmapDetailView.panelSize(showsActivity: context.showsActivity)+ size: HeatmapDetailView.panelSize)}diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex bf30709..13ce8c5 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -146,7 +146,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {func install() {configureStatusButton()configurePopover()- observeGlobalHotKeySettings()+ configureGlobalHotKey()// 订阅时 CombineLatest 会同步发出当前值, 初始图标由订阅路径统一渲染observeViewModel()observeSyncState()@@ -160,7 +160,9 @@ final class StatusItemController: NSObject, NSMenuDelegate {statusIconHostingView = nilsyncScheduler.cancel()setAuxiliaryWindowKeyFocus(true)+ globalHotKeySettings.configureRegistration(nil)globalHotKeyController.uninstall()+ registeredHotKeyShortcut = nilcancellables.removeAll()NSStatusBar.system.removeStatusItem(statusItem)}@@ -317,15 +319,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {}.store(in: &cancellables)- hasTaskCenterContent- .sink { [weak self] isAvailable in- guard let self, !isAvailable else {- return- }- activityCenterPanelController.hide(immediate: true)- }- .store(in: &cancellables)-mainPanelSettings.$layout.sink { [weak self] layout inguard let self else {@@ -356,41 +349,28 @@ final class StatusItemController: NSObject, NSMenuDelegate {.store(in: &cancellables)}- private func observeGlobalHotKeySettings() {- globalHotKeySettings.$shortcut- .removeDuplicates()- .sink { [weak self] shortcut in- self?.applyGlobalHotKey(shortcut)- }- .store(in: &cancellables)+ private func configureGlobalHotKey() {+ globalHotKeySettings.configureRegistration { [weak self] shortcut in+ self?.applyGlobalHotKey(shortcut)+ }}- private func applyGlobalHotKey(_ shortcut: GlobalHotKeyShortcut?) {+ private func applyGlobalHotKey(_ shortcut: GlobalHotKeyShortcut?) -> String? {guard shortcut != registeredHotKeyShortcut else {- return+ return nil}guard let shortcut else {globalHotKeyController.uninstall()registeredHotKeyShortcut = nil- return- }-- if globalHotKeyController.install(shortcut: shortcut) {- registeredHotKeyShortcut = shortcut- globalHotKeySettings.clearError()- return+ return nil}- let message = hotKeyConflictMessage(for: shortcut)- guard let previousShortcut = registeredHotKeyShortcut else {- // 启动阶段冲突时还没有成功注册过任何快捷键- // 此时 restoreShortcut(nil) 会清空用户保存的配置, 只能提示冲突- globalHotKeySettings.setRegistrationError(message)- return+ guard globalHotKeyController.install(shortcut: shortcut) else {+ return hotKeyConflictMessage(for: shortcut)}-- globalHotKeySettings.restoreShortcut(previousShortcut, message: message)+ registeredHotKeyShortcut = shortcut+ return nil}private func hotKeyConflictMessage(for shortcut: GlobalHotKeyShortcut) -> String {diff --git a/CodexBar/Models/ActivityAggregate.swift b/CodexBar/Models/ActivityAggregate.swiftindex 61adf5d..4f54dca 100644--- a/CodexBar/Models/ActivityAggregate.swift+++ b/CodexBar/Models/ActivityAggregate.swift@@ -12,43 +12,42 @@ nonisolated enum ActivityIdentifiers {/// 全量和增量路径都收集 ID, 只有 finalize 时才按保留策略决定是否落盘nonisolated struct ActivityAccumulator {private var aggregate: ActivityAggregate- private var sessionIDs: Set<String> = []+ private var threadIDs: Set<String> = []private var turnIDs: Set<String> = []+ private var baseThreadCount = 0+ private var baseTurnCount = 0+ private var restoresCompactedIdentity = falseinit(rebuilding date: String,generationID: String?,- generationStartedEmpty: Bool,eventCountAvailability: ActivityCountAvailability) {aggregate = ActivityAggregate(date: date,generationID: generationID,- generationStartedEmpty: generationStartedEmpty,eventCountAvailability: eventCountAvailability)}init(appending aggregate: ActivityAggregate,- generationID: String?,- generationStartedEmpty: Bool+ generationID: String?) {var aggregate = aggregateaggregate.generationID = generationID- aggregate.generationStartedEmpty = generationStartedEmptyself.aggregate = aggregate- sessionIDs = Set(aggregate.sessionIDs ?? [])+ threadIDs = Set(aggregate.threadIDs ?? [])turnIDs = Set(aggregate.turnIDs ?? [])+ baseThreadCount = aggregate.threadCount ?? 0+ baseTurnCount = aggregate.turnCount ?? 0+ restoresCompactedIdentity = !aggregate.supportsIncrementalAggregation}mutating func record(_ event: ActivityRecord) {- // origin 只控制实时活动过滤, 历史统计按全部业务事件事实保持原口径Self.increment(&aggregate.eventCount)switch event.eventKind {- case .sessionStarted: Self.increment(&aggregate.sessionStartedCount)- case .sessionEnded: Self.increment(&aggregate.sessionEndedCount)case .turnStarted: Self.increment(&aggregate.turnStartedCount)case .turnCompleted: Self.increment(&aggregate.turnCompletedCount)case .turnAborted: Self.increment(&aggregate.turnAbortedCount)@@ -63,11 +62,12 @@ nonisolated struct ActivityAccumulator {}// 终态事件不单独构成对应的当日活跃轮次- if event.eventKind != .sessionEnded, let sessionID = event.sessionID {- sessionIDs.insert(sessionID)+ if let threadID = event.threadID, threadIDs.insert(threadID).inserted, restoresCompactedIdentity {+ baseThreadCount += 1}- if event.eventKind != .turnCompleted, event.eventKind != .turnAborted, let turnID = event.turnID {- turnIDs.insert(turnID)+ if event.eventKind != .turnCompleted, event.eventKind != .turnAborted,+ let turnID = event.turnID, turnIDs.insert(turnID).inserted, restoresCompactedIdentity {+ baseTurnCount += 1}if let projectDisplayName = event.projectDisplayName {@@ -78,18 +78,27 @@ nonisolated struct ActivityAccumulator {}}+ mutating func restoreIdentity(from event: ActivityRecord) {+ if let threadID = event.threadID {+ threadIDs.insert(threadID)+ }+ if event.eventKind != .turnCompleted, event.eventKind != .turnAborted, let turnID = event.turnID {+ turnIDs.insert(turnID)+ }+ }+func finalized(identifierStorage: ActivityIdentifiers) -> ActivityAggregate {var aggregate = aggregateswitch identifierStorage {case .retained:- aggregate.sessionCount = nil+ aggregate.threadCount = nilaggregate.turnCount = nil- aggregate.sessionIDs = Self.normalizedIdentifiers(sessionIDs)+ aggregate.threadIDs = Self.normalizedIdentifiers(threadIDs)aggregate.turnIDs = Self.normalizedIdentifiers(turnIDs)case .compacted:- aggregate.sessionCount = sessionIDs.count- aggregate.turnCount = turnIDs.count- aggregate.sessionIDs = nil+ aggregate.threadCount = restoresCompactedIdentity ? baseThreadCount : threadIDs.count+ aggregate.turnCount = restoresCompactedIdentity ? baseTurnCount : turnIDs.count+ aggregate.threadIDs = nilaggregate.turnIDs = nil}return aggregate@@ -111,11 +120,6 @@ nonisolated struct ActivityCountAvailability {events: Set(ActivityEventKind.allCases))- static let legacy = ActivityCountAvailability(- includesEventCount: true,- events: Set(ActivityEventKind.allCases.filter { $0 != .turnAborted })- )-private let includesEventCount: Boolprivate let events: Set<ActivityEventKind>@@ -140,12 +144,14 @@ nonisolated struct ActivityCountAvailability {/// Aggregates/activity.jsonl 中的持久化聚合行, 同时兼容保留 ID 和只保留计数两种形态nonisolated struct ActivityAggregate: Codable, Equatable {+ static let currentVersion = 1+ var version = Self.currentVersion+ var aggregationVersion = AggregationVersion.activity+ var sourceCheckpoint: ActivitySourceCheckpoint?+let date: Stringvar generationID: String?- var generationStartedEmpty: Boolvar eventCount: Int?- var sessionStartedCount: Int?- var sessionEndedCount: Int?var turnStartedCount: Int?var turnCompletedCount: Int?var turnAbortedCount: Int?@@ -156,30 +162,26 @@ nonisolated struct ActivityAggregate: Codable, Equatable {var compactionCompletedCount: Int?var subagentStartedCount: Int?var subagentEndedCount: Int?- var sessionCount: Int?+ var threadCount: Int?var turnCount: Int?var projectCounts: [String: Int]var modelCounts: [String: Int]- var sessionIDs: [String]?+ var threadIDs: [String]?var turnIDs: [String]?/// 增量路径只有在完整 ID 集合仍然存在时才能继续安全去重var supportsIncrementalAggregation: Bool {- sessionCount == nil && turnCount == nil+ threadCount == nil && turnCount == nil}init(date: String,generationID: String? = nil,- generationStartedEmpty: Bool = false,eventCountAvailability: ActivityCountAvailability = .all) {self.date = dateself.generationID = generationID- self.generationStartedEmpty = generationStartedEmptyeventCount = eventCountAvailability.initialEventCount- sessionStartedCount = eventCountAvailability.initialCount(for: .sessionStarted)- sessionEndedCount = eventCountAvailability.initialCount(for: .sessionEnded)turnStartedCount = eventCountAvailability.initialCount(for: .turnStarted)turnCompletedCount = eventCountAvailability.initialCount(for: .turnCompleted)turnAbortedCount = eventCountAvailability.initialCount(for: .turnAborted)@@ -190,22 +192,24 @@ nonisolated struct ActivityAggregate: Codable, Equatable {compactionCompletedCount = eventCountAvailability.initialCount(for: .compactionCompleted)subagentStartedCount = eventCountAvailability.initialCount(for: .subagentStarted)subagentEndedCount = eventCountAvailability.initialCount(for: .subagentEnded)- sessionCount = nil+ threadCount = nilturnCount = nilprojectCounts = [:]modelCounts = [:]- sessionIDs = []+ threadIDs = []turnIDs = []}init(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self)+ version = try container.decode(Int.self, forKey: .version)+ try StorageVersion.require(version, current: Self.currentVersion, name: "ActivityAggregate")+ sourceCheckpoint = try container.decodeIfPresent(ActivitySourceCheckpoint.self, forKey: .sourceCheckpoint)+ aggregationVersion = try container.decode(Int.self, forKey: .aggregationVersion)+ try AggregationVersion.require(aggregationVersion, current: AggregationVersion.activity, name: "Activity")date = try container.decode(String.self, forKey: .date)generationID = try container.decodeIfPresent(String.self, forKey: .generationID)- generationStartedEmpty = try container.decodeIfPresent(Bool.self, forKey: .generationStartedEmpty) ?? falseeventCount = try container.decodeIfPresent(Int.self, forKey: .eventCount)- sessionStartedCount = try container.decodeIfPresent(Int.self, forKey: .sessionStartedCount)- sessionEndedCount = try container.decodeIfPresent(Int.self, forKey: .sessionEndedCount)turnStartedCount = try container.decodeIfPresent(Int.self, forKey: .turnStartedCount)turnCompletedCount = try container.decodeIfPresent(Int.self, forKey: .turnCompletedCount)turnAbortedCount = try container.decodeIfPresent(Int.self, forKey: .turnAbortedCount)@@ -216,30 +220,30 @@ nonisolated struct ActivityAggregate: Codable, Equatable {compactionCompletedCount = try container.decodeIfPresent(Int.self, forKey: .compactionCompletedCount)subagentStartedCount = try container.decodeIfPresent(Int.self, forKey: .subagentStartedCount)subagentEndedCount = try container.decodeIfPresent(Int.self, forKey: .subagentEndedCount)- sessionCount = try container.decodeIfPresent(Int.self, forKey: .sessionCount)+ threadCount = try container.decodeIfPresent(Int.self, forKey: .threadCount)turnCount = try container.decodeIfPresent(Int.self, forKey: .turnCount)projectCounts = try container.decodeIfPresent([String: Int].self, forKey: .projectCounts) ?? [:]modelCounts = try container.decodeIfPresent([String: Int].self, forKey: .modelCounts) ?? [:]- sessionIDs = try container.decodeIfPresent([String].self, forKey: .sessionIDs)+ threadIDs = try container.decodeIfPresent([String].self, forKey: .threadIDs)turnIDs = try container.decodeIfPresent([String].self, forKey: .turnIDs)}mutating func normalizeIdentifierStorage(retainsIdentifiers: Bool) {guard !retainsIdentifiers else {- sessionIDs = Self.normalizedIdentifiers(sessionIDs)+ threadIDs = Self.normalizedIdentifiers(threadIDs)turnIDs = Self.normalizedIdentifiers(turnIDs)return}- sessionCount = CountResolution.preferredCount(- compactedCount: sessionCount,- identifiers: sessionIDs- ) ?? sessionStartedCount+ threadCount = CountResolution.preferredCount(+ compactedCount: threadCount,+ identifiers: threadIDs+ )turnCount = CountResolution.preferredCount(compactedCount: turnCount,identifiers: turnIDs- ) ?? turnCompletedCount- sessionIDs = nil+ )+ threadIDs = nilturnIDs = nil}@@ -285,8 +289,6 @@ nonisolated struct ActivityAggregate: Codable, Equatable {func eventCount(for event: ActivityEventKind) -> Int? {switch event {- case .sessionStarted: sessionStartedCount- case .sessionEnded: sessionEndedCountcase .turnStarted: turnStartedCountcase .turnCompleted: turnCompletedCountcase .turnAborted: turnAbortedCount@@ -302,11 +304,11 @@ nonisolated struct ActivityAggregate: Codable, Equatable {var syncedAggregate: SyncedActivity {SyncedActivity(+ aggregationVersion: aggregationVersion,+ sourceCheckpoint: sourceCheckpoint,date: date,generationID: generationID,eventCount: eventCount,- sessionStartedCount: sessionStartedCount,- sessionEndedCount: sessionEndedCount,turnStartedCount: turnStartedCount,turnCompletedCount: turnCompletedCount,turnAbortedCount: turnAbortedCount,@@ -317,17 +319,17 @@ nonisolated struct ActivityAggregate: Codable, Equatable {compactionCompletedCount: compactionCompletedCount,subagentStartedCount: subagentStartedCount,subagentEndedCount: subagentEndedCount,- sessionCount: syncedSessionCount,+ threadCount: syncedThreadCount,turnCount: syncedTurnCount,projectCounts: projectCounts,modelCounts: modelCounts)}- private var syncedSessionCount: Int? {+ private var syncedThreadCount: Int? {CountResolution.preferredCount(- compactedCount: sessionCount,- identifiers: sessionIDs+ compactedCount: threadCount,+ identifiers: threadIDs)}@@ -347,12 +349,10 @@ nonisolated struct ActivityAggregate: Codable, Equatable {}private enum CodingKeys: String, CodingKey {+ case version, aggregationVersion, sourceCheckpointcase datecase generationID- case generationStartedEmptycase eventCount- case sessionStartedCount- case sessionEndedCountcase turnStartedCountcase turnCompletedCountcase turnAbortedCount@@ -363,13 +363,11 @@ nonisolated struct ActivityAggregate: Codable, Equatable {case compactionCompletedCountcase subagentStartedCountcase subagentEndedCount- case sessionCount+ case threadCountcase turnCountcase projectCountscase modelCounts- case sessionIDs+ case threadIDscase turnIDs}}--// 同步用的每日聚合行, 保留 Aggregates/activity.jsonl 中的计数, 不包含 sessionIds 和 turnIdsdiff --git a/CodexBar/Models/ActivityEventKind.swift b/CodexBar/Models/ActivityEventKind.swiftindex e135e14..acc51fc 100644--- a/CodexBar/Models/ActivityEventKind.swift+++ b/CodexBar/Models/ActivityEventKind.swift@@ -1,7 +1,5 @@/// app-server 事件映射到业务统计的生命周期阶段, 持久化直接使用枚举名称nonisolated enum ActivityEventKind: String, CaseIterable, Hashable {- case sessionStarted- case sessionEndedcase turnStartedcase toolStartedcase toolCompleted@@ -17,10 +15,3 @@ nonisolated enum ActivityEventKind: String, CaseIterable, Hashable {self.init(rawValue: eventName)}}--/// 审批路由的文件值直接使用成员名称, 协议解码在 app-server 边界完成-nonisolated enum ApprovalReviewer: String, Codable, CaseIterable {- case user- case autoReview- case guardianSubagent-}diff --git a/CodexBar/Models/ActivityInput.swift b/CodexBar/Models/ActivityInput.swiftnew file mode 100644index 0000000..9e13a78--- /dev/null+++ b/CodexBar/Models/ActivityInput.swift@@ -0,0 +1,177 @@+import Foundation++/// 协议适配后的输入, 状态处理只依赖 kind, 原方法名称只用于来源诊断+nonisolated struct ActivityInput {+ enum Category { case state, progress, presentation, ignored }++ enum Kind: String {+ case threadDiscovered+ case threadStatusChanged+ case usageUpdated+ case turnStarted+ case turnFinished+ case itemStarted+ case itemFinished+ case commandApprovalRequested+ case fileApprovalRequested+ case permissionsRequested+ case requestResolved+ case replyProgress+ case reasoningProgress+ case reasoningSummaryProgress+ case commandProgress+ case inputRequested+ case planChanged+ case diffChanged+ case modelChanged+ case verificationRequested+ case authRecoveryStarted+ case authRecoveryFinished+ case safetyBufferingChanged+ case hookStarted+ case hookFinished+ case errorReported+ case ignored++ var category: Category {+ switch self {+ case .threadDiscovered, .threadStatusChanged, .usageUpdated, .turnStarted, .turnFinished, .itemStarted, .itemFinished,+ .commandApprovalRequested, .fileApprovalRequested, .permissionsRequested, .requestResolved: .state+ case .replyProgress, .reasoningProgress, .reasoningSummaryProgress, .commandProgress: .progress+ case .inputRequested, .planChanged, .diffChanged, .modelChanged, .verificationRequested,+ .authRecoveryStarted, .authRecoveryFinished, .safetyBufferingChanged, .hookStarted, .hookFinished, .errorReported: .presentation+ case .ignored: .ignored+ }+ }+ }++ let id: String?+ let kind: Kind+ let provenanceMethod: String+ let params: Params+ let live: ActivityLiveContext++ struct Params {+ var threadId: String?+ var turnId: String?+ var itemId: String?+ var approvalId: String?+ var requestId: String?+ var thread: ActivityThread?+ var turn: ActivityTurn?+ var item: ActivityItem?+ var status: ActivityThreadStatus?+ var startedAt: Date?+ var completedAt: Date?+ var tokenUsage: ActivityTokenUpdate?+ var commandActions: [ActivityItem.CommandAction]?+ }+}++nonisolated enum ActivityTurnStatus: String, Codable {+ case running, completed, failed, interrupted, unknown+ var isTerminal: Bool {+ self == .completed || self == .failed || self == .interrupted+ }+}++nonisolated struct ActivityThread {+ let id: String+ var cwd: String?+ var model: String?+ var reasoningEffort: String?+ var status: ActivityThreadStatus?+ var origin: ActivityOrigin = .unknown+ var parentID: String?+ var createdAt: Date?+}++nonisolated struct ActivityThreadStatus {+ enum State: String { case active, idle, notLoaded, unknown }+ enum Flag: String { case waitingOnApproval, waitingOnUserInput, unknown }+ let type: State+ var activeFlags: [Flag]?+ var isWaiting: Bool {+ activeFlags?.contains(.waitingOnApproval) == true+ }+}++nonisolated struct ActivityTurn {+ let id: String+ let status: ActivityTurnStatus+ var rootTurnId: String?+ var items: [ActivityItem]?+ var startedAt: Date?+ var completedAt: Date?+ var duration: TimeInterval?+}++nonisolated struct ActivityItem {+ enum ItemType: String, Codable {+ case commandExecution, fileChange, webSearch, imageView, imageGeneration, sleep+ case mcpToolCall, dynamicToolCall, collabAgentToolCall, contextCompaction, subAgentActivity+ case agentMessage, reasoning, enteredReviewMode, exitedReviewMode, unknown+ }++ struct CommandAction { let type: String }+ struct WebAction { var type: String? }+ struct AgentState { var status: String? }+ let id: String+ let type: ItemType+ var status: String?+ var tool: String?+ var server: String?+ var agentThreadId: String?+ var kind: String?+ var model: String?+ var reasoningEffort: String?+ var commandActions: [CommandAction]?+ var phase: String?+ var action: WebAction?+ var success: Bool?+ var agentsStates: [String: AgentState]?+ var isToolCall: Bool {+ Self.isToolType(type)+ }++ static func isToolType(_ type: ItemType) -> Bool {+ switch type {+ case .commandExecution, .fileChange, .webSearch, .imageView, .imageGeneration, .sleep,+ .mcpToolCall, .dynamicToolCall, .collabAgentToolCall: true+ default: false+ }+ }+}++nonisolated struct ActivityTokenUpdate {+ let total: TokenUsage+ let last: TokenUsage+}++nonisolated struct ActivityLiveContext {+ enum InputMode { case form, external, verification, service }+ enum HookOutcome: String { case completed, failed, blocked, stopped, unknown }+ struct Hook {+ let id: String+ let status: HookOutcome?+ let isSynchronous: Bool+ }++ let inputMode: InputMode+ let planCompleted: Int?+ let planTotal: Int?+ let run: Hook?+ let isSafetyBuffering: Bool+ let willRetry: Bool?+ let fromModel: String?+ let toModel: String?+ let requiresVerification: Bool+}++nonisolated extension ActivityItem {+ static func isObservedType(_ type: ItemType) -> Bool {+ isToolType(type) || [+ .contextCompaction, .subAgentActivity, .agentMessage, .reasoning, .enteredReviewMode, .exitedReviewMode+ ].contains(type)+ }+}diff --git a/CodexBar/Models/ActivityModels.swift b/CodexBar/Models/ActivityModels.swiftindex 5affba9..20e3f82 100644--- a/CodexBar/Models/ActivityModels.swift+++ b/CodexBar/Models/ActivityModels.swift@@ -8,29 +8,23 @@ nonisolated enum ActivityRetention {/// 正在运行或等待批准的任务摘要, 不对 UI 暴露原始会话 IDnonisolated struct ActivityTaskSnapshot: Equatable, Identifiable {let id: UUID- let isAnonymous: Boollet projectName: String?let modelName: String?let effort: String?- let toolName: String?let startedAt: Date?let stateChangedAt: Date- let showsPreciseDuration: Bool/// nil 表示 活动字段不足, 无法可靠统计; 0 表示已确认当前没有活跃子 Agentlet activeSubagentCount: Int?var tokenUsage: TokenUsage?- var itemType: String?+ var approvalActionText: String?var presentation: ActivityLiveSummary?-- var toolDisplayName: String? {- ActivityDisplayFormat.toolActionText(itemType: itemType, toolName: toolName)- }}/// 最近确认结束的任务; 完成只表示一轮任务结束, 不代表执行成功nonisolated struct ActivityCompletion: Equatable, Identifiable {let id: UUID- let isAnonymous: Bool+ // 延续运行期间的 UI 状态, 终态记录仍使用独立的 id+ var taskID: UUID?let projectName: String?let modelName: String?let effort: String?@@ -67,7 +61,7 @@ nonisolated enum ActivityTerminalEvent: Equatable {/// 最近确认终止的任务; 中断和其他终止都不会触发完成提醒nonisolated struct ActivityTermination: Equatable, Identifiable {let id: UUID- let isAnonymous: Bool+ var taskID: UUID?let projectName: String?let modelName: String?let effort: String?@@ -212,13 +206,6 @@ nonisolated enum CodexPrimaryActivity: Equatable {nonisolated enum ActivityTransition: Equatable {case waitingApproval(ActivityTaskSnapshot)case completed(ActivityCompletion)-- var isAnonymous: Bool {- switch self {- case let .waitingApproval(task): task.isAnonymous- case let .completed(completion): completion.isAnonymous- }- }}nonisolated enum CodexDurationFormat {diff --git a/CodexBar/Models/ActivityRecord.swift b/CodexBar/Models/ActivityRecord.swiftindex 668ceab..848df6d 100644--- a/CodexBar/Models/ActivityRecord.swift+++ b/CodexBar/Models/ActivityRecord.swift@@ -2,7 +2,7 @@ import Foundation// MARK: - 归一化活动事件-/// 事件来源的本地归一化分类, 不保留原始 source 内容+/// 事件来源的本地归一化分类, 不保留原始 context 内容nonisolated enum ActivityOrigin: String, Codable, Sendable {case maincase autoReview@@ -23,25 +23,25 @@ nonisolated struct ActivityRecord: Codable, Equatable {let name: Stringlet origin: ActivityOriginlet cwd: String?- let tool: String?+ let toolName: String?+ let commandActionTypes: [String]?let model: String?let effort: String?- let approvalReviewer: ApprovalReviewer?- let sessionID: String?+ let threadID: String?let turnID: String?let agentID: String?- var source: AppServerEventSource?+ var context: ActivityContext?init(timestamp: Date,name: String,origin: ActivityOrigin,cwd: String?,- tool: String?,+ toolName: String?,+ commandActionTypes: [String]? = nil,model: String?,effort: String?,- approvalReviewer: ApprovalReviewer?,- sessionID: String?,+ threadID: String?,turnID: String?,agentID: String?,id: String? = nil@@ -49,13 +49,13 @@ nonisolated struct ActivityRecord: Codable, Equatable {self.id = idself.timestamp = timestampself.name = name- self.origin = Self.resolvedOrigin(origin, model: model)+ self.origin = originself.cwd = cwd- self.tool = tool+ self.toolName = toolName+ self.commandActionTypes = commandActionTypesself.model = modelself.effort = effort- self.approvalReviewer = approvalReviewer- self.sessionID = sessionID+ self.threadID = threadIDself.turnID = turnIDself.agentID = agentID}@@ -68,7 +68,7 @@ nonisolated struct ActivityRecord: Codable, Equatable {throw DecodingError.dataCorruptedError(forKey: .name, in: container, debugDescription: "Unknown activity phase")}let name = event.rawValue- source = try container.decodeIfPresent(AppServerEventSource.self, forKey: .source)+ context = try container.decodeIfPresent(ActivityContext.self, forKey: .context)id = try container.decodeIfPresent(String.self, forKey: .id)let decodedOrigin = (try? container.decode(ActivityOrigin.self, forKey: .origin)) ?? .unknown@@ -76,16 +76,13 @@ nonisolated struct ActivityRecord: Codable, Equatable {self.timestamp = timestampself.name = name- origin = Self.resolvedOrigin(decodedOrigin, model: decodedModel)+ origin = decodedOrigincwd = Self.string(from: container, key: .cwd)- tool = Self.string(from: container, key: .tool)+ toolName = Self.string(from: container, key: .toolName)+ commandActionTypes = try container.decodeIfPresent([String].self, forKey: .commandActionTypes)model = decodedModeleffort = Self.string(from: container, key: .effort)- approvalReviewer = try? container.decode(- ApprovalReviewer.self,- forKey: .approvalReviewer- )- sessionID = Self.string(from: container, key: .sessionID)+ threadID = Self.string(from: container, key: .threadID)turnID = Self.string(from: container, key: .turnID)agentID = Self.string(from: container, key: .agentID)}@@ -116,18 +113,6 @@ nonisolated struct ActivityRecord: Codable, Equatable {return trimmedValue.isEmpty ? nil : trimmedValue}- /// 来源元数据缺失时, 专用审核模型只作为未知来源的保守后备- private static func resolvedOrigin(- _ origin: ActivityOrigin,- model: String?- ) -> ActivityOrigin {- guard origin == .unknown,- model == autoReviewModelName else {- return origin- }- return .autoReview- }-func encode(to encoder: Encoder) throws {var container = encoder.container(keyedBy: CodingKeys.self)try container.encodeIfPresent(id, forKey: .id)@@ -138,14 +123,14 @@ nonisolated struct ActivityRecord: Codable, Equatable {try container.encode(eventKind.rawValue, forKey: .name)try container.encode(origin, forKey: .origin)try container.encodeIfPresent(cwd, forKey: .cwd)- try container.encodeIfPresent(tool, forKey: .tool)+ try container.encodeIfPresent(toolName, forKey: .toolName)+ try container.encodeIfPresent(commandActionTypes, forKey: .commandActionTypes)try container.encodeIfPresent(model, forKey: .model)try container.encodeIfPresent(effort, forKey: .effort)- try container.encodeIfPresent(approvalReviewer, forKey: .approvalReviewer)- try container.encodeIfPresent(sessionID, forKey: .sessionID)+ try container.encodeIfPresent(threadID, forKey: .threadID)try container.encodeIfPresent(turnID, forKey: .turnID)try container.encodeIfPresent(agentID, forKey: .agentID)- try container.encodeIfPresent(source, forKey: .source)+ try container.encodeIfPresent(context, forKey: .context)}private enum CodingKeys: String, CodingKey {@@ -154,15 +139,33 @@ nonisolated struct ActivityRecord: Codable, Equatable {case namecase origincase cwd- case tool+ case toolName+ case commandActionTypescase modelcase effort- case approvalReviewer- case sessionID+ case threadIDcase turnIDcase agentID- case source+ case context}+}- private static let autoReviewModelName = "codex-auto-review"+/// 任务归属与生命周期事实, 时间统一为 Date 和秒, method 仅用于来源诊断+nonisolated struct ActivityContext: Codable, Equatable {+ let method: String+ let threadID: String+ var turnID: String?+ var parentThreadID: String?+ var rootThreadID: String?+ var rootTurnID: String?+ var itemID: String?+ var itemType: String?+ var itemStatus: String?+ var agentThreadID: String?+ var itemKind: String?+ var requestID: String?+ var turnStatus: ActivityTurnStatus?+ var turnStartedAt: Date?+ var turnCompletedAt: Date?+ var duration: TimeInterval?}diff --git a/CodexBar/Models/ActivitySourceCheckpoint.swift b/CodexBar/Models/ActivitySourceCheckpoint.swiftnew file mode 100644index 0000000..6cb87ee--- /dev/null+++ b/CodexBar/Models/ActivitySourceCheckpoint.swift@@ -0,0 +1,48 @@+import CryptoKit+import Foundation++/// 检查点描述原始日志前缀, 不使用统计计数判断来源覆盖+nonisolated struct ActivitySourceCheckpoint: Codable, Equatable {+ let byteCount: UInt64+ let digest: String+ var aggregationRanges: [AggregationRange] = []++ private enum CodingKeys: String, CodingKey { case byteCount, digest, aggregationRanges }++ init(byteCount: UInt64, digest: String) {+ self.byteCount = byteCount+ self.digest = digest+ }++ init(from decoder: Decoder) throws {+ let values = try decoder.container(keyedBy: CodingKeys.self)+ byteCount = try values.decode(UInt64.self, forKey: .byteCount)+ digest = try values.decode(String.self, forKey: .digest)+ aggregationRanges = try values.decodeIfPresent([AggregationRange].self, forKey: .aggregationRanges) ?? []+ try AggregationRange.validate(aggregationRanges, end: byteCount, current: AggregationVersion.activity)+ guard byteCount > 0, digest.count == 64, digest.allSatisfy({ "0123456789abcdef".contains($0) }) else {+ throw StorageCompatibilityError.incompleteSource+ }+ }++ func matchesSource(_ other: Self?) -> Bool {+ guard let other else { return false }+ return byteCount == other.byteCount && digest == other.digest+ }++ static func read(at url: URL, byteCount: UInt64) throws -> Self {+ let handle = try FileHandle(forReadingFrom: url)+ defer { try? handle.close() }+ var remaining = byteCount+ var hash = SHA256()+ while remaining > 0 {+ try Task.checkCancellation()+ guard let chunk = try handle.read(upToCount: Int(min(remaining, 64 * 1024))), !chunk.isEmpty else {+ throw StorageCompatibilityError.incompleteSource+ }+ hash.update(data: chunk)+ remaining -= UInt64(chunk.count)+ }+ return Self(byteCount: byteCount, digest: hash.finalize().map { String(format: "%02x", $0) }.joined())+ }+}diff --git a/CodexBar/Models/ActivitySyncRecord.swift b/CodexBar/Models/ActivitySyncRecord.swiftindex 4d8aab4..f2eb593 100644--- a/CodexBar/Models/ActivitySyncRecord.swift+++ b/CodexBar/Models/ActivitySyncRecord.swift@@ -1,11 +1,14 @@import Foundationnonisolated struct SyncedActivity: Codable, Equatable {+ static let currentVersion = 1+ var version = Self.currentVersion+ var aggregationVersion = AggregationVersion.activity+ var sourceCheckpoint: ActivitySourceCheckpoint?+let date: Stringvar generationID: String?var eventCount: Int?- var sessionStartedCount: Int?- var sessionEndedCount: Int?var turnStartedCount: Int?var turnCompletedCount: Int?var turnAbortedCount: Int?@@ -16,7 +19,7 @@ nonisolated struct SyncedActivity: Codable, Equatable {var compactionCompletedCount: Int?var subagentStartedCount: Int?var subagentEndedCount: Int?- var sessionCount: Int?+ var threadCount: Int?var turnCount: Int?var projectCounts: [String: Int]var modelCounts: [String: Int]@@ -24,14 +27,8 @@ nonisolated struct SyncedActivity: Codable, Equatable {var metrics: ActivityMetrics {ActivityMetrics(startDate: date,- sessionCount: CountResolution.resolvedCount(- compactedCount: sessionCount,- fallback: sessionStartedCount ?? 0- ),- turnCount: CountResolution.resolvedCount(- compactedCount: turnCount,- fallback: turnCompletedCount ?? 0- ),+ threadCount: threadCount,+ turnCount: turnCount,toolStartedCount: toolStartedCount ?? 0,toolCompletedCount: toolCompletedCount ?? 0,approvalRequestedCount: approvalRequestedCount ?? 0,@@ -40,7 +37,7 @@ nonisolated struct SyncedActivity: Codable, Equatable {subagentStartedCount: subagentStartedCount ?? 0,subagentEndedCount: subagentEndedCount ?? 0,modelCounts: modelCounts,- turnAbortedCount: turnAbortedCount+ turnAbortedCount: turnAbortedCount ?? 0)}@@ -60,11 +57,10 @@ nonisolated struct SyncedActivity: Codable, Equatable {}private enum CodingKeys: String, CodingKey {+ case version, aggregationVersion, sourceCheckpointcase datecase generationIDcase eventCount- case sessionStartedCount- case sessionEndedCountcase turnStartedCountcase turnCompletedCountcase turnAbortedCount@@ -75,7 +71,7 @@ nonisolated struct SyncedActivity: Codable, Equatable {case compactionCompletedCountcase subagentStartedCountcase subagentEndedCount- case sessionCount+ case threadCountcase turnCountcase projectCountscase modelCounts@@ -85,11 +81,14 @@ nonisolated struct SyncedActivity: Codable, Equatable {extension SyncedActivity {nonisolated init(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self)+ version = try container.decode(Int.self, forKey: .version)+ try StorageVersion.require(version, current: Self.currentVersion, name: "ActivityAggregate")+ sourceCheckpoint = try container.decodeIfPresent(ActivitySourceCheckpoint.self, forKey: .sourceCheckpoint)+ aggregationVersion = try container.decode(Int.self, forKey: .aggregationVersion)+ try AggregationVersion.require(aggregationVersion, current: AggregationVersion.activity, name: "Activity")date = try container.decode(String.self, forKey: .date)generationID = try container.decodeIfPresent(String.self, forKey: .generationID)eventCount = try container.decodeIfPresent(Int.self, forKey: .eventCount)- sessionStartedCount = try container.decodeIfPresent(Int.self, forKey: .sessionStartedCount)- sessionEndedCount = try container.decodeIfPresent(Int.self, forKey: .sessionEndedCount)turnStartedCount = try container.decodeIfPresent(Int.self, forKey: .turnStartedCount)turnCompletedCount = try container.decodeIfPresent(Int.self, forKey: .turnCompletedCount)turnAbortedCount = try container.decodeIfPresent(Int.self, forKey: .turnAbortedCount)@@ -100,7 +99,7 @@ extension SyncedActivity {compactionCompletedCount = try container.decodeIfPresent(Int.self, forKey: .compactionCompletedCount)subagentStartedCount = try container.decodeIfPresent(Int.self, forKey: .subagentStartedCount)subagentEndedCount = try container.decodeIfPresent(Int.self, forKey: .subagentEndedCount)- sessionCount = try container.decodeIfPresent(Int.self, forKey: .sessionCount)+ threadCount = try container.decodeIfPresent(Int.self, forKey: .threadCount)turnCount = try container.decodeIfPresent(Int.self, forKey: .turnCount)projectCounts = try container.decodeIfPresent([String: Int].self, forKey: .projectCounts) ?? [:]modelCounts = try container.decodeIfPresent([String: Int].self, forKey: .modelCounts) ?? [:]diff --git a/CodexBar/Models/AppServerEventRecord.swift b/CodexBar/Models/AppServerEventRecord.swiftindex 266568e..23c404d 100644--- a/CodexBar/Models/AppServerEventRecord.swift+++ b/CodexBar/Models/AppServerEventRecord.swift@@ -1,26 +1,5 @@import Foundation-/// 白名单协议元数据, 原始线程身份与业务统计归属分开保存-nonisolated struct AppServerEventSource: Codable, Equatable {- let method: String- let threadID: String- var turnID: String?- var parentThreadID: String?- var rootThreadID: String?- var rootTurnID: String?- var itemID: String?- var itemType: String?- var itemStatus: String?- var agentThreadID: String?- var itemKind: String?- var requestID: String?- var reviewID: String?- var turnStatus: String?- var turnStartedAt: Date?- var turnCompletedAt: Date?- var durationMs: Double?-}-/// 统一日志的版本与类型边界, Token 快照不会作为活动进入计数nonisolated struct AppServerEventRecord: Codable, Equatable {enum Kind: String, Codable { case activity, tokenSnapshot, tokenObservation }@@ -29,7 +8,7 @@ nonisolated struct AppServerEventRecord: Codable, Equatable {let version: Intlet kind: Kindlet recordedAt: Date- let source: AppServerEventSource?+ let context: ActivityContext?private let activityPayload: ActivityRecord?let token: TokenTurn?let observation: TokenObservation?@@ -46,7 +25,7 @@ nonisolated struct AppServerEventRecord: Codable, Equatable {var activity: ActivityRecord? {guard var activity = activityPayload else { return nil }- activity.source = source+ activity.context = contextreturn activity}@@ -54,19 +33,19 @@ nonisolated struct AppServerEventRecord: Codable, Equatable {version = Self.currentVersionkind = .activityself.recordedAt = recordedAt- source = activity.source+ context = activity.contextvar payload = activity- payload.source = nil+ payload.context = nilactivityPayload = payloadtoken = nilobservation = nil}- init(token: TokenTurn, source: AppServerEventSource? = nil, recordedAt: Date) {+ init(token: TokenTurn, context: ActivityContext? = nil, recordedAt: Date) {version = Self.currentVersionkind = .tokenSnapshotself.recordedAt = recordedAt- self.source = source+ self.context = contextactivityPayload = nilself.token = tokenobservation = nil@@ -76,7 +55,7 @@ nonisolated struct AppServerEventRecord: Codable, Equatable {version = Self.currentVersionkind = .tokenObservationself.recordedAt = recordedAt- source = nil+ context = nilactivityPayload = niltoken = nilself.observation = observation@@ -90,7 +69,7 @@ nonisolated struct AppServerEventRecord: Codable, Equatable {}kind = try container.decode(Kind.self, forKey: .kind)recordedAt = try container.decode(Date.self, forKey: .recordedAt)- source = try container.decodeIfPresent(AppServerEventSource.self, forKey: .source)+ context = try container.decodeIfPresent(ActivityContext.self, forKey: .context)observation = try container.decodeIfPresent(TokenObservation.self, forKey: .observation)switch kind {case .activity:@@ -137,7 +116,7 @@ nonisolated struct AppServerEventRecord: Codable, Equatable {case versioncase kindcase recordedAt- case source+ case contextcase activityPayloadcase tokencase observationdiff --git a/CodexBar/Models/CodexAccountModels.swift b/CodexBar/Models/CodexAccountModels.swiftindex ea91ce3..19094db 100644--- a/CodexBar/Models/CodexAccountModels.swift+++ b/CodexBar/Models/CodexAccountModels.swift@@ -29,4 +29,16 @@ nonisolated struct CodexAccount: Decodable, Equatable {/// account/read 允许 account 为空, 由上层转换为`未登录`状态nonisolated struct AccountReadResponse: Decodable {let account: CodexAccount?++ init(account: CodexAccount?) {+ self.account = account+ }++ private enum CodingKeys: String, CodingKey { case account }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ // 缺字段是无效响应, 只有显式 null 才表示没有账户+ account = try container.decodeNil(forKey: .account) ? nil : container.decode(CodexAccount.self, forKey: .account)+ }}diff --git a/CodexBar/Models/CodexStatusError.swift b/CodexBar/Models/CodexStatusError.swiftindex df5ba50..2fea780 100644--- a/CodexBar/Models/CodexStatusError.swift+++ b/CodexBar/Models/CodexStatusError.swift@@ -10,6 +10,7 @@ nonisolated enum CodexStatusError: LocalizedError {case unsupportedMethodcase unsupportedVersion(minimum: String)case notLoggedIn+ case authenticationRequiredvar errorDescription: String? {switch self {@@ -25,6 +26,8 @@ nonisolated enum CodexStatusError: LocalizedError {String(localized: "codex-status.app-server.error.unsupported-method")case let .unsupportedVersion(minimum):String(localized: "codex-version.requirement", defaultValue: "\(minimum)")+ case .authenticationRequired:+ "Codex account authentication required"case .notLoggedIn:String(localized: "codex-status.account.error.not-logged-in")}@@ -33,7 +36,7 @@ nonisolated enum CodexStatusError: LocalizedError {/// codex app-server 未登录var isAuthenticationRequired: Bool {switch self {- case .notLoggedIn:+ case .notLoggedIn, .authenticationRequired:truedefault:serverErrorMessageContains("codex account authentication required")diff --git a/CodexBar/Models/CodexUsageModels.swift b/CodexBar/Models/CodexUsageModels.swiftindex 2fe3899..cccb41e 100644--- a/CodexBar/Models/CodexUsageModels.swift+++ b/CodexBar/Models/CodexUsageModels.swift@@ -13,14 +13,6 @@ nonisolated struct UsageSummary: Decodable, Equatable {let longestRunningTurnSec: Int?let longestStreakDays: Int?let peakDailyTokens: Int?-- var hasAvailableMetrics: Bool {- currentStreakDays != nil- || lifetimeTokens != nil- || longestRunningTurnSec != nil- || longestStreakDays != nil- || peakDailyTokens != nil- }}/// 单日 token bucket, startDate 使用 yyyy-MM-dd 作为稳定键@@ -39,10 +31,6 @@ nonisolated struct CodexUsageSnapshot: Equatable {tokensByDate != nil}- var hasAppServerData: Bool {- summary.hasAvailableMetrics || hasDailyUsageBuckets- }-init(summary: UsageSummary, dailyBuckets: [DailyUsageBucket]?) {self.summary = summarytokensByDate = dailyBuckets.map { buckets indiff --git a/CodexBar/Models/HistorySnapshot.swift b/CodexBar/Models/HistorySnapshot.swiftindex 36472f3..39c70c8 100644--- a/CodexBar/Models/HistorySnapshot.swift+++ b/CodexBar/Models/HistorySnapshot.swift@@ -3,12 +3,12 @@/// 热力图详情面板直接消费的每日统计nonisolated struct ActivityMetrics: Equatable {let startDate: String- let sessionCount: Int- let turnCount: Int- let toolCallCount: Int- let approvalRequestedCount: Int- let contextCompactionCount: Int- let subagentCount: Int+ let threadCount: Int?+ let turnCount: Int?+ let toolCallCount: Int?+ let approvalRequestedCount: Int?+ let contextCompactionCount: Int?+ let subagentCount: Int?let modelCounts: [String: Int]let turnAbortedCount: Int?@@ -23,17 +23,17 @@ nonisolated struct ActivityMetrics: Equatable {init(startDate: String,- sessionCount: Int,- turnCount: Int,- toolCallCount: Int,- approvalRequestedCount: Int,- contextCompactionCount: Int,- subagentCount: Int,+ threadCount: Int?,+ turnCount: Int?,+ toolCallCount: Int?,+ approvalRequestedCount: Int?,+ contextCompactionCount: Int?,+ subagentCount: Int?,modelCounts: [String: Int] = [:],turnAbortedCount: Int? = nil) {self.startDate = startDate- self.sessionCount = sessionCount+ self.threadCount = threadCountself.turnCount = turnCountself.toolCallCount = toolCallCountself.approvalRequestedCount = approvalRequestedCount@@ -43,10 +43,22 @@ nonisolated struct ActivityMetrics: Equatable {self.turnAbortedCount = turnAbortedCount}+ static func unavailable(startDate: String) -> ActivityMetrics {+ ActivityMetrics(+ startDate: startDate,+ threadCount: nil,+ turnCount: nil,+ toolCallCount: nil,+ approvalRequestedCount: nil,+ contextCompactionCount: nil,+ subagentCount: nil+ )+ }+static func empty(startDate: String) -> ActivityMetrics {ActivityMetrics(startDate: startDate,- sessionCount: 0,+ threadCount: 0,turnCount: 0,toolCallCount: 0,approvalRequestedCount: 0,@@ -57,25 +69,25 @@ nonisolated struct ActivityMetrics: Equatable {init(startDate: String,- sessionCount: Int,- turnCount: Int,- toolStartedCount: Int,- toolCompletedCount: Int,- approvalRequestedCount: Int,- compactionStartedCount: Int,- compactionCompletedCount: Int,- subagentStartedCount: Int,- subagentEndedCount: Int,+ threadCount: Int?,+ turnCount: Int?,+ toolStartedCount: Int?,+ toolCompletedCount: Int?,+ approvalRequestedCount: Int?,+ compactionStartedCount: Int?,+ compactionCompletedCount: Int?,+ subagentStartedCount: Int?,+ subagentEndedCount: Int?,modelCounts: [String: Int],turnAbortedCount: Int? = nil) {self.startDate = startDate- self.sessionCount = sessionCount+ self.threadCount = threadCountself.turnCount = turnCount- toolCallCount = max(toolStartedCount, toolCompletedCount)+ toolCallCount = toolStartedCount.flatMap { lhs in toolCompletedCount.map { max(lhs, $0) } }self.approvalRequestedCount = approvalRequestedCount- contextCompactionCount = max(compactionStartedCount, compactionCompletedCount)- subagentCount = max(subagentStartedCount, subagentEndedCount)+ contextCompactionCount = compactionStartedCount.flatMap { lhs in compactionCompletedCount.map { max(lhs, $0) } }+ subagentCount = subagentStartedCount.flatMap { lhs in subagentEndedCount.map { max(lhs, $0) } }self.modelCounts = modelCountsself.turnAbortedCount = turnAbortedCount}@@ -83,12 +95,12 @@ nonisolated struct ActivityMetrics: Equatable {func adding(_ other: ActivityMetrics) -> ActivityMetrics {ActivityMetrics(startDate: startDate,- sessionCount: sessionCount + other.sessionCount,- turnCount: turnCount + other.turnCount,- toolCallCount: toolCallCount + other.toolCallCount,- approvalRequestedCount: approvalRequestedCount + other.approvalRequestedCount,- contextCompactionCount: contextCompactionCount + other.contextCompactionCount,- subagentCount: subagentCount + other.subagentCount,+ threadCount: threadCount.flatMap { lhs in other.threadCount.map { lhs + $0 } },+ turnCount: turnCount.flatMap { lhs in other.turnCount.map { lhs + $0 } },+ toolCallCount: toolCallCount.flatMap { lhs in other.toolCallCount.map { lhs + $0 } },+ approvalRequestedCount: approvalRequestedCount.flatMap { lhs in other.approvalRequestedCount.map { lhs + $0 } },+ contextCompactionCount: contextCompactionCount.flatMap { lhs in other.contextCompactionCount.map { lhs + $0 } },+ subagentCount: subagentCount.flatMap { lhs in other.subagentCount.map { lhs + $0 } },modelCounts: Self.mergedCounts(modelCounts, other.modelCounts),turnAbortedCount: turnAbortedCount.flatMap { lhs in other.turnAbortedCount.map { lhs + $0 } })@@ -110,6 +122,8 @@ nonisolated struct ActivityMetrics: Equatable {nonisolated struct HistorySnapshot: Equatable {let dailyMetrics: [ActivityMetrics]var tokenUsageByDate: [String: TokenUsage] = [:]+ var unavailableActivityDates = Set<String>()+ var isActivityComplete = truestatic let empty = HistorySnapshot(dailyMetrics: [])@@ -125,7 +139,8 @@ nonisolated struct HistorySnapshot: Equatable {) {var metricsByDate = [String: ActivityMetrics]()- let localByDate = Dictionary(uniqueKeysWithValues: localAggregates.map { ($0.date, $0) })+ let localByDate = Dictionary(localAggregates.map { ($0.date, $0) }, uniquingKeysWith: { _, newer in newer })+ unavailableActivityDates = Set(Dictionary(grouping: localAggregates, by: \.date).filter { $0.value.count > 1 }.keys)let currentDeviceRecords = syncedRecords.filter { $0.deviceID == currentDeviceID }let otherDeviceRecords = syncedRecords.filter { $0.deviceID != currentDeviceID }@@ -158,17 +173,13 @@ nonisolated struct HistorySnapshot: Equatable {local.syncedAggregate.matchesRemoteSource($0.daily)}- guard remoteRecords.isEmpty || local.generationStartedEmpty || matchingIndex != nil else {- merge(remoteRecords, into: &metricsByDate)- return- }-for (index, record) in remoteRecords.enumerated() where index != matchingIndex {merge(record.daily.metrics, into: &metricsByDate)}if let matchingIndex,- (remoteRecords[matchingIndex].daily.eventCount ?? 0) > (local.eventCount ?? 0) {+ remoteRecords[matchingIndex].daily.aggregationVersion > local.aggregationVersion+ || (remoteRecords[matchingIndex].daily.sourceCheckpoint?.byteCount ?? 0) > (local.sourceCheckpoint?.byteCount ?? 0) {merge(remoteRecords[matchingIndex].daily.metrics, into: &metricsByDate)} else {merge(local.metrics, into: &metricsByDate)diff --git a/CodexBar/Models/StorageVersion.swift b/CodexBar/Models/StorageVersion.swiftnew file mode 100644index 0000000..54cbfcd--- /dev/null+++ b/CodexBar/Models/StorageVersion.swift@@ -0,0 +1,64 @@+import Foundation++/// 格式不支持与损坏分开传递, 调用方不得将版本错误转换为空数据+nonisolated enum StorageCompatibilityError: Error, Equatable {+ case unsupportedFormat(String, Int)+ case unsupportedAlgorithm(String, Int)+ case incompleteSource+ case sourceConflict+}++nonisolated enum StorageVersion {+ private struct Header: Decodable { let version: Int }++ static func validate(_ data: Data, current: Int, name: String) throws {+ try require(JSONDecoder().decode(Header.self, from: data).version, current: current, name: name)+ }++ static func require(_ version: Int, current: Int, name: String) throws {+ guard version == current else { throw StorageCompatibilityError.unsupportedFormat(name, version) }+ }++ static func validateExistingFile(at url: URL, current: Int, name: String) throws {+ do {+ try validate(Data(contentsOf: url), current: current, name: name)+ } catch let error as CocoaError where error.code == .fileReadNoSuchFile {+ return+ }+ }+}++nonisolated enum AggregationVersion {+ static let activity = 1+ static let tokens = 1++ static func require(_ version: Int, current: Int, name: String) throws {+ guard version > 0, version <= current else { throw StorageCompatibilityError.unsupportedAlgorithm(name, version) }+ }+}++/// 每段以排他的源边界结束, 连续使用同一算法时只扩展末段+nonisolated struct AggregationRange: Codable, Equatable {+ var version: Int+ var end: UInt64++ static func appending(to ranges: [Self], version: Int, end: UInt64) -> [Self] {+ var result = ranges+ if result.last?.version == version {+ result[result.count - 1].end = end+ } else {+ result.append(Self(version: version, end: end))+ }+ return result+ }++ static func validate(_ ranges: [Self], end: UInt64, current: Int) throws {+ var previous: UInt64 = 0+ for range in ranges {+ try AggregationVersion.require(range.version, current: current, name: "AggregationRange")+ guard range.end > previous, range.end <= end else { throw StorageCompatibilityError.incompleteSource }+ previous = range.end+ }+ guard ranges.isEmpty || previous == end else { throw StorageCompatibilityError.incompleteSource }+ }+}diff --git a/CodexBar/Models/TokenHistory.swift b/CodexBar/Models/TokenHistory.swiftindex 3cc9cfe..b07d844 100644--- a/CodexBar/Models/TokenHistory.swift+++ b/CodexBar/Models/TokenHistory.swift@@ -3,6 +3,7 @@ import Foundation/// 一条线程轮次的累计快照, 身份只保存哈希, 不保存对话正文或原始 IDnonisolated struct TokenTurn: Codable, Equatable, Identifiable {+ var aggregationVersion = AggregationVersion.tokenslet id: Stringvar rootID: Stringvar startedAt: Date?@@ -24,8 +25,10 @@ nonisolated struct TokenTurn: Codable, Equatable, Identifiable {generationID: String = "initial",ancestorIDs: Set<String> = [],checkpoint: [String: TokenObservationCheckpoint] = [:],- hasConflict: Bool = false+ hasConflict: Bool = false,+ aggregationVersion: Int = AggregationVersion.tokens) {+ self.aggregationVersion = aggregationVersionself.id = idself.rootID = rootIDself.startedAt = startedAt.map(JSONLines.storageDate)@@ -39,12 +42,32 @@ nonisolated struct TokenTurn: Codable, Equatable, Identifiable {}private enum CodingKeys: String, CodingKey {- case id, rootID, startedAt, updatedAt, usage, rebuiltAt+ case id, rootID, startedAt, updatedAt, usage, rebuiltAt, aggregationVersioncase generationID, ancestorIDs, checkpoint, hasConflict}+ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ aggregationVersion = try container.decode(Int.self, forKey: .aggregationVersion)+ try AggregationVersion.require(aggregationVersion, current: AggregationVersion.tokens, name: "Tokens")+ id = try container.decode(String.self, forKey: .id)+ rootID = try container.decode(String.self, forKey: .rootID)+ startedAt = try container.decodeIfPresent(Date.self, forKey: .startedAt)+ updatedAt = try container.decode(Date.self, forKey: .updatedAt)+ usage = try container.decodeIfPresent(TokenUsage.self, forKey: .usage)+ rebuiltAt = try container.decodeIfPresent(Date.self, forKey: .rebuiltAt)+ generationID = try container.decode(String.self, forKey: .generationID)+ ancestorIDs = try container.decode(Set<String>.self, forKey: .ancestorIDs)+ checkpoint = try container.decode([String: TokenObservationCheckpoint].self, forKey: .checkpoint)+ hasConflict = try container.decode(Bool.self, forKey: .hasConflict)+ guard usage == nil || !checkpoint.isEmpty else {+ throw DecodingError.dataCorruptedError(forKey: .checkpoint, in: container, debugDescription: "Token usage requires an observation checkpoint")+ }+ }+func encode(to encoder: Encoder) throws {var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(aggregationVersion, forKey: .aggregationVersion)try container.encode(id, forKey: .id)try container.encode(rootID, forKey: .rootID)try container.encodeIfPresent(startedAt, forKey: .startedAt)@@ -74,8 +97,11 @@ nonisolated struct TokenTurn: Codable, Equatable, Identifiable {return String(bytes: result, encoding: .utf8) ?? ""}- func merging(_ other: Self) -> Self {+ func merging(_ other: Self) throws -> Self {precondition(id == other.id)+ try AggregationVersion.require(aggregationVersion, current: AggregationVersion.tokens, name: "Tokens")+ try AggregationVersion.require(other.aggregationVersion, current: AggregationVersion.tokens, name: "Tokens")+ guard rootID == other.rootID else { throw TokenCacheError.rootIdentityConflict }if generationID != other.generationID {if ancestorIDs.contains(other.generationID) {return incorporatingUncoveredObservations(from: other)@@ -102,23 +128,11 @@ nonisolated struct TokenTurn: Codable, Equatable, Identifiable {}}var result = self- if rootID == id {- result.rootID = other.rootID- }+ result.aggregationVersion = max(aggregationVersion, other.aggregationVersion)if let date = other.startedAt {result.startedAt = min(startedAt ?? date, date)}result.updatedAt = max(updatedAt, other.updatedAt)- if let candidate = other.usage, candidate.isValid {- if let current = usage {- // 同一累计快照的副本和较短扫描都不能重复累加或覆盖更完整的数据- if Self.usageOrder(candidate).lexicographicallyPrecedes(Self.usageOrder(current)) == false {- result.usage = candidate- }- } else {- result.usage = candidate- }- }return result}@@ -133,6 +147,7 @@ nonisolated struct TokenTurn: Codable, Equatable, Identifiable {ancestorIDs.insert(generationID)generationID = UUID().uuidString.lowercased()rebuiltAt = JSONLines.storageDate(date)+ aggregationVersion = AggregationVersion.tokens}private func incorporatingUncoveredObservations(from old: Self) -> Self {@@ -148,6 +163,7 @@ nonisolated struct TokenTurn: Codable, Equatable, Identifiable {let usage = result.usage?.adding(delta), usage.isValid else { return conflicting(with: old) }result.usage = usageresult.checkpoint[stream] = incoming+ result.aggregationVersion = max(result.aggregationVersion, old.aggregationVersion)result.updatedAt = max(result.updatedAt, old.updatedAt)}return result@@ -184,14 +200,15 @@ nonisolated struct TokenTurn: Codable, Equatable, Identifiable {return result}- static func merged(_ records: [Self]) -> [String: Self] {- records.reduce(into: [:]) { result, record in- result[record.id] = result[record.id]?.merging(record) ?? record+ static func merged(_ records: [Self]) throws -> [String: Self] {+ try records.reduce(into: [:]) { result, record in+ result[record.id] = try result[record.id]?.merging(record) ?? record}}static func dailyUsage(_ records: [Self], now: Date = Date()) -> [String: TokenUsage] {- let byID = merged(records)+ // 根身份矛盾时无法证明日期归属, 不展示不完整合计+ guard let byID = try? merged(records) else { return [:] }let cutoff = HistoryStorage.retentionCutoffDate(today: now)var result: [String: TokenUsage] = [:]var invalidDates: Set<String> = []@@ -246,7 +263,7 @@ nonisolated struct TokenTurn: Codable, Equatable, Identifiable {id: exportedID, rootID: rootID == id ? exportedID : hash(rootID),startedAt: startedAt, updatedAt: updatedAt, usage: usage, rebuiltAt: rebuiltAt,generationID: generationID, ancestorIDs: ancestorIDs,- checkpoint: checkpoint, hasConflict: hasConflict+ checkpoint: checkpoint, hasConflict: hasConflict, aggregationVersion: aggregationVersion)}@@ -276,16 +293,38 @@ nonisolated struct TokenHistoryBaseline {self.turns = turns}- func replacement(for local: TokenTurn) -> TokenTurn? {+ func contains(_ local: TokenTurn) -> Bool {let exported = local.pseudonymized(salt: salt)- guard var remote = turns[exported.id], remote.rootID == exported.rootID else { return nil }- remote = exported.merging(remote)- guard remote != exported else { return nil }+ return turns[exported.id]?.rootID == exported.rootID+ }++ func acceptsRecovery(_ local: TokenTurn) -> Bool {+ let exported = local.pseudonymized(salt: salt)+ guard let remote = turns[exported.id] else { return true }+ return remote.rootID == exported.rootID && !local.hasConflict && !remote.hasConflict+ && exported.covers(remote.checkpoint) && (remote.usage == nil || local.usage != nil)+ }++ func replacement(for local: TokenTurn, recovering: Bool = false, now: Date = Date()) -> TokenTurn? {+ guard !recovering || acceptsRecovery(local) else { return nil }+ let exported = local.pseudonymized(salt: salt)+ guard let remote = turns[exported.id], remote.rootID == exported.rootID else { return nil }+ if recovering, !local.hasConflict, !remote.hasConflict,+ exported.covers(remote.checkpoint), remote.usage == nil || local.usage != nil,+ !local.ancestorIDs.contains(remote.generationID),+ local.aggregationVersion != remote.aggregationVersion || local.usage != remote.usage {+ var corrected = local+ corrected.generationID = remote.generationID+ corrected.ancestorIDs.formUnion(remote.ancestorIDs)+ corrected.startNewGeneration(at: now)+ return corrected+ }+ guard let merged = try? exported.merging(remote), merged != exported else { return nil }return TokenTurn(- id: local.id, rootID: local.rootID, startedAt: remote.startedAt ?? local.startedAt,- updatedAt: remote.updatedAt, usage: remote.usage, rebuiltAt: remote.rebuiltAt,- generationID: remote.generationID, ancestorIDs: remote.ancestorIDs,- checkpoint: remote.checkpoint, hasConflict: remote.hasConflict+ id: local.id, rootID: local.rootID, startedAt: merged.startedAt ?? local.startedAt,+ updatedAt: merged.updatedAt, usage: merged.usage, rebuiltAt: merged.rebuiltAt,+ generationID: merged.generationID, ancestorIDs: merged.ancestorIDs,+ checkpoint: merged.checkpoint, hasConflict: merged.hasConflict, aggregationVersion: merged.aggregationVersion)}}@@ -293,19 +332,67 @@ nonisolated struct TokenHistoryBaseline {nonisolated struct TokenObservationCheckpoint: Codable, Equatable {var sequence: Int64var usage: TokenUsage+ var aggregationRanges: [AggregationRange] = []++ private enum CodingKeys: String, CodingKey { case sequence, usage, aggregationRanges }++ init(sequence: Int64, usage: TokenUsage, aggregationRanges: [AggregationRange] = []) {+ self.sequence = sequence+ self.usage = usage+ self.aggregationRanges = aggregationRanges+ }++ init(from decoder: Decoder) throws {+ let values = try decoder.container(keyedBy: CodingKeys.self)+ sequence = try values.decode(Int64.self, forKey: .sequence)+ usage = try values.decode(TokenUsage.self, forKey: .usage)+ aggregationRanges = try values.decodeIfPresent([AggregationRange].self, forKey: .aggregationRanges) ?? []+ guard sequence > 0, usage.isValid else { throw StorageCompatibilityError.incompleteSource }+ try AggregationRange.validate(aggregationRanges, end: UInt64(sequence), current: AggregationVersion.tokens)+ }+}++/// 原始身份与时间不依赖聚合结果, 算法升级后仍可独立重放+nonisolated struct TokenObservationIdentity: Codable, Equatable {+ let id: String+ let rootID: String+ let startedAt: Date?+ let updatedAt: Date++ init(_ turn: TokenTurn) {+ id = turn.id+ rootID = turn.rootID+ startedAt = turn.startedAt+ updatedAt = turn.updatedAt+ }++ var emptyTurn: TokenTurn {+ TokenTurn(id: id, rootID: rootID, startedAt: startedAt, updatedAt: updatedAt)+ }}/// streamID 是每次采集连续区间生成的随机身份, 不包含设备或原始线程信息nonisolated struct TokenObservation: Codable, Equatable {- let turn: TokenTurn+ let turn: TokenObservationIdentitylet rootStartedAt: Date?let streamID: Stringlet sequence: Int64let previous: TokenUsagelet current: TokenUsage+ init(turn: TokenTurn, rootStartedAt: Date?, streamID: String, sequence: Int64, previous: TokenUsage, current: TokenUsage) {+ self.turn = TokenObservationIdentity(turn)+ self.rootStartedAt = rootStartedAt+ self.streamID = streamID+ self.sequence = sequence+ self.previous = previous+ self.current = current+ }+func applying(to existing: TokenTurn?) throws -> TokenTurn {- var result = existing ?? turn+ var result = existing ?? turn.emptyTurn+ guard result.id == turn.id, result.rootID == turn.rootID else { throw TokenCacheError.rootIdentityConflict }+ try AggregationVersion.require(result.aggregationVersion, current: AggregationVersion.tokens, name: "Tokens")let boundary = result.checkpoint[streamID]if let boundary, boundary.sequence >= sequence {return result@@ -321,7 +408,16 @@ nonisolated struct TokenObservation: Codable, Equatable {}result.usage = usage}- result.checkpoint[streamID] = TokenObservationCheckpoint(sequence: sequence, usage: observed)+ let previousRanges = boundary.map {+ $0.aggregationRanges.isEmpty+ ? [AggregationRange(version: result.aggregationVersion, end: UInt64($0.sequence))]+ : $0.aggregationRanges+ } ?? []+ result.checkpoint[streamID] = TokenObservationCheckpoint(+ sequence: sequence, usage: observed,+ aggregationRanges: AggregationRange.appending(to: previousRanges, version: AggregationVersion.tokens, end: UInt64(sequence))+ )+ result.aggregationVersion = AggregationVersion.tokensresult.updatedAt = max(result.updatedAt, turn.updatedAt)return result}diff --git a/CodexBar/Models/UsageHeatmapDay.swift b/CodexBar/Models/UsageHeatmapDay.swiftindex b081342..572c8aa 100644--- a/CodexBar/Models/UsageHeatmapDay.swift+++ b/CodexBar/Models/UsageHeatmapDay.swift@@ -36,14 +36,11 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {static func grid(usage: CodexUsageSnapshot?,history: HistorySnapshot,- showsActivity: Bool,columnCount: Int,today: Date) -> [UsageHeatmapDay?] {let todayTokenCount = usage?.tokenCount(on: today)let hasDailyUsageBuckets = usage?.hasDailyUsageBuckets == true- // 活动统计可见时包含今天, 仅展示 Token 时等待当天 bucket 返回- let endingDaysAgo = showsActivity || todayTokenCount != nil ? 0 : 1let historyByDate = history.dailyMetrics.reduce(into: [String: ActivityMetrics]()) { result, metrics inresult[metrics.startDate] = metrics}@@ -51,7 +48,6 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {return CodexWeekGrid.dates(columnCount: columnCount,- endingDaysAgo: endingDaysAgo,today: today).map { date -> UsageHeatmapDay? in@@ -72,7 +68,8 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {return UsageHeatmapDay(startDate: startDate,tokenState: tokenState,- history: historyByDate[startDate] ?? .empty(startDate: startDate),+ history: history.unavailableActivityDates.contains(startDate) ? .unavailable(startDate: startDate)+ : historyByDate[startDate] ?? (history.isActivityComplete ? .empty(startDate: startDate) : .unavailable(startDate: startDate)),tokenUsage: history.tokenUsageByDate[startDate])}diff --git a/CodexBar/Resources/AppIcon.icon/Assets/AppIcon.png b/CodexBar/Resources/AppIcon.icon/Assets/AppIcon.pngdeleted file mode 100644index 4c77a8d..0000000Binary files a/CodexBar/Resources/AppIcon.icon/Assets/AppIcon.png and /dev/null differdiff --git a/CodexBar/Resources/AppIcon.icon/Assets/CodexBar.png b/CodexBar/Resources/AppIcon.icon/Assets/CodexBar.pngnew file mode 100644index 0000000..28f6cccBinary files /dev/null and b/CodexBar/Resources/AppIcon.icon/Assets/CodexBar.png differdiff --git a/CodexBar/Resources/AppIcon.icon/icon.json b/CodexBar/Resources/AppIcon.icon/icon.jsonindex 8f5a0d5..3302c09 100644--- a/CodexBar/Resources/AppIcon.icon/icon.json+++ b/CodexBar/Resources/AppIcon.icon/icon.json@@ -1,15 +1,13 @@{"color-space-for-untagged-svg-colors" : "display-p3",- "fill" : {- "solid" : "extended-gray:1.00000,1.00000"- },+ "fill" : "automatic","groups" : [{"layers" : [{"glass" : true,- "image-name" : "AppIcon.png",- "name" : "AppIcon"+ "image-name" : "CodexBar.png",+ "name" : "CodexBar"}],"shadow" : {@@ -18,11 +16,13 @@},"translucency" : {"enabled" : true,- "value" : 0.5+ "value" : 0.3}}],"supported-platforms" : {- "squares" : "shared"+ "squares" : [+ "macOS"+ ]}}\ No newline at end of filediff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstringsindex dd081eb..334aef1 100644--- a/CodexBar/Resources/Localizable.xcstrings+++ b/CodexBar/Resources/Localizable.xcstrings@@ -70,7 +70,7 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Completed: %lld"+ "value" : "Completed %lld"}},"zh-Hans" : {@@ -86,7 +86,7 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Stopped: %lld"+ "value" : "Stopped %lld"}},"zh-Hans" : {@@ -102,7 +102,7 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Running: %lld"+ "value" : "Running %lld"}},"zh-Hans" : {@@ -118,7 +118,7 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Waiting: %lld"+ "value" : "Waiting %lld"}},"zh-Hans" : {@@ -401,22 +401,6 @@}}},- "activity.anonymous.keep-awake-exclusion" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Anonymous tasks do not prevent sleep"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "匿名任务不参与防睡眠"- }- }- }- },"activity.duration.elapsed" : {"localizations" : {"en" : {@@ -817,70 +801,6 @@}}},- "activity.live.approval-aborted" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Auto-approval aborted"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "自动审批已中止"- }- }- }- },- "activity.live.approval-approved" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Auto-approved"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "自动审批已通过"- }- }- }- },- "activity.live.approval-denied" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Auto-denied"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "自动审批未通过"- }- }- }- },- "activity.live.approval-timeout" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Auto-approval timed out"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "自动审批已超时"- }- }- }- },"activity.live.auth-recovery-ended" : {"localizations" : {"en" : {@@ -897,22 +817,6 @@}}},- "activity.live.auto-approval" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Reviewing"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "正在自动审批"- }- }- }- },"activity.live.buffering" : {"localizations" : {"en" : {@@ -1169,22 +1073,6 @@}}},- "activity.live.connecting-tool" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Starting MCP"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "正在启动 MCP 服务"- }- }- }- },"activity.live.diff-updated" : {"localizations" : {"en" : {@@ -1196,7 +1084,7 @@"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "改动详情已更新"+ "value" : "变更详情已更新"}}}@@ -1249,38 +1137,6 @@}}},- "activity.live.environment-connected" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Environment connected"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "已连接执行环境"- }- }- }- },- "activity.live.environment-disconnected" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Environment disconnected"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "已断开执行环境连接"- }- }- }- },"activity.live.failed" : {"localizations" : {"en" : {@@ -1441,22 +1297,6 @@}}},- "activity.live.idle" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "No tasks"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "暂无任务"- }- }- }- },"activity.live.image-completed" : {"localizations" : {"en" : {@@ -1665,22 +1505,6 @@}}},- "activity.live.planning" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Planning"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "正在制定计划"- }- }- }- },"activity.live.processing" : {"localizations" : {"en" : {@@ -1692,7 +1516,7 @@"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "正在处理任务"+ "value" : "正在处理"}}}@@ -1772,7 +1596,7 @@"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "正在回复"+ "value" : "正在回答"}}}@@ -2006,13 +1830,13 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Using web tool"+ "value" : "Browsing the web"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "正在使用网页工具"+ "value" : "正在浏览网页"}}}@@ -2124,7 +1948,7 @@"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "等待回应服务请求"+ "value" : "等待回应请求"}}}@@ -2145,22 +1969,6 @@}}},- "activity.live.waiting-verification" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Awaiting verification"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "等待用户验证"- }- }- }- },"activity.relative.completed-minutes-ago" : {"localizations" : {"en" : {@@ -2657,22 +2465,6 @@}}},- "codex-status.daemon.error.unavailable" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Codex Daemon is unavailable"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "Codex 后台服务不可用"- }- }- }- },"codex-tui-notifications.error.read-failed" : {"localizations" : {"en" : {@@ -3302,13 +3094,13 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Helper validation failed. Reinstall CodexBar"+ "value" : "CodexBar Helper is invalid"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Helper 组件或配置异常, 请重新安装 CodexBar"+ "value" : "CodexBar Helper 组件或配置异常"}}}@@ -3318,13 +3110,13 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Helper incomplete. Reinstall CodexBar"+ "value" : "CodexBar Helper is missing"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "CodexBar Helper 组件或配置丢失, 请重新安装 CodexBar"+ "value" : "CodexBar Helper 组件或配置丢失"}}}@@ -3430,13 +3222,13 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Allow CodexBar to run in the background"+ "value" : "Allow CodexBar Helper to run in the background"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "需要授权允许 CodexBar 后台运行"+ "value" : "需要授权允许 CodexBar Helper 后台运行"}}}@@ -3500,7 +3292,7 @@"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "权限请求"+ "value" : "权限审批"}}}@@ -5409,6 +5201,22 @@}}},+ "settings.general.launch-at-login-authorization-required" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Allow CodexBar to run in the background"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "需要授权允许 CodexBar 后台运行"+ }+ }+ }+ },"settings.general.launch-at-login-failed" : {"localizations" : {"en" : {@@ -6497,22 +6305,6 @@}}},- "usage.heatmap.no-data" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "No daily usage data"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "暂无日用量数据"- }- }- }- },"usage.heatmap.past-weeks" : {"localizations" : {"en" : {diff --git a/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift b/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swiftindex f1b6fe8..0f3b7f6 100644--- a/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift+++ b/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift@@ -72,18 +72,8 @@ nonisolated extension ActivityLiveLabel {String(localized: "activity.live.agent-waiting")case "answering":String(localized: "activity.live.answering")- case "approval-aborted":- String(localized: "activity.live.approval-aborted")- case "approval-approved":- String(localized: "activity.live.approval-approved")- case "approval-denied":- String(localized: "activity.live.approval-denied")- case "approval-timeout":- String(localized: "activity.live.approval-timeout")case "auth-recovery-ended":String(localized: "activity.live.auth-recovery-ended")- case "auto-approval":- String(localized: "activity.live.auto-approval")case "buffering":String(localized: "activity.live.buffering")case "calling-tool":@@ -112,8 +102,6 @@ nonisolated extension ActivityLiveLabel {String(localized: "activity.live.compaction-completed")case "connecting":String(localized: "activity.live.connecting")- case "connecting-tool":- String(localized: "activity.live.connecting-tool")case "diff-updated":String(localized: "activity.live.diff-updated")case "editing":@@ -122,10 +110,6 @@ nonisolated extension ActivityLiveLabel {String(localized: "activity.live.elapsed-running")case "elapsed-waiting":String(localized: "activity.live.elapsed-waiting")- case "environment-connected":- String(localized: "activity.live.environment-connected")- case "environment-disconnected":- String(localized: "activity.live.environment-disconnected")case "failed":String(localized: "activity.live.failed")case "file-completed":@@ -146,8 +130,6 @@ nonisolated extension ActivityLiveLabel {String(localized: "activity.live.hook-failed")case "hook-stopped":String(localized: "activity.live.hook-stopped")- case "idle":- String(localized: "activity.live.idle")case "image-completed":String(localized: "activity.live.image-completed")case "image-declined":@@ -166,8 +148,6 @@ nonisolated extension ActivityLiveLabel {String(localized: "activity.live.plan-step-completed")case "plan-updated":String(localized: "activity.live.plan-updated")- case "planning":- String(localized: "activity.live.planning")case "processing":String(localized: "activity.live.processing")case "recent-event":@@ -222,8 +202,6 @@ nonisolated extension ActivityLiveLabel {String(localized: "activity.live.waiting-service")case "waiting-user":String(localized: "activity.live.waiting-user")- case "waiting-verification":- String(localized: "activity.live.waiting-verification")default:String(localized: "activity.live.processing")}diff --git a/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift b/CodexBar/Services/Activity/ActivityLivePresentation+Items.swiftindex 8c862d1..a1af358 100644--- a/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift+++ b/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift@@ -3,23 +3,27 @@ import Foundationnonisolated extension ActivityItem {var liveLabel: ActivityLiveLabel? {switch type {- case "reasoning": ActivityLiveLabel("thinking")- case "agentMessage":+ case .reasoning: ActivityLiveLabel("thinking")+ case .agentMessage:ActivityLiveLabel(phase == "final_answer" ? "answering" : phase == "commentary" ? "commentary" : "replying")- case "plan": ActivityLiveLabel("planning")- case "contextCompaction": ActivityLiveLabel("compacting")- case "commandExecution": commandLabel- case "fileChange": ActivityLiveLabel("editing")- case "webSearch": ActivityLiveLabel(webLabel)- case "imageView": ActivityLiveLabel("viewing-image")- case "imageGeneration": ActivityLiveLabel("generating-image")- case "sleep": ActivityLiveLabel("sleeping")- case "collabAgentToolCall": ActivityLiveLabel(ActivityDisplayFormat.agentAction(tool: tool).statusKey)- case "mcpToolCall", "dynamicToolCall": ActivityLiveLabel("calling-tool", detail: tool)+ case .contextCompaction: ActivityLiveLabel("compacting")+ case .commandExecution: commandLabel+ case .fileChange: ActivityLiveLabel("editing")+ case .webSearch: ActivityLiveLabel(webLabel)+ case .imageView: ActivityLiveLabel("viewing-image")+ case .imageGeneration: ActivityLiveLabel("generating-image")+ case .sleep: ActivityLiveLabel("sleeping")+ case .collabAgentToolCall: ActivityLiveLabel(ActivityDisplayFormat.agentAction(tool: tool).statusKey)+ case .mcpToolCall, .dynamicToolCall: ActivityLiveLabel("calling-tool", detail: toolDisplayName)default: nil}}+ private var toolDisplayName: String? {+ guard type == .mcpToolCall, let server, !server.isEmpty, let tool, !tool.isEmpty else { return tool }+ return server + "." + tool+ }+private var commandLabel: ActivityLiveLabel {let types = Set((commandActions ?? []).map(\.type))let actions = orderedCommandActions@@ -49,34 +53,34 @@ nonisolated extension ActivityItem {}var liveCompletionLabel: ActivityLiveLabel? {- if type == "subAgentActivity" {+ if type == .subAgentActivity {return ["started": "agent-started", "completed": "agent-completed", "interrupted": "agent-interrupted"][kind ?? ""].map { ActivityLiveLabel($0) }}- if type == "contextCompaction" {+ if type == .contextCompaction {return ActivityLiveLabel("compaction-completed")}- if type == "collabAgentToolCall", agentsStates?.values.contains(where: { $0.status == "errored" }) == true {+ if type == .collabAgentToolCall, agentsStates?.values.contains(where: { $0.status == "errored" }) == true {return ActivityLiveLabel("agent-failed")}guard isToolCall else { return nil }- let prefix = type == "fileChange" ? "file" : type == "imageGeneration" ? "image" : "tool"+ let prefix = type == .fileChange ? "file" : type == .imageGeneration ? "image" : "tool"let outcome: Stringif status == "declined" {outcome = "declined"} else if status == "failed" || success == false {outcome = "failed"- } else if status == "completed" || success == true || ["webSearch", "imageView", "sleep"].contains(type) {+ } else if status == "completed" || success == true || [.webSearch, .imageView, .sleep].contains(type) {outcome = "completed"} else {return nil}let detail = switch type {- case "commandExecution": commandActionDetail- case "collabAgentToolCall": String(localized: ActivityDisplayFormat.agentAction(tool: tool).action)+ case .commandExecution: commandActionDetail+ case .collabAgentToolCall: String(localized: ActivityDisplayFormat.agentAction(tool: tool).action)default: toolDisplayName}- if detail != nil, type == "commandExecution" || type == "collabAgentToolCall" {+ if detail != nil, type == .commandExecution || type == .collabAgentToolCall {return ActivityLiveLabel("action-" + outcome, detail: detail)}return ActivityLiveLabel(prefix + "-" + outcome, detail: prefix == "tool" ? detail : nil)@@ -95,25 +99,29 @@ nonisolated extension ActivityDisplayFormat {return ActivityLiveLabel("actions-" + actions.joined(separator: "-")).text}- static func agentAction(tool: String?) -> (statusKey: String, action: LocalizedStringResource) {+ /// 使用命名类型避免编译器遗漏 switch 元组分支中的本地化引用+ nonisolated struct AgentAction {+ let statusKey: String+ let action: LocalizedStringResource+ }++ static func agentAction(tool: String?) -> AgentAction {switch tool {- case "spawnAgent": ("agent-starting", "activity.action.start-subagent")- case "sendInput", "followupTask": ("agent-assigning", "activity.action.assign-subagent")- case "sendMessage": ("agent-contacting", "activity.action.message-subagent")- case "resumeAgent": ("agent-resuming", "activity.action.resume-subagent")- case "wait": ("agent-waiting", "activity.action.wait-subagent")- case "interruptAgent": ("agent-interrupting", "activity.action.interrupt-subagent")- case "closeAgent": ("agent-closing", "activity.action.close-subagent")- case "listAgents": ("agent-querying", "activity.action.query-subagent")- default: ("agent-coordinating", "activity.action.coordinate-subagents")+ case "spawnAgent": AgentAction(statusKey: "agent-starting", action: LocalizedStringResource("activity.action.start-subagent"))+ case "sendInput", "followupTask": AgentAction(statusKey: "agent-assigning", action: LocalizedStringResource("activity.action.assign-subagent"))+ case "sendMessage": AgentAction(statusKey: "agent-contacting", action: LocalizedStringResource("activity.action.message-subagent"))+ case "resumeAgent": AgentAction(statusKey: "agent-resuming", action: LocalizedStringResource("activity.action.resume-subagent"))+ case "wait": AgentAction(statusKey: "agent-waiting", action: LocalizedStringResource("activity.action.wait-subagent"))+ case "interruptAgent": AgentAction(statusKey: "agent-interrupting", action: LocalizedStringResource("activity.action.interrupt-subagent"))+ case "closeAgent": AgentAction(statusKey: "agent-closing", action: LocalizedStringResource("activity.action.close-subagent"))+ case "listAgents": AgentAction(statusKey: "agent-querying", action: LocalizedStringResource("activity.action.query-subagent"))+ default: AgentAction(statusKey: "agent-coordinating", action: LocalizedStringResource("activity.action.coordinate-subagents"))}}- static func toolActionText(itemType: String?, toolName: String?) -> String? {+ static func toolActionText(itemType: String?, toolName: String?, commandActionTypes: [String]? = nil) -> String? {if itemType == "commandExecution" {- // 历史事件的 tool 字段保存分类组合, 仅在类型明确时按该格式读取- let actions = toolName?.split(separator: "/").map(String.init) ?? []- return commandActionText(actions) ?? String(localized: "activity.action.command")+ return commandActionText(commandActionTypes ?? []) ?? String(localized: "activity.action.command")}if itemType == "collabAgentToolCall" {return String(localized: agentAction(tool: toolName).action)@@ -134,7 +142,7 @@ nonisolated extension ActivityDisplayFormat {static func liveSummaryComponents(for task: ActivityTaskSnapshot, now: Date, waiting: Bool = false) -> [String] {let live = task.presentation- let running = if task.showsPreciseDuration, let started = task.startedAt {+ let running = if let started = task.startedAt {ActivityLiveLabel("elapsed-running").text + " " + CodexDurationFormat.activityText(for: now.timeIntervalSince(started))} else {ActivityLiveLabel("running").textdiff --git a/CodexBar/Services/Activity/ActivityLivePresentation.swift b/CodexBar/Services/Activity/ActivityLivePresentation.swiftindex 51c271d..7ad2490 100644--- a/CodexBar/Services/Activity/ActivityLivePresentation.swift+++ b/CodexBar/Services/Activity/ActivityLivePresentation.swift@@ -1,60 +1,5 @@import Foundation-/// 只解码展示所需的协议元数据, 不保留回答, 命令, 路径, 表单或认证正文-nonisolated struct ActivityLivePayload: Decodable {- var threadId: String?- var turnId: String?- var reviewId: String?- var targetItemId: String?- var mode: String?- var isBlocking: Bool?- var plan: [Status]?- var review: Status?- var run: Hook?- var status: String?- var server: String?- var name: String?- var showBufferingUi: Bool?- var willRetry: Bool?- var fromModel: String?- var toModel: String?- var verifications: [String]?-- struct Status: Decodable { var status: String? }- struct Hook: Decodable {- let id: String- var status: String?- var executionMode: String?- }-- private enum CodingKeys: String, CodingKey {- case threadId, turnId, reviewId, targetItemId, mode, isBlocking, plan, review, run, status, server, name- case showBufferingUi, willRetry, fromModel, toModel, verifications- }-- init(from decoder: Decoder) throws {- let values = try decoder.container(keyedBy: CodingKeys.self)- threadId = try values.decodeIfPresent(String.self, forKey: .threadId)- turnId = try values.decodeIfPresent(String.self, forKey: .turnId)- reviewId = try values.decodeIfPresent(String.self, forKey: .reviewId)- targetItemId = try values.decodeIfPresent(String.self, forKey: .targetItemId)- mode = try values.decodeIfPresent(String.self, forKey: .mode)- isBlocking = try values.decodeIfPresent(Bool.self, forKey: .isBlocking)- plan = try values.decodeIfPresent([Status].self, forKey: .plan)- review = try values.decodeIfPresent(Status.self, forKey: .review)- run = try values.decodeIfPresent(Hook.self, forKey: .run)- // thread/status/changed 使用对象, MCP 启动状态使用字符串- status = try? values.decode(String.self, forKey: .status)- server = try values.decodeIfPresent(String.self, forKey: .server)- name = try values.decodeIfPresent(String.self, forKey: .name)- showBufferingUi = try values.decodeIfPresent(Bool.self, forKey: .showBufferingUi)- willRetry = try values.decodeIfPresent(Bool.self, forKey: .willRetry)- fromModel = try values.decodeIfPresent(String.self, forKey: .fromModel)- toModel = try values.decodeIfPresent(String.self, forKey: .toModel)- verifications = try values.decodeIfPresent([String].self, forKey: .verifications)- }-}-nonisolated struct ActivityLiveLabel: Equatable {let key: Stringvar detail: String?@@ -122,58 +67,55 @@ nonisolated struct ActivityLivePresentation {}mutating func reconcile(status: ActivityThreadStatus?, observedAt: Date? = nil) {- guard let status, ["active", "idle"].contains(status.type) else { return }- guard let flags = status.type == "idle" ? [] : status.activeFlags else { return }- let label: ActivityLiveLabel? = if flags.contains("waitingOnApproval") {+ guard let status, [.active, .idle].contains(status.type) else { return }+ guard let flags = status.type == .idle ? [] : status.activeFlags else { return }+ let label: ActivityLiveLabel? = if flags.contains(.waitingOnApproval) {ActivityLiveLabel("waiting-approval")- } else if flags.contains("waitingOnUserInput") {+ } else if flags.contains(.waitingOnUserInput) {ActivityLiveLabel("waiting-input")} else {nil}if let label {- flagWait = ActivityLiveWait(label: label, since: flagWait?.since ?? observedAt)+ flagWait = ActivityLiveWait(label: label, since: flagWait?.label == label ? flagWait?.since : observedAt)} else {flagWait = nilrequests.removeAll()}}- mutating func consume(_ notification: ActivityNotification, at date: Date) {+ mutating func consume(_ notification: ActivityInput, at date: Date) {let params = notification.params- switch notification.method {- case "turn/started":+ switch notification.kind {+ case .turnStarted:inventoryKnown = true- case "thread/status/changed":+ case .threadStatusChanged:reconcile(status: params.status, observedAt: date)- case "item/started", "item/completed":- if let item = params.item {- consume(item, starting: notification.method == "item/started", at: date)+ case .itemStarted, .itemFinished:+ if let item = params.item, ActivityItem.isObservedType(item.type) {+ consume(item, starting: notification.kind == .itemStarted, at: date)}- case "item/agentMessage/delta", "item/plan/delta", "item/reasoning/textDelta", "item/reasoning/summaryTextDelta":- let label = if notification.method == "item/agentMessage/delta" {+ case .replyProgress, .reasoningProgress, .reasoningSummaryProgress:+ let label = if notification.kind == .replyProgress {params.itemId.flatMap { items[$0]?.label } ?? ActivityLiveLabel("replying")} else {- ActivityLiveLabel(notification.method == "item/plan/delta" ? "planning" : "thinking")+ ActivityLiveLabel("thinking")}phase = Entry(label: label, at: date)phaseItemID = params.itemIdoperations.removeValue(forKey: "retry")- case "item/commandExecution/outputDelta", "item/fileChange/outputDelta":+ case .commandProgress:if let id = params.itemId {// 中途接入可能没有 started, 输出类型足以恢复通用状态, 但不能补全工具清单- let label = items[id]?.label ?? ActivityLiveLabel(notification.method == "item/commandExecution/outputDelta" ? "command" : "editing")+ let label = items[id]?.label ?? ActivityLiveLabel("command")items[id] = Entry(label: label, at: date, isTool: true)}- case "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "item/permissions/requestApproval",- "item/tool/requestUserInput", "mcpServer/elicitation/request":+ case .commandApprovalRequested, .fileApprovalRequested, .permissionsRequested,+ .inputRequested:consumeRequest(notification, at: date)- case "serverRequest/resolved":- if let id = params.requestId?.identifier, requests.removeValue(forKey: id) != nil {+ case .requestResolved:+ if let id = params.requestId, requests.removeValue(forKey: id) != nil {record("request-ended", at: date)- if requests.isEmpty {- flagWait = nil- }}default:consumeSupplement(notification, at: date)@@ -181,18 +123,15 @@ nonisolated struct ActivityLivePresentation {boundStorage()}- private mutating func consumeRequest(_ notification: ActivityNotification, at date: Date) {- guard let id = notification.id?.identifier else { return }+ private mutating func consumeRequest(_ notification: ActivityInput, at date: Date) {+ guard let id = notification.id else { return }let key: String- switch notification.method {- case "item/tool/requestUserInput":- guard notification.live.isBlocking == true else { return }- key = "waiting-input"- case "mcpServer/elicitation/request":- key = switch notification.live.mode {- case "form", "openai/form", "openaiForm": "waiting-form"- case "url": "waiting-external"- case "openai/userVerification": "waiting-verification"+ switch notification.kind {+ case .inputRequested:+ guard notification.live.inputMode != .verification else { return }+ key = switch notification.live.inputMode {+ case .form: "waiting-form"+ case .external: "waiting-external"default: "waiting-service"}default:@@ -202,10 +141,10 @@ nonisolated struct ActivityLivePresentation {}private mutating func consume(_ item: ActivityItem, starting: Bool, at date: Date) {- if item.type == "enteredReviewMode" {+ if item.type == .enteredReviewMode {isReviewing = true}- if item.type == "exitedReviewMode" {+ if item.type == .exitedReviewMode {isReviewing = false}if starting, let label = item.liveLabel {@@ -224,64 +163,45 @@ nonisolated struct ActivityLivePresentation {}}- private mutating func consumeSupplement(_ notification: ActivityNotification, at date: Date) {+ private mutating func consumeSupplement(_ notification: ActivityInput, at date: Date) {let live = notification.live- switch notification.method {- case "turn/plan/updated":- guard let plan = live.plan else { return }- let completed = plan.filter { $0.status == "completed" }.count+ switch notification.kind {+ case .planChanged:+ guard let completed = live.planCompleted, let total = live.planTotal else { return }record(completed > (planCompleted ?? completed) ? "plan-step-completed" : "plan-updated", at: date)planCompleted = completed- planTotal = plan.count- case "turn/diff/updated": record("diff-updated", at: date)- case "model/rerouted":+ planTotal = total+ case .diffChanged: record("diff-updated", at: date)+ case .modelChanged:let detail = [live.fromModel, live.toModel].compactMap(\.self).joined(separator: " → ")record("model-changed", detail: detail.isEmpty ? nil : detail, at: date)- case "model/verification":- if live.verifications?.isEmpty == false {+ case .verificationRequested:+ if live.requiresVerification {record("verification-needed", at: date)}- case "thread/environment/connected": record("environment-connected", at: date)- case "thread/environment/disconnected": record("environment-disconnected", at: date)- case "error":+ case .errorReported:setOperation("retry", label: "retrying", active: live.willRetry == true, at: date)- case "modelProvider/authRecoveryStarted":+ case .authRecoveryStarted:setOperation("auth", label: "recovering-auth", active: true, at: date)- case "modelProvider/authRecoveryCompleted":+ case .authRecoveryFinished:setOperation("auth", label: "recovering-auth", active: false, at: date)record("auth-recovery-ended", at: date)- case "model/safetyBuffering/updated":- setOperation("buffer", label: "buffering", active: live.showBufferingUi == true, at: date)- case "mcpServer/startupStatus/updated":- if let name = live.name ?? live.server {- setOperation("mcp:" + name, label: "connecting-tool", active: live.status == "starting", at: date)- }- case "item/autoApprovalReview/started", "item/autoApprovalReview/completed":- consumeReview(notification, at: date)- case "hook/started", "hook/completed":+ case .safetyBufferingChanged:+ setOperation("buffer", label: "buffering", active: live.isSafetyBuffering, at: date)+ case .hookStarted, .hookFinished:consumeHook(notification, at: date)default: break}}- private mutating func consumeReview(_ notification: ActivityNotification, at date: Date) {- guard let id = notification.params.reviewId ?? notification.params.targetItemId else { return }- let starting = notification.method == "item/autoApprovalReview/started"- setOperation("review:" + id, label: "auto-approval", active: starting, at: date)- let outcomes = ["approved": "approval-approved", "denied": "approval-denied", "timedOut": "approval-timeout", "aborted": "approval-aborted"]- if !starting, let status = notification.live.review?.status, let key = outcomes[status] {- record(key, at: date)- }- }-- private mutating func consumeHook(_ notification: ActivityNotification, at date: Date) {+ private mutating func consumeHook(_ notification: ActivityInput, at date: Date) {guard let run = notification.live.run else { return }- let starting = notification.method == "hook/started"- if !starting || run.executionMode == "sync" {+ let starting = notification.kind == .hookStarted+ if !starting || run.isSynchronous {setOperation("hook:" + run.id, label: "running-hook", active: starting, at: date)}let outcomes = ["completed": "hook-completed", "failed": "hook-failed", "blocked": "hook-blocked", "stopped": "hook-stopped"]- if !starting, let status = run.status, let key = outcomes[status] {+ if !starting, let status = run.status, let key = outcomes[status.rawValue] {record(key, at: date)}}diff --git a/CodexBar/Services/Activity/ActivityMonitor+Completion.swift b/CodexBar/Services/Activity/ActivityMonitor+Completion.swiftindex b2f6622..3555678 100644--- a/CodexBar/Services/Activity/ActivityMonitor+Completion.swift+++ b/CodexBar/Services/Activity/ActivityMonitor+Completion.swift@@ -3,81 +3,43 @@ import Foundationimport osextension ActivityMonitor {- /// Interrupt 只结束匹配的 turn, 不清空同 session 的新任务- func interruptTask(from event: ActivityRecord, source: ActivityEventSource) {- let eventKey = ActivityTaskKey(event: event)- if recentEndedDate(for: eventKey) != nil {+ func finishTask(from event: ActivityRecord, source: ActivityEventSource, into transitions: inout [ActivityTransition]) {+ guard let eventKey = ActivityTaskKey(event: event) else { return }+ guard recentEndedDate(for: eventKey) == nil else {discardStaleTerminalTask(for: eventKey)return}-- let match = matchingTerminalTask(for: event, allowsAnonymousFallback: event.sessionID == nil)- let key: ActivityTaskKey- let task: ActivityTask?- switch match {- case let .active(matchedKey):- key = matchedKey- task = tasks[key]- case let .pending(matchedKey):- key = matchedKey- task = pendingTerminalTasks[key]?.task- case .ambiguous:- AppLog.activity.error("任务中断未关联: reason=ambiguousInterrupt")- return- case .none:- key = eventKey- task = nil- }- guard task.map({ event.timestamp >= $0.lastMainEventAt }) ?? true else {- return- }- if recentEndedDate(for: key) != nil {- discardStaleTerminalTask(for: key)- return+ let key = eventKey+ var task = pendingTerminalTasks[key]?.task ?? tasks[key] ?? ActivityTask(+ displayID: UUID(), key: key, event: event, state: .running,+ startedAt: event.context?.turnStartedAt, progressGeneration: 0+ )+ // 服务端轮次时间可能只有整秒精度, 同秒内的工具事件不应阻止明确终态+ let timestampTolerance: TimeInterval = event.context?.turnCompletedAt == nil ? 0 : 1+ guard event.timestamp.addingTimeInterval(timestampTolerance) >= task.lastMainEventAt else { return }+ task.mergeMetadata(from: event)+ if task.startedAt == nil, let start = event.context?.turnStartedAt, start <= event.timestamp {+ task.startedAt = start}-tasks.removeValue(forKey: key)pendingTerminalTasks.removeValue(forKey: key)- clearProtection(for: key, taskID: task?.displayID, reason: .terminal)- let termination = storeTermination(- for: key,- projectName: event.projectDisplayName ?? task?.projectName,- modelName: event.model ?? task?.modelName,- effort: event.effort ?? task?.effort,- terminatedAt: event.timestamp,- duration: event.source == nil || event.source?.turnCompletedAt != nil ? task?.preciseDuration(until: event.timestamp) : nil,- task: task,- isFailure: event.source?.turnStatus == "failed"- )- recordTerminalPresentationEvent(.terminated(termination))- recordEndedTask(key, at: event.timestamp)- if let resolved = task?.resolvedTurnKey {- recordEndedTask(resolved, at: event.timestamp)+ let completedAt = event.context == nil ? event.timestamp : event.context?.turnCompletedAt+ let terminal: SessionTerminalState+ if event.eventKind == .turnCompleted {+ terminal = .completed(at: completedAt, duration: event.context?.duration)+ } else {+ task.terminalFailed = task.terminalFailed || event.context?.turnStatus == .failed+ terminal = .aborted(at: completedAt, duration: event.context?.duration)}+ resolveTerminal(+ terminal, task: task, key: key, abortFallback: event.timestamp,+ publishesEvents: source == .live, into: &transitions+ )recordEndedTask(eventKey, at: event.timestamp)- if source == .live {- AppLog.activity.notice("任务已终止: source=turnInterrupted")- }}// MARK: - 终态判定与记录- /// PermissionRequest 表示进入审批流程; 只有 服务端明确把审批路由给 user 时才是 UI 等待- func resolvePendingApprovalIfPossible(- for task: inout ActivityTask,- into transitions: inout [ActivityTransition]- ) -> Bool {- let wasWaiting = task.state == .waitingApproval- guard task.resolvePendingApprovals() else { return false }- if !wasWaiting, task.state == .waitingApproval, canPublishActivityTransitions,- !task.key.isAnonymous, let sessionTransitionNotBefore,- task.stateChangedAt >= sessionTransitionNotBefore,- Date().timeIntervalSince(task.stateChangedAt) <= 10 {- transitions.append(.waitingApproval(task.snapshot))- }- return true- }-/// app-server 终态归类的唯一入口; 活动任务和等待终态确认任务只有 abort 兜底时间不同/// 终止记录供任务中心和流光展示, 不发布通知 transitionfunc resolveTerminal(@@ -97,16 +59,16 @@ extension ActivityMonitor {return}switch terminal {- case let .aborted(reportedAt):+ case let .aborted(reportedAt, duration):let terminatedAt = max(reportedAt ?? abortFallback, task.lastActivityAt)- let termination = storeTermination(task, at: terminatedAt, includesDuration: reportedAt != nil)+ let termination = storeTermination(+ task, at: terminatedAt,+ duration: duration ?? reportedAt.flatMap { task.preciseDuration(until: $0) }+ )if publishesEvents {recordTerminalPresentationEvent(.terminated(termination))}recordEndedTask(key, at: terminatedAt)- if let resolved = task.resolvedTurnKey {- recordEndedTask(resolved, at: terminatedAt)- }case let .completed(completedAt, duration):let completion = storeResolvedCompletion(task,@@ -117,7 +79,7 @@ extension ActivityMonitor {)guard publishesEvents else { return }recordTerminalPresentationEvent(.completed(completion))- if canPublishActivityTransitions, !completion.isAnonymous,+ if canPublishActivityTransitions,Date().timeIntervalSince(completion.completedAt) <= 10,let sessionTransitionNotBefore,completion.completedAt >= sessionTransitionNotBefore {@@ -144,7 +106,7 @@ extension ActivityMonitor {) -> Bool {var didChange = falseif state.readStatus == .complete, let status = state.turnStatus {- task.terminalFailed = status == "failed"+ task.terminalFailed = status == .failed}if let startedAt = backfilledStartedAt(for: task, state: state) {task.startedAt = startedAt@@ -167,7 +129,7 @@ extension ActivityMonitor {let recordedCompletedAt = max(completedAt ?? observedAt, task.lastActivityAt)let completion = ActivityCompletion(id: UUID(),- isAnonymous: key.isAnonymous,+ taskID: task.displayID,projectName: task.projectName,modelName: task.modelName,effort: task.effort,@@ -175,54 +137,28 @@ extension ActivityMonitor {duration: reportedDuration ?? completedAt.flatMap { task.preciseDuration(until: $0) })completions.append(completion)- terminalTaskKeyByID[completion.id] = key- registerTerminalTokenUsage(id: completion.id, key: key, task: task, endedAt: recordedCompletedAt)+ registerTerminalTokenUsage(id: completion.id, task: task)recordEndedTask(key, at: recordedCompletedAt)- if let resolved = task.resolvedTurnKey {- recordEndedTask(resolved, at: recordedCompletedAt)- }return completion}private func storeTermination(_ task: ActivityTask,at terminatedAt: Date,- includesDuration: Bool+ duration: TimeInterval?) -> ActivityTermination {- storeTermination(- for: task.key,+ let termination = ActivityTermination(+ id: UUID(),+ taskID: task.displayID,projectName: task.projectName,modelName: task.modelName,effort: task.effort,terminatedAt: terminatedAt,- duration: includesDuration ? task.preciseDuration(until: terminatedAt) : nil,- task: task- )- }-- private func storeTermination(- for key: ActivityTaskKey,- projectName: String?,- modelName: String?,- effort: String?,- terminatedAt: Date,- duration: TimeInterval?,- task: ActivityTask? = nil,- isFailure: Bool = false- ) -> ActivityTermination {- let termination = ActivityTermination(- id: UUID(),- isAnonymous: key.isAnonymous,- projectName: projectName,- modelName: modelName,- effort: effort,- terminatedAt: terminatedAt,duration: duration,- isFailure: isFailure || task?.terminalFailed == true+ isFailure: task.terminalFailed)terminations.append(termination)- terminalTaskKeyByID[termination.id] = key- registerTerminalTokenUsage(id: termination.id, key: key, task: task, endedAt: terminatedAt)+ registerTerminalTokenUsage(id: termination.id, task: task)return termination}@@ -247,9 +183,6 @@ extension ActivityMonitor {guard let date = recentlyEndedTaskAt[key] else {return nil}- if key.isSessionOnly, let startedAt = tasks[key]?.startedAt, startedAt > date {- return nil- }guard date > now.addingTimeInterval(-Self.endedTaskRetention) else {recentlyEndedTaskAt.removeValue(forKey: key)return nil@@ -259,10 +192,6 @@ extension ActivityMonitor {func recordEndedTask(_ key: ActivityTaskKey, at date: Date) {recentlyEndedTaskAt[key] = max(recentlyEndedTaskAt[key] ?? .distantPast, date)- if let sessionID = key.sessionID {- let sessionKey = ActivityTaskKey.session(sessionID)- recentlyEndedTaskAt[sessionKey] = max(recentlyEndedTaskAt[sessionKey] ?? .distantPast, date)- }}func clearCollectedActivityState() {@@ -278,9 +207,7 @@ extension ActivityMonitor {completions.removeAll()terminations.removeAll()recentlyEndedTaskAt.removeAll()- terminalTaskKeyByID.removeAll()terminalTokenUsageRequests.removeAll()- activityTaskOrigins.removeAll()pendingSubagentEvents.removeAll()subagentTurnLinks.removeAll()}@@ -316,8 +243,7 @@ extension ActivityMonitor {}for (index, key) in taskKeys.enumerated() {- guard !key.isAnonymous,- lastWaitingIndexByKey[key] == index,+ guard lastWaitingIndexByKey[key] == index,let task = tasks[key],task.state == .waitingApproval,let sessionTransitionNotBefore,diff --git a/CodexBar/Services/Activity/ActivityMonitor+Origins.swift b/CodexBar/Services/Activity/ActivityMonitor+Origins.swiftdeleted file mode 100644index 7038d56..0000000--- a/CodexBar/Services/Activity/ActivityMonitor+Origins.swift+++ /dev/null@@ -1,126 +0,0 @@-import Foundation-import os--extension ActivityMonitor {- /// 仅为实时链路归一化事件副本, 来源过滤和执行身份使用同一判断- func activityEvent(from event: ActivityRecord, source: ActivityEventSource) -> ActivityRecord? {- guard let origin = activityOrigin(for: event, source: source) else { return nil }- guard origin != event.origin else { return event }- var resolved = ActivityRecord(- timestamp: event.timestamp, name: event.name, origin: origin,- cwd: event.cwd, tool: event.tool, model: event.model,- effort: event.effort, approvalReviewer: event.approvalReviewer,- sessionID: event.sessionID, turnID: event.turnID, agentID: event.agentID, id: event.id- )- resolved.source = event.source- return resolved- }-- private func activityOrigin(- for event: ActivityRecord,- source: ActivityEventSource- ) -> ActivityOrigin? {- let exactKey = Self.exactTurnKey(for: event)- switch event.origin {- case .autoReview:- guard let exactKey else {- return nil- }-- let wasAlreadyIgnored = activityTaskOrigins[exactKey]?.origin == .autoReview- rememberActivityOrigin(event.origin, for: exactKey, at: event.timestamp)- discardExcludedActivity(for: exactKey)- if !wasAlreadyIgnored, source == .live {- AppLog.activity.notice("Auto-review 任务已过滤")- }- return nil- case .main, .auxiliary:- if let exactKey {- rememberActivityOrigin(event.origin, for: exactKey, at: event.timestamp)- }- return event.origin- case .unknown:- guard let exactKey,- let knownOrigin = activityTaskOrigins[exactKey] else {- return nil- }- guard knownOrigin.observedAt > Date().addingTimeInterval(-Self.activityRetention) else {- activityTaskOrigins.removeValue(forKey: exactKey)- return nil- }- guard knownOrigin.origin == .main || knownOrigin.origin == .auxiliary else {- return nil- }- // 一次读取失败不推翻已确认来源, 迟到事件仍交给状态机检查时间顺序- rememberActivityOrigin(knownOrigin.origin, for: exactKey, at: event.timestamp)- return knownOrigin.origin- }- }-- private func rememberActivityOrigin(- _ origin: ActivityOrigin,- for key: ActivityTaskKey,- at timestamp: Date- ) {- activityTaskOrigins[key] = (- origin: origin,- observedAt: max(activityTaskOrigins[key]?.observedAt ?? .distantPast, min(timestamp, Date()))- )- }-- private static func exactTurnKey(for event: ActivityRecord) -> ActivityTaskKey? {- guard let sessionID = event.sessionID,- let turnID = event.turnID else {- return nil- }- return .turn(session: sessionID, turn: turnID)- }-- private func discardExcludedActivity(for key: ActivityTaskKey) {- var taskIDs = Set<UUID>()- if let task = tasks.removeValue(forKey: key) {- taskIDs.insert(task.displayID)- }- if let pending = pendingTerminalTasks.removeValue(forKey: key) {- taskIDs.insert(pending.task.displayID)- }-- if taskIDs.isEmpty {- clearProtection(for: key, taskID: nil, reason: .terminal)- } else {- for taskID in taskIDs {- clearProtection(for: key, taskID: taskID, reason: .terminal)- }- }-- completions.removeAll { terminalTaskKeyByID[$0.id] == key }- terminations.removeAll { terminalTaskKeyByID[$0.id] == key }- terminalTaskKeyByID = terminalTaskKeyByID.filter { $0.value != key }-- removeTerminalMemory(for: key)- }-- private func removeTerminalMemory(for key: ActivityTaskKey) {- guard let removedAt = recentlyEndedTaskAt.removeValue(forKey: key),- let sessionID = key.sessionID else {- return- }-- let sessionKey = ActivityTaskKey.session(sessionID)- guard recentlyEndedTaskAt[sessionKey] == removedAt else {- return- }- let remainingSessionDate = recentlyEndedTaskAt.compactMap { candidateKey, date -> Date? in- guard candidateKey != sessionKey,- candidateKey.sessionID == sessionID else {- return nil- }- return date- }.max()- if let remainingSessionDate {- recentlyEndedTaskAt[sessionKey] = remainingSessionDate- } else {- recentlyEndedTaskAt.removeValue(forKey: sessionKey)- }- }-}diff --git a/CodexBar/Services/Activity/ActivityMonitor+Protection.swift b/CodexBar/Services/Activity/ActivityMonitor+Protection.swiftindex f7e3004..27cd637 100644--- a/CodexBar/Services/Activity/ActivityMonitor+Protection.swift+++ b/CodexBar/Services/Activity/ActivityMonitor+Protection.swift@@ -7,6 +7,7 @@ extension ActivityMonitor {private var canEvaluateProtection: Bool {isStarted&& isProtectionEnabled+ && isProtectionStoreAvailable&& activityReader != nil&& !isBootstrapping&& !isProtectionRecoveryInProgress@@ -31,6 +32,7 @@ extension ActivityMonitor {refreshSnapshot(now: now)return}+ loadProtectionState()reconcileProtection(now: now, sendsNotification: false)}@@ -75,8 +77,7 @@ extension ActivityMonitor {for (key, var task) in tasks {guard task.hasFreshLifecycle(at: now),- let identifier = key.protectionIdentifier,- let record = protectionRecords[identifier] else {+ let record = protectionRecords[key.protectionIdentifier] else {continue}@@ -112,8 +113,7 @@ extension ActivityMonitor {let threshold = protectionSettings.inactivityDuration.timeIntervallet restorableKeys = tasks.compactMap { key, task -> ActivityTaskKey? in- guard !key.isAnonymous,- task.state == .suppressed,+ guard task.state == .suppressed,task.protectionReferenceAt.addingTimeInterval(threshold) > now else {return nil}@@ -124,8 +124,7 @@ extension ActivityMonitor {}let overdueKeys = tasks.compactMap { key, task -> ActivityTaskKey? in- guard !key.isAnonymous,- task.state == .running,+ guard task.state == .running,let deadline = task.protectionDeadline(at: now, inactivityDuration: threshold),deadline <= now else {return nil@@ -146,8 +145,7 @@ extension ActivityMonitor {let threshold = protectionSettings.inactivityDuration.timeIntervallet nextDeadline = tasks.compactMap { key, task -> Date? in- guard !key.isAnonymous,- task.state == .running,+ guard task.state == .running,protectionAttempts[key] == nil else {return nil}@@ -191,8 +189,7 @@ extension ActivityMonitor {let threshold = protectionSettings.inactivityDuration.timeIntervallet candidates = tasks.compactMap { key, task -> ProtectionCandidate? in- guard !key.isAnonymous,- task.state == .running,+ guard task.state == .running,protectionAttempts[key] == nil,let deadline = task.protectionDeadline(at: now, inactivityDuration: threshold),deadline <= now else {@@ -313,8 +310,7 @@ extension ActivityMonitor {markedAt: Date) {cancelProtectionAttempt(for: key)- guard !key.isAnonymous,- var task = tasks[key],+ guard var task = tasks[key],task.state == .running else {return}@@ -334,8 +330,7 @@ extension ActivityMonitor {_ key: ActivityTaskKey,now: Date) {- guard !key.isAnonymous,- canEvaluateProtection,+ guard canEvaluateProtection,let task = tasks[key],task.state == .running,let deadline = task.protectionDeadline(at: now, inactivityDuration: protectionSettings.inactivityDuration.timeInterval),@@ -391,8 +386,7 @@ extension ActivityMonitor {_ candidate: ProtectionCandidate,now: Date) -> Bool {- guard !candidate.key.isAnonymous,- canEvaluateProtection,+ guard canEvaluateProtection,protectionSettings.inactivityDuration == candidate.inactivityDuration,let task = tasks[candidate.key],task.displayID == candidate.taskID,@@ -423,8 +417,7 @@ extension ActivityMonitor {for key: ActivityTaskKey,progressAt: Date) -> Bool {- guard let identifier = key.protectionIdentifier,- let record = protectionRecords[identifier] else {+ guard let record = protectionRecords[key.protectionIdentifier] else {return true}return progressAt > record.lastProgressAt@@ -436,11 +429,11 @@ extension ActivityMonitor {reason: ProtectionClearReason) {cancelProtectionAttempt(for: key)- if let identifier = key.protectionIdentifier,- let record = protectionRecords.removeValue(forKey: identifier) {+ let identifier = key.protectionIdentifier+ if let record = protectionRecords.removeValue(forKey: identifier) {let matchingMarkedAt: Date? = switch reason {case .progress, .thresholdChange: record.markedAt- case .terminal, .retention: nil+ case .terminal: nil}enqueueProtectionPersistence(removals: [@@ -486,8 +479,8 @@ extension ActivityMonitor {attempt.timeoutTask.cancel()protectionAttempts.removeValue(forKey: key)- if let identifier = key.protectionIdentifier,- let record = protectionRecords[identifier],+ let identifier = key.protectionIdentifier+ if let record = protectionRecords[identifier],record.markedAt == attempt.markedAt {protectionRecords.removeValue(forKey: identifier)enqueueProtectionPersistence(@@ -534,14 +527,11 @@ extension ActivityMonitor {lastProgressAt: Date,markedAt: Date) {- guard let taskIdentifier = key.protectionIdentifier else {- return- }let record = ProtectionRecord(- taskIdentifier: taskIdentifier,+ taskIdentifier: key.protectionIdentifier,lastProgressAt: lastProgressAt,markedAt: markedAt,- expiresAt: lastProgressAt.addingTimeInterval(Self.activityRetention)+ expiresAt: lastProgressAt.addingTimeInterval(ActivityRetention.window))protectionRecords[record.taskIdentifier] = recordenqueueProtectionPersistence(upserts: [record])diff --git a/CodexBar/Services/Activity/ActivityMonitor+Subagents.swift b/CodexBar/Services/Activity/ActivityMonitor+Subagents.swiftindex b7f6247..c4a9481 100644--- a/CodexBar/Services/Activity/ActivityMonitor+Subagents.swift+++ b/CodexBar/Services/Activity/ActivityMonitor+Subagents.swift@@ -11,19 +11,18 @@ extension ActivityMonitor {for event: ActivityRecord) -> ActivityTaskKey? {guard let reference = subagentReference(for: event),- let rootKey = subagentTurnLinks[reference], rootKey.sessionID == event.sessionID else { return nil }- return tasks.first(where: { $0.value.resolvedTurnKey == rootKey })?.key+ let rootKey = subagentTurnLinks[reference]?.root, rootKey.threadID == event.threadID else { return nil }+ return tasks[rootKey] == nil ? nil : rootKey}func subagentReference(for event: ActivityRecord) -> ActivityTurnReference? {guard let agentID = event.agentID, let turnID = event.turnID else { return nil }- // 引用的相等性只由线程和轮次决定, 时间用于保留窗口- return ActivityTurnReference(threadID: agentID, turnID: turnID, startedAt: event.timestamp)+ return ActivityTurnReference(threadID: agentID, turnID: turnID)}func deferUnassociatedSubagentEvent(_ event: ActivityRecord, source: ActivityEventSource) -> Bool {guard let reference = subagentReference(for: event), subagentTurnLinks[reference] == nil else { return false }- guard event.sessionID != nil else { return true }+ guard event.threadID != nil else { return true }if !pendingSubagentEvents.contains(where: { $0.event == event }) {pendingSubagentEvents.append(PendingSubagentEvent(event: event, source: source))}@@ -34,12 +33,12 @@ extension ActivityMonitor {let cutoff = Date().addingTimeInterval(-ActivityRetention.window)pendingSubagentEvents.removeAll { $0.event.timestamp <= cutoff }// 结束后的关联也保留一个回放窗口, 用于拒绝旧 Agent 的迟到生命周期事件- subagentTurnLinks = subagentTurnLinks.filter { $0.key.startedAt > cutoff }+ subagentTurnLinks = subagentTurnLinks.filter { $0.value.retainedAt > cutoff }var references = pendingSubagentEvents.compactMap { subagentReference(for: $0.event) }for task in tasks.values {for (owner, execution) in task.executions where !execution.isTerminal {guard let agentID = owner.agentID, let turnID = owner.turnID else { continue }- references.append(ActivityTurnReference(threadID: agentID, turnID: turnID, startedAt: execution.lastEventAt))+ references.append(ActivityTurnReference(threadID: agentID, turnID: turnID))}}return Array(Set(references))@@ -47,36 +46,28 @@ extension ActivityMonitor {func applySubagentLifecycle(_ state: SessionLifecycleState,- terminalOnly: Bool,- into transitions: inout [ActivityTransition]+ terminalOnly: Bool) -> Bool {guard state.readStatus == .complete,let rootTurnID = state.rootTurnID,+ let rootThreadID = state.rootThreadID,let parentThreadID = state.parentThreadID, parentThreadID != state.requestedThreadID else { return false }- let reference = ActivityTurnReference(threadID: state.requestedThreadID, turnID: state.turnID, startedAt: state.startedAt ?? Date())- let eventSessions = Set(pendingSubagentEvents.compactMap { pending -> String? in- subagentReference(for: pending.event) == reference ? pending.event.sessionID : nil+ let reference = ActivityTurnReference(threadID: state.requestedThreadID, turnID: state.turnID)+ let eventThreads = Set(pendingSubagentEvents.compactMap { pending -> String? in+ subagentReference(for: pending.event) == reference ? pending.event.threadID : nil})- let rootSessionID = state.rootSessionID ?? subagentTurnLinks[reference]?.sessionID- ?? (eventSessions.count == 1 ? eventSessions.first : nil)- guard let rootSessionID, rootSessionID != state.requestedThreadID,- eventSessions.isEmpty || eventSessions == [rootSessionID] else { return false }- let rootKey = ActivityTaskKey.turn(session: rootSessionID, turn: rootTurnID)- guard subagentTurnLinks[reference].map({ $0 == rootKey }) ?? true else { return false }- subagentTurnLinks[reference] = rootKey+ guard rootThreadID != state.requestedThreadID,+ eventThreads.isEmpty || eventThreads == [rootThreadID] else { return false }+ let rootKey = ActivityTaskKey(thread: rootThreadID, turn: rootTurnID)+ guard subagentTurnLinks[reference].map({ $0.root == rootKey }) ?? true else { return false }+ subagentTurnLinks[reference] = (rootKey, state.startedAt ?? subagentTurnLinks[reference]?.retainedAt ?? Date())guard !terminalOnly || state.terminal != nil,- let key = tasks.first(where: { $0.value.resolvedTurnKey == rootKey })?.key,- var task = tasks[key] else { return false }+ var task = tasks[rootKey] else { return false }+ let key = rootKeylet owner = ActivityExecutionKey(agentID: state.requestedThreadID, turnID: state.turnID)let wasWaiting = task.state == .waitingApproval+ task.mergeEffort(state.effort)task.mergeExecutionLifecycle(state, owner: owner)- let wasRunning = task.subagentsByID[state.requestedThreadID]?.isRunning- let isRunning = state.terminal == nil- if wasRunning != isRunning {- let observedAt = state.lastProgressAt ?? state.startedAt ?? Date()- task.recordSubagentActivity(agentID: state.requestedThreadID, isStarting: isRunning, at: observedAt)- }- _ = resolvePendingApprovalIfPossible(for: &task, into: &transitions)if !terminalOnly {_ = mergeLifecycleProgress(from: state, key: key, into: &task)}@@ -87,6 +78,43 @@ extension ActivityMonitor {return true}+ @discardableResult+ func reconcileSubagentCounts(_ states: [SessionLifecycleState]) -> Bool {+ var changed = false+ for (key, var task) in tasks {+ let root = task.turnReference+ let children = SessionLifecycleState.subagentStates(for: [root], in: states)+ let references = Set(children.map { ActivityTurnReference(threadID: $0.requestedThreadID, turnID: $0.turnID) })+ let agentIDs = Set(children.map(\.requestedThreadID))+ let hasRoot = states.contains { $0.requestedThreadID == root.threadID && $0.turnID == root.turnID && $0.readStatus == .complete }+ let hasChildren = children.allSatisfy {+ $0.readStatus == .complete && $0.rootThreadID == root.threadID && $0.rootTurnID == root.turnID+ && subagentTurnLinks[ActivityTurnReference(threadID: $0.requestedThreadID, turnID: $0.turnID)]?.root == key+ }+ let hasExecutions = task.executions.keys.allSatisfy { owner in+ guard !owner.isUnattributed else { return false }+ guard let agent = owner.agentID else { return true }+ guard let turn = owner.turnID else { return false }+ return references.contains(ActivityTurnReference(threadID: agent, turnID: turn))+ }+ let hasPendingEvents = pendingSubagentEvents.contains { $0.event.threadID == root.threadID }+ let previousCount = task.snapshot.activeSubagentCount+ task.hasCompleteSubagentCoverage = hasRoot && hasChildren && hasExecutions && !hasPendingEvents+ && Set(task.subagentsByID.keys).isSubset(of: agentIDs)+ if task.hasCompleteSubagentCoverage {+ task.subagentsByID = Dictionary(grouping: children, by: \.requestedThreadID).mapValues { turns in+ SubagentObservation(+ isRunning: turns.contains { $0.terminal == nil },+ timestamp: turns.compactMap { $0.lastProgressAt ?? $0.startedAt }.max() ?? .distantPast+ )+ }+ }+ changed = previousCount != task.snapshot.activeSubagentCount || changed+ tasks[key] = task+ }+ return changed+ }+func replayAssociatedSubagentEvents(into transitions: inout [ActivityTransition]) -> Bool {var remaining: [PendingSubagentEvent] = []var ready: [PendingSubagentEvent] = []@@ -101,8 +129,8 @@ extension ActivityMonitor {var waitingKeys: [ActivityTaskKey] = []for pending in ready {guard let reference = subagentReference(for: pending.event),- subagentTurnLinks[reference]?.sessionID == pending.event.sessionID else { continue }- if let key = apply(pending.event, source: pending.source), pending.source == .live {+ subagentTurnLinks[reference]?.root.threadID == pending.event.threadID else { continue }+ if let key = apply(pending.event, source: pending.source, into: &transitions), pending.source == .live {waitingKeys.append(key)}}diff --git a/CodexBar/Services/Activity/ActivityMonitor+Tokens.swift b/CodexBar/Services/Activity/ActivityMonitor+Tokens.swiftindex 0bf210e..dc372e9 100644--- a/CodexBar/Services/Activity/ActivityMonitor+Tokens.swift+++ b/CodexBar/Services/Activity/ActivityMonitor+Tokens.swift@@ -4,8 +4,6 @@ struct TaskTokenRequest {let root: ActivityTurnReferencelet expectedAgentIDs: Set<String>var references: Set<ActivityTurnReference>- let deadline: Date- var nextReadAt = Date.distantPastfunc usage(from states: [SessionLifecycleState], requiresFinalUsage: Bool = true) -> TokenUsage? {let agentIDs = Set(references.filter { $0 != root }.map(\.threadID))@@ -15,7 +13,7 @@ struct TaskTokenRequest {guard let state = states.first(where: { $0.requestedThreadID == reference.threadID && $0.turnID == reference.turnID }),state.readStatus == .complete,state.rootTurnID == root.turnID,- (state.rootSessionID ?? state.requestedThreadID) == root.threadID,+ (state.rootThreadID ?? state.requestedThreadID) == root.threadID,!requiresFinalUsage || reference == root || state.terminal != nil,let usage = state.tokenUsage else {if requiresFinalUsage {@@ -36,38 +34,33 @@ struct TaskTokenRequest {extension ActivityMonitor {func registerTerminalTokenUsage(- id: UUID, key: ActivityTaskKey, task: ActivityTask?, endedAt: Date, now: Date = Date()+ id: UUID, task: ActivityTask) {- guard let session = key.sessionID, let turn = task?.associatedTurnID ?? key.turnID else { return }// 缺少子 Agent 身份时不能把主线程小计展示为整项任务总量- guard task?.executions.keys.contains(where: \.isUnattributed) != true else { return }- let root = ActivityTurnReference(threadID: session, turnID: turn, startedAt: task?.startedAt ?? endedAt)- terminalTokenUsageRequests[id] = tokenUsageRequest(root: root, task: task, deadline: now.addingTimeInterval(30))+ guard !task.executions.keys.contains(where: \.isUnattributed) else { return }+ terminalTokenUsageRequests[id] = tokenUsageRequest(for: task)}private func tokenUsageRequest(- root: ActivityTurnReference, task: ActivityTask?, deadline: Date+ for task: ActivityTask) -> TaskTokenRequest {+ let root = task.turnReferencevar references: Set = [root]- let rootKey = ActivityTaskKey.turn(session: root.threadID, turn: root.turnID)- references.formUnion(subagentTurnLinks.filter { $0.value == rootKey }.map(\.key))- if let task {- for owner in task.executions.keys {- guard let agent = owner.agentID, let turn = owner.turnID else { continue }- references.insert(ActivityTurnReference(threadID: agent, turnID: turn, startedAt: root.startedAt))- }+ references.formUnion(subagentTurnLinks.filter { $0.value.root == task.key }.map(\.key))+ for owner in task.executions.keys {+ guard let agent = owner.agentID, let turn = owner.turnID else { continue }+ references.insert(ActivityTurnReference(threadID: agent, turnID: turn))}return TaskTokenRequest(- root: root, expectedAgentIDs: Set(task?.subagentsByID.keys.map(\.self) ?? []),- references: references, deadline: deadline+ root: root, expectedAgentIDs: Set(task.subagentsByID.keys),+ references: references)}func activeTokenUsageReferences() -> [ActivityTurnReference] {var references: Set<ActivityTurnReference> = []for task in tasks.values {- guard let root = task.turnReference else { continue }- references.formUnion(tokenUsageRequest(root: root, task: task, deadline: .distantFuture).references)+ references.formUnion(tokenUsageRequest(for: task).references)}return Array(references)}@@ -76,8 +69,7 @@ extension ActivityMonitor {func applyActiveTokenUsage(_ states: [SessionLifecycleState]) -> Bool {var changed = falsefor (key, var task) in tasks {- guard let root = task.turnReference else { continue }- let request = tokenUsageRequest(root: root, task: task, deadline: .distantFuture)+ let request = tokenUsageRequest(for: task)// 运行中汇总已明确归属的累计用量, 尚未产生记录的线程不伪造零值let usage = request.usage(from: states, requiresFinalUsage: false)guard task.tokenUsage != usage else { continue }@@ -88,16 +80,12 @@ extension ActivityMonitor {return changed}- /// 结束后有界重读, 轮次终态可能先于最后一条用量更新- func prepareTerminalTokenUsageReadBatch(now: Date) -> [ActivityTurnReference] {- terminalTokenUsageRequests = terminalTokenUsageRequests.filter { $0.value.deadline > now }- let due = terminalTokenUsageRequests.filter { $0.value.nextReadAt <= now }- .sorted { $0.value.nextReadAt < $1.value.nextReadAt }.prefix(16)+ /// 完成卡片保留期间继续补齐用量, 轮次终态可能先于最后一条用量更新+ func terminalTokenUsageReferences() -> [ActivityTurnReference] {var references: Set<ActivityTurnReference> = []- for (id, var request) in due {- let rootKey = ActivityTaskKey.turn(session: request.root.threadID, turn: request.root.turnID)- request.references.formUnion(subagentTurnLinks.filter { $0.value == rootKey }.map(\.key))- request.nextReadAt = now.addingTimeInterval(2)+ for (id, var request) in terminalTokenUsageRequests {+ let rootKey = ActivityTaskKey(thread: request.root.threadID, turn: request.root.turnID)+ request.references.formUnion(subagentTurnLinks.filter { $0.value.root == rootKey }.map(\.key))terminalTokenUsageRequests[id] = requestreferences.formUnion(request.references)}@@ -109,8 +97,8 @@ extension ActivityMonitor {var changed = falsefor (id, var request) in terminalTokenUsageRequests {guard states.contains(where: { $0.requestedThreadID == request.root.threadID && $0.turnID == request.root.turnID }) else { continue }- let rootKey = ActivityTaskKey.turn(session: request.root.threadID, turn: request.root.turnID)- request.references.formUnion(subagentTurnLinks.filter { $0.value == rootKey }.map(\.key))+ let rootKey = ActivityTaskKey(thread: request.root.threadID, turn: request.root.turnID)+ request.references.formUnion(subagentTurnLinks.filter { $0.value.root == rootKey }.map(\.key))terminalTokenUsageRequests[id] = request// 仅汇总已确认属于本轮的线程, 临时读取不完整时保留上次结果guard let usage = request.usage(from: states) else { continue }diff --git a/CodexBar/Services/Activity/ActivityMonitor.swift b/CodexBar/Services/Activity/ActivityMonitor.swiftindex 2f60330..8bc396f 100644--- a/CodexBar/Services/Activity/ActivityMonitor.swift+++ b/CodexBar/Services/Activity/ActivityMonitor.swift@@ -16,6 +16,7 @@ final class ActivityMonitor: ObservableObject {presentationSubject.eraseToAnyPublisher()}+ var onAccountChange: ((AccountChange) -> Void)?var onProtectionTriggered: ((ProtectionNotice) async -> Bool)?var onProtectionInvalidated: ((UUID, UUID) -> Void)?@@ -28,15 +29,13 @@ final class ActivityMonitor: ObservableObject {var pendingTerminalPresentationEvents: [ActivityTerminalEvent] = []var terminalPresentationNotBefore = Date()var tasks: [ActivityTaskKey: ActivityTask] = [:]- var subagentTurnLinks: [ActivityTurnReference: ActivityTaskKey] = [:]+ var subagentTurnLinks: [ActivityTurnReference: (root: ActivityTaskKey, retainedAt: Date)] = [:]var pendingSubagentEvents: [PendingSubagentEvent] = []var pendingTerminalTasks: [ActivityTaskKey: PendingTerminalTask] = [:]var completions: [ActivityCompletion] = []var terminations: [ActivityTermination] = []var recentlyEndedTaskAt: [ActivityTaskKey: Date] = [:]- var terminalTaskKeyByID: [UUID: ActivityTaskKey] = [:]var terminalTokenUsageRequests: [UUID: TaskTokenRequest] = [:]- var activityTaskOrigins: [ActivityTaskKey: (origin: ActivityOrigin, observedAt: Date)] = [:]var activityReader: AppServerActivityReader?private var activityReaderControlTask: Task<Void, Never>?private var activityReaderGeneration: UInt64 = 0@@ -54,8 +53,14 @@ final class ActivityMonitor: ObservableObject {var protectionRecords: [String: ProtectionRecord] = [:]private var protectionStateLoadTask: Task<Void, Never>?var protectionPersistenceTask: Task<Void, Never>?- private var isProtectionStateLoaded = false+ enum ProtectionLoadState { case idle, loading, available, retryableFailure, blocked }+ var protectionLoadState = ProtectionLoadState.idle+ private var protectionLoadGeneration: UInt64 = 0var isProtectionEnabled = false+ var isProtectionStoreAvailable: Bool {+ protectionLoadState == .available+ }+@Published var isActivitySourceHealthy = false@Published private(set) var sourcePresentation: ActivityLiveLabel? = ActivityLiveLabel("unavailable")private var hasConnectedActivitySource = false@@ -63,6 +68,7 @@ final class ActivityMonitor: ObservableObject {var isProtectionRecoveryInProgress = falsevar protectionRecoveryGeneration: UInt64 = 0private var cancellables = Set<AnyCancellable>()+ private var isPreparingForTermination = falsevar isStarted = falsevar isBootstrapping = false/// 初始快照跨多个批次到达, 事件数累加到 bootstrapEnd 才一次记完@@ -144,34 +150,85 @@ final class ActivityMonitor: ObservableObject {}isStarted = falsecancellables.removeAll()- protectionStateLoadTask?.cancel()- protectionStateLoadTask = nil+ cancelProtectionStateLoad()stopReaderAndClearState()}- private func loadProtectionState() {- guard !isProtectionStateLoaded,- protectionStateLoadTask == nil else {- return+ func prepareForTermination() async -> Bool {+ isPreparingForTermination = true+ cancelProtectionStateLoad()+ recoveryTask?.cancel()+ recoveryTask = nil+ resetProtectionRecovery()+ cancelInactivityCheck()+ sessionLifecyclePollTask?.cancel()+ sessionLifecyclePollTask = nil+ activityReaderControlTask?.cancel()+ activityReaderControlTask = nil+ isActivitySourceHealthy = false+ guard let reader = activityReader else { return true }+ return await reader.stop()+ }++ func resumeAfterTerminationCancellation() async {+ isPreparingForTermination = false+ loadProtectionState()+ if let reader = activityReader {+ await reader.start()+ startSessionLifecyclePolling(generation: activityReaderGeneration)+ } else {+ startReaderIfReady()}+ }+ func loadProtectionState() {+ guard isStarted, !isPreparingForTermination,+ protectionLoadState != .available, protectionStateLoadTask == nil else { return }+ protectionLoadGeneration &+= 1+ let generation = protectionLoadGeneration+ protectionLoadState = .loadingprotectionStateLoadTask = Task { @MainActor [weak self] in- guard let self else {- return+ guard let self else { return }+ defer {+ if generation == protectionLoadGeneration {+ protectionStateLoadTask = nil+ }}- let records = await protectionStore.load()- guard isStarted, !Task.isCancelled else {- return+ for attempt in 0 ..< 3 {+ do {+ let records = try await protectionStore.load()+ guard isStarted, !Task.isCancelled, generation == protectionLoadGeneration else { return }+ protectionRecords = records+ protectionLoadState = .available+ // 成功重读后必须经过活动读取屏障, 才能重新判定任务+ beginProtectionRecovery()+ startReaderIfReady()+ requestActivityRecovery()+ return+ } catch {+ guard isStarted, !Task.isCancelled, generation == protectionLoadGeneration else { return }+ let isBlocked = error is StorageCompatibilityError || error is DecodingError+ protectionLoadState = isBlocked ? .blocked : .retryableFailure+ AppLog.activity.error("异常任务存储不可用, 暂停保护判定: \(error.localizedDescription, privacy: .public)")+ startReaderIfReady()+ guard !isBlocked, attempt < 2 else { return }+ do { try await Task.sleep(for: .seconds(attempt == 0 ? 1 : 3)) } catch { return }+ }}- protectionRecords = records- isProtectionStateLoaded = true- protectionStateLoadTask = nil- startReaderIfReady()+ }+ }++ private func cancelProtectionStateLoad() {+ protectionLoadGeneration &+= 1+ protectionStateLoadTask?.cancel()+ protectionStateLoadTask = nil+ if protectionLoadState == .loading {+ protectionLoadState = .idle}}private func startReaderIfReady() {- guard isStarted, isProtectionStateLoaded, activityReader == nil else { return }+ guard isStarted, !isPreparingForTermination, protectionLoadState != .idle, protectionLoadState != .loading, activityReader == nil else { return }AppLog.activity.notice("任务监控已启动: reason=appLaunch")activityReaderGeneration &+= 1@@ -181,6 +238,10 @@ final class ActivityMonitor: ObservableObject {lifecycleCache: lifecycleCache,tokenHistory: TokenHistoryStore(directoryURL: activityDirectoryURL),recorder: ActivityRecorder(directoryURL: activityDirectoryURL),+ onAccountChange: { [weak self] change in+ guard let self, activityReaderGeneration == generation else { return }+ onAccountChange?(change)+ },onBatch: { [weak self] batch inguard let self, activityReaderGeneration == generation else {return@@ -279,9 +340,7 @@ final class ActivityMonitor: ObservableObject {into transitions: inout [ActivityTransition]) -> Bool {guard !terminalOnly || (state.readStatus == .complete && state.terminal != nil) else { return false }- let exact = ActivityTaskKey.turn(session: state.requestedThreadID, turn: state.turnID)- let key = tasks.first(where: { $0.value.resolvedTurnKey == exact })?.key- ?? pendingTerminalTasks.first(where: { $0.value.task.resolvedTurnKey == exact })?.key ?? exact+ let key = ActivityTaskKey(thread: state.requestedThreadID, turn: state.turnID)if var pending = pendingTerminalTasks[key] {let pendingDidChange = Self.mergeLifecycleBackfill(from: state,@@ -340,20 +399,10 @@ final class ActivityMonitor: ObservableObject {return true}+ let wasSuppressed = task.state == .suppressedtask.mergeExecutionLifecycle(state, owner: ActivityExecutionKey(agentID: nil, turnID: state.turnID))-- let wasSuppressedBeforeApproval = task.state == .suppressed- if resolvePendingApprovalIfPossible(- for: &task,- into: &transitions- ) {- if wasSuppressedBeforeApproval, task.state == .waitingApproval {- clearProtection(- for: key,- taskID: task.displayID,- reason: .progress- )- }+ if wasSuppressed, task.state == .waitingApproval {+ clearProtection(for: key, taskID: task.displayID, reason: .progress)}tasks[key] = task@@ -424,20 +473,12 @@ final class ActivityMonitor: ObservableObject {}}- private func lifecycleReferences(now: Date, includeAll: Bool) -> [ActivityTurnReference] {+ func lifecycleReferences() -> [ActivityTurnReference] {var references = activeTokenUsageReferences()references.append(contentsOf: subagentLifecycleReferences())- references.append(contentsOf: prepareTerminalTokenUsageReadBatch(now: now))- let due = pendingTerminalTasks.filter { includeAll || $0.value.nextPollAt <= now }- .sorted { $0.value.nextPollAt < $1.value.nextPollAt }- for (key, var pending) in due.prefix(16) {- if let reference = pending.task.turnReference {- references.append(reference)- }- pending.nextPollAt = now.addingTimeInterval(now < pending.deadline ? 1 : 30)- pendingTerminalTasks[key] = pending- }- return references+ references.append(contentsOf: terminalTokenUsageReferences())+ references.append(contentsOf: pendingTerminalTasks.values.map(\.task.turnReference))+ return Array(Set(references))}@discardableResult@@ -454,24 +495,25 @@ final class ActivityMonitor: ObservableObject {defer { isReconcilingLifecycles = false }let bootstrapGeneration = bootstrapCompletionGenerationlet recoveryGeneration = protectionRecoveryGeneration- let references = lifecycleReferences(now: Date(), includeAll: recovering)+ let references = lifecycleReferences()let states = await lifecycleCache.lifecycleStates(for: references)guard !Task.isCancelled, generation == activityReaderGeneration,bootstrapGeneration == bootstrapCompletionGeneration,recoveryGeneration == protectionRecoveryGeneration,activityReader != nil, !isBootstrapping, terminalOnly || isActivitySourceHealthy,!isSystemSleeping else { return false }- let unavailable = Set(states.filter { $0.readStatus != .complete }.map { ActivityTaskKey.turn(session: $0.requestedThreadID, turn: $0.turnID) })+ let unavailable = Set(states.filter { $0.readStatus != .complete }.map { ActivityTaskKey(thread: $0.requestedThreadID, turn: $0.turnID) })let availabilityChanged = unavailableTurns != unavailableunavailableTurns = unavailablevar didChange = availabilityChangedvar transitions: [ActivityTransition] = []for state in states {- didChange = applySubagentLifecycle(state, terminalOnly: terminalOnly, into: &transitions) || didChange+ didChange = applySubagentLifecycle(state, terminalOnly: terminalOnly) || didChangedidChange = applyLifecycleState(state, terminalOnly: terminalOnly, into: &transitions) || didChange}if !terminalOnly {didChange = replayAssociatedSubagentEvents(into: &transitions) || didChange+ didChange = reconcileSubagentCounts(states) || didChange}if !terminalOnly {didChange = applyActiveTokenUsage(states) || didChange@@ -499,6 +541,7 @@ final class ActivityMonitor: ObservableObject {// MARK: - 活动事件消费func consume(_ batch: ActivityEventBatch) {+ guard !isPreparingForTermination else { return }switch batch {case .lifecycleChanged:refreshSessionLifecycleNow()@@ -518,11 +561,14 @@ final class ActivityMonitor: ObservableObject {cancelInactivityCheck()clearCollectedActivityState()publishSnapshot(.empty)- case let .bootstrapEvents(events):- sourcePresentation = ActivityLiveLabel("recovering-state")- bootstrapEventCount += events.count+ case let .snapshotEvents(events):+ if isBootstrapping {+ sourcePresentation = ActivityLiveLabel("recovering-state")+ bootstrapEventCount += events.count+ }+ var transitions: [ActivityTransition] = []for event in events {- _ = apply(event, source: .bootstrap)+ _ = apply(event, source: .bootstrap, into: &transitions)}case .bootstrapEnd:sourcePresentation = ActivityLiveLabel("recovering-state")@@ -538,8 +584,9 @@ final class ActivityMonitor: ObservableObject {case let .live(events):let activeCountBefore = snapshot.activeCountvar waitingTaskKeys: [ActivityTaskKey] = []+ var transitions: [ActivityTransition] = []for event in events {- if let key = apply(event, source: .live) {+ if let key = apply(event, source: .live, into: &transitions) {waitingTaskKeys.append(key)}}@@ -556,12 +603,13 @@ final class ActivityMonitor: ObservableObject {)AppLog.activity.notice("任务数变化: \(details, privacy: .public)")}+ for transition in transitions {+ transitionSubject.send(transition)+ }publishWaitingApprovalTransitions(waitingTaskKeys)if !pendingTerminalTasks.isEmpty {// 新进入终态确认窗口的任务立即查询, 不等待下次周期核对refreshSessionLifecycleNow()- } else if events.contains(where: { $0.eventKind == .turnCompleted }) {- refreshSessionLifecycleNow()}case .sourceUnavailable:sourcePresentation = ActivityLiveLabel("unavailable")@@ -584,8 +632,7 @@ final class ActivityMonitor: ObservableObject {completionGeneration: UInt64) async {let recoveryGeneration = protectionRecoveryGeneration- let references = tasks.values.compactMap(\.turnReference)- + pendingTerminalTasks.values.compactMap(\.task.turnReference)+ let references = lifecycleReferences()if !references.isEmpty {let states = await lifecycleCache.lifecycleStates(for: references)guard !Task.isCancelled, completionGeneration == bootstrapCompletionGeneration,@@ -595,8 +642,11 @@ final class ActivityMonitor: ObservableObject {var ignoredTransitions: [ActivityTransition] = []if recoveryGeneration == protectionRecoveryGeneration, isActivitySourceHealthy, !isSystemSleeping {for state in states {+ _ = applySubagentLifecycle(state, terminalOnly: false)_ = applyLifecycleState(state, into: &ignoredTransitions)}+ _ = replayAssociatedSubagentEvents(into: &ignoredTransitions)+ _ = reconcileSubagentCounts(states)}}@@ -632,9 +682,10 @@ final class ActivityMonitor: ObservableObject {func apply(_ event: ActivityRecord,- source: ActivityEventSource+ source: ActivityEventSource,+ into transitions: inout [ActivityTransition]) -> ActivityTaskKey? {- guard let event = activityEvent(from: event, source: source) else {+ guard event.origin == .main || event.origin == .auxiliary else {return nil}@@ -659,20 +710,10 @@ final class ActivityMonitor: ObservableObject {updateSubagentActivity(from: event, isStarting: false, source: source)case .approvalRequested:return waitForApproval(from: event, source: source)- case .turnCompleted:- guard isTopLevelEvent else {- return nil- }- observeStop(from: event, source: source)- case .turnAborted:- guard isTopLevelEvent else {- return nil- }- interruptTask(from: event, source: source)- case .sessionEnded:+ case .turnCompleted, .turnAborted:guard isTopLevelEvent else { return nil }- terminateSession(from: event)- case .sessionStarted, .none:+ finishTask(from: event, source: source, into: &transitions)+ case .none:break}return nil@@ -684,57 +725,31 @@ final class ActivityMonitor: ObservableObject {from event: ActivityRecord,source: ActivityEventSource) {- let key = ActivityTaskKey(event: event)- guard !updateAliasedPrompt(from: event, key: key) else { return }- preserveSupersededSessionTask(from: event, key: key)- if let pending = pendingTerminalTasks[key] {- guard key.turnID == nil, event.timestamp > pending.supersededAt else { return }- pendingTerminalTasks.removeValue(forKey: key)- if let resolved = pending.task.resolvedTurnKey {- pendingTerminalTasks[resolved] = pending- }- }- if pendingTerminalTasks.values.contains(where: { $0.task.resolvedTurnKey == key }) {- return- }+ guard let key = ActivityTaskKey(event: event) else { return }+ guard pendingTerminalTasks[key] == nil else { return }let existingTask = tasks[key]let displayID = existingTask?.displayID ?? UUID()- if let endedAt = recentEndedDate(for: key) {- if case .turn = key {- return- }- if event.timestamp <= endedAt {- return- }- }- if let existing = tasks[key], event.timestamp < existing.lastMainEventAt {+ guard recentEndedDate(for: key) == nil else { return }+ if let existing = existingTask, event.timestamp < existing.lastMainEventAt {return}- if let sessionID = key.sessionID {- // 同一 session 的 turn 按顺序执行. 新 prompt 让旧 turn 立即退出活动列表- // 但保留短暂终态确认窗口, 避免把迟到的正常完成误记为终止- guard !tasks.values.contains(where: {- $0.key.sessionID == sessionID && $0.lastMainEventAt > event.timestamp- }) else {- return- }- let supersededTasks = tasks.values.filter {- $0.key != key && $0.key.sessionID == sessionID- }- for task in supersededTasks {- clearProtection(for: task.key, taskID: task.displayID, reason: .terminal)- pendingTerminalTasks[task.key] = PendingTerminalTask(- task: task,- supersededAt: event.timestamp,- deadline: Date().addingTimeInterval(Self.supersededTerminalGracePeriod)- )- }- tasks = tasks.filter { taskKey, _ in- taskKey == key || taskKey.sessionID != sessionID- }+ let threadID = key.threadID+ // 当前轮次由 app-server 确认, 旧轮次的毫秒级活动时间不能否定秒级起点+ // 旧任务退出活动列表后继续等待明确终态+ let supersededTasks = tasks.values.filter {+ $0.key != key && $0.key.threadID == threadID+ }+ for task in supersededTasks {+ clearProtection(for: task.key, taskID: task.displayID, reason: .terminal)+ pendingTerminalTasks[task.key] = PendingTerminalTask(+ task: task,+ supersededAt: event.timestamp+ )+ }+ tasks = tasks.filter { taskKey, _ in+ taskKey == key || taskKey.threadID != threadID}-if source == .live {clearProtection(for: key,@@ -743,26 +758,23 @@ final class ActivityMonitor: ObservableObject {)}- recentlyEndedTaskAt.removeValue(forKey: key)- if let sessionID = key.sessionID {- // 缺少 turn 的事件复用 session 键; 新 turn 开始后清除上一轮的终态记忆- recentlyEndedTaskAt.removeValue(forKey: .session(sessionID))- }-- if resumePromptInSameTurn(from: event, existing: existingTask) {+ if var task = existingTask {+ task.resumeExecution(from: event)+ task.mergeMetadata(from: event)+ task.recordProgress(at: event.timestamp)+ task.startedAt = task.startedAt ?? event.context?.turnStartedAt+ tasks[key] = taskreturn}- var task = ActivityTask(+ tasks[key] = ActivityTask(displayID: displayID,key: key,event: event,state: .running,- startedAt: event.timestamp,- progressGeneration: (existingTask?.progressGeneration ?? 0) &+ 1+ startedAt: event.context?.turnStartedAt,+ progressGeneration: 1)- task.lastProgressAt = max(task.lastProgressAt, existingTask?.lastProgressAt ?? .distantPast)- tasks[key] = task}private func resumeTask(@@ -770,9 +782,9 @@ final class ActivityMonitor: ObservableObject {allowsRecovery: Bool,source: ActivityEventSource) {- let eventKey = ActivityTaskKey(event: event)+ guard let eventKey = ActivityTaskKey(event: event) else { return }let matchedKey = event.agentID == nil- ? matchingActiveTaskKey(for: event)+ ? eventKey: matchingSubagentParentTaskKey(for: event)if let key = matchedKey, var task = tasks[key] {@@ -787,7 +799,7 @@ final class ActivityMonitor: ObservableObject {let wasSuppressed = task.state == .suppressedtask.resumeExecution(from: event)task.mergeMetadata(from: event)- task.recordEvent(at: event.timestamp)+ task.recordProgress(at: event.timestamp)tasks[key] = taskif wasSuppressed || source == .live {clearProtection(@@ -801,8 +813,7 @@ final class ActivityMonitor: ObservableObject {guard allowsRecovery,recentEndedDate(for: eventKey) == nil,- pendingTerminalTasks[eventKey] == nil,- !pendingTerminalTasks.values.contains(where: { $0.task.resolvedTurnKey == eventKey }) else {+ pendingTerminalTasks[eventKey] == nil else {return}@@ -829,33 +840,27 @@ final class ActivityMonitor: ObservableObject {isStarting: Bool,source: ActivityEventSource) {- guard let key = matchingSubagentParentTaskKey(for: event),- recentEndedDate(for: key) == nil,- pendingTerminalTasks[key] == nil,- var task = tasks[key] else {- return- }-- // 归属已精确关联, 仍拒绝早于根任务起点的事件+ guard let agentID = event.agentID, let rootThread = event.context?.rootThreadID, let rootTurn = event.context?.rootTurnID else { return }+ let key = ActivityTaskKey(thread: rootThread, turn: rootTurn)+ guard recentEndedDate(for: key) == nil, pendingTerminalTasks[key] == nil, var task = tasks[key] else { return }if let startedAt = task.startedAt, event.timestamp < startedAt {return}-+ // 创建活动标识子线程, 不能拿发出通知的父轮次伪造子执行+ let executions = task.executions.filter { $0.key.agentID == agentID }task.recordSubagentActivity(- agentID: event.agentID,- isStarting: isStarting,- hasEnded: task.executions[task.executionKey(for: event)]?.isTerminal == true,- at: event.timestamp+ agentID: event.agentID, isStarting: isStarting,+ hasEnded: !executions.isEmpty && executions.values.allSatisfy(\.isTerminal), at: event.timestamp)-- if task.acceptsExecutionEvent(event) {- let wasSuppressed = task.state == .suppressed- task.resumeExecution(from: event)- task.mergeMetadata(from: event)- task.recordEvent(at: event.timestamp)- if wasSuppressed || source == .live {- clearProtection(for: key, taskID: task.displayID, reason: .progress)- }+ task.mergeMetadata(from: event)+ task.recordProgress(at: event.timestamp)+ let wasSuppressed = task.state == .suppressed+ if wasSuppressed {+ task.state = .running+ task.stateChangedAt = event.timestamp+ }+ if wasSuppressed || source == .live {+ clearProtection(for: key, taskID: task.displayID, reason: .progress)}tasks[key] = task}@@ -864,9 +869,9 @@ final class ActivityMonitor: ObservableObject {from event: ActivityRecord,source: ActivityEventSource) -> ActivityTaskKey? {- let eventKey = ActivityTaskKey(event: event)+ guard let eventKey = ActivityTaskKey(event: event) else { return nil }let matchedKey = event.agentID == nil- ? matchingActiveTaskKey(for: event)+ ? eventKey: matchingSubagentParentTaskKey(for: event)if let key = matchedKey, var task = tasks[key] {@@ -880,10 +885,7 @@ final class ActivityMonitor: ObservableObject {let wasSuppressed = task.state == .suppressedtask.mergeMetadata(from: event)- // 权限事件描述当前请求; 缺失工具名时不能沿用上一条工具事件- task.toolName = event.tool- task.itemType = event.source?.itemType- task.recordEvent(at: event.timestamp)+ task.recordProgress(at: event.timestamp)let enteredWaiting = task.recordApprovalRequest(from: event)tasks[key] = taskif wasSuppressed || source == .live {@@ -898,8 +900,7 @@ final class ActivityMonitor: ObservableObject {guard event.agentID == nil,recentEndedDate(for: eventKey) == nil,- pendingTerminalTasks[eventKey] == nil,- !pendingTerminalTasks.values.contains(where: { $0.task.resolvedTurnKey == eventKey }) else {+ pendingTerminalTasks[eventKey] == nil else {return nil}@@ -923,36 +924,6 @@ final class ActivityMonitor: ObservableObject {return enteredWaiting ? eventKey : nil}- /// 结束提示与生命周期分开处理, 完成分类由服务端轮次终态确认- private func observeStop(from event: ActivityRecord, source: ActivityEventSource) {- let eventKey = ActivityTaskKey(event: event)- guard recentEndedDate(for: eventKey) == nil else {- discardStaleTerminalTask(for: eventKey)- return- }-- let match = matchingTerminalTask(for: event, allowsAnonymousFallback: event.sessionID == nil)- switch match {- case .ambiguous:- AppLog.activity.error("任务终态已延后: reason=ambiguousStop")- case let .pending(key):- guard var pending = pendingTerminalTasks[key],- event.timestamp >= pending.task.lastMainEventAt else {- return- }- // 新 turn 或 SessionEnd 已确定旧任务退出活动列表, Stop 不恢复它或重置 grace- pending.task.mergeMetadata(from: event)- pending.task.recordEvent(at: event.timestamp)- pendingTerminalTasks[key] = pending- case .active, .none:- resumeTask(- from: event,- allowsRecovery: true,- source: source- )- }- }-func discardStaleTerminalTask(for key: ActivityTaskKey) {if let task = tasks.removeValue(forKey: key) {clearProtection(@@ -970,131 +941,6 @@ final class ActivityMonitor: ObservableObject {}}- /// SessionEnd 没有 turn_id, 以 session 为边界把活跃任务移入终态确认窗口- /// 任务立即退出活跃列表, 后续继续从 app-server 确认完成或终止分类- private func terminateSession(from event: ActivityRecord) {- guard let sessionID = event.sessionID else {- return- }-- let deadline = Date().addingTimeInterval(Self.supersededTerminalGracePeriod)- let matchingPendingTasks = pendingTerminalTasks.filter { key, pending in- key.sessionID == sessionID && pending.task.lastMainEventAt <= event.timestamp- }- for (key, pending) in matchingPendingTasks {- pendingTerminalTasks[key] = PendingTerminalTask(- task: pending.task,- supersededAt: max(pending.supersededAt, event.timestamp),- deadline: min(pending.deadline, deadline)- )- }-- let matchingActiveTasks = tasks.filter { key, task in- key.sessionID == sessionID && task.lastMainEventAt <= event.timestamp- }- for (key, task) in matchingActiveTasks {- tasks.removeValue(forKey: key)- clearProtection(for: key, taskID: task.displayID, reason: .terminal)- pendingTerminalTasks[key] = PendingTerminalTask(- task: task,- supersededAt: event.timestamp,- deadline: deadline- )- }- }-- /// 精确 turn 失败后只接受同 session 唯一活动任务, 有待确认旧 turn 时不猜测- private func matchingActiveTaskKey(for event: ActivityRecord) -> ActivityTaskKey? {- let exactKey = ActivityTaskKey(event: event)- if let key = tasks.first(where: { $0.value.resolvedTurnKey == exactKey })?.key {- return key- }- if tasks[exactKey] != nil {- return exactKey- }-- if let sessionID = event.sessionID {- guard !pendingTerminalTasks.values.contains(where: {- $0.task.key.sessionID == sessionID- }) else {- return nil- }- let candidates = tasks.values.filter { task in- task.key.sessionID == sessionID- && (event.turnID == nil || task.associatedTurnID == nil)- }- guard candidates.count == 1 else {- return nil- }- return candidates[0].key- }-- let anonymousKey = ActivityTaskKey.anonymous(- project: ActivityTaskKey.projectIdentifier(event.projectDisplayName)- )- return tasks[anonymousKey] == nil ? nil : anonymousKey- }-- func matchingTerminalTask(- for event: ActivityRecord,- allowsAnonymousFallback: Bool = true- ) -> TerminalTaskMatch {- let exactKey = ActivityTaskKey(event: event)- if let key = pendingTerminalTasks.first(where: { $0.value.task.resolvedTurnKey == exactKey })?.key {- return .pending(key)- }- if let key = tasks.first(where: { $0.value.resolvedTurnKey == exactKey })?.key {- return .active(key)- }- if pendingTerminalTasks[exactKey] != nil {- return .pending(exactKey)- }- if tasks[exactKey] != nil,- event.turnID != nil || event.sessionID == nil {- return .active(exactKey)- }-- if let sessionID = event.sessionID {- let pendingCandidates = pendingTerminalTasks.filter {- $0.value.task.key.sessionID == sessionID- && $0.value.task.lastMainEventAt <= event.timestamp- && (event.turnID == nil || $0.value.task.associatedTurnID == nil)- }- if pendingCandidates.count == 1, let key = pendingCandidates.keys.first {- return .pending(key)- }- if pendingCandidates.count > 1 {- return .ambiguous- }-- let activeCandidates = tasks.values.filter {- $0.key.sessionID == sessionID- && $0.lastMainEventAt <= event.timestamp- && (event.turnID == nil || $0.associatedTurnID == nil)- }- if activeCandidates.count == 1 {- return .active(activeCandidates[0].key)- }- if activeCandidates.count > 1 {- return .ambiguous- }- }-- guard allowsAnonymousFallback else {- return .none- }- let anonymousKey = ActivityTaskKey.anonymous(- project: ActivityTaskKey.projectIdentifier(event.projectDisplayName)- )- if tasks[anonymousKey] != nil {- return .active(anonymousKey)- }- if pendingTerminalTasks[anonymousKey] != nil {- return .pending(anonymousKey)- }- return .none- }-// MARK: - 快照与过期清理func refreshSnapshot(now: Date) {@@ -1112,7 +958,8 @@ final class ActivityMonitor: ObservableObject {recentCompletions: recentCompletions,recentTerminations: recentTerminations)- let events = pendingTerminalPresentationEvents.filter { terminalTaskKeyByID[$0.id] != nil }+ let retainedTerminalIDs = Set(completions.map(\.id)).union(terminations.map(\.id))+ let events = pendingTerminalPresentationEvents.filter { retainedTerminalIDs.contains($0.id) }pendingTerminalPresentationEvents.removeAll()publishSnapshot(newSnapshot, terminalEvents: events)@@ -1132,7 +979,7 @@ final class ActivityMonitor: ObservableObject {private func sortedTasks(in state: ActivityTaskState) -> [ActivityTask] {tasks.values- .filter { $0.state == state && !unavailableTurns.contains($0.resolvedTurnKey ?? $0.key) }+ .filter { $0.state == state && !unavailableTurns.contains($0.key) }.sorted(by: Self.recentFirst(\.lastActivityAt, \.displayID))}@@ -1152,44 +999,24 @@ final class ActivityMonitor: ObservableObject {private func pruneExpiredState(now: Date) {finalizeExpiredPendingTerminalTasks(now: now)- let activityCutoff = now.addingTimeInterval(-Self.activityRetention)- let expiredTasks = tasks.filter { $0.value.lastActivityAt <= activityCutoff }- for (key, task) in expiredTasks {- clearProtection(- for: key,- taskID: task.displayID,- reason: .retention- )- }- tasks = tasks.filter { $0.value.lastActivityAt > activityCutoff }-removeExpiredProtectionRecords(now: now)let historyCutoff = now.addingTimeInterval(-Self.recentHistoryRetention)completions.removeAll { $0.completedAt <= historyCutoff }terminations.removeAll { $0.terminatedAt <= historyCutoff }let retainedTerminalIDs = Set(completions.map(\.id)).union(terminations.map(\.id))- terminalTaskKeyByID = terminalTaskKeyByID.filter {- retainedTerminalIDs.contains($0.key)- }terminalTokenUsageRequests = terminalTokenUsageRequests.filter { retainedTerminalIDs.contains($0.key) }let endedTaskCutoff = now.addingTimeInterval(-Self.endedTaskRetention)recentlyEndedTaskAt = recentlyEndedTaskAt.filter {$0.value > endedTaskCutoff}- activityTaskOrigins = activityTaskOrigins.filter {- $0.value.observedAt > activityCutoff- }}private func scheduleNextCleanup(now: Date) {- var deadlines = tasks.values.map {- $0.lastActivityAt.addingTimeInterval(Self.activityRetention)- }- deadlines.append(contentsOf: completions.map {+ var deadlines = completions.map {$0.completedAt.addingTimeInterval(Self.recentHistoryRetention)- })+ }deadlines.append(contentsOf: terminations.map {$0.terminatedAt.addingTimeInterval(Self.recentHistoryRetention)})@@ -1197,9 +1024,6 @@ final class ActivityMonitor: ObservableObject {deadlines.append(contentsOf: recentlyEndedTaskAt.values.map {$0.addingTimeInterval(Self.endedTaskRetention)})- deadlines.append(contentsOf: activityTaskOrigins.values.map {- $0.observedAt.addingTimeInterval(Self.activityRetention)- })deadlines.append(contentsOf: protectionRecords.values.map(\.expiresAt))guard let nextDeadline = deadlines.filter({ $0 > now }).min() else {@@ -1227,45 +1051,6 @@ final class ActivityMonitor: ObservableObject {private static let recentHistoryRetention: TimeInterval = 10 * 60static let endedTaskRetention: TimeInterval = 24 * 60 * 60- static let activityRetention = ActivityRetention.windowstatic let protectionNotificationSubmissionGrace: Duration = .seconds(3)- private static let supersededTerminalGracePeriod: TimeInterval = 5private static let sessionLifecyclePollInterval: TimeInterval = 1}--private extension ActivityMonitor {- func resumePromptInSameTurn(from event: ActivityRecord, existing: ActivityTask?) -> Bool {- guard var task = existing, let turnID = event.turnID, task.associatedTurnID == turnID else { return false }- task.resumeExecution(from: event)- task.mergeMetadata(from: event)- task.recordEvent(at: event.timestamp)- task.startedAt = task.startedAt ?? event.timestamp- tasks[task.key] = task- return true- }-- func preserveSupersededSessionTask(from event: ActivityRecord, key: ActivityTaskKey) {- if let existing = tasks[key], key.isSessionOnly,- let resolved = existing.resolvedTurnKey,- event.timestamp > (existing.startedAt ?? existing.lastEventAt) {- pendingTerminalTasks[resolved] = PendingTerminalTask(- task: existing,- supersededAt: event.timestamp,- deadline: Date().addingTimeInterval(Self.supersededTerminalGracePeriod)- )- }- }-- func updateAliasedPrompt(from event: ActivityRecord, key: ActivityTaskKey) -> Bool {- guard let existing = tasks.values.first(where: { $0.resolvedTurnKey == key && $0.key != key }) else {- return false- }- guard event.timestamp >= existing.lastMainEventAt else { return true }- var task = existing- task.mergeMetadata(from: event)- task.recordExecutionEvent(event)- task.recordEvent(at: event.timestamp)- tasks[existing.key] = task- return true- }-}diff --git a/CodexBar/Services/Activity/ActivityTask.swift b/CodexBar/Services/Activity/ActivityTask.swiftindex 6b4c523..6ac612c 100644--- a/CodexBar/Services/Activity/ActivityTask.swift+++ b/CodexBar/Services/Activity/ActivityTask.swift@@ -1,69 +1,29 @@import CryptoKitimport Foundation-enum ActivityTaskKey: Hashable {- case turn(session: String, turn: String)- case session(String)- case anonymous(project: String)-- init(event: ActivityRecord) {- if let sessionID = event.sessionID, let turnID = event.turnID {- self = .turn(session: sessionID, turn: turnID)- } else if let sessionID = event.sessionID {- self = .session(sessionID)- } else {- self = .anonymous(project: Self.projectIdentifier(event.projectDisplayName))- }- }-- var sessionID: String? {- switch self {- case let .turn(session, _), let .session(session): session- case .anonymous: nil- }- }-- var turnID: String? {- if case let .turn(_, turn) = self {- return turn- }- return nil- }+struct ActivityTaskKey: Hashable {+ let threadID: String+ let turnID: String- var isAnonymous: Bool {- if case .anonymous = self {- return true- }- return false+ init(thread: String, turn: String) {+ threadID = thread+ turnID = turn}- var isSessionOnly: Bool {- if case .session = self {- return true- }- return false+ init?(event: ActivityRecord) {+ guard let threadID = event.threadID, !threadID.isEmpty,+ let turnID = event.turnID, !turnID.isEmpty else { return nil }+ self.init(thread: threadID, turn: turnID)}- var protectionIdentifier: String? {- let value: String- switch self {- case let .turn(session, turn):- value = "turn\u{0}\(session)\u{0}\(turn)"- case let .session(session):- value = "session\u{0}\(session)"- case .anonymous:- return nil- }+ var protectionIdentifier: String {+ let value = "turn\u{0}\(threadID)\u{0}\(turnID)"// 哈希域固定不随代码命名变化, 避免同一任务生成不同的保护标识let data = Data("CodexBar.ActivityProtection.v1\u{0}\(value)".utf8)return SHA256.hash(data: data).map {String(format: "%02x", $0)}.joined()}-- static func projectIdentifier(_ project: String?) -> String {- project ?? "__codex__"- }}enum ActivityEventSource {@@ -71,18 +31,10 @@ enum ActivityEventSource {case live}-enum TerminalTaskMatch {- case active(ActivityTaskKey)- case pending(ActivityTaskKey)- case ambiguous- case none-}-enum ProtectionClearReason {case progresscase thresholdChangecase terminal- case retention}struct ProtectionCandidate {@@ -110,8 +62,6 @@ enum ActivityTaskState: Equatable {struct PendingTerminalTask {var task: ActivityTasklet supersededAt: Date- let deadline: Date- var nextPollAt: Date = .distantPastvar expiresAt: Date {supersededAt.addingTimeInterval(ActivityRetention.window)}@@ -120,23 +70,19 @@ struct PendingTerminalTask {struct ActivityTask {let displayID: UUIDlet key: ActivityTaskKey- var associatedTurnID: String?var lifecycleCoverageCheckedAt: Date?var terminalFailed = falsevar state: ActivityTaskStatevar projectName: String?var modelName: String?var effort: String?- var toolName: String?- var itemType: String?var startedAt: Date?var stateChangedAt: Date- var lastEventAt: Datevar lastProgressAt: Datevar progressGeneration: UInt64var executions: [ActivityExecutionKey: ActivityExecution] = [:]var subagentsByID: [String: SubagentObservation]- var isSubagentCountReliable: Bool+ var hasCompleteSubagentCoverage = falsevar tokenUsage: TokenUsage?init(@@ -149,30 +95,21 @@ struct ActivityTask {) {self.displayID = displayIDself.key = key- associatedTurnID = key.turnIDself.state = stateprojectName = event.projectDisplayNamemodelName = event.modeleffort = Self.normalizedEffort(event.effort)- toolName = event.tool- itemType = event.source?.itemTypeself.startedAt = startedAtstateChangedAt = event.timestamp- lastEventAt = event.timestamplastProgressAt = event.timestampself.progressGeneration = progressGenerationsubagentsByID = [:]- isSubagentCountReliable = startedAt != nilrecordExecutionEvent(event)}- var showsPreciseDuration: Bool {- startedAt != nil && !key.isAnonymous- }-/// 起点可信时返回到 end 的精确耗时, 起点缺失或晚于 end 时为 nilfunc preciseDuration(until end: Date) -> TimeInterval? {- guard showsPreciseDuration, let startedAt, end >= startedAt else {+ guard let startedAt, end >= startedAt else {return nil}return end.timeIntervalSince(startedAt)@@ -181,17 +118,14 @@ struct ActivityTask {var snapshot: ActivityTaskSnapshot {ActivityTaskSnapshot(id: displayID,- isAnonymous: key.isAnonymous,projectName: projectName,modelName: modelName,effort: effort,- toolName: displayedApproval.map(\.toolName) ?? toolName,startedAt: startedAt,stateChangedAt: stateChangedAt,- showsPreciseDuration: showsPreciseDuration,activeSubagentCount: activeSubagentCount,tokenUsage: tokenUsage,- itemType: displayedApproval.map(\.itemType) ?? itemType,+ approvalActionText: displayedApproval?.actionText,presentation: livePresentation)}@@ -209,22 +143,13 @@ struct ActivityTask {return result}- var turnReference: ActivityTurnReference? {- guard let sessionID = key.sessionID, let turnID = associatedTurnID else {- return nil- }- return ActivityTurnReference(- threadID: sessionID,- turnID: turnID,- startedAt: startedAt ?? lastActivityAt+ var turnReference: ActivityTurnReference {+ ActivityTurnReference(+ threadID: key.threadID,+ turnID: key.turnID)}- var resolvedTurnKey: ActivityTaskKey? {- guard let session = key.sessionID, let turn = associatedTurnID else { return nil }- return .turn(session: session, turn: turn)- }-var lastActivityAt: Date {lastProgressAt}@@ -249,25 +174,11 @@ struct ActivityTask {}mutating func mergeMetadata(from event: ActivityRecord) {- if associatedTurnID == nil, !key.isAnonymous, event.agentID == nil {- associatedTurnID = event.turnID+ if event.agentID == nil {+ projectName = event.projectDisplayName ?? projectName+ modelName = event.model ?? modelName}- projectName = event.projectDisplayName ?? projectName- modelName = event.model ?? modelName_ = mergeEffort(event.effort)- switch event.eventKind {- case .toolStarted, .toolCompleted, .approvalRequested:- toolName = event.tool- itemType = event.source?.itemType- default:- break- }- }-- /// 业务事件顺序独立于执行进展, 避免用量记录使稍早的状态事件失效- mutating func recordEvent(at timestamp: Date) {- lastEventAt = max(lastEventAt, timestamp)- recordProgress(at: timestamp)}mutating func recordProgress(at timestamp: Date) {@@ -298,7 +209,7 @@ struct ActivityTask {at timestamp: Date) {guard let agentID else {- isSubagentCountReliable = false+ hasCompleteSubagentCoverage = falsereturn}@@ -307,7 +218,7 @@ struct ActivityTask {return}if !isStarting, previous == nil {- isSubagentCountReliable = false+ hasCompleteSubagentCoverage = false}subagentsByID[agentID] = SubagentObservation(isRunning: isStarting && !hasEnded,@@ -316,7 +227,7 @@ struct ActivityTask {}private var activeSubagentCount: Int? {- guard isSubagentCountReliable else {+ guard hasCompleteSubagentCoverage else {return nil}return subagentsByID.values.reduce(into: 0) { count, observation in@@ -335,10 +246,7 @@ struct ActivityTask {}var displayedApproval: ActivityApproval? {- executions.values.compactMap { execution -> ActivityApproval? in- guard case let .waiting(approval)? = execution.approval else { return nil }- return approval- }.min {+ executions.values.compactMap(\.approval).min {if $0.requestedAt != $1.requestedAt {return $0.requestedAt < $1.requestedAt}@@ -368,64 +276,28 @@ struct ActivityTask {let owner = executionKey(for: event)var execution = executions[owner] ?? ActivityExecution()execution.lastEventAt = max(execution.lastEventAt, event.timestamp)- execution.mergeReviewer(event.approvalReviewer, at: event.timestamp)executions[owner] = execution}mutating func resumeExecution(from event: ActivityRecord) {recordExecutionEvent(event)- let owner = executionKey(for: event)- if owner.isReliable, var execution = executions[owner] {- execution.approval = nil- execution.lastExecutionProgressAt = max(execution.lastExecutionProgressAt ?? .distantPast, event.timestamp)- executions[owner] = execution- }refreshApprovalState(at: event.timestamp, restoresRunning: true)}- /// 审批路由未知时只保存候选, 后续上下文只能确认同一执行归属mutating func recordApprovalRequest(from event: ActivityRecord) -> Bool {let wasWaiting = state == .waitingApprovallet owner = executionKey(for: event)- guard event.timestamp > (executions[owner]?.lastApprovalRequestedAt ?? .distantPast),- event.timestamp >= (executions[owner]?.lastExecutionProgressAt ?? .distantPast) else { return false }recordExecutionEvent(event)- executions[owner]?.lastApprovalRequestedAt = event.timestampif executions[owner]?.approval == nil {- executions[owner]?.approval = .pending(ActivityApproval(- requestedAt: event.timestamp, toolName: event.tool, sequence: progressGeneration,- itemType: event.source?.itemType- ))+ executions[owner]?.approval = ActivityApproval(+ requestedAt: event.timestamp, toolName: event.toolName, sequence: progressGeneration,+ itemType: event.context?.itemType, commandActionTypes: event.commandActionTypes+ )}- _ = resolvePendingApprovals()+ refreshApprovalState(at: event.timestamp)return !wasWaiting && state == .waitingApproval}- @discardableResult- mutating func resolvePendingApprovals() -> Bool {- var changed = false- for owner in executions.keys {- guard var execution = executions[owner], case let .pending(pending)? = execution.approval,- let reviewer = execution.approvalReviewer else { continue }- execution.approval = reviewer == .user ? .waiting(pending) : nil- executions[owner] = execution- changed = true- }- if changed {- refreshApprovalState(at: displayedApproval?.requestedAt ?? lastProgressAt)- }- return changed- }-- mutating func mergeApprovalContext(- reviewer: ApprovalReviewer?, observedAt: Date?, owner: ActivityExecutionKey- ) {- guard let observedAt else { return }- var execution = executions[owner] ?? ActivityExecution()- execution.mergeReviewer(reviewer, at: observedAt)- executions[owner] = execution- }-mutating func mergeExecutionLifecycle(_ lifecycle: SessionLifecycleState, owner: ActivityExecutionKey) {guard lifecycle.readStatus == .complete else { return }var execution = executions[owner] ?? ActivityExecution()@@ -434,15 +306,18 @@ struct ActivityTask {if lifecycle.terminal != nil {finishExecution(owner, at: lifecycle.lastProgressAt ?? lastProgressAt)} else {- mergeApprovalContext(reviewer: lifecycle.approvalReviewer, observedAt: lifecycle.contextObservedAt, owner: owner)- mergeExecutionProgress(at: lifecycle.lastExecutionProgressAt, owner: owner)if let waiting = lifecycle.isWaitingApproval, let changedAt = lifecycle.approvalChangedAt {var execution = executions[owner] ?? ActivityExecution()if waiting {- let approval = execution.approval?.request ?? ActivityApproval(+ let approval = lifecycle.pendingApprovals.min {+ if $0.value.requestedAt != $1.value.requestedAt {+ return $0.value.requestedAt < $1.value.requestedAt+ }+ return $0.key < $1.key+ }?.value ?? ActivityApproval(requestedAt: changedAt, toolName: nil, sequence: progressGeneration)- execution.approval = .waiting(approval)+ execution.approval = approval} else {execution.approval = nil}@@ -452,17 +327,6 @@ struct ActivityTask {}}- mutating func mergeExecutionProgress(at timestamp: Date?, owner: ActivityExecutionKey) {- guard owner.isReliable, let timestamp else { return }- var execution = executions[owner] ?? ActivityExecution()- execution.lastExecutionProgressAt = max(execution.lastExecutionProgressAt ?? .distantPast, timestamp)- if let approval = execution.approval, timestamp > approval.request.requestedAt {- execution.approval = nil- }- executions[owner] = execution- refreshApprovalState(at: timestamp)- }-mutating func finishExecution(_ owner: ActivityExecutionKey, at timestamp: Date) {var execution = executions[owner] ?? ActivityExecution()execution.approval = nil@@ -491,45 +355,25 @@ struct ActivityExecutionKey: Hashable {let agentID: String?let turnID: String?var isUnattributed = false-- var isReliable: Bool {- turnID != nil && !isUnattributed- }}-struct ActivityApproval {+nonisolated struct ActivityApproval {let requestedAt: Datelet toolName: String?let sequence: UInt64var itemType: String?-}--enum ActivityApprovalState {- case pending(ActivityApproval)- case waiting(ActivityApproval)+ var commandActionTypes: [String]?- var request: ActivityApproval {- switch self {- case let .pending(request), let .waiting(request): request- }+ var actionText: String? {+ ActivityDisplayFormat.toolActionText(itemType: itemType, toolName: toolName, commandActionTypes: commandActionTypes)}}struct ActivityExecution {var lastEventAt: Date = .distantPast- var approvalReviewer: ApprovalReviewer?- var approvalContextObservedAt: Date?- var lastExecutionProgressAt: Date?- var lastApprovalRequestedAt: Date?- var approval: ActivityApprovalState?+ var approval: ActivityApproval?var isTerminal = falsevar presentation: ActivityLivePresentation?-- mutating func mergeReviewer(_ reviewer: ApprovalReviewer?, at timestamp: Date) {- guard let reviewer, timestamp >= (approvalContextObservedAt ?? .distantPast) else { return }- approvalReviewer = reviewer- approvalContextObservedAt = timestamp- }}struct SubagentObservation {diff --git a/CodexBar/Services/Activity/AppServerActivityModels.swift b/CodexBar/Services/Activity/AppServerActivityModels.swiftindex 6cf233b..0f3150f 100644--- a/CodexBar/Services/Activity/AppServerActivityModels.swift+++ b/CodexBar/Services/Activity/AppServerActivityModels.swift@@ -1,10 +1,12 @@-nonisolated struct ActivityThread: Decodable {+import Foundation++private nonisolated struct WireActivityThread: Decodable {let id: Stringvar cwd: String?var model: String?var reasoningEffort: String?- var status: ActivityThreadStatus?- var source: ActivityThreadSource?+ var status: WireActivityThreadStatus?+ var source: WireActivityThreadSource?var parentThreadId: String?var createdAt: Double?@@ -17,7 +19,7 @@ nonisolated struct ActivityThread: Decodable {}}-nonisolated struct ActivityThreadStatus: Decodable {+private nonisolated struct WireActivityThreadStatus: Decodable {let type: Stringvar activeFlags: [String]?var isWaiting: Bool {@@ -25,7 +27,7 @@ nonisolated struct ActivityThreadStatus: Decodable {}}-nonisolated struct ActivityThreadSource: Decodable {+private nonisolated struct WireActivityThreadSource: Decodable {let origin: ActivityOriginlet parentID: String?@@ -103,15 +105,17 @@ indirect nonisolated enum ActivityJSONValue: Decodable {}}-nonisolated struct ActivityTurn: Decodable {+private nonisolated struct WireActivityTurn: Decodable {let id: Stringlet status: String+ var rootTurnId: String?+ var items: [WireActivityItem]?var startedAt: Double?var completedAt: Double?var durationMs: Double?}-nonisolated struct ActivityItem: Decodable {+private nonisolated struct WireActivityItem: Decodable {struct CommandAction: Decodable {let type: String}@@ -120,8 +124,11 @@ nonisolated struct ActivityItem: Decodable {let type: Stringvar status: String?var tool: String?+ var server: String?var agentThreadId: String?var kind: String?+ var model: String?+ var reasoningEffort: String?var commandActions: [CommandAction]?var phase: String?var action: WebAction?@@ -130,31 +137,9 @@ nonisolated struct ActivityItem: Decodable {struct WebAction: Decodable { var type: String? }struct AgentState: Decodable { var status: String? }-- var toolDisplayName: String? {- guard type == "commandExecution" else { return tool }- var seen: Set<String> = []- let types = (commandActions ?? []).map(\.type).filter {- !$0.isEmpty && $0 != "unknown" && seen.insert($0).inserted- }- return types.isEmpty ? nil : types.joined(separator: "/")- }-- /// 调用类型决定是否计数, 具体工具名缺失不影响分类- var isToolCall: Bool {- Self.isToolType(type)- }-- static func isToolType(_ type: String) -> Bool {- switch type {- case "commandExecution", "fileChange", "webSearch", "imageView", "imageGeneration", "sleep",- "mcpToolCall", "dynamicToolCall", "collabAgentToolCall": true- default: false- }- }}-nonisolated struct ActivityTokenBreakdown: Decodable {+private nonisolated struct WireActivityTokenBreakdown: Decodable {let inputTokens: Int64let cachedInputTokens: Int64var cacheWriteInputTokens: Int64?@@ -170,83 +155,62 @@ nonisolated struct ActivityTokenBreakdown: Decodable {}}-nonisolated struct ActivityTokenUpdate: Decodable {- let total: ActivityTokenBreakdown- let last: ActivityTokenBreakdown+private nonisolated struct WireActivityTokenUpdate: Decodable {+ let total: WireActivityTokenBreakdown+ let last: WireActivityTokenBreakdown}-nonisolated struct ActivityNotification: Decodable {- enum Category {- case state- case progress- case presentation- case ignored- }-- /// 方法名称相似不代表协议含义相同, 采集和日志共用完整名称分类- static func category(for method: String) -> Category {- switch method {- case "thread/started", "thread/status/changed", "thread/settings/updated", "thread/tokenUsage/updated",- "turn/started", "turn/completed", "item/started", "item/completed", "item/autoApprovalReview/started",- "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "item/permissions/requestApproval", "serverRequest/resolved":- .state- case "item/agentMessage/delta", "item/plan/delta", "item/reasoning/textDelta", "item/reasoning/summaryTextDelta",- "item/commandExecution/outputDelta", "item/fileChange/outputDelta":- .progress- case "item/tool/requestUserInput", "mcpServer/elicitation/request", "item/autoApprovalReview/completed",- "turn/plan/updated", "turn/diff/updated", "model/rerouted", "model/verification",- "modelProvider/authRecoveryStarted", "modelProvider/authRecoveryCompleted", "model/safetyBuffering/updated",- "thread/environment/connected", "thread/environment/disconnected", "hook/started", "hook/completed",- "mcpServer/startupStatus/updated", "error":- .presentation- default:- .ignored- }+private nonisolated struct WireActivityInput: Decodable {+ struct Params: Decodable {+ var threadId: String?+ var turnId: String?+ var itemId: String?+ var approvalId: String?+ var requestId: ActivityJSONValue?+ var thread: WireActivityThread?+ var turn: WireActivityTurn?+ var item: WireActivityItem?+ var status: WireActivityThreadStatus?+ var startedAtMs: Double?+ var completedAtMs: Double?+ var tokenUsage: WireActivityTokenUpdate?+ var commandActions: [WireActivityItem.CommandAction]?}let id: ActivityJSONValue?- let method: String+ let kind: ActivityInput.Kind+ let provenanceMethod: Stringlet params: Params- let live: ActivityLivePayload+ let live: WireActivityLivePayloadprivate enum CodingKeys: String, CodingKey { case id, method, params }init(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self)id = try container.decodeIfPresent(ActivityJSONValue.self, forKey: .id)- method = try container.decode(String.self, forKey: .method)- live = try container.decode(ActivityLivePayload.self, forKey: .params)+ provenanceMethod = try container.decode(String.self, forKey: .method)+ kind = AppServerActivityProtocol.kind(for: provenanceMethod)+ live = try container.decode(WireActivityLivePayload.self, forKey: .params)// 展示通知有不同的 status 类型, 不交给线程生命周期解码器解释- if Self.category(for: method) == .presentation {- params = Params(threadId: live.threadId, turnId: live.turnId, targetItemId: live.targetItemId, reviewId: live.reviewId)+ if kind.category == .presentation {+ params = Params(threadId: live.threadId, turnId: live.turnId)} else {params = try container.decode(Params.self, forKey: .params)+ switch kind {+ case .itemStarted, .itemFinished, .usageUpdated,+ .commandApprovalRequested, .fileApprovalRequested, .permissionsRequested,+ .replyProgress, .reasoningProgress, .reasoningSummaryProgress, .commandProgress:+ guard let turnID = params.turnId, !turnID.isEmpty else {+ throw DecodingError.dataCorruptedError(forKey: .params, in: container, debugDescription: "Missing turn identity")+ }+ default: break+ }+ if [.commandApprovalRequested, .fileApprovalRequested, .permissionsRequested].contains(kind),+ params.itemId == nil || params.startedAtMs == nil {+ throw DecodingError.dataCorruptedError(forKey: .params, in: container, debugDescription: "Missing approval identity")+ }}}-- struct Params: Decodable {- var threadId: String?- var turnId: String?- var itemId: String?- var requestId: ActivityJSONValue?- var targetItemId: String?- var reviewId: String?- var thread: ActivityThread?- var turn: ActivityTurn?- var item: ActivityItem?- var status: ActivityThreadStatus?- var threadSettings: Settings?- var startedAtMs: Double?- var completedAtMs: Double?- var tokenUsage: ActivityTokenUpdate?- }-- struct Settings: Decodable {- var model: String?- var effort: String?- var cwd: String?- var approvalsReviewer: ActivityApprovalReviewer?- }}nonisolated struct ActivityThreadRead: Decodable { let thread: ActivityThread }@@ -260,24 +224,199 @@ nonisolated struct ActivityTurnsPage: Decodable { let data: [ActivityTurn]nonisolated struct ActivityThreadResume: Decodable {let thread: ActivityThread- var model: String?- var reasoningEffort: String?- var approvalsReviewer: ActivityApprovalReviewer?}-/// Codex 协议使用 snake_case, 本地持久化使用业务枚举本身的名称-nonisolated struct ActivityApprovalReviewer: Decodable {- let value: ApprovalReviewer+nonisolated enum AppServerActivityProtocol {+ static func observes(itemType: String) -> Bool {+ ActivityItem.isObservedType(.init(rawValue: itemType) ?? .unknown)+ }++ static func kind(for method: String) -> ActivityInput.Kind {+ switch method {+ case "thread/started": .threadDiscovered+ case "thread/status/changed": .threadStatusChanged+ case "thread/tokenUsage/updated": .usageUpdated+ case "turn/started": .turnStarted+ case "turn/completed": .turnFinished+ case "item/started": .itemStarted+ case "item/completed": .itemFinished+ case "item/commandExecution/requestApproval": .commandApprovalRequested+ case "item/fileChange/requestApproval": .fileApprovalRequested+ case "item/permissions/requestApproval": .permissionsRequested+ case "serverRequest/resolved": .requestResolved+ case "item/agentMessage/delta": .replyProgress+ case "item/reasoning/textDelta": .reasoningProgress+ case "item/reasoning/summaryTextDelta": .reasoningSummaryProgress+ case "item/commandExecution/outputDelta": .commandProgress+ case "mcpServer/elicitation/request": .inputRequested+ case "turn/plan/updated": .planChanged+ case "turn/diff/updated": .diffChanged+ case "model/rerouted": .modelChanged+ case "model/verification": .verificationRequested+ case "modelProvider/authRecoveryStarted": .authRecoveryStarted+ case "modelProvider/authRecoveryCompleted": .authRecoveryFinished+ case "model/safetyBuffering/updated": .safetyBufferingChanged+ case "hook/started": .hookStarted+ case "hook/completed": .hookFinished+ case "error": .errorReported+ default: .ignored+ }+ }+}++nonisolated extension ActivityThread: Decodable {+ init(from decoder: Decoder) throws {+ let wire = try WireActivityThread(from: decoder)+ self.init(+ id: wire.id,+ cwd: wire.cwd,+ model: wire.model,+ reasoningEffort: wire.reasoningEffort,+ status: wire.status.map(Self.status),+ origin: wire.origin,+ parentID: wire.parentID,+ createdAt: wire.createdAt.map(Date.init(timeIntervalSince1970:))+ )+ }+ fileprivate static func status(_ value: WireActivityThreadStatus) -> ActivityThreadStatus {+ ActivityThreadStatus(+ type: .init(rawValue: value.type) ?? .unknown,+ activeFlags: value.activeFlags?.map { .init(rawValue: $0) ?? .unknown }+ )+ }+}++nonisolated extension ActivityTurn: Decodable {init(from decoder: Decoder) throws {- let container = try decoder.singleValueContainer()- let raw = try container.decode(String.self)- switch raw {- case "user": value = .user- case "auto_review": value = .autoReview- case "guardian_subagent": value = .guardianSubagent- default:- throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unknown approval reviewer")+ self = try WireActivityTurn(from: decoder).normalized+ }+}++private nonisolated extension WireActivityTurn {+ var normalized: ActivityTurn {+ ActivityTurn(+ id: id,+ status: status == "inProgress" ? .running : ActivityTurnStatus(rawValue: status) ?? .unknown,+ rootTurnId: rootTurnId,+ items: items?.map(\.normalized),+ startedAt: startedAt.map(Date.init(timeIntervalSince1970:)),+ completedAt: completedAt.map(Date.init(timeIntervalSince1970:)),+ duration: durationMs.map { $0 / 1000 }+ )+ }+}++private nonisolated extension WireActivityItem {+ var normalized: ActivityItem {+ ActivityItem(+ id: id,+ type: .init(rawValue: type) ?? .unknown,+ status: status,+ tool: tool,+ server: server,+ agentThreadId: agentThreadId,+ kind: kind,+ model: model,+ reasoningEffort: reasoningEffort,+ commandActions: commandActions?.map { .init(type: $0.type) },+ phase: phase,+ action: action.map { .init(type: $0.type) },+ success: success,+ agentsStates: agentsStates?.mapValues { .init(status: $0.status) }+ )+ }+}++nonisolated extension ActivityInput: Decodable {+ init(from decoder: Decoder) throws {+ let wire = try WireActivityInput(from: decoder)+ let raw = wire.params+ let thread = raw.thread.map { value in+ ActivityThread(+ id: value.id,+ cwd: value.cwd,+ model: value.model,+ reasoningEffort: value.reasoningEffort,+ status: value.status.map(ActivityThread.status),+ origin: value.origin,+ parentID: value.parentID,+ createdAt: value.createdAt.map(Date.init(timeIntervalSince1970:))+ )+ }+ self.init(+ id: wire.id?.identifier,+ kind: wire.kind,+ provenanceMethod: wire.provenanceMethod,+ params: Params(+ threadId: raw.threadId,+ turnId: raw.turnId,+ itemId: raw.itemId,+ approvalId: raw.approvalId,+ requestId: raw.requestId?.identifier,+ thread: thread,+ turn: raw.turn?.normalized,+ item: raw.item?.normalized,+ status: raw.status.map(ActivityThread.status),+ startedAt: raw.startedAtMs.map { Date(timeIntervalSince1970: $0 / 1000) },+ completedAt: raw.completedAtMs.map { Date(timeIntervalSince1970: $0 / 1000) },+ tokenUsage: raw.tokenUsage.map { ActivityTokenUpdate(total: $0.total.usage, last: $0.last.usage) },+ commandActions: raw.commandActions?.map { .init(type: $0.type) }+ ),+ live: wire.live.normalized+ )+ }+}++/// 只解码展示所需的协议元数据, 不保留回答, 命令, 路径, 表单或认证正文+private nonisolated struct WireActivityLivePayload: Decodable {+ var threadId: String?+ var turnId: String?+ var mode: String?+ var plan: [Status]?+ var run: Hook?+ var showBufferingUi: Bool?+ var willRetry: Bool?+ var fromModel: String?+ var toModel: String?+ var verifications: [String]?++ struct Status: Decodable { var status: String? }+ struct Hook: Decodable {+ let id: String+ var status: String?+ var executionMode: String?+ }+}++private nonisolated extension WireActivityLivePayload {+ var normalized: ActivityLiveContext {+ let inputMode: ActivityLiveContext.InputMode = switch mode {+ case "form", "openai/form", "openaiForm": .form+ case "url": .external+ case "openai/userVerification": .verification+ default: .service}+ return ActivityLiveContext(+ inputMode: inputMode,+ planCompleted: plan.map { $0.filter { $0.status == "completed" }.count },+ planTotal: plan?.count,+ run: run.map { .init(id: $0.id, status: $0.status.map { .init(rawValue: $0) ?? .unknown }, isSynchronous: $0.executionMode == "sync") },+ isSafetyBuffering: showBufferingUi == true,+ willRetry: willRetry,+ fromModel: fromModel,+ toModel: toModel,+ requiresVerification: verifications?.isEmpty == false+ )+ }+}++nonisolated extension AppServerActivityProtocol {+ static func recoveryThreadID(from data: Data) -> String? {+ guard let envelope = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let params = envelope["params"] as? [String: Any],+ let thread = params["threadId"] as? String ?? (params["thread"] as? [String: Any])?["id"] as? String,+ !thread.isEmpty else { return nil }+ return thread}}diff --git a/CodexBar/Services/Activity/AppServerActivityReader.swift b/CodexBar/Services/Activity/AppServerActivityReader.swiftindex 13a6a8a..6eee93e 100644--- a/CodexBar/Services/Activity/AppServerActivityReader.swift+++ b/CodexBar/Services/Activity/AppServerActivityReader.swift@@ -2,7 +2,7 @@ import Foundationnonisolated enum ActivityEventBatch {case bootstrapStart- case bootstrapEvents([ActivityRecord])+ case snapshotEvents([ActivityRecord])case bootstrapEndcase live([ActivityRecord])case sourceUnavailable@@ -22,55 +22,82 @@ actor AppServerActivityReader {}private let lifecycleCache: SessionLifecycleCache+ private let onAccountChange: @MainActor @Sendable (AccountChange) -> Void+ private var pendingAccountChange: AccountChange?private let onBatch: @MainActor @Sendable (ActivityEventBatch) -> Voidprivate let socketURL: URL+ private let logStorage: AppServerLogStore?private let tokenHistory: TokenHistoryStoreprivate let recorder: ActivityRecorderprivate var session: AppServerSession?private var reducer = AppServerActivityReducer()private var subscribed = Set<String>()private var loop: Task<Void, Never>?+ private var storageTask: Task<Void, Never>?+ private var tokenRefreshTask: Task<[TokenTurn], Error>?private var generation = 0private var connectedAt = Date.distantFutureprivate var reconciledAt = Date.distantPastprivate var lastTokenRefresh = Date.distantPastprivate var isRunning = falseprivate var isStopping = false- private var stopWaiters: [CheckedContinuation<Void, Never>] = []+ private var stopWaiters: [CheckedContinuation<Bool, Never>] = []private var stateChanged = falseprivate var lastPublished = Date.distantPastprivate var isTokenWriter = false+ private var writerRetryAfter = Date.distantPastprivate var drainWaiters: [CheckedContinuation<ActivityEventDrainResult, Never>] = []- private var pendingEvents: [ActivityRecord] = []+ private var pendingEvents: [(event: ActivityRecord, bytes: Int)] = []private var pendingPublication: [ActivityRecord] = []- private var pendingObservations: [TokenObservation] = []- private var deferredNotifications: [ActivityNotification] = []- private var verifiedThreads: [String: Date] = [:]+ private var pendingObservations: [(observation: TokenObservation, bytes: Int)] = []+ private var pendingStorageBytes = 0+ private var deferredNotifications: [ActivityInput] = []+ private var verifiedTurns: [ActivityTurnReference: Date] = [:]+ private var turnCursors: [String: String] = [:]++ private struct TurnReadResult {+ var turns: [ActivityTurn]+ var remaining: Set<String>+ var cursor: String?+ }+private var checkedThreads: [String: Date] = [:]private var revisions: [String: Int] = [:]private var preparingThread: String?private var invalidThreads = Set<String>()private var storageRetryAfter = Date.distantPastprivate var storageFailed = false- private var storagePaused = false+ private var isHistoryRecordingPaused = false+ private var tokenRefreshFailed = false+ private var tokenRetryAfter = Date.distantPastprivate let maximumPendingEvents: Intprivate let maximumPendingBytes: Int+ private let maximumLoadedPages: Int+ private let reconciliationTimeout: TimeIntervalinit(lifecycleCache: SessionLifecycleCache,socketURL: URL = AppServerActivityReader.defaultSocketURL,+ logStorage: AppServerLogStore? = .shared,tokenHistory: TokenHistoryStore = TokenHistoryStore(),recorder: ActivityRecorder = ActivityRecorder(),maximumPendingEvents: Int = 4096,maximumPendingBytes: Int = 8 * 1024 * 1024,+ maximumLoadedPages: Int = 100,+ reconciliationTimeout: TimeInterval = 30,+ onAccountChange: @escaping @MainActor @Sendable (AccountChange) -> Void = { _ in },onBatch: @escaping @MainActor @Sendable (ActivityEventBatch) -> Void) {self.lifecycleCache = lifecycleCacheself.socketURL = socketURL+ self.logStorage = logStorageself.tokenHistory = tokenHistoryself.recorder = recorderself.maximumPendingEvents = maximumPendingEventsself.maximumPendingBytes = maximumPendingBytes+ self.maximumLoadedPages = maximumLoadedPages+ self.reconciliationTimeout = reconciliationTimeout+ self.onAccountChange = onAccountChangeself.onBatch = onBatch}@@ -79,25 +106,28 @@ actor AppServerActivityReader {isRunning = truegeneration += 1let current = generation+ startStorageWorker()loop = Task { [weak self] in await self?.run(generation: current) }}- func stop() async {+ @discardableResult+ func stop() async -> Bool {if isStopping {- await withCheckedContinuation { stopWaiters.append($0) }- return+ return await withCheckedContinuation { stopWaiters.append($0) }}isStopping = true+ var saved = falsedefer {isStopping = falselet waiters = stopWaitersstopWaiters.removeAll()for waiter in waiters {- waiter.resume()+ waiter.resume(returning: saved)}}isRunning = falsegeneration += 1+ tokenRefreshTask?.cancel()let previous = loopprevious?.cancel()loop = nil@@ -105,11 +135,26 @@ actor AppServerActivityReader {session = nilsubscribed.removeAll()await previous?.value- try? await persistPending()+ pendingAccountChange = nil+ pendingPublication.removeAll()+ deferredNotifications.removeAll()+ verifiedTurns.removeAll()+ turnCursors.removeAll()+ checkedThreads.removeAll()+ invalidThreads.removeAll()+ if storageTask == nil, !pendingEvents.isEmpty || !pendingObservations.isEmpty {+ startStorageWorker()+ }+ // 退出只给已接收记录有限的排空时间, 慢文件操作不能卡住 App 退出+ let deadline = ContinuousClock.now.advanced(by: .seconds(2))+ while storageTask != nil, ContinuousClock.now < deadline, !Task.isCancelled {+ try? await Task.sleep(for: .milliseconds(10))+ }+ saved = storageTask == nil && pendingEvents.isEmpty && pendingObservations.isEmpty+ storageTask?.cancel()completeDrains(.cancelled)- isTokenWriter = false- await tokenHistory.releaseRecordingLease()await lifecycleCache.invalidate()+ return saved}/// 每次调用执行本次请求之后的查询, 不复用正在进行的旧快照@@ -122,25 +167,18 @@ actor AppServerActivityReader {private func run(generation current: Int) async {while isRunning, generation == current, !Task.isCancelled {do {- if storagePaused {- guard await retryStorage() else {- try await Task.sleep(for: .milliseconds(100))- continue- }- storagePaused = false- }if session == nil {try await connect(generation: current)}- try await acquireTokenWriter(generation: current)try await consumeAvailable(generation: current)if !drainWaiters.isEmpty || Date().timeIntervalSince(reconciledAt) >= 2 {let waiters = drainWaitersdrainWaiters.removeAll()do {- try await reconcile(bootstrap: false, forced: !waiters.isEmpty, generation: current)+ let covered = try await reconcile(bootstrap: false, forced: !waiters.isEmpty, generation: current)try await consumeAvailable(generation: current)- let result: ActivityEventDrainResult = isRunning && generation == current && !Task.isCancelled ? .completed : .cancelled+ let result: ActivityEventDrainResult = isRunning && generation == current && !Task+ .isCancelled ? (covered ? .completed : .sourceUnavailable) : .cancelledfor waiter in waiters {waiter.resume(returning: result)}@@ -163,50 +201,49 @@ actor AppServerActivityReader {}private func connect(generation current: Int) async throws {- // 存储未准备好时不创建连接, 避免本地故障触发重复初始化- isTokenWriter = try await tokenHistory.acquireRecordingLease()- try await persistPending()- let persistedTokens = try await tokenHistory.refresh()+ reducer.reconnect()+ reducer.setTokenRecordingEnabled(isTokenWriter && !isHistoryRecordingPaused)try checkGeneration(current)await onBatch(.bootstrapStart)try checkGeneration(current)- let connection = try AppServerSession(socketURL: socketURL)+ let connection = try AppServerSession(socketURL: socketURL, logStorage: logStorage)do {- try connection.initialize()+ try connection.initialize(clientName: "codex_bar_activity", minimumVersion: CodexVersionReader.minimumAppServerVersion)} catch {connection.close()throw error}session = connectionconnectedAt = Date()- reducer.reconnect()- reducer.restoreTokenTurns(persistedTokens)- try await reconcile(bootstrap: true, forced: true, generation: current)+ _ = try await reconcile(bootstrap: true, forced: true, generation: current)try checkGeneration(current)await onBatch(.bootstrapEnd)}private func acquireTokenWriter(generation current: Int) async throws {- guard !isTokenWriter, Date() >= storageRetryAfter else { return }+ guard !isTokenWriter, Date() >= writerRetryAfter else { return }do {if try await tokenHistory.acquireRecordingLease() {- try await persistPending()- let persistedTokens = try await tokenHistory.refresh()try checkGeneration(current)- reducer.restoreTokenTurns(persistedTokens)isTokenWriter = true+ writerRetryAfter = .distantPast+ reducer.setTokenRecordingEnabled(!isHistoryRecordingPaused)+ } else {+ writerRetryAfter = Date().addingTimeInterval(1)}} catch is CancellationError {throw CancellationError()} catch {- recordStorageFailure(error)+ if writerRetryAfter == .distantPast {+ logStorage?.recordFailure(method: "activity/storage", message: error.localizedDescription, connection: "activity")+ }+ writerRetryAfter = Date().addingTimeInterval(1)}}private func recover(from error: Error, generation current: Int) async {guard generation == current, isRunning else { return }- let method = error is StorageBacklogFull || session == nil && !(error is CodexStatusError) ? "activity/storage" : "activity/connection"- AppServerLogStore.shared.recordFailure(method: method, message: error.localizedDescription, connection: "activity")+ logStorage?.recordFailure(method: "activity/connection", message: error.localizedDescription, connection: "activity")// 后续协议错误不能丢掉前面已取得的有效结果, 存储失败时保留队列供下一轮重试try? await flushPending(generation: current)guard generation == current, isRunning else { return }@@ -227,59 +264,91 @@ actor AppServerActivityReader {session = nilsubscribed.removeAll()deferredNotifications.removeAll()- verifiedThreads.removeAll()+ pendingAccountChange = nil+ verifiedTurns.removeAll()+ turnCursors.removeAll()invalidThreads.removeAll()checkedThreads.removeAll()- isTokenWriter = false- await tokenHistory.releaseRecordingLease()await lifecycleCache.invalidate()await onBatch(.sourceUnavailable)}- private func reconcile(bootstrap: Bool, forced: Bool, generation current: Int) async throws {+ private func reconcile(bootstrap: Bool, forced: Bool, generation current: Int) async throws -> Bool {+ let budget = AppServerRequestBudget(deadline: Date().addingTimeInterval(reconciliationTimeout))+ return try await AppServerRequestBudget.$current.withValue(budget) {+ try await reconcileWithinBudget(bootstrap: bootstrap, forced: forced, generation: current)+ }+ }++ private func loadThreads(generation current: Int) async throws -> Set<String> {var loaded = Set<String>()var cursor: String?- repeat {- var params: [String: Any] = ["limit": 100]- if let cursor {- params["cursor"] = cursor- }- let page: ActivityLoadedPage = try await request("thread/loaded/list", params: params, generation: current)+ var cursors = Set<String>()+ for _ in 0 ..< maximumLoadedPages {+ let page = try await request(ActivityRequests.loadedThreads(cursor: cursor), generation: current)loaded.formUnion(page.data)- cursor = page.nextCursor- } while cursor != nil && loaded.count < 10000+ guard loaded.count <= 10000 else { throw CodexStatusError.invalidServerResponse }+ guard let next = page.nextCursor else { return loaded }+ guard cursors.insert(next).inserted else { throw CodexStatusError.invalidServerResponse }+ cursor = next+ }+ // 不发布截断列表, 否则未读取的线程会被错误地当作已经卸载+ throw CodexStatusError.invalidServerResponse+ }++ private func reconcileWithinBudget(bootstrap: Bool, forced: Bool, generation current: Int) async throws -> Bool {+ let loaded = try await loadThreads(generation: current)let knownActive = Set(reducer.states.keys.filter {- reducer.states[$0]?.terminal == nil && reducer.threads[$0.threadID]?.status?.type != "notLoaded"+ reducer.states[$0]?.terminal == nil && reducer.threads[$0.threadID]?.status?.type != .notLoaded}.map(\.threadID))let now = Date()- let candidates = loaded.union(knownActive).filter { id in- let interval: TimeInterval = invalidThreads.contains(id) || knownActive.contains(id) || reducer.threads[id]?.status?.type == "active" ? 5 : 60+ let dependencies = Set(reducer.missingRootTurns(liveOnly: forced).keys)+ .union(reducer.missingSubagentParents(liveOnly: forced))+ let required = loaded.union(knownActive).union(reducer.missingRootTurns(liveOnly: true).keys)+ .union(reducer.missingSubagentParents(liveOnly: true))+ let candidates = loaded.union(knownActive).union(dependencies).filter { id in+ let interval: TimeInterval = invalidThreads.contains(id) || knownActive.contains(id)+ || dependencies.contains(id) || reducer.threads[id]?.status?.type == .active ? 5 : 60return forced || now.timeIntervalSince(checkedThreads[id] ?? .distantPast) >= interval- }.sorted { (checkedThreads[$0] ?? .distantPast, $0) < (checkedThreads[$1] ?? .distantPast, $1) }+ }.sorted {+ if required.contains($0) != required.contains($1) {+ return required.contains($0)+ }+ return (checkedThreads[$0] ?? .distantPast, $0) < (checkedThreads[$1] ?? .distantPast, $1)+ }let deadline = ContinuousClock.now.advanced(by: .seconds(1))+ var covered = truefor id in candidates {try checkGeneration(current)- try await reconcileThread(id, loaded: loaded, bootstrap: bootstrap, generation: current)+ let verified = try await reconcileThread(id, loaded: loaded, bootstrap: bootstrap, forced: forced, generation: current)+ if loaded.contains(id) || knownActive.contains(id) {+ covered = covered && verified+ }// 日常核对分轮执行, 强制排空则等待本轮完整覆盖if !forced, ContinuousClock.now >= deadline {break}}+ reducer.maintain(loadedThreads: loaded, now: Date())subscribed.formIntersection(loaded)- let retained = loaded.union(knownActive)+ let retained = loaded.union(knownActive).union(dependencies)checkedThreads = checkedThreads.filter { retained.contains($0.key) }revisions = revisions.filter { retained.contains($0.key) }- verifiedThreads = verifiedThreads.filter { retained.contains($0.key) }+ verifiedTurns = verifiedTurns.filter { reducer.states[$0.key] != nil && retained.contains($0.key.threadID) }+ turnCursors = turnCursors.filter { retained.contains($0.key) }invalidThreads.formIntersection(retained)reconciledAt = Date()- await lifecycleCache.replace(reducer.states, verifiedThreads: verifiedThreads)+ await lifecycleCache.replace(reducer.states, verifiedTurns: verifiedTurns)try checkGeneration(current)if !bootstrap {await onBatch(.lifecycleChanged)}+ return covered && !reducer.states.values.contains {+ $0.terminal == nil && ($0.rootThreadID == nil || $0.rootTurnID == nil)+ }}- private func reconcileThread(_ id: String, loaded: Set<String>, bootstrap: Bool, generation current: Int) async throws {+ private func reconcileThread(_ id: String, loaded: Set<String>, bootstrap: Bool, forced: Bool, generation current: Int) async throws -> Bool {let started = Date()let revision = revisions[id, default: 0]let newSubscription = !subscribed.contains(id)@@ -287,40 +356,49 @@ actor AppServerActivityReader {preparingThread = id}defer { preparingThread = nil }+ var covered = falsedo {- let read: ActivityThreadRead = try await request("thread/read", params: ["threadId": id, "includeTurns": false], generation: current)+ let read: ActivityThreadRead = try await request(ActivityRequests.thread(id), generation: current)var thread = read.thread- var reviewer: ApprovalReviewer?- if loaded.contains(id), newSubscription, thread.status?.type != "notLoaded" {+ if loaded.contains(id), newSubscription, thread.status?.type != .notLoaded {let joined: ActivityThreadResume = try await request(- "thread/resume", params: ["threadId": id, "excludeTurns": true], generation: current+ ActivityRequests.subscribe(id), generation: current)thread = joined.thread- thread.model = joined.model ?? thread.model- thread.reasoningEffort = joined.reasoningEffort ?? thread.reasoningEffort- reviewer = joined.approvalsReviewer?.valuesubscribed.insert(id)}if newSubscription {reducer.threads[id] = thread}- let turns: ActivityTurnsPage = try await request(- "thread/turns/list", params: ["threadId": id, "limit": 10, "itemsView": "summary"], generation: current+ let includesItems = newSubscription || !reducer.missingSubagentContexts(in: id, liveOnly: forced).isEmpty+ let first: ActivityTurnsPage = try await request(+ ActivityRequests.turns(id, limit: 10, includesItems: includesItems), generation: current)- if newSubscription, turns.data.count <= 1, turns.data.allSatisfy({ $0.status == "inProgress" }),- let created = thread.createdAt, created >= connectedAt.timeIntervalSince1970 {+ if newSubscription, first.nextCursor == nil, first.data.count <= 1,+ first.data.allSatisfy({ $0.status == .running }),+ let created = thread.createdAt, created >= connectedAt {reducer.markNewThread(id)}- // 查询期间收到的新状态优先, 不用旧响应倒退实时状态+ let result = try await readRemainingTurns(id, first: first, includesItems: includesItems, forced: forced, generation: current)+ // 查询期间收到的新状态优先, 不用旧响应倒退实时状态或刷新其验证时间if revision == revisions[id, default: 0] {- let events = reducer.reconcile(thread: thread, turns: turns.data, reviewer: reviewer, now: Date(), bootstrap: bootstrap || newSubscription)- if !events.isEmpty {- await onBatch(.bootstrapEvents(events))+ let events = reducer.reconcile(thread: thread, turns: result.turns, now: Date(), bootstrap: bootstrap || newSubscription)+ for turn in result.turns {+ verifiedTurns[ActivityTurnReference(threadID: id, turnID: turn.id)] = started}- }- if !invalidThreads.contains(id) || revision == revisions[id, default: 0] {+ for turnID in result.remaining {+ let key = ActivityTurnReference(threadID: id, turnID: turnID)+ verifiedTurns[key] = nil+ reducer.states[key]?.readStatus = result.cursor == nil ? .notFound : .unavailable+ }+ let observations = reducer.takeTokenObservations()+ enqueueHistory(events: [], observations: observations)+ turnCursors[id] = result.cursorinvalidThreads.remove(id)- verifiedThreads[id] = started+ covered = result.remaining.isEmpty && thread.status?.type != .notLoaded+ if !events.isEmpty {+ await onBatch(.snapshotEvents(events))+ }}preparingThread = nilconsumeDeferred(for: id)@@ -334,7 +412,8 @@ actor AppServerActivityReader {} catch let error as CodexStatusError where error.isMissingRollout(for: id)|| (!error.isTransportFailure && !error.isProtocolOrParameterFailure) {reducer.invalidateThread(id)- verifiedThreads[id] = nil+ verifiedTurns = verifiedTurns.filter { $0.key.threadID != id }+ turnCursors[id] = nilsubscribed.remove(id)consumeDeferred(for: id)} catch {@@ -342,6 +421,49 @@ actor AppServerActivityReader {throw error}checkedThreads[id] = started+ return covered+ }++ private func readRemainingTurns(+ _ id: String, first: ActivityTurnsPage, includesItems: Bool, forced: Bool, generation current: Int+ ) async throws -> TurnReadResult {+ var turns = first.data+ let activeTurns = reducer.states.keys.filter {+ $0.threadID == id && reducer.states[$0]?.terminal == nil+ }.map(\.turnID)+ var remaining = Set(activeTurns)+ remaining.formUnion(reducer.missingRootTurns(liveOnly: forced)[id] ?? [])+ remaining.subtract(first.data.map(\.id))+ var missingAgents = reducer.missingSubagentContexts(in: id, liveOnly: forced)+ func foundAgents(in turns: [ActivityTurn]) -> Set<String> {+ var agents = Set<String>()+ for turn in turns {+ for item in turn.items ?? [] where item.type == .subAgentActivity && item.kind == "started" {+ if let agent = item.agentThreadId {+ agents.insert(agent)+ }+ }+ }+ return agents+ }+ missingAgents.subtract(foundAgents(in: first.data))+ var cursor = turnCursors[id] ?? first.nextCursor+ // 每轮重读最新页, 深页沿上次游标继续, 避免旧轮次一直被新轮次挤出查询窗口+ for _ in 0 ..< (forced ? 8 : 1) {+ guard !remaining.isEmpty || !missingAgents.isEmpty, let next = cursor else { break }+ let page: ActivityTurnsPage = try await request(+ ActivityRequests.turns(id, limit: 100, includesItems: includesItems, cursor: next), generation: current+ )+ guard page.nextCursor != next else { throw CodexStatusError.invalidServerResponse }+ turns += page.data+ remaining.subtract(page.data.map(\.id))+ missingAgents.subtract(foundAgents(in: page.data))+ cursor = page.nextCursor+ }+ return TurnReadResult(+ turns: turns, remaining: remaining.intersection(activeTurns),+ cursor: remaining.isEmpty && missingAgents.isEmpty ? nil : cursor+ )}private func consumeDeferred(for id: String) {@@ -353,10 +475,10 @@ actor AppServerActivityReader {}}- private func request<Response: Decodable>(_ method: String, params: [String: Any], generation current: Int) async throws -> Response {+ private func request<Response>(_ request: AppServerRequest<Response>, generation current: Int) async throws -> Response {try checkGeneration(current)guard let connection = session else { throw CodexStatusError.serverConnectionClosed }- let pending = try connection.beginRequest(method, params: params)+ let pending = try connection.beginRequest(request.method, params: request.params ?? [:])var received = falsedo {while true {@@ -382,23 +504,28 @@ actor AppServerActivityReader {}private func checkGeneration(_ current: Int) throws {- try Task.checkCancellation()+ try AppServerRequestBudget.checkCurrent()guard generation == current, isRunning else { throw CancellationError() }}private func consume(_ data: Data) throws {let method = try JSONDecoder().decode(MethodEnvelope.self, from: data).method- guard ActivityNotification.category(for: method) != .ignored else { return }- let notification: ActivityNotification+ if let change = AccountChange(method: method) {+ pendingAccountChange = change.merging(pendingAccountChange)+ return+ }+ guard AppServerActivityProtocol.kind(for: method).category != .ignored else { return }+ let notification: ActivityInputdo {- notification = try JSONDecoder().decode(ActivityNotification.self, from: data)+ notification = try JSONDecoder().decode(ActivityInput.self, from: data)} catch is DecodingError {- guard let envelope = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- let params = envelope["params"] as? [String: Any],- let threadID = params["threadId"] as? String ?? (params["thread"] as? [String: Any])?["id"] as? String,- !threadID.isEmpty else { throw CodexStatusError.invalidServerResponse }+ guard let threadID = AppServerActivityProtocol.recoveryThreadID(from: data) else { throw CodexStatusError.invalidServerResponse }// 用量或轮次边界缺失时不能把跨轮次消耗归到下一条通知- invalidateThread(threadID, method: method, resetTokenBaseline: ["thread/tokenUsage/updated", "turn/started", "turn/completed"].contains(method))+ invalidateThread(+ threadID,+ method: method,+ resetTokenBaseline: [ActivityInput.Kind.usageUpdated, .turnStarted, .turnFinished].contains(AppServerActivityProtocol.kind(for: method))+ )return}let id = notification.params.threadId ?? notification.params.thread?.id@@ -410,22 +537,19 @@ actor AppServerActivityReader {consume(notification)}- private func consume(_ notification: ActivityNotification) {+ private func consume(_ notification: ActivityInput) {stateChanged = trueif let id = notification.params.threadId ?? notification.params.thread?.id,- ActivityNotification.category(for: notification.method) != .progress {+ notification.kind.category != .progress {revisions[id, default: 0] += 1}let events = reducer.consume(notification, now: Date())- pendingEvents += eventspendingPublication += eventsif let id = notification.params.threadId ?? notification.params.thread?.id, invalidThreads.contains(id) {reducer.invalidateThread(id)}let observations = reducer.takeTokenObservations()- if isTokenWriter {- pendingObservations += observations- }+ enqueueHistory(events: events, observations: observations)}private func consumeAvailable(generation current: Int) async throws {@@ -443,52 +567,158 @@ actor AppServerActivityReader {try await flushPending(generation: current)}+ private func startStorageWorker() {+ guard storageTask == nil else { return }+ let current = generation+ storageTask = Task { [weak self] in await self?.runStorage(generation: current) }+ }++ private func runStorage(generation current: Int) async {+ while isRunning, generation == current, !Task.isCancelled {+ do {+ try await acquireTokenWriter(generation: current)+ _ = await retryStorage()+ try checkGeneration(current)+ await refreshTokenHistory(generation: current)+ try await Task.sleep(for: .milliseconds(100))+ } catch {+ break+ }+ }+ var failures = 0+ while !Task.isCancelled, failures < 3, !pendingEvents.isEmpty || !pendingObservations.isEmpty {+ do {+ try await persistPending()+ } catch {+ failures += 1+ recordStorageFailure(error)+ try? await Task.sleep(for: .milliseconds(100))+ }+ }+ await tokenHistory.releaseRecordingLease()+ isTokenWriter = false+ reducer.setTokenRecordingEnabled(false)+ storageTask = nil+ // 上一次排空尚未结束时重新启用, 必须等旧写入确认后再启动下一轮+ if isRunning {+ startStorageWorker()+ }+ }+private func persistPending() async throws {- while let event = pendingEvents.first {- try await recorder.record(event: event)- pendingEvents.removeFirst()- }- if isTokenWriter, !pendingObservations.isEmpty || Date().timeIntervalSince(lastTokenRefresh) >= 1 {- let batch = pendingObservations- let committed = try await tokenHistory.recordObservations(batch)- pendingObservations.removeFirst(batch.count)- reducer.acceptTokenTurns(committed)+ var failure: Error?+ do {+ for pending in pendingEvents.prefix(64) {+ try Task.checkCancellation()+ try await recorder.record(event: pending.event)+ pendingEvents.removeFirst()+ pendingStorageBytes -= pending.bytes+ }+ } catch {+ failure = error+ }+ do {+ for pending in pendingObservations.prefix(64) {+ try Task.checkCancellation()+ try await tokenHistory.appendObservation(pending.observation)+ pendingObservations.removeFirst()+ pendingStorageBytes -= pending.bytes+ }+ } catch {+ failure = failure ?? error+ }+ if let failure {+ throw failure+ }+ }++ private func refreshTokenHistory(generation current: Int) async {+ guard isTokenWriter, pendingObservations.isEmpty, Date() >= tokenRetryAfter,+ Date().timeIntervalSince(lastTokenRefresh) >= 1 else { return }+ let refresh = Task { try await tokenHistory.refresh() }+ tokenRefreshTask = refresh+ defer { tokenRefreshTask = nil }+ do {+ let committed = try await refresh.value+ guard generation == current, isRunning, !Task.isCancelled else { return }+ // 此循环刷新期间不写队列, 新观测全部在队列中, 按检查点重放后再发布+ try reducer.acceptTokenTurns(committed, replaying: pendingObservations.map(\.observation))+ stateChanged = true+ tokenRefreshFailed = false+ tokenRetryAfter = .distantPastlastTokenRefresh = Date()+ } catch is CancellationError {+ return+ } catch {+ guard generation == current, isRunning else { return }+ if !tokenRefreshFailed {+ logStorage?.recordFailure(method: "activity/storage", message: error.localizedDescription, connection: "activity")+ }+ tokenRefreshFailed = true+ tokenRetryAfter = Date().addingTimeInterval(1)}}private func flushPending(generation current: Int, force: Bool = true) async throws {try checkGeneration(current)- guard stateChanged || !pendingEvents.isEmpty || !pendingObservations.isEmpty || !pendingPublication.isEmpty else { return }- if !force, pendingEvents.isEmpty, pendingObservations.isEmpty, Date().timeIntervalSince(lastPublished) < 0.1 {+ if let change = pendingAccountChange {+ pendingAccountChange = nil+ await onAccountChange(change)+ try checkGeneration(current)+ }+ guard stateChanged || !pendingPublication.isEmpty else { return }+ if !force, pendingPublication.isEmpty, Date().timeIntervalSince(lastPublished) < 0.1 {return}- _ = await retryStorage()- try checkGeneration(current)- await lifecycleCache.replace(reducer.states, verifiedThreads: verifiedThreads)+ await lifecycleCache.replace(reducer.states, verifiedTurns: verifiedTurns)try checkGeneration(current)stateChanged = falselastPublished = Date()let events = pendingPublicationpendingPublication.removeAll()- let visible = events.filter { event in- guard [.subagentStarted, .subagentEnded].contains(event.eventKind),- let agent = event.agentID, let turn = event.turnID else { return true }- return reducer.states[ActivityTurnReference(threadID: agent, turnID: turn, startedAt: event.timestamp)] != nil- }- if !visible.isEmpty {- await onBatch(.live(visible))+ if !events.isEmpty {+ await onBatch(.live(events))}await onBatch(.lifecycleChanged)- if storageFailed, try pendingStorageExceedsLimit() {- storagePaused = true- throw StorageBacklogFull()+ }++ private func enqueueHistory(events: [ActivityRecord], observations: [TokenObservation]) {+ do {+ for event in events {+ guard !isHistoryRecordingPaused else { return }+ let bytes = try AppServerEventRecord(activity: event).jsonLineData().count+ pendingEvents.append((event, bytes))+ pendingStorageBytes += bytes+ enforceStorageLimit()+ }+ for observation in observations where isTokenWriter {+ guard !isHistoryRecordingPaused else { return }+ let bytes = try JSONLines.stableEncoder.encode(observation).count+ pendingObservations.append((observation, bytes))+ pendingStorageBytes += bytes+ enforceStorageLimit()+ }+ } catch {+ recordStorageFailure(error)+ pauseHistoryRecording()}}+ private func enforceStorageLimit() {+ if pendingEvents.count + pendingObservations.count >= maximumPendingEvents || pendingStorageBytes >= maximumPendingBytes {+ pauseHistoryRecording()+ }+ }++ private func pauseHistoryRecording() {+ isHistoryRecordingPaused = true+ reducer.setTokenRecordingEnabled(false)+ }+private func invalidateThread(_ id: String, method: String, resetTokenBaseline: Bool) {let firstFailure = invalidThreads.insert(id).inserted- verifiedThreads[id] = nil+ verifiedTurns = verifiedTurns.filter { $0.key.threadID != id }+ turnCursors[id] = nilrevisions[id, default: 0] += 1stateChanged = truereducer.invalidateThread(id)@@ -496,7 +726,7 @@ actor AppServerActivityReader {reducer.invalidateTokenBaseline(id)}if firstFailure {- AppServerLogStore.shared.recordFailure(method: method, message: "Invalid payload for thread \(id)", connection: "activity")+ logStorage?.recordFailure(method: method, message: "Invalid payload for thread \(id)", connection: "activity")}}@@ -506,6 +736,10 @@ actor AppServerActivityReader {try await persistPending()storageFailed = falsestorageRetryAfter = .distantPast+ if isHistoryRecordingPaused, pendingEvents.isEmpty, pendingObservations.isEmpty, isRunning, !Task.isCancelled {+ isHistoryRecordingPaused = false+ reducer.setTokenRecordingEnabled(isTokenWriter)+ }return true} catch {recordStorageFailure(error)@@ -515,32 +749,11 @@ actor AppServerActivityReader {private func recordStorageFailure(_ error: Error) {if !storageFailed {- AppServerLogStore.shared.recordFailure(method: "activity/storage", message: error.localizedDescription, connection: "activity")+ logStorage?.recordFailure(method: "activity/storage", message: error.localizedDescription, connection: "activity")}storageFailed = truestorageRetryAfter = Date().addingTimeInterval(1)}- private func pendingStorageExceedsLimit() throws -> Bool {- if pendingEvents.count + pendingObservations.count >= maximumPendingEvents {- return true- }- var bytes = 0- for event in pendingEvents {- bytes += try AppServerEventRecord(activity: event).jsonLineData().count- if bytes >= maximumPendingBytes {- return true- }- }- bytes += try JSONLines.stableEncoder.encode(pendingObservations).count- return bytes >= maximumPendingBytes- }-- private struct StorageBacklogFull: LocalizedError {- var errorDescription: String? {- "Activity persistence buffer is full; collection is paused until pending data is saved"- }- }-private struct MethodEnvelope: Decodable { let method: String }}diff --git a/CodexBar/Services/Activity/AppServerActivityReducer.swift b/CodexBar/Services/Activity/AppServerActivityReducer.swiftindex 6221de4..8a0a587 100644--- a/CodexBar/Services/Activity/AppServerActivityReducer.swift+++ b/CodexBar/Services/Activity/AppServerActivityReducer.swift@@ -4,33 +4,65 @@ import Foundationnonisolated struct AppServerActivityReducer {var threads: [String: ActivityThread] = [:]var states: [ActivityTurnReference: SessionLifecycleState] = [:]- private var childRoots: [String: (session: String, turn: String)] = [:]+ private struct SubagentContext {+ let parent: ActivityTurnReference+ let model: String?+ let effort: String?+ }++ private var subagentContexts: [String: SubagentContext] = [:]+ private struct PendingUsage {+ var usage: TokenUsage+ var updatedAt: Date+ }++ private var pendingUsage: [ActivityTurnReference: PendingUsage] = [:]private var threadTotals: [String: TokenUsage] = [:]- private var tokenStreamID = UUID().uuidString.lowercased()- private var tokenSequences: [String: Int64] = [:]+ /// 淘汰内存序列后重新观察时使用新流身份, 防止与磁盘检查点冲突+ private struct TokenStream {+ let id = UUID().uuidString.lowercased()+ var sequence: Int64 = 0+ }++ private var tokenStreams: [String: TokenStream] = [:]+ private var threadLastObserved: [String: Date] = [:]+ private var loadedThreads = Set<String>()+ private var lastHistoryCutoff: Date?+ private var lastTransientPrune = Date.distantPastprivate(set) var tokenObservations: [TokenObservation] = []private var seenEvents: [String: Date] = [:]private var approvals: [String: ActivityTurnReference] = [:]private var waitingSince: [String: Date] = [:]- private var toolItems: [String: (item: ActivityItem, at: Date)] = [:]private var observingSince = Date.distantPast- private(set) var tokenTurns: [TokenTurn] = []+ private(set) var tokenTurns: [String: TokenTurn] = [:]+ private var isTokenRecordingEnabled = true++ mutating func setTokenRecordingEnabled(_ enabled: Bool) {+ guard enabled != isTokenRecordingEnabled else { return }+ isTokenRecordingEnabled = enabled+ // 丢弃采集中断前的累计基线与待关联增量, 新观测使用独立流身份+ threadTotals.removeAll()+ tokenStreams.removeAll()+ pendingUsage.removeAll()+ tokenObservations.removeAll()+ }mutating func reconnect(now: Date = Date()) {// 断线期间的累计变化没有完整轮次归属, 重新建立基线, 不归入重连后的轮次threadTotals.removeAll()- tokenStreamID = UUID().uuidString.lowercased()- tokenSequences.removeAll()+ tokenStreams.removeAll()+ pendingUsage.removeAll()approvals.removeAll()waitingSince.removeAll()observingSince = nowfor key in states.keys {states[key]?.presentation = nil+ states[key]?.pendingApprovals.removeAll()}}mutating func invalidateThread(_ id: String) {- threads[id]?.status = ActivityThreadStatus(type: "notLoaded")+ threads[id]?.status = ActivityThreadStatus(type: .notLoaded)for key in states.keys where key.threadID == id && states[key]?.terminal == nil {states[key]?.readStatus = .unavailablestates[key]?.presentation = nil@@ -42,7 +74,7 @@ nonisolated struct AppServerActivityReducer {}mutating func markNewThread(_ id: String) {- if threadTotals[id] == nil {+ if isTokenRecordingEnabled, threadTotals[id] == nil {threadTotals[id] = .zero}}@@ -52,33 +84,45 @@ nonisolated struct AppServerActivityReducer {return tokenObservations}- mutating func acceptTokenTurns(_ turns: [TokenTurn]) {- tokenTurns = turns- let records = Dictionary(uniqueKeysWithValues: turns.map { ($0.id, $0) })+ mutating func acceptTokenTurns(_ turns: [TokenTurn], replaying observations: [TokenObservation] = []) throws {+ var records = Dictionary(uniqueKeysWithValues: turns.map { ($0.id, $0) })+ for observation in observations {+ let turn = observation.turn+ records[turn.id] = try observation.applying(to: records[turn.id])+ if turn.rootID != turn.id, records[turn.rootID] == nil {+ records[turn.rootID] = TokenTurn(id: turn.rootID, rootID: turn.rootID, startedAt: observation.rootStartedAt, updatedAt: turn.updatedAt)+ }+ }+ tokenTurns = records+ lastHistoryCutoff = nilfor key in states.keys {states[key]?.tokenUsage = records[TokenTurn.identifier(thread: key.threadID, turn: key.turnID)]?.usage}}- mutating func restoreTokenTurns(_ turns: [TokenTurn]) {- threadTotals.removeAll()- acceptTokenTurns(turns)- }-- mutating func reconcile(thread: ActivityThread, turns: [ActivityTurn], reviewer: ApprovalReviewer?, now: Date, bootstrap: Bool = false) -> [ActivityRecord] {- var thread = thread- // thread/read 不返回完整配置, 保留 resume 和 settings 通知提供的模型上下文- thread.model = thread.model ?? threads[thread.id]?.model- thread.reasoningEffort = thread.reasoningEffort ?? threads[thread.id]?.reasoningEffort+ mutating func reconcile(thread: ActivityThread, turns: [ActivityTurn], now: Date, bootstrap: Bool = false) -> [ActivityRecord] {threads[thread.id] = thread- var events: [ActivityRecord] = []+ threadLastObserved[thread.id] = now+ let previousReferences = Set(states.keys)for turn in turns {- let reference = reference(thread.id, turn.id, at: turn.startedAt.map(Date.init(timeIntervalSince1970:)) ?? now)- let existed = states[reference] != nil- updateTurn(turn, threadID: thread.id, reviewer: reviewer, now: now, historical: true)- if !existed || bootstrap, turn.status == "inProgress", thread.status?.type == "active" {- events.append(event(.turnStarted, threadID: thread.id, turnID: turn.id, at: reference.startedAt))+ for item in turn.items ?? [] {+ recordSubagentContext(item, threadID: thread.id, turnID: turn.id)}+ updateTurn(turn, threadID: thread.id, now: now, historical: true)+ }+ resolveRoots()+ var events: [ActivityRecord] = []+ for turn in turns where turn.status == .running && thread.status?.type == .active {+ let key = reference(thread.id, turn.id)+ guard !previousReferences.contains(key) || bootstrap else { continue }+ let state = states[key]+ var value = event(.turnStarted, threadID: thread.id, turnID: turn.id, at: state?.startedAt ?? now)+ value.context = ActivityContext(+ method: "thread/turns/list", threadID: thread.id, turnID: turn.id,+ parentThreadID: thread.parentID, rootThreadID: state?.rootThreadID,+ rootTurnID: state?.rootTurnID, turnStartedAt: state?.startedAt+ )+ events.append(value)}updateWaiting(threadID: thread.id, status: thread.status, now: now)if let key = activeReference(thread.id) {@@ -86,12 +130,11 @@ nonisolated struct AppServerActivityReducer {live.reconcile(status: thread.status)states[key]?.presentation = live}- resolveRoots()return events}- mutating func consume(_ notification: ActivityNotification, now: Date) -> [ActivityRecord] {- let category = ActivityNotification.category(for: notification.method)+ mutating func consume(_ notification: ActivityInput, now: Date) -> [ActivityRecord] {+ let category = notification.kind.categoryguard category != .ignored else { return [] }let params = notification.paramsguard let threadID = params.threadId ?? params.thread?.id else { return [] }@@ -100,60 +143,56 @@ nonisolated struct AppServerActivityReducer {threads[threadID] = thread}guard threads[threadID] != nil else { return [] }- let date = (params.completedAtMs ?? params.startedAtMs).map { Date(timeIntervalSince1970: $0 / 1000) } ?? now- let turnID = params.turnId ?? params.turn?.id ?? activeReference(threadID)?.turnID+ threadLastObserved[threadID] = now+ let date = (params.completedAt ?? params.startedAt) ?? now+ let turnID = params.turnId ?? params.turn?.idvar events: [ActivityRecord] = []- switch notification.method {- case "thread/started":- if !wasKnown, let created = params.thread?.createdAt, created >= floor(observingSince.timeIntervalSince1970) {+ switch notification.kind {+ case .threadDiscovered:+ if !wasKnown, let created = params.thread?.createdAt, created >= Date(timeIntervalSince1970: floor(observingSince.timeIntervalSince1970)) {markNewThread(threadID)}- case "thread/settings/updated":- updateSettings(params.threadSettings, threadID: threadID, now: now)- case "thread/status/changed":+ case .threadStatusChanged:threads[threadID]?.status = params.statusupdateWaiting(threadID: threadID, status: params.status, now: now)- case "turn/started", "turn/completed":- guard let turn = params.turn, ["inProgress", "completed", "failed", "interrupted"].contains(turn.status) else { break }+ case .turnStarted, .turnFinished:+ guard let turn = params.turn, turn.status != .unknown else { break }events.append(turnEvent(turn, threadID: threadID, now: now))- case "item/started", "item/completed":- if let turnID, let item = params.item {- events += itemEvents(item, method: notification.method, threadID: threadID, turnID: turnID, at: date)+ case .itemStarted, .itemFinished:+ if let turnID, let item = params.item, ActivityItem.isObservedType(item.type) {+ events += itemEvents(item, method: notification.kind, threadID: threadID, turnID: turnID, at: date)}- case "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "item/permissions/requestApproval":- guard let turnID else { break }- let reference = reference(threadID, turnID, at: date)- if let id = notification.id?.identifier {+ case .commandApprovalRequested, .fileApprovalRequested, .permissionsRequested:+ guard let turnID, let identity = approvalIdentity(notification) else { break }+ let reference = reference(threadID, turnID)+ guard states[reference]?.terminal == nil, states[reference] != nil else { break }+ let item = approvalItem(notification)+ if let id = notification.id {approvals[id] = reference+ states[reference]?.pendingApprovals[id] = ActivityApproval(+ requestedAt: date, toolName: item?.type == .commandExecution ? nil : item?.tool,+ sequence: 0, itemType: item?.type.rawValue,+ commandActionTypes: item?.commandActions?.map(\.type)+ )}events.append(event(.approvalRequested,threadID: threadID,turnID: turnID,at: date,- item: approvalItem(params.itemId, threadID: threadID, turnID: turnID, method: notification.method),- identity: params.itemId ?? notification.id?.identifier,- reviewer: .user+ item: item,+ identity: identity))states[reference]?.isWaitingApproval = truestates[reference]?.approvalChangedAt = waitingSince[threadID] ?? date- case "item/autoApprovalReview/started":- guard let turnID else { break }- events.append(event(- .approvalRequested,- threadID: threadID,- turnID: turnID,- at: date,- identity: params.targetItemId ?? params.reviewId,- reviewer: .autoReview- ))- case "serverRequest/resolved":- if let id = params.requestId?.identifier, let reference = approvals.removeValue(forKey: id),- !approvals.values.contains(reference) {- states[reference]?.isWaitingApproval = false+ case .requestResolved:+ if let id = params.requestId, let reference = approvals.removeValue(forKey: id) {+ states[reference]?.pendingApprovals.removeValue(forKey: id)+ let isWaiting = !(states[reference]?.pendingApprovals.isEmpty ?? true)+ states[reference]?.isWaitingApproval = isWaitingstates[reference]?.approvalChangedAt = now}- case "thread/tokenUsage/updated":+ case .usageUpdated:if let turnID, let usage = params.tokenUsage {updateUsage(threadID: threadID, turnID: turnID, update: usage, now: now)}@@ -163,37 +202,40 @@ nonisolated struct AppServerActivityReducer {}}updatePresentation(notification, threadID: threadID, turnID: turnID, at: date)- resolveRoots()+ if params.thread != nil || params.item?.type == .subAgentActivity {+ resolveRoots()+ }prune(now: now)return finish(events, notification: notification, threadID: threadID, turnID: turnID, now: now)}- private mutating func updatePresentation(_ notification: ActivityNotification, threadID: String, turnID: String?, at date: Date) {- let requestID = notification.params.requestId?.identifier- // resolved 不携带 turnId, 必须先匹配原请求, 不能误清除新轮次的等待- let matched = requestID.flatMap { id in- states.keys.first { $0.threadID == threadID && states[$0]?.presentation?.requests[id] != nil }+ private mutating func updatePresentation(_ notification: ActivityInput, threadID: String, turnID: String?, at date: Date) {+ let reference: ActivityTurnReference? = switch notification.kind {+ case .threadStatusChanged:+ activeReference(threadID)+ case .requestResolved:+ // resolved 不携带 turnId, 必须先匹配原请求, 不能误清除新轮次的等待+ notification.params.requestId.flatMap { id in+ states.keys.first { $0.threadID == threadID && states[$0]?.presentation?.requests[id] != nil }+ }+ default:+ turnID.map { self.reference(threadID, $0) }}- guard let key = matched ?? turnID.map({ reference(threadID, $0, at: date) }),+ guard let key = reference,states[key]?.terminal == nil, states[key] != nil else { return }- // 独立的 MCP 和 Hook 请求没有明确轮次归属时不挂到当前任务- if ["mcpServer/elicitation/request", "hook/started", "hook/completed"].contains(notification.method),- notification.live.turnId == nil {- return- }var live = states[key]?.presentation ?? ActivityLivePresentation()live.consume(notification, at: date)states[key]?.presentation = live}private mutating func finish(- _ events: [ActivityRecord], notification: ActivityNotification,+ _ events: [ActivityRecord], notification: ActivityInput,threadID: String, turnID: String?, now: Date) -> [ActivityRecord] {- let source = source(notification, threadID: threadID, turnID: turnID)+ let context = context(notification, threadID: threadID, turnID: turnID)return events.map { value invar value = value- value.source = source+ value.context = contextreturn value}.filter { value inguard let id = value.id else { return false }@@ -203,74 +245,105 @@ nonisolated struct AppServerActivityReducer {}}- private func source(_ notification: ActivityNotification, threadID: String, turnID: String?) -> AppServerEventSource {+ private func context(_ notification: ActivityInput, threadID: String, turnID: String?) -> ActivityContext {let params = notification.params- let state = turnID.flatMap { states[reference(threadID, $0, at: .distantPast)] }- let item = params.item ?? turnID.flatMap {- approvalItem(params.itemId, threadID: threadID, turnID: $0, method: notification.method)- }- return AppServerEventSource(- method: notification.method, threadID: threadID, turnID: turnID,+ let state = turnID.flatMap { states[reference(threadID, $0)] }+ let item = params.item ?? approvalItem(notification)+ return ActivityContext(+ method: notification.provenanceMethod, threadID: threadID, turnID: turnID,parentThreadID: threads[threadID]?.parentID,- rootThreadID: state?.rootSessionID, rootTurnID: state?.rootTurnID,- itemID: params.item?.id ?? params.itemId ?? params.targetItemId,- itemType: item?.type, itemStatus: params.item?.status,+ rootThreadID: state?.rootThreadID, rootTurnID: state?.rootTurnID,+ itemID: params.item?.id ?? params.itemId,+ itemType: item?.type.rawValue, itemStatus: params.item?.status,agentThreadID: params.item?.agentThreadId, itemKind: params.item?.kind,- requestID: notification.id?.identifier ?? params.requestId?.identifier,- reviewID: params.reviewId, turnStatus: params.turn?.status,- turnStartedAt: params.turn?.startedAt.map(Date.init(timeIntervalSince1970:)),- turnCompletedAt: params.turn?.completedAt.map(Date.init(timeIntervalSince1970:)),- durationMs: params.turn?.durationMs+ requestID: notification.id ?? params.requestId,+ turnStatus: params.turn?.status,+ turnStartedAt: params.turn?.startedAt,+ turnCompletedAt: params.turn?.completedAt,+ duration: params.turn?.duration)}private mutating func turnEvent(_ turn: ActivityTurn, threadID: String, now: Date) -> ActivityRecord {- updateTurn(turn, threadID: threadID, reviewer: nil, now: now, historical: false)- if turn.status != "inProgress", threadTotals[threadID] == .zero {+ updateTurn(turn, threadID: threadID, now: now, historical: false)+ resolveRoots()+ if turn.status != .running, threadTotals[threadID] == .zero {// 未观察到本轮用量就已结束, 零基线不能把漏掉的消耗算到下一轮threadTotals.removeValue(forKey: threadID)}- let phase: ActivityEventKind = turn.status == "inProgress" ? .turnStarted : turn.status == "completed" ? .turnCompleted : .turnAborted- let timestamp = (turn.status == "inProgress" ? turn.startedAt : turn.completedAt).map(Date.init(timeIntervalSince1970:)) ?? now+ let phase: ActivityEventKind = turn.status == .running ? .turnStarted : turn.status == .completed ? .turnCompleted : .turnAborted+ let timestamp = (turn.status == .running ? turn.startedAt : turn.completedAt) ?? nowreturn event(phase, threadID: threadID, turnID: turn.id, at: timestamp)}+ mutating func maintain(loadedThreads: Set<String>, now: Date) {+ self.loadedThreads = loadedThreads+ prune(now: now)+ }+private mutating func prune(now: Date) {let retainedDate = HistoryStorage.retentionCutoffDate(today: now)- let retainedRoots = Set(tokenTurns.filter { $0.updatedAt >= retainedDate }.map(\.rootID))- tokenTurns = tokenTurns.filter { $0.updatedAt >= retainedDate || retainedRoots.contains($0.id) }+ if lastHistoryCutoff != retainedDate {+ let retainedRoots = Set(tokenTurns.values.filter { $0.updatedAt >= retainedDate }.map(\.rootID))+ tokenTurns = tokenTurns.filter { $0.value.updatedAt >= retainedDate || retainedRoots.contains($0.key) }+ lastHistoryCutoff = retainedDate+ }+ guard now.timeIntervalSince(lastTransientPrune) >= 60 else { return }+ lastTransientPrune = nowlet cutoff = now.addingTimeInterval(-ActivityRetention.window)seenEvents = seenEvents.filter { $0.value > cutoff }- toolItems = toolItems.filter { $0.value.at > cutoff }- states = states.filter { $0.value.terminal == nil || ($0.value.lastProgressAt ?? .distantPast) > cutoff }- }-- private mutating func updateSettings(_ settings: ActivityNotification.Settings?, threadID: String, now: Date) {- if let settings, var thread = threads[threadID] {- thread.model = settings.model ?? thread.model- thread.reasoningEffort = settings.effort- thread.cwd = settings.cwd ?? thread.cwd- threads[threadID] = thread- for key in states.keys where key.threadID == threadID && states[key]?.terminal == nil {- states[key]?.effort = settings.effort- if let reviewer = settings.approvalsReviewer?.value {- states[key]?.approvalReviewer = reviewer+ var retained = Set(states.keys.filter { key in+ guard let state = states[key] else { return false }+ return (state.lastProgressAt ?? .distantPast) > cutoff+ || (state.terminal == nil && state.readStatus != .notFound && (loadedThreads.contains(key.threadID) || state.readStatus == .complete))+ })+ // 子线程仍在使用的祖先状态必须保留, 否则迟到用量会失去根轮次归属+ var changed = true+ while changed {+ let previous = retained+ for key in previous {+ guard let state = states[key] else { continue }+ if let root = state.rootThreadID, let turn = state.rootTurnID {+ retained.insert(reference(root, turn))+ }+ if let parent = subagentContexts[key.threadID]?.parent {+ retained.insert(parent)}- states[key]?.contextObservedAt = now}+ changed = previous != retained}+ states = states.filter { retained.contains($0.key) }+ pendingUsage = pendingUsage.filter { retained.contains($0.key) }+ let retainedThreads = loadedThreads.union(retained.flatMap { ancestorThreads(of: $0.threadID) })+ .union(threadLastObserved.filter { $0.value > cutoff }.keys)+ threads = threads.filter { retainedThreads.contains($0.key) }+ threadLastObserved = threadLastObserved.filter { retainedThreads.contains($0.key) }+ subagentContexts = subagentContexts.filter { retainedThreads.contains($0.key) || retained.contains($0.value.parent) }+ threadTotals = threadTotals.filter { retainedThreads.contains($0.key) }+ waitingSince = waitingSince.filter { retainedThreads.contains($0.key) }+ approvals = approvals.filter { states[$0.value]?.terminal == nil && states[$0.value] != nil }+ let retainedTokens = Set(retained.map { TokenTurn.identifier(thread: $0.threadID, turn: $0.turnID) })+ .union(tokenObservations.map(\.turn.id))+ tokenStreams = tokenStreams.filter { retainedTokens.contains($0.key) }}- private mutating func itemEvents(_ item: ActivityItem, method: String, threadID: String, turnID: String, at date: Date) -> [ActivityRecord] {+ private func approvalIdentity(_ notification: ActivityInput) -> String? {+ let params = notification.params+ guard let item = params.itemId, let started = params.startedAt else { return nil }+ let callback = params.approvalId.map { "callback:" + $0 } ?? "started:\(started.timeIntervalSince1970)"+ return [notification.kind.rawValue, item, callback].joined(separator: ":")+ }++ private mutating func itemEvents(_ item: ActivityItem, method: ActivityInput.Kind, threadID: String, turnID: String, at date: Date) -> [ActivityRecord] {var events: [ActivityRecord] = []+ recordSubagentContext(item, threadID: threadID, turnID: turnID)progress(threadID, turnID, at: date)- let starting = method == "item/started"+ let starting = method == .itemStartedif item.isToolCall {- toolItems["\(threadID):\(turnID):\(item.id)"] = (item, date)events.append(event(starting ? .toolStarted : .toolCompleted, threadID: threadID, turnID: turnID, at: date, item: item))- } else if item.type == "contextCompaction" {+ } else if item.type == .contextCompaction {events.append(event(starting ? .compactionStarted : .compactionCompleted, threadID: threadID, turnID: turnID, at: date, item: item))- } else if !starting, item.type == "subAgentActivity", ["started", "completed", "interrupted"].contains(item.kind ?? "") {+ } else if !starting, item.type == .subAgentActivity, ["started", "completed", "interrupted"].contains(item.kind ?? "") {// interacted 只是活动, 不代表创建或结束子 Agentevents.append(event(item.kind == "started" ? .subagentStarted : .subagentEnded,@@ -283,72 +356,76 @@ nonisolated struct AppServerActivityReducer {return events}- private func approvalItem(_ id: String?, threadID: String, turnID: String, method: String) -> ActivityItem? {- guard let id else { return nil }- if let known = toolItems["\(threadID):\(turnID):\(id)"] {- return known.item- }- if method == "item/commandExecution/requestApproval" {- return ActivityItem(id: id, type: "commandExecution")- }- if method == "item/fileChange/requestApproval" {- return ActivityItem(id: id, type: "fileChange")+ private func approvalItem(_ notification: ActivityInput) -> ActivityItem? {+ guard let id = notification.params.itemId else { return nil }+ switch notification.kind {+ case .commandApprovalRequested:+ return ActivityItem(id: id, type: .commandExecution, commandActions: notification.params.commandActions)+ case .fileApprovalRequested:+ return ActivityItem(id: id, type: .fileChange)+ default:+ return nil}- return nil}- private mutating func updateTurn(_ turn: ActivityTurn, threadID: String, reviewer: ApprovalReviewer?, now: Date, historical: Bool) {- let start = turn.startedAt.map(Date.init(timeIntervalSince1970:))- let reference = reference(threadID, turn.id, at: start ?? now)+ private mutating func updateTurn(_ turn: ActivityTurn, threadID: String, now: Date, historical: Bool) {+ let start = turn.startedAt+ let reference = reference(threadID, turn.id)let previous = states[reference]let terminal: SessionTerminalState?- let isTerminal = ["completed", "failed", "interrupted"].contains(turn.status)- let isLoaded = ["active", "idle"].contains(threads[threadID]?.status?.type ?? "")+ let isTerminal = turn.status.isTerminal+ let isLoaded = [.active, .idle].contains(threads[threadID]?.status?.type ?? .unknown)if isTerminal, turn.completedAt != nil || !historical || isLoaded {- let date = turn.completedAt.map(Date.init(timeIntervalSince1970:))- if turn.status == "completed" {+ let date = turn.completedAt+ if turn.status == .completed {var reportedAt = date- var duration = turn.durationMs.map { $0 / 1000 }+ var duration = turn.durationif case let .completed(previousAt, previousDuration) = previous?.terminal {reportedAt = reportedAt ?? previousAtduration = duration ?? previousDuration}terminal = .completed(at: reportedAt, duration: duration)- } else if case let .aborted(previousAt) = previous?.terminal {- terminal = .aborted(at: date ?? previousAt)} else {- terminal = .aborted(at: date)+ var reportedAt = date+ var duration = turn.duration+ if case let .aborted(previousAt, previousDuration) = previous?.terminal {+ reportedAt = reportedAt ?? previousAt+ duration = duration ?? previousDuration+ }+ terminal = .aborted(at: reportedAt, duration: duration)}} else {terminal = previous?.terminal}var state = SessionLifecycleState(- requestedThreadID: threadID, turnID: turn.id, startedAt: start,- approvalReviewer: reviewer ?? previous?.approvalReviewer,+ requestedThreadID: threadID, turnID: turn.id, startedAt: start ?? previous?.startedAt,effort: threads[threadID]?.reasoningEffort, lastProgressAt: previous?.lastProgressAt ?? start,- terminal: terminal, readStatus: terminal == nil && (!isLoaded || turn.status != "inProgress") ? .unavailable : .complete,- contextObservedAt: now, rootTurnID: previous?.rootTurnID,- rootSessionID: previous?.rootSessionID,+ terminal: terminal, readStatus: terminal == nil && (!isLoaded || turn.status != .running) ? .unavailable : .complete,+ contextObservedAt: now, rootTurnID: turn.rootTurnId.flatMap { $0.isEmpty ? nil : $0 } ?? previous?.rootTurnID,+ rootThreadID: nil,parentThreadID: threads[threadID]?.parentID,- lastExecutionProgressAt: previous?.lastExecutionProgressAt,- tokenUsage: previous?.tokenUsage ?? tokenTurns.first(where: { $0.id == TokenTurn.identifier(thread: threadID, turn: turn.id) })?.usage,+ tokenUsage: previous?.tokenUsage ?? tokenTurns[TokenTurn.identifier(thread: threadID, turn: turn.id)]?.usage,isHistoricalTerminal: previous?.terminal == nil ? historical : previous?.isHistoricalTerminal ?? historical,isWaitingApproval: previous?.isWaitingApproval, approvalChangedAt: previous?.approvalChangedAt)if terminal != nil {state.terminalObservedAt = previous?.terminalObservedAt ?? now- state.lastProgressAt = turn.completedAt.map(Date.init(timeIntervalSince1970:)) ?? state.terminalObservedAt+ state.lastProgressAt = turn.completedAt ?? state.terminalObservedAt}+ state.pendingApprovals = previous?.pendingApprovals ?? [:]state.presentation = previous?.presentationstate.turnStatus = turn.statusif terminal != nil {state.presentation = nil+ state.pendingApprovals.removeAll()+ state.isWaitingApproval = false+ approvals = approvals.filter { $0.value != reference }}states[reference] = state}private mutating func updateWaiting(threadID: String, status: ActivityThreadStatus?, now: Date) {- guard let status, status.type == "active" || status.type == "idle" else { return }+ guard let status, status.type == .active || status.type == .idle else { return }if status.isWaiting, waitingSince[threadID] == nil {waitingSince[threadID] = now}@@ -360,112 +437,172 @@ nonisolated struct AppServerActivityReducer {}if !status.isWaiting {waitingSince.removeValue(forKey: threadID)+ approvals = approvals.filter { $0.value.threadID != threadID }+ for key in states.keys where key.threadID == threadID {+ states[key]?.pendingApprovals.removeAll()+ }}}private mutating func progress(_ threadID: String, _ turnID: String, at date: Date) {- let key = reference(threadID, turnID, at: date)+ let key = reference(threadID, turnID)let lastProgress = states[key]?.lastProgressAt ?? .distantPaststates[key]?.lastProgressAt = max(lastProgress, date)- // 输出增量是执行进展, 但等待中的其他并发请求仍由服务端状态裁决- states[key]?.lastExecutionProgressAt = date}+ /// 只匹配服务端给出的根轮次, 不根据创建时间或父线程当前轮次推断private mutating func resolveRoots() {- for _ in 0 ..< 16 {- var changed = false- for key in states.keys {- guard var state = states[key], state.rootTurnID == nil else { continue }- if let parent = threads[key.threadID]?.parentID {- if let root = childRoots[key.threadID] {- state.rootTurnID = root.turn- state.rootSessionID = root.session- states[key] = state- changed = true- continue- }- guard let start = threads[key.threadID]?.createdAt.map(Date.init(timeIntervalSince1970:)) ?? state.startedAt,- let ancestor = states.values.filter({- $0.requestedThreadID == parent && ($0.startedAt ?? .distantFuture) <= start- }).max(by: { ($0.startedAt ?? .distantPast) < ($1.startedAt ?? .distantPast) }),- let rootTurn = ancestor.rootTurnID, let rootSession = ancestor.rootSessionID else { continue }- state.rootTurnID = rootTurn- state.rootSessionID = rootSession- childRoots[key.threadID] = (rootSession, rootTurn)- } else if threads[key.threadID]?.origin == .main || threads[key.threadID]?.origin == .autoReview {- state.rootTurnID = key.turnID- state.rootSessionID = key.threadID- } else {- continue- }- states[key] = state- changed = true- }- if !changed {- break+ let byTurn = Dictionary(grouping: states.keys, by: \.turnID)+ for key in states.keys {+ guard let root = states[key]?.rootTurnID else { continue }+ let candidates = byTurn[root] ?? []+ let ancestors = ancestorThreads(of: key.threadID)+ let related = candidates.filter { ancestors.contains($0.threadID) }+ let matches = related.isEmpty ? candidates : related+ states[key]?.rootThreadID = root == key.turnID ? key.threadID : matches.count == 1 ? matches.first?.threadID : nil+ }+ for key in states.keys {+ let resolvedEffort = effort(for: key)+ states[key]?.effort = resolvedEffort+ }+ for (key, pending) in pendingUsage where states[key]?.rootThreadID != nil {+ recordUsage(key, previous: .zero, current: pending.usage, now: pending.updatedAt)+ pendingUsage.removeValue(forKey: key)+ }+ }++ private func ancestorThreads(of id: String) -> Set<String> {+ var result = Set<String>()+ var current: String? = id+ while let thread = current, result.insert(thread).inserted {+ current = threads[thread]?.parentID ?? subagentContexts[thread]?.parent.threadID+ }+ return result+ }++ /// 缺少根轮次时只沿已知父链补读, 每次读取的时间和分页由 reader 限制+ func missingRootTurns(liveOnly: Bool = false) -> [String: Set<String>] {+ var result: [String: Set<String>] = [:]+ for state in states.values where state.rootThreadID == nil && (!liveOnly || state.terminal == nil) {+ guard let root = state.rootTurnID else { continue }+ for thread in ancestorThreads(of: state.requestedThreadID) {+ result[thread, default: []].insert(root)}}+ return result+ }++ func missingSubagentContexts(in threadID: String, liveOnly: Bool = false) -> Set<String> {+ let liveThreads = Set(states.values.filter { $0.terminal == nil }.map(\.requestedThreadID))+ return Set(threads.values.filter {+ $0.parentID == threadID && subagentContexts[$0.id] == nil && (!liveOnly || liveThreads.contains($0.id))+ }.map(\.id))}- private func reference(_ threadID: String, _ turnID: String, at date: Date) -> ActivityTurnReference {- ActivityTurnReference(threadID: threadID, turnID: turnID, startedAt: date)+ func missingSubagentParents(liveOnly: Bool = false) -> Set<String> {+ let liveThreads = Set(states.values.filter { $0.terminal == nil }.map(\.requestedThreadID))+ return Set(threads.values.filter {+ subagentContexts[$0.id] == nil && (!liveOnly || liveThreads.contains($0.id))+ }.compactMap(\.parentID))+ }++ private mutating func recordSubagentContext(_ item: ActivityItem, threadID: String, turnID: String) {+ guard item.type == .subAgentActivity, item.kind == "started", let agent = item.agentThreadId else { return }+ subagentContexts[agent] = SubagentContext(+ parent: reference(threadID, turnID), model: item.model, effort: item.reasoningEffort+ )+ }++ private func effort(for key: ActivityTurnReference) -> String? {+ let current = threads[key.threadID]?.reasoningEffort+ // 创建参数只属于创建时的根工作, 子线程参与其他根轮次时不能继续带入+ guard let context = subagentContexts[key.threadID], let root = states[key]?.rootTurnID,+ states[context.parent]?.rootTurnID == root else { return current }+ if let created = context.effort, let current, created != current {+ return "mixed"+ }+ return current ?? context.effort+ }++ private func reference(_ threadID: String, _ turnID: String) -> ActivityTurnReference {+ ActivityTurnReference(threadID: threadID, turnID: turnID)}private func activeReference(_ threadID: String) -> ActivityTurnReference? {- states.keys.filter { $0.threadID == threadID && states[$0]?.terminal == nil }.max { $0.startedAt < $1.startedAt }+ states.filter { $0.key.threadID == threadID && $0.value.terminal == nil }.max {+ ($0.value.startedAt ?? .distantPast) < ($1.value.startedAt ?? .distantPast)+ }?.key}private func event(_ phase: ActivityEventKind, threadID: String, turnID: String, at date: Date,- item: ActivityItem? = nil, identity: String? = nil, reviewer: ApprovalReviewer? = nil+ item: ActivityItem? = nil, identity: String? = nil) -> ActivityRecord {let thread = threads[threadID]- let state = states[reference(threadID, turnID, at: date)]+ let state = states[reference(threadID, turnID)]let isChild = thread?.parentID != nillet agentID = item?.agentThreadId ?? (isChild ? threadID : nil)- let eventTurn = item?.agentThreadId.flatMap { activeReference($0)?.turnID } ?? turnID+ let isAgentActivity = item?.type == .subAgentActivity+ let agentThread = agentID.flatMap { threads[$0] }+ let context = agentID.flatMap { subagentContexts[$0] }+ let agentModel = item?.kind == "started" ? item?.model : agentThread?.model ?? context?.model+ let agentEffort = item?.kind == "started" ? item?.reasoningEffort : agentThread?.reasoningEffort ?? context?.effortreturn ActivityRecord(timestamp: date, name: phase.rawValue, origin: thread?.origin ?? .unknown,- cwd: thread?.cwd, tool: item?.toolDisplayName, model: thread?.model,- effort: thread?.reasoningEffort, approvalReviewer: reviewer ?? state?.approvalReviewer,- sessionID: isChild ? state?.rootSessionID : threadID, turnID: eventTurn, agentID: agentID,- id: [threadID, turnID, item?.id ?? identity ?? "turn", phase.rawValue].joined(separator: ":")+ cwd: thread?.cwd, toolName: item?.type == .commandExecution ? nil : item?.tool,+ commandActionTypes: item?.type == .commandExecution ? item?.commandActions?.map(\.type) : nil,+ model: isAgentActivity ? agentModel : thread?.model,+ effort: isAgentActivity ? agentEffort : thread?.reasoningEffort,+ threadID: isChild ? state?.rootThreadID : threadID, turnID: isAgentActivity ? nil : turnID, agentID: agentID,+ id: [threadID, turnID, identity ?? item?.id ?? "turn", phase.rawValue].joined(separator: ":"))}private mutating func updateUsage(threadID: String, turnID: String, update: ActivityTokenUpdate, now: Date) {- let total = update.total.usage+ guard isTokenRecordingEnabled else { return }+ let total = update.totalguard total.isValid else { return }defer { threadTotals[threadID] = total }guard let previous = threadTotals[threadID], let delta = total.subtracting(previous), delta != .zero else { return }- let key = reference(threadID, turnID, at: now)- guard let state = states[key], let rootSession = state.rootSessionID, let rootTurn = state.rootTurnID else { return }- let id = TokenTurn.identifier(thread: threadID, turn: turnID)- let existing = tokenTurns.first { $0.id == id }- let sequence = (tokenSequences[id] ?? 0) + 1- tokenSequences[id] = sequence- let rootKey = reference(rootSession, rootTurn, at: now)+ let key = reference(threadID, turnID)+ guard let state = states[key] else { return }+ guard state.rootThreadID != nil, state.rootTurnID != nil else {+ if let usage = (pendingUsage[key]?.usage ?? .zero).adding(delta), usage.isValid {+ pendingUsage[key] = PendingUsage(usage: usage, updatedAt: now)+ }+ return+ }+ recordUsage(key, previous: previous, current: total, now: now)+ }++ private mutating func recordUsage(_ key: ActivityTurnReference, previous: TokenUsage, current: TokenUsage, now: Date) {+ guard let state = states[key], let rootThread = state.rootThreadID, let rootTurn = state.rootTurnID else { return }+ let id = TokenTurn.identifier(thread: key.threadID, turn: key.turnID)+ let existing = tokenTurns[id]+ var stream = tokenStreams[id] ?? TokenStream()+ stream.sequence += 1+ tokenStreams[id] = stream+ let rootKey = reference(rootThread, rootTurn)let metadata = TokenTurn(id: id,- rootID: TokenTurn.identifier(thread: rootSession, turn: rootTurn),+ rootID: TokenTurn.identifier(thread: rootThread, turn: rootTurn),startedAt: state.startedAt,updatedAt: now)let observation = TokenObservation(turn: metadata,rootStartedAt: states[rootKey]?.startedAt,- streamID: tokenStreamID,- sequence: sequence,+ streamID: stream.id,+ sequence: stream.sequence,previous: previous,- current: total+ current: current)tokenObservations.append(observation)guard let record = try? observation.applying(to: existing) else { return }states[key]?.tokenUsage = record.usage- tokenTurns.removeAll { $0.id == id }- tokenTurns.append(record)- if record.rootID != id, !tokenTurns.contains(where: { $0.id == record.rootID }), let root = states[rootKey] {- tokenTurns.append(TokenTurn(id: record.rootID, rootID: record.rootID, startedAt: root.startedAt, updatedAt: now, usage: nil))+ tokenTurns[id] = record+ if record.rootID != id, tokenTurns[record.rootID] == nil, let root = states[rootKey] {+ tokenTurns[record.rootID] = TokenTurn(id: record.rootID, rootID: record.rootID, startedAt: root.startedAt, updatedAt: now, usage: nil)}}}diff --git a/CodexBar/Services/Activity/ProtectionStore.swift b/CodexBar/Services/Activity/ProtectionStore.swiftindex abe2fe1..8767b1b 100644--- a/CodexBar/Services/Activity/ProtectionStore.swift+++ b/CodexBar/Services/Activity/ProtectionStore.swift@@ -34,22 +34,15 @@ actor ProtectionStore {lockURL = self.directoryURL.appendingPathComponent("state.lock", isDirectory: false)}- func load(now: Date = Date()) -> [String: ProtectionRecord] {- do {- return try withExclusiveLock {- var records = loadRecordsWithoutLock()- let originalCount = records.count- records = records.filter { $0.value.expiresAt > now }- if records.count != originalCount {- try saveRecordsWithoutLock(records)- }- return records+ func load(now: Date = Date()) throws -> [String: ProtectionRecord] {+ try withExclusiveLock {+ var records = try loadRecordsWithoutLock()+ let originalCount = records.count+ records = records.filter { $0.value.expiresAt > now }+ if records.count != originalCount {+ try saveRecordsWithoutLock(records)}- } catch {- AppLog.activity.error(- "异常任务状态读取失败: reason=\(error.localizedDescription, privacy: .public)"- )- return [:]+ return records}}@@ -59,7 +52,7 @@ actor ProtectionStore {now: Date = Date()) throws {try withExclusiveLock {- var records = loadRecordsWithoutLock()+ var records = try loadRecordsWithoutLock()records = records.filter { $0.value.expiresAt > now }for removal in removals {@@ -123,16 +116,13 @@ actor ProtectionStore {private static let lockTimeout: TimeInterval = 2private static let lockRetryMicroseconds: useconds_t = 50000- private func loadRecordsWithoutLock() -> [String: ProtectionRecord] {+ private func loadRecordsWithoutLock() throws -> [String: ProtectionRecord] {guard fileManager.fileExists(atPath: stateURL.path) else {return [:]}- guard let data = try? Data(contentsOf: stateURL), !data.isEmpty,- let state = try? JSONDecoder().decode(ProtectionState.self, from: data),- state.version == ProtectionState.currentVersion else {- AppLog.activity.error("异常任务状态已忽略: reason=invalidState")- return [:]- }+ let data = try Data(contentsOf: stateURL)+ try StorageVersion.validate(data, current: ProtectionState.currentVersion, name: "Protection")+ let state = try JSONDecoder().decode(ProtectionState.self, from: data)return Dictionary(state.records.map { ($0.taskIdentifier, $0) },diff --git a/CodexBar/Services/Activity/SessionLifecycleCache.swift b/CodexBar/Services/Activity/SessionLifecycleCache.swiftindex 10e3315..a8f87a5 100644--- a/CodexBar/Services/Activity/SessionLifecycleCache.swift+++ b/CodexBar/Services/Activity/SessionLifecycleCache.swift@@ -3,45 +3,33 @@ import Foundationnonisolated struct ActivityTurnReference: Hashable {let threadID: Stringlet turnID: String- let startedAt: Date-- static func == (lhs: Self, rhs: Self) -> Bool {- lhs.threadID == rhs.threadID && lhs.turnID == rhs.turnID- }-- func hash(into hasher: inout Hasher) {- hasher.combine(threadID)- hasher.combine(turnID)- }}-/// 运行状态按线程验证有效期, 已确认终态不随连接或刷新期限失效+/// 运行状态按轮次验证有效期, 已确认终态不随连接或刷新期限失效actor SessionLifecycleCache {private var states: [ActivityTurnReference: SessionLifecycleState] = [:]- private var verifiedThreads: [String: Date] = [:]+ private var verifiedTurns: [ActivityTurnReference: Date] = [:]- func replace(_ states: [ActivityTurnReference: SessionLifecycleState], verifiedThreads: [String: Date]) {+ func replace(_ states: [ActivityTurnReference: SessionLifecycleState], verifiedTurns: [ActivityTurnReference: Date]) {self.states = states- self.verifiedThreads = verifiedThreads+ self.verifiedTurns = verifiedTurns}func invalidate() {- verifiedThreads.removeAll()+ verifiedTurns.removeAll()}func lifecycleStates(for references: [ActivityTurnReference], now: Date = Date()) -> [SessionLifecycleState] {let requested = Set(references)- let childReferences = states.keys.filter { reference in- guard let state = states[reference], state.parentThreadID != nil,- let root = state.rootSessionID, let turn = state.rootTurnID else { return false }- return requested.contains(ActivityTurnReference(threadID: root, turnID: turn, startedAt: now))+ let childReferences = SessionLifecycleState.subagentStates(for: requested, in: Array(states.values)).map {+ ActivityTurnReference(threadID: $0.requestedThreadID, turnID: $0.turnID)}var result = Array(requested.union(childReferences)).map { reference invar state = states[reference] ?? SessionLifecycleState(requestedThreadID: reference.threadID, turnID: reference.turnID, startedAt: nil,- approvalReviewer: nil, effort: nil, lastProgressAt: nil, terminal: nil, readStatus: .notFound+ effort: nil, lastProgressAt: nil, terminal: nil, readStatus: .notFound)- let verified = verifiedThreads[reference.threadID] ?? .distantPast+ let verified = verifiedTurns[reference] ?? .distantPast// 已确认终态是事实, 不依赖运行状态的刷新期限if state.terminal == nil, now.timeIntervalSince(verified) > 15 {state.readStatus = .unavailable@@ -52,12 +40,12 @@ actor SessionLifecycleCache {while changed {changed = falsefor child in result where child.terminal == nil && child.readStatus != .complete {- guard let root = child.rootSessionID, let turn = child.rootTurnID else { continue }+ guard let root = child.rootThreadID, let turn = child.rootTurnID else { continue }for index in result.indices {let parent = result[index]let isRoot = parent.requestedThreadID == root && parent.turnID == turnlet isAncestor = parent.requestedThreadID == child.parentThreadID- && parent.rootSessionID == root && parent.rootTurnID == turn+ && parent.rootThreadID == root && parent.rootTurnID == turnif isRoot || isAncestor, parent.terminal == nil, parent.readStatus == .complete {result[index].readStatus = .unavailablechanged = true@@ -73,23 +61,52 @@ nonisolated struct SessionLifecycleState {let requestedThreadID: Stringlet turnID: Stringlet startedAt: Date?- var approvalReviewer: ApprovalReviewer?var effort: String?var lastProgressAt: Date?let terminal: SessionTerminalState?var readStatus: SessionReadStatus = .completevar contextObservedAt: Date?var rootTurnID: String?- var rootSessionID: String?+ var rootThreadID: String?var parentThreadID: String?- var lastExecutionProgressAt: Date?var tokenUsage: TokenUsage?var isHistoricalTerminal = falsevar isWaitingApproval: Bool?var approvalChangedAt: Date?+ var pendingApprovals: [String: ActivityApproval] = [:]var terminalObservedAt: Date?var presentation: ActivityLivePresentation?- var turnStatus: String?+ var turnStatus: ActivityTurnStatus?++ /// 保留父线程已知但根轮次尚未确定的子任务, 不能把这部分缺口当成零+ static func subagentStates(for roots: Set<ActivityTurnReference>, in states: [Self]) -> [Self] {+ var result: [ActivityTurnReference: Self] = [:]+ for root in roots {+ let matching = states.filter { state in+ state.parentThreadID != nil && state.rootThreadID == root.threadID && state.rootTurnID == root.turnID+ }+ var threads = Set(matching.map(\.requestedThreadID)).union([root.threadID])+ var unresolved = states.filter { state in+ (state.rootThreadID == nil || state.rootTurnID == nil)+ && (state.rootThreadID == nil || state.rootThreadID == root.threadID)+ && (state.rootTurnID == nil || state.rootTurnID == root.turnID)+ }+ for state in matching {+ result[ActivityTurnReference(threadID: state.requestedThreadID, turnID: state.turnID)] = state+ }+ while true {+ let children = unresolved.filter { $0.parentThreadID.map(threads.contains) == true }+ guard !children.isEmpty else { break }+ for state in children {+ result[ActivityTurnReference(threadID: state.requestedThreadID, turnID: state.turnID)] = state+ }+ let parents = threads+ unresolved.removeAll { $0.parentThreadID.map(parents.contains) == true }+ threads.formUnion(children.map(\.requestedThreadID))+ }+ }+ return Array(result.values)+ }}nonisolated enum SessionReadStatus {@@ -100,5 +117,5 @@ nonisolated enum SessionReadStatus {nonisolated enum SessionTerminalState {case completed(at: Date?, duration: TimeInterval?)- case aborted(at: Date?)+ case aborted(at: Date?, duration: TimeInterval?)}diff --git a/CodexBar/Services/AppServer/AccountSession.swift b/CodexBar/Services/AppServer/AccountSession.swiftindex 2fa514f..4322ab6 100644--- a/CodexBar/Services/AppServer/AccountSession.swift+++ b/CodexBar/Services/AppServer/AccountSession.swift@@ -1,12 +1,27 @@import Foundation-import os++/// 账户通知只触发重新读取, 不将不完整的推送载荷合并进账户快照+nonisolated enum AccountChange: Sendable {+ case account+ case rateLimits++ init?(method: String) {+ switch method {+ case "account/updated": self = .account+ case "account/rateLimits/updated": self = .rateLimits+ default: return nil+ }+ }++ func merging(_ other: Self?) -> Self {+ self == .account || other == .account ? .account : .rateLimits+ }+}/// 账户连接负责业务解码与重试, 传输和请求日志复用共享 WebSocketfinal nonisolated class AccountSession {private let transport: AppServerSessionprivate let timeout: TimeInterval- private let logStorage: AppServerLogStore?- private var nextID = 1private var unsupportedMethods: Set<String> = []var isOpen: Bool {@@ -16,60 +31,31 @@ final nonisolated class AccountSession {init(socketURL: URL, timeout: TimeInterval = 20, logStorage: AppServerLogStore? = .shared) throws {transport = try AppServerSession(socketURL: socketURL, retainsNotifications: false, logStorage: logStorage, connectionName: "account")self.timeout = timeout- self.logStorage = logStorage}func initializeAccount() throws -> (version: String, account: AccountReadResponse) {- let result = try request(- "initialize",- params: ["clientInfo": [- "name": "codex_bar",- "title": "Codex Bar",- "version": Self.clientVersion()- ], "capabilities": ["experimentalApi": true]],- as: InitializeResult.self+ let version = try transport.initialize(+ clientName: "codex_bar_account", minimumVersion: CodexVersionReader.minimumAppServerVersion, timeout: timeout, title: "Codex Bar")- let version = Self.serverVersion(fromUserAgent: result.userAgent)- let minimum = CodexMinimumVersion.account- // 版本未知不能作为明确的低版本结论- guard let version, let isSupported = CodexVersionReader.isVersion(version, atLeast: minimum) else {- throw CodexStatusError.invalidServerResponse- }- guard isSupported else {- let error = CodexStatusError.unsupportedVersion(minimum: minimum)- if let logStorage {- let details = LogFields.joined("current=\(version)", "minimum=\(minimum)")- AppLog.codex.notice("Codex 版本不支持: \(details, privacy: .public)")- logStorage.recordFailure(message: error.localizedDescription)- }- throw error- }- try notify("initialized")- let account = try request("account/read", params: ["refreshToken": false], as: AccountReadResponse.self)- guard account.account != nil else { throw CodexStatusError.notLoggedIn }+ let account = try perform(AccountRequests.account(refreshToken: false))return (version, account)}- private static func clientVersion() -> String {- guard let version = Bundle.main.shortVersionString, !version.isEmpty else { return "1.0.0" }- return version- }-- /// userAgent 首个 token 中 "/" 之后的部分才是实际运行版本- private static func serverVersion(fromUserAgent userAgent: String?) -> String? {- guard let firstToken = userAgent?.split(separator: " ").first,- let slashIndex = firstToken.firstIndex(of: "/") else { return nil }- let version = firstToken[firstToken.index(after: slashIndex)...]- return version.isEmpty ? nil : String(version)+ /// 与请求共用所属 actor, 空闲读取不会与响应读取并发+ func pollChanges() throws -> AccountChange? {+ let deadline = ContinuousClock.now.advanced(by: .milliseconds(50))+ for _ in 0 ..< 32 {+ guard ContinuousClock.now < deadline, try transport.nextEvent() != nil else { break }+ }+ return transport.takeAccountChange()}func close() {transport.close()}- func notify(_ method: String, params: [String: Any]? = nil) throws {- let data = try AppServerRPC.encode(method: method, id: nil, params: params)- try transport.notify(data)+ func perform<Response>(_ request: AppServerRequest<Response>) throws -> Response {+ try self.request(request.method, params: request.params, as: Response.self)}func request<Response: Decodable>(@@ -92,10 +78,10 @@ final nonisolated class AccountSession {private func performRequestRememberingUnsupported<Response: Decodable>(_ method: String,params: [String: Any]? = nil,- as type: Response.Type+ as _: Response.Type) throws -> Response {do {- return try performRequest(method, params: params, as: type)+ return try transport.request(method, params: params, timeout: timeout)} catch let error as CodexStatusError {if error.isUnsupportedMethod {unsupportedMethods.insert(method)@@ -103,28 +89,4 @@ final nonisolated class AccountSession {throw error}}-- private func performRequest<Response: Decodable>(- _ method: String,- params: [String: Any]? = nil,- as type: Response.Type- ) throws -> Response {- try AppServerRequestBudget.checkCurrent()- let id = nextID- nextID += 1- let payload = try AppServerRPC.encode(method: method, id: id, params: params)- do {- let data = try transport.exchange(payload, id: id, timeout: timeout)- return try AppServerRPC.decode(data, as: type)- } catch {- if error is CancellationError || (error as? CodexStatusError)?.isTransportFailure == true {- close()- }- throw error- }- }-}--private nonisolated struct InitializeResult: Decodable {- let userAgent: String?}diff --git a/CodexBar/Services/AppServer/AppServerLogStore.swift b/CodexBar/Services/AppServer/AppServerLogStore.swiftindex c1c951c..f5d7457 100644--- a/CodexBar/Services/AppServer/AppServerLogStore.swift+++ b/CodexBar/Services/AppServer/AppServerLogStore.swift@@ -23,6 +23,7 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {}static let databaseName = "logs.sqlite"+ private static let schemaVersion = 1struct Limits: Sendable {var entries = 10000@@ -32,6 +33,8 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {}private let limits: Limits+ private let now: @Sendable () -> Date+ private var lastRetentionCutoff: Date?private var storedBytes = 0private var storedCount = 0private var needsCheckpoint = false@@ -45,9 +48,10 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {private var isFinished = falseprivate static let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)- init(directoryURL: URL, limits: Limits = Limits()) {+ init(directoryURL: URL, limits: Limits = Limits(), now: @escaping @Sendable () -> Date = { Date() }) {self.limits = limitsself.directoryURL = directoryURL+ self.now = now}deinit {@@ -233,11 +237,7 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {do {try open()try operation(self)- if needsCheckpoint {- try execute("PRAGMA wal_checkpoint(TRUNCATE)")- try execute("PRAGMA incremental_vacuum(256)")- needsCheckpoint = false- }+ try reclaimSpaceIfNeeded()writeError = nil} catch {writeError = String(localized: "log.persistence.error.write")@@ -252,6 +252,7 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {queue.async { [self] indo {try open()+ try transaction { try pruneIfNeeded() }admissionLock.lock()let dropped = droppedEntriesdroppedEntries = 0@@ -268,6 +269,7 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {try transaction { try save(entry, inserting: true) }}let result = try operation(self)+ try reclaimSpaceIfNeeded()if let writeError {throw StorageError(message: writeError)}@@ -292,6 +294,12 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {}database = openeddo {+ let version = try scalar("PRAGMA user_version")+ if version != 0 {+ try StorageVersion.require(version, current: Self.schemaVersion, name: "Logs")+ } else if try scalar("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'entries'") != 0 {+ throw StorageCompatibilityError.unsupportedFormat("Logs", version)+ }try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path)sqlite3_busy_timeout(database, 3000)if try scalar("PRAGMA auto_vacuum") != 2 {@@ -303,6 +311,7 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {try execute("PRAGMA wal_autocheckpoint = 256")try execute("PRAGMA synchronous = NORMAL")try execute("PRAGMA secure_delete = ON")+ try execute("BEGIN IMMEDIATE")try execute("CREATE TABLE IF NOT EXISTS metadata (revision INTEGER NOT NULL, generation INTEGER NOT NULL, total INTEGER NOT NULL)")try execute("INSERT INTO metadata SELECT 0, 0, 0 WHERE NOT EXISTS (SELECT 1 FROM metadata)")try execute("""@@ -313,6 +322,8 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {""")try execute("CREATE INDEX IF NOT EXISTS entries_revision ON entries(revision)")try execute("CREATE INDEX IF NOT EXISTS entries_state ON entries(state)")+ try execute("PRAGMA user_version = \(Self.schemaVersion)")+ try execute("COMMIT")storedCount = try scalar("SELECT COUNT(*) FROM entries")storedBytes = try scalar("SELECT COALESCE(SUM(length(payload)), 0) FROM entries")try transaction { try pruneIfNeeded() }@@ -353,6 +364,18 @@ 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)+ """)+ if sqlite3_changes(database) > 0 {+ try didPrune()+ }+ lastRetentionCutoff = cutoff+ }guard storedCount > limits.entries || storedBytes > limits.bytes else { return }let count = max(1, limits.entries * 9 / 10)let bytes = max(1, limits.bytes * 9 / 10)@@ -364,12 +387,23 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {) WHERE n > \(count) OR bytes > \(bytes))""")+ try didPrune()+ }++ private func didPrune() throws {storedCount = try scalar("SELECT COUNT(*) FROM entries")storedBytes = try scalar("SELECT COALESCE(SUM(length(payload)), 0) FROM entries")try execute("UPDATE metadata SET total = \(storedCount), revision = revision + 1, generation = generation + 1")needsCheckpoint = true}+ private func reclaimSpaceIfNeeded() throws {+ guard needsCheckpoint else { return }+ try execute("PRAGMA incremental_vacuum")+ try execute("PRAGMA wal_checkpoint(TRUNCATE)")+ needsCheckpoint = false+ }+private func scalar(_ sql: String) throws -> Int {let statement = try prepare(sql)defer { sqlite3_finalize(statement) }diff --git a/CodexBar/Services/AppServer/AppServerRequests.swift b/CodexBar/Services/AppServer/AppServerRequests.swiftnew file mode 100644index 0000000..1e177b0--- /dev/null+++ b/CodexBar/Services/AppServer/AppServerRequests.swift@@ -0,0 +1,60 @@+import Foundation++/// 方法和参数只在协议入口定义, 调用方通过响应类型约束请求+nonisolated struct AppServerRequest<Response: Decodable> {+ let method: String+ var params: [String: Any]?+}++nonisolated enum AccountRequests {+ static func account(refreshToken: Bool) -> AppServerRequest<AccountReadResponse> {+ AppServerRequest(method: "account/read", params: ["refreshToken": refreshToken])+ }++ static var rateLimits: AppServerRequest<AccountRateLimitsResponse> {+ AppServerRequest(method: "account/rateLimits/read")+ }++ static var usage: AppServerRequest<AccountUsageResponse> {+ AppServerRequest(method: "account/usage/read")+ }++ static var configuration: AppServerRequest<ConfigReadResponse> {+ AppServerRequest(method: "config/read", params: ["includeLayers": false])+ }++ static func consumeCredit(id: String, idempotencyKey: String) -> AppServerRequest<ResetCreditConsumeResponse> {+ AppServerRequest(method: "account/rateLimitResetCredit/consume", params: ["creditId": id, "idempotencyKey": idempotencyKey])+ }++ static func setTUINotifications(_ enabled: Bool) -> AppServerRequest<ConfigWriteResponse> {+ let edit = ConfigBatchEdit(keyPath: "tui.notifications", value: enabled, mergeStrategy: "upsert")+ return AppServerRequest(method: "config/batchWrite", params: ["edits": [edit.appServerObject], "reloadUserConfig": true])+ }+}++nonisolated enum ActivityRequests {+ static func loadedThreads(cursor: String?) -> AppServerRequest<ActivityLoadedPage> {+ var params: [String: Any] = ["limit": 100]+ if let cursor {+ params["cursor"] = cursor+ }+ return AppServerRequest(method: "thread/loaded/list", params: params)+ }++ static func thread(_ id: String) -> AppServerRequest<ActivityThreadRead> {+ AppServerRequest(method: "thread/read", params: ["threadId": id, "includeTurns": false])+ }++ static func subscribe(_ id: String) -> AppServerRequest<ActivityThreadResume> {+ AppServerRequest(method: "thread/resume", params: ["threadId": id, "excludeTurns": true])+ }++ static func turns(_ id: String, limit: Int, includesItems: Bool, cursor: String? = nil) -> AppServerRequest<ActivityTurnsPage> {+ var params: [String: Any] = ["threadId": id, "limit": limit, "itemsView": includesItems ? "full" : "notLoaded"]+ if let cursor {+ params["cursor"] = cursor+ }+ return AppServerRequest(method: "thread/turns/list", params: params)+ }+}diff --git a/CodexBar/Services/AppServer/AppServerSession.swift b/CodexBar/Services/AppServer/AppServerSession.swiftindex b6c6e9f..8df78e9 100644--- a/CodexBar/Services/AppServer/AppServerSession.swift+++ b/CodexBar/Services/AppServer/AppServerSession.swift@@ -1,6 +1,7 @@import CryptoKitimport Darwinimport Foundation+import osnonisolated struct AppServerConnectionError: LocalizedError {let code: Int32@@ -19,6 +20,7 @@ final nonisolated class AppServerSession {private var descriptor: Int32 = -1private var nextID = 0private var notifications: [Data] = []+ private var accountChange: AccountChange?private let logStorage: AppServerLogStore?private let socketPath: Stringprivate let connectionName: String@@ -88,27 +90,52 @@ final nonisolated class AppServerSession {guard descriptor >= 0 else { return }Darwin.close(descriptor)descriptor = -1+ accountChange = nil+ notifications.removeAll()logStorage?.recordConnection(method: "connection/closed", detail: socketPath, connection: connectionName, status: .information)}- func initialize() throws {+ @discardableResult+ func initialize(clientName: String, minimumVersion: String, timeout: TimeInterval = 10, title: String? = nil) throws -> String {+ var clientInfo = ["name": clientName, "version": Bundle.main.shortVersionString.flatMap { $0.isEmpty ? nil : $0 } ?? "1.0.0"]+ clientInfo["title"] = titlelet result: Initialization = try request("initialize", params: [- "clientInfo": ["name": "codex_bar_activity", "version": Bundle.main.shortVersionString ?? "1.0.0"],- "capabilities": ["experimentalApi": true]- ])- let version = result.userAgent.split(separator: " ").first?.split(separator: "/").last.map(String.init)- guard let version,- CodexVersionReader.isVersion(version, atLeast: CodexMinimumVersion.activity) == true else {- throw CodexStatusError.unsupportedVersion(minimum: CodexMinimumVersion.activity)+ "clientInfo": clientInfo,+ "capabilities": ["experimentalApi": false]+ ], timeout: timeout)+ guard let firstToken = result.userAgent?.split(separator: " ").first,+ let slash = firstToken.firstIndex(of: "/") else {+ throw CodexStatusError.invalidServerResponse+ }+ let version = String(firstToken[firstToken.index(after: slash)...])+ guard let supported = CodexVersionReader.isVersion(version, atLeast: minimumVersion) else {+ throw CodexStatusError.invalidServerResponse+ }+ guard supported else {+ let error = CodexStatusError.unsupportedVersion(minimum: minimumVersion)+ if let logStorage {+ let details = LogFields.joined("current=\(version)", "minimum=\(minimumVersion)")+ AppLog.codex.notice("Codex 版本不支持: \(details, privacy: .public)")+ logStorage.recordFailure(message: error.localizedDescription, connection: connectionName)+ }+ throw error}- try send(["method": "initialized"])+ try notify("initialized")+ return version}- func request<Response: Decodable>(_ method: String, params: [String: Any] = [:]) throws -> Response {+ func request<Response: Decodable>(_ method: String, params: [String: Any]? = nil, timeout: TimeInterval = 10) throws -> Response {+ try AppServerRequestBudget.checkCurrent()nextID += 1- let id = nextID- let payload = try AppServerRPC.encode(method: method, id: id, params: params)- return try AppServerRPC.decode(exchange(payload, id: id, timeout: 10), as: Response.self)+ let payload = try AppServerRPC.encode(method: method, id: nextID, params: params)+ do {+ return try AppServerRPC.decode(exchange(payload, id: nextID, timeout: timeout), as: Response.self)+ } catch {+ if error is CancellationError || (error as? CodexStatusError)?.isTransportFailure == true {+ close()+ }+ throw error+ }}struct PendingRequest {@@ -167,7 +194,7 @@ final nonisolated class AppServerSession {}/// 账户和活动连接共用帧协议与请求日志, 业务解码由调用方负责- func exchange(_ payload: Data, id: Int, timeout: TimeInterval) throws -> Data {+ private func exchange(_ payload: Data, id: Int, timeout: TimeInterval) throws -> Data {try AppServerRequestBudget.checkCurrent()exchangeDeadline = ContinuousClock.now.advanced(by: .seconds(timeout))defer { exchangeDeadline = nil }@@ -214,7 +241,11 @@ final nonisolated class AppServerSession {throw CodexStatusError.serverTimeout}- func notify(_ payload: Data) throws {+ func notify(_ method: String, params: [String: Any]? = nil) throws {+ try notify(AppServerRPC.encode(method: method, id: nil, params: params))+ }++ private func notify(_ payload: Data) throws {let object = try JSONSerialization.jsonObject(with: payload) as? [String: Any]let method = object?["method"] as? String ?? "unknown"let text = String(data: payload, encoding: .utf8) ?? ""@@ -227,6 +258,11 @@ final nonisolated class AppServerSession {}}+ func takeAccountChange() -> AccountChange? {+ defer { accountChange = nil }+ return accountChange+ }+func nextEvent() throws -> Data? {if !notifications.isEmpty {return notifications.removeFirst()@@ -267,10 +303,6 @@ final nonisolated class AppServerSession {}}- private func send(_ object: [String: Any]) throws {- try notify(JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes]))- }-private func sendFrame(_ payload: Data, opcode: UInt8) throws {let mask = (0 ..< 4).map { _ in UInt8.random(in: .min ... .max) }var frame = Data([0x80 | opcode])@@ -342,6 +374,11 @@ final nonisolated class AppServerSession {guard header[0] & 0x70 == 0, opcode == (fragmented ? 0 : 1) else { throw CodexStatusError.invalidServerResponse }message.append(payload)if header[0] & 128 != 0 {+ if !retainsNotifications,+ let object = try? JSONSerialization.jsonObject(with: message) as? [String: Any],+ let method = object["method"] as? String, let change = AccountChange(method: method) {+ accountChange = change.merging(accountChange)+ }recordIncoming(message, matchingResponseID: matchingResponseID)return message}@@ -362,14 +399,14 @@ final nonisolated class AppServerSession {logStorage.recordReceived(method: method, payload: framePayload(data), connection: connectionName)}- /// 推送只记录活动采集使用的状态和展示事件, 跳过高频 delta, 保留错误和异常协议消息+ /// 推送只记录已使用的账户和活动事件, 跳过高频 delta, 保留错误和异常协议消息/// 此判断不参与消息路由, 被过滤的消息仍交给业务消费private static func shouldRecordIncoming(_ object: [String: Any]?) -> Bool {guard let object, let method = object["method"] as? String else { return true }- if method == "error" || method == "warning" {+ if method == "error" || method == "warning" || AccountChange(method: method) != nil {return true}- switch ActivityNotification.category(for: method) {+ switch AppServerActivityProtocol.kind(for: method).category {case .progress, .ignored: return falsecase .state, .presentation: break}@@ -377,9 +414,9 @@ final nonisolated class AppServerSession {case "item/started", "item/completed":guard let params = object["params"] as? [String: Any],let item = params["item"] as? [String: Any], let type = item["type"] as? String else { return true }- return ActivityItem.isToolType(type) || [- "contextCompaction", "subAgentActivity", "agentMessage", "reasoning", "plan", "enteredReviewMode", "exitedReviewMode"- ].contains(type)+ return AppServerActivityProtocol.observes(itemType: type)+ case "mcpServer/elicitation/request":+ return (object["params"] as? [String: Any])?["mode"] as? String != "openai/userVerification"default:return true}@@ -449,5 +486,5 @@ final nonisolated class AppServerSession {}}- private struct Initialization: Decodable { let userAgent: String }+ private struct Initialization: Decodable { let userAgent: String? }}diff --git a/CodexBar/Services/AppServer/AppServerStartup.swift b/CodexBar/Services/AppServer/AppServerStartup.swiftindex f9f4cba..00c2b97 100644--- a/CodexBar/Services/AppServer/AppServerStartup.swift+++ b/CodexBar/Services/AppServer/AppServerStartup.swift@@ -1,14 +1,21 @@import Foundationimport os-/// App 启动入口的一次性准备, 只请求官方启动命令, 不接管 Codex 后台服务生命周期+/// 启动与连接恢复共用的有界准备, 只启动明确缺失的 Codex 后台服务actor AppServerStartup {private let environment: [String: String]private let installations: CodexInstallations?private let probeConnection: @Sendable () throws -> Voidprivate let commandTimeout: TimeIntervalprivate let readinessAttempts: Int- private var isStarting = false+ enum Trigger { case automatic, manual }++ private let now: @Sendable () -> ContinuousClock.Instant+ private var lastFailure: String?+ private var automaticAttempts = 0+ private var retryAfter: ContinuousClock.Instant?+ private var inFlight: (id: UUID, task: Task<Void, any Error>)?+ private var waiters = Set<UUID>()private var unfinishedProcess: Process?init(@@ -17,8 +24,10 @@ actor AppServerStartup {installations: CodexInstallations? = nil,commandTimeout: TimeInterval = 15,readinessAttempts: Int = 10,- probeConnection: (@Sendable () throws -> Void)? = nil+ probeConnection: (@Sendable () throws -> Void)? = nil,+ now: @escaping @Sendable () -> ContinuousClock.Instant = { .now }) {+ self.now = nowself.environment = environmentself.installations = installationsself.commandTimeout = commandTimeout@@ -29,26 +38,92 @@ actor AppServerStartup {}}- func ensureStarted() async throws {+ func ensureStarted(trigger: Trigger = .automatic) async throws {+ do {+ try await waitForAttempt(trigger: trigger)+ } catch let error as StartupError where trigger == .manual {+ switch error {+ case .retryDeferred, .retryExhausted:+ // 手动请求若赶上自动额度检查, 清理完成后仍允许独立尝试一次+ try await waitForAttempt(trigger: .manual)+ default: throw error+ }+ }+ }++ private func waitForAttempt(trigger: Trigger) async throws {try Task.checkCancellation()- // 异步命令执行期间允许 actor 重入, 但不能重叠启动命令- guard !isStarting, unfinishedProcess?.isRunning != true else { throw StartupError.notReady }- unfinishedProcess = nil- isStarting = true- defer { isStarting = false }+ let operation: (id: UUID, task: Task<Void, any Error>)+ if let inFlight {+ operation = inFlight+ } else {+ operation = (UUID(), Task { try await self.startIfAbsent(trigger: trigger) })+ inFlight = operation+ }+ let waiter = UUID()+ waiters.insert(waiter)+ defer {+ if inFlight?.id == operation.id {+ inFlight = nil+ waiters.removeAll()+ }+ }do {- try probeConnection()- AppLog.codex.notice("Codex 后台服务已就绪: source=existing")+ try await withTaskCancellationHandler {+ try await operation.task.value+ try Task.checkCancellation()+ } onCancel: {+ Task { await self.cancelWaiter(waiter, operationID: operation.id) }+ }+ } catch {+ if inFlight?.id == operation.id {+ switch error {+ case is CancellationError, StartupError.retryDeferred, StartupError.retryExhausted: break+ default: lastFailure = error.localizedDescription+ }+ }+ throw error+ }+ }++ private func cancelWaiter(_ waiter: UUID, operationID: UUID) {+ guard inFlight?.id == operationID else { return }+ waiters.remove(waiter)+ // 一个调用方取消不影响其他等待者, 最后一个离开后才取消命令+ if waiters.isEmpty {+ inFlight?.task.cancel()+ }+ }++ private func connectionIsReady() throws {+ try probeConnection()+ automaticAttempts = 0+ retryAfter = nil+ lastFailure = nil+ }++ private func startIfAbsent(trigger: Trigger) async throws {+ try Task.checkCancellation()+ do {+ try connectionIsReady()return} catch let error as AppServerConnectionError where error.serverIsAbsent {// 只有明确缺少监听者才启动, 权限或协议错误不改变服务状态}+ guard unfinishedProcess?.isRunning != true else { throw StartupError.notReady }+ unfinishedProcess = nil+ if trigger == .automatic {+ guard automaticAttempts < 3 else { throw StartupError.retryExhausted(lastFailure ?? "") }+ guard retryAfter.map({ now() >= $0 }) ?? true else { throw StartupError.retryDeferred(lastFailure ?? "") }+ automaticAttempts += 1+ }+ retryAfter = now().advanced(by: .seconds(60))let executable = try await supportedExecutable()try Task.checkCancellation()// 能力检测期间其他客户端可能已经启动服务do {- try probeConnection()+ try connectionIsReady()return} catch let error as AppServerConnectionError where error.serverIsAbsent {}@@ -64,7 +139,7 @@ actor AppServerStartup {// 命令失败也探测一次, 允许与其他客户端并发启动后复用已就绪的服务for attempt in 0 ..< readinessAttempts {do {- try probeConnection()+ try connectionIsReady()AppLog.codex.notice("Codex 后台服务已就绪: source=daemonStart")return} catch let error as AppServerConnectionError where error.serverIsAbsent {@@ -83,9 +158,19 @@ actor AppServerStartup {let paths = [installations.globalPath, installations.bundledPath].compactMap(\.self)guard !paths.isEmpty else { throw StartupError.notInstalled }var checked = Set<String>()+ var hasSupportedVersion = falsefor path in paths where checked.insert(CodexPaths.canonicalPath(path)).inserted {try Task.checkCancellation()let executable = URL(fileURLWithPath: path)+ let version = await BoundedProcess.runAsync(+ executable: executable, arguments: ["--version"], timeout: 2.5, environment: environment+ )+ unfinishedProcess = version.runningProcess+ try Task.checkCancellation()+ guard version.runningProcess == nil else { throw StartupError.notReady }+ guard version.exitCode == 0,+ CodexVersionReader.isVersion(version.output, atLeast: CodexVersionReader.minimumAppServerVersion) == true else { continue }+ hasSupportedVersion = truelet result = await BoundedProcess.runAsync(executable: executable,arguments: ["app-server", "daemon", "start", "--help"],@@ -99,6 +184,7 @@ actor AppServerStartup {return executable}}+ guard hasSupportedVersion else { throw CodexStatusError.unsupportedVersion(minimum: CodexVersionReader.minimumAppServerVersion) }throw StartupError.unsupportedCommand}@@ -108,6 +194,8 @@ actor AppServerStartup {case timeoutcase commandFailed(Int32)case notReady+ case retryDeferred(String)+ case retryExhausted(String)var errorDescription: String? {switch self {@@ -121,6 +209,8 @@ actor AppServerStartup {String(localized: "codex.daemon.command-failed", defaultValue: "\(code)")case .notReady:String(localized: "codex.daemon.not-ready")+ case let .retryDeferred(reason), let .retryExhausted(reason):+ reason}}}diff --git a/CodexBar/Services/Codex/CodexVersionService.swift b/CodexBar/Services/Codex/CodexVersionService.swiftindex 263eda7..ccae9c4 100644--- a/CodexBar/Services/Codex/CodexVersionService.swift+++ b/CodexBar/Services/Codex/CodexVersionService.swift@@ -202,14 +202,10 @@ actor CodexVersionService {}}-/// CodexBar 各能力依赖的 app-server 最低版本-nonisolated enum CodexMinimumVersion {- static let account = "0.157.0"- static let activity = "0.157.0"-}-/// 从 ` codex --version` 的输出中提取用户可读版本号nonisolated enum CodexVersionReader {+ static let minimumAppServerVersion = "0.162.0"+static func displayVersion(from output: String) -> String {output.split(whereSeparator: \.isWhitespace)diff --git a/CodexBar/Services/CodexStatus/AutoResetController.swift b/CodexBar/Services/CodexStatus/AutoResetController.swiftindex cd3cd8d..c684853 100644--- a/CodexBar/Services/CodexStatus/AutoResetController.swift+++ b/CodexBar/Services/CodexStatus/AutoResetController.swift@@ -57,7 +57,7 @@ final class AutoResetController {}private let settings: AutoResetSettings- private let snapshots: AnyPublisher<CodexQuotaSnapshot?, Never>+ private let outcomes: AnyPublisher<CodexFetchOutcome, Never>private let dependencies: Dependenciesprivate var cancellables = Set<AnyCancellable>()private var scheduledTask: Task<Void, Never>?@@ -70,6 +70,7 @@ final class AutoResetController {private var records: [String: Record] = [:]private var isStarted = falseprivate var isSleeping = false+ private var isAccountBlocked = falseprivate var isPreparingForTermination = falseprivate(set) var scheduledDate: Date?private(set) var wakeDate: Date?@@ -81,7 +82,7 @@ final class AutoResetController {notificationService: NotificationService,keepAliveController: KeepAliveController) {- self.init(settings: settings, snapshots: statusViewModel.$snapshot.eraseToAnyPublisher(), dependencies: Dependencies(+ self.init(settings: settings, outcomes: statusViewModel.fetchOutcomes, dependencies: Dependencies(read: { try await service.readCreditsForAutoReset(budget: $0) },consume: { candidate, account, budget intry await service.consumeResetCredit(@@ -100,9 +101,9 @@ final class AutoResetController {))}- init(settings: AutoResetSettings, snapshots: AnyPublisher<CodexQuotaSnapshot?, Never>, dependencies: Dependencies) {+ init(settings: AutoResetSettings, outcomes: AnyPublisher<CodexFetchOutcome, Never>, dependencies: Dependencies) {self.settings = settings- self.snapshots = snapshots+ self.outcomes = outcomesself.dependencies = dependencies}@@ -116,7 +117,7 @@ final class AutoResetController {guard !isStarted else { return }isStarted = truedependencies.setRequested(settings.isEnabled)- snapshots.sink { [weak self] in self?.handleSnapshot($0) }.store(in: &cancellables)+ outcomes.sink { [weak self] in self?.handleOutcome($0) }.store(in: &cancellables)settings.$isEnabled.dropFirst().sink { [weak self] in self?.handleEnabledChange($0) }.store(in: &cancellables)settings.$leadTime.dropFirst().receive(on: DispatchQueue.main).sink { [weak self] _ inguard let self, settings.isEnabled else { return }@@ -175,7 +176,7 @@ final class AutoResetController {}private var canEvaluate: Bool {- isEnabled && !isSleeping+ isEnabled && !isSleeping && !isAccountBlocked}private func handleEnabledChange(_ enabled: Bool) {@@ -195,19 +196,48 @@ final class AutoResetController {}}- private func handleSnapshot(_ snapshot: CodexQuotaSnapshot?) {- guard isEnabled, let snapshot, !snapshot.isRateLimitsStale else { return }- let previousKey = target?.key- let previousExpiration = target?.candidate.expirationDate- let identity = AutoResetIdentity.accountIdentity(for: snapshot.account)- if let accountIdentity, accountIdentity != identity {- invalidateEvaluation()+ private func handleOutcome(_ outcome: CodexFetchOutcome) {+ guard isStarted, !isPreparingForTermination else { return }+ switch outcome {+ case .notLoggedIn:+ blockAccount(signedOut: true)+ case .authenticationRequired:+ blockAccount(signedOut: false)+ case .initializationFailed, .unsupportedVersion:+ break+ case let .data(snapshot):+ let identity = AutoResetIdentity.accountIdentity(for: snapshot.account)+ let changedAccount = accountIdentity != identity+ let wasBlocked = isAccountBlocked+ if changedAccount {+ cancelWork()+ target = nil+ accountIdentity = identity+ }+ isAccountBlocked = false+ guard !snapshot.isRateLimitsStale else {+ if changedAccount || wasBlocked {+ requestEvaluation(trigger: .statusRefresh)+ }+ return+ }+ let previousKey = target?.key+ let previousExpiration = target?.candidate.expirationDate+ reconcile(AutoResetRead(accountIdentity: identity, availableCount: snapshot.resetCreditsAvailableCount, candidates: snapshot.autoResetCandidates))+ if let previousKey, previousKey != target?.key || previousExpiration != target?.candidate.expirationDate {+ invalidateEvaluation()+ }+ refreshSchedule()}- reconcile(AutoResetRead(accountIdentity: identity, availableCount: snapshot.resetCreditsAvailableCount, candidates: snapshot.autoResetCandidates))- if let previousKey, previousKey != target?.key || previousExpiration != target?.candidate.expirationDate {- invalidateEvaluation()+ }++ private func blockAccount(signedOut: Bool) {+ isAccountBlocked = true+ cancelWork()+ target = nil+ if signedOut {+ accountIdentity = nil}- refreshSchedule()}private func requestEvaluation(trigger: LogTrigger) {@@ -350,13 +380,23 @@ final class AutoResetController {if error is CancellationError || error is AutoResetServiceError {return}- guard let key = evaluation?.target.key ?? target?.key else { return }- if let error = error as? CodexStatusError {- if error.isAuthenticationRequired {+ let key = evaluation?.target.key ?? target?.key+ if let error = error as? CodexStatusError, error.isAuthenticationRequired {+ if let key {records[key]?.block = .authenticationdependencies.failed(.authentication, key)- dependencies.refresh()- } else if error.isProtocolOrParameterFailure {+ }+ if case .notLoggedIn = error {+ blockAccount(signedOut: true)+ } else {+ blockAccount(signedOut: false)+ }+ dependencies.refresh()+ return+ }+ guard let key else { return }+ if let error = error as? CodexStatusError {+ if error.isProtocolOrParameterFailure {records[key]?.block = .permanentdependencies.failed(.permanent, key)}diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swiftindex 9332265..00e7019 100644--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift@@ -1,21 +1,13 @@import Foundationimport os-/// 刷新结果携带连接失败原因, 请求响应细节保留在交互日志中+/// 额度刷新结果, 请求响应细节保留在交互日志中nonisolated enum CodexFetchOutcome {case data(CodexQuotaSnapshot)case notLoggedIn+ case authenticationRequiredcase unsupportedVersion(minimum: String)- case initializationFailed(message: String)-- var connectionErrorMessage: String? {- switch self {- case .data: nil- case .notLoggedIn: CodexStatusError.notLoggedIn.localizedDescription- case let .unsupportedVersion(minimum): CodexStatusError.unsupportedVersion(minimum: minimum).localizedDescription- case let .initializationFailed(message): message- }- }+ case initializationFailed}/// 一次刷新里各步的结果分类, 只用于日志@@ -57,9 +49,9 @@ nonisolated struct CodexFetchResult {private nonisolated enum ConnectionResolution {case ready(connection: AppServerConnection, reused: Bool)- case notLoggedIn+ case authenticationRequiredcase unsupportedVersion(minimum: String)- case initializationFailed(message: String)+ case initializationFailed}// 单接口读取结果按后续动作分类: 跳过, 刷新认证, 重建连接@@ -71,12 +63,13 @@ private nonisolated enum ReadResult<Value> {}private nonisolated enum ReadSkipReason {- case requestFailed+ case requestFailed(CodexStatusError)case methodUnsupported}private nonisolated enum FetchFailure: Error {case notLoggedIn+ case authenticationRequiredcase needsRebuild}@@ -128,7 +121,7 @@ private nonisolated extension ReadResult {case .value, .skipped:return selfcase .authRequired:- throw FetchFailure.notLoggedIn+ throw FetchFailure.authenticationRequiredcase .broken:throw FetchFailure.needsRebuild}@@ -140,19 +133,49 @@ actor CodexStatusService {private var connection: AppServerConnection?private var supplementalDataCache = SupplementalDataCache()private let socketURL: URL+ private let logStorage: AppServerLogStore?+ private let startup: AppServerStartup?- init(socketURL: URL = AppServerActivityReader.defaultSocketURL) {+ init(socketURL: URL = AppServerActivityReader.defaultSocketURL, logStorage: AppServerLogStore? = .shared, startup: AppServerStartup? = nil) {self.socketURL = socketURL+ self.logStorage = logStorage+ self.startup = startup}// MARK: - 对外入口func fetchOutcome() async -> CodexFetchResult {var trace = CodexFetchTrace()+ do {+ try await startup?.ensureStarted()+ } catch {+ trace.failureStage = .connect+ let outcome: CodexFetchOutcome = if case let CodexStatusError.unsupportedVersion(minimum) = error {+ .unsupportedVersion(minimum: minimum)+ } else {+ .initializationFailed+ }+ return CodexFetchResult(outcome: outcome, trace: trace)+ }let outcome = resolveOutcome(allowRebuild: true, trace: &trace)return CodexFetchResult(outcome: outcome, trace: trace)}+ func pollAccountChanges() -> AccountChange? {+ guard let connection, connection.session.isOpen else { return nil }+ do {+ let change = try connection.session.pollChanges()+ if change == .account {+ supplementalDataCache = SupplementalDataCache()+ }+ return change+ } catch {+ teardownConnection()+ // 一次断线触发一次有界重连, 失败后仍由定时刷新兜底+ return .account+ }+ }+func currentConnectionInfo() async -> CodexServerConnectionInfo? {guard let connection, connection.session.isOpen else {return nil@@ -162,9 +185,10 @@ actor CodexStatusService {}/// 只重建当前客户端连接, 不重启 Codex 后台服务- func reconnect(minimumVersion: String) throws -> CodexServerConnectionInfo {+ func reconnect(minimumVersion: String) async throws -> CodexServerConnectionInfo {teardownConnection()supplementalDataCache = SupplementalDataCache()+ try await startup?.ensureStarted(trigger: .manual)let candidate = try readyConnection()guard let version = candidate.connectionInfo.version,CodexVersionReader.isVersion(version, atLeast: minimumVersion) == true else {@@ -174,29 +198,14 @@ actor CodexStatusService {return candidate.connectionInfo}- func readCodexConfig() async throws -> ConfigReadResponse {- let connection = try readyConnection()- return try connection.session.request(- "config/read",- params: ["includeLayers": false],- as: ConfigReadResponse.self- )+ func areTUINotificationsEnabled() async throws -> Bool {+ try readyConnection().session.perform(AccountRequests.configuration).areTUINotificationsEnabled}- /// 设置写入统一走批量接口, 让 Codex 负责刷新用户配置- func writeCodexConfigBatch(edits: [ConfigBatchEdit]) async throws -> ConfigWriteResponse {- let connection = try readyConnection()- return try connection.session.request(- "config/batchWrite",- params: [- "edits": edits.map(\.appServerObject),- "reloadUserConfig": true- ],- as: ConfigWriteResponse.self- )+ func setTUINotificationsEnabled(_ enabled: Bool) async throws {+ _ = try readyConnection().session.perform(AccountRequests.setTUINotifications(enabled))}- /// 自动重置前必须绕过补充数据缓存读取一份新凭证明细func readCreditsForAutoReset(budget: AppServerRequestBudget) throws -> AutoResetRead {try AppServerRequestBudget.$current.withValue(budget) {try withAutoResetConnection { connection in@@ -225,11 +234,7 @@ actor CodexStatusService {expirationDate: Date) throws -> ResetCreditConsumeResult {let response: ResetCreditConsumeResponse = try withAutoResetConnection { connection in- let accountResponse = try connection.session.request(- "account/read",- params: ["refreshToken": false],- as: AccountReadResponse.self- )+ let accountResponse = try connection.session.perform(AccountRequests.account(refreshToken: false))guard let account = accountResponse.account else {throw CodexStatusError.notLoggedIn}@@ -243,14 +248,7 @@ actor CodexStatusService {guard Date() < AutoResetSchedule.cutoff(for: expirationDate) else {throw AutoResetServiceError.deadlineReached}- return try connection.session.request(- "account/rateLimitResetCredit/consume",- params: [- "creditId": creditID,- "idempotencyKey": idempotencyKey- ],- as: ResetCreditConsumeResponse.self- )+ return try connection.session.perform(AccountRequests.consumeCredit(id: creditID, idempotencyKey: idempotencyKey))}// 消费结果已经确定时刷新失败不能覆盖结果@@ -269,15 +267,15 @@ actor CodexStatusService {trace: inout CodexFetchTrace) -> CodexFetchOutcome {switch ensureConnection() {- case .notLoggedIn:- trace.failureStage = .connect- return .notLoggedIn+ case .authenticationRequired:+ trace.failureStage = .account+ return .authenticationRequiredcase let .unsupportedVersion(minimum):trace.failureStage = .connectreturn .unsupportedVersion(minimum: minimum)- case let .initializationFailed(message):+ case .initializationFailed:trace.failureStage = .connect- return .initializationFailed(message: message)+ return .initializationFailedcase let .ready(connection, reused):trace.connection = reused ? .reused : .newdo {@@ -289,18 +287,19 @@ actor CodexStatusService {return .data(snapshot)} catch FetchFailure.notLoggedIn {supplementalDataCache = SupplementalDataCache()- teardownConnection()+ connection.accountResponse = AccountReadResponse(account: nil)return .notLoggedIn+ } catch FetchFailure.authenticationRequired {+ return .authenticationRequired} catch FetchFailure.needsRebuild {teardownConnection()if reused, allowRebuild {AppLog.app.notice("codex 连接已失效: reason=transportError")return resolveOutcome(allowRebuild: false, trace: &trace)}- return .initializationFailed(message: CodexStatusError.serverConnectionClosed.localizedDescription)+ return .initializationFailed} catch {- teardownConnection()- return .initializationFailed(message: CodexStatusError.serverConnectionClosed.localizedDescription)+ return .initializationFailed}}}@@ -311,8 +310,8 @@ actor CodexStatusService {switch ensureConnection() {case let .ready(connection, _):return connection- case .notLoggedIn:- throw CodexStatusError.notLoggedIn+ case .authenticationRequired:+ throw CodexStatusError.authenticationRequiredcase let .unsupportedVersion(minimum):throw CodexStatusError.unsupportedVersion(minimum: minimum)case .initializationFailed:@@ -351,11 +350,16 @@ actor CodexStatusService {do {return try operation(connection)} catch let error as CodexStatusError where error.isAuthenticationRequired {+ if case .notLoggedIn = error {+ throw error+ }try AppServerRequestBudget.checkCurrent()do {try Self.refreshAccount(using: connection)} catch FetchFailure.notLoggedIn {throw CodexStatusError.notLoggedIn+ } catch FetchFailure.authenticationRequired {+ throw CodexStatusError.authenticationRequired} catch FetchFailure.needsRebuild {throw CodexStatusError.serverConnectionClosed}@@ -363,7 +367,10 @@ actor CodexStatusService {do {return try operation(connection)} catch let error as CodexStatusError where error.isAuthenticationRequired {- throw CodexStatusError.notLoggedIn+ if case .notLoggedIn = error {+ throw error+ }+ throw CodexStatusError.authenticationRequired}}}@@ -373,7 +380,7 @@ actor CodexStatusService {return .ready(connection: connection, reused: true)}teardownConnection()- let resolution = Self.openConnection(socketURL: socketURL)+ let resolution = Self.openConnection(socketURL: socketURL, logStorage: logStorage)if case let .ready(newConnection, _) = resolution {connection = newConnection}@@ -390,11 +397,7 @@ actor CodexStatusService {private func readCreditsForAutoReset(using connection: AppServerConnection) throws -> AutoResetRead {- let accountResponse = try connection.session.request(- "account/read",- params: ["refreshToken": false],- as: AccountReadResponse.self- )+ let accountResponse = try connection.session.perform(AccountRequests.account(refreshToken: false))guard let account = accountResponse.account else {throw CodexStatusError.notLoggedIn}@@ -404,10 +407,7 @@ actor CodexStatusService {AppLog.app.notice("额度缓存已丢弃: reason=accountChanged")}- let rateLimitsResponse = try connection.session.request(- "account/rateLimits/read",- as: AccountRateLimitsResponse.self- )+ let rateLimitsResponse = try connection.session.perform(AccountRequests.rateLimits)supplementalDataCache.rateLimits = rateLimitsResponselet summary = rateLimitsResponse.rateLimitResetCredits@@ -429,7 +429,7 @@ actor CodexStatusService {var didRefresh = falsefunc refreshTokenIfNeeded() throws {- guard !didRefresh else { throw FetchFailure.notLoggedIn }+ guard !didRefresh else { throw FetchFailure.authenticationRequired }didRefresh = truetry Self.refreshAccount(using: connection)}@@ -445,13 +445,12 @@ actor CodexStatusService {}func readSupplemental<Value: Decodable>(- _ method: String,- as type: Value.Type,+ _ request: AppServerRequest<Value>,cache: inout Value?) throws -> CachedSupplementalRead<Value> {try cachedRead(readResultWithAuthRefresh {- Self.read(method, using: connection, as: type)+ Self.read(request, using: connection)},cache: &cache)@@ -463,12 +462,16 @@ actor CodexStatusService {trace.failureStage = .accountif refreshAccountInfo {let accountResult: ReadResult<AccountReadResponse> = try readResultWithAuthRefresh {- Self.read("account/read", params: ["refreshToken": false], using: connection, as: AccountReadResponse.self)+ Self.read(AccountRequests.account(refreshToken: false), using: connection)}- if let response = accountResult.value {- guard response.account != nil else { throw FetchFailure.notLoggedIn }- connection.accountResponse = response+ guard let response = accountResult.value else {+ if case let .skipped(.requestFailed(error)) = accountResult {+ throw error+ }+ throw CodexStatusError.unsupportedMethod}+ guard response.account != nil else { throw FetchFailure.notLoggedIn }+ connection.accountResponse = responsetrace.account = Self.accountStepResult(response: accountResult.value, didRefresh: didRefresh)} else {trace.account = .skipped@@ -484,15 +487,13 @@ actor CodexStatusService {}let rateLimitsRead = try readSupplemental(- "account/rateLimits/read",- as: AccountRateLimitsResponse.self,+ AccountRequests.rateLimits,cache: &supplementalDataCache.rateLimits)trace.rateLimits = rateLimitsRead.steplet usageRead = try readSupplemental(- "account/usage/read",- as: AccountUsageResponse.self,+ AccountRequests.usage,cache: &supplementalDataCache.usage)trace.usage = usageRead.step@@ -573,13 +574,11 @@ actor CodexStatusService {}private static func read<Value: Decodable>(- _ method: String,- params: [String: Any]? = nil,- using connection: AppServerConnection,- as type: Value.Type+ _ request: AppServerRequest<Value>,+ using connection: AppServerConnection) -> ReadResult<Value> {do {- return try .value(connection.session.request(method, params: params, as: type))+ return try .value(connection.session.perform(request))} catch let error as CodexStatusError {return classify(error)} catch {@@ -596,19 +595,21 @@ actor CodexStatusService {}// 重试后仍失败的非认证业务错误不阻断整轮刷新- return error.isTransportFailure ? .broken : .skipped(.requestFailed)+ return error.isTransportFailure ? .broken : .skipped(.requestFailed(error))}private static func refreshAccount(using connection: AppServerConnection) throws {let response: AccountReadResponsedo {- response = try connection.session.request(- "account/read",- params: ["refreshToken": true],- as: AccountReadResponse.self- )+ response = try connection.session.perform(AccountRequests.account(refreshToken: true))} catch let error as CodexStatusError {- throw error.isTransportFailure ? FetchFailure.needsRebuild : FetchFailure.notLoggedIn+ if error.isTransportFailure {+ throw FetchFailure.needsRebuild+ }+ if error.isAuthenticationRequired {+ throw FetchFailure.authenticationRequired+ }+ throw error} catch {throw FetchFailure.needsRebuild}@@ -619,20 +620,21 @@ actor CodexStatusService {}}- /// 初始化失败与未登录在这里分流; 两者都关闭本次新建的连接- private static func openConnection(socketURL: URL) -> ConnectionResolution {+ /// 握手和账户读取成功即可保留连接, 账户为空时继续监听登录变化+ private static func openConnection(socketURL: URL, logStorage: AppServerLogStore?) -> ConnectionResolution {do {- let session = try AccountSession(socketURL: socketURL)- return initializeConnection(session: session, socketURL: socketURL)+ let session = try AccountSession(socketURL: socketURL, logStorage: logStorage)+ return initializeConnection(session: session, socketURL: socketURL, logStorage: logStorage)} catch {- AppServerLogStore.shared.recordFailure(message: error.localizedDescription)- return .initializationFailed(message: String(localized: "codex-status.daemon.error.unavailable"))+ logStorage?.recordFailure(message: error.localizedDescription)+ return .initializationFailed}}private static func initializeConnection(session: AccountSession,- socketURL: URL+ socketURL: URL,+ logStorage: AppServerLogStore?) -> ConnectionResolution {do {let initialized = try session.initializeAccount()@@ -649,22 +651,22 @@ actor CodexStatusService {),reused: false)- } catch CodexStatusError.notLoggedIn {+ } catch let error as CodexStatusError where error.isAuthenticationRequired {session.close()- return .notLoggedIn+ return .authenticationRequired} catch let CodexStatusError.unsupportedVersion(minimum) {session.close()return .unsupportedVersion(minimum: minimum)} catch {// app-server 链路的细节按既有分工进日志窗口, 不重复写系统日志- AppServerLogStore.shared.recordFailure(+ logStorage?.recordFailure(message: String(localized: "log.app-server.error.initialization-failed",defaultValue: "\(error.localizedDescription)"))session.close()- return .initializationFailed(message: CodexStatusError.serverConnectionClosed.localizedDescription)+ return .initializationFailed}}}diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swiftindex 1dff450..bc2817d 100644--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift@@ -49,7 +49,6 @@ final class CodexStatusViewModel: ObservableObject {@Published private(set) var isRefreshing = false@Published private(set) var loadState: CodexLoadState = .loading@Published private(set) var codexConnectionInfo: CodexServerConnectionInfo?- @Published private(set) var connectionErrorMessage: String?@Published private(set) var autoRefreshCountdownStartedAt: Date?@Published private(set) var dataUpdateInterval: DataUpdateInterval@@ -64,14 +63,21 @@ final class CodexStatusViewModel: ObservableObject {private static let dataUpdateIntervalKey = "DataUpdate.intervalSeconds"+ private let fetchResults = CurrentValueSubject<CodexFetchOutcome?, Never>(nil)+ var fetchOutcomes: AnyPublisher<CodexFetchOutcome, Never> {+ fetchResults.compactMap(\.self).eraseToAnyPublisher()+ }+private let service: CodexStatusServiceprivate let defaults: UserDefaultsprivate var autoRefreshTask: Task<Void, Never>?private var pendingRefreshTask: Task<Void, Never>?+ private var accountNotificationTask: Task<Void, Never>?+ private var notificationRefreshTask: Task<Void, Never>?+ private var notificationSchedule = AccountNotificationSchedule()private var pendingForcedRefreshTrigger: LogTrigger?private let refreshCoordinator = RefreshTaskCoordinator()private var connectionInfoGeneration: UInt64 = 0- private var startupErrorMessage: String?init(service: CodexStatusService = CodexStatusService(), defaults: UserDefaults = .standard) {self.service = service@@ -82,6 +88,8 @@ final class CodexStatusViewModel: ObservableObject {deinit {autoRefreshTask?.cancel()+ accountNotificationTask?.cancel()+ notificationRefreshTask?.cancel()pendingRefreshTask?.cancel()refreshCoordinator.cancel()}@@ -94,12 +102,12 @@ final class CodexStatusViewModel: ObservableObject {refresh(trigger: trigger)}- func startAutoRefresh(startupError: String? = nil) {+ func startAutoRefresh() {guard autoRefreshTask == nil else {return}- startupErrorMessage = startupError+ startAccountNotifications()refreshAfterCurrent(trigger: .launch)scheduleAutoRefresh()}@@ -139,6 +147,12 @@ final class CodexStatusViewModel: ObservableObject {return}+ // 持续推送和慢查询不能挤占已到期的定时维护+ let trigger = trigger == .accountNotification && autoRefreshTask != nil+ && dataUpdateInterval.remainingTime(since: autoRefreshCountdownStartedAt, now: Date()) == 0 ? .auto : trigger+ notificationRefreshTask?.cancel()+ notificationRefreshTask = nil+ notificationSchedule.didStartRefresh(at: .now)lastRefreshTrigger = triggerAppLog.app.notice("额度刷新开始: trigger=\(trigger.rawValue, privacy: .public)")let duration = LogDuration()@@ -166,11 +180,13 @@ final class CodexStatusViewModel: ObservableObject {case let .unsupportedVersion(minimum):snapshot = nilloadState = .unsupportedVersion(minimum: minimum)- case .initializationFailed:+ case .authenticationRequired, .initializationFailed:snapshot = nilloadState = .initializationFailed}+ fetchResults.send(result.fetch.outcome)+// 只记各步结果分类, 额度与用量是用户数据, 不进系统日志// RPC 层面的请求响应细节仍然只进日志窗口logRefreshOutcome(@@ -179,15 +195,46 @@ final class CodexStatusViewModel: ObservableObject {elapsed: duration.elapsed)codexConnectionInfo = result.connectionInfo- if loadState != .initializationFailed {- startupErrorMessage = nil+ // 推送只更新账户快照, 定时刷新继续驱动原有历史维护和同步周期+ if trigger != .accountNotification {+ autoRefreshCountdownStartedAt = Date()}- connectionErrorMessage = startupErrorMessage ?? result.fetch.outcome.connectionErrorMessage- autoRefreshCountdownStartedAt = Date()})}+ private func startAccountNotifications() {+ guard accountNotificationTask == nil else { return }+ accountNotificationTask = Task { [weak self, service] in+ while !Task.isCancelled, self != nil {+ let generation = self?.connectionInfoGeneration+ let change = await service.pollAccountChanges()+ guard !Task.isCancelled else { return }+ if generation == self?.connectionInfoGeneration, let change {+ self?.receiveAccountChange(change)+ }+ do { try await Task.sleep(for: .milliseconds(250)) } catch { return }+ }+ }+ }++ func receiveAccountChange(_ change: AccountChange) {+ notificationSchedule.receive(change, at: .now)+ scheduleNotificationRefresh()+ }++ private func scheduleNotificationRefresh() {+ notificationRefreshTask?.cancel()+ notificationRefreshTask = nil+ guard !isRefreshing, !isReconnecting, let deadline = notificationSchedule.readyAt else { return }+ notificationRefreshTask = Task { @MainActor [weak self] in+ do { try await ContinuousClock().sleep(until: deadline) } catch { return }+ guard let self, !Task.isCancelled else { return }+ notificationRefreshTask = nil+ refresh(trigger: .accountNotification)+ }+ }+/// 自动消费完成后不能因为普通刷新正在运行而丢掉最终核对func refreshAfterCurrent(trigger: LogTrigger) {guard isRefreshing || isReconnecting else {@@ -200,7 +247,9 @@ final class CodexStatusViewModel: ObservableObject {private func setRefreshing(_ refreshing: Bool) {isRefreshing = refreshing- guard !refreshing, let trigger = pendingForcedRefreshTrigger else {+ guard !refreshing else { return }+ guard let trigger = pendingForcedRefreshTrigger else {+ scheduleNotificationRefresh()return}@@ -291,10 +340,12 @@ final class CodexStatusViewModel: ObservableObject {}isReconnecting = true+ notificationRefreshTask?.cancel()+ notificationRefreshTask = nil+ notificationSchedule = AccountNotificationSchedule()codexConnectionInfo = nilsnapshot = nilloadState = .loading- connectionErrorMessage = nilconnectionInfoGeneration &+= 1var didReconnect = falsedefer {@@ -303,12 +354,14 @@ final class CodexStatusViewModel: ObservableObject {pendingForcedRefreshTrigger = nilif didReconnect || trigger != nil {refresh(trigger: trigger ?? .manual)+ } else {+ scheduleNotificationRefresh()}}do {codexConnectionInfo = try await service.reconnect(- minimumVersion: CodexMinimumVersion.activity+ minimumVersion: CodexVersionReader.minimumAppServerVersion)didReconnect = true} catch {@@ -317,7 +370,6 @@ final class CodexStatusViewModel: ObservableObject {case let CodexStatusError.unsupportedVersion(minimum): .unsupportedVersion(minimum: minimum)default: .initializationFailed}- connectionErrorMessage = error.localizedDescription}}@@ -330,3 +382,26 @@ final class CodexStatusViewModel: ObservableObject {return max(1, remaining)}}++/// 首条通知固定合并截止时间, 后续通知不能无限延后刷新+nonisolated struct AccountNotificationSchedule {+ private(set) var readyAt: ContinuousClock.Instant?+ private var pending: AccountChange?+ private var lastRefreshStartedAt: ContinuousClock.Instant?++ mutating func receive(_ change: AccountChange, at now: ContinuousClock.Instant) {+ let deadline = now.advanced(by: .seconds(1))+ if change == .account {+ readyAt = min(readyAt ?? deadline, deadline)+ } else if pending == nil {+ readyAt = max(deadline, lastRefreshStartedAt?.advanced(by: .seconds(10)) ?? deadline)+ }+ pending = change.merging(pending)+ }++ mutating func didStartRefresh(at now: ContinuousClock.Instant) {+ readyAt = nil+ pending = nil+ lastRefreshStartedAt = now+ }+}diff --git a/CodexBar/Services/History/AppServerEventJournal.swift b/CodexBar/Services/History/AppServerEventJournal.swiftindex 14f8ce8..edee40f 100644--- a/CodexBar/Services/History/AppServerEventJournal.swift+++ b/CodexBar/Services/History/AppServerEventJournal.swift@@ -11,6 +11,13 @@ nonisolated struct AppServerEventJournal {let eventLogURL = HistoryStorage.eventLogURL(for: dateKey, in: eventsDirectory)let maintenanceURL = HistoryStorage.maintenanceURL(in: directoryURL)var maintenanceState = try JSONFileStorage.load(HistoryMaintenanceState.self, from: maintenanceURL) ?? HistoryMaintenanceState()+ if !FileManager.default.fileExists(atPath: eventLogURL.path) {+ let header = Header(version: Header.currentVersion, date: dateKey, generationID: UUID().uuidString.lowercased())+ try FileManager.default.createDirectory(at: eventsDirectory, withIntermediateDirectories: true)+ try (JSONLines.stableEncoder.encode(header) + Data([JSONLines.newlineByte])).write(to: eventLogURL, options: .atomic)+ }+ let header = try Self.header(at: eventLogURL)+ guard header.date == dateKey else { throw StorageCompatibilityError.sourceConflict }let existingStat = HistoryStorage.fileStat(at: eventLogURL)var stateChanged = falseif entry.deduplicationID != nil, sizes[dateKey] != existingStat?.size || inodes[dateKey] != existingStat?.identifier {@@ -34,31 +41,11 @@ nonisolated struct AppServerEventJournal {return}- if let existingStat {- let day = maintenanceState.days[dateKey]- let identifierChanged = day?.fileIdentifier != nil- && day?.fileIdentifier != existingStat.identifier- let fileShrank = day.map { existingStat.size < $0.offset } ?? false-- if identifierChanged || fileShrank {- maintenanceState.startNewGeneration(- for: dateKey,- startedEmpty: existingStat.size == 0,- fileIdentifier: existingStat.identifier- )- stateChanged = true- } else {- stateChanged = maintenanceState.ensureGenerationID(- for: dateKey,- fileIdentifier: existingStat.identifier- )- }- } else {- maintenanceState.startNewGeneration(- for: dateKey,- startedEmpty: true,- fileIdentifier: nil+ if maintenanceState.days[dateKey]?.generationID != header.generationID {+ maintenanceState.days[dateKey] = HistoryDayMaintenanceState(+ generationID: header.generationID, fileIdentifier: existingStat?.identifier)+ maintenanceState.markDirty(dateKey)stateChanged = true}@@ -88,21 +75,60 @@ nonisolated struct AppServerEventJournal {}/// 分块扫描并限制单行大小, 截断或损坏的行不影响其他完整记录- static func read(at url: URL, from offset: UInt64 = 0, onInvalidLine: (() -> Void)? = nil, consume: (AppServerEventRecord) throws -> Void) throws {+ static func read(+ at url: URL,+ from offset: UInt64 = 0,+ upTo endOffset: UInt64? = nil,+ onInvalidLine: (() -> Void)? = nil,+ consume: (AppServerEventRecord) throws -> Void+ ) throws {+ if let endOffset, endOffset <= offset {+ return+ }+ let header = try Self.header(at: url)let handle = try FileHandle(forReadingFrom: url)defer { try? handle.close() }try handle.seek(toOffset: offset)+ var remaining = endOffset.map { $0 > offset ? $0 - offset : 0 } ?? UInt64.maxvar buffer = Data()var droppingLine = falselet maximumLineSize = 1024 * 1024- while let chunk = try handle.read(upToCount: 64 * 1024), !chunk.isEmpty {+ var firstLine = offset == 0+ func consumeLine(_ data: Data) throws {+ try Task.checkCancellation()+ if firstLine {+ firstLine = false+ let decoded = try JSONLines.decoder.decode(Header.self, from: data)+ guard decoded == header else { throw StorageCompatibilityError.sourceConflict }+ return+ }+ if let text = String(bytes: data, encoding: .utf8), text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ return+ }+ let entry: AppServerEventRecord+ do {+ try StorageVersion.validate(data, current: AppServerEventRecord.currentVersion, name: "Event")+ entry = try AppServerEventRecord.decode(from: data)+ } catch is DecodingError {+ onInvalidLine?()+ return+ }+ try consume(entry)+ }+ while remaining > 0 {+ try Task.checkCancellation()+ let readSize = Int(min(remaining, 64 * 1024))+ guard let chunk = try handle.read(upToCount: readSize), !chunk.isEmpty else { break }+ remaining -= UInt64(chunk.count)buffer.append(chunk)while let newline = buffer.firstIndex(of: JSONLines.newlineByte) {let line = Data(buffer[..<newline])- if !droppingLine, line.count <= maximumLineSize, let entry = try? AppServerEventRecord.decode(from: line) {- try consume(entry)- } else if !droppingLine, !line.isEmpty {- onInvalidLine?()+ if !droppingLine {+ if line.count <= maximumLineSize {+ try consumeLine(line)+ } else {+ onInvalidLine?()+ }}droppingLine = falsebuffer.removeSubrange(...newline)@@ -115,11 +141,31 @@ nonisolated struct AppServerEventJournal {droppingLine = true}}- if !droppingLine, let entry = try? AppServerEventRecord.decode(from: buffer) {- try consume(entry)- } else if !droppingLine, !buffer.isEmpty {- onInvalidLine?()+ if !droppingLine, !buffer.isEmpty {+ try consumeLine(buffer)+ }+ }++ struct Header: Codable, Equatable {+ static let currentVersion = 1+ let version: Int+ let date: String+ let generationID: String+ }++ static func header(at url: URL) throws -> Header {+ let handle = try FileHandle(forReadingFrom: url)+ defer { try? handle.close() }+ guard let data = try handle.read(upToCount: 4096), let end = data.firstIndex(of: JSONLines.newlineByte) else {+ throw StorageCompatibilityError.incompleteSource+ }+ let line = Data(data[..<end])+ try StorageVersion.validate(line, current: Header.currentVersion, name: "EventJournal")+ let header = try JSONLines.decoder.decode(Header.self, from: line)+ guard HistoryStorage.isValidDateKey(header.date), !header.generationID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ throw StorageCompatibilityError.sourceConflict}+ return header}private func append(_ data: Data, to url: URL) throws {diff --git a/CodexBar/Services/History/HistoryMaintenance.swift b/CodexBar/Services/History/HistoryMaintenance.swiftindex 11bdf1e..594d224 100644--- a/CodexBar/Services/History/HistoryMaintenance.swift+++ b/CodexBar/Services/History/HistoryMaintenance.swift@@ -9,7 +9,7 @@ nonisolated struct HistoryMaintenanceState: Codable, Equatable {case days}- /// 原始事件到每日聚合的算法版本, 变化时统一从原始 JSONL 重建+ /// 维护状态的格式版本, 与每条聚合实际使用的算法版本独立static let currentVersion = 1var version: Int@@ -31,8 +31,8 @@ nonisolated struct HistoryMaintenanceState: Codable, Equatable {init(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self)- // 缺少版本只能说明来源更旧, 不能乐观视为当前算法- version = try container.decodeIfPresent(Int.self, forKey: .version) ?? 0+ version = try container.decode(Int.self, forKey: .version)+ try StorageVersion.require(version, current: Self.currentVersion, name: "AggregationState")pending = try Self.normalizedDates(container.decodeIfPresent([String].self, forKey: .pending) ?? [])dirty = try Self.normalizedDates(container.decodeIfPresent([String].self, forKey: .dirty) ?? [])days = try container.decodeIfPresent([String: HistoryDayMaintenanceState].self, forKey: .days) ?? [:]@@ -86,42 +86,6 @@ nonisolated struct HistoryMaintenanceState: Codable, Equatable {days.removeValue(forKey: dateKey)}- @discardableResult- mutating func ensureGenerationID(- for dateKey: String,- fileIdentifier: UInt64?- ) -> Bool {- var day = days[dateKey] ?? HistoryDayMaintenanceState()- var changed = false-- if day.generationID == nil {- day.generationID = Self.makeGenerationID()- day.generationStartedEmpty = false- changed = true- }- if day.fileIdentifier == nil, let fileIdentifier {- day.fileIdentifier = fileIdentifier- changed = true- }-- days[dateKey] = day- return changed- }-- mutating func startNewGeneration(- for dateKey: String,- startedEmpty: Bool,- fileIdentifier: UInt64?- ) {- days[dateKey] = HistoryDayMaintenanceState(- requiresCloudReplacement: days[dateKey]?.requiresCloudReplacement ?? false,- generationID: Self.makeGenerationID(),- generationStartedEmpty: startedEmpty,- fileIdentifier: fileIdentifier- )- markDirty(dateKey)- }-mutating func normalize() -> Bool {let previousPending = pendinglet previousDirty = dirty@@ -147,62 +111,43 @@ nonisolated struct HistoryMaintenanceState: Codable, Equatable {private static func normalizedDates(_ dates: [String]) -> [String] {Set(dates.filter(HistoryStorage.isValidDateKey)).sorted()}-- private static func makeGenerationID() -> String {- UUID().uuidString.lowercased()- }}nonisolated struct HistoryDayMaintenanceState: Codable, Equatable {private enum CodingKeys: String, CodingKey {- case requiresCloudReplacementcase offsetcase sizecase corruptcase generationID- case generationStartedEmptycase fileIdentifier- case boundaryHash}- var requiresCloudReplacement: Boolvar offset: UInt64var size: UInt64var corrupt: Intvar generationID: String?- var generationStartedEmpty: Boolvar fileIdentifier: UInt64?- var boundaryHash: String?init(- requiresCloudReplacement: Bool = false,offset: UInt64 = 0,size: UInt64 = 0,corrupt: Int = 0,generationID: String? = nil,- generationStartedEmpty: Bool = false,- fileIdentifier: UInt64? = nil,- boundaryHash: String? = nil+ fileIdentifier: UInt64? = nil) {- self.requiresCloudReplacement = requiresCloudReplacementself.offset = offsetself.size = sizeself.corrupt = corruptself.generationID = generationID- self.generationStartedEmpty = generationStartedEmptyself.fileIdentifier = fileIdentifier- self.boundaryHash = boundaryHash}init(from decoder: Decoder) throws {let container = try decoder.container(keyedBy: CodingKeys.self)- requiresCloudReplacement = try container.decodeIfPresent(Bool.self, forKey: .requiresCloudReplacement) ?? falseoffset = try container.decodeIfPresent(UInt64.self, forKey: .offset) ?? 0size = try container.decodeIfPresent(UInt64.self, forKey: .size) ?? 0corrupt = try container.decodeIfPresent(Int.self, forKey: .corrupt) ?? 0generationID = try container.decodeIfPresent(String.self, forKey: .generationID)- generationStartedEmpty = try container.decodeIfPresent(Bool.self, forKey: .generationStartedEmpty) ?? falsefileIdentifier = try container.decodeIfPresent(UInt64.self, forKey: .fileIdentifier)- boundaryHash = try container.decodeIfPresent(String.self, forKey: .boundaryHash)}}diff --git a/CodexBar/Services/History/HistoryService.swift b/CodexBar/Services/History/HistoryService.swiftindex 7fc2b23..98f7c2b 100644--- a/CodexBar/Services/History/HistoryService.swift+++ b/CodexBar/Services/History/HistoryService.swift@@ -1,4 +1,3 @@-import CryptoKitimport Foundationimport os@@ -43,7 +42,7 @@ actor HistoryService {/// 上一条维护日志之后连续空转的轮数, 记出去就清零private var idleMaintenanceRounds = 0private var verifiedBoundaries: [String: HistoryBoundaryVerification] = [:]- private static let eventReadChunkSize = 64 * 1024+ private var lastRetentionCutoff: Date?init(directoryURL: URL = HistoryStorage.directoryURL(),@@ -63,20 +62,26 @@ actor HistoryService {synchronize: Bool = false,trigger: LogTrigger = .auto) async -> HistorySnapshot {- await makeSnapshot(- localAggregates: loadDailyAggregates() ?? [],+ let decoded = try? loadDailyAggregatesWithFailures()+ var snapshot = await makeSnapshot(+ localAggregates: decoded?.compatibilityError == nil ? ActivityAggregate.normalized(aggregates: decoded?.values ?? []) : [],synchronize: synchronize,trigger: trigger)+ snapshot.isActivityComplete = snapshot.isActivityComplete && decoded != nil+ && decoded?.compatibilityError == nil && decoded?.failedLineCount == 0+ return snapshot}/// 先跑一轮维护再取快照/// counts 为 nil 表示这一轮空转, 由调用方决定记不记日志func loadSnapshotWithMaintenance(synchronize: Bool,- trigger: LogTrigger+ trigger: LogTrigger,+ now: Date = Date()) async -> (snapshot: HistorySnapshot, counts: HistoryMaintenanceCounts?) {- let counts = performMaintenanceIfNeeded()+ await syncService.pruneLocalCaches(now: now)+ let counts = performMaintenanceIfNeeded(now: now)let snapshot = await loadSnapshot(synchronize: synchronize, trigger: trigger)return (snapshot, counts)}@@ -87,9 +92,6 @@ actor HistoryService {trigger: LogTrigger,localTokenTurns: [TokenTurn]? = nil) async -> HistorySnapshot {- let replacements = readyReplacements()- // 零值替换仍需同步, 展示和普通上传不生成 Token-only 日期的活动贡献- let localAggregates = localAggregates.filter { $0.eventCount != 0 }let tokenTurns: [TokenTurn]if let localTokenTurns {tokenTurns = localTokenTurns@@ -100,27 +102,38 @@ actor HistoryService {} catch {let error = error as NSErrorAppLog.history.error("Token 历史读取失败: domain=\(error.domain, privacy: .public) code=\(error.code)")- tokenTurns = []+ tokenTurns = await (try? tokenHistory.persistedTurns()) ?? []}}+ let maintenance = try? HistoryStorage.loadMaintenanceState(in: directoryURL)+ let uploadable = localAggregates.filter { aggregate in+ guard let state = maintenance, !state.dirty.contains(aggregate.date),+ let day = state.days[aggregate.date] else { return false }+ return day.generationID == aggregate.generationID && day.offset == aggregate.sourceCheckpoint?.byteCount+ }let syncSnapshot: SyncSnapshot = if synchronize {await syncService.synchronizeIfEnabled(- localAggregates: localAggregates, localTokenTurns: tokenTurns, replacements: replacements, trigger: trigger+ localAggregates: uploadable, localTokenTurns: tokenTurns,+ recoveredTokenIDs: tokenHistory.pendingRecoveryIDs(), trigger: trigger)} else {- await syncService.snapshotFromCacheIfEnabled(localTokenTurns: tokenTurns, replacements: replacements)+ await syncService.snapshotFromCacheIfEnabled(localTokenTurns: tokenTurns)}- acknowledgeReplacements(syncSnapshot.completedReplacements)var snapshot = HistorySnapshot(localAggregates: localAggregates,- syncedRecords: syncSnapshot.records.filter { $0.daily.eventCount != 0 },+ syncedRecords: syncSnapshot.records,currentDeviceID: syncSnapshot.currentDeviceID)snapshot.tokenUsageByDate = syncSnapshot.tokenUsageByDate ?? TokenTurn.dailyUsage(tokenTurns)+ snapshot.isActivityComplete = snapshot.isActivityComplete && syncSnapshot.isActivityComplete && maintenance != nil+ let knownDates = Set(localAggregates.map(\.date)).union(+ syncSnapshot.records.filter { $0.deviceID == syncSnapshot.currentDeviceID }.map(\.date)+ )+ snapshot.unavailableActivityDates.formUnion(Set(maintenance?.dirty ?? []).subtracting(knownDates))return snapshot}- /// 以指定日期范围内的本机原始事件为权威来源重建, 并安排替换当前设备的同日云端贡献+ /// 从指定日期的原始事件重建, 同一来源继续使用同一云端记录func rebuildData(for dateKeys: [String],synchronize: Bool@@ -190,12 +203,13 @@ actor HistoryService {localTokenTurns: localTurns)let tokenSyncPending = await syncService.hasPendingTokenUpdates(local: localTurns)+ let activitySyncPending = await syncService.hasPendingActivityUpdates(local: loadDailyAggregates() ?? [])let tokenFailures = didFailTokenRebuild ? normalizedDateKeys : tokenResult.failedDateKeyslet summary = HistoryDataRebuildSummary(rebuiltDateCount: Set(rebuildResults.map(\.dateKey)).union(tokenResult.dateKeys).subtracting(failedDateKeys).subtracting(tokenFailures).count,eventCount: rebuildResults.reduce(0) { $0 + ($1.aggregate.eventCount ?? 0) },- isSyncReplacementPending: hasPendingReplacement(for: eventDateKeysWithData) || tokenSyncPending,+ isSyncPending: activitySyncPending || tokenSyncPending,failedDateKeys: failedDateKeys,failedRequestDateKeys: failedRequestDateKeys,failedTokenDateKeys: tokenFailures,@@ -214,54 +228,9 @@ actor HistoryService {return HistoryDataRebuildOutcome(snapshot: snapshot, summary: summary)}- func hasPendingReplacement(for dates: [String]) -> Bool {- let state = HistoryStorage.loadMaintenanceState(in: directoryURL)- return dates.contains { state.days[$0]?.requiresCloudReplacement == true }- }-- /// 只从同一锁内读取的聚合和提交状态形成替换授权, dirty 状态不允许覆盖云端- private func readyReplacements() -> [ActivityAggregate] {- (try? HistoryStorage.withExclusiveLock(in: directoryURL) {- let state = HistoryStorage.loadMaintenanceState(in: directoryURL)- return (loadDailyAggregates() ?? []).filter { aggregate in- guard let day = state.days[aggregate.date], day.requiresCloudReplacement,- !state.dirty.contains(aggregate.date), day.corrupt == 0, day.offset == day.size, day.offset > 0,- let generation = day.generationID, aggregate.generationID == generation,- aggregate.eventCount != nil,- let stat = HistoryStorage.fileStat(at: eventLogURL(for: aggregate.date)),- stat.identifier == day.fileIdentifier, stat.size >= day.offset else { return false }- return !hasBoundaryChanged(dateKey: aggregate.date, day: day, stat: stat)- }- }) ?? []- }-- func acknowledgeReplacements(_ completed: [String: String]) {- guard !completed.isEmpty else { return }- do {- try HistoryStorage.withExclusiveLock(in: directoryURL) {- var state = HistoryStorage.loadMaintenanceState(in: directoryURL)- for (date, generation) in completed where state.days[date]?.generationID == generation- && !state.dirty.contains(date) {- state.days[date]?.requiresCloudReplacement = false- }- try HistoryStorage.saveMaintenanceState(state, in: directoryURL)- }- } catch {- AppLog.history.error("云端替换确认保存失败: \(error.localizedDescription, privacy: .public)")- }- }-private func loadDailyAggregates() -> [ActivityAggregate]? {- guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {- return nil- }-- let aggregates: [ActivityAggregate] = JSONLines.decode(from: data)- guard !aggregates.isEmpty else {- return nil- }-- return ActivityAggregate.normalized(aggregates: aggregates)+ guard let decoded = try? loadDailyAggregatesWithFailures(), decoded.compatibilityError == nil else { return nil }+ return ActivityAggregate.normalized(aggregates: decoded.values)}// MARK: - 重建与维护调度@@ -270,7 +239,7 @@ actor HistoryService {var aggregates = loadDailyAggregates() ?? []let eventCountAvailability = aggregates.first(where: { $0.date == dateKey })?- .eventCountAvailability ?? .legacy+ .eventCountAvailability ?? .alllet task = try prepareRebuildTask(for: dateKey,eventCountAvailability: eventCountAvailability@@ -305,9 +274,13 @@ actor HistoryService {throw HistoryDataRebuildError.sourceUnavailable}- var state = HistoryStorage.loadMaintenanceState(in: directoryURL)- state.startNewGeneration(for: dateKey, startedEmpty: false, fileIdentifier: stat.identifier)- state.days[dateKey]?.requiresCloudReplacement = true+ var state = try HistoryStorage.loadMaintenanceState(in: directoryURL)+ let header = try AppServerEventJournal.header(at: eventLogURL(for: dateKey))+ guard header.date == dateKey else { throw StorageCompatibilityError.sourceConflict }+ if state.days[dateKey]?.generationID != header.generationID {+ state.days[dateKey] = HistoryDayMaintenanceState(generationID: header.generationID, fileIdentifier: stat.identifier)+ }+ state.markDirty(dateKey)try HistoryStorage.saveMaintenanceState(state, in: directoryURL)guard let day = state.days[dateKey] else { throw HistoryDataRebuildError.sourceUnavailable }return dirtyTask(for: dateKey, day: day, size: stat.size, eventCountAvailability: eventCountAvailability)@@ -323,7 +296,7 @@ actor HistoryService {}return (try? HistoryStorage.withExclusiveLock(in: directoryURL) {- guard let day = HistoryStorage.loadMaintenanceState(in: directoryURL).days[result.dateKey] else {+ guard let day = try HistoryStorage.loadMaintenanceState(in: directoryURL).days[result.dateKey] else {return false}return day.generationID == result.aggregate.generationID@@ -334,11 +307,14 @@ actor HistoryService {/// 空转的一轮返回 nil/// 维护跟随额度刷新执行, 只记录有实际工作的轮次, 避免空闲时持续产生重复日志/// 收尾日志由 SyncScheduler 统一记, 这里只负责判断有没有值得记的东西- private func performMaintenanceIfNeeded() -> HistoryMaintenanceCounts? {+ private func performMaintenanceIfNeeded(now: Date) -> HistoryMaintenanceCounts? {let duration = LogDuration()var counts = HistoryMaintenanceCounts()var stage = MaintenanceStage.preparedo {+ stage = .prune+ counts.pruned = try pruneExpiredEventFiles(now: now)+ stage = .preparelet tasks = try prepareMaintenanceTasks()stage = .writelet didCommitDailyLog = perform(tasks, counts: &counts)@@ -346,8 +322,6 @@ actor HistoryService {if !didCommitDailyLog {try normalizeDailyAggregatesIfNeeded()}- stage = .prune- counts.pruned = try pruneExpiredEventFiles()} catch {let elapsed = duration.elapsedlet details = LogFields.joined(@@ -407,10 +381,12 @@ actor HistoryService {"stage=daily","date=\(task.dateKey)","detail=\(error.localizedDescription)",- "action=markDirty"+ "action=retry")AppLog.history.error("事件汇总失败: \(details, privacy: .public)")- markDirty(task.dateKey)+ if case .rebuild = task.mode {+ markDirty(task.dateKey)+ }}}@@ -418,11 +394,14 @@ actor HistoryService {}private func prepareMaintenanceTasks() throws -> [HistoryMaintenanceTask] {- let eventDateKeys = eventDateKeys()- let dailyDecodeResult = loadDailyAggregatesWithFailures()+ let eventDateKeys = try eventDateKeys()+ let dailyDecodeResult = try loadDailyAggregatesWithFailures()+ if let error = dailyDecodeResult.compatibilityError {+ throw error+ }return try HistoryStorage.withExclusiveLock(in: directoryURL) {- var state = HistoryStorage.loadMaintenanceState(in: directoryURL)+ var state = try HistoryStorage.loadMaintenanceState(in: directoryURL)var changedState = state.normalize()let dailyByDate = dailyDecodeResult.values.reduce(into: [String: ActivityAggregate]()) { result, aggregate inresult[aggregate.date] = aggregate@@ -430,11 +409,10 @@ actor HistoryService {let changedByRebuild = markRebuildDates(eventDateKeys: eventDateKeys,- dailyDecodeResult: dailyDecodeResult,dailyByDate: dailyByDate,state: &state)- let changedByReconcile = reconcileEventFiles(eventDateKeys: eventDateKeys, state: &state)+ let changedByReconcile = try reconcileEventFiles(eventDateKeys: eventDateKeys, dailyByDate: dailyByDate, state: &state)changedState = changedState || changedByRebuild || changedByReconcilelet tasks = makeMaintenanceTasks(@@ -453,22 +431,11 @@ actor HistoryService {private func markRebuildDates(eventDateKeys: [String],- dailyDecodeResult: JSONLinesDecodeResult<ActivityAggregate>,dailyByDate: [String: ActivityAggregate],state: inout HistoryMaintenanceState) -> Bool {var changed = false- if state.version != HistoryMaintenanceState.currentVersion {- changed = state.markDirty(contentsOf: eventDateKeys) || changed- state.version = HistoryMaintenanceState.currentVersion- changed = true- }-- if dailyDecodeResult.failedLineCount > 0 || (dailyDecodeResult.values.isEmpty && !eventDateKeys.isEmpty) {- changed = state.markDirty(contentsOf: eventDateKeys) || changed- }-changed = state.markDirty(contentsOf: eventDateKeys.filter { dailyByDate[$0] == nil }) || changedchanged = state.markDirty(contentsOf: state.pending.filter { dailyByDate[$0] == nil }) || changed@@ -477,34 +444,47 @@ actor HistoryService {private func reconcileEventFiles(eventDateKeys: [String],+ dailyByDate: [String: ActivityAggregate],state: inout HistoryMaintenanceState- ) -> Bool {+ ) throws -> Bool {verifiedBoundaries = verifiedBoundaries.filter { state.days[$0.key] != nil }- var changed = state.markDirty(contentsOf: eventDateKeys.filter { state.days[$0] == nil })+ var changed = falsefor dateKey in eventDateKeys {guard let stat = HistoryStorage.fileStat(at: eventLogURL(for: dateKey)) else {continue}- changed = state.ensureGenerationID(- for: dateKey,- fileIdentifier: stat.identifier- ) || changed+ let header: AppServerEventJournal.Header+ do {+ header = try AppServerEventJournal.header(at: eventLogURL(for: dateKey))+ guard header.date == dateKey else { throw StorageCompatibilityError.sourceConflict }+ } catch {+ changed = state.markDirty(dateKey) || changed+ continue+ }+ if state.days[dateKey] == nil, let aggregate = dailyByDate[dateKey],+ aggregate.generationID == header.generationID, let checkpoint = aggregate.sourceCheckpoint,+ !hasBoundaryChanged(dateKey: dateKey, checkpoint: checkpoint, stat: stat) {+ state.days[dateKey] = HistoryDayMaintenanceState(+ offset: checkpoint.byteCount, size: checkpoint.byteCount,+ generationID: header.generationID, fileIdentifier: stat.identifier+ )+ changed = true+ } else if state.days[dateKey]?.generationID != header.generationID {+ state.days[dateKey] = HistoryDayMaintenanceState(generationID: header.generationID, fileIdentifier: stat.identifier)+ changed = state.markDirty(dateKey) || changed+ }guard let day = state.days[dateKey] else {continue}let identifierChanged = day.fileIdentifier != nil&& day.fileIdentifier != stat.identifier- let boundaryChanged = hasBoundaryChanged(dateKey: dateKey, day: day, stat: stat)+ let boundaryChanged = hasBoundaryChanged(dateKey: dateKey, checkpoint: dailyByDate[dateKey]?.sourceCheckpoint, stat: stat)if identifierChanged || stat.size < day.offset || boundaryChanged {- state.startNewGeneration(- for: dateKey,- startedEmpty: stat.size == 0,- fileIdentifier: stat.identifier- )+ state.markDirty(dateKey)changed = true} else if day.offset != day.size {state.markDirty(dateKey)@@ -520,29 +500,18 @@ actor HistoryService {return changed}- /// boundaryHash 覆盖 offset 之前的边界片段, 追加只写在 offset 之后- /// 文件未修改时复用已有哈希, 减少持锁时间和采集器的等待- private func hasBoundaryChanged(- dateKey: String,- day: HistoryDayMaintenanceState,- stat: HistoryFileStat- ) -> Bool {- guard let recordedHash = day.boundaryHash else {- return false- }-- // 只有完整 stat 可以跳过校验, 毫秒精度不能区分同毫秒内的改写+ /// 完整前缀校验避免日志中部改写被误认成普通追加, 文件未变时复用校验结果+ private func hasBoundaryChanged(dateKey: String, checkpoint: ActivitySourceCheckpoint?, stat: HistoryFileStat) -> Bool {+ guard let checkpoint else { return true }if let verified = verifiedBoundaries[dateKey],- verified.offset == day.offset, verified.digest == recordedHash, verified.stat == stat {+ verified.offset == checkpoint.byteCount, verified.digest == checkpoint.digest, verified.stat == stat {return false}-- guard (try? eventLogBoundaryHash(for: dateKey, endingAt: day.offset)) == recordedHash else {+ guard checkpoint.matchesSource(try? ActivitySourceCheckpoint.read(at: eventLogURL(for: dateKey), byteCount: checkpoint.byteCount)) else {verifiedBoundaries.removeValue(forKey: dateKey)return true}-- verifiedBoundaries[dateKey] = HistoryBoundaryVerification(offset: day.offset, digest: recordedHash, stat: stat)+ verifiedBoundaries[dateKey] = HistoryBoundaryVerification(offset: checkpoint.byteCount, digest: checkpoint.digest, stat: stat)return false}@@ -551,8 +520,9 @@ actor HistoryService {dailyByDate: [String: ActivityAggregate],changedState: inout Bool) -> [HistoryMaintenanceTask] {- let dirty = Set(state.dirty)- var tasks: [HistoryMaintenanceTask] = state.dirty.compactMap { dateKey in+ let cutoff = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate())+ let dirty = Set(state.dirty.filter { $0 >= cutoff })+ var tasks: [HistoryMaintenanceTask] = state.dirty.filter { $0 >= cutoff }.compactMap { dateKey inguard let day = state.days[dateKey] else {return nil}@@ -560,11 +530,11 @@ actor HistoryService {for: dateKey,day: day,eventCountAvailability: dailyByDate[dateKey]?- .eventCountAvailability ?? .legacy+ .eventCountAvailability ?? .all)}- for dateKey in state.pending where !dirty.contains(dateKey) {+ for dateKey in state.pending where dateKey >= cutoff && !dirty.contains(dateKey) {let day = state.days[dateKey] ?? HistoryDayMaintenanceState()let size = eventLogSize(for: dateKey)guard size > day.offset else {@@ -575,7 +545,8 @@ actor HistoryService {let existingAggregate = dailyByDate[dateKey]guard let baseAggregate = existingAggregate,- baseAggregate.generationID == day.generationID else {+ baseAggregate.generationID == day.generationID,+ baseAggregate.sourceCheckpoint?.byteCount == day.offset else {state.markDirty(dateKey)changedState = truetasks.append(dirtyTask(@@ -583,22 +554,7 @@ actor HistoryService {day: day,size: size,eventCountAvailability: existingAggregate?- .eventCountAvailability ?? .legacy- ))- continue- }-- // ID 已压缩的聚合无法判断追加事件是否属于已有 session 或 turn- // 任何不能证明与全量结果等价的增量任务都降级为完整重建- guard retainsIdentifiers(for: dateKey),- baseAggregate.supportsIncrementalAggregation else {- state.markDirty(dateKey)- changedState = true- tasks.append(dirtyTask(- for: dateKey,- day: day,- size: size,- eventCountAvailability: baseAggregate.eventCountAvailability+ .eventCountAvailability ?? .all))continue}@@ -620,7 +576,7 @@ actor HistoryService {for dateKey: String,day: HistoryDayMaintenanceState,size: UInt64? = nil,- eventCountAvailability: ActivityCountAvailability = .legacy+ eventCountAvailability: ActivityCountAvailability = .all) -> HistoryMaintenanceTask {let stat = HistoryStorage.fileStat(at: eventLogURL(for: dateKey))return HistoryMaintenanceTask(@@ -630,7 +586,6 @@ actor HistoryService {mode: .rebuild(eventCountAvailability),existingCorrupt: 0,generationID: day.generationID,- generationStartedEmpty: day.generationStartedEmpty,fileIdentifier: stat?.identifier)}@@ -648,7 +603,6 @@ actor HistoryService {mode: .append(baseAggregate),existingCorrupt: day.corrupt,generationID: day.generationID,- generationStartedEmpty: day.generationStartedEmpty,fileIdentifier: day.fileIdentifier)}@@ -663,41 +617,17 @@ actor HistoryService {HistoryStorage.fileSize(at: eventLogURL(for: dateKey))}- private func eventLogBoundaryHash(- for dateKey: String,- endingAt offset: UInt64- ) throws -> String? {- guard offset > 0 else {- return nil- }-- let length = min(offset, 4 * 1024)- let handle = try FileHandle(forReadingFrom: eventLogURL(for: dateKey))- defer {- try? handle.close()- }-- try handle.seek(toOffset: offset - length)- guard let data = try handle.read(upToCount: Int(length)),- data.count == Int(length) else {- throw CocoaError(.fileReadUnknown)- }-- return SHA256.hash(data: data)- .map { String(format: "%02x", $0) }- .joined()- }-- private func loadDailyAggregatesWithFailures() -> JSONLinesDecodeResult<ActivityAggregate> {- guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {+ private func loadDailyAggregatesWithFailures() throws -> JSONLinesDecodeResult<ActivityAggregate> {+ do {+ return try JSONLines.decodeWithFailures(from: Data(contentsOf: dailyLogURL))+ } catch let error as CocoaError where error.code == .fileReadNoSuchFile {return JSONLinesDecodeResult(values: [], failedLineCount: 0)}-- return JSONLines.decodeWithFailures(from: data)}- private func eventDateKeys() -> [String] {- HistoryStorage.eventLogDateKeys(in: eventsDirectoryURL)+ private func eventDateKeys() throws -> [String] {+ let cutoff = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate())+ return try HistoryStorage.readEventLogDateKeys(in: eventsDirectoryURL).filter { $0 >= cutoff }}private func buildDailyAggregate(@@ -708,17 +638,22 @@ actor HistoryService {ActivityAccumulator(rebuilding: task.dateKey,generationID: task.generationID,- generationStartedEmpty: task.generationStartedEmpty,+eventCountAvailability: eventCountAvailability)case let .append(baseAggregate):ActivityAccumulator(appending: baseAggregate,- generationID: task.generationID,- generationStartedEmpty: task.generationStartedEmpty+ generationID: task.generationID)}var corrupt = task.existingCorrupt+ if case let .append(base) = task.mode, !base.supportsIncrementalAggregation {+ // 恢复去重身份不重新计算旧计数, 追加到压缩日期也不会改变历史口径+ corrupt += try readEvents(at: eventLogURL(for: task.dateKey), from: 0, upTo: task.startOffset) {+ accumulator.restoreIdentity(from: $0)+ }+ }corrupt += try readEvents(at: eventLogURL(for: task.dateKey),@@ -731,14 +666,25 @@ actor HistoryService {let identifierStorage: ActivityIdentifiers = retainsIdentifiers(for: task.dateKey)? .retained: .compacted- let aggregate = accumulator.finalized(identifierStorage: identifierStorage)- return try HistoryMaintenanceResult(+ var aggregate = accumulator.finalized(identifierStorage: identifierStorage)+ var checkpoint = try ActivitySourceCheckpoint.read(at: eventLogURL(for: task.dateKey), byteCount: task.size)+ let ranges: [AggregationRange] = switch task.mode {+ case .rebuild:+ []+ case let .append(base):+ base.sourceCheckpoint?.aggregationRanges.isEmpty == false+ ? base.sourceCheckpoint?.aggregationRanges ?? []+ : [AggregationRange(version: base.aggregationVersion, end: task.startOffset)]+ }+ checkpoint.aggregationRanges = AggregationRange.appending(to: ranges, version: AggregationVersion.activity, end: task.size)+ aggregate.aggregationVersion = AggregationVersion.activity+ aggregate.sourceCheckpoint = checkpoint+ return HistoryMaintenanceResult(dateKey: task.dateKey,aggregate: aggregate,size: task.size,corrupt: corrupt,- fileIdentifier: task.fileIdentifier,- boundaryHash: eventLogBoundaryHash(for: task.dateKey, endingAt: task.size)+ fileIdentifier: task.fileIdentifier)}@@ -748,69 +694,15 @@ actor HistoryService {upTo size: UInt64,record: (ActivityRecord) -> Void) throws -> Int {- guard size > startOffset else {- return 0- }-- let fileHandle = try FileHandle(forReadingFrom: url)- defer {- try? fileHandle.close()- }-- try fileHandle.seek(toOffset: startOffset)-- var remainingBytes = size - startOffset- var buffer = Data()var corrupt = 0-- // 分块读取防止大日志一次性进内存, 但仍按完整 JSONL 行解码- while remainingBytes > 0 {- let readSize = min(Int(remainingBytes), Self.eventReadChunkSize)- guard let chunk = try fileHandle.read(upToCount: readSize), !chunk.isEmpty else {- break+ try AppServerEventJournal.read(at: url, from: startOffset, upTo: size, onInvalidLine: { corrupt += 1 }, consume: { entry in+ if let event = entry.activity {+ record(event)}-- remainingBytes -= UInt64(chunk.count)- buffer.append(chunk)-- while let newlineIndex = buffer.firstIndex(of: JSONLines.newlineByte) {- let lineData = buffer[..<newlineIndex]- corrupt += Self.decode(lineData, record: record)- buffer.removeSubrange(...newlineIndex)- }- }-- if !buffer.isEmpty {- corrupt += Self.decode(buffer, record: record)- }-+ })return corrupt}- nonisolated static func decode(- _ lineData: Data.SubSequence,- record: (ActivityRecord) -> Void- ) -> Int {- guard let line = String(bytes: lineData, encoding: .utf8)?- .trimmingCharacters(in: .whitespacesAndNewlines) else {- return 1- }-- guard !line.isEmpty else {- return 0- }-- guard let data = line.data(using: .utf8),- let entry = try? AppServerEventRecord.decode(from: data) else {- return 1- }-- if let event = entry.activity {- record(event)- }- return 0- }-// MARK: - 落盘与状态提交/// 返回聚合与维护状态是否都基于同一份事件源完成提交@@ -819,9 +711,9 @@ actor HistoryService {aggregates: inout [ActivityAggregate]) throws -> Bool {try HistoryStorage.withExclusiveLock(in: directoryURL) {- var state = HistoryStorage.loadMaintenanceState(in: directoryURL)+ var state = try HistoryStorage.loadMaintenanceState(in: directoryURL)guard let currentSize = try validatedEventLogSize(for: result, state: &state) else { return false }- if state.days[result.dateKey]?.requiresCloudReplacement == true, result.corrupt > 0 {+ if result.corrupt > 0 {throw HistoryDataRebuildError.incompleteSource}// 两个文件提交前先标脏, 中途退出会从事件重建, 不沿旧偏移重复追加@@ -830,11 +722,9 @@ actor HistoryService {aggregates = loadDailyAggregates() ?? []try writeDailyAggregate(result.aggregate, into: &aggregates)state.days[result.dateKey] = HistoryDayMaintenanceState(- requiresCloudReplacement: state.days[result.dateKey]?.requiresCloudReplacement ?? false,offset: result.size, size: result.size, corrupt: result.corrupt,generationID: result.aggregate.generationID,- generationStartedEmpty: result.aggregate.generationStartedEmpty,- fileIdentifier: result.fileIdentifier, boundaryHash: result.boundaryHash+ fileIdentifier: result.fileIdentifier)state.removeDirty(result.dateKey)if currentSize == result.size {@@ -847,7 +737,7 @@ actor HistoryService {}}- /// 锁内确认读取期间仍是同一份追加源; 断代时换 generation 并等待重建+ /// 锁内确认读取期间仍是同一份追加源, 发生改写则等待重建private func validatedEventLogSize(for result: HistoryMaintenanceResult,state: inout HistoryMaintenanceState@@ -859,20 +749,15 @@ actor HistoryService {let stat = HistoryStorage.fileStat(at: eventLogURL(for: result.dateKey))let identifierMatches = result.fileIdentifier == nil|| result.fileIdentifier == stat?.identifier- let boundaryMatches = (try? eventLogBoundaryHash(- for: result.dateKey,- endingAt: result.size- )) == result.boundaryHash+ let boundaryMatches = result.aggregate.sourceCheckpoint?.matchesSource(try? ActivitySourceCheckpoint.read(+ at: eventLogURL(for: result.dateKey), byteCount: result.size+ )) == trueguard let stat,stat.size >= result.size,identifierMatches,boundaryMatches else {- state.startNewGeneration(- for: result.dateKey,- startedEmpty: stat?.size == 0,- fileIdentifier: stat?.identifier- )+ state.markDirty(result.dateKey)try HistoryStorage.saveMaintenanceState(state, in: directoryURL)return nil}@@ -884,6 +769,9 @@ actor HistoryService {_ aggregate: ActivityAggregate,into aggregates: inout [ActivityAggregate]) throws {+ if let error = try loadDailyAggregatesWithFailures().compatibilityError {+ throw error+ }try FileManager.default.createDirectory(at: dailyLogURL.deletingLastPathComponent(),withIntermediateDirectories: true@@ -895,42 +783,47 @@ actor HistoryService {try data.write(to: dailyLogURL, options: .atomic)}- private func normalizeDailyAggregatesIfNeeded() throws {- guard let stat = HistoryStorage.fileStat(at: dailyLogURL), stat.size > 0 else {- return- }+ func normalizeDailyAggregatesIfNeeded() throws {+ try HistoryStorage.withExclusiveLock(in: directoryURL) {+ guard let stat = HistoryStorage.fileStat(at: dailyLogURL), stat.size > 0 else {+ return+ }- // 稳态下文件与日期都没变, 跳过全量解码与重编码比对- let dayKey = HistoryStorage.dateKey(for: Date())- if lastNormalizedDailyLog == HistoryDailyLogStamp(size: stat.size, identifier: stat.identifier, dayKey: dayKey) {- return- }+ // 稳态下文件与日期都没变, 跳过全量解码与重编码比对+ let dayKey = HistoryStorage.dateKey(for: Date())+ if lastNormalizedDailyLog == HistoryDailyLogStamp(size: stat.size, identifier: stat.identifier, dayKey: dayKey) {+ return+ }- guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {- return- }+ guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {+ return+ }- let decodeResult = JSONLines.decodeWithFailures(ActivityAggregate.self, from: data)- guard decodeResult.failedLineCount == 0 else {- return- }+ let decodeResult = JSONLines.decodeWithFailures(ActivityAggregate.self, from: data)+ if let error = decodeResult.compatibilityError {+ throw error+ }+ guard decodeResult.failedLineCount == 0 else {+ return+ }- let normalizedAggregates = ActivityAggregate.normalized(aggregates: decodeResult.values)- let normalizedData = try ActivityAggregate.encodeJSONLines(normalizedAggregates)- if normalizedData != data {- try FileManager.default.createDirectory(- at: dailyLogURL.deletingLastPathComponent(),- withIntermediateDirectories: true- )- try normalizedData.write(to: dailyLogURL, options: .atomic)- }+ let normalizedAggregates = ActivityAggregate.normalized(aggregates: decodeResult.values)+ let normalizedData = try ActivityAggregate.encodeJSONLines(normalizedAggregates)+ if normalizedData != data {+ try FileManager.default.createDirectory(+ at: dailyLogURL.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )+ try normalizedData.write(to: dailyLogURL, options: .atomic)+ }- if let latestStat = HistoryStorage.fileStat(at: dailyLogURL) {- lastNormalizedDailyLog = HistoryDailyLogStamp(- size: latestStat.size,- identifier: latestStat.identifier,- dayKey: dayKey- )+ if let latestStat = HistoryStorage.fileStat(at: dailyLogURL) {+ lastNormalizedDailyLog = HistoryDailyLogStamp(+ size: latestStat.size,+ identifier: latestStat.identifier,+ dayKey: dayKey+ )+ }}}@@ -945,7 +838,7 @@ actor HistoryService {private func markDirty(_ dateKey: String) {do {try HistoryStorage.withExclusiveLock(in: directoryURL) {- var state = HistoryStorage.loadMaintenanceState(in: directoryURL)+ var state = try HistoryStorage.loadMaintenanceState(in: directoryURL)state.markDirty(dateKey)try HistoryStorage.saveMaintenanceState(state, in: directoryURL)}@@ -963,29 +856,40 @@ actor HistoryService {// MARK: - 保留期清理@discardableResult- private func pruneExpiredEventFiles() throws -> Int {- let cutoffDate = HistoryStorage.retentionCutoffDate()- let expiredDateKeys = eventDateKeys().filter { dateKey in- guard let date = CodexDateFormat.dayDate(from: dateKey) else {- return false+ private func pruneExpiredEventFiles(now: Date) throws -> Int {+ let cutoffDate = HistoryStorage.retentionCutoffDate(today: now)+ guard lastRetentionCutoff != cutoffDate else { return 0 }+ let expiredDateKeys = try HistoryStorage.withExclusiveLock(in: directoryURL) {+ let expiredDateKeys = try HistoryStorage.readEventLogDateKeys(in: eventsDirectoryURL).filter { dateKey in+ dateKey < HistoryStorage.dateKey(for: cutoffDate)}-- return date < cutoffDate- }-- guard !expiredDateKeys.isEmpty else {- return 0- }-- try HistoryStorage.withExclusiveLock(in: directoryURL) {- var state = HistoryStorage.loadMaintenanceState(in: directoryURL)+ var state = try HistoryStorage.loadMaintenanceState(in: directoryURL)+ var failedDates = Set<String>()for dateKey in expiredDateKeys {- try? FileManager.default.removeItem(at: eventLogURL(for: dateKey))+ do {+ try AppServerEventJournal.read(at: eventLogURL(for: dateKey)) { _ in }+ try FileManager.default.removeItem(at: eventLogURL(for: dateKey))+ } catch CocoaError.fileNoSuchFile {+ continue+ } catch {+ failedDates.insert(dateKey)+ AppLog.history.error("过期事件清理失败: date=\(dateKey, privacy: .public) detail=\(error.localizedDescription, privacy: .public)")+ }+ }+ let cutoffKey = HistoryStorage.dateKey(for: cutoffDate)+ let expiredStateKeys = Set(state.days.keys).union(state.pending).union(state.dirty)+ .filter { $0 < cutoffKey && !failedDates.contains($0) }+ for dateKey in expiredStateKeys {state.remove(dateKey)}-- try HistoryStorage.saveMaintenanceState(state, in: directoryURL)+ if !expiredStateKeys.isEmpty {+ try HistoryStorage.saveMaintenanceState(state, in: directoryURL)+ }+ return expiredDateKeys.filter { !failedDates.contains($0) }}+ // 单文件失败留待下一天或重启后重试, 避免刷新时反复扫描同一异常文件+ lastRetentionCutoff = cutoffDate+ guard !expiredDateKeys.isEmpty else { return 0 }// 保留期到点会真的删掉原始事件文件, 数据对不上时要能查到哪些日期被清掉了let details = LogFields.joined("dates=\(expiredDateKeys.count)",@@ -1032,7 +936,6 @@ private nonisolated struct HistoryMaintenanceTask {let mode: HistoryMaintenanceModelet existingCorrupt: Intlet generationID: String?- let generationStartedEmpty: Boollet fileIdentifier: UInt64?var baseEventCount: Int {@@ -1052,13 +955,12 @@ private nonisolated struct HistoryMaintenanceResult {let size: UInt64let corrupt: Intlet fileIdentifier: UInt64?- let boundaryHash: String?}nonisolated struct HistoryDataRebuildSummary: Equatable, Sendable {let rebuiltDateCount: Intlet eventCount: Int- let isSyncReplacementPending: Bool+ let isSyncPending: Boollet failedDateKeys: [String]let failedRequestDateKeys: [String]let failedTokenDateKeys: [String]diff --git a/CodexBar/Services/History/HistoryStorage.swift b/CodexBar/Services/History/HistoryStorage.swiftindex 3ed24c1..cfa2c9f 100644--- a/CodexBar/Services/History/HistoryStorage.swift+++ b/CodexBar/Services/History/HistoryStorage.swift@@ -43,17 +43,27 @@ nonisolated enum HistoryStorage {) throws -> T {// 采集与维护使用独立服务实例, 文件事务必须共享同一把锁let url = lockURL(in: root)- return try JSONFileStorage.withLock(in: url.deletingLastPathComponent(), name: url.lastPathComponent, work)+ let deadline = ContinuousClock.now.advanced(by: .seconds(2))+ while true {+ try Task.checkCancellation()+ if let descriptor = try JSONFileStorage.acquireLock(in: url.deletingLastPathComponent(), name: url.lastPathComponent, nonblocking: true) {+ defer { JSONFileStorage.releaseLock(descriptor) }+ return try work()+ }+ guard ContinuousClock.now < deadline else { throw POSIXError(.ETIMEDOUT) }+ Thread.sleep(forTimeInterval: 0.01)+ }}- static func loadMaintenanceState(in root: URL = directoryURL()) -> HistoryMaintenanceState {+ static func loadMaintenanceState(in root: URL = directoryURL()) throws -> HistoryMaintenanceState {let url = maintenanceURL(in: root)- guard let data = try? Data(contentsOf: url), !data.isEmpty,- let state = try? JSONLines.decoder.decode(HistoryMaintenanceState.self, from: data) else {+ do {+ let data = try Data(contentsOf: url)+ try StorageVersion.validate(data, current: HistoryMaintenanceState.currentVersion, name: "AggregationState")+ return try JSONLines.decoder.decode(HistoryMaintenanceState.self, from: data)+ } catch let error as CocoaError where error.code == .fileReadNoSuchFile {return HistoryMaintenanceState()}-- return state}static func saveMaintenanceState(_ state: HistoryMaintenanceState, in root: URL = directoryURL()) throws {@@ -91,11 +101,16 @@ nonisolated enum HistoryStorage {/// 枚举目录中文件名为合法日期键的 .jsonl 事件日志, 返回升序日期键static func eventLogDateKeys(in directoryURL: URL = eventsDirectoryURL()) -> [String] {- guard let contents = try? FileManager.default.contentsOfDirectory(- at: directoryURL,- includingPropertiesForKeys: nil,- options: [.skipsHiddenFiles]- ) else {+ (try? readEventLogDateKeys(in: directoryURL)) ?? []+ }++ static func readEventLogDateKeys(in directoryURL: URL) throws -> [String] {+ let contents: [URL]+ do {+ contents = try FileManager.default.contentsOfDirectory(+ at: directoryURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]+ )+ } catch CocoaError.fileReadNoSuchFile {return []}diff --git a/CodexBar/Services/History/TokenHistoryStore.swift b/CodexBar/Services/History/TokenHistoryStore.swiftindex 4202a79..94b1fed 100644--- a/CodexBar/Services/History/TokenHistoryStore.swift+++ b/CodexBar/Services/History/TokenHistoryStore.swift@@ -1,13 +1,14 @@import Foundationimport os-/// 仅保存订阅期间取得的轮次累计快照, 不扫描 Codex 会话文件+/// 保存订阅期间的原始 Token 观测, 聚合缓存可独立重建actor TokenHistoryStore {private let directoryURL: URLprivate var recordingLease: Int32?private var journal = AppServerEventJournal()private var journalFiles: [String: TokenJournalCheckpoint] = [:]private var scannedFiles: [String: HistoryFileStat] = [:]+ private var recoveredTurnIDs = Set<String>()init(directoryURL: URL = HistoryStorage.directoryURL()) {self.directoryURL = directoryURL@@ -35,31 +36,10 @@ actor TokenHistoryStore {recordingLease = nil}- func recordObservations(_ observations: [TokenObservation], now: Date = Date()) throws -> [TokenTurn] {+ /// 原始记录不依赖聚合缓存可读, 聚合失败后仍可按日志检查点恢复+ func appendObservation(_ observation: TokenObservation, now: Date = Date()) throws {try HistoryStorage.withExclusiveLock(in: directoryURL) {- var records = try load(now: now)- for observation in observations {- let existing = records[observation.turn.id]- let updated = try observation.applying(to: existing)- // 原始观测先落盘, 快照失败后按同一检查点重放, 重试不会重复累计- try journal.append(AppServerEventRecord(observation: observation, recordedAt: now), in: directoryURL)- records[updated.id] = updated- Self.ensureRoot(for: observation, in: &records)- }- try save(records)- return Array(records.values)- }- }-- private static func ensureRoot(for observation: TokenObservation, in records: inout [String: TokenTurn]) {- let turn = observation.turn- if turn.rootID != turn.id, records[turn.rootID] == nil {- records[turn.rootID] = TokenTurn(- id: turn.rootID,- rootID: turn.rootID,- startedAt: observation.rootStartedAt,- updatedAt: turn.updatedAt- )+ try journal.append(AppServerEventRecord(observation: observation, recordedAt: now), in: directoryURL)}}@@ -69,12 +49,15 @@ actor TokenHistoryStore {var replacements: [TokenTurn] = []if let baseline {for (id, turn) in records {- if let replacement = baseline.replacement(for: turn) {+ if let replacement = baseline.replacement(for: turn, recovering: recoveredTurnIDs.contains(id), now: now) {records[id] = replacementif replacement != turn {replacements.append(replacement)}}+ if baseline.contains(turn), baseline.acceptsRecovery(turn) {+ recoveredTurnIDs.remove(id)+ }}}let roots = Set(replacements.map(\.rootID))@@ -89,6 +72,16 @@ actor TokenHistoryStore {try HistoryStorage.withExclusiveLock(in: directoryURL) { try Array(load(now: now).values) }}+ func pendingRecoveryIDs() -> Set<String> {+ recoveredTurnIDs+ }++ func persistedTurns(now: Date = Date()) throws -> [TokenTurn] {+ try HistoryStorage.withExclusiveLock(in: directoryURL) {+ try Array(retained(readCache()?.turns ?? [:], now: now).values)+ }+ }+func rebuildableDateKeys(now: Date = Date()) throws -> [String] {try Array(TokenTurn.dailyUsage(currentTurns(now: now), now: now).keys).sorted()}@@ -136,14 +129,14 @@ actor TokenHistoryStore {}private func saveObservedTurns(_ records: [TokenTurn], now: Date) throws {- for record in TokenTurn.merged(records).values.sorted(by: { $0.id < $1.id }) {+ for record in try TokenTurn.merged(records).values.sorted(by: { $0.id < $1.id }) {try journal.append(AppServerEventRecord(token: record, recordedAt: now), in: directoryURL)}}private func journalTurns(now: Date, baseline: [String: TokenTurn]) throws -> TokenJournalReplay {var replay = try TokenJournalReplay(baseline: baseline, replayingFromEmpty: true)- for date in journalDates(now: now) {+ for date in try journalDates(now: now) {let url = HistoryStorage.eventLogURL(for: date, in: HistoryStorage.eventsDirectoryURL(in: directoryURL))var invalid = falsetry AppServerEventJournal.read(at: url, onInvalidLine: { invalid = true }, consume: { entry in@@ -156,10 +149,10 @@ actor TokenHistoryStore {return replay}- private func journalDates(now: Date) -> [String] {+ private func journalDates(now: Date) throws -> [String] {let directory = HistoryStorage.eventsDirectoryURL(in: directoryURL)let cutoff = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate(today: now))- return HistoryStorage.eventLogDateKeys(in: directory).filter { $0 >= cutoff }+ return try HistoryStorage.readEventLogDateKeys(in: directory).filter { $0 >= cutoff }}private var ledgerURL: URL {@@ -180,26 +173,31 @@ actor TokenHistoryStore {} catch is DecodingError {AppLog.history.error("Token 缓存损坏, 从原始事件恢复")cache = nil+ } catch StorageCompatibilityError.incompleteSource {+ AppLog.history.error("Token 缓存检查点损坏, 从原始事件恢复")+ cache = nil}return cache}private func load(now: Date) throws -> [String: TokenTurn] {let cache = try readCache()+ recoveredTurnIDs = Set(cache?.recoveredTurnIDs ?? [])if cache == nil {journalFiles.removeAll()scannedFiles.removeAll()}- let baseline = cache?.turns ?? [:]+ var baseline = cache?.turns ?? [:]var replay = try TokenJournalReplay(baseline: baseline)journalFiles = cache?.files ?? [:]let directory = HistoryStorage.eventsDirectoryURL(in: directoryURL)- let dates = journalDates(now: now)+ let dates = try journalDates(now: now)let previousFiles = journalFilesvar rootsByFile: [String: Set<String>] = [:]journalFiles = journalFiles.filter { dates.contains($0.key) }scannedFiles = scannedFiles.filter { dates.contains($0.key) }for date in dates {+ try Task.checkCancellation()let url = HistoryStorage.eventLogURL(for: date, in: directory)guard let stat = HistoryStorage.fileStat(at: url) else { throw TokenCacheError.incompleteJournal }let previous = journalFiles[date]@@ -213,7 +211,7 @@ actor TokenHistoryStore {if let root = entry.observation?.turn.rootID ?? entry.token?.rootID {rootsByFile[date, default: []].insert(root)}- try replay.consume(entry, includesSnapshots: true)+ try replay.consume(entry, includesSnapshots: true, rebuildingCache: cache == nil)})if invalid {guard cache != nil else { throw TokenCacheError.incompleteJournal }@@ -224,6 +222,13 @@ actor TokenHistoryStore {journalFiles[date] = TokenJournalCheckpoint(size: stat.size, identifier: stat.identifier, modificationTime: stat.modificationTime)scannedFiles[date] = stat}+ if cache == nil {+ let replacements = replay.recoverSnapshots(now: now)+ // 原始观测不足时只沿用可信旧快照, 不把它标记为重算结果+ let conflictedRoots = Set(replay.snapshots.values.filter(\.hasConflict).map(\.rootID))+ baseline = replay.snapshots.filter { !conflictedRoots.contains($0.value.rootID) }+ try saveObservedTurns(replacements, now: now)+ }// 回滚失败根轮次在本轮的所有改动, 涉及的文件保留原游标以便下次重试for (date, roots) in rootsByFile where !roots.isDisjoint(with: replay.failedRoots) {journalFiles[date] = previousFiles[date]@@ -233,12 +238,15 @@ actor TokenHistoryStore {for (id, turn) in baseline where replay.failedRoots.contains(turn.rootID) {records[id] = turn}+ if cache == nil {+ recoveredTurnIDs.formUnion(replay.records.values.filter { !replay.failedRoots.contains($0.rootID) }.map(\.id))+ }return retained(records, now: now)}private func save(_ records: [String: TokenTurn]) throws {// 日志与缓存共用时间编码, 避免 epoch 换算精度差异影响重建标记比较- let data = try AppServerEventRecord.encode(TokenAggregateCache(turns: records, files: journalFiles))+ let data = try AppServerEventRecord.encode(TokenAggregateCache(turns: records, files: journalFiles, recoveredTurnIDs: recoveredTurnIDs.intersection(records.keys).sorted()))guard (try? Data(contentsOf: ledgerURL)) != data else { return }try FileManager.default.createDirectory(at: ledgerURL.deletingLastPathComponent(), withIntermediateDirectories: true)try data.write(to: ledgerURL, options: .atomic)@@ -257,6 +265,7 @@ private nonisolated struct TokenJournalReplay {var failedRoots = Set<String>()private var rootByTurn: [String: String] = [:]private var startsByRoot: [String: Date] = [:]+ var snapshots: [String: TokenTurn] = [:]init(baseline: [String: TokenTurn], replayingFromEmpty: Bool = false) throws {records = replayingFromEmpty ? [:] : baseline@@ -265,10 +274,10 @@ private nonisolated struct TokenJournalReplay {}}- mutating func consume(_ entry: AppServerEventRecord, includesSnapshots: Bool) throws {+ mutating func consume(_ entry: AppServerEventRecord, includesSnapshots: Bool, rebuildingCache: Bool = false) throws {if let observation = entry.observation {let turn = observation.turn- try register(turn, rootStartedAt: observation.rootStartedAt)+ try register(turn.emptyTurn, rootStartedAt: observation.rootStartedAt)guard !failedRoots.contains(turn.rootID) else { return }do {records[turn.id] = try observation.applying(to: records[turn.id])@@ -286,10 +295,46 @@ private nonisolated struct TokenJournalReplay {}} else if let turn = entry.token {try register(turn, rootStartedAt: nil)- if includesSnapshots, !failedRoots.contains(turn.rootID) {- records[turn.id] = records[turn.id]?.merging(turn) ?? turn+ if rebuildingCache {+ snapshots[turn.id] = try snapshots[turn.id]?.merging(turn) ?? turn+ } else if includesSnapshots, !failedRoots.contains(turn.rootID) {+ records[turn.id] = try records[turn.id]?.merging(turn) ?? turn+ }+ }+ }++ /// 重算值只来自原始观测, 快照用于校验覆盖范围与继承替换关系+ mutating func recoverSnapshots(now: Date) -> [TokenTurn] {+ var replacements: [TokenTurn] = []+ for (root, previousTurns) in Dictionary(grouping: snapshots.values, by: \.rootID) {+ let coversPrevious = previousTurns.allSatisfy { previous in+ guard let candidate = records[previous.id] else { return false }+ return candidate.covers(previous.checkpoint)+ && (previous.usage == nil || candidate.usage != nil)+ }+ guard !failedRoots.contains(root), coversPrevious else {+ failedRoots.insert(root)+ continue+ }+ // 主轮次与子 Agent 全部通过检查后再生成替换, 不提交半个任务+ for previous in previousTurns {+ guard var candidate = records[previous.id] else { continue }+ candidate.startedAt = candidate.startedAt ?? previous.startedAt+ candidate.updatedAt = max(candidate.updatedAt, previous.updatedAt)+ candidate.generationID = previous.generationID+ candidate.ancestorIDs = previous.ancestorIDs+ candidate.rebuiltAt = previous.rebuiltAt+ if previous.hasConflict || candidate.usage != previous.usage+ || candidate.aggregationVersion != previous.aggregationVersion || candidate.checkpoint != previous.checkpoint {+ candidate.startNewGeneration(at: now)+ }+ records[candidate.id] = candidate+ if candidate != previous {+ replacements.append(candidate)+ }}}+ return replacements}func selectedRoots(in dates: Set<String>) throws -> [String: String] {@@ -325,6 +370,7 @@ private nonisolated struct TokenAggregateCache: Codable {var version = Self.currentVersionvar turns: [String: TokenTurn]var files: [String: TokenJournalCheckpoint]+ var recoveredTurnIDs: [String]?}private nonisolated struct TokenJournalCheckpoint: Codable {@@ -381,4 +427,4 @@ nonisolated struct TokenFileCache<Value: Codable & Equatable> {}}-nonisolated enum TokenCacheError: Error { case unsupportedVersion(Int), incompleteJournal }+nonisolated enum TokenCacheError: Error { case unsupportedVersion(Int), incompleteJournal, rootIdentityConflict }diff --git a/CodexBar/Services/KeepAlive/HelperConfiguration.swift b/CodexBar/Services/KeepAlive/HelperConfiguration.swiftindex 306325c..1765226 100644--- a/CodexBar/Services/KeepAlive/HelperConfiguration.swift+++ b/CodexBar/Services/KeepAlive/HelperConfiguration.swift@@ -48,33 +48,28 @@ enum HelperConfiguration {.seconds(1)]- static var service: SMAppService {- SMAppService.daemon(plistName: CodexBarHelperIPC.daemonPlistName)- }-- static var assetsArePresent: Bool {- FileManager.default.fileExists(atPath: daemonPlistURL.path)- && FileManager.default.isExecutableFile(atPath: helperExecutableURL.path)- }-nonisolated static func validatePackage(appURL: URL, machServiceName: String) -> HelperPackageIssue? {- let helperURL = appURL.appending(path: "Contents/Resources/CodexBarHelper")- let plistURL = appURL.appending(path: "Contents/Library/LaunchDaemons/\(machServiceName).plist")+ let managerURL = HelperManagement.bundleURL(in: appURL)+ let helperURL = managerURL.appending(path: "Contents/Resources/CodexBarHelper")+ let plistURL = managerURL.appending(path: "Contents/Library/LaunchDaemons/\(machServiceName).plist")let fileManager = FileManager.defaultguard fileManager.fileExists(atPath: plistURL.path),fileManager.isExecutableFile(atPath: helperURL.path) else {return .missing}- guard let appIdentifier = Bundle(url: appURL)?.bundleIdentifier,+ guard let manager = Bundle(url: managerURL),+ manager.bundleIdentifier == HelperManagement.bundleIdentifier,+ manager.executableURL.map({ fileManager.isExecutableFile(atPath: $0.path) }) == true,let plistData = try? Data(contentsOf: plistURL),let plist = try? PropertyListSerialization.propertyList(from: plistData, format: nil) as? [String: Any],plist["Label"] as? String == machServiceName,plist["BundleProgram"] as? String == "Contents/Resources/CodexBarHelper",- (plist["AssociatedBundleIdentifiers"] as? [String])?.contains(appIdentifier) == true,+ plist["AssociatedBundleIdentifiers"] as? [String] == [HelperManagement.bundleIdentifier],(plist["MachServices"] as? [String: Any])?[machServiceName] as? Bool == true else {return .invalid}- guard helperSignatureIsValid(helperURL: helperURL, appURL: appURL, machServiceName: machServiceName) else {+ guard helperSignatureIsValid(helperURL: managerURL, appURL: appURL, machServiceName: HelperManagement.bundleIdentifier),+ helperSignatureIsValid(helperURL: helperURL, appURL: appURL, machServiceName: machServiceName) else {return .invalid}return nil@@ -112,20 +107,15 @@ enum HelperConfiguration {return SecStaticCodeCheckValidity(helperCode, flags, requirement) == errSecSuccess}- static func registrationNeedsRefresh(defaults: UserDefaults) -> Bool {- guard let fingerprint else {- return false- }- return defaults.string(forKey: registrationFingerprintKey) != fingerprint+ static func registrationNeedsRefresh(defaults: UserDefaults, fingerprint: String) -> Bool {+ defaults.string(forKey: registrationFingerprintKey) != fingerprint}static func beginUpdate(defaults: UserDefaults,- requiresSleepReset: Bool- ) -> String? {- guard let fingerprint else {- return nil- }+ requiresSleepReset: Bool,+ fingerprint: String+ ) -> String {// 待完成重置是跨 Helper 版本的欠账, 后续更新只能转交给新指纹, 不能清除let hasPendingSleepReset = defaults.string(forKey: pendingUpdateIdentifierKey) != nilif requiresSleepReset || hasPendingSleepReset {@@ -136,9 +126,8 @@ enum HelperConfiguration {return fingerprint}- static func pendingUpdateIdentifier(defaults: UserDefaults) -> String? {- guard let fingerprint,- defaults.string(forKey: registrationFingerprintKey) == fingerprint,+ static func pendingUpdateIdentifier(defaults: UserDefaults, fingerprint: String) -> String? {+ guard defaults.string(forKey: registrationFingerprintKey) == fingerprint,defaults.string(forKey: pendingUpdateIdentifierKey) == fingerprint else {return nil}@@ -157,9 +146,10 @@ enum HelperConfiguration {static func recordRegistration(defaults: UserDefaults,- status: KeepAliveController.HelperStatus+ status: KeepAliveController.HelperStatus,+ fingerprint: String) {- guard status.isRegisteredOrAwaitingApproval, let fingerprint else {+ guard status.isRegisteredOrAwaitingApproval else {return}defaults.set(fingerprint, forKey: registrationFingerprintKey)@@ -171,19 +161,15 @@ enum HelperConfiguration {&& error.code == operationNotPermittedErrorCode}- static func registerRefreshedHelper(_ service: SMAppService) async throws {+ static func registerRefreshedHelper(_ service: HelperManagerClient) async throws {await Task.yield()var retryDelays = registrationRetryDelays.makeIterator()while true {do {- try service.register()+ _ = try await service.perform(.register)return} catch {- let status = KeepAliveController.HelperStatus(service.status)- if status.isRegisteredOrAwaitingApproval {- return- }guard isTransientRegistrationError(error),let retryDelay = retryDelays.next() else {throw error@@ -197,74 +183,80 @@ enum HelperConfiguration {private static let pendingUpdateIdentifierKey = "KeepAlive.pendingHelperUpdateIdentifier"private static let operationNotPermittedErrorCode = 1- private static var fingerprint: String? {- guard let helperData = try? Data(contentsOf: helperExecutableURL, options: .mappedIfSafe),+ nonisolated static func inspectPackage(appURL: URL, machServiceName: String) -> HelperPackageSnapshot {+ if let issue = validatePackage(appURL: appURL, machServiceName: machServiceName) {+ return HelperPackageSnapshot(issue: issue, fingerprint: nil)+ }+ let managerURL = HelperManagement.bundleURL(in: appURL)+ let managerExecutableURL = managerURL.appending(path: "Contents/MacOS/\(HelperManagement.executableName)")+ let helperExecutableURL = managerURL.appending(path: "Contents/Resources/CodexBarHelper")+ let daemonPlistURL = managerURL.appending(path: "Contents/Library/LaunchDaemons/\(machServiceName).plist")+ guard let managerData = try? Data(contentsOf: managerExecutableURL, options: .mappedIfSafe),+ let managerInfo = try? Data(contentsOf: managerURL.appending(path: "Contents/Info.plist")),+ let managerSeal = try? Data(contentsOf: managerURL.appending(path: "Contents/_CodeSignature/CodeResources")),+ let helperData = try? Data(contentsOf: helperExecutableURL, options: .mappedIfSafe),let daemonPlistData = try? Data(contentsOf: daemonPlistURL, options: .mappedIfSafe) else {- return nil+ return HelperPackageSnapshot(issue: .invalid, fingerprint: nil)}var hasher = SHA256()for (name, data) in [+ (managerExecutableURL.lastPathComponent, managerData),+ ("Info.plist", managerInfo),+ ("CodeResources", managerSeal),(helperExecutableURL.lastPathComponent, helperData),(daemonPlistURL.lastPathComponent, daemonPlistData)] {hasher.update(data: Data("\(name)\n\(data.count)\n".utf8))hasher.update(data: data)}- return hasher.finalize().map { String(format: "%02x", $0) }.joined()- }-- private static var appContentsURL: URL {- Bundle.main.bundleURL.appending(path: "Contents", directoryHint: .isDirectory)- }-- private static var helperExecutableURL: URL {- appContentsURL- .appending(path: "Resources", directoryHint: .isDirectory)- .appending(path: "CodexBarHelper")+ return HelperPackageSnapshot(issue: nil, fingerprint: hasher.finalize().map { String(format: "%02x", $0) }.joined())}+}- private static var daemonPlistURL: URL {- appContentsURL- .appending(path: "Library/LaunchDaemons", directoryHint: .isDirectory)- .appending(path: CodexBarHelperIPC.daemonPlistName)- }+nonisolated struct HelperPackageSnapshot {+ let issue: HelperPackageIssue?+ let fingerprint: String?}@MainActorfinal class HelperPackageValidation: ObservableObject {- /// 包校验与安装前检查共用组件异常, 不写入注册操作错误+ /// 同一轮校验提供注册与就绪判断共用的指纹, 不在主 actor 读取包文件@Published private(set) var issue: HelperPackageIssue?+ private(set) var fingerprint: String?+ var onValidated: (() -> Void)?+ private let inspect: @Sendable () async -> HelperPackageSnapshotprivate var task: Task<Void, Never>?- func refresh() {- guard task == nil else { return }+ init(inspect: @escaping @Sendable () async -> HelperPackageSnapshot = {let appURL = Bundle.main.bundleURLlet machServiceName = CodexBarHelperIPC.machServiceName+ return await Task.detached(priority: .utility) {+ HelperConfiguration.inspectPackage(appURL: appURL, machServiceName: machServiceName)+ }.value+ }) {+ self.inspect = inspect+ }++ func refresh() {+ guard task == nil else { return }+ fingerprint = nil+ let inspect = inspecttask = Task { [weak self] in- let worker = Task.detached(priority: .utility) {- HelperConfiguration.validatePackage(appURL: appURL, machServiceName: machServiceName)- }- let result = await worker.value+ let result = await inspect()guard let self, !Task.isCancelled else { return }task = nil- if issue != result {- issue = result+ fingerprint = result.issue == nil ? result.fingerprint : nil+ if issue != result.issue {+ issue = result.issue}+ onValidated?()}}- func reportMissingAssets() {- // 丢弃先前校验结果, 避免旧的正常结果覆盖刚确认的缺失- cancel()- if issue != .missing {- issue = .missing- }- refresh()- }-func cancel() {task?.cancel()task = nil+ fingerprint = nil}}diff --git a/CodexBar/Services/KeepAlive/HelperManagerClient.swift b/CodexBar/Services/KeepAlive/HelperManagerClient.swiftnew file mode 100644index 0000000..a6fb7bd--- /dev/null+++ b/CodexBar/Services/KeepAlive/HelperManagerClient.swift@@ -0,0 +1,101 @@+import Foundation+import ServiceManagement++/// 管理进程只在查询或变更注册时启动, 输出与执行时间由共用进程内核约束+actor HelperManagerClient {+ private let executeCommand: @Sendable (HelperManagement.Command) async throws -> SMAppService.Status+ private let retryDelay: Duration+ private var pending: Task<SMAppService.Status, Error>?+ private var generation: UInt64 = 0++ init(+ appURL: URL = Bundle.main.bundleURL,+ retryDelay: Duration = .seconds(1),+ executeCommand: (@Sendable (HelperManagement.Command) async throws -> SMAppService.Status)? = nil+ ) {+ self.executeCommand = executeCommand ?? { command in+ try await Self.execute(command, appURL: appURL)+ }+ self.retryDelay = retryDelay+ }++ func perform(_ command: HelperManagement.Command) async throws -> SMAppService.Status {+ let previous = pending+ let executeCommand = executeCommand+ let retryDelay = retryDelay+ generation &+= 1+ let requestGeneration = generation+ let task = Task {+ _ = try? await previous?.value+ // 只重试只读查询, 避免重复注册或注销改变系统状态+ var retriesRemaining = command == .status ? 2 : 0+ while true {+ try Task.checkCancellation()+ do {+ let status = try await executeCommand(command)+ try Task.checkCancellation()+ return status+ } catch is CancellationError {+ throw CancellationError()+ } catch {+ try Task.checkCancellation()+ guard retriesRemaining > 0 else { throw error }+ retriesRemaining -= 1+ try await Task.sleep(for: retryDelay)+ }+ }+ }+ pending = task+ defer {+ if generation == requestGeneration {+ pending = nil+ }+ }+ return try await withTaskCancellationHandler {+ try await task.value+ } onCancel: {+ task.cancel()+ }+ }++ private nonisolated static func execute(_ command: HelperManagement.Command, appURL: URL) async throws -> SMAppService.Status {+ let executable = HelperManagement.bundleURL(in: appURL)+ .appending(path: "Contents/MacOS/\(HelperManagement.executableName)")+ let result = await BoundedProcess.runAsync(+ executable: executable,+ arguments: [command.rawValue],+ timeout: 10,+ configuration: .init(outputMode: .separate)+ )+ try Task.checkCancellation()+ guard result.exitCode == 0, !result.standardOutput.isTruncated else {+ throw ClientError.executionFailed+ }+ return try Self.status(from: result.standardOutput.data, command: command)+ }++ nonisolated static func status(from data: Data, command: HelperManagement.Command) throws -> SMAppService.Status {+ let reply = try JSONDecoder().decode(HelperManagement.Reply.self, from: data)+ guard let status = SMAppService.Status(rawValue: reply.status) else {+ throw ClientError.invalidStatus+ }+ switch status {+ case .notRegistered, .enabled, .requiresApproval, .notFound:+ break+ @unknown default:+ throw ClientError.invalidStatus+ }+ // 首次注册等待系统批准时可能返回 EPERM, 状态已经登记才接受该结果+ if let domain = reply.errorDomain, let code = reply.errorCode {+ if command != .register || (status != .enabled && status != .requiresApproval) {+ throw NSError(domain: domain, code: code)+ }+ }+ return status+ }++ enum ClientError: Error {+ case executionFailed+ case invalidStatus+ }+}diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swiftindex fea474f..88ddb31 100644--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift@@ -109,6 +109,10 @@ final class KeepAliveController: ObservableObject {private var retryTask: Task<Void, Never>?private var requestTimeoutTask: Task<Void, Never>?private let helperStatusMonitor = HelperStatusMonitor()+ private let helperManager = HelperManagerClient()+ private var isHelperStatusAvailable = false+ private var helperFailureTask: Task<Void, Never>?+ private var helperLifecycleGeneration: UInt64 = 0private var retryAttempt = 0private var helperRegistrationTask: Task<Void, Never>?private let helperPackageValidation = HelperPackageValidation()@@ -148,6 +152,10 @@ final class KeepAliveController: ObservableObject {// 默认关闭: 它会让人离开后机器一直停在解锁状态, 这个取舍只能由用户自己做keepsDisplayAwake = defaults.bool(forKey: Self.keepsDisplayAwakeKey)activityMonitor.setProtectionEnabled(isEnabled)+ helperPackageValidation.onValidated = { [weak self] in+ guard let self, isStarted else { return }+ refreshRegistrationAndSleepState(refreshPackage: false)+ }autoResetWakeScheduler.onErrorMessageChanged = { [weak self] message inself?.autoResetWakeScheduleErrorMessage = message}@@ -251,23 +259,17 @@ final class KeepAliveController: ObservableObject {refreshRegistrationAndSleepState()}- private func refreshRegistrationAndSleepState() {- if isStarted {+ private func refreshRegistrationAndSleepState(refreshPackage: Bool = true) {+ if isStarted, refreshPackage {helperPackageValidation.refresh()+ return}guard helperRegistrationTask == nil else {reconcileSleepState(trigger: .statusRefresh)return}- refreshHelperStatus()- if isEnabled- || isAutoResetRequested- || helperStatus.isRegisteredOrAwaitingApproval {- ensureHelperRegistration()- }- reconcileSleepState(trigger: .statusRefresh)- reconcileAutoResetWakeSchedule()+ ensureHelperRegistration()}// MARK: - 设置入口@@ -475,8 +477,8 @@ final class KeepAliveController: ObservableObject {}private func handleActivitySnapshot(_ snapshot: ActivitySnapshot) {- let currentRunningTaskIDs = keepAliveTaskIDs(in: snapshot.runningTasks)- let currentWaitingTaskIDs = keepAliveTaskIDs(in: snapshot.waitingTasks)+ let currentRunningTaskIDs = Set(snapshot.runningTasks.map(\.id))+ let currentWaitingTaskIDs = Set(snapshot.waitingTasks.map(\.id))// 运行与等待互斥, 新任务和等待后恢复都表现为运行集合新增成员let hasEnteredRunning = !currentRunningTaskIDs.isSubset(of: runningTaskIDs)runningTaskIDs = currentRunningTaskIDs@@ -490,10 +492,6 @@ final class KeepAliveController: ObservableObject {reconcileSleepState(trigger: .taskChanged)}- private func keepAliveTaskIDs(in tasks: [ActivityTaskSnapshot]) -> Set<UUID> {- Set(tasks.lazy.filter { !$0.isAnonymous }.map(\.id))- }-/// 还没真正挡住睡眠时只清零不起表, 等禁用成功后由 begin 补上private func restartMaximumDurationPeriod() {guard isEnabled else {@@ -505,78 +503,71 @@ final class KeepAliveController: ObservableObject {// MARK: - helper 注册- func openSystemSettings() {- SMAppService.openSystemSettingsLoginItems()- }-private func ensureHelperRegistration() {- guard helperRegistrationTask == nil else {- return- }-- let service = HelperConfiguration.service- refreshHelperStatus()-- switch helperStatus {- case .enabled, .requiresApproval:- if HelperConfiguration.registrationNeedsRefresh(defaults: defaults) {- refreshRegisteredHelper()- } else if helperStatus == .enabled,- let updateIdentifier = HelperConfiguration.pendingUpdateIdentifier(- defaults: defaults- ) {- completePendingHelperUpdate(updateIdentifier)- } else {- reconcileAutoResetWakeSchedule()+ guard helperRegistrationTask == nil else { return }+ guard let fingerprint = helperPackageValidation.fingerprint else {+ if helperPackageValidation.issue == nil {+ helperPackageValidation.refresh()}return- case .notRegistered, .notFound:- guard HelperConfiguration.assetsArePresent else {- helperPackageValidation.reportMissingAssets()- return- }}-- AppLog.keepAlive.notice("Helper 注册开始")- do {- try service.register()- } catch {- refreshHelperStatus()- if !helperStatus.isRegisteredOrAwaitingApproval {- AppLog.keepAlive.error(- "Helper 注册失败: detail=\(error.localizedDescription, privacy: .public)"- )- registrationErrorMessage = KeepAliveLocalizedMessage.registrationFailed+ let lifecycleGeneration = helperLifecycleGeneration+ helperRegistrationTask = Task { @MainActor [weak self] in+ guard let self else { return }+ defer {+ if lifecycleGeneration == helperLifecycleGeneration {+ helperRegistrationTask = nil+ }}+ guard await refreshHelperStatus(), isStarted, !Task.isCancelled else { return }+ switch helperStatus {+ case .enabled, .requiresApproval:+ if HelperConfiguration.registrationNeedsRefresh(defaults: defaults, fingerprint: fingerprint) {+ await refreshRegisteredHelper()+ } else if helperStatus == .enabled,+ let updateIdentifier = HelperConfiguration.pendingUpdateIdentifier(+ defaults: defaults, fingerprint: fingerprint+ ) {+ await completePendingHelperUpdate(updateIdentifier)+ }+ case .notRegistered, .notFound:+ if isEnabled || isAutoResetRequested {+ AppLog.keepAlive.notice("Helper 注册开始")+ do {+ _ = try await helperManager.perform(.register)+ } catch is CancellationError {+ return+ } catch {+ AppLog.keepAlive.error("Helper 注册失败: detail=\(error.localizedDescription, privacy: .public)")+ registrationErrorMessage = KeepAliveLocalizedMessage.registrationFailed+ }+ guard await refreshHelperStatus(), !Task.isCancelled else { return }+ HelperConfiguration.recordRegistration(defaults: defaults, status: helperStatus, fingerprint: fingerprint)+ if helperStatus == .enabled,+ let updateIdentifier = HelperConfiguration.pendingUpdateIdentifier(defaults: defaults, fingerprint: fingerprint) {+ await completePendingHelperUpdate(updateIdentifier)+ }+ }+ }+ guard isStarted, !Task.isCancelled else { return }+ reconcileSleepState(trigger: .statusRefresh)+ reconcileAutoResetWakeSchedule()}-- refreshHelperStatus()- HelperConfiguration.recordRegistration(defaults: defaults, status: helperStatus)- if helperStatus == .enabled,- let updateIdentifier = HelperConfiguration.pendingUpdateIdentifier(- defaults: defaults- ) {- completePendingHelperUpdate(updateIdentifier)- }- reconcileAutoResetWakeSchedule()}- private func refreshRegisteredHelper() {+ private func refreshRegisteredHelper() async {let requiresSleepReset = helperStatus == .enabled- guard helperRegistrationTask == nil,- HelperConfiguration.assetsArePresent else {+ guard let fingerprint = helperPackageValidation.fingerprint else {return}guard autoResetWakeScheduler.beginHelperInterruptionPreparation() else {return}- guard let updateIdentifier = HelperConfiguration.beginUpdate(+ let updateIdentifier = HelperConfiguration.beginUpdate(defaults: defaults,- requiresSleepReset: requiresSleepReset- ) else {- autoResetWakeScheduler.resumeAfterHelperInterruption()- return- }+ requiresSleepReset: requiresSleepReset,+ fingerprint: fingerprint+ )assign(true, to: \.isRefreshingHelper)cancelRetryTask()@@ -586,17 +577,13 @@ final class KeepAliveController: ObservableObject {registrationErrorMessage = niloperationErrorMessage = nil- let service = HelperConfiguration.service- helperRegistrationTask = Task { @MainActor [weak self] in- guard let self else {- return- }+ do {defer {autoResetWakeScheduler.resumeAfterHelperInterruption()}let updateError: Error?do {- try await replaceRegisteredHelper(service)+ try await replaceRegisteredHelper()updateError = nil} catch is CancellationError {return@@ -609,13 +596,14 @@ final class KeepAliveController: ObservableObject {return}- refreshHelperStatus()+ guard await refreshHelperStatus() else { return }var helperWasUpdated = falseif updateError == nil,helperStatus.isRegisteredOrAwaitingApproval {HelperConfiguration.recordRegistration(defaults: defaults,- status: helperStatus+ status: helperStatus,+ fingerprint: fingerprint)if !requiresSleepReset {helperWasUpdated = true@@ -636,7 +624,6 @@ final class KeepAliveController: ObservableObject {}assign(!helperWasUpdated && helperStatus == .enabled, to: \.isRefreshingHelper)- helperRegistrationTask = nilreconcileSleepState(trigger: .helperRegistered, force: true)reconcileAutoResetWakeSchedule()}@@ -656,9 +643,27 @@ final class KeepAliveController: ObservableObject {self[keyPath: keyPath] = value}- private func refreshHelperStatus() {+ @discardableResult+ private func refreshHelperStatus() async -> Bool {+ let status: SMAppService.Status+ do {+ status = try await helperManager.perform(.status)+ try Task.checkCancellation()+ } catch is CancellationError {+ return false+ } catch {+ AppLog.keepAlive.error("Helper 注册状态查询失败: detail=\(error.localizedDescription, privacy: .public)")+ registrationErrorMessage = KeepAliveLocalizedMessage.connectionFailed+ isHelperStatusAvailable = false+ cancelRetryTask()+ invalidateConnection()+ reconcileSleepState(trigger: .statusRefresh)+ reconcileAutoResetWakeSchedule()+ return false+ }+ isHelperStatusAvailable = truelet previousStatus = helperStatus- assign(HelperStatus(HelperConfiguration.service.status), to: \.helperStatus)+ assign(HelperStatus(status), to: \.helperStatus)// 每次 App 激活都会跑, 只记真正的迁移, 否则日志会被无变化的求值淹没// 取局部量再插值: Logger 的插值是 autoclosure, 直接写属性会被要求显式 self, 与 --self remove 冲突let currentStatus = helperStatus@@ -684,6 +689,7 @@ final class KeepAliveController: ObservableObject {publishDerivedState(blockReason: sleepBlockReason)reconcileAutoResetWakeSchedule()}+ return true}// MARK: - 决策与条件日志@@ -1156,15 +1162,23 @@ final class KeepAliveController: ObservableObject {/// 断连和超时统一先复核授权, retrying 为 nil 时只收敛状态, 不重试租约private func handleHelperFailure(_ message: String?, retrying requested: Bool?) {invalidateConnection()- refreshHelperStatus()- guard helperStatus == .enabled else {- return- }- if let message {- operationErrorMessage = message- }- if let requested {- scheduleRetryIfNeeded(for: requested)+ guard helperFailureTask == nil else { return }+ let lifecycleGeneration = helperLifecycleGeneration+ helperFailureTask = Task { @MainActor [weak self] in+ guard let self else { return }+ defer {+ if lifecycleGeneration == helperLifecycleGeneration {+ helperFailureTask = nil+ }+ }+ guard await refreshHelperStatus(), isStarted, !Task.isCancelled,+ helperStatus == .enabled else { return }+ if let message {+ operationErrorMessage = message+ }+ if let requested {+ scheduleRetryIfNeeded(for: requested)+ }}}@@ -1294,8 +1308,10 @@ final class KeepAliveController: ObservableObject {/// 让一个附加效果的失败显示成防睡眠本身出错private func reconcileDisplayAwake() {let shouldKeepAwake = keepsDisplayAwake && isActivelyPreventingSleep- guard shouldKeepAwake != systemSleepService.isPreventingDisplaySleep else {- return+ if shouldKeepAwake {+ guard !systemSleepService.isPreventingDisplaySleep else { return }+ } else {+ guard systemSleepService.hasDisplaySleepResources else { return }}guard shouldKeepAwake else {@@ -1326,6 +1342,9 @@ final class KeepAliveController: ObservableObject {}private func cancelHelperRegistrationTask() {+ helperLifecycleGeneration &+= 1+ helperFailureTask?.cancel()+ helperFailureTask = nilhelperRegistrationTask?.cancel()helperRegistrationTask = nilassign(false, to: \.isRefreshingHelper)@@ -1334,7 +1353,6 @@ final class KeepAliveController: ObservableObject {}private func scheduleRetryIfNeeded(for requested: Bool) {- refreshHelperStatus()guard isStarted,helperStatus == .enabled,requested == shouldDisableSleep,@@ -1368,11 +1386,10 @@ final class KeepAliveController: ObservableObject {guard !Task.isCancelled, let self else {return}- retryTask = nil- refreshHelperStatus()- guard helperStatus == .enabled else {+ guard await refreshHelperStatus(), isStarted, !Task.isCancelled, helperStatus == .enabled else {return}+ retryTask = nilguard requested == shouldDisableSleep else {reconcileSleepState(trigger: .retry)return@@ -1408,7 +1425,7 @@ final class KeepAliveController: ObservableObject {return .userOff}// 先检查依赖, 避免任务恢复前以 noTasks 提前放出未授权 Helper 的设置入口- if helperStatus != .enabled {+ if !isHelperStatusAvailable || helperStatus != .enabled {return .helperUnavailable}if !hasKeepAliveTasks {@@ -1437,17 +1454,17 @@ final class KeepAliveController: ObservableObject {}extension KeepAliveController {- private func replaceRegisteredHelper(_ service: SMAppService) async throws {+ private func replaceRegisteredHelper() async throws {try Task.checkCancellation()guard await autoResetWakeScheduler.cancelBeforeHelperInterruption() else {throw KeepAliveError.wakeScheduleCancellationFailed}reconcileAutoResetWakeSchedule()try Task.checkCancellation()- try await service.unregister()+ _ = try await helperManager.perform(.unregister)mayHaveHelperLease = falsetry Task.checkCancellation()- try await HelperConfiguration.registerRefreshedHelper(service)+ try await HelperConfiguration.registerRefreshedHelper(helperManager)}func setAutoResetRequested(_ requested: Bool) {@@ -1471,12 +1488,13 @@ extension KeepAliveController {}private var isHelperReadyForAutoResetWake: Bool {- guard helperStatus == .enabled,+ guard isHelperStatusAvailable, helperStatus == .enabled,!isRefreshingHelper,- !HelperConfiguration.registrationNeedsRefresh(defaults: defaults) else {+ let fingerprint = helperPackageValidation.fingerprint,+ !HelperConfiguration.registrationNeedsRefresh(defaults: defaults, fingerprint: fingerprint) else {return false}- return HelperConfiguration.pendingUpdateIdentifier(defaults: defaults) == nil+ return HelperConfiguration.pendingUpdateIdentifier(defaults: defaults, fingerprint: fingerprint) == nil}private func reconcileAutoResetWakeSchedule() {@@ -1487,36 +1505,21 @@ extension KeepAliveController {}private extension KeepAliveController {- func completePendingHelperUpdate(_ updateIdentifier: String) {- guard helperRegistrationTask == nil else {- return- }-+ func completePendingHelperUpdate(_ updateIdentifier: String) async {assign(true, to: \.isRefreshingHelper)reconcileAutoResetWakeSchedule()cancelRetryTask()cancelExternalObservation()registrationErrorMessage = niloperationErrorMessage = nil-- helperRegistrationTask = Task { @MainActor [weak self] in- guard let self else {- return- }-- let succeeded = await completeHelperUpdate(updateIdentifier)- guard isStarted, !Task.isCancelled else {- return- }- if !succeeded {- registrationErrorMessage = KeepAliveLocalizedMessage.updateFailed- }-- assign(!succeeded && helperStatus == .enabled, to: \.isRefreshingHelper)- helperRegistrationTask = nil- reconcileSleepState(trigger: .helperRegistered, force: true)- reconcileAutoResetWakeSchedule()+ let succeeded = await completeHelperUpdate(updateIdentifier)+ guard isStarted, !Task.isCancelled else { return }+ if !succeeded {+ registrationErrorMessage = KeepAliveLocalizedMessage.updateFailed}+ assign(!succeeded && helperStatus == .enabled, to: \.isRefreshingHelper)+ reconcileSleepState(trigger: .helperRegistered, force: true)+ reconcileAutoResetWakeSchedule()}func completeHelperUpdate(_ updateIdentifier: String) async -> Bool {@@ -1528,8 +1531,7 @@ private extension KeepAliveController {return false}- refreshHelperStatus()- guard helperStatus == .enabled else {+ guard await refreshHelperStatus(), helperStatus == .enabled else {continue}if await resetSleepAfterHelperUpdate(updateIdentifier) {diff --git a/CodexBar/Services/KeepAlive/SystemSleepService.swift b/CodexBar/Services/KeepAlive/SystemSleepService.swiftindex 9299128..8772a9e 100644--- a/CodexBar/Services/KeepAlive/SystemSleepService.swift+++ b/CodexBar/Services/KeepAlive/SystemSleepService.swift@@ -21,30 +21,25 @@ final class SystemSleepService {id != IOPMAssertionID(kIOPMNullAssertionID)}- mutating func begin() -> IOReturn {+ mutating func begin(create: (CFString, CFString, inout IOPMAssertionID) -> IOReturn) -> IOReturn {guard !isActive else {return kIOReturnSuccess}var createdAssertionID = IOPMAssertionID(kIOPMNullAssertionID)- let result = IOPMAssertionCreateWithName(- type,- IOPMAssertionLevel(kIOPMAssertionLevelOn),- name,- &createdAssertionID- )+ let result = create(type, name, &createdAssertionID)if result == kIOReturnSuccess {id = createdAssertionID}return result}- mutating func end() -> IOReturn {+ mutating func end(release: (IOPMAssertionID) -> IOReturn) -> IOReturn {guard isActive else {return kIOReturnSuccess}- let result = IOPMAssertionRelease(id)+ let result = release(id)if result == kIOReturnSuccess || result == kIOReturnNotFound {id = IOPMAssertionID(kIOPMNullAssertionID)}@@ -52,6 +47,11 @@ final class SystemSleepService {}}+ private let createAssertion: (CFString, CFString, inout IOPMAssertionID) -> IOReturn+ private let releaseAssertion: (IOPMAssertionID) -> IOReturn+ private let declareActivity: (CFString, inout IOPMAssertionID) -> IOReturn+ private let displayReleaseRetryDelays: [Duration]+ private var displayReleaseRetryTask: Task<Void, Never>?private var sleepAssertion: Assertionprivate var displayAssertion = Assertion(type: kIOPMAssertionTypeNoDisplaySleep as CFString,@@ -63,14 +63,30 @@ final class SystemSleepService {/// 上一拍声明成功没有, 用来只在成败翻转时记日志; 每轮起表时归位成"成功"private var didDeclareUserActivity = true- /// 认节拍而不是认断言: 释放失败的那一轮会留下"断言还在但节拍已停", 认断言会把它当成还留着屏幕,- /// 之后再要留住时被判定成无事可做, 于是屏幕不睡而屏保照常启动- /// 反过来"节拍在而断言不在"不可达, 节拍只在断言建立成功之后才起var isPreventingDisplaySleep: Bool {- userActivityTask != nil+ displayAssertion.isActive && userActivityTask != nil}- init(sleepAssertionName: String = "CodexBar - Codex activity") {+ var hasDisplaySleepResources: Bool {+ displayAssertion.isActive || userActivityTask != nil+ || userActivityAssertionID != IOPMAssertionID(kIOPMNullAssertionID)+ }++ init(+ sleepAssertionName: String = "CodexBar - Codex activity",+ createAssertion: @escaping (CFString, CFString, inout IOPMAssertionID) -> IOReturn = { type, name, id in+ IOPMAssertionCreateWithName(type, IOPMAssertionLevel(kIOPMAssertionLevelOn), name, &id)+ },+ releaseAssertion: @escaping (IOPMAssertionID) -> IOReturn = { IOPMAssertionRelease($0) },+ declareActivity: @escaping (CFString, inout IOPMAssertionID) -> IOReturn = { name, id in+ IOPMAssertionDeclareUserActivity(name, kIOPMUserActiveLocal, &id)+ },+ displayReleaseRetryDelays: [Duration] = [.seconds(1), .seconds(2), .seconds(5)]+ ) {+ self.createAssertion = createAssertion+ self.releaseAssertion = releaseAssertion+ self.declareActivity = declareActivity+ self.displayReleaseRetryDelays = displayReleaseRetryDelayssleepAssertion = Assertion(type: kIOPMAssertionTypePreventUserIdleSystemSleep as CFString,name: sleepAssertionName as CFString@@ -78,16 +94,18 @@ final class SystemSleepService {}func beginPreventingIdleSleep() -> IOReturn {- sleepAssertion.begin()+ sleepAssertion.begin(create: createAssertion)}func endPreventingIdleSleep() -> IOReturn {- sleepAssertion.end()+ sleepAssertion.end(release: releaseAssertion)}/// 屏幕不睡与不进屏保是两件事, 后者要靠节拍声明用户活动, 所以两者收在同一对方法里func beginPreventingDisplaySleep() -> IOReturn {- let result = displayAssertion.begin()+ displayReleaseRetryTask?.cancel()+ displayReleaseRetryTask = nil+ let result = displayAssertion.begin(create: createAssertion)guard result == kIOReturnSuccess else {return result}@@ -100,11 +118,42 @@ final class SystemSleepService {userActivityTask?.cancel()userActivityTask = nildidDeclareUserActivity = true+ displayReleaseRetryTask?.cancel()+ displayReleaseRetryTask = nil+ let result = releaseDisplayAssertions()+ if result != kIOReturnSuccess {+ scheduleDisplayReleaseRetry()+ }+ return result+ }++ private func releaseDisplayAssertions() -> IOReturn {+ var activityResult = kIOReturnSuccessif userActivityAssertionID != IOPMAssertionID(kIOPMNullAssertionID) {- IOPMAssertionRelease(userActivityAssertionID)- userActivityAssertionID = IOPMAssertionID(kIOPMNullAssertionID)+ activityResult = releaseAssertion(userActivityAssertionID)+ if activityResult == kIOReturnSuccess || activityResult == kIOReturnNotFound {+ userActivityAssertionID = IOPMAssertionID(kIOPMNullAssertionID)+ activityResult = kIOReturnSuccess+ }+ }+ let displayResult = displayAssertion.end(release: releaseAssertion)+ return displayResult == kIOReturnSuccess ? activityResult : displayResult+ }++ private func scheduleDisplayReleaseRetry() {+ displayReleaseRetryTask = Task { @MainActor [weak self, delays = displayReleaseRetryDelays] in+ for delay in delays {+ do { try await Task.sleep(for: delay) } catch { return }+ guard let self, !Task.isCancelled else { return }+ if releaseDisplayAssertions() == kIOReturnSuccess {+ displayReleaseRetryTask = nil+ AppLog.keepAlive.notice("显示断言已释放: reason=retry")+ return+ }+ }+ self?.displayReleaseRetryTask = nil+ AppLog.keepAlive.error("显示断言释放重试已耗尽")}- return displayAssertion.end()}/// 屏保与闲置锁屏跟的是系统 idle 计时, 显示断言只保证屏幕不睡, 挡不住它们@@ -125,11 +174,7 @@ final class SystemSleepService {/// 定期声明用户活动时只记录成败变化, 避免持续失败产生重复日志private func declareUserActivity() {- let result = IOPMAssertionDeclareUserActivity(- displayAssertion.name,- kIOPMUserActiveLocal,- &userActivityAssertionID- )+ let result = declareActivity(displayAssertion.name, &userActivityAssertionID)let didSucceed = result == kIOReturnSuccessdefer {didDeclareUserActivity = didSucceeddiff --git a/CodexBar/Services/Notifications/NotificationContent.swift b/CodexBar/Services/Notifications/NotificationContent.swiftindex 18d1ca9..64ec8a0 100644--- a/CodexBar/Services/Notifications/NotificationContent.swift+++ b/CodexBar/Services/Notifications/NotificationContent.swift@@ -93,22 +93,22 @@ nonisolated struct NotificationContent: Equatable {)}- static func taskWaiting(project: String?, toolName: String?) -> NotificationContent {- let body = switch (project, toolName) {- case let (project?, toolName?):+ static func taskWaiting(project: String?, actionText: String?) -> NotificationContent {+ let body = switch (project, actionText) {+ case let (project?, actionText?):String(localized: "notification.task-waiting.body.project-tool",- defaultValue: "\(project)\(toolName)"+ defaultValue: "\(project)\(actionText)")case let (project?, nil):String(localized: "notification.task-waiting.body.project",defaultValue: "\(project)")- case let (nil, toolName?):+ case let (nil, actionText?):String(localized: "notification.task-waiting.body.codex-tool",- defaultValue: "\(toolName)"+ defaultValue: "\(actionText)")case (nil, nil):String(localized: "notification.task-waiting.body.codex")diff --git a/CodexBar/Services/Notifications/NotificationService.swift b/CodexBar/Services/Notifications/NotificationService.swiftindex d4ffd9e..916f9e5 100644--- a/CodexBar/Services/Notifications/NotificationService.swift+++ b/CodexBar/Services/Notifications/NotificationService.swift@@ -119,9 +119,6 @@ final class NotificationService: NSObject {// MARK: - 任务提醒private func handleActivityTransition(_ transition: ActivityTransition) {- guard !transition.isAnonymous else {- return- }performTaskHapticFeedbackIfEnabled()guard settings.canDeliver else {@@ -137,7 +134,7 @@ final class NotificationService: NSObject {let identifier = Self.taskWaitingNotificationIdentifier(for: taskID)taskWaitingNotificationIdentifiers.insert(identifier)send(- .taskWaiting(project: task.projectName, toolName: task.toolDisplayName),+ .taskWaiting(project: task.projectName, actionText: task.approvalActionText),sound: settings.taskWaitingSound,identifier: identifier,isStillRelevant: { [weak self] indiff --git a/CodexBar/Services/Settings/GlobalHotKeySettings.swift b/CodexBar/Services/Settings/GlobalHotKeySettings.swiftindex bb91130..c94028c 100644--- a/CodexBar/Services/Settings/GlobalHotKeySettings.swift+++ b/CodexBar/Services/Settings/GlobalHotKeySettings.swift@@ -2,7 +2,7 @@ import Combineimport Foundationimport os-/// 全局快捷键偏好设置, 负责持久化和注册失败后的 UI 回滚+/// 全局快捷键偏好设置, 注册成功后发布并持久化@MainActorfinal class GlobalHotKeySettings: ObservableObject {@Published private(set) var shortcut: GlobalHotKeyShortcut?@@ -10,6 +10,7 @@ final class GlobalHotKeySettings: ObservableObject {private let defaults: UserDefaultsprivate let encoder = JSONEncoder()+ private var registrationHandler: ((GlobalHotKeyShortcut?) -> String?)?init(defaults: UserDefaults = .standard) {self.defaults = defaults@@ -22,6 +23,11 @@ final class GlobalHotKeySettings: ObservableObject {return}+ if let message = registrationHandler?(shortcut) {+ errorMessage = message+ return+ }+AppLog.settings.notice("快捷键已设置")self.shortcut = shortcutsaveShortcut(shortcut)@@ -29,6 +35,10 @@ final class GlobalHotKeySettings: ObservableObject {}func clearShortcut() {+ if let message = registrationHandler?(nil) {+ errorMessage = message+ return+ }AppLog.settings.notice("快捷键已清除")shortcut = nilsaveShortcut(nil)@@ -40,19 +50,15 @@ final class GlobalHotKeySettings: ObservableObject {}/// 只设用户可见文案, 不记日志- /// 注册失败由 GlobalHotKeyController 记且带 code=, 这里再记一条会把一次冲突算成两次- /// 另一个调用方是录制时的按键解析失败, 那次根本没发起注册, 记成 stage=register 更是误导+ /// 按键解析失败时尚未发起注册, 不记为注册失败func setRegistrationError(_ message: String) {errorMessage = message}- /// 参数不可为空: 传 nil 会经 saveShortcut 清空用户保存的配置- /// 没有可回退的快捷键时应改用 setRegistrationError- func restoreShortcut(_ shortcut: GlobalHotKeyShortcut, message: String) {- AppLog.settings.notice("快捷键已回退: reason=occupied")- self.shortcut = shortcut- saveShortcut(shortcut)- errorMessage = message+ func configureRegistration(_ handler: ((GlobalHotKeyShortcut?) -> String?)?) {+ registrationHandler = handler+ // 启动注册失败只提示错误, 不覆盖用户保存的快捷键+ errorMessage = handler?(shortcut)}func clearError() {diff --git a/CodexBar/Services/Settings/LoginItemSettings.swift b/CodexBar/Services/Settings/LoginItemSettings.swiftindex d115dd7..21db529 100644--- a/CodexBar/Services/Settings/LoginItemSettings.swift+++ b/CodexBar/Services/Settings/LoginItemSettings.swift@@ -6,11 +6,37 @@ import ServiceManagement/// 开机启动设置, 所有 ServiceManagement 错误只展示简短文案@MainActorfinal class LoginItemSettings: ObservableObject {- @Published private(set) var isEnabled = false+ @Published private(set) var status: SMAppService.Status = .notRegistered@Published private(set) var errorMessage: String?+ var isEnabled: Bool {+ status == .enabled+ }++ var requiresApproval: Bool {+ status == .requiresApproval+ }++ private let readStatus: () -> SMAppService.Status+ private let register: () throws -> Void+ private let unregister: () throws -> Void++ init(+ readStatus: @escaping () -> SMAppService.Status = { SMAppService.mainApp.status },+ register: @escaping () throws -> Void = { try SMAppService.mainApp.register() },+ unregister: @escaping () throws -> Void = { try SMAppService.mainApp.unregister() }+ ) {+ self.readStatus = readStatus+ self.register = register+ self.unregister = unregister+ }+func refresh() {- isEnabled = SMAppService.mainApp.status == .enabled+ let currentStatus = readStatus()+ if currentStatus != status {+ errorMessage = nil+ }+ status = currentStatus}func setEnabled(_ enabled: Bool) {@@ -19,11 +45,12 @@ final class LoginItemSettings: ObservableObject {AppLog.settings.notice("开机自动启动变更: enabled=\(enabled ? 1 : 0)")do {if enabled {- try SMAppService.mainApp.register()+ try register()} else {- try SMAppService.mainApp.unregister()+ try unregister()}+ // 注册成功仍可能等待系统批准, 开关只反映实际授权refresh()} catch {let details = LogFields.joined(@@ -32,7 +59,9 @@ final class LoginItemSettings: ObservableObject {)AppLog.settings.error("开机自动启动失败: \(details, privacy: .public)")refresh()- errorMessage = String(localized: "settings.general.launch-at-login-failed")+ if !requiresApproval {+ errorMessage = String(localized: "settings.general.launch-at-login-failed")+ }}}}diff --git a/CodexBar/Services/Settings/TUINotificationSettings.swift b/CodexBar/Services/Settings/TUINotificationSettings.swiftindex 59dbc7c..860f0f3 100644--- a/CodexBar/Services/Settings/TUINotificationSettings.swift+++ b/CodexBar/Services/Settings/TUINotificationSettings.swift@@ -22,9 +22,9 @@ final class TUINotificationSettings: ObservableObject {}runLatestUpdate(operation: .read) { settings, generation in- let response = try await settings.codexStatusService.readCodexConfig()+ let enabledOnServer = try await settings.codexStatusService.areTUINotificationsEnabled()try settings.ensureCurrentUpdate(generation)- return response.areTUINotificationsEnabled+ return enabledOnServer}}@@ -35,20 +35,12 @@ final class TUINotificationSettings: ObservableObject {}runLatestUpdate(operation: .write) { settings, generation in- _ = try await settings.codexStatusService.writeCodexConfigBatch(- edits: [- .init(- keyPath: Self.configKeyPath,- value: enabled,- mergeStrategy: Self.configMergeStrategy- )- ]- )+ try await settings.codexStatusService.setTUINotificationsEnabled(enabled)try settings.ensureCurrentUpdate(generation)- let response = try await settings.codexStatusService.readCodexConfig()+ let enabledOnServer = try await settings.codexStatusService.areTUINotificationsEnabled()try settings.ensureCurrentUpdate(generation)- guard response.areTUINotificationsEnabled == enabled else {+ guard enabledOnServer == enabled else {throw SettingsError.verificationFailed}return enabled@@ -128,7 +120,4 @@ final class TUINotificationSettings: ObservableObject {String(localized: "codex-tui-notifications.error.state-mismatch")}}-- private static let configKeyPath = "tui.notifications"- private static let configMergeStrategy = "upsert"}diff --git a/CodexBar/Services/Support/AppLog.swift b/CodexBar/Services/Support/AppLog.swiftindex 6c55d14..3c818b4 100644--- a/CodexBar/Services/Support/AppLog.swift+++ b/CodexBar/Services/Support/AppLog.swift@@ -50,6 +50,7 @@ nonisolated enum LogTrigger: String {case limitReached/// 电量或供电方式变化case battery+ case accountNotificationcase statusRefreshcase autoReset}diff --git a/CodexBar/Services/Support/JSONLines.swift b/CodexBar/Services/Support/JSONLines.swiftindex ed2274a..a2d9a4c 100644--- a/CodexBar/Services/Support/JSONLines.swift+++ b/CodexBar/Services/Support/JSONLines.swift@@ -52,6 +52,7 @@ nonisolated enum JSONLines {) -> JSONLinesDecodeResult<T> {var values = [T]()var failedLineCount = 0+ var compatibilityError: StorageCompatibilityError?// 逐行独立解码: 进程被杀或断电会留下截断的多字节序列// 整块处理时一处损坏会连带丢掉同一次读取里的所有完好事件, 且调用方仍会推进 offset@@ -61,15 +62,18 @@ nonisolated enum JSONLines {guard !isBlankLine(line) else {continue}- guard let value = try? decoder.decode(T.self, from: Data(line)) else {+ do {+ try values.append(decoder.decode(T.self, from: Data(line)))+ } catch StorageCompatibilityError.incompleteSource {+ failedLineCount += 1+ } catch let error as StorageCompatibilityError {+ compatibilityError = error+ } catch {failedLineCount += 1- continue}-- values.append(value)}- return JSONLinesDecodeResult(values: values, failedLineCount: failedLineCount)+ return JSONLinesDecodeResult(values: values, failedLineCount: failedLineCount, compatibilityError: compatibilityError)}}@@ -77,4 +81,5 @@ nonisolated enum JSONLines {nonisolated struct JSONLinesDecodeResult<T> {let values: [T]let failedLineCount: Int+ var compatibilityError: StorageCompatibilityError?}diff --git a/CodexBar/Services/Sync/ActivityRecordCodec.swift b/CodexBar/Services/Sync/ActivityRecordCodec.swiftindex 585c495..ab6c8c3 100644--- a/CodexBar/Services/Sync/ActivityRecordCodec.swift+++ b/CodexBar/Services/Sync/ActivityRecordCodec.swift@@ -5,6 +5,7 @@ import Foundationnonisolated enum ActivityRecordCodec {static let version = 1+ static let metadataVersion = 1enum RecordTypes {static let metadata = "Metadata"@@ -14,12 +15,12 @@ nonisolated enum ActivityRecordCodec {enum FieldKeys {static let salt = "salt"static let version = "version"+ static let aggregationVersion = "aggregationVersion"+ static let sourceCheckpoint = "sourceCheckpoint"static let deviceID = "deviceID"static let date = "date"static let generationID = "generationID"static let eventCount = "eventCount"- static let sessionStartedCount = "sessionStartedCount"- static let sessionEndedCount = "sessionEndedCount"static let turnStartedCount = "turnStartedCount"static let turnCompletedCount = "turnCompletedCount"static let turnAbortedCount = "turnAbortedCount"@@ -30,7 +31,7 @@ nonisolated enum ActivityRecordCodec {static let compactionCompletedCount = "compactionCompletedCount"static let subagentStartedCount = "subagentStartedCount"static let subagentEndedCount = "subagentEndedCount"- static let sessionCount = "sessionCount"+ static let threadCount = "threadCount"static let turnCount = "turnCount"static let projectCounts = "projectCounts"static let modelCounts = "modelCounts"@@ -43,12 +44,11 @@ nonisolated enum ActivityRecordCodec {to record: CKRecord) {record[FieldKeys.version] = version as CKRecordValue+ record[FieldKeys.aggregationVersion] = aggregate.aggregationVersion as CKRecordValuerecord[FieldKeys.deviceID] = deviceID as CKRecordValuerecord[FieldKeys.date] = aggregate.date as CKRecordValuerecord[FieldKeys.generationID] = aggregate.generationID as CKRecordValue?record[FieldKeys.eventCount] = aggregate.eventCount as CKRecordValue?- record[FieldKeys.sessionStartedCount] = aggregate.sessionStartedCount as CKRecordValue?- record[FieldKeys.sessionEndedCount] = aggregate.sessionEndedCount as CKRecordValue?record[FieldKeys.turnStartedCount] = aggregate.turnStartedCount as CKRecordValue?record[FieldKeys.turnCompletedCount] = aggregate.turnCompletedCount as CKRecordValue?record[FieldKeys.turnAbortedCount] = aggregate.turnAbortedCount as CKRecordValue?@@ -59,27 +59,35 @@ nonisolated enum ActivityRecordCodec {record[FieldKeys.compactionCompletedCount] = aggregate.compactionCompletedCount as CKRecordValue?record[FieldKeys.subagentStartedCount] = aggregate.subagentStartedCount as CKRecordValue?record[FieldKeys.subagentEndedCount] = aggregate.subagentEndedCount as CKRecordValue?- record[FieldKeys.sessionCount] = aggregate.sessionCount as CKRecordValue?+ record[FieldKeys.threadCount] = aggregate.threadCount as CKRecordValue?record[FieldKeys.turnCount] = aggregate.turnCount as CKRecordValue?record[FieldKeys.projectCounts] = countsData(aggregate.projectCounts) as CKRecordValuerecord[FieldKeys.modelCounts] = countsData(aggregate.modelCounts) as CKRecordValue+ record[FieldKeys.sourceCheckpoint] = aggregate.sourceCheckpoint.flatMap { try? JSONLines.stableEncoder.encode($0) } as CKRecordValue?record[FieldKeys.updatedAt] = Date() as CKRecordValue}static func remoteDailyRecord(from record: CKRecord) throws -> ActivitySyncRecord? {- guard record.recordType == RecordTypes.activity,- let deviceID = record[FieldKeys.deviceID] as? String,- let date = record[FieldKeys.date] as? String,- HistoryStorage.isValidDateKey(date) else {- return nil+ guard record.recordType == RecordTypes.activity else { return nil }+ try StorageVersion.require(optionalIntValue(record[FieldKeys.version]) ?? -1, current: version, name: "CloudActivity")+ try AggregationVersion.require(optionalIntValue(record[FieldKeys.aggregationVersion]) ?? -1, current: AggregationVersion.activity, name: "Activity")+ guard+ let deviceID = record[FieldKeys.deviceID] as? String,+ let date = record[FieldKeys.date] as? String,+ HistoryStorage.isValidDateKey(date) else {+ throw ActivitySyncError.invalidRecordIdentity}- let aggregate = SyncedActivity(+ guard let checkpointData = record[FieldKeys.sourceCheckpoint] as? Data else {+ throw StorageCompatibilityError.incompleteSource+ }+ let checkpoint = try JSONDecoder().decode(ActivitySourceCheckpoint.self, from: checkpointData)+ let aggregate = try SyncedActivity(+ aggregationVersion: optionalIntValue(record[FieldKeys.aggregationVersion]) ?? -1,+ sourceCheckpoint: checkpoint,date: date,generationID: record[FieldKeys.generationID] as? String,eventCount: optionalIntValue(record[FieldKeys.eventCount]),- sessionStartedCount: optionalIntValue(record[FieldKeys.sessionStartedCount]),- sessionEndedCount: optionalIntValue(record[FieldKeys.sessionEndedCount]),turnStartedCount: optionalIntValue(record[FieldKeys.turnStartedCount]),turnCompletedCount: optionalIntValue(record[FieldKeys.turnCompletedCount]),turnAbortedCount: optionalIntValue(record[FieldKeys.turnAbortedCount]),@@ -90,7 +98,7 @@ nonisolated enum ActivityRecordCodec {compactionCompletedCount: optionalIntValue(record[FieldKeys.compactionCompletedCount]),subagentStartedCount: optionalIntValue(record[FieldKeys.subagentStartedCount]),subagentEndedCount: optionalIntValue(record[FieldKeys.subagentEndedCount]),- sessionCount: optionalIntValue(record[FieldKeys.sessionCount]),+ threadCount: optionalIntValue(record[FieldKeys.threadCount]),turnCount: optionalIntValue(record[FieldKeys.turnCount]),projectCounts: counts(from: record[FieldKeys.projectCounts]),modelCounts: counts(from: record[FieldKeys.modelCounts])@@ -114,11 +122,10 @@ nonisolated enum ActivityRecordCodec {return nil}- static func counts(from value: CKRecordValue?) -> [String: Int] {- guard let data = value as? Data,- let counts = try? JSONDecoder().decode([String: Int].self, from: data) else {- return [:]- }+ static func counts(from value: CKRecordValue?) throws -> [String: Int] {+ guard let data = value as? Data else { throw StorageCompatibilityError.incompleteSource }+ let counts = try JSONDecoder().decode([String: Int].self, from: data)+ guard counts.values.allSatisfy({ $0 >= 0 }) else { throw StorageCompatibilityError.incompleteSource }return counts}diff --git a/CodexBar/Services/Sync/ActivitySyncStore.swift b/CodexBar/Services/Sync/ActivitySyncStore.swiftindex eb755f3..9fee059 100644--- a/CodexBar/Services/Sync/ActivitySyncStore.swift+++ b/CodexBar/Services/Sync/ActivitySyncStore.swift@@ -44,14 +44,19 @@ nonisolated struct ActivitySyncStore {}}- func removeCursorIfPresent() throws {- try update { $0.cursor = nil }- }-func reset(state: SyncState) throws {try update { $0 = ActivitySyncCache(state: state) }}+ func prune(now: Date) throws {+ try JSONFileStorage.withLock(in: cacheDirectoryURL) {+ var cache = try read()+ if cache.prune(now: now) {+ try JSONFileStorage.save(cache, to: cacheURL)+ }+ }+ }+private func read() throws -> ActivitySyncCache {let cache: ActivitySyncCachedo {@@ -79,6 +84,7 @@ nonisolated struct ActivitySyncStore {try JSONFileStorage.withLock(in: cacheDirectoryURL) {var cache = try read()try body(&cache)+ cache.prune()try JSONFileStorage.save(cache, to: cacheURL)}}@@ -96,6 +102,15 @@ nonisolated struct ActivitySyncCache: Codable, Equatable {var state = SyncState()var records: [ActivitySyncRecord] = []var cursor: Data?++ @discardableResult+ mutating func prune(now: Date = Date()) -> Bool {+ let cutoff = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate(today: now))+ let previousCount = records.count + state.hashByDate.count+ records.removeAll { $0.date < cutoff }+ state.hashByDate = state.hashByDate.filter { $0.key >= cutoff }+ return previousCount != records.count + state.hashByDate.count+ }}nonisolated struct SyncState: Codable, Equatable {diff --git a/CodexBar/Services/Sync/SyncService.swift b/CodexBar/Services/Sync/SyncService.swiftindex cf24032..582afe4 100644--- a/CodexBar/Services/Sync/SyncService.swift+++ b/CodexBar/Services/Sync/SyncService.swift@@ -25,13 +25,13 @@ private nonisolated enum SyncStage: String {case prune}-/// 将本机 daily.jsonl 中不含 sessionIds 和 turnIds 的聚合行同步到 CloudKit private database+/// 将本机 daily.jsonl 中不含 threadIDs 和 turnIds 的聚合行同步到 CloudKit private databaseactor SyncService {private let container: CKContainer?private let suppliedDatabase: (any SyncDatabase)?private lazy var database: any SyncDatabase = suppliedDatabase ?? (container ?? SyncCloudKit.makeContainer()).privateCloudDatabase- private let fileManager: FileManagerprivate let directoryURL: URL+ private let activityEventsDirectoryURL: URLprivate let isEnabled: @Sendable () -> Boolprivate lazy var tokenSync = TokenSync(database: database, directoryURL: directoryURL.appendingPathComponent("Tokens"), isEnabled: isEnabled@@ -41,30 +41,53 @@ actor SyncService {// salt 只在单轮内复用, 每轮确认同名 zone 是否已经被其他设备重建private var isSyncZoneConfirmed = falseprivate var cachedAccountSalt: Data?+ private var lastActivityCacheRetentionCutoff: Date?+ private var lastTokenCacheRetentionCutoff: Date?+ private var isActivityCacheComplete = trueinit(container: CKContainer? = nil,database: (any SyncDatabase)? = nil,- fileManager: FileManager = .default,directoryURL: URL = HistoryStorage.syncDirectoryURL(),+ activityEventsDirectoryURL: URL? = nil,isEnabled: @escaping @Sendable () -> Bool = { SyncSettings.isEnabled() }) {self.container = containersuppliedDatabase = database- self.fileManager = fileManagerself.directoryURL = directoryURL+ self.activityEventsDirectoryURL = activityEventsDirectoryURL ?? HistoryStorage.eventsDirectoryURL(in: directoryURL.deletingLastPathComponent())self.isEnabled = isEnabled}// MARK: - 同步入口- func snapshotFromCacheIfEnabled(localTokenTurns: [TokenTurn] = [], replacements: [ActivityAggregate] = []) async -> SyncSnapshot {+ func pruneLocalCaches(now: Date = Date()) {+ let cutoff = HistoryStorage.retentionCutoffDate(today: now)+ if lastActivityCacheRetentionCutoff != cutoff {+ do {+ try activityStore.prune(now: now)+ lastActivityCacheRetentionCutoff = cutoff+ } catch {+ AppLog.sync.error("活动同步缓存过期清理失败")+ }+ }+ if lastTokenCacheRetentionCutoff != cutoff {+ do {+ try TokenSync.pruneLocalCache(in: directoryURL.appendingPathComponent("Tokens"), now: now)+ lastTokenCacheRetentionCutoff = cutoff+ } catch {+ AppLog.sync.error("Token 同步缓存过期清理失败")+ }+ }+ }++ func snapshotFromCacheIfEnabled(localTokenTurns: [TokenTurn] = []) async -> SyncSnapshot {guard isEnabled() else {return .disabled}let state = activityStore.loadState()- return await snapshot(from: state, localTokenTurns: localTokenTurns, replacementDates: Set(replacements.map(\.date)))+ return await snapshot(from: state, localTokenTurns: localTokenTurns)}func tokenRecoveryBaselineIfEnabled() async -> TokenHistoryBaseline? {@@ -72,14 +95,23 @@ actor SyncService {return await tokenSync.recoveryBaseline(accountScopedDeviceID: activityStore.loadState().deviceID)}+ func hasPendingActivityUpdates(local: [ActivityAggregate]) -> Bool {+ guard isEnabled() else { return false }+ guard let state = try? activityStore.load().state else { return !local.isEmpty }+ return local.contains { aggregate in+ (try? hash(for: aggregate.syncedAggregate)) != state.hashByDate[aggregate.date]+ }+ }+func hasPendingTokenUpdates(local: [TokenTurn]) async -> Bool {- await tokenSync.hasPendingUpdates(local: local, accountScopedDeviceID: activityStore.loadState().deviceID)+ guard isEnabled() else { return false }+ return await tokenSync.hasPendingUpdates(local: local, accountScopedDeviceID: activityStore.loadState().deviceID)}func synchronizeIfEnabled(localAggregates: [ActivityAggregate],localTokenTurns: [TokenTurn] = [],- replacements: [ActivityAggregate] = [],+ recoveredTokenIDs: Set<String> = [],trigger: LogTrigger) async -> SyncSnapshot {guard isEnabled(), !Task.isCancelled else {@@ -101,8 +133,11 @@ actor SyncService {)}- var state = activityStore.loadState()- var completedReplacements: [String: String] = [:]+ var state: SyncState+ do { state = try activityStore.load().state } catch {+ failureMessage = SyncFailureReason.classify(error).message+ return SyncSnapshot(records: [], currentDeviceID: nil, isActivityComplete: false)+ }// 显式开启同步允许恢复缺失的 zone, 同一轮最多重新执行一次cachedAccountSalt = nil@@ -110,8 +145,7 @@ actor SyncService {do {try SyncCancellation.check(isEnabled: isEnabled)failureMessage = try await synchronizeOnce(- localAggregates: localAggregates, localTokenTurns: localTokenTurns,- replacements: replacements, completedReplacements: &completedReplacements,+ localAggregates: localAggregates, localTokenTurns: localTokenTurns, recoveredTokenIDs: recoveredTokenIDs,state: &state, stage: &stage, trigger: trigger)didSucceed = failureMessage == nil@@ -122,7 +156,6 @@ actor SyncService {invalidateAccountScopedCaches()}if SyncRecovery.isMissingZone(error, zoneID: syncZoneID), !Task.isCancelled, isEnabled() {- completedReplacements.removeAll()do {try await resetSyncState(state: &state)if attempt == 0 {@@ -146,14 +179,11 @@ actor SyncService {guard !Task.isCancelled, isEnabled() else { return .disabled }let latestState = activityStore.loadState()- var result = await snapshot(from: latestState, localTokenTurns: localTokenTurns, replacementDates: Set(replacements.map(\.date)))- result.completedReplacements = completedReplacements- return result+ return await snapshot(from: latestState, localTokenTurns: localTokenTurns)}private func synchronizeOnce(- localAggregates: [ActivityAggregate], localTokenTurns: [TokenTurn],- replacements: [ActivityAggregate], completedReplacements: inout [String: String],+ localAggregates: [ActivityAggregate], localTokenTurns: [TokenTurn], recoveredTokenIDs: Set<String>,state: inout SyncState, stage: inout SyncStage, trigger: LogTrigger) async throws -> String? {let duration = LogDuration()@@ -162,22 +192,17 @@ actor SyncService {let deviceID = try await resolveCurrentDeviceID()try await resetStateIfDeviceChanged(deviceID, state: &state)- var localByDate: [String: LocalSyncAggregate] = [:]+ var localByDate: [String: SyncedActivity] = [:]var confirmedDates = Set<String>()var activityFailure: Error?do {stage = .uploadlocalByDate = try Self.syncedAggregatesByDate(localAggregates)- for (date, var replacement) in try Self.syncedAggregatesByDate(replacements) {- guard replacement.aggregate.eventCount != nil else { throw ActivitySyncError.invalidRecordIdentity }- replacement.isReplacement = true- localByDate[date] = replacement- }confirmedDates = try await synchronizeActivity(- localByDate: localByDate, deviceID: deviceID, state: &state, stage: &stage,- completedReplacements: &completedReplacements+ localByDate: localByDate, deviceID: deviceID, state: &state, stage: &stage)} catch {+ isActivityCacheComplete = falseif SyncRecovery.stopsOtherSync(error) {throw error}@@ -192,7 +217,7 @@ actor SyncService {}stage = .tokenstry await tokenSync.synchronize(- local: localTokenTurns, accountScopedDeviceID: deviceID, salt: accountSalt(), zoneID: syncZoneID+ local: localTokenTurns, recoveredIDs: recoveredTokenIDs, accountScopedDeviceID: deviceID, salt: accountSalt(), zoneID: syncZoneID)if let activityFailure {try SyncCancellation.check(isEnabled: isEnabled)@@ -216,19 +241,19 @@ actor SyncService {}private func synchronizeActivity(- localByDate: [String: LocalSyncAggregate], deviceID: String,- state: inout SyncState, stage: inout SyncStage,- completedReplacements: inout [String: String]+ localByDate: [String: SyncedActivity], deviceID _: String,+ state: inout SyncState, stage: inout SyncStage) async throws -> Set<String> {stage = .fetch- try await refreshCacheBeforeUpload(localByDate: localByDate, deviceID: deviceID, state: &state)+ try await refreshCacheFromRemote()stage = .uploadlet dates = try await uploadChangedAggregates(- localByDate: localByDate, remoteRecords: activityStore.loadCachedRecords(),- state: &state, completedReplacements: &completedReplacements+ localByDate: localByDate,+ state: &state)stage = .fetchtry await refreshCacheFromRemote()+ isActivityCacheComplete = truereturn dates}@@ -274,25 +299,6 @@ actor SyncService {AppLog.sync.error("同步失败: \(details, privacy: .public)")}- private func refreshCacheBeforeUpload(- localByDate: [String: LocalSyncAggregate],- deviceID: String,- state: inout SyncState- ) async throws {- guard localByDate.values.contains(where: \.isReplacement) else {- try await refreshCacheFromRemote()- return- }-- // 替换前全量拉取, 避免增量缓存遗漏同设备同日期的旧 generation- try await rebuildCacheFromRemote()- try await preparePendingReplacements(- localByDate: localByDate,- deviceID: deviceID,- state: &state- )- }-private func resetStateIfDeviceChanged(_ deviceID: String,state: inout SyncState@@ -317,45 +323,31 @@ actor SyncService {private static func syncedAggregatesByDate(_ aggregates: [ActivityAggregate]- ) throws -> [String: LocalSyncAggregate] {- try aggregates.reduce(into: [String: LocalSyncAggregate]()) { result, aggregate in+ ) throws -> [String: SyncedActivity] {+ try aggregates.reduce(into: [String: SyncedActivity]()) { result, aggregate in_ = try aggregate.syncedAggregate.requiredGenerationID()- result[aggregate.date] = LocalSyncAggregate(- aggregate: aggregate.syncedAggregate,- generationStartedEmpty: aggregate.generationStartedEmpty- )+ result[aggregate.date] = aggregate.syncedAggregate}}- private func snapshot(from state: SyncState, localTokenTurns: [TokenTurn], replacementDates: Set<String>) async -> SyncSnapshot {- guard let deviceID = state.deviceID else {- return .disabled- }-- let records = Self.filteredRetained(records: activityStore.loadCachedRecords()).filter { record in- record.deviceID != deviceID || !replacementDates.contains(record.date)+ private func snapshot(from state: SyncState, localTokenTurns: [TokenTurn]) async -> SyncSnapshot {+ var result = SyncSnapshot(records: [], currentDeviceID: state.deviceID)+ do {+ let cache = try activityStore.load()+ result = SyncSnapshot(records: Self.filteredRetained(records: cache.records), currentDeviceID: cache.state.deviceID)+ } catch {+ result.isActivityComplete = false}-- return await SyncSnapshot(- records: records,- currentDeviceID: deviceID,- tokenUsageByDate: tokenSync.snapshot(local: localTokenTurns, accountScopedDeviceID: deviceID)- )+ result.tokenUsageByDate = try? await tokenSync.snapshot(local: localTokenTurns, accountScopedDeviceID: state.deviceID)+ result.isActivityComplete = result.isActivityComplete && isActivityCacheComplete+ return result}}private extension SyncService {- struct LocalSyncAggregate {- let aggregate: SyncedActivity- let generationStartedEmpty: Bool- var isReplacement = false- }-struct PendingUpload {let date: Stringlet aggregate: SyncedActivity- let generationStartedEmpty: Bool- var isReplacement = falselet hash: String}@@ -409,10 +401,8 @@ private extension SyncService {// MARK: - 上传func uploadChangedAggregates(- localByDate: [String: LocalSyncAggregate],- remoteRecords: [ActivitySyncRecord],- state: inout SyncState,- completedReplacements: inout [String: String]+ localByDate: [String: SyncedActivity],+ state: inout SyncState) async throws -> Set<String> {guard let deviceID = state.deviceID else {return []@@ -420,7 +410,7 @@ private extension SyncService {// 每个日期的 hash 是一次 JSON 编码加 SHA256, 本轮只算一次// 既用来判定"和上次一样不必上传", 也直接填进待上传项- let localHashByDate = try localByDate.mapValues { try hash(for: $0.aggregate) }+ let localHashByDate = try localByDate.mapValues { try hash(for: $0) }var confirmedDates = Set<String>()for (date, hash) in localHashByDate where state.hashByDate[date] == hash {@@ -447,10 +437,7 @@ private extension SyncService {let batchEnd = min(batchStart + Metrics.uploadBatchSize, pendingUploads.count)let batch = Array(pendingUploads[batchStart ..< batchEnd])- let result = try await processUploadBatch(batch, deviceID: deviceID, remoteRecords: remoteRecords)- for confirmation in result.confirmed where confirmation.didUpload && localByDate[confirmation.date]?.isReplacement == true {- completedReplacements[confirmation.date] = localByDate[confirmation.date]?.aggregate.generationID- }+ let result = try await processUploadBatch(batch, deviceID: deviceID)try applyConfirmedHashes(result.confirmed, to: &state)confirmedDates.formUnion(result.confirmed.map(\.date))try result.failures.checkStopping()@@ -463,39 +450,6 @@ private extension SyncService {return confirmedDates}- func preparePendingReplacements(- localByDate: [String: LocalSyncAggregate],- deviceID: String,- state: inout SyncState- ) async throws {- let replacementDates = Set(localByDate.filter(\.value.isReplacement).keys)- guard !replacementDates.isEmpty else {- return- }-- let cachedRecords = activityStore.loadCachedRecords()- let recordsToReplace = cachedRecords.filter {- $0.deviceID == deviceID && replacementDates.contains($0.date)- }- var recordIDs = Set(recordsToReplace.map {- CKRecord.ID(recordName: $0.id, zoneID: syncZoneID)- })-- for date in replacementDates {- guard let local = localByDate[date] else { continue }- try recordIDs.insert(recordID(deviceID: deviceID, date: date, generation: local.aggregate.requiredGenerationID()))- }-- try await deleteRecords(Array(recordIDs))-- for date in replacementDates {- state.hashByDate.removeValue(forKey: date)- }- try activityStore.saveCachedRecords(cachedRecords.filter {- $0.deviceID != deviceID || !replacementDates.contains($0.date)- }, state: state)- }-func deleteRecords(_ recordIDs: [CKRecord.ID]) async throws {for batchStart in stride(from: 0, to: recordIDs.count, by: Metrics.uploadBatchSize) {let batchEnd = min(batchStart + Metrics.uploadBatchSize, recordIDs.count)@@ -504,7 +458,7 @@ private extension SyncService {let result = try await database.modifyRecords(saving: [],deleting: batch,- savePolicy: .changedKeys,+ savePolicy: .ifServerRecordUnchanged,atomically: false)@@ -543,7 +497,7 @@ private extension SyncService {/// hash 由调用方一次算好传进来, 这里只做筛选func makePendingUploads(- localByDate: [String: LocalSyncAggregate],+ localByDate: [String: SyncedActivity],localHashByDate: [String: String],state: SyncState) -> [PendingUpload] {@@ -555,9 +509,7 @@ private extension SyncService {return PendingUpload(date: date,- aggregate: local.aggregate,- generationStartedEmpty: local.generationStartedEmpty,- isReplacement: local.isReplacement,+ aggregate: local,hash: hash)}@@ -570,41 +522,45 @@ private extension SyncService {case save(CKRecord)}- /// 远端已有更完整的同源聚合, 或者同日已有记录且本地不是新鲜来源时都不覆盖+ /// 只有可验证的同源日志前缀才能覆盖, 算法改变后计数减少也允许提交private func resolveUploadTarget(_ pendingRecord: PendingRecord,- deviceID: String,- remoteRecords: [ActivitySyncRecord],existingRecords: [CKRecord.ID: Result<CKRecord, any Error>]) throws -> UploadTarget {- let existing = try Self.fetchedRecord(from: existingRecords[pendingRecord.recordID])- if pendingRecord.upload.isReplacement {- return .save(existing ?? CKRecord(recordType: RecordTypes.activity, recordID: pendingRecord.recordID))+ guard let candidateCheckpoint = pendingRecord.upload.aggregate.sourceCheckpoint else {+ throw StorageCompatibilityError.incompleteSource+ }+ let candidate = pendingRecord.upload.aggregate+ let journal = HistoryStorage.eventLogURL(+ for: candidate.date,+ in: activityEventsDirectoryURL+ )+ let header = try AppServerEventJournal.header(at: journal)+ guard header.date == candidate.date, header.generationID == candidate.generationID,+ try candidateCheckpoint.matchesSource(ActivitySourceCheckpoint.read(at: journal, byteCount: candidateCheckpoint.byteCount)) else {+ throw StorageCompatibilityError.sourceConflict}+ let existing = try Self.fetchedRecord(from: existingRecords[pendingRecord.recordID])if let existing {- guard let remote = try ActivityRecordCodec.remoteDailyRecord(from: existing) else {+ guard let remote = try ActivityRecordCodec.remoteDailyRecord(from: existing),+ remote.daily.generationID == candidate.generationID,+ let checkpoint = remote.daily.sourceCheckpoint else {throw ActivitySyncError.invalidRecordIdentity}- if (remote.daily.eventCount ?? 0) > (pendingRecord.upload.aggregate.eventCount ?? 0) {+ if remote.daily.aggregationVersion > candidate.aggregationVersion || checkpoint.byteCount > candidateCheckpoint.byteCount {return .skip}+ guard try checkpoint.matchesSource(ActivitySourceCheckpoint.read(at: journal, byteCount: checkpoint.byteCount)) else {+ throw StorageCompatibilityError.sourceConflict+ }return .save(existing)}-- let hasRemoteHistory = remoteRecords.contains {- $0.deviceID == deviceID && $0.date == pendingRecord.upload.date- }- if !hasRemoteHistory || pendingRecord.upload.generationStartedEmpty {- return .save(CKRecord(recordType: RecordTypes.activity, recordID: pendingRecord.recordID))- }-- return .skip+ return .save(CKRecord(recordType: RecordTypes.activity, recordID: pendingRecord.recordID))}func processUploadBatch(_ pendingUploads: [PendingUpload],- deviceID: String,- remoteRecords: [ActivitySyncRecord]+ deviceID: String) async throws -> UploadBatchResult {let pendingRecords = try pendingUploads.map { upload intry PendingRecord(@@ -622,8 +578,6 @@ private extension SyncService {do {switch try resolveUploadTarget(pendingRecord,- deviceID: deviceID,- remoteRecords: remoteRecords,existingRecords: existingRecords) {case .skip:@@ -658,7 +612,7 @@ private extension SyncService {let result = try await database.modifyRecords(saving: records,deleting: [],- savePolicy: .changedKeys,+ savePolicy: .ifServerRecordUnchanged,atomically: false)@@ -739,25 +693,7 @@ private extension SyncService {}func rebuildCacheFromRemote() async throws {- try activityStore.removeCursorIfPresent()- let syncedRecords = try await fetchAllRemoteDailyRecords()- let retainedRecords = Self.filteredRetained(records: syncedRecords)- try activityStore.saveFetchedRecords(retainedRecords, cursor: nil)- try await establishCursorBaseline(cachedRecords: retainedRecords)- }-- func fetchAllRemoteDailyRecords() async throws -> [ActivitySyncRecord] {- let query = CKQuery(- recordType: RecordTypes.activity,- predicate: NSPredicate(format: "TRUEPREDICATE")- )- query.sortDescriptors = [- NSSortDescriptor(key: FieldKeys.deviceID, ascending: true),- NSSortDescriptor(key: FieldKeys.date, ascending: true)- ]-- let matches = try await fetchAllRecordMatches(matching: query)- return try Self.remoteDailyRecords(from: matches)+ try await applyZoneChangesToCache(since: nil, cachedRecords: [])}func fetchCurrentDeviceRecordIDsToPrune(@@ -775,17 +711,14 @@ private extension SyncService {let currentDeviceMatches = try await fetchAllRecordMatches(matching: query,- desiredKeys: [FieldKeys.date]+ desiredKeys: nil)return try currentDeviceMatches.compactMap { recordID, result inlet record = try result.get()- guard let date = record[FieldKeys.date] as? String,- HistoryStorage.isValidDateKey(date) else {- // 无法进入保留窗口比较的当前设备记录是异常数据, 一并清理- return recordID+ guard let decoded = try ActivityRecordCodec.remoteDailyRecord(from: record) else {+ throw ActivitySyncError.invalidRecordIdentity}-- return date < cutoffKey ? recordID : nil+ return decoded.date < cutoffKey ? recordID : nil}}@@ -817,28 +750,6 @@ private extension SyncService {return matches}- func establishCursorBaseline(cachedRecords: [ActivitySyncRecord]) async throws {- do {- try await applyZoneChangesToCache(- since: nil,- cachedRecords: cachedRecords- )- } catch {- // zone 已被删除时必须恢复整条同步链路, 不能仅丢弃游标后继续上传- if error is ActivitySyncError || SyncRecovery.isMissingZone(error, zoneID: syncZoneID) {- throw error- }- guard !Task.isCancelled else { return }- // 丢掉游标, 下次同步会从头拉一遍- let details = LogFields.joined(- "detail=\(error.localizedDescription)",- "action=dropCursor"- )- AppLog.sync.notice("游标基线已降级: \(details, privacy: .public)")- try? activityStore.removeCursorIfPresent()- }- }-func mergeChangedRecords(_ modificationResults: Dictionary<CKRecord.ID, Result<CKRecord, Error>>.Values,into cacheByID: inout [String: ActivitySyncRecord]@@ -931,6 +842,7 @@ private extension SyncService {guard let record = try Self.fetchedRecord(from: result[recordID]) else {return nil}+ try StorageVersion.require(ActivityRecordCodec.optionalIntValue(record[FieldKeys.version]) ?? -1, current: ActivityRecordCodec.metadataVersion, name: "CloudMetadata")guard let salt = record[FieldKeys.salt] as? Data,salt.count == Metrics.saltByteCount else {throw SyncError.missingAccountSalt@@ -942,7 +854,7 @@ private extension SyncService {let salt = try Self.randomSalt()let record = CKRecord(recordType: RecordTypes.metadata, recordID: recordID)record[FieldKeys.salt] = salt as CKRecordValue- record[FieldKeys.version] = Metrics.syncVersion as CKRecordValue+ record[FieldKeys.version] = ActivityRecordCodec.metadataVersion as CKRecordValuedo {try SyncCancellation.check(isEnabled: isEnabled)@@ -1059,14 +971,6 @@ extension SyncService {}private extension SyncService {- static func remoteDailyRecords(- from matchResults: [(CKRecord.ID, Result<CKRecord, Error>)]- ) throws -> [ActivitySyncRecord] {- try matchResults.compactMap { _, result in- try ActivityRecordCodec.remoteDailyRecord(from: result.get())- }- }-static func fetchedRecord(from result: Result<CKRecord, Error>?) throws -> CKRecord? {@@ -1137,13 +1041,13 @@ private extension SyncService {}}-/// records 包含所有设备的日聚合, 不含 sessionIds 和 turnIds+/// records 包含所有设备的日聚合, 不含 threadIDs 和 turnIds/// currentDeviceId 用于展示时替换本机云端副本, 避免重复计数nonisolated struct SyncSnapshot: Equatable {let records: [ActivitySyncRecord]let currentDeviceID: String?var tokenUsageByDate: [String: TokenUsage]?- var completedReplacements: [String: String] = [:]+ var isActivityComplete = truestatic let disabled = SyncSnapshot(records: [], currentDeviceID: nil)}diff --git a/CodexBar/Services/Sync/TokenSync.swift b/CodexBar/Services/Sync/TokenSync.swiftindex ed87dcc..0d2d20c 100644--- a/CodexBar/Services/Sync/TokenSync.swift+++ b/CodexBar/Services/Sync/TokenSync.swift@@ -22,11 +22,12 @@ actor TokenSync {return TokenHistoryBaseline(salt: cache.salt, turns: cache.turns)}- func snapshot(local: [TokenTurn], accountScopedDeviceID: String?) -> [String: TokenUsage] {- guard let cache = try? load(), cache.accountScopedDeviceID == accountScopedDeviceID else {+ func snapshot(local: [TokenTurn], accountScopedDeviceID: String?) throws -> [String: TokenUsage] {+ guard let cache = try load(), cache.accountScopedDeviceID == accountScopedDeviceID else {return TokenTurn.dailyUsage(local)}- return TokenTurn.dailyUsage(TokenTurn.pseudonymized(local, salt: cache.salt) + Array(cache.turns.values))+ let merged = try TokenTurn.merged(TokenTurn.pseudonymized(local, salt: cache.salt) + Array(cache.turns.values))+ return TokenTurn.dailyUsage(Array(merged.values))}func hasPendingUpdates(local: [TokenTurn], accountScopedDeviceID: String?) -> Bool {@@ -35,7 +36,7 @@ actor TokenSync {return records.contains { turn inlet candidate = turn.pseudonymized(salt: cache.salt)guard let remote = cache.turns[candidate.id] else { return true }- return remote.merging(candidate) != remote+ return (try? remote.merging(candidate)) != remote}}@@ -46,6 +47,9 @@ actor TokenSync {}defer { JSONFileStorage.releaseLock(lock) }try JSONFileStorage.withLock(in: directoryURL) {+ do { _ = try Self.loadCache(&fileCache) } catch is DecodingError {+ // 已知格式损坏可清除, 未知版本继续向上抛出+ }if FileManager.default.fileExists(atPath: fileCache.url.path) {try FileManager.default.removeItem(at: fileCache.url)}@@ -53,7 +57,7 @@ actor TokenSync {}}- func synchronize(local: [TokenTurn], accountScopedDeviceID: String, salt: Data, zoneID: CKRecordZone.ID) async throws {+ func synchronize(local: [TokenTurn], recoveredIDs: Set<String> = [], accountScopedDeviceID: String, salt: Data, zoneID: CKRecordZone.ID) async throws {try SyncCancellation.check(isEnabled: isEnabled)// 整轮同步共用非阻塞锁, 防止另一个进程用较早的快照覆盖游标, 界面读取不等待网络guard let lock = try JSONFileStorage.acquireLock(in: directoryURL, name: "sync.lock", nonblocking: true) else { return }@@ -76,7 +80,7 @@ actor TokenSync {}// 先落盘拉取结果, 上传失败时也能展示已经读取的其他设备贡献try save(cache)- try await upload(local: local, cache: &cache, zoneID: zoneID)+ try await upload(local: local, recoveredIDs: recoveredIDs, cache: &cache, zoneID: zoneID)try await prune(cache: &cache, zoneID: zoneID)try save(cache)}@@ -104,11 +108,18 @@ actor TokenSync {cache.cursor = try token.map { try NSKeyedArchiver.archivedData(withRootObject: $0, requiringSecureCoding: true) }}- private func upload(local: [TokenTurn], cache: inout TokenSyncCache, zoneID: CKRecordZone.ID) async throws {- let pending = TokenTurn.pseudonymized(TokenTurn.syncable(local), salt: cache.salt)+ private func upload(local: [TokenTurn], recoveredIDs: Set<String>, cache: inout TokenSyncCache, zoneID: CKRecordZone.ID) async throws {+ // 恢复结果先与本轮新鲜云端基线建立替换关系, 再执行普通条件写入+ let baseline = TokenHistoryBaseline(salt: cache.salt, turns: cache.turns)+ let candidates = local.compactMap { turn -> TokenTurn? in+ guard recoveredIDs.contains(turn.id) else { return turn }+ guard baseline.acceptsRecovery(turn) else { return nil }+ return baseline.replacement(for: turn, recovering: true) ?? turn+ }+ let pending = try TokenTurn.pseudonymized(TokenTurn.syncable(candidates), salt: cache.salt).filter { candidate inguard let remote = cache.turns[candidate.id] else { return true }- return remote.merging(candidate) != remote+ return try remote.merging(candidate) != remote}.sorted { $0.updatedAt > $1.updatedAt }let deadline = Date().addingTimeInterval(20)@@ -124,8 +135,11 @@ actor TokenSync {for candidate in batch {let id = Self.recordID(candidate.id, zoneID: zoneID)let record: CKRecord+ let remote: TokenTurn?do {- record = try fetchedRecord(existing[id]) ?? CKRecord(recordType: Self.recordType, recordID: id)+ let fetched = try fetchedRecord(existing[id])+ remote = try fetched.flatMap(Self.turn)+ record = fetched ?? CKRecord(recordType: Self.recordType, recordID: id)} catch {failures.record(error)if failures.stopping != nil {@@ -133,8 +147,7 @@ actor TokenSync {}continue}- let remote = Self.turn(from: record)- let merged = remote?.merging(candidate) ?? candidate+ let merged = try remote?.merging(candidate) ?? candidateif remote == merged {cache.turns[merged.id] = mergedcontinue@@ -152,7 +165,7 @@ actor TokenSync {for record in saving {switch result.saveResults[record.recordID] {case let .success(saved):- if let turn = Self.turn(from: saved) {+ if let turn = try Self.turn(from: saved) {cache.turns[turn.id] = turn}case let .failure(error): failures.record(error)@@ -193,26 +206,40 @@ actor TokenSync {}private func load() throws -> TokenSyncCache? {- try JSONFileStorage.withLock(in: directoryURL) {- try fileCache.load { data in- let header = try JSONLines.decoder.decode(TokenSyncCacheHeader.self, from: data)- guard header.version == TokenSyncCache.currentVersion else { throw SyncRecovery.Failure.unsupportedCacheVersion }- }+ try JSONFileStorage.withLock(in: directoryURL) { try Self.loadCache(&fileCache) }+ }++ private nonisolated static func loadCache(_ fileCache: inout TokenFileCache<TokenSyncCache>) throws -> TokenSyncCache? {+ try fileCache.load { data in+ let header = try JSONLines.decoder.decode(TokenSyncCacheHeader.self, from: data)+ guard header.version == TokenSyncCache.currentVersion else { throw SyncRecovery.Failure.unsupportedCacheVersion }}}private func save(_ cache: TokenSyncCache) throws {try JSONFileStorage.withLock(in: directoryURL) {+ var cache = cache+ cache.prune()try fileCache.save(cache)}}+ nonisolated static func pruneLocalCache(in directoryURL: URL, now: Date) throws {+ try JSONFileStorage.withLock(in: directoryURL) {+ var fileCache = TokenFileCache<TokenSyncCache>(url: directoryURL.appendingPathComponent("cache.json"))+ if var cache = try loadCache(&fileCache), cache.prune(now: now) {+ try fileCache.save(cache)+ }+ }+ }+static func recordID(_ id: String, zoneID: CKRecordZone.ID) -> CKRecord.ID {CKRecord.ID(recordName: id, zoneID: zoneID)}static func apply(_ turn: TokenTurn, to record: CKRecord) {record["version"] = currentVersion as CKRecordValue+ record["aggregationVersion"] = turn.aggregationVersion as CKRecordValuerecord["rootID"] = turn.rootID as CKRecordValuerecord["startedAt"] = turn.startedAt as CKRecordValue?record["updatedAt"] = turn.updatedAt as CKRecordValue@@ -224,31 +251,37 @@ actor TokenSync {record["usage"] = turn.usage.flatMap { try? JSONLines.stableEncoder.encode($0) } as CKRecordValue?}- static func turn(from record: CKRecord) -> TokenTurn? {- guard record.recordType == recordType, (record["version"] as? NSNumber)?.intValue == currentVersion,- let rootID = record["rootID"] as? String,- let updatedAt = record["updatedAt"] as? Date,- let generationID = record["generationID"] as? String,- let ancestors = record["ancestorIDs"] as? [String],- let checkpointData = record["checkpoint"] as? Data,- let checkpoint = try? JSONDecoder().decode([String: TokenObservationCheckpoint].self, from: checkpointData),- checkpoint.values.allSatisfy({ $0.sequence > 0 && $0.usage.isValid }),- let hasConflict = record["hasConflict"] as? NSNumber else { return nil }+ static func turn(from record: CKRecord) throws -> TokenTurn? {+ guard record.recordType == recordType else { return nil }+ try StorageVersion.require((record["version"] as? NSNumber)?.intValue ?? -1, current: currentVersion, name: "CloudTokens")+ try AggregationVersion.require((record["aggregationVersion"] as? NSNumber)?.intValue ?? -1, current: AggregationVersion.tokens, name: "Tokens")+ guard+ let rootID = record["rootID"] as? String,+ let updatedAt = record["updatedAt"] as? Date,+ let generationID = record["generationID"] as? String,+ let ancestors = record["ancestorIDs"] as? [String],+ let checkpointData = record["checkpoint"] as? Data,+ let checkpoint = try? JSONDecoder().decode([String: TokenObservationCheckpoint].self, from: checkpointData),+ checkpoint.values.allSatisfy({ $0.sequence > 0 && $0.usage.isValid }),+ let hasConflict = record["hasConflict"] as? NSNumber else { throw StorageCompatibilityError.incompleteSource }let id = record.recordID.recordName- guard isHash(id), isHash(rootID) else { return nil }+ guard isHash(id), isHash(rootID) else { throw StorageCompatibilityError.incompleteSource }var usage: TokenUsage?if let value = record["usage"] {- guard let data = value as? Data, let decoded = try? JSONDecoder().decode(TokenUsage.self, from: data), decoded.isValid else { return nil }+ guard let data = value as? Data, let decoded = try? JSONDecoder().decode(TokenUsage.self, from: data),+ decoded.isValid else { throw StorageCompatibilityError.incompleteSource }usage = decoded}+ guard usage == nil || !checkpoint.isEmpty else { throw StorageCompatibilityError.incompleteSource }if let rebuiltAt = record["rebuiltAt"], !(rebuiltAt is Date) {- return nil+ throw StorageCompatibilityError.incompleteSource}return TokenTurn(id: id, rootID: rootID, startedAt: record["startedAt"] as? Date, updatedAt: updatedAt,usage: usage, rebuiltAt: record["rebuiltAt"] as? Date,generationID: generationID, ancestorIDs: Set(ancestors),- checkpoint: checkpoint, hasConflict: hasConflict.boolValue+ checkpoint: checkpoint, hasConflict: hasConflict.boolValue,+ aggregationVersion: (record["aggregationVersion"] as? NSNumber)?.intValue ?? -1)}@@ -266,6 +299,18 @@ private nonisolated struct TokenSyncCache: Codable, Equatable {let salt: Datavar turns: [String: TokenTurn] = [:]var cursor: Data?++ @discardableResult+ mutating func prune(now: Date = Date()) -> Bool {+ let cutoff = HistoryStorage.retentionCutoffDate(today: now)+ let roots = Set(turns.values.filter { $0.updatedAt >= cutoff }.map(\.rootID))+ let retained = turns.filter { $0.value.updatedAt >= cutoff || roots.contains($0.key) }+ guard retained.count != turns.count else { return false }+ turns = retained+ // 本地先过期, 云端删除仍可能失败. 下次完整拉取让过期记录重新进入删除流程+ cursor = nil+ return true+ }}private nonisolated enum TokenSyncError: Error {diff --git a/CodexBar/Views/Menu/ActivityCard.swift b/CodexBar/Views/Menu/ActivityCard.swiftindex 735dab5..c9841c9 100644--- a/CodexBar/Views/Menu/ActivityCard.swift+++ b/CodexBar/Views/Menu/ActivityCard.swift@@ -10,6 +10,7 @@ struct ActivityCard: View {@Environment(\.mainPanelAnimationsEnabled) private var allowsAnimations@State private var frameProvider = ScreenFrameProvider()@State private var isHovered = false+ @State private var wrappedHeaderTaskIDs: Set<UUID> = []private var snapshot: ActivitySnapshot {activityMonitor.snapshot@@ -27,7 +28,7 @@ struct ActivityCard: View {presentationState.isPresented}- /// 卡片显示"暂无数据"时一并隐藏防睡眠徽标, 保持状态一致+ /// 活动源不可用时隐藏防睡眠徽标, 保持状态一致private var showsKeepAliveBadge: Bool {keepAliveController.isActivelyPreventingSleep && !showsUnavailableState}@@ -35,7 +36,7 @@ struct ActivityCard: View {// MARK: - 卡片布局var body: some View {- // 保留同一张卡片的视图身份, 空闲时只禁用交互, 避免打断内容和高度过渡+ // 连接状态提示沿用卡片容器, 无任务记录时禁止打开任务中心Button {onTaskCenterTap(frameProvider)} label: {@@ -48,6 +49,9 @@ struct ActivityCard: View {ScreenFrameReader(provider: frameProvider)}.onHover { isHovered = $0 }+ .onChange(of: retainedHeaderTaskIDs) { _, retainedIDs in+ wrappedHeaderTaskIDs.formIntersection(retainedIDs)+ }}private func card(now: Date) -> some View {@@ -90,9 +94,10 @@ struct ActivityCard: View {}private func statusRow(_ content: ActivityCardContent) -> some View {- HStack(alignment: .top, spacing: 10) {+ HStack(alignment: .firstTextBaseline, spacing: 10) {Image(systemName: content.symbolName)- .font(.system(size: 14, weight: .semibold))+ .font(.caption.weight(.semibold))+ .imageScale(.large).foregroundStyle(content.tint).frame(width: 20)@@ -120,33 +125,55 @@ struct ActivityCard: View {.padding(.top, 12).padding(.bottom, content.detail == nil ? 8 : 12).animation(.codexStatus, value: showsKeepAliveBadge)- .animation(.codexStatus, value: content.isAnonymous)// 徽标只占用标题行的宽度, 下方状态和附加信息可以使用完整文本区域.animation(.codexStatus, value: content.otherTaskCount)}private func statusHeader(_ content: ActivityCardContent) -> some View {HStack(alignment: .firstTextBaseline, spacing: 10) {- Text(content.header.joined(separator: " • "))- .font(.caption.weight(.semibold))- .foregroundStyle(Color.codexLabel)- .numericTransition(value: content.header, enabled: allowsAnimations)- .fixedSize(horizontal: false, vertical: true)- .frame(maxWidth: .infinity, alignment: .leading)- if content.isAnonymous || content.otherTaskCount > 0 || showsKeepAliveBadge {+ ActivitySummaryText(+ components: content.headerLines,+ primaryLineLimit: 1,+ primaryTruncationMode: .middle,+ supplementaryLineLimit: 1,+ singleLineWidthReserve: Metrics.headerWidthReserve,+ wrappedLayout: wrappedHeaderLayout(for: content.taskID)+ )+ // 换行锁定只属于当前任务, 新任务在首次布局时重新判断+ .id(content.taskID)+ .font(.caption.weight(.semibold))+ .foregroundStyle(Color.codexLabel)+ .numericTransition(value: content.header, enabled: allowsAnimations)+ .fixedSize(horizontal: false, vertical: true)+ .frame(maxWidth: .infinity, alignment: .leading)+ if content.otherTaskCount > 0 || showsKeepAliveBadge {statusBadges(content).fixedSize()}}}- private func statusBadges(_ content: ActivityCardContent) -> some View {- HStack(alignment: .firstTextBaseline, spacing: 10) {- if content.isAnonymous {- ActivityAnonymousIcon()- .transition(.opacity)+ private var retainedHeaderTaskIDs: Set<UUID> {+ Set(snapshot.waitingTasks.map(\.id)+ + snapshot.runningTasks.map(\.id)+ + snapshot.recentCompletions.map { $0.taskID ?? $0.id }+ + snapshot.recentTerminations.map { $0.taskID ?? $0.id })+ }++ private func wrappedHeaderLayout(for taskID: UUID?) -> Binding<Bool>? {+ guard let taskID else { return nil }+ return Binding(+ get: { wrappedHeaderTaskIDs.contains(taskID) },+ set: { isWrapped in+ if isWrapped {+ wrappedHeaderTaskIDs.insert(taskID)+ }}+ )+ }+ private func statusBadges(_ content: ActivityCardContent) -> some View {+ HStack(alignment: .firstTextBaseline, spacing: 10) {if content.otherTaskCount > 0 {Text(verbatim: "+\(content.otherTaskCount)").font(.caption2.monospacedDigit().weight(.semibold))@@ -236,11 +263,11 @@ struct ActivityCard: View {relativeText: ActivityDisplayFormat.completionRelativeText(completion.completedAt, now: now))return ActivityCardContent(+ taskID: completion.taskID ?? completion.id,symbolName: "checkmark.circle.fill",tint: .green,detail: nil,otherTaskCount: 0,- isAnonymous: completion.isAnonymous,tokenUsage: completion.tokenUsage,header: [completion.projectName ?? String(localized: "common.codex"),@@ -253,11 +280,11 @@ struct ActivityCard: View {relativeText: ActivityDisplayFormat.terminationRelativeText(termination.terminatedAt, now: now))return ActivityCardContent(+ taskID: termination.taskID ?? termination.id,symbolName: "xmark.circle.fill",tint: .red,detail: ActivityLiveLabel(termination.isFailure ? "failed" : "interrupted").text,otherTaskCount: 0,- isAnonymous: termination.isAnonymous,tokenUsage: termination.tokenUsage,header: [termination.projectName ?? String(localized: "common.codex"),@@ -268,9 +295,8 @@ struct ActivityCard: View {return ActivityCardContent(symbolName: "moon.zzz.fill",tint: .secondary,- detail: activityMonitor.sourcePresentation?.text ?? ActivityLiveLabel("idle").text,+ detail: activityMonitor.sourcePresentation?.text,otherTaskCount: 0,- isAnonymous: false,header: [String(localized: "common.codex")])}@@ -284,11 +310,11 @@ struct ActivityCard: View {) -> ActivityCardContent {let summary = ActivityDisplayFormat.liveSummaryComponents(for: task, now: timelineDate, waiting: waiting)return ActivityCardContent(+ taskID: task.id,symbolName: symbolName,tint: tint,detail: ActivityDisplayFormat.liveStatus(for: task, waiting: waiting),otherTaskCount: otherTaskCount,- isAnonymous: task.isAnonymous,tokenUsage: task.tokenUsage,header: [task.projectName ?? String(localized: "common.codex"),@@ -313,6 +339,8 @@ struct ActivityCard: View {}private enum Metrics {+ // 单行排版为时间文案增长预留宽度+ static let headerWidthReserve: CGFloat = 32static let height: CGFloat = 58static let usageHeight: CGFloat = 108static let expansionAnimation = Animation.timingCurve(0.22, 1, 0.36, 1, duration: 0.32)@@ -358,23 +386,18 @@ private struct ActivityCardButtonStyle: ButtonStyle {}private struct ActivityCardContent {+ var taskID: UUID?let symbolName: Stringlet tint: Colorlet detail: String?let otherTaskCount: Int- let isAnonymous: Boolvar tokenUsage: TokenUsage?let header: [String]var recent: String?var detailSupplement: String?-}-struct ActivityAnonymousIcon: View {- var body: some View {- Image(systemName: "person.crop.circle.dashed")- // 虚线圆形 symbol 留白较多, 适当放大以接近相邻状态图标的视觉面积- .font(.system(size: 13, weight: .semibold))- .foregroundStyle(Color.orange)- .help("activity.anonymous.keep-awake-exclusion")+ var headerLines: [String] {+ [header.first ?? "", header.dropFirst().joined(separator: " • ")]+ .filter { !$0.isEmpty }}}diff --git a/CodexBar/Views/Menu/ActivityCenterView.swift b/CodexBar/Views/Menu/ActivityCenterView.swiftindex 4d1c7fe..72e0efd 100644--- a/CodexBar/Views/Menu/ActivityCenterView.swift+++ b/CodexBar/Views/Menu/ActivityCenterView.swift@@ -264,7 +264,6 @@ struct ActivityCenterView: View {projectName: task.projectName,modelName: task.modelName,effort: task.effort,- isAnonymous: task.isAnonymous,detail: taskDetail(task, now: now, isWaiting: isWaiting),effect: isWaiting ? .ionizing(taskID: task.id) : .shimmer)@@ -277,7 +276,6 @@ struct ActivityCenterView: View {projectName: completion.projectName,modelName: completion.modelName,effort: completion.effort,- isAnonymous: completion.isAnonymous,detail: historyDetail(duration: completion.duration,relativeText: ActivityDisplayFormat.completionRelativeText(@@ -296,7 +294,6 @@ struct ActivityCenterView: View {projectName: termination.projectName,modelName: termination.modelName,effort: termination.effort,- isAnonymous: termination.isAnonymous,detail: historyDetail(duration: termination.duration,relativeText: ActivityDisplayFormat.terminationRelativeText(@@ -314,21 +311,15 @@ struct ActivityCenterView: View {projectName: String?,modelName: String?,effort: String?,- isAnonymous: Bool,detail: String,tokenUsage: TokenUsage? = nil,effect: ActivityStatusText.Effect = .none) -> some View {HStack(alignment: .top, spacing: 9) {- if isAnonymous {- ActivityAnonymousIcon()- .frame(width: Metrics.symbolWidth, height: Metrics.titleLineHeight)- } else {- Image(systemName: symbolName)- .font(.system(size: 11, weight: .semibold))- .foregroundStyle(tint)- .frame(width: Metrics.symbolWidth, height: Metrics.titleLineHeight)- }+ Image(systemName: symbolName)+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(tint)+ .frame(width: Metrics.symbolWidth, height: Metrics.titleLineHeight)VStack(alignment: .leading, spacing: 3) {titleLine(diff --git a/CodexBar/Views/Menu/ActivityStatusText.swift b/CodexBar/Views/Menu/ActivityStatusText.swiftindex 904809b..2fe80a3 100644--- a/CodexBar/Views/Menu/ActivityStatusText.swift+++ b/CodexBar/Views/Menu/ActivityStatusText.swift@@ -171,20 +171,37 @@ private struct ActivityStatusShimmer: View {/// 附加信息放不下时整体换行, 避免分隔点单独留在行首或行尾struct ActivitySummaryText: View {let components: [String]+ var primaryLineLimit: Int?+ var primaryTruncationMode: Text.TruncationMode = .tailvar supplementaryLineLimit: Int?+ var singleLineWidthReserve: CGFloat = 0+ var wrappedLayout: Binding<Bool>?var body: some View {- ViewThatFits(in: .horizontal) {- Text(components.joined(separator: " • "))- .fixedSize()- VStack(alignment: .leading, spacing: 2) {- ForEach(Array(components.enumerated()), id: \.offset) { index, component in- Text(component)- .lineLimit(index == 0 ? nil : supplementaryLineLimit)- .truncationMode(.tail)- .fixedSize(horizontal: false, vertical: true)- .frame(maxWidth: .infinity, alignment: .leading)- }+ if wrappedLayout?.wrappedValue == true {+ wrappedContent+ } else {+ ViewThatFits(in: .horizontal) {+ Text(components.joined(separator: " • "))+ .fixedSize()+ .padding(.trailing, singleLineWidthReserve)+ wrappedContent+ // 只在换行布局被选中后锁定, 不让候选布局的预先测量改变状态+ .onAppear {+ wrappedLayout?.wrappedValue = true+ }+ }+ }+ }++ private var wrappedContent: some View {+ VStack(alignment: .leading, spacing: 2) {+ ForEach(Array(components.enumerated()), id: \.offset) { index, component in+ Text(component)+ .lineLimit(index == 0 ? primaryLineLimit : supplementaryLineLimit)+ .truncationMode(index == 0 ? primaryTruncationMode : .tail)+ .fixedSize(horizontal: false, vertical: true)+ .frame(maxWidth: .infinity, alignment: .leading)}}}diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swiftindex 442b41c..503dbdb 100644--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift@@ -48,6 +48,13 @@ struct CodexStatusMenuView: View {let onResetCreditsTap: (ResetCreditsPanelContext) -> Voidlet onActivityCenterTap: (ActivityCenterPanelContext) -> Void@EnvironmentObject private var appUpdater: AppUpdater+ @State private var activitySectionVisibility: Bool?++ private var showsActivitySection: Bool {+ // 订阅建立前直接读取当前状态, 避免首次打开时先显示空卡片再收回+ activitySectionVisibility+ ?? (activityMonitor.snapshot.hasTaskCenterContent || !activityMonitor.isActivitySourceHealthy)+ }var body: some View {VStack(alignment: .leading, spacing: Metrics.verticalSpacing) {@@ -68,6 +75,16 @@ struct CodexStatusMenuView: View {.animation(Metrics.statusAnimation, value: syncSettings.isEnabled).animation(Metrics.statusAnimation, value: syncSettings.isSyncing).animation(Metrics.statusAnimation, value: syncSettings.hasSyncFailure)+ .animation(+ mainPanelSettings.areAnimationsEnabled ? Metrics.activityExpansionAnimation : nil,+ value: showsActivitySection+ )+ .onReceive(+ activityMonitor.$snapshot+ .combineLatest(activityMonitor.$isActivitySourceHealthy)+ .map { snapshot, isHealthy in snapshot.hasTaskCenterContent || !isHealthy }+ .removeDuplicates()+ ) { activitySectionVisibility = $0 }.transaction { transaction in// 已关闭的 NSPopover 仍可能绘制数字过渡, 让字体缓存逐轮增长guard !animationState.allowsAnimations else {@@ -85,15 +102,22 @@ private extension CodexStatusMenuView {static let surfaceCornerRadius: CGFloat = 14static let verticalSpacing: CGFloat = 10static let statusAnimation = Animation.codexStatus+ static let activityExpansionAnimation = Animation.timingCurve(0.22, 1, 0.36, 1, duration: 0.32)}@ViewBuildervar content: some View {- let visibleSections = mainPanelSettings.layout.visibleSections+ let visibleSections = mainPanelSettings.layout.visibleSections.filter { section in+ section != .activity || showsActivitySection+ }let dataPlaceholderSection = dataPlaceholderSection(in: visibleSections)ForEach(visibleSections) { section insectionView(section, dataPlaceholderSection: dataPlaceholderSection)+ .transition(section == .activity ? .modifier(+ active: ActivitySectionReveal(progress: 0),+ identity: ActivitySectionReveal(progress: 1)+ ) : .opacity)}if !hasRenderableContent(@@ -182,7 +206,6 @@ private extension CodexStatusMenuView {UsageSummaryView(usage: viewModel.snapshot?.usage,history: historyViewModel.snapshot,- showsActivity: true,isStale: viewModel.snapshot?.isUsageStale ?? false,onHoverContextChange: onUsageHeatmapHoverChange)@@ -258,3 +281,39 @@ private extension CodexStatusMenuView {)}}++private struct ActivitySectionReveal: AnimatableModifier {+ var progress: CGFloat++ var animatableData: CGFloat {+ get { progress }+ set { progress = newValue }+ }++ func body(content: Content) -> some View {+ ActivitySectionRevealLayout(progress: progress) {+ content+ }+ // 完全展开后为玻璃表面的外投影留出空间, 不裁掉边缘高光和阴影+ .clipShape(Rectangle().inset(by: progress < 1 ? 0 : -64))+ }+}++private struct ActivitySectionRevealLayout: Layout {+ var progress: CGFloat++ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache _: inout ()) -> CGSize {+ guard let subview = subviews.first else { return .zero }+ let size = subview.sizeThatFits(ProposedViewSize(width: proposal.width, height: nil))+ return CGSize(width: size.width, height: size.height * min(1, max(0, progress)))+ }++ func placeSubviews(in bounds: CGRect, proposal _: ProposedViewSize, subviews: Subviews, cache _: inout ()) {+ // 保留内容的自然高度, 只改变裁剪区域, 避免展开和收回时压缩文字+ subviews.first?.place(+ at: bounds.origin,+ anchor: .topLeading,+ proposal: ProposedViewSize(width: bounds.width, height: nil)+ )+ }+}diff --git a/CodexBar/Views/Menu/HeatmapDetailView.swift b/CodexBar/Views/Menu/HeatmapDetailView.swiftindex 6698a5c..42fc974 100644--- a/CodexBar/Views/Menu/HeatmapDetailView.swift+++ b/CodexBar/Views/Menu/HeatmapDetailView.swift@@ -5,9 +5,10 @@ struct HeatmapDetailView: View {@Environment(\.colorScheme) private var colorSchemevar body: some View {- let panelSize = Self.panelSize(showsActivity: context.showsActivity)+ let panelSize = Self.panelSize- detailContent+ activityContent+ .markStale(context.isStale).padding(.horizontal, Metrics.horizontalPadding).padding(.vertical, Metrics.verticalPadding).frame(@@ -23,20 +24,8 @@ struct HeatmapDetailView: View {Metrics.cornerRadius}- static func panelSize(showsActivity: Bool) -> CGSize {- CGSize(- width: showsActivity ? Metrics.activityPanelWidth : Metrics.panelWidth,- height: showsActivity ? Metrics.activityPanelHeight : Metrics.tokenPanelHeight- )- }-- @ViewBuilder- private var detailContent: some View {- if context.showsActivity {- activityContent- } else {- tokenOnlyContent- }+ static var panelSize: CGSize {+ CGSize(width: Metrics.activityPanelWidth, height: Metrics.activityPanelHeight)}private var header: some View {@@ -131,17 +120,6 @@ struct HeatmapDetailView: View {}}- private var tokenOnlyContent: some View {- VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {- header-- LiquidGlassDivider()- .opacity(0.62)-- tokenIntensityMetricRow- }- }-private var tokenIntensityMetricRow: some View {tokenIntensityStrip.frame(maxWidth: .infinity)@@ -186,7 +164,7 @@ struct HeatmapDetailView: View {[ActivityMetricRow(label: String(localized: "history.metric.sessions"),- value: context.day.history.sessionCount,+ value: context.day.history.threadCount,tint: .green),ActivityMetricRow(@@ -277,14 +255,15 @@ struct HeatmapDetailView: View {}private func metricRow(_ row: ActivityMetricRow) -> some View {- metricRowLayout {+ let count = row.value ?? 0+ return metricRowLayout {metricDot(tint: row.tint)Text(row.label).foregroundStyle(.secondary).fixedSize(horizontal: true, vertical: false).frame(height: Metrics.metricRowHeight)- fittingMetricValue("\(row.value)", comparison: Double(row.value))+ fittingMetricValue(String(count), comparison: Double(count))}}@@ -325,7 +304,7 @@ struct HeatmapDetailView: View {private struct ActivityMetricRow: Identifiable {let label: String- let value: Int+ let value: Int?let tint: Colorvar id: String {@@ -334,12 +313,10 @@ struct HeatmapDetailView: View {}private enum Metrics {- static let panelWidth: CGFloat = 212static let activityPanelWidth: CGFloat = 360static let activityPanelHeight: CGFloat = 232static let columnSpacing: CGFloat = 12static let columnHeight: CGFloat = 150- static let tokenPanelHeight: CGFloat = 84static let sectionSpacing: CGFloat = 8static let horizontalPadding: CGFloat = 12static let verticalPadding: CGFloat = 10diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swiftindex c5393d9..cd3f38b 100644--- a/CodexBar/Views/Menu/UsageHeatmap.swift+++ b/CodexBar/Views/Menu/UsageHeatmap.swift@@ -4,7 +4,7 @@ import SwiftUI/// hover 详情面板需要的完整上下文, 包括屏幕坐标和峰值 tokennonisolated struct UsageHeatmapHoverContext: Equatable {let day: UsageHeatmapDay- let showsActivity: Bool+ let isStale: Boollet alignmentScreenFrame: CGRect?let preferredSide: UsageHeatmapDetailSidelet peakTokens: Intdiff --git a/CodexBar/Views/Menu/UsageSummaryView.swift b/CodexBar/Views/Menu/UsageSummaryView.swiftindex 522f671..d5c8e70 100644--- a/CodexBar/Views/Menu/UsageSummaryView.swift+++ b/CodexBar/Views/Menu/UsageSummaryView.swift@@ -7,7 +7,6 @@ struct UsageSummaryView: View {@Environment(\.mainPanelAnimationsEnabled) private var allowsAnimationslet usage: CodexUsageSnapshot?let isStale: Bool- let showsActivity: Boollet onHoverContextChange: (UsageHeatmapHoverContext?) -> Voidprivate let days: [UsageHeatmapDay?]private let peakTokens: Int@@ -17,19 +16,16 @@ struct UsageSummaryView: View {init(usage: CodexUsageSnapshot?,history: HistorySnapshot,- showsActivity: Bool,isStale: Bool = false,onHoverContextChange: @escaping (UsageHeatmapHoverContext?) -> Void = { _ in }) {self.usage = usageself.isStale = isStale- self.showsActivity = showsActivityself.onHoverContextChange = onHoverContextChangelet days = UsageHeatmapDay.grid(usage: usage,history: history,- showsActivity: showsActivity,columnCount: UsageHeatmap.Metrics.columnCount,today: Date())@@ -58,30 +54,17 @@ struct UsageSummaryView: View {.animation(allowsAnimations ? Metrics.statusAnimation : nil, value: days)}- @ViewBuilderprivate var content: some View {- if usage?.hasAppServerData == true || showsActivity {- VStack(alignment: .leading, spacing: 8) {- metricsGrid-- if usage?.hasDailyUsageBuckets == true || showsActivity {- UsageHeatmap(- days: days,- selection: $hoverSelection,- peakTokens: peakTokens,- onScreenFrameChange: { frame in- heatmapScreenFrame = frame- }- )- } else {- dailyUsageUnavailable+ VStack(alignment: .leading, spacing: 8) {+ metricsGrid+ UsageHeatmap(+ days: days,+ selection: $hoverSelection,+ peakTokens: peakTokens,+ onScreenFrameChange: { frame in+ heatmapScreenFrame = frame}- }- } else {- Text("common.empty.no-data")- .foregroundStyle(.secondary)- .frame(maxWidth: .infinity, alignment: .center)- .padding(.vertical, MenuMetrics.loadingVerticalPadding)+ )}}@@ -117,14 +100,6 @@ struct UsageSummaryView: View {}}- private var dailyUsageUnavailable: some View {- Text("usage.heatmap.no-data")- .font(.caption)- .foregroundStyle(.secondary)- .frame(maxWidth: .infinity, alignment: .center)- .frame(height: UsageHeatmap.Metrics.height)- }-private func textMetric(label: LocalizedStringResource, value: String) -> some View {metric(label: label) {Text(value)@@ -178,7 +153,7 @@ struct UsageSummaryView: View {hoverSelection.map {UsageHeatmapHoverContext(day: $0.day,- showsActivity: showsActivity,+ isStale: isStale,alignmentScreenFrame: heatmapScreenFrame,preferredSide: UsageHeatmap.Metrics.preferredDetailSide(for: $0.column),peakTokens: peakTokensdiff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex 3f3b955..28c0fc5 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -1,4 +1,5 @@import AppKit+import ServiceManagementimport SwiftUI/// 设置窗口根视图, 按通用、高级和关于分页汇总设置与版本信息@@ -83,6 +84,7 @@ struct AppSettingsView: View {refreshStatusRows()}.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in+ loginItemSettings.refresh()syncSettings.refresh()menuBarQuotaSettings.refresh()mainPanelSettings.refresh()@@ -91,6 +93,7 @@ struct AppSettingsView: View {refreshStatusRows()}.onReceive(NotificationCenter.default.publisher(for: .settingsWindowDidOpen)) { _ in+ loginItemSettings.refresh()selectedRebuildRange = nilisShowingRebuildConfirmation = falsehelperFeatureConfirmation = nil@@ -255,27 +258,23 @@ private extension AppSettingsView {}var generalSettingsPage: some View {- VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {- VStack(alignment: .leading, spacing: Metrics.rowSpacing) {- mainPanelLayoutRow- LiquidGlassDivider()- notificationRow- LiquidGlassDivider()- MainPanelAnimationsSettingsRow(settings: mainPanelSettings)- LiquidGlassDivider()- launchAtLoginRow- LiquidGlassDivider()- automaticUpdateCheckRow- LiquidGlassDivider()- menuBarQuotaRow- LiquidGlassDivider()- hotKeyRow- }- .padding(Metrics.panelPadding)- .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius)-- settingsErrorPanel+ VStack(alignment: .leading, spacing: Metrics.rowSpacing) {+ mainPanelLayoutRow+ LiquidGlassDivider()+ notificationRow+ LiquidGlassDivider()+ MainPanelAnimationsSettingsRow(settings: mainPanelSettings)+ LiquidGlassDivider()+ launchAtLoginRow+ LiquidGlassDivider()+ automaticUpdateCheckRow+ LiquidGlassDivider()+ menuBarQuotaRow+ LiquidGlassDivider()+ hotKeyRow}+ .padding(Metrics.panelPadding)+ .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius)}var advancedSettingsPage: some View {@@ -326,14 +325,25 @@ private extension AppSettingsView {// MARK: - 通用页各行var launchAtLoginRow: some View {- SettingsToggleRow(- icon: "power",- title: "settings.general.launch-at-login",- isOn: Binding(- get: { loginItemSettings.isEnabled },- set: { loginItemSettings.setEnabled($0) }+ VStack(alignment: .leading, spacing: 4) {+ SettingsToggleRow(+ icon: "power",+ title: "settings.general.launch-at-login",+ isOn: Binding(+ get: { loginItemSettings.isEnabled },+ set: { loginItemSettings.setEnabled($0) }+ ))- )++ if loginItemSettings.requiresApproval {+ settingsStatusCaptionRow(SettingsStatusCaption(+ message: String(localized: "settings.general.launch-at-login-authorization-required"),+ showsSystemSettingsButton: true+ ))+ } else if let message = loginItemSettings.errorMessage {+ SettingsCaptionMessageRow(message: message)+ }+ }}var automaticUpdateCheckRow: some View {@@ -577,7 +587,7 @@ private extension AppSettingsView {if caption.showsSystemSettingsButton {Button("common.action.open-system-settings") {- keepAliveController.openSystemSettings()+ SMAppService.openSystemSettingsLoginItems()}.controlSize(.small).fixedSize()@@ -830,7 +840,7 @@ private extension AppSettingsView {if !summary.failedRequestDateKeys.isEmpty {message += String(localized: "history.rebuild.summary.request-failed")}- if summary.isSyncReplacementPending {+ if summary.isSyncPending {message += String(localized: "history.rebuild.summary.cloud-replacement-pending")}@@ -929,7 +939,6 @@ private extension AppSettingsView {connectionInfo: statusViewModel.codexConnectionInfo,isReconnecting: statusViewModel.isReconnecting,isBusy: statusViewModel.isRefreshing || statusViewModel.isReconnecting || codexVersions.isRefreshing,- errorMessage: statusViewModel.connectionErrorMessage,onReconnect: {Task { @MainActor inawait statusViewModel.reconnectCodex()@@ -966,19 +975,6 @@ private extension AppSettingsView {statusViewModel.refreshCodexConnectionInfo()}- @ViewBuilder- var settingsErrorPanel: some View {- if let message = loginItemSettings.errorMessage {- Text(message)- .font(.caption)- .foregroundStyle(.red)- .fixedSize(horizontal: false, vertical: true)- .frame(maxWidth: .infinity, alignment: .leading)- .padding(Metrics.panelPadding)- .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius)- }- }-var checkUpdateButton: some View {Button {appUpdater.checkForUpdates()diff --git a/CodexBar/Views/Settings/CodexVersionSection.swift b/CodexBar/Views/Settings/CodexVersionSection.swiftindex a67dc4f..e04c638 100644--- a/CodexBar/Views/Settings/CodexVersionSection.swift+++ b/CodexBar/Views/Settings/CodexVersionSection.swift@@ -8,7 +8,6 @@ struct CodexVersionSection: View {let connectionInfo: CodexServerConnectionInfo?let isReconnecting: Boollet isBusy: Bool- let errorMessage: String?let onReconnect: () -> Void@State private var copiedPathResetTasks: [String: Task<Void, Never>] = [:]@@ -34,13 +33,6 @@ struct CodexVersionSection: View {}}.padding(.leading, Metrics.childIndent)-- if let message = errorMessage {- Text(message)- .font(.caption)- .foregroundStyle(.red)- .fixedSize(horizontal: false, vertical: true)- }}.onDisappear {copiedPathResetTasks.values.forEach { $0.cancel() }diff --git a/CodexBarHelper/app.zabrian.codexbar.helper.debug.plist b/CodexBarHelper/app.zabrian.codexbar.helper.debug.plistindex e509b3d..f6220ab 100644--- a/CodexBarHelper/app.zabrian.codexbar.helper.debug.plist+++ b/CodexBarHelper/app.zabrian.codexbar.helper.debug.plist@@ -4,7 +4,7 @@<dict><key>AssociatedBundleIdentifiers</key><array>- <string>app.zabrian.codexbar.debug</string>+ <string>app.zabrian.codexbar.helper-manager.debug</string></array><key>BundleProgram</key><string>Contents/Resources/CodexBarHelper</string>diff --git a/CodexBarHelper/app.zabrian.codexbar.helper.plist b/CodexBarHelper/app.zabrian.codexbar.helper.plistindex 0eb2aa5..024d63f 100644--- a/CodexBarHelper/app.zabrian.codexbar.helper.plist+++ b/CodexBarHelper/app.zabrian.codexbar.helper.plist@@ -4,7 +4,7 @@<dict><key>AssociatedBundleIdentifiers</key><array>- <string>app.zabrian.codexbar</string>+ <string>app.zabrian.codexbar.helper-manager</string></array><key>BundleProgram</key><string>Contents/Resources/CodexBarHelper</string>diff --git a/CodexBarHelperManager/ManagerMain.swift b/CodexBarHelperManager/ManagerMain.swiftnew file mode 100644index 0000000..ba0d9e2--- /dev/null+++ b/CodexBarHelperManager/ManagerMain.swift@@ -0,0 +1,35 @@+import Foundation+import ServiceManagement++@main+enum HelperManagerMain {+ static func main() async {+ let arguments = CommandLine.arguments+ guard arguments.count == 2,+ let command = HelperManagement.Command(rawValue: arguments[1]) else {+ return+ }+ let service = SMAppService.daemon(plistName: CodexBarHelperIPC.daemonPlistName)+ var failure: NSError?+ do {+ switch command {+ case .status:+ break+ case .register:+ try service.register()+ case .unregister:+ try await service.unregister()+ }+ } catch {+ failure = error as NSError+ }+ let reply = HelperManagement.Reply(+ status: service.status.rawValue,+ errorDomain: failure?.domain,+ errorCode: failure?.code+ )+ if let data = try? JSONEncoder().encode(reply) {+ FileHandle.standardOutput.write(data)+ }+ }+}diff --git a/CodexBarHelperManager/Resources/AppIcon.icon/Assets/CodexBar Helper.png b/CodexBarHelperManager/Resources/AppIcon.icon/Assets/CodexBar Helper.pngnew file mode 100644index 0000000..0d3ce5fBinary files /dev/null and b/CodexBarHelperManager/Resources/AppIcon.icon/Assets/CodexBar Helper.png differdiff --git a/CodexBarHelperManager/Resources/AppIcon.icon/icon.json b/CodexBarHelperManager/Resources/AppIcon.icon/icon.jsonnew file mode 100644index 0000000..f1b3634--- /dev/null+++ b/CodexBarHelperManager/Resources/AppIcon.icon/icon.json@@ -0,0 +1,26 @@+{+ "fill" : "automatic",+ "groups" : [+ {+ "layers" : [+ {+ "image-name" : "CodexBar Helper.png",+ "name" : "CodexBar Helper"+ }+ ],+ "shadow" : {+ "kind" : "neutral",+ "opacity" : 0.5+ },+ "translucency" : {+ "enabled" : true,+ "value" : 0.3+ }+ }+ ],+ "supported-platforms" : {+ "squares" : [+ "macOS"+ ]+ }+}\ No newline at end of filediff --git a/CodexBarTests/Activity/ActivityArchitectureTests.swift b/CodexBarTests/Activity/ActivityArchitectureTests.swiftnew file mode 100644index 0000000..f5eece2--- /dev/null+++ b/CodexBarTests/Activity/ActivityArchitectureTests.swift@@ -0,0 +1,316 @@+import Foundation+import Testing++struct ActivityArchitectureTests {+ @Test(arguments: [false, true])+ func currentTurnSurvivesPreviousTurnsMillisecondProgress(snapshot: Bool) throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = makeMonitor(directory, preferences)+ defer { monitor.stop() }+ let now = Date(timeIntervalSince1970: floor(Date().timeIntervalSince1970) - 5)+ monitor.consume(.live([TestFixtures.event(at: now.addingTimeInterval(-10))]))+ monitor.consume(.live([TestFixtures.event(.toolCompleted, at: now.addingTimeInterval(0.1))]))+ let event = TestFixtures.event(at: now, turn: "turn-b")+ monitor.consume(snapshot ? .snapshotEvents([event]) : .live([event]))+ let old = ActivityTaskKey(thread: "thread-a", turn: "turn-a")+ let current = ActivityTaskKey(thread: "thread-a", turn: "turn-b")+ let id = try #require(monitor.tasks[current]?.displayID)+ #expect(monitor.tasks[old] == nil)+ #expect(monitor.pendingTerminalTasks[old] != nil)+ monitor.consume(.snapshotEvents([event, TestFixtures.event(at: now)]))+ #expect(monitor.tasks[current]?.displayID == id)+ #expect(monitor.tasks.count == 1)+ monitor.consume(.live([TestFixtures.event(.turnCompleted, at: now.addingTimeInterval(1))]))+ #expect(monitor.pendingTerminalTasks.isEmpty)+ #expect(monitor.completions.count == 1)+ #expect(monitor.terminations.isEmpty)+ monitor.consume(.live([TestFixtures.event(.turnCompleted, at: now.addingTimeInterval(2), turn: "turn-b")]))+ monitor.consume(.snapshotEvents([event]))+ #expect(monitor.tasks.isEmpty)+ }++ @Test func creationNoticeUpdatesRootWithoutInventingExecution() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = makeMonitor(directory, preferences)+ defer { monitor.stop() }+ let now = Date()+ monitor.consume(.snapshotEvents([TestFixtures.event(at: now)]))+ var event = ActivityRecord(+ timestamp: now.addingTimeInterval(1), name: ActivityEventKind.subagentStarted.rawValue, origin: .main,+ cwd: "/child-project", toolName: nil, model: "child-model", effort: "low",+ threadID: "thread-a", turnID: nil, agentID: "child"+ )+ event.context = ActivityContext(+ method: "item/completed", threadID: "thread-a", turnID: "turn-a",+ rootThreadID: "thread-a", rootTurnID: "turn-a", agentThreadID: "child", itemKind: "started"+ )+ monitor.consume(.live([event]))+ let task = try #require(monitor.tasks[.init(thread: "thread-a", turn: "turn-a")])+ #expect(task.modelName == "gpt-5")+ #expect(task.projectName == "example")+ #expect(task.effort == "mixed")+ #expect(task.executions.keys.allSatisfy { $0.agentID == nil })+ #expect(task.subagentsByID["child"]?.isRunning == true)+ }++ @Test func authoritativeChildrenRecoverCountWithoutObservedStarts() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = makeMonitor(directory, preferences)+ defer { monitor.stop() }+ let now = Date()+ monitor.consume(.snapshotEvents([TestFixtures.event(at: now)]))+ let key = ActivityTaskKey(thread: "thread-a", turn: "turn-a")+ #expect(monitor.tasks[key]?.snapshot.activeSubagentCount == nil)+ let root = state("thread-a", at: now)+ apply([root], to: monitor)+ #expect(monitor.tasks[key]?.snapshot.activeSubagentCount == 0)+ monitor.tasks[key]?.recordSubagentActivity(agentID: "finished", isStarting: false, at: now)+ #expect(monitor.tasks[key]?.snapshot.activeSubagentCount == nil)+ let finished = state("finished", at: now, parent: "thread-a", terminal: .completed(at: now, duration: 1))+ let active = state("active", at: now, parent: "thread-a")+ apply([root, finished, active], to: monitor)+ #expect(monitor.tasks[key]?.snapshot.activeSubagentCount == 1)+ var unavailable = active+ unavailable.readStatus = .unavailable+ apply([root, finished, unavailable], to: monitor)+ #expect(monitor.tasks[key]?.snapshot.activeSubagentCount == nil)+ apply([root, finished, active], to: monitor)+ #expect(monitor.tasks[key]?.snapshot.activeSubagentCount == 1)+ apply([root, finished], to: monitor)+ #expect(monitor.tasks[key]?.snapshot.activeSubagentCount == nil)+ let ended = state("active", at: now.addingTimeInterval(1), parent: "thread-a", terminal: .completed(at: now.addingTimeInterval(1), duration: 1))+ apply([root, finished, ended], to: monitor)+ #expect(monitor.tasks[key]?.snapshot.activeSubagentCount == 0)+ }++ @Test func unresolvedAncestryKeepsCountUnknownUntilOwnershipRecovers() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = makeMonitor(directory, preferences)+ defer { monitor.stop() }+ let now = Date()+ monitor.consume(.snapshotEvents([TestFixtures.event(at: now)]))+ let root = ActivityTurnReference(threadID: "thread-a", turnID: "turn-a")+ let child = ActivityTurnReference(threadID: "child", turnID: "turn-a")+ let grandchild = ActivityTurnReference(threadID: "grandchild", turnID: "turn-a")+ let cache = SessionLifecycleCache()+ var states = [root: state("thread-a", at: now), child: state("child", at: now, parent: "thread-a"), grandchild: state("grandchild", at: now, parent: "child")]+ for reference in [child, grandchild] {+ states[reference]?.rootThreadID = nil+ states[reference]?.rootTurnID = nil+ }+ let verified = Dictionary(uniqueKeysWithValues: states.keys.map { ($0, now) })+ await cache.replace(states, verifiedTurns: verified)+ let incomplete = await cache.lifecycleStates(for: [root], now: now)+ #expect(incomplete.count == 3)+ apply(incomplete, to: monitor)+ let key = ActivityTaskKey(thread: "thread-a", turn: "turn-a")+ #expect(monitor.tasks[key]?.snapshot.activeSubagentCount == nil)+ for reference in [child, grandchild] {+ states[reference]?.rootThreadID = "thread-a"+ states[reference]?.rootTurnID = "turn-a"+ }+ await cache.replace(states, verifiedTurns: verified)+ await apply(cache.lifecycleStates(for: [root], now: now), to: monitor)+ #expect(monitor.tasks[key]?.snapshot.activeSubagentCount == 2)+ let unidentified = TestFixtures.event(.toolStarted, at: now, origin: .auxiliary)+ monitor.tasks[key]?.recordExecutionEvent(unidentified)+ await apply(cache.lifecycleStates(for: [root], now: now), to: monitor)+ #expect(monitor.tasks[key]?.snapshot.activeSubagentCount == nil)+ }++ @Test func cacheReconciliationIncludesEveryRetainedTaskWithoutDelay() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = makeMonitor(directory, preferences)+ defer { monitor.stop() }+ let now = Date()+ var transitions: [ActivityTransition] = []+ var terminalStates: [ActivityTurnReference: SessionLifecycleState] = [:]+ for index in 0 ..< 20 {+ let event = TestFixtures.event(at: now, thread: "session-\(index)")+ let key = try #require(ActivityTaskKey(event: event))+ let task = ActivityTask(displayID: UUID(), key: key, event: event, state: .running, startedAt: now, progressGeneration: 1)+ monitor.resolveTerminal(.completed(at: now, duration: 1), task: task, key: key, abortFallback: now, into: &transitions)+ let reference = task.turnReference+ var lifecycle = state(reference.threadID, at: now, terminal: .completed(at: now, duration: 1))+ lifecycle.rootThreadID = reference.threadID+ terminalStates[reference] = lifecycle+ let pendingEvent = TestFixtures.event(at: now, thread: "pending-\(index)")+ let pendingKey = try #require(ActivityTaskKey(event: pendingEvent))+ let pending = ActivityTask(displayID: UUID(), key: pendingKey, event: pendingEvent, state: .running, startedAt: now, progressGeneration: 1)+ monitor.pendingTerminalTasks[pendingKey] = PendingTerminalTask(task: pending, supersededAt: now)+ }+ let cache = SessionLifecycleCache()+ await cache.replace(terminalStates, verifiedTurns: [:])+ #expect(monitor.lifecycleReferences().count == 40)+ #expect(await !monitor.applyTerminalTokenUsage(cache.lifecycleStates(for: monitor.lifecycleReferences())))+ for reference in terminalStates.keys {+ terminalStates[reference]?.tokenUsage = TokenUsage(+ inputTokens: 100, cachedInputTokens: 0, cacheWriteInputTokens: 0,+ outputTokens: 0, reasoningOutputTokens: 0, totalTokens: 100+ )+ }+ await cache.replace(terminalStates, verifiedTurns: [:])+ #expect(monitor.lifecycleReferences().count == 40)+ #expect(await monitor.applyTerminalTokenUsage(cache.lifecycleStates(for: monitor.lifecycleReferences())))+ #expect(monitor.completions.count == 20)+ #expect(monitor.completions.allSatisfy { $0.tokenUsage?.totalTokens == 100 })+ }++ @Test(arguments: [false, true], [nil, "read", "search"] as [String?])+ func approvalUsesRequestActionsWithoutInferringFromTool(cachedTool: Bool, action: String?) throws {+ let now = Date()+ var reducer = AppServerActivityReducer()+ let thread = try mainThread()+ _ = reducer.reconcile(thread: thread, turns: [ActivityTurn(id: "turn", status: .running)], now: now)+ if cachedTool {+ let started = try TestFixtures.decode(ActivityInput.self, """+ {"method":"item/started","params":{"threadId":"main","turnId":"turn",+ "item":{"id":"item","type":"commandExecution","commandActions":[{"type":"read"}]}}}+ """)+ _ = reducer.consume(started, now: now)+ }+ let actions = action.map { "[{\"type\":\"\($0)\"}]" } ?? "null"+ let request = try TestFixtures.decode(ActivityInput.self, """+ {"id":1,"method":"item/commandExecution/requestApproval","params":{+ "threadId":"main","turnId":"turn","itemId":"item","startedAtMs":1000,"commandActions":\(actions)}}+ """)+ let event = try #require(reducer.consume(request, now: now).first)+ #expect(event.commandActionTypes == action.map { [$0] })+ #expect(event.context?.itemType == "commandExecution")+ #expect(reducer.states.values.first?.pendingApprovals.values.first?.commandActionTypes == action.map { [$0] })+ let stored = try #require(AppServerEventRecord.decode(from: AppServerEventRecord(activity: event).jsonLineData()).activity)+ #expect(stored.commandActionTypes == event.commandActionTypes)+ }++ @Test(arguments: [false, true])+ func unknownStartRemainsUnknownUntilServerBackfill(snapshot: Bool) throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = makeMonitor(directory, preferences)+ defer { monitor.stop() }+ let now = Date(timeIntervalSince1970: floor(Date().timeIntervalSince1970))+ var reducer = AppServerActivityReducer()+ let thread = try mainThread()+ let initial = reducer.reconcile(thread: thread, turns: [ActivityTurn(id: "turn", status: .running)], now: now)+ if snapshot {+ monitor.consume(.snapshotEvents(initial))+ } else {+ let started = try TestFixtures.decode(ActivityInput.self, """+ {"method":"turn/started","params":{"threadId":"main","turn":{"id":"turn","status":"inProgress","startedAt":null}}}+ """)+ monitor.consume(.live(reducer.consume(started, now: now)))+ }+ let key = ActivityTaskKey(thread: "main", turn: "turn")+ var task = try #require(monitor.tasks[key])+ let displayID = task.displayID+ #expect(task.startedAt == nil)+ #expect(task.preciseDuration(until: now) == nil)+ let startedAt = now.addingTimeInterval(-60)+ let corrected = ActivityTurn(id: "turn", status: .running, startedAt: startedAt)+ _ = reducer.reconcile(thread: thread, turns: [corrected], now: now)+ let state = try #require(reducer.states.values.first)+ #expect(ActivityMonitor.mergeLifecycleBackfill(from: state, into: &task))+ #expect(task.startedAt == startedAt)+ #expect(task.preciseDuration(until: now) == 60)+ #expect(task.displayID == displayID)+ monitor.tasks[key] = task+ monitor.consume(.snapshotEvents(reducer.reconcile(+ thread: thread, turns: [ActivityTurn(id: "turn", status: .running)], now: now, bootstrap: true+ )))+ #expect(monitor.tasks[key]?.startedAt == startedAt)+ }++ @Test(arguments: ["completed", "failed", "interrupted"], [+ (snapshot: false, timestamps: false), (snapshot: false, timestamps: true),+ (snapshot: true, timestamps: false), (snapshot: true, timestamps: true)+ ])+ func terminalUsesServerDurationForLiveAndSnapshot(status: String, scenario: (snapshot: Bool, timestamps: Bool)) throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = makeMonitor(directory, preferences)+ defer { monitor.stop() }+ let now = Date(timeIntervalSince1970: floor(Date().timeIntervalSince1970))+ var reducer = AppServerActivityReducer()+ let thread = try mainThread()+ let key = ActivityTaskKey(thread: "main", turn: "turn")+ let active = ActivityTurn(id: "turn", status: .running)+ monitor.consume(.snapshotEvents(reducer.reconcile(thread: thread, turns: [active], now: now)))+ let terminal = ActivityTurn(+ id: "turn",+ status: ActivityTurnStatus(rawValue: status) ?? .unknown,+ startedAt: scenario.timestamps ? now.addingTimeInterval(-2) : nil,+ completedAt: scenario.timestamps ? now : nil,+ duration: 1.5+ )+ if scenario.snapshot {+ _ = reducer.reconcile(thread: thread, turns: [terminal], now: now)+ // 后续快照缺少时间字段时保留已经确认的终态时间和耗时+ _ = reducer.reconcile(thread: thread, turns: [ActivityTurn(id: "turn", status: ActivityTurnStatus(rawValue: status) ?? .unknown)], now: now)+ let lifecycle = try #require(reducer.states.values.first)+ var task = try #require(monitor.tasks[key])+ _ = ActivityMonitor.mergeLifecycleBackfill(from: lifecycle, into: &task)+ var transitions: [ActivityTransition] = []+ try monitor.resolveTerminal(#require(lifecycle.terminal), task: task, key: key, abortFallback: now, into: &transitions)+ } else {+ let start = terminal.startedAt.map { String($0.timeIntervalSince1970) } ?? "null"+ let end = terminal.completedAt.map { String($0.timeIntervalSince1970) } ?? "null"+ let completed = try TestFixtures.decode(ActivityInput.self, """+ {"method":"turn/completed","params":{"threadId":"main","turn":{"id":"turn","status":"\(status)",+ "startedAt":\(start),"completedAt":\(end),"durationMs":1500}}}+ """)+ monitor.consume(.live(reducer.consume(completed, now: now)))+ }+ if status == "completed" {+ #expect(monitor.completions.first?.duration == 1.5)+ } else {+ #expect(monitor.terminations.first?.duration == 1.5)+ #expect(monitor.terminations.first?.isFailure == (status == "failed"))+ }+ }++ private func mainThread() throws -> ActivityThread {+ try TestFixtures.decode(ActivityThread.self, #"{"id":"main","source":"cli","status":{"type":"active"}}"#)+ }++ private func apply(_ states: [SessionLifecycleState], to monitor: ActivityMonitor) {+ for state in states {+ _ = monitor.applySubagentLifecycle(state, terminalOnly: false)+ }+ monitor.reconcileSubagentCounts(states)+ }++ private func state(_ id: String, at date: Date, parent: String? = nil, terminal: SessionTerminalState? = nil) -> SessionLifecycleState {+ SessionLifecycleState(+ requestedThreadID: id, turnID: "turn-a", startedAt: date, effort: nil,+ lastProgressAt: date, terminal: terminal, rootTurnID: "turn-a", rootThreadID: "thread-a", parentThreadID: parent+ )+ }++ private func makeMonitor(_ directory: TestDirectory, _ preferences: TestPreferences) -> ActivityMonitor {+ let monitor = ActivityMonitor(+ protectionSettings: ProtectionSettings(defaults: preferences.defaults),+ protectionStore: ProtectionStore(directoryURL: directory.url), activityDirectoryURL: directory.url+ )+ monitor.isActivitySourceHealthy = true+ return monitor+ }+}diff --git a/CodexBarTests/Activity/ActivityIsolationTests.swift b/CodexBarTests/Activity/ActivityIsolationTests.swiftindex 7f866b3..221ed22 100644--- a/CodexBarTests/Activity/ActivityIsolationTests.swift+++ b/CodexBarTests/Activity/ActivityIsolationTests.swift@@ -13,7 +13,7 @@ struct ActivityIsolationTests {let now = Date().addingTimeInterval(-60)let server = try SharedServerFixture { peer inlet initialize = try peer.readMessage()- try peer.reply(to: initialize, result: ["userAgent": "codex/0.160.0"])+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])_ = try peer.readMessage()var emitted = falsewhile let request = try? peer.readMessage() {@@ -28,7 +28,7 @@ struct ActivityIsolationTests {try peer.reply(to: request, result: ["thread": Self.thread(id, now: now)])}case "thread/turns/list":- try peer.reply(to: request, result: ["data": [["id": "turn", "status": "inProgress", "startedAt": now.timeIntervalSince1970]]])+ try peer.reply(to: request, result: ["data": [["id": "turn", "rootTurnId": "turn", "status": "inProgress", "startedAt": now.timeIntervalSince1970]]])if id == "healthy", !emitted {emitted = trueif !brokenQuery {@@ -55,7 +55,7 @@ struct ActivityIsolationTests {if case .sourceUnavailable = batch {disconnected = true}- if case let .live(events) = batch, events.contains(where: { $0.sessionID == "healthy" }) {+ if case let .live(events) = batch, events.contains(where: { $0.threadID == "healthy" }) {observed = true}}@@ -64,7 +64,7 @@ struct ActivityIsolationTests {try await Task.sleep(for: .milliseconds(10))}#expect(observed && !disconnected)- let references = ["a-broken", "healthy"].map { ActivityTurnReference(threadID: $0, turnID: "turn", startedAt: now) }+ let references = ["a-broken", "healthy"].map { ActivityTurnReference(threadID: $0, turnID: "turn") }let states = await lifecycle.lifecycleStates(for: references)#expect(states.first { $0.requestedThreadID == "healthy" }?.readStatus == .complete)#expect(states.first { $0.requestedThreadID == "a-broken" }?.readStatus == .unavailable)@@ -78,24 +78,32 @@ struct ActivityIsolationTests {}@Test(arguments: [false, true])- func fullStorageBufferStopsReadingAndKeepsAcceptedEvents(byteLimit: Bool) async throws {+ func fullStorageBufferKeepsLiveReadingAndRetainsAcceptedEvents(byteLimit: Bool) async throws {let directory = try TestDirectory()defer { try? directory.remove() }let blocker = try directory.write("blocked", to: "State")let now = Date().addingTimeInterval(-60)let server = try SharedServerFixture { peer inlet initialize = try peer.readMessage()- try peer.reply(to: initialize, result: ["userAgent": "codex/0.160.0"])+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])_ = try peer.readMessage()try peer.reply(to: peer.readMessage(), result: ["data": ["healthy"]])for _ in 0 ..< 2 {try peer.reply(to: peer.readMessage(), result: ["thread": Self.thread("healthy", now: now)])}- try peer.reply(to: peer.readMessage(), result: ["data": [["id": "turn", "status": "inProgress", "startedAt": now.timeIntervalSince1970]]])+ try peer.reply(to: peer.readMessage(), result: ["data": [["id": "turn", "rootTurnId": "turn", "status": "inProgress", "startedAt": now.timeIntervalSince1970]]])for id in ["one", "two", "three"] {try peer.send(Self.tool(thread: "healthy", id: id))}- _ = try? peer.readMessage()+ while let request = try? peer.readMessage() {+ switch request["method"] as? String {+ case "thread/loaded/list": try peer.reply(to: request, result: ["data": ["healthy"]])+ case "thread/read", "thread/resume": try peer.reply(to: request, result: ["thread": Self.thread("healthy", now: now)])+ case "thread/turns/list":+ try peer.reply(to: request, result: ["data": [["id": "turn", "rootTurnId": "turn", "status": "inProgress", "startedAt": now.timeIntervalSince1970]]])+ default: Issue.record("Unexpected request")+ }+ }}defer { server.close() }var failures = 0@@ -113,12 +121,12 @@ struct ActivityIsolationTests {}}await reader.start()- for _ in 0 ..< 200 where failures == 0 {+ for _ in 0 ..< 200 where observed < 3 {try await Task.sleep(for: .milliseconds(10))}- #expect(failures == 1)- #expect(observed == (byteLimit ? 1 : 2))- #expect(await reader.drainNow() == .sourceUnavailable)+ #expect(failures == 0)+ #expect(observed == 3)+ #expect(await reader.drainNow() == .completed)try FileManager.default.removeItem(at: blocker)await reader.stop()var recorded = 0@@ -142,3 +150,268 @@ struct ActivityIsolationTests {["method": "item/started", "params": ["threadId": thread, "turnId": "turn", "item": ["id": id, "type": "commandExecution"]]]}}++extension ActivityIsolationTests {+ @Test func busyHistoryLockDoesNotDelayLiveTasksOrDrain() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let lockURL = HistoryStorage.lockURL(in: directory.url)+ var descriptor = try JSONFileStorage.acquireLock(in: lockURL.deletingLastPathComponent(), name: lockURL.lastPathComponent, nonblocking: true)+ defer {+ if let descriptor {+ JSONFileStorage.releaseLock(descriptor)+ }+ }+ let phase = Mutex(0)+ let server = try Self.tokenServer(now: Date().addingTimeInterval(-60), phase: { phase.withLock { $0 } })+ defer { server.close() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ var observed = 0+ var disconnected = false+ let reader = AppServerActivityReader(+ lifecycleCache: SessionLifecycleCache(), socketURL: server.url, logStorage: nil,+ tokenHistory: store, recorder: ActivityRecorder(directoryURL: directory.url)+ ) { batch in+ if case let .live(events) = batch {+ observed += events.count+ }+ if case .sourceUnavailable = batch {+ disconnected = true+ }+ }+ await reader.start()+ for _ in 0 ..< 100 where observed == 0 {+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(observed == 1)+ phase.withLock { $0 = 1 }+ let started = ContinuousClock.now+ #expect(await reader.drainNow() == .completed)+ #expect(ContinuousClock.now - started < .seconds(1))+ #expect(observed == 2 && !disconnected)+ try JSONFileStorage.releaseLock(#require(descriptor))+ descriptor = nil+ #expect(await reader.stop())+ let observations = try Self.observations(in: directory.url)+ #expect(observations.map(\.current.totalTokens) == [120, 150])+ #expect(try await store.refresh().first?.usage?.totalTokens == 50)+ #expect(try await store.refresh().first?.usage?.totalTokens == 50)+ try server.finish()+ }++ @Test func stopDoesNotWaitIndefinitelyForBusyStorageOrPublishLateResults() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ let entered = Mutex(false)+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let blocked = Task { await store.holdForReaderTest(entered: { entered.withLock { $0 = true } }, release: release) }+ for _ in 0 ..< 100 where !entered.withLock({ $0 }) {+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(entered.withLock { $0 })+ let server = try Self.tokenServer(now: Date().addingTimeInterval(-60), phase: { 0 })+ defer { server.close() }+ var observed = 0+ var batches = 0+ let reader = AppServerActivityReader(+ lifecycleCache: SessionLifecycleCache(), socketURL: server.url, logStorage: nil,+ tokenHistory: store, recorder: ActivityRecorder(directoryURL: directory.url)+ ) { batch in+ batches += 1+ if case let .live(events) = batch {+ observed += events.count+ }+ }+ await reader.start()+ for _ in 0 ..< 100 where observed == 0 {+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(observed == 1)+ let started = ContinuousClock.now+ #expect(await reader.stop() == false)+ #expect(ContinuousClock.now - started < .seconds(3))+ let countAtStop = batches+ release.signal()+ await blocked.value+ // 再次停止等待旧工作循环释放资源, 不能发布已停止连接的状态+ _ = await reader.stop()+ #expect(batches == countAtStop)+ #expect(try await store.acquireRecordingLease())+ await store.releaseRecordingLease()+ try server.finish()+ }++ @Test(arguments: [false, true])+ func brokenTokenCacheDoesNotInterruptLiveCollection(corruptWhileRunning: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date().addingTimeInterval(-60)+ let phase = Mutex(0)+ let store = TokenHistoryStore(directoryURL: directory.url)+ let oldDate = HistoryStorage.dateKey(for: now.addingTimeInterval(-86400))+ func corruptHistory() throws -> URL {+ _ = try directory.write("broken cache", to: "Aggregates/tokens.json")+ return try directory.writeJournal(Data("broken event\n".utf8), to: "Events/\(oldDate).jsonl")+ }+ var brokenJournal: URL?+ if !corruptWhileRunning {+ brokenJournal = try corruptHistory()+ }+ let server = try Self.tokenServer(now: now, phase: { phase.withLock { $0 } })+ defer { server.close() }+ var observed = 0+ var disconnected = false+ let lifecycle = SessionLifecycleCache()+ let reader = AppServerActivityReader(+ lifecycleCache: lifecycle, socketURL: server.url, logStorage: nil,+ tokenHistory: store, recorder: ActivityRecorder(directoryURL: directory.url)+ ) { batch in+ if case .sourceUnavailable = batch {+ disconnected = true+ }+ if case let .live(events) = batch {+ observed += events.count+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where observed < 1 {+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(observed == 1)+ if corruptWhileRunning {+ brokenJournal = try corruptHistory()+ }+ phase.withLock { $0 = 1 }+ #expect(await reader.drainNow() == .completed)+ #expect(observed == 2)+ // 给周期缓存刷新一次触发机会, 失败不能使实时连接失效+ try await Task.sleep(for: .milliseconds(1200))+ #expect(await reader.drainNow() == .completed)+ #expect(!disconnected)+ let states = await lifecycle.lifecycleStates(for: [.init(threadID: "healthy", turnID: "turn")])+ #expect(states.first?.readStatus == .complete)+ await #expect(throws: TokenCacheError.self) { try await store.refresh() }+ #expect(try String(contentsOf: directory.url.appendingPathComponent("Aggregates/tokens.json"), encoding: .utf8) == "broken cache")+ let observations = try Self.observations(in: directory.url)+ #expect(observations.map(\.sequence) == [1, 2])+ #expect(observations.map(\.current.totalTokens) == [120, 150])+ try FileManager.default.removeItem(at: #require(brokenJournal))+ let recovered = try await store.refresh()+ #expect(recovered.first?.usage?.totalTokens == 50)+ #expect(try await store.refresh() == recovered)+ #expect(await reader.stop())+ try server.finish()+ }++ private nonisolated static func tokenServer(now: Date, phase: @escaping @Sendable () -> Int) throws -> SharedServerFixture {+ try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ var emitted = false+ var emittedPhase = 0+ while let request = try? peer.readMessage() {+ switch request["method"] as? String {+ case "thread/loaded/list":+ let nextPhase = phase()+ if nextPhase > emittedPhase {+ emittedPhase = nextPhase+ for total in nextPhase == 1 ? [150] : [200, 250] {+ try peer.send(Self.usage(total))+ }+ try peer.send(Self.tool(thread: "healthy", id: "phase-\(nextPhase)"))+ }+ try peer.reply(to: request, result: ["data": ["healthy"]])+ case "thread/read", "thread/resume":+ try peer.reply(to: request, result: ["thread": Self.thread("healthy", now: now)])+ case "thread/turns/list":+ try peer.reply(to: request, result: ["data": [["id": "turn", "rootTurnId": "turn", "status": "inProgress", "startedAt": now.timeIntervalSince1970]]])+ if !emitted {+ emitted = true+ try peer.send(Self.usage(100))+ try peer.send(Self.usage(120))+ try peer.send(Self.tool(thread: "healthy", id: "first"))+ }+ default: Issue.record("Unexpected request")+ }+ }+ }+ }++ private nonisolated static func observations(in directory: URL) throws -> [TokenObservation] {+ let url = HistoryStorage.eventLogURL(for: HistoryStorage.dateKey(for: Date()), in: directory.appendingPathComponent("Events"))+ var observations: [TokenObservation] = []+ try AppServerEventJournal.read(at: url) {+ if let observation = $0.observation {+ observations.append(observation)+ }+ }+ return observations+ }++ private nonisolated static func usage(_ total: Int) -> [String: Any] {+ let counts = ["inputTokens": total, "cachedInputTokens": 0, "outputTokens": 0, "reasoningOutputTokens": 0, "totalTokens": total]+ return ["method": "thread/tokenUsage/updated", "params": [+ "threadId": "healthy", "turnId": "turn", "tokenUsage": ["total": counts, "last": counts]+ ]]+ }+}++private extension TokenHistoryStore {+ func holdForReaderTest(entered: @Sendable () -> Void, release: DispatchSemaphore) {+ entered()+ _ = release.wait(timeout: .now() + 10)+ }+}++extension ActivityIsolationTests {+ @Test func fullObservationQueueResumesWithNewBaselineAfterStorageRecovery() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let blocker = try directory.write("blocked", to: "State")+ let phase = Mutex(0)+ let server = try Self.tokenServer(now: Date().addingTimeInterval(-60), phase: { phase.withLock { $0 } })+ defer { server.close() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ var observed = 0+ var disconnected = false+ let reader = AppServerActivityReader(+ lifecycleCache: SessionLifecycleCache(), socketURL: server.url, logStorage: nil,+ tokenHistory: store, recorder: ActivityRecorder(directoryURL: directory.url), maximumPendingEvents: 1+ ) { batch in+ if case .sourceUnavailable = batch {+ disconnected = true+ }+ if case let .live(events) = batch {+ observed += events.count+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where observed < 1 {+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(observed == 1)+ phase.withLock { $0 = 1 }+ #expect(await reader.drainNow() == .completed)+ #expect(observed == 2)+ try FileManager.default.removeItem(at: blocker)+ for _ in 0 ..< 200 where !FileManager.default.fileExists(atPath: HistoryStorage.maintenanceURL(in: directory.url).path) {+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(await reader.drainNow() == .completed)+ phase.withLock { $0 = 2 }+ #expect(await reader.drainNow() == .completed)+ #expect(observed == 3)+ #expect(!disconnected)+ #expect(await reader.stop())+ let observations = try Self.observations(in: directory.url)+ #expect(observations.map(\.sequence) == [1, 1])+ #expect(Set(observations.map(\.streamID)).count == 2)+ let restored = try await store.refresh()+ #expect(restored.first?.usage?.totalTokens == 70)+ #expect(try await store.refresh() == restored)+ try server.finish()+ }+}diff --git a/CodexBarTests/Activity/ActivityLivePresentationTests.swift b/CodexBarTests/Activity/ActivityLivePresentationTests.swiftindex 4dc0498..2a3da91 100644--- a/CodexBarTests/Activity/ActivityLivePresentationTests.swift+++ b/CodexBarTests/Activity/ActivityLivePresentationTests.swift@@ -4,18 +4,18 @@ import Testingstruct ActivityLivePresentationTests {private let now = TestFixtures.now- private func message(_ method: String, _ fields: String = "", id: Int? = nil, turn: Bool = true) throws -> ActivityNotification {+ private func message(_ method: String, _ fields: String = "", id: Int? = nil, turn: Bool = true) throws -> ActivityInput {let identity = id.map { "\"id\":\($0)," } ?? ""let turnField = turn ? #", "turnId":"turn-a""# : ""- return try TestFixtures.decode(ActivityNotification.self, """- {\(identity)"method":"\(method)","params":{"threadId":"session-a"\(turnField)\(fields.isEmpty ? "" : "," + fields)}}+ return try TestFixtures.decode(ActivityInput.self, """+ {\(identity)"method":"\(method)","params":{"threadId":"thread-a"\(turnField)\(fields.isEmpty ? "" : "," + fields)}}""")}private func prepared() throws -> AppServerActivityReducer {var reducer = AppServerActivityReducer()- let thread = ActivityThread(id: "session-a", status: ActivityThreadStatus(type: "active", activeFlags: []))- _ = reducer.reconcile(thread: thread, turns: [ActivityTurn(id: "turn-a", status: "inProgress")], reviewer: .user, now: now)+ let thread = ActivityThread(id: "thread-a", status: ActivityThreadStatus(type: .active, activeFlags: []))+ _ = reducer.reconcile(thread: thread, turns: [ActivityTurn(id: "turn-a", status: .running)], now: now)_ = try reducer.consume(message("turn/started", #""turn":{"id":"turn-a","status":"inProgress"}"#), now: now)return reducer}@@ -57,12 +57,12 @@ struct ActivityLivePresentationTests {#expect(live.summary.toolCount == 0)}- @Test(arguments: [("commandExecution", "command"), ("fileChange", "editing")])+ @Test(arguments: [("commandExecution", "command")])func outputAfterReconnectRestoresToolPhaseWithoutInventingInventory(type: String, key: String) throws {var reducer = try prepared()reducer.reconnect(now: now)- let thread = ActivityThread(id: "session-a", status: ActivityThreadStatus(type: "active", activeFlags: []))- _ = reducer.reconcile(thread: thread, turns: [ActivityTurn(id: "turn-a", status: "inProgress")], reviewer: .user, now: now)+ let thread = ActivityThread(id: "thread-a", status: ActivityThreadStatus(type: .active, activeFlags: []))+ _ = reducer.reconcile(thread: thread, turns: [ActivityTurn(id: "turn-a", status: .running)], now: now)let output = try message("item/\(type)/outputDelta", #""itemId":"tool","delta":"output""#)#expect(reducer.consume(output, now: now.addingTimeInterval(1)).isEmpty)#expect(try summary(reducer).current.key == key)@@ -82,8 +82,10 @@ struct ActivityLivePresentationTests {try live.consume(message("item/started", #""item":{"id":"cmd","type":"commandExecution","commandActions":[{"type":"read"}]}"#), at: now)try live.consume(message("item/commandExecution/outputDelta", #""itemId":"cmd""#), at: now.addingTimeInterval(1))#expect(live.summary.current.key == "command-read")- try live.consume(message("item/fileChange/outputDelta", #""itemId":"edit""#), at: now.addingTimeInterval(2))- try live.consume(message("item/fileChange/outputDelta", #""itemId":"edit""#), at: now.addingTimeInterval(3))+ try live.consume(message("item/started", #""item":{"id":"edit","type":"fileChange"}"#), at: now.addingTimeInterval(2))+ let beforeDeprecatedMessage = live.summary+ try live.consume(message("item/fileChange/outputDelta", #""itemId":"unknown""#), at: now.addingTimeInterval(3))+ #expect(live.summary == beforeDeprecatedMessage)#expect(live.summary.toolCount == 2)try live.consume(message("item/completed", #""item":{"id":"cmd","type":"commandExecution","status":"completed"}"#), at: now.addingTimeInterval(4))#expect(live.summary.current.key == "editing")@@ -96,11 +98,11 @@ struct ActivityLivePresentationTests {@Test func recoveredToolOutputDoesNotClearUserWait() throws {var live = ActivityLivePresentation()- try live.consume(message("item/tool/requestUserInput", #""isBlocking":true"#, id: 1), at: now)+ try live.consume(message("thread/status/changed", #""status":{"type":"active","activeFlags":["waitingOnUserInput"]}"#, turn: false), at: now)try live.consume(message("item/commandExecution/outputDelta", #""itemId":"cmd""#), at: now.addingTimeInterval(1))#expect(live.summary.current.key == "waiting-input")#expect(live.summary.waiting?.since == now)- try live.consume(message("serverRequest/resolved", #""requestId":1"#, turn: false), at: now.addingTimeInterval(2))+ try live.consume(message("thread/status/changed", #""status":{"type":"active","activeFlags":[]}"#, turn: false), at: now.addingTimeInterval(2))#expect(live.summary.current.key == "command")}@@ -111,7 +113,7 @@ struct ActivityLivePresentationTests {(["read", "unknown"], "command"), (["future"], "command"), ([], "command")])func commandActionsUseServerClassification(actions: [String], key: String) {- let item = ActivityItem(id: "cmd", type: "commandExecution", commandActions: actions.map { .init(type: $0) })+ let item = ActivityItem(id: "cmd", type: .commandExecution, commandActions: actions.map { .init(type: $0) })#expect(item.liveLabel?.key == key)if actions.contains("read"), actions.contains("unknown") {#expect(item.liveLabel?.detail != nil)@@ -127,7 +129,7 @@ struct ActivityLivePresentationTests {] as [([String], String?)])func commandCompletionLocalizesAndOrdersKnownActions(actions: [String], detailKey: String?) {let item = ActivityItem(- id: "cmd", type: "commandExecution", status: "failed",+ id: "cmd", type: .commandExecution, status: "failed",commandActions: actions.map { .init(type: $0) })#expect(item.liveCompletionLabel?.key == (detailKey == nil ? "tool-failed" : "action-failed"))@@ -153,24 +155,31 @@ struct ActivityLivePresentationTests {#expect(!recent.label.text.contains(" • "))}- @Test(arguments: ["mcpToolCall", "dynamicToolCall"])- func completionPreservesActualToolNames(type: String) {+ @Test(arguments: ["mcpToolCall", "dynamicToolCall"], [nil, "server"] as [String?])+ func completionPreservesActualToolNames(type: String, server: String?) {let item = ActivityItem(- id: "tool", type: type, status: "failed", tool: "search/read",+ id: "tool", type: ActivityItem.ItemType(rawValue: type) ?? .unknown, status: "failed", tool: "search/read", server: server,commandActions: [.init(type: "read")])#expect(item.liveCompletionLabel?.key == "tool-failed")- #expect(item.liveCompletionLabel?.detail == "search/read")- let name = "search/read"+ let name = type == "mcpToolCall" ? server.map { $0 + ".search/read" } ?? "search/read" : "search/read"+ #expect(item.liveCompletionLabel?.detail == name)#expect(item.liveCompletionLabel?.text == String(localized: "activity.live.named-tool-failed", defaultValue: "\(name)"))}@Test func currentToolDetailsUseLocalizedTemplates() throws {- let name = "web.search"- let tool = ActivityItem(id: "tool", type: "mcpToolCall", tool: name)- #expect(tool.liveLabel?.text == String(localized: "activity.live.calling-named-tool", defaultValue: "\(name)"))+ let name = "server.tools"+ var reducer = try prepared()+ _ = try reducer.consume(message("item/started", """+ "item":{"id":"tool","type":"mcpToolCall","server":"server","tool":"tools","status":"inProgress","arguments":{"limit":1}}+ """), now: now)+ #expect(try summary(reducer).current.text == String(localized: "activity.live.calling-named-tool", defaultValue: "\(name)"))+ _ = try reducer.consume(message("item/completed", """+ "item":{"id":"tool","type":"mcpToolCall","server":"server","tool":"tools","status":"completed"}+ """), now: now.addingTimeInterval(1))+ #expect(try summary(reducer).recent?.label.detail == name)let command = ActivityItem(- id: "cmd", type: "commandExecution", commandActions: ["search", "unknown", "read"].map { .init(type: $0) }+ id: "cmd", type: .commandExecution, commandActions: ["search", "unknown", "read"].map { .init(type: $0) })let label = try #require(command.liveLabel)let detail = try #require(label.detail)@@ -210,13 +219,13 @@ struct ActivityLivePresentationTests {operation: (tool: String, expected: (statusKey: String, action: LocalizedStringResource)), status: String) {let item = ActivityItem(- id: "agent", type: "collabAgentToolCall", status: status, tool: operation.tool,+ id: "agent", type: .collabAgentToolCall, status: status, tool: operation.tool,agentsStates: ["child": .init(status: "running")])#expect(item.liveLabel?.key == operation.expected.statusKey)#expect(item.liveCompletionLabel?.key == "action-" + status)#expect(item.liveCompletionLabel?.detail == String(localized: operation.expected.action))- #expect(ActivityDisplayFormat.toolActionText(itemType: item.type, toolName: operation.tool) == item.liveCompletionLabel?.detail)+ #expect(ActivityDisplayFormat.toolActionText(itemType: item.type.rawValue, toolName: operation.tool) == item.liveCompletionLabel?.detail)}@Test(arguments: [@@ -243,7 +252,7 @@ struct ActivityLivePresentationTests {@Test(arguments: [("form", "waiting-form"), ("openai/form", "waiting-form"), ("openaiForm", "waiting-form"),- ("url", "waiting-external"), ("openai/userVerification", "waiting-verification"), ("future", "waiting-service")+ ("url", "waiting-external"), ("future", "waiting-service")])func elicitationWaitsAreSpecificAndEndByRequestID(mode: String, key: String) throws {var reducer = try prepared()@@ -258,7 +267,7 @@ struct ActivityLivePresentationTests {@Test func unrelatedOutputAndResolvedRequestDoNotClearConcurrentWait() throws {var live = ActivityLivePresentation()- try live.consume(message("item/tool/requestUserInput", #""isBlocking":true"#, id: 1), at: now)+ try live.consume(message("mcpServer/elicitation/request", #""mode":"form""#, id: 1), at: now)try live.consume(message("mcpServer/elicitation/request", #""mode":"url""#, id: 2), at: now.addingTimeInterval(1))try live.consume(message("item/agentMessage/delta", #""itemId":"answer""#), at: now.addingTimeInterval(2))try live.consume(message("serverRequest/resolved", #""requestId":1"#, turn: false), at: now.addingTimeInterval(3))@@ -277,26 +286,29 @@ struct ActivityLivePresentationTests {@Test func reconnectDropsUnverifiablePhasesAndWaitingDuration() throws {var reducer = try prepared()- _ = try reducer.consume(message("item/tool/requestUserInput", #""isBlocking":true"#, id: 1), now: now)+ _ = try reducer.consume(message("thread/status/changed", #""status":{"type":"active","activeFlags":["waitingOnUserInput"]}"#, turn: false), now: now)reducer.reconnect(now: now.addingTimeInterval(10))#expect(reducer.states.values.first?.presentation == nil)- let thread = ActivityThread(id: "session-a", status: ActivityThreadStatus(type: "active", activeFlags: ["waitingOnUserInput"]))- _ = reducer.reconcile(thread: thread, turns: [ActivityTurn(id: "turn-a", status: "inProgress")], reviewer: .user, now: now.addingTimeInterval(12))+ let thread = ActivityThread(id: "thread-a", status: ActivityThreadStatus(type: .active, activeFlags: [.waitingOnUserInput]))+ _ = reducer.reconcile(thread: thread, turns: [ActivityTurn(id: "turn-a", status: .running)], now: now.addingTimeInterval(12))#expect(try summary(reducer).waiting?.label.key == "waiting-input")#expect(try summary(reducer).waiting?.since == nil)#expect(try summary(reducer).toolCount == nil)}@Test(arguments: ["approved", "denied", "timedOut", "aborted"])- func automaticReviewIsNotUserWaitingAndCompletes(status: String) throws {+ func automaticReviewHasNoPresentationOrHistory(status: String) throws {var reducer = try prepared()_ = try reducer.consume(message("item/autoApprovalReview/started", #""reviewId":"review","review":{"status":"inProgress"}"#), now: now)- #expect(try summary(reducer).current.key == "auto-approval")+ #expect(try summary(reducer).current.key == "processing")#expect(try summary(reducer).waiting == nil)- let events = try reducer.consume(message("item/autoApprovalReview/completed", "\"reviewId\":\"review\",\"review\":{\"status\":\"\(status)\"}"), now: now.addingTimeInterval(1))+ let events = try reducer.consume(+ message("item/autoApprovalReview/completed", "\"reviewId\":\"review\",\"review\":{\"status\":\"\(status)\"}"),+ now: now.addingTimeInterval(1)+ )#expect(events.isEmpty)#expect(try summary(reducer).current.key == "processing")- #expect(try summary(reducer).recent?.label.key.hasPrefix("approval-") == true)+ #expect(try summary(reducer).recent == nil)}@Test func presentationEventsNeverProduceHistoricalRecords() throws {@@ -304,7 +316,6 @@ struct ActivityLivePresentationTests {let messages = try [message("turn/plan/updated", #""plan":[{"step":"private","status":"completed"}]"#),message("turn/diff/updated", #""diff":"private diff""#),- message("mcpServer/startupStatus/updated", #""name":"test","status":"starting""#),message("model/rerouted", #""fromModel":"old","toModel":"new""#),message("modelProvider/authRecoveryStarted"),message("modelProvider/authRecoveryCompleted"),@@ -312,7 +323,7 @@ struct ActivityLivePresentationTests {message("hook/started", #""run":{"id":"hook","status":"running","executionMode":"sync"}"#)]for notification in messages {- #expect(ActivityNotification.category(for: notification.method) == .presentation)+ #expect(notification.kind.category == .presentation)#expect(reducer.consume(notification, now: now).isEmpty)}#expect(try summary(reducer).planCompleted == 1)@@ -323,22 +334,22 @@ struct ActivityLivePresentationTests {@Test(arguments: ["completed", "failed", "declined", "unknown"])func toolOutcomeDoesNotAssumeSuccess(status: String) {- let item = ActivityItem(id: "image", type: "imageGeneration", status: status)+ let item = ActivityItem(id: "image", type: .imageGeneration, status: status)#expect(item.liveCompletionLabel?.key == (status == "unknown" ? nil : "image-" + status))}@Test func displayWaitingDoesNotChangeApprovalOrProtectionState() throws {let event = TestFixtures.event()- var task = ActivityTask(+ var task = try ActivityTask(displayID: UUID(),- key: ActivityTaskKey(event: event),+ key: #require(ActivityTaskKey(event: event)),event: event,state: .running,startedAt: now,progressGeneration: 0)var reducer = try prepared()- _ = try reducer.consume(message("item/tool/requestUserInput", #""isBlocking":true"#, id: 1), now: now)+ _ = try reducer.consume(message("thread/status/changed", #""status":{"type":"active","activeFlags":["waitingOnUserInput"]}"#, turn: false), now: now)let state = try #require(reducer.states.values.first)task.mergeExecutionLifecycle(state, owner: ActivityExecutionKey(agentID: nil, turnID: "turn-a"))let snapshot = ActivitySnapshot(waitingTasks: [], runningTasks: [task.snapshot], recentCompletions: [], recentTerminations: [])@@ -357,7 +368,7 @@ struct ActivityLivePresentationTests {@Test func authoritativeIdleClearsRequestsWithoutInventingApproval() throws {var live = ActivityLivePresentation()try live.consume(message("mcpServer/elicitation/request", #""mode":"form""#, id: 1), at: now)- live.reconcile(status: ActivityThreadStatus(type: "idle"))+ live.reconcile(status: ActivityThreadStatus(type: .idle))#expect(live.summary.waiting == nil)#expect(live.summary.recent == nil)}@@ -377,9 +388,9 @@ struct ActivityLivePresentationTests {@Test func childWaitSurvivesRootOutputUntilChildLifecycleResolvesIt() throws {let event = TestFixtures.event()- var task = ActivityTask(+ var task = try ActivityTask(displayID: UUID(),- key: ActivityTaskKey(event: event),+ key: #require(ActivityTaskKey(event: event)),event: event,state: .running,startedAt: now,@@ -388,13 +399,13 @@ struct ActivityLivePresentationTests {var root = ActivityLivePresentation()try root.consume(message("item/agentMessage/delta", #""itemId":"answer""#), at: now.addingTimeInterval(4))var child = ActivityLivePresentation()- try child.consume(message("item/tool/requestUserInput", #""isBlocking":true"#, id: 1), at: now)+ try child.consume(message("thread/status/changed", #""status":{"type":"active","activeFlags":["waitingOnUserInput"]}"#, turn: false), at: now)task.executions[ActivityExecutionKey(agentID: nil, turnID: "turn-a")] = ActivityExecution(presentation: root)let childOwner = ActivityExecutionKey(agentID: "child", turnID: "child-turn")task.executions[childOwner] = ActivityExecution(presentation: child)#expect(task.snapshot.presentation?.waiting?.since == now)#expect(task.snapshot.presentation?.current.key == "waiting-input")- try child.consume(message("serverRequest/resolved", #""requestId":1"#, turn: false), at: now.addingTimeInterval(5))+ try child.consume(message("thread/status/changed", #""status":{"type":"active","activeFlags":[]}"#, turn: false), at: now.addingTimeInterval(5))task.executions[childOwner]?.presentation = child#expect(task.snapshot.presentation?.waiting == nil)#expect(task.snapshot.presentation?.current.key == "replying")@@ -404,14 +415,14 @@ struct ActivityLivePresentationTests {var reducer = try prepared()let events = try reducer.consume(message("turn/completed", #""turn":{"id":"turn-a","status":"failed"}"#), now: now)let state = try #require(reducer.states.values.first)- #expect(state.turnStatus == "failed")+ #expect(state.turnStatus == .failed)#expect(state.presentation == nil)#expect(events.first?.eventKind == .turnAborted)- #expect(events.first?.source?.turnStatus == "failed")+ #expect(events.first?.context?.turnStatus == .failed)let event = TestFixtures.event()- var task = ActivityTask(+ var task = try ActivityTask(displayID: UUID(),- key: ActivityTaskKey(event: event),+ key: #require(ActivityTaskKey(event: event)),event: event,state: .running,startedAt: now,@@ -423,7 +434,7 @@ struct ActivityLivePresentationTests {@Test func mixedCommandActionsResolveTheExplicitLocalizedKey() {let item = ActivityItem(- id: "cmd", type: "commandExecution",+ id: "cmd", type: .commandExecution,commandActions: ["search", "unknown", "read", "read"].map { .init(type: $0) })#expect(item.liveLabel?.key == "command")@@ -431,4 +442,33 @@ struct ActivityLivePresentationTests {let actions = String(localized: "activity.live.actions-read-search")#expect(item.liveLabel?.text == String(localized: "activity.live.command-with-actions", defaultValue: "\(actions)"))}++ @Test func resolvedRequestDoesNotClearThreadInputWait() throws {+ var live = ActivityLivePresentation()+ try live.consume(message("thread/status/changed", #""status":{"type":"active","activeFlags":["waitingOnUserInput"]}"#, turn: false), at: now)+ try live.consume(message("mcpServer/elicitation/request", #""mode":"form""#, id: 1), at: now)+ try live.consume(message("serverRequest/resolved", #""requestId":1"#, turn: false), at: now.addingTimeInterval(2))+ #expect(live.summary.waiting?.label.key == "waiting-input")+ #expect(live.summary.waiting?.since == now)+ try live.consume(message("thread/status/changed", #""status":{"type":"active","activeFlags":[]}"#, turn: false), at: now.addingTimeInterval(3))+ #expect(live.summary.waiting == nil)+ }++ @Test func verificationRequestDoesNotCreateWaitingOrRecentEvent() throws {+ var reducer = try prepared()+ let before = try summary(reducer)+ #expect(try reducer.consume(message("mcpServer/elicitation/request", #""mode":"openai/userVerification""#, id: 1), now: now).isEmpty)+ _ = try reducer.consume(message("serverRequest/resolved", #""requestId":1"#, turn: false), now: now)+ #expect(try summary(reducer) == before)+ }++ @Test(arguments: ["item/started", "item/completed"])+ func planItemsDoNotChangePresentationOrProgress(method: String) throws {+ var reducer = try prepared()+ let before = try summary(reducer)+ let progress = reducer.states.values.first?.lastProgressAt+ #expect(try reducer.consume(message(method, #""item":{"id":"plan","type":"plan"}"#), now: now.addingTimeInterval(10)).isEmpty)+ #expect(try summary(reducer) == before)+ #expect(reducer.states.values.first?.lastProgressAt == progress)+ }}diff --git a/CodexBarTests/Activity/ActivityReaderBoundsTests.swift b/CodexBarTests/Activity/ActivityReaderBoundsTests.swiftnew file mode 100644index 0000000..06ae4bf--- /dev/null+++ b/CodexBarTests/Activity/ActivityReaderBoundsTests.swift@@ -0,0 +1,233 @@+import Foundation+import Testing++struct ActivityReaderBoundsTests {+ @Test(arguments: [["repeat", "repeat"], ["a", "b", "a"], ["a", "b", "c"]])+ func invalidPaginationCannotCompleteBootstrap(cursors: [String]) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let server = try SharedServerFixture { peer in+ try Self.initialize(peer)+ for cursor in cursors {+ let request = try peer.readMessage()+ #expect(request["method"] as? String == "thread/loaded/list")+ try peer.reply(to: request, result: ["data": [], "nextCursor": cursor])+ }+ _ = release.wait(timeout: .now() + 5)+ }+ defer { server.close() }+ var failed = false+ var ready = false+ let reader = AppServerActivityReader(+ lifecycleCache: SessionLifecycleCache(), socketURL: server.url, logStorage: nil,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url),+ recorder: ActivityRecorder(directoryURL: directory.url), maximumLoadedPages: 3+ ) { batch in+ if case .sourceUnavailable = batch {+ failed = true+ }+ if case .bootstrapEnd = batch {+ ready = true+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where !failed {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(failed)+ #expect(!ready)+ await reader.stop()+ release.signal()+ try server.finish()+ }++ @Test(arguments: [false, true])+ func incompleteDiscoveryCannotReportSuccessfulDrain(timesOut: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let server = try SharedServerFixture { peer in+ try Self.initialize(peer)+ let first = try peer.readMessage()+ try peer.reply(to: first, result: ["data": [], "nextCursor": "last"])+ let last = try peer.readMessage()+ #expect((last["params"] as? [String: Any])?["cursor"] as? String == "last")+ try peer.reply(to: last, result: ["data": []])+ let next = try peer.readMessage()+ #expect((next["params"] as? [String: Any])?["cursor"] == nil)+ if !timesOut {+ try peer.reply(to: next, result: ["data": [], "nextCursor": "repeat"])+ let repeated = try peer.readMessage()+ try peer.reply(to: repeated, result: ["data": [], "nextCursor": "repeat"])+ }+ _ = release.wait(timeout: .now() + 5)+ }+ defer { server.close() }+ var ready = false+ let reader = AppServerActivityReader(+ lifecycleCache: SessionLifecycleCache(), socketURL: server.url, logStorage: nil,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url),+ recorder: ActivityRecorder(directoryURL: directory.url), reconciliationTimeout: 0.5+ ) { batch in+ if case .bootstrapEnd = batch {+ ready = true+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where !ready {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(ready)+ let start = Date()+ #expect(await reader.drainNow() == .sourceUnavailable)+ #expect(Date().timeIntervalSince(start) < 2)+ await reader.stop()+ release.signal()+ try server.finish()+ }++ @Test func missingRootAndCreationMetadataAreReadFromUnloadedParent() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date().addingTimeInterval(-60)+ let server = try SharedServerFixture { peer in+ try Self.initialize(peer)+ while let request = try? peer.readMessage() {+ let params = request["params"] as? [String: Any] ?? [:]+ let id = params["threadId"] as? String ?? ""+ switch request["method"] as? String {+ case "thread/loaded/list":+ try peer.reply(to: request, result: ["data": ["child"]])+ case "thread/read", "thread/resume":+ if request["method"] as? String == "thread/resume" {+ #expect(id == "child")+ }+ var thread: [String: Any] = ["id": id, "source": "cli", "status": ["type": id == "child" ? "active" : "notLoaded"]]+ if id == "child" {+ thread["parentThreadId"] = "parent"+ }+ try peer.reply(to: request, result: ["thread": thread])+ case "thread/turns/list":+ if id == "child" {+ try peer.reply(to: request, result: ["data": [[+ "id": "child-turn", "rootTurnId": "root-turn", "status": "inProgress", "startedAt": now.timeIntervalSince1970 + 1+ ]]])+ } else if params["cursor"] == nil {+ #expect(params["itemsView"] as? String == "full")+ try peer.reply(to: request, result: ["data": [], "nextCursor": "older"])+ } else {+ #expect(params["cursor"] as? String == "older")+ #expect(params["itemsView"] as? String == "full")+ let item: [String: Any] = [+ "id": "spawn", "type": "subAgentActivity", "kind": "started",+ "agentThreadId": "child", "model": "child-model", "reasoningEffort": "low"+ ]+ let turn: [String: Any] = [+ "id": "root-turn", "rootTurnId": "root-turn", "status": "completed",+ "startedAt": now.timeIntervalSince1970, "completedAt": now.timeIntervalSince1970 + 2, "items": [item]+ ]+ try peer.reply(to: request, result: ["data": [turn]])+ }+ default:+ Issue.record("Unexpected request")+ }+ }+ }+ defer { server.close() }+ let lifecycle = SessionLifecycleCache()+ var ready = false+ let reader = AppServerActivityReader(+ lifecycleCache: lifecycle, socketURL: server.url, logStorage: nil,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url), recorder: ActivityRecorder(directoryURL: directory.url)+ ) { batch in+ if case .bootstrapEnd = batch {+ ready = true+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where !ready {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(ready)+ #expect(await reader.drainNow() == .completed)+ let states = await lifecycle.lifecycleStates(for: [.init(threadID: "child", turnID: "child-turn")])+ let child = try #require(states.first)+ #expect(child.rootThreadID == "parent")+ #expect(child.rootTurnID == "root-turn")+ #expect(child.effort == "low")+ await reader.stop()+ try server.finish()+ }++ private nonisolated static func initialize(_ peer: SharedServerFixture.Peer) throws {+ let request = try peer.readMessage()+ try peer.reply(to: request, result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ }+}++extension ActivityReaderBoundsTests {+ @Test(arguments: [false, true])+ func unresolvedChildOnlyBlocksLiveDrainWhileRunning(running: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date().addingTimeInterval(-60)+ let server = try SharedServerFixture { peer in+ let request = try peer.readMessage()+ try peer.reply(to: request, result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ while let request = try? peer.readMessage() {+ let params = request["params"] as? [String: Any] ?? [:]+ let id = params["threadId"] as? String ?? ""+ switch request["method"] as? String {+ case "thread/loaded/list":+ try peer.reply(to: request, result: ["data": ["healthy", "child"]])+ case "thread/read", "thread/resume":+ var thread: [String: Any] = ["id": id, "source": "cli", "status": ["type": id == "healthy" ? "active" : id == "child" ? "idle" : "notLoaded"]]+ if id == "child" {+ thread["parentThreadId"] = "deleted-parent"+ }+ try peer.reply(to: request, result: ["thread": thread])+ case "thread/turns/list":+ let turns: [[String: Any]] = if id == "healthy" {+ [["id": "healthy-turn", "rootTurnId": "healthy-turn", "status": "inProgress", "startedAt": now.timeIntervalSince1970]]+ } else if id == "child" {+ [[+ "id": "child-turn", "rootTurnId": "missing-root", "status": running ? "inProgress" : "completed",+ "startedAt": now.timeIntervalSince1970, "completedAt": now.timeIntervalSince1970 + 10+ ]]+ } else {+ []+ }+ try peer.reply(to: request, result: ["data": turns])+ default: Issue.record("Unexpected request")+ }+ }+ }+ defer { server.close() }+ let lifecycle = SessionLifecycleCache()+ var ready = false+ let reader = AppServerActivityReader(+ lifecycleCache: lifecycle, socketURL: server.url, logStorage: nil,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url), recorder: ActivityRecorder(directoryURL: directory.url)+ ) { batch in+ if case .bootstrapEnd = batch {+ ready = true+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where !ready {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(ready)+ let result = await reader.drainNow()+ let states = await lifecycle.lifecycleStates(for: [.init(threadID: "healthy", turnID: "healthy-turn")])+ #expect(states.first?.readStatus == .complete)+ #expect(result == (running ? .sourceUnavailable : .completed))+ await reader.stop()+ try server.finish()+ }+}diff --git a/CodexBarTests/Activity/ActivityRecoveryTests.swift b/CodexBarTests/Activity/ActivityRecoveryTests.swiftindex 33d4b51..2a25474 100644--- a/CodexBarTests/Activity/ActivityRecoveryTests.swift+++ b/CodexBarTests/Activity/ActivityRecoveryTests.swift@@ -8,7 +8,7 @@ struct ActivityRecoveryTests {let now = Date()let store = TokenHistoryStore(directoryURL: directory.url)let id = TokenTurn.identifier(thread: "t", turn: "u")- let record = TokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: .zero)+ let record = TestFixtures.tokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: .zero)try await directory.seedTokenSnapshots([record], now: now)let cache = try directory.write("broken", to: "Aggregates/tokens.json")var refreshFailed = false@@ -31,7 +31,7 @@ struct ActivityRecoveryTests {let timestamp = Date().timeIntervalSince1970let server = try SharedServerFixture { peer inlet initialize = try peer.readMessage()- try peer.reply(to: initialize, result: ["userAgent": "codex/0.160.0"])+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])_ = try peer.readMessage()let loaded = try peer.readMessage()try peer.reply(to: loaded, result: ["data": ["thread"]])diff --git a/CodexBarTests/Activity/ActivitySchedulingTests.swift b/CodexBarTests/Activity/ActivitySchedulingTests.swiftindex 174e7b3..76575a0 100644--- a/CodexBarTests/Activity/ActivitySchedulingTests.swift+++ b/CodexBarTests/Activity/ActivitySchedulingTests.swift@@ -23,7 +23,7 @@ struct ActivitySchedulingTests {#expect(observed.wait(timeout: .now() + 2) == .success)try peer.reply(to: read, result: ["thread": Self.thread(timestamp, status: "idle")])let turns = try peer.readMessage()- try peer.reply(to: turns, result: ["data": [["id": "turn", "status": "inProgress", "startedAt": timestamp]]])+ try peer.reply(to: turns, result: ["data": [["id": "turn", "rootTurnId": "turn", "status": "inProgress", "startedAt": timestamp]]])_ = release.wait(timeout: .now() + 5)}defer { server.close() }@@ -46,8 +46,8 @@ struct ActivitySchedulingTests {try await Task.sleep(for: .milliseconds(5))}#expect(ready)- #expect(await reader.drainNow() == .completed)- let reference = ActivityTurnReference(threadID: "thread", turnID: "turn", startedAt: Date(timeIntervalSince1970: timestamp))+ #expect(await reader.drainNow() == .sourceUnavailable)+ let reference = ActivityTurnReference(threadID: "thread", turnID: "turn")#expect(await lifecycle.lifecycleStates(for: [reference]).first?.isWaitingApproval == true)await reader.stop()release.signal()@@ -160,7 +160,7 @@ struct ActivitySchedulingTests {#expect(discoveries.withLock { $0 } == 2)if ready, !disconnected {#expect(await reader.drainNow() == .completed)- let reference = ActivityTurnReference(threadID: "a-missing", turnID: "turn", startedAt: Date(timeIntervalSince1970: timestamp))+ let reference = ActivityTurnReference(threadID: "a-missing", turnID: "turn")#expect(await lifecycle.lifecycleStates(for: [reference]).first?.readStatus == .complete)#expect(!disconnected)}@@ -202,10 +202,10 @@ struct ActivitySchedulingTests {#expect(published == 1)#expect(failures == 0)try FileManager.default.removeItem(at: blocker)- for _ in 0 ..< 150 where HistoryStorage.loadMaintenanceState(in: directory.url).days.isEmpty {+ for _ in 0 ..< 150 where try HistoryStorage.loadMaintenanceState(in: directory.url).days.isEmpty {try await Task.sleep(for: .milliseconds(10))}- #expect(!HistoryStorage.loadMaintenanceState(in: directory.url).days.isEmpty)+ #expect(try !HistoryStorage.loadMaintenanceState(in: directory.url).days.isEmpty)#expect(failures == 0)#expect(published == 1)await reader.stop()@@ -230,7 +230,7 @@ struct ActivitySchedulingTests {onDiscovery: @Sendable () -> Void) throws {let initialize = try peer.readMessage()- try peer.reply(to: initialize, result: ["userAgent": "codex/0.160.0"])+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])#expect(try peer.readMessage()["method"] as? String == "initialized")let loaded = try peer.readMessage()try peer.reply(to: loaded, result: ["data": ["a-missing", "thread"]])@@ -252,7 +252,7 @@ struct ActivitySchedulingTests {try peer.reply(to: request, result: ["thread": Self.thread(timestamp)])}let turns = try peer.readMessage()- try peer.reply(to: turns, result: ["data": [["id": "turn", "status": "inProgress", "startedAt": timestamp]]])+ try peer.reply(to: turns, result: ["data": [["id": "turn", "rootTurnId": "turn", "status": "inProgress", "startedAt": timestamp]]])try peer.send(["method": "item/started", "params": ["threadId": "thread", "turnId": "turn", "item": ["id": "tool", "type": "commandExecution"]]])@@ -279,7 +279,8 @@ struct ActivitySchedulingTests {}let request = try peer.readMessage()#expect(request["method"] as? String == "thread/turns/list")- try peer.reply(to: request, result: ["data": [["id": "turn", "status": "inProgress", "startedAt": timestamp]]])+ #expect((request["params"] as? [String: Any])?["itemsView"] as? String == (id == "a-missing" ? "full" : "notLoaded"))+ try peer.reply(to: request, result: ["data": [["id": "turn", "rootTurnId": "turn", "status": "inProgress", "startedAt": timestamp]]])}_ = release.wait(timeout: .now() + 5)}@@ -290,7 +291,7 @@ struct ActivitySchedulingTests {private nonisolated static func bootstrap(_ peer: SharedServerFixture.Peer, timestamp: Double, idle: Bool = false) throws {let initialize = try peer.readMessage()- try peer.reply(to: initialize, result: ["userAgent": "codex/0.160.0"])+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])_ = try peer.readMessage()let loaded = try peer.readMessage()try peer.reply(to: loaded, result: ["data": ["thread"]])@@ -299,6 +300,123 @@ struct ActivitySchedulingTests {try peer.reply(to: request, result: ["thread": thread(timestamp, status: idle ? "idle" : "active")])}let turns = try peer.readMessage()- try peer.reply(to: turns, result: ["data": [["id": "turn", "status": idle ? "completed" : "inProgress", "startedAt": timestamp]]])+ #expect(turns["method"] as? String == "thread/turns/list")+ #expect((turns["params"] as? [String: Any])?["itemsView"] as? String == "full")+ try peer.reply(to: turns, result: ["data": [["id": "turn", "rootTurnId": "turn", "status": idle ? "completed" : "inProgress", "startedAt": timestamp]]])+ }+}++extension ActivitySchedulingTests {+ @Test func turnPaginationResumesAndDoesNotVerifyOmittedTurn() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let timestamp = Date().addingTimeInterval(-60).timeIntervalSince1970+ let server = try SharedServerFixture { peer in+ try Self.bootstrap(peer, timestamp: timestamp)+ for cycle in 0 ..< 2 {+ let loaded = try peer.readMessage()+ try peer.reply(to: loaded, result: ["data": ["thread"]])+ let read = try peer.readMessage()+ try peer.reply(to: read, result: ["thread": Self.thread(timestamp, status: "idle")])+ let first = try peer.readMessage()+ #expect((first["params"] as? [String: Any])?["cursor"] == nil)+ let recent = (0 ..< 10).map { ["id": "recent-\($0)", "status": "completed"] }+ try peer.reply(to: first, result: ["data": recent, "nextCursor": "page-1"])+ if cycle == 0 {+ for page in 1 ... 8 {+ let request = try peer.readMessage()+ #expect((request["params"] as? [String: Any])?["cursor"] as? String == "page-\(page)")+ try peer.reply(to: request, result: ["data": [["id": "history-\(page)", "status": "completed"]], "nextCursor": "page-\(page + 1)"])+ }+ } else {+ let request = try peer.readMessage()+ #expect((request["params"] as? [String: Any])?["cursor"] as? String == "page-9")+ try peer.reply(to: request, result: ["data": [["id": "turn", "rootTurnId": "turn", "status": "completed", "completedAt": timestamp + 30]]])+ }+ }+ _ = release.wait(timeout: .now() + 5)+ }+ defer { server.close() }+ let cache = SessionLifecycleCache()+ var ready = false+ let reader = AppServerActivityReader(+ lifecycleCache: cache,+ socketURL: server.url,+ logStorage: nil,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url),+ recorder: ActivityRecorder(directoryURL: directory.url)+ ) {+ if case .bootstrapEnd = $0 {+ ready = true+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where !ready {+ try await Task.sleep(for: .milliseconds(5))+ }+ try #require(ready)+ let reference = ActivityTurnReference(threadID: "thread", turnID: "turn")+ #expect(await reader.drainNow() == .sourceUnavailable)+ #expect(await cache.lifecycleStates(for: [reference]).first?.readStatus == .unavailable)+ #expect(await reader.drainNow() == .completed)+ let state = try #require(await cache.lifecycleStates(for: [reference]).first)+ #expect(state.readStatus == .complete)+ #expect(state.terminal != nil)+ #expect(await reader.stop())+ release.signal()+ try server.finish()+ }++ @Test(arguments: [false, true])+ func stopWaitsForPendingWritesAndReportsPersistenceFailure(failFirstStop: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let blocker = try directory.write("block maintenance directory", to: "State")+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let server = try SharedServerFixture { peer in+ try Self.bootstrap(peer, timestamp: Date().addingTimeInterval(-60).timeIntervalSince1970)+ try peer.send(["method": "item/started", "params": ["threadId": "thread", "turnId": "turn", "item": ["id": "tool", "type": "commandExecution"]]])+ _ = release.wait(timeout: .now() + 5)+ }+ defer { server.close() }+ var published = false+ let reader = AppServerActivityReader(+ lifecycleCache: SessionLifecycleCache(),+ socketURL: server.url,+ logStorage: nil,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url),+ recorder: ActivityRecorder(directoryURL: directory.url)+ ) {+ if case let .live(events) = $0, !events.isEmpty {+ published = true+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where !published {+ try await Task.sleep(for: .milliseconds(5))+ }+ try #require(published)+ if failFirstStop {+ #expect(await reader.stop() == false)+ }+ try FileManager.default.removeItem(at: blocker)+ #expect(await reader.stop())+ let dates = HistoryStorage.eventLogDateKeys(in: HistoryStorage.eventsDirectoryURL(in: directory.url))+ var count = 0+ for date in dates {+ let url = HistoryStorage.eventLogURL(for: date, in: HistoryStorage.eventsDirectoryURL(in: directory.url))+ try AppServerEventJournal.read(at: url) {+ if $0.activity != nil {+ count += 1+ }+ }+ }+ #expect(count == 1)+ #expect(try !HistoryStorage.loadMaintenanceState(in: directory.url).pending.isEmpty)+ release.signal()+ try server.finish()}}diff --git a/CodexBarTests/Activity/ActivityTaskTests.swift b/CodexBarTests/Activity/ActivityTaskTests.swiftindex 8c72269..5fe1c80 100644--- a/CodexBarTests/Activity/ActivityTaskTests.swift+++ b/CodexBarTests/Activity/ActivityTaskTests.swift@@ -2,6 +2,194 @@ import Foundationimport Testingstruct ActivityTaskTests {+ @Test(arguments: [ActivityEventKind.turnCompleted, .turnAborted])+ func terminalSnapshotPreservesTaskIdentityAcrossTurns(terminal: ActivityEventKind) 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), activityDirectoryURL: directory.url+ )+ defer { monitor.stop() }+ monitor.isActivitySourceHealthy = true+ let now = Date()+ monitor.consume(.live([TestFixtures.event(at: now)]))+ let firstID = try #require(monitor.tasks.values.first?.snapshot.id)+ monitor.consume(.live([TestFixtures.event(terminal, at: now.addingTimeInterval(1))]))+ if terminal == .turnCompleted {+ let completion = try #require(monitor.completions.first)+ #expect(completion.taskID == firstID)+ #expect(completion.id != firstID)+ } else {+ let termination = try #require(monitor.terminations.first)+ #expect(termination.taskID == firstID)+ #expect(termination.id != firstID)+ }+ monitor.consume(.live([TestFixtures.event(at: now.addingTimeInterval(2), turn: "turn-b")]))+ let nextID = try #require(monitor.tasks.values.first?.snapshot.id)+ #expect(nextID != firstID)+ }++ @Test(arguments: ["thread", "turn", "both", "empty-thread", "empty-turn"], [false, true])+ func incompleteIdentityCannotCreateOrChangeTasks(missing: String, snapshot: Bool) 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), activityDirectoryURL: directory.url+ )+ defer { monitor.stop() }+ monitor.isActivitySourceHealthy = true+ let now = Date()+ let thread: String? = switch missing {+ case "thread", "both": nil+ case "empty-thread": ""+ default: "thread-a"+ }+ let turn: String? = switch missing {+ case "turn", "both": nil+ case "empty-turn": ""+ default: "turn-a"+ }+ let events = ActivityEventKind.allCases.map {+ TestFixtures.event($0, at: now.addingTimeInterval(1), thread: thread, turn: turn)+ }+ monitor.consume(snapshot ? .snapshotEvents(events) : .live(events))+ #expect(monitor.tasks.isEmpty)+ #expect(monitor.completions.isEmpty)+ #expect(monitor.terminations.isEmpty)+ monitor.consume(.live([TestFixtures.event(at: now)]))+ let original = try #require(monitor.tasks.values.first?.snapshot)+ monitor.consume(snapshot ? .snapshotEvents(events) : .live(events))+ #expect(monitor.tasks.count == 1)+ #expect(monitor.tasks.values.first?.snapshot == original)+ #expect(monitor.completions.isEmpty)+ #expect(monitor.terminations.isEmpty)+ #expect(monitor.pendingTerminalTasks.isEmpty)+ #expect(monitor.terminalTokenUsageRequests.isEmpty)+ }++ @Test func lateTerminalOnlyCompletesItsOwnTurnOnce() 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), activityDirectoryURL: directory.url+ )+ defer { monitor.stop() }+ monitor.isActivitySourceHealthy = true+ let now = Date()+ monitor.consume(.live([TestFixtures.event(at: now)]))+ monitor.consume(.live([TestFixtures.event(at: now.addingTimeInterval(1), turn: "turn-b")]))+ let terminal = TestFixtures.event(.turnCompleted, at: now.addingTimeInterval(2))+ monitor.consume(.live([terminal, terminal]))+ #expect(Set(monitor.tasks.keys) == [.init(thread: "thread-a", turn: "turn-b")])+ #expect(monitor.pendingTerminalTasks.isEmpty)+ #expect(monitor.completions.count == 1)+ #expect(monitor.terminations.isEmpty)+ }++ @Test func dailySnapshotDoesNotEnterConnectionRecovery() 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), activityDirectoryURL: directory.url+ )+ defer { monitor.stop() }+ monitor.isActivitySourceHealthy = true+ let presentation = monitor.sourcePresentation+ monitor.consume(.snapshotEvents([TestFixtures.event(at: Date())]))+ #expect(monitor.tasks.count == 1)+ #expect(monitor.sourcePresentation == presentation)+ #expect(!monitor.isBootstrapping)+ }++ @Test func guardianIsFilteredAtEntryAndAutoReviewedUserTaskRemainsVisible() 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), activityDirectoryURL: directory.url+ )+ defer { monitor.stop() }+ monitor.isActivitySourceHealthy = true+ let now = Date()+ for kind in [ActivityEventKind.turnStarted, .toolStarted, .approvalRequested, .turnCompleted, .turnAborted] {+ monitor.consume(.live([TestFixtures.event(kind, at: now, origin: .autoReview)]))+ }+ #expect(monitor.tasks.isEmpty)+ #expect(monitor.pendingTerminalTasks.isEmpty)+ #expect(monitor.completions.isEmpty)+ #expect(monitor.terminations.isEmpty)+ #expect(monitor.recentlyEndedTaskAt.isEmpty)+ monitor.consume(.live([TestFixtures.event(at: now)]))+ #expect(monitor.tasks.count == 1)+ }++ @Test func subagentLinkRetentionDoesNotDependOnIdentityOrRefreshTime() 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), activityDirectoryURL: directory.url+ )+ defer { monitor.stop() }+ let root = ActivityTaskKey(thread: "root", turn: "root-turn")+ let child = ActivityTurnReference(threadID: "child", turnID: "child-turn")+ let expired = Date().addingTimeInterval(-ActivityRetention.window - 1)+ monitor.subagentTurnLinks[child] = (root, expired)+ var state = SessionLifecycleState(+ requestedThreadID: "child", turnID: "child-turn", startedAt: nil,+ effort: nil, lastProgressAt: nil, terminal: nil+ )+ state.rootThreadID = "root"+ state.rootTurnID = "root-turn"+ state.parentThreadID = "root"+ _ = monitor.applySubagentLifecycle(state, terminalOnly: false)+ #expect(monitor.subagentTurnLinks[child]?.retainedAt == expired)+ _ = monitor.subagentLifecycleReferences()+ #expect(monitor.subagentTurnLinks[child] == nil)+ }++ @Test func incompleteSubagentRootCannotBeGuessedFromQueuedEventsOrPreviousLink() 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), activityDirectoryURL: directory.url+ )+ defer { monitor.stop() }+ let event = TestFixtures.event(.toolStarted, agent: "child", origin: .auxiliary)+ #expect(monitor.deferUnassociatedSubagentEvent(event, source: .live))+ var state = SessionLifecycleState(+ requestedThreadID: "child", turnID: "turn-a", startedAt: TestFixtures.now,+ effort: nil, lastProgressAt: nil, terminal: nil,+ rootTurnID: "turn-a", parentThreadID: "thread-a"+ )+ let reference = ActivityTurnReference(threadID: "child", turnID: "turn-a")+ #expect(!monitor.applySubagentLifecycle(state, terminalOnly: false))+ #expect(monitor.subagentTurnLinks[reference] == nil)+ monitor.subagentTurnLinks[reference] = (.init(thread: "thread-a", turn: "turn-a"), TestFixtures.now)+ #expect(!monitor.applySubagentLifecycle(state, terminalOnly: false))+ state.rootThreadID = "different-thread"+ #expect(!monitor.applySubagentLifecycle(state, terminalOnly: false))+ }+@Test(arguments: [-172800.0, 0.5, 2.0])func lifecycleBackfillsMissingStartWithTimestampTolerance(offset: TimeInterval) {var task = makeTask()@@ -17,49 +205,84 @@ struct ActivityTaskTests {}}- @Test func namelessToolAndApprovalDoNotReusePreviousToolName() {+ @Test func onlyPendingApprovalExposesNotificationAction() {var task = makeTask(TestFixtures.event(.toolStarted))- #expect(task.snapshot.toolName == "exec_command")+ #expect(task.snapshot.approvalActionText == nil)let event = ActivityRecord(timestamp: TestFixtures.now.addingTimeInterval(1), name: ActivityEventKind.toolStarted.rawValue,- origin: .main, cwd: nil, tool: nil, model: nil, effort: nil,- approvalReviewer: .user, sessionID: "session-a", turnID: "turn-a", agentID: nil+ origin: .main, cwd: nil, toolName: nil, model: nil, effort: nil,+ threadID: "thread-a", turnID: "turn-a", agentID: nil)var nameless = event- nameless.source = AppServerEventSource(method: "item/started", threadID: "session-a", itemType: "fileChange")+ nameless.context = ActivityContext(method: "item/started", threadID: "thread-a", itemType: "fileChange")task.mergeMetadata(from: nameless)- #expect(task.snapshot.toolName == nil)- #expect(task.snapshot.toolDisplayName == String(localized: "activity.action.edit-files"))+ #expect(task.snapshot.approvalActionText == nil)var approval = ActivityRecord(timestamp: TestFixtures.now.addingTimeInterval(2), name: ActivityEventKind.approvalRequested.rawValue,- origin: .main, cwd: nil, tool: nil, model: nil, effort: nil,- approvalReviewer: .user, sessionID: "session-a", turnID: "turn-a", agentID: nil+ origin: .main, cwd: nil, toolName: nil, model: nil, effort: nil,+ threadID: "thread-a", turnID: "turn-a", agentID: nil)- approval.source = AppServerEventSource(method: "item/commandExecution/requestApproval", threadID: "session-a", itemType: "commandExecution")+ approval.context = ActivityContext(method: "item/commandExecution/requestApproval", threadID: "thread-a", itemType: "commandExecution")task.mergeMetadata(from: approval)let enteredWaiting = task.recordApprovalRequest(from: approval)#expect(enteredWaiting)- #expect(task.snapshot.toolName == nil)- #expect(task.snapshot.toolDisplayName == String(localized: "activity.action.command"))+ #expect(task.snapshot.approvalActionText == String(localized: "activity.action.command"))+ task.resumeExecution(from: TestFixtures.event(.toolStarted, at: TestFixtures.now.addingTimeInterval(3)))+ #expect(task.snapshot.approvalActionText == String(localized: "activity.action.command"))+ var lifecycle = healthyLifecycle(startedAt: TestFixtures.now)+ lifecycle.isWaitingApproval = false+ lifecycle.approvalChangedAt = TestFixtures.now.addingTimeInterval(4)+ task.mergeExecutionLifecycle(lifecycle, owner: ActivityExecutionKey(agentID: nil, turnID: "turn-a"))+ #expect(task.snapshot.approvalActionText == nil)+ }++ @Test(arguments: [nil, [], ["read"]] as [[String]?])+ func approvalActionsDoNotFallBackToAnotherCommandsActions(_ actions: [String]?) {+ var task = makeTask()+ var earlier = TestFixtures.event(.toolStarted)+ earlier.context = ActivityContext(method: "item/started", threadID: "thread-a", itemType: "commandExecution")+ task.mergeMetadata(from: earlier)+ var approval = ActivityRecord(+ timestamp: TestFixtures.now.addingTimeInterval(1), name: ActivityEventKind.approvalRequested.rawValue,+ origin: .main, cwd: nil, toolName: nil, commandActionTypes: actions, model: nil, effort: nil,+ threadID: "thread-a", turnID: "turn-a", agentID: nil+ )+ approval.context = ActivityContext(method: "item/commandExecution/requestApproval", threadID: "thread-a", itemType: "commandExecution")+ let enteredWaiting = task.recordApprovalRequest(from: approval)+ #expect(enteredWaiting)+ #expect(task.displayedApproval?.commandActionTypes == actions)+ let expected = actions?.isEmpty == false+ ? String(localized: "activity.live.actions-read")+ : String(localized: "activity.action.command")+ #expect(task.snapshot.approvalActionText == expected)}- @Test func anonymousTaskHasNoProtectionIdentityOrPreciseDuration() {- let task = makeTask(TestFixtures.event(session: nil))- #expect(task.key.isAnonymous)- #expect(task.key.protectionIdentifier == nil)- #expect(!task.snapshot.showsPreciseDuration)- #expect(task.preciseDuration(until: TestFixtures.now.addingTimeInterval(60)) == nil)+ @Test func unknownSourceCannotReuseAnotherEventsOrigin() 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), activityDirectoryURL: directory.url+ )+ defer { monitor.stop() }+ monitor.isActivitySourceHealthy = true+ monitor.consume(.live([TestFixtures.event(at: Date())]))+ monitor.consume(.live([TestFixtures.event(.turnCompleted, at: Date(), origin: .unknown)]))+ #expect(monitor.tasks.count == 1)+ #expect(monitor.completions.isEmpty)}- @Test func taskIdentitySeparatesSessionsTurnsAndAnonymousProjects() {- #expect(ActivityTaskKey(event: TestFixtures.event()).sessionID == "session-a")- #expect(ActivityTaskKey(event: TestFixtures.event(turn: nil)).isSessionOnly)- let first = ActivityTaskKey.turn(session: "ab", turn: "c").protectionIdentifier- let second = ActivityTaskKey.turn(session: "a", turn: "bc").protectionIdentifier+ @Test func taskIdentityRequiresSessionAndTurnAndSeparatesTheirBoundaries() {+ #expect(ActivityTaskKey(event: TestFixtures.event())?.threadID == "thread-a")+ #expect(ActivityTaskKey(event: TestFixtures.event(turn: nil)) == nil)+ #expect(ActivityTaskKey(event: TestFixtures.event(thread: nil)) == nil)+ let first = ActivityTaskKey(thread: "ab", turn: "c").protectionIdentifier+ let second = ActivityTaskKey(thread: "a", turn: "bc").protectionIdentifier#expect(first != second)- #expect(first?.count == 64)- #expect(first != ActivityTaskKey.session("ab").protectionIdentifier)+ #expect(first.count == 64)}@Test func preciseDurationRequiresKnownStartAndNonnegativeInterval() {@@ -87,8 +310,8 @@ struct ActivityTaskTests {@Test func executionProgressDoesNotMoveEventOrderingBarrier() {var task = makeTask()task.recordProgress(at: TestFixtures.now.addingTimeInterval(30))- task.recordEvent(at: TestFixtures.now.addingTimeInterval(10))- #expect(task.lastEventAt == TestFixtures.now.addingTimeInterval(10))+ task.recordProgress(at: TestFixtures.now.addingTimeInterval(10))+ #expect(task.acceptsExecutionEvent(TestFixtures.event(.toolCompleted, at: TestFixtures.now.addingTimeInterval(10))))#expect(task.lastProgressAt == TestFixtures.now.addingTimeInterval(30))#expect(task.progressGeneration == 3)}@@ -117,13 +340,15 @@ struct ActivityTaskTests {#expect(task.protectionDeadline(at: now, inactivityDuration: 3600) == nil)}- @Test func unavailableSourceCannotResumeApprovalButCompleteProgressCan() {+ @Test func onlyCompleteAuthoritativeStateCanResumeApproval() {var task = makeTask()_ = task.recordApprovalRequest(from: TestFixtures.event(.approvalRequested))let now = TestFixtures.now.addingTimeInterval(3600)var state = healthyLifecycle()state.readStatus = .unavailable- state.lastExecutionProgressAt = now+ state.lastProgressAt = now+ state.isWaitingApproval = false+ state.approvalChangedAt = nowlet owner = ActivityExecutionKey(agentID: nil, turnID: "turn-a")task.recordLifecycleRead(state, at: now)task.mergeExecutionLifecycle(state, owner: owner)@@ -139,7 +364,7 @@ struct ActivityTaskTests {private func healthyLifecycle(startedAt: Date? = nil) -> SessionLifecycleState {SessionLifecycleState(- requestedThreadID: "session-a", turnID: "turn-a", startedAt: startedAt, approvalReviewer: nil, effort: nil,+ requestedThreadID: "thread-a", turnID: "turn-a", startedAt: startedAt, effort: nil,lastProgressAt: nil, terminal: nil, readStatus: .complete)}@@ -199,7 +424,7 @@ struct ActivityTaskTests {let newDeadline = progressStoppedAt.addingTimeInterval(newDuration.timeInterval)var task = makeTask(TestFixtures.event(at: progressStoppedAt))let key = task.key- let identifier = try #require(key.protectionIdentifier)+ let identifier = key.protectionIdentifiertask.recordLifecycleRead(healthyLifecycle(), at: hiddenAt)monitor.tasks[key] = taskmonitor.protectionSettings.setInactivityDuration(previousDuration)@@ -233,6 +458,7 @@ struct ActivityTaskTests {protectionSettings: ProtectionSettings(defaults: preferences.defaults),protectionStore: ProtectionStore(directoryURL: directory.url))+ monitor.protectionLoadState = .availablemonitor.isStarted = truemonitor.isProtectionEnabled = truemonitor.isActivitySourceHealthy = true@@ -246,6 +472,8 @@ struct ActivityTaskTests {@Test func subagentCountDeduplicatesAndRejectsOlderEvents() {var task = makeTask()+ #expect(task.snapshot.activeSubagentCount == nil)+ task.hasCompleteSubagentCoverage = true#expect(task.snapshot.activeSubagentCount == 0)task.recordSubagentActivity(agentID: "agent", isStarting: true, at: TestFixtures.now)task.recordSubagentActivity(agentID: "agent", isStarting: true, at: TestFixtures.now)@@ -257,35 +485,23 @@ struct ActivityTaskTests {@Test func missingSubagentIdentityAndUnmatchedStopMakeCountUnavailable() {var missing = makeTask()+ missing.hasCompleteSubagentCoverage = truemissing.recordSubagentActivity(agentID: nil, isStarting: true, at: TestFixtures.now)#expect(missing.snapshot.activeSubagentCount == nil)var unmatched = makeTask()+ unmatched.hasCompleteSubagentCoverage = trueunmatched.recordSubagentActivity(agentID: "unknown", isStarting: false, at: TestFixtures.now)#expect(unmatched.snapshot.activeSubagentCount == nil)}- @Test func onlyUserApprovalTransitionsToWaiting() {- for reviewer in [ApprovalReviewer.user, .autoReview, .guardianSubagent] {- var task = makeTask(TestFixtures.event(reviewer: reviewer))- let transitioned = task.recordApprovalRequest(from: TestFixtures.event(.approvalRequested, reviewer: reviewer))- #expect(transitioned == (reviewer == .user))- #expect(task.state == (reviewer == .user ? .waitingApproval : .running))- }- }-- @Test func unknownApprovalWaitsForContextOfSameExecution() {- var task = makeTask(TestFixtures.event(reviewer: nil))- let requestedWaiting = task.recordApprovalRequest(from: TestFixtures.event(.approvalRequested, reviewer: nil))- #expect(!requestedWaiting)- let otherOwner = ActivityExecutionKey(agentID: "other", turnID: "turn-a")- task.mergeApprovalContext(reviewer: .user, observedAt: TestFixtures.now, owner: otherOwner)- let resolvedOtherExecution = task.resolvePendingApprovals()- #expect(!resolvedOtherExecution)- #expect(task.state == .running)- let owner = ActivityExecutionKey(agentID: nil, turnID: "turn-a")- task.mergeApprovalContext(reviewer: .user, observedAt: TestFixtures.now, owner: owner)- let resolvedOwner = task.resolvePendingApprovals()- #expect(resolvedOwner)+ @Test func approvalRequestImmediatelyWaitsWithoutReviewerContext() {+ var task = makeTask(TestFixtures.event())+ let request = TestFixtures.event(.approvalRequested)+ let enteredWaiting = task.recordApprovalRequest(from: request)+ #expect(enteredWaiting)+ #expect(task.state == .waitingApproval)+ let repeated = task.recordApprovalRequest(from: request)+ #expect(!repeated)#expect(task.state == .waitingApproval)}@@ -297,6 +513,8 @@ struct ActivityTaskTests {task.resumeExecution(from: TestFixtures.event(.toolCompleted, at: TestFixtures.now.addingTimeInterval(1)))#expect(task.state == .waitingApproval)task.resumeExecution(from: TestFixtures.event(.toolCompleted, at: TestFixtures.now.addingTimeInterval(2), agent: "agent", origin: .auxiliary))+ #expect(task.state == .waitingApproval)+ task.finishExecution(ActivityExecutionKey(agentID: "agent", turnID: "turn-a"), at: TestFixtures.now.addingTimeInterval(3))#expect(task.state == .running)}@@ -314,30 +532,29 @@ struct ActivityTaskTests {#expect(task.state == .running)}- @Test func lateApprovalDoesNotUndoConfirmedExecutionProgress() {+ @Test func anotherToolsProgressDoesNotInvalidateAnApprovalRequest() {var task = makeTask()let progress = TestFixtures.now.addingTimeInterval(2)task.resumeExecution(from: TestFixtures.event(.toolCompleted, at: progress))let lateRequestChanged = task.recordApprovalRequest(from: TestFixtures.event(.approvalRequested))- #expect(!lateRequestChanged)- #expect(task.state == .running)+ #expect(lateRequestChanged)+ #expect(task.state == .waitingApproval)task.finishExecution(ActivityExecutionKey(agentID: nil, turnID: "turn-a"), at: progress)#expect(!task.acceptsExecutionEvent(TestFixtures.event(.toolStarted, at: progress.addingTimeInterval(1))))}- @Test func equalTimestampExecutionProgressDoesNotDismissApproval() {+ @Test func executionProgressDoesNotDismissApproval() {var task = makeTask()_ = task.recordApprovalRequest(from: TestFixtures.event(.approvalRequested))- let owner = ActivityExecutionKey(agentID: nil, turnID: "turn-a")- task.mergeExecutionProgress(at: TestFixtures.now, owner: owner)+ task.resumeExecution(from: TestFixtures.event(.toolCompleted))+ #expect(task.state == .waitingApproval)+ task.resumeExecution(from: TestFixtures.event(.toolCompleted, at: TestFixtures.now.addingTimeInterval(0.001)))#expect(task.state == .waitingApproval)- task.mergeExecutionProgress(at: TestFixtures.now.addingTimeInterval(0.001), owner: owner)- #expect(task.state == .running)}private func makeTask(_ event: ActivityRecord = TestFixtures.event()) -> ActivityTask {ActivityTask(- displayID: UUID(), key: ActivityTaskKey(event: event), event: event,+ displayID: UUID(), key: ActivityTaskKey(event: event)!, event: event,state: .running, startedAt: event.timestamp, progressGeneration: 1)}diff --git a/CodexBarTests/Activity/ActivityTokenUsageTests.swift b/CodexBarTests/Activity/ActivityTokenUsageTests.swiftindex f4154ed..840a0d4 100644--- a/CodexBarTests/Activity/ActivityTokenUsageTests.swift+++ b/CodexBarTests/Activity/ActivityTokenUsageTests.swift@@ -16,14 +16,14 @@ struct ActivityTokenUsageTests {}@Test(arguments: [true, false])- func rootAndMultipleChildTurnsAreSummedOnce(explicitRootSession: Bool) throws {- let root = reference("session-a", "turn-a")+ func rootAndMultipleChildTurnsAreSummedOnce(explicitRootThread: Bool) throws {+ let root = reference("thread-a", "turn-a")let first = reference("child-a", "child-turn-a")let second = reference("child-a", "child-turn-b")let third = reference("child-b", "child-turn-c")let request = request(root: root, children: [first, second, third, first])var rootState = state(root, input: 100)- rootState.rootSessionID = explicitRootSession ? root.threadID : nil+ rootState.rootThreadID = explicitRootThread ? root.threadID : nillet states = [rootState, state(first, input: 200), state(second, input: 300), state(third, input: 400)]let usage = try #require(request.usage(from: states))#expect(usage.inputTokens == 1000)@@ -34,14 +34,14 @@ struct ActivityTokenUsageTests {@Test(arguments: ["missing", "unavailable", "other-root", "other-session", "running-child", "missing-usage"])func incompleteOrUnrelatedChildPreventsPartialTotal(scenario: String) {- let root = reference("session-a", "turn-a")+ let root = reference("thread-a", "turn-a")let child = reference("child-a", "child-turn")let request = request(root: root, children: [child])var childState = state(child)switch scenario {case "unavailable": childState.readStatus = .unavailablecase "other-root": childState.rootTurnID = "other-root"- case "other-session": childState.rootSessionID = "other-session"+ case "other-session": childState.rootThreadID = "other-session"case "missing-usage": childState.tokenUsage = nilcase "running-child": childState = state(child, terminal: nil)default: break@@ -51,15 +51,15 @@ struct ActivityTokenUsageTests {}@Test func knownAgentWithoutResolvedTurnPreventsPartialTotal() {- let root = reference("session-a", "turn-a")+ let root = reference("thread-a", "turn-a")let request = TaskTokenRequest(- root: root, expectedAgentIDs: ["unknown-child"], references: [root], deadline: TestFixtures.now+ root: root, expectedAgentIDs: ["unknown-child"], references: [root])#expect(request.usage(from: [state(root)]) == nil)}@Test func inProgressUsageIncludesAvailableRunningAndCompletedChildren() throws {- let root = reference("session-a", "turn-a")+ let root = reference("thread-a", "turn-a")let running = reference("child-a", "child-turn-a")let completed = reference("child-a", "child-turn-b")let unknown = reference("child-b", "child-turn-c")@@ -74,13 +74,13 @@ struct ActivityTokenUsageTests {@Test(arguments: ["other-root", "other-session", "other-thread", "unavailable", "missing-usage"])func inProgressUsageDoesNotIncludeUnverifiedChildren(scenario: String) {- let root = reference("session-a", "turn-a")+ let root = reference("thread-a", "turn-a")let child = reference("child-a", "child-turn")let request = request(root: root, children: [child])var childState = state(child, terminal: nil)switch scenario {case "other-root": childState.rootTurnID = "other-root"- case "other-session": childState.rootSessionID = "other-session"+ case "other-session": childState.rootThreadID = "other-session"case "other-thread": childState = state(reference("other-thread", child.turnID), terminal: nil)case "unavailable": childState.readStatus = .unavailabledefault: childState.tokenUsage = nil@@ -96,14 +96,14 @@ struct ActivityTokenUsageTests {defer { preferences.remove() }let monitor = try makeMonitor(directory: directory, preferences: preferences)let event = TestFixtures.event()- let key = ActivityTaskKey(event: event)+ let key = try #require(ActivityTaskKey(event: event))monitor.tasks[key] = ActivityTask(displayID: UUID(), key: key, event: event, state: .running,startedAt: TestFixtures.now, progressGeneration: 1)- let root = reference("session-a", "turn-a")+ let root = reference("thread-a", "turn-a")let child = reference("child-a", "child-turn")- monitor.subagentTurnLinks[child] = key+ monitor.subagentTurnLinks[child] = (key, TestFixtures.now)#expect(Set(monitor.activeTokenUsageReferences()) == [root, child])#expect(monitor.tasks[key]?.snapshot.tokenUsage == nil)let initial = [state(root, terminal: nil)]@@ -138,14 +138,14 @@ struct ActivityTokenUsageTests {defer { preferences.remove() }let monitor = try makeMonitor(directory: directory, preferences: preferences)let event = TestFixtures.event(turn: "turn-b")- let key = ActivityTaskKey(event: event)+ let key = try #require(ActivityTaskKey(event: event))monitor.tasks[key] = ActivityTask(displayID: UUID(), key: key, event: event, state: .running,startedAt: TestFixtures.now, progressGeneration: 1)- #expect(!monitor.applyActiveTokenUsage([state(reference("session-a", "turn-a"))]))+ #expect(!monitor.applyActiveTokenUsage([state(reference("thread-a", "turn-a"))]))#expect(monitor.tasks[key]?.tokenUsage == nil)- var current = state(reference("session-a", "turn-b"), terminal: nil)+ var current = state(reference("thread-a", "turn-b"), terminal: nil)current.rootTurnID = "turn-b"#expect(monitor.applyActiveTokenUsage([current]))#expect(monitor.tasks[key]?.tokenUsage?.totalTokens == 110)@@ -176,7 +176,7 @@ struct ActivityTokenUsageTests {defer { preferences.remove() }let monitor = try makeMonitor(directory: directory, preferences: preferences)let event = TestFixtures.event()- let key = ActivityTaskKey(event: event)+ let key = try #require(ActivityTaskKey(event: event))let task = ActivityTask(displayID: UUID(), key: key, event: event, state: .running,startedAt: TestFixtures.now, progressGeneration: 1@@ -187,19 +187,19 @@ struct ActivityTokenUsageTests {abortFallback: TestFixtures.now, into: &transitions)let completedID = try #require(monitor.completions.first?.id)- let otherEvent = TestFixtures.event(turn: "turn-b")- let otherKey = ActivityTaskKey(event: otherEvent)+ let otherEvent = TestFixtures.event(.turnAborted, turn: "turn-b")+ let otherKey = try #require(ActivityTaskKey(event: otherEvent))monitor.tasks[otherKey] = ActivityTask(displayID: UUID(), key: otherKey, event: otherEvent, state: .running,startedAt: TestFixtures.now, progressGeneration: 1)- monitor.interruptTask(from: otherEvent, source: .bootstrap)+ monitor.finishTask(from: otherEvent, source: .bootstrap, into: &transitions)#expect(monitor.completions.first?.tokenUsage == nil)#expect(monitor.terminations.first?.tokenUsage == nil)- var stopped = state(reference("session-a", "turn-b"), input: 200, terminal: nil)+ var stopped = state(reference("thread-a", "turn-b"), input: 200, terminal: nil)stopped.rootTurnID = "turn-b"- let states = [state(reference("session-a", "turn-a")), stopped]+ let states = [state(reference("thread-a", "turn-a")), stopped]#expect(monitor.applyTerminalTokenUsage(states))#expect(monitor.completions.first?.tokenUsage?.totalTokens == 110)#expect(monitor.terminations.first?.tokenUsage?.totalTokens == 210)@@ -209,12 +209,11 @@ struct ActivityTokenUsageTests {stopped.readStatus = .unavailable#expect(!monitor.applyTerminalTokenUsage([stopped]))#expect(monitor.terminations.first?.tokenUsage?.totalTokens == 210)- let queryTime = Date()- let terminalReferences = monitor.prepareTerminalTokenUsageReadBatch(now: queryTime)+ let terminalReferences = monitor.terminalTokenUsageReferences()#expect(terminalReferences.count == 2)- #expect(monitor.prepareTerminalTokenUsageReadBatch(now: queryTime.addingTimeInterval(1)).isEmpty)- _ = monitor.prepareTerminalTokenUsageReadBatch(now: Date().addingTimeInterval(31))- #expect(monitor.terminalTokenUsageRequests.isEmpty)+ let laterReferences = monitor.terminalTokenUsageReferences()+ #expect(Set(laterReferences) == Set(terminalReferences))+ #expect(monitor.terminalTokenUsageRequests.count == 2)#expect(monitor.completions.first?.tokenUsage?.totalTokens == 110)monitor.clearCollectedActivityState()#expect(monitor.completions.isEmpty)@@ -227,18 +226,18 @@ struct ActivityTokenUsageTests {defer { preferences.remove() }let monitor = try makeMonitor(directory: directory, preferences: preferences)let first = TestFixtures.event()- let firstKey = ActivityTaskKey(event: first)+ let firstKey = try #require(ActivityTaskKey(event: first))let task = ActivityTask(displayID: UUID(), key: firstKey, event: first, state: .running,startedAt: TestFixtures.now, progressGeneration: 1)var transitions: [ActivityTransition] = []monitor.resolveTerminal(.completed(at: TestFixtures.now, duration: 1), task: task, key: firstKey, abortFallback: TestFixtures.now, into: &transitions)- let firstState = state(reference("session-a", "turn-a"))+ let firstState = state(reference("thread-a", "turn-a"))_ = monitor.applyTerminalTokenUsage([firstState])#expect(monitor.completions.first?.tokenUsage?.totalTokens == 110)let second = TestFixtures.event(at: TestFixtures.now.addingTimeInterval(2), turn: "turn-b")- let secondKey = ActivityTaskKey(event: second)+ let secondKey = try #require(ActivityTaskKey(event: second))monitor.tasks[secondKey] = ActivityTask(displayID: UUID(), key: secondKey, event: second, state: .running,startedAt: second.timestamp, progressGeneration: 2@@ -248,7 +247,7 @@ struct ActivityTokenUsageTests {_ = monitor.applyTerminalTokenUsage([firstState])#expect(monitor.completions.first?.tokenUsage?.totalTokens == 110)let lateChild = reference("child-a", "child-turn-a")- monitor.subagentTurnLinks[lateChild] = firstKey+ monitor.subagentTurnLinks[lateChild] = (firstKey, TestFixtures.now)#expect(!monitor.applyTerminalTokenUsage([firstState]))#expect(monitor.completions.first?.tokenUsage?.totalTokens == 110)#expect(monitor.applyTerminalTokenUsage([firstState, state(lateChild, input: 200)]))@@ -256,7 +255,7 @@ struct ActivityTokenUsageTests {var unavailable = firstStateunavailable.readStatus = .unavailable#expect(!monitor.applyTerminalTokenUsage([unavailable]))- _ = monitor.prepareTerminalTokenUsageReadBatch(now: Date().addingTimeInterval(31))+ _ = monitor.terminalTokenUsageReferences()#expect(monitor.completions.first?.tokenUsage?.totalTokens == 320)}@@ -275,14 +274,14 @@ struct ActivityTokenUsageTests {#expect(monitor.canPublishActivityTransitions)for publishesEvents in [false, true] {let event = TestFixtures.event(at: now, turn: publishesEvents ? "live-turn" : "historical-turn")- let key = ActivityTaskKey(event: event)+ let key = try #require(ActivityTaskKey(event: event))let task = ActivityTask(displayID: UUID(), key: key, event: event, state: .running,startedAt: now, progressGeneration: 1)var transitions: [ActivityTransition] = []monitor.resolveTerminal(- aborted ? .aborted(at: now) : .completed(at: now, duration: 1),+ aborted ? .aborted(at: now, duration: nil) : .completed(at: now, duration: 1),task: task, key: key, abortFallback: now, publishesEvents: publishesEvents, into: &transitions)#expect(transitions.isEmpty == (aborted || !publishesEvents))@@ -290,7 +289,7 @@ struct ActivityTokenUsageTests {#expect(monitor.recentEndedDate(for: key, now: now) != nil)let presentationCount = monitor.pendingTerminalPresentationEvents.countmonitor.resolveTerminal(- aborted ? .aborted(at: now) : .completed(at: now, duration: 1),+ aborted ? .aborted(at: now, duration: nil) : .completed(at: now, duration: 1),task: task, key: key, abortFallback: now, publishesEvents: true, into: &transitions)#expect(monitor.pendingTerminalPresentationEvents.count == presentationCount)@@ -299,8 +298,8 @@ struct ActivityTokenUsageTests {#expect(monitor.terminalTokenUsageRequests.count == 2)}- @Test(arguments: [false, true], [false, true])- func liveTerminalPresentationPreservesAnonymousAndInterruptBehavior(interrupted: Bool, anonymous: Bool) throws {+ @Test(arguments: [false, true])+ func liveTerminalPresentationPreservesInterruptBehavior(interrupted: Bool) throws {let directory = try TestDirectory()defer { try? directory.remove() }let preferences = try TestPreferences()@@ -311,8 +310,8 @@ struct ActivityTokenUsageTests {let now = Date()monitor.sessionTransitionNotBefore = now.addingTimeInterval(-1)monitor.terminalPresentationNotBefore = now.addingTimeInterval(-1)- let event = TestFixtures.event(.turnAborted, at: now, session: anonymous ? nil : "session-a")- let key = ActivityTaskKey(event: event)+ let event = TestFixtures.event(.turnAborted, at: now)+ let key = try #require(ActivityTaskKey(event: event))let task = ActivityTask(displayID: UUID(), key: key, event: event, state: .running,startedAt: now, progressGeneration: 1@@ -320,31 +319,80 @@ struct ActivityTokenUsageTests {var transitions: [ActivityTransition] = []if interrupted {monitor.tasks[key] = task- monitor.interruptTask(from: event, source: .live)- monitor.interruptTask(from: event, source: .live)+ monitor.finishTask(from: event, source: .live, into: &transitions)+ monitor.finishTask(from: event, source: .live, into: &transitions)#expect(monitor.tasks.isEmpty)#expect(monitor.terminations.count == 1)- #expect(monitor.terminations.first?.isAnonymous == anonymous)} else {monitor.resolveTerminal(.completed(at: now, duration: 1), task: task, key: key,abortFallback: now, into: &transitions)#expect(monitor.completions.count == 1)- #expect(monitor.completions.first?.isAnonymous == anonymous)}- #expect(transitions.count == (interrupted || anonymous ? 0 : 1))+ #expect(transitions.count == (interrupted ? 0 : 1))#expect(monitor.pendingTerminalPresentationEvents.count == 1)- #expect(monitor.terminalTokenUsageRequests.count == (anonymous ? 0 : 1))+ #expect(monitor.terminalTokenUsageRequests.count == 1)+ }++ @Test(arguments: [ActivityTaskState.running, .waitingApproval])+ func tasksDoNotExpireWithoutProgress(state: ActivityTaskState) throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = try makeMonitor(directory: directory, preferences: preferences)+ let now = Date()+ let old = now.addingTimeInterval(-ActivityRetention.window - 1)+ let event = TestFixtures.event(at: old)+ let key = try #require(ActivityTaskKey(event: event))+ monitor.tasks[key] = ActivityTask(+ displayID: UUID(), key: key, event: event, state: state,+ startedAt: old, progressGeneration: 1+ )+ monitor.refreshSnapshot(now: now)+ #expect(monitor.tasks.count == 1)+ #expect(monitor.snapshot.activeCount == 1)+ }++ @Test(arguments: [false, true])+ func terminalUsageContinuesUntilCardIsRemoved(clearExplicitly: 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)+ let now = Date()+ let event = TestFixtures.event(at: now)+ let key = try #require(ActivityTaskKey(event: event))+ let task = ActivityTask(+ displayID: UUID(), key: key, event: event, state: .running,+ startedAt: now, progressGeneration: 1+ )+ var transitions: [ActivityTransition] = []+ monitor.resolveTerminal(.completed(at: now, duration: 1), task: task, key: key, abortFallback: now, into: &transitions)+ let root = reference("thread-a", "turn-a")+ #expect(monitor.terminalTokenUsageReferences().contains(root))+ #expect(monitor.terminalTokenUsageReferences().contains(root))+ #expect(monitor.applyTerminalTokenUsage([state(root, input: 500)]))+ #expect(monitor.completions.first?.tokenUsage?.totalTokens == 510)+ if clearExplicitly {+ monitor.clearCollectedActivityState()+ } else {+ monitor.refreshSnapshot(now: now.addingTimeInterval(601))+ }+ #expect(monitor.completions.isEmpty)+ #expect(monitor.terminalTokenUsageRequests.isEmpty)+ #expect(monitor.terminalTokenUsageReferences().isEmpty)}private func reference(_ thread: String, _ turn: String) -> ActivityTurnReference {- ActivityTurnReference(threadID: thread, turnID: turn, startedAt: TestFixtures.now)+ ActivityTurnReference(threadID: thread, turnID: turn)}private func request(root: ActivityTurnReference, children: [ActivityTurnReference]) -> TaskTokenRequest {TaskTokenRequest(- root: root, expectedAgentIDs: Set(children.map(\.threadID)), references: Set([root] + children), deadline: TestFixtures.now+ root: root, expectedAgentIDs: Set(children.map(\.threadID)), references: Set([root] + children))}@@ -354,8 +402,8 @@ struct ActivityTokenUsageTests {) -> SessionLifecycleState {SessionLifecycleState(requestedThreadID: reference.threadID, turnID: reference.turnID, startedAt: TestFixtures.now,- approvalReviewer: nil, effort: nil, lastProgressAt: TestFixtures.now, terminal: terminal,- rootTurnID: "turn-a", rootSessionID: "session-a",+ effort: nil, lastProgressAt: TestFixtures.now, terminal: terminal,+ rootTurnID: "turn-a", rootThreadID: "thread-a",tokenUsage: TokenUsage(inputTokens: input, cachedInputTokens: 20, cacheWriteInputTokens: 0,outputTokens: 10, reasoningOutputTokens: 2, totalTokens: input + 10@@ -364,7 +412,7 @@ struct ActivityTokenUsageTests {}private func makeMonitor(directory: TestDirectory, preferences: TestPreferences) throws -> ActivityMonitor {- try ActivityMonitor(+ ActivityMonitor(protectionSettings: ProtectionSettings(defaults: preferences.defaults),protectionStore: ProtectionStore(directoryURL: directory.url))@@ -384,7 +432,7 @@ extension ActivityTokenUsageTests {let monitor = try makeMonitor(directory: directory, preferences: preferences)let now = Date()let event = TestFixtures.event(at: now.addingTimeInterval(-60))- let key = ActivityTaskKey(event: event)+ let key = try #require(ActivityTaskKey(event: event))let task = ActivityTask(displayID: UUID(),key: key,diff --git a/CodexBarTests/Activity/AppServerActivityTests.swift b/CodexBarTests/Activity/AppServerActivityTests.swiftindex 6a32178..3c21633 100644--- a/CodexBarTests/Activity/AppServerActivityTests.swift+++ b/CodexBarTests/Activity/AppServerActivityTests.swift@@ -12,23 +12,44 @@ struct AppServerActivityTests {}private func turn(_ id: String = "turn", status: String = "inProgress") -> ActivityTurn {- ActivityTurn(id: id, status: status, startedAt: now.timeIntervalSince1970)+ ActivityTurn(id: id, status: ActivityTurnStatus(rawValue: status == "inProgress" ? "running" : status) ?? .unknown, rootTurnId: id, startedAt: now)}- private func message(_ method: String, params: String, id: Int? = nil) throws -> ActivityNotification {- let request = id.map { "\"id\":\($0)," } ?? ""- return try TestFixtures.decode(ActivityNotification.self, "{\(request)\"method\":\"\(method)\",\"params\":\(params)}")+ private func message(_ method: String, params: String, id: Int? = nil) throws -> ActivityInput {+ var fields = try #require(JSONSerialization.jsonObject(with: Data(params.utf8)) as? [String: Any])+ if method.hasSuffix("/requestApproval"), fields["startedAtMs"] == nil {+ fields["startedAtMs"] = now.timeIntervalSince1970 * 1000+ }+ var envelope: [String: Any] = ["method": method, "params": fields]+ if let id {+ envelope["id"] = id+ }+ return try JSONDecoder().decode(ActivityInput.self, from: JSONSerialization.data(withJSONObject: envelope))}private func prepared() throws -> AppServerActivityReducer {var reducer = AppServerActivityReducer()- _ = try reducer.reconcile(thread: thread(), turns: [turn()], reviewer: .user, now: now)+ _ = try reducer.reconcile(thread: thread(), turns: [turn()], now: now)return reducer}@Test(arguments: [- "item/agentMessage/delta", "item/plan/delta", "item/reasoning/textDelta", "item/reasoning/summaryTextDelta",- "item/commandExecution/outputDelta", "item/fileChange/outputDelta"+ "item/started", "item/completed", "thread/tokenUsage/updated",+ "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "item/permissions/requestApproval",+ "item/agentMessage/delta", "item/reasoning/textDelta", "item/reasoning/summaryTextDelta", "item/commandExecution/outputDelta"+ ], [nil, ""] as [String?])+ func turnScopedNotificationsRejectMissingIdentity(_ method: String, turnID: String?) throws {+ var params: [String: Any] = ["threadId": "main", "itemId": "item", "item": ["id": "item", "type": "commandExecution"]]+ if let turnID {+ params["turnId"] = turnID+ }+ let json = try #require(String(data: JSONSerialization.data(withJSONObject: params), encoding: .utf8))+ #expect(throws: DecodingError.self) { try message(method, params: json) }+ }++ @Test(arguments: [+ "item/agentMessage/delta", "item/reasoning/textDelta", "item/reasoning/summaryTextDelta",+ "item/commandExecution/outputDelta"])func recognizedProgressOnlyRefreshesActivity(_ method: String) throws {var reducer = try prepared()@@ -44,7 +65,6 @@ struct AppServerActivityTests {"""), now: later)let state = try #require(reducer.states.values.first)#expect(state.lastProgressAt == later)- #expect(state.lastExecutionProgressAt == later)#expect(state.isWaitingApproval == true)#expect(state.approvalChangedAt == now)#expect(events.isEmpty)@@ -53,7 +73,9 @@ struct AppServerActivityTests {}@Test(arguments: [- "item/future/delta", "item/future/outputDelta", "hook/delta", "command/exec/outputDelta",+ "thread/settings/updated", "thread/environment/connected", "thread/environment/disconnected",+ "item/plan/delta", "item/tool/requestUserInput", "item/autoApprovalReview/started", "item/autoApprovalReview/completed",+ "item/fileChange/outputDelta", "item/future/delta", "item/future/outputDelta", "hook/delta", "command/exec/outputDelta","process/outputDelta", "item/reasoning/textDelta/extra", "item/agentMessage/Delta"])func unknownMethodsCannotRefreshActivity(_ method: String) throws {@@ -62,9 +84,8 @@ struct AppServerActivityTests {{"threadId":"main","turnId":"turn","delta":"content"}"""), now: now.addingTimeInterval(30))let state = try #require(reducer.states.values.first)- #expect(ActivityNotification.category(for: method) == .ignored)+ #expect(AppServerActivityProtocol.kind(for: method).category == .ignored)#expect(state.lastProgressAt == now)- #expect(state.lastExecutionProgressAt == nil)#expect(events.isEmpty)#expect(reducer.tokenTurns.isEmpty)}@@ -78,7 +99,10 @@ struct AppServerActivityTests {#expect(events.isEmpty)}- @Test(arguments: ["commandExecution", "fileChange", "webSearch", "imageView", "imageGeneration", "sleep", "mcpToolCall", "dynamicToolCall", "collabAgentToolCall"], [false, true])+ @Test(+ arguments: ["commandExecution", "fileChange", "webSearch", "imageView", "imageGeneration", "sleep", "mcpToolCall", "dynamicToolCall", "collabAgentToolCall"],+ [false, true]+ )func toolStartAndEndPreserveOneInvocation(_ type: String, hasToolName: Bool) throws {var reducer = try prepared()let expectedTool = hasToolName && type != "commandExecution" ? "test" : nil@@ -89,18 +113,18 @@ struct AppServerActivityTests {let started = try reducer.consume(message("item/started", params: params), now: now)let ended = try reducer.consume(message("item/completed", params: params), now: now)#expect(started.first?.eventKind == .toolStarted)- #expect(started.first?.source?.method == "item/started")- #expect(started.first?.source?.threadID == "main")- #expect(started.first?.source?.itemType == type)- #expect(started.first?.tool == expectedTool)- #expect(ended.first?.tool == expectedTool)+ #expect(started.first?.context?.method == "item/started")+ #expect(started.first?.context?.threadID == "main")+ #expect(started.first?.context?.itemType == type)+ #expect(started.first?.toolName == expectedTool)+ #expect(ended.first?.toolName == expectedTool)#expect(ended.first?.eventKind == .toolCompleted)#expect(started.first?.name == "toolStarted")#expect(started.first?.id == "main:turn:item:toolStarted")#expect(ended.first?.name == "toolCompleted")#expect(ended.first?.id == "main:turn:item:toolCompleted")#expect(try reducer.consume(message("item/completed", params: params), now: now).isEmpty)- var accumulator = ActivityAccumulator(rebuilding: CodexDateFormat.dayString(from: now), generationID: nil, generationStartedEmpty: true, eventCountAvailability: .all)+ var accumulator = ActivityAccumulator(rebuilding: CodexDateFormat.dayString(from: now), generationID: nil, eventCountAvailability: .all)for event in started + ended {accumulator.record(event)}@@ -109,22 +133,17 @@ struct AppServerActivityTests {let data = try AppServerEventRecord(activity: event, recordedAt: now).jsonLineData()let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])let activity = try #require(object["activityPayload"] as? [String: Any])- #expect(activity["tool"] as? String == expectedTool)- #expect((object["source"] as? [String: Any])?["itemType"] as? String == type)+ #expect(activity["toolName"] as? String == expectedTool)+ #expect(activity["tool"] == nil)+ #expect(activity["commandActionTypes"] == nil)+ #expect((object["context"] as? [String: Any])?["itemType"] as? String == type)let restored = try #require(AppServerEventRecord.decode(from: data).activity)- var task = ActivityTask(- displayID: UUID(), key: ActivityTaskKey(event: restored), event: restored,- state: .running, startedAt: now, progressGeneration: 0- )- let expectedDisplay = try #require(ActivityDisplayFormat.toolActionText(itemType: type, toolName: expectedTool))- #expect(task.snapshot.toolDisplayName == expectedDisplay)- try task.mergeMetadata(from: #require(ended.first))-- #expect(task.snapshot.toolDisplayName == expectedDisplay)+ #expect(restored.toolName == expectedTool)+ #expect(restored.context?.itemType == type)}@Test(arguments: ["item/started", "item/completed"])- func commandActionsKeepRawOrderAndLocalizeDisplay(_ method: String) throws {+ func commandActionTypesKeepRawOrderAndLocalizeDisplay(_ method: String) throws {var reducer = try prepared()let events = try reducer.consume(message(method, params: """{"threadId":"main","turnId":"turn","item":{"id":"command","type":"commandExecution","commandActions":[@@ -138,16 +157,23 @@ struct AppServerActivityTests {let data = try AppServerEventRecord(activity: event, recordedAt: now).jsonLineData()let storedText = try #require(String(data: data, encoding: .utf8))#expect(!storedText.contains("private"))+ let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])+ let payload = try #require(object["activityPayload"] as? [String: Any])+ #expect(payload["commandActionTypes"] as? [String] == ["search", "unknown", "read", "search", "listFiles", "read"])+ #expect(payload["commandActions"] == nil)+ #expect(payload["toolName"] == nil)+ #expect(payload["tool"] == nil)let restored = try #require(AppServerEventRecord.decode(from: data).activity)- let task = ActivityTask(- displayID: UUID(), key: ActivityTaskKey(event: restored), event: restored,- state: .running,- startedAt: now, progressGeneration: 0+ let approval = ActivityApproval(+ requestedAt: now, toolName: restored.toolName, sequence: 0,+ itemType: restored.context?.itemType, commandActionTypes: restored.commandActionTypes)- #expect(restored.tool == "search/read/listFiles")+ #expect(restored.toolName == nil)+ #expect(restored.commandActionTypes == ["search", "unknown", "read", "search", "listFiles", "read"])+ #expect(approval.commandActionTypes == restored.commandActionTypes)let expectedDisplay = String(localized: "activity.live.actions-read-listFiles-search")- #expect(task.snapshot.toolDisplayName == expectedDisplay)- #expect(restored.source?.itemType == "commandExecution")+ #expect(approval.actionText == expectedDisplay)+ #expect(restored.context?.itemType == "commandExecution")#expect(restored.eventKind == (method == "item/started" ? .toolStarted : .toolCompleted))}@@ -158,20 +184,61 @@ struct AppServerActivityTests {{"threadId":"main","turnId":"turn","item":{"id":"command","type":"commandExecution"\(actions)}}"""), now: now)let event = try #require(events.first)- let task = ActivityTask(- displayID: UUID(), key: ActivityTaskKey(event: event), event: event,- state: .running, startedAt: now, progressGeneration: 0+ let approval = ActivityApproval(+ requestedAt: now, toolName: event.toolName, sequence: 0,+ itemType: event.context?.itemType, commandActionTypes: event.commandActionTypes)- #expect(event.tool == nil)- #expect(task.snapshot.toolDisplayName == String(localized: "activity.action.command"))+ #expect(event.toolName == nil)+ #expect(approval.actionText == String(localized: "activity.action.command"))}- @Test func commandActionsDoNotOverrideOtherToolNames() throws {+ @Test(arguments: ["actual_tool", "search/read"])+ func commandActionTypesDoNotOverrideOtherToolNames(_ name: String) throws {var reducer = try prepared()let events = try reducer.consume(message("item/started", params: """- {"threadId":"main","turnId":"turn","item":{"id":"tool","type":"mcpToolCall","tool":"actual_tool","commandActions":[{"type":"read"}]}}+ {"threadId":"main","turnId":"turn","item":{"id":"tool","type":"mcpToolCall","tool":"\(name)","commandActions":[{"type":"read"}]}}"""), now: now)- #expect(events.first?.tool == "actual_tool")+ let event = try #require(events.first)+ #expect(event.toolName == name)+ #expect(event.commandActionTypes == nil)+ let restored = try #require(AppServerEventRecord.decode(from: AppServerEventRecord(activity: event).jsonLineData()).activity)+ let approval = ActivityApproval(+ requestedAt: now, toolName: restored.toolName, sequence: 0,+ itemType: restored.context?.itemType, commandActionTypes: restored.commandActionTypes+ )+ #expect(approval.actionText == name)+ }++ @Test func approvalKeepsCommandActionTypesWhenAnotherToolUpdatesTheTask() throws {+ var reducer = try prepared()+ let started = try reducer.consume(message("item/started", params: """+ {"threadId":"main","turnId":"turn","item":{"id":"command","type":"commandExecution","commandActions":[{"type":"read"},{"type":"search"}]}}+ """), now: now)+ let event = try #require(started.first)+ var task = try ActivityTask(+ displayID: UUID(), key: #require(ActivityTaskKey(event: event)), event: event,+ state: .running, startedAt: now, progressGeneration: 0+ )+ let approvals = try reducer.consume(message("item/commandExecution/requestApproval", params: """+ {"threadId":"main","turnId":"turn","itemId":"command","commandActions":[{"type":"read"},{"type":"search"}]}+ """, id: 1), now: now.addingTimeInterval(1))+ let approval = try #require(approvals.first)+ let restored = try #require(AppServerEventRecord.decode(from: AppServerEventRecord(activity: approval).jsonLineData()).activity)+ let enteredWaiting = task.recordApprovalRequest(from: restored)+ #expect(enteredWaiting)+ let others = try reducer.consume(message("item/started", params: """+ {"threadId":"main","turnId":"turn","item":{"id":"other","type":"mcpToolCall","tool":"search/read"}}+ """), now: now.addingTimeInterval(2))+ try task.mergeMetadata(from: #require(others.first))+ try task.resumeExecution(from: #require(others.first))+ #expect(task.state == .waitingApproval)+ let lifecycle = try #require(reducer.states[ActivityTurnReference(threadID: "main", turnID: "turn")])+ task.mergeExecutionLifecycle(lifecycle, owner: ActivityExecutionKey(agentID: nil, turnID: "turn"))+ #expect(task.displayedApproval?.toolName == nil)+ #expect(task.displayedApproval?.commandActionTypes == ["read", "search"])+ #expect(task.snapshot.approvalActionText == String(localized: "activity.live.actions-read-search"))+ let notification = NotificationContent.taskWaiting(project: task.snapshot.projectName, actionText: task.snapshot.approvalActionText)+ #expect(notification.body.contains(String(localized: "activity.live.actions-read-search")))}@Test func approvalResolutionDoesNotInventAnotherToolCall() throws {@@ -180,22 +247,22 @@ struct AppServerActivityTests {{"threadId":"main","turnId":"turn","itemId":"command"}""", id: 1), now: now)#expect(events.first?.eventKind == .approvalRequested)- #expect(events.first?.source?.requestID != nil)- #expect(events.first?.source?.itemID == "command")- #expect(events.first?.source?.itemType == "commandExecution")- #expect(events.first?.tool == nil)- let key = ActivityTurnReference(threadID: "main", turnID: "turn", startedAt: now)+ #expect(events.first?.context?.requestID != nil)+ #expect(events.first?.context?.itemID == "command")+ #expect(events.first?.context?.itemType == "commandExecution")+ #expect(events.first?.toolName == nil)+ let key = ActivityTurnReference(threadID: "main", turnID: "turn")#expect(reducer.states[key]?.isWaitingApproval == true)#expect(try reducer.consume(message("serverRequest/resolved", params: #"{"threadId":"main","requestId":1}"#), now: now).isEmpty)#expect(reducer.states[key]?.isWaitingApproval == false)}- @Test func automaticReviewCountsRequestWithoutWaitingForUser() throws {+ @Test func automaticReviewDoesNotCountRequest() throws {var reducer = try prepared()let events = try reducer.consume(message("item/autoApprovalReview/started", params: """{"threadId":"main","turnId":"turn","targetItemId":"command","reviewId":"review"}"""), now: now)- #expect(events.first?.approvalReviewer == .autoReview)+ #expect(events.isEmpty)#expect(reducer.states.values.first?.isWaitingApproval != true)}@@ -211,8 +278,8 @@ struct AppServerActivityTests {@Test func detachedHistoryWithoutTerminalTimestampDoesNotEndLiveTask() throws {var reducer = try prepared()var detached = try thread()- detached.status = ActivityThreadStatus(type: "notLoaded")- _ = reducer.reconcile(thread: detached, turns: [turn(status: "interrupted")], reviewer: nil, now: now)+ detached.status = ActivityThreadStatus(type: .notLoaded)+ _ = reducer.reconcile(thread: detached, turns: [turn(status: "interrupted")], now: now)#expect(reducer.states.values.first?.terminal == nil)#expect(reducer.states.values.first?.readStatus == .unavailable)}@@ -220,7 +287,7 @@ struct AppServerActivityTests {@Test func reconnectRestoresActiveSnapshotWithoutRecountingPrompt() throws {var reducer = try prepared()reducer.reconnect()- let events = try reducer.reconcile(thread: thread(), turns: [turn()], reviewer: .user, now: now, bootstrap: true)+ let events = try reducer.reconcile(thread: thread(), turns: [turn()], now: now, bootstrap: true)#expect(events.count == 1)#expect(events.first?.timestamp == now)}@@ -235,10 +302,10 @@ struct AppServerActivityTests {{"threadId":"main","turnId":"turn","item":{"id":"spawn","type":"subAgentActivity","kind":"started","agentThreadId":"child"}}"""), now: now)#expect(agent.first?.eventKind == .subagentStarted)- #expect(agent.first?.tool == nil)+ #expect(agent.first?.toolName == nil)}- private func tokenMessage(total: Int) throws -> ActivityNotification {+ private func tokenMessage(total: Int) throws -> ActivityInput {try message("thread/tokenUsage/updated", params: """{"threadId":"main","turnId":"turn","tokenUsage":{"total":{"inputTokens":\(total),"cachedInputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":\(total)},@@ -251,23 +318,23 @@ struct AppServerActivityTests {_ = try reducer.consume(tokenMessage(total: 1000), now: now)#expect(reducer.tokenTurns.isEmpty)_ = try reducer.consume(tokenMessage(total: 1100), now: now)- #expect(reducer.tokenTurns.first?.usage?.totalTokens == 100)+ #expect(reducer.tokenTurns.values.first?.usage?.totalTokens == 100)_ = try reducer.consume(tokenMessage(total: 1100), now: now)- #expect(reducer.tokenTurns.first?.usage?.totalTokens == 100)+ #expect(reducer.tokenTurns.values.first?.usage?.totalTokens == 100)reducer.reconnect()_ = try reducer.consume(tokenMessage(total: 5000), now: now)_ = try reducer.consume(tokenMessage(total: 5020), now: now)- #expect(reducer.tokenTurns.first?.usage?.totalTokens == 120)+ #expect(reducer.tokenTurns.values.first?.usage?.totalTokens == 120)}@Test func newThreadIncludesFirstResponseAndCounterResetDoesNotSubtractUsage() throws {var reducer = try prepared()reducer.markNewThread("main")_ = try reducer.consume(tokenMessage(total: 100), now: now)- #expect(reducer.tokenTurns.first?.usage?.totalTokens == 100)+ #expect(reducer.tokenTurns.values.first?.usage?.totalTokens == 100)_ = try reducer.consume(tokenMessage(total: 20), now: now)_ = try reducer.consume(tokenMessage(total: 30), now: now)- #expect(reducer.tokenTurns.first?.usage?.totalTokens == 110)+ #expect(reducer.tokenTurns.values.first?.usage?.totalTokens == 110)}@Test func eventRecorderDeduplicatesAcrossInstancesAndRestarts() async throws {@@ -362,45 +429,181 @@ struct AppServerActivityTests {@Test func multipleApprovalRequestsResolveIndependently() throws {var reducer = try prepared()+ let event = TestFixtures.event(at: now, thread: "main", turn: "turn")+ var task = ActivityTask(displayID: UUID(), key: .init(thread: "main", turn: "turn"), event: event, state: .running, startedAt: now, progressGeneration: 0)+ let reference = ActivityTurnReference(threadID: "main", turnID: "turn")+ let owner = ActivityExecutionKey(agentID: nil, turnID: "turn")for id in [1, 2] {+ let action = id == 1 ? "read" : "search"_ = try reducer.consume(message("item/commandExecution/requestApproval", params: """- {"threadId":"main","turnId":"turn","itemId":"command-\(id)"}+ {"threadId":"main","turnId":"turn","itemId":"command-\(id)","commandActions":[{"type":"\(action)"}]}""", id: id), now: now)}+ try task.mergeExecutionLifecycle(#require(reducer.states[reference]), owner: owner)+ #expect(task.displayedApproval?.commandActionTypes == ["read"])+ _ = try reducer.consume(message("serverRequest/resolved", params: #"{"threadId":"main","requestId":999}"#), now: now)+ #expect(reducer.states[reference]?.pendingApprovals.count == 2)_ = try reducer.consume(message("serverRequest/resolved", params: #"{"threadId":"main","requestId":1}"#), now: now)#expect(reducer.states.values.first?.isWaitingApproval == true)+ try task.mergeExecutionLifecycle(#require(reducer.states[reference]), owner: owner)+ #expect(task.state == .waitingApproval)+ #expect(task.displayedApproval?.commandActionTypes == ["search"])_ = try reducer.consume(message("serverRequest/resolved", params: #"{"threadId":"main","requestId":2}"#), now: now)#expect(reducer.states.values.first?.isWaitingApproval == false)+ try task.mergeExecutionLifecycle(#require(reducer.states[reference]), owner: owner)+ #expect(task.state == .running)+ #expect(task.snapshot.approvalActionText == nil)+ }++ @Test(arguments: ["thread/status/changed", "turn/completed"])+ func authoritativeStateClearsPendingRequests(method: String) throws {+ var reducer = try prepared()+ _ = try reducer.consume(message("item/commandExecution/requestApproval", params: #"{"threadId":"main","turnId":"turn","itemId":"command"}"#, id: 1), now: now)+ let params = method == "turn/completed"+ ? #"{"threadId":"main","turn":{"id":"turn","status":"completed"}}"#+ : #"{"threadId":"main","status":{"type":"active","activeFlags":[]}}"#+ _ = try reducer.consume(message(method, params: params), now: now)+ let state = try #require(reducer.states[ActivityTurnReference(threadID: "main", turnID: "turn")])+ #expect(state.pendingApprovals.isEmpty)+ #expect(state.isWaitingApproval == false)}- @Test func childKeepsItsOriginalRootAcrossParentTurns() throws {+ @Test func eachChildTurnUsesItsDeclaredRoot() throws {+ var reducer = try prepared()+ var parentTurn = turn()+ parentTurn.items = [ActivityItem(id: "spawn", type: .subAgentActivity, agentThreadId: "child", kind: "started", reasoningEffort: "low")]+ _ = try reducer.reconcile(thread: thread(), turns: [parentTurn], now: now)+ let child = try thread("child", source: #"{"subAgent":{"thread_spawn":{"parent_thread_id":"main"}}}"#)+ var first = turn("child-turn")+ first.rootTurnId = "turn"+ _ = reducer.reconcile(thread: child, turns: [first], now: now)+ let next = ActivityTurn(id: "next", status: .running, rootTurnId: "next", startedAt: now.addingTimeInterval(10))+ _ = try reducer.reconcile(thread: thread(), turns: [next], now: now.addingTimeInterval(10))+ var followup = turn("child-followup")+ followup.rootTurnId = "next"+ _ = reducer.reconcile(thread: child, turns: [followup], now: now.addingTimeInterval(11))+ #expect(reducer.states[.init(threadID: "child", turnID: first.id)]?.rootTurnID == "turn")+ let state = reducer.states[ActivityTurnReference(threadID: "child", turnID: followup.id)]+ #expect(state?.rootThreadID == "main")+ #expect(state?.rootTurnID == "next")+ #expect(state?.effort == "high")+ #expect(reducer.states[.init(threadID: "child", turnID: first.id)]?.effort == "mixed")+ }++ @Test func absentRootDoesNotInferFromParentTime() throws {var reducer = try prepared()let child = try thread("child", source: #"{"subAgent":{"thread_spawn":{"parent_thread_id":"main"}}}"#)- _ = reducer.reconcile(thread: child, turns: [turn("child-turn")], reviewer: .user, now: now)- let next = ActivityTurn(id: "next", status: "inProgress", startedAt: now.addingTimeInterval(10).timeIntervalSince1970)- _ = try reducer.reconcile(thread: thread(), turns: [next], reviewer: .user, now: now.addingTimeInterval(10))- _ = reducer.reconcile(thread: child, turns: [turn("child-followup")], reviewer: .user, now: now.addingTimeInterval(11))- let state = reducer.states[ActivityTurnReference(threadID: "child", turnID: "child-followup", startedAt: now)]- #expect(state?.rootSessionID == "main")- #expect(state?.rootTurnID == "turn")+ let unknown = ActivityTurn(id: "child-turn", status: .running, startedAt: now)+ _ = reducer.reconcile(thread: child, turns: [unknown], now: now)+ let state = reducer.states[.init(threadID: "child", turnID: unknown.id)]+ #expect(state?.rootTurnID == nil)+ #expect(state?.rootThreadID == nil)}- @Test func settingsUpdateChangesMetadataWithoutInventingEvents() throws {+ @Test func lateRootResolvesNestedChildAndRetainsObservedTokens() throws {+ var reducer = AppServerActivityReducer()+ let child = try thread("child", source: #"{"subAgent":{"thread_spawn":{"parent_thread_id":"middle"}}}"#)+ var childTurn = turn("child-turn")+ childTurn.rootTurnId = "turn"+ _ = reducer.reconcile(thread: child, turns: [childTurn], now: now)+ #expect(reducer.missingRootTurns()["middle"] == ["turn"])+ reducer.markNewThread("child")+ _ = try reducer.consume(message("thread/tokenUsage/updated", params: """+ {"threadId":"child","turnId":"child-turn","tokenUsage":{+ "total":{"inputTokens":15,"cachedInputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":15},+ "last":{"inputTokens":15,"cachedInputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":15}}}+ """), now: now)+ #expect(reducer.takeTokenObservations().isEmpty)+ _ = try reducer.reconcile(thread: thread(), turns: [turn()], now: now)+ let state = reducer.states[.init(threadID: "child", turnID: childTurn.id)]+ #expect(state?.rootThreadID == "main")+ let observation = try #require(reducer.takeTokenObservations().first)+ #expect(observation.turn.rootID == TokenTurn.identifier(thread: "main", turn: "turn"))+ #expect(observation.current.totalTokens == 15)+ _ = try reducer.reconcile(thread: thread(), turns: [turn()], now: now)+ #expect(reducer.takeTokenObservations().isEmpty)+ }++ @Test func creationMetadataUsesChildModelWithoutInventingChildTurn() throws {+ var reducer = try prepared()+ let events = try reducer.consume(message("item/completed", params: """+ {"threadId":"main","turnId":"turn","item":{"id":"spawn","type":"subAgentActivity","kind":"started",+ "agentThreadId":"child","model":"child-model","reasoningEffort":"low"}}+ """), now: now)+ let event = try #require(events.first)+ #expect(event.model == "child-model")+ #expect(event.effort == "low")+ #expect(event.turnID == nil)+ #expect(event.context?.turnID == "turn")+ var accumulator = ActivityAccumulator(rebuilding: "2026-10-09", generationID: nil, eventCountAvailability: .all)+ accumulator.record(event)+ #expect(accumulator.finalized(identifierStorage: .retained).modelCounts == ["child-model": 1])+ let parentEvent = try #require(reducer.reconcile(thread: thread(), turns: [turn()], now: now, bootstrap: true).first)+ var task = ActivityTask(displayID: UUID(), key: .init(thread: "main", turn: "turn"), event: parentEvent, state: .running, startedAt: now, progressGeneration: 0)+ task.mergeMetadata(from: event)+ #expect(task.modelName == "gpt-5")+ #expect(task.effort == "mixed")+ }++ @Test func missingCreationMetadataDoesNotBorrowParentConfiguration() throws {+ var reducer = try prepared()+ let events = try reducer.consume(message("item/completed", params: """+ {"threadId":"main","turnId":"turn","item":{"id":"spawn","type":"subAgentActivity","kind":"started","agentThreadId":"child"}}+ """), now: now)+ let event = try #require(events.first)+ #expect(event.model == nil)+ #expect(event.effort == nil)+ #expect(event.turnID == nil)+ }++ @Test func creationBeforeChildDiscoverySurvivesPruning() throws {+ var reducer = try prepared()+ _ = try reducer.consume(message("item/completed", params: """+ {"threadId":"main","turnId":"turn","item":{"id":"spawn","type":"subAgentActivity","kind":"started",+ "agentThreadId":"child","model":"child-model","reasoningEffort":"low"}}+ """), now: now)+ var child = try thread("child", source: #"{"subAgent":{"thread_spawn":{"parent_thread_id":"main"}}}"#)+ child.reasoningEffort = nil+ var childTurn = turn("child-turn")+ childTurn.rootTurnId = "turn"+ _ = reducer.reconcile(thread: child, turns: [childTurn], now: now)+ #expect(reducer.missingSubagentContexts(in: "main").isEmpty)+ #expect(reducer.states[.init(threadID: "child", turnID: "child-turn")]?.effort == "low")+ }++ @Test func snapshotCreationMetadataBackfillsKnownChildWithoutRecounting() throws {+ var reducer = try prepared()+ var child = try thread("child", source: #"{"subAgent":{"thread_spawn":{"parent_thread_id":"main"}}}"#)+ child.reasoningEffort = nil+ var childTurn = turn("child-turn")+ childTurn.rootTurnId = "turn"+ _ = reducer.reconcile(thread: child, turns: [childTurn], now: now)+ #expect(reducer.missingSubagentContexts(in: "main") == ["child"])+ var parentTurn = turn()+ parentTurn.items = [ActivityItem(id: "spawn", type: .subAgentActivity, agentThreadId: "child", kind: "started", model: "child-model", reasoningEffort: "low")]+ let events = try reducer.reconcile(thread: thread(), turns: [parentTurn], now: now)+ #expect(events.isEmpty)+ #expect(reducer.missingSubagentContexts(in: "main").isEmpty)+ #expect(reducer.states[.init(threadID: "child", turnID: "child-turn")]?.effort == "low")+ }++ @Test func threadReadReplacesConfigurationIncludingUnsetValues() throws {var reducer = try prepared()let events = try reducer.consume(message("thread/settings/updated", params: """{"threadId":"main","threadSettings":{"model":"new-model","effort":"low","approvalsReviewer":"auto_review"}}"""), now: now)#expect(events.isEmpty)var snapshot = try thread()+ snapshot.cwd = "/updated"snapshot.model = nilsnapshot.reasoningEffort = nil- _ = reducer.reconcile(thread: snapshot, turns: [turn()], reviewer: nil, now: now)+ _ = reducer.reconcile(thread: snapshot, turns: [turn()], now: now)let command = try reducer.consume(message("item/started", params: """{"threadId":"main","turnId":"turn","item":{"id":"command","type":"commandExecution"}}"""), now: now)- #expect(command.first?.model == "new-model")- #expect(command.first?.effort == "low")- #expect(command.first?.approvalReviewer == .autoReview)+ #expect(command.first?.cwd == "/updated")+ #expect(command.first?.model == nil)+ #expect(command.first?.effort == nil)}@Test func missingFirstTurnUsageDoesNotMoveItsTokensIntoNextTurn() throws {@@ -426,8 +629,12 @@ extension AppServerActivityTests {@Test(arguments: ["completed", "failed", "interrupted"])func loadedTerminalWithoutTimestampEndsLiveTurn(status: String) throws {var reducer = try prepared()- let idle = ActivityThread(id: "main", status: ActivityThreadStatus(type: "idle"))- _ = reducer.reconcile(thread: idle, turns: [ActivityTurn(id: "turn", status: status)], reviewer: nil, now: now.addingTimeInterval(30))+ let idle = ActivityThread(id: "main", status: ActivityThreadStatus(type: .idle))+ _ = reducer.reconcile(+ thread: idle,+ turns: [ActivityTurn(id: "turn", status: ActivityTurnStatus(rawValue: status == "inProgress" ? "running" : status) ?? .unknown)],+ now: now.addingTimeInterval(30)+ )let state = try #require(reducer.states.values.first { $0.turnID == "turn" })#expect(state.terminal != nil)#expect(state.readStatus == .complete)@@ -447,6 +654,24 @@ extension AppServerActivityTests {}extension AppServerActivityTests {+ @Test func refreshedHistoryReplaysOnlyUncommittedObservationsWithoutLosingLiveUsage() throws {+ var reducer = try prepared()+ reducer.markNewThread("main")+ _ = try reducer.consume(tokenMessage(total: 100), now: now)+ _ = reducer.takeTokenObservations()+ let snapshot = Array(reducer.tokenTurns.values)+ _ = try reducer.consume(tokenMessage(total: 120), now: now.addingTimeInterval(1))+ _ = try reducer.consume(tokenMessage(total: 150), now: now.addingTimeInterval(2))+ let pending = reducer.takeTokenObservations()+ try reducer.acceptTokenTurns(snapshot, replaying: pending)+ #expect(reducer.states.values.first?.tokenUsage?.totalTokens == 150)+ let committed = Array(reducer.tokenTurns.values)+ try reducer.acceptTokenTurns(committed, replaying: pending)+ #expect(reducer.states.values.first?.tokenUsage?.totalTokens == 150)+ _ = try reducer.consume(tokenMessage(total: 160), now: now.addingTimeInterval(3))+ #expect(reducer.states.values.first?.tokenUsage?.totalTokens == 160)+ }+@Test func collectorContinuesFromCommittedCorrectionWithoutResettingServerCounter() async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -455,7 +680,7 @@ extension AppServerActivityTests {reducer.markNewThread("main")_ = try reducer.consume(tokenMessage(total: 100), now: now)let committed = try await store.recordObservations(reducer.takeTokenObservations(), now: now)- reducer.acceptTokenTurns(committed)+ try reducer.acceptTokenTurns(committed)var correction = try #require(committed.first { $0.usage != nil })correction.usage = TokenUsage(inputTokens: 60,@@ -470,22 +695,139 @@ extension AppServerActivityTests {// 修正发生在采集器提交下一笔之前, 内存仍可能暂时持有旧累计值_ = try reducer.consume(tokenMessage(total: 110), now: now.addingTimeInterval(1))let result = try await store.recordObservations(reducer.takeTokenObservations(), now: now)- reducer.acceptTokenTurns(result)- #expect(reducer.tokenTurns.first?.usage?.totalTokens == 70)+ try reducer.acceptTokenTurns(result)+ #expect(reducer.tokenTurns.values.first?.usage?.totalTokens == 70)#expect(reducer.states.values.first?.tokenUsage?.totalTokens == 70)_ = try reducer.consume(tokenMessage(total: 120), now: now.addingTimeInterval(2))- #expect(reducer.tokenTurns.first?.usage?.totalTokens == 80)+ #expect(reducer.tokenTurns.values.first?.usage?.totalTokens == 80)}@Test func repeatedHistoricalTerminalKeepsObservationTimeAndNotificationPolicy() throws {var reducer = try prepared()- let idle = ActivityThread(id: "main", status: ActivityThreadStatus(type: "idle"))- let completed = ActivityTurn(id: "turn", status: "completed")- _ = reducer.reconcile(thread: idle, turns: [completed], reviewer: nil, now: now)- _ = reducer.reconcile(thread: idle, turns: [completed], reviewer: nil, now: now.addingTimeInterval(60))+ let idle = ActivityThread(id: "main", status: ActivityThreadStatus(type: .idle))+ let completed = ActivityTurn(id: "turn", status: .completed)+ _ = reducer.reconcile(thread: idle, turns: [completed], now: now)+ _ = reducer.reconcile(thread: idle, turns: [completed], now: now.addingTimeInterval(60))let state = try #require(reducer.states.values.first)#expect(state.terminalObservedAt == now)#expect(state.lastProgressAt == now)#expect(state.isHistoricalTerminal)}}++extension AppServerActivityTests {+ @Test(arguments: [true, false])+ func distinctApprovalCallbacksArePersistedButReplayIsDeduplicated(hasApprovalID: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ var reducer = try prepared()+ let recorder = ActivityRecorder(directoryURL: directory.url)+ let date = Date()+ var events: [ActivityRecord] = []+ for (index, callback) in [1, 2, 1].enumerated() {+ let started = date.timeIntervalSince1970 * 1000 + (hasApprovalID ? 0 : Double(callback))+ let approval = hasApprovalID ? ",\"approvalId\":\"callback-\(callback)\"" : ""+ let notification = try message("item/commandExecution/requestApproval", params: """+ {"threadId":"main","turnId":"turn","itemId":"command","startedAtMs":\(started)\(approval)}+ """, id: index)+ events += reducer.consume(notification, now: date)+ }+ #expect(events.count == 2)+ #expect(Set(events.compactMap(\.id)).count == 2)+ for event in events + events {+ try await recorder.record(event: event)+ }+ let url = HistoryStorage.eventLogURL(for: HistoryStorage.dateKey(for: date), in: HistoryStorage.eventsDirectoryURL(in: directory.url))+ var count = 0+ try AppServerEventJournal.read(at: url) {+ if $0.activity?.eventKind == .approvalRequested {+ count += 1+ }+ }+ #expect(count == 2)+ }++ @Test func inactiveThreadMetadataExpiresWhileRunningAndLoadedThreadsRemain() throws {+ var reducer = AppServerActivityReducer()+ for index in 0 ..< 100 {+ _ = try reducer.reconcile(thread: thread("old-\(index)"), turns: [turn(status: "completed")], now: now)+ }+ _ = try reducer.reconcile(thread: thread("running"), turns: [turn()], now: now)+ _ = try reducer.reconcile(thread: thread("loaded"), turns: [turn(status: "completed")], now: now)+ reducer.maintain(loadedThreads: ["loaded"], now: now.addingTimeInterval(2 * 86400))+ #expect(Set(reducer.threads.keys) == ["running", "loaded"])+ #expect(reducer.states.count == 1)+ }++ @Test func historyRetentionIsRecheckedOnNextDayAndAfterReplacingHistory() throws {+ var reducer = try prepared()+ let cutoff = HistoryStorage.retentionCutoffDate(today: now)+ let retained = TokenTurn(id: "edge", rootID: "edge", updatedAt: cutoff)+ try reducer.acceptTokenTurns([retained])+ reducer.maintain(loadedThreads: ["main"], now: now)+ #expect(reducer.tokenTurns.count == 1)+ let expired = TokenTurn(id: "expired", rootID: "expired", updatedAt: cutoff.addingTimeInterval(-1))+ try reducer.acceptTokenTurns([retained, expired])+ reducer.maintain(loadedThreads: ["main"], now: now.addingTimeInterval(1))+ #expect(Set(reducer.tokenTurns.keys) == ["edge"])+ reducer.maintain(loadedThreads: ["main"], now: now.addingTimeInterval(86400))+ #expect(reducer.tokenTurns.isEmpty)+ }+}++extension AppServerActivityTests {+ @Test func retiringThreadDoesNotReuseTokenSequenceOnReobservation() throws {+ var reducer = try prepared()+ _ = try reducer.consume(tokenMessage(total: 100), now: now)+ _ = try reducer.consume(tokenMessage(total: 110), now: now)+ let first = try #require(reducer.takeTokenObservations().first)+ _ = try reducer.consume(message("turn/completed", params: """+ {"threadId":"main","turn":{"id":"turn","status":"completed","completedAt":\(now.timeIntervalSince1970)}}+ """), now: now)+ let later = now.addingTimeInterval(2 * 86400)+ reducer.maintain(loadedThreads: [], now: later)+ #expect(reducer.threads.isEmpty)+ _ = try reducer.reconcile(thread: thread(), turns: [turn()], now: later)+ _ = try reducer.consume(tokenMessage(total: 500), now: later)+ _ = try reducer.consume(tokenMessage(total: 520), now: later)+ let second = try #require(reducer.takeTokenObservations().first)+ #expect(second.sequence == 1)+ #expect(second.streamID != first.streamID)+ #expect(reducer.tokenTurns.values.first?.usage?.totalTokens == 30)+ }++ @Test func malformedApprovalCannotInventPersistentIdentity() throws {+ #expect(throws: DecodingError.self) {+ try TestFixtures.decode(ActivityInput.self, """+ {"id":1,"method":"item/commandExecution/requestApproval","params":{"threadId":"main","turnId":"turn","itemId":"command"}}+ """)+ }+ }+}++extension AppServerActivityTests {+ @Test func historyRecordingGapStartsNewTokenStreamWithoutCountingMissingUsage() throws {+ var reducer = try prepared()+ _ = try reducer.consume(tokenMessage(total: 100), now: now)+ _ = try reducer.consume(tokenMessage(total: 120), now: now)+ let first = try #require(reducer.takeTokenObservations().first)+ let persisted = try first.applying(to: nil)+ reducer.setTokenRecordingEnabled(false)+ _ = try reducer.consume(tokenMessage(total: 500), now: now)+ #expect(reducer.takeTokenObservations().isEmpty)+ let events = try reducer.consume(message("item/started", params: """+ {"threadId":"main","turnId":"turn","item":{"id":"tool","type":"commandExecution"}}+ """), now: now)+ #expect(!events.isEmpty)+ reducer.setTokenRecordingEnabled(true)+ _ = try reducer.consume(tokenMessage(total: 600), now: now)+ #expect(reducer.takeTokenObservations().isEmpty)+ _ = try reducer.consume(tokenMessage(total: 650), now: now)+ let resumed = try #require(reducer.takeTokenObservations().first)+ #expect(resumed.streamID != first.streamID)+ #expect(resumed.sequence == 1)+ let combined = try resumed.applying(to: persisted)+ #expect(combined.usage?.totalTokens == 70)+ #expect(try resumed.applying(to: combined) == combined)+ }+}diff --git a/CodexBarTests/Activity/ProtectionRecoveryTests.swift b/CodexBarTests/Activity/ProtectionRecoveryTests.swiftnew file mode 100644index 0000000..3895f85--- /dev/null+++ b/CodexBarTests/Activity/ProtectionRecoveryTests.swift@@ -0,0 +1,71 @@+import Foundation+import Testing++@MainActor+struct ProtectionRecoveryTests {+ @Test func repairedStoreReloadsWhenProtectionIsEnabled() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let bad = try directory.write("broken", to: "state.json")+ let monitor = makeMonitor(directory: directory, preferences: preferences)+ monitor.isStarted = true+ monitor.loadProtectionState()+ try await wait { monitor.protectionLoadState == .blocked }+ #expect(!monitor.isProtectionStoreAvailable)+ try FileManager.default.removeItem(at: bad)+ monitor.setProtectionEnabled(true)+ try await wait { monitor.isProtectionStoreAvailable }+ #expect(monitor.isProtectionRecoveryInProgress)+ monitor.stop()+ }++ @Test func transientReadFailureRetriesAndStopInvalidatesLoad() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let path = directory.url.appendingPathComponent("state.json")+ try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)+ let monitor = makeMonitor(directory: directory, preferences: preferences)+ monitor.isStarted = true+ monitor.loadProtectionState()+ try await wait { monitor.protectionLoadState == .retryableFailure }+ try FileManager.default.removeItem(at: path)+ try await wait { monitor.isProtectionStoreAvailable }+ monitor.stop()+ monitor.protectionLoadState = .idle+ monitor.isStarted = true+ monitor.loadProtectionState()+ monitor.stop()+ try await Task.sleep(for: .milliseconds(30))+ #expect(monitor.protectionLoadState == .idle)+ }++ private func makeMonitor(directory: TestDirectory, preferences: TestPreferences) -> ActivityMonitor {+ let monitor = ActivityMonitor(+ protectionSettings: ProtectionSettings(defaults: preferences.defaults),+ protectionStore: ProtectionStore(directoryURL: directory.url),+ activityDirectoryURL: directory.url+ )+ // 注入未启动的 reader, 避免状态恢复测试连接真实 Codex+ monitor.activityReader = AppServerActivityReader(+ lifecycleCache: SessionLifecycleCache(), socketURL: directory.url.appendingPathComponent("absent.sock"),+ tokenHistory: TokenHistoryStore(directoryURL: directory.url),+ recorder: ActivityRecorder(directoryURL: directory.url)+ ) { _ in }+ monitor.isBootstrapping = true+ return monitor+ }++ private func wait(until condition: () -> Bool) async throws {+ for _ in 0 ..< 200 {+ if condition() {+ return+ }+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(condition())+ }+}diff --git a/CodexBarTests/Activity/ProtectionStoreTests.swift b/CodexBarTests/Activity/ProtectionStoreTests.swiftindex 79aec83..aa4db78 100644--- a/CodexBarTests/Activity/ProtectionStoreTests.swift+++ b/CodexBarTests/Activity/ProtectionStoreTests.swift@@ -8,10 +8,10 @@ struct ProtectionStoreTests {let store = ProtectionStore(directoryURL: directory.url)let record = makeRecord("task", markedAfter: 0, expiresAfter: 10)try await store.apply(upserts: [record], now: TestFixtures.now)- #expect(await store.load(now: TestFixtures.now.addingTimeInterval(9))["task"] == record)- #expect(await store.load(now: TestFixtures.now.addingTimeInterval(10)).isEmpty)+ #expect(try await store.load(now: TestFixtures.now.addingTimeInterval(9))["task"] == record)+ #expect(try await store.load(now: TestFixtures.now.addingTimeInterval(10)).isEmpty)let reopened = ProtectionStore(directoryURL: directory.url)- #expect(await reopened.load(now: TestFixtures.now).isEmpty)+ #expect(try await reopened.load(now: TestFixtures.now).isEmpty)}@Test func olderUpsertAndStaleRemovalCannotOverwriteNewerRecord() async throws {@@ -23,9 +23,9 @@ struct ProtectionStoreTests {let newer = makeRecord("task", markedAfter: 5)try await first.apply(upserts: [newer], now: TestFixtures.now)try await second.apply(upserts: [older], removals: [ProtectionRemoval(taskIdentifier: "task", matchingMarkedAt: older.markedAt)], now: TestFixtures.now)- #expect(await first.load(now: TestFixtures.now)["task"] == newer)+ #expect(try await first.load(now: TestFixtures.now)["task"] == newer)try await second.apply(removals: [ProtectionRemoval(taskIdentifier: "task", matchingMarkedAt: newer.markedAt)], now: TestFixtures.now)- #expect(await first.load(now: TestFixtures.now).isEmpty)+ #expect(try await first.load(now: TestFixtures.now).isEmpty)}@Test func concurrentStoreInstancesPreserveIndependentRecords() async throws {@@ -36,19 +36,19 @@ struct ProtectionStoreTests {async let firstWrite: Void = first.apply(upserts: [makeRecord("first", markedAfter: 0)], now: TestFixtures.now)async let secondWrite: Void = second.apply(upserts: [makeRecord("second", markedAfter: 0)], now: TestFixtures.now)_ = try await (firstWrite, secondWrite)- #expect(await Set(first.load(now: TestFixtures.now).keys) == ["first", "second"])+ #expect(try await Set(first.load(now: TestFixtures.now).keys) == ["first", "second"])}@Test(arguments: ["not-json", #"{"version":999,"records":[]}"#])- func invalidStateLoadsEmptyAndCanBeReplaced(_ content: String) async throws {+ func invalidStateIsPreservedAndRejectsWrites(_ content: String) async throws {let directory = try TestDirectory()defer { try? directory.remove() }_ = try directory.write(content, to: "state.json")let store = ProtectionStore(directoryURL: directory.url)- #expect(await store.load(now: TestFixtures.now).isEmpty)+ await #expect(throws: (any Error).self) { try await store.load(now: TestFixtures.now) }let record = makeRecord("task", markedAfter: 0)- try await store.apply(upserts: [record], now: TestFixtures.now)- #expect(await store.load(now: TestFixtures.now)["task"] == record)+ await #expect(throws: (any Error).self) { try await store.apply(upserts: [record], now: TestFixtures.now) }+ #expect(try String(contentsOf: directory.url.appendingPathComponent("state.json"), encoding: .utf8) == content)}@Test func duplicateStoredIdentifiersChooseLatestMarkAndFileIsPrivate() async throws {@@ -59,7 +59,7 @@ struct ProtectionStoreTests {let records = try #require(String(data: JSONEncoder().encode([newer, older]), encoding: .utf8))let url = try directory.write("{\"version\":1,\"records\":\(records)}", to: "state.json")let store = ProtectionStore(directoryURL: directory.url)- #expect(await store.load(now: TestFixtures.now)["task"] == newer)+ #expect(try await store.load(now: TestFixtures.now)["task"] == newer)try await store.apply(now: TestFixtures.now)let attributes = try FileManager.default.attributesOfItem(atPath: url.path)#expect((attributes[.posixPermissions] as? NSNumber)?.intValue == 0o600)diff --git a/CodexBarTests/Activity/SessionLifecycleCacheTests.swift b/CodexBarTests/Activity/SessionLifecycleCacheTests.swiftindex aa9be4f..b4b0c67 100644--- a/CodexBarTests/Activity/SessionLifecycleCacheTests.swift+++ b/CodexBarTests/Activity/SessionLifecycleCacheTests.swift@@ -7,17 +7,19 @@ struct SessionLifecycleCacheTests {let now = Date()var states: [ActivityTurnReference: SessionLifecycleState] = [:]for id in ["root", "child", "grandchild", "other"] {- let reference = ActivityTurnReference(threadID: id, turnID: "turn", startedAt: now)+ let reference = ActivityTurnReference(threadID: id, turnID: "turn")var state = SessionLifecycleState(- requestedThreadID: id, turnID: "turn", startedAt: now, approvalReviewer: nil,- effort: nil, lastProgressAt: now, terminal: nil+ requestedThreadID: id, turnID: "turn", startedAt: now, effort: nil, lastProgressAt: now, terminal: nil)state.parentThreadID = id == "grandchild" ? "child" : id == "child" ? "root" : nil- state.rootSessionID = id == "grandchild" || id == "child" ? "root" : nil+ state.rootThreadID = id == "grandchild" || id == "child" ? "root" : nilstate.rootTurnID = "turn"states[reference] = state}- await reader.replace(states, verifiedThreads: ["root": now, "child": now, "other": now])+ let verified = Dictionary(uniqueKeysWithValues: ["root", "child", "other"].map {+ (ActivityTurnReference(threadID: $0, turnID: "turn"), now)+ })+ await reader.replace(states, verifiedTurns: verified)let result = await reader.lifecycleStates(for: Array(states.keys), now: now)#expect(result.first { $0.requestedThreadID == "other" }?.readStatus == .complete)#expect(result.filter { $0.requestedThreadID != "other" }.allSatisfy { $0.readStatus == .unavailable })@@ -26,19 +28,18 @@ struct SessionLifecycleCacheTests {@Test func disconnectAndCoverageExpiryInvalidateCachedLifecycle() async {let reader = SessionLifecycleCache()let now = TestFixtures.now- let reference = ActivityTurnReference(threadID: "thread", turnID: "turn", startedAt: now)+ let reference = ActivityTurnReference(threadID: "thread", turnID: "turn")let state = SessionLifecycleState(- requestedThreadID: "thread", turnID: "turn", startedAt: now, approvalReviewer: .user,- effort: "high", lastProgressAt: now, terminal: nil+ requestedThreadID: "thread", turnID: "turn", startedAt: now, effort: "high", lastProgressAt: now, terminal: nil)- await reader.replace([reference: state], verifiedThreads: [reference.threadID: now])+ await reader.replace([reference: state], verifiedTurns: [reference: now])#expect(await reader.lifecycleStates(for: [reference], now: now).first?.readStatus == .complete)#expect(await reader.lifecycleStates(for: [reference], now: now.addingTimeInterval(16)).first?.readStatus == .unavailable)await reader.invalidate()#expect(await reader.lifecycleStates(for: [reference], now: now).first?.readStatus == .unavailable)- await reader.replace([:], verifiedThreads: [reference.threadID: now])+ await reader.replace([:], verifiedTurns: [reference: now])#expect(await reader.lifecycleStates(for: [reference], now: now).first?.readStatus == .notFound)- await reader.replace([:], verifiedThreads: [:])+ await reader.replace([:], verifiedTurns: [:])#expect(await reader.lifecycleStates(for: [reference], now: now).first?.readStatus == .unavailable)}}@@ -48,20 +49,19 @@ extension SessionLifecycleCacheTests {let reader = SessionLifecycleCache()let now = TestFixtures.nowfunc reference(_ id: String) -> ActivityTurnReference {- .init(threadID: id, turnID: "turn", startedAt: now)+ .init(threadID: id, turnID: "turn")}func state(_ id: String) -> SessionLifecycleState {.init(requestedThreadID: id,turnID: "turn",startedAt: now,- approvalReviewer: .user,effort: nil,lastProgressAt: now,terminal: nil)}- await reader.replace([reference("a"): state("a"), reference("b"): state("b")], verifiedThreads: ["a": now, "b": now.addingTimeInterval(-16)])+ await reader.replace([reference("a"): state("a"), reference("b"): state("b")], verifiedTurns: [reference("a"): now, reference("b"): now.addingTimeInterval(-16)])#expect(await reader.lifecycleStates(for: [reference("a")], now: now).first?.readStatus == .complete)#expect(await reader.lifecycleStates(for: [reference("b")], now: now).first?.readStatus == .unavailable)}@@ -72,13 +72,12 @@ extension SessionLifecycleCacheTests {func finishedChildCannotExpireRunningRoot(previousTurn: Bool) async {let cache = SessionLifecycleCache()let now = TestFixtures.now- let root = ActivityTurnReference(threadID: "root", turnID: "current", startedAt: now)- let child = ActivityTurnReference(threadID: "child", turnID: "child", startedAt: now)+ let root = ActivityTurnReference(threadID: "root", turnID: "current")+ let child = ActivityTurnReference(threadID: "child", turnID: "child")let rootState = SessionLifecycleState(requestedThreadID: "root",turnID: "current",startedAt: now,- approvalReviewer: nil,effort: nil,lastProgressAt: now,terminal: nil@@ -87,15 +86,14 @@ extension SessionLifecycleCacheTests {requestedThreadID: "child",turnID: "child",startedAt: now,- approvalReviewer: nil,effort: nil,lastProgressAt: now,terminal: .completed(at: nil, duration: nil),rootTurnID: previousTurn ? "old" : "current",- rootSessionID: "root",+ rootThreadID: "root",parentThreadID: "root")- await cache.replace([root: rootState, child: childState], verifiedThreads: ["root": now])+ await cache.replace([root: rootState, child: childState], verifiedTurns: [root: now])let states = await cache.lifecycleStates(for: [root], now: now)#expect(states.first { $0.requestedThreadID == "root" }?.readStatus == .complete)#expect(states.allSatisfy { $0.readStatus == .complete })@@ -105,7 +103,7 @@ extension SessionLifecycleCacheTests {let cache = SessionLifecycleCache()let now = TestFixtures.nowfunc reference(_ thread: String, _ turn: String) -> ActivityTurnReference {- .init(threadID: thread, turnID: turn, startedAt: now)+ .init(threadID: thread, turnID: turn)}var states: [ActivityTurnReference: SessionLifecycleState] = [:]for turn in ["old", "current"] {@@ -113,7 +111,6 @@ extension SessionLifecycleCacheTests {requestedThreadID: "root",turnID: turn,startedAt: now,- approvalReviewer: nil,effort: nil,lastProgressAt: now,terminal: nil@@ -123,19 +120,67 @@ extension SessionLifecycleCacheTests {requestedThreadID: "child",turnID: "child",startedAt: now,- approvalReviewer: nil,effort: nil,lastProgressAt: now,terminal: nil,rootTurnID: "old",- rootSessionID: "root",+ rootThreadID: "root",parentThreadID: "root")- await cache.replace(states, verifiedThreads: ["root": now])+ await cache.replace(states, verifiedTurns: [reference("root", "old"): now, reference("root", "current"): now])let result = await cache.lifecycleStates(for: [reference("root", "old"), reference("root", "current")], now: now)#expect(result.first { $0.turnID == "old" }?.readStatus == .unavailable)#expect(result.first { $0.turnID == "current" }?.readStatus == .complete)- await cache.replace(states, verifiedThreads: ["root": now, "child": now])+ await cache.replace(states, verifiedTurns: Dictionary(uniqueKeysWithValues: states.keys.map { ($0, now) }))#expect(await cache.lifecycleStates(for: Array(states.keys), now: now).allSatisfy { $0.readStatus == .complete })}}++extension SessionLifecycleCacheTests {+ @Test func verifyingNewTurnDoesNotRefreshOmittedTurnInSameThread() async {+ let cache = SessionLifecycleCache()+ let now = TestFixtures.now+ let old = ActivityTurnReference(threadID: "thread", turnID: "old")+ let current = ActivityTurnReference(threadID: "thread", turnID: "current")+ let states = Dictionary(uniqueKeysWithValues: [old, current].map {+ ($0, SessionLifecycleState(+ requestedThreadID: $0.threadID,+ turnID: $0.turnID,+ startedAt: now,+ effort: nil,+ lastProgressAt: now,+ terminal: nil+ ))+ })+ await cache.replace(states, verifiedTurns: [current: now])+ let result = await cache.lifecycleStates(for: [old, current], now: now)+ #expect(result.first { $0.turnID == "old" }?.readStatus == .unavailable)+ #expect(result.first { $0.turnID == "current" }?.readStatus == .complete)+ }+}++extension SessionLifecycleCacheTests {+ @Test func unresolvedChildrenRespectKnownRootIdentityAcrossNestedThreads() {+ let now = TestFixtures.now+ let a = ActivityTurnReference(threadID: "parent", turnID: "a")+ let b = ActivityTurnReference(threadID: "parent", turnID: "b")+ func child(_ id: String, parent: String, root: String?) -> SessionLifecycleState {+ SessionLifecycleState(+ requestedThreadID: id, turnID: id, startedAt: now, effort: nil,+ lastProgressAt: now, terminal: nil, rootTurnID: root, parentThreadID: parent+ )+ }+ let states = [+ child("child-a", parent: "parent", root: "a"),+ child("grandchild-a", parent: "child-a", root: "a"),+ child("child-b", parent: "parent", root: "b"),+ child("unknown", parent: "parent", root: nil)+ ]+ func ids(_ roots: Set<ActivityTurnReference>) -> Set<String> {+ Set(SessionLifecycleState.subagentStates(for: roots, in: states).map(\.requestedThreadID))+ }+ #expect(ids([a]) == ["child-a", "grandchild-a", "unknown"])+ #expect(ids([b]) == ["child-b", "unknown"])+ #expect(ids([a, b]) == Set(states.map(\.requestedThreadID)))+ }+}diff --git a/CodexBarTests/AppServer/AppServerLogTests.swift b/CodexBarTests/AppServer/AppServerLogTests.swiftindex 62e4124..2c94dee 100644--- a/CodexBarTests/AppServer/AppServerLogTests.swift+++ b/CodexBarTests/AppServer/AppServerLogTests.swift@@ -4,6 +4,22 @@ import SQLite3import Testingstruct AppServerLogTests {+ @Test func unsupportedDatabaseVersionRejectsWritesAndClear() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = directory.url.appendingPathComponent(AppServerLogStore.databaseName)+ var database: OpaquePointer?+ #expect(sqlite3_open(url.path, &database) == SQLITE_OK)+ #expect(sqlite3_exec(database, "PRAGMA user_version = 999; CREATE TABLE future_data (value TEXT); INSERT INTO future_data VALUES ('keep');", nil, nil, nil) == SQLITE_OK)+ sqlite3_close(database)+ let before = try Data(contentsOf: url)+ let store = AppServerLogStore(directoryURL: directory.url)+ store.recordFailure(message: "must not be written")+ await #expect(throws: (any Error).self) { try await store.page() }+ await #expect(throws: (any Error).self) { try await store.clear() }+ #expect(try Data(contentsOf: url) == before)+ }+@Test(arguments: [0, 5])func unchangedRefreshDoesNotPublishOrChangePaging(entryCount: Int) async throws {let directory = try TestDirectory()diff --git a/CodexBarTests/AppServer/AppServerRequestBudgetTests.swift b/CodexBarTests/AppServer/AppServerRequestBudgetTests.swiftindex c11e060..9169e1d 100644--- a/CodexBarTests/AppServer/AppServerRequestBudgetTests.swift+++ b/CodexBarTests/AppServer/AppServerRequestBudgetTests.swift@@ -63,7 +63,7 @@ struct AppServerRequestBudgetTests {@Test func expiredCreditIsRejectedBeforeConsumeEvenWithRemainingRequestBudget() async throws {let server = try SharedServerFixture { peer inlet initialize = try peer.readMessage()- try peer.reply(to: initialize, result: ["userAgent": "codex/0.157.0"])+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])#expect(try peer.readMessage()["method"] as? String == "initialized")for _ in 0 ..< 2 {let account = try peer.readMessage()diff --git a/CodexBarTests/AppServer/AppServerSessionTests.swift b/CodexBarTests/AppServer/AppServerSessionTests.swiftindex 1b41439..9a31249 100644--- a/CodexBarTests/AppServer/AppServerSessionTests.swift+++ b/CodexBarTests/AppServer/AppServerSessionTests.swift@@ -4,6 +4,68 @@ import Foundationimport Testingstruct AppServerSessionTests {+ @Test(arguments: ["account", "activity"], [nil, "0.162.0", "codex/", "codex/invalid", "codex/0.159.0"] as [String?])+ func connectionsShareHandshakeValidation(_ connection: String, userAgent: String?) throws {+ let server = try SharedServerFixture { peer in+ let request = try peer.readMessage()+ var result: [String: Any] = [:]+ result["userAgent"] = userAgent+ try peer.reply(to: request, result: result)+ }+ defer { server.close() }+ do {+ if connection == "account" {+ let session = try AccountSession(socketURL: server.url, logStorage: nil)+ defer { session.close() }+ _ = try session.initializeAccount()+ } else {+ let session = try AppServerSession(socketURL: server.url, logStorage: nil)+ defer { session.close() }+ try session.initialize(clientName: "codex_bar_activity", minimumVersion: CodexVersionReader.minimumAppServerVersion)+ }+ Issue.record("Expected handshake rejection")+ } catch let error as CodexStatusError {+ if userAgent == "codex/0.159.0" {+ guard case .unsupportedVersion = error else { Issue.record("Wrong error: \(error)")+ return+ }+ } else {+ guard case .invalidServerResponse = error else { Issue.record("Wrong error: \(error)")+ return+ }+ }+ }+ try server.finish()+ }++ @Test func accountRetriesUseNewIDsAndRememberUnsupportedMethods() throws {+ let server = try SharedServerFixture { peer in+ let first = try peer.readMessage()+ #expect(first["method"] as? String == "account/read")+ try peer.send(["id": #require(first["id"]), "error": ["code": -32000, "message": "temporary failure"]])+ let retry = try peer.readMessage()+ #expect(retry["id"] as? Int != first["id"] as? Int)+ try peer.reply(to: retry, result: ["value": 7])+ let unsupported = try peer.readMessage()+ #expect(unsupported["id"] as? Int != retry["id"] as? Int)+ try peer.send(["id": #require(unsupported["id"]), "error": ["code": -32601, "message": "unknown method"]])+ let next = try peer.readMessage()+ #expect(next["method"] as? String == "probe")+ try peer.reply(to: next, result: ["value": 8])+ }+ defer { server.close() }+ let session = try AccountSession(socketURL: server.url, logStorage: nil)+ defer { session.close() }+ let first = try session.request("account/read", as: Value.self)+ #expect(first.value == 7)+ for _ in 0 ..< 2 {+ #expect(throws: CodexStatusError.self) { _ = try session.request("missing", as: Value.self) }+ }+ let next = try session.request("probe", as: Value.self)+ #expect(next.value == 8)+ try server.finish()+ }+@Test(arguments: [true, false])func activityReaderValidatesVersionAndReusesConnection(_ supported: Bool) async throws {let directory = try TestDirectory()@@ -13,7 +75,7 @@ struct AppServerSessionTests {let server = try SharedServerFixture { peer inlet initialize = try peer.readMessage()#expect(initialize["method"] as? String == "initialize")- try peer.reply(to: initialize, result: ["userAgent": supported ? "codex/0.157.0" : "codex/0.156.0"])+ try peer.reply(to: initialize, result: ["userAgent": supported ? "codex/0.162.0" : "codex/0.159.0"])if supported {#expect(try peer.readMessage()["method"] as? String == "initialized")for _ in 0 ..< 4 {@@ -136,11 +198,10 @@ struct AppServerSessionTests {private func logDeliveryMessages() throws -> (filtered: [Data], retained: [Data]) {var filtered = try unusedNotifications()var retained = try [- "thread/started", "thread/status/changed", "thread/settings/updated", "turn/started", "turn/completed",- "item/autoApprovalReview/started", "item/autoApprovalReview/completed", "serverRequest/resolved", "error", "warning",- "hook/started", "hook/completed", "mcpServer/startupStatus/updated", "model/rerouted", "model/verification",- "modelProvider/authRecoveryStarted", "modelProvider/authRecoveryCompleted", "model/safetyBuffering/updated",- "thread/environment/connected", "thread/environment/disconnected"+ "thread/started", "thread/status/changed", "turn/started", "turn/completed",+ "serverRequest/resolved", "account/updated", "account/rateLimits/updated", "error", "warning",+ "hook/started", "hook/completed", "model/rerouted", "model/verification",+ "modelProvider/authRecoveryStarted", "modelProvider/authRecoveryCompleted", "model/safetyBuffering/updated"].map { try notification($0, params: ["marker": $0]) }try retained.append(notification("turn/diff/updated", params: ["diff": "original patch"]))try retained.append(notification("turn/plan/updated", params: ["plan": [["step": "original step", "status": "pending"]]]))@@ -170,7 +231,6 @@ struct AppServerSessionTests {"subAgentActivity","agentMessage","reasoning",- "plan","enteredReviewMode","exitedReviewMode"] {@@ -180,7 +240,7 @@ struct AppServerSessionTests {}for method in ["item/commandExecution/requestApproval", "item/fileChange/requestApproval", "item/permissions/requestApproval",- "item/tool/requestUserInput", "mcpServer/elicitation/request"+ "mcpServer/elicitation/request"] {try retained.append(JSONSerialization.data(withJSONObject: ["id": "approval", "method": method, "params": ["command": "original"]@@ -197,7 +257,9 @@ struct AppServerSessionTests {private func unusedNotifications() throws -> [Data] {var messages: [Data] = []for method in [- "hook/futureEvent", "account/updated", "account/rateLimits/updated",+ "thread/settings/updated", "thread/environment/connected", "thread/environment/disconnected",+ "item/tool/requestUserInput", "item/autoApprovalReview/started", "item/autoApprovalReview/completed",+ "hook/futureEvent","remoteControl/status/changed", "thread/goal/cleared", "thread/name/updated", "future/tool/delta"] {try messages.append(notification(method, params: ["marker": method]))@@ -208,11 +270,15 @@ struct AppServerSessionTests {}try messages.append(notification("item/reasoning/summaryPartAdded", params: ["summaryIndex": 0]))try messages.append(notification("item/mcpToolCall/progress", params: ["message": "working"]))- for type in ["userMessage", "hookPrompt", "functionCallOutput", "futureItem"] {+ try messages.append(notification("mcpServer/startupStatus/updated", params: [+ "threadId": "thread", "name": "tripo_backend", "status": "starting"+ ]))+ for type in ["plan", "userMessage", "hookPrompt", "functionCallOutput", "futureItem"] {for method in ["item/started", "item/completed"] {try messages.append(notification(method, params: ["item": ["id": type, "type": type, "text": "body"]]))}}+ try messages.append(notification("mcpServer/elicitation/request", params: ["mode": "openai/userVerification"]))return messages}@@ -220,8 +286,8 @@ struct AppServerSessionTests {let server = try SharedServerFixture { peer inlet initialize = try peer.readMessage()#expect(initialize["method"] as? String == "initialize")- #expect((initialize["params"] as? [String: Any])?["capabilities"] as? [String: Bool] == ["experimentalApi": true])- try peer.reply(to: initialize, result: ["userAgent": "codex/0.157.0"])+ #expect((initialize["params"] as? [String: Any])?["capabilities"] as? [String: Bool] == ["experimentalApi": false])+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])#expect(try peer.readMessage()["method"] as? String == "initialized")let account = try peer.readMessage()#expect(account["method"] as? String == "account/read")@@ -231,7 +297,7 @@ struct AppServerSessionTests {defer { server.close() }let session = try AccountSession(socketURL: server.url, logStorage: nil)let result = try session.initializeAccount()- #expect(result.version == "0.157.0")+ #expect(result.version == "0.162.0")#expect(result.account.account != nil)session.close()#expect(!session.isOpen)diff --git a/CodexBarTests/AppServer/AppServerStartupTests.swift b/CodexBarTests/AppServer/AppServerStartupTests.swiftindex 6f589fd..dc315ae 100644--- a/CodexBarTests/AppServer/AppServerStartupTests.swift+++ b/CodexBarTests/AppServer/AppServerStartupTests.swift@@ -18,8 +18,8 @@ struct AppServerStartupTests {@Test func startsMissingServiceWithResolvedEnvironmentAndBundledFallback() async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let unsupported = try directory.executable("exit 2", named: "old codex")- let supported = try directory.executable("""+ let unsupported = try Self.executable(in: directory, "exit 2", named: "old codex")+ let supported = try Self.executable(in: directory, """printf '%s\\n' "$*" >> "$HOME/calls"if [ "$4" = '--help' ]; thenprintf 'Usage: codex app-server daemon start [OPTIONS]'@@ -79,7 +79,7 @@ struct AppServerStartupTests {@Test func reportsMissingAndUnsupportedInstallations() async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let unsupported = try directory.executable("exit 2", named: "fake codex")+ let unsupported = try Self.executable(in: directory, "exit 2", named: "fake codex")for path in [nil, unsupported.path] {let startup = AppServerStartup(environment: [:], installations: CodexInstallations(globalPath: path, bundledPath: nil),@@ -102,7 +102,7 @@ struct AppServerStartupTests {func boundsFailedStartsAndReadinessRetries(_ body: String) async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let command = try directory.executable("""+ let command = try Self.executable(in: directory, """if [ "$4" = '--help' ]; thenprintf 'Usage: codex app-server daemon start [OPTIONS]'exit 0@@ -135,7 +135,7 @@ struct AppServerStartupTests {@Test func rechecksConnectionBeforeIssuingStart() async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let command = try directory.executable("""+ let command = try Self.executable(in: directory, """if [ "$4" != '--help' ]; thenprintf 'unexpected start' > "$HOME/started"exit 1@@ -163,7 +163,7 @@ struct AppServerStartupTests {@Test func reusesServiceEvenWhenTheStartCommandFails() async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let command = try directory.executable("""+ let command = try Self.executable(in: directory, """if [ "$4" = '--help' ]; then printf 'daemon start'; exit 0; fiprintf ready > "$PROCESS_TEST_DIR/started"exit 7@@ -186,7 +186,7 @@ struct AppServerStartupTests {func preventsOverlappingCommandsAndAllowsRetryAfterCancellation(_ stage: String) async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let command = try directory.executable("""+ let command = try Self.executable(in: directory, """if [ -f "$PROCESS_TEST_DIR/retry" ]; thenif [ "$4" = '--help' ]; then printf 'daemon start'else printf ready > "$PROCESS_TEST_DIR/started"; fi@@ -211,18 +211,16 @@ struct AppServerStartupTests {let task = Task { try await startup.ensureStarted() }defer { task.cancel() }try await directory.waitForFile("blocked")- do {- try await startup.ensureStarted()- Issue.record("Expected overlapping startup to be rejected")- } catch let error as AppServerStartup.StartupError {- guard case .notReady = error else { throw error }- }+ let joined = Task { try await startup.ensureStarted() }+ await Task.yield()+ joined.cancel()task.cancel()await #expect(throws: CancellationError.self) { try await task.value }+ await #expect(throws: CancellationError.self) { try await joined.value }#expect(!FileManager.default.fileExists(atPath: marker.path))#expect(try String(contentsOf: directory.url.appendingPathComponent("calls"), encoding: .utf8) == "blocked")_ = try directory.write("retry", to: "retry")- try await startup.ensureStarted()+ try await startup.ensureStarted(trigger: .manual)#expect(FileManager.default.fileExists(atPath: marker.path))}@@ -236,4 +234,204 @@ struct AppServerStartupTests {#expect(error.serverIsAbsent)}}++ @Test(arguments: ["0.161.0", "0.162.0-alpha.17.2", "unrecognized", "absent"])+ func selectsSupportedBundledVersionBeforeLaunching(cliVersion: String) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let cli = try directory.executable("""+ if [ "$1" = '--version' ]; then printf '%s' '\(cliVersion)'; exit 0; fi+ printf unexpected > "$PROCESS_TEST_DIR/cli-command"+ exit 0+ """, named: "cli")+ let bundled = try Self.executable(in: directory, """+ if [ "$4" = '--help' ]; then printf 'daemon start'; exit 0; fi+ printf ready > "$PROCESS_TEST_DIR/ready"+ """, named: "bundled")+ let ready = directory.url.appendingPathComponent("ready")+ let startup = AppServerStartup(+ environment: ["PROCESS_TEST_DIR": directory.url.path],+ installations: .init(globalPath: cliVersion == "absent" ? nil : cli.path, bundledPath: bundled.path),+ probeConnection: {+ guard FileManager.default.fileExists(atPath: ready.path) else { throw AppServerConnectionError(code: ENOENT) }+ }+ )+ try await startup.ensureStarted()+ #expect(FileManager.default.fileExists(atPath: ready.path))+ #expect(!FileManager.default.fileExists(atPath: directory.url.appendingPathComponent("cli-command").path))+ }++ @Test func rejectsOldVersionsBeforeCapabilityChecksOrStartup() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let command = try directory.executable("""+ if [ "$1" = '--version' ]; then printf 'codex-cli 0.161.0'; exit 0; fi+ printf unexpected > "$PROCESS_TEST_DIR/called"+ """)+ let startup = AppServerStartup(+ environment: ["PROCESS_TEST_DIR": directory.url.path], installations: .init(globalPath: command.path, bundledPath: command.path),+ probeConnection: { throw AppServerConnectionError(code: ECONNREFUSED) }+ )+ do {+ try await startup.ensureStarted()+ Issue.record("Expected minimum version rejection")+ } catch let CodexStatusError.unsupportedVersion(minimum) {+ #expect(minimum == "0.162.0")+ }+ #expect(!FileManager.default.fileExists(atPath: directory.url.appendingPathComponent("called").path))+ }++ @Test func automaticRetriesAreBoundedManualBypassesAndConnectionResetsBudget() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let clock = OSAllocatedUnfairLock(initialState: ContinuousClock.now)+ let ready = OSAllocatedUnfairLock(initialState: false)+ let command = try Self.executable(in: directory, """+ if [ "$4" = '--help' ]; then printf 'daemon start'; exit 0; fi+ printf 'start\\n' >> "$PROCESS_TEST_DIR/calls"+ exit 7+ """)+ let startup = AppServerStartup(+ environment: ["PROCESS_TEST_DIR": directory.url.path], installations: .init(globalPath: command.path, bundledPath: nil),+ probeConnection: {+ if !ready.withLock({ $0 }) {+ throw AppServerConnectionError(code: ENOENT)+ }+ },+ now: { clock.withLock { $0 } }+ )+ for index in 0 ..< 3 {+ if index > 0 {+ clock.withLock { $0 = $0.advanced(by: .seconds(60)) }+ }+ do { try await startup.ensureStarted()+ Issue.record("Expected command failure")+ } catch let error as AppServerStartup.StartupError {+ guard case .commandFailed(7) = error else { throw error }+ }+ do { try await startup.ensureStarted()+ Issue.record("Expected automatic retry limit")+ } catch let error as AppServerStartup.StartupError {+ if index < 2 {+ guard case .retryDeferred = error else { throw error }+ } else {+ guard case .retryExhausted = error else { throw error }+ }+ }+ }+ await #expect(throws: AppServerStartup.StartupError.self) { try await startup.ensureStarted(trigger: .manual) }+ ready.withLock { $0 = true }+ try await startup.ensureStarted()+ ready.withLock { $0 = false }+ do { try await startup.ensureStarted()+ Issue.record("Expected a fresh automatic attempt")+ } catch let error as AppServerStartup.StartupError { guard case .commandFailed(7) = error else { throw error } }+ let calls = try String(contentsOf: directory.url.appendingPathComponent("calls"), encoding: .utf8)+ #expect(calls.split(separator: "\n").count == 5)+ }++ @Test func concurrentRequestsShareOneStartAndOneCancellationDoesNotCancelOthers() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let command = try Self.executable(in: directory, """+ if [ "$4" = '--help' ]; then printf 'daemon start'; exit 0; fi+ printf 'start\\n' >> "$PROCESS_TEST_DIR/calls"+ printf waiting > "$PROCESS_TEST_DIR/waiting"+ while [ ! -f "$PROCESS_TEST_DIR/release" ]; do /bin/sleep 0.01; done+ printf ready > "$PROCESS_TEST_DIR/ready"+ """)+ let ready = directory.url.appendingPathComponent("ready")+ let startup = AppServerStartup(+ environment: ["PROCESS_TEST_DIR": directory.url.path], installations: .init(globalPath: command.path, bundledPath: nil),+ probeConnection: {+ if !FileManager.default.fileExists(atPath: ready.path) {+ throw AppServerConnectionError(code: ENOENT)+ }+ }+ )+ let first = Task { try await startup.ensureStarted() }+ defer { first.cancel() }+ try await directory.waitForFile("waiting")+ let second = Task { try await startup.ensureStarted(trigger: .manual) }+ defer { second.cancel() }+ try await Task.sleep(for: .milliseconds(50))+ first.cancel()+ _ = try directory.write("release", to: "release")+ await #expect(throws: CancellationError.self) { try await first.value }+ try await second.value+ #expect(try String(contentsOf: directory.url.appendingPathComponent("calls"), encoding: .utf8) == "start\n")+ }++ @Test(arguments: [false, true])+ func accountRecoveryCanStartAfterInitialFailure(manual: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let clock = OSAllocatedUnfairLock(initialState: ContinuousClock.now)+ let command = try Self.executable(in: directory, """+ if [ "$4" = '--help' ]; then printf 'daemon start'; exit 0; fi+ printf 'start\\n' >> "$PROCESS_TEST_DIR/calls"+ if [ ! -f "$PROCESS_TEST_DIR/allow" ]; then exit 7; fi+ printf ready > "$PROCESS_TEST_DIR/ready"+ """)+ let ready = directory.url.appendingPathComponent("ready")+ let startup = AppServerStartup(+ environment: ["PROCESS_TEST_DIR": directory.url.path], installations: .init(globalPath: command.path, bundledPath: nil),+ probeConnection: {+ if !FileManager.default.fileExists(atPath: ready.path) {+ throw AppServerConnectionError(code: ENOENT)+ }+ },+ now: { clock.withLock { $0 } }+ )+ await #expect(throws: AppServerStartup.StartupError.self) { try await startup.ensureStarted() }+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ let account = try peer.readMessage()+ try peer.reply(to: account, result: ["account": NSNull()])+ }+ defer { server.close() }+ let service = CodexStatusService(socketURL: server.url, logStorage: nil, startup: startup)+ let deferred = await service.fetchOutcome()+ guard case .initializationFailed = deferred.outcome else { Issue.record("Expected deferred retry")+ return+ }+ _ = try directory.write("allow", to: "allow")+ if manual {+ #expect(try await service.reconnect(minimumVersion: "0.162.0").version == "0.162.0")+ } else {+ clock.withLock { $0 = $0.advanced(by: .seconds(60)) }+ let recovered = await service.fetchOutcome()+ guard case .notLoggedIn = recovered.outcome else { Issue.record("Expected successful account read")+ return+ }+ }+ let calls = try String(contentsOf: directory.url.appendingPathComponent("calls"), encoding: .utf8)+ #expect(calls.split(separator: "\n").count == 2)+ try server.finish()+ }++ @Test func existingOldDaemonIsRejectedWithoutStartingAnother() async throws {+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.161.0"])+ }+ defer { server.close() }+ let startup = AppServerStartup(environment: [:], installations: .init(globalPath: nil, bundledPath: nil), probeConnection: {})+ let service = CodexStatusService(socketURL: server.url, logStorage: nil, startup: startup)+ let result = await service.fetchOutcome()+ guard case let .unsupportedVersion(minimum) = result.outcome else { Issue.record("Expected actual server version check")+ return+ }+ #expect(minimum == "0.162.0")+ try server.finish()+ }++ private static func executable(in directory: TestDirectory, _ body: String, named name: String = "fake codex") throws -> URL {+ try directory.executable("""+ if [ "$1" = '--version' ]; then printf 'codex-cli 0.162.0'; exit 0; fi+ \(body)+ """, named: name)+ }}diff --git a/CodexBarTests/Codex/CodexVersionTests.swift b/CodexBarTests/Codex/CodexVersionTests.swiftindex 32a484f..4e7661c 100644--- a/CodexBarTests/Codex/CodexVersionTests.swift+++ b/CodexBarTests/Codex/CodexVersionTests.swift@@ -6,13 +6,17 @@ struct CodexVersionTests {("0.150.0", false),("0.156.0", false),("0.157.0-alpha.2", false),- ("0.157.0", true),- ("0.160.0-alpha.2", true),- ("0.160.1", true)+ ("0.157.0", false),+ ("0.159.0", false),+ ("0.160.0-alpha.2", false),+ ("0.160.0", false),+ ("0.161.0", false),+ ("0.162.0-alpha.2", false),+ ("0.162.0", true),+ ("0.162.1", true)])- func activityRequiresSharedServerProtocol(_ version: String, _ expected: Bool) {- #expect(CodexVersionReader.isVersion(version, atLeast: CodexMinimumVersion.activity) == expected)- #expect(CodexVersionReader.isVersion(version, atLeast: CodexMinimumVersion.account) == expected)+ func appServerRequiresMinimumVersion(_ version: String, _ expected: Bool) {+ #expect(CodexVersionReader.isVersion(version, atLeast: CodexVersionReader.minimumAppServerVersion) == expected)}@Test(arguments: [diff --git a/CodexBarTests/CodexStatus/AccountNotificationTests.swift b/CodexBarTests/CodexStatus/AccountNotificationTests.swiftnew file mode 100644index 0000000..ecb6a28--- /dev/null+++ b/CodexBarTests/CodexStatus/AccountNotificationTests.swift@@ -0,0 +1,279 @@+import Foundation+import os+import Testing++@Suite(.timeLimit(.minutes(1)))+struct AccountNotificationTests {+ @Test func repeatedNotificationsKeepFirstDeadlineAndRespectCooldown() {+ var schedule = AccountNotificationSchedule()+ let now = ContinuousClock.now+ schedule.receive(.rateLimits, at: now)+ schedule.receive(.rateLimits, at: now.advanced(by: .milliseconds(500)))+ #expect(schedule.readyAt == now.advanced(by: .seconds(1)))+ schedule.didStartRefresh(at: now.advanced(by: .seconds(1)))+ schedule.receive(.rateLimits, at: now.advanced(by: .seconds(2)))+ schedule.receive(.rateLimits, at: now.advanced(by: .seconds(9)))+ #expect(schedule.readyAt == now.advanced(by: .seconds(11)))+ }++ @Test func accountChangeBypassesQuotaCooldownAndKeepsPriority() {+ var schedule = AccountNotificationSchedule()+ let now = ContinuousClock.now+ schedule.didStartRefresh(at: now)+ schedule.receive(.rateLimits, at: now)+ schedule.receive(.account, at: now.advanced(by: .seconds(1)))+ schedule.receive(.rateLimits, at: now.advanced(by: .seconds(1)))+ #expect(schedule.readyAt == now.advanced(by: .seconds(2)))+ }++ @Test func anyRefreshConsumesEarlierSignalsButKeepsLaterChanges() {+ var schedule = AccountNotificationSchedule()+ let now = ContinuousClock.now+ schedule.receive(.account, at: now)+ schedule.didStartRefresh(at: now)+ #expect(schedule.readyAt == nil)+ schedule.receive(.rateLimits, at: now.advanced(by: .seconds(2)))+ #expect(schedule.readyAt == now.advanced(by: .seconds(10)))+ schedule.receive(.account, at: now.advanced(by: .seconds(3)))+ #expect(schedule.readyAt == now.advanced(by: .seconds(4)))+ }++ @Test func accountSessionCoalescesInterleavedAndIdleNotifications() throws {+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let server = try SharedServerFixture { peer in+ let request = try peer.readMessage()+ for _ in 0 ..< 20 {+ try peer.send(["method": "account/rateLimits/updated", "params": [:]])+ }+ try peer.send(["method": "account/updated", "params": [:]])+ try peer.reply(to: request, result: ["value": 1])+ let next = try peer.readMessage()+ try peer.reply(to: next, result: ["value": 2])+ try peer.send(["method": "account/rateLimits/updated", "params": [:]])+ _ = release.wait(timeout: .now() + 5)+ }+ defer { server.close() }+ let session = try AccountSession(socketURL: server.url, logStorage: nil)+ defer { session.close() }+ let first = try session.request("probe", as: Value.self)+ #expect(first.value == 1)+ #expect(try session.pollChanges() == .account)+ #expect(try session.pollChanges() == nil)+ let second = try session.request("probe", as: Value.self)+ #expect(second.value == 2)+ #expect(try session.pollChanges() == .rateLimits)+ #expect(try session.pollChanges() == nil)+ release.signal()+ try server.finish()+ }++ @Test func signedOutConnectionReceivesLoginAndRefreshesWithoutNewHandshake() async throws {+ let release = DispatchSemaphore(value: 0)+ let login = DispatchSemaphore(value: 0)+ let logout = DispatchSemaphore(value: 0)+ defer { release.signal()+ login.signal()+ logout.signal()+ }+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])+ #expect(try peer.readMessage()["method"] as? String == "initialized")+ let initialAccount = try peer.readMessage()+ try peer.reply(to: initialAccount, result: ["account": NSNull()])+ #expect(login.wait(timeout: .now() + 5) == .success)+ try peer.send(["method": "account/updated", "params": ["authMode": "apikey"]])+ let account = try peer.readMessage()+ #expect(account["method"] as? String == "account/read")+ try peer.reply(to: account, result: ["account": ["type": "apiKey"]])+ for method in ["account/rateLimits/read", "account/usage/read"] {+ let request = try peer.readMessage()+ #expect(request["method"] as? String == method)+ try peer.send(["id": #require(request["id"]), "error": ["code": -32601, "message": "unsupported"]])+ }+ #expect(logout.wait(timeout: .now() + 5) == .success)+ try peer.send(["method": "account/updated", "params": ["authMode": NSNull()]])+ let signedOut = try peer.readMessage()+ #expect(signedOut["method"] as? String == "account/read")+ try peer.reply(to: signedOut, result: ["account": NSNull()])+ _ = release.wait(timeout: .now() + 5)+ }+ defer { server.close() }+ let suite = "AccountNotificationTests.\(UUID().uuidString)"+ let defaults = try #require(UserDefaults(suiteName: suite))+ defer { defaults.removePersistentDomain(forName: suite) }+ let service = CodexStatusService(socketURL: server.url, logStorage: nil)+ let model = CodexStatusViewModel(service: service, defaults: defaults)+ model.startAutoRefresh()+ try await eventually { model.loadState == .notLoggedIn && !model.isRefreshing }+ let maintenanceClock = model.autoRefreshCountdownStartedAt+ #expect(await service.currentConnectionInfo()?.version == "0.162.0")+ login.signal()+ try await eventually { model.snapshot != nil && !model.isRefreshing }+ #expect(model.lastRefreshTrigger == .accountNotification)+ #expect(model.autoRefreshCountdownStartedAt == maintenanceClock)+ logout.signal()+ try await eventually { model.loadState == .notLoggedIn && !model.isRefreshing }+ #expect(model.snapshot == nil)+ #expect(model.autoRefreshCountdownStartedAt == maintenanceClock)+ #expect(await service.currentConnectionInfo()?.version == "0.162.0")+ release.signal()+ try server.finish()+ }++ @Test func notificationDuringRefreshRunsOnceAfterwardWithoutMovingMaintenanceClock() async throws {+ let entered = OSAllocatedUnfairLock(initialState: false)+ let respond = DispatchSemaphore(value: 0)+ let release = DispatchSemaphore(value: 0)+ defer { respond.signal()+ release.signal()+ }+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ let first = try peer.readMessage()+ entered.withLock { $0 = true }+ #expect(respond.wait(timeout: .now() + 5) == .success)+ try peer.reply(to: first, result: ["account": NSNull()])+ let second = try peer.readMessage()+ #expect(second["method"] as? String == "account/read")+ try peer.reply(to: second, result: ["account": NSNull()])+ _ = release.wait(timeout: .now() + 5)+ }+ defer { server.close() }+ let suite = "AccountNotificationTests.\(UUID().uuidString)"+ let defaults = try #require(UserDefaults(suiteName: suite))+ defer { defaults.removePersistentDomain(forName: suite) }+ let model = CodexStatusViewModel(service: CodexStatusService(socketURL: server.url, logStorage: nil), defaults: defaults)+ model.refresh(trigger: .manual)+ try await eventually { entered.withLock { $0 } }+ for _ in 0 ..< 20 {+ model.receiveAccountChange(.rateLimits)+ model.receiveAccountChange(.account)+ }+ respond.signal()+ try await eventually { !model.isRefreshing && model.autoRefreshCountdownStartedAt != nil }+ let maintenanceClock = model.autoRefreshCountdownStartedAt+ try await eventually { model.lastRefreshTrigger == .accountNotification && !model.isRefreshing }+ #expect(model.autoRefreshCountdownStartedAt == maintenanceClock)+ #expect(model.loadState == .notLoggedIn)+ release.signal()+ try server.finish()+ }++ @Test func closedConnectionRequestsRecoveryOnlyOnce() async throws {+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ let account = try peer.readMessage()+ try peer.reply(to: account, result: ["account": NSNull()])+ try peer.sendRaw(Data(), opcode: 8)+ }+ defer { server.close() }+ let service = CodexStatusService(socketURL: server.url, logStorage: nil)+ _ = await service.fetchOutcome()+ #expect(await service.pollAccountChanges() == .account)+ #expect(await service.pollAccountChanges() == nil)+ #expect(await service.currentConnectionInfo() == nil)+ try server.finish()+ }++ @Test func activityConnectionForwardsAccountChangesWithoutActivityEvents() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let release = DispatchSemaphore(value: 0)+ defer { release.signal() }+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ let loaded = try peer.readMessage()+ try peer.send(["method": "account/rateLimits/updated", "params": [:]])+ try peer.send(["method": "account/updated", "params": [:]])+ try peer.reply(to: loaded, result: ["data": []])+ _ = release.wait(timeout: .now() + 5)+ }+ defer { server.close() }+ var changes: [AccountChange] = []+ var events: [ActivityRecord] = []+ let reader = AppServerActivityReader(+ lifecycleCache: SessionLifecycleCache(), socketURL: server.url, logStorage: nil,+ tokenHistory: TokenHistoryStore(directoryURL: directory.url),+ recorder: ActivityRecorder(directoryURL: directory.url),+ onAccountChange: { changes.append($0) },+ onBatch: { batch in+ switch batch {+ case let .live(values), let .snapshotEvents(values): events += values+ default: break+ }+ }+ )+ await reader.start()+ try await eventually { changes.contains(.account) }+ await reader.stop()+ #expect(events.isEmpty)+ #expect(!FileManager.default.fileExists(atPath: directory.url.appendingPathComponent("Events").path))+ release.signal()+ try server.finish()+ }++ private func eventually(_ condition: () -> Bool) async throws {+ for _ in 0 ..< 300 {+ if condition() {+ return+ }+ try await Task.sleep(for: .milliseconds(10))+ }+ Issue.record("Condition was not reached")+ }++ private nonisolated struct Value: Decodable { let value: Int }+}++extension AccountNotificationTests {+ @Test func missingAccountFieldIsNotSignedOut() throws {+ #expect(throws: DecodingError.self) { try TestFixtures.decode(AccountReadResponse.self, "{}") }+ #expect(try TestFixtures.decode(AccountReadResponse.self, "{\"account\":null}").account == nil)+ }++ @Test(arguments: ["signedOut", "authentication", "serverError", "invalidPayload", "connectionClosed"])+ func refreshFailureKeepsAuthenticationSeparateFromReadFailure(result: String) async throws {+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ let account = try peer.readMessage()+ try peer.reply(to: account, result: ["account": ["type": "apiKey"]])+ let limits = try peer.readMessage()+ #expect(limits["method"] as? String == "account/rateLimits/read")+ try peer.send(["id": #require(limits["id"]), "error": ["code": -32000, "message": "codex account authentication required"]])+ for _ in 0 ..< (result == "serverError" ? 2 : 1) {+ let refresh = try peer.readMessage()+ #expect(refresh["method"] as? String == "account/read")+ #expect((refresh["params"] as? [String: Any])?["refreshToken"] as? Bool == true)+ switch result {+ case "signedOut": try peer.reply(to: refresh, result: ["account": NSNull()])+ case "invalidPayload": try peer.reply(to: refresh, result: [:])+ case "connectionClosed": return+ default:+ try peer.send(["id": #require(refresh["id"]), "error": [+ "code": -32000, "message": result == "authentication" ? "codex account authentication required" : "upstream network request failed"+ ]])+ }+ }+ }+ defer { server.close() }+ let service = CodexStatusService(socketURL: server.url, logStorage: nil)+ let outcome = await service.fetchOutcome().outcome+ switch outcome {+ case .notLoggedIn: #expect(result == "signedOut")+ case .authenticationRequired: #expect(result == "authentication")+ case .initializationFailed: #expect(["serverError", "invalidPayload", "connectionClosed"].contains(result))+ default: Issue.record("Unexpected fetch outcome")+ }+ try server.finish()+ }+}diff --git a/CodexBarTests/CodexStatus/AutoResetControllerTests.swift b/CodexBarTests/CodexStatus/AutoResetControllerTests.swiftindex 8341841..b674a9a 100644--- a/CodexBarTests/CodexStatus/AutoResetControllerTests.swift+++ b/CodexBarTests/CodexStatus/AutoResetControllerTests.swift@@ -11,12 +11,12 @@ struct AutoResetControllerTests {fixture.state.error = CodexStatusError.serverTimeoutfixture.controller.start()// 首次读取尚无目标, 用快照发现凭证后再计入业务尝试- try fixture.snapshots.send(fixture.snapshot())+ try fixture.outcomes.send(.data(fixture.snapshot()))for (index, offset) in [0.0, 15, 45, 105, 225].enumerated() {fixture.clock.advance(to: fixture.start.addingTimeInterval(offset))try await eventually { fixture.controller.scheduledDate != nil && fixture.state.readCount >= index + 1 }for _ in 0 ..< 10 {- try fixture.snapshots.send(fixture.snapshot())+ try fixture.outcomes.send(.data(fixture.snapshot()))}if index < 4 {#expect(fixture.controller.scheduledDate == fixture.start.addingTimeInterval([15, 45, 105, 225][index]))@@ -87,7 +87,7 @@ struct AutoResetControllerTests {#expect(fixture.controller.scheduledDate == nil)#expect(fixture.controller.wakeDate == nil)for _ in 0 ..< 10 {- try fixture.snapshots.send(fixture.snapshot())+ try fixture.outcomes.send(.data(fixture.snapshot()))}await settle()#expect(fixture.state.consumeCount == 2)@@ -108,7 +108,7 @@ struct AutoResetControllerTests {defer { fixture.stop() }let gate = ResetGate<AutoResetRead>()fixture.state.readOverride = { await gate.wait() }- try fixture.snapshots.send(fixture.snapshot())+ try fixture.outcomes.send(.data(fixture.snapshot()))fixture.controller.start()try await eventually { fixture.state.readCount == 1 }fixture.controller.handleSleep()@@ -127,7 +127,7 @@ struct AutoResetControllerTests {try await eventually { fixture.controller.scheduledDate != nil }fixture.controller.prepareForTermination()fixture.clock.advance(to: fixture.start.addingTimeInterval(400))- try fixture.snapshots.send(fixture.snapshot())+ try fixture.outcomes.send(.data(fixture.snapshot()))await settle()#expect(fixture.state.consumeCount == 1)#expect(fixture.controller.wakeDate == nil)@@ -135,22 +135,80 @@ struct AutoResetControllerTests {try await eventually { fixture.state.consumeCount == 2 && fixture.state.activeAssertions.isEmpty }}- @Test func changedAccountRejectsLateOldRead() async throws {+ @Test(arguments: [false, true])+ func changedAccountRejectsLateOldRead(stale: Bool) async throws {let fixture = try ResetFixture()defer { fixture.stop() }let gate = ResetGate<AutoResetRead>()let old = fixture.state.read- try fixture.snapshots.send(fixture.snapshot())+ try fixture.outcomes.send(.data(fixture.snapshot()))fixture.state.readOverride = { await gate.wait() }fixture.controller.start()try await eventually { fixture.state.readCount == 1 }fixture.state.account = CodexAccount(type: "chatgpt", email: "[email protected]", planType: "plus")fixture.state.readOverride = nil- try fixture.snapshots.send(fixture.snapshot())+ try fixture.outcomes.send(.data(fixture.snapshot(isStale: stale)))gate.release(old)try await eventually { fixture.state.consumeCount == 1 && fixture.state.activeAssertions.isEmpty }#expect(fixture.state.consumedAccounts == [AutoResetIdentity.accountIdentity(for: fixture.state.account)])}++ @Test(arguments: [false, true])+ func unavailableAccountClearsScheduleAndIgnoresLateRead(signedOut: Bool) async throws {+ let fixture = try ResetFixture()+ defer { fixture.stop() }+ let gate = ResetGate<AutoResetRead>()+ try fixture.outcomes.send(.data(fixture.snapshot()))+ fixture.state.readOverride = { await gate.wait() }+ fixture.controller.start()+ try await eventually { fixture.state.readCount == 1 }+ #expect(fixture.controller.wakeDate != nil)+ fixture.outcomes.send(signedOut ? .notLoggedIn : .authenticationRequired)+ #expect(fixture.controller.wakeDate == nil)+ #expect(fixture.controller.scheduledDate == nil)+ fixture.controller.handleWake()+ gate.release(fixture.state.read)+ try await eventually { fixture.state.activeAssertions.isEmpty }+ #expect(fixture.state.consumeCount == 0)+ #expect(fixture.controller.wakeDate == nil)+ fixture.state.readOverride = nil+ try fixture.outcomes.send(.data(fixture.snapshot()))+ let retry = try #require(fixture.controller.scheduledDate)+ fixture.clock.advance(to: retry)+ try await eventually { fixture.state.consumeCount == 1 }+ }++ @Test func failedAccountReadPreservesExistingPlan() async throws {+ let fixture = try ResetFixture()+ defer { fixture.stop() }+ fixture.controller.start()+ try await eventually { fixture.controller.scheduledDate != nil }+ let wake = fixture.controller.wakeDate+ let scheduled = fixture.controller.scheduledDate+ fixture.outcomes.send(.initializationFailed)+ await settle()+ #expect(fixture.controller.wakeDate == wake)+ #expect(fixture.controller.scheduledDate == scheduled)+ }++ @Test func confirmedConsumptionAfterSignOutCannotRecreatePlanOrBeConsumedAgain() async throws {+ let fixture = try ResetFixture()+ defer { fixture.stop() }+ let consume = ResetGate<ResetCreditConsumeResult>()+ fixture.state.consumeOverride = { await consume.wait() }+ fixture.controller.start()+ try await eventually { fixture.state.consumeCount == 1 }+ fixture.outcomes.send(.notLoggedIn)+ consume.release(ResetCreditConsumeResult(outcome: .reset, refreshedRead: fixture.state.read))+ try await eventually { fixture.state.activeAssertions.isEmpty }+ #expect(fixture.state.successes == 1)+ #expect(fixture.controller.wakeDate == nil)+ fixture.state.consumeOverride = nil+ try fixture.outcomes.send(.data(fixture.snapshot()))+ fixture.controller.handleWake()+ try await eventually { fixture.state.readCount >= 2 && fixture.state.activeAssertions.isEmpty }+ #expect(fixture.state.consumeCount == 1)+ }}private func eventually(_ predicate: () -> Bool) async throws {@@ -255,7 +313,7 @@ private final class ResetFixture {let preferences: TestPreferenceslet settings: AutoResetSettingslet controller: AutoResetController- let snapshots = CurrentValueSubject<CodexQuotaSnapshot?, Never>(nil)+ let outcomes = CurrentValueSubject<CodexFetchOutcome, Never>(.initializationFailed)let start = Date(timeIntervalSince1970: 1800000000)let clock: ResetClocklet state: ResetState@@ -272,7 +330,7 @@ private final class ResetFixture {state = ResetState(expiration: start.addingTimeInterval(900))let state = statelet clock = clock- controller = AutoResetController(settings: settings, snapshots: snapshots.eraseToAnyPublisher(), dependencies: .init(+ controller = AutoResetController(settings: settings, outcomes: outcomes.eraseToAnyPublisher(), dependencies: .init(read: { _ instate.readCount += 1if let handler = state.readOverride {@@ -297,13 +355,13 @@ private final class ResetFixture {))}- func snapshot() throws -> CodexQuotaSnapshot {+ func snapshot(isStale: Bool = false) throws -> CodexQuotaSnapshot {let response = try TestFixtures.decode(AccountRateLimitsResponse.self, """{"rateLimits":{},"rateLimitResetCredits":{"availableCount":1,"credits":[{"id":"test-credit","status":"available","resetType":"codexRateLimits","expiresAt":\(Int(expiration.timeIntervalSince1970))}]}}""")- return try CodexQuotaSnapshot(accountResponse: AccountReadResponse(account: state.account), rateLimitsResponse: response)+ return try CodexQuotaSnapshot(accountResponse: AccountReadResponse(account: state.account), rateLimitsResponse: response, isRateLimitsStale: isStale)}func stop() {diff --git a/CodexBarTests/CodexStatus/CodexQuotaAndIdentityTests.swift b/CodexBarTests/CodexStatus/CodexQuotaAndIdentityTests.swiftindex 56d9b89..483e9ca 100644--- a/CodexBarTests/CodexStatus/CodexQuotaAndIdentityTests.swift+++ b/CodexBarTests/CodexStatus/CodexQuotaAndIdentityTests.swift@@ -137,8 +137,8 @@ struct CodexQuotaAndIdentityTests {let date = try #require(CodexDateFormat.dayDate(from: "2026-09-15"))let usage = CodexUsageSnapshot(summary: summary, dailyBuckets: [DailyUsageBucket(startDate: "2026-09-15", tokens: 2), DailyUsageBucket(startDate: "2026-09-15", tokens: 3)])#expect(usage.tokenCount(on: date) == 5)- #expect(!CodexUsageSnapshot(summary: summary, dailyBuckets: nil).hasAppServerData)- #expect(CodexUsageSnapshot(summary: summary, dailyBuckets: []).hasAppServerData)+ #expect(!CodexUsageSnapshot(summary: summary, dailyBuckets: nil).hasDailyUsageBuckets)+ #expect(CodexUsageSnapshot(summary: summary, dailyBuckets: []).hasDailyUsageBuckets)}@Test func autoResetUUIDMatchesIndependentUUIDv5Vector() {diff --git a/CodexBarTests/History/AggregationPolicyTests.swift b/CodexBarTests/History/AggregationPolicyTests.swiftnew file mode 100644index 0000000..1d56312--- /dev/null+++ b/CodexBarTests/History/AggregationPolicyTests.swift@@ -0,0 +1,180 @@+import CloudKit+import Foundation+import Testing++struct AggregationPolicyTests {+ @Test func refreshPreservesExistingResultsUntilExplicitRebuild() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let date = HistoryStorage.dateKey(for: now)+ let service = history(in: directory)+ let recorder = ActivityRecorder(directoryURL: directory.url)+ try await recorder.record(event: event(at: now))+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ let url = HistoryStorage.dailyURL(in: directory.url)+ var old = try #require(JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: url)).first)+ old.aggregationVersion = 1+ let oldBoundary = try #require(old.sourceCheckpoint?.byteCount)+ old.sourceCheckpoint?.aggregationRanges = [.init(version: 1, end: oldBoundary)]+ old.turnStartedCount = 50+ try old.jsonLineData().write(to: url)+ let unchanged = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .auto)+ #expect(unchanged.counts == nil)+ #expect(try JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: url)).first?.turnStartedCount == 50)++ try await recorder.record(event: event(at: now.addingTimeInterval(1), turn: "second"))+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .auto)+ let appended = try #require(JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: url)).first)+ #expect(appended.turnStartedCount == 51)+ #expect(appended.metrics.turnCount == 2)+ #expect(appended.sourceCheckpoint?.aggregationRanges.first?.version == 1)+ #expect(appended.sourceCheckpoint?.aggregationRanges.last?.version == AggregationVersion.activity)++ _ = try await service.rebuildData(for: [date], synchronize: false)+ let rebuilt = try #require(JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: url)).first)+ #expect(rebuilt.turnStartedCount == 2)+ #expect(rebuilt.aggregationVersion == AggregationVersion.activity)+ #expect(try rebuilt.sourceCheckpoint?.aggregationRanges == [.init(version: AggregationVersion.activity, end: #require(rebuilt.sourceCheckpoint?.byteCount))])+ }++ @Test func damagedActivityFileRecoversOnlyMissingDates() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let yesterday = try #require(Calendar.current.date(byAdding: .day, value: -1, to: now))+ let service = history(in: directory)+ let recorder = ActivityRecorder(directoryURL: directory.url)+ try await recorder.record(event: event(at: now))+ try await recorder.record(event: event(at: yesterday))+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ let url = HistoryStorage.dailyURL(in: directory.url)+ var preserved = try #require(JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: url)).first { $0.date == HistoryStorage.dateKey(for: yesterday) })+ preserved.turnStartedCount = 40+ try (preserved.jsonLineData() + Data("broken\n".utf8)).write(to: url)+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .auto)+ let results = try JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: url))+ #expect(results.first { $0.date == preserved.date }?.turnStartedCount == 40)+ #expect(results.first { $0.date == HistoryStorage.dateKey(for: now) }?.turnStartedCount == 1)+ }++ @Test func expiredInvalidFileDoesNotBlockHealthyDate() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let expired = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate(today: now).addingTimeInterval(-86400))+ let bad = try directory.write("broken header\n", to: "Events/\(expired).jsonl")+ var state = HistoryMaintenanceState(dirty: [expired])+ state.markPending(expired)+ try HistoryStorage.saveMaintenanceState(state, in: directory.url)+ let recorder = ActivityRecorder(directoryURL: directory.url)+ try await recorder.record(event: event(at: now))+ let service = history(in: directory)+ let result = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ #expect(result.counts?.written == 1)+ #expect(result.snapshot.dailyMetrics.first?.turnCount == 1)+ #expect(try String(contentsOf: bad, encoding: .utf8) == "broken header\n")+ #expect(try HistoryStorage.loadMaintenanceState(in: directory.url).dirty.contains(expired))+ }++ @Test func pendingTodayKeepsYesterdaysMetricsVisible() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let yesterday = try #require(Calendar.current.date(byAdding: .day, value: -1, to: now))+ let recorder = ActivityRecorder(directoryURL: directory.url)+ let service = history(in: directory)+ try await recorder.record(event: event(at: yesterday))+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ try await recorder.record(event: event(at: now))+ let snapshot = await service.loadSnapshot()+ let days = UsageHeatmapDay.grid(usage: nil, history: snapshot, columnCount: 2, today: now).compactMap(\.self)+ #expect(days.first { $0.startDate == HistoryStorage.dateKey(for: yesterday) }?.history.turnCount == 1)+ #expect(days.first { $0.startDate == HistoryStorage.dateKey(for: now) }?.history.turnCount == nil)+ }++ @Test func tokenIdentityAndCloudEncodingPreserveAlgorithmVersions() throws {+ let now = Date()+ let id = TokenTurn.identifier(thread: "thread", turn: "turn")+ var turn = TestFixtures.tokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: .zero)+ turn.aggregationVersion = 1+ let exported = turn.pseudonymized(salt: Data("salt".utf8))+ #expect(exported.aggregationVersion == 1)+ let record = CKRecord(recordType: TokenSync.recordType, recordID: CKRecord.ID(recordName: exported.id))+ TokenSync.apply(exported, to: record)+ #expect(try TokenSync.turn(from: record)?.aggregationVersion == 1)+ let baseline = TokenHistoryBaseline(salt: Data("salt".utf8), turns: [exported.id: exported])+ #expect(baseline.replacement(for: turn) == nil)+ let observation = TokenObservation(turn: turn, rootStartedAt: now, streamID: "stream", sequence: 1, previous: .zero, current: .zero)+ let encoded = try JSONLines.stableEncoder.encode(observation)+ let object = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any])+ let identity = try #require(object["turn"] as? [String: Any])+ #expect(identity["aggregationVersion"] == nil)+ #expect(identity["usage"] == nil)+ }++ @Test func algorithmCompatibilityAcceptsPastAndRejectsFuture() throws {+ try AggregationVersion.require(1, current: 2, name: "test")+ #expect(throws: StorageCompatibilityError.self) { try AggregationVersion.require(3, current: 2, name: "test") }+ #expect(throws: StorageCompatibilityError.self) { try AggregationVersion.require(0, current: 2, name: "test") }+ }++ private func event(at date: Date, turn: String = "first") -> ActivityRecord {+ ActivityRecord(+ timestamp: date, name: ActivityEventKind.turnStarted.rawValue, origin: .main,+ cwd: nil, toolName: nil, model: nil, effort: nil,+ threadID: "thread", turnID: turn, agentID: nil, id: "event-\(date.timeIntervalSince1970)-\(turn)"+ )+ }++ private func history(in directory: TestDirectory) -> HistoryService {+ HistoryService(directoryURL: directory.url, syncService: SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { false }))+ }+}++extension AggregationPolicyTests {+ @Test func recoveredTokenResultsReplaceCoveredCloudBaseline() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let id = TokenTurn.identifier(thread: "thread", turn: "turn")+ let observed = TokenUsage(inputTokens: 10, cachedInputTokens: 0, cacheWriteInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0, totalTokens: 10)+ let observation = TokenObservation(+ turn: TokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now),+ rootStartedAt: now, streamID: "stream", sequence: 1, previous: .zero, current: observed+ )+ let store = TokenHistoryStore(directoryURL: directory.url)+ let recorded = try await store.recordObservations([observation], now: now)+ var previous = try #require(recorded.first)+ previous.aggregationVersion = 1+ previous.usage = TokenUsage(inputTokens: 12, cachedInputTokens: 0, cacheWriteInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0, totalTokens: 12)+ let salt = Data("account".utf8)+ let remote = previous.pseudonymized(salt: salt)+ let baseline = TokenHistoryBaseline(salt: salt, turns: [remote.id: remote])+ try FileManager.default.removeItem(at: directory.url.appendingPathComponent("Aggregates/tokens.json"))+ // 离线恢复后重新启动, 仍须保留与云端旧结果建立替换关系的能力+ _ = try await store.refresh(now: now)+ let reopened = TokenHistoryStore(directoryURL: directory.url)+ let records = try await reopened.refresh(now: now, baseline: baseline)+ let recovered = try #require(records.first)+ #expect(recovered.usage == observed)+ #expect(!recovered.hasConflict)+ #expect(recovered.aggregationVersion == AggregationVersion.tokens)+ #expect(recovered.ancestorIDs.contains(previous.generationID))+ let merged = try remote.merging(recovered.pseudonymized(salt: salt))+ #expect(merged.usage == observed)+ #expect(merged.aggregationVersion == AggregationVersion.tokens)+ #expect(try await reopened.refresh(now: now, baseline: baseline).first?.generationID == recovered.generationID)+ }++ @Test func partialSourcesKeepKnownValuesVisible() {+ let now = Date()+ let date = HistoryStorage.dateKey(for: now)+ var aggregate = ActivityAggregate(date: date)+ aggregate.turnCount = 3+ var snapshot = HistorySnapshot(dailyMetrics: [aggregate.metrics])+ snapshot.isActivityComplete = false+ let day = UsageHeatmapDay.grid(usage: nil, history: snapshot, columnCount: 1, today: now).compactMap(\.self).first { $0.startDate == date }+ #expect(day?.history.turnCount == 3)+ }+}diff --git a/CodexBarTests/History/AppServerEventStorageTests.swift b/CodexBarTests/History/AppServerEventStorageTests.swiftindex 919edc3..12f3e1a 100644--- a/CodexBarTests/History/AppServerEventStorageTests.swift+++ b/CodexBarTests/History/AppServerEventStorageTests.swift@@ -5,11 +5,13 @@ import Testingstruct AppServerEventStorageTests {private let now = TestFixtures.now- private func token(id: String = "root", root: String = "root", at date: Date? = nil, input: Int64 = 100) -> TokenTurn {- TokenTurn(id: id, rootID: root, startedAt: date ?? now, updatedAt: date ?? now, usage: TokenUsage(+ private func token(id: String = "root", root: String = "root", at date: Date? = nil, input: Int64 = 100, sequence: Int64 = 1) -> TokenTurn {+ var value = TestFixtures.tokenTurn(id: id, rootID: root, startedAt: date ?? now, updatedAt: date ?? now, usage: TokenUsage(inputTokens: input, cachedInputTokens: 20, cacheWriteInputTokens: 5,outputTokens: 10, reasoningOutputTokens: 2, totalTokens: input + 10))+ value.checkpoint["test-stream"]?.sequence = sequence+ return value}private func events(in directory: URL, date: Date? = nil) throws -> [AppServerEventRecord] {@@ -20,34 +22,109 @@ struct AppServerEventStorageTests {}@Test func mixedJournalPreservesEveryActivityMetricAndSkipsTokensWithoutCorruption() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let path = "Events/\(HistoryStorage.dateKey(for: now)).jsonl"let activity = ActivityEventKind.allCases.map { TestFixtures.event($0) }- var before = ActivityAccumulator(rebuilding: HistoryStorage.dateKey(for: now), generationID: nil, generationStartedEmpty: true, eventCountAvailability: .all)+ var before = ActivityAccumulator(rebuilding: HistoryStorage.dateKey(for: now), generationID: nil, eventCountAvailability: .all)var after = before- var corrupt = 0+ var data = Data()for event in activity {before.record(event)- let record = AppServerEventRecord(activity: event, recordedAt: now)- corrupt += try HistoryService.decode(record.jsonLineData()) { after.record($0) }- let token = AppServerEventRecord(token: token(), recordedAt: now)- corrupt += try HistoryService.decode(token.jsonLineData()) { after.record($0) }+ try data.append(AppServerEventRecord(activity: event, recordedAt: now).jsonLineData())+ try data.append(AppServerEventRecord(token: token(), recordedAt: now).jsonLineData())}+ let url = try directory.writeJournal(data, to: path)+ var corrupt = 0+ try AppServerEventJournal.read(at: url, onInvalidLine: { corrupt += 1 }, consume: { entry in+ if let event = entry.activity {+ after.record(event)+ }+ })let expected = before.finalized(identifierStorage: .retained)let actual = after.finalized(identifierStorage: .retained)#expect(corrupt == 0)#expect(actual == expected)}+ @Test func boundedReadExcludesLaterRecordsAndResumesAtBoundary() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let first = TestFixtures.event(.turnStarted)+ let second = TestFixtures.event(.turnCompleted)+ let firstData = try AppServerEventRecord(activity: first, recordedAt: now).jsonLineData()+ let secondData = try AppServerEventRecord(activity: second, recordedAt: now).jsonLineData()+ let url = try directory.writeJournal(firstData + secondData, to: "Events/\(HistoryStorage.dateKey(for: now)).jsonl")+ let boundary = HistoryStorage.fileSize(at: url) - UInt64(secondData.count)+ var records: [ActivityRecord] = []+ try AppServerEventJournal.read(at: url, upTo: boundary) { entry in+ if let event = entry.activity {+ records.append(event)+ }+ }+ #expect(records == [first])+ try AppServerEventJournal.read(at: url, from: boundary) { entry in+ if let event = entry.activity {+ records.append(event)+ }+ }+ #expect(records == [first, second])+ }++ @Test func cancelledJournalScanStopsBetweenRecordsAndCanBeReadAgain() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let line = try AppServerEventRecord(activity: TestFixtures.event(), recordedAt: now).jsonLineData()+ let url = try directory.writeJournal(line + line, to: "Events/\(HistoryStorage.dateKey(for: now)).jsonl")+ let scan = Task.detached {+ var count = 0+ do {+ try AppServerEventJournal.read(at: url) { _ in+ count += 1+ withUnsafeCurrentTask { $0?.cancel() }+ }+ return false+ } catch is CancellationError {+ return count == 1+ }+ }+ #expect(try await scan.value)+ var count = 0+ try AppServerEventJournal.read(at: url) { _ in count += 1 }+ #expect(count == 2)+ }++ @Test func oversizedAndPartialLinesDoNotHideFollowingValidRecords() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let event = TestFixtures.event()+ var data = Data(repeating: 120, count: 1024 * 1024 + 100)+ data.append(Data("\n \t\r\n".utf8))+ try data.append(AppServerEventRecord(activity: event, recordedAt: now).jsonLineData())+ data.append(Data("{broken".utf8))+ let url = try directory.writeJournal(data, to: "Events/\(HistoryStorage.dateKey(for: now)).jsonl")+ var corrupt = 0+ var records: [ActivityRecord] = []+ try AppServerEventJournal.read(at: url, upTo: HistoryStorage.fileSize(at: url), onInvalidLine: { corrupt += 1 }, consume: { entry in+ if let event = entry.activity {+ records.append(event)+ }+ })+ #expect(corrupt == 2)+ #expect(records == [event])+ }+@Test func nativeMetadataRoundTripsWithoutChangingBusinessIdentity() throws {- var event = TestFixtures.event(.toolStarted, session: "root", turn: "child-turn", agent: "child", origin: .auxiliary)- event.source = AppServerEventSource(+ var event = TestFixtures.event(.toolStarted, thread: "root", turn: "child-turn", agent: "child", origin: .auxiliary)+ event.context = ActivityContext(method: "item/started", threadID: "child", turnID: "child-turn", parentThreadID: "parent",rootThreadID: "root", rootTurnID: "root-turn", itemID: "item", itemType: "commandExecution", itemStatus: "inProgress")let record = AppServerEventRecord(activity: event, recordedAt: now)let decoded = try AppServerEventRecord.decode(from: record.jsonLineData())#expect(decoded.activity == event)- #expect(decoded.source?.threadID == "child")- #expect(decoded.activity?.sessionID == "root")+ #expect(decoded.context?.threadID == "child")+ #expect(decoded.activity?.threadID == "root")let text = try #require(String(bytes: record.jsonLineData(), encoding: .utf8))#expect(text.contains("toolStarted"))#expect(!text.contains("PreToolUse"))@@ -55,30 +132,30 @@ struct AppServerEventStorageTests {}@Test func activityStorageSeparatesProtocolContextFromBusinessFields() throws {- var event = TestFixtures.event(.approvalRequested, agent: "child", reviewer: .user)- event.source = AppServerEventSource(+ var event = TestFixtures.event(.approvalRequested, agent: "child")+ event.context = ActivityContext(method: "item/commandExecution/requestApproval", threadID: "child", turnID: "child-turn",parentThreadID: "parent", rootThreadID: "root", rootTurnID: "root-turn", itemID: "item",itemType: "commandExecution", itemStatus: "inProgress", agentThreadID: "child",- itemKind: "started", requestID: "request", reviewID: "review", turnStatus: "inProgress",- turnStartedAt: now, turnCompletedAt: now.addingTimeInterval(1), durationMs: 1000+ itemKind: "started", requestID: "request", turnStatus: .running,+ turnStartedAt: now, turnCompletedAt: now.addingTimeInterval(1), duration: 1)let data = try AppServerEventRecord(activity: event, recordedAt: now).jsonLineData()let record = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])- #expect(Set(record.keys) == ["version", "kind", "recordedAt", "source", "activityPayload"])- let context = try #require(record["source"] as? [String: Any])+ #expect(Set(record.keys) == ["version", "kind", "recordedAt", "context", "activityPayload"])+ let context = try #require(record["context"] as? [String: Any])#expect(Set(context.keys) == ["method", "threadID", "turnID", "parentThreadID", "rootThreadID","rootTurnID", "itemID", "itemType", "itemStatus", "agentThreadID",- "itemKind", "requestID", "reviewID", "turnStatus", "turnStartedAt", "turnCompletedAt", "durationMs"+ "itemKind", "requestID", "turnStatus", "turnStartedAt", "turnCompletedAt", "duration"])#expect(context["itemKind"] as? String == "started")- #expect(context["durationMs"] as? Double == 1000)+ #expect(context["duration"] as? Double == 1)#expect(context["turnStartedAt"] as? Double == now.timeIntervalSince1970 * 1000)let payload = try #require(record["activityPayload"] as? [String: Any])#expect(Set(payload.keys) == [- "timestamp", "name", "origin", "cwd", "tool", "model", "effort",- "approvalReviewer", "sessionID", "turnID", "agentID"+ "timestamp", "name", "origin", "cwd", "toolName", "model", "effort",+ "threadID", "turnID", "agentID"])#expect(try AppServerEventRecord.decode(from: data).activity == event)}@@ -94,14 +171,26 @@ struct AppServerEventStorageTests {let record = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])#expect(Set(record.keys) == ["version", "kind", "recordedAt", "token"])let snapshot = try #require(record["token"] as? [String: Any])- #expect(Set(snapshot.keys) == ["id", "rootID", "startedAt", "updatedAt", "rebuiltAt", "usage", "generationID", "ancestorIDs", "checkpoint", "hasConflict"])+ #expect(Set(snapshot.keys) == [+ "aggregationVersion",+ "id",+ "rootID",+ "startedAt",+ "updatedAt",+ "rebuiltAt",+ "usage",+ "generationID",+ "ancestorIDs",+ "checkpoint",+ "hasConflict"+ ])let counts = try #require(snapshot["usage"] as? [String: Int64])#expect(counts == ["inputTokens": 100, "cachedInputTokens": 20, "cacheWriteInputTokens": 5, "outputTokens": 10, "reasoningOutputTokens": 2, "totalTokens": 110])#expect(try AppServerEventRecord.decode(from: data).token == turn)_ = try await store.refresh(now: now)let cacheData = try Data(contentsOf: directory.url.appendingPathComponent("Aggregates/tokens.json"))let cache = try #require(JSONSerialization.jsonObject(with: cacheData) as? [String: Any])- #expect(Set(cache.keys) == ["version", "turns", "files"])+ #expect(Set(cache.keys) == ["version", "turns", "files", "recoveredTurnIDs"])let checkpoints = try #require(cache["files"] as? [String: [String: Any]])let checkpoint = try #require(checkpoints[HistoryStorage.dateKey(for: now)])#expect(Set(checkpoint.keys) == ["size", "identifier", "modificationTime"])@@ -125,7 +214,7 @@ struct AppServerEventStorageTests {try await directory.seedTokenSnapshots([token()], now: now)#expect(try events(in: directory.url).count == 2)#expect(try await first.refresh(now: now) == [token()])- let update = token(at: now.addingTimeInterval(1), input: 200)+ let update = token(at: now.addingTimeInterval(1), input: 200, sequence: 2)try await directory.seedTokenSnapshots([update], now: now)#expect(try await first.refresh(now: now).first?.usage == update.usage)try FileManager.default.removeItem(at: directory.url.appendingPathComponent("Aggregates/tokens.json"))@@ -153,9 +242,9 @@ struct AppServerEventStorageTests {let timestamp = now.addingTimeInterval(0.1234567)let expected = Int64(now.timeIntervalSince1970 * 1000) + 123var event = TestFixtures.event(.turnStarted)- event.source = AppServerEventSource(+ event.context = ActivityContext(method: "turn/started", threadID: "thread", turnStartedAt: timestamp,- turnCompletedAt: timestamp, durationMs: 0.4567+ turnCompletedAt: timestamp, duration: 0.4567)let data = try AppServerEventRecord(activity: event, recordedAt: timestamp).jsonLineData()let text = try #require(String(data: data, encoding: .utf8))@@ -163,7 +252,7 @@ struct AppServerEventStorageTests {#expect(text.contains("\"turnStartedAt\":\(expected)}"))let decoded = try AppServerEventRecord.decode(from: data)#expect(decoded.recordedAt == Date(timeIntervalSince1970: Double(expected) / 1000))- #expect(decoded.source?.durationMs == 0.4567)+ #expect(decoded.context?.duration == 0.4567)let directory = try TestDirectory()defer { try? directory.remove() }@@ -198,9 +287,12 @@ struct AppServerEventStorageTests {#expect(utimensat(AT_FDCWD, url.path, firstTimes, 0) == 0)_ = try await store.refresh(now: now)let before = try #require(HistoryStorage.fileStat(at: url))- let replacement = try AppServerEventRecord(token: token(input: 200), recordedAt: now).jsonLineData()- #expect(UInt64(replacement.count) == before.size)+ let replacement = try AppServerEventRecord(token: token(input: 200, sequence: 2), recordedAt: now).jsonLineData()+ #expect(UInt64(replacement.count) < before.size)+ let headerSize = try UInt64(#require(Data(contentsOf: url).firstIndex(of: 10)) + 1)+ #expect(UInt64(replacement.count) + headerSize == before.size)let handle = try FileHandle(forWritingTo: url)+ try handle.seek(toOffset: headerSize)try handle.write(contentsOf: replacement)try handle.close()let secondTimes = [timespec(tv_sec: seconds, tv_nsec: 1000900), timespec(tv_sec: seconds, tv_nsec: 1000900)]@@ -256,8 +348,8 @@ struct AppServerEventStorageTests {let store = TokenHistoryStore(directoryURL: directory.url)let event = ActivityRecord(timestamp: now, name: ActivityEventKind.toolStarted.rawValue, origin: .main,- cwd: nil, tool: "Bash", model: "model", effort: nil,- approvalReviewer: nil, sessionID: "thread", turnID: "turn", agentID: nil, id: "tool"+ cwd: nil, toolName: "Bash", model: "model", effort: nil,+ threadID: "thread", turnID: "turn", agentID: nil, id: "tool")try await recorder.record(event: event)try await directory.seedTokenSnapshots([token()], now: now)@@ -266,7 +358,7 @@ struct AppServerEventStorageTests {try handle.seekToEnd()try handle.write(contentsOf: Data("{\"partial\":".utf8))try handle.close()- let updated = token(at: now.addingTimeInterval(1), input: 300)+ let updated = token(at: now.addingTimeInterval(1), input: 300, sequence: 2)try await directory.seedTokenSnapshots([updated], now: now)try await recorder.record(event: event)let entries = try events(in: directory.url)diff --git a/CodexBarTests/History/HistoryAggregationTests.swift b/CodexBarTests/History/HistoryAggregationTests.swiftindex 5e7f01f..d0bbd83 100644--- a/CodexBarTests/History/HistoryAggregationTests.swift+++ b/CodexBarTests/History/HistoryAggregationTests.swift@@ -51,18 +51,21 @@ struct HistoryAggregationTests {}@Test func identifierFieldsUseModelPropertyNames() throws {- let aggregate = try TestFixtures.decode(ActivityAggregate.self, #"{"date":"2026-09-15","sessionIDs":["session-a"],"turnIDs":["turn-a"]}"#)- #expect(aggregate.sessionIDs == ["session-a"])+ let aggregate = try TestFixtures.decode(+ ActivityAggregate.self,+ #"{"version":1,"aggregationVersion":1,"date":"2026-09-15","threadIDs":["thread-a"],"turnIDs":["turn-a"]}"#+ )+ #expect(aggregate.threadIDs == ["thread-a"])#expect(aggregate.turnIDs == ["turn-a"])let encoded = try JSONEncoder().encode(aggregate)let fields = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any])- #expect(fields["sessionIDs"] as? [String] == ["session-a"])+ #expect(fields["threadIDs"] as? [String] == ["thread-a"])#expect(fields["turnIDs"] as? [String] == ["turn-a"])- #expect(fields["sessionIds"] == nil)+ #expect(fields["threadIds"] == nil)#expect(fields["turnIds"] == nil)let record = try TestFixtures.decode(ActivitySyncRecord.self, """- {"deviceID":"device-a","recordName":"device-a_2026-09-15_source","daily":{"date":"2026-09-15","generationID":"source"}}+ {"deviceID":"device-a","recordName":"device-a_2026-09-15_source","daily":{"version":1,"aggregationVersion":1,"date":"2026-09-15","generationID":"source"}}""")#expect(record.deviceID == "device-a")let recordData = try JSONEncoder().encode(record)@@ -72,7 +75,7 @@ struct HistoryAggregationTests {}@Test func missingEventCountsRemainUnavailableThroughBothStorageFormats() throws {- let aggregate = try TestFixtures.decode(ActivityAggregate.self, #"{"date":"2026-09-15","turnCompletedCount":0}"#)+ let aggregate = try TestFixtures.decode(ActivityAggregate.self, #"{"version":1,"aggregationVersion":1,"date":"2026-09-15","turnCompletedCount":0}"#)#expect(aggregate.eventCount == nil)#expect(aggregate.turnAbortedCount == nil)#expect(aggregate.turnCompletedCount == 0)@@ -83,37 +86,47 @@ struct HistoryAggregationTests {#expect(synced.turnCompletedCount == 0)}+ @Test func completionEventsCannotStandInForUniqueTurnCounts() throws {+ var aggregate = try TestFixtures.decode(ActivityAggregate.self, #"{"version":1,"aggregationVersion":1,"date":"2026-09-15","turnCompletedCount":9}"#)+ aggregate.normalizeIdentifierStorage(retainsIdentifiers: false)+ #expect(aggregate.turnCount == nil)+ #expect(aggregate.metrics.turnCount == nil)+ let synced = try JSONDecoder().decode(SyncedActivity.self, from: aggregate.syncedAggregate.jsonLineData())+ #expect(synced.turnCount == nil)+ #expect(synced.metrics.turnCount == nil)+ }+@Test func eventPairsAndIdentifiersAreCountedWithoutDoubleCounting() {var accumulator = makeAccumulator()- for name in [ActivityEventKind.sessionStarted, .turnStarted, .toolStarted, .toolCompleted, .compactionStarted, .compactionCompleted, .subagentStarted, .subagentEnded] {+ for name in [ActivityEventKind.turnStarted, .toolStarted, .toolCompleted, .compactionStarted, .compactionCompleted, .subagentStarted, .subagentEnded] {accumulator.record(TestFixtures.event(name))}- accumulator.record(TestFixtures.event(.turnCompleted, session: "terminal-only", turn: "terminal-only"))- accumulator.record(TestFixtures.event(.turnAborted, session: "interrupt-only", turn: "interrupt-only"))+ accumulator.record(TestFixtures.event(.turnCompleted, thread: "terminal-only", turn: "terminal-only"))+ accumulator.record(TestFixtures.event(.turnAborted, thread: "interrupt-only", turn: "interrupt-only"))let retained = accumulator.finalized(identifierStorage: .retained)let compacted = accumulator.finalized(identifierStorage: .compacted)- #expect(retained.eventCount == 10)- #expect(retained.sessionIDs == ["interrupt-only", "session-a", "terminal-only"])+ #expect(retained.eventCount == 9)+ #expect(retained.threadIDs == ["interrupt-only", "terminal-only", "thread-a"])#expect(retained.turnIDs == ["turn-a"])#expect(retained.metrics.toolCallCount == 1)#expect(retained.metrics.contextCompactionCount == 1)#expect(retained.metrics.subagentCount == 1)#expect(retained.metrics.turnAbortedCount == 1)#expect(retained.metrics == compacted.metrics)- #expect(compacted.sessionIDs == nil)+ #expect(compacted.threadIDs == nil)#expect(compacted.turnIDs == nil)#expect(!compacted.supportsIncrementalAggregation)}@Test func incrementalAggregationMatchesFullReplay() {- let firstEvents = [TestFixtures.event(.sessionStarted), TestFixtures.event()]+ let firstEvents = [TestFixtures.event(), TestFixtures.event(.toolCompleted)]let laterEvents = [TestFixtures.event(.toolStarted), TestFixtures.event(turn: "turn-b")]var full = makeAccumulator()(firstEvents + laterEvents).forEach { full.record($0) }var initial = makeAccumulator()firstEvents.forEach { initial.record($0) }var incremental = ActivityAccumulator(- appending: initial.finalized(identifierStorage: .retained), generationID: "source", generationStartedEmpty: true+ appending: initial.finalized(identifierStorage: .retained), generationID: "source")laterEvents.forEach { incremental.record($0) }#expect(incremental.finalized(identifierStorage: .retained) == full.finalized(identifierStorage: .retained))@@ -125,21 +138,22 @@ struct HistoryAggregationTests {#expect(accumulator.finalized(identifierStorage: .compacted).metrics.turnCount == 1)}- @Test func sessionEndAloneDoesNotCreateAnActiveSession() {+ @Test func permissionRequestsCountEachRequest() {var accumulator = makeAccumulator()- accumulator.record(TestFixtures.event(.sessionEnded, turn: nil))- let aggregate = accumulator.finalized(identifierStorage: .compacted)- #expect(aggregate.sessionEndedCount == 1)- #expect(aggregate.metrics.sessionCount == 0)- #expect(aggregate.metrics.turnCount == 0)+ for turn in ["a", "b", "c", "d"] {+ accumulator.record(TestFixtures.event(.approvalRequested, turn: turn))+ }+ let aggregate = accumulator.finalized(identifierStorage: .retained)+ #expect(aggregate.approvalRequestedCount == 4)+ #expect(aggregate.eventCount == 4)}- @Test func unavailableInterruptCountPropagatesAcrossDeviceMetrics() {+ @Test func missingHistoricalMetricContributesZeroToDisplay() {var known = TestFixtures.aggregate()known.turnAbortedCount = 3var unknown = TestFixtures.aggregate()unknown.turnAbortedCount = nil- #expect(known.metrics.adding(unknown.metrics).turnAbortedCount == nil)+ #expect(known.metrics.adding(unknown.metrics).turnAbortedCount == 3)#expect(known.metrics.adding(known.metrics).turnAbortedCount == 6)}@@ -153,12 +167,12 @@ struct HistoryAggregationTests {@Test func compactingLegacyIdentifiersPreservesUniqueCounts() throws {var aggregate = try TestFixtures.decode(ActivityAggregate.self, """- {"date":"2026-09-15","sessionCount":0,"sessionIDs":["a","a","b"],"turnIDs":["x","x"],"turnCompletedCount":9}+ {"version":1,"aggregationVersion":1,"date":"2026-09-15","threadCount":0,"threadIDs":["a","a","b"],"turnIDs":["x","x"],"turnCompletedCount":9}""")aggregate.normalizeIdentifierStorage(retainsIdentifiers: false)- #expect(aggregate.sessionCount == 2)+ #expect(aggregate.threadCount == 2)#expect(aggregate.turnCount == 1)- #expect(aggregate.sessionIDs == nil)+ #expect(aggregate.threadIDs == nil)}@Test func syncExportContainsCountsWithoutRawTaskIdentifiers() throws {@@ -166,21 +180,25 @@ struct HistoryAggregationTests {accumulator.record(TestFixtures.event())let data = try accumulator.finalized(identifierStorage: .retained).syncedAggregate.jsonLineData()let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])- #expect(object["sessionIDs"] == nil)+ #expect(object["threadIDs"] == nil)#expect(object["turnIDs"] == nil)- #expect(object["sessionCount"] as? Int == 1)+ #expect(object["threadCount"] as? Int == 1)let text = try #require(String(data: data, encoding: .utf8))- #expect(!text.contains("session-a"))+ #expect(!text.contains("thread-a"))}@Test func cloudDailyCountsRoundTripWithEventNames() throws {let counts = [- "sessionStartedCount": 1, "sessionEndedCount": 2, "turnStartedCount": 3,+ "threadCount": 2, "turnCount": 3,+ "turnStartedCount": 3,"turnCompletedCount": 4, "turnAbortedCount": 5, "toolStartedCount": 6,"toolCompletedCount": 7, "approvalRequestedCount": 8, "compactionStartedCount": 9,"compactionCompletedCount": 10, "subagentStartedCount": 11, "subagentEndedCount": 12]var fields: [String: Any] = counts+ fields["version"] = 1+ fields["aggregationVersion"] = 1+ fields["sourceCheckpoint"] = ["byteCount": 1, "digest": String(repeating: "a", count: 64)]fields["date"] = "2026-09-15"fields["generationID"] = "source"let aggregate = try JSONDecoder().decode(@@ -189,7 +207,7 @@ struct HistoryAggregationTests {let record = CKRecord(recordType: "Activity", recordID: CKRecord.ID(recordName: "device-a_2026-09-15_source"))ActivityRecordCodec.apply(aggregate, deviceID: "device-a", to: record)#expect(Set(record.allKeys()) == Set(counts.keys).union([- "version", "deviceID", "date", "generationID", "projectCounts", "modelCounts", "updatedAt"+ "version", "aggregationVersion", "sourceCheckpoint", "deviceID", "date", "generationID", "projectCounts", "modelCounts", "updatedAt"]))for (name, count) in counts {#expect((record[name] as? NSNumber)?.intValue == count)@@ -207,6 +225,11 @@ struct HistoryAggregationTests {@Test(arguments: [nil, "", " "]) func cloudActivityRejectsMissingGeneration(generation: String?) {let record = CKRecord(recordType: "Activity", recordID: CKRecord.ID(recordName: "device_2026-09-15_source"))+ record["version"] = 1 as CKRecordValue+ record["aggregationVersion"] = 1 as CKRecordValue+ record["sourceCheckpoint"] = try? JSONEncoder().encode(ActivitySourceCheckpoint(byteCount: 1, digest: String(repeating: "a", count: 64))) as CKRecordValue+ record["projectCounts"] = Data("{}".utf8) as CKRecordValue+ record["modelCounts"] = Data("{}".utf8) as CKRecordValuerecord["deviceID"] = "device" as CKRecordValuerecord["date"] = "2026-09-15" as CKRecordValuerecord["generationID"] = generation as CKRecordValue?@@ -214,17 +237,26 @@ struct HistoryAggregationTests {}@Test func cloudAndCachedActivityRejectMismatchedIdentity() throws {- let daily = SyncedActivity(date: "2026-09-15", generationID: "source", projectCounts: [:], modelCounts: [:])+ let daily = SyncedActivity(+ sourceCheckpoint: ActivitySourceCheckpoint(byteCount: 1, digest: String(repeating: "a", count: 64)),+ date: "2026-09-15",+ generationID: "source",+ projectCounts: [:],+ modelCounts: [:]+ )let record = CKRecord(recordType: "Activity", recordID: CKRecord.ID(recordName: "device_2026-09-15"))ActivityRecordCodec.apply(daily, deviceID: "device", to: record)#expect(throws: ActivitySyncError.self) { try ActivityRecordCodec.remoteDailyRecord(from: record) }#expect(throws: DecodingError.self) {- try TestFixtures.decode(ActivitySyncRecord.self, #"{"deviceID":"device","recordName":"device_2026-09-15","daily":{"date":"2026-09-15","generationID":"source"}}"#)+ try TestFixtures.decode(+ ActivitySyncRecord.self,+ #"{"deviceID":"device","recordName":"device_2026-09-15","daily":{"version":1,"aggregationVersion":1,"date":"2026-09-15","generationID":"source"}}"#+ )}}private func makeAccumulator() -> ActivityAccumulator {- ActivityAccumulator(rebuilding: "2026-09-15", generationID: "source", generationStartedEmpty: true, eventCountAvailability: .all)+ ActivityAccumulator(rebuilding: "2026-09-15", generationID: "source", eventCountAvailability: .all)}}@@ -237,13 +269,13 @@ struct HistoryMergeTests {}@Test func freshIndependentGenerationAddsToPreviousContribution() throws {- let local = TestFixtures.aggregate(generation: "new", fresh: true, turns: 2)+ let local = TestFixtures.aggregate(generation: "new", turns: 2)#expect(try snapshot(local, [record(TestFixtures.aggregate(turns: 3))]).dailyMetrics.first?.turnCount == 5)}- @Test func unverifiedLocalGenerationDoesNotDoubleCountRemoteHistory() throws {- let local = TestFixtures.aggregate(generation: "unknown", fresh: false, turns: 2)- #expect(try snapshot(local, [record(TestFixtures.aggregate(turns: 3))]).dailyMetrics.first?.turnCount == 3)+ @Test func independentSourceRemainsIndependentWithoutFreshnessFlag() throws {+ let local = TestFixtures.aggregate(generation: "unknown", turns: 2)+ #expect(try snapshot(local, [record(TestFixtures.aggregate(turns: 3))]).dailyMetrics.first?.turnCount == 5)}@Test func sameGenerationDeduplicatesAndOtherDevicesStillAdd() throws {diff --git a/CodexBarTests/History/HistoryMaintenanceTests.swift b/CodexBarTests/History/HistoryMaintenanceTests.swiftindex d9d49ec..0c5fee1 100644--- a/CodexBarTests/History/HistoryMaintenanceTests.swift+++ b/CodexBarTests/History/HistoryMaintenanceTests.swift@@ -1,8 +1,81 @@import Darwinimport Foundation+import Synchronizationimport Testingstruct HistoryMaintenanceTests {+ @Test func normalizationWaitsForWriterAndUsesLatestAggregate() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let sync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { false })+ let service = HistoryService(directoryURL: directory.url, syncService: sync)+ let date = HistoryStorage.dateKey(for: HistoryStorage.identifierRetentionCutoffDate().addingTimeInterval(-86400))+ var aggregate = ActivityAggregate(date: date)+ aggregate.eventCount = 1+ aggregate.threadIDs = ["session"]+ aggregate.turnIDs = ["turn"]+ let dailyURL = HistoryStorage.dailyURL(in: directory.url)+ try FileManager.default.createDirectory(at: dailyURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ try aggregate.jsonLineData().write(to: dailyURL)+ try FileManager.default.createDirectory(at: HistoryStorage.lockURL(in: directory.url).deletingLastPathComponent(), withIntermediateDirectories: true)+ let descriptor = open(HistoryStorage.lockURL(in: directory.url).path, O_CREAT | O_RDWR, 0o600)+ try #require(descriptor >= 0)+ defer { flock(descriptor, LOCK_UN)+ close(descriptor)+ }+ try #require(flock(descriptor, LOCK_EX) == 0)+ let started = Mutex(false)+ let finished = Mutex(false)+ let normalization = Task.detached {+ started.withLock { $0 = true }+ try await service.normalizeDailyAggregatesIfNeeded()+ finished.withLock { $0 = true }+ }+ for _ in 0 ..< 100 where !started.withLock({ $0 }) {+ try await Task.sleep(for: .milliseconds(5))+ }+ try #require(started.withLock { $0 })+ try await Task.sleep(for: .milliseconds(100))+ #expect(!finished.withLock { $0 })+ aggregate.eventCount = 7+ try aggregate.jsonLineData().write(to: dailyURL, options: .atomic)+ #expect(flock(descriptor, LOCK_UN) == 0)+ try await normalization.value+ let normalized = try #require(JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: dailyURL)).first)+ #expect(normalized.eventCount == 7)+ #expect(normalized.threadIDs == nil)+ #expect(normalized.turnIDs == nil)+ }++ @Test func explicitRebuildRecalculatesFromEventsWithoutChangingFormatOrSource() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let date = HistoryStorage.dateKey(for: now)+ let records = ["request-a", "request-b"].map {+ AppServerEventRecord(activity: TestFixtures.event(.approvalRequested, at: now, turn: $0), recordedAt: now)+ }+ let recordsData = try records.reduce(into: Data()) { result, record in try result.append(record.jsonLineData()) }+ let journalURL = try directory.writeJournal(recordsData, to: "Events/\(date).jsonl")+ let data = try Data(contentsOf: journalURL)+ let sync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { false })+ let service = HistoryService(directoryURL: directory.url, syncService: sync)+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ var aggregate = try #require(JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: HistoryStorage.dailyURL(in: directory.url))).first)+ aggregate.approvalRequestedCount = 1+ try aggregate.jsonLineData().write(to: HistoryStorage.dailyURL(in: directory.url))+ var state = try HistoryStorage.loadMaintenanceState(in: directory.url)+ state.markDirty(date)+ try HistoryStorage.saveMaintenanceState(state, in: directory.url)+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ let rebuilt = try #require(JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: HistoryStorage.dailyURL(in: directory.url))).first)+ #expect(rebuilt.approvalRequestedCount == 2)+ #expect(rebuilt.eventCount == 2)+ #expect(rebuilt.generationID == aggregate.generationID)+ #expect(try HistoryStorage.loadMaintenanceState(in: directory.url).version == HistoryMaintenanceState.currentVersion)+ #expect(try Data(contentsOf: directory.url.appendingPathComponent("Events/\(date).jsonl")) == data)+ }+@Test func historyMaintenanceUsesOnlyInjectedRoot() async throws {let first = try TestDirectory()let second = try TestDirectory()@@ -12,8 +85,7 @@ struct HistoryMaintenanceTests {let recorder = ActivityRecorder(directoryURL: first.url)let event = ActivityRecord(timestamp: Date(), name: ActivityEventKind.turnStarted.rawValue, origin: .main,- cwd: nil, tool: nil, model: nil, effort: nil, approvalReviewer: .user,- sessionID: "session", turnID: "turn", agentID: nil, id: "isolated"+ cwd: nil, toolName: nil, model: nil, effort: nil, threadID: "session", turnID: "turn", agentID: nil, id: "isolated")try await recorder.record(event: event)let sync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: first.url), isEnabled: { false })@@ -22,8 +94,8 @@ struct HistoryMaintenanceTests {#expect(result.counts?.events == 1)#expect(FileManager.default.fileExists(atPath: HistoryStorage.dailyURL(in: first.url).path))#expect(!FileManager.default.fileExists(atPath: HistoryStorage.dailyURL(in: second.url).path))- #expect(!HistoryStorage.loadMaintenanceState(in: first.url).days.isEmpty)- #expect(HistoryStorage.loadMaintenanceState(in: second.url).days.isEmpty)+ #expect(try !HistoryStorage.loadMaintenanceState(in: first.url).days.isEmpty)+ #expect(try HistoryStorage.loadMaintenanceState(in: second.url).days.isEmpty)}}@@ -33,22 +105,25 @@ extension HistoryMaintenanceTests {defer { try? directory.remove() }let now = Date()let date = HistoryStorage.dateKey(for: now)- let original = try AppServerEventRecord(activity: TestFixtures.event(.turnStarted, at: now), recordedAt: now).jsonLineData()+ var originalEvent = TestFixtures.event(.turnStarted, at: now)+ originalEvent.context = nil+ let original = try AppServerEventRecord(activity: originalEvent, recordedAt: now).jsonLineData()let replacement = try AppServerEventRecord(activity: TestFixtures.event(.toolStarted, at: now), recordedAt: now).jsonLineData()#expect(original.count == replacement.count)- let url = try directory.write(original, to: "Events/\(date).jsonl")+ let url = try directory.writeJournal(original, to: "Events/\(date).jsonl")let seconds = Int(now.timeIntervalSince1970)let firstTimes = [timespec(tv_sec: seconds, tv_nsec: 1000100), timespec(tv_sec: seconds, tv_nsec: 1000100)]#expect(utimensat(AT_FDCWD, url.path, firstTimes, 0) == 0)let sync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { false })let service = HistoryService(directoryURL: directory.url, syncService: sync)_ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)- let stateBefore = HistoryStorage.loadMaintenanceState(in: directory.url)+ let stateBefore = try HistoryStorage.loadMaintenanceState(in: directory.url)let maintenanceBefore = try #require(HistoryStorage.fileStat(at: HistoryStorage.maintenanceURL(in: directory.url)))_ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)#expect(HistoryStorage.fileStat(at: HistoryStorage.maintenanceURL(in: directory.url)) == maintenanceBefore)let before = try #require(HistoryStorage.fileStat(at: url))let handle = try FileHandle(forWritingTo: url)+ try handle.seek(toOffset: UInt64(#require(Data(contentsOf: url).firstIndex(of: 10)) + 1))try handle.write(contentsOf: replacement)try handle.close()let secondTimes = [timespec(tv_sec: seconds, tv_nsec: 1000900), timespec(tv_sec: seconds, tv_nsec: 1000900)]@@ -60,7 +135,7 @@ extension HistoryMaintenanceTests {let rebuilt = try #require(JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: HistoryStorage.dailyURL(in: directory.url))).first)#expect(rebuilt.toolStartedCount == 1)#expect(rebuilt.turnStartedCount == 0)- #expect(rebuilt.generationID != stateBefore.days[date]?.generationID)+ #expect(rebuilt.generationID == stateBefore.days[date]?.generationID)let restarted = HistoryService(directoryURL: directory.url, syncService: sync)let maintenanceAfter = try #require(HistoryStorage.fileStat(at: HistoryStorage.maintenanceURL(in: directory.url)))_ = await restarted.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)@@ -110,37 +185,49 @@ extension HistoryMaintenanceTests {}}- @Test func legacyMaintenanceStateRequiresRebuildAndNormalizesDateQueues() throws {+ @Test func maintenanceNormalizesQueuesAndRejectsUnknownVersion() throws {let state = try TestFixtures.decode(HistoryMaintenanceState.self, """- {"pending":["2026-09-15","invalid","2026-09-14","2026-09-15"],"dirty":["2026-02-30","2026-09-14"]}+ {"version":1,"pending":["2026-09-15","invalid","2026-09-14","2026-09-15"],"dirty":["2026-02-30","2026-09-14"]}""")- #expect(state.version == 0)#expect(state.pending == ["2026-09-14", "2026-09-15"])#expect(state.dirty == ["2026-09-14"])+ #expect(throws: StorageCompatibilityError.self) {+ try TestFixtures.decode(HistoryMaintenanceState.self, "{\"version\":2}")+ }}- @Test func fileReplacementResetsOffsetsHashesAndMarksDayDirty() throws {- let date = "2026-09-15"- var state = HistoryMaintenanceState(days: [date: HistoryDayMaintenanceState(- offset: 50, size: 60, corrupt: 2, generationID: "old", generationStartedEmpty: false,- fileIdentifier: 1, boundaryHash: "old-hash"- )])- state.startNewGeneration(for: date, startedEmpty: true, fileIdentifier: 2)- let day = try #require(state.days[date])- #expect(day.offset == 0)- #expect(day.corrupt == 0)- #expect(day.generationID != "old")- #expect(day.generationStartedEmpty)- #expect(day.fileIdentifier == 2)- #expect(day.boundaryHash == nil)- #expect(state.dirty == [date])+ @Test func sourceIdentitySurvivesMissingMaintenanceState() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let recorder = ActivityRecorder(directoryURL: directory.url)+ let event = ActivityRecord(+ timestamp: Date(),+ name: ActivityEventKind.turnStarted.rawValue,+ origin: .main,+ cwd: nil,+ toolName: nil,+ model: nil,+ effort: nil,+ threadID: "thread",+ turnID: "turn",+ agentID: nil,+ id: "source-recovery"+ )+ try await recorder.record(event: event)+ let service = HistoryService(directoryURL: directory.url, syncService: SyncService(isEnabled: { false }))+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ let original = try HistoryStorage.loadMaintenanceState(in: directory.url)+ try FileManager.default.removeItem(at: HistoryStorage.maintenanceURL(in: directory.url))+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ let recovered = try HistoryStorage.loadMaintenanceState(in: directory.url)+ #expect(recovered.days.mapValues(\.generationID) == original.days.mapValues(\.generationID))}@Test func maintenanceStoragePreservesReadBoundaryAndFileIdentity() throws {let date = "2026-09-15"let state = HistoryMaintenanceState(pending: [date], dirty: [date], days: [date: HistoryDayMaintenanceState(- offset: 50, size: 60, corrupt: 2, generationID: "source", generationStartedEmpty: true,- fileIdentifier: 7, boundaryHash: "digest"+ offset: 50, size: 60, corrupt: 2, generationID: "source",+ fileIdentifier: 7)])let data = try JSONLines.stableEncoder.encode(state)let root = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])@@ -148,24 +235,22 @@ extension HistoryMaintenanceTests {let days = try #require(root["days"] as? [String: [String: Any]])let day = try #require(days[date])#expect(Set(day.keys) == [- "requiresCloudReplacement", "offset", "size", "corrupt", "generationID", "generationStartedEmpty",- "fileIdentifier", "boundaryHash"+ "offset", "size", "corrupt", "generationID",+ "fileIdentifier"])#expect(try JSONDecoder().decode(HistoryMaintenanceState.self, from: data) == state)}- @Test func repeatedPendingAndSourceUpdatesAreIdempotent() throws {+ @Test func repeatedPendingAndDirtyUpdatesAreIdempotent() {var state = HistoryMaintenanceState()- let firstPending = state.markPending("2026-09-15")- let secondPending = state.markPending("2026-09-15")- #expect(firstPending)- #expect(!secondPending)- let firstSource = state.ensureGenerationID(for: "2026-09-15", fileIdentifier: 1)- let generation = try #require(state.days["2026-09-15"]?.generationID)- let secondSource = state.ensureGenerationID(for: "2026-09-15", fileIdentifier: 1)- #expect(firstSource)- #expect(!secondSource)- #expect(state.days["2026-09-15"]?.generationID == generation)- #expect(state.days["2026-09-15"]?.generationStartedEmpty == false)+ let result0 = state.markPending("2026-09-15")+ #expect(result0)+ let result1 = !state.markPending("2026-09-15")+ #expect(result1)+ let result2 = state.markDirty("2026-09-15")+ #expect(result2)+ let result3 = !state.markDirty("2026-09-15")+ #expect(result3)+ #expect(state.days["2026-09-15"]?.generationID == nil)}}diff --git a/CodexBarTests/History/JSONLinesAndActivityTests.swift b/CodexBarTests/History/JSONLinesAndActivityTests.swiftindex 2f7f5b0..db0f553 100644--- a/CodexBarTests/History/JSONLinesAndActivityTests.swift+++ b/CodexBarTests/History/JSONLinesAndActivityTests.swift@@ -31,12 +31,12 @@ struct JSONLinesAndActivityTests {@Test func eventDecodingToleratesMissingMetadataAndUnknownOrigins() throws {let event = try TestFixtures.decode(ActivityRecord.self, """- {"timestamp":0,"name":"turnStarted","origin":"future","sessionID":" ","tool":123}+ {"timestamp":0,"name":"turnStarted","origin":"future","threadID":" ","toolName":123}""")#expect(event.eventKind == .turnStarted)#expect(event.origin == .unknown)- #expect(event.sessionID == nil)- #expect(event.tool == nil)+ #expect(event.threadID == nil)+ #expect(event.toolName == nil)}@Test(arguments: [#"{"name":"turnCompleted"}"#, #"{"timestamp":"invalid","name":"turnCompleted"}"#, #"{"timestamp":0,"name":" "}"#])@@ -49,19 +49,18 @@ struct JSONLinesAndActivityTests {@Test func eventSerializationRoundTripsEscapedMetadata() throws {let event = ActivityRecord(timestamp: TestFixtures.now, name: "toolStarted", origin: .main,- cwd: "/projects/a\"b", tool: "line\nbreak", model: nil,- effort: nil, approvalReviewer: nil,- sessionID: "session", turnID: "turn", agentID: "agent"+ cwd: "/projects/a\"b", toolName: "line\nbreak", model: nil,+ effort: nil, threadID: "session", turnID: "turn", agentID: "agent")let data = try JSONLines.stableEncoder.encode(event)#expect(!data.contains(JSONLines.newlineByte))#expect(try JSONLines.decoder.decode(ActivityRecord.self, from: data) == event)}- @Test func guardianModelOnlyFillsUnknownOrigin() throws {+ @Test func modelNameDoesNotClassifyTaskOrigin() throws {let unknown = try TestFixtures.decode(ActivityRecord.self, #"{"timestamp":0,"name":"turnCompleted","model":"codex-auto-review"}"#)let explicit = try TestFixtures.decode(ActivityRecord.self, #"{"timestamp":0,"name":"turnCompleted","model":"codex-auto-review","origin":"main"}"#)- #expect(unknown.origin == .autoReview)+ #expect(unknown.origin == .unknown)#expect(explicit.origin == .main)}}diff --git a/CodexBarTests/History/StorageEvolutionTests.swift b/CodexBarTests/History/StorageEvolutionTests.swiftnew file mode 100644index 0000000..7e6291d--- /dev/null+++ b/CodexBarTests/History/StorageEvolutionTests.swift@@ -0,0 +1,76 @@+import Foundation+import Testing++struct StorageEvolutionTests {+ @Test(arguments: ["version", "aggregationVersion"])+ func unsupportedAggregateIsNotRewrittenOrShownAsZero(_ field: String) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ var aggregate = TestFixtures.aggregate()+ aggregate = ActivityAggregate(date: HistoryStorage.dateKey(for: Date()), generationID: aggregate.generationID)+ var object = try #require(JSONSerialization.jsonObject(with: aggregate.jsonLineData()) as? [String: Any])+ object[field] = 999+ let original = try JSONSerialization.data(withJSONObject: object)+ let url = try directory.write(original, to: "Aggregates/activity.jsonl")+ let history = HistoryService(directoryURL: directory.url, syncService: SyncService(isEnabled: { false }))+ let result = await history.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ #expect(!result.snapshot.isActivityComplete)+ #expect(try Data(contentsOf: url) == original)+ let days = UsageHeatmapDay.grid(usage: nil, history: result.snapshot, columnCount: 1, today: Date()).compactMap(\.self)+ #expect(days.allSatisfy { $0.history.threadCount == nil && $0.history.toolCallCount == nil })+ }++ @Test func unsupportedJournalCannotBeAppendedOrPruned() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let old = HistoryStorage.retentionCutoffDate(today: now).addingTimeInterval(-86400)+ let date = HistoryStorage.dateKey(for: old)+ let data = Data("{\"version\":999,\"date\":\"\(date)\",\"generationID\":\"source\"}\n".utf8)+ let url = try directory.write(data, to: "Events/\(date).jsonl")+ var journal = AppServerEventJournal()+ #expect(throws: StorageCompatibilityError.self) {+ try journal.append(AppServerEventRecord(activity: TestFixtures.event(at: old)), in: directory.url)+ }+ let history = HistoryService(directoryURL: directory.url, syncService: SyncService(isEnabled: { false }))+ _ = await history.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual, now: now)+ #expect(try Data(contentsOf: url) == data)+ }++ @Test func checkpointDetectsMiddleRewriteOutsideOldTailWindow() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try directory.write(Data(repeating: 97, count: 16384), to: "prefix")+ let checkpoint = try ActivitySourceCheckpoint.read(at: url, byteCount: 16384)+ let handle = try FileHandle(forWritingTo: url)+ try handle.seek(toOffset: 10)+ try handle.write(contentsOf: Data([98]))+ try handle.close()+ #expect(try ActivitySourceCheckpoint.read(at: url, byteCount: 16384) != checkpoint)+ #expect(throws: StorageCompatibilityError.incompleteSource) {+ try ActivitySourceCheckpoint.read(at: url, byteCount: 16385)+ }+ }++ @Test func tokenAlgorithmMismatchCannotBeMerged() throws {+ let first = TestFixtures.tokenTurn(id: "turn", rootID: "turn", startedAt: Date(), updatedAt: Date(), usage: .zero)+ var unsupported = first+ unsupported.aggregationVersion = 999+ #expect(throws: StorageCompatibilityError.self) { try first.merging(unsupported) }+ #expect(throws: StorageCompatibilityError.self) {+ try JSONLines.decoder.decode(TokenTurn.self, from: JSONLines.stableEncoder.encode(unsupported))+ }+ }++ @Test func protocolBoundaryNormalizesStatusAndTimeUnits() throws {+ let input = try TestFixtures.decode(ActivityInput.self, """+ {"method":"turn/completed","params":{"threadId":"thread","turn":{"id":"turn","status":"completed","startedAt":1000,"completedAt":1002,"durationMs":1500}}}+ """)+ #expect(input.kind == .turnFinished)+ #expect(input.params.turn?.status == .completed)+ #expect(input.params.turn?.startedAt == Date(timeIntervalSince1970: 1000))+ #expect(input.params.turn?.duration == 1.5)+ let unknown = try TestFixtures.decode(ActivityInput.self, "{\"method\":\"future/event\",\"params\":{}}")+ #expect(unknown.kind == .ignored)+ }+}diff --git a/CodexBarTests/History/StorageRetentionTests.swift b/CodexBarTests/History/StorageRetentionTests.swiftnew file mode 100644index 0000000..8313942--- /dev/null+++ b/CodexBarTests/History/StorageRetentionTests.swift@@ -0,0 +1,257 @@+import Foundation+import SQLite3+import Testing++struct StorageRetentionTests {+ @Test func dailyCleanupSkipsRepeatedRefreshButStillAggregatesNewEvents() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let tomorrow = try #require(Calendar.current.date(byAdding: .day, value: 1, to: now))+ let expiredKey = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate(today: now).addingTimeInterval(-86400))+ let sync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { false })+ let service = HistoryService(directoryURL: directory.url, syncService: sync)+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual, now: now)+ let expiredURL = try directory.writeJournal(Data(), to: "Events/\(expiredKey).jsonl")+ let recorder = ActivityRecorder(directoryURL: directory.url)+ try await recorder.record(event: ActivityRecord(+ timestamp: now, name: ActivityEventKind.turnStarted.rawValue, origin: .main,+ cwd: nil, toolName: nil, model: nil, effort: nil, threadID: "session", turnID: "turn", agentID: nil, id: "new-event"+ ))+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual, now: now)+ #expect(FileManager.default.fileExists(atPath: expiredURL.path))+ let data = try Data(contentsOf: HistoryStorage.dailyURL(in: directory.url))+ #expect(JSONLines.decode(ActivityAggregate.self, from: data).first { $0.date == HistoryStorage.dateKey(for: now) }?.turnStartedCount == 1)+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual, now: tomorrow)+ #expect(!FileManager.default.fileExists(atPath: expiredURL.path))+ _ = try directory.writeJournal(Data(), to: "Events/\(expiredKey).jsonl")+ let restarted = HistoryService(directoryURL: directory.url, syncService: sync)+ _ = await restarted.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual, now: tomorrow)+ #expect(!FileManager.default.fileExists(atPath: expiredURL.path))+ }++ @Test func failedEventCleanupRetriesDuringSameDay() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let date = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate(today: now).addingTimeInterval(-86400))+ let expiredURL = try directory.writeJournal(Data(), to: "Events/\(date).jsonl")+ let lockURL = HistoryStorage.lockURL(in: directory.url)+ try FileManager.default.createDirectory(at: lockURL, withIntermediateDirectories: true)+ let sync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { false })+ let service = HistoryService(directoryURL: directory.url, syncService: sync)+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual, now: now)+ #expect(FileManager.default.fileExists(atPath: expiredURL.path))+ try FileManager.default.removeItem(at: lockURL)+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual, now: now)+ #expect(!FileManager.default.fileExists(atPath: expiredURL.path))+ }++ @Test func cacheCleanupRunsDailyAndRetriesOnlyFailedStore() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let tomorrow = try #require(Calendar.current.date(byAdding: .day, value: 1, to: now))+ let expired = HistoryStorage.retentionCutoffDate(today: now).addingTimeInterval(-86400)+ let key = HistoryStorage.dateKey(for: expired)+ let activity = try JSONLines.stableEncoder.encode(ActivitySyncCache(state: SyncState(hashByDate: [key: "old"])))+ let token = TokenTurn(id: "old", rootID: "old", updatedAt: expired)+ let tokens = try JSONLines.stableEncoder.encode(SeededTokenCache(turns: [token.id: token]))+ let activityURL = try directory.write(activity, to: "Activity/cache.json")+ let tokenURL = try directory.write(Data(#"{"version":999}"#.utf8), to: "Tokens/cache.json")+ let sync = SyncService(directoryURL: directory.url, isEnabled: { false })+ await sync.pruneLocalCaches(now: now)+ #expect(try JSONLines.decoder.decode(ActivitySyncCache.self, from: Data(contentsOf: activityURL)).state.hashByDate.isEmpty)+ try activity.write(to: activityURL)+ try tokens.write(to: tokenURL)+ await sync.pruneLocalCaches(now: now)+ #expect(try Data(contentsOf: activityURL) == activity)+ #expect(try JSONLines.decoder.decode(SeededTokenCache.self, from: Data(contentsOf: tokenURL)).turns.isEmpty)+ try tokens.write(to: tokenURL)+ await sync.pruneLocalCaches(now: now)+ #expect(try Data(contentsOf: tokenURL) == tokens)+ _ = try ActivitySyncStore(directoryURL: directory.url).load()+ #expect(try Data(contentsOf: activityURL) == activity)+ await sync.pruneLocalCaches(now: tomorrow)+ #expect(try JSONLines.decoder.decode(ActivitySyncCache.self, from: Data(contentsOf: activityURL)).state.hashByDate.isEmpty)+ #expect(try JSONLines.decoder.decode(SeededTokenCache.self, from: Data(contentsOf: tokenURL)).turns.isEmpty)+ }++ @Test func eventFilesAndOrphanedStateExpireAtCalendarBoundary() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let cutoff = HistoryStorage.retentionCutoffDate()+ let dates = [cutoff.addingTimeInterval(-86400), cutoff, Date()]+ let keys = dates.map { HistoryStorage.dateKey(for: $0) }+ for (date, key) in zip(dates, keys) {+ let record = AppServerEventRecord(activity: TestFixtures.event(.turnStarted, at: date), recordedAt: date)+ _ = try directory.writeJournal(record.jsonLineData(), to: "Events/\(key).jsonl")+ }+ let orphan = HistoryStorage.dateKey(for: cutoff.addingTimeInterval(-2 * 86400))+ var state = HistoryMaintenanceState()+ state.markPending(orphan)+ state.markDirty(orphan)+ try HistoryStorage.saveMaintenanceState(state, in: directory.url)+ let sync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { false })+ let service = HistoryService(directoryURL: directory.url, syncService: sync)+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ #expect(HistoryStorage.eventLogDateKeys(in: HistoryStorage.eventsDirectoryURL(in: directory.url)) == Array(keys.dropFirst()))+ let retained = try HistoryStorage.loadMaintenanceState(in: directory.url)+ #expect(retained.days[orphan] == nil)+ #expect(!retained.pending.contains(orphan))+ #expect(!retained.dirty.contains(orphan))+ let aggregates = try Data(contentsOf: HistoryStorage.dailyURL(in: directory.url))+ #expect(JSONLines.decode(ActivityAggregate.self, from: aggregates).allSatisfy { $0.date >= keys[1] })+ }++ @Test(arguments: [false, true])+ func logsExpireOnReadAndReopenWithoutCapacityPressure(reopen: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let clock = RetentionClock()+ let storage = AppServerLogStore(directoryURL: directory.url, now: { clock.read() })+ let expired = storage.beginRequest(method: "expired", payload: "{}")+ let boundary = storage.beginRequest(method: "boundary", payload: "{}")+ let original = try await storage.page()+ let tomorrow = try #require(Calendar.current.date(byAdding: .day, value: 1, to: clock.read()))+ let cutoff = HistoryStorage.retentionCutoffDate(today: tomorrow)+ var database: OpaquePointer?+ #expect(sqlite3_open(directory.url.appendingPathComponent(AppServerLogStore.databaseName).path, &database) == SQLITE_OK)+ defer { sqlite3_close(database) }+ for (id, date) in [(expired, cutoff.addingTimeInterval(-1)), (boundary, cutoff)] {+ let sql = "UPDATE entries SET payload = CAST(json_set(CAST(payload AS TEXT), '$.requestedAt', \(date.timeIntervalSinceReferenceDate)) AS BLOB) WHERE id = '\(id.uuidString)'"+ #expect(sqlite3_exec(database, sql, nil, nil, nil) == SQLITE_OK)+ }+ clock.set(tomorrow)+ let reader = reopen ? AppServerLogStore(directoryURL: directory.url, now: { clock.read() }) : storage+ let page = try await reader.page()+ #expect(page.total == 1)+ #expect(page.entries.map(\.id) == [boundary])+ #expect(page.generation > original.generation)+ reader.finishRequest(expired, response: "late response")+ #expect(try await reader.page().total == 1)+ }++ @Test func disabledSyncStillPrunesBothLocalCachesAndKeepsRequiredTokenRoot() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let cutoff = HistoryStorage.retentionCutoffDate()+ let expired = cutoff.addingTimeInterval(-86400)+ let expiredKey = HistoryStorage.dateKey(for: expired)+ let retainedKey = HistoryStorage.dateKey(for: cutoff)+ let records = try [expiredKey, retainedKey].map { date in+ let daily = try TestFixtures.decode(SyncedActivity.self, """+ {"version":1,"aggregationVersion":1,"date":"\(date)","generationID":"source","eventCount":1}+ """)+ return try ActivitySyncRecord(+ deviceID: "device", daily: daily,+ recordName: ActivitySyncRecord.recordName(deviceID: "device", date: date, generation: "source")+ )+ }+ let cache = ActivitySyncCache(state: SyncState(hashByDate: [expiredKey: "old", retainedKey: "keep"]), records: records)+ _ = try directory.write(JSONLines.stableEncoder.encode(cache), to: "Sync/Activity/cache.json")+ let turns = [+ TokenTurn(id: "expired", rootID: "expired", updatedAt: expired),+ TokenTurn(id: "root", rootID: "root", updatedAt: expired),+ TokenTurn(id: "child", rootID: "root", updatedAt: cutoff)+ ]+ let tokenCache = SeededTokenCache(turns: Dictionary(uniqueKeysWithValues: turns.map { ($0.id, $0) }))+ _ = try directory.write(JSONLines.stableEncoder.encode(tokenCache), to: "Sync/Tokens/cache.json")+ let sync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { false })+ let service = HistoryService(directoryURL: directory.url, syncService: sync)+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ let activityData = try Data(contentsOf: directory.url.appendingPathComponent("Sync/Activity/cache.json"))+ let activity = try JSONLines.decoder.decode(ActivitySyncCache.self, from: activityData)+ #expect(activity.records.map(\.date) == [retainedKey])+ #expect(activity.state.hashByDate == [retainedKey: "keep"])+ let tokenData = try Data(contentsOf: directory.url.appendingPathComponent("Sync/Tokens/cache.json"))+ let tokens = try JSONLines.decoder.decode(SeededTokenCache.self, from: tokenData)+ #expect(Set(tokens.turns.keys) == ["root", "child"])+ #expect(tokens.cursor == nil)+ }+}++private nonisolated struct SeededTokenCache: Codable {+ var version = 1+ var accountScopedDeviceID = "device"+ var salt = Data(repeating: 1, count: 32)+ var turns: [String: TokenTurn]+ var cursor: Data? = Data("cursor".utf8)+}++private final nonisolated class RetentionClock: @unchecked Sendable {+ private let lock = NSLock()+ private var value = Date()++ func read() -> Date {+ lock.withLock { value }+ }++ func set(_ date: Date) {+ lock.withLock { value = date }+ }+}++extension StorageRetentionTests {+ @Test func eventDirectoryReadFailureDoesNotCompleteDailyCleanup() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let eventsURL = try directory.write("not a directory", to: "Events")+ #expect(throws: (any Error).self) { try HistoryStorage.readEventLogDateKeys(in: eventsURL) }+ let now = Date()+ let sync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { false })+ let service = HistoryService(directoryURL: directory.url, syncService: sync)+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual, now: now)+ try FileManager.default.removeItem(at: eventsURL)+ #expect(try HistoryStorage.readEventLogDateKeys(in: eventsURL).isEmpty)+ let expired = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate(today: now).addingTimeInterval(-86400))+ let expiredURL = try directory.writeJournal(Data(), to: "Events/\(expired).jsonl")+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual, now: now)+ #expect(!FileManager.default.fileExists(atPath: expiredURL.path))+ }++ @Test func newDailyAggregateIncludesKnownZeroAborts() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let recorder = ActivityRecorder(directoryURL: directory.url)+ let event = ActivityRecord(+ timestamp: now,+ name: ActivityEventKind.turnStarted.rawValue,+ origin: .main,+ cwd: nil,+ toolName: nil,+ model: nil,+ effort: nil,+ threadID: "session",+ turnID: "turn",+ agentID: nil,+ id: "start"+ )+ try await recorder.record(event: event)+ let sync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { false })+ let service = HistoryService(directoryURL: directory.url, syncService: sync)+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ let first = try #require(JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: HistoryStorage.dailyURL(in: directory.url))).first)+ #expect(first.turnStartedCount == 1)+ #expect(first.turnAbortedCount == 0)+ let aborted = ActivityRecord(+ timestamp: now,+ name: ActivityEventKind.turnAborted.rawValue,+ origin: .main,+ cwd: nil,+ toolName: nil,+ model: nil,+ effort: nil,+ threadID: "session",+ turnID: "turn",+ agentID: nil,+ id: "abort"+ )+ try await recorder.record(event: aborted)+ _ = await service.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ let second = try #require(JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: HistoryStorage.dailyURL(in: directory.url))).first)+ #expect(second.turnAbortedCount == 1)+ #expect(try HistoryStorage.loadMaintenanceState(in: directory.url).version == HistoryMaintenanceState.currentVersion)+ }+}diff --git a/CodexBarTests/History/TokenHistoryTests.swift b/CodexBarTests/History/TokenHistoryTests.swiftindex 5a313e0..f07c62f 100644--- a/CodexBarTests/History/TokenHistoryTests.swift+++ b/CodexBarTests/History/TokenHistoryTests.swift@@ -5,6 +5,27 @@ import Synchronizationimport Testingstruct TokenHistoryTests {+ @Test func usageWithoutObservationBoundaryIsRejectedLocallyAndInCloud() throws {+ var value = turn("main", "a", input: 100)+ value.checkpoint.removeAll()+ let data = try JSONEncoder().encode(value)+ #expect(throws: DecodingError.self) { try JSONDecoder().decode(TokenTurn.self, from: data) }+ let record = CKRecord(recordType: TokenSync.recordType, recordID: .init(recordName: value.id))+ TokenSync.apply(value, to: record)+ #expect(throws: StorageCompatibilityError.self) { try TokenSync.turn(from: record) }+ value.usage = nil+ #expect(try JSONDecoder().decode(TokenTurn.self, from: JSONEncoder().encode(value)) == value)+ }++ @Test func sameObservationBoundaryWithDifferentTotalsIsConflict() throws {+ let first = turn("main", "a", input: 100)+ var second = first+ second.usage = usage(input: 200)+ #expect(try first.merging(second).hasConflict)+ #expect(try first.merging(second).usage == nil)+ #expect(try second.merging(first).usage == nil)+ }+@Test func unchangedTokenStorageDoesNotReplaceFile() throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -88,22 +109,23 @@ struct TokenHistoryTests {#expect(try second.load() == ["cursor": 3])}- @Test func cloudRebuildMarkerOverridesStaleTotalsAndCanClearUsage() {+ @Test func cloudRebuildMarkerOverridesStaleTotalsAndCanClearUsage() throws {let stale = turn("main", "a", input: 500)var rebuilt = turn("main", "a", input: 100)+ rebuilt.checkpoint = stale.checkpointrebuilt.startNewGeneration(at: TestFixtures.now)- #expect(stale.merging(rebuilt) == rebuilt)- #expect(rebuilt.merging(stale) == rebuilt)+ #expect(try stale.merging(rebuilt) == rebuilt)+ #expect(try rebuilt.merging(stale) == rebuilt)let exported = rebuilt.pseudonymized(salt: Data("account".utf8))let record = CKRecord(recordType: TokenSync.recordType, recordID: .init(recordName: exported.id))TokenSync.apply(exported, to: record)- #expect(TokenSync.turn(from: record) == exported)+ #expect(try TokenSync.turn(from: record) == exported)var cleared = exportedcleared.usage = nilcleared.startNewGeneration(at: TestFixtures.now.addingTimeInterval(1))TokenSync.apply(cleared, to: record)- #expect(TokenSync.turn(from: record) == cleared)- #expect(exported.merging(cleared).usage == nil)+ #expect(try TokenSync.turn(from: record) == cleared)+ #expect(try exported.merging(cleared).usage == nil)#expect(TokenTurn.syncable([cleared]) == [cleared])}@@ -134,14 +156,15 @@ struct TokenHistoryTests {JSONFileStorage.releaseLock(next)}- @Test func cumulativeSnapshotsAndMultipleDevicesCountEachThreadTurnOnce() {+ @Test func cumulativeSnapshotsAndMultipleDevicesCountEachThreadTurnOnce() throws {let root = turn("main", "a", input: 100)var updated = turn("main", "a", input: 200)+ updated.checkpoint["test-stream"]?.sequence = 2updated.updatedAt = TestFixtures.now.addingTimeInterval(10)let child = turn("child", "b", root: root.id, input: 300)let result = TokenTurn.dailyUsage([root, updated, root, child, child], now: TestFixtures.now.addingTimeInterval(60))#expect(result[day]?.totalTokens == 520)- #expect(TokenTurn.merged([updated, root])[root.id] == TokenTurn.merged([root, updated])[root.id])+ #expect(try TokenTurn.merged([updated, root])[root.id] == TokenTurn.merged([root, updated])[root.id])}@Test func allChildrenIncludingLaterTurnsBelongToRootStartDate() throws {@@ -185,8 +208,19 @@ struct TokenHistoryTests {#expect(id.recordName == exported.id)let record = CKRecord(recordType: TokenSync.recordType, recordID: id)TokenSync.apply(exported, to: record)- #expect(TokenSync.turn(from: record) == exported)- #expect(Set(record.allKeys()) == ["updatedAt", "rootID", "version", "startedAt", "usage", "generationID", "ancestorIDs", "checkpoint", "hasConflict"])+ #expect(try TokenSync.turn(from: record) == exported)+ #expect(Set(record.allKeys()) == [+ "updatedAt",+ "rootID",+ "version",+ "aggregationVersion",+ "startedAt",+ "usage",+ "generationID",+ "ancestorIDs",+ "checkpoint",+ "hasConflict"+ ])let cloudUsage = try #require(record["usage"] as? Data)let cloudCounts = try #require(JSONSerialization.jsonObject(with: cloudUsage) as? [String: Int64])#expect(Set(cloudCounts.keys) == [@@ -198,7 +232,7 @@ struct TokenHistoryTests {#expect(!text.contains("private-turn"))record["version"] = 99 as CKRecordValue#expect(record.recordID == TokenSync.recordID(exported.id, zoneID: zone))- #expect(TokenSync.turn(from: record) == nil)+ #expect(throws: StorageCompatibilityError.self) { try TokenSync.turn(from: record) }}@Test func childUsageWaitsForRootStartAndNeedsNoRootUsageRecord() {@@ -225,7 +259,7 @@ struct TokenHistoryTests {@Test func heatmapSeparatesAccountIntensityFromLocalDailyMetrics() throws {var history = HistorySnapshot.emptyhistory.tokenUsageByDate = [day: usage(input: 100)]- let grid = UsageHeatmapDay.grid(usage: nil, history: history, showsActivity: true, columnCount: 2, today: TestFixtures.now)+ let grid = UsageHeatmapDay.grid(usage: nil, history: history, columnCount: 2, today: TestFixtures.now)let today = try #require(grid.compactMap(\.self).first { $0.startDate == day })#expect(today.tokenState == .unavailable)#expect(today.tokenUsage?.totalTokens == 110)@@ -242,7 +276,7 @@ struct TokenHistoryTests {private func turn(_ thread: String, _ turn: String, root: String? = nil, input: Int64) -> TokenTurn {let id = TokenTurn.identifier(thread: thread, turn: turn)- return TokenTurn(id: id, rootID: root ?? id, startedAt: TestFixtures.now, updatedAt: TestFixtures.now, usage: usage(input: input))+ return TestFixtures.tokenTurn(id: id, rootID: root ?? id, startedAt: TestFixtures.now, updatedAt: TestFixtures.now, usage: usage(input: input))}}@@ -271,7 +305,7 @@ extension TokenHistoryTests {let directory = try TestDirectory()defer { try? directory.remove() }let cache = try directory.write("broken cache", to: "Aggregates/tokens.json")- _ = try directory.write("broken event\n", to: "Events/\(HistoryStorage.dateKey(for: Date())).jsonl")+ _ = try directory.writeJournal(Data("broken event\n".utf8), to: "Events/\(HistoryStorage.dateKey(for: Date())).jsonl")let store = TokenHistoryStore(directoryURL: directory.url)await #expect(throws: TokenCacheError.self) { try await store.refresh() }#expect(try String(contentsOf: cache, encoding: .utf8) == "broken cache")@@ -319,7 +353,9 @@ extension TokenHistoryTests {let restarted = TokenHistoryStore(directoryURL: directory.url)#expect(try await restarted.recordObservations([second], now: TestFixtures.now).first?.usage?.totalTokens == 70)try FileManager.default.removeItem(at: directory.url.appendingPathComponent("Aggregates/tokens.json"))- #expect(try await restarted.refresh(now: TestFixtures.now).first?.usage?.totalTokens == 70)+ let recovered = try #require(try await restarted.refresh(now: TestFixtures.now).first)+ #expect(recovered.usage?.totalTokens == 110)+ #expect(recovered.ancestorIDs.contains(corrected.generationID))}@Test func remoteCoveredObservationIsNotAddedTwice() async throws {@@ -369,12 +405,12 @@ extension TokenHistoryTests {b.startNewGeneration(at: TestFixtures.now.addingTimeInterval(-9999))a.usage = observation(sequence: 1, previous: 0, current: 60).currentb.usage = observation(sequence: 1, previous: 0, current: 80).current- let merged = a.merging(b)+ let merged = try a.merging(b)#expect(merged.hasConflict)#expect(merged.usage == nil)- #expect(merged.generationID == b.merging(a).generationID)- #expect(merged.merging(a).generationID == merged.generationID)- #expect(merged.merging(b).generationID == merged.generationID)+ #expect(try merged.generationID == b.merging(a).generationID)+ #expect(try merged.merging(a).generationID == merged.generationID)+ #expect(try merged.merging(b).generationID == merged.generationID)#expect(TokenTurn.dailyUsage([merged], now: TestFixtures.now).isEmpty)}@@ -383,7 +419,7 @@ extension TokenHistoryTests {defer { try? directory.remove() }let store = TokenHistoryStore(directoryURL: directory.url)let missingFirst = observation(sequence: 2, previous: 100, current: 110)- await #expect(throws: TokenCacheError.self) { try await store.recordObservations([missingFirst], now: TestFixtures.now) }+ #expect(try await store.recordObservations([missingFirst], now: TestFixtures.now).isEmpty)#expect(try await store.currentTurns(now: TestFixtures.now).isEmpty)}}@@ -395,12 +431,12 @@ extension TokenHistoryTests {correction.startNewGeneration(at: TestFixtures.now)correction.usage = observation(sequence: 1, previous: 0, current: 60).currentlet stale = try observation(sequence: 2, previous: 100, current: 110).applying(to: original)- let merged = correction.merging(stale)+ let merged = try correction.merging(stale)#expect(merged.usage?.totalTokens == 70)#expect(merged.generationID == correction.generationID)- #expect(stale.merging(correction) == merged)- #expect(merged.merging(stale) == merged)- #expect(merged.merging(correction) == merged)+ #expect(try stale.merging(correction) == merged)+ #expect(try merged.merging(stale) == merged)+ #expect(try merged.merging(correction) == merged)}}@@ -422,7 +458,7 @@ extension TokenHistoryTests {let data = try observations.reduce(into: Data()) { result, observation intry result.append(AppServerEventRecord(observation: observation, recordedAt: date).jsonLineData())}- _ = try directory.write(data, to: "Events/\(HistoryStorage.dateKey(for: date)).jsonl")+ _ = try directory.writeJournal(data, to: "Events/\(HistoryStorage.dateKey(for: date)).jsonl")}@Test func unselectedIncompleteRootDoesNotBlockRebuildOrSubsequentCacheLoad() async throws {@@ -503,14 +539,16 @@ extension TokenHistoryTests {let fourth = rebuildObservation("root", sequence: 4, previous: 30, current: 40)let store = TokenHistoryStore(directoryURL: directory.url)let before = try #require(try await store.recordObservations([first], now: TestFixtures.now).first)+ let cacheURL = directory.url.appendingPathComponent("Aggregates/tokens.json")+ let previousCache = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: cacheURL)) as? [String: Any])+ let previousFiles = try #require(previousCache["files"] as? NSDictionary)try writeJournal([first, second], in: directory)let nextDay = TestFixtures.now.addingTimeInterval(86400)try writeJournal([fourth], in: directory, at: nextDay)let partial = try await store.refresh(now: nextDay)#expect(partial == [before])- let cacheURL = directory.url.appendingPathComponent("Aggregates/tokens.json")let cache = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: cacheURL)) as? [String: Any])- #expect((cache["files"] as? [String: Any])?.isEmpty == true)+ #expect(cache["files"] as? NSDictionary == previousFiles)try writeJournal([third, fourth], in: directory, at: nextDay)let restarted = TokenHistoryStore(directoryURL: directory.url)let repaired = try await restarted.refresh(now: nextDay)@@ -527,7 +565,10 @@ extension TokenHistoryTests {let cacheURL = directory.url.appendingPathComponent("Aggregates/tokens.json")let before = try Data(contentsOf: cacheURL)let eventURL = HistoryStorage.eventLogURL(for: day, in: HistoryStorage.eventsDirectoryURL(in: directory.url))- try Data("broken record\n".utf8).write(to: eventURL)+ let broken = try FileHandle(forWritingTo: eventURL)+ try broken.seekToEnd()+ try broken.write(contentsOf: Data("broken record\n".utf8))+ try broken.close()await #expect(throws: TokenCacheError.self) { try await store.rebuild(for: [day], now: TestFixtures.now) }#expect(try Data(contentsOf: cacheURL) == before)let ambiguous = rebuildObservation("root", root: "different")@@ -536,3 +577,128 @@ extension TokenHistoryTests {#expect(try Data(contentsOf: cacheURL) == before)}}++extension TokenHistoryTests {+ @Test(arguments: [false, true])+ func rootIdentityCannotChangeAcrossMergeGenerations(rebuilt: Bool) throws {+ let original = turn("root", "turn", input: 15)+ var incoming = original+ incoming.rootID = "different-root"+ if rebuilt {+ incoming.startNewGeneration(at: TestFixtures.now)+ }+ #expect(throws: TokenCacheError.self) { try original.merging(incoming) }+ #expect(throws: TokenCacheError.self) { try incoming.merging(original) }+ #expect(TokenTurn.dailyUsage([original, incoming], now: TestFixtures.now).isEmpty)+ #expect(TokenTurn.dailyUsage([incoming, original], now: TestFixtures.now).isEmpty)+ var otherChild = original+ otherChild.rootID = "another-root"+ #expect(throws: TokenCacheError.self) { try incoming.merging(otherChild) }+ let observation = TokenObservation(+ turn: incoming, rootStartedAt: TestFixtures.now, streamID: "test-stream", sequence: 1,+ previous: .zero, current: usage(input: 15)+ )+ #expect(throws: TokenCacheError.self) { try observation.applying(to: original) }+ }+}++extension TokenHistoryTests {+ @Test(arguments: [true, false], [true, false])+ func cacheRecoveryRecomputesMixedSnapshots(snapshotsFirst: Bool, damagedCache: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ let first = observation(sequence: 1, previous: 0, current: 10)+ _ = try await store.recordObservations([first], now: TestFixtures.now)+ let cacheURL = directory.url.appendingPathComponent("Aggregates/tokens.json")+ var cache = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: cacheURL)) as? [String: Any])+ var turns = try #require(cache["turns"] as? [String: Any])+ var previous = try #require(turns[first.turn.id] as? [String: Any])+ previous["aggregationVersion"] = 1+ previous["usage"] = try JSONSerialization.jsonObject(with: JSONEncoder().encode(observation(sequence: 1, previous: 0, current: 12).current))+ var checkpoints = try #require(previous["checkpoint"] as? [String: Any])+ var point = try #require(checkpoints["stream"] as? [String: Any])+ point["aggregationRanges"] = [["version": 1, "end": 1]]+ checkpoints["stream"] = point+ previous["checkpoint"] = checkpoints+ turns[first.turn.id] = previous+ cache["turns"] = turns+ try JSONSerialization.data(withJSONObject: cache).write(to: cacheURL)++ let second = observation(sequence: 2, previous: 10, current: 15)+ let mixed = try #require(try await store.recordObservations([second], now: TestFixtures.now).first)+ #expect(mixed.usage?.totalTokens == 17)+ #expect(mixed.aggregationVersion == AggregationVersion.tokens)+ #expect(mixed.checkpoint["stream"]?.aggregationRanges.first?.version == 1)+ #expect(mixed.checkpoint["stream"]?.aggregationRanges.last?.version == AggregationVersion.tokens)+ let salt = Data("account".utf8)+ var remote = mixed.pseudonymized(salt: salt)+ remote.updatedAt = TestFixtures.now.addingTimeInterval(1)+ _ = try await store.refresh(now: TestFixtures.now, baseline: TokenHistoryBaseline(salt: salt, turns: [remote.id: remote]))+ let path = "Events/\(day).jsonl"+ var entries: [AppServerEventRecord] = []+ try AppServerEventJournal.read(at: directory.url.appendingPathComponent(path)) { entries.append($0) }+ #expect(entries.contains { $0.token?.usage?.totalTokens == 17 })+ if snapshotsFirst {+ entries = entries.filter { $0.token != nil } + entries.filter { $0.token == nil }+ try directory.writeJournal(entries.reduce(into: Data()) { try $0.append($1.jsonLineData()) }, to: path)+ }+ if damagedCache {+ try Data("broken cache".utf8).write(to: cacheURL)+ } else {+ try FileManager.default.removeItem(at: cacheURL)+ }+ let recovered = try #require(try await store.refresh(now: TestFixtures.now).first)+ #expect(recovered.usage?.totalTokens == 15)+ #expect(!recovered.hasConflict)+ #expect(recovered.ancestorIDs.contains(mixed.generationID))+ #expect(recovered.checkpoint["stream"]?.aggregationRanges == [.init(version: AggregationVersion.tokens, end: 2)])+ #expect(await store.pendingRecoveryIDs() == [recovered.id])+ let reopened = TokenHistoryStore(directoryURL: directory.url)+ #expect(try await reopened.refresh(now: TestFixtures.now) == [recovered])+ #expect(try await reopened.refresh(now: TestFixtures.now) == [recovered])+ let third = observation(sequence: 3, previous: 15, current: 20)+ let continued = try #require(try await reopened.recordObservations([second, third, third], now: TestFixtures.now).first)+ #expect(continued.usage?.totalTokens == 20)+ #expect(continued.generationID == recovered.generationID)+ }++ @Test(arguments: [true, false])+ func unreadableEventsDirectoryPreservesCache(hasValidCache: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenHistoryStore(directoryURL: directory.url)+ _ = try await store.recordObservations([observation(sequence: 1, previous: 0, current: 10)], now: TestFixtures.now)+ let cacheURL = directory.url.appendingPathComponent("Aggregates/tokens.json")+ if !hasValidCache {+ try Data("broken cache".utf8).write(to: cacheURL)+ }+ let before = try Data(contentsOf: cacheURL)+ let events = directory.url.appendingPathComponent("Events")+ try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: events.path)+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: events.path) }+ #expect(throws: (any Error).self) { try HistoryStorage.readEventLogDateKeys(in: events) }+ await #expect(throws: (any Error).self) { try await store.refresh(now: TestFixtures.now) }+ #expect(try Data(contentsOf: cacheURL) == before)+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: events.path)+ #expect(try await store.refresh(now: TestFixtures.now).first?.usage?.totalTokens == 10)+ }++ @Test func cacheRecoveryPreservesWholeRootWhenChildObservationsAreMissing() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let root = rebuildObservation("root")+ let child = rebuildObservation("child", root: "root")+ let store = TokenHistoryStore(directoryURL: directory.url)+ let before = try await store.recordObservations([root, child], now: TestFixtures.now)+ var data = try AppServerEventRecord(observation: root, recordedAt: TestFixtures.now).jsonLineData()+ for turn in before {+ try data.append(AppServerEventRecord(token: turn, recordedAt: TestFixtures.now).jsonLineData())+ }+ try directory.writeJournal(data, to: "Events/\(day).jsonl")+ try FileManager.default.removeItem(at: directory.url.appendingPathComponent("Aggregates/tokens.json"))+ let restored = try await store.refresh(now: TestFixtures.now)+ #expect(try TokenTurn.merged(restored) == TokenTurn.merged(before))+ #expect(await store.pendingRecoveryIDs().isEmpty)+ }+}diff --git a/CodexBarTests/KeepAlive/HelperManagerClientTests.swift b/CodexBarTests/KeepAlive/HelperManagerClientTests.swiftnew file mode 100644index 0000000..c3bae8b--- /dev/null+++ b/CodexBarTests/KeepAlive/HelperManagerClientTests.swift@@ -0,0 +1,123 @@+import Foundation+import ServiceManagement+import Testing++@Suite(.timeLimit(.minutes(1)))+struct HelperManagerClientTests {+ @Test func transientStatusFailureRecoversWithinSameRequest() async throws {+ let execution = HelperManagerExecutionStub(failures: 1, status: .enabled)+ let client = HelperManagerClient(retryDelay: .zero, executeCommand: { try await execution.execute($0) })+ #expect(try await client.perform(.status) == .enabled)+ #expect(await execution.commands == [.status, .status])+ }++ @Test(arguments: [SMAppService.Status.notRegistered, .enabled, .requiresApproval, .notFound])+ func validStatusIsNeverRetried(_ status: SMAppService.Status) async throws {+ let execution = HelperManagerExecutionStub(failures: 0, status: status)+ let client = HelperManagerClient(retryDelay: .zero, executeCommand: { try await execution.execute($0) })+ #expect(try await client.perform(.status) == status)+ #expect(await execution.commands == [.status])+ }++ @Test func persistentFailureStopsAfterThreeAttemptsAndAllowsLaterRefresh() async throws {+ let execution = HelperManagerExecutionStub(failures: 3, status: .enabled)+ let client = HelperManagerClient(retryDelay: .zero, executeCommand: { try await execution.execute($0) })+ await #expect(throws: HelperManagerClient.ClientError.self) {+ try await client.perform(.status)+ }+ #expect(await execution.commands.count == 3)+ #expect(try await client.perform(.status) == .enabled)+ #expect(await execution.commands.count == 4)+ }++ @Test(arguments: [HelperManagement.Command.register, .unregister])+ func mutationsAreNeverRetried(_ command: HelperManagement.Command) async {+ let execution = HelperManagerExecutionStub(failures: 3, status: .enabled)+ let client = HelperManagerClient(retryDelay: .zero, executeCommand: { try await execution.execute($0) })+ await #expect(throws: HelperManagerClient.ClientError.self) {+ try await client.perform(command)+ }+ #expect(await execution.commands == [command])+ }++ @Test func cancellationStopsRetryAndAllowsNextRequest() async throws {+ let execution = HelperManagerExecutionStub(failures: 1, status: .enabled)+ let client = HelperManagerClient(retryDelay: .seconds(30), executeCommand: { try await execution.execute($0) })+ let request = Task { try await client.perform(.status) }+ await execution.waitForFirstAttempt()+ request.cancel()+ await #expect(throws: CancellationError.self) {+ try await request.value+ }+ #expect(await execution.commands == [.status])+ #expect(try await client.perform(.status) == .enabled)+ #expect(await execution.commands == [.status, .status])+ }++ @Test(arguments: [SMAppService.Status.notRegistered, .enabled, .requiresApproval, .notFound])+ func statusKeepsSystemMeaning(_ status: SMAppService.Status) throws {+ let data = try reply(status)+ #expect(try HelperManagerClient.status(from: data, command: .status) == status)+ }++ @Test func pendingApprovalIsRegisteredButNotEnabled() throws {+ let data = try reply(.requiresApproval, errorDomain: SMAppServiceErrorDomain, errorCode: 1)+ let status = try HelperManagerClient.status(from: data, command: .register)+ #expect(status == .requiresApproval)+ #expect(KeepAliveController.HelperStatus(status).isRegisteredOrAwaitingApproval)+ }++ @Test func registrationFailureCannotBeMistakenForApproval() throws {+ let data = try reply(.notRegistered, errorDomain: SMAppServiceErrorDomain, errorCode: 1)+ #expect(throws: NSError.self) {+ try HelperManagerClient.status(from: data, command: .register)+ }+ }++ @Test func unregistrationFailureIsNotHiddenByEnabledStatus() throws {+ let data = try reply(.enabled, errorDomain: SMAppServiceErrorDomain, errorCode: 1)+ #expect(throws: NSError.self) {+ try HelperManagerClient.status(from: data, command: .unregister)+ }+ }++ @Test func malformedReplyDoesNotBecomeNotRegistered() {+ for data in [Data(), Data("{}".utf8), Data("{\"status\":999}".utf8)] {+ #expect(throws: (any Error).self) {+ try HelperManagerClient.status(from: data, command: .status)+ }+ }+ }++ private func reply(_ status: SMAppService.Status, errorDomain: String? = nil, errorCode: Int? = nil) throws -> Data {+ try JSONEncoder().encode(HelperManagement.Reply(status: status.rawValue, errorDomain: errorDomain, errorCode: errorCode))+ }+}++private actor HelperManagerExecutionStub {+ private var failures: Int+ private let status: SMAppService.Status+ private(set) var commands: [HelperManagement.Command] = []+ private var firstAttempt: CheckedContinuation<Void, Never>?++ init(failures: Int, status: SMAppService.Status) {+ self.failures = failures+ self.status = status+ }++ func execute(_ command: HelperManagement.Command) throws -> SMAppService.Status {+ commands.append(command)+ firstAttempt?.resume()+ firstAttempt = nil+ if failures > 0 {+ failures -= 1+ throw HelperManagerClient.ClientError.executionFailed+ }+ return status+ }++ func waitForFirstAttempt() async {+ guard commands.isEmpty else { return }+ await withCheckedContinuation { firstAttempt = $0 }+ }+}diff --git a/CodexBarTests/KeepAlive/HelperPackageValidationTests.swift b/CodexBarTests/KeepAlive/HelperPackageValidationTests.swiftnew file mode 100644index 0000000..b794519--- /dev/null+++ b/CodexBarTests/KeepAlive/HelperPackageValidationTests.swift@@ -0,0 +1,105 @@+import Foundation+import Testing++struct HelperPackageValidationTests {+ @Test func concurrentRefreshesShareOneInspection() async throws {+ let probe = PackageInspectionProbe()+ let validation = HelperPackageValidation { await probe.inspect() }+ defer { validation.cancel() }+ var completions = 0+ validation.onValidated = { completions += 1 }+ validation.refresh()+ validation.refresh()+ try await probe.waitForRequests(1)+ #expect(validation.fingerprint == nil)+ await probe.finish(0, fingerprint: "current")+ for _ in 0 ..< 100 where completions == 0 {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(await probe.count == 1)+ #expect(completions == 1)+ #expect(validation.fingerprint == "current")+ }++ @Test func cancelledInspectionCannotOverwriteReplacement() async throws {+ let probe = PackageInspectionProbe()+ let validation = HelperPackageValidation { await probe.inspect() }+ defer { validation.cancel() }+ var completions = 0+ validation.onValidated = { completions += 1 }+ validation.refresh()+ try await probe.waitForRequests(1)+ validation.cancel()+ validation.refresh()+ try await probe.waitForRequests(2)+ await probe.finish(1, fingerprint: "new")+ for _ in 0 ..< 100 where completions == 0 {+ try await Task.sleep(for: .milliseconds(5))+ }+ await probe.finish(0, fingerprint: "old")+ try await Task.sleep(for: .milliseconds(20))+ #expect(validation.fingerprint == "new")+ #expect(completions == 1)+ }++ @Test func failedInspectionClearsPreviousFingerprint() async throws {+ let probe = PackageInspectionProbe()+ let validation = HelperPackageValidation { await probe.inspect() }+ defer { validation.cancel() }+ validation.refresh()+ try await probe.waitForRequests(1)+ await probe.finish(0, fingerprint: "valid")+ for _ in 0 ..< 100 where validation.fingerprint == nil {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(validation.fingerprint == "valid")+ validation.refresh()+ #expect(validation.fingerprint == nil)+ try await probe.waitForRequests(2)+ await probe.finish(1, fingerprint: "invalid", issue: .invalid)+ for _ in 0 ..< 100 where validation.issue == nil {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(validation.issue == .invalid)+ #expect(validation.fingerprint == nil)+ }++ @Test func registrationUsesInspectedFingerprintAndPreservesPendingReset() throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let defaults = preferences.defaults+ _ = HelperConfiguration.beginUpdate(defaults: defaults, requiresSleepReset: true, fingerprint: "first")+ HelperConfiguration.recordRegistration(defaults: defaults, status: .enabled, fingerprint: "first")+ #expect(!HelperConfiguration.registrationNeedsRefresh(defaults: defaults, fingerprint: "first"))+ #expect(HelperConfiguration.registrationNeedsRefresh(defaults: defaults, fingerprint: "second"))+ _ = HelperConfiguration.beginUpdate(defaults: defaults, requiresSleepReset: false, fingerprint: "second")+ HelperConfiguration.recordRegistration(defaults: defaults, status: .requiresApproval, fingerprint: "second")+ HelperConfiguration.completeUpdate("first", defaults: defaults)+ #expect(HelperConfiguration.pendingUpdateIdentifier(defaults: defaults, fingerprint: "second") == "second")+ HelperConfiguration.completeUpdate("second", defaults: defaults)+ #expect(HelperConfiguration.pendingUpdateIdentifier(defaults: defaults, fingerprint: "second") == nil)+ }+}++private actor PackageInspectionProbe {+ private var replies: [CheckedContinuation<HelperPackageSnapshot, Never>?] = []+ var count: Int {+ replies.count+ }++ func inspect() async -> HelperPackageSnapshot {+ await withCheckedContinuation { replies.append($0) }+ }++ func finish(_ index: Int, fingerprint: String, issue: HelperPackageIssue? = nil) {+ replies[index]?.resume(returning: HelperPackageSnapshot(issue: issue, fingerprint: fingerprint))+ replies[index] = nil+ }++ func waitForRequests(_ count: Int) async throws {+ for _ in 0 ..< 100 where replies.count < count {+ try await Task.sleep(for: .milliseconds(5))+ }+ try #require(replies.count == count)+ }+}diff --git a/CodexBarTests/KeepAlive/SystemSleepServiceTests.swift b/CodexBarTests/KeepAlive/SystemSleepServiceTests.swiftnew file mode 100644index 0000000..fb7eb18--- /dev/null+++ b/CodexBarTests/KeepAlive/SystemSleepServiceTests.swift@@ -0,0 +1,88 @@+import Foundation+import IOKit+import IOKit.pwr_mgt+import Testing++struct SystemSleepServiceTests {+ @Test(arguments: [false, true])+ func failedReleaseRemainsPendingUntilRetrySucceeds(userActivityFails: Bool) async throws {+ var releaseCounts: [IOPMAssertionID: Int] = [:]+ var didDeclare = false+ let failedID: IOPMAssertionID = userActivityFails ? 2 : 1+ let service = SystemSleepService(+ createAssertion: { _, _, id in id = 1+ return kIOReturnSuccess+ },+ releaseAssertion: { id in+ releaseCounts[id, default: 0] += 1+ return id == failedID && releaseCounts[id] == 1 ? kIOReturnError : kIOReturnSuccess+ },+ declareActivity: { _, id in id = 2+ didDeclare = true+ return kIOReturnSuccess+ },+ displayReleaseRetryDelays: [.milliseconds(1)]+ )+ #expect(service.beginPreventingDisplaySleep() == kIOReturnSuccess)+ for _ in 0 ..< 100 where !didDeclare {+ try await Task.sleep(for: .milliseconds(1))+ }+ #expect(didDeclare)+ #expect(service.endPreventingDisplaySleep() == kIOReturnError)+ #expect(!service.isPreventingDisplaySleep)+ #expect(service.hasDisplaySleepResources)+ for _ in 0 ..< 100 where service.hasDisplaySleepResources {+ try await Task.sleep(for: .milliseconds(1))+ }+ #expect(!service.hasDisplaySleepResources)+ #expect(releaseCounts[failedID] == 2)+ #expect(releaseCounts[userActivityFails ? 1 : 2] == 1)+ }++ @Test func releaseRetriesAreBoundedAndNotFoundCountsAsReleased() async throws {+ var releases = 0+ var result = kIOReturnError+ let service = SystemSleepService(+ createAssertion: { _, _, id in id = 1+ return kIOReturnSuccess+ },+ releaseAssertion: { _ in releases += 1+ return result+ },+ declareActivity: { _, _ in kIOReturnSuccess },+ displayReleaseRetryDelays: [.milliseconds(1), .milliseconds(1)]+ )+ #expect(service.beginPreventingDisplaySleep() == kIOReturnSuccess)+ #expect(service.endPreventingDisplaySleep() == kIOReturnError)+ for _ in 0 ..< 100 where releases < 3 {+ try await Task.sleep(for: .milliseconds(1))+ }+ try await Task.sleep(for: .milliseconds(10))+ #expect(releases == 3)+ #expect(service.hasDisplaySleepResources)+ result = kIOReturnNotFound+ #expect(service.endPreventingDisplaySleep() == kIOReturnSuccess)+ #expect(!service.hasDisplaySleepResources)+ }++ @Test func reenableCancelsPendingRelease() async throws {+ var releases = 0+ let service = SystemSleepService(+ createAssertion: { _, _, id in id = 1+ return kIOReturnSuccess+ },+ releaseAssertion: { _ in releases += 1+ return kIOReturnError+ },+ declareActivity: { _, _ in kIOReturnSuccess },+ displayReleaseRetryDelays: [.milliseconds(1)]+ )+ #expect(service.beginPreventingDisplaySleep() == kIOReturnSuccess)+ #expect(service.endPreventingDisplaySleep() == kIOReturnError)+ #expect(service.beginPreventingDisplaySleep() == kIOReturnSuccess)+ try await Task.sleep(for: .milliseconds(10))+ #expect(releases == 1)+ #expect(service.isPreventingDisplaySleep)+ _ = service.endPreventingDisplaySleep()+ }+}diff --git a/CodexBarTests/Presentation/ActivityPresentationTests.swift b/CodexBarTests/Presentation/ActivityPresentationTests.swiftindex b0e374c..5ce2ea8 100644--- a/CodexBarTests/Presentation/ActivityPresentationTests.swift+++ b/CodexBarTests/Presentation/ActivityPresentationTests.swift@@ -3,26 +3,112 @@ import Foundationimport Testingstruct ActivityPresentationTests {+ @Test(arguments: ["active", "missing", "pending", "bootstrap", "recovering", "old", "superseded", "rounded", "missing-time"])+ func completedEventFinalizesWithoutLifecyclePolling(_ scenario: String) 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), activityDirectoryURL: directory.url+ )+ defer { monitor.stop() }+ let now = Date()+ let endedAt = switch scenario {+ case "old": now.addingTimeInterval(-60)+ case "rounded": Date(timeIntervalSince1970: floor(now.timeIntervalSince1970) - 1)+ default: now+ }+ let startedAt = endedAt.addingTimeInterval(-2)+ let start = TestFixtures.event(at: startedAt)+ let key = try #require(ActivityTaskKey(event: start))+ var task = ActivityTask(displayID: UUID(), key: key, event: start, state: .running, startedAt: startedAt, progressGeneration: 1)+ if scenario == "rounded" {+ let progress = TestFixtures.event(.toolCompleted, at: endedAt.addingTimeInterval(0.5))+ task.recordExecutionEvent(progress)+ task.recordProgress(at: progress.timestamp)+ }+ monitor.isActivitySourceHealthy = true+ monitor.sessionTransitionNotBefore = startedAt+ monitor.terminalPresentationNotBefore = startedAt+ monitor.isProtectionRecoveryInProgress = scenario == "recovering"+ var notices = 0+ let subscription = monitor.transitionPublisher.sink { transition in+ if case .completed = transition {+ notices += 1+ #expect(monitor.snapshot.recentCompletions.count == 1)+ #expect(monitor.snapshot.runningTasks.count == (scenario == "superseded" ? 1 : 0))+ }+ }+ defer { subscription.cancel() }+ var presentations: [ActivityPresentationUpdate] = []+ let presentation = monitor.presentationPublisher.sink { presentations.append($0) }+ defer { presentation.cancel() }+ if scenario == "pending" || scenario == "superseded" {+ monitor.pendingTerminalTasks[key] = PendingTerminalTask(task: task, supersededAt: now)+ } else if scenario != "missing" {+ monitor.tasks[key] = task+ }+ let next = TestFixtures.event(at: now, turn: "next")+ if scenario == "superseded" {+ let nextKey = try #require(ActivityTaskKey(event: next))+ monitor.tasks[nextKey] = ActivityTask(displayID: UUID(), key: nextKey, event: next, state: .running, startedAt: now, progressGeneration: 0)+ }+ var end = TestFixtures.event(.turnCompleted, at: endedAt, thread: start.threadID, turn: start.turnID)+ end.context = ActivityContext(+ method: "turn/completed", threadID: "thread-a", turnID: "turn-a", turnStatus: .completed,+ turnStartedAt: startedAt, turnCompletedAt: scenario == "missing-time" ? nil : endedAt, duration: scenario == "missing-time" ? nil : 2+ )+ if scenario == "bootstrap" {+ monitor.consume(.snapshotEvents([end, end]))+ } else {+ monitor.consume(.live([end, end]))+ }+ #expect(monitor.tasks[key] == nil)+ #expect(monitor.pendingTerminalTasks[key] == nil)+ #expect(monitor.completions.count == 1)+ #expect(monitor.completions.first?.duration == (scenario == "missing-time" ? nil : 2))+ #expect(monitor.terminalTokenUsageRequests.count == 1)+ let audible = ["active", "missing", "pending", "superseded", "rounded", "missing-time"].contains(scenario)+ #expect(notices == (audible ? 1 : 0))+ if scenario == "superseded" {+ #expect(try monitor.tasks[#require(ActivityTaskKey(event: next))] != nil)+ }+ if ["bootstrap", "recovering", "old"].contains(scenario) {+ let hasNoTerminalEvents = presentations.allSatisfy(\.terminalEvents.isEmpty)+ #expect(hasNoTerminalEvents)+ }+ var repeated: [ActivityTransition] = []+ monitor.resolveTerminal(.completed(at: endedAt, duration: 2), task: task, key: key, abortFallback: endedAt, into: &repeated)+ #expect(repeated.isEmpty)+ #expect(monitor.completions.count == 1)+ }+@Test(arguments: [- (("commandExecution", "search/read/read"), "activity.live.actions-read-search"),- (("commandExecution", nil), "activity.action.command"),- (("fileChange", nil), "activity.action.edit-files"),- (("collabAgentToolCall", "spawnAgent"), "activity.action.start-subagent")- ] as [((String, String?), LocalizedStringResource)], [false, true])+ (ActivityItem(id: "command", type: .commandExecution, commandActions: ["search", "read", "read"].map { .init(type: $0) }), "activity.live.actions-read-search"),+ (ActivityItem(id: "command", type: .commandExecution), "activity.action.command"),+ (ActivityItem(id: "file", type: .fileChange), "activity.action.edit-files"),+ (ActivityItem(id: "agent", type: .collabAgentToolCall, tool: "spawnAgent"), "activity.action.start-subagent")+ ] as [(ActivityItem, LocalizedStringResource)], [false, true])func waitingSurfacesShareLocalizedActions(- operation: (source: (type: String, tool: String?), action: LocalizedStringResource), hasProject: Bool+ operation: (source: ActivityItem, action: LocalizedStringResource), hasProject: Bool) {+ let approval = ActivityApproval(+ requestedAt: TestFixtures.now, toolName: operation.source.tool, sequence: 0,+ itemType: operation.source.type.rawValue, commandActionTypes: operation.source.commandActions?.map(\.type)+ )let task = ActivityTaskSnapshot(- id: UUID(), isAnonymous: false,- projectName: hasProject ? "CodexBar" : nil, modelName: nil, effort: nil, toolName: operation.source.tool,+ id: UUID(),+ projectName: hasProject ? "CodexBar" : nil, modelName: nil, effort: nil,startedAt: TestFixtures.now, stateChangedAt: TestFixtures.now,- showsPreciseDuration: true, activeSubagentCount: nil, itemType: operation.source.type+ activeSubagentCount: nil, approvalActionText: approval.actionText)let expected = String(localized: operation.action)- let notice = NotificationContent.taskWaiting(project: task.projectName, toolName: task.toolDisplayName)- #expect(task.toolDisplayName == expected)+ let notice = NotificationContent.taskWaiting(project: task.projectName, actionText: task.approvalActionText)+ #expect(task.approvalActionText == expected)#expect(notice.body.contains(expected))- #expect(!notice.body.contains(operation.source.type))+ #expect(!notice.body.contains(operation.source.type.rawValue))if let raw = operation.source.tool {#expect(!notice.body.contains(raw))}@@ -39,6 +125,7 @@ struct ActivityPresentationTests {protectionStore: ProtectionStore(directoryURL: directory.url),activityDirectoryURL: directory.url)+ monitor.protectionLoadState = .availablemonitor.isStarted = truemonitor.isActivitySourceHealthy = truedefer { monitor.stop() }@@ -73,7 +160,7 @@ struct ActivityPresentationTests {monitor.consume(.sourceUnavailable)#expect(updates.count == count)monitor.isActivitySourceHealthy = true- monitor.consume(.live([TestFixtures.event(at: now.addingTimeInterval(2), session: "restored")]))+ monitor.consume(.live([TestFixtures.event(at: now.addingTimeInterval(2), thread: "restored")]))#expect(updates.last?.snapshot == monitor.snapshot)#expect(updates.last?.terminalEvents.isEmpty == true)#expect(glow.state != .hidden)diff --git a/CodexBarTests/Presentation/DateAndPresentationTests.swift b/CodexBarTests/Presentation/DateAndPresentationTests.swiftindex b9b5828..a09a6ea 100644--- a/CodexBarTests/Presentation/DateAndPresentationTests.swift+++ b/CodexBarTests/Presentation/DateAndPresentationTests.swift@@ -53,17 +53,15 @@ struct DateAndPresentationTests {let today = try #require(CodexDateFormat.dayDate(from: "2026-09-15"))let summary = try TestFixtures.decode(UsageSummary.self, "{}")let usage = CodexUsageSnapshot(summary: summary, dailyBuckets: [])- let grid = UsageHeatmapDay.grid(usage: usage, history: .empty, showsActivity: true, columnCount: 2, today: today).compactMap(\.self)+ let grid = UsageHeatmapDay.grid(usage: usage, history: .empty, columnCount: 2, today: today).compactMap(\.self)#expect(grid.last?.tokenState == .pending)#expect(grid.first?.tokenState == .available(0))- let unavailable = UsageHeatmapDay.grid(usage: nil, history: .empty, showsActivity: true, columnCount: 2, today: today).compactMap(\.self)+ let unavailable = UsageHeatmapDay.grid(usage: nil, history: .empty, columnCount: 2, today: today).compactMap(\.self)#expect(unavailable.allSatisfy { $0.tokenState == .unavailable })- let hiddenToday = UsageHeatmapDay.grid(usage: usage, history: .empty, showsActivity: false, columnCount: 2, today: today).compactMap(\.self)- #expect(!hiddenToday.contains { $0.startDate == "2026-09-15" })}@Test func statusItemTerminalExpiresAtTenSecondsWhileCardKeepsHistory() {- let completion = ActivityCompletion(id: UUID(), isAnonymous: false, 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)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)@@ -72,27 +70,27 @@ struct DateAndPresentationTests {#expect(!snapshot.hasActiveTasks)}- @Test func waitingTaskTakesPriorityAndAnonymousTasksRemainVisible() {- let waiting = task(isAnonymous: true)- let running = task(isAnonymous: false)+ @Test func waitingTaskTakesPriorityOverRunningTask() {+ let waiting = task()+ let running = task()let snapshot = ActivitySnapshot(waitingTasks: [waiting], runningTasks: [running], recentCompletions: [], recentTerminations: [])#expect(snapshot.primaryActivity == .waiting(waiting))#expect(snapshot.activeCount == 2)#expect(snapshot.statusItemActivityExpiration == nil)}- private func task(isAnonymous: Bool) -> ActivityTaskSnapshot {+ private func task() -> ActivityTaskSnapshot {ActivityTaskSnapshot(- id: UUID(), isAnonymous: isAnonymous,- projectName: nil, modelName: nil, effort: nil, toolName: nil,+ id: UUID(),+ projectName: nil, modelName: nil, effort: nil,startedAt: TestFixtures.now, stateChangedAt: TestFixtures.now,- showsPreciseDuration: !isAnonymous, activeSubagentCount: nil+ activeSubagentCount: nil)}@Test(arguments: [false, true])func accountFailureKeepsLiveTaskIcon(waiting: Bool) {- let task = task(isAnonymous: false)+ let task = task()let activity = ActivitySnapshot(waitingTasks: waiting ? [task] : [], runningTasks: waiting ? [] : [task],recentCompletions: [], recentTerminations: []diff --git a/CodexBarTests/Presentation/TaskGlowPreviewTests.swift b/CodexBarTests/Presentation/TaskGlowPreviewTests.swiftindex aa1c84c..e19e0e8 100644--- a/CodexBarTests/Presentation/TaskGlowPreviewTests.swift+++ b/CodexBarTests/Presentation/TaskGlowPreviewTests.swift@@ -84,7 +84,7 @@ struct TaskGlowPreviewTests {state.refresh(now: time(10), terminalDuration: 15)state.suspend(now: time(10.1))let termination = ActivityTermination(- id: UUID(), isAnonymous: false, projectName: nil, modelName: nil,+ id: UUID(), projectName: nil, modelName: nil,effort: nil, terminatedAt: time(10.2), duration: 60)let snapshot = ActivitySnapshot(@@ -221,7 +221,7 @@ struct TaskGlowPreviewTests {private func completed(at seconds: TimeInterval) -> ActivitySnapshot {let completion = ActivityCompletion(- id: UUID(), isAnonymous: false, projectName: nil, modelName: nil,+ id: UUID(), projectName: nil, modelName: nil,effort: nil, completedAt: time(seconds), duration: 60)return ActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])@@ -229,9 +229,9 @@ struct TaskGlowPreviewTests {private func active(waiting: Bool = false) -> ActivitySnapshot {let task = ActivityTaskSnapshot(- id: UUID(), isAnonymous: false, projectName: nil,- modelName: nil, effort: nil, toolName: nil, startedAt: now,- stateChangedAt: now, showsPreciseDuration: true, activeSubagentCount: nil+ id: UUID(), projectName: nil,+ modelName: nil, effort: nil, startedAt: now,+ stateChangedAt: now, activeSubagentCount: nil)return ActivitySnapshot(waitingTasks: waiting ? [task] : [], runningTasks: waiting ? [] : [task], recentCompletions: [], recentTerminations: []diff --git a/CodexBarTests/Presentation/TaskGlowTests.swift b/CodexBarTests/Presentation/TaskGlowTests.swiftindex f4f5188..da81194 100644--- a/CodexBarTests/Presentation/TaskGlowTests.swift+++ b/CodexBarTests/Presentation/TaskGlowTests.swift@@ -202,9 +202,9 @@ struct TaskGlowTests {@Test func concurrentTaskCompletionStillShowsBrieflyThenRestoresRunning() throws {var presentation = TaskGlowPresentationState()let running = ActivityTaskSnapshot(- id: UUID(), isAnonymous: false, projectName: nil,- modelName: nil, effort: nil, toolName: nil, startedAt: TestFixtures.now,- stateChangedAt: TestFixtures.now, showsPreciseDuration: true, activeSubagentCount: nil+ id: UUID(), projectName: nil,+ modelName: nil, effort: nil, startedAt: TestFixtures.now,+ stateChangedAt: TestFixtures.now, activeSubagentCount: nil)let snapshot = ActivitySnapshot(waitingTasks: [], runningTasks: [running],@@ -224,7 +224,7 @@ struct TaskGlowTests {private func completedSnapshot() -> ActivitySnapshot {let completion = ActivityCompletion(- id: UUID(), isAnonymous: false, projectName: nil, modelName: nil,+ id: UUID(), projectName: nil, modelName: nil,effort: nil, completedAt: TestFixtures.now, duration: 60)return ActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])diff --git a/CodexBarTests/Settings/GlobalHotKeySettingsTests.swift b/CodexBarTests/Settings/GlobalHotKeySettingsTests.swiftnew file mode 100644index 0000000..f98879a--- /dev/null+++ b/CodexBarTests/Settings/GlobalHotKeySettingsTests.swift@@ -0,0 +1,61 @@+import Carbon.HIToolbox+import Combine+import Testing++struct GlobalHotKeySettingsTests {+ @Test func registrationFailurePreservesPublishedAndStoredShortcut() throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let settings = GlobalHotKeySettings(defaults: preferences.defaults)+ let previous = settings.shortcut+ let replacement = GlobalHotKeyShortcut(keyCode: UInt32(kVK_ANSI_R), modifiers: UInt32(cmdKey | shiftKey), keyLabel: "R")+ var active = previous+ settings.configureRegistration { shortcut in+ if shortcut == replacement {+ return "conflict"+ }+ active = shortcut+ return nil+ }+ settings.setShortcut(replacement)+ #expect(settings.shortcut == previous)+ #expect(active == previous)+ #expect(settings.errorMessage == "conflict")+ #expect(GlobalHotKeySettings(defaults: preferences.defaults).shortcut == previous)+ }++ @Test func successfulRegistrationPrecedesPublicationAndPersists() throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let settings = GlobalHotKeySettings(defaults: preferences.defaults)+ let replacement = GlobalHotKeyShortcut(keyCode: UInt32(kVK_ANSI_R), modifiers: UInt32(cmdKey | shiftKey), keyLabel: "R")+ var active = settings.shortcut+ settings.configureRegistration { shortcut in+ active = shortcut+ return nil+ }+ let observer = settings.$shortcut.sink { shortcut in+ #expect(active == shortcut)+ }+ defer { observer.cancel() }+ settings.setShortcut(replacement)+ #expect(settings.shortcut == replacement)+ #expect(GlobalHotKeySettings(defaults: preferences.defaults).shortcut == replacement)+ settings.clearShortcut()+ #expect(active == nil)+ #expect(GlobalHotKeySettings(defaults: preferences.defaults).shortcut == nil)+ settings.restoreDefaultShortcut()+ #expect(active == .default)+ #expect(GlobalHotKeySettings(defaults: preferences.defaults).shortcut == .default)+ }++ @Test func startupConflictPreservesPreferenceAndError() throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let settings = GlobalHotKeySettings(defaults: preferences.defaults)+ settings.configureRegistration { _ in "conflict" }+ #expect(settings.shortcut == .default)+ #expect(settings.errorMessage == "conflict")+ #expect(GlobalHotKeySettings(defaults: preferences.defaults).shortcut == .default)+ }+}diff --git a/CodexBarTests/Settings/LoginItemSettingsTests.swift b/CodexBarTests/Settings/LoginItemSettingsTests.swiftnew file mode 100644index 0000000..3c43cf4--- /dev/null+++ b/CodexBarTests/Settings/LoginItemSettingsTests.swift@@ -0,0 +1,94 @@+import ServiceManagement+import Testing++struct LoginItemSettingsTests {+ @Test(arguments: [SMAppService.Status.enabled, .requiresApproval, .notRegistered])+ func successfulRegistrationUsesActualAuthorization(_ result: SMAppService.Status) {+ var status: SMAppService.Status = .notRegistered+ let settings = LoginItemSettings(+ readStatus: { status },+ register: { status = result },+ unregister: { status = .notRegistered }+ )+ settings.setEnabled(true)+ #expect(settings.isEnabled == (result == .enabled))+ #expect(settings.requiresApproval == (result == .requiresApproval))+ #expect(settings.errorMessage == nil)+ settings.setEnabled(false)+ #expect(!settings.isEnabled)+ #expect(!settings.requiresApproval)+ }++ @Test(arguments: [false, true])+ func failedChangeUsesSystemState(_ enabled: Bool) {+ enum Failure: Error { case rejected }+ let status: SMAppService.Status = enabled ? .notRegistered : .enabled+ let settings = LoginItemSettings(+ readStatus: { status },+ register: { throw Failure.rejected },+ unregister: { throw Failure.rejected }+ )+ settings.refresh()++ settings.setEnabled(enabled)++ #expect(settings.isEnabled == !enabled)+ #expect(settings.errorMessage != nil)+ }++ @Test func refreshFollowsExternalChangesAndDoesNotTreatApprovalAsEnabled() {+ var status: SMAppService.Status = .notRegistered+ let settings = LoginItemSettings(+ readStatus: { status },+ register: { Issue.record("Refresh must not register the login item") },+ unregister: { Issue.record("Refresh must not unregister the login item") }+ )++ for state: SMAppService.Status in [.notRegistered, .enabled, .requiresApproval, .enabled, .notFound] {+ status = state+ settings.refresh()+ #expect(settings.isEnabled == (state == .enabled))+ #expect(settings.requiresApproval == (state == .requiresApproval))+ }+ }++ @Test func registrationErrorWhileAwaitingApprovalUsesAuthorizationStatus() {+ var status: SMAppService.Status = .notRegistered+ let settings = LoginItemSettings(+ readStatus: { status },+ register: {+ status = .requiresApproval+ throw NSError(domain: SMAppServiceErrorDomain, code: 1)+ },+ unregister: { status = .notRegistered }+ )++ settings.setEnabled(true)+ #expect(!settings.isEnabled)+ #expect(settings.requiresApproval)+ #expect(settings.errorMessage == nil)++ status = .enabled+ settings.refresh()+ #expect(settings.isEnabled)+ #expect(!settings.requiresApproval)+ #expect(settings.errorMessage == nil)+ }++ @Test func externalAuthorizationClearsPreviousRegistrationFailure() {+ var status: SMAppService.Status = .notRegistered+ let settings = LoginItemSettings(+ readStatus: { status },+ register: { throw NSError(domain: SMAppServiceErrorDomain, code: 1) },+ unregister: { status = .notRegistered }+ )++ settings.setEnabled(true)+ #expect(settings.errorMessage != nil)++ status = .enabled+ settings.refresh()+ #expect(settings.isEnabled)+ #expect(settings.errorMessage == nil)+ }+}diff --git a/CodexBarTests/Support/TestSupport.swift b/CodexBarTests/Support/TestSupport.swiftindex b6b2943..e302824 100644--- a/CodexBarTests/Support/TestSupport.swift+++ b/CodexBarTests/Support/TestSupport.swift@@ -11,31 +11,45 @@ nonisolated enum TestFixtures {static func event(_ name: ActivityEventKind = .turnStarted,at timestamp: Date = now,- session: String? = "session-a",+ thread: String? = "thread-a",turn: String? = "turn-a",agent: String? = nil,- origin: ActivityOrigin = .main,- reviewer: ApprovalReviewer? = .user+ origin: ActivityOrigin = .main) -> ActivityRecord {- ActivityRecord(+ var event = ActivityRecord(timestamp: timestamp, name: name.rawValue, origin: origin,- cwd: "/projects/example", tool: "exec_command", model: "gpt-5",- effort: "high", approvalReviewer: reviewer,- sessionID: session, turnID: turn, agentID: agent+ cwd: "/projects/example", toolName: "exec_command", model: "gpt-5",+ effort: "high",+ threadID: thread, turnID: turn, agentID: agent+ )+ if name == .turnStarted, let thread {+ event.context = ActivityContext(+ method: "turn/started", threadID: agent ?? thread, turnID: turn, turnStartedAt: timestamp+ )+ }+ return event+ }++ static func tokenTurn(+ id: String, rootID: String, startedAt: Date? = nil, updatedAt: Date, usage: TokenUsage? = nil+ ) -> TokenTurn {+ TokenTurn(+ id: id, rootID: rootID, startedAt: startedAt, updatedAt: updatedAt, usage: usage,+ checkpoint: usage.map { ["test-stream": TokenObservationCheckpoint(sequence: 1, usage: $0)] } ?? [:])}static func aggregate(generation: String? = "generation-a",- fresh: Bool = false,events: Int = 2,turns: Int = 1) -> ActivityAggregate {- var aggregate = ActivityAggregate(date: "2026-09-15", generationID: generation, generationStartedEmpty: fresh)+ var aggregate = ActivityAggregate(date: "2026-09-15", generationID: generation)+ aggregate.sourceCheckpoint = ActivitySourceCheckpoint(byteCount: UInt64(events + 1), digest: String(repeating: "a", count: 64))aggregate.eventCount = eventsaggregate.turnCount = turns- aggregate.sessionCount = 1- aggregate.sessionIDs = nil+ aggregate.threadCount = 1+ aggregate.threadIDs = nilaggregate.turnIDs = nilreturn aggregate}@@ -102,3 +116,37 @@ struct TestPreferences {defaults.removePersistentDomain(forName: suite)}}++nonisolated extension TestDirectory {+ @discardableResult+ func writeJournal(_ records: Data, to relativePath: String, generation: String? = nil) throws -> URL {+ let url = url.appendingPathComponent(relativePath)+ let date = url.deletingPathExtension().lastPathComponent+ let source = generation ?? (try? AppServerEventJournal.header(at: url).generationID) ?? UUID().uuidString.lowercased()+ let header = AppServerEventJournal.Header(version: 1, date: date, generationID: source)+ return try write(JSONLines.stableEncoder.encode(header) + Data([10]) + records, to: relativePath)+ }++ func activityAggregate(date: String, generation: String = "source", events: Int = 1) throws -> ActivityAggregate {+ let path = "Events/\(date).jsonl"+ let url = url.appendingPathComponent(path)+ if !FileManager.default.fileExists(atPath: url.path) {+ try writeJournal(Data(), to: path, generation: generation)+ }+ var aggregate = ActivityAggregate(date: date, generationID: generation)+ aggregate.eventCount = events+ aggregate.sourceCheckpoint = try ActivitySourceCheckpoint.read(at: url, byteCount: HistoryStorage.fileSize(at: url))+ return aggregate+ }+}++/// 测试夹具按采集器的原始记录与缓存聚合两个步骤写入+extension TokenHistoryStore {+ func recordObservations(_ observations: [TokenObservation], now: Date = Date()) throws -> [TokenTurn] {+ _ = try refresh(now: now)+ for observation in observations {+ try appendObservation(observation, now: now)+ }+ return try refresh(now: now)+ }+}diff --git a/CodexBarTests/Sync/SyncRecoveryTests.swift b/CodexBarTests/Sync/SyncRecoveryTests.swiftindex c8114f5..1347963 100644--- a/CodexBarTests/Sync/SyncRecoveryTests.swift+++ b/CodexBarTests/Sync/SyncRecoveryTests.swift@@ -4,28 +4,86 @@ import Foundationimport Testingstruct SyncRecoveryTests {+ @Test func conflictingTokenRootCannotOverwriteRemoteOrProduceCompleteTotals() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = SyncDatabaseFixture()+ let local = Self.turn(0)+ var remote = local.pseudonymized(salt: Self.salt)+ remote.rootID = TokenTurn.identifier(thread: "other-root", turn: "other-turn")+ let record = CKRecord(recordType: TokenSync.recordType, recordID: TokenSync.recordID(remote.id, zoneID: Self.zone))+ TokenSync.apply(remote, to: record)+ await database.storeRecord(record)+ let service = TokenSync(database: database, directoryURL: directory.url, isEnabled: { true })+ await #expect(throws: TokenCacheError.self) {+ try await service.synchronize(local: [local], accountScopedDeviceID: "device", salt: Self.salt, zoneID: Self.zone)+ }+ #expect(await database.savedTypes.isEmpty)+ let records = try await database.records(for: [record.recordID], desiredKeys: nil)+ let saved = try #require(try records[record.recordID]?.get())+ #expect(try TokenSync.turn(from: saved)?.rootID == remote.rootID)+ await #expect(throws: TokenCacheError.self) { try await service.snapshot(local: [local], accountScopedDeviceID: "device") }+ }++ @Test func expiredTokenCacheStaysBoundedWhenCloudDeletionFailsAndRetries() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = SyncDatabaseFixture()+ let expiredAt = HistoryStorage.retentionCutoffDate().addingTimeInterval(-86400)+ var expiredIDs: [CKRecord.ID] = []+ for index in 1 ... 2 {+ var turn = Self.turn(index).pseudonymized(salt: Self.salt)+ turn.updatedAt = expiredAt+ let record = CKRecord(recordType: TokenSync.recordType, recordID: TokenSync.recordID(turn.id, zoneID: Self.zone))+ TokenSync.apply(turn, to: record)+ await database.storeRecord(record)+ expiredIDs.append(record.recordID)+ }+ await database.failNextDeletion()+ let service = TokenSync(database: database, directoryURL: directory.url, isEnabled: { true })+ await #expect(throws: (any Error).self) {+ try await service.synchronize(local: [Self.turn(0)], accountScopedDeviceID: "device", salt: Self.salt, zoneID: Self.zone)+ }+ #expect(try Self.cachedTurnCount(in: directory.url) == 1)+ let reopened = TokenSync(database: database, directoryURL: directory.url, isEnabled: { true })+ try await reopened.synchronize(local: [Self.turn(0)], accountScopedDeviceID: "device", salt: Self.salt, zoneID: Self.zone)+ #expect(try Self.cachedTurnCount(in: directory.url) == 1)+ let remaining = try await database.records(for: expiredIDs, desiredKeys: nil)+ for id in expiredIDs {+ #expect(throws: (any Error).self) { try remaining[id]?.get() }+ }+ }+@Test func previousEncodingHashConvergesWithoutRepeatedUploads() async throws {let directory = try TestDirectory()defer { try? directory.remove() }let database = SyncDatabaseFixture()let date = HistoryStorage.dateKey(for: Date())- let local = try TestFixtures.decode(ActivityAggregate.self, """- {"date":"\(date)","generationID":"source","eventCount":1}- """)- let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ let local = try directory.activityAggregate(date: date)+ let service = SyncService(+ database: database,+ directoryURL: directory.url,+ activityEventsDirectoryURL: directory.url.appendingPathComponent("Events"),+ isEnabled: { true }+ )_ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)let store = ActivitySyncStore(directoryURL: directory.url)var state = store.loadState()let currentHash = try #require(state.hashByDate[date])let previousBytes = Data(("""- {"date":"\(date)","generationID":"source","eventCount":1,"sessionCount":null,"turnCount":null,"projectCounts":{},"modelCounts":{}}+ {"date":"\(date)","generationID":"source","eventCount":1,"threadCount":null,"turnCount":null,"projectCounts":{},"modelCounts":{}}""" + "\n").utf8)let previousHash = TokenTurn.hexString(SHA256.hash(data: previousBytes))#expect(previousHash != currentHash)state.hashByDate[date] = previousHashtry store.saveState(state)- let restarted = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ let restarted = SyncService(+ database: database,+ directoryURL: directory.url,+ activityEventsDirectoryURL: directory.url.appendingPathComponent("Events"),+ isEnabled: { true }+ )_ = await restarted.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)#expect(store.loadState().hashByDate[date] == currentHash)#expect(await database.activityRecords().count == 1)@@ -45,19 +103,76 @@ struct SyncRecoveryTests {let directory = try TestDirectory()defer { try? directory.remove() }let database = SyncDatabaseFixture()- let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ let service = SyncService(+ database: database,+ directoryURL: directory.url,+ activityEventsDirectoryURL: directory.url.appendingPathComponent("Events"),+ isEnabled: { true }+ )_ = await service.synchronizeIfEnabled(localAggregates: [], trigger: .manual)let url = directory.url.appendingPathComponent("Activity/cache.json")var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])json["cursor"] = Data("broken cursor".utf8).base64EncodedString()try JSONSerialization.data(withJSONObject: json).write(to: url)let queriesBefore = await database.queryCount+ let changesBefore = await database.changesSinceNil.count_ = await service.synchronizeIfEnabled(localAggregates: [], localTokenTurns: [Self.turn(0)], trigger: .manual)- #expect(await database.queryCount > queriesBefore)+ #expect(await database.queryCount == queriesBefore)+ #expect(await database.changesSinceNil.count > changesBefore)+ #expect(await database.changesSinceNil[changesBefore])#expect(await database.savedTypes.contains(TokenSync.recordType))#expect(try ActivitySyncStore(directoryURL: directory.url).load().cursor == nil)}+ @Test(arguments: [false, true])+ func activityRebuildCommitsOnlyAfterAllPagesSucceed(failSecondPage: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = SyncDatabaseFixture()+ let service = SyncService(+ database: database,+ directoryURL: directory.url,+ activityEventsDirectoryURL: directory.url.appendingPathComponent("Events"),+ isEnabled: { true }+ )+ _ = await service.synchronizeIfEnabled(localAggregates: [], trigger: .manual)+ let store = ActivitySyncStore(directoryURL: directory.url)+ let date = HistoryStorage.dateKey(for: Date())+ let daily = try directory.activityAggregate(date: date).syncedAggregate+ let generation = try #require(daily.generationID)+ let stale = try ActivitySyncRecord(deviceID: "stale", daily: daily, recordName: "stale_\(date)_\(generation)")+ try store.saveFetchedRecords([stale], cursor: nil)+ let url = directory.url.appendingPathComponent("Activity/cache.json")+ let original = try Data(contentsOf: url)+ let remote = CKRecord(recordType: "Activity", recordID: CKRecord.ID(recordName: "remote_\(date)_\(generation)", zoneID: Self.zone))+ ActivityRecordCodec.apply(daily, deviceID: "remote", to: remote)+ remote["updatedAt"] = Date(timeIntervalSince1970: Date().timeIntervalSince1970.rounded(.down)) as CKRecordValue+ let deleted = CKRecord(recordType: "Activity", recordID: CKRecord.ID(recordName: "deleted_\(date)_\(generation)", zoneID: Self.zone))+ ActivityRecordCodec.apply(daily, deviceID: "deleted", to: deleted)+ let metadata = CKRecord(recordType: "Metadata", recordID: CKRecord.ID(recordName: "ignored", zoneID: Self.zone))+ let first = SyncChanges(+ records: [remote.recordID: .success(remote), deleted.recordID: .success(deleted), metadata.recordID: .success(metadata)],+ deletions: [], token: nil, moreComing: true+ )+ let last = SyncChanges(records: [:], deletions: [(deleted.recordID, "Activity")], token: nil, moreComing: false)+ // 同步在上传前后各拉取一次, 两次都要独立得到完整结果+ await database.setChangesPages(failSecondPage+ ? [.success(first), .failure(CKError(.networkFailure))]+ : [.success(first), .success(last), .success(first), .success(last)])+ let queriesBefore = await database.queryCount+ let result = await service.synchronizeIfEnabled(localAggregates: [], trigger: .manual)+ #expect(await database.queryCount == queriesBefore)+ #expect(await database.remainingChangesPages == 0)+ if failSecondPage {+ #expect(try Data(contentsOf: url) == original)+ #expect(result.records == [stale])+ } else {+ let expected = try #require(try ActivityRecordCodec.remoteDailyRecord(from: remote))+ #expect(result.records == [expected])+ #expect(try store.load().records == [expected])+ }+ }+@Test(arguments: [false, true]) func damagedTokenCacheOrCursorRebuilds(cursorOnly: Bool) async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -93,8 +208,13 @@ struct SyncRecoveryTests {@Test(arguments: [false, true]) func activityFailureOnlyStopsTokensForSharedErrors(shared: Bool) async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let database = SyncDatabaseFixture(queryError: shared ? .networkFailure : .invalidArguments)- let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ let database = SyncDatabaseFixture(nextChangesError: shared ? .networkFailure : .invalidArguments)+ let service = SyncService(+ database: database,+ directoryURL: directory.url,+ activityEventsDirectoryURL: directory.url.appendingPathComponent("Events"),+ isEnabled: { true }+ )_ = await service.synchronizeIfEnabled(localAggregates: [], localTokenTurns: [Self.turn(0)], trigger: .manual)#expect(await database.savedTypes.contains(TokenSync.recordType) == !shared)}@@ -120,13 +240,14 @@ struct SyncRecoveryTests {let directory = try TestDirectory()defer { try? directory.remove() }let dates = (0 ..< 30).map { HistoryStorage.dateKey(for: Date().addingTimeInterval(Double(-$0) * 86400)) }- let aggregates = dates.map { date in- var value = ActivityAggregate(date: date, generationID: "source", generationStartedEmpty: true)- value.eventCount = 1- return value- }+ let aggregates = try dates.map { try directory.activityAggregate(date: $0) }let database = SyncDatabaseFixture(failingDate: dates[0])- let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ let service = SyncService(+ database: database,+ directoryURL: directory.url,+ activityEventsDirectoryURL: directory.url.appendingPathComponent("Events"),+ isEnabled: { true }+ )_ = await service.synchronizeIfEnabled(localAggregates: aggregates, localTokenTurns: [Self.turn(0)], trigger: .manual)#expect(ActivitySyncStore(directoryURL: directory.url).loadState().hashByDate.count == 29)#expect(await database.savedTypes.filter { $0 == "Activity" }.count == 29)@@ -241,41 +362,38 @@ struct SyncRecoveryTests {#expect(try Data(contentsOf: url) == original)}- @Test func activityUsesOneIdentityAndPreservesMoreCompleteRemoteCounts() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let database = SyncDatabaseFixture()- let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })- var local = ActivityAggregate(date: HistoryStorage.dateKey(for: Date()), generationID: "source", generationStartedEmpty: true)- local.eventCount = 5- _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)- let records = await database.activityRecords()- let remote = try #require(records.first)- let deviceID = try #require(remote["deviceID"] as? String)- let identity = "\(deviceID)_\(local.date)_source"- #expect(records.count == 1)- #expect(remote.recordID.recordName == identity)- #expect(await database.requestedIDs.filter { $0.recordName != "accountSalt" }.map(\.recordName) == [identity])-- local.eventCount = 2- _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)- #expect(await database.activityRecords().first?["eventCount"] as? Int == 5)+ @Test func sameSourceRecalculationCanReduceCountsWithoutDeletingRecord() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { try? fixture.directory.remove() }+ let before = try #require(await fixture.database.activityRecords().first)+ let result = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)+ let after = try #require(await fixture.database.activityRecords().first)+ #expect(before.recordID == after.recordID)+ #expect(before["eventCount"] as? Int == 9)+ #expect(after["eventCount"] as? Int == 1)+ #expect(!result.summary.isSyncPending)+ #expect(await fixture.database.deletedIDs.isEmpty)}@Test func missingLocalGenerationFailsBeforeReplacingRemoteRecords() async throws {let directory = try TestDirectory()defer { try? directory.remove() }let database = SyncDatabaseFixture()- let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })- var local = ActivityAggregate(date: HistoryStorage.dateKey(for: Date()), generationID: "source", generationStartedEmpty: true)+ let service = SyncService(+ database: database,+ directoryURL: directory.url,+ activityEventsDirectoryURL: directory.url.appendingPathComponent("Events"),+ isEnabled: { true }+ )+ var local = try directory.activityAggregate(date: HistoryStorage.dateKey(for: Date()))local.eventCount = 5_ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)let before = await database.activityRecords().map(\.recordID)local.generationID = nil- let result = await service.synchronizeIfEnabled(localAggregates: [local], replacements: [local], trigger: .manual)+ let result = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)#expect(await database.deletedIDs.isEmpty)#expect(await database.activityRecords().map(\.recordID) == before)- #expect(result.completedReplacements.isEmpty)+ #expect(result.records.count == before.count)}@Test func invalidGenerationDuringCursorBaselineStopsActivityUpload() async throws {@@ -286,8 +404,13 @@ struct SyncRecoveryTests {invalid["deviceID"] = "device" as CKRecordValueinvalid["date"] = HistoryStorage.dateKey(for: Date()) as CKRecordValueawait database.injectChangesRecord(invalid)- let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })- var local = ActivityAggregate(date: HistoryStorage.dateKey(for: Date()), generationID: "source", generationStartedEmpty: true)+ let service = SyncService(+ database: database,+ directoryURL: directory.url,+ activityEventsDirectoryURL: directory.url.appendingPathComponent("Events"),+ isEnabled: { true }+ )+ var local = try directory.activityAggregate(date: HistoryStorage.dateKey(for: Date()))local.eventCount = 1_ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)#expect(await database.activityRecords().isEmpty)@@ -295,26 +418,47 @@ struct SyncRecoveryTests {#expect(ActivitySyncStore(directoryURL: directory.url).loadState().hashByDate.isEmpty)}- @Test func replacingHistoryDeletesEveryPreviousGeneration() async throws {+ @Test func independentJournalSourcesAreNotDeletedByRebuild() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { try? fixture.directory.remove() }+ let previous = try #require(await fixture.database.activityRecords().first)+ let old = CKRecord(recordType: "Activity", recordID: CKRecord.ID(recordName: "older-source", zoneID: Self.zone))+ var independent = fixture.local.syncedAggregate+ independent.generationID = "independent"+ try ActivityRecordCodec.apply(independent, deviceID: #require(previous["deviceID"] as? String), to: old)+ await fixture.database.storeRecord(old)+ _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)+ #expect(await fixture.database.activityRecords().count == 2)+ #expect(await fixture.database.deletedIDs.isEmpty)+ }++ @Test func unknownCloudVersionPreservesCacheAndPreventsActivityUpload() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { try? fixture.directory.remove() }+ let cacheURL = HistoryStorage.syncDirectoryURL(in: fixture.directory.url).appendingPathComponent("Activity/cache.json")+ let before = try Data(contentsOf: cacheURL)+ let unsupported = CKRecord(recordType: "Activity", recordID: CKRecord.ID(recordName: "future", zoneID: Self.zone))+ unsupported["version"] = 999 as CKRecordValue+ await fixture.database.injectChangesRecord(unsupported)+ let result = await fixture.history.loadSnapshot(synchronize: true)+ #expect(!result.isActivityComplete)+ #expect(try Data(contentsOf: cacheURL) == before)+ #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 9)+ #expect(await fixture.database.deletedIDs.isEmpty)+ }++ @Test func unknownLocalSyncCacheFailsBeforeCloudMutation() async throws {let directory = try TestDirectory()defer { try? directory.remove() }+ let original = Data("{\"version\":999}".utf8)+ let url = try directory.write(original, to: "Activity/cache.json")let database = SyncDatabaseFixture()let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })- var local = ActivityAggregate(date: HistoryStorage.dateKey(for: Date()), generationID: "first", generationStartedEmpty: true)- local.eventCount = 1- _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)- local.generationID = "second"- _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)- let previous = await Set(database.activityRecords().map(\.recordID))- #expect(previous.count == 2)- local.generationID = "rebuilt"- local.generationStartedEmpty = false- let result = await service.synchronizeIfEnabled(localAggregates: [local], replacements: [local], trigger: .manual)- let current = await database.activityRecords()- #expect(current.count == 1)- #expect(current.first?["generationID"] as? String == "rebuilt")- #expect(await previous.isSubset(of: Set(database.deletedIDs)))- #expect(result.completedReplacements == [local.date: "rebuilt"])+ let result = await service.synchronizeIfEnabled(localAggregates: [], localTokenTurns: [Self.turn(0)], trigger: .manual)+ #expect(!result.isActivityComplete)+ #expect(await database.savedTypes.isEmpty)+ #expect(await database.deletedIDs.isEmpty)+ #expect(try Data(contentsOf: url) == original)}private static func cachedTurnCount(in directory: URL) throws -> Int {@@ -326,19 +470,22 @@ struct SyncRecoveryTests {private static func turn(_ index: Int) -> TokenTurn {let id = TokenTurn.identifier(thread: "test", turn: String(index))let now = Date().addingTimeInterval(Double(-index))- return TokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: .zero)+ return TestFixtures.tokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: .zero)}}private actor SyncDatabaseFixture: SyncDatabase {private var stored: [CKRecord.ID: CKRecord] = [:]- private let queryError: CKError.Code?+ private var nextChangesError: CKError.Code?private let changesFail: Boolprivate var changesRecordFails = false+ private var changesPages: [Result<SyncChanges, Error>] = []+private var failingName: String?private var failingDate: String?private let readFailure: Boolprivate(set) var queryCount = 0+ private(set) var changesSinceNil: [Bool] = []private(set) var savedTypes: [String] = []private(set) var requestedIDs: [CKRecord.ID] = []private(set) var deletedIDs: [CKRecord.ID] = []@@ -346,6 +493,14 @@ private actor SyncDatabaseFixture: SyncDatabase {private var deletionFails = falseprivate var activitySaveCallback: (@Sendable () -> Void)?+ var remainingChangesPages: Int {+ changesPages.count+ }++ func setChangesPages(_ pages: [Result<SyncChanges, Error>]) {+ changesPages = pages+ }+func failNextDeletion() {deletionFails = true}@@ -370,8 +525,8 @@ private actor SyncDatabaseFixture: SyncDatabase {changesRecord = Self.copy(record)}- init(queryError: CKError.Code? = nil, changesFail: Bool = false, failingName: String? = nil, failingDate: String? = nil, readFailure: Bool = false) {- self.queryError = queryError+ init(nextChangesError: CKError.Code? = nil, changesFail: Bool = false, failingName: String? = nil, failingDate: String? = nil, readFailure: Bool = false) {+ self.nextChangesError = nextChangesErrorself.changesFail = changesFailself.failingName = failingNameself.failingDate = failingDate@@ -402,7 +557,12 @@ private actor SyncDatabaseFixture: SyncDatabase {})}- func modifyRecords(saving records: [CKRecord], deleting ids: [CKRecord.ID], savePolicy _: CKModifyRecordsOperation.RecordSavePolicy, atomically _: Bool) async throws -> Modification {+ func modifyRecords(+ saving records: [CKRecord],+ deleting ids: [CKRecord.ID],+ savePolicy _: CKModifyRecordsOperation.RecordSavePolicy,+ atomically _: Bool+ ) async throws -> Modification {var saved: Records = [:]for record in records {if record.recordID.recordName == failingName || (failingDate != nil && record["date"] as? String == failingDate) {@@ -429,9 +589,6 @@ private actor SyncDatabaseFixture: SyncDatabase {func records(matching query: CKQuery, inZoneWith _: CKRecordZone.ID?, desiredKeys _: [CKRecord.FieldKey]?, resultsLimit _: Int) async throws -> QueryPage {queryCount += 1- if let queryError {- throw CKError(queryError)- }return (stored.values.filter { $0.recordType == query.recordType }.map { ($0.recordID, .success(Self.copy($0))) }, nil)}@@ -447,7 +604,15 @@ private actor SyncDatabaseFixture: SyncDatabase {(Dictionary(uniqueKeysWithValues: zones.map { ($0.zoneID, .success($0)) }), [:])}- func fetchChanges(inZoneWith _: CKRecordZone.ID, since _: CKServerChangeToken?, resultsLimit _: Int) async throws -> SyncChanges {+ func fetchChanges(inZoneWith _: CKRecordZone.ID, since token: CKServerChangeToken?, resultsLimit _: Int) async throws -> SyncChanges {+ changesSinceNil.append(token == nil)+ if !changesPages.isEmpty {+ return try changesPages.removeFirst().get()+ }+ if let error = nextChangesError {+ nextChangesError = nil+ throw CKError(error)+ }if changesFail {throw CKError(.networkFailure)}@@ -463,77 +628,59 @@ private actor SyncDatabaseFixture: SyncDatabase {}extension SyncRecoveryTests {- @Test func failedRebuildPreservesCloudUntilSuccessfulRetryAfterRestart() async throws {+ @Test func failedUploadPreservesRemoteAndRetriesAfterRestart() async throws {let fixture = try await HistoryRebuildFixture()defer { try? fixture.directory.remove() }- try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: fixture.eventURL.path)- defer { try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: fixture.eventURL.path) }- await #expect(throws: (any Error).self) {- try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)- }- #expect(await fixture.history.hasPendingReplacement(for: [fixture.date]))- let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: fixture.sync)- _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)+ let outcome = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)+ #expect(outcome.summary.isSyncPending)+ await fixture.database.failActivityUpload(on: fixture.date)+ _ = await fixture.history.loadSnapshot(synchronize: true)#expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 9)#expect(await fixture.database.deletedIDs.isEmpty)- try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: fixture.eventURL.path)+ await fixture.database.repair()+ let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: fixture.sync)_ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)#expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 1)- #expect(await !restarted.hasPendingReplacement(for: [fixture.date]))+ #expect(await fixture.database.activityRecords().count == 1)}- @Test func zeroRebuildSurvivesRestartAndClearsOldCloudContribution() async throws {+ @Test func repeatedRebuildKeepsSourceAndNeedsNoSeparateAcknowledgement() async throws {let fixture = try await HistoryRebuildFixture()defer { try? fixture.directory.remove() }- let now = Date()- let id = TokenTurn.identifier(thread: "zero", turn: "zero")- let token = TokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: .zero)- try AppServerEventRecord(token: token, recordedAt: now).jsonLineData().write(to: fixture.eventURL)- let outcome = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)- #expect(outcome.summary.eventCount == 0)- #expect(outcome.summary.isSyncReplacementPending)- let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: fixture.sync)- _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)+ _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)+ _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)+ let state = try HistoryStorage.loadMaintenanceState(in: fixture.directory.url)+ #expect(state.days[fixture.date]?.generationID == fixture.local.generationID)+ #expect(state.dirty.isEmpty)#expect(await fixture.database.activityRecords().count == 1)- #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 0)- #expect(await !restarted.hasPendingReplacement(for: [fixture.date]))- let snapshot = await restarted.loadSnapshot(synchronize: true)- #expect(snapshot.dailyMetrics.isEmpty)- }-- @Test func ordinaryTokenOnlyDateDoesNotUploadActivity() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let database = SyncDatabaseFixture()- let sync = SyncService(database: database, directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { true })- let tokens = TokenHistoryStore(directoryURL: directory.url)- let now = Date()- let id = TokenTurn.identifier(thread: "only", turn: "tokens")- try await directory.seedTokenSnapshots([TokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: .zero)], now: now)- let history = HistoryService(directoryURL: directory.url, syncService: sync, tokenHistory: tokens)- _ = await history.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)- #expect(await database.activityRecords().isEmpty)- #expect(await database.deletedIDs.isEmpty)+ #expect(await fixture.database.deletedIDs.isEmpty)}- @Test func uncommittedAggregateCannotAuthorizeCloudReplacement() async throws {+ @Test func unavailableSourceCannotOverwriteRemoteAndRecoversAfterRepair() async throws {let fixture = try await HistoryRebuildFixture()defer { try? fixture.directory.remove() }- var state = HistoryStorage.loadMaintenanceState(in: fixture.directory.url)- state.startNewGeneration(for: fixture.date, startedEmpty: false, fileIdentifier: state.days[fixture.date]?.fileIdentifier)- state.days[fixture.date]?.requiresCloudReplacement = true- try HistoryStorage.saveMaintenanceState(state, in: fixture.directory.url)- var aggregate = fixture.local- aggregate.generationID = state.days[fixture.date]?.generationID- aggregate.eventCount = 0- try ActivityAggregate.encodeJSONLines([aggregate]).write(to: HistoryStorage.dailyURL(in: fixture.directory.url))+ let original = try Data(contentsOf: fixture.eventURL)+ try Data("broken journal\n".utf8).write(to: fixture.eventURL)+ await #expect(throws: (any Error).self) {+ try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)+ }let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: fixture.sync)- _ = await restarted.loadSnapshot(synchronize: true)- #expect(await fixture.database.deletedIDs.isEmpty)+ _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)#expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 9)+ #expect(await fixture.database.deletedIDs.isEmpty)+ try original.write(to: fixture.eventURL)_ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)#expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 1)- #expect(await !restarted.hasPendingReplacement(for: [fixture.date]))+ }++ @Test func rewrittenPrefixCannotOverwriteRemoteEvenWithMoreEvents() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { try? fixture.directory.remove() }+ let event = TestFixtures.event(.toolStarted, at: Date(), turn: "different")+ try fixture.directory.writeJournal(AppServerEventRecord(activity: event).jsonLineData(), to: "Events/\(fixture.date).jsonl")+ _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)+ #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 9)+ #expect(await fixture.database.deletedIDs.isEmpty)}@Test func requestSaveFailureDoesNotModifyAggregateOrCloud() async throws {@@ -548,133 +695,44 @@ extension SyncRecoveryTests {try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)}#expect(try Data(contentsOf: aggregateURL) == original)- #expect(await !fixture.history.hasPendingReplacement(for: [fixture.date]))#expect(await fixture.database.deletedIDs.isEmpty)}- @Test(arguments: ["delete", "upload", "acknowledge"])- func interruptedReplacementRetriesAfterRestart(_ stage: String) async throws {- let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }- _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)- let stateDirectory = HistoryStorage.maintenanceURL(in: fixture.directory.url).deletingLastPathComponent()- defer { try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: stateDirectory.path) }- switch stage {- case "delete": await fixture.database.failNextDeletion()- case "upload": await fixture.database.failActivityUpload(on: fixture.date)- default:- await fixture.database.afterActivitySave {- try? FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: stateDirectory.path)- }- }- _ = await fixture.history.loadSnapshot(synchronize: true)- #expect(await fixture.history.hasPendingReplacement(for: [fixture.date]))- await fixture.database.repair()- try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: stateDirectory.path)- let sync = SyncService(database: fixture.database, directoryURL: HistoryStorage.syncDirectoryURL(in: fixture.directory.url), isEnabled: { true })- let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: sync)- _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)- #expect(await !restarted.hasPendingReplacement(for: [fixture.date]))- #expect(await fixture.database.activityRecords().count == 1)- #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 1)- }-- @Test func staleAcknowledgementCannotClearNewRebuildRequest() async throws {- let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }- _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)- let old = try #require(HistoryStorage.loadMaintenanceState(in: fixture.directory.url).days[fixture.date]?.generationID)- _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)- await fixture.history.acknowledgeReplacements([fixture.date: old])- #expect(await fixture.history.hasPendingReplacement(for: [fixture.date]))- _ = await fixture.history.loadSnapshot(synchronize: true)- #expect(await !fixture.history.hasPendingReplacement(for: [fixture.date]))- }-}--private struct HistoryRebuildFixture {- let directory: TestDirectory- let database: SyncDatabaseFixture- let sync: SyncService- let history: HistoryService- let date: String- let eventURL: URL- let local: ActivityAggregate-- init() async throws {- directory = try TestDirectory()- database = SyncDatabaseFixture()- sync = SyncService(database: database, directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { true })- history = HistoryService(directoryURL: directory.url, syncService: sync)- let now = Date()- date = HistoryStorage.dateKey(for: now)- eventURL = try directory.write(AppServerEventRecord(activity: TestFixtures.event(at: now), recordedAt: now).jsonLineData(), to: "Events/\(date).jsonl")- _ = await history.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)- local = try #require(JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: HistoryStorage.dailyURL(in: directory.url))).first)- var remote = local- remote.eventCount = 9- remote.generationStartedEmpty = true- _ = await sync.synchronizeIfEnabled(localAggregates: [remote], trigger: .manual)- }-}--extension SyncRecoveryTests {- @Test func partialReplacementAcknowledgesHealthyDatesAndPreservesOtherDevices() async throws {- let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }- let otherDate = HistoryStorage.dateKey(for: Date().addingTimeInterval(-86400))- let otherEvent = TestFixtures.event(at: Date().addingTimeInterval(-86400))- _ = try fixture.directory.write(AppServerEventRecord(activity: otherEvent).jsonLineData(), to: "Events/\(otherDate).jsonl")- let otherDevice = CKRecord(recordType: "Activity", recordID: CKRecord.ID(recordName: "other_\(fixture.date)_source", zoneID: Self.zone))- let contribution = SyncedActivity(date: fixture.date, generationID: "source", eventCount: 7, projectCounts: [:], modelCounts: [:])- ActivityRecordCodec.apply(contribution, deviceID: "other", to: otherDevice)- await fixture.database.storeRecord(otherDevice)- _ = try await fixture.history.rebuildData(for: [fixture.date, otherDate], synchronize: false)- await fixture.database.failActivityUpload(on: otherDate)- _ = await fixture.history.loadSnapshot(synchronize: true)- #expect(await !fixture.history.hasPendingReplacement(for: [fixture.date]))- #expect(await fixture.history.hasPendingReplacement(for: [otherDate]))- let records = await fixture.database.activityRecords()- #expect(records.first { $0["deviceID"] as? String == "other" }?["eventCount"] as? Int == 7)- #expect(await !fixture.database.deletedIDs.contains(otherDevice.recordID))- await fixture.database.repair()- _ = await fixture.history.loadSnapshot(synchronize: true)- #expect(await !fixture.history.hasPendingReplacement(for: [otherDate]))- }-- @Test func disabledSyncKeepsRebuildRequestForNextEnabledService() async throws {+ @Test func disabledSyncKeepsUpdatedAggregateForNextEnabledRun() async throws {let fixture = try await HistoryRebuildFixture()defer { try? fixture.directory.remove() }let disabled = SyncService(database: fixture.database, directoryURL: HistoryStorage.syncDirectoryURL(in: fixture.directory.url), isEnabled: { false })let history = HistoryService(directoryURL: fixture.directory.url, syncService: disabled)_ = try await history.rebuildData(for: [fixture.date], synchronize: true)- #expect(await history.hasPendingReplacement(for: [fixture.date]))- #expect(await fixture.database.deletedIDs.isEmpty)#expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 9)_ = await fixture.history.loadSnapshot(synchronize: true)- #expect(await !history.hasPendingReplacement(for: [fixture.date]))#expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 1)}-}-extension SyncRecoveryTests {- @Test func appendedEventsKeepReplacementGenerationAndAreIncludedInRetry() async throws {+ @Test func appendedEventsKeepGenerationAndExtendCheckpoint() async throws {let fixture = try await HistoryRebuildFixture()defer { try? fixture.directory.remove() }- _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)- let generation = HistoryStorage.loadMaintenanceState(in: fixture.directory.url).days[fixture.date]?.generationIDlet recorder = ActivityRecorder(directoryURL: fixture.directory.url)let event = ActivityRecord(- timestamp: Date(), name: ActivityEventKind.toolStarted.rawValue, origin: .main,- cwd: nil, tool: "exec_command", model: nil, effort: nil, approvalReviewer: nil,- sessionID: "session-a", turnID: "turn-a", agentID: nil, id: "appended-tool"+ timestamp: Date(),+ name: ActivityEventKind.toolStarted.rawValue,+ origin: .main,+ cwd: nil,+ toolName: "exec_command",+ model: nil,+ effort: nil,+ threadID: "thread-a",+ turnID: "turn-a",+ agentID: nil,+ id: "appended-tool")try await recorder.record(event: event)_ = await fixture.history.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)- #expect(await !fixture.history.hasPendingReplacement(for: [fixture.date]))let remote = try #require(await fixture.database.activityRecords().first)#expect(remote["eventCount"] as? Int == 2)- #expect(remote["generationID"] as? String == generation)+ #expect(remote["generationID"] as? String == fixture.local.generationID)+ let updated = try #require(try ActivityRecordCodec.remoteDailyRecord(from: remote))+ #expect(try #require(updated.daily.sourceCheckpoint).byteCount > #require(fixture.local.sourceCheckpoint).byteCount)}@Test func partialTokenFailureIsReportedWithoutClaimingWholeDaySuccess() async throws {@@ -707,23 +765,200 @@ extension SyncRecoveryTests {}}+private struct HistoryRebuildFixture {+ let directory: TestDirectory+ let database: SyncDatabaseFixture+ let sync: SyncService+ let history: HistoryService+ let date: String+ let eventURL: URL+ let local: ActivityAggregate++ init() async throws {+ directory = try TestDirectory()+ database = SyncDatabaseFixture()+ sync = SyncService(database: database, directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { true })+ history = HistoryService(directoryURL: directory.url, syncService: sync)+ let now = Date()+ date = HistoryStorage.dateKey(for: now)+ eventURL = try directory.writeJournal(AppServerEventRecord(activity: TestFixtures.event(at: now), recordedAt: now).jsonLineData(), to: "Events/\(date).jsonl")+ _ = await history.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ local = try #require(JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: HistoryStorage.dailyURL(in: directory.url))).first)+ var remote = local+ remote.eventCount = 9+ _ = await sync.synchronizeIfEnabled(localAggregates: [remote], trigger: .manual)+ #expect(await database.activityRecords().count == 1)+ }+}+extension SyncRecoveryTests {- @Test func corruptJournalCannotBecomeAuthoritativeZeroDuringRebuildOrRetry() async throws {+ @Test func rebuildUploadsAlgorithmVersionEvenWhenCountsAreUnchanged() async throws {let fixture = try await HistoryRebuildFixture()defer { try? fixture.directory.remove() }- let original = try Data(contentsOf: fixture.eventURL)- try Data("broken event\n".utf8).write(to: fixture.eventURL)- await #expect(throws: (any Error).self) {- try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)+ var previous = fixture.local+ previous.aggregationVersion = 1+ let boundary = try #require(previous.sourceCheckpoint?.byteCount)+ previous.sourceCheckpoint?.aggregationRanges = [.init(version: 1, end: boundary)]+ try previous.jsonLineData().write(to: HistoryStorage.dailyURL(in: fixture.directory.url))+ let remote = try #require(await fixture.database.activityRecords().first)+ try ActivityRecordCodec.apply(previous.syncedAggregate, deviceID: #require(remote["deviceID"] as? String), to: remote)+ _ = try await fixture.database.modifyRecords(saving: [remote], deleting: [], savePolicy: .ifServerRecordUnchanged, atomically: false)+ _ = await fixture.sync.synchronizeIfEnabled(localAggregates: [previous], trigger: .manual)+ let outcome = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)+ let updated = try #require(await fixture.database.activityRecords().first)+ #expect(updated["eventCount"] as? Int == previous.eventCount)+ #expect(updated["aggregationVersion"] as? Int == AggregationVersion.activity)+ #expect(!outcome.summary.isSyncPending)+ #expect(await fixture.database.activityRecords().count == 1)+ }+}++extension SyncRecoveryTests {+ @Test(arguments: [true, false])+ func recoveredTokensUseFreshCloudBaselineBeforeUploading(coversRemote: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let id = TokenTurn.identifier(thread: "thread", turn: "turn")+ let usage = TokenUsage(inputTokens: 10, cachedInputTokens: 0, cacheWriteInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0, totalTokens: 10)+ let observation = TokenObservation(+ turn: TokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now),+ rootStartedAt: now, streamID: "stream", sequence: 1, previous: .zero, current: usage+ )+ let store = TokenHistoryStore(directoryURL: directory.url)+ var old = try #require(try await store.recordObservations([observation], now: now).first)+ old.usage = TokenUsage(inputTokens: 12, cachedInputTokens: 0, cacheWriteInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0, totalTokens: 12)+ old.aggregationVersion = 1+ if !coversRemote {+ old.checkpoint = ["missing-stream": TokenObservationCheckpoint(sequence: 1, usage: usage)]}- let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: fixture.sync)- _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)- #expect(await fixture.database.deletedIDs.isEmpty)- #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 9)- #expect(await restarted.hasPendingReplacement(for: [fixture.date]))- try original.write(to: fixture.eventURL)- _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)- #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 1)- #expect(await !restarted.hasPendingReplacement(for: [fixture.date]))+ let salt = Data("account".utf8)+ let remote = old.pseudonymized(salt: salt)+ let record = CKRecord(recordType: TokenSync.recordType, recordID: CKRecord.ID(recordName: remote.id, zoneID: Self.zone))+ TokenSync.apply(remote, to: record)+ let database = SyncDatabaseFixture()+ await database.storeRecord(record)+ try FileManager.default.removeItem(at: directory.url.appendingPathComponent("Aggregates/tokens.json"))+ let recovered = try await store.refresh(now: now)+ let sync = TokenSync(database: database, directoryURL: directory.url.appendingPathComponent("Sync/Tokens"), isEnabled: { true })+ try await sync.synchronize(local: recovered, recoveredIDs: store.pendingRecoveryIDs(), accountScopedDeviceID: "device", salt: salt, zoneID: Self.zone)+ let saved = try #require(try await database.records(for: [record.recordID], desiredKeys: nil)[record.recordID]?.get())+ let updated = try #require(try TokenSync.turn(from: saved))+ if !coversRemote {+ #expect(updated == remote)+ #expect(await store.pendingRecoveryIDs().contains(id))+ return+ }+ #expect(updated.usage == usage)+ #expect(!updated.hasConflict)+ #expect(updated.aggregationVersion == AggregationVersion.tokens)+ #expect(updated.ancestorIDs.contains(old.generationID))+ let more = TokenUsage(inputTokens: 15, cachedInputTokens: 0, cacheWriteInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0, totalTokens: 15)+ let next = TokenObservation(+ turn: observation.turn.emptyTurn, rootStartedAt: now, streamID: "stream", sequence: 2,+ previous: usage, current: more+ )+ _ = try await store.recordObservations([next], now: now)+ let cloudBaseline = TokenHistoryBaseline(salt: salt, turns: [updated.id: updated])+ let reconciled = try #require(try await store.refresh(now: now, baseline: cloudBaseline).first)+ #expect(reconciled.usage == more)+ #expect(!reconciled.hasConflict)+ #expect(reconciled.ancestorIDs.contains(updated.generationID))+ #expect(await store.pendingRecoveryIDs().isEmpty)+ #expect(try await store.refresh(now: now, baseline: cloudBaseline).first?.generationID == reconciled.generationID)+ }++ @Test func remoteDateDoesNotHideMissingLocalContribution() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let date = HistoryStorage.dateKey(for: now)+ var remote = ActivityAggregate(date: date, generationID: "other-source")+ remote.turnCount = 8+ let record = try ActivitySyncRecord(+ deviceID: "other", daily: remote.syncedAggregate,+ recordName: ActivitySyncRecord.recordName(deviceID: "other", date: date, generation: "other-source")+ )+ let root = HistoryStorage.syncDirectoryURL(in: directory.url)+ try ActivitySyncStore(directoryURL: root).saveCachedRecords([record], state: SyncState(deviceID: "local"))+ var journal = AppServerEventJournal()+ try journal.append(AppServerEventRecord(activity: TestFixtures.event(at: now)), in: directory.url)+ let sync = SyncService(database: SyncDatabaseFixture(), directoryURL: root, isEnabled: { true })+ let history = HistoryService(directoryURL: directory.url, syncService: sync)+ let snapshot = await history.loadSnapshot()+ let day = UsageHeatmapDay.grid(usage: nil, history: snapshot, columnCount: 1, today: now).compactMap(\.self).first { $0.startDate == date }+ #expect(snapshot.unavailableActivityDates.contains(date))+ #expect(day?.history.turnCount == nil)+ }+}++extension SyncRecoveryTests {+ @Test(arguments: [true, false])+ func recoveringOneTaskDoesNotReplaceUnrecoverableCloudTask(hasLocalSnapshot: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ func counts(_ value: Int64) -> TokenUsage {+ TokenUsage(inputTokens: value, cachedInputTokens: 0, cacheWriteInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0, totalTokens: value)+ }+ func observation(_ name: String, sequence: Int64 = 1, previous: Int64 = 0, current: Int64) -> TokenObservation {+ let id = TokenTurn.identifier(thread: name, turn: "turn")+ return TokenObservation(+ turn: TokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now), rootStartedAt: now,+ streamID: name, sequence: sequence, previous: counts(previous), current: counts(current)+ )+ }+ let a = observation("a", current: 100)+ let b = observation("b", current: 200)+ var oldA = try a.applying(to: nil)+ oldA.usage = counts(120)+ let oldB = try b.applying(to: nil)+ let remoteA = oldA.pseudonymized(salt: Self.salt)+ let remoteB = oldB.pseudonymized(salt: Self.salt)+ let database = SyncDatabaseFixture()+ let aID = TokenSync.recordID(remoteA.id, zoneID: Self.zone)+ let bID = TokenSync.recordID(remoteB.id, zoneID: Self.zone)+ for turn in [remoteA, remoteB] {+ let record = CKRecord(recordType: TokenSync.recordType, recordID: TokenSync.recordID(turn.id, zoneID: Self.zone))+ TokenSync.apply(turn, to: record)+ await database.storeRecord(record)+ }+ let brokenB = observation("b", sequence: 3, previous: 250, current: 300)+ var data = try AppServerEventRecord(observation: a, recordedAt: now).jsonLineData()+ + AppServerEventRecord(observation: brokenB, recordedAt: now).jsonLineData()+ if hasLocalSnapshot {+ for turn in [oldA, oldB] {+ try data.append(AppServerEventRecord(token: turn, recordedAt: now).jsonLineData())+ }+ }+ try directory.writeJournal(data, to: "Events/\(HistoryStorage.dateKey(for: now)).jsonl")+ try directory.write("broken cache", to: "Aggregates/tokens.json")+ let store = TokenHistoryStore(directoryURL: directory.url)+ let recovered = try await store.refresh(now: now)+ #expect(recovered.first { $0.id == a.turn.id }?.usage == counts(100))+ #expect(recovered.first { $0.id == b.turn.id } == (hasLocalSnapshot ? oldB : nil))+ #expect(await store.pendingRecoveryIDs() == [a.turn.id])+ let sync = TokenSync(database: database, directoryURL: directory.url.appendingPathComponent("Sync/Tokens"), isEnabled: { true })+ try await sync.synchronize(local: recovered, recoveredIDs: store.pendingRecoveryIDs(), accountScopedDeviceID: "device", salt: Self.salt, zoneID: Self.zone)+ let saved = try await database.records(for: [aID, bID], desiredKeys: nil)+ let aRecord = try #require(try saved[aID]?.get())+ let bRecord = try #require(try saved[bID]?.get())+ let savedA = try #require(try TokenSync.turn(from: aRecord))+ let savedB = try #require(try TokenSync.turn(from: bRecord))+ #expect(savedA.usage == counts(100))+ #expect(!savedA.hasConflict)+ #expect(savedA.aggregationVersion == AggregationVersion.tokens)+ #expect(savedA.ancestorIDs.contains(oldA.generationID))+ #expect(savedB == remoteB)+ #expect(await database.savedTypes == [TokenSync.recordType])+ #expect(await database.deletedIDs.isEmpty)+ let baseline = try #require(await sync.recoveryBaseline(accountScopedDeviceID: "device"))+ let reopened = TokenHistoryStore(directoryURL: directory.url)+ let reconciled = try await reopened.refresh(now: now, baseline: baseline)+ try await sync.synchronize(local: reconciled, recoveredIDs: reopened.pendingRecoveryIDs(), accountScopedDeviceID: "device", salt: Self.salt, zoneID: Self.zone)+ #expect(await database.savedTypes == [TokenSync.recordType])+ #expect(await database.deletedIDs.isEmpty)+ let total = try await sync.snapshot(local: reconciled, accountScopedDeviceID: "device")+ #expect(total[HistoryStorage.dateKey(for: now)] == counts(300))}}diff --git a/CodexBarTests/Sync/ZoneRecoveryTests.swift b/CodexBarTests/Sync/ZoneRecoveryTests.swiftindex b037173..3edd20e 100644--- a/CodexBarTests/Sync/ZoneRecoveryTests.swift+++ b/CodexBarTests/Sync/ZoneRecoveryTests.swift@@ -15,7 +15,7 @@ struct ZoneRecoveryTests {_ = try directory.write("invalid activity cache", to: "Activity/cache.json")_ = try directory.write("invalid token cache", to: "Tokens/cache.json")let service = service(database, directory)- let snapshot = await service.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ let snapshot = try await service.synchronizeIfEnabled(localAggregates: [aggregate(0, directory: directory)], localTokenTurns: [turn(0)], trigger: .manual)#expect(snapshot.currentDeviceID != nil)#expect(await database.creations == 1)#expect(await database.recordCount("Activity") == 1)@@ -29,11 +29,25 @@ struct ZoneRecoveryTests {defer { try? directory.remove() }let database = ZoneDatabase()let service = service(database, directory)- _ = await service.synchronizeIfEnabled(localAggregates: [aggregate(0), aggregate(1)], localTokenTurns: [turn(0), turn(1)], trigger: .manual)+ _ = try await service.synchronizeIfEnabled(+ localAggregates: [aggregate(0, directory: directory), aggregate(1, directory: directory)],+ localTokenTurns: [turn(0), turn(1)],+ trigger: .manual+ )let previousID = ActivitySyncStore(directoryURL: directory.url).loadState().deviceID+ if point == .query {+ let store = ActivitySyncStore(directoryURL: directory.url)+ var state = store.loadState()+ state.lastPrunedDate = nil+ try store.saveState(state)+ }// 保留 salt 可以验证恢复不依赖设备 ID 碰巧变化await database.failOnce(at: point, wrapped: wrapped, preservingSalt: true)- let snapshot = await service.synchronizeIfEnabled(localAggregates: [aggregate(0, events: 3)], localTokenTurns: [turn(0, tokens: 3)], trigger: .manual)+ let snapshot = try await service.synchronizeIfEnabled(+ localAggregates: [aggregate(0, events: 3, directory: directory)],+ localTokenTurns: [turn(0, tokens: 3)],+ trigger: .manual+ )#expect(snapshot.currentDeviceID == previousID)#expect(await database.creations == 1)#expect(await database.recordCount("Activity") == 1)@@ -48,9 +62,13 @@ struct ZoneRecoveryTests {defer { try? directory.remove() }let database = ZoneDatabase()let service = service(database, directory)- let first = await service.synchronizeIfEnabled(localAggregates: [aggregate(0), aggregate(1)], localTokenTurns: [turn(0), turn(1)], trigger: .manual)+ let first = try await service.synchronizeIfEnabled(+ localAggregates: [aggregate(0, directory: directory), aggregate(1, directory: directory)],+ localTokenTurns: [turn(0), turn(1)],+ trigger: .manual+ )await database.recreateByPeer()- let second = await service.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ let second = try await service.synchronizeIfEnabled(localAggregates: [aggregate(0, directory: directory)], localTokenTurns: [turn(0)], trigger: .manual)#expect(first.currentDeviceID != second.currentDeviceID)#expect(second.currentDeviceID != nil)#expect(await database.creations == 0)@@ -66,7 +84,11 @@ struct ZoneRecoveryTests {defer { try? directory.remove() }let database = ZoneDatabase()let first = service(database, directory)- _ = await first.synchronizeIfEnabled(localAggregates: [aggregate(0), aggregate(1)], localTokenTurns: [turn(0), turn(1)], trigger: .manual)+ _ = try await first.synchronizeIfEnabled(+ localAggregates: [aggregate(0, directory: directory), aggregate(1, directory: directory)],+ localTokenTurns: [turn(0), turn(1)],+ trigger: .manual+ )let store = ActivitySyncStore(directoryURL: directory.url)var state = store.loadState()state.containerIdentifier = containerIdentifier@@ -80,7 +102,7 @@ struct ZoneRecoveryTests {#expect(snapshot.records.isEmpty)#expect(await next.tokenRecoveryBaselineIfEnabled() == nil)#expect(store.loadState().hashByDate.isEmpty)- let synced = await next.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ let synced = try await next.synchronizeIfEnabled(localAggregates: [aggregate(0, directory: directory)], localTokenTurns: [turn(0)], trigger: .manual)#expect(synced.currentDeviceID != nil)#expect(synced.records.count == 1)#expect(try cachedTokenCount(directory) == 1)@@ -95,13 +117,13 @@ struct ZoneRecoveryTests {let database = ZoneDatabase()await database.failOnce(at: .query, repeats: true)let service = service(database, directory)- let failed = await service.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ let failed = try await service.synchronizeIfEnabled(localAggregates: [aggregate(0, directory: directory)], localTokenTurns: [turn(0)], trigger: .manual)#expect(await database.queryCount == 2)#expect(await database.creations == 1)#expect(failed.currentDeviceID == nil)#expect(ActivitySyncStore(directoryURL: directory.url).loadState().hashByDate.isEmpty)await database.repair()- let recovered = await service.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ let recovered = try await service.synchronizeIfEnabled(localAggregates: [aggregate(0, directory: directory)], localTokenTurns: [turn(0)], trigger: .manual)#expect(recovered.currentDeviceID != nil)#expect(await database.creations == 2)#expect(await database.recordCount("Activity") == 1)@@ -114,11 +136,11 @@ struct ZoneRecoveryTests {defer { try? directory.remove() }let database = ZoneDatabase()let service = service(database, directory)- _ = await service.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ _ = try await service.synchronizeIfEnabled(localAggregates: [aggregate(0, directory: directory)], localTokenTurns: [turn(0)], trigger: .manual)let before = ActivitySyncStore(directoryURL: directory.url).loadState()let tokens = try Data(contentsOf: directory.url.appendingPathComponent("Tokens/cache.json"))- await database.rejectQueries(code)- _ = await service.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ await database.rejectChanges(code)+ _ = try await service.synchronizeIfEnabled(localAggregates: [aggregate(0, directory: directory)], localTokenTurns: [turn(0)], trigger: .manual)#expect(await database.creations == 0)#expect(ActivitySyncStore(directoryURL: directory.url).loadState() == before)#expect(try Data(contentsOf: directory.url.appendingPathComponent("Tokens/cache.json")) == tokens)@@ -130,8 +152,13 @@ struct ZoneRecoveryTests {let enabled = Mutex(true)let database = ZoneDatabase(onFailure: { enabled.withLock { $0 = false } })await database.removeZone()- let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { enabled.withLock { $0 } })- _ = await service.synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ let service = SyncService(+ database: database,+ directoryURL: directory.url,+ activityEventsDirectoryURL: directory.url.appendingPathComponent("Events"),+ isEnabled: { enabled.withLock { $0 } }+ )+ _ = try await service.synchronizeIfEnabled(localAggregates: [aggregate(0, directory: directory)], localTokenTurns: [turn(0)], trigger: .manual)#expect(await database.creations == 0)#expect(await database.recordCount("Metadata") == 0)}@@ -142,15 +169,19 @@ struct ZoneRecoveryTests {let database = ZoneDatabase()await database.removeZone()let store = ActivitySyncStore(directoryURL: directory.url)- try store.saveState(SyncState(deviceID: "stale", hashByDate: [aggregate(0).date: "stale"]))+ try store.saveState(SyncState(deviceID: "stale", hashByDate: [aggregate(0, directory: directory).date: "stale"]))let blocked = directory.url.appendingPathComponent("Tokens/store.lock")try FileManager.default.createDirectory(at: blocked, withIntermediateDirectories: true)- _ = await service(database, directory).synchronizeIfEnabled(localAggregates: [aggregate(0)], trigger: .manual)+ _ = try await service(database, directory).synchronizeIfEnabled(localAggregates: [aggregate(0, directory: directory)], trigger: .manual)#expect(store.loadState().deviceID == nil)#expect(store.loadState().hashByDate.isEmpty)#expect(await database.creations == 0)try FileManager.default.removeItem(at: blocked)- let snapshot = await service(database, directory).synchronizeIfEnabled(localAggregates: [aggregate(0)], localTokenTurns: [turn(0)], trigger: .manual)+ let snapshot = try await service(database, directory).synchronizeIfEnabled(+ localAggregates: [aggregate(0, directory: directory)],+ localTokenTurns: [turn(0)],+ trigger: .manual+ )#expect(snapshot.currentDeviceID != nil)#expect(await database.creations == 1)#expect(await database.recordCount("Activity") == 1)@@ -171,13 +202,11 @@ struct ZoneRecoveryTests {}private func service(_ database: ZoneDatabase, _ directory: TestDirectory) -> SyncService {- SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ SyncService(database: database, directoryURL: directory.url, activityEventsDirectoryURL: directory.url.appendingPathComponent("Events"), isEnabled: { true })}- private func aggregate(_ index: Int, events: Int = 1) -> ActivityAggregate {- var value = ActivityAggregate(date: HistoryStorage.dateKey(for: Date().addingTimeInterval(Double(-index) * 86400)), generationID: "source", generationStartedEmpty: true)- value.eventCount = events- return value+ private func aggregate(_ index: Int, events: Int = 1, directory: TestDirectory) throws -> ActivityAggregate {+ try directory.activityAggregate(date: HistoryStorage.dateKey(for: Date().addingTimeInterval(Double(-index) * 86400)), events: events)}private func turn(_ index: Int, tokens: Int = 1) -> TokenTurn {@@ -187,7 +216,7 @@ struct ZoneRecoveryTests {inputTokens: Int64(tokens), cachedInputTokens: 0, cacheWriteInputTokens: 0,outputTokens: 0, reasoningOutputTokens: 0, totalTokens: Int64(tokens))- return TokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: usage)+ return TestFixtures.tokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: usage)}private func cachedTokenCount(_ directory: TestDirectory) throws -> Int {@@ -207,7 +236,7 @@ private actor ZoneDatabase: SyncDatabase {private var repeats = falseprivate var savedMetadata: CKRecord?private var preservesSalt = false- private var queryError: CKError.Code?+ private var changesError: CKError.Code?private let onFailure: @Sendable () -> Voidprivate(set) var creations = 0private(set) var queryCount = 0@@ -238,8 +267,8 @@ private actor ZoneDatabase: SyncDatabase {failurePoint = nil}- func rejectQueries(_ code: CKError.Code) {- queryError = code+ func rejectChanges(_ code: CKError.Code) {+ changesError = code}func recreateByPeer() {@@ -293,7 +322,12 @@ private actor ZoneDatabase: SyncDatabase {})}- func modifyRecords(saving records: [CKRecord], deleting ids: [CKRecord.ID], savePolicy _: CKModifyRecordsOperation.RecordSavePolicy, atomically _: Bool) async throws -> Modification {+ func modifyRecords(+ saving records: [CKRecord],+ deleting ids: [CKRecord.ID],+ savePolicy _: CKModifyRecordsOperation.RecordSavePolicy,+ atomically _: Bool+ ) async throws -> Modification {if let record = records.first {let point: Point? = record.recordType == "Activity" ? .activityUpload : record.recordType == "Tokens" ? .tokenUpload : niltry check(point, zone: record.recordID.zoneID, record: record.recordID)@@ -310,9 +344,6 @@ private actor ZoneDatabase: SyncDatabase {func records(matching query: CKQuery, inZoneWith zone: CKRecordZone.ID?, desiredKeys _: [CKRecord.FieldKey]?, resultsLimit _: Int) async throws -> QueryPage {queryCount += 1- if let queryError {- throw CKError(queryError)- }try check(.query, zone: zone ?? CKRecordZone.default().zoneID)return (stored.values.filter { $0.recordType == query.recordType }.map { ($0.recordID, .success(copy($0))) }, nil)}@@ -322,6 +353,9 @@ private actor ZoneDatabase: SyncDatabase {}func fetchChanges(inZoneWith zone: CKRecordZone.ID, since _: CKServerChangeToken?, resultsLimit _: Int) async throws -> SyncChanges {+ if let changesError {+ throw CKError(changesError)+ }try check(.changes, zone: zone)return SyncChanges(records: stored.mapValues { .success(copy($0)) }, deletions: [], token: nil, moreComing: false)}diff --git a/Config/CloudKit.ckdb b/Config/CloudKit.ckdbindex 1de36b6..b0e133a 100644--- a/Config/CloudKit.ckdb+++ b/Config/CloudKit.ckdb@@ -1,98 +1,84 @@DEFINE SCHEMARECORD TYPE Activity (- deviceID STRING QUERYABLE SORTABLE,- date STRING SORTABLE,- generationID STRING,-- eventCount INT64,- sessionCount INT64,- turnCount INT64,-- sessionStartedCount INT64,- sessionEndedCount INT64,- turnStartedCount INT64,- turnCompletedCount INT64,- turnAbortedCount INT64,- toolStartedCount INT64,- toolCompletedCount INT64,+ "___createTime" TIMESTAMP,+ "___createdBy" REFERENCE,+ "___etag" STRING,+ "___modTime" TIMESTAMP,+ "___modifiedBy" REFERENCE,+ "___recordID" REFERENCE QUERYABLE,+ aggregationVersion INT64,approvalRequestedCount INT64,- subagentStartedCount INT64,- subagentEndedCount INT64,- compactionStartedCount INT64,compactionCompletedCount INT64,-+ compactionStartedCount INT64,+ date STRING SORTABLE,+ deviceID STRING QUERYABLE SORTABLE,+ eventCount INT64,+ generationID STRING,modelCounts BYTES,projectCounts BYTES,-+ sourceCheckpoint BYTES,+ subagentEndedCount INT64,+ subagentStartedCount INT64,+ threadCount INT64,+ toolCompletedCount INT64,+ toolStartedCount INT64,+ turnAbortedCount INT64,+ turnCompletedCount INT64,+ turnCount INT64,+ turnStartedCount INT64,updatedAt TIMESTAMP,version INT64,-- "___recordID" REFERENCE QUERYABLE,- "___createTime" TIMESTAMP,- "___createdBy" REFERENCE,- "___modTime" TIMESTAMP,- "___modifiedBy" REFERENCE,- "___etag" STRING,-GRANT WRITE TO "_creator",GRANT CREATE TO "_icloud",GRANT READ TO "_world");RECORD TYPE Metadata (- salt BYTES QUERYABLE SORTABLE,- version INT64 QUERYABLE SORTABLE,-- "___recordID" REFERENCE QUERYABLE,"___createTime" TIMESTAMP,"___createdBy" REFERENCE,+ "___etag" STRING,"___modTime" TIMESTAMP,"___modifiedBy" REFERENCE,- "___etag" STRING,-+ "___recordID" REFERENCE QUERYABLE,+ salt BYTES QUERYABLE SORTABLE,+ version INT64 QUERYABLE SORTABLE,GRANT WRITE TO "_creator",GRANT CREATE TO "_icloud",GRANT READ TO "_world");RECORD TYPE Tokens (- rootID STRING,- startedAt TIMESTAMP,-- generationID STRING,- ancestorIDs LIST<STRING>,- checkpoint BYTES,- hasConflict INT64,-- usage BYTES,-- rebuiltAt TIMESTAMP,- updatedAt TIMESTAMP,- version INT64,-- "___recordID" REFERENCE QUERYABLE,- "___createTime" TIMESTAMP,- "___createdBy" REFERENCE,- "___modTime" TIMESTAMP,- "___modifiedBy" REFERENCE,- "___etag" STRING,-+ "___createTime" TIMESTAMP,+ "___createdBy" REFERENCE,+ "___etag" STRING,+ "___modTime" TIMESTAMP,+ "___modifiedBy" REFERENCE,+ "___recordID" REFERENCE QUERYABLE,+ aggregationVersion INT64,+ ancestorIDs LIST<STRING>,+ checkpoint BYTES,+ generationID STRING,+ hasConflict INT64,+ rebuiltAt TIMESTAMP,+ rootID STRING,+ startedAt TIMESTAMP,+ updatedAt TIMESTAMP,+ usage BYTES,+ version INT64,GRANT WRITE TO "_creator",GRANT CREATE TO "_icloud",GRANT READ TO "_world");RECORD TYPE Users (- roles LIST<INT64>,-- "___recordID" REFERENCE,"___createTime" TIMESTAMP,"___createdBy" REFERENCE,+ "___etag" STRING,"___modTime" TIMESTAMP,"___modifiedBy" REFERENCE,- "___etag" STRING,-+ "___recordID" REFERENCE,+ roles LIST<INT64>,GRANT WRITE TO "_creator",GRANT READ TO "_world");diff --git a/Images/icon.png b/Images/icon.pngindex caf129b..5eba19a 100644Binary files a/Images/icon.png and b/Images/icon.png differdiff --git a/Protocol.en.md b/Protocol.en.mdnew file mode 100644index 0000000..510d83e--- /dev/null+++ b/Protocol.en.md@@ -0,0 +1,92 @@+# app-server API Inventory++Applicable version Codex `0.162.0`++## Outgoing Calls++### Requests++| API | Purpose |+| --- | --- |+| `initialize` | Initialize the connection and retrieve the server version |+| `account/read` | Read account information and refresh authentication |+| `account/rateLimits/read` | Read rate limits, credit balance, and reset credits |+| `account/usage/read` | Read account usage summaries and daily token usage |+| `account/rateLimitResetCredit/consume` | Consume a rate limit reset credit |+| `config/read` | Read Codex TUI notification settings |+| `config/batchWrite` | Update Codex TUI notification settings |+| `thread/loaded/list` | List loaded threads |+| `thread/read` | Read thread information and status |+| `thread/resume` | Subscribe to messages from a loaded thread |+| `thread/turns/list` | Read a thread's turns, statuses, root turn IDs, and sub-agent creation information |++### Notifications++| API | Purpose |+| --- | --- |+| `initialized` | Notify the server that initialization is complete |++## Incoming Messages++### Account Notifications++| API | Purpose |+| --- | --- |+| `account/updated` | Receive account change notifications |+| `account/rateLimits/updated` | Receive rate limit change notifications |++### Thread, Turn, and Item Notifications++| API | Purpose |+| --- | --- |+| `thread/started` | Receive thread start notifications |+| `thread/status/changed` | Receive thread status changes |+| `thread/tokenUsage/updated` | Receive thread token usage updates |+| `turn/started` | Receive turn start notifications |+| `turn/completed` | Receive turn end notifications |+| `item/started` | Receive item start notifications |+| `item/completed` | Receive item end notifications |++### Progress Notifications++| API | Purpose |+| --- | --- |+| `item/agentMessage/delta` | Track response output progress |+| `item/reasoning/textDelta` | Track reasoning text output progress |+| `item/reasoning/summaryTextDelta` | Track reasoning summary output progress |+| `item/commandExecution/outputDelta` | Track command output progress |++### Status and Presentation Notifications++| API | Purpose |+| --- | --- |+| `turn/plan/updated` | Receive plan progress updates |+| `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 |+| `model/safetyBuffering/updated` | Receive safety buffering display status |+| `hook/started` | Observe the start of hook execution |+| `hook/completed` | Receive hook execution results |+| `serverRequest/resolved` | Observe that a server request has been resolved |+| `error` | Receive error notifications |+| `warning` | Log server warnings |++### Server Requests++| API | Purpose |+| --- | --- |+| `item/commandExecution/requestApproval` | Observe command execution approval requests |+| `item/fileChange/requestApproval` | Observe file change approval requests |+| `item/permissions/requestApproval` | Observe permission approval requests |+| `mcpServer/elicitation/request` | Observe MCP elicitation requests |++## Root Turn and Sub-Agent Fields Used++| API | Field | Purpose |+| --- | --- | --- |+| `thread/turns/list` | Request parameter `itemsView` | Use `notLoaded` to read turn information and `full` to read items containing sub-agent creation information |+| `thread/turns/list`, `turn/started`, `turn/completed` | `Turn.rootTurnId` | Read the ID of the root turn in the chain of work leading to the current turn |+| `thread/turns/list`, `item/started`, `item/completed` | `subAgentActivity.model` | Read the resolved model at sub-agent creation when `kind` is `started` |+| `thread/turns/list`, `item/started`, `item/completed` | `subAgentActivity.reasoningEffort` | Read the resolved reasoning effort at sub-agent creation when `kind` is `started` |diff --git a/Protocol.md b/Protocol.mdnew file mode 100644index 0000000..2cd6fca--- /dev/null+++ b/Protocol.md@@ -0,0 +1,92 @@+# app-server 接口清单++适用版本 Codex `0.162.0`++## 主动调用++### 请求++| 接口 | 作用 |+| --- | --- |+| `initialize` | 初始化连接,获取服务端版本 |+| `account/read` | 读取账户信息、刷新认证 |+| `account/rateLimits/read` | 读取额度、余额和重置凭证 |+| `account/usage/read` | 读取账户用量汇总和每日 Token 用量 |+| `account/rateLimitResetCredit/consume` | 消费额度重置凭证 |+| `config/read` | 读取 Codex TUI 通知配置 |+| `config/batchWrite` | 修改 Codex TUI 通知配置 |+| `thread/loaded/list` | 获取已加载线程列表 |+| `thread/read` | 读取线程信息和状态 |+| `thread/resume` | 订阅已加载线程的消息 |+| `thread/turns/list` | 获取线程的轮次列表、状态、根轮次标识和子 Agent 创建信息 |++### 通知++| 接口 | 作用 |+| --- | --- |+| `initialized` | 告知服务端初始化已完成 |++## 被动接收++### 账户通知++| 接口 | 作用 |+| --- | --- |+| `account/updated` | 接收账户变化通知 |+| `account/rateLimits/updated` | 接收额度变化通知 |++### 线程、轮次和 item 通知++| 接口 | 作用 |+| --- | --- |+| `thread/started` | 接收线程启动通知 |+| `thread/status/changed` | 接收线程状态变化 |+| `thread/tokenUsage/updated` | 接收线程 Token 用量更新 |+| `turn/started` | 接收轮次开始通知 |+| `turn/completed` | 接收轮次结束通知 |+| `item/started` | 接收执行项开始通知 |+| `item/completed` | 接收执行项结束通知 |++### 进展通知++| 接口 | 作用 |+| --- | --- |+| `item/agentMessage/delta` | 感知回答输出进展 |+| `item/reasoning/textDelta` | 感知思考文本输出进展 |+| `item/reasoning/summaryTextDelta` | 感知思考摘要输出进展 |+| `item/commandExecution/outputDelta` | 感知命令输出进展 |++### 状态与展示通知++| 接口 | 作用 |+| --- | --- |+| `turn/plan/updated` | 接收计划进度更新 |+| `turn/diff/updated` | 感知代码差异更新 |+| `model/rerouted` | 接收模型切换信息 |+| `model/verification` | 感知模型验证需求 |+| `modelProvider/authRecoveryStarted` | 感知认证恢复开始 |+| `modelProvider/authRecoveryCompleted` | 感知认证恢复结束 |+| `model/safetyBuffering/updated` | 接收安全缓冲展示状态 |+| `hook/started` | 感知 hook 执行开始 |+| `hook/completed` | 接收 hook 执行结果 |+| `serverRequest/resolved` | 感知服务端请求已处理完毕 |+| `error` | 接收错误通知 |+| `warning` | 记录服务端警告 |++### 服务端请求++| 接口 | 作用 |+| --- | --- |+| `item/commandExecution/requestApproval` | 观察命令执行审批请求 |+| `item/fileChange/requestApproval` | 观察文件修改审批请求 |+| `item/permissions/requestApproval` | 观察权限审批请求 |+| `mcpServer/elicitation/request` | 观察 MCP 交互请求 |++## 使用的根轮次和子 Agent 字段++| 接口 | 字段 | 作用 |+| --- | --- | --- |+| `thread/turns/list` | 请求参数 `itemsView` | 使用 `notLoaded` 读取轮次信息,使用 `full` 读取包含子 Agent 创建信息的执行项 |+| `thread/turns/list`、`turn/started`、`turn/completed` | `Turn.rootTurnId` | 获取当前轮次所属工作链的根轮次 ID |+| `thread/turns/list`、`item/started`、`item/completed` | `subAgentActivity.model` | 获取 `kind` 为 `started` 时子 Agent 创建所用的实际模型 |+| `thread/turns/list`、`item/started`、`item/completed` | `subAgentActivity.reasoningEffort` | 获取 `kind` 为 `started` 时子 Agent 创建所用的实际推理强度 |diff --git a/README.en.md b/README.en.mdindex 8d0842b..3244f7f 100644--- a/README.en.md+++ b/README.en.md@@ -14,7 +14,7 @@[](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)+[Features](#features) | [Installation](#installation) | [Privacy](#privacy) | [Runtime Architecture](https://codexbar.zabrian.app/architecture) | [Performance Report](https://codexbar.zabrian.app/performance) | [Protocol](Protocol.en.md)<img src="Images/preview.gif" width="640" alt="CodexBar preview">@@ -56,11 +56,6 @@ CodexBar is a menu bar app for macOS that displays your Codex account informatio- Optionally stay awake while waiting for approval or keep the display on as well- Set a keep-awake time limit, low-battery protection, and stalled task protection-### Make it your own--- Customize main panel section order, visibility, and animations-- Use a global keyboard shortcut, launch at login, and automatic update checks-- Choose Simplified Chinese or English and browse logs for troubleshooting## Installation@@ -78,7 +73,7 @@ Download the latest version from [GitHub Releases](https://github.com/bob-zebedy- 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 background service version `0.157.0` or later+- Codex background service version `0.162.0` or later- Cross-device sync requires an available iCloud account on the Mac## Privacydiff --git a/README.md b/README.mdindex 63ff585..654c2eb 100644--- a/README.md+++ b/README.md@@ -14,7 +14,7 @@[](https://github.com/bob-zebedy/CodexBar/releases)[](LICENSE)-[功能](#功能) | [安装](#安装) | [快速开始](#快速开始) | [隐私](#隐私) | [运行架构](https://codexbar.zabrian.app/architecture) | [性能报告](https://codexbar.zabrian.app/performance)+[功能](#功能) | [安装](#安装) | [快速开始](#快速开始) | [隐私](#隐私) | [运行架构](https://codexbar.zabrian.app/architecture) | [性能报告](https://codexbar.zabrian.app/performance) | [协议](Protocol.md)<img src="Images/preview.gif" width="640" alt="CodexBar 预览">@@ -56,11 +56,6 @@ CodexBar 是 macOS 的菜单栏 App,用于集中展示 Codex 账户、额度- 可在等待审批时继续保持唤醒,或同时保持屏幕常亮- 支持防睡眠时限、低电量保护和异常会话保护-### 按你的习惯使用--- 自定义主面板区域的顺序、显隐和动画效果-- 支持全局快捷键、开机启动和自动检查更新-- 提供简体中文、英文界面,以及便于排查问题的日志查看功能## 安装@@ -78,8 +73,8 @@ brew install --cask bob-zebedy/tap/codexbar- macOS 15.0 或更高版本- 已安装并登录 [Codex CLI](https://github.com/openai/codex) 或安装了内置 Codex 的 ChatGPT App 或 Codex App-- Codex 后台服务版本为 `0.157.0` 或更高版本-- 使用跨设备同步时,Mac 需要登录可用的 iCloud 账户+- Codex 后台服务版本为 `0.162.0` 或更高版本+- 使用跨设备同步时,需要登录可用的 iCloud 账户## 隐私diff --git a/Resources/CodexBar Helper.icon/Assets/CodexBar Helper.png b/Resources/CodexBar Helper.icon/Assets/CodexBar Helper.pngnew file mode 100644index 0000000..0d3ce5fBinary files /dev/null and b/Resources/CodexBar Helper.icon/Assets/CodexBar Helper.png differdiff --git a/Resources/CodexBar Helper.icon/icon.json b/Resources/CodexBar Helper.icon/icon.jsonnew file mode 100644index 0000000..f1b3634--- /dev/null+++ b/Resources/CodexBar Helper.icon/icon.json@@ -0,0 +1,26 @@+{+ "fill" : "automatic",+ "groups" : [+ {+ "layers" : [+ {+ "image-name" : "CodexBar Helper.png",+ "name" : "CodexBar Helper"+ }+ ],+ "shadow" : {+ "kind" : "neutral",+ "opacity" : 0.5+ },+ "translucency" : {+ "enabled" : true,+ "value" : 0.3+ }+ }+ ],+ "supported-platforms" : {+ "squares" : [+ "macOS"+ ]+ }+}\ No newline at end of filediff --git a/Resources/CodexBar Helper.pxd b/Resources/CodexBar Helper.pxdnew file mode 100644index 0000000..c1cec62Binary files /dev/null and b/Resources/CodexBar Helper.pxd differdiff --git a/Resources/CodexBar.icon/Assets/CodexBar.png b/Resources/CodexBar.icon/Assets/CodexBar.pngnew file mode 100644index 0000000..28f6cccBinary files /dev/null and b/Resources/CodexBar.icon/Assets/CodexBar.png differdiff --git a/Resources/CodexBar.icon/icon.json b/Resources/CodexBar.icon/icon.jsonnew file mode 100644index 0000000..3302c09--- /dev/null+++ b/Resources/CodexBar.icon/icon.json@@ -0,0 +1,28 @@+{+ "color-space-for-untagged-svg-colors" : "display-p3",+ "fill" : "automatic",+ "groups" : [+ {+ "layers" : [+ {+ "glass" : true,+ "image-name" : "CodexBar.png",+ "name" : "CodexBar"+ }+ ],+ "shadow" : {+ "kind" : "neutral",+ "opacity" : 0.5+ },+ "translucency" : {+ "enabled" : true,+ "value" : 0.3+ }+ }+ ],+ "supported-platforms" : {+ "squares" : [+ "macOS"+ ]+ }+}\ No newline at end of filediff --git a/Resources/CodexBar.pxd b/Resources/CodexBar.pxdnew file mode 100644index 0000000..a12573dBinary files /dev/null and b/Resources/CodexBar.pxd differdiff --git a/Scripts/cleanup.swift b/Scripts/cleanup.swiftindex 9570af5..22f4dc4 100755--- a/Scripts/cleanup.swift+++ b/Scripts/cleanup.swift@@ -42,6 +42,15 @@ private enum CleanupBuildConfiguration: String, CaseIterable {case release = "Release"case debug = "Debug"+ var managerBundleName: String {+ switch self {+ case .release:+ "CodexBar Helper.app"+ case .debug:+ "CodexBar Helper Debug.app"+ }+ }+var bundleIdentifier: String {switch self {case .release:@@ -98,6 +107,7 @@ private struct CleanupOptions {var signingIdentity = ProcessInfo.processInfo.environment["CODEXBAR_CLEANUP_SIGN_IDENTITY"]?? "Apple Development"var isCheckOnly = false+ var usesLegacyRegistration = falsefunc includes(_ configuration: CleanupBuildConfiguration) -> Bool {selectedConfigurations.isEmpty || selectedConfigurations.contains(configuration)@@ -146,7 +156,8 @@ private final class KeepAliveCleanupCommand {cleanupExecutableURL: cleanupExecutableURL,temporaryRoot: temporaryRoot,signingIdentity: options.signingIdentity,- isCheckOnly: options.isCheckOnly+ isCheckOnly: options.isCheckOnly,+ usesLegacyRegistration: options.usesLegacyRegistration)}}@@ -160,6 +171,8 @@ private final class KeepAliveCleanupCommand {options.selectedConfigurations.insert(.release)case "--debug":options.selectedConfigurations.insert(.debug)+ case "--legacy":+ options.usesLegacyRegistration = truecase "--check":options.isCheckOnly = truecase "-h", "--help":@@ -184,6 +197,7 @@ private final class KeepAliveCleanupCommand {--release 只移除 Release Helper--debug 只移除 Debug Helper--check 只检查目标+ --legacy 清理主 App 直接注册的旧 Helper-h, --help 显示帮助不指定 --release 或 --debug 时同时处理两个目标@@ -258,7 +272,7 @@ private final class KeepAliveCleanupCommand {"/usr/bin/xcodebuild",["-project", projectURL.appending(path: "CodexBar.xcodeproj").path,- "-scheme", "CodexBar",+ "-target", "CodexBar","-configuration", configuration.rawValue,"-destination", "generic/platform=macOS","-showBuildSettings"@@ -285,13 +299,13 @@ private final class KeepAliveCleanupCommand {}private func resolveHelperSourceURL(for target: CleanupTarget) throws -> URL {- let bundledHelperURL = helperURL(in: target.appURL)+ let bundledHelperURL = helperURL(in: target.appURL, configuration: target.buildConfiguration)if fileManager.isExecutableFile(atPath: bundledHelperURL.path) {return bundledHelperURL}let builtAppURL = try resolveBuiltAppURL(configuration: target.buildConfiguration)- let builtHelperURL = helperURL(in: builtAppURL)+ let builtHelperURL = helperURL(in: builtAppURL, configuration: target.buildConfiguration)guard fileManager.isExecutableFile(atPath: builtHelperURL.path) else {throw CleanupError.message("CodexBarHelper 未构建, configuration=\(target.buildConfiguration.rawValue)"@@ -300,8 +314,10 @@ private final class KeepAliveCleanupCommand {return builtHelperURL}- private func helperURL(in appURL: URL) -> URL {- appURL.appending(path: "Contents/Resources/CodexBarHelper")+ private func helperURL(in appURL: URL, configuration: CleanupBuildConfiguration) -> URL {+ let nested = appURL.appending(path: "Contents/Library/LoginItems/\(configuration.managerBundleName)/Contents/Resources/CodexBarHelper")+ return fileManager.isExecutableFile(atPath: nested.path)+ ? nested : appURL.appending(path: "Contents/Resources/CodexBarHelper")}private func runningTargets(in targets: [CleanupTarget]) -> [CleanupTarget] {@@ -318,7 +334,8 @@ private final class KeepAliveCleanupCommand {cleanupExecutableURL: URL,temporaryRoot: URL,signingIdentity: String,- isCheckOnly: Bool+ isCheckOnly: Bool,+ usesLegacyRegistration: Bool) throws {let teamIdentifier = try signingTeamIdentifier(for: target.appURL)let cleanupAppURL = temporaryRoot@@ -350,7 +367,9 @@ private final class KeepAliveCleanupCommand {let destinationPlistURL = daemonsURL.appending(path: target.plistName)let destinationHelperURL = resourcesURL.appending(path: "CodexBarHelper")let destinationExecutableURL = macOSURL.appending(path: "KeepAliveCleanup")- try fileManager.copyItem(at: sourcePlistURL, to: destinationPlistURL)+ var daemonPlist = try propertyListDictionary(at: sourcePlistURL)+ daemonPlist["AssociatedBundleIdentifiers"] = [target.bundleIdentifier]+ try writePropertyList(daemonPlist, to: destinationPlistURL)try fileManager.copyItem(at: helperSourceURL, to: destinationHelperURL)try fileManager.copyItem(at: cleanupExecutableURL, to: destinationExecutableURL)try fileManager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: destinationHelperURL.path)@@ -389,12 +408,24 @@ private final class KeepAliveCleanupCommand {failureReason: "验证 App 签名失败")+ let managerURL = target.appURL.appending(path: "Contents/Library/LoginItems/\(target.buildConfiguration.managerBundleName)")+ let usesManager = !usesLegacyRegistration && fileManager.fileExists(atPath: managerURL.path)+ if usesManager {+ try runCodeSigningChecked(["--verify", "--deep", "--strict", managerURL.path], failureReason: "验证管理 App 签名失败")+ guard try signingTeamIdentifier(for: managerURL) == teamIdentifier else {+ throw CleanupError.codeSigningValidationFailed("管理 App 与主 App 的 Team ID 不匹配")+ }+ }if isCheckOnly {print("目标验证完成: bundle=\(target.bundleIdentifier)")return}- try runChecked(destinationExecutableURL.path, ["--unregister-child", target.plistName])+ var childArguments = ["--unregister-child", target.plistName]+ if usesManager {+ childArguments.append(managerURL.appending(path: "Contents/MacOS/CodexBarHelperManager").path)+ }+ try runChecked(destinationExecutableURL.path, childArguments)for key in ["KeepAlive.isEnabled", "AutoReset.isEnabled"] {try runChecked("/usr/bin/defaults",@@ -536,7 +567,35 @@ private final class KeepAliveCleanupCommand {}}-private func runUnregisterChild(plistName: String) -> Never {+private func runUnregisterChild(plistName: String, managerExecutable: String?) -> Never {+ if let managerExecutable {+ let label = String(plistName.dropLast(".plist".count))+ guard cancelAutoResetWakeScheduleBeforeUnregister(serviceLabel: label) else {+ Darwin.exit(EXIT_FAILURE)+ }+ let process = Process()+ let pipe = Pipe()+ process.executableURL = URL(fileURLWithPath: managerExecutable)+ process.arguments = ["unregister"]+ process.standardOutput = pipe+ do {+ try process.run()+ let data = pipe.fileHandleForReading.readDataToEndOfFile()+ process.waitUntilExit()+ let reply = try JSONSerialization.jsonObject(with: data) as? [String: Any]+ guard process.terminationStatus == 0,+ reply?["errorDomain"] == nil,+ let status = reply?["status"] as? Int,+ status == SMAppService.Status.notRegistered.rawValue || status == SMAppService.Status.notFound.rawValue else {+ throw CleanupError.message("管理 App 未确认 Helper 已注销")+ }+ print("后台服务已注销: service=\(plistName)")+ Darwin.exit(EXIT_SUCCESS)+ } catch {+ FileHandle.standardError.write(Data("Helper 注销失败: \(error.localizedDescription)\n".utf8))+ Darwin.exit(EXIT_FAILURE)+ }+ }let service = SMAppService.daemon(plistName: plistName)switch service.status {case .enabled, .requiresApproval:@@ -649,13 +708,13 @@ private func reportWakeScheduleCancellationFailure(owner: String, detail: Stringlet arguments = Array(CommandLine.arguments.dropFirst())if arguments.first == "--unregister-child" {- guard arguments.count == 2 else {+ guard arguments.count == 2 || arguments.count == 3 else {FileHandle.standardError.write(- Data("内部参数无效: expected=2, actual=\(arguments.count)\n".utf8)+ Data("内部参数无效: expected=2 or 3, actual=\(arguments.count)\n".utf8))Darwin.exit(EXIT_FAILURE)}- runUnregisterChild(plistName: arguments[1])+ runUnregisterChild(plistName: arguments[1], managerExecutable: arguments.count == 3 ? arguments[2] : nil)}do {diff --git a/Scripts/lib/validate.sh b/Scripts/lib/validate.shindex f6c7678..f2e1b39 100644--- a/Scripts/lib/validate.sh+++ b/Scripts/lib/validate.sh@@ -1,12 +1,78 @@#!/usr/bin/env bash+validate_helper_manager_distribution() {+ local manager_path="$1"+ local architectures="$2"+ local architecture=""+ local details=""+ local authority=""+ local timestamp=""+ local entitlements=""+ local debugger_entitlement=""++ for architecture in ${architectures}; do+ if ! details="$(codesign --display --verbose=4 --arch "${architecture}" "${manager_path}" 2>&1)"; then+ validation_fail "Helper manager ${architecture} signature metadata" "codesign could not read the signature" "${details}"+ return 1+ fi+ if ! printf '%s\n' "${details}" | grep -Eq '^CodeDirectory .*flags=.*\(runtime\)'; then+ validation_fail "Helper manager ${architecture} Hardened Runtime" "The CodeDirectory does not contain the runtime flag"+ return 1+ fi+ validation_pass "Helper manager ${architecture} Hardened Runtime"++ if [[ "${CONFIGURATION}" != "Release" ]]; then+ continue+ fi++ authority="$(printf '%s\n' "${details}" | awk '/^Authority=/ {sub(/^Authority=/, ""); print; exit}')"+ timestamp="$(printf '%s\n' "${details}" | awk '/^Timestamp=/ {sub(/^Timestamp=/, ""); print; exit}')"+ if [[ "${authority}" != "Developer ID Application: "* ]]; then+ validation_fail "Helper manager ${architecture} Developer ID" "Expected Developer ID Application, got ${authority:-none}"+ return 1+ fi+ if [[ -z "${timestamp}" || "${timestamp}" == "none" ]]; then+ validation_fail "Helper manager ${architecture} secure timestamp" "The signature has no secure timestamp"+ return 1+ fi+ validation_field "Helper manager ${architecture} authority" "${authority}"+ validation_field "Helper manager ${architecture} timestamp" "${timestamp}"++ entitlements="${TEMP_ROOT}/validation/manager-${architecture}-entitlements.plist"+ : > "${entitlements}"+ if ! codesign --display --arch "${architecture}" --entitlements="${entitlements}" --xml "${manager_path}" >/dev/null 2>&1; then+ validation_fail "Helper manager ${architecture} entitlements" "codesign could not read the entitlements"+ return 1+ fi+ # 没有 entitlements 的管理 App 同样符合发布要求+ if [[ -s "${entitlements}" ]]; then+ if ! plutil -lint "${entitlements}" >/dev/null 2>&1; then+ validation_fail "Helper manager ${architecture} entitlements" "Invalid entitlements plist"+ return 1+ fi+ debugger_entitlement="$(read_plist_value "${entitlements}" com.apple.security.get-task-allow)"+ if [[ "${debugger_entitlement}" == "true" || "${debugger_entitlement}" == "1" ]]; then+ validation_fail "Helper manager ${architecture} debugger attachment" "get-task-allow is enabled"+ return 1+ fi+ fi+ validation_pass "Helper manager ${architecture} distribution signature"+ done+}+validate_final_app() {local app_path="$1"local contents_path="${app_path}/Contents"local info_plist="${contents_path}/Info.plist"local executable_path="${contents_path}/MacOS/${PRODUCT_NAME}"- local helper_path="${contents_path}/Resources/CodexBarHelper"- local launch_daemons_path="${contents_path}/Library/LaunchDaemons"+ local manager_name="CodexBar Helper"+ if [[ "${CONFIGURATION}" == "Debug" ]]; then+ manager_name="CodexBar Helper Debug"+ fi+ local manager_path="${contents_path}/Library/LoginItems/${manager_name}.app"+ local manager_executable="${manager_path}/Contents/MacOS/CodexBarHelperManager"+ local helper_path="${manager_path}/Contents/Resources/CodexBarHelper"+ local launch_daemons_path="${manager_path}/Contents/Library/LaunchDaemons"local embedded_profile="${contents_path}/embedded.provisionprofile"local validation_dir="${TEMP_ROOT}/validation"local main_entitlements="${validation_dir}/main-entitlements.plist"@@ -19,6 +85,10 @@ validate_final_app() {local helper_signing_certificate_prefix="${validation_dir}/helper-signing-certificate"local helper_signing_certificate="${helper_signing_certificate_prefix}0"local bundle_identifier=""+ local component_identifier_prefix=""+ local component_identifier_suffix=""+ local expected_helper_identifier=""+ local expected_manager_identifier=""local display_name=""local short_version=""local build_version=""@@ -91,10 +161,23 @@ validate_final_app() {return 1fivalidation_pass "Embedded helper"+ if [[ ! -x "${manager_executable}" ]]; then+ validation_fail "Helper manager" "Executable not found at ${manager_executable}"+ return 1+ fi+ local manager_identifier+ manager_identifier="$(read_plist_value "${manager_path}/Contents/Info.plist" CFBundleIdentifier)"mkdir -p "${validation_dir}"bundle_identifier="$(read_plist_value "${info_plist}" CFBundleIdentifier)"+ component_identifier_prefix="${bundle_identifier}"+ if [[ "${CONFIGURATION}" == "Debug" ]]; then+ component_identifier_prefix="${bundle_identifier%.debug}"+ component_identifier_suffix=".debug"+ fi+ expected_helper_identifier="${component_identifier_prefix}.helper${component_identifier_suffix}"+ expected_manager_identifier="${component_identifier_prefix}.helper-manager${component_identifier_suffix}"display_name="$(read_plist_value "${info_plist}" CFBundleDisplayName)"short_version="$(read_plist_value "${info_plist}" CFBundleShortVersionString)"build_version="$(read_plist_value "${info_plist}" CFBundleVersion)"@@ -176,14 +259,31 @@ validate_final_app() {signing_cdhash="$(printf '%s\n' "${signature_details}" | awk -F= '/^CDHash=/ {print $2; exit}')"if [[ "${signature_identifier}" != "${bundle_identifier}" ||- "${helper_signature_identifier}" != "${bundle_identifier}.helper" ||+ "${helper_signature_identifier}" != "${expected_helper_identifier}" ||-z "${signing_team}" || "${helper_signing_team}" != "${signing_team}" ]]; thenvalidation_fail \"Code signature identifiers" \- "Expected app ${bundle_identifier}, helper ${bundle_identifier}.helper, and one shared team; got app ${signature_identifier}, helper ${helper_signature_identifier}, teams ${signing_team:-none}/${helper_signing_team:-none}"+ "Expected app ${bundle_identifier}, helper ${expected_helper_identifier}, and one shared team; got app ${signature_identifier}, helper ${helper_signature_identifier}, teams ${signing_team:-none}/${helper_signing_team:-none}"return 1fivalidation_pass "Code signature identifiers"+ if [[ "${manager_identifier}" != "${expected_manager_identifier}" ]] ||+ ! codesign --verify --strict --all-architectures \+ -R="anchor apple generic and certificate leaf[subject.OU] = \"${signing_team}\" and identifier \"${manager_identifier}\"" \+ "${manager_path}"; then+ validation_fail "Helper manager signature" "Unexpected identifier, team, or invalid signature"+ return 1+ fi+ local manager_architectures+ manager_architectures="$(lipo -archs "${manager_executable}")"+ if [[ "${manager_architectures}" != "${architectures}" ]]; then+ validation_fail "Helper manager architectures" "Expected ${architectures}, got ${manager_architectures}"+ return 1+ fi+ validation_pass "Helper manager signature and architectures"+ if ! validate_helper_manager_distribution "${manager_path}" "${manager_architectures}"; then+ return 1+ fiif ! printf '%s\n' "${signature_details}" | grep -Eq '^CodeDirectory .*flags=.*\(runtime\)'; thenvalidation_fail "App Hardened Runtime" "The app CodeDirectory does not contain the runtime flag"@@ -281,10 +381,10 @@ validate_final_app() {fiif [[ "${main_application_identifier}" != "${signing_team}.${bundle_identifier}" ||- "${helper_application_identifier}" != "${signing_team}.${bundle_identifier}.helper" ]]; then+ "${helper_application_identifier}" != "${signing_team}.${expected_helper_identifier}" ]]; thenvalidation_fail \"Entitlement application identifiers" \- "Expected ${signing_team}.${bundle_identifier} and ${signing_team}.${bundle_identifier}.helper; got ${main_application_identifier:-none} and ${helper_application_identifier:-none}"+ "Expected ${signing_team}.${bundle_identifier} and ${signing_team}.${expected_helper_identifier}; got ${main_application_identifier:-none} and ${helper_application_identifier:-none}"return 1fivalidation_pass "Entitlement application identifiers"@@ -338,12 +438,12 @@ validate_final_app() {launch_daemon_label="$(read_plist_value "${launch_daemon_plist}" Label)"launch_daemon_bundle_identifier="$(read_plist_value "${launch_daemon_plist}" AssociatedBundleIdentifiers:0)"launch_daemon_program="$(read_plist_value "${launch_daemon_plist}" BundleProgram)"- if [[ "${launch_daemon_label}" != "${bundle_identifier}.helper" ||- "${launch_daemon_bundle_identifier}" != "${bundle_identifier}" ||+ if [[ "${launch_daemon_label}" != "${expected_helper_identifier}" ||+ "${launch_daemon_bundle_identifier}" != "${manager_identifier}" ||"${launch_daemon_program}" != "Contents/Resources/CodexBarHelper" ]]; thenvalidation_fail \"LaunchDaemon configuration" \- "Expected label ${bundle_identifier}.helper, bundle ${bundle_identifier}, and program Contents/Resources/CodexBarHelper; got ${launch_daemon_label:-none}, ${launch_daemon_bundle_identifier:-none}, ${launch_daemon_program:-none}"+ "Expected label ${expected_helper_identifier}, bundle ${manager_identifier}, and program Contents/Resources/CodexBarHelper; got ${launch_daemon_label:-none}, ${launch_daemon_bundle_identifier:-none}, ${launch_daemon_program:-none}"return 1fivalidation_pass "LaunchDaemon configuration"diff --git a/Shared/HelperManagement.swift b/Shared/HelperManagement.swiftnew file mode 100644index 0000000..4a219c9--- /dev/null+++ b/Shared/HelperManagement.swift@@ -0,0 +1,28 @@+import Foundation++nonisolated enum HelperManagement {+ static let executableName = "CodexBarHelperManager"+ #if DEBUG+ static let bundleName = "CodexBar Helper Debug.app"+ static let bundleIdentifier = "app.zabrian.codexbar.helper-manager.debug"+ #else+ static let bundleName = "CodexBar Helper.app"+ static let bundleIdentifier = "app.zabrian.codexbar.helper-manager"+ #endif++ enum Command: String, Sendable {+ case status+ case register+ case unregister+ }++ struct Reply: Codable, Sendable {+ let status: Int+ let errorDomain: String?+ let errorCode: Int?+ }++ static func bundleURL(in appURL: URL) -> URL {+ appURL.appending(path: "Contents/Library/LoginItems/\(bundleName)")+ }+}