CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
refactor: 精简重复测试并保留关键回归覆盖
Bob71a86960a1e6
diff --git a/CodexBar/Controllers/ScreenGeometry.swift b/CodexBar/Controllers/ScreenGeometry.swiftindex 57e61bd..3d8f9bf 100644--- a/CodexBar/Controllers/ScreenGeometry.swift+++ b/CodexBar/Controllers/ScreenGeometry.swift@@ -1,9 +1,9 @@import AppKit/// 屏幕坐标相关的共享几何工具+@MainActorextension NSScreen {/// 鼠标当前所在屏幕- @MainActorstatic func containingMouse() -> NSScreen? {let mouseLocation = NSEvent.mouseLocationreturn NSScreen.screens.first { screen in@@ -24,9 +24,9 @@ nonisolated extension CGRect {}}+@MainActorextension NSWindow {/// LSUIElement 应用无 Dock 图标, 把窗口可靠拉到最前依赖这套固定激活序列- @MainActorfunc bringToFrontActivatingApp() {orderFrontRegardless()NSRunningApplication.current.activate(options: [])@@ -34,9 +34,9 @@ extension NSWindow {}}+@MainActorextension NSView {/// SwiftUI hosting 视图的 fittingSize 可能给出非有限或非正尺寸, 校验通过才能用于窗口布局- @MainActorvar validFittingSize: NSSize? {layoutSubtreeIfNeeded()let size = fittingSizediff --git a/CodexBar/Services/Activity/ActivityTask.swift b/CodexBar/Services/Activity/ActivityTask.swiftindex cbcb5ed..2956966 100644--- a/CodexBar/Services/Activity/ActivityTask.swift+++ b/CodexBar/Services/Activity/ActivityTask.swift@@ -343,11 +343,9 @@ nonisolated struct ActivityTask {state = .waitingApprovalstateChangedAt = approval.requestedAt}- } else if state == .waitingApproval || restoresRunning {- if state != .running {- state = .running- stateChangedAt = timestamp- }+ } else if state == .waitingApproval || restoresRunning, state != .running {+ state = .running+ stateChangedAt = timestamp}}}diff --git a/CodexBar/Services/Activity/ActivityTaskGraph.swift b/CodexBar/Services/Activity/ActivityTaskGraph.swiftindex fcd7e13..c4f1ba4 100644--- a/CodexBar/Services/Activity/ActivityTaskGraph.swift+++ b/CodexBar/Services/Activity/ActivityTaskGraph.swift@@ -133,8 +133,7 @@ nonisolated struct ActivityTaskGraph {private mutating func resumeTask(from event: ActivityDataRecord) -> ActivityTaskKey? {guard let eventKey = ActivityTaskKey(event: event) else { return nil }let matchedKey = event.agentThreadID == nil ? eventKey : matchingSubagentParentTaskKey(for: event)- guard let key = matchedKey, recentEndedDate(for: key) == nil, pendingTerminalTasks[key] == nil else { return nil }- guard tasks[key] != nil || event.agentThreadID == nil else { return nil }+ guard let key = matchedKey, recentEndedDate(for: key) == nil, pendingTerminalTasks[key] == nil, tasks[key] != nil || event.agentThreadID == nil else { return nil }var task = tasks[key] ?? ActivityTask(displayID: UUID(), key: key, event: event, state: .running, startedAt: nil, progressGeneration: 0)guard task.acceptsExecutionEvent(event) else { return nil }task.mergeMetadata(from: event)diff --git a/CodexBar/Services/Activity/AppServerActivityReducer.swift b/CodexBar/Services/Activity/AppServerActivityReducer.swiftindex a4e2715..d335bb4 100644--- a/CodexBar/Services/Activity/AppServerActivityReducer.swift+++ b/CodexBar/Services/Activity/AppServerActivityReducer.swift@@ -230,8 +230,7 @@ nonisolated struct AppServerActivityReducer {value.context = contextreturn value}.filter { value in- guard let id = value.id else { return false }- guard seenEvents[id] == nil else { return false }+ guard let id = value.id, seenEvents[id] == nil else { return false }seenEvents[id] = nowreturn true}diff --git a/CodexBar/Services/AppServer/AppServerLogStore.swift b/CodexBar/Services/AppServer/AppServerLogStore.swiftindex f506fcc..76297e7 100644--- a/CodexBar/Services/AppServer/AppServerLogStore.swift+++ b/CodexBar/Services/AppServer/AppServerLogStore.swift@@ -207,8 +207,7 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {let statement = try storage.prepare("SELECT position, payload, id FROM entries WHERE id = ?")defer { sqlite3_finalize(statement) }try storage.bind(id.uuidString, to: statement, at: 1)- guard try storage.step(statement) == SQLITE_ROW else { return }- guard var entry = storage.decode(statement, skipCorrupt: true) else { return }+ guard try storage.step(statement) == SQLITE_ROW, var entry = storage.decode(statement, skipCorrupt: true) else { return }entry.status = statusentry.detail = detailentry.detailOriginalBytes = originalBytes > storage.limits.bodyBytes ? originalBytes : nildiff --git a/CodexBar/Services/AppServer/AppServerSession.swift b/CodexBar/Services/AppServer/AppServerSession.swiftindex 3016d1c..caf23cf 100644--- a/CodexBar/Services/AppServer/AppServerSession.swift+++ b/CodexBar/Services/AppServer/AppServerSession.swift@@ -48,8 +48,7 @@ final nonisolated class AppServerSession {let connectionLogID = logStorage?.recordConnection(method: "connection/open", detail: socketPath, connection: connectionName, status: .pending)do {descriptor = socket(AF_UNIX, SOCK_STREAM, 0)- guard descriptor >= 0 else { throw AppServerConnectionError(code: errno) }- guard fcntl(descriptor, F_SETFL, O_NONBLOCK) == 0 else { throw AppServerConnectionError(code: errno) }+ guard descriptor >= 0, fcntl(descriptor, F_SETFL, O_NONBLOCK) == 0 else { throw AppServerConnectionError(code: errno) }var address = sockaddr_un()address.sun_family = sa_family_t(AF_UNIX)let path = Array(socketURL.path.utf8CString)diff --git a/CodexBar/Services/CodexStatus/AutoResetController.swift b/CodexBar/Services/CodexStatus/AutoResetController.swiftindex c684853..8dcecbb 100644--- a/CodexBar/Services/CodexStatus/AutoResetController.swift+++ b/CodexBar/Services/CodexStatus/AutoResetController.swift@@ -293,8 +293,7 @@ final class AutoResetController {let read = try await dependencies.read(budget)guard isCurrent(generation) else { return }reconcile(read)- guard read.candidates != nil else { return }- guard let currentTarget = target else { return }+ guard read.candidates != nil, let currentTarget = target else { return }if let evaluation, evaluation.target.key != currentTarget.key {return}diff --git a/CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift b/CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swiftindex 6b2692f..f9a3032 100644--- a/CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift+++ b/CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift@@ -176,10 +176,7 @@ final class AutoResetWakeScheduler {}private func reconcile() {- guard preparationState == .none else {- return- }- guard isPowerHelperReady else {+ guard preparationState == .none, isPowerHelperReady else {return}guard syncTask == nil else {diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swiftindex 2fef0ba..d2c13a8 100644--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift@@ -535,10 +535,7 @@ final class KeepAliveController: ObservableObject {private func refreshRegisteredPowerHelper() async {let requiresSleepReset = powerHelperStatus == .enabled- guard let fingerprint = powerHelperPackageValidation.fingerprint else {- return- }- guard autoResetWakeScheduler.beginPowerHelperInterruptionPreparation() else {+ guard let fingerprint = powerHelperPackageValidation.fingerprint, autoResetWakeScheduler.beginPowerHelperInterruptionPreparation() else {return}let updateIdentifier = PowerHelperConfiguration.beginUpdate(@@ -570,11 +567,7 @@ final class KeepAliveController: ObservableObject {}guard isStarted,- !Task.isCancelled else {- return- }-- guard await refreshPowerHelperStatus() else { return }+ !Task.isCancelled, await refreshPowerHelperStatus() else { return }var powerHelperWasUpdated = falseif updateError == nil,powerHelperStatus.isRegisteredOrAwaitingApproval {@@ -1354,10 +1347,7 @@ final class KeepAliveController: ObservableObject {retryTask = Task { @MainActor [weak self] intry? await Task.sleep(for: delay)- guard !Task.isCancelled, let self else {- return- }- guard await refreshPowerHelperStatus(), isStarted, !Task.isCancelled, powerHelperStatus == .enabled else {+ guard !Task.isCancelled, let self, await refreshPowerHelperStatus(), isStarted, !Task.isCancelled, powerHelperStatus == .enabled else {return}retryTask = nildiff --git a/CodexBar/Services/Settings/MainPanelSettings.swift b/CodexBar/Services/Settings/MainPanelSettings.swiftindex f8f0390..85bcdcd 100644--- a/CodexBar/Services/Settings/MainPanelSettings.swift+++ b/CodexBar/Services/Settings/MainPanelSettings.swift@@ -86,10 +86,7 @@ final class MainPanelSettings: ObservableObject {isVisible: Bool,undoManager: UndoManager) {- guard layout.isVisible(section) != isVisible else {- return- }- guard isVisible || layout.visibleSections.count > 1 else {+ guard layout.isVisible(section) != isVisible, isVisible || layout.visibleSections.count > 1 else {return}diff --git a/CodexBar/Views/Settings/RebuildDateRange.swift b/CodexBar/Views/Settings/RebuildDateRange.swiftindex 3d1d8a3..ac56aed 100644--- a/CodexBar/Views/Settings/RebuildDateRange.swift+++ b/CodexBar/Views/Settings/RebuildDateRange.swift@@ -15,15 +15,11 @@ struct RebuildDateRange: Equatable {var dayCount: Int {guard let endDateKey,let startDate = CodexDateFormat.dayDate(from: startDateKey),- let endDate = CodexDateFormat.dayDate(from: endDateKey) else {- return 0- }-- guard let dayDifference = CodexDateFormat.localGregorianCalendar.dateComponents(- [.day],- from: startDate,- to: endDate- ).day else {+ let endDate = CodexDateFormat.dayDate(from: endDateKey), let dayDifference = CodexDateFormat.localGregorianCalendar.dateComponents(+ [.day],+ from: startDate,+ to: endDate+ ).day else {return 0}return dayDifference + 1diff --git a/Tests/App/Activity/ActivityLivePresentationTests.swift b/Tests/App/Activity/ActivityLivePresentationTests.swiftindex 2ea0f4a..5244bc2 100644--- a/Tests/App/Activity/ActivityLivePresentationTests.swift+++ b/Tests/App/Activity/ActivityLivePresentationTests.swift@@ -416,20 +416,28 @@ struct ActivityLivePresentationTests {("closeAgent", ("agent-closing", "activity.action.close-subagent")),("listAgents", ("agent-querying", "activity.action.query-subagent")),("future", ("agent-coordinating", "activity.action.coordinate-subagents"))- ] as [(String, (String, LocalizedStringResource))], ["completed", "failed", "declined"])- func subagentOperationOutcomesDescribeTheCall(- operation: (tool: String, expected: (statusKey: String, action: LocalizedStringResource)), status: String- ) {+ ] as [(String, (String, LocalizedStringResource))])+ func subagentOperationsDescribeTheCall(operation: (tool: String, expected: (statusKey: String, action: LocalizedStringResource))) {let item = ActivityItem(- id: "agent", type: .collabAgentToolCall, status: status, tool: operation.tool,+ id: "agent", type: .collabAgentToolCall, status: "completed", tool: operation.tool,agentsStates: ["child": .init(status: "running")])#expect(item.liveLabel?.key == operation.expected.statusKey)- #expect(item.liveCompletionLabel?.key == "action-" + status)+ #expect(item.liveCompletionLabel?.key == "action-completed")#expect(item.liveCompletionLabel?.detail == String(localized: operation.expected.action))#expect(ActivityDisplayFormat.toolActionText(itemType: item.type.rawValue, toolName: operation.tool) == item.liveCompletionLabel?.detail)}+ @Test(arguments: ["completed", "failed", "declined"])+ func subagentCompletionPreservesOutcome(status: String) {+ let item = ActivityItem(+ id: "agent", type: .collabAgentToolCall, status: status, tool: "spawnAgent",+ agentsStates: ["child": .init(status: "running")]+ )+ #expect(item.liveCompletionLabel?.key == "action-" + status)+ #expect(item.liveCompletionLabel?.detail == String(localized: "activity.action.start-subagent"))+ }+@Test(arguments: [("commandExecution", "activity.action.command"), ("fileChange", "activity.action.edit-files"),("webSearch", "activity.action.search-web"), ("imageView", "activity.action.view-image"),diff --git a/Tests/App/Activity/ActivityRecoveryTests.swift b/Tests/App/Activity/ActivityRecoveryTests.swiftindex 817152c..55af8f8 100644--- a/Tests/App/Activity/ActivityRecoveryTests.swift+++ b/Tests/App/Activity/ActivityRecoveryTests.swift@@ -2,28 +2,6 @@ import Foundationimport Testingstruct ActivityRecoveryTests {- @Test func damagedDerivedCacheRecoversRefreshAndRebuild() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let now = Date()- let store = TokenUsageHistoryStore(directoryURL: directory.url)- try await store.appendObservation(TestFixtures.tokenUsageObservation(at: now, tokenUsage: .zero), now: now)- _ = try await store.refresh(now: now)- let database = try HistoryDatabase(directoryURL: directory.url)- try database.execute("UPDATE aggregates SET tokenUsage = ?", [.data(Data("broken".utf8))])- var refreshFailed = false- var rebuildFailed = false- do { _ = try await store.refresh(now: now) } catch { refreshFailed = true }- try database.execute("UPDATE aggregates SET tokenUsage = ?", [.data(Data("broken".utf8))])- do { _ = try await store.rebuild(for: [CodexDateFormat.dayString(from: now)]) } catch { rebuildFailed = true }- #expect(!refreshFailed && !rebuildFailed)- try database.execute("""- UPDATE aggregates SET tokenUsage = NULL- """)- let recovered = try await store.refresh(now: now)- #expect(recovered.count == 1)- }-@Test(arguments: [false, true])func laterMalformedMessagePreservesEarlierValidEvent(_ malformed: Bool) async throws {let directory = try TestDirectory()diff --git a/Tests/App/Activity/AppServerActivityTests.swift b/Tests/App/Activity/AppServerActivityTests.swiftindex e584ff2..04d7211 100644--- a/Tests/App/Activity/AppServerActivityTests.swift+++ b/Tests/App/Activity/AppServerActivityTests.swift@@ -357,18 +357,6 @@ struct AppServerActivityTests {#expect(records.first?.tokenUsage == tokenUsage)}- @Test func tokenWriterLeaseTransfersWithoutTwoWriters() throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let first = TokenUsageHistoryStore(directoryURL: directory.url)- let second = TokenUsageHistoryStore(directoryURL: directory.url)- #expect(try first.acquireRecordingLease())- #expect(try !second.acquireRecordingLease())- first.releaseRecordingLease()- #expect(try second.acquireRecordingLease())- second.releaseRecordingLease()- }-@Test func rebuildUsesObservedRecordsAndContinuesCollecting() async throws {let directory = try TestDirectory()defer { try? directory.remove() }diff --git a/Tests/App/AppServer/AppServerRPCTests.swift b/Tests/App/AppServer/AppServerRPCTests.swiftindex 1af33d6..f9715a1 100644--- a/Tests/App/AppServer/AppServerRPCTests.swift+++ b/Tests/App/AppServer/AppServerRPCTests.swift@@ -48,6 +48,7 @@ struct AppServerRPCTests {}do {let _: Int = try AppServerRPC.decode(Data(#"{"result":"wrong"}"#.utf8), as: Int.self)+ Issue.record("Expected invalid response payload")} catch let error as CodexStatusError {#expect(!error.isTransportFailure)} catch { Issue.record(error) }diff --git a/Tests/App/Codex/CodexVersionTests.swift b/Tests/App/Codex/CodexVersionTests.swiftindex 4e7661c..77ac85d 100644--- a/Tests/App/Codex/CodexVersionTests.swift+++ b/Tests/App/Codex/CodexVersionTests.swift@@ -3,13 +3,6 @@ import Testingstruct CodexVersionTests {@Test(arguments: [- ("0.150.0", false),- ("0.156.0", false),- ("0.157.0-alpha.2", false),- ("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),diff --git a/Tests/App/CodexStatus/CodexServiceStatusTests.swift b/Tests/App/CodexStatus/CodexServiceStatusTests.swiftindex b5b3aae..1c52135 100644--- a/Tests/App/CodexStatus/CodexServiceStatusTests.swift+++ b/Tests/App/CodexStatus/CodexServiceStatusTests.swift@@ -16,13 +16,6 @@ struct CodexServiceStatusTests {#expect(try CodexServiceStatus(data: data) == CodexServiceStatus(level: .degradedPerformance, componentNames: [name]))}- @Test(arguments: CodexServiceStatus.Level.allCases)- func preservesComponentLevel(_ level: CodexServiceStatus.Level) throws {- let status = try CodexServiceStatus(data: Self.response(affected: [("cli", level.rawValue)]))- #expect(status.level == level)- #expect(status.componentNames == (level == .operational ? [] : ["CLI"]))- }-@Test func reportsHighestComponentsOnceInCatalogOrder() throws {let affected = [("web", "partial_outage"), ("cli", "full_outage"), ("api", "full_outage"), ("cli", "degraded_performance"),diff --git a/Tests/App/History/HistoryDatabaseTests.swift b/Tests/App/History/HistoryDatabaseTests.swiftindex 019a273..91f170f 100644--- a/Tests/App/History/HistoryDatabaseTests.swift+++ b/Tests/App/History/HistoryDatabaseTests.swift@@ -187,7 +187,7 @@ struct HistoryDatabaseTests {#expect(try database.pendingActivityDataDates() == [HistoryStorage.dateKey(for: yesterday)])}- @Test func recordingLeaseHasOneWriterAndReleasesOnStop() throws {+ @Test func recordingLeaseTransfersWithoutTwoWriters() throws {let directory = try TestDirectory()defer { try? directory.remove() }let first = TokenUsageHistoryStore(directoryURL: directory.url)@@ -432,9 +432,12 @@ extension HistoryDatabaseTests {let database = try HistoryDatabase(directoryURL: directory.url)try database.execute("UPDATE aggregates SET tokenUsage = ?", [.data(Data("broken".utf8))])#expect(try await store.refresh(now: now) == initial)+ try database.execute("UPDATE aggregates SET tokenUsage = ?", [.data(Data("broken".utf8))])let rebuilt = try await store.rebuild(for: [HistoryStorage.dateKey(for: now)])#expect(rebuilt.eventCount == 2)#expect(try await store.persistedAggregates(now: now) == initial)+ try database.execute("UPDATE aggregates SET tokenUsage = NULL")+ #expect(try await store.refresh(now: now) == initial)}@Test func observedDateSurvivesDelayedWriteAcrossMidnight() async throws {diff --git a/Tests/App/History/JSONLinesAndActivityDataTests.swift b/Tests/App/History/JSONLinesAndActivityDataTests.swiftindex 1aa8e00..93bff5a 100644--- a/Tests/App/History/JSONLinesAndActivityDataTests.swift+++ b/Tests/App/History/JSONLinesAndActivityDataTests.swift@@ -12,16 +12,12 @@ struct JSONLinesAndActivityDataTests {}}- @Test(arguments: ["PermissionRequest", "permission_request", "permission-request", "approval.requested"])- func eventAliasesAreNotAccepted(_ name: String) {+ @Test(arguments: ["PermissionRequest", "permission_request", "permission-request", "approval.requested", "future_event"])+ func aliasesAndUnknownEventNamesAreNotAccepted(_ name: String) {#expect(ActivityDataEventKind(eventName: name) == nil)#expect(ActivityDataEventKind(eventName: "approvalRequested") == .approvalRequested)}- @Test func unknownEventNamesAreNotGuessed() {- #expect(ActivityDataEventKind(eventName: "future_event") == nil)- }-@Test func eventDecodingToleratesMissingMetadataAndUnknownOrigins() throws {let event = try TestFixtures.decode(ActivityDataRecord.self, """{"timestamp":0,"name":"turnStarted","origin":"future","threadID":" ","toolName":123}diff --git a/Tests/App/Presentation/SettingsTests.swift b/Tests/App/Presentation/SettingsTests.swiftindex fc5e03e..eb9ef3a 100644--- a/Tests/App/Presentation/SettingsTests.swift+++ b/Tests/App/Presentation/SettingsTests.swift@@ -12,18 +12,23 @@ struct SettingsTests {#expect(SyncSettings.isEnabled(defaults: defaults) == enabled)}- @Test func protectionPreferencePersistsAndRefreshes() throws {+ @Test func protectionPreferenceFallsBackPersistsAndRefreshes() throws {let preferences = try TestPreferences()defer { preferences.remove() }let defaults = preferences.defaults+ #expect(ProtectionSettings(defaults: defaults).inactivityDuration == .oneHour)+ defaults.set("invalid", forKey: "Protection.inactivityDurationSeconds")let settings = ProtectionSettings(defaults: defaults)#expect(settings.inactivityDuration == .oneHour)settings.setInactivityDuration(.thirtyMinutes)#expect(defaults.integer(forKey: "Protection.inactivityDurationSeconds") == 1800)- defaults.set(14400, forKey: "Protection.inactivityDurationSeconds")- settings.refresh()- #expect(settings.inactivityDuration == .fourHours)- #expect(ProtectionSettings(defaults: defaults).inactivityDuration == .fourHours)+ #expect(ProtectionSettings(defaults: defaults).inactivityDuration == .thirtyMinutes)+ for duration in [ProtectionSettings.InactivityDuration.twoHours, .fourHours] {+ defaults.set(duration.rawValue, forKey: "Protection.inactivityDurationSeconds")+ settings.refresh()+ #expect(settings.inactivityDuration == duration)+ #expect(ProtectionSettings(defaults: defaults).inactivityDuration == duration)+ }}@Test(arguments: DataUpdateInterval.allCases)@@ -109,19 +114,6 @@ struct SettingsTests {#expect(initial.leadTime == .sixHours)}- @Test func protectionFallsBackToOneHourAndReloadsChanges() throws {- let preferences = try TestPreferences()- defer { preferences.remove() }- preferences.defaults.set("invalid", forKey: "Protection.inactivityDurationSeconds")- let settings = ProtectionSettings(defaults: preferences.defaults)- #expect(settings.inactivityDuration == .oneHour)- settings.setInactivityDuration(.thirtyMinutes)- #expect(ProtectionSettings(defaults: preferences.defaults).inactivityDuration == .thirtyMinutes)- preferences.defaults.set(7200, forKey: "Protection.inactivityDurationSeconds")- settings.refresh()- #expect(settings.inactivityDuration == .twoHours)- }-@Test func layoutRepairsDuplicateOrderAndAlwaysKeepsAVisibleSection() {let layout = MainPanelLayout(orderedSections: [.usage, .usage, .activity], hiddenSections: Set(MainPanelSection.allCases))#expect(layout.orderedSections == [.usage, .activity, .account, .quota, .serviceStatus, .status])diff --git a/Tests/App/Presentation/TaskGlowTests.swift b/Tests/App/Presentation/TaskGlowTests.swiftindex 81ae26b..4f2299e 100644--- a/Tests/App/Presentation/TaskGlowTests.swift+++ b/Tests/App/Presentation/TaskGlowTests.swift@@ -36,24 +36,21 @@ struct TaskGlowTests {}@Test(arguments: [0, 2, 6])- func repeatedOverflowPreservesColorAndSelection(_ cursor: Int) {+ func overflowPreservesColorAndSelection(_ cursor: Int) {let formatter = TaskGlowHexFormatter()let original = "123456"let originalRange = NSRange(location: cursor, length: 0)- for _ in 0 ..< 100 {- var proposed = (original as NSString).replacingCharacters(in: originalRange, with: "a") as NSString- var proposedRange = NSRange(location: cursor + 1, length: 0)- let accepted = formatter.isPartialStringValid(- &proposed,- proposedSelectedRange: &proposedRange,- originalString: original,- originalSelectedRange: originalRange,- errorDescription: nil- )- #expect(!accepted)- #expect(proposed as String == original)- #expect(proposedRange == originalRange)- }+ var proposed = (original as NSString).replacingCharacters(in: originalRange, with: "a") as NSString+ var proposedRange = NSRange(location: cursor + 1, length: 0)+ #expect(!formatter.isPartialStringValid(+ &proposed,+ proposedSelectedRange: &proposedRange,+ originalString: original,+ originalSelectedRange: originalRange,+ errorDescription: nil+ ))+ #expect(proposed as String == original)+ #expect(proposedRange == originalRange)}@Test func colorFormatterLimitsReplacementWithoutChangingSurroundingText() {diff --git a/Tests/App/Support/ActivityUpdateFixtures.swift b/Tests/App/Support/ActivityUpdateFixtures.swiftindex cb904a5..8b1eacd 100644--- a/Tests/App/Support/ActivityUpdateFixtures.swift+++ b/Tests/App/Support/ActivityUpdateFixtures.swift@@ -6,8 +6,9 @@ import Foundationvar graph = ActivityTaskGraph()}+@MainActorextension AppServerActivityReader {- @MainActor init(+ init(probe: ActivityReaderProbe,socketURL: URL = AppServerActivityReader.defaultSocketURL,logStorage: AppServerLogStore? = nil,diff --git a/Tests/App/Sync/SyncRecoveryTests.swift b/Tests/App/Sync/SyncRecoveryTests.swiftindex fd02aa4..bb55b2f 100644--- a/Tests/App/Sync/SyncRecoveryTests.swift+++ b/Tests/App/Sync/SyncRecoveryTests.swift@@ -438,14 +438,18 @@ struct SyncRecoveryTests {let fixture = try await HistoryRebuildFixture()defer { try? fixture.directory.remove() }let previous = try #require(await fixture.database.activityDataRecords().first)+ let event = TestFixtures.event(.toolStarted, at: Date(), turn: "different")try fixture.directory.replaceHistory(- AppServerEventRecord(activityData: TestFixtures.event(at: Date())).jsonLineData(),+ AppServerEventRecord(activityData: event).jsonLineData(),date: fixture.date)_ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)let updated = try #require(await fixture.database.activityDataRecords().first)#expect(updated.recordID == previous.recordID)- #expect(try Self.activityDataEventCount(updated) == 1)+ let counts = try #require(try ActivityDataRecordCodec.remoteDailyRecord(from: updated)?.activityData)+ #expect(counts.eventCount == 1)+ #expect(counts.turnStartedCount == 0)+ #expect(counts.toolStartedCount == 1)#expect(await fixture.database.activityDataRecords().count == 1)#expect(await fixture.database.deletedIDs.isEmpty)}@@ -705,16 +709,6 @@ extension SyncRecoveryTests {#expect(try await Self.activityDataEventCount(fixture.database.activityDataRecords().first) == 1)}- @Test func rewrittenLocalJournalReplacesCloudCounts() async throws {- let fixture = try await HistoryRebuildFixture()- defer { try? fixture.directory.remove() }- let event = TestFixtures.event(.toolStarted, at: Date(), turn: "different")- try fixture.directory.replaceHistory(AppServerEventRecord(activityData: event).jsonLineData(), date: fixture.date)- _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)- #expect(try await Self.activityDataEventCount(fixture.database.activityDataRecords().first) == 1)- #expect(await fixture.database.deletedIDs.isEmpty)- }-@Test func requestSaveFailureDoesNotModifyAggregateOrCloud() async throws {let fixture = try await HistoryRebuildFixture()defer { try? fixture.directory.remove() }