Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix: CloudKit fetch-then-save + proper quota backoff + per-record logging

libokaic0f2f8b09506
diff --git a/CodePulse-macOS/Services/CloudKitSync.swift b/CodePulse-macOS/Services/CloudKitSync.swift
index 8e6c6953..f9a243e6 100644
--- a/CodePulse-macOS/Services/CloudKitSync.swift
+++ b/CodePulse-macOS/Services/CloudKitSync.swift
@@ -22,39 +22,19 @@ final class CloudKitSync {
self?.syncToCloud(sessions)
}
.store(in: &cancellables)
- logger.info("CloudKitSync initialized")
- }
-
- private static let logURL = FileManager.default.homeDirectoryForCurrentUser
- .appendingPathComponent(".codepulse/cloudkit-debug.log")
-
- private static func log(_ msg: String) {
- let line = "[\(Date())] \(msg)\n"
- if let handle = try? FileHandle(forWritingTo: logURL) {
- handle.seekToEndOfFile()
- handle.write(line.data(using: .utf8)!)
- try? handle.close()
- } else {
- try? line.write(to: logURL, atomically: false, encoding: .utf8)
- }
}
private func syncToCloud(_ sessions: [SessionState]) {
guard !isSyncing else { return }
- // Respect quota backoff
- if let backoff = quotaBackoffUntil, Date() < backoff {
- let remaining = Int(backoff.timeIntervalSinceNow)
- Self.log("Quota backoff: \(remaining)s remaining")
- return
- }
+ // Respect quota backoff — do NOT send any requests during backoff
+ if let backoff = quotaBackoffUntil, Date() < backoff { return }
quotaBackoffUntil = nil
let changed = sessions.filter { session in
session.status != .completed
&& previousStates[session.sessionId]?.updatedAt != session.updatedAt
}
-
guard !changed.isEmpty else { return }
isSyncing = true
@@ -64,16 +44,16 @@ final class CloudKitSync {
do {
try await CloudKitManager.shared.saveBatch(changed)
- Self.log("Batch saved \(changed.count) sessions OK")
for session in changed {
previousStates[session.sessionId] = session
}
} catch let error as CKError where error.code == .quotaExceeded || error.code == .requestRateLimited {
- let retryAfter = error.retryAfterSeconds ?? 300
- Self.log("Quota hit, backing off \(Int(retryAfter))s")
- quotaBackoffUntil = Date().addingTimeInterval(retryAfter)
+ let retryAfter = error.retryAfterSeconds ?? 600
+ // Double the backoff to be safe
+ quotaBackoffUntil = Date().addingTimeInterval(retryAfter * 2)
} catch {
- Self.log("ERROR: \(error)")
+ // Unknown error — backoff 5 minutes
+ quotaBackoffUntil = Date().addingTimeInterval(300)
}
}
}
diff --git a/CodePulseShared/Sources/CloudKit/CloudKitManager.swift b/CodePulseShared/Sources/CloudKit/CloudKitManager.swift
index 0c006769..d5178d80 100644
--- a/CodePulseShared/Sources/CloudKit/CloudKitManager.swift
+++ b/CodePulseShared/Sources/CloudKit/CloudKitManager.swift
@@ -22,15 +22,28 @@ public final class CloudKitManager: Sendable {
let recordIDs = sessions.map { CKRecord.ID(recordName: $0.sessionId) }
var existingRecords: [String: CKRecord] = [:]
- // Fetch existing records (ignore errors for records that don't exist yet)
+ // Fetch existing records to get change tags (ignore errors for new records)
let fetchResults = try? await database.records(for: recordIDs)
if let fetchResults {
for (recordID, result) in fetchResults {
- if case .success(let record) = result {
+ switch result {
+ case .success(let record):
existingRecords[recordID.recordName] = record
+ logger.debug("Fetched existing record: \(recordID.recordName.prefix(8))")
+ case .failure(let error):
+ logger.debug("Record \(recordID.recordName.prefix(8)) not found: \(error.localizedDescription)")
}
}
}
+ logger.info("Fetch phase: \(existingRecords.count) existing, \(sessions.count - existingRecords.count) new")
+ // File-based debug log (os.Logger not visible from CLI)
+ let debugLine = "[\(Date())] CK fetch: \(existingRecords.count) existing, \(sessions.count - existingRecords.count) new\n"
+ let debugURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".codepulse/cloudkit-debug.log")
+ if let handle = try? FileHandle(forWritingTo: debugURL) {
+ handle.seekToEndOfFile()
+ handle.write(debugLine.data(using: .utf8)!)
+ try? handle.close()
+ }
// Build records: update existing or create new
let records: [CKRecord] = sessions.map { session in
@@ -49,13 +62,32 @@ public final class CloudKitManager: Sendable {
operation.qualityOfService = .utility
return try await withCheckedThrowingContinuation { continuation in
+ var perRecordErrors: [String] = []
+ var savedCount = 0
+
+ operation.perRecordSaveBlock = { recordID, result in
+ switch result {
+ case .success:
+ savedCount += 1
+ case .failure(let error):
+ perRecordErrors.append("\(recordID.recordName.prefix(8)): \(error.localizedDescription)")
+ }
+ }
+
operation.modifyRecordsResultBlock = { result in
+ if !perRecordErrors.isEmpty {
+ logger.error("Per-record errors: \(perRecordErrors.joined(separator: "; "))")
+ }
+ logger.info("Batch save: \(savedCount)/\(sessions.count) succeeded")
+
switch result {
case .success:
- logger.info("Batch saved \(sessions.count) sessions to CloudKit")
- continuation.resume()
+ if savedCount > 0 {
+ continuation.resume()
+ } else {
+ continuation.resume(throwing: CKError(.partialFailure))
+ }
case .failure(let error):
- logger.error("Batch save failed: \(error.localizedDescription)")
continuation.resume(throwing: error)
}
}