A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
iPhone step 4: the Mac publishes agent sessions to iCloud (#211)
Louis0db297ff32d8
diff --git a/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift b/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swiftindex f9b33be2..4f44ef04 100644--- a/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift+++ b/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift@@ -4,7 +4,8 @@ import CloudKit// MARK: - iPhone link spike (DebugCloud only)//-// Proves that the Mac and the iPhone app share a private CloudKit database:+// Step 1 spike, kept for testing: when the phoneLinkPing default is on, proves+// that the Mac and the iPhone app share a private CloudKit database:// writes a `Ping` every 60 s, waits for the iPhone's `Pong`, and logs the// round trip to ~/Library/Logs/NotchBuddy/nb.log. Pongs arrive both through a// silent push (CKDatabaseSubscription) and a 5 s poll, so the log shows which@@ -28,6 +29,7 @@ final class CloudProbe {private var seenPongs = Set<String>()private var fetching = falseprivate var lastPushAt: Date?+ private var started = falseprivate var pingTask: Task<Void, Never>?private var pollTask: Task<Void, Never>?@@ -44,7 +46,8 @@ final class CloudProbe {}func start() {- guard pingTask == nil else { return }+ guard !started else { return }+ started = true#if DEBUGlet build = "debug"#else@@ -52,7 +55,14 @@ final class CloudProbe {#endiflog("starting (\(appLabel), \(build) build, container \(Self.containerID))")NSApplication.shared.registerForRemoteNotifications()+ SessionPublisher.shared.start()+ // Step 1 Ping/Pong test: off unless asked for, so the Mac stays idle at rest+ // (defaults write fr.louisraille.NotchBuddy phoneLinkPing -bool YES).+ guard UserDefaults.standard.bool(forKey: "phoneLinkPing") else {+ log("ping test off (phoneLinkPing)")+ return+ }pingTask = Task { [weak self] inwhile !Task.isCancelled {await self?.pingTick()diff --git a/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift b/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swiftnew file mode 100644index 00000000..392c4925--- /dev/null+++ b/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift@@ -0,0 +1,216 @@+#if PHONE_LINK+import AppKit+import CloudKit+import Combine++// MARK: - iPhone plan, step 4: publish agent sessions to iCloud+//+// One `Session` record per agent pill (VS Code / Claude Code, Cursor, Codex,+// Antigravity, Gemini CLI…) in the private zone `Coucou`, so the iPhone can show+// them. Driven only by AppState changes (debounced), never by a timer: nothing+// runs while no agent changes. Integrations (Stripe, Vercel…) are not sessions.+//+// In clear (needed for sorting and widgets): pillId, state, step counts, flags,+// dates. Encrypted with the user's iCloud keys: project name, steps, cwd,+// last message, the pending command and question.++@MainActor+final class SessionPublisher {+ static let shared = SessionPublisher()++ private let container = CKContainer(identifier: "iCloud.fr.louisraille.Coucou")+ private var database: CKDatabase { container.privateCloudDatabase }+ private var cancellable: AnyCancellable?++ /// What was last written to iCloud, by pill ID.+ private var published: [String: SessionSnapshot] = [:]+ private var zoneReady = false+ private var cleanedUp = false+ private var publishing = false+ private var pending: [String: SessionSnapshot]?++ func start() {+ guard cancellable == nil else { return }+ let state = AppState.shared+ cancellable = state.$tasks+ .combineLatest(state.$pendingApproval, state.$pendingQuestion)+ .map { tasks, approval, question in+ SessionSnapshot.all(tasks: tasks, approval: approval, question: question)+ }+ .removeDuplicates()+ .debounce(for: .milliseconds(500), scheduler: RunLoop.main)+ .sink { [weak self] snapshots in+ MainActor.assumeIsolated { self?.publish(snapshots) }+ }+ log("session publisher on")+ }++ // MARK: Publishing++ private func publish(_ snapshots: [String: SessionSnapshot]) {+ guard !publishing else { pending = snapshots; return }+ publishing = true+ Task {+ await write(snapshots)+ publishing = false+ if let next = pending {+ pending = nil+ publish(next)+ }+ }+ }++ private func write(_ snapshots: [String: SessionSnapshot]) async {+ do {+ if !zoneReady {+ _ = try await database.modifyRecordZones(saving: [CKRecordZone(zoneID: SessionSnapshot.zoneID)], deleting: [])+ zoneReady = true+ }+ if !cleanedUp {+ // Sessions left by a previous run (the Mac quit or crashed).+ published = try await existingSessions()+ cleanedUp = true+ }++ let changed = snapshots.values.filter { published[$0.pillId] != $0 }+ let removed = published.keys.filter { snapshots[$0] == nil }+ guard !changed.isEmpty || !removed.isEmpty else { return }++ let records = changed.map { $0.record() }+ let deletions = removed.map { SessionSnapshot.recordID(for: $0) }+ let result = try await database.modifyRecords(saving: records, deleting: deletions,+ savePolicy: .changedKeys, atomically: false)+ for (id, outcome) in result.saveResults {+ guard let pillId = SessionSnapshot.pillId(from: id) else { continue }+ switch outcome {+ case .success: published[pillId] = snapshots[pillId]+ case .failure(let error): log("save \(pillId) failed: \(error.localizedDescription)")+ }+ }+ for (id, outcome) in result.deleteResults {+ guard let pillId = SessionSnapshot.pillId(from: id) else { continue }+ switch outcome {+ case .success: published[pillId] = nil+ case .failure(let error): log("delete \(pillId) failed: \(error.localizedDescription)")+ }+ }+ let summary = changed.map { "\($0.pillId)=\($0.state)" }.sorted().joined(separator: ", ")+ log("published \(changed.count) session(s)\(summary.isEmpty ? "" : " [\(summary)]"), removed \(removed.count)")+ } catch let error as CKError where error.code == .zoneNotFound || error.code == .userDeletedZone {+ zoneReady = false+ log("zone missing, will recreate on the next change")+ } catch {+ log("publish failed: \(error.localizedDescription)")+ }+ }++ /// Session records already in the zone, so the first write can delete stale ones.+ private func existingSessions() async throws -> [String: SessionSnapshot] {+ var found: [String: SessionSnapshot] = [:]+ var token: CKServerChangeToken?+ var more = true+ while more {+ let changes = try await database.recordZoneChanges(inZoneWith: CloudProbe.zoneID, since: token)+ for (id, result) in changes.modificationResultsByID {+ guard case .success(let mod) = result, mod.record.recordType == SessionSnapshot.recordType,+ let pillId = SessionSnapshot.pillId(from: id) else { continue }+ // Unknown content: a placeholder that never equals a real snapshot,+ // so it is rewritten if the session still exists, deleted otherwise.+ found[pillId] = SessionSnapshot.placeholder(pillId: pillId)+ }+ token = changes.changeToken+ more = changes.moreComing+ }+ return found+ }++ private func log(_ message: String) {+ CloudProbe.shared.log("[sessions] \(message)")+ }+}++// MARK: - Snapshot++/// The part of an AgentTask the iPhone needs. Equatable so unchanged sessions+/// are not rewritten.+struct SessionSnapshot: Equatable {+ static let recordType = "Session"++ let pillId: String+ let name: String+ let color: String+ let state: String+ let stepIndex: Int+ let steps: [String]+ let cwd: String+ let finalLine: String+ let approvalTool: String+ let approvalCommand: String+ let question: String++ static func all(tasks: [AgentTask], approval: ApprovalInfo?,+ question: AskQuestion?) -> [String: SessionSnapshot] {+ var result: [String: SessionSnapshot] = [:]+ for task in tasks where task.source != .n8n {+ let hasApproval = approval?.pillId == task.id+ let questionText = task.state == .question+ ? (question?.questions.map(\.question).joined(separator: "\n") ?? "")+ : ""+ result[task.id] = SessionSnapshot(+ pillId: task.id,+ name: task.name,+ color: task.color,+ state: task.state.rawValue,+ stepIndex: task.stepIndex,+ steps: task.steps,+ cwd: task.sessionCwd ?? "",+ finalLine: task.finalLine ?? "",+ approvalTool: hasApproval ? (approval?.tool ?? "") : "",+ approvalCommand: hasApproval ? (approval?.command ?? "") : "",+ question: questionText)+ }+ return result+ }++ static func placeholder(pillId: String) -> SessionSnapshot {+ SessionSnapshot(pillId: pillId, name: "", color: "", state: "", stepIndex: -1, steps: [],+ cwd: "", finalLine: "", approvalTool: "", approvalCommand: "", question: "")+ }++ /// Same zone as CloudProbe.zoneID, rebuilt here because that one is main-actor isolated.+ static var zoneID: CKRecordZone.ID {+ CKRecordZone.ID(zoneName: "Coucou", ownerName: CKCurrentUserDefaultName)+ }++ static func recordID(for pillId: String) -> CKRecord.ID {+ CKRecord.ID(recordName: "session-\(pillId)", zoneID: zoneID)+ }++ static func pillId(from id: CKRecord.ID) -> String? {+ let name = id.recordName+ guard name.hasPrefix("session-") else { return nil }+ return String(name.dropFirst("session-".count))+ }++ func record() -> CKRecord {+ let record = CKRecord(recordType: Self.recordType, recordID: Self.recordID(for: pillId))+ record["pillId"] = pillId+ record["color"] = color+ record["state"] = state+ record["stepIndex"] = stepIndex+ record["stepCount"] = steps.count+ record["needsApproval"] = !approvalCommand.isEmpty || !approvalTool.isEmpty+ record["needsAnswer"] = !question.isEmpty+ record["updatedAt"] = Date()+ record["macName"] = Host.current().localizedName ?? ""+ record.encryptedValues["name"] = name+ record.encryptedValues["steps"] = steps+ record.encryptedValues["cwd"] = cwd+ record.encryptedValues["finalLine"] = finalLine+ record.encryptedValues["approvalTool"] = approvalTool+ record.encryptedValues["approvalCommand"] = approvalCommand+ record.encryptedValues["question"] = question+ return record+ }+}+#endifdiff --git a/NotchBuddy/Sources/Phone/LinkTestView.swift b/NotchBuddy/Sources/Phone/LinkTestView.swiftindex 795d0601..22947f1d 100644--- a/NotchBuddy/Sources/Phone/LinkTestView.swift+++ b/NotchBuddy/Sources/Phone/LinkTestView.swift@@ -20,6 +20,37 @@ struct LinkTestView: View {}}+ Section("Sessions on your Mac") {+ if link.sessions.isEmpty {+ Text("No session yet. Open Coucou on your Mac (NotchBuddyCloud).")+ .foregroundStyle(.secondary)+ }+ ForEach(link.sessions) { session in+ HStack(alignment: .top, spacing: 12) {+ MochiStill(state: session.state)+ .padding(4)+ .frame(width: 40, height: 40)+ .background(Color(hex: session.color), in: RoundedRectangle(cornerRadius: 10))+ VStack(alignment: .leading, spacing: 2) {+ Text(session.name.isEmpty ? session.pillName : session.name)+ Text("\(session.pillName) · \(session.state.rawValue)" ++ (session.steps.isEmpty ? "" : " · \(session.stepIndex + 1)/\(session.steps.count)"))+ .font(.caption).foregroundStyle(.secondary)+ if session.needsApproval {+ Text(session.approvalCommand.isEmpty ? "Waiting for your approval" : session.approvalCommand)+ .font(.caption.monospaced()).foregroundStyle(.orange).lineLimit(2)+ } else if !session.question.isEmpty {+ Text(session.question).font(.caption).foregroundStyle(.cyan).lineLimit(2)+ } else if let step = session.currentStep {+ Text(step).font(.caption).lineLimit(1)+ }+ Text(session.updatedAt, style: .relative)+ .font(.caption2).foregroundStyle(.secondary)+ }+ }+ }+ }+Section {Button {sending = truediff --git a/NotchBuddy/Sources/Phone/PhoneLink.swift b/NotchBuddy/Sources/Phone/PhoneLink.swiftindex 2a6f699a..918af19f 100644--- a/NotchBuddy/Sources/Phone/PhoneLink.swift+++ b/NotchBuddy/Sources/Phone/PhoneLink.swift@@ -15,6 +15,40 @@ struct PingItem: Identifiable {var delay: TimeInterval? { receivedAt.map { $0.timeIntervalSince(sentAt) } }}+/// An agent session published by the Mac (SessionPublisher), as seen by the iPhone.+struct SessionItem: Identifiable {+ let id: String // pill ID+ let name: String+ let color: String+ let state: BotState+ let stepIndex: Int+ let steps: [String]+ let needsApproval: Bool+ let approvalCommand: String+ let question: String+ let finalLine: String+ let updatedAt: Date+ let macName: String++ init(record: CKRecord) {+ id = record["pillId"] as? String ?? record.recordID.recordName+ name = record.encryptedValues["name"] as? String ?? ""+ color = record["color"] as? String ?? "#C0C4CC"+ state = BotState(rawValue: record["state"] as? String ?? "") ?? .idle+ stepIndex = record["stepIndex"] as? Int ?? 0+ steps = record.encryptedValues["steps"] as? [String] ?? []+ needsApproval = record["needsApproval"] as? Bool ?? false+ approvalCommand = record.encryptedValues["approvalCommand"] as? String ?? ""+ question = record.encryptedValues["question"] as? String ?? ""+ finalLine = record.encryptedValues["finalLine"] as? String ?? ""+ updatedAt = record["updatedAt"] as? Date ?? record.modificationDate ?? .now+ macName = record["macName"] as? String ?? ""+ }++ var pillName: String { PillCatalog.definition(for: id)?.name ?? id }+ var currentStep: String? { steps.indices.contains(stepIndex) ? steps[stepIndex] : steps.last }+}+@MainActor@Observablefinal class PhoneLink {@@ -30,10 +64,14 @@ final class PhoneLink {static let containerID = "iCloud.fr.louisraille.Coucou"static let zoneID = CKRecordZone.ID(zoneName: "Coucou", ownerName: CKCurrentUserDefaultName)- private static let subscriptionID = "coucou-zone-phone"+ private static let subscriptionID = "coucou-zone-phone-silent"+ /// Step 1's subscription showed a "Ping from your Mac" banner. A saved+ /// subscription keeps its notification settings, so it is deleted rather than reused.+ private static let oldSubscriptionID = "coucou-zone-phone"var status: Status = .startingvar pings: [PingItem] = []+ var sessions: [SessionItem] = []var lastPong: String?var pushError: String?var notificationsAllowed: Bool?@@ -74,14 +112,13 @@ final class PhoneLink {private func subscribe() async {let sub = CKDatabaseSubscription(subscriptionID: Self.subscriptionID)+ // Silent: the Mac now writes on every session change, a banner each+ // time would be noise. Real notifications come with step 7.let info = CKSubscription.NotificationInfo()- info.title = "Coucou"- info.alertBody = "Ping from your Mac"- info.soundName = "default"info.shouldSendContentAvailable = truesub.notificationInfo = infodo {- _ = try await database.modifySubscriptions(saving: [sub], deleting: [])+ _ = try await database.modifySubscriptions(saving: [sub], deleting: [Self.oldSubscriptionID])subscribed = true} catch {status = .failed("Subscription: \(error.localizedDescription)")@@ -101,6 +138,10 @@ final class PhoneLink {for (_, result) in changes.modificationResultsByID {if case .success(let mod) = result, add(mod.record) { gotNew = true }}+ for deletion in changes.deletions where deletion.recordType == "Session" {+ sessions.removeAll { "session-\($0.id)" == deletion.recordID.recordName }+ gotNew = true+ }changeToken = changes.changeTokenmore = changes.moreComing}@@ -120,6 +161,13 @@ final class PhoneLink {}private func add(_ record: CKRecord) -> Bool {+ if record.recordType == "Session" {+ let item = SessionItem(record: record)+ sessions.removeAll { $0.id == item.id }+ sessions.append(item)+ sessions.sort { $0.updatedAt > $1.updatedAt }+ return true+ }guard record.recordType == "Ping",!pings.contains(where: { $0.id == record.recordID }) else { return false }pings.append(PingItem(