Skip to content

CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息

fix: 修复历史重建与数据链路异常恢复

Bob0b04392cd518
diff --git a/CodexBar/Controllers/CodexBarAppDelegate.swift b/CodexBar/App/CodexBarAppDelegate.swift
similarity index 100%
rename from CodexBar/Controllers/CodexBarAppDelegate.swift
rename to CodexBar/App/CodexBarAppDelegate.swift
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index c7bea58..e3bdcc8 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -268,10 +268,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {
// MARK: - 订阅与全局快捷键
private func observeViewModel() {
- let hasQuotaSnapshot = viewModel.$snapshot
- .map { $0 != nil }
- .removeDuplicates()
-
let hasTaskCenterContent = activityMonitor.$snapshot
.map(\.hasTaskCenterContent)
.removeDuplicates()
@@ -280,14 +276,13 @@ final class StatusItemController: NSObject, NSMenuDelegate {
.map { $0.isVisible(.activity) }
.removeDuplicates()
- Publishers.CombineLatest4(
+ Publishers.CombineLatest3(
menuSurfaceVisibility.$isVisible,
- hasQuotaSnapshot,
hasTaskCenterContent,
isTaskCenterVisible
)
- .map { isMenuVisible, hasQuotaSnapshot, hasActivity, isTaskCenterVisible in
- isMenuVisible && hasQuotaSnapshot && hasActivity && isTaskCenterVisible
+ .map { isMenuVisible, hasActivity, isTaskCenterVisible in
+ isMenuVisible && hasActivity && isTaskCenterVisible
}
.removeDuplicates()
.sink { [weak self] isActive in
@@ -306,7 +301,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
usesErrorImage: loadState.isError || snapshot?.hasTrustedData == false,
ordinaryUsageAllowed: snapshot?.ordinaryUsageAllowed,
progress: StatusIconProgress(snapshot: snapshot, selection: selection),
- activity: snapshot == nil ? .empty : activity
+ activity: activity
)
}
.removeDuplicates()
@@ -325,7 +320,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
}
.store(in: &cancellables)
- hasQuotaSnapshot
+ hasTaskCenterContent
.sink { [weak self] isAvailable in
guard let self, !isAvailable else {
return
@@ -355,8 +350,11 @@ final class StatusItemController: NSObject, NSMenuDelegate {
private func observeSyncState() {
syncSettings.$syncAvailability
.removeDuplicates()
+ // 同步调度会回读设置, 等可用性提交后再处理恢复
+ .receive(on: DispatchQueue.main)
.sink { [weak self] availability in
- self?.handleSyncChanged(isSyncAvailable: availability.isAvailable)
+ guard let self, availability == syncSettings.syncAvailability else { return }
+ syncScheduler.requestSync(trigger: .settings)
}
.store(in: &cancellables)
}
@@ -844,6 +842,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
private func refreshHistory(performMaintenance: Bool) {
if performMaintenance {
+ syncSettings.refreshAvailabilityIfNeeded()
// 统计维护挂在额度刷新完成事件上, 触发来源继承那一次刷新
syncScheduler.requestMaintenance(
allowsSync: true,
@@ -854,18 +853,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {
}
}
- /// isSyncAvailable 由调用方传入
- /// 从 $syncAvailability 的订阅进来时 syncSettings.isSyncAvailable 还是旧值, 只有回调参数是新的
- /// 不在这里判断该不该跳过: requestSync 的 guard 已经统一处理并记下 reason=
- private func handleSyncChanged(isSyncAvailable: Bool) {
- syncScheduler.requestSync(
- trigger: .settings,
- activation: syncSettings.activation(
- isSyncAvailable: isSyncAvailable
- )
- )
- }
-
private var syncActivation: SyncActivation {
syncSettings.activation()
}
diff --git a/CodexBar/Models/ActivityAggregate.swift b/CodexBar/Models/ActivityAggregate.swift
index 920fa25..61adf5d 100644
--- a/CodexBar/Models/ActivityAggregate.swift
+++ b/CodexBar/Models/ActivityAggregate.swift
@@ -276,22 +276,7 @@ nonisolated struct ActivityAggregate: Codable, Equatable {
}
func jsonLineData() throws -> Data {
- var fields = try [
- OrderedJSON.field(CodingKeys.date.rawValue, date),
- OrderedJSON.field(CodingKeys.generationID.rawValue, generationID),
- OrderedJSON.field(CodingKeys.generationStartedEmpty.rawValue, generationStartedEmpty)
- ]
- try fields.append(contentsOf: OrderedJSON.presentCountFields(eventCountFields))
- try fields.append(contentsOf: [
- OrderedJSON.field(CodingKeys.sessionCount.rawValue, sessionCount),
- OrderedJSON.field(CodingKeys.turnCount.rawValue, turnCount),
- OrderedJSON.field(CodingKeys.projectCounts.rawValue, projectCounts),
- OrderedJSON.field(CodingKeys.modelCounts.rawValue, modelCounts),
- OrderedJSON.field(CodingKeys.sessionIDs.rawValue, sessionIDs),
- OrderedJSON.field(CodingKeys.turnIDs.rawValue, turnIDs)
- ])
-
- return OrderedJSON.lineData(fields)
+ try JSONLines.stableEncoder.encode(self) + Data([JSONLines.newlineByte])
}
var eventCountAvailability: ActivityCountAvailability {
@@ -353,24 +338,6 @@ nonisolated struct ActivityAggregate: Codable, Equatable {
)
}
- private var eventCountFields: [(String, Int?)] {
- [
- (CodingKeys.eventCount.rawValue, eventCount),
- (CodingKeys.sessionStartedCount.rawValue, sessionStartedCount),
- (CodingKeys.sessionEndedCount.rawValue, sessionEndedCount),
- (CodingKeys.turnStartedCount.rawValue, turnStartedCount),
- (CodingKeys.turnCompletedCount.rawValue, turnCompletedCount),
- (CodingKeys.turnAbortedCount.rawValue, turnAbortedCount),
- (CodingKeys.toolStartedCount.rawValue, toolStartedCount),
- (CodingKeys.toolCompletedCount.rawValue, toolCompletedCount),
- (CodingKeys.approvalRequestedCount.rawValue, approvalRequestedCount),
- (CodingKeys.compactionStartedCount.rawValue, compactionStartedCount),
- (CodingKeys.compactionCompletedCount.rawValue, compactionCompletedCount),
- (CodingKeys.subagentStartedCount.rawValue, subagentStartedCount),
- (CodingKeys.subagentEndedCount.rawValue, subagentEndedCount)
- ]
- }
-
private static func normalizedIdentifiers(_ identifiers: [String]?) -> [String]? {
identifiers.map { Set($0).sorted() }
}
diff --git a/CodexBar/Models/ActivityModels.swift b/CodexBar/Models/ActivityModels.swift
index 79d7d01..e719352 100644
--- a/CodexBar/Models/ActivityModels.swift
+++ b/CodexBar/Models/ActivityModels.swift
@@ -19,12 +19,6 @@ nonisolated enum ActivityPhase: Equatable {
case stopRequested
}
-/// bootstrap 后需要向更早日期定向查找 Prompt 起点的精确任务引用
-nonisolated struct ActivityPromptReference: Hashable {
- let sessionID: String
- let turnID: String
-}
-
/// 正在运行或等待批准的任务摘要, 不对 UI 暴露原始会话 ID
nonisolated struct ActivityTaskSnapshot: Equatable, Identifiable {
let id: UUID
diff --git a/CodexBar/Models/ActivitySyncRecord.swift b/CodexBar/Models/ActivitySyncRecord.swift
index 68be60c..4d8aab4 100644
--- a/CodexBar/Models/ActivitySyncRecord.swift
+++ b/CodexBar/Models/ActivitySyncRecord.swift
@@ -45,37 +45,7 @@ nonisolated struct SyncedActivity: Codable, Equatable {
}
func jsonLineData() throws -> Data {
- var fields = try [
- OrderedJSON.field(CodingKeys.date.rawValue, date),
- OrderedJSON.field(CodingKeys.generationID.rawValue, generationID)
- ]
- try fields.append(contentsOf: OrderedJSON.presentCountFields(eventCountFields))
- try fields.append(contentsOf: [
- OrderedJSON.field(CodingKeys.sessionCount.rawValue, sessionCount),
- OrderedJSON.field(CodingKeys.turnCount.rawValue, turnCount),
- OrderedJSON.field(CodingKeys.projectCounts.rawValue, projectCounts),
- OrderedJSON.field(CodingKeys.modelCounts.rawValue, modelCounts)
- ])
-
- return OrderedJSON.lineData(fields)
- }
-
- private var eventCountFields: [(String, Int?)] {
- [
- (CodingKeys.eventCount.rawValue, eventCount),
- (CodingKeys.sessionStartedCount.rawValue, sessionStartedCount),
- (CodingKeys.sessionEndedCount.rawValue, sessionEndedCount),
- (CodingKeys.turnStartedCount.rawValue, turnStartedCount),
- (CodingKeys.turnCompletedCount.rawValue, turnCompletedCount),
- (CodingKeys.turnAbortedCount.rawValue, turnAbortedCount),
- (CodingKeys.toolStartedCount.rawValue, toolStartedCount),
- (CodingKeys.toolCompletedCount.rawValue, toolCompletedCount),
- (CodingKeys.approvalRequestedCount.rawValue, approvalRequestedCount),
- (CodingKeys.compactionStartedCount.rawValue, compactionStartedCount),
- (CodingKeys.compactionCompletedCount.rawValue, compactionCompletedCount),
- (CodingKeys.subagentStartedCount.rawValue, subagentStartedCount),
- (CodingKeys.subagentEndedCount.rawValue, subagentEndedCount)
- ]
+ try JSONLines.stableEncoder.encode(self) + Data([JSONLines.newlineByte])
}
func requiredGenerationID() throws -> String {
diff --git a/CodexBar/Models/AppServerEventRecord.swift b/CodexBar/Models/AppServerEventRecord.swift
index 4d940a4..266568e 100644
--- a/CodexBar/Models/AppServerEventRecord.swift
+++ b/CodexBar/Models/AppServerEventRecord.swift
@@ -25,7 +25,7 @@ nonisolated struct AppServerEventSource: Codable, Equatable {
nonisolated struct AppServerEventRecord: Codable, Equatable {
enum Kind: String, Codable { case activity, tokenSnapshot, tokenObservation }
- static let currentVersion = 2
+ static let currentVersion = 1
let version: Int
let kind: Kind
let recordedAt: Date
diff --git a/CodexBar/Models/StatusIconState.swift b/CodexBar/Models/StatusIconState.swift
index 04db63e..d41a3a7 100644
--- a/CodexBar/Models/StatusIconState.swift
+++ b/CodexBar/Models/StatusIconState.swift
@@ -7,15 +7,12 @@ struct StatusIconState: Equatable {
let activity: ActivitySnapshot
func symbolName(at now: Date) -> String {
- if usesErrorImage {
- return "person.slash.fill"
- }
switch activity.statusItemActivity(at: now) {
- case .waiting: return "person.badge.key.fill"
- case .running: return "person.badge.clock.fill"
- case .completed: return "person.badge.shield.checkmark.fill"
- case .terminated: return "person.badge.shield.exclamationmark.fill"
- case .idle: return "person.fill"
+ case .waiting: "person.badge.key.fill"
+ case .running: "person.badge.clock.fill"
+ case .completed: "person.badge.shield.checkmark.fill"
+ case .terminated: "person.badge.shield.exclamationmark.fill"
+ case .idle: usesErrorImage ? "person.slash.fill" : "person.fill"
}
}
diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstrings
index 541425a..17d6068 100644
--- a/CodexBar/Resources/Localizable.xcstrings
+++ b/CodexBar/Resources/Localizable.xcstrings
@@ -2049,6 +2049,22 @@
}
}
},
+ "history.rebuild.error.incomplete-source" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "The original event log contains unreadable records. Previous results have been kept. Repair the log and retry."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "原始事件日志包含无法读取的记录, 已保留原结果, 请修复日志后重试"
+ }
+ }
+ }
+ },
"history.rebuild.error.source-changed" : {
"localizations" : {
"en" : {
@@ -2166,13 +2182,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Days rebuilt: %1$lld; events: %2$lld"
+ "value" : "Days fully rebuilt: %1$lld; rebuilt events: %2$lld"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "已重建 %1$lld 天, 包含活动事件 %2$lld 条"
+ "value" : "完整重建 %1$lld 天, 已重算活动事件 %2$lld 条"
}
}
}
@@ -2209,34 +2225,18 @@
}
}
},
- "history.rebuild.summary.skipped-invalid-events" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "; skipped %lld invalid events"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : ", 跳过 %lld 条无效数据"
- }
- }
- }
- },
- "history.rebuild.summary.sync-replacement-marking-failed" : {
+ "history.rebuild.summary.request-failed" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "; could not replace cloud data, please try again later"
+ "value" : "; rebuild could not start for %@, please retry"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "; 云端替换未能完成, 请稍后重新尝试"
+ "value" : "; 重建请求未能保存 (%@), 请重新尝试"
}
}
}
@@ -2246,13 +2246,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "; session data rebuild incomplete, please retry"
+ "value" : "; session data rebuild incomplete (%@), please retry the incomplete dates"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "; 会话数据重建未完成, 请重试"
+ "value" : "; 会话数据重建未完成 (%@), 请重新尝试未完成日期"
}
}
}
diff --git a/CodexBar/Services/Activity/ActivityMonitor.swift b/CodexBar/Services/Activity/ActivityMonitor.swift
index 15e89af..bc50a40 100644
--- a/CodexBar/Services/Activity/ActivityMonitor.swift
+++ b/CodexBar/Services/Activity/ActivityMonitor.swift
@@ -56,7 +56,7 @@ final class ActivityMonitor: ObservableObject {
var protectionPersistenceTask: Task<Void, Never>?
private var isProtectionStateLoaded = false
var isProtectionEnabled = false
- var isActivitySourceHealthy = false
+ @Published var isActivitySourceHealthy = false
private var unavailableTurns = Set<ActivityTaskKey>()
var isProtectionRecoveryInProgress = false
var protectionRecoveryGeneration: UInt64 = 0
@@ -222,7 +222,7 @@ final class ActivityMonitor: ObservableObject {
clearCollectedActivityState()
isBootstrapping = false
sessionTransitionNotBefore = nil
- snapshot = .empty
+ publishSnapshot(.empty)
}
// MARK: - 会话生命周期
@@ -495,7 +495,7 @@ final class ActivityMonitor: ObservableObject {
// MARK: - 活动事件消费
- private func consume(_ batch: ActivityEventBatch) {
+ func consume(_ batch: ActivityEventBatch) {
switch batch {
case .lifecycleChanged:
refreshSessionLifecycleNow()
@@ -513,6 +513,7 @@ final class ActivityMonitor: ObservableObject {
isActivitySourceHealthy = false
cancelInactivityCheck()
clearCollectedActivityState()
+ publishSnapshot(.empty)
case let .bootstrapEvents(events):
bootstrapEventCount += events.count
for event in events {
@@ -562,7 +563,7 @@ final class ActivityMonitor: ObservableObject {
isActivitySourceHealthy = false
resetTerminalPresentationEvents()
beginProtectionRecovery()
- snapshot = .empty
+ publishSnapshot(.empty)
cancelInactivityCheck()
cancelAllProtectionAttempts()
AppLog.activity.error(
@@ -607,7 +608,6 @@ final class ActivityMonitor: ObservableObject {
let now = Date()
applyPersistedProtection(now: now)
reconcileProtection(now: now, sendsNotification: false)
- backfillPromptStartTimesFromHistory()
let activeCount = snapshot.activeCount
let eventCount = bootstrapEventCount
@@ -621,44 +621,6 @@ final class ActivityMonitor: ObservableObject {
AppLog.activity.notice("历史回放完成: \(details, privacy: .public)")
}
- /// bootstrap 只覆盖 24 小时窗口; 窗口内恢复出的无起点任务向更早日期回查 Prompt 起点
- private func backfillPromptStartTimesFromHistory() {
- let references = tasks.values.compactMap(\.promptReference)
- guard !references.isEmpty, let reader = activityReader else {
- return
- }
- let generation = activityReaderGeneration
-
- Task { @MainActor [weak self] in
- let startTimes = await reader.findPromptStartTimes(for: references)
- guard let self,
- activityReaderGeneration == generation,
- !isBootstrapping,
- !startTimes.isEmpty else {
- return
- }
- backfillStartTimes(startTimes)
- }
- }
-
- private func backfillStartTimes(_ startTimes: [ActivityPromptReference: Date]) {
- var didChange = false
- for (reference, startedAt) in startTimes {
- let key = ActivityTaskKey.turn(session: reference.sessionID, turn: reference.turnID)
- guard var task = tasks[key],
- task.startedAt == nil,
- startedAt <= task.lastActivityAt else {
- continue
- }
- task.startedAt = startedAt
- tasks[key] = task
- didChange = true
- }
- if didChange {
- refreshSnapshot(now: Date())
- }
- }
-
func apply(
_ event: ActivityRecord,
source: ActivityEventSource
@@ -1170,16 +1132,20 @@ final class ActivityMonitor: ObservableObject {
)
let events = pendingTerminalPresentationEvents.filter { terminalTaskKeyByID[$0.id] != nil }
pendingTerminalPresentationEvents.removeAll()
+ publishSnapshot(newSnapshot, terminalEvents: events)
+
+ scheduleNextCleanup(now: now)
+ scheduleNextInactivityCheck(now: now)
+ }
+
+ private func publishSnapshot(_ newSnapshot: ActivitySnapshot, terminalEvents: [ActivityTerminalEvent] = []) {
let didChange = newSnapshot != snapshot
if didChange {
snapshot = newSnapshot
}
- if didChange || !events.isEmpty {
- presentationSubject.send(ActivityPresentationUpdate(snapshot: newSnapshot, terminalEvents: events))
+ if didChange || !terminalEvents.isEmpty {
+ presentationSubject.send(ActivityPresentationUpdate(snapshot: newSnapshot, terminalEvents: terminalEvents))
}
-
- scheduleNextCleanup(now: now)
- scheduleNextInactivityCheck(now: now)
}
private func sortedTasks(in state: ActivityTaskState) -> [ActivityTask] {
diff --git a/CodexBar/Services/Activity/ActivityTask.swift b/CodexBar/Services/Activity/ActivityTask.swift
index ca34643..0b9df9d 100644
--- a/CodexBar/Services/Activity/ActivityTask.swift
+++ b/CodexBar/Services/Activity/ActivityTask.swift
@@ -209,14 +209,6 @@ struct ActivityTask {
)
}
- var promptReference: ActivityPromptReference? {
- guard startedAt == nil,
- let sessionID = key.sessionID, let turnID = associatedTurnID else {
- return nil
- }
- return ActivityPromptReference(sessionID: sessionID, turnID: turnID)
- }
-
var resolvedTurnKey: ActivityTaskKey? {
guard let session = key.sessionID, let turn = associatedTurnID else { return nil }
return .turn(session: session, turn: turn)
diff --git a/CodexBar/Services/Activity/AppServerActivityReader.swift b/CodexBar/Services/Activity/AppServerActivityReader.swift
index 395c4d5..e0aa254 100644
--- a/CodexBar/Services/Activity/AppServerActivityReader.swift
+++ b/CodexBar/Services/Activity/AppServerActivityReader.swift
@@ -121,17 +121,6 @@ actor AppServerActivityReader {
return await withCheckedContinuation { drainWaiters.append($0) }
}
- func findPromptStartTimes(for references: [ActivityPromptReference]) -> [ActivityPromptReference: Date] {
- var result: [ActivityPromptReference: Date] = [:]
- for reference in references {
- let key = ActivityTurnReference(threadID: reference.sessionID, turnID: reference.turnID, startedAt: Date())
- if let start = reducer.states[key]?.startedAt {
- result[reference] = start
- }
- }
- return result
- }
-
private func run(generation current: Int) async {
while isRunning, generation == current, !Task.isCancelled {
do {
diff --git a/CodexBar/Services/Codex/CodexPaths.swift b/CodexBar/Services/Codex/CodexPaths.swift
index e19059a..b3dc8c7 100644
--- a/CodexBar/Services/Codex/CodexPaths.swift
+++ b/CodexBar/Services/Codex/CodexPaths.swift
@@ -156,9 +156,8 @@ nonisolated enum CodexPaths {
}
/// "两个路径是否指向同一文件"的统一口径
- static func canonicalPath(_ path: String, expandingTilde: Bool = false) -> String {
- let expandedPath = expandingTilde ? (path as NSString).expandingTildeInPath : path
- return URL(fileURLWithPath: expandedPath)
+ static func canonicalPath(_ path: String) -> String {
+ URL(fileURLWithPath: path)
.resolvingSymlinksInPath()
.standardizedFileURL
.path
diff --git a/CodexBar/Services/Codex/CodexVersionService.swift b/CodexBar/Services/Codex/CodexVersionService.swift
index 2fadcd5..3429ff1 100644
--- a/CodexBar/Services/Codex/CodexVersionService.swift
+++ b/CodexBar/Services/Codex/CodexVersionService.swift
@@ -228,16 +228,6 @@ nonisolated enum CodexVersionReader {
return parsedVersion >= parsedMinimumVersion
}
- /// 返回 nil 表示任一版本不可识别, 构建标记不影响版本优先级
- static func isVersion(_ version: String, newerThan otherVersion: String) -> Bool? {
- guard let parsedVersion = SemanticVersion(version),
- let parsedOtherVersion = SemanticVersion(otherVersion) else {
- return nil
- }
-
- return parsedVersion > parsedOtherVersion
- }
-
private struct SemanticVersion: Comparable {
let core: [Int]
let prerelease: [PrereleaseIdentifier]?
diff --git a/CodexBar/Services/History/HistoryMaintenance.swift b/CodexBar/Services/History/HistoryMaintenance.swift
index fbcb825..11bdf1e 100644
--- a/CodexBar/Services/History/HistoryMaintenance.swift
+++ b/CodexBar/Services/History/HistoryMaintenance.swift
@@ -10,7 +10,7 @@ nonisolated struct HistoryMaintenanceState: Codable, Equatable {
}
/// 原始事件到每日聚合的算法版本, 变化时统一从原始 JSONL 重建
- static let currentVersion = 2
+ static let currentVersion = 1
var version: Int
var pending: [String]
@@ -114,6 +114,7 @@ nonisolated struct HistoryMaintenanceState: Codable, Equatable {
fileIdentifier: UInt64?
) {
days[dateKey] = HistoryDayMaintenanceState(
+ requiresCloudReplacement: days[dateKey]?.requiresCloudReplacement ?? false,
generationID: Self.makeGenerationID(),
generationStartedEmpty: startedEmpty,
fileIdentifier: fileIdentifier
@@ -154,6 +155,7 @@ nonisolated struct HistoryMaintenanceState: Codable, Equatable {
nonisolated struct HistoryDayMaintenanceState: Codable, Equatable {
private enum CodingKeys: String, CodingKey {
+ case requiresCloudReplacement
case offset
case size
case corrupt
@@ -163,6 +165,7 @@ nonisolated struct HistoryDayMaintenanceState: Codable, Equatable {
case boundaryHash
}
+ var requiresCloudReplacement: Bool
var offset: UInt64
var size: UInt64
var corrupt: Int
@@ -172,6 +175,7 @@ nonisolated struct HistoryDayMaintenanceState: Codable, Equatable {
var boundaryHash: String?
init(
+ requiresCloudReplacement: Bool = false,
offset: UInt64 = 0,
size: UInt64 = 0,
corrupt: Int = 0,
@@ -180,6 +184,7 @@ nonisolated struct HistoryDayMaintenanceState: Codable, Equatable {
fileIdentifier: UInt64? = nil,
boundaryHash: String? = nil
) {
+ self.requiresCloudReplacement = requiresCloudReplacement
self.offset = offset
self.size = size
self.corrupt = corrupt
@@ -191,6 +196,7 @@ nonisolated struct HistoryDayMaintenanceState: Codable, Equatable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
+ requiresCloudReplacement = try container.decodeIfPresent(Bool.self, forKey: .requiresCloudReplacement) ?? false
offset = try container.decodeIfPresent(UInt64.self, forKey: .offset) ?? 0
size = try container.decodeIfPresent(UInt64.self, forKey: .size) ?? 0
corrupt = try container.decodeIfPresent(Int.self, forKey: .corrupt) ?? 0
diff --git a/CodexBar/Services/History/HistoryService.swift b/CodexBar/Services/History/HistoryService.swift
index b976c49..2cadcd8 100644
--- a/CodexBar/Services/History/HistoryService.swift
+++ b/CodexBar/Services/History/HistoryService.swift
@@ -89,7 +89,8 @@ actor HistoryService {
trigger: LogTrigger,
localTokenTurns: [TokenTurn]? = nil
) async -> HistorySnapshot {
- // 只有 Token 的日志日期需要维护游标, 但不能生成一次活动统计贡献
+ let replacements = readyReplacements()
+ // 零值替换仍需同步, 展示和普通上传不生成 Token-only 日期的活动贡献
let localAggregates = localAggregates.filter { $0.eventCount != 0 }
let tokenTurns: [TokenTurn]
if let localTokenTurns {
@@ -105,13 +106,16 @@ actor HistoryService {
}
}
let syncSnapshot: SyncSnapshot = if synchronize {
- await syncService.synchronizeIfEnabled(localAggregates: localAggregates, localTokenTurns: tokenTurns, trigger: trigger)
+ await syncService.synchronizeIfEnabled(
+ localAggregates: localAggregates, localTokenTurns: tokenTurns, replacements: replacements, trigger: trigger
+ )
} else {
- await syncService.snapshotFromCacheIfEnabled(localTokenTurns: tokenTurns)
+ await syncService.snapshotFromCacheIfEnabled(localTokenTurns: tokenTurns, replacements: replacements)
}
+ acknowledgeReplacements(syncSnapshot.completedReplacements)
var snapshot = HistorySnapshot(
localAggregates: localAggregates,
- syncedRecords: syncSnapshot.records,
+ syncedRecords: syncSnapshot.records.filter { $0.daily.eventCount != 0 },
currentDeviceID: syncSnapshot.currentDeviceID
)
snapshot.tokenUsageByDate = syncSnapshot.tokenUsageByDate ?? TokenTurn.dailyUsage(tokenTurns)
@@ -129,15 +133,17 @@ actor HistoryService {
throw HistoryDataRebuildError.sourceUnavailable
}
- // 单日失败不中止整批: 失败的日期已被 rebuildLocalData 标脏, 常规维护会自动重建
+ // 已保存请求的失败日期交给常规维护重试, 单日失败不中止整批
// 中止会让「前几天已改写, 后几天没碰」这个事实完全不被上报
var rebuildResults = [HistoryMaintenanceResult]()
var failedDateKeys = [String]()
+ var failedRequestDateKeys = [String]()
var firstFailure: Error?
let eventDateKeysWithData = normalizedDateKeys.filter { HistoryStorage.fileSize(at: eventLogURL(for: $0)) > 0 }
for dateKey in eventDateKeysWithData {
+ var requestWasSaved = false
do {
- try rebuildResults.append(rebuildLocalData(for: dateKey))
+ try rebuildResults.append(rebuildLocalData(for: dateKey, requestWasSaved: &requestWasSaved))
} catch {
// 整批成功时这个原因不会往上抛, 摘要只带得走日期
let details = LogFields.joined(
@@ -147,9 +153,10 @@ actor HistoryService {
)
AppLog.history.error("数据重建失败: \(details, privacy: .public)")
failedDateKeys.append(dateKey)
- if firstFailure == nil {
- firstFailure = error
+ if !requestWasSaved {
+ failedRequestDateKeys.append(dateKey)
}
+ firstFailure = firstFailure ?? error
}
}
@@ -157,6 +164,9 @@ actor HistoryService {
var didFailTokenRebuild = false
do {
tokenResult = try await tokenHistory.rebuild(for: normalizedDateKeys)
+ if !tokenResult.failedDateKeys.isEmpty {
+ firstFailure = firstFailure ?? TokenCacheError.incompleteJournal
+ }
} catch {
didFailTokenRebuild = true
firstFailure = firstFailure ?? error
@@ -164,29 +174,17 @@ actor HistoryService {
AppLog.history.error("Token 重建失败: domain=\(error.domain, privacy: .public) code=\(error.code)")
}
- // 成功与失败的日期都要登记: 失败的日期稍后会被自动重建并推进 generationID,
- // 届时会上传到新的 record ID, 不清理旧记录会在云端留下同日重复的贡献
- // 全部失败时同样要登记, 它们一样已被标脏
- var didFailReplacementMarking = false
- do {
- try await syncService.markReplacementNeeded(for: eventDateKeysWithData)
- } catch {
- let details = LogFields.joined(
- "stage=replacementMarking",
- "dates=\(normalizedDateKeys.count)",
- "detail=\(error.localizedDescription)"
- )
- AppLog.history.error("数据重建失败: \(details, privacy: .public)")
- didFailReplacementMarking = true
- }
-
// 一天都没成功才算整体失败, 并保留首个真实原因而非笼统报「数据发生变化」
guard !rebuildResults.isEmpty || !tokenResult.dateKeys.isEmpty else {
throw firstFailure ?? HistoryDataRebuildError.sourceUnavailable
}
// 重建只由设置页的用户操作发起
- let localTurns = await (try? tokenHistory.currentTurns()) ?? []
+ let localTurns = if let turns = tokenResult.turns {
+ turns
+ } else {
+ await (try? tokenHistory.currentTurns()) ?? []
+ }
let snapshot = await makeSnapshot(
localAggregates: loadDailyAggregates() ?? [],
synchronize: synchronize,
@@ -194,22 +192,23 @@ actor HistoryService {
localTokenTurns: localTurns
)
let tokenSyncPending = await syncService.hasPendingTokenUpdates(local: localTurns)
- let summary = await HistoryDataRebuildSummary(
- rebuiltDateCount: Set(rebuildResults.map(\.dateKey)).union(tokenResult.dateKeys).count,
+ let tokenFailures = didFailTokenRebuild ? normalizedDateKeys : tokenResult.failedDateKeys
+ let summary = HistoryDataRebuildSummary(
+ rebuiltDateCount: Set(rebuildResults.map(\.dateKey)).union(tokenResult.dateKeys)
+ .subtracting(failedDateKeys).subtracting(tokenFailures).count,
eventCount: rebuildResults.reduce(0) { $0 + ($1.aggregate.eventCount ?? 0) },
- corruptLineCount: rebuildResults.reduce(0) { $0 + $1.corrupt },
- isSyncReplacementPending: syncService.hasPendingReplacement(for: eventDateKeysWithData) || tokenSyncPending,
+ isSyncReplacementPending: hasPendingReplacement(for: eventDateKeysWithData) || tokenSyncPending,
failedDateKeys: failedDateKeys,
- didFailSyncReplacementMarking: didFailReplacementMarking,
+ failedRequestDateKeys: failedRequestDateKeys,
+ failedTokenDateKeys: tokenFailures,
tokenTurnCount: tokenResult.turnCount,
- didFailTokenRebuild: didFailTokenRebuild
+ didFailTokenRebuild: didFailTokenRebuild || !tokenResult.failedDateKeys.isEmpty
)
let elapsed = duration.elapsed
let details = LogFields.joined(
"dates=\(summary.rebuiltDateCount)",
"events=\(summary.eventCount)",
"tokenTurns=\(summary.tokenTurnCount)",
- "corruptLines=\(summary.corruptLineCount)",
"failedDates=\(failedDateKeys.count)",
"elapsed=\(elapsed)"
)
@@ -217,6 +216,43 @@ actor HistoryService {
return HistoryDataRebuildOutcome(snapshot: snapshot, summary: summary)
}
+ func hasPendingReplacement(for dates: [String]) -> Bool {
+ let state = HistoryStorage.loadMaintenanceState(in: directoryURL)
+ return dates.contains { state.days[$0]?.requiresCloudReplacement == true }
+ }
+
+ /// 只从同一锁内读取的聚合和提交状态形成替换授权, dirty 状态不允许覆盖云端
+ private func readyReplacements() -> [ActivityAggregate] {
+ (try? HistoryStorage.withExclusiveLock(in: directoryURL) {
+ let state = HistoryStorage.loadMaintenanceState(in: directoryURL)
+ return (loadDailyAggregates() ?? []).filter { aggregate in
+ guard let day = state.days[aggregate.date], day.requiresCloudReplacement,
+ !state.dirty.contains(aggregate.date), day.corrupt == 0, day.offset == day.size, day.offset > 0,
+ let generation = day.generationID, aggregate.generationID == generation,
+ aggregate.eventCount != nil,
+ let stat = HistoryStorage.fileStat(at: eventLogURL(for: aggregate.date)),
+ stat.identifier == day.fileIdentifier, stat.size >= day.offset else { return false }
+ return !hasBoundaryChanged(dateKey: aggregate.date, day: day, stat: stat)
+ }
+ }) ?? []
+ }
+
+ func acknowledgeReplacements(_ completed: [String: String]) {
+ guard !completed.isEmpty else { return }
+ do {
+ try HistoryStorage.withExclusiveLock(in: directoryURL) {
+ var state = HistoryStorage.loadMaintenanceState(in: directoryURL)
+ for (date, generation) in completed where state.days[date]?.generationID == generation
+ && !state.dirty.contains(date) {
+ state.days[date]?.requiresCloudReplacement = false
+ }
+ try HistoryStorage.saveMaintenanceState(state, in: directoryURL)
+ }
+ } catch {
+ AppLog.history.error("云端替换确认保存失败: \(error.localizedDescription, privacy: .public)")
+ }
+ }
+
private func loadDailyAggregates() -> [ActivityAggregate]? {
guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {
return nil
@@ -232,7 +268,7 @@ actor HistoryService {
// MARK: - 重建与维护调度
- private func rebuildLocalData(for dateKey: String) throws -> HistoryMaintenanceResult {
+ private func rebuildLocalData(for dateKey: String, requestWasSaved: inout Bool) throws -> HistoryMaintenanceResult {
var aggregates = loadDailyAggregates() ?? []
let eventCountAvailability = aggregates
.first(where: { $0.date == dateKey })?
@@ -241,6 +277,7 @@ actor HistoryService {
for: dateKey,
eventCountAvailability: eventCountAvailability
)
+ requestWasSaved = true
do {
let result = try buildDailyAggregate(for: task)
@@ -271,14 +308,11 @@ actor HistoryService {
}
var state = HistoryStorage.loadMaintenanceState(in: directoryURL)
- state.ensureGenerationID(for: dateKey, fileIdentifier: stat.identifier)
- state.markDirty(dateKey)
+ state.startNewGeneration(for: dateKey, startedEmpty: false, fileIdentifier: stat.identifier)
+ state.days[dateKey]?.requiresCloudReplacement = true
try HistoryStorage.saveMaintenanceState(state, in: directoryURL)
guard let day = state.days[dateKey] else { throw HistoryDataRebuildError.sourceUnavailable }
- var task = dirtyTask(for: dateKey, day: day, size: stat.size, eventCountAvailability: eventCountAvailability)
- task.generationID = UUID().uuidString.lowercased()
- task.generationStartedEmpty = false
- return task
+ return dirtyTask(for: dateKey, day: day, size: stat.size, eventCountAvailability: eventCountAvailability)
}
}
@@ -597,7 +631,6 @@ actor HistoryService {
size: size ?? stat?.size ?? 0,
mode: .rebuild(eventCountAvailability),
existingCorrupt: 0,
- expectedGenerationID: day.generationID,
generationID: day.generationID,
generationStartedEmpty: day.generationStartedEmpty,
fileIdentifier: stat?.identifier
@@ -616,7 +649,6 @@ actor HistoryService {
size: size,
mode: .append(baseAggregate),
existingCorrupt: day.corrupt,
- expectedGenerationID: day.generationID,
generationID: day.generationID,
generationStartedEmpty: day.generationStartedEmpty,
fileIdentifier: day.fileIdentifier
@@ -705,7 +737,6 @@ actor HistoryService {
return try HistoryMaintenanceResult(
dateKey: task.dateKey,
aggregate: aggregate,
- expectedGenerationID: task.expectedGenerationID,
size: task.size,
corrupt: corrupt,
fileIdentifier: task.fileIdentifier,
@@ -792,12 +823,16 @@ actor HistoryService {
try HistoryStorage.withExclusiveLock(in: directoryURL) {
var state = HistoryStorage.loadMaintenanceState(in: directoryURL)
guard let currentSize = try validatedEventLogSize(for: result, state: &state) else { return false }
+ if state.days[result.dateKey]?.requiresCloudReplacement == true, result.corrupt > 0 {
+ throw HistoryDataRebuildError.incompleteSource
+ }
// 两个文件提交前先标脏, 中途退出会从事件重建, 不沿旧偏移重复追加
state.markDirty(result.dateKey)
try HistoryStorage.saveMaintenanceState(state, in: directoryURL)
aggregates = loadDailyAggregates() ?? []
try writeDailyAggregate(result.aggregate, into: &aggregates)
state.days[result.dateKey] = HistoryDayMaintenanceState(
+ requiresCloudReplacement: state.days[result.dateKey]?.requiresCloudReplacement ?? false,
offset: result.size, size: result.size, corrupt: result.corrupt,
generationID: result.aggregate.generationID,
generationStartedEmpty: result.aggregate.generationStartedEmpty,
@@ -819,7 +854,7 @@ actor HistoryService {
for result: HistoryMaintenanceResult,
state: inout HistoryMaintenanceState
) throws -> UInt64? {
- guard state.days[result.dateKey]?.generationID == result.expectedGenerationID else {
+ guard state.days[result.dateKey]?.generationID == result.aggregate.generationID else {
return nil
}
@@ -998,9 +1033,8 @@ private nonisolated struct HistoryMaintenanceTask {
let size: UInt64
let mode: HistoryMaintenanceMode
let existingCorrupt: Int
- let expectedGenerationID: String?
- var generationID: String?
- var generationStartedEmpty: Bool
+ let generationID: String?
+ let generationStartedEmpty: Bool
let fileIdentifier: UInt64?
var baseEventCount: Int {
@@ -1017,7 +1051,6 @@ private nonisolated struct HistoryMaintenanceTask {
private nonisolated struct HistoryMaintenanceResult {
let dateKey: String
let aggregate: ActivityAggregate
- let expectedGenerationID: String?
let size: UInt64
let corrupt: Int
let fileIdentifier: UInt64?
@@ -1027,11 +1060,10 @@ private nonisolated struct HistoryMaintenanceResult {
nonisolated struct HistoryDataRebuildSummary: Equatable, Sendable {
let rebuiltDateCount: Int
let eventCount: Int
- let corruptLineCount: Int
let isSyncReplacementPending: Bool
- /// 未完成的日期, 已标脏并会由常规维护自动重建
let failedDateKeys: [String]
- let didFailSyncReplacementMarking: Bool
+ let failedRequestDateKeys: [String]
+ let failedTokenDateKeys: [String]
let tokenTurnCount: Int
let didFailTokenRebuild: Bool
}
@@ -1044,6 +1076,7 @@ nonisolated struct HistoryDataRebuildOutcome {
private nonisolated enum HistoryDataRebuildError: LocalizedError {
case sourceUnavailable
case sourceChanged
+ case incompleteSource
var errorDescription: String? {
switch self {
@@ -1051,6 +1084,8 @@ private nonisolated enum HistoryDataRebuildError: LocalizedError {
String(localized: "history.rebuild.error.source-unavailable")
case .sourceChanged:
String(localized: "history.rebuild.error.source-changed")
+ case .incompleteSource:
+ String(localized: "history.rebuild.error.incomplete-source")
}
}
}
diff --git a/CodexBar/Services/History/TokenHistoryStore.swift b/CodexBar/Services/History/TokenHistoryStore.swift
index 40ca6e5..1180fea 100644
--- a/CodexBar/Services/History/TokenHistoryStore.swift
+++ b/CodexBar/Services/History/TokenHistoryStore.swift
@@ -37,26 +37,6 @@ actor TokenHistoryStore {
recordingLease = nil
}
- func record(_ turns: [TokenTurn], sources: [String: AppServerEventSource] = [:], now: Date = Date()) throws {
- guard !turns.isEmpty else { return }
- try HistoryStorage.withExclusiveLock(in: directoryURL) {
- var records = try load(now: now)
- var changed: [TokenTurn] = []
- for turn in turns {
- let merged = records[turn.id]?.merging(turn) ?? turn
- if records[turn.id] != merged {
- changed.append(merged)
- }
- records[turn.id] = merged
- }
- // 日志先于快照提交, 意外退出后可以从已采集的数据重建
- let roots = Set(changed.map(\.rootID))
- try saveObservedTurns(changed + roots.compactMap { records[$0] }, sources: sources, now: now)
- records = retained(records, now: now)
- try save(records)
- }
- }
-
func recordObservations(_ observations: [TokenObservation], now: Date = Date()) throws -> [TokenTurn] {
try HistoryStorage.withExclusiveLock(in: directoryURL) {
var records = try load(now: now)
@@ -117,63 +97,78 @@ actor TokenHistoryStore {
func rebuild(for dateKeys: [String], now: Date = Date()) throws -> TokenRebuildResult {
try HistoryStorage.withExclusiveLock(in: directoryURL) {
- let recorded = try journalTurns(now: now)
- let dates = Set(dateKeys)
var ledger = try load(now: now)
- var count = 0
+ let replay = try journalTurns(now: now, baseline: ledger)
+ let dates = Set(dateKeys)
+ let roots = try replay.selectedRoots(in: dates)
var rebuiltDates = Set<String>()
+ var failedDates = Set<String>()
var rebuiltTurns: [TokenTurn] = []
- for var turn in recorded.values {
- guard let rootStart = recorded[turn.rootID]?.startedAt else { continue }
- let date = CodexDateFormat.dayString(from: rootStart)
- guard dates.contains(date) else { continue }
- let previous = ledger[turn.id]
- guard turn.covers(previous?.checkpoint ?? [:]) else { throw TokenCacheError.incompleteJournal }
- turn.generationID = previous?.generationID ?? turn.generationID
- turn.ancestorIDs = previous?.ancestorIDs ?? []
- turn.startNewGeneration(at: now)
- ledger[turn.id] = turn
- rebuiltTurns.append(turn)
+ let existingByRoot = Dictionary(grouping: ledger.values, by: \.rootID)
+ let recordedByRoot = Dictionary(grouping: replay.records.values, by: \.rootID)
+ for (root, date) in roots.sorted(by: { $0.key < $1.key }) {
+ let candidates = recordedByRoot[root] ?? []
+ let coversExisting = (existingByRoot[root] ?? []).allSatisfy { previous in
+ guard let candidate = replay.records[previous.id] else { return false }
+ return candidate.covers(previous.checkpoint)
+ && (previous.usage == nil || candidate.usage != nil)
+ }
+ guard !replay.failedRoots.contains(root), !candidates.isEmpty, coversExisting else {
+ failedDates.insert(date)
+ continue
+ }
+ // 同一根轮次的全部成员先通过检查, 再生成修正记录
+ for var turn in candidates {
+ let previous = ledger[turn.id]
+ turn.generationID = previous?.generationID ?? turn.generationID
+ turn.ancestorIDs = previous?.ancestorIDs ?? []
+ turn.startNewGeneration(at: now)
+ ledger[turn.id] = turn
+ rebuiltTurns.append(turn)
+ }
rebuiltDates.insert(date)
- count += 1
}
try saveObservedTurns(rebuiltTurns, now: now)
try save(ledger)
- return TokenRebuildResult(dateKeys: rebuiltDates.sorted(), turnCount: count)
+ return TokenRebuildResult(
+ dateKeys: rebuiltDates.sorted(), turnCount: rebuiltTurns.count,
+ failedDateKeys: failedDates.sorted(), turns: Array(ledger.values)
+ )
}
}
- private func saveObservedTurns(_ records: [TokenTurn], sources: [String: AppServerEventSource] = [:], now: Date) throws {
+ private func saveObservedTurns(_ records: [TokenTurn], now: Date) throws {
for record in TokenTurn.merged(records).values.sorted(by: { $0.id < $1.id }) {
- try journal.append(AppServerEventRecord(token: record, source: sources[record.id], recordedAt: now), in: directoryURL)
+ try journal.append(AppServerEventRecord(token: record, recordedAt: now), in: directoryURL)
}
}
- private func journalTurns(now: Date) throws -> [String: TokenTurn] {
- let directory = HistoryStorage.eventsDirectoryURL(in: directoryURL)
- let cutoff = CodexDateFormat.dayString(from: HistoryStorage.retentionCutoffDate(today: now))
- var result: [String: TokenTurn] = [:]
- for date in HistoryStorage.eventLogDateKeys(in: directory) where date >= cutoff {
- let url = HistoryStorage.eventLogURL(for: date, in: directory)
+ private func journalTurns(now: Date, baseline: [String: TokenTurn]) throws -> TokenJournalReplay {
+ var replay = try TokenJournalReplay(baseline: baseline, replayingFromEmpty: true)
+ for date in journalDates(now: now) {
+ let url = HistoryStorage.eventLogURL(for: date, in: HistoryStorage.eventsDirectoryURL(in: directoryURL))
var invalid = false
try AppServerEventJournal.read(at: url, onInvalidLine: { invalid = true }, consume: { entry in
- if let observation = entry.observation {
- result[observation.turn.id] = try observation.applying(to: result[observation.turn.id])
- Self.ensureRoot(for: observation, in: &result)
- }
+ try replay.consume(entry, includesSnapshots: false)
})
if invalid {
throw TokenCacheError.incompleteJournal
}
}
- return result
+ return replay
+ }
+
+ private func journalDates(now: Date) -> [String] {
+ let directory = HistoryStorage.eventsDirectoryURL(in: directoryURL)
+ let cutoff = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate(today: now))
+ return HistoryStorage.eventLogDateKeys(in: directory).filter { $0 >= cutoff }
}
private var ledgerURL: URL {
directoryURL.appendingPathComponent("Aggregates/tokens.json")
}
- private func load(now: Date) throws -> [String: TokenTurn] {
+ private func readCache() throws -> TokenAggregateCache? {
let cache: TokenAggregateCache?
do {
let data = try Data(contentsOf: ledgerURL)
@@ -188,20 +183,27 @@ actor TokenHistoryStore {
AppLog.history.error("Token 缓存损坏, 从原始事件恢复")
cache = nil
}
+ return cache
+ }
+
+ private func load(now: Date) throws -> [String: TokenTurn] {
+ let cache = try readCache()
if cache == nil {
journalFiles.removeAll()
scannedFiles.removeAll()
}
- var records = cache?.turns ?? [:]
+ let baseline = cache?.turns ?? [:]
+ var replay = try TokenJournalReplay(baseline: baseline)
journalFiles = cache?.files ?? [:]
let directory = HistoryStorage.eventsDirectoryURL(in: directoryURL)
- let cutoff = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate(today: now))
- let dates = HistoryStorage.eventLogDateKeys(in: directory).filter { $0 >= cutoff }
+ let dates = journalDates(now: now)
+ let previousFiles = journalFiles
+ var rootsByFile: [String: Set<String>] = [:]
journalFiles = journalFiles.filter { dates.contains($0.key) }
scannedFiles = scannedFiles.filter { dates.contains($0.key) }
for date in dates {
let url = HistoryStorage.eventLogURL(for: date, in: directory)
- guard let stat = HistoryStorage.fileStat(at: url) else { continue }
+ guard let stat = HistoryStorage.fileStat(at: url) else { throw TokenCacheError.incompleteJournal }
let previous = journalFiles[date]
if previous?.size == stat.size, previous?.identifier == stat.identifier,
previous?.modificationTime == stat.modificationTime, scannedFiles[date] == stat {
@@ -210,19 +212,29 @@ actor TokenHistoryStore {
let offset = previous.flatMap { $0.identifier == stat.identifier && $0.size < stat.size ? $0.size : nil } ?? 0
var invalid = false
try AppServerEventJournal.read(at: url, from: offset, onInvalidLine: { invalid = true }, consume: { entry in
- if let observation = entry.observation {
- records[observation.turn.id] = try observation.applying(to: records[observation.turn.id])
- Self.ensureRoot(for: observation, in: &records)
- } else if let turn = entry.token {
- records[turn.id] = records[turn.id]?.merging(turn) ?? turn
+ if let root = entry.observation?.turn.rootID ?? entry.token?.rootID {
+ rootsByFile[date, default: []].insert(root)
}
+ try replay.consume(entry, includesSnapshots: true)
})
- if invalid, cache == nil {
- throw TokenCacheError.incompleteJournal
+ if invalid {
+ guard cache != nil else { throw TokenCacheError.incompleteJournal }
+ // 日常恢复可沿用已有缓存处理完整记录, 显式重建仍要求原始日志完整
+ scannedFiles.removeValue(forKey: date)
+ continue
}
journalFiles[date] = TokenJournalCheckpoint(size: stat.size, identifier: stat.identifier, modificationTime: stat.modificationTime)
scannedFiles[date] = stat
}
+ // 回滚失败根轮次在本轮的所有改动, 涉及的文件保留原游标以便下次重试
+ for (date, roots) in rootsByFile where !roots.isDisjoint(with: replay.failedRoots) {
+ journalFiles[date] = previousFiles[date]
+ scannedFiles.removeValue(forKey: date)
+ }
+ var records = replay.records.filter { !replay.failedRoots.contains($0.value.rootID) }
+ for (id, turn) in baseline where replay.failedRoots.contains(turn.rootID) {
+ records[id] = turn
+ }
return retained(records, now: now)
}
@@ -241,8 +253,77 @@ actor TokenHistoryStore {
}
}
+/// 重放错误以根轮次为边界, 归属不明时不能证明错误与选区无关
+private nonisolated struct TokenJournalReplay {
+ var records: [String: TokenTurn]
+ var failedRoots = Set<String>()
+ private var rootByTurn: [String: String] = [:]
+ private var startsByRoot: [String: Date] = [:]
+
+ init(baseline: [String: TokenTurn], replayingFromEmpty: Bool = false) throws {
+ records = replayingFromEmpty ? [:] : baseline
+ for turn in baseline.values {
+ try register(turn, rootStartedAt: baseline[turn.rootID]?.startedAt)
+ }
+ }
+
+ mutating func consume(_ entry: AppServerEventRecord, includesSnapshots: Bool) throws {
+ if let observation = entry.observation {
+ let turn = observation.turn
+ try register(turn, rootStartedAt: observation.rootStartedAt)
+ guard !failedRoots.contains(turn.rootID) else { return }
+ do {
+ records[turn.id] = try observation.applying(to: records[turn.id])
+ if turn.id != turn.rootID, records[turn.rootID] == nil {
+ records[turn.rootID] = TokenTurn(
+ id: turn.rootID, rootID: turn.rootID,
+ startedAt: startsByRoot[turn.rootID], updatedAt: turn.updatedAt
+ )
+ }
+ if records[turn.rootID]?.startedAt == nil {
+ records[turn.rootID]?.startedAt = startsByRoot[turn.rootID]
+ }
+ } catch {
+ failedRoots.insert(turn.rootID)
+ }
+ } else if let turn = entry.token {
+ try register(turn, rootStartedAt: nil)
+ if includesSnapshots, !failedRoots.contains(turn.rootID) {
+ records[turn.id] = records[turn.id]?.merging(turn) ?? turn
+ }
+ }
+ }
+
+ func selectedRoots(in dates: Set<String>) throws -> [String: String] {
+ var result: [String: String] = [:]
+ for root in Set(rootByTurn.values) {
+ guard let start = startsByRoot[root] else { throw TokenCacheError.incompleteJournal }
+ let date = HistoryStorage.dateKey(for: start)
+ if dates.contains(date) {
+ result[root] = date
+ }
+ }
+ return result
+ }
+
+ private mutating func register(_ turn: TokenTurn, rootStartedAt: Date?) throws {
+ if let previous = rootByTurn[turn.id], previous != turn.rootID {
+ throw TokenCacheError.incompleteJournal
+ }
+ rootByTurn[turn.id] = turn.rootID
+ let start = rootStartedAt ?? (turn.id == turn.rootID ? turn.startedAt : nil)
+ if let start {
+ if let previous = startsByRoot[turn.rootID],
+ HistoryStorage.dateKey(for: previous) != HistoryStorage.dateKey(for: start) {
+ throw TokenCacheError.incompleteJournal
+ }
+ startsByRoot[turn.rootID] = start
+ }
+ }
+}
+
private nonisolated struct TokenAggregateCache: Codable {
- static let currentVersion = 2
+ static let currentVersion = 1
var version = Self.currentVersion
var turns: [String: TokenTurn]
var files: [String: TokenJournalCheckpoint]
@@ -257,6 +338,8 @@ private nonisolated struct TokenJournalCheckpoint: Codable {
nonisolated struct TokenRebuildResult {
let dateKeys: [String]
let turnCount: Int
+ var failedDateKeys: [String] = []
+ var turns: [TokenTurn]?
static let empty = Self(dateKeys: [], turnCount: 0)
}
diff --git a/CodexBar/Services/Notifications/NotificationService.swift b/CodexBar/Services/Notifications/NotificationService.swift
index 98911ba..d4ffd9e 100644
--- a/CodexBar/Services/Notifications/NotificationService.swift
+++ b/CodexBar/Services/Notifications/NotificationService.swift
@@ -29,8 +29,8 @@ final class NotificationService: NSObject {
private var sentDedupKeys: [String]
private var submittingDedupKeys = Set<String>()
- /// 阈值穿越判定的会话内上一帧剩余比例, key 为 account|limitId|windowId
- private var lastRemainingPercents: [String: Int] = [:]
+ /// 阈值观察随额度周期重置, key 为 account|limitId|windowId
+ private var lowQuotaObservations: [String: LowQuotaObservation] = [:]
/// 低额度判定依据的两个设置项
/// 订阅回调跑在 @Published 的 willSet, 那时属性还是旧值, 只有回调参数是新的
@@ -327,7 +327,7 @@ final class NotificationService: NSObject {
private func resetLowQuotaObservation(for snapshot: CodexQuotaSnapshot) {
forEachQuotaWindowWithData(in: snapshot) { _, _, stateKey in
- lastRemainingPercents.removeValue(forKey: stateKey)
+ lowQuotaObservations.removeValue(forKey: stateKey)
}
}
@@ -352,22 +352,18 @@ final class NotificationService: NSObject {
return
}
- let previousRemainingPercent = lastRemainingPercents[stateKey]
- lastRemainingPercents[stateKey] = window.remainingPercent
+ let crossedThreshold = lowQuotaObservations[stateKey, default: LowQuotaObservation()].observe(
+ remainingPercent: window.remainingPercent,
+ resetsAt: window.resetsAt,
+ thresholdPercent: lowQuota.thresholdPercent
+ )
guard let resetsAt = window.resetsAt,
- window.remainingPercent <= lowQuota.thresholdPercent,
+ crossedThreshold,
lowQuota.isEnabled else {
return
}
- // 穿越判定: 上一帧高于阈值才提醒; 会话内首次观察即低于也视为穿越
- // (App 可能在跌破后才启动), 持久化去重键保证每周期只发一次
- if let previousRemainingPercent,
- previousRemainingPercent <= lowQuota.thresholdPercent {
- return
- }
-
// 阈值是用户设置值不是用量数据, 记它才能解释这条通知为什么会发出来
let threshold = lowQuota.thresholdPercent
let details = LogFields.joined(
@@ -387,7 +383,7 @@ final class NotificationService: NSObject {
sound: settings.lowQuotaSound,
dedupKey: dedupKey,
onSubmissionFailure: { [weak self] in
- self?.lastRemainingPercents.removeValue(forKey: stateKey)
+ self?.lowQuotaObservations.removeValue(forKey: stateKey)
}
)
}
@@ -566,7 +562,7 @@ final class NotificationService: NSObject {
return false
}
- return abs(TimeInterval(existingEpoch) - TimeInterval(resetEpoch)) <= Self.lowQuotaResetTolerance
+ return LowQuotaObservation.matchesReset(existingEpoch, resetEpoch)
}
if let existingKey = sentDedupKeys.first(where: matchesReset) {
@@ -758,12 +754,35 @@ final class NotificationService: NSObject {
private static let taskHapticPulseCount = 10
private static let taskHapticPulseInterval = Duration.milliseconds(100)
private static let notificationSubmissionRetryCount = 1
- private static let lowQuotaResetTolerance: TimeInterval = 60
private static let sentKeysLimit = 300
private static let sentKeysKey = "Notification.sentKeys"
private static let legacyResetDedupKeyPrefix = "reset|"
private static let legacyPendingResetReminderKey = "Notification.pendingResetReminders"
+ struct LowQuotaObservation {
+ private var remainingPercent: Int?
+ private var resetEpoch: Int?
+
+ mutating func observe(remainingPercent: Int, resetsAt: Date?, thresholdPercent: Int) -> Bool {
+ let newResetEpoch = resetsAt.map { Int($0.timeIntervalSince1970) }
+ let isSameCycle = resetEpoch.flatMap { previous in
+ newResetEpoch.map { Self.matchesReset(previous, $0) }
+ } ?? false
+ let previousRemainingPercent = isSameCycle ? self.remainingPercent : nil
+ // 周期比较和持久化去重都以固定时间为锚点
+ if !isSameCycle {
+ resetEpoch = newResetEpoch
+ }
+ self.remainingPercent = remainingPercent
+ return newResetEpoch != nil && remainingPercent <= thresholdPercent
+ && (previousRemainingPercent.map { $0 > thresholdPercent } ?? true)
+ }
+
+ static func matchesReset(_ lhs: Int, _ rhs: Int) -> Bool {
+ abs(TimeInterval(lhs) - TimeInterval(rhs)) <= 60
+ }
+ }
+
/// 单个额度窗口的重置观察状态: 记录大于 0 的消耗, 归零时消费并发送
private struct QuotaWindowResetObservation {
/// 窗口生命周期标记, 迟到的发送失败回调据此丢弃
diff --git a/CodexBar/Services/Settings/SyncSettings.swift b/CodexBar/Services/Settings/SyncSettings.swift
index a0bebf9..9d3bdc6 100644
--- a/CodexBar/Services/Settings/SyncSettings.swift
+++ b/CodexBar/Services/Settings/SyncSettings.swift
@@ -13,13 +13,32 @@ final class SyncSettings: ObservableObject {
@Published private(set) var syncAvailability = SyncAvailability.unknown
private let defaults: UserDefaults
+ private let queryAvailability: () async -> SyncAvailabilityResult
+ private let loadLastUpload: () -> Date?
private var cancellables = Set<AnyCancellable>()
private let accountStatusCoordinator = RefreshTaskCoordinator()
+ private var isCheckingAvailability = false
+ private var lastAvailabilityCheckAt: Date?
+ private static let availabilityRetryInterval: TimeInterval = 60
+
+ convenience init(defaults: UserDefaults = .standard) {
+ self.init(
+ defaults: defaults,
+ queryAvailability: { await Self.querySyncAvailability() },
+ loadLastUpload: Self.loadLastUploadAt
+ )
+ }
- init(defaults: UserDefaults = .standard) {
+ init(
+ defaults: UserDefaults,
+ queryAvailability: @escaping () async -> SyncAvailabilityResult,
+ loadLastUpload: @escaping () -> Date?
+ ) {
self.defaults = defaults
+ self.queryAvailability = queryAvailability
+ self.loadLastUpload = loadLastUpload
isEnabled = Self.isEnabled(defaults: defaults)
- lastUploadAt = Self.loadLastUploadAt()
+ lastUploadAt = loadLastUpload()
observeSyncNotifications()
refreshSyncAvailability()
}
@@ -29,10 +48,19 @@ final class SyncSettings: ObservableObject {
if !isEnabled {
clearSyncActivity()
}
- lastUploadAt = Self.loadLastUploadAt()
+ lastUploadAt = loadLastUpload()
refreshSyncAvailability()
}
+ /// 自动维护只重查未恢复的同步状态, 本地维护无需等待 iCloud
+ func refreshAvailabilityIfNeeded(now: Date = Date()) {
+ guard isEnabled, !isSyncAvailable,
+ lastAvailabilityCheckAt.map({ now.timeIntervalSince($0) >= Self.availabilityRetryInterval }) ?? true else {
+ return
+ }
+ refreshSyncAvailability(now: now)
+ }
+
@discardableResult
func setEnabled(_ enabled: Bool) -> Bool {
guard !enabled || syncAvailability.isAvailable else {
@@ -45,10 +73,12 @@ final class SyncSettings: ObservableObject {
}
defaults.set(enabled, forKey: Self.enabledKey)
if !enabled {
+ accountStatusCoordinator.cancel()
+ isCheckingAvailability = false
clearSyncActivity()
}
isEnabled = enabled
- lastUploadAt = Self.loadLastUploadAt()
+ lastUploadAt = loadLastUpload()
return previousValue != enabled
}
@@ -60,9 +90,9 @@ final class SyncSettings: ObservableObject {
syncFailureMessage != nil
}
- func activation(isSyncAvailable: Bool? = nil) -> SyncActivation {
+ func activation() -> SyncActivation {
guard isEnabled else { return .syncOff }
- guard isSyncAvailable ?? self.isSyncAvailable else { return .unavailable }
+ guard isSyncAvailable else { return .unavailable }
return .active
}
@@ -107,16 +137,21 @@ final class SyncSettings: ObservableObject {
.store(in: &cancellables)
}
- private func refreshSyncAvailability() {
- accountStatusCoordinator.start { [weak self] generation in
- let result = await Self.querySyncAvailability()
+ private func refreshSyncAvailability(now: Date = Date()) {
+ guard !isCheckingAvailability else { return }
+ isCheckingAvailability = true
+ lastAvailabilityCheckAt = now
+ accountStatusCoordinator.start { [weak self, queryAvailability] generation in
+ let result = await queryAvailability()
guard let self,
accountStatusCoordinator.canCommit(generation) else {
return
}
applyAvailabilityResult(result)
- accountStatusCoordinator.finish(generation) {}
+ accountStatusCoordinator.finish(generation) {
+ isCheckingAvailability = false
+ }
}
}
@@ -135,7 +170,7 @@ final class SyncSettings: ObservableObject {
} else {
applySyncFailure(failureMessage)
}
- lastUploadAt = Self.loadLastUploadAt()
+ lastUploadAt = loadLastUpload()
}
private func applyAvailabilityResult(_ result: SyncAvailabilityResult) {
diff --git a/CodexBar/Services/Support/AppStorage.swift b/CodexBar/Services/Support/AppStorage.swift
index f277f3d..7e1f634 100644
--- a/CodexBar/Services/Support/AppStorage.swift
+++ b/CodexBar/Services/Support/AppStorage.swift
@@ -2,9 +2,9 @@ import Foundation
nonisolated enum AppStorage {
#if DEBUG
- static let directoryName = "CodexBar Debug"
+ static let directoryName = "CodexBar Data Debug"
#else
- static let directoryName = "CodexBar"
+ static let directoryName = "CodexBar Data"
#endif
static func directoryURL(fileManager: FileManager = .default) -> URL {
diff --git a/CodexBar/Services/Support/JSONLines.swift b/CodexBar/Services/Support/JSONLines.swift
index 9b22c97..ed2274a 100644
--- a/CodexBar/Services/Support/JSONLines.swift
+++ b/CodexBar/Services/Support/JSONLines.swift
@@ -41,17 +41,6 @@ nonisolated enum JSONLines {
Date(timeIntervalSince1970: (date.timeIntervalSince1970 * 1000).rounded(.down) / 1000)
}
- /// 从文件中部 seek 读取时首行必然残缺: 丢弃首个换行(含)之前的内容
- /// 找不到换行时原样返回, 交给按行解码当坏行跳过
- static func droppingLeadingPartialLine(_ data: Data) -> Data {
- guard let firstNewlineIndex = data.firstIndex(of: newlineByte) else {
- return data
- }
-
- let firstCompleteIndex = data.index(after: firstNewlineIndex)
- return firstCompleteIndex < data.endIndex ? Data(data[firstCompleteIndex...]) : Data()
- }
-
/// 按行解码 JSONL: 切分换行, 跳过空行与解码失败的行
static func decode<T: Decodable>(_ type: T.Type = T.self, from data: Data) -> [T] {
decodeWithFailures(type, from: data).values
diff --git a/CodexBar/Services/Support/OrderedJSON.swift b/CodexBar/Services/Support/OrderedJSON.swift
deleted file mode 100644
index 51d2688..0000000
--- a/CodexBar/Services/Support/OrderedJSON.swift
+++ /dev/null
@@ -1,41 +0,0 @@
-import Foundation
-
-/// 写入 JSONL 时固定字段顺序, 便于人工排查和 diff
-nonisolated enum OrderedJSON {
- static func lineData(_ fields: [String]) -> Data {
- let json = "{\(fields.joined(separator: ","))}"
- return Data(json.utf8) + Data([0x0A])
- }
-
- static func field(_ name: String, _ value: (some Encodable)?) throws -> String {
- try "\"\(name)\":\(Self.value(value))"
- }
-
- static func value(_ value: (some Encodable)?) throws -> String {
- guard let value else {
- return "null"
- }
-
- return try Self.value(value)
- }
-
- static func value(_ value: some Encodable) throws -> String {
- let data = try JSONLines.stableEncoder.encode(value)
- guard let text = String(bytes: data, encoding: .utf8) else {
- throw EncodingError.invalidValue(
- value,
- .init(codingPath: [], debugDescription: "Encoded history JSON was not UTF-8")
- )
- }
- return text
- }
-
- static func presentCountFields(_ values: [(String, Int?)]) throws -> [String] {
- try values.compactMap { name, value in
- guard let value else {
- return nil
- }
- return try field(name, value)
- }
- }
-}
diff --git a/CodexBar/Services/Sync/ActivitySyncStore.swift b/CodexBar/Services/Sync/ActivitySyncStore.swift
index 0b28198..eb755f3 100644
--- a/CodexBar/Services/Sync/ActivitySyncStore.swift
+++ b/CodexBar/Services/Sync/ActivitySyncStore.swift
@@ -102,7 +102,6 @@ nonisolated struct SyncState: Codable, Equatable {
var containerIdentifier: String?
var deviceID: String?
var hashByDate: [String: String]
- var replacementDates: [String]
var lastUploadAt: Date?
var lastPrunedDate: String?
@@ -110,14 +109,12 @@ nonisolated struct SyncState: Codable, Equatable {
containerIdentifier: String? = SyncCloudKit.containerIdentifier,
deviceID: String? = nil,
hashByDate: [String: String] = [:],
- replacementDates: [String] = [],
lastUploadAt: Date? = nil,
lastPrunedDate: String? = nil
) {
self.containerIdentifier = containerIdentifier
self.deviceID = deviceID
self.hashByDate = hashByDate
- self.replacementDates = replacementDates
self.lastUploadAt = lastUploadAt
self.lastPrunedDate = lastPrunedDate
}
@@ -129,13 +126,6 @@ nonisolated struct SyncState: Codable, Equatable {
deviceID = try container.decodeIfPresent(String.self, forKey: .deviceID)
hashByDate = try container.decodeIfPresent([String: String].self, forKey: .hashByDate)
?? [:]
- let decodedReplacementDates = try container.decodeIfPresent(
- [String].self,
- forKey: .replacementDates
- ) ?? []
- replacementDates = Set(
- decodedReplacementDates.filter(HistoryStorage.isValidDateKey)
- ).sorted()
lastUploadAt = try container.decodeIfPresent(Date.self, forKey: .lastUploadAt)
lastPrunedDate = try container.decodeIfPresent(String.self, forKey: .lastPrunedDate)
}
@@ -144,7 +134,6 @@ nonisolated struct SyncState: Codable, Equatable {
case containerIdentifier
case deviceID
case hashByDate
- case replacementDates
case lastUploadAt
case lastPrunedDate
}
diff --git a/CodexBar/Services/Sync/SyncScheduler.swift b/CodexBar/Services/Sync/SyncScheduler.swift
index a060c9f..e75c498 100644
--- a/CodexBar/Services/Sync/SyncScheduler.swift
+++ b/CodexBar/Services/Sync/SyncScheduler.swift
@@ -56,10 +56,8 @@ final class SyncScheduler {
drain()
}
- /// activation 传 nil 时现场求值
- /// 从 @Published 的订阅里调用必须显式传入: 那时属性还是旧值, 现场求值会得到刚被改掉的那个结论
- func requestSync(trigger: LogTrigger, activation overrideActivation: SyncActivation? = nil) {
- let activation = overrideActivation ?? syncActivation()
+ func requestSync(trigger: LogTrigger) {
+ let activation = syncActivation()
guard activation.isActive else {
let details = LogFields.joined(
"trigger=\(trigger.rawValue)",
diff --git a/CodexBar/Services/Sync/SyncService.swift b/CodexBar/Services/Sync/SyncService.swift
index fb365ce..cf24032 100644
--- a/CodexBar/Services/Sync/SyncService.swift
+++ b/CodexBar/Services/Sync/SyncService.swift
@@ -58,34 +58,13 @@ actor SyncService {
// MARK: - 同步入口
- func snapshotFromCacheIfEnabled(localTokenTurns: [TokenTurn] = []) async -> SyncSnapshot {
+ func snapshotFromCacheIfEnabled(localTokenTurns: [TokenTurn] = [], replacements: [ActivityAggregate] = []) async -> SyncSnapshot {
guard isEnabled() else {
return .disabled
}
let state = activityStore.loadState()
- return await snapshot(from: state, localTokenTurns: localTokenTurns)
- }
-
- /// 显式重建后, 将所选日期标记为当前设备云端贡献的权威替换来源
- func markReplacementNeeded(for dates: [String]) throws {
- let validDates = Set(dates.filter(HistoryStorage.isValidDateKey))
- guard !validDates.isEmpty else {
- return
- }
-
- var state = activityStore.loadState()
- state.replacementDates = Set(state.replacementDates)
- .union(validDates)
- .sorted()
- for date in validDates {
- state.hashByDate.removeValue(forKey: date)
- }
- try activityStore.saveState(state)
- }
-
- func hasPendingReplacement(for dates: [String]) -> Bool {
- !Set(activityStore.loadState().replacementDates).isDisjoint(with: dates)
+ return await snapshot(from: state, localTokenTurns: localTokenTurns, replacementDates: Set(replacements.map(\.date)))
}
func tokenRecoveryBaselineIfEnabled() async -> TokenHistoryBaseline? {
@@ -100,6 +79,7 @@ actor SyncService {
func synchronizeIfEnabled(
localAggregates: [ActivityAggregate],
localTokenTurns: [TokenTurn] = [],
+ replacements: [ActivityAggregate] = [],
trigger: LogTrigger
) async -> SyncSnapshot {
guard isEnabled(), !Task.isCancelled else {
@@ -122,6 +102,7 @@ actor SyncService {
}
var state = activityStore.loadState()
+ var completedReplacements: [String: String] = [:]
// 显式开启同步允许恢复缺失的 zone, 同一轮最多重新执行一次
cachedAccountSalt = nil
@@ -130,7 +111,8 @@ actor SyncService {
try SyncCancellation.check(isEnabled: isEnabled)
failureMessage = try await synchronizeOnce(
localAggregates: localAggregates, localTokenTurns: localTokenTurns,
- state: &state, stage: &stage, trigger: trigger, duration: duration
+ replacements: replacements, completedReplacements: &completedReplacements,
+ state: &state, stage: &stage, trigger: trigger
)
didSucceed = failureMessage == nil
break
@@ -140,6 +122,7 @@ actor SyncService {
invalidateAccountScopedCaches()
}
if SyncRecovery.isMissingZone(error, zoneID: syncZoneID), !Task.isCancelled, isEnabled() {
+ completedReplacements.removeAll()
do {
try await resetSyncState(state: &state)
if attempt == 0 {
@@ -163,13 +146,17 @@ actor SyncService {
guard !Task.isCancelled, isEnabled() else { return .disabled }
let latestState = activityStore.loadState()
- return await snapshot(from: latestState, localTokenTurns: localTokenTurns)
+ var result = await snapshot(from: latestState, localTokenTurns: localTokenTurns, replacementDates: Set(replacements.map(\.date)))
+ result.completedReplacements = completedReplacements
+ return result
}
private func synchronizeOnce(
localAggregates: [ActivityAggregate], localTokenTurns: [TokenTurn],
- state: inout SyncState, stage: inout SyncStage, trigger: LogTrigger, duration: LogDuration
+ replacements: [ActivityAggregate], completedReplacements: inout [String: String],
+ state: inout SyncState, stage: inout SyncStage, trigger: LogTrigger
) async throws -> String? {
+ let duration = LogDuration()
try await ensureSyncZoneExists(state: &state)
stage = .device
let deviceID = try await resolveCurrentDeviceID()
@@ -181,7 +168,15 @@ actor SyncService {
do {
stage = .upload
localByDate = try Self.syncedAggregatesByDate(localAggregates)
- confirmedDates = try await synchronizeActivity(localByDate: localByDate, deviceID: deviceID, state: &state, stage: &stage)
+ for (date, var replacement) in try Self.syncedAggregatesByDate(replacements) {
+ guard replacement.aggregate.eventCount != nil else { throw ActivitySyncError.invalidRecordIdentity }
+ replacement.isReplacement = true
+ localByDate[date] = replacement
+ }
+ confirmedDates = try await synchronizeActivity(
+ localByDate: localByDate, deviceID: deviceID, state: &state, stage: &stage,
+ completedReplacements: &completedReplacements
+ )
} catch {
if SyncRecovery.stopsOtherSync(error) {
throw error
@@ -222,13 +217,16 @@ actor SyncService {
private func synchronizeActivity(
localByDate: [String: LocalSyncAggregate], deviceID: String,
- state: inout SyncState, stage: inout SyncStage
+ state: inout SyncState, stage: inout SyncStage,
+ completedReplacements: inout [String: String]
) async throws -> Set<String> {
stage = .fetch
try await refreshCacheBeforeUpload(localByDate: localByDate, deviceID: deviceID, state: &state)
stage = .upload
- let dates = try await uploadChangedAggregates(localByDate: localByDate, remoteRecords: activityStore.loadCachedRecords(), state: &state)
- try finalizeUpload(confirmedDates: dates, state: &state)
+ let dates = try await uploadChangedAggregates(
+ localByDate: localByDate, remoteRecords: activityStore.loadCachedRecords(),
+ state: &state, completedReplacements: &completedReplacements
+ )
stage = .fetch
try await refreshCacheFromRemote()
return dates
@@ -281,7 +279,7 @@ actor SyncService {
deviceID: String,
state: inout SyncState
) async throws {
- guard !state.replacementDates.isEmpty else {
+ guard localByDate.values.contains(where: \.isReplacement) else {
try await refreshCacheFromRemote()
return
}
@@ -295,17 +293,6 @@ actor SyncService {
)
}
- private func finalizeUpload(
- confirmedDates: Set<String>,
- state: inout SyncState
- ) throws {
- let completedReplacementDates = Set(state.replacementDates).intersection(confirmedDates)
- if !completedReplacementDates.isEmpty {
- state.replacementDates.removeAll { completedReplacementDates.contains($0) }
- try activityStore.saveState(state)
- }
- }
-
private func resetStateIfDeviceChanged(
_ deviceID: String,
state: inout SyncState
@@ -322,7 +309,7 @@ actor SyncService {
private func resetSyncState(state: inout SyncState) async throws {
try SyncCancellation.check(isEnabled: isEnabled)
// 先持久化未绑定状态, 中途失败或退出后仍会重新清理, 不把旧缓存当作已恢复
- state = SyncState(replacementDates: state.replacementDates)
+ state = SyncState()
try activityStore.reset(state: state)
try await tokenSync.resetCache()
try SyncCancellation.check(isEnabled: isEnabled)
@@ -340,12 +327,11 @@ actor SyncService {
}
}
- private func snapshot(from state: SyncState, localTokenTurns: [TokenTurn]) async -> SyncSnapshot {
+ private func snapshot(from state: SyncState, localTokenTurns: [TokenTurn], replacementDates: Set<String>) async -> SyncSnapshot {
guard let deviceID = state.deviceID else {
return .disabled
}
- let replacementDates = Set(state.replacementDates)
let records = Self.filteredRetained(records: activityStore.loadCachedRecords()).filter { record in
record.deviceID != deviceID || !replacementDates.contains(record.date)
}
@@ -362,12 +348,14 @@ private extension SyncService {
struct LocalSyncAggregate {
let aggregate: SyncedActivity
let generationStartedEmpty: Bool
+ var isReplacement = false
}
struct PendingUpload {
let date: String
let aggregate: SyncedActivity
let generationStartedEmpty: Bool
+ var isReplacement = false
let hash: String
}
@@ -423,7 +411,8 @@ private extension SyncService {
func uploadChangedAggregates(
localByDate: [String: LocalSyncAggregate],
remoteRecords: [ActivitySyncRecord],
- state: inout SyncState
+ state: inout SyncState,
+ completedReplacements: inout [String: String]
) async throws -> Set<String> {
guard let deviceID = state.deviceID else {
return []
@@ -459,6 +448,9 @@ private extension SyncService {
let batchEnd = min(batchStart + Metrics.uploadBatchSize, pendingUploads.count)
let batch = Array(pendingUploads[batchStart ..< batchEnd])
let result = try await processUploadBatch(batch, deviceID: deviceID, remoteRecords: remoteRecords)
+ for confirmation in result.confirmed where confirmation.didUpload && localByDate[confirmation.date]?.isReplacement == true {
+ completedReplacements[confirmation.date] = localByDate[confirmation.date]?.aggregate.generationID
+ }
try applyConfirmedHashes(result.confirmed, to: &state)
confirmedDates.formUnion(result.confirmed.map(\.date))
try result.failures.checkStopping()
@@ -476,7 +468,7 @@ private extension SyncService {
deviceID: String,
state: inout SyncState
) async throws {
- let replacementDates = Set(state.replacementDates).intersection(localByDate.keys)
+ let replacementDates = Set(localByDate.filter(\.value.isReplacement).keys)
guard !replacementDates.isEmpty else {
return
}
@@ -565,6 +557,7 @@ private extension SyncService {
date: date,
aggregate: local.aggregate,
generationStartedEmpty: local.generationStartedEmpty,
+ isReplacement: local.isReplacement,
hash: hash
)
}
@@ -585,6 +578,9 @@ private extension SyncService {
existingRecords: [CKRecord.ID: Result<CKRecord, any Error>]
) throws -> UploadTarget {
let existing = try Self.fetchedRecord(from: existingRecords[pendingRecord.recordID])
+ if pendingRecord.upload.isReplacement {
+ return .save(existing ?? CKRecord(recordType: RecordTypes.activity, recordID: pendingRecord.recordID))
+ }
if let existing {
guard let remote = try ActivityRecordCodec.remoteDailyRecord(from: existing) else {
throw ActivitySyncError.invalidRecordIdentity
@@ -881,7 +877,6 @@ private extension SyncService {
let cutoffKey = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate())
let expiredDates = Set(state.hashByDate.keys.filter { $0 < cutoffKey })
- state.replacementDates.removeAll { $0 < cutoffKey }
let recordIDs = try await Set(
fetchCurrentDeviceRecordIDsToPrune(
deviceID: deviceID,
@@ -1148,6 +1143,7 @@ nonisolated struct SyncSnapshot: Equatable {
let records: [ActivitySyncRecord]
let currentDeviceID: String?
var tokenUsageByDate: [String: TokenUsage]?
+ var completedReplacements: [String: String] = [:]
static let disabled = SyncSnapshot(records: [], currentDeviceID: nil)
}
diff --git a/CodexBar/Services/Sync/TokenSync.swift b/CodexBar/Services/Sync/TokenSync.swift
index 89c4e3b..ed87dcc 100644
--- a/CodexBar/Services/Sync/TokenSync.swift
+++ b/CodexBar/Services/Sync/TokenSync.swift
@@ -8,7 +8,7 @@ actor TokenSync {
private let isEnabled: @Sendable () -> Bool
private var fileCache: TokenFileCache<TokenSyncCache>
static let recordType = "Tokens"
- private static let currentVersion = 2
+ private static let currentVersion = 1
init(database: any SyncDatabase, directoryURL: URL, isEnabled: @escaping @Sendable () -> Bool = { SyncSettings.isEnabled() }) {
self.database = database
@@ -260,7 +260,7 @@ actor TokenSync {
private nonisolated struct TokenSyncCacheHeader: Decodable { let version: Int }
private nonisolated struct TokenSyncCache: Codable, Equatable {
- static let currentVersion = 2
+ static let currentVersion = 1
var version = currentVersion
let accountScopedDeviceID: String
let salt: Data
diff --git a/CodexBar/Views/Menu/ActivityCard.swift b/CodexBar/Views/Menu/ActivityCard.swift
index 31e280f..6fbee22 100644
--- a/CodexBar/Views/Menu/ActivityCard.swift
+++ b/CodexBar/Views/Menu/ActivityCard.swift
@@ -6,14 +6,17 @@ struct ActivityCard: View {
@ObservedObject var activityMonitor: ActivityMonitor
@ObservedObject var presentationState: ActivityCenterPresentationState
@ObservedObject var keepAliveController: KeepAliveController
- let showsUnavailableState: Bool
let onTaskCenterTap: (ScreenFrameProvider) -> Void
@Environment(\.mainPanelAnimationsEnabled) private var allowsAnimations
@State private var frameProvider = ScreenFrameProvider()
@State private var isHovered = false
private var snapshot: ActivitySnapshot {
- showsUnavailableState ? .empty : activityMonitor.snapshot
+ activityMonitor.snapshot
+ }
+
+ private var showsUnavailableState: Bool {
+ !activityMonitor.isActivitySourceHealthy
}
private var timelineDate: Date {
diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swift
index 330c114..442b41c 100644
--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift
+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift
@@ -148,7 +148,6 @@ private extension CodexStatusMenuView {
activityMonitor: activityMonitor,
presentationState: activityCenterPresentationState,
keepAliveController: keepAliveController,
- showsUnavailableState: viewModel.snapshot == nil,
onTaskCenterTap: { anchorProvider in
onActivityCenterTap(
ActivityCenterPanelContext(
@@ -179,12 +178,12 @@ private extension CodexStatusMenuView {
@ViewBuilder
func usageSection(dataPlaceholderSection: MainPanelSection?) -> some View {
- if let snapshot = viewModel.snapshot {
+ if hasData(for: .usage) {
UsageSummaryView(
- usage: snapshot.usage,
+ usage: viewModel.snapshot?.usage,
history: historyViewModel.snapshot,
showsActivity: true,
- isStale: snapshot.isUsageStale,
+ isStale: viewModel.snapshot?.isUsageStale ?? false,
onHoverContextChange: onUsageHeatmapHoverChange
)
.id(menuSurfaceVisibility.presentationGeneration)
@@ -220,7 +219,8 @@ private extension CodexStatusMenuView {
case .quota:
viewModel.snapshot?.limits.isEmpty == false
case .usage:
- viewModel.snapshot != nil
+ viewModel.snapshot != nil || !historyViewModel.snapshot.dailyMetrics.isEmpty
+ || !historyViewModel.snapshot.tokenUsageByDate.isEmpty
case .account, .activity, .status:
false
}
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index b3037f6..5ea5e54 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -814,25 +814,26 @@ private extension AppSettingsView {
)
message += String(localized: "history.rebuild.summary.token-record-count", defaultValue: "\(summary.tokenTurnCount, specifier: "%lld")")
if summary.didFailTokenRebuild {
- message += String(localized: "history.rebuild.summary.token-history-incomplete")
- }
- if summary.corruptLineCount > 0 {
- message += String(localized: "history.rebuild.summary.skipped-invalid-events", defaultValue: "\(summary.corruptLineCount, specifier: "%lld")")
+ let dates = summary.failedTokenDateKeys.prefix(rebuildFailedDateListLimit).joined(separator: ", ")
+ message += String(localized: "history.rebuild.summary.token-history-incomplete", defaultValue: "\(dates)")
}
- if !summary.failedDateKeys.isEmpty {
- let listed = summary.failedDateKeys.prefix(rebuildFailedDateListLimit)
+ let retryDates = summary.failedDateKeys.filter { !summary.failedRequestDateKeys.contains($0) }
+ if !retryDates.isEmpty {
+ let listed = retryDates.prefix(rebuildFailedDateListLimit)
var dates = listed.joined(separator: ", ")
- if summary.failedDateKeys.count > listed.count {
+ if retryDates.count > listed.count {
dates += String(localized: "history.rebuild.summary.additional-dates")
}
- message += String(localized: "history.rebuild.summary.incomplete-dates", defaultValue: "\(summary.failedDateKeys.count, specifier: "%lld")\(dates)")
+ message += String(localized: "history.rebuild.summary.incomplete-dates", defaultValue: "\(retryDates.count, specifier: "%lld")\(dates)")
message += String(localized: "history.rebuild.summary.retry-later")
}
- if summary.didFailSyncReplacementMarking {
- message += String(localized: "history.rebuild.summary.sync-replacement-marking-failed")
- } else if summary.isSyncReplacementPending {
+ if !summary.failedRequestDateKeys.isEmpty {
+ let dates = summary.failedRequestDateKeys.prefix(rebuildFailedDateListLimit).joined(separator: ", ")
+ message += String(localized: "history.rebuild.summary.request-failed", defaultValue: "\(dates)")
+ }
+ if summary.isSyncReplacementPending {
message += String(localized: "history.rebuild.summary.cloud-replacement-pending")
}
diff --git a/CodexBar/Views/Menu/ScreenFrameReader.swift b/CodexBar/Views/Shared/ScreenFrameReader.swift
similarity index 100%
rename from CodexBar/Views/Menu/ScreenFrameReader.swift
rename to CodexBar/Views/Shared/ScreenFrameReader.swift
diff --git a/CodexBarTests/ActivityIsolationTests.swift b/CodexBarTests/Activity/ActivityIsolationTests.swift
similarity index 100%
rename from CodexBarTests/ActivityIsolationTests.swift
rename to CodexBarTests/Activity/ActivityIsolationTests.swift
diff --git a/CodexBarTests/ActivityRecoveryTests.swift b/CodexBarTests/Activity/ActivityRecoveryTests.swift
similarity index 98%
rename from CodexBarTests/ActivityRecoveryTests.swift
rename to CodexBarTests/Activity/ActivityRecoveryTests.swift
index 457e268..33d4b51 100644
--- a/CodexBarTests/ActivityRecoveryTests.swift
+++ b/CodexBarTests/Activity/ActivityRecoveryTests.swift
@@ -9,7 +9,7 @@ struct ActivityRecoveryTests {
let store = TokenHistoryStore(directoryURL: directory.url)
let id = TokenTurn.identifier(thread: "t", turn: "u")
let record = TokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: .zero)
- try await store.record([record], now: now)
+ try await directory.seedTokenSnapshots([record], now: now)
let cache = try directory.write("broken", to: "Aggregates/tokens.json")
var refreshFailed = false
var rebuildFailed = false
diff --git a/CodexBarTests/ActivitySchedulingTests.swift b/CodexBarTests/Activity/ActivitySchedulingTests.swift
similarity index 100%
rename from CodexBarTests/ActivitySchedulingTests.swift
rename to CodexBarTests/Activity/ActivitySchedulingTests.swift
diff --git a/CodexBarTests/ActivityTaskTests.swift b/CodexBarTests/Activity/ActivityTaskTests.swift
similarity index 95%
rename from CodexBarTests/ActivityTaskTests.swift
rename to CodexBarTests/Activity/ActivityTaskTests.swift
index 2237582..730938c 100644
--- a/CodexBarTests/ActivityTaskTests.swift
+++ b/CodexBarTests/Activity/ActivityTaskTests.swift
@@ -2,6 +2,21 @@ import Foundation
import Testing
struct ActivityTaskTests {
+ @Test(arguments: [-172800.0, 0.5, 2.0])
+ func lifecycleBackfillsMissingStartWithTimestampTolerance(offset: TimeInterval) {
+ var task = makeTask()
+ task.startedAt = nil
+ let start = task.lastActivityAt.addingTimeInterval(offset)
+ let state = healthyLifecycle(startedAt: start)
+ _ = ActivityMonitor.mergeLifecycleBackfill(from: state, into: &task)
+ #expect(task.startedAt == (offset <= 1 ? start : nil))
+ if task.startedAt != nil {
+ let earlier = healthyLifecycle(startedAt: start.addingTimeInterval(-60))
+ _ = ActivityMonitor.mergeLifecycleBackfill(from: earlier, into: &task)
+ #expect(task.startedAt == start)
+ }
+ }
+
@Test func namelessToolAndApprovalDoNotReusePreviousToolName() {
var task = makeTask(TestFixtures.event(.toolStarted))
#expect(task.snapshot.toolName == "exec_command")
@@ -123,9 +138,9 @@ struct ActivityTaskTests {
#expect(task.state == .running)
}
- private func healthyLifecycle() -> SessionLifecycleState {
+ private func healthyLifecycle(startedAt: Date? = nil) -> SessionLifecycleState {
SessionLifecycleState(
- requestedThreadID: "session-a", turnID: "turn-a", startedAt: nil, approvalReviewer: nil, effort: nil,
+ requestedThreadID: "session-a", turnID: "turn-a", startedAt: startedAt, approvalReviewer: nil, effort: nil,
lastProgressAt: nil, terminal: nil, readStatus: .complete, hasContext: true
)
}
diff --git a/CodexBarTests/ActivityTokenUsageTests.swift b/CodexBarTests/Activity/ActivityTokenUsageTests.swift
similarity index 100%
rename from CodexBarTests/ActivityTokenUsageTests.swift
rename to CodexBarTests/Activity/ActivityTokenUsageTests.swift
diff --git a/CodexBarTests/AppServerActivityTests.swift b/CodexBarTests/Activity/AppServerActivityTests.swift
similarity index 98%
rename from CodexBarTests/AppServerActivityTests.swift
rename to CodexBarTests/Activity/AppServerActivityTests.swift
index a880fd9..ffd6160 100644
--- a/CodexBarTests/AppServerActivityTests.swift
+++ b/CodexBarTests/Activity/AppServerActivityTests.swift
@@ -304,8 +304,11 @@ struct AppServerActivityTests {
reasoningOutputTokens: 5,
totalTokens: 120
)
- let record = TokenTurn(id: "one", rootID: "one", startedAt: now, updatedAt: now, usage: usage)
- try await store.record([record, record], now: now)
+ let observation = TokenObservation(
+ turn: TokenTurn(id: "one", rootID: "one", startedAt: now, updatedAt: now),
+ rootStartedAt: now, streamID: "stream", sequence: 1, previous: .zero, current: usage
+ )
+ _ = try await store.recordObservations([observation, observation], now: now)
let restarted = TokenHistoryStore(directoryURL: directory.url)
let records = try await restarted.refresh(now: now)
#expect(records.count == 1)
@@ -462,7 +465,7 @@ extension AppServerActivityTests {
totalTokens: 60
)
correction.startNewGeneration(at: now)
- try await store.record([correction], now: now)
+ try await directory.seedTokenSnapshots([correction], now: now)
// 修正发生在采集器提交下一笔之前, 内存仍可能暂时持有旧累计值
_ = try reducer.consume(tokenMessage(total: 110), now: now.addingTimeInterval(1))
let result = try await store.recordObservations(reducer.takeTokenObservations(), now: now)
diff --git a/CodexBarTests/ProtectionStoreTests.swift b/CodexBarTests/Activity/ProtectionStoreTests.swift
similarity index 100%
rename from CodexBarTests/ProtectionStoreTests.swift
rename to CodexBarTests/Activity/ProtectionStoreTests.swift
diff --git a/CodexBarTests/SessionLifecycleCacheTests.swift b/CodexBarTests/Activity/SessionLifecycleCacheTests.swift
similarity index 100%
rename from CodexBarTests/SessionLifecycleCacheTests.swift
rename to CodexBarTests/Activity/SessionLifecycleCacheTests.swift
diff --git a/CodexBarTests/AppServerLogTests.swift b/CodexBarTests/AppServer/AppServerLogTests.swift
similarity index 100%
rename from CodexBarTests/AppServerLogTests.swift
rename to CodexBarTests/AppServer/AppServerLogTests.swift
diff --git a/CodexBarTests/AppServerRPCTests.swift b/CodexBarTests/AppServer/AppServerRPCTests.swift
similarity index 100%
rename from CodexBarTests/AppServerRPCTests.swift
rename to CodexBarTests/AppServer/AppServerRPCTests.swift
diff --git a/CodexBarTests/AppServerRequestBudgetTests.swift b/CodexBarTests/AppServer/AppServerRequestBudgetTests.swift
similarity index 100%
rename from CodexBarTests/AppServerRequestBudgetTests.swift
rename to CodexBarTests/AppServer/AppServerRequestBudgetTests.swift
diff --git a/CodexBarTests/AppServerSessionTests.swift b/CodexBarTests/AppServer/AppServerSessionTests.swift
similarity index 100%
rename from CodexBarTests/AppServerSessionTests.swift
rename to CodexBarTests/AppServer/AppServerSessionTests.swift
diff --git a/CodexBarTests/AppServerStartupTests.swift b/CodexBarTests/AppServer/AppServerStartupTests.swift
similarity index 100%
rename from CodexBarTests/AppServerStartupTests.swift
rename to CodexBarTests/AppServer/AppServerStartupTests.swift
diff --git a/CodexBarTests/CodexVersionProcessTests.swift b/CodexBarTests/Codex/CodexVersionProcessTests.swift
similarity index 100%
rename from CodexBarTests/CodexVersionProcessTests.swift
rename to CodexBarTests/Codex/CodexVersionProcessTests.swift
diff --git a/CodexBarTests/CodexVersionTests.swift b/CodexBarTests/Codex/CodexVersionTests.swift
similarity index 100%
rename from CodexBarTests/CodexVersionTests.swift
rename to CodexBarTests/Codex/CodexVersionTests.swift
diff --git a/CodexBarTests/AutoResetControllerTests.swift b/CodexBarTests/CodexStatus/AutoResetControllerTests.swift
similarity index 100%
rename from CodexBarTests/AutoResetControllerTests.swift
rename to CodexBarTests/CodexStatus/AutoResetControllerTests.swift
diff --git a/CodexBarTests/AutoResetScheduleTests.swift b/CodexBarTests/CodexStatus/AutoResetScheduleTests.swift
similarity index 100%
rename from CodexBarTests/AutoResetScheduleTests.swift
rename to CodexBarTests/CodexStatus/AutoResetScheduleTests.swift
diff --git a/CodexBarTests/CodexQuotaAndIdentityTests.swift b/CodexBarTests/CodexStatus/CodexQuotaAndIdentityTests.swift
similarity index 100%
rename from CodexBarTests/CodexQuotaAndIdentityTests.swift
rename to CodexBarTests/CodexStatus/CodexQuotaAndIdentityTests.swift
diff --git a/CodexBarTests/CodexStatus/LowQuotaObservationTests.swift b/CodexBarTests/CodexStatus/LowQuotaObservationTests.swift
new file mode 100644
index 0000000..460515b
--- /dev/null
+++ b/CodexBarTests/CodexStatus/LowQuotaObservationTests.swift
@@ -0,0 +1,53 @@
+import Foundation
+import Testing
+
+struct LowQuotaObservationTests {
+ @Test func newCycleCanNotifyWithoutAnObservedRecoveryAboveThreshold() {
+ var observation = NotificationService.LowQuotaObservation()
+ let reset = TestFixtures.now
+ let firstLow = observation.observe(remainingPercent: 5, resetsAt: reset, thresholdPercent: 10)
+ #expect(firstLow)
+ let sameCycleLow = observation.observe(remainingPercent: 4, resetsAt: reset, thresholdPercent: 10)
+ #expect(!sameCycleLow)
+ let nextReset = reset.addingTimeInterval(18000)
+ let nextCycleLow = observation.observe(remainingPercent: 5, resetsAt: nextReset, thresholdPercent: 10)
+ #expect(nextCycleLow)
+ let repeatedNextCycleLow = observation.observe(remainingPercent: 3, resetsAt: nextReset, thresholdPercent: 10)
+ #expect(!repeatedNextCycleLow)
+ }
+
+ @Test(arguments: [-60.0, -1, 0, 1, 60])
+ func resetTimeDriftDoesNotCreateANewCycle(_ drift: TimeInterval) {
+ var observation = NotificationService.LowQuotaObservation()
+ let firstLow = observation.observe(remainingPercent: 5, resetsAt: TestFixtures.now, thresholdPercent: 10)
+ #expect(firstLow)
+ let driftedLow = observation.observe(remainingPercent: 5, resetsAt: TestFixtures.now.addingTimeInterval(drift), thresholdPercent: 10)
+ #expect(!driftedLow)
+ let returnedLow = observation.observe(remainingPercent: 4, resetsAt: TestFixtures.now, thresholdPercent: 10)
+ #expect(!returnedLow)
+ }
+
+ @Test func thresholdCrossingAndMissingResetRetainTheirMeaning() {
+ var observation = NotificationService.LowQuotaObservation()
+ let aboveThreshold = observation.observe(remainingPercent: 50, resetsAt: TestFixtures.now, thresholdPercent: 10)
+ #expect(!aboveThreshold)
+ let atThreshold = observation.observe(remainingPercent: 10, resetsAt: TestFixtures.now, thresholdPercent: 10)
+ #expect(atThreshold)
+ let missingReset = observation.observe(remainingPercent: 5, resetsAt: nil, thresholdPercent: 10)
+ #expect(!missingReset)
+ let restoredReset = observation.observe(remainingPercent: 5, resetsAt: TestFixtures.now, thresholdPercent: 10)
+ #expect(restoredReset)
+ }
+
+ @Test func newCycleAboveThresholdArmsALaterCrossing() {
+ var observation = NotificationService.LowQuotaObservation()
+ let nextReset = TestFixtures.now.addingTimeInterval(18000)
+ let results = [
+ observation.observe(remainingPercent: 5, resetsAt: TestFixtures.now, thresholdPercent: 10),
+ observation.observe(remainingPercent: 80, resetsAt: nextReset, thresholdPercent: 10),
+ observation.observe(remainingPercent: 10, resetsAt: nextReset, thresholdPercent: 10),
+ observation.observe(remainingPercent: 9, resetsAt: nextReset, thresholdPercent: 10)
+ ]
+ #expect(results == [true, false, true, false])
+ }
+}
diff --git a/CodexBarTests/AppServerEventStorageTests.swift b/CodexBarTests/History/AppServerEventStorageTests.swift
similarity index 94%
rename from CodexBarTests/AppServerEventStorageTests.swift
rename to CodexBarTests/History/AppServerEventStorageTests.swift
index 8d39495..919edc3 100644
--- a/CodexBarTests/AppServerEventStorageTests.swift
+++ b/CodexBarTests/History/AppServerEventStorageTests.swift
@@ -89,7 +89,7 @@ struct AppServerEventStorageTests {
let store = TokenHistoryStore(directoryURL: directory.url)
var turn = token()
turn.rebuiltAt = now
- try await store.record([turn], now: now)
+ try await directory.seedTokenSnapshots([turn], now: now)
let data = try AppServerEventRecord(token: turn, recordedAt: now).jsonLineData()
let record = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
#expect(Set(record.keys) == ["version", "kind", "recordedAt", "token"])
@@ -110,8 +110,8 @@ struct AppServerEventStorageTests {
@Test func unsupportedVersionAndMixedPayloadAreRejected() throws {
let valid = try #require(String(bytes: AppServerEventRecord(token: token(), recordedAt: now).jsonLineData(), encoding: .utf8))
- let future = valid.replacingOccurrences(of: "\"version\":2", with: "\"version\":99")
- let mixed = valid.replacingOccurrences(of: "\"version\":2", with: "\"version\":2,\"activityPayload\":{}")
+ let future = valid.replacingOccurrences(of: "\"version\":1", with: "\"version\":99")
+ let mixed = valid.replacingOccurrences(of: "\"version\":1", with: "\"version\":1,\"activityPayload\":{}")
for text in [future, mixed] {
#expect(throws: (any Error).self) { try AppServerEventRecord.decode(from: Data(text.utf8)) }
}
@@ -121,12 +121,12 @@ struct AppServerEventStorageTests {
let directory = try TestDirectory()
defer { try? directory.remove() }
let first = TokenHistoryStore(directoryURL: directory.url)
- let second = TokenHistoryStore(directoryURL: directory.url)
- try await first.record([token()], now: now)
- try await second.record([token()], now: now)
- #expect(try events(in: directory.url).count == 1)
+ try await directory.seedTokenSnapshots([token()], now: now)
+ try await directory.seedTokenSnapshots([token()], now: now)
+ #expect(try events(in: directory.url).count == 2)
+ #expect(try await first.refresh(now: now) == [token()])
let update = token(at: now.addingTimeInterval(1), input: 200)
- try await second.record([update], now: now)
+ try await directory.seedTokenSnapshots([update], now: now)
#expect(try await first.refresh(now: now).first?.usage == update.usage)
try FileManager.default.removeItem(at: directory.url.appendingPathComponent("Aggregates/tokens.json"))
let restarted = TokenHistoryStore(directoryURL: directory.url)
@@ -141,7 +141,7 @@ struct AppServerEventStorageTests {
defer { try? directory.remove() }
let store = TokenHistoryStore(directoryURL: directory.url)
let timestamp = now.addingTimeInterval(0.1234567)
- try await store.record([token(at: timestamp)], now: timestamp)
+ try await directory.seedTokenSnapshots([token(at: timestamp)], now: timestamp)
_ = try await store.rebuild(for: [HistoryStorage.dateKey(for: timestamp)], now: timestamp.addingTimeInterval(0.0000456))
let original = try await store.refresh(now: timestamp)
try FileManager.default.removeItem(at: directory.url.appendingPathComponent("Aggregates/tokens.json"))
@@ -191,7 +191,7 @@ struct AppServerEventStorageTests {
let directory = try TestDirectory()
defer { try? directory.remove() }
let store = TokenHistoryStore(directoryURL: directory.url)
- try await store.record([token()], now: now)
+ try await directory.seedTokenSnapshots([token()], now: now)
let url = HistoryStorage.eventLogURL(for: HistoryStorage.dateKey(for: now), in: HistoryStorage.eventsDirectoryURL(in: directory.url))
let seconds = Int(now.timeIntervalSince1970)
let firstTimes = [timespec(tv_sec: seconds, tv_nsec: 1000100), timespec(tv_sec: seconds, tv_nsec: 1000100)]
@@ -241,8 +241,8 @@ struct AppServerEventStorageTests {
let start = try #require(CodexDateFormat.dayDate(from: "2026-09-15")).addingTimeInterval(86390)
let next = start.addingTimeInterval(60)
let store = TokenHistoryStore(directoryURL: directory.url)
- try await store.record([token(at: start)], now: start)
- try await store.record([token(id: "child", at: next, input: 200)], now: next)
+ try await directory.seedTokenSnapshots([token(at: start)], now: start)
+ try await directory.seedTokenSnapshots([token(id: "child", at: next, input: 200)], now: next)
try FileManager.default.removeItem(at: directory.url.appendingPathComponent("Aggregates/tokens.json"))
let restored = try await store.refresh(now: next)
#expect(TokenTurn.dailyUsage(restored, now: next)["2026-09-15"]?.totalTokens == 320)
@@ -260,14 +260,14 @@ struct AppServerEventStorageTests {
approvalReviewer: nil, sessionID: "thread", turnID: "turn", agentID: nil, id: "tool"
)
try await recorder.record(event: event)
- try await store.record([token()], now: now)
+ try await directory.seedTokenSnapshots([token()], now: now)
let url = HistoryStorage.eventLogURL(for: HistoryStorage.dateKey(for: now), in: HistoryStorage.eventsDirectoryURL(in: directory.url))
let handle = try FileHandle(forWritingTo: url)
try handle.seekToEnd()
try handle.write(contentsOf: Data("{\"partial\":".utf8))
try handle.close()
let updated = token(at: now.addingTimeInterval(1), input: 300)
- try await store.record([updated], now: now)
+ try await directory.seedTokenSnapshots([updated], now: now)
try await recorder.record(event: event)
let entries = try events(in: directory.url)
#expect(entries.compactMap(\.activity).count == 1)
diff --git a/CodexBarTests/HistoryAggregationTests.swift b/CodexBarTests/History/HistoryAggregationTests.swift
similarity index 85%
rename from CodexBarTests/HistoryAggregationTests.swift
rename to CodexBarTests/History/HistoryAggregationTests.swift
index dd684c0..5e7f01f 100644
--- a/CodexBarTests/HistoryAggregationTests.swift
+++ b/CodexBarTests/History/HistoryAggregationTests.swift
@@ -3,27 +3,47 @@ import Foundation
import Testing
struct HistoryAggregationTests {
- @Test func syncStateIsIsolatedByApplicationRoot() async throws {
+ @Test func aggregateJSONLinesPreserveSlashesAndStableBytes() throws {
+ var first = TestFixtures.aggregate()
+ first.projectCounts = ["/projects/a": 1, "/projects/z": 2]
+ first.modelCounts = ["model/name": 3]
+ var second = first
+ second.projectCounts = Dictionary(uniqueKeysWithValues: first.projectCounts.sorted { $0.key > $1.key })
+ let local = try first.jsonLineData()
+ let synced = try first.syncedAggregate.jsonLineData()
+ #expect(try local == (second.jsonLineData()))
+ #expect(try synced == (second.syncedAggregate.jsonLineData()))
+ for data in [local, synced] {
+ let text = try #require(String(bytes: data, encoding: .utf8))
+ #expect(text.contains("/projects/a"))
+ #expect(text.contains("model/name"))
+ #expect(!text.contains(#"\/"#))
+ #expect(data.last == JSONLines.newlineByte)
+ #expect(data.filter { $0 == JSONLines.newlineByte }.count == 1)
+ }
+ #expect(try JSONLines.decoder.decode(ActivityAggregate.self, from: local) == first)
+ #expect(try JSONLines.decoder.decode(SyncedActivity.self, from: synced) == first.syncedAggregate)
+ }
+
+ @Test func syncStateIsIsolatedByApplicationRoot() throws {
let directory = try TestDirectory()
defer { try? directory.remove() }
- let debugRoot = directory.url.appendingPathComponent("CodexBar Debug", isDirectory: true)
- let releaseRoot = directory.url.appendingPathComponent("CodexBar", isDirectory: true)
- let debugSync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: debugRoot), isEnabled: { false })
- let releaseSync = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: releaseRoot), isEnabled: { false })
- try await releaseSync.markReplacementNeeded(for: ["2026-09-15"])
- #expect(await !debugSync.hasPendingReplacement(for: ["2026-09-15"]))
- try await debugSync.markReplacementNeeded(for: ["2026-10-05"])
- #expect(await !releaseSync.hasPendingReplacement(for: ["2026-10-05"]))
- let restored = SyncService(directoryURL: HistoryStorage.syncDirectoryURL(in: debugRoot), isEnabled: { false })
- #expect(await restored.hasPendingReplacement(for: ["2026-10-05"]))
- #expect(FileManager.default.fileExists(atPath: debugRoot.appendingPathComponent("Sync/Activity/cache.json").path))
- #expect(FileManager.default.fileExists(atPath: releaseRoot.appendingPathComponent("Sync/Activity/cache.json").path))
+ let debugRoot = directory.url.appendingPathComponent("CodexBar Data Debug", isDirectory: true)
+ let releaseRoot = directory.url.appendingPathComponent("CodexBar Data", isDirectory: true)
+ let debugStore = ActivitySyncStore(directoryURL: HistoryStorage.syncDirectoryURL(in: debugRoot))
+ let releaseStore = ActivitySyncStore(directoryURL: HistoryStorage.syncDirectoryURL(in: releaseRoot))
+ try releaseStore.saveState(SyncState(hashByDate: ["2026-09-15": "release"]))
+ #expect(debugStore.loadState().hashByDate.isEmpty)
+ try debugStore.saveState(SyncState(hashByDate: ["2026-10-05": "debug"]))
+ #expect(releaseStore.loadState().hashByDate["2026-10-05"] == nil)
+ let restored = ActivitySyncStore(directoryURL: HistoryStorage.syncDirectoryURL(in: debugRoot))
+ #expect(restored.loadState().hashByDate["2026-10-05"] == "debug")
#expect(SyncCloudKit.zoneName == "CodexBarAppZone")
let root = AppStorage.directoryURL()
#if DEBUG
- #expect(root.lastPathComponent == "CodexBar Debug")
+ #expect(root.lastPathComponent == "CodexBar Data Debug")
#else
- #expect(root.lastPathComponent == "CodexBar")
+ #expect(root.lastPathComponent == "CodexBar Data")
#endif
#expect(HistoryStorage.directoryURL() == root)
#expect(HistoryStorage.syncDirectoryURL() == root.appendingPathComponent("Sync", isDirectory: true))
diff --git a/CodexBarTests/HistoryMaintenanceTests.swift b/CodexBarTests/History/HistoryMaintenanceTests.swift
similarity index 98%
rename from CodexBarTests/HistoryMaintenanceTests.swift
rename to CodexBarTests/History/HistoryMaintenanceTests.swift
index de79774..9b3a98b 100644
--- a/CodexBarTests/HistoryMaintenanceTests.swift
+++ b/CodexBarTests/History/HistoryMaintenanceTests.swift
@@ -130,7 +130,7 @@ extension HistoryMaintenanceTests {
let days = try #require(root["days"] as? [String: [String: Any]])
let day = try #require(days[date])
#expect(Set(day.keys) == [
- "offset", "size", "corrupt", "generationID", "generationStartedEmpty",
+ "requiresCloudReplacement", "offset", "size", "corrupt", "generationID", "generationStartedEmpty",
"fileIdentifier", "boundaryHash"
])
#expect(try JSONDecoder().decode(HistoryMaintenanceState.self, from: data) == state)
diff --git a/CodexBarTests/JSONLinesAndActivityTests.swift b/CodexBarTests/History/JSONLinesAndActivityTests.swift
similarity index 89%
rename from CodexBarTests/JSONLinesAndActivityTests.swift
rename to CodexBarTests/History/JSONLinesAndActivityTests.swift
index 7c4749e..2f7f5b0 100644
--- a/CodexBarTests/JSONLinesAndActivityTests.swift
+++ b/CodexBarTests/History/JSONLinesAndActivityTests.swift
@@ -19,12 +19,6 @@ struct JSONLinesAndActivityTests {
#expect(result.failedLineCount == 2)
}
- @Test func leadingPartialLineIsDroppedAtByteBoundary() {
- #expect(JSONLines.droppingLeadingPartialLine(Data("partial\n1\n2\n".utf8)) == Data("1\n2\n".utf8))
- #expect(JSONLines.droppingLeadingPartialLine(Data("partial\n".utf8)).isEmpty)
- #expect(JSONLines.droppingLeadingPartialLine(Data("partial".utf8)) == Data("partial".utf8))
- }
-
@Test(arguments: ["PermissionRequest", "permission_request", "permission-request", "approval.requested"])
func eventAliasesAreNotAccepted(_ name: String) {
#expect(ActivityEventKind(eventName: name) == nil)
diff --git a/CodexBarTests/TokenHistoryTests.swift b/CodexBarTests/History/TokenHistoryTests.swift
similarity index 72%
rename from CodexBarTests/TokenHistoryTests.swift
rename to CodexBarTests/History/TokenHistoryTests.swift
index 19529c5..5a313e0 100644
--- a/CodexBarTests/TokenHistoryTests.swift
+++ b/CodexBarTests/History/TokenHistoryTests.swift
@@ -346,7 +346,7 @@ extension TokenHistoryTests {
var bad = try #require(try await store.recordObservations([first], now: TestFixtures.now).first)
bad.startNewGeneration(at: TestFixtures.now)
bad.usage = observation(sequence: 1, previous: 0, current: 900).current
- try await store.record([bad], now: TestFixtures.now)
+ try await directory.seedTokenSnapshots([bad], now: TestFixtures.now)
_ = try await store.rebuild(for: [day], now: TestFixtures.now)
let restored = try #require(try await store.currentTurns(now: TestFixtures.now).first)
#expect(restored.usage?.totalTokens == 100)
@@ -354,8 +354,10 @@ extension TokenHistoryTests {
let second = observation(sequence: 2, previous: 1100, current: 1120)
var remote = try second.applying(to: restored)
remote.startNewGeneration(at: TestFixtures.now)
- try await store.record([remote], now: TestFixtures.now)
- await #expect(throws: TokenCacheError.self) { try await store.rebuild(for: [day], now: TestFixtures.now) }
+ try await directory.seedTokenSnapshots([remote], now: TestFixtures.now)
+ let failed = try await store.rebuild(for: [day], now: TestFixtures.now)
+ #expect(failed.failedDateKeys == [day])
+ #expect(failed.turnCount == 0)
#expect(try await store.currentTurns(now: TestFixtures.now).first == remote)
}
@@ -401,3 +403,136 @@ extension TokenHistoryTests {
#expect(merged.merging(correction) == merged)
}
}
+
+extension TokenHistoryTests {
+ private func rebuildObservation(
+ _ name: String, root: String? = nil, start: Date = TestFixtures.now,
+ sequence: Int64 = 1, previous: Int64 = 0, current: Int64 = 10
+ ) -> TokenObservation {
+ let id = TokenTurn.identifier(thread: name, turn: "rebuild")
+ let rootID = TokenTurn.identifier(thread: root ?? name, turn: "rebuild")
+ let counts = observation(sequence: sequence, previous: previous, current: current)
+ return TokenObservation(
+ turn: TokenTurn(id: id, rootID: rootID, startedAt: start, updatedAt: TestFixtures.now),
+ rootStartedAt: start, streamID: name, sequence: sequence, previous: counts.previous, current: counts.current
+ )
+ }
+
+ private func writeJournal(_ observations: [TokenObservation], in directory: TestDirectory, at date: Date = TestFixtures.now) throws {
+ let data = try observations.reduce(into: Data()) { result, observation in
+ try result.append(AppServerEventRecord(observation: observation, recordedAt: date).jsonLineData())
+ }
+ _ = try directory.write(data, to: "Events/\(HistoryStorage.dateKey(for: date)).jsonl")
+ }
+
+ @Test func unselectedIncompleteRootDoesNotBlockRebuildOrSubsequentCacheLoad() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let selected = rebuildObservation("selected")
+ let unselected = rebuildObservation("other", start: TestFixtures.now.addingTimeInterval(-86400), sequence: 2, previous: 10, current: 20)
+ try writeJournal([selected, unselected], in: directory)
+ let store = TokenHistoryStore(directoryURL: directory.url)
+ let result = try await store.rebuild(for: [day], now: TestFixtures.now)
+ #expect(result.failedDateKeys.isEmpty)
+ #expect(result.turnCount == 1)
+ let expected = try #require(result.turns?.first { $0.id == selected.turn.id })
+ #expect(expected.usage?.totalTokens == 10)
+ let restarted = TokenHistoryStore(directoryURL: directory.url)
+ let loaded = try await restarted.refresh(now: TestFixtures.now)
+ #expect(loaded == [expected])
+ let cache = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: directory.url.appendingPathComponent("Aggregates/tokens.json"))) as? [String: Any])
+ #expect((cache["files"] as? [String: Any])?.isEmpty == true)
+ }
+
+ @Test func failedRootPreservesOldResultWhileSameDayHealthyRootIsRebuilt() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let store = TokenHistoryStore(directoryURL: directory.url)
+ let previous = rebuildObservation("bad")
+ let old = try #require(try await store.recordObservations([previous], now: TestFixtures.now).first)
+ let good = rebuildObservation("good")
+ let broken = rebuildObservation("bad", sequence: 3, previous: 20, current: 30)
+ try writeJournal([good, broken], in: directory)
+ let result = try await store.rebuild(for: [day], now: TestFixtures.now)
+ #expect(result.failedDateKeys == [day])
+ #expect(result.turnCount == 1)
+ #expect(result.turns?.first { $0.id == old.id } == old)
+ let rebuilt = try #require(result.turns?.first { $0.id == good.turn.id })
+ #expect(rebuilt.generationID != "initial")
+ let reopened = TokenHistoryStore(directoryURL: directory.url)
+ let loaded = try await reopened.refresh(now: TestFixtures.now)
+ #expect(loaded.first { $0.id == old.id } == old)
+ #expect(loaded.first { $0.id == rebuilt.id } == rebuilt)
+ }
+
+ @Test func rebuildIncludesChildObservationsWrittenOnAnotherDay() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let root = rebuildObservation("root")
+ let child = rebuildObservation("child", root: "root", current: 20)
+ try writeJournal([root], in: directory)
+ try writeJournal([child], in: directory, at: TestFixtures.now.addingTimeInterval(86400))
+ let store = TokenHistoryStore(directoryURL: directory.url)
+ let result = try await store.rebuild(for: [day], now: TestFixtures.now.addingTimeInterval(86400))
+ #expect(result.failedDateKeys.isEmpty)
+ #expect(result.turnCount == 2)
+ #expect(TokenTurn.dailyUsage(result.turns ?? [], now: TestFixtures.now.addingTimeInterval(86400))[day]?.totalTokens == 30)
+ }
+
+ @Test func missingCachedChildPreventsReplacingItsWholeRoot() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let store = TokenHistoryStore(directoryURL: directory.url)
+ let root = rebuildObservation("root")
+ let child = rebuildObservation("child", root: "root")
+ let before = try await store.recordObservations([root, child], now: TestFixtures.now)
+ try writeJournal([root], in: directory)
+ let result = try await store.rebuild(for: [day], now: TestFixtures.now)
+ #expect(result.failedDateKeys == [day])
+ #expect(result.turnCount == 0)
+ #expect(Set(result.turns?.map(\.generationID) ?? []) == Set(before.map(\.generationID)))
+ #expect(result.turns?.first { $0.id == child.turn.id } == before.first { $0.id == child.turn.id })
+ }
+
+ @Test func failedRootRollsBackAcrossFilesAndRetainsCursorsUntilRepair() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let first = rebuildObservation("root")
+ let second = rebuildObservation("root", sequence: 2, previous: 10, current: 20)
+ let third = rebuildObservation("root", sequence: 3, previous: 20, current: 30)
+ let fourth = rebuildObservation("root", sequence: 4, previous: 30, current: 40)
+ let store = TokenHistoryStore(directoryURL: directory.url)
+ let before = try #require(try await store.recordObservations([first], now: TestFixtures.now).first)
+ try writeJournal([first, second], in: directory)
+ let nextDay = TestFixtures.now.addingTimeInterval(86400)
+ try writeJournal([fourth], in: directory, at: nextDay)
+ let partial = try await store.refresh(now: nextDay)
+ #expect(partial == [before])
+ let cacheURL = directory.url.appendingPathComponent("Aggregates/tokens.json")
+ let cache = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: cacheURL)) as? [String: Any])
+ #expect((cache["files"] as? [String: Any])?.isEmpty == true)
+ try writeJournal([third, fourth], in: directory, at: nextDay)
+ let restarted = TokenHistoryStore(directoryURL: directory.url)
+ let repaired = try await restarted.refresh(now: nextDay)
+ #expect(repaired.first?.usage?.totalTokens == 40)
+ #expect(try await restarted.refresh(now: nextDay) == repaired)
+ }
+
+ @Test func unattributedCorruptionAndConflictingOwnershipDoNotOverwriteLedger() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let store = TokenHistoryStore(directoryURL: directory.url)
+ let first = rebuildObservation("root")
+ _ = try await store.recordObservations([first], now: TestFixtures.now)
+ let cacheURL = directory.url.appendingPathComponent("Aggregates/tokens.json")
+ let before = try Data(contentsOf: cacheURL)
+ let eventURL = HistoryStorage.eventLogURL(for: day, in: HistoryStorage.eventsDirectoryURL(in: directory.url))
+ try Data("broken record\n".utf8).write(to: eventURL)
+ await #expect(throws: TokenCacheError.self) { try await store.rebuild(for: [day], now: TestFixtures.now) }
+ #expect(try Data(contentsOf: cacheURL) == before)
+ let ambiguous = rebuildObservation("root", root: "different")
+ try writeJournal([first, ambiguous], in: directory)
+ await #expect(throws: TokenCacheError.self) { try await store.rebuild(for: [day], now: TestFixtures.now) }
+ #expect(try Data(contentsOf: cacheURL) == before)
+ }
+}
diff --git a/CodexBarTests/HelperStatusMonitorTests.swift b/CodexBarTests/KeepAlive/HelperStatusMonitorTests.swift
similarity index 100%
rename from CodexBarTests/HelperStatusMonitorTests.swift
rename to CodexBarTests/KeepAlive/HelperStatusMonitorTests.swift
diff --git a/CodexBarTests/Presentation/ActivityPresentationTests.swift b/CodexBarTests/Presentation/ActivityPresentationTests.swift
new file mode 100644
index 0000000..085da27
--- /dev/null
+++ b/CodexBarTests/Presentation/ActivityPresentationTests.swift
@@ -0,0 +1,57 @@
+import Combine
+import Foundation
+import Testing
+
+struct ActivityPresentationTests {
+ @Test(arguments: [false, true], ["unavailable", "bootstrap", "stop"])
+ func clearingActivityAlsoClearsGlow(waiting: Bool, reason: String) throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let preferences = try TestPreferences()
+ defer { preferences.remove() }
+ let monitor = ActivityMonitor(
+ protectionSettings: ProtectionSettings(defaults: preferences.defaults),
+ protectionStore: ProtectionStore(directoryURL: directory.url),
+ activityDirectoryURL: directory.url
+ )
+ monitor.isStarted = true
+ monitor.isActivitySourceHealthy = true
+ defer { monitor.stop() }
+ var updates: [ActivityPresentationUpdate] = []
+ var glow = TaskGlowPresentationState()
+ let now = Date()
+ let subscription = monitor.presentationPublisher.sink { update in
+ updates.append(update)
+ glow.update(snapshot: update.snapshot, terminalEvents: update.terminalEvents, isEnabled: true, acceptsBriefEvents: true, now: now)
+ glow.refresh(now: now, terminalDuration: 10)
+ }
+ defer { subscription.cancel() }
+ monitor.consume(.live([TestFixtures.event(at: now)]))
+ if waiting {
+ monitor.consume(.live([TestFixtures.event(.approvalRequested, at: now.addingTimeInterval(1))]))
+ }
+ #expect(glow.state == (waiting ? .waiting : .running))
+ #expect(monitor.snapshot.activeCount == 1)
+
+ switch reason {
+ case "unavailable": monitor.consume(.sourceUnavailable)
+ case "bootstrap": monitor.consume(.bootstrapStart)
+ default: monitor.stop()
+ }
+ #expect(monitor.snapshot == .empty)
+ #expect(updates.last?.snapshot == .empty)
+ #expect(updates.last?.terminalEvents.isEmpty == true)
+ #expect(glow.state == .hidden)
+
+ if reason == "unavailable" {
+ let count = updates.count
+ monitor.consume(.sourceUnavailable)
+ #expect(updates.count == count)
+ monitor.isActivitySourceHealthy = true
+ monitor.consume(.live([TestFixtures.event(at: now.addingTimeInterval(2), session: "restored")]))
+ #expect(updates.last?.snapshot == monitor.snapshot)
+ #expect(updates.last?.terminalEvents.isEmpty == true)
+ #expect(glow.state != .hidden)
+ }
+ }
+}
diff --git a/CodexBarTests/DateAndPresentationTests.swift b/CodexBarTests/Presentation/DateAndPresentationTests.swift
similarity index 80%
rename from CodexBarTests/DateAndPresentationTests.swift
rename to CodexBarTests/Presentation/DateAndPresentationTests.swift
index 997cd66..ef3cf9e 100644
--- a/CodexBarTests/DateAndPresentationTests.swift
+++ b/CodexBarTests/Presentation/DateAndPresentationTests.swift
@@ -66,4 +66,19 @@ struct DateAndPresentationTests {
showsPreciseDuration: !isAnonymous, activeSubagentCount: nil
)
}
+
+ @Test(arguments: [false, true])
+ func accountFailureKeepsLiveTaskIconAndExplainsBothStates(waiting: Bool) {
+ let task = task(isAnonymous: false)
+ let activity = ActivitySnapshot(
+ waitingTasks: waiting ? [task] : [], runningTasks: waiting ? [] : [task],
+ recentCompletions: [], recentTerminations: []
+ )
+ let state = StatusIconState(usesErrorImage: true, ordinaryUsageAllowed: nil, progress: nil, activity: activity)
+ #expect(state.symbolName(at: TestFixtures.now) == (waiting ? "person.badge.key.fill" : "person.badge.clock.fill"))
+ #expect(state.hasLiveDuration)
+ #expect(state.toolTip(at: TestFixtures.now)?.contains(String(localized: "codex-status.account.unavailable")) == true)
+ let idle = StatusIconState(usesErrorImage: true, ordinaryUsageAllowed: nil, progress: nil, activity: .empty)
+ #expect(idle.symbolName(at: TestFixtures.now) == "person.slash.fill")
+ }
}
diff --git a/CodexBarTests/SettingsTests.swift b/CodexBarTests/Presentation/SettingsTests.swift
similarity index 100%
rename from CodexBarTests/SettingsTests.swift
rename to CodexBarTests/Presentation/SettingsTests.swift
diff --git a/CodexBarTests/TaskGlowPreviewTests.swift b/CodexBarTests/Presentation/TaskGlowPreviewTests.swift
similarity index 100%
rename from CodexBarTests/TaskGlowPreviewTests.swift
rename to CodexBarTests/Presentation/TaskGlowPreviewTests.swift
diff --git a/CodexBarTests/TaskGlowTests.swift b/CodexBarTests/Presentation/TaskGlowTests.swift
similarity index 100%
rename from CodexBarTests/TaskGlowTests.swift
rename to CodexBarTests/Presentation/TaskGlowTests.swift
diff --git a/CodexBarTests/BoundedProcessTests.swift b/CodexBarTests/Support/BoundedProcessTests.swift
similarity index 100%
rename from CodexBarTests/BoundedProcessTests.swift
rename to CodexBarTests/Support/BoundedProcessTests.swift
diff --git a/CodexBarTests/RefreshTaskCoordinatorTests.swift b/CodexBarTests/Support/RefreshTaskCoordinatorTests.swift
similarity index 100%
rename from CodexBarTests/RefreshTaskCoordinatorTests.swift
rename to CodexBarTests/Support/RefreshTaskCoordinatorTests.swift
diff --git a/CodexBarTests/TestSupport.swift b/CodexBarTests/Support/TestSupport.swift
similarity index 88%
rename from CodexBarTests/TestSupport.swift
rename to CodexBarTests/Support/TestSupport.swift
index 5a4e54d..b6b2943 100644
--- a/CodexBarTests/TestSupport.swift
+++ b/CodexBarTests/Support/TestSupport.swift
@@ -60,6 +60,16 @@ nonisolated struct TestDirectory {
try write(Data(text.utf8), to: relativePath)
}
+ func seedTokenSnapshots(_ turns: [TokenTurn], now: Date) async throws {
+ try HistoryStorage.withExclusiveLock(in: url) {
+ var journal = AppServerEventJournal()
+ for turn in turns {
+ try journal.append(AppServerEventRecord(token: turn, recordedAt: now), in: url)
+ }
+ }
+ _ = try await TokenHistoryStore(directoryURL: url).refresh(now: now)
+ }
+
func remove() throws {
try FileManager.default.removeItem(at: url)
}
diff --git a/CodexBarTests/Sync/SyncAvailabilityTests.swift b/CodexBarTests/Sync/SyncAvailabilityTests.swift
new file mode 100644
index 0000000..907f799
--- /dev/null
+++ b/CodexBarTests/Sync/SyncAvailabilityTests.swift
@@ -0,0 +1,78 @@
+import Combine
+import Foundation
+import Testing
+
+struct SyncAvailabilityTests {
+ @Test func maintenanceRecoversAvailabilityWithoutOpeningSettings() async throws {
+ let preferences = try TestPreferences()
+ defer { preferences.remove() }
+ preferences.defaults.set(true, forKey: "Sync.isEnabled")
+ var queries = 0
+ let settings = SyncSettings(defaults: preferences.defaults, queryAvailability: {
+ queries += 1
+ return queries == 1 ? .unavailable(.networkUnavailable) : .available
+ }, loadLastUpload: { nil })
+ var synchronizations = 0
+ let scheduler = SyncScheduler(syncActivation: { settings.activation() }, maintenance: { synchronizes, _ in
+ if synchronizes {
+ synchronizations += 1
+ }
+ return nil
+ }, rebuild: { _, _ in throw CancellationError() })
+ defer { scheduler.cancel() }
+ let subscription = settings.$syncAvailability
+ .removeDuplicates()
+ .receive(on: DispatchQueue.main)
+ .sink { availability in
+ guard availability == settings.syncAvailability else { return }
+ scheduler.requestSync(trigger: .settings)
+ }
+ defer { subscription.cancel() }
+ try await waitUntil { settings.syncAvailability == .unavailable }
+ let now = Date()
+ settings.refreshAvailabilityIfNeeded(now: now.addingTimeInterval(30))
+ scheduler.requestMaintenance(allowsSync: true, trigger: .auto)
+ #expect(queries == 1)
+ #expect(synchronizations == 0)
+
+ settings.refreshAvailabilityIfNeeded(now: now.addingTimeInterval(61))
+ try await waitUntil { synchronizations == 1 }
+ #expect(queries == 2)
+ #expect(settings.isEffectivelyActive)
+ settings.refreshAvailabilityIfNeeded(now: now.addingTimeInterval(180))
+ #expect(queries == 2)
+ }
+
+ @Test func availabilityRequestsCoalesceAndDisablingIgnoresLateResults() async throws {
+ let preferences = try TestPreferences()
+ defer { preferences.remove() }
+ preferences.defaults.set(true, forKey: "Sync.isEnabled")
+ var queries = 0
+ var pending: CheckedContinuation<SyncAvailabilityResult, Never>?
+ let settings = SyncSettings(defaults: preferences.defaults, queryAvailability: {
+ queries += 1
+ return await withCheckedContinuation { pending = $0 }
+ }, loadLastUpload: { nil })
+ try await waitUntil { pending != nil }
+ settings.refresh()
+ settings.refreshAvailabilityIfNeeded(now: Date().addingTimeInterval(120))
+ #expect(queries == 1)
+ #expect(settings.setEnabled(false))
+ pending?.resume(returning: .available)
+ pending = nil
+ for _ in 0 ..< 10 {
+ await Task.yield()
+ }
+ #expect(settings.syncAvailability == .unknown)
+ #expect(settings.activation() == .syncOff)
+ settings.refreshAvailabilityIfNeeded(now: Date().addingTimeInterval(240))
+ #expect(queries == 1)
+ }
+
+ private func waitUntil(_ condition: () -> Bool) async throws {
+ for _ in 0 ..< 200 where !condition() {
+ try await Task.sleep(for: .milliseconds(5))
+ }
+ try #require(condition())
+ }
+}
diff --git a/CodexBarTests/SyncRecoveryTests.swift b/CodexBarTests/Sync/SyncRecoveryTests.swift
similarity index 52%
rename from CodexBarTests/SyncRecoveryTests.swift
rename to CodexBarTests/Sync/SyncRecoveryTests.swift
index 141b3c3..c8114f5 100644
--- a/CodexBarTests/SyncRecoveryTests.swift
+++ b/CodexBarTests/Sync/SyncRecoveryTests.swift
@@ -1,8 +1,43 @@
import CloudKit
+import CryptoKit
import Foundation
import Testing
struct SyncRecoveryTests {
+ @Test func previousEncodingHashConvergesWithoutRepeatedUploads() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let database = SyncDatabaseFixture()
+ let date = HistoryStorage.dateKey(for: Date())
+ let local = try TestFixtures.decode(ActivityAggregate.self, """
+ {"date":"\(date)","generationID":"source","eventCount":1}
+ """)
+ let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })
+ _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)
+ let store = ActivitySyncStore(directoryURL: directory.url)
+ var state = store.loadState()
+ let currentHash = try #require(state.hashByDate[date])
+ let previousBytes = Data(("""
+ {"date":"\(date)","generationID":"source","eventCount":1,"sessionCount":null,"turnCount":null,"projectCounts":{},"modelCounts":{}}
+ """ + "\n").utf8)
+ let previousHash = TokenTurn.hexString(SHA256.hash(data: previousBytes))
+ #expect(previousHash != currentHash)
+ state.hashByDate[date] = previousHash
+ try store.saveState(state)
+
+ let restarted = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })
+ _ = await restarted.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)
+ #expect(store.loadState().hashByDate[date] == currentHash)
+ #expect(await database.activityRecords().count == 1)
+ #expect(await database.activityRecords().first?["eventCount"] as? Int == 1)
+ #expect(await database.deletedIDs.isEmpty)
+ let writes = await database.savedTypes.count
+ let reads = await database.requestedIDs.filter { $0.recordName != "accountSalt" }.count
+ _ = await restarted.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)
+ #expect(await database.savedTypes.count == writes)
+ #expect(await database.requestedIDs.filter { $0.recordName != "accountSalt" }.count == reads)
+ }
+
private static let zone = CKRecordZone.ID(zoneName: SyncCloudKit.zoneName, ownerName: CKCurrentUserDefaultName)
private static let salt = Data(repeating: 1, count: 32)
@@ -139,7 +174,7 @@ struct SyncRecoveryTests {
json["cursor"] = Data("previous cursor".utf8).base64EncodedString()
try JSONSerialization.data(withJSONObject: json).write(to: url)
var updated = state
- updated.replacementDates = ["2026-10-05"]
+ updated.lastPrunedDate = "2026-10-05"
try store.saveState(updated)
#expect(try store.load().cursor == Data("previous cursor".utf8))
let daily = SyncedActivity(date: "2026-10-05", generationID: "source", eventCount: 2, projectCounts: [:], modelCounts: [:])
@@ -236,12 +271,11 @@ struct SyncRecoveryTests {
local.eventCount = 5
_ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)
let before = await database.activityRecords().map(\.recordID)
- try await service.markReplacementNeeded(for: [local.date])
local.generationID = nil
- _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)
+ let result = await service.synchronizeIfEnabled(localAggregates: [local], replacements: [local], trigger: .manual)
#expect(await database.deletedIDs.isEmpty)
#expect(await database.activityRecords().map(\.recordID) == before)
- #expect(await service.hasPendingReplacement(for: [local.date]))
+ #expect(result.completedReplacements.isEmpty)
}
@Test func invalidGenerationDuringCursorBaselineStopsActivityUpload() async throws {
@@ -275,13 +309,12 @@ struct SyncRecoveryTests {
#expect(previous.count == 2)
local.generationID = "rebuilt"
local.generationStartedEmpty = false
- try await service.markReplacementNeeded(for: [local.date])
- _ = await service.synchronizeIfEnabled(localAggregates: [local], trigger: .manual)
+ let result = await service.synchronizeIfEnabled(localAggregates: [local], replacements: [local], trigger: .manual)
let current = await database.activityRecords()
#expect(current.count == 1)
#expect(current.first?["generationID"] as? String == "rebuilt")
#expect(await previous.isSubset(of: Set(database.deletedIDs)))
- #expect(await !service.hasPendingReplacement(for: [local.date]))
+ #expect(result.completedReplacements == [local.date: "rebuilt"])
}
private static func cachedTurnCount(in directory: URL) throws -> Int {
@@ -303,18 +336,36 @@ private actor SyncDatabaseFixture: SyncDatabase {
private let changesFail: Bool
private var changesRecordFails = false
private var failingName: String?
- private let failingDate: String?
+ private var failingDate: String?
private let readFailure: Bool
private(set) var queryCount = 0
private(set) var savedTypes: [String] = []
private(set) var requestedIDs: [CKRecord.ID] = []
private(set) var deletedIDs: [CKRecord.ID] = []
private var changesRecord: CKRecord?
+ private var deletionFails = false
+ private var activitySaveCallback: (@Sendable () -> Void)?
+
+ func failNextDeletion() {
+ deletionFails = true
+ }
+
+ func failActivityUpload(on date: String) {
+ failingDate = date
+ }
+
+ func afterActivitySave(_ callback: @escaping @Sendable () -> Void) {
+ activitySaveCallback = callback
+ }
func activityRecords() -> [CKRecord] {
stored.values.filter { $0.recordType == "Activity" }.map(Self.copy)
}
+ func storeRecord(_ record: CKRecord) {
+ stored[record.recordID] = Self.copy(record)
+ }
+
func injectChangesRecord(_ record: CKRecord) {
changesRecord = Self.copy(record)
}
@@ -337,6 +388,8 @@ private actor SyncDatabaseFixture: SyncDatabase {
func repair() {
failingName = nil
+ failingDate = nil
+ activitySaveCallback = nil
}
func records(for ids: [CKRecord.ID], desiredKeys _: [CKRecord.FieldKey]?) async throws -> Records {
@@ -358,11 +411,18 @@ private actor SyncDatabaseFixture: SyncDatabase {
stored[record.recordID] = record.copy() as? CKRecord
saved[record.recordID] = .success(record)
savedTypes.append(record.recordType)
+ if record.recordType == "Activity" {
+ activitySaveCallback?()
+ }
}
}
deletedIDs.append(contentsOf: ids)
for id in ids {
stored[id] = nil
+ if deletionFails {
+ deletionFails = false
+ throw CKError(.networkFailure)
+ }
}
return (saved, Dictionary(uniqueKeysWithValues: ids.map { ($0, .success(())) }))
}
@@ -401,3 +461,269 @@ private actor SyncDatabaseFixture: SyncDatabase {
return SyncChanges(records: records, deletions: [], token: nil, moreComing: false)
}
}
+
+extension SyncRecoveryTests {
+ @Test func failedRebuildPreservesCloudUntilSuccessfulRetryAfterRestart() async throws {
+ let fixture = try await HistoryRebuildFixture()
+ defer { try? fixture.directory.remove() }
+ try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: fixture.eventURL.path)
+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: fixture.eventURL.path) }
+ await #expect(throws: (any Error).self) {
+ try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)
+ }
+ #expect(await fixture.history.hasPendingReplacement(for: [fixture.date]))
+ let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: fixture.sync)
+ _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)
+ #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 9)
+ #expect(await fixture.database.deletedIDs.isEmpty)
+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: fixture.eventURL.path)
+ _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)
+ #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 1)
+ #expect(await !restarted.hasPendingReplacement(for: [fixture.date]))
+ }
+
+ @Test func zeroRebuildSurvivesRestartAndClearsOldCloudContribution() async throws {
+ let fixture = try await HistoryRebuildFixture()
+ defer { try? fixture.directory.remove() }
+ let now = Date()
+ let id = TokenTurn.identifier(thread: "zero", turn: "zero")
+ let token = TokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: .zero)
+ try AppServerEventRecord(token: token, recordedAt: now).jsonLineData().write(to: fixture.eventURL)
+ let outcome = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)
+ #expect(outcome.summary.eventCount == 0)
+ #expect(outcome.summary.isSyncReplacementPending)
+ let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: fixture.sync)
+ _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)
+ #expect(await fixture.database.activityRecords().count == 1)
+ #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 0)
+ #expect(await !restarted.hasPendingReplacement(for: [fixture.date]))
+ let snapshot = await restarted.loadSnapshot(synchronize: true)
+ #expect(snapshot.dailyMetrics.isEmpty)
+ }
+
+ @Test func ordinaryTokenOnlyDateDoesNotUploadActivity() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let database = SyncDatabaseFixture()
+ let sync = SyncService(database: database, directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { true })
+ let tokens = TokenHistoryStore(directoryURL: directory.url)
+ let now = Date()
+ let id = TokenTurn.identifier(thread: "only", turn: "tokens")
+ try await directory.seedTokenSnapshots([TokenTurn(id: id, rootID: id, startedAt: now, updatedAt: now, usage: .zero)], now: now)
+ let history = HistoryService(directoryURL: directory.url, syncService: sync, tokenHistory: tokens)
+ _ = await history.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)
+ #expect(await database.activityRecords().isEmpty)
+ #expect(await database.deletedIDs.isEmpty)
+ }
+
+ @Test func uncommittedAggregateCannotAuthorizeCloudReplacement() async throws {
+ let fixture = try await HistoryRebuildFixture()
+ defer { try? fixture.directory.remove() }
+ var state = HistoryStorage.loadMaintenanceState(in: fixture.directory.url)
+ state.startNewGeneration(for: fixture.date, startedEmpty: false, fileIdentifier: state.days[fixture.date]?.fileIdentifier)
+ state.days[fixture.date]?.requiresCloudReplacement = true
+ try HistoryStorage.saveMaintenanceState(state, in: fixture.directory.url)
+ var aggregate = fixture.local
+ aggregate.generationID = state.days[fixture.date]?.generationID
+ aggregate.eventCount = 0
+ try ActivityAggregate.encodeJSONLines([aggregate]).write(to: HistoryStorage.dailyURL(in: fixture.directory.url))
+ let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: fixture.sync)
+ _ = await restarted.loadSnapshot(synchronize: true)
+ #expect(await fixture.database.deletedIDs.isEmpty)
+ #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 9)
+ _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)
+ #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 1)
+ #expect(await !restarted.hasPendingReplacement(for: [fixture.date]))
+ }
+
+ @Test func requestSaveFailureDoesNotModifyAggregateOrCloud() async throws {
+ let fixture = try await HistoryRebuildFixture()
+ defer { try? fixture.directory.remove() }
+ let aggregateURL = HistoryStorage.dailyURL(in: fixture.directory.url)
+ let original = try Data(contentsOf: aggregateURL)
+ let stateDirectory = HistoryStorage.maintenanceURL(in: fixture.directory.url).deletingLastPathComponent()
+ try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: stateDirectory.path)
+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: stateDirectory.path) }
+ await #expect(throws: (any Error).self) {
+ try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)
+ }
+ #expect(try Data(contentsOf: aggregateURL) == original)
+ #expect(await !fixture.history.hasPendingReplacement(for: [fixture.date]))
+ #expect(await fixture.database.deletedIDs.isEmpty)
+ }
+
+ @Test(arguments: ["delete", "upload", "acknowledge"])
+ func interruptedReplacementRetriesAfterRestart(_ stage: String) async throws {
+ let fixture = try await HistoryRebuildFixture()
+ defer { try? fixture.directory.remove() }
+ _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)
+ let stateDirectory = HistoryStorage.maintenanceURL(in: fixture.directory.url).deletingLastPathComponent()
+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: stateDirectory.path) }
+ switch stage {
+ case "delete": await fixture.database.failNextDeletion()
+ case "upload": await fixture.database.failActivityUpload(on: fixture.date)
+ default:
+ await fixture.database.afterActivitySave {
+ try? FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: stateDirectory.path)
+ }
+ }
+ _ = await fixture.history.loadSnapshot(synchronize: true)
+ #expect(await fixture.history.hasPendingReplacement(for: [fixture.date]))
+ await fixture.database.repair()
+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: stateDirectory.path)
+ let sync = SyncService(database: fixture.database, directoryURL: HistoryStorage.syncDirectoryURL(in: fixture.directory.url), isEnabled: { true })
+ let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: sync)
+ _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)
+ #expect(await !restarted.hasPendingReplacement(for: [fixture.date]))
+ #expect(await fixture.database.activityRecords().count == 1)
+ #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 1)
+ }
+
+ @Test func staleAcknowledgementCannotClearNewRebuildRequest() async throws {
+ let fixture = try await HistoryRebuildFixture()
+ defer { try? fixture.directory.remove() }
+ _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)
+ let old = try #require(HistoryStorage.loadMaintenanceState(in: fixture.directory.url).days[fixture.date]?.generationID)
+ _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)
+ await fixture.history.acknowledgeReplacements([fixture.date: old])
+ #expect(await fixture.history.hasPendingReplacement(for: [fixture.date]))
+ _ = await fixture.history.loadSnapshot(synchronize: true)
+ #expect(await !fixture.history.hasPendingReplacement(for: [fixture.date]))
+ }
+}
+
+private struct HistoryRebuildFixture {
+ let directory: TestDirectory
+ let database: SyncDatabaseFixture
+ let sync: SyncService
+ let history: HistoryService
+ let date: String
+ let eventURL: URL
+ let local: ActivityAggregate
+
+ init() async throws {
+ directory = try TestDirectory()
+ database = SyncDatabaseFixture()
+ sync = SyncService(database: database, directoryURL: HistoryStorage.syncDirectoryURL(in: directory.url), isEnabled: { true })
+ history = HistoryService(directoryURL: directory.url, syncService: sync)
+ let now = Date()
+ date = HistoryStorage.dateKey(for: now)
+ eventURL = try directory.write(AppServerEventRecord(activity: TestFixtures.event(at: now), recordedAt: now).jsonLineData(), to: "Events/\(date).jsonl")
+ _ = await history.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)
+ local = try #require(JSONLines.decode(ActivityAggregate.self, from: Data(contentsOf: HistoryStorage.dailyURL(in: directory.url))).first)
+ var remote = local
+ remote.eventCount = 9
+ remote.generationStartedEmpty = true
+ _ = await sync.synchronizeIfEnabled(localAggregates: [remote], trigger: .manual)
+ }
+}
+
+extension SyncRecoveryTests {
+ @Test func partialReplacementAcknowledgesHealthyDatesAndPreservesOtherDevices() async throws {
+ let fixture = try await HistoryRebuildFixture()
+ defer { try? fixture.directory.remove() }
+ let otherDate = HistoryStorage.dateKey(for: Date().addingTimeInterval(-86400))
+ let otherEvent = TestFixtures.event(at: Date().addingTimeInterval(-86400))
+ _ = try fixture.directory.write(AppServerEventRecord(activity: otherEvent).jsonLineData(), to: "Events/\(otherDate).jsonl")
+ let otherDevice = CKRecord(recordType: "Activity", recordID: CKRecord.ID(recordName: "other_\(fixture.date)_source", zoneID: Self.zone))
+ let contribution = SyncedActivity(date: fixture.date, generationID: "source", eventCount: 7, projectCounts: [:], modelCounts: [:])
+ ActivityRecordCodec.apply(contribution, deviceID: "other", to: otherDevice)
+ await fixture.database.storeRecord(otherDevice)
+ _ = try await fixture.history.rebuildData(for: [fixture.date, otherDate], synchronize: false)
+ await fixture.database.failActivityUpload(on: otherDate)
+ _ = await fixture.history.loadSnapshot(synchronize: true)
+ #expect(await !fixture.history.hasPendingReplacement(for: [fixture.date]))
+ #expect(await fixture.history.hasPendingReplacement(for: [otherDate]))
+ let records = await fixture.database.activityRecords()
+ #expect(records.first { $0["deviceID"] as? String == "other" }?["eventCount"] as? Int == 7)
+ #expect(await !fixture.database.deletedIDs.contains(otherDevice.recordID))
+ await fixture.database.repair()
+ _ = await fixture.history.loadSnapshot(synchronize: true)
+ #expect(await !fixture.history.hasPendingReplacement(for: [otherDate]))
+ }
+
+ @Test func disabledSyncKeepsRebuildRequestForNextEnabledService() async throws {
+ let fixture = try await HistoryRebuildFixture()
+ defer { try? fixture.directory.remove() }
+ let disabled = SyncService(database: fixture.database, directoryURL: HistoryStorage.syncDirectoryURL(in: fixture.directory.url), isEnabled: { false })
+ let history = HistoryService(directoryURL: fixture.directory.url, syncService: disabled)
+ _ = try await history.rebuildData(for: [fixture.date], synchronize: true)
+ #expect(await history.hasPendingReplacement(for: [fixture.date]))
+ #expect(await fixture.database.deletedIDs.isEmpty)
+ #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 9)
+ _ = await fixture.history.loadSnapshot(synchronize: true)
+ #expect(await !history.hasPendingReplacement(for: [fixture.date]))
+ #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 1)
+ }
+}
+
+extension SyncRecoveryTests {
+ @Test func appendedEventsKeepReplacementGenerationAndAreIncludedInRetry() async throws {
+ let fixture = try await HistoryRebuildFixture()
+ defer { try? fixture.directory.remove() }
+ _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)
+ let generation = HistoryStorage.loadMaintenanceState(in: fixture.directory.url).days[fixture.date]?.generationID
+ let recorder = ActivityRecorder(directoryURL: fixture.directory.url)
+ let event = ActivityRecord(
+ timestamp: Date(), name: ActivityEventKind.toolStarted.rawValue, origin: .main,
+ cwd: nil, tool: "exec_command", model: nil, effort: nil, approvalReviewer: nil,
+ sessionID: "session-a", turnID: "turn-a", agentID: nil, id: "appended-tool"
+ )
+ try await recorder.record(event: event)
+ _ = await fixture.history.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)
+ #expect(await !fixture.history.hasPendingReplacement(for: [fixture.date]))
+ let remote = try #require(await fixture.database.activityRecords().first)
+ #expect(remote["eventCount"] as? Int == 2)
+ #expect(remote["generationID"] as? String == generation)
+ }
+
+ @Test func partialTokenFailureIsReportedWithoutClaimingWholeDaySuccess() async throws {
+ let fixture = try await HistoryRebuildFixture()
+ defer { try? fixture.directory.remove() }
+ let now = Date()
+ let goodID = TokenTurn.identifier(thread: "good", turn: "summary")
+ let badID = TokenTurn.identifier(thread: "bad", turn: "summary")
+ let good = TokenObservation(
+ turn: TokenTurn(id: goodID, rootID: goodID, startedAt: now, updatedAt: now), rootStartedAt: now,
+ streamID: "good", sequence: 1, previous: .zero, current: .zero
+ )
+ let bad = TokenObservation(
+ turn: TokenTurn(id: badID, rootID: badID, startedAt: now, updatedAt: now), rootStartedAt: now,
+ streamID: "bad", sequence: 2, previous: .zero, current: .zero
+ )
+ let handle = try FileHandle(forWritingTo: fixture.eventURL)
+ try handle.seekToEnd()
+ try handle.write(contentsOf: AppServerEventRecord(observation: good, recordedAt: now).jsonLineData())
+ try handle.write(contentsOf: AppServerEventRecord(observation: bad, recordedAt: now).jsonLineData())
+ try handle.close()
+ let result = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)
+ #expect(result.summary.rebuiltDateCount == 0)
+ #expect(result.summary.eventCount == 1)
+ #expect(result.summary.tokenTurnCount == 1)
+ #expect(result.summary.failedTokenDateKeys == [fixture.date])
+ #expect(result.summary.didFailTokenRebuild)
+ #expect(result.summary.failedDateKeys.isEmpty)
+ #expect(result.summary.failedRequestDateKeys.isEmpty)
+ }
+}
+
+extension SyncRecoveryTests {
+ @Test func corruptJournalCannotBecomeAuthoritativeZeroDuringRebuildOrRetry() async throws {
+ let fixture = try await HistoryRebuildFixture()
+ defer { try? fixture.directory.remove() }
+ let original = try Data(contentsOf: fixture.eventURL)
+ try Data("broken event\n".utf8).write(to: fixture.eventURL)
+ await #expect(throws: (any Error).self) {
+ try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)
+ }
+ let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: fixture.sync)
+ _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)
+ #expect(await fixture.database.deletedIDs.isEmpty)
+ #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 9)
+ #expect(await restarted.hasPendingReplacement(for: [fixture.date]))
+ try original.write(to: fixture.eventURL)
+ _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)
+ #expect(await fixture.database.activityRecords().first?["eventCount"] as? Int == 1)
+ #expect(await !restarted.hasPendingReplacement(for: [fixture.date]))
+ }
+}
diff --git a/CodexBarTests/SyncSchedulerTests.swift b/CodexBarTests/Sync/SyncSchedulerTests.swift
similarity index 100%
rename from CodexBarTests/SyncSchedulerTests.swift
rename to CodexBarTests/Sync/SyncSchedulerTests.swift
diff --git a/CodexBarTests/ZoneRecoveryTests.swift b/CodexBarTests/Sync/ZoneRecoveryTests.swift
similarity index 100%
rename from CodexBarTests/ZoneRecoveryTests.swift
rename to CodexBarTests/Sync/ZoneRecoveryTests.swift