CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 完善测试隔离与数据库资源清理
Bobb65e1524b424
diff --git a/.gitignore b/.gitignoreindex de81f0b..f33d444 100644--- a/.gitignore+++ b/.gitignore@@ -22,7 +22,6 @@ buildServer.json# Swift Package Manager.build/.swiftpm/-Package.resolved# Code signing inspection outputcodesign0diff --git a/AGENTS.md b/AGENTS.mdindex 5534805..cf5c4ad 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -61,11 +61,14 @@ CodexBar 是面向 macOS 的 `LSUIElement` 菜单栏应用,使用 Swift 6, Swi## 构建、测试与开发命令- `xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build` 执行代码变更后的构建验证-- `xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'platform=macOS' test` 执行无宿主单元测试+- `env -u CC -u CXX xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'platform=macOS' -testPlan Standard test` 执行日常无宿主单元测试+- `env -u CC -u CXX xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'platform=macOS' -testPlan Sanitizers test` 分别运行 TSan 和 ASan 诊断;使用 `-only-test-configuration ThreadSanitizer` 或 `-only-test-configuration AddressSanitizer` 可单独运行对应配置- `swiftformat .` 按 `.swiftformat` 格式化全部 Swift,使用 Swift 6 和 4 空格缩进- `swiftlint` 按 `.swiftlint.yml` 检查- `/usr/bin/log stream --predicate 'subsystem == "app.zabrian.codexbar"' --style compact` 查看系统日志,Debug 版 subsystem 带 `.debug` 后缀+测试命令中的 `env -u CC -u CXX` 用于清除终端的编译器覆盖,确保使用 Xcode 工具链,避免 Homebrew LLVM 干扰 Sanitizer。+`Scripts/build.sh` `dmg.sh` 和 `appcast.sh` 需要 Developer ID 与公证凭据,不用于日常验证。## 写作风格@@ -148,8 +151,11 @@ CodexBar 是面向 macOS 的 `LSUIElement` 菜单栏应用,使用 Swift 6, Swi- 测试围绕可观察行为、关键边界和失败恢复设计,优先复用现有测试;新增测试应能发现实际回归,避免只重复实现或为简单改名机械补测- 单元测试使用独立临时数据和可控依赖,测试结束后清理资源;不得读写真实用户数据、调用真实外部服务、启动特权服务或修改系统设置- 代码改动需完成受影响目标的构建、相关自动化测试及项目配置的格式和静态检查;涉及共享逻辑、构建配置或跨模块行为时,扩大验证范围;纯文档改动检查内容和格式即可+- 日常代码改动默认运行 `Standard` 测试计划,按影响范围选择相关测试+- 修改共享可变状态、锁或跨线程访问时,追加运行 `Sanitizers` 中的 `ThreadSanitizer` 配置;修改 SQLite、Darwin、C 接口或指针相关的内存访问与资源生命周期时,追加运行 `AddressSanitizer` 配置;同时涉及两类风险时,分别运行两种配置+- 测试完成后同时检查失败用例和运行期警告,定位并处理新增的 Sanitizer、Main Thread Checker 和 Thread Performance Checker 报告- 自动化测试无法覆盖的交互、系统集成和生命周期行为,补充手动验证;验证前确认运行产物、构建配置和测试环境,避免混用不同版本-- 交付时说明实际执行的验证及结果;未执行或受环境限制的项目应明确列出,并说明待验证场景,不以构建通过代替运行行为验证+- 交付时说明实际执行的验证、测试计划与配置、结果及运行期警告;未执行或受环境限制的项目应明确列出,并说明待验证场景,不以构建通过代替运行行为验证## Git 规范diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex 00686e6..d2c980f 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -62,6 +62,8 @@/* Begin PBXFileReference section */B10000000000000000000014 /* CodexBarPowerHelper */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = CodexBarPowerHelper; sourceTree = BUILT_PRODUCTS_DIR; };C449FB5030203E0000ED2123 /* Version.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Version.xcconfig; sourceTree = "<group>"; };+ A82000000000000000000001 /* Standard.xctestplan */ = {isa = PBXFileReference; lastKnownFileType = text; path = Standard.xctestplan; sourceTree = "<group>"; };+ A82000000000000000000002 /* Sanitizers.xctestplan */ = {isa = PBXFileReference; lastKnownFileType = text; path = Sanitizers.xctestplan; sourceTree = "<group>"; };C4A0FD952FD9302E000263A7 /* CodexBar Debug.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "CodexBar Debug.app"; sourceTree = BUILT_PRODUCTS_DIR; };D10000000000000000000002 /* CodexBarTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CodexBarTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };E10000000000000000000002 /* CodexBarPowerHelperTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CodexBarPowerHelperTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };@@ -149,6 +151,7 @@D10000000000000000000003 /* Exceptions for "CodexBar" folder in "CodexBarTests" target */ = {isa = PBXFileSystemSynchronizedBuildFileExceptionSet;membershipExceptions = (+ App/CodexBarMain.swift,Resources/AppIcon.icon,Resources/Info.plist,);@@ -241,6 +244,8 @@isa = PBXGroup;children = (C449FB5030203E0000ED2123 /* Version.xcconfig */,+ A82000000000000000000001 /* Standard.xctestplan */,+ A82000000000000000000002 /* Sanitizers.xctestplan */,);path = Config;sourceTree = "<group>";@@ -552,6 +557,7 @@CLANG_WARN_UNREACHABLE_CODE = YES;CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;CODEXBAR_POWER_HELPER_MANAGER_WRAPPER_NAME = "CodexBar Power Helper Debug.app";+ COMPILATION_CACHE_ENABLE_CACHING = YES;COPY_PHASE_STRIP = NO;DEAD_CODE_STRIPPING = YES;DEBUG_INFORMATION_FORMAT = dwarf;@@ -623,6 +629,7 @@CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;CODEXBAR_POWER_HELPER_MANAGER_WRAPPER_NAME = "CodexBar Power Helper.app";CODE_SIGN_INJECT_BASE_ENTITLEMENTS = NO;+ COMPILATION_CACHE_ENABLE_CACHING = YES;COPY_PHASE_STRIP = NO;DEAD_CODE_STRIPPING = YES;DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";@@ -658,7 +665,6 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- ENABLE_APP_INTENTS_METADATA_GENERATION = NO;ENABLE_APP_SANDBOX = NO;ENABLE_HARDENED_RUNTIME = YES;ENABLE_PREVIEWS = YES;@@ -673,7 +679,6 @@);PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.debug;PRODUCT_NAME = "$(TARGET_NAME)";- REGISTER_APP_GROUPS = YES;SWIFT_APPROACHABLE_CONCURRENCY = YES;SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;SWIFT_EMIT_LOC_STRINGS = YES;@@ -691,7 +696,6 @@CODE_SIGN_IDENTITY = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- ENABLE_APP_INTENTS_METADATA_GENERATION = NO;ENABLE_APP_SANDBOX = NO;ENABLE_HARDENED_RUNTIME = YES;ENABLE_PREVIEWS = YES;@@ -707,7 +711,6 @@PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "$(CODEXBAR_PROVISIONING_PROFILE_SPECIFIER)";- REGISTER_APP_GROUPS = YES;SWIFT_APPROACHABLE_CONCURRENCY = YES;SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;SWIFT_EMIT_LOC_STRINGS = YES;@@ -729,7 +732,6 @@PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.tests;PRODUCT_NAME = "$(TARGET_NAME)";SKIP_INSTALL = YES;- SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) CODEXBAR_TESTING";SWIFT_APPROACHABLE_CONCURRENCY = YES;SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;SWIFT_EMIT_LOC_STRINGS = NO;@@ -751,7 +753,6 @@PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.tests;PRODUCT_NAME = "$(TARGET_NAME)";SKIP_INSTALL = YES;- SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) CODEXBAR_TESTING";SWIFT_APPROACHABLE_CONCURRENCY = YES;SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;SWIFT_EMIT_LOC_STRINGS = NO;@@ -886,7 +887,7 @@repositoryURL = "https://github.com/sparkle-project/Sparkle";requirement = {kind = upToNextMajorVersion;- minimumVersion = 2.10.0;+ minimumVersion = 2.10.1;};};/* End XCRemoteSwiftPackageReference section */diff --git a/CodexBar.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/CodexBar.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvednew file mode 100644index 0000000..3c98e6a--- /dev/null+++ b/CodexBar.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -0,0 +1,15 @@+{+ "originHash" : "e721da7f9826abdffcb6185e886155efa2514bd6234475f1afa893e29eb258d6",+ "pins" : [+ {+ "identity" : "sparkle",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/sparkle-project/Sparkle",+ "state" : {+ "revision" : "ab7d71291238df6e0492143b120c9b696a35f603",+ "version" : "2.10.1"+ }+ }+ ],+ "version" : 3+}diff --git a/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme b/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcschemeindex 0807655..6d08d84 100644--- a/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme+++ b/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme@@ -1,7 +1,7 @@<?xml version="1.0" encoding="UTF-8"?><SchemeLastUpgradeVersion = "2700"- version = "1.7">+ version = "1.8"><BuildActionparallelizeBuildables = "YES"buildImplicitDependencies = "YES"@@ -27,29 +27,16 @@buildConfiguration = "Debug"selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"- shouldUseLaunchSchemeArgsEnv = "YES"- shouldAutocreateTestPlan = "YES">- <Testables>- <TestableReference- skipped = "NO"- parallelizable = "NO">- <BuildableReference- BuildableIdentifier = "primary"- BlueprintIdentifier = "D10000000000000000000010"- BuildableName = "CodexBarTests.xctest"- BlueprintName = "CodexBarTests"- ReferencedContainer = "container:CodexBar.xcodeproj">- </BuildableReference>- </TestableReference>- <TestableReference skipped = "NO" parallelizable = "NO">- <BuildableReference BuildableIdentifier = "primary"- BlueprintIdentifier = "E10000000000000000000010"- BuildableName = "CodexBarPowerHelperTests.xctest"- BlueprintName = "CodexBarPowerHelperTests"- ReferencedContainer = "container:CodexBar.xcodeproj">- </BuildableReference>- </TestableReference>- </Testables>+ shouldUseLaunchSchemeArgsEnv = "YES">+ <TestPlans>+ <TestPlanReference+ reference = "container:Config/Standard.xctestplan"+ default = "YES">+ </TestPlanReference>+ <TestPlanReference+ reference = "container:Config/Sanitizers.xctestplan">+ </TestPlanReference>+ </TestPlans></TestAction><LaunchActionbuildConfiguration = "Debug"@@ -61,7 +48,8 @@debugDocumentVersioning = "YES"debugServiceExtension = "internal"allowLocationSimulation = "YES"- queueDebuggingEnableBacktraceRecording = "Yes">+ queueDebuggingEnableBacktraceRecording = "Yes"+ enableThreadPerformanceChecker = "YES"><BuildableProductRunnablerunnableDebuggingMode = "0"><BuildableReferencediff --git a/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plist b/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plistdeleted file mode 100644index 2c4df98..0000000--- a/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plist+++ /dev/null@@ -1,32 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>SchemeUserState</key>- <dict>- <key>CodexBar.xcscheme_^#shared#^_</key>- <dict>- <key>orderHint</key>- <integer>0</integer>- </dict>- <key>CodexBarPowerHelper.xcscheme_^#shared#^_</key>- <dict>- <key>orderHint</key>- <integer>1</integer>- </dict>- <key>CodexBarPowerHelperManager.xcscheme_^#shared#^_</key>- <dict>- <key>orderHint</key>- <integer>2</integer>- </dict>- </dict>- <key>SuppressBuildableAutocreation</key>- <dict>- <key>C4A0FD942FD9302E000263A7</key>- <dict>- <key>primary</key>- <true/>- </dict>- </dict>-</dict>-</plist>diff --git a/CodexBar/App/CodexBarApp.swift b/CodexBar/App/CodexBarApp.swiftindex e3a2812..2ef8afd 100644--- a/CodexBar/App/CodexBarApp.swift+++ b/CodexBar/App/CodexBarApp.swift@@ -1,32 +1,6 @@import AppKit-import Darwin-import osimport SwiftUI-// 测试时禁用应用入口-#if !CODEXBAR_TESTING- @main-#endif-nonisolated enum CodexBarMain {- static func main() {- do {- // 在 SwiftUI 创建 AppDelegate 前互斥, 避免重复实例初始化服务- guard let descriptor = try JSONFileStorage.acquireLock(- at: AppStorage().lockURL(.appInstance), nonblocking: true- ) else { return }- defer { JSONFileStorage.releaseLock(descriptor) }-- // 同步进程入口位于主线程, 取得锁后才进入 SwiftUI 生命周期- MainActor.assumeIsolated {- CodexBarApp.main()- }- } catch {- AppLog.app.error("App 实例锁获取失败")- exit(EXIT_FAILURE)- }- }-}-struct CodexBarApp: App {@NSApplicationDelegateAdaptor(CodexBarAppDelegate.self) private var appDelegatediff --git a/CodexBar/App/CodexBarAppDelegate.swift b/CodexBar/App/CodexBarAppDelegate.swiftindex a9a27be..c4ecba5 100644--- a/CodexBar/App/CodexBarAppDelegate.swift+++ b/CodexBar/App/CodexBarAppDelegate.swift@@ -5,7 +5,7 @@ import os/// 应用级对象装配点, 持有服务和 ViewModel 生命周期@MainActorfinal class CodexBarAppDelegate: NSObject, NSApplicationDelegate {- private lazy var codexStatusService = CodexStatusService(startup: appServerStartup)+ private lazy var codexStatusService = CodexStatusService(logStorage: .shared, startup: appServerStartup)private lazy var appServerStartup = AppServerStartup()lazy var viewModel = CodexStatusViewModel(service: codexStatusService, serviceStatusMonitor: serviceStatusMonitor)let historyViewModel = HistoryViewModel()@@ -14,7 +14,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {)let protectionSettings = ProtectionSettings()lazy var activityMonitor = ActivityMonitor(- protectionSettings: protectionSettings+ protectionSettings: protectionSettings, logStorage: .shared)lazy var keepAliveController = KeepAliveController(activityMonitor: activityMonitor@@ -181,7 +181,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {return}if success {- do { try await AppServerLogStore.shared.finish() } catch {+ do { try await AppServerLogStore.shared.close() } catch {AppLog.app.error("退出 App 前日志写入失败")}}diff --git a/CodexBar/App/CodexBarMain.swift b/CodexBar/App/CodexBarMain.swiftnew file mode 100644index 0000000..f51b282--- /dev/null+++ b/CodexBar/App/CodexBarMain.swift@@ -0,0 +1,24 @@+import Darwin+import os+import SwiftUI++@main+nonisolated enum CodexBarMain {+ static func main() {+ do {+ // 在 SwiftUI 创建 AppDelegate 前互斥, 避免重复实例初始化服务+ guard let descriptor = try JSONFileStorage.acquireLock(+ at: AppStorage().lockURL(.appInstance), nonblocking: true+ ) else { return }+ defer { JSONFileStorage.releaseLock(descriptor) }++ // 同步进程入口位于主线程, 取得锁后才进入 SwiftUI 生命周期+ MainActor.assumeIsolated {+ CodexBarApp.main()+ }+ } catch {+ AppLog.app.error("App 实例锁获取失败")+ exit(EXIT_FAILURE)+ }+ }+}diff --git a/CodexBar/Controllers/LogWindowController.swift b/CodexBar/Controllers/LogWindowController.swiftindex 9796506..8714845 100644--- a/CodexBar/Controllers/LogWindowController.swift+++ b/CodexBar/Controllers/LogWindowController.swift@@ -10,7 +10,7 @@ final class LogWindowController: HostingWindowController {init(mainPanelSettings: MainPanelSettings,- store: AppServerLogViewModel = .shared,+ store: AppServerLogViewModel = AppServerLogViewModel(storage: .shared),screenProvider: @escaping () -> NSScreen?) {self.store = storediff --git a/CodexBar/Services/Activity/ActivityMonitor.swift b/CodexBar/Services/Activity/ActivityMonitor.swiftindex 8e2b0f2..49efcbe 100644--- a/CodexBar/Services/Activity/ActivityMonitor.swift+++ b/CodexBar/Services/Activity/ActivityMonitor.swift@@ -77,7 +77,6 @@ final class ActivityMonitor: ObservableObject {@Published var isActivitySourceHealthy = false@Published private(set) var sourcePresentation: ActivityLiveLabel? = ActivityLiveLabel("unavailable")private var hasConnectedActivitySource = false- private var unavailableTurns = Set<ActivityTaskKey>()var isProtectionRecoveryInProgress = falsevar protectionRecoveryGeneration: UInt64 = 0private var cancellables = Set<AnyCancellable>()@@ -86,14 +85,18 @@ final class ActivityMonitor: ObservableObject {var isBootstrapping = falsevar turnTransitionNotBefore: Date?+ private let logStorage: AppServerLogStore?+init(protectionSettings: ProtectionSettings,protectionStore: ProtectionStore = ProtectionStore(),- activityDataDirectoryURL: URL = AppStorage.directoryURL()+ activityDataDirectoryURL: URL = AppStorage.directoryURL(),+ logStorage: AppServerLogStore? = nil) {self.protectionSettings = protectionSettingsself.protectionStore = protectionStoreself.activityDataDirectoryURL = activityDataDirectoryURL+ self.logStorage = logStorage}func start() {@@ -242,6 +245,7 @@ final class ActivityMonitor: ObservableObject {activityReaderGeneration &+= 1let generation = activityReaderGenerationlet reader = AppServerActivityReader(+ logStorage: logStorage,tokenUsageHistory: TokenUsageHistoryStore(directoryURL: activityDataDirectoryURL),activityDataRecorder: ActivityDataRecorder(directoryURL: activityDataDirectoryURL),onAccountChange: { [weak self] change in@@ -364,7 +368,6 @@ final class ActivityMonitor: ObservableObject {publishedRevision = update.revisionlet previous = graph.tasksgraph = update.graph- unavailableTurns = graph.unavailableTurnsfor (key, old) in previous {guard let task = tasks[key] else {clearProtection(for: key, taskID: old.displayID, reason: .terminal)@@ -480,7 +483,7 @@ final class ActivityMonitor: ObservableObject {private func sortedTasks(in state: ActivityTaskState) -> [ActivityTask] {tasks.values- .filter { $0.state == state && suppressedTasks[$0.key] == nil && !unavailableTurns.contains($0.key) }+ .filter { $0.state == state && suppressedTasks[$0.key] == nil && !graph.unavailableTurns.contains($0.key) }.sorted(by: Self.recentFirst(\.lastActivityAt, \.displayID))}diff --git a/CodexBar/Services/Activity/AppServerActivityReader.swift b/CodexBar/Services/Activity/AppServerActivityReader.swiftindex a44620a..fdd2df8 100644--- a/CodexBar/Services/Activity/AppServerActivityReader.swift+++ b/CodexBar/Services/Activity/AppServerActivityReader.swift@@ -130,7 +130,7 @@ actor AppServerActivityReader {init(socketURL: URL = AppServerActivityReader.defaultSocketURL,- logStorage: AppServerLogStore? = .shared,+ logStorage: AppServerLogStore?,tokenUsageHistory: TokenUsageHistoryStore = TokenUsageHistoryStore(),activityDataRecorder: ActivityDataRecorder = ActivityDataRecorder(),maximumPendingEvents: Int = 4096,@@ -906,15 +906,9 @@ actor AppServerActivityReader {await publish(.lifecycleChanged)}- #if CODEXBAR_TESTING- func historyTargetsForTesting() -> Set<ActivityTurnReference> {- Set(backfillScans.keys)- }-- func lifecycleStatesForTesting(for references: [ActivityTurnReference]) -> [TurnLifecycleState] {- TurnLifecycleSnapshot(states: reducer.states, verifiedTurns: verifiedTurns).lifecycleStates(for: references)- }- #endif+ var lifecycleSnapshot: TurnLifecycleSnapshot {+ TurnLifecycleSnapshot(states: reducer.states, verifiedTurns: verifiedTurns)+ }private func publish(_ phase: ActivityUpdate.Phase, events: [ActivityDataRecord] = []) async {if case .bootstrapStart = phase {@@ -925,7 +919,6 @@ actor AppServerActivityReader {} else {.bootstrap}- let lifecycleSnapshot = TurnLifecycleSnapshot(states: reducer.states, verifiedTurns: verifiedTurns)let transitions = taskGraph.update(events: events, source: source, lifecycle: lifecycleSnapshot)let terminalEvents = taskGraph.terminalEventslet backfilledTasks = taskGraph.backfilledTasksdiff --git a/CodexBar/Services/AppServer/AccountSession.swift b/CodexBar/Services/AppServer/AccountSession.swiftindex 9a315e7..787bdfa 100644--- a/CodexBar/Services/AppServer/AccountSession.swift+++ b/CodexBar/Services/AppServer/AccountSession.swift@@ -28,7 +28,7 @@ final nonisolated class AccountSession {transport.isOpen}- init(socketURL: URL, timeout: TimeInterval = 20, logStorage: AppServerLogStore? = .shared) throws {+ init(socketURL: URL, timeout: TimeInterval = 20, logStorage: AppServerLogStore?) throws {transport = try AppServerSession(socketURL: socketURL, retainsNotifications: false, logStorage: logStorage, connectionName: "account")self.timeout = timeout}diff --git a/CodexBar/Services/AppServer/AppServerLogStore.swift b/CodexBar/Services/AppServer/AppServerLogStore.swiftindex 8c8bee2..6ae2187 100644--- a/CodexBar/Services/AppServer/AppServerLogStore.swift+++ b/CodexBar/Services/AppServer/AppServerLogStore.swift@@ -12,11 +12,11 @@ nonisolated struct AppServerLogPage: Sendable {/// SQLite 连接和全部可变状态仅在 queue 上访问, 请求线程只提交有序写入final nonisolated class AppServerLogStore: @unchecked Sendable {- #if CODEXBAR_TESTING- static let shared = AppServerLogStore(directoryURL: FileManager.default.temporaryDirectory.appendingPathComponent("CodexBarTestLogs-\(UUID().uuidString)"))- #else- static let shared = AppServerLogStore(directoryURL: defaultDirectory)- #endif+ static let shared = AppServerLogStore(directoryURL: defaultDirectory)++ enum LifecycleError: Error {+ case closed+ }static var defaultDirectory: URL {AppStorage().logDirectoryURL@@ -60,6 +60,37 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {}}+ /// 排空此前提交的操作并关闭连接, 可重复调用+ /// 关闭后的写入丢弃, 读取和清空操作报错, 不会重新打开数据库+ func close() async throws {+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in+ queue.async { [self] in+ let shouldFinish = !isFinished+ isFinished = true+ let finishing = Result {+ guard shouldFinish else { return }+ try prepareForAccess()+ try reclaimSpaceIfNeeded()+ try execute("PRAGMA wal_checkpoint(TRUNCATE)")+ if let writeError {+ throw StorageError(message: writeError)+ }+ }+ do {+ if let database {+ guard sqlite3_close(database) == SQLITE_OK else { throw failure() }+ self.database = nil+ }+ writeError = nil+ try finishing.get()+ continuation.resume()+ } catch {+ continuation.resume(throwing: error)+ }+ }+ }+ }+func beginRequest(method: String, payload: String, connection: String? = nil, source: AppServerLogEntry.Source = .request) -> UUID {let entry = AppServerLogEntry(id: UUID(), connection: connection, requestedAt: Date(), source: source, status: .pending, method: method, request: payload)append(entry)@@ -182,14 +213,6 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {}}- /// 正常退出时排空已提交写入, 之后到达的网络回调不再追加日志- func finish() async throws {- try await perform { storage in- storage.isFinished = true- try storage.execute("PRAGMA wal_checkpoint(TRUNCATE)")- }- }-private func append(_ entry: AppServerLogEntry) {let entry = entry.bounded(to: limits.bodyBytes)enqueue(cost: (entry.request?.utf8.count ?? 0) + (entry.detail?.utf8.count ?? 0)@@ -250,23 +273,8 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {try await withCheckedThrowingContinuation { continuation inqueue.async { [self] indo {- try open()- try transaction { try pruneIfNeeded() }- admissionLock.lock()- let dropped = droppedEntries- droppedEntries = 0- admissionLock.unlock()- if dropped > 0, !isFinished {- let entry = AppServerLogEntry(- id: UUID(),- requestedAt: Date(),- source: .local, status: .failure,- method: "log/backpressure",- request: nil,- detail: "Skipped \(dropped) log entries because the write buffer was full"- )- try transaction { try save(entry, inserting: true) }- }+ guard !isFinished else { throw LifecycleError.closed }+ try prepareForAccess()let result = try operation(self)try reclaimSpaceIfNeeded()if let writeError {@@ -280,6 +288,26 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {}}+ private func prepareForAccess() throws {+ try open()+ try transaction { try pruneIfNeeded() }+ admissionLock.lock()+ let dropped = droppedEntries+ droppedEntries = 0+ admissionLock.unlock()+ if dropped > 0 {+ let entry = AppServerLogEntry(+ id: UUID(),+ requestedAt: Date(),+ source: .local, status: .failure,+ method: "log/backpressure",+ request: nil,+ detail: "Skipped \(dropped) log entries because the write buffer was full"+ )+ try transaction { try save(entry, inserting: true) }+ }+ }+private func open() throws {guard database == nil else { return }try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])diff --git a/CodexBar/Services/AppServer/AppServerLogViewModel.swift b/CodexBar/Services/AppServer/AppServerLogViewModel.swiftindex 395b423..8ebde95 100644--- a/CodexBar/Services/AppServer/AppServerLogViewModel.swift+++ b/CodexBar/Services/AppServer/AppServerLogViewModel.swift@@ -3,8 +3,6 @@ import Foundation@MainActorfinal class AppServerLogViewModel: ObservableObject {- static let shared = AppServerLogViewModel()-@Published private(set) var entries: [AppServerLogEntry] = []@Published private(set) var totalCount = 0@Published private(set) var hasMore = false@@ -22,7 +20,7 @@ final class AppServerLogViewModel: ObservableObject {private var observation: Task<Void, Never>?private var observationGeneration = 0- init(storage: AppServerLogStore = .shared, pageSize: Int = 100, maximumEntries: Int = 1000) {+ init(storage: AppServerLogStore, pageSize: Int = 100, maximumEntries: Int = 1000) {self.storage = storageself.pageSize = min(pageSize, maximumEntries)self.maximumEntries = maximumEntriesdiff --git a/CodexBar/Services/AppServer/AppServerSession.swift b/CodexBar/Services/AppServer/AppServerSession.swiftindex caf23cf..c600972 100644--- a/CodexBar/Services/AppServer/AppServerSession.swift+++ b/CodexBar/Services/AppServer/AppServerSession.swift@@ -36,7 +36,7 @@ final nonisolated class AppServerSession {init(socketURL: URL,retainsNotifications: Bool = true,- logStorage: AppServerLogStore? = .shared,+ logStorage: AppServerLogStore?,connectionName: String = "activity",maximumMessageSize: Int = AppServerSession.defaultMaximumMessageSize) throws {diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swiftindex 31998b9..5991df9 100644--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift@@ -85,7 +85,7 @@ actor CodexStatusService {private let logStorage: AppServerLogStore?private let startup: AppServerStartup?- init(socketURL: URL = AppServerActivityReader.defaultSocketURL, logStorage: AppServerLogStore? = .shared, startup: AppServerStartup? = nil) {+ init(socketURL: URL = AppServerActivityReader.defaultSocketURL, logStorage: AppServerLogStore?, startup: AppServerStartup? = nil) {self.socketURL = socketURLself.logStorage = logStorageself.startup = startupdiff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swiftindex 4459608..5ce3f80 100644--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift@@ -81,7 +81,7 @@ final class CodexStatusViewModel: ObservableObject {private var connectionInfoGeneration: UInt64 = 0init(- service: CodexStatusService = CodexStatusService(),+ service: CodexStatusService,serviceStatusMonitor: CodexServiceStatusMonitor? = nil,defaults: UserDefaults = .standard) {diff --git a/CodexBar/Services/History/HistoryDatabaseStore.swift b/CodexBar/Services/History/HistoryDatabaseStore.swiftindex 2cde2a8..febbc8c 100644--- a/CodexBar/Services/History/HistoryDatabaseStore.swift+++ b/CodexBar/Services/History/HistoryDatabaseStore.swift@@ -33,16 +33,21 @@ actor HistoryDatabaseStore {self.directoryURL = directoryURL}+ /// 释放当前连接, 已提交数据保留, 下次访问时按需重开+ func releaseConnection() {+ database = nil+ }+func access<Value: Sendable>(_ operation: @Sendable (HistoryDatabase) throws -> Value) throws -> Value {try Task.checkCancellation()do {if let database, try !database.canReuseConnection() {- self.database = nil+ releaseConnection()}} catch {guard let failure = error as? HistoryDatabase.Failure, failure.requiresReopening else { throw error }// 检查阶段还没有执行本次操作, 可以安全重开连接- database = nil+ releaseConnection()}let database: HistoryDatabaseif let existing = self.database {@@ -54,14 +59,14 @@ actor HistoryDatabaseStore {// 失败回滚后仍有事务的连接不能交给下一位调用方defer {if database.hasOpenTransaction {- self.database = nil+ releaseConnection()}}do {return try operation(database)} catch {if let failure = error as? HistoryDatabase.Failure, failure.requiresReopening {- self.database = nil+ releaseConnection()}throw error}diff --git a/CodexBar/Services/Notifications/NotificationService.swift b/CodexBar/Services/Notifications/NotificationService.swiftindex 431da10..cce3eae 100644--- a/CodexBar/Services/Notifications/NotificationService.swift+++ b/CodexBar/Services/Notifications/NotificationService.swift@@ -39,12 +39,6 @@ final class NotificationService: NSObject {private var cancellables = Set<AnyCancellable>()private var taskHapticFeedbackTask: Task<Void, Never>?private var taskWaitingNotificationIdentifiers = Set<String>()- #if CODEXBAR_TESTING- private(set) var lastSubmissionTaskForTesting: Task<Bool, Never>?- var taskWaitingNotificationIdentifiersForTesting: Set<String> {- taskWaitingNotificationIdentifiers- }- #endifprivate let creditExpiryReminderScheduler = ReminderCheckScheduler()private var latestQuotaSnapshot: CodexQuotaSnapshot?@@ -143,22 +137,23 @@ final class NotificationService: NSObject {// MARK: - 任务提醒- private func handleActivityTransition(_ transition: ActivityTransition) {+ @discardableResult+ func handleActivityTransition(_ transition: ActivityTransition) -> Task<Bool, Never>? {performTaskHapticFeedbackIfEnabled()guard settings.canDeliver else {- return+ return nil}switch transition {case let .waiting(task, _):guard settings.isTaskWaitingEnabled else {- return+ return nil}let taskID = task.idlet identifier = Self.taskWaitingNotificationIdentifier(for: taskID)taskWaitingNotificationIdentifiers.insert(identifier)- send(+ return send(.taskWaiting(project: task.projectName, actionText: task.approvalActionText),sound: settings.taskWaitingSound,identifier: identifier,@@ -173,9 +168,9 @@ final class NotificationService: NSObject {guard settings.isTaskCompletionEnabled,let duration = completion.duration,duration >= TimeInterval(settings.taskCompletionMinimumDurationSeconds) else {- return+ return nil}- send(+ return send(.taskCompleted(project: completion.projectName, duration: duration),sound: settings.taskCompletionSound)@@ -631,7 +626,7 @@ final class NotificationService: NSObject {content: content,trigger: nil)- let task = Task { @MainActor [weak self] in+ return Task { @MainActor [weak self] inawait self?.deliver(request,kind: kind,@@ -641,10 +636,6 @@ final class NotificationService: NSObject {retryCount: retryCount) ?? false}- #if CODEXBAR_TESTING- lastSubmissionTaskForTesting = task- #endif- return task}/// 返回值是"这条通知真的提交出去了", 调用方据此决定要不要记下已通知diff --git a/Config/Sanitizers.xctestplan b/Config/Sanitizers.xctestplannew file mode 100644index 0000000..65b0d0f--- /dev/null+++ b/Config/Sanitizers.xctestplan@@ -0,0 +1,53 @@+{+ "configurations" : [+ {+ "id" : "EB7BB41D-299A-4B84-A3E5-F2ABF660AEA8",+ "name" : "ThreadSanitizer",+ "options" : {+ "threadSanitizerEnabled" : true+ }+ },+ {+ "id" : "B4D77222-B922-4264-AFD2-0DB980901DF8",+ "name" : "AddressSanitizer",+ "options" : {+ "addressSanitizer" : {+ "enabled" : true+ }+ }+ }+ ],+ "defaultOptions" : {+ "codeCoverage" : false,+ "language" : "zh-Hans",+ "mainThreadCheckerDetectionPolicy" : {+ "enabled" : true,+ "severity" : "warning"+ },+ "region" : "CN",+ "testTimeoutsEnabled" : true,+ "threadPerformanceCheckerRuntimeIssueDetection" : {+ "enabled" : true,+ "severity" : "warning"+ }+ },+ "testTargets" : [+ {+ "parallelizable" : false,+ "target" : {+ "containerPath" : "container:CodexBar.xcodeproj",+ "identifier" : "D10000000000000000000010",+ "name" : "CodexBarTests"+ }+ },+ {+ "parallelizable" : false,+ "target" : {+ "containerPath" : "container:CodexBar.xcodeproj",+ "identifier" : "E10000000000000000000010",+ "name" : "CodexBarPowerHelperTests"+ }+ }+ ],+ "version" : 1+}diff --git a/Config/Standard.xctestplan b/Config/Standard.xctestplannew file mode 100644index 0000000..09c0a8e--- /dev/null+++ b/Config/Standard.xctestplan@@ -0,0 +1,42 @@+{+ "configurations" : [+ {+ "id" : "DD93DD84-3303-41B5-A30A-AB0E4C95EDC1",+ "name" : "Standard",+ "options" : {++ }+ }+ ],+ "defaultOptions" : {+ "codeCoverage" : true,+ "language" : "zh-Hans",+ "mainThreadCheckerDetectionPolicy" : {+ "severity" : "warning"+ },+ "region" : "CN",+ "testTimeoutsEnabled" : true,+ "threadPerformanceCheckerRuntimeIssueDetection" : {+ "severity" : "warning"+ }+ },+ "testTargets" : [+ {+ "parallelizable" : false,+ "target" : {+ "containerPath" : "container:CodexBar.xcodeproj",+ "identifier" : "D10000000000000000000010",+ "name" : "CodexBarTests"+ }+ },+ {+ "parallelizable" : false,+ "target" : {+ "containerPath" : "container:CodexBar.xcodeproj",+ "identifier" : "E10000000000000000000010",+ "name" : "CodexBarPowerHelperTests"+ }+ }+ ],+ "version" : 1+}diff --git a/Tests/App/Activity/ActivityBackfillTests.swift b/Tests/App/Activity/ActivityBackfillTests.swiftindex a40f7b9..6cd5e3e 100644--- a/Tests/App/Activity/ActivityBackfillTests.swift+++ b/Tests/App/Activity/ActivityBackfillTests.swift@@ -94,6 +94,7 @@ struct ActivityBackfillTests {defer { server.close() }let store = TokenUsageHistoryStore(directoryURL: directory.url)let logs = AppServerLogStore(directoryURL: directory.url.appendingPathComponent("Logs"))+ defer { await #expect(throws: Never.self) { try await logs.close() } }let probe = ActivityReaderProbe()var ready = falsevar updates = 0@@ -124,7 +125,7 @@ struct ActivityBackfillTests {#expect(probe.graph.tasks[key]?.state == .running)let progress = probe.graph.tasks[key]?.progressGenerationlet references = [ActivityTurnReference(threadID: "child", turnID: "child-turn")]- let before = await reader.lifecycleStatesForTesting(for: references).first+ let before = await reader.lifecycleSnapshot.lifecycleStates(for: references).first#expect(before?.effort == "high")if outcome == .stop {await reader.stop()@@ -146,7 +147,7 @@ struct ActivityBackfillTests {}#expect(updates > beforeBackfillUpdates)}- let after = await reader.lifecycleStatesForTesting(for: references).first+ let after = await reader.lifecycleSnapshot.lifecycleStates(for: references).first#expect(after?.effort == (outcome == .complete ? "mixed" : "high"))#expect(after?.verifiedAt == before?.verifiedAt)#expect(probe.graph.tasks[key]?.progressGeneration == progress)@@ -292,11 +293,14 @@ extension ActivityBackfillTests {releasePage.signal()}let cursors = Mutex<[String?]>([])+ let queriedThreads = Mutex<Set<String>>([])let timestamp = Date().addingTimeInterval(-60).timeIntervalSince1970let server = try SharedServerFixture(connections: 4, concurrentConnections: true) { peer inif try Self.initialize(peer) == "codex_bar_activity_backfill" {let request = try peer.readMessage()let params = try #require(request["params"] as? [String: Any])+ let threadID = try #require(params["threadId"] as? String)+ _ = queriedThreads.withLock { $0.insert(threadID) }if params["threadId"] as? String == "child" {try peer.reply(to: request, result: ["data": []])return@@ -333,24 +337,24 @@ extension ActivityBackfillTests {await reader.start()let references = [ActivityTurnReference(threadID: "new-child", turnID: "new-child-turn"), .init(threadID: "child", turnID: "child-turn")]for _ in 0 ..< 200 {- if await reader.lifecycleStatesForTesting(for: references).contains(where: { $0.requestedThreadID == "new-child" && $0.startedAt != nil }) {+ if await reader.lifecycleSnapshot.lifecycleStates(for: references).contains(where: { $0.requestedThreadID == "new-child" && $0.startedAt != nil }) {break}try await Task.sleep(for: .milliseconds(10))}- #expect(await reader.lifecycleStatesForTesting(for: references).contains { $0.requestedThreadID == "new-child" && $0.startedAt != nil })+ #expect(await reader.lifecycleSnapshot.lifecycleStates(for: references).contains { $0.requestedThreadID == "new-child" && $0.startedAt != nil })releasePage.signal()for _ in 0 ..< 200 {- if await reader.lifecycleStatesForTesting(for: references).allSatisfy({ $0.effort == "low" }) {+ if await reader.lifecycleSnapshot.lifecycleStates(for: references).allSatisfy({ $0.effort == "low" }) {break}try await Task.sleep(for: .milliseconds(10))}- #expect(await reader.lifecycleStatesForTesting(for: references).allSatisfy { $0.effort == "low" })+ #expect(await reader.lifecycleSnapshot.lifecycleStates(for: references).allSatisfy { $0.effort == "low" })#expect(cursors.withLock { $0 } == [nil, "older"])- #expect(await !reader.historyTargetsForTesting().contains(.init(threadID: "new-child", turnID: "new-child-turn")))await reader.stop()try server.finish()+ #expect(queriedThreads.withLock { $0 } == ["parent", "child"])}private nonisolated static func serveNewSubagent(_ peer: SharedServerFixture.Peer, timestamp: Double, firstPage: DispatchSemaphore) throws {@@ -509,6 +513,8 @@ extension ActivityBackfillTests {@Test func taskStartedWhileReaderIsConnectedDoesNotQueryHistory() async throws {let directory = try TestDirectory()defer { try? directory.remove() }+ let logs = AppServerLogStore(directoryURL: directory.url.appendingPathComponent("Logs"))+ defer { await #expect(throws: Never.self) { try await logs.close() } }let startTask = Mutex(false)let server = try SharedServerFixture { peer intry Self.initialize(peer)@@ -542,7 +548,7 @@ extension ActivityBackfillTests {let reader = AppServerActivityReader(probe: probe,socketURL: server.url,- logStorage: nil,+ logStorage: logs,tokenUsageHistory: TokenUsageHistoryStore(directoryURL: directory.url),activityDataRecorder: ActivityDataRecorder(directoryURL: directory.url)) {@@ -558,8 +564,8 @@ extension ActivityBackfillTests {startTask.withLock { $0 = true }#expect(await reader.drainNow().status == .completed)#expect(probe.graph.tasks[.init(thread: "main", turn: "root")]?.state == .running)- #expect(await reader.historyTargetsForTesting().isEmpty)#expect(await reader.stop())+ #expect(try await !logs.page().entries.contains { $0.method == "thread/items/list" })#expect(try directory.historyRecords().allSatisfy { $0.context?.method != "thread/items/list" })try server.finish()}diff --git a/Tests/App/Activity/ActivityIsolationTests.swift b/Tests/App/Activity/ActivityIsolationTests.swiftindex f8ad42b..7384839 100644--- a/Tests/App/Activity/ActivityIsolationTests.swift+++ b/Tests/App/Activity/ActivityIsolationTests.swift@@ -35,6 +35,7 @@ struct ActivityIsolationTests {defer { server.close() }let store = TokenUsageHistoryStore(directoryURL: directory.url)let logs = AppServerLogStore(directoryURL: directory.url.appendingPathComponent("Logs"))+ defer { await #expect(throws: Never.self) { try await logs.close() } }var received = falsevar liveUsage: Int64?let reader = AppServerActivityReader(diff --git a/Tests/App/Activity/ActivityReaderBoundsTests.swift b/Tests/App/Activity/ActivityReaderBoundsTests.swiftindex e848a4a..f3d8fed 100644--- a/Tests/App/Activity/ActivityReaderBoundsTests.swift+++ b/Tests/App/Activity/ActivityReaderBoundsTests.swift@@ -157,13 +157,13 @@ struct ActivityReaderBoundsTests {#expect(ready)#expect(await reader.drainNow().status == .completed)for _ in 0 ..< 200 {- let current = await reader.lifecycleStatesForTesting(for: [.init(threadID: "child", turnID: "child-turn")])+ let current = await reader.lifecycleSnapshot.lifecycleStates(for: [.init(threadID: "child", turnID: "child-turn")])if current.first?.effort == "low" {break}try await Task.sleep(for: .milliseconds(10))}- let states = await reader.lifecycleStatesForTesting(for: [.init(threadID: "child", turnID: "child-turn")])+ let states = await reader.lifecycleSnapshot.lifecycleStates(for: [.init(threadID: "child", turnID: "child-turn")])let child = try #require(states.first)#expect(child.rootThreadID == "parent")#expect(child.rootTurnID == "root-turn")diff --git a/Tests/App/Activity/ActivitySchedulingTests.swift b/Tests/App/Activity/ActivitySchedulingTests.swiftindex 7040fcf..568128f 100644--- a/Tests/App/Activity/ActivitySchedulingTests.swift+++ b/Tests/App/Activity/ActivitySchedulingTests.swift@@ -342,7 +342,7 @@ extension ActivitySchedulingTests {try await Task.sleep(for: .milliseconds(5))}#expect(await reader.drainNow().status == .partial)- let state = await reader.lifecycleStatesForTesting(for: [.init(threadID: "thread", turnID: "turn")]).first+ let state = await reader.lifecycleSnapshot.lifecycleStates(for: [.init(threadID: "thread", turnID: "turn")]).first#expect(state?.presentation?.summary.waiting != nil)await reader.stop()release.signal()@@ -393,7 +393,7 @@ extension ActivitySchedulingTests {#expect(probe.graph.tasks[.init(thread: "thread", turn: "turn")] == nil)#expect(probe.graph.tasks[.init(thread: "thread", turn: "new-turn")]?.state == .running)#expect(probe.graph.completions.count == 1)- let old = await reader.lifecycleStatesForTesting(for: [.init(threadID: "thread", turnID: "turn")]).first+ let old = await reader.lifecycleSnapshot.lifecycleStates(for: [.init(threadID: "thread", turnID: "turn")]).first#expect(old?.terminal != nil)#expect(old?.turnStatus == .completed)await reader.stop()diff --git a/Tests/App/AppServer/AppServerLogTests.swift b/Tests/App/AppServer/AppServerLogTests.swiftindex 680397f..b386dea 100644--- a/Tests/App/AppServer/AppServerLogTests.swift+++ b/Tests/App/AppServer/AppServerLogTests.swift@@ -5,17 +5,57 @@ import SQLite3import Testingstruct AppServerLogTests {+ @Test func closeDrainsWritesAndPermanentlyClosesDatabase() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }+ storage.recordFailure(message: "before cleanup")+ _ = try await storage.page()+ #expect(try !directory.openFilePaths().isEmpty)+ storage.recordFailure(message: "queued before cleanup")+ try await storage.close()+ try await storage.close()+ #expect(try directory.openFilePaths().isEmpty)+ await #expect(throws: AppServerLogStore.LifecycleError.closed) { try await storage.page() }+ await #expect(throws: AppServerLogStore.LifecycleError.closed) { try await storage.changes(since: 0) }+ await #expect(throws: AppServerLogStore.LifecycleError.closed) { try await storage.clear() }+ #expect(try directory.openFilePaths().isEmpty)+ storage.recordFailure(message: "after cleanup")+ try await storage.close()+ let reopened = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await reopened.close() } }+ let page = try await reopened.page()+ #expect(page.entries.map(\.detail) == ["queued before cleanup", "before cleanup"])+ }++ @Test func closePersistsSkippedWriteCountBeforeReleasingConnection() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let storage = AppServerLogStore(directoryURL: directory.url, limits: .init(bytes: 4096))+ defer { await #expect(throws: Never.self) { try await storage.close() } }+ storage.recordFailure(message: String(repeating: "a", count: 8192))+ try await storage.close()+ #expect(try directory.openFilePaths().isEmpty)+ let reopened = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await reopened.close() } }+ let page = try await reopened.page()+ #expect(page.total == 1)+ #expect(page.entries.first?.method == "log/backpressure")+ #expect(page.entries.first?.detail == "Skipped 1 log entries because the write buffer was full")+ }+@Test(arguments: [false, true])func stoppingDuringFirstReadDiscardsResultsAndAllowsReopening(reopenImmediately: Bool) async throws {let directory = try TestDirectory()defer { try? directory.remove() }let writer = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await writer.close() } }writer.recordFailure(message: "saved log")_ = try await writer.page()let reads = OSAllocatedUnfairLock(initialState: 0)let release = DispatchSemaphore(value: 0)- defer { release.signal() }let storage = AppServerLogStore(directoryURL: directory.url, now: {let firstRead = reads.withLock { count incount += 1@@ -27,6 +67,8 @@ struct AppServerLogTests {}return Date()})+ defer { await #expect(throws: Never.self) { try await storage.close() } }+ defer { release.signal() }let model = AppServerLogViewModel(storage: storage)defer { model.stop() }let firstRead = Task { await model.refresh() }@@ -65,6 +107,7 @@ struct AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }storage.recordFailure(message: "startup log")let model = AppServerLogViewModel(storage: storage)defer { model.stop() }@@ -106,9 +149,11 @@ struct AppServerLogTests {sqlite3_close(database)let before = try Data(contentsOf: url)let store = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await store.close() } }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() }+ await #expect(throws: (any Error).self) { try await store.close() }#expect(try Data(contentsOf: url) == before)}@@ -117,6 +162,7 @@ struct AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }for index in 0 ..< entryCount {storage.recordFailure(message: "entry-\(index)")}@@ -151,6 +197,7 @@ struct AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }storage.recordFailure(message: "existing")let model = AppServerLogViewModel(storage: storage)await model.refresh()@@ -180,6 +227,7 @@ struct AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url, limits: .init(entries: 4))+ defer { await #expect(throws: Never.self) { try await storage.close() } }for index in 0 ..< 4 {storage.recordFailure(message: "old-\(index)")}@@ -210,6 +258,7 @@ struct AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }let first = storage.beginRequest(method: "healthy", payload: "{}")storage.finishRequest(first, response: "ok")let broken = storage.beginRequest(method: "broken", payload: "{}")@@ -219,6 +268,7 @@ struct AppServerLogTests {defer { sqlite3_close(database) }#expect(sqlite3_exec(database, "UPDATE entries SET payload = x'7B' WHERE id = '\(broken.uuidString)'", nil, nil, nil) == SQLITE_OK)let reopened = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await reopened.close() } }let page = try await reopened.page(limit: 1)#expect(page.entries.first?.id == broken)#expect(page.entries.first?.method == "log/corrupt")@@ -230,6 +280,7 @@ struct AppServerLogTests {reopened.recordFailure(message: "still writes")#expect(try await reopened.page().total == 3)let again = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await again.close() } }#expect(try await again.page().entries.first(where: { $0.id == broken })?.detail == page.entries.first?.detail)try await again.clear()#expect(try await again.page().total == 0)@@ -239,6 +290,7 @@ struct AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }for index in 0 ..< 625 {let id = storage.beginRequest(method: "probe/\(index)", payload: "{\"secret\":\"unchanged\",\"index\":\(index)}", connection: "activity")storage.finishRequest(id, response: " response \(index)\n")@@ -250,6 +302,7 @@ struct AppServerLogTests {#expect(page.entries.first?.detail == " response 624\n")#expect(page.hasMore)let reopened = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await reopened.close() } }let restored = try await reopened.page(limit: 700)#expect(restored.total == 625)#expect(restored.entries.count == 625)@@ -262,6 +315,7 @@ struct AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }var ids: [UUID] = []for index in 0 ..< 12 {ids.append(storage.beginRequest(method: "probe/\(index)", payload: "{}"))@@ -285,6 +339,7 @@ struct AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }let pending = storage.beginRequest(method: "old", payload: "{}")let before = try await storage.page()try await storage.clear()@@ -297,6 +352,7 @@ struct AppServerLogTests {#expect(after.generation > before.generation)#expect(after.entries.first?.position ?? 0 > before.entries.first?.position ?? 0)let reopened = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await reopened.close() } }#expect(try await reopened.page().entries.map(\.id) == [new])}@@ -304,10 +360,12 @@ struct AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }var writer: AppServerLogStore? = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await writer?.close() } }let id = try #require(writer).beginRequest(method: "unfinished", payload: "{}")_ = try await writer?.page()writer = nillet reopened = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await reopened.close() } }let entry = try #require(try await reopened.page().entries.first)#expect(entry.id == id)#expect(entry.status == .failure)@@ -320,6 +378,7 @@ struct AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }var ids: [UUID] = []for index in 0 ..< 9 {ids.append(storage.beginRequest(method: "probe/\(index)", payload: "{}"))@@ -353,11 +412,13 @@ struct AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }let id = storage.beginRequest(method: "last", payload: "{}")storage.finishRequest(id, response: "saved")- try await storage.finish()+ try await storage.close()storage.recordFailure(message: "after shutdown")let reopened = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await reopened.close() } }let page = try await reopened.page()#expect(page.total == 1)#expect(page.entries.first?.detail == "saved")@@ -368,11 +429,14 @@ struct AppServerLogTests {defer { try? directory.remove() }let file = try directory.write("not a directory", to: "blocked")let storage = AppServerLogStore(directoryURL: file)+ defer { await #expect(throws: Never.self) { try await storage.close() } }storage.recordFailure(message: "recording remains nonthrowing")let store = AppServerLogViewModel(storage: storage)await store.refresh()#expect(store.errorMessage != nil)#expect(store.entries.isEmpty)+ await #expect(throws: (any Error).self) { try await storage.close() }+ #expect(try directory.openFilePaths().isEmpty)}}@@ -382,13 +446,15 @@ extension AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }let payload = String(repeating: "a", count: bodyBytes - 4) + "🙂"let id = storage.beginRequest(method: "large/request", payload: payload)storage.finishRequest(id, response: payload)storage.recordReceived(method: "large/event", payload: payload, connection: "activity")- try await storage.finish()+ try await storage.close()let reopened = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await reopened.close() } }let page = try await reopened.page()let request = try #require(page.entries.first { $0.id == id })let event = try #require(page.entries.first { $0.method == "large/event" })@@ -414,6 +480,7 @@ extension AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url, limits: .init(entries: 10))+ defer { await #expect(throws: Never.self) { try await storage.close() } }let first = storage.beginRequest(method: "old", payload: "{}")let initial = try await storage.page()for index in 0 ..< 40 {@@ -433,6 +500,7 @@ extension AppServerLogTests {defer { try? directory.remove() }let limits = AppServerLogStore.Limits(entries: 100, bytes: 4096, bodyBytes: 256, pageEntries: 10)let storage = AppServerLogStore(directoryURL: directory.url, limits: limits)+ defer { await #expect(throws: Never.self) { try await storage.close() } }let text = String(repeating: "你好🙂", count: 300)for index in 0 ..< 30 {let id = storage.beginRequest(method: "large-\(index)", payload: text)@@ -451,8 +519,9 @@ extension AppServerLogTests {#expect(entry.request?.contains("Truncated") == true)#expect(entry.request?.contains("�") == false)}- try await storage.finish()+ try await storage.close()let reopened = AppServerLogStore(directoryURL: directory.url, limits: limits)+ defer { await #expect(throws: Never.self) { try await reopened.close() } }#expect(try await reopened.page().total == page.total)let size = try directory.url.appendingPathComponent(AppServerLogStore.databaseName).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0@@ -463,6 +532,7 @@ extension AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url, limits: .init(pageEntries: 5))+ defer { await #expect(throws: Never.self) { try await storage.close() } }let model = AppServerLogViewModel(storage: storage, pageSize: 3, maximumEntries: 6)await model.refresh()for index in 0 ..< 20 {@@ -500,6 +570,7 @@ extension AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }let success = storage.beginRequest(method: "success", payload: "{}")let failure = storage.beginRequest(method: "failure", payload: "{}")let pending = try await storage.page().entries@@ -517,6 +588,7 @@ extension AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }storage.recordSent(method: "initialized", payload: "{}")storage.recordSent(method: "websocket/pong", payload: "ping", error: "disconnected")storage.recordReceived(method: "turn/completed", payload: #"{"status":"failed"}"#, connection: "activity")@@ -536,6 +608,7 @@ extension AppServerLogTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }let attempt = storage.recordConnection(method: "connection/open", detail: "socket", connection: "activity", status: .pending)#expect(try await storage.page().entries.first?.status == .pending)storage.finishRequest(attempt, response: "socket")@@ -548,6 +621,7 @@ extension AppServerLogTests {#expect(entries.first { $0.id == handshake }?.status == .failure)#expect(entries.first { $0.method == "connection/closed" }?.status == .information)let reopened = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await reopened.close() } }#expect(try await reopened.page().entries == entries)}}diff --git a/Tests/App/AppServer/AppServerRequestBudgetTests.swift b/Tests/App/AppServer/AppServerRequestBudgetTests.swiftindex f7b9c24..02c2ffb 100644--- a/Tests/App/AppServer/AppServerRequestBudgetTests.swift+++ b/Tests/App/AppServer/AppServerRequestBudgetTests.swift@@ -77,7 +77,7 @@ struct AppServerRequestBudgetTests {defer { server.close() }let socketURL = server.urltry await Task.detached {- let service = CodexStatusService(socketURL: socketURL)+ let service = CodexStatusService(socketURL: socketURL, logStorage: nil)do {_ = try await service.consumeResetCredit(id: "test-credit", idempotencyKey: "test-key",diff --git a/Tests/App/AppServer/AppServerSessionTests.swift b/Tests/App/AppServer/AppServerSessionTests.swiftindex 6e4f6c9..273d0d1 100644--- a/Tests/App/AppServer/AppServerSessionTests.swift+++ b/Tests/App/AppServer/AppServerSessionTests.swift@@ -231,6 +231,7 @@ struct AppServerSessionTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }let (filtered, retained) = try logDeliveryMessages()let messages = filtered + retainedlet server = try SharedServerFixture { peer in@@ -288,6 +289,7 @@ struct AppServerSessionTests {#expect(page.entries.first { $0.method == "probe" }?.status == .success)#expect(page.entries.contains { $0.method == "connection/closed" })let reopened = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await reopened.close() } }#expect(try await reopened.page(limit: 200).entries == page.entries)}@@ -484,6 +486,7 @@ struct AppServerSessionTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }let server = try SharedServerFixture { peer inlet request = try peer.readMessage()try peer.send(["id": #require(request["id"]), "error": ["message": "body and secret", "code": -1]])@@ -511,6 +514,7 @@ struct AppServerSessionTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }let server = try SharedServerFixture { peer inlet request = try peer.readMessage()try peer.send(["method": "thread/tokenUsage/updated", "params": ["token": 123]])@@ -558,6 +562,7 @@ struct AppServerSessionTests {let directory = try TestDirectory()defer { try? directory.remove() }let storage = AppServerLogStore(directoryURL: directory.url)+ defer { await #expect(throws: Never.self) { try await storage.close() } }let server = try SharedServerFixture { peer in_ = try peer.readMessage()try peer.sendRaw(Data("{broken JSON".utf8))diff --git a/Tests/App/History/HistoryDatabaseStoreTests.swift b/Tests/App/History/HistoryDatabaseStoreTests.swiftindex cacb417..522af63 100644--- a/Tests/App/History/HistoryDatabaseStoreTests.swift+++ b/Tests/App/History/HistoryDatabaseStoreTests.swift@@ -3,6 +3,18 @@ import SQLite3import Testingstruct HistoryDatabaseStoreTests {+ @Test func releasingConnectionPreservesCommittedData() async throws {+ let directory = try TestDirectory()+ defer { await #expect(throws: Never.self) { try await directory.removeAfterClosingHistory() } }+ let store = HistoryDatabaseStore.shared(in: directory.url)+ try await store.access { try $0.execute("INSERT INTO days(date) VALUES ('committed')") }+ #expect(try !directory.openFilePaths().isEmpty)+ await store.releaseConnection()+ await store.releaseConnection()+ #expect(try directory.openFilePaths().isEmpty)+ #expect(try await store.access { try $0.dates() } == ["committed"])+ }+@Test func activityAndTokenWritersUseTheSharedConnection() async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -125,8 +137,13 @@ struct HistoryDatabaseStoreTests {@Test func replacingDatabaseReopensConnectionAndDiscardsThreadSnapshots() async throws {let directory = try TestDirectory()defer { try? directory.remove() }- let store = HistoryDatabaseStore.shared(in: directory.url)- let tokens = TokenUsageHistoryStore(directoryURL: directory.url)+ let activeDirectory = directory.url.appendingPathComponent("active", isDirectory: true)+ let store = HistoryDatabaseStore.shared(in: activeDirectory)+ defer {+ await store.releaseConnection()+ #expect(throws: Never.self) { try #require(directory.openFilePaths().isEmpty) }+ }+ let tokens = TokenUsageHistoryStore(directoryURL: activeDirectory)let now = Date()let first = Self.observation(tokens: 5, at: now)try await tokens.appendObservation(first)@@ -134,9 +151,9 @@ struct HistoryDatabaseStoreTests {let replacementDirectory = directory.url.appendingPathComponent("replacement", isDirectory: true)let replacement = Self.observation(tokens: 20, at: now)try HistoryDatabase(directoryURL: replacementDirectory).append(AppServerEventRecord(tokenUsage: replacement, recordedAt: now))- let url = directory.url.appendingPathComponent("event.db")- try FileManager.default.moveItem(at: url, to: directory.url.appendingPathComponent("previous.db"))- try FileManager.default.moveItem(at: replacementDirectory.appendingPathComponent("event.db"), to: url)+ // 替换容器目录以改变数据库身份, 避免直接重命名 SQLite 监视的文件+ try FileManager.default.moveItem(at: activeDirectory, to: directory.url.appendingPathComponent("previous", isDirectory: true))+ try FileManager.default.moveItem(at: replacementDirectory, to: activeDirectory)#expect(try await tokens.snapshot(threadID: "thread").turns["turn"]?.totalTokens == 20)#expect(try await store.access { try $0.dates() } == [HistoryStorage.dateKey(for: now)])}diff --git a/Tests/App/History/StorageRetentionTests.swift b/Tests/App/History/StorageRetentionTests.swiftindex 8628aa4..fa54900 100644--- a/Tests/App/History/StorageRetentionTests.swift+++ b/Tests/App/History/StorageRetentionTests.swift@@ -47,6 +47,7 @@ struct StorageRetentionTests {defer { try? directory.remove() }let clock = RetentionClock()let storage = AppServerLogStore(directoryURL: directory.url, now: { clock.read() })+ defer { await #expect(throws: Never.self) { try await storage.close() } }let expired = storage.beginRequest(method: "expired", payload: "{}")let boundary = storage.beginRequest(method: "boundary", payload: "{}")let original = try await storage.page()@@ -61,6 +62,7 @@ struct StorageRetentionTests {}clock.set(tomorrow)let reader = reopen ? AppServerLogStore(directoryURL: directory.url, now: { clock.read() }) : storage+ defer { await #expect(throws: Never.self) { try await reader.close() } }let page = try await reader.page()#expect(page.total == 1)#expect(page.entries.map(\.id) == [boundary])diff --git a/Tests/App/Notifications/TaskWaitingNotificationTests.swift b/Tests/App/Notifications/TaskWaitingNotificationTests.swiftindex d803655..4cbbb03 100644--- a/Tests/App/Notifications/TaskWaitingNotificationTests.swift+++ b/Tests/App/Notifications/TaskWaitingNotificationTests.swift@@ -3,21 +3,34 @@ import Testingimport UserNotificationsstruct TaskWaitingNotificationTests {+ @Test(arguments: [false, true])+ func monitorTransitionDeliversAndSnapshotWithdrawsNotification(blockingInput: Bool) async throws {+ let fixture = try Fixture()+ defer { fixture.cleanUp() }+ try await fixture.start()+ try fixture.publishWaiting(blockingInput: blockingInput)+ try await waitUntil { fixture.delivery.delivered == [fixture.identifier] }+ #expect(fixture.delivery.attempts == [fixture.identifier])+ try fixture.resolveWaiting()+ #expect(fixture.delivery.delivered.isEmpty)+ #expect(fixture.delivery.removals == [[fixture.identifier]])+ }+@Test(arguments: [false, true])func resolvedBeforeSubmissionSkipsDeliveryAndClearsTracking(blockingInput: Bool) async throws {let fixture = try Fixture()defer { fixture.cleanUp() }try await fixture.start()let submission = try fixture.enterWaiting(blockingInput: blockingInput)- #expect(fixture.service.taskWaitingNotificationIdentifiersForTesting == [fixture.identifier])try fixture.resolveWaiting()- #expect(fixture.service.taskWaitingNotificationIdentifiersForTesting.isEmpty)#expect(fixture.delivery.attempts.isEmpty)#expect(await submission.value == false)#expect(fixture.delivery.attempts.isEmpty)#expect(fixture.delivery.delivered.isEmpty)#expect(fixture.delivery.removals == [[fixture.identifier]])+ try fixture.resolveWaiting()+ #expect(fixture.delivery.removals == [[fixture.identifier]])}@Test(arguments: [false, true])@@ -30,14 +43,12 @@ struct TaskWaitingNotificationTests {try await waitUntil { fixture.delivery.hasPendingSubmission }try fixture.resolveWaiting()- #expect(fixture.service.taskWaitingNotificationIdentifiersForTesting.isEmpty)#expect(fixture.delivery.removals == [[fixture.identifier]])fixture.delivery.resumeSubmission()#expect(await submission.value == false)#expect(fixture.delivery.attempts.count == 1)#expect(fixture.delivery.delivered.isEmpty)#expect(fixture.delivery.removals == [[fixture.identifier], [fixture.identifier]])- #expect(fixture.service.taskWaitingNotificationIdentifiersForTesting.isEmpty)}@Test(arguments: [false, true])@@ -48,14 +59,14 @@ struct TaskWaitingNotificationTests {let submission = try fixture.enterWaiting(blockingInput: blockingInput)#expect(await submission.value)#expect(fixture.delivery.delivered == [fixture.identifier])- #expect(fixture.service.taskWaitingNotificationIdentifiersForTesting == [fixture.identifier])try fixture.resolveWaiting(keepsNonblockingQuestion: true)#expect(fixture.monitor.snapshot.panelWaitingTasks.count == 1)#expect(fixture.monitor.snapshot.blockingWaitingTaskIDs.isEmpty)#expect(fixture.delivery.delivered.isEmpty)#expect(fixture.delivery.removals == [[fixture.identifier]])- #expect(fixture.service.taskWaitingNotificationIdentifiersForTesting.isEmpty)+ try fixture.resolveWaiting()+ #expect(fixture.delivery.removals == [[fixture.identifier]])}@Test(arguments: [false, true])@@ -68,7 +79,6 @@ struct TaskWaitingNotificationTests {#expect(await submission.value == false)#expect(fixture.delivery.attempts.count == 2)#expect(fixture.monitor.snapshot.blockingWaitingTaskIDs == [fixture.taskID])- #expect(fixture.service.taskWaitingNotificationIdentifiersForTesting.isEmpty)#expect(fixture.delivery.delivered.isEmpty)#expect(fixture.delivery.removals.isEmpty)@@ -79,7 +89,8 @@ struct TaskWaitingNotificationTests {#expect(fixture.delivery.delivered == [fixture.identifier])try fixture.resolveWaiting()#expect(fixture.delivery.removals == [[fixture.identifier]])- #expect(fixture.service.taskWaitingNotificationIdentifiersForTesting.isEmpty)+ try fixture.resolveWaiting()+ #expect(fixture.delivery.removals == [[fixture.identifier]])}}@@ -139,6 +150,17 @@ private final class Fixture {}func enterWaiting(blockingInput: Bool) throws -> Task<Bool, Never> {+ let transition = try waitingTransition(blockingInput: blockingInput)+ monitor.acceptFixtureGraph(graph)+ return try #require(service.handleActivityTransition(transition))+ }++ func publishWaiting(blockingInput: Bool) throws {+ let transition = try waitingTransition(blockingInput: blockingInput)+ monitor.acceptFixtureGraph(graph, transitions: [transition])+ }++ private func waitingTransition(blockingInput: Bool) throws -> ActivityTransition {let now = Date()if blockingInput {graph.tasks[key]?.executions[owner]?.presentation = try question(blocking: true, at: now)@@ -146,8 +168,7 @@ private final class Fixture {_ = graph.tasks[key]?.recordApprovalRequest(from: TestFixtures.event(.approvalRequested, at: now))}let snapshot = try #require(graph.tasks[key]?.snapshot)- monitor.acceptFixtureGraph(graph, transitions: [.waiting(snapshot, since: now)])- return try #require(service.lastSubmissionTaskForTesting)+ return .waiting(snapshot, since: now)}func resolveWaiting(keepsNonblockingQuestion: Bool = false) throws {diff --git a/Tests/App/Presentation/SettingsTests.swift b/Tests/App/Presentation/SettingsTests.swiftindex 19a38b0..5623843 100644--- a/Tests/App/Presentation/SettingsTests.swift+++ b/Tests/App/Presentation/SettingsTests.swift@@ -71,7 +71,7 @@ struct SettingsTests {}private nonisolated func makeStatusService(suiteName: String) -> CodexStatusService {- CodexStatusService(socketURL: URL(fileURLWithPath: "/tmp/\(suiteName).sock"))+ CodexStatusService(socketURL: URL(fileURLWithPath: "/tmp/\(suiteName).sock"), logStorage: nil)}@Test func mainPanelAnimationsPreserveStoredPreferenceAndDefault() throws {diff --git a/Tests/App/Support/JSONFileStorageTests.swift b/Tests/App/Support/JSONFileStorageTests.swiftindex fae706a..6124f4a 100644--- a/Tests/App/Support/JSONFileStorageTests.swift+++ b/Tests/App/Support/JSONFileStorageTests.swift@@ -45,7 +45,7 @@ struct JSONFileStorageTests {let first = try #require(try JSONFileStorage.acquireLock(at: directory.url.appendingPathComponent("first/store.lock"), nonblocking: true))defer { JSONFileStorage.releaseLock(first) }let second = try #require(try JSONFileStorage.acquireLock(at: directory.url.appendingPathComponent("second/store.lock"), nonblocking: true))- defer { JSONFileStorage.releaseLock(second) }+ JSONFileStorage.releaseLock(second)}@Test nonisolated func storageFailureIsDistinctFromLockContention() throws {diff --git a/Tests/App/Support/TestSupport.swift b/Tests/App/Support/TestSupport.swiftindex 72e0fdd..8953e95 100644--- a/Tests/App/Support/TestSupport.swift+++ b/Tests/App/Support/TestSupport.swift@@ -1,3 +1,4 @@+import Darwinimport Foundationimport Testing@@ -108,6 +109,32 @@ nonisolated struct TestDirectory {try FileManager.default.removeItem(at: url)}+ func removeAfterClosingHistory() async throws {+ await HistoryDatabaseStore.shared(in: url).releaseConnection()+ try #require(openFilePaths().isEmpty)+ try remove()+ }++ func openFilePaths() throws -> [String] {+ let byteCount = proc_pidinfo(getpid(), PROC_PIDLISTFDS, 0, nil, 0)+ guard byteCount > 0 else { throw POSIXError(.EIO) }+ var descriptors = [proc_fdinfo](repeating: proc_fdinfo(), count: Int(byteCount) / MemoryLayout<proc_fdinfo>.stride)+ let written = descriptors.withUnsafeMutableBytes { buffer in+ proc_pidinfo(getpid(), PROC_PIDLISTFDS, 0, buffer.baseAddress, Int32(buffer.count))+ }+ guard written > 0 else { throw POSIXError(.EIO) }+ let prefix = url.resolvingSymlinksInPath().path + "/"+ return descriptors.prefix(Int(written) / MemoryLayout<proc_fdinfo>.stride).compactMap { descriptor in+ guard descriptor.proc_fdtype == PROX_FDTYPE_VNODE else { return nil }+ var path = [CChar](repeating: 0, count: Int(MAXPATHLEN))+ guard fcntl(descriptor.proc_fd, F_GETPATH, &path) == 0 else { return nil }+ let bytes = path.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }+ guard let value = String(bytes: bytes, encoding: .utf8) else { return nil }+ let normalized = URL(fileURLWithPath: value).resolvingSymlinksInPath().path+ return normalized.hasPrefix(prefix) ? value : nil+ }+ }+func executable(_ body: String, named name: String = "test command") throws -> URL {let command = try write("#!/bin/sh\n\(body)\n", to: name)try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: command.path)diff --git a/Tests/App/Sync/SyncRecoveryTests.swift b/Tests/App/Sync/SyncRecoveryTests.swiftindex 0d6ecd5..2b404d1 100644--- a/Tests/App/Sync/SyncRecoveryTests.swift+++ b/Tests/App/Sync/SyncRecoveryTests.swift@@ -422,7 +422,7 @@ struct SyncRecoveryTests {@Test func sameSourceRecalculationCanReduceCountsWithoutDeletingRecord() async throws {let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }let before = try #require(await fixture.database.activityDataRecords().first)let result = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)let after = try #require(await fixture.database.activityDataRecords().first)@@ -477,7 +477,7 @@ struct SyncRecoveryTests {@Test func recreatedJournalReplacesSameDeviceDateInsteadOfAddingAnotherBatch() async throws {let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }let previous = try #require(await fixture.database.activityDataRecords().first)let event = TestFixtures.event(.toolStarted, at: Date(), turn: "different")try fixture.directory.replaceHistory(@@ -497,7 +497,7 @@ struct SyncRecoveryTests {@Test func unknownCloudVersionPreservesCacheAndPreventsActivityDataUpload() async throws {let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }let cacheURL = fixture.directory.url.appendingPathComponent("Sync/activityData.json")let before = try Data(contentsOf: cacheURL)let unsupported = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "future", zoneID: Self.zone))@@ -700,7 +700,7 @@ private actor SyncDatabaseFixture: SyncDatabase {extension SyncRecoveryTests {@Test func failedUploadPreservesRemoteAndRetriesAfterRestart() async throws {let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }let outcome = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)#expect(outcome.summary.isSyncPending)await fixture.database.failActivityDataUpload(on: fixture.date)@@ -716,7 +716,7 @@ extension SyncRecoveryTests {@Test func repeatedRebuildKeepsSourceAndNeedsNoSeparateAcknowledgement() async throws {let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }let initial = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)#expect(initial.summary.failedTokenUsageDateKeys.isEmpty)#expect(!initial.summary.didFailTokenUsageRebuild)@@ -730,7 +730,7 @@ extension SyncRecoveryTests {@Test func unavailableSourceCannotOverwriteRemoteAndRecoversAfterRepair() async throws {let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }let local = try HistoryDatabase(directoryURL: fixture.directory.url)let original = try local.exportJSONLines(date: fixture.date)try local.execute("UPDATE events SET payload = ?", [.data(Data("broken".utf8))])@@ -749,7 +749,7 @@ extension SyncRecoveryTests {@Test func requestSaveFailureDoesNotModifyAggregateOrCloud() async throws {let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }let local = try HistoryDatabase(directoryURL: fixture.directory.url)let original = try local.activityDataAggregates()try local.execute("CREATE TRIGGER reject_aggregate BEFORE UPDATE ON aggregates BEGIN SELECT RAISE(ABORT, 'injected failure'); END")@@ -762,7 +762,7 @@ extension SyncRecoveryTests {@Test func disabledSyncKeepsUpdatedAggregateForNextEnabledRun() async throws {let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }let disabled = SyncService(database: fixture.database, directoryURL: fixture.directory.url, isEnabled: { false })let history = HistoryService(directoryURL: fixture.directory.url, syncService: disabled)_ = try await history.rebuildData(for: [fixture.date], synchronize: true)@@ -773,7 +773,7 @@ extension SyncRecoveryTests {@Test func appendedEventsUpdateSameDeviceDailyCounts() async throws {let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }let activityDataRecorder = ActivityDataRecorder(directoryURL: fixture.directory.url)let event = ActivityDataRecord(timestamp: Date(),@@ -798,7 +798,7 @@ extension SyncRecoveryTests {@Test func unavailableTokenUsageHistoryMarksAllRequestedDatesFailed() async throws {let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }let brokenDirectory = try TestDirectory()defer { try? brokenDirectory.remove() }_ = try brokenDirectory.write(Data("broken".utf8), to: "event.db")@@ -820,7 +820,7 @@ extension SyncRecoveryTests {@Test func partialTokenUsageFailureIsReportedWithoutClaimingWholeDaySuccess() async throws {let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }let now = Date()let good = TestFixtures.tokenUsageObservation(id: "good", at: now, tokenUsage: .zero)let bad = TokenUsageObservation(id: "bad", observedAt: now, previous: Self.counts(10), current: TokenUsageUpdate(total: .zero, last: .zero))@@ -865,7 +865,7 @@ private struct HistoryRebuildFixture {extension SyncRecoveryTests {@Test func rebuildUploadsAlgorithmVersionEvenWhenCountsAreUnchanged() async throws {let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }var previous = fixture.localprevious.aggregationVersion = 1try HistoryDatabase(directoryURL: fixture.directory.url).execute(