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.

feat: replace print() with os.Logger, add CloudKit retry with backoff

libokai805809927711
diff --git a/CodePulse-iOS/Services/CloudKitReceiver.swift b/CodePulse-iOS/Services/CloudKitReceiver.swift
index ad0f046d..f99e4c33 100644
--- a/CodePulse-iOS/Services/CloudKitReceiver.swift
+++ b/CodePulse-iOS/Services/CloudKitReceiver.swift
@@ -2,6 +2,9 @@ import Foundation
import CloudKit
import Combine
import CodePulseShared
+import os
+
+private let logger = Logger(subsystem: "com.pokai.CodePulse.ios", category: "CloudKitReceiver")
@MainActor
final class CloudKitReceiver: ObservableObject {
@@ -11,8 +14,9 @@ final class CloudKitReceiver: ObservableObject {
func start() async {
do {
try await CloudKitManager.shared.subscribeToChanges()
+ logger.info("CloudKit subscription active")
} catch {
- print("Failed to subscribe to CloudKit changes: \(error)")
+ logger.error("Failed to subscribe to CloudKit: \(error.localizedDescription)")
}
await fetch()
}
@@ -20,17 +24,20 @@ final class CloudKitReceiver: ObservableObject {
func fetch() async {
do {
sessions = try await CloudKitManager.shared.fetchAll()
+ logger.debug("Fetched \(self.sessions.count) sessions")
} catch {
- print("Failed to fetch from CloudKit: \(error)")
+ logger.error("CloudKit fetch failed: \(error.localizedDescription)")
}
}
func onRemoteNotification() async {
+ logger.debug("Remote notification received")
await fetch()
}
func startPolling() {
guard pollTimer == nil else { return }
+ logger.info("Starting CloudKit polling (30s interval)")
pollTimer = Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { [weak self] _ in
Task { @MainActor in
await self?.fetch()
@@ -41,5 +48,6 @@ final class CloudKitReceiver: ObservableObject {
func stopPolling() {
pollTimer?.invalidate()
pollTimer = nil
+ logger.info("Stopped CloudKit polling")
}
}
diff --git a/CodePulse-macOS/Services/CloudKitSync.swift b/CodePulse-macOS/Services/CloudKitSync.swift
index 741f9b1d..ccf861d2 100644
--- a/CodePulse-macOS/Services/CloudKitSync.swift
+++ b/CodePulse-macOS/Services/CloudKitSync.swift
@@ -1,6 +1,9 @@
import Foundation
import Combine
import CodePulseShared
+import os
+
+private let logger = Logger(subsystem: "com.pokai.CodePulse", category: "CloudKitSync")
@MainActor
final class CloudKitSync {
@@ -17,21 +20,35 @@ final class CloudKitSync {
self?.syncToCloud(sessions)
}
.store(in: &cancellables)
+ logger.info("CloudKitSync initialized")
}
private func syncToCloud(_ sessions: [SessionState]) {
syncTask?.cancel()
syncTask = Task {
+ var syncedCount = 0
for session in sessions {
+ guard !Task.isCancelled else { return }
let previous = previousStates[session.sessionId]
do {
try await CloudKitManager.shared.saveIfChanged(session, previous: previous)
previousStates[session.sessionId] = session
+ syncedCount += 1
+ } catch {
+ logger.error("CloudKit sync failed for session \(session.sessionId): \(error.localizedDescription)")
+ }
+ }
+ if syncedCount > 0 {
+ logger.debug("Synced \(syncedCount) sessions to CloudKit")
+ }
+ // Cleanup less frequently — only if we synced something
+ if syncedCount > 0 {
+ do {
+ try await CloudKitManager.shared.deleteCompleted()
} catch {
- print("CloudKit sync error for \(session.sessionId): \(error)")
+ logger.debug("CloudKit cleanup skipped: \(error.localizedDescription)")
}
}
- try? await CloudKitManager.shared.deleteCompleted()
}
}
}
diff --git a/CodePulse-macOS/Services/SessionScanner.swift b/CodePulse-macOS/Services/SessionScanner.swift
index 23598cee..5831bf42 100644
--- a/CodePulse-macOS/Services/SessionScanner.swift
+++ b/CodePulse-macOS/Services/SessionScanner.swift
@@ -1,5 +1,8 @@
import Foundation
import Combine
+import os
+
+private let logger = Logger(subsystem: "com.pokai.CodePulse", category: "SessionScanner")
@MainActor
final class SessionScanner: ObservableObject {
@@ -20,6 +23,7 @@ final class SessionScanner: ObservableObject {
self?.scan()
}
}
+ logger.info("SessionScanner started, watching \(ClaudePaths.sessionsDir.path)")
}
func stop() {
@@ -28,6 +32,7 @@ final class SessionScanner: ObservableObject {
scanTimer?.invalidate()
scanTimer = nil
debounceTask?.cancel()
+ logger.info("SessionScanner stopped")
}
private func scheduleScan() {
@@ -46,12 +51,18 @@ final class SessionScanner: ObservableObject {
guard PIDChecker.isAlive(pid: file.pid) else { continue }
newSessions[file.sessionId] = file
}
+ if newSessions.count != activeSessions.count {
+ logger.info("Active sessions: \(newSessions.count)")
+ }
activeSessions = newSessions
}
private func watchDirectory(_ url: URL, handler: @escaping () -> Void) {
let fd = open(url.path, O_EVTONLY)
- guard fd >= 0 else { return }
+ guard fd >= 0 else {
+ logger.warning("Failed to watch directory: \(url.path)")
+ return
+ }
let source = DispatchSource.makeFileSystemObjectSource(
fileDescriptor: fd,
eventMask: [.write, .rename, .delete],
diff --git a/CodePulse.xcodeproj/project.pbxproj b/CodePulse.xcodeproj/project.pbxproj
index c098c81e..48275c5b 100644
--- a/CodePulse.xcodeproj/project.pbxproj
+++ b/CodePulse.xcodeproj/project.pbxproj
@@ -3,7 +3,7 @@
archiveVersion = 1;
classes = {
};
- objectVersion = 77;
+ objectVersion = 63;
objects = {
/* Begin PBXBuildFile section */
@@ -69,7 +69,7 @@
3935CEE144EC8AFCA3AEAEA3 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
3B652652FD106495A82565C8 /* CodePulseLiveActivity.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = CodePulseLiveActivity.appex; sourceTree = BUILT_PRODUCTS_DIR; };
3BCD1168005B123A7F9ACB37 /* CodePulseLiveActivityBundle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodePulseLiveActivityBundle.swift; sourceTree = "<group>"; };
- 3EB0548BFADFAFC3616A8C4B /* CodePulse-iOS.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = "CodePulse-iOS.app"; sourceTree = BUILT_PRODUCTS_DIR; };
+ 3EB0548BFADFAFC3616A8C4B /* CodePulse-iOS.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; name = "CodePulse-iOS.app"; path = CodePulse.app; sourceTree = BUILT_PRODUCTS_DIR; };
42BAF66F7C50D732B7E69333 /* SessionScanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionScanner.swift; sourceTree = "<group>"; };
433D534BFD8D3D76B489B324 /* CodePulse-iOS.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = "CodePulse-iOS.entitlements"; sourceTree = "<group>"; };
4A67A3CD19408484AB11BB73 /* CodePulseApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodePulseApp.swift; sourceTree = "<group>"; };
@@ -91,7 +91,7 @@
D866EFD6224AECD6846B76BE /* IOSOnboardingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSOnboardingView.swift; sourceTree = "<group>"; };
DA699D0197B8A14FD7D1BDC4 /* SessionListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionListView.swift; sourceTree = "<group>"; };
DF291DF4A4EF932B774F227D /* IOSRootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSRootView.swift; sourceTree = "<group>"; };
- F033CA1408917B1655BC66D2 /* CodePulseShared */ = {isa = PBXFileReference; lastKnownFileType = folder; name = CodePulseShared; path = CodePulseShared; sourceTree = SOURCE_ROOT; };
+ F033CA1408917B1655BC66D2 /* CodePulseShared */ = {isa = PBXFileReference; lastKnownFileType = folder; path = CodePulseShared; sourceTree = SOURCE_ROOT; };
F19A27E00B1B13A579A950F4 /* CloudKitReceiver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudKitReceiver.swift; sourceTree = "<group>"; };
F71E03612F167D883C324D25 /* SessionStateManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionStateManager.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
@@ -343,7 +343,6 @@
packageReferences = (
2546D0E01391BBF7D36B931E /* XCLocalSwiftPackageReference "CodePulseShared" */,
);
- preferredProjectObjectVersion = 77;
projectDirPath = "";
projectRoot = "";
targets = (
@@ -454,7 +453,10 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = "CodePulse-macOS/App/CodePulse.entitlements";
+ CODE_SIGN_IDENTITY = "Apple Development";
+ CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
+ DEVELOPMENT_TEAM = DEVELOPMENT_TEAM_REDACTED;
ENABLE_APP_SANDBOX = NO;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_LSUIElement = YES;
@@ -466,6 +468,7 @@
MACOSX_DEPLOYMENT_TARGET = 14.0;
PRODUCT_BUNDLE_IDENTIFIER = com.pokai.CodePulse;
PRODUCT_NAME = CodePulse;
+ PROVISIONING_PROFILE_SPECIFIER = "";
SDKROOT = macosx;
SWIFT_VERSION = 6.0;
};
@@ -476,7 +479,10 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = "CodePulse-macOS/App/CodePulse.entitlements";
+ CODE_SIGN_IDENTITY = "Apple Development";
+ CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
+ DEVELOPMENT_TEAM = DEVELOPMENT_TEAM_REDACTED;
ENABLE_APP_SANDBOX = NO;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_LSUIElement = YES;
@@ -488,6 +494,7 @@
MACOSX_DEPLOYMENT_TARGET = 14.0;
PRODUCT_BUNDLE_IDENTIFIER = com.pokai.CodePulse;
PRODUCT_NAME = CodePulse;
+ PROVISIONING_PROFILE_SPECIFIER = "";
SDKROOT = macosx;
SWIFT_VERSION = 6.0;
};
diff --git a/CodePulseShared/Sources/CloudKit/CloudKitManager.swift b/CodePulseShared/Sources/CloudKit/CloudKitManager.swift
index 4b245102..1ceeaabd 100644
--- a/CodePulseShared/Sources/CloudKit/CloudKitManager.swift
+++ b/CodePulseShared/Sources/CloudKit/CloudKitManager.swift
@@ -1,5 +1,8 @@
import CloudKit
import Foundation
+import os
+
+private let logger = Logger(subsystem: "com.pokai.CodePulse", category: "CloudKit")
public final class CloudKitManager: Sendable {
public static let shared = CloudKitManager()
@@ -8,9 +11,14 @@ public final class CloudKitManager: Sendable {
private init() {}
+ // MARK: - Write (macOS)
+
public func save(_ session: SessionState) async throws {
let record = CKRecordMapper.toRecord(session)
- _ = try await database.save(record)
+ try await retryOnQuotaExceeded {
+ _ = try await self.database.save(record)
+ }
+ logger.debug("Saved session \(session.sessionId) to CloudKit")
}
public func saveIfChanged(_ session: SessionState, previous: SessionState?) async throws {
@@ -18,16 +26,22 @@ public final class CloudKitManager: Sendable {
try await save(session)
}
+ // MARK: - Read (iOS)
+
public func fetchAll() async throws -> [SessionState] {
let query = CKQuery(recordType: CKRecordMapper.recordType, predicate: NSPredicate(value: true))
query.sortDescriptors = [NSSortDescriptor(key: "updatedAt", ascending: false)]
let (results, _) = try await database.records(matching: query, resultsLimit: 20)
- return results.compactMap { _, result in
- guard case .success(let record) = result else { return nil }
+ let sessions = results.compactMap { _, result in
+ guard case .success(let record) = result else { return nil as SessionState? }
return CKRecordMapper.fromRecord(record)
}
+ logger.info("Fetched \(sessions.count) sessions from CloudKit")
+ return sessions
}
+ // MARK: - Subscribe (iOS)
+
public func subscribeToChanges() async throws {
let subscription = CKQuerySubscription(
recordType: CKRecordMapper.recordType,
@@ -39,8 +53,11 @@ public final class CloudKitManager: Sendable {
info.shouldSendContentAvailable = true
subscription.notificationInfo = info
_ = try await database.save(subscription)
+ logger.info("Subscribed to CloudKit changes")
}
+ // MARK: - Cleanup
+
public func deleteCompleted(olderThan hours: Int = 24) async throws {
let cutoff = Date().addingTimeInterval(TimeInterval(-hours * 3600))
let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [
@@ -50,7 +67,31 @@ public final class CloudKitManager: Sendable {
let query = CKQuery(recordType: CKRecordMapper.recordType, predicate: predicate)
let (results, _) = try await database.records(matching: query)
for (id, _) in results {
- try await database.deleteRecord(withID: id)
+ try? await database.deleteRecord(withID: id)
+ }
+ if !results.isEmpty {
+ logger.info("Deleted \(results.count) completed sessions from CloudKit")
+ }
+ }
+
+ // MARK: - Retry Logic
+
+ private func retryOnQuotaExceeded(maxRetries: Int = 3, operation: @Sendable () async throws -> Void) async throws {
+ for attempt in 0..<maxRetries {
+ do {
+ try await operation()
+ return
+ } catch let error as CKError where error.code == .requestRateLimited || error.code == .zoneBusy || error.code == .serviceUnavailable {
+ let retryAfter = error.retryAfterSeconds ?? Double(attempt + 1) * 5
+ logger.warning("CloudKit rate limited (attempt \(attempt + 1)/\(maxRetries)), retrying after \(retryAfter)s")
+ try await Task.sleep(for: .seconds(min(retryAfter, 30))) // cap at 30s
+ } catch let error as CKError where error.code == .quotaExceeded {
+ let retryAfter = error.retryAfterSeconds ?? 60
+ logger.warning("CloudKit quota exceeded (attempt \(attempt + 1)/\(maxRetries)), retrying after \(min(retryAfter, 60))s")
+ try await Task.sleep(for: .seconds(min(retryAfter, 60)))
+ }
}
+ // Final attempt, let error propagate
+ try await operation()
}
}