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 steps 1–2: CloudKit link spike + Developer ID build with iCloud (#209)
Louis2d3a1692ac92
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 8f1fb928..04f54a91 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -54,3 +54,42 @@ jobs:build \CODE_SIGNING_ALLOWED=NO \CODE_SIGNING_REQUIRED=NO++ - name: Build App Store target (unsigned)+ run: |+ xcodebuild \+ -project NotchBuddy/NotchBuddy.xcodeproj \+ -scheme CoucouAppStore \+ -configuration Debug \+ build \+ CODE_SIGNING_ALLOWED=NO \+ CODE_SIGNING_REQUIRED=NO++ - name: Build iPhone link spike (Mac, DebugCloud, unsigned)+ run: |+ xcodebuild \+ -project NotchBuddy/NotchBuddy.xcodeproj \+ -scheme NotchBuddyCloud \+ -configuration DebugCloud \+ build \+ CODE_SIGNING_ALLOWED=NO \+ CODE_SIGNING_REQUIRED=NO++ - name: Build iPhone link spike (Mac, ReleaseCloud, unsigned)+ run: |+ xcodebuild \+ -project NotchBuddy/NotchBuddy.xcodeproj \+ -scheme NotchBuddy \+ -configuration ReleaseCloud \+ build \+ CODE_SIGNING_ALLOWED=NO \+ CODE_SIGNING_REQUIRED=NO++ - name: Build iPhone app (unsigned)+ run: |+ xcodebuild \+ -project NotchBuddy/NotchBuddy.xcodeproj \+ -scheme CoucouPhone \+ -destination 'generic/platform=iOS' \+ build \+ CODE_SIGNING_ALLOWED=NOdiff --git a/NotchBuddy/Resources/CoucouAppStoreCloud.entitlements b/NotchBuddy/Resources/CoucouAppStoreCloud.entitlementsnew file mode 100644index 00000000..8cb503f6--- /dev/null+++ b/NotchBuddy/Resources/CoucouAppStoreCloud.entitlements@@ -0,0 +1,24 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.security.app-sandbox</key>+ <true/>+ <key>com.apple.security.network.client</key>+ <true/>+ <key>com.apple.security.files.user-selected.read-write</key>+ <true/>+ <key>com.apple.security.files.bookmarks.app-scope</key>+ <true/>+ <key>com.apple.developer.icloud-container-identifiers</key>+ <array>+ <string>iCloud.fr.louisraille.Coucou</string>+ </array>+ <key>com.apple.developer.icloud-services</key>+ <array>+ <string>CloudKit</string>+ </array>+ <key>com.apple.developer.aps-environment</key>+ <string>development</string>+</dict>+</plist>diff --git a/NotchBuddy/Resources/CoucouCloud.entitlements b/NotchBuddy/Resources/CoucouCloud.entitlementsnew file mode 100644index 00000000..4ffd53e9--- /dev/null+++ b/NotchBuddy/Resources/CoucouCloud.entitlements@@ -0,0 +1,18 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.security.automation.apple-events</key>+ <true/>+ <key>com.apple.developer.icloud-container-identifiers</key>+ <array>+ <string>iCloud.fr.louisraille.Coucou</string>+ </array>+ <key>com.apple.developer.icloud-services</key>+ <array>+ <string>CloudKit</string>+ </array>+ <key>com.apple.developer.aps-environment</key>+ <string>development</string>+</dict>+</plist>diff --git a/NotchBuddy/Resources/CoucouPhone.entitlements b/NotchBuddy/Resources/CoucouPhone.entitlementsnew file mode 100644index 00000000..e8455bbb--- /dev/null+++ b/NotchBuddy/Resources/CoucouPhone.entitlements@@ -0,0 +1,16 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>aps-environment</key>+ <string>development</string>+ <key>com.apple.developer.icloud-container-identifiers</key>+ <array>+ <string>iCloud.fr.louisraille.Coucou</string>+ </array>+ <key>com.apple.developer.icloud-services</key>+ <array>+ <string>CloudKit</string>+ </array>+</dict>+</plist>diff --git a/NotchBuddy/Resources/CoucouPhoneProduction.entitlements b/NotchBuddy/Resources/CoucouPhoneProduction.entitlementsnew file mode 100644index 00000000..85dee5e5--- /dev/null+++ b/NotchBuddy/Resources/CoucouPhoneProduction.entitlements@@ -0,0 +1,18 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>aps-environment</key>+ <string>development</string>+ <key>com.apple.developer.icloud-container-identifiers</key>+ <array>+ <string>iCloud.fr.louisraille.Coucou</string>+ </array>+ <key>com.apple.developer.icloud-services</key>+ <array>+ <string>CloudKit</string>+ </array>+ <key>com.apple.developer.icloud-container-environment</key>+ <string>Production</string>+</dict>+</plist>diff --git a/NotchBuddy/Resources/CoucouReleaseCloud.entitlements b/NotchBuddy/Resources/CoucouReleaseCloud.entitlementsnew file mode 100644index 00000000..90d7976a--- /dev/null+++ b/NotchBuddy/Resources/CoucouReleaseCloud.entitlements@@ -0,0 +1,24 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.security.automation.apple-events</key>+ <true/>+ <key>com.apple.application-identifier</key>+ <string>256AUJ9555.fr.louisraille.NotchBuddy</string>+ <key>com.apple.developer.team-identifier</key>+ <string>256AUJ9555</string>+ <key>com.apple.developer.icloud-container-identifiers</key>+ <array>+ <string>iCloud.fr.louisraille.Coucou</string>+ </array>+ <key>com.apple.developer.icloud-services</key>+ <array>+ <string>CloudKit</string>+ </array>+ <key>com.apple.developer.icloud-container-environment</key>+ <string>Production</string>+ <key>com.apple.developer.aps-environment</key>+ <string>production</string>+</dict>+</plist>diff --git a/NotchBuddy/Resources/InfoPhone.plist b/NotchBuddy/Resources/InfoPhone.plistnew file mode 100644index 00000000..23a20f93--- /dev/null+++ b/NotchBuddy/Resources/InfoPhone.plist@@ -0,0 +1,40 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>$(DEVELOPMENT_LANGUAGE)</string>+ <key>CFBundleDisplayName</key>+ <string>Coucou</string>+ <key>CFBundleExecutable</key>+ <string>$(EXECUTABLE_NAME)</string>+ <key>CFBundleIdentifier</key>+ <string>fr.louisraille.Coucou</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>Coucou</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>0.1</string>+ <key>CFBundleVersion</key>+ <string>1</string>+ <key>ITSAppUsesNonExemptEncryption</key>+ <false/>+ <key>LSRequiresIPhoneOS</key>+ <true/>+ <key>UIApplicationSupportsIndirectInputEvents</key>+ <true/>+ <key>UIBackgroundModes</key>+ <array>+ <string>remote-notification</string>+ </array>+ <key>UILaunchScreen</key>+ <dict/>+ <key>UISupportedInterfaceOrientations</key>+ <array>+ <string>UIInterfaceOrientationPortrait</string>+ </array>+</dict>+</plist>diff --git a/NotchBuddy/Sources/App/AppDelegate.swift b/NotchBuddy/Sources/App/AppDelegate.swiftindex 4c8902ad..cad996da 100644--- a/NotchBuddy/Sources/App/AppDelegate.swift+++ b/NotchBuddy/Sources/App/AppDelegate.swift@@ -18,6 +18,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate {NSApp.setActivationPolicy(.accessory)setupMenuBarItem()setupIsland()+ #if PHONE_LINK+ CloudProbe.shared.start()+ #endif}// MARK: - Menu bardiff --git a/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift b/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swiftnew file mode 100644index 00000000..f9b33be2--- /dev/null+++ b/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift@@ -0,0 +1,216 @@+#if PHONE_LINK+import AppKit+import CloudKit++// MARK: - iPhone link spike (DebugCloud only)+//+// 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+// path is faster. Compiled only with PHONE_LINK; normal builds never see it.++@MainActor+final class CloudProbe {+ static let shared = CloudProbe()++ static let containerID = "iCloud.fr.louisraille.Coucou"+ static let zoneID = CKRecordZone.ID(zoneName: "Coucou", ownerName: CKCurrentUserDefaultName)+ private static let subscriptionID = "coucou-zone-mac"++ private let container = CKContainer(identifier: CloudProbe.containerID)+ private var database: CKDatabase { container.privateCloudDatabase }++ private let launchDate = Date()+ private var ready = false+ private var pingCount = 0+ private var changeToken: CKServerChangeToken?+ private var seenPongs = Set<String>()+ private var fetching = false+ private var lastPushAt: Date?+ private var pingTask: Task<Void, Never>?+ private var pollTask: Task<Void, Never>?++ private var appLabel: String {+ #if APPSTORE+ "CoucouAppStore"+ #else+ "NotchBuddy"+ #endif+ }++ private var macName: String {+ Host.current().localizedName ?? ProcessInfo.processInfo.hostName+ }++ func start() {+ guard pingTask == nil else { return }+ #if DEBUG+ let build = "debug"+ #else+ let build = "release"+ #endif+ log("starting (\(appLabel), \(build) build, container \(Self.containerID))")+ NSApplication.shared.registerForRemoteNotifications()++ pingTask = Task { [weak self] in+ while !Task.isCancelled {+ await self?.pingTick()+ try? await Task.sleep(for: .seconds(60))+ }+ }+ pollTask = Task { [weak self] in+ while !Task.isCancelled {+ try? await Task.sleep(for: .seconds(5))+ await self?.fetchChanges(source: "poll")+ }+ }+ }++ // MARK: Setup++ /// Checks the iCloud account, creates the zone and the subscription.+ /// Returns false (and logs why) when iCloud isn't usable yet; retried on the next tick.+ private func prepare() async -> Bool {+ if ready { return true }+ do {+ let status = try await container.accountStatus()+ guard status == .available else {+ log("iCloud account not available (status \(describe(status))), will retry in 60 s")+ return false+ }+ _ = try await database.modifyRecordZones(saving: [CKRecordZone(zoneID: Self.zoneID)], deleting: [])+ log("zone Coucou ready")++ let sub = CKDatabaseSubscription(subscriptionID: Self.subscriptionID)+ let info = CKSubscription.NotificationInfo()+ info.shouldSendContentAvailable = true // silent push+ sub.notificationInfo = info+ _ = try await database.modifySubscriptions(saving: [sub], deleting: [])+ log("database subscription saved")+ let subs = try await database.allSubscriptions()+ log("subscriptions on this iCloud account: \(subs.map(\.subscriptionID).sorted().joined(separator: ", "))")+ ready = true+ return true+ } catch {+ log("setup failed: \(error.localizedDescription)")+ return false+ }+ }++ // MARK: Ping++ private func pingTick() async {+ guard await prepare() else { return }+ pingCount += 1+ let record = CKRecord(recordType: "Ping",+ recordID: CKRecord.ID(recordName: UUID().uuidString, zoneID: Self.zoneID))+ let sentAt = Date()+ record["macName"] = macName+ record["app"] = appLabel+ record["sentAt"] = sentAt+ record.encryptedValues["message"] = "Ping #\(pingCount) from \(appLabel)"+ do {+ _ = try await database.save(record)+ log("Ping #\(pingCount) saved in \(String(format: "%.1f", Date().timeIntervalSince(sentAt))) s")+ } catch {+ log("Ping #\(pingCount) failed: \(error.localizedDescription)")+ }+ }++ // MARK: Pong++ func handleRemoteNotification(_ userInfo: [String: Any]) {+ guard CKNotification(fromRemoteNotificationDictionary: userInfo) != nil else {+ log("remote notification received, not from CloudKit (keys: \(userInfo.keys.sorted().joined(separator: ", ")))")+ return+ }+ lastPushAt = Date()+ log("push received")+ Task { await fetchChanges(source: "push") }+ }++ private func fetchChanges(source: String) async {+ guard ready, !fetching else { return }+ fetching = true+ defer { fetching = false }+ do {+ var more = true+ while more {+ let changes = try await database.recordZoneChanges(inZoneWith: Self.zoneID, since: changeToken)+ for (_, result) in changes.modificationResultsByID {+ if case .success(let mod) = result { handle(mod.record, source: source) }+ }+ changeToken = changes.changeToken+ more = changes.moreComing+ }+ } catch let error as CKError where error.code == .changeTokenExpired {+ changeToken = nil+ } catch let error as CKError where error.code == .zoneNotFound {+ log("zone Coucou missing, recreating")+ ready = false+ } catch {+ log("fetch (\(source)) failed: \(error.localizedDescription)")+ }+ }++ private func handle(_ record: CKRecord, source: String) {+ guard record.recordType == "Pong" else { return }+ let id = record.recordID.recordName+ guard !seenPongs.contains(id) else { return }+ seenPongs.insert(id)+ // Older pongs from previous runs: remember them, don't log them.+ guard let created = record.creationDate, created >= launchDate else { return }++ let message = record.encryptedValues["message"] as? String ?? "?"+ var line = "Pong from iPhone: \(message)"+ if let pingSentAt = record["pingSentAt"] as? Date {+ line += String(format: ", round trip %.1f s", Date().timeIntervalSince(pingSentAt))+ }+ if let repliedAt = record["repliedAt"] as? Date {+ line += String(format: ", %.1f s after the tap", Date().timeIntervalSince(repliedAt))+ }+ line += " (via \(source)"+ if source == "poll", let push = lastPushAt, Date().timeIntervalSince(push) < 10 {+ line += ", push came \(String(format: "%.1f", Date().timeIntervalSince(push))) s ago"+ }+ line += ")"+ log(line)+ }++ // MARK: Helpers++ private func describe(_ status: CKAccountStatus) -> String {+ switch status {+ case .available: "available"+ case .noAccount: "no account"+ case .restricted: "restricted"+ case .couldNotDetermine: "could not determine"+ case .temporarilyUnavailable: "temporarily unavailable"+ @unknown default: "unknown"+ }+ }++ /// Writes to nb.log and to the Xcode console (the sandboxed build's nb.log+ /// sits in its container, which Terminal can't read).+ func log(_ message: String) {+ appendAppLog("nb.log", "[PhoneLink] \(message)")+ print("[PhoneLink] \(message)")+ }+}++extension AppDelegate {+ @objc func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {+ let token = deviceToken.prefix(4).map { String(format: "%02x", $0) }.joined()+ CloudProbe.shared.log("registered for remote notifications (token \(token)…)")+ }++ @objc func application(_ application: NSApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {+ CloudProbe.shared.log("remote notification registration failed: \(error.localizedDescription)")+ }++ @objc func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String: Any]) {+ CloudProbe.shared.handleRemoteNotification(userInfo)+ }+}+#endifdiff --git a/NotchBuddy/Sources/App/ShortcutsSettingsView.swift b/NotchBuddy/Sources/App/ShortcutsSettingsView.swiftindex ce75985f..7856462d 100644--- a/NotchBuddy/Sources/App/ShortcutsSettingsView.swift+++ b/NotchBuddy/Sources/App/ShortcutsSettingsView.swift@@ -27,12 +27,9 @@ struct ShortcutsSettingsView: View {private var globalSection: some View {GroupBox("Global shortcuts — work from any app") {VStack(alignment: .leading, spacing: 0) {- ForEach(ShortcutAction.allCases, id: \.self) { action in- #if APPSTORE- if action.isNonAppStore { EmptyView(); return }- #endif+ ForEach(globalActions, id: \.self) { action inshortcutRow(action)- if action != ShortcutAction.allCases.last {+ if action != globalActions.last {Divider().padding(.leading, 24)}}@@ -49,6 +46,15 @@ struct ShortcutsSettingsView: View {}}+ /// Shortcuts listed here. The App Store build hides the ones it can't run.+ private var globalActions: [ShortcutAction] {+ #if APPSTORE+ ShortcutAction.allCases.filter { !$0.isNonAppStore }+ #else+ ShortcutAction.allCases+ #endif+ }+@ViewBuilderprivate func shortcutRow(_ action: ShortcutAction) -> some View {let isEnabled = enabled[action] ?? action.enabledByDefaultdiff --git a/NotchBuddy/Sources/Phone/CoucouPhoneApp.swift b/NotchBuddy/Sources/Phone/CoucouPhoneApp.swiftnew file mode 100644index 00000000..345bb71c--- /dev/null+++ b/NotchBuddy/Sources/Phone/CoucouPhoneApp.swift@@ -0,0 +1,51 @@+import SwiftUI+import UIKit+import UserNotifications+import CloudKit++// Coucou on iPhone — step 1 spike: a "link test" screen that shows the Pings+// written by the Mac in the shared private CloudKit zone and answers with Pongs.++@main+struct CoucouPhoneApp: App {+ @UIApplicationDelegateAdaptor(PhoneAppDelegate.self) var delegate+ @Environment(\.scenePhase) private var scenePhase++ var body: some Scene {+ WindowGroup {+ LinkTestView(link: PhoneLink.shared)+ }+ .onChange(of: scenePhase) { _, phase in+ if phase == .active { Task { await PhoneLink.shared.refresh() } }+ }+ }+}++final class PhoneAppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {+ func application(_ application: UIApplication,+ didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {+ UNUserNotificationCenter.current().delegate = self+ application.registerForRemoteNotifications()+ Task { await PhoneLink.shared.start() }+ return true+ }++ func application(_ application: UIApplication,+ didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async -> UIBackgroundFetchResult {+ guard CKNotification(fromRemoteNotificationDictionary: userInfo) != nil else { return .noData }+ let gotNew = await PhoneLink.shared.handlePush()+ return gotNew ? .newData : .noData+ }++ func application(_ application: UIApplication,+ didFailToRegisterForRemoteNotificationsWithError error: Error) {+ let message = error.localizedDescription+ Task { @MainActor in PhoneLink.shared.pushError = message }+ }++ // Show the "Ping from your Mac" banner even when the app is open.+ nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,+ willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {+ [.banner, .sound]+ }+}diff --git a/NotchBuddy/Sources/Phone/LinkTestView.swift b/NotchBuddy/Sources/Phone/LinkTestView.swiftnew file mode 100644index 00000000..5cfab38e--- /dev/null+++ b/NotchBuddy/Sources/Phone/LinkTestView.swift@@ -0,0 +1,93 @@+import SwiftUI++struct LinkTestView: View {+ let link: PhoneLink+ @State private var sending = false++ var body: some View {+ NavigationStack {+ List {+ Section {+ statusRow+ if link.notificationsAllowed == false {+ Label("Notifications are off: the \"Ping from your Mac\" banner won't show.",+ systemImage: "bell.slash")+ .foregroundStyle(.secondary)+ }+ if let error = link.pushError {+ Label("Push registration failed: \(error)", systemImage: "exclamationmark.triangle")+ .foregroundStyle(.orange)+ }+ }++ Section {+ Button {+ sending = true+ Task {+ await link.sendPong()+ sending = false+ }+ } label: {+ HStack {+ Text("Send pong")+ if sending { Spacer(); ProgressView() }+ }+ }+ .disabled(link.pings.isEmpty || sending || link.status != .ready)+ if let pong = link.lastPong {+ Text(pong).font(.footnote).foregroundStyle(.secondary)+ }+ }++ Section("Pings from your Mac") {+ if link.pings.isEmpty {+ Text("No ping yet.").foregroundStyle(.secondary)+ }+ ForEach(link.pings) { ping in+ VStack(alignment: .leading, spacing: 4) {+ Text(ping.message.isEmpty ? "Ping" : ping.message)+ HStack {+ Text("\(ping.macName) · \(ping.app)")+ Spacer()+ Text(ping.sentAt, style: .time)+ }+ .font(.caption)+ .foregroundStyle(.secondary)+ Text(delayText(ping))+ .font(.caption.monospacedDigit())+ .foregroundStyle(ping.delay == nil ? Color.secondary : Color.accentColor)+ }+ }+ }+ }+ .navigationTitle("Coucou link test")+ .refreshable { await link.refresh() }+ }+ }++ @ViewBuilder private var statusRow: some View {+ switch link.status {+ case .starting:+ Label("Connecting to iCloud…", systemImage: "icloud")+ case .noAccount(let reason):+ Label("iCloud not connected. \(reason) Sign in in Settings, using the same account as your Mac.",+ systemImage: "icloud.slash")+ .foregroundStyle(.orange)+ case .zoneMissing:+ Label("The Coucou zone doesn't exist yet. Launch Coucou on your Mac (NotchBuddyCloud scheme), then pull to refresh.",+ systemImage: "tray")+ .foregroundStyle(.orange)+ case .ready:+ Label("Linked to iCloud", systemImage: "checkmark.icloud")+ .foregroundStyle(.green)+ case .failed(let message):+ Label(message, systemImage: "exclamationmark.icloud")+ .foregroundStyle(.red)+ }+ }++ private func delayText(_ ping: PingItem) -> String {+ guard let delay = ping.delay else { return "already there at launch" }+ return String(format: "received %.1f s after sending", delay)+ }+}diff --git a/NotchBuddy/Sources/Phone/PhoneLink.swift b/NotchBuddy/Sources/Phone/PhoneLink.swiftnew file mode 100644index 00000000..2a6f699a--- /dev/null+++ b/NotchBuddy/Sources/Phone/PhoneLink.swift@@ -0,0 +1,167 @@+import CloudKit+import Observation+import UIKit+import UserNotifications++/// A Ping written by the Mac, as seen by the iPhone.+struct PingItem: Identifiable {+ let id: CKRecord.ID+ let macName: String+ let app: String+ let message: String+ let sentAt: Date+ /// When this iPhone first saw it. nil for pings that were already there at launch.+ let receivedAt: Date?+ var delay: TimeInterval? { receivedAt.map { $0.timeIntervalSince(sentAt) } }+}++@MainActor+@Observable+final class PhoneLink {+ static let shared = PhoneLink()++ enum Status: Equatable {+ case starting+ case noAccount(String)+ case zoneMissing+ case ready+ case failed(String)+ }++ static let containerID = "iCloud.fr.louisraille.Coucou"+ static let zoneID = CKRecordZone.ID(zoneName: "Coucou", ownerName: CKCurrentUserDefaultName)+ private static let subscriptionID = "coucou-zone-phone"++ var status: Status = .starting+ var pings: [PingItem] = []+ var lastPong: String?+ var pushError: String?+ var notificationsAllowed: Bool?++ @ObservationIgnored private let container = CKContainer(identifier: PhoneLink.containerID)+ @ObservationIgnored private var database: CKDatabase { container.privateCloudDatabase }+ @ObservationIgnored private var changeToken: CKServerChangeToken?+ @ObservationIgnored private var firstFetchDone = false+ @ObservationIgnored private var subscribed = false+ @ObservationIgnored private var fetching = false++ func start() async {+ let center = UNUserNotificationCenter.current()+ notificationsAllowed = (try? await center.requestAuthorization(options: [.alert, .sound, .badge])) ?? false+ await refresh()+ }++ /// Checks the account, makes sure the subscription exists, then fetches new records.+ func refresh() async {+ do {+ let accountStatus = try await container.accountStatus()+ guard accountStatus == .available else {+ status = .noAccount(describe(accountStatus))+ return+ }+ } catch {+ status = .noAccount(error.localizedDescription)+ return+ }+ if !subscribed { await subscribe() }+ _ = await fetchChanges()+ }++ /// Called on a CloudKit push. Returns true when new records arrived.+ func handlePush() async -> Bool {+ await fetchChanges()+ }++ private func subscribe() async {+ let sub = CKDatabaseSubscription(subscriptionID: Self.subscriptionID)+ let info = CKSubscription.NotificationInfo()+ info.title = "Coucou"+ info.alertBody = "Ping from your Mac"+ info.soundName = "default"+ info.shouldSendContentAvailable = true+ sub.notificationInfo = info+ do {+ _ = try await database.modifySubscriptions(saving: [sub], deleting: [])+ subscribed = true+ } catch {+ status = .failed("Subscription: \(error.localizedDescription)")+ }+ }++ @discardableResult+ private func fetchChanges() async -> Bool {+ guard !fetching else { return false }+ fetching = true+ defer { fetching = false }+ var gotNew = false+ do {+ var more = true+ while more {+ let changes = try await database.recordZoneChanges(inZoneWith: Self.zoneID, since: changeToken)+ for (_, result) in changes.modificationResultsByID {+ if case .success(let mod) = result, add(mod.record) { gotNew = true }+ }+ changeToken = changes.changeToken+ more = changes.moreComing+ }+ firstFetchDone = true+ status = .ready+ } catch let error as CKError where error.code == .zoneNotFound || error.code == .userDeletedZone {+ status = .zoneMissing+ } catch let error as CKError where error.code == .changeTokenExpired {+ changeToken = nil+ } catch let error as CKError where error.code == .notAuthenticated {+ status = .noAccount(error.localizedDescription)+ } catch {+ status = .failed(error.localizedDescription)+ }+ pings.sort { $0.sentAt > $1.sentAt }+ return gotNew+ }++ private func add(_ record: CKRecord) -> Bool {+ guard record.recordType == "Ping",+ !pings.contains(where: { $0.id == record.recordID }) else { return false }+ pings.append(PingItem(+ id: record.recordID,+ macName: record["macName"] as? String ?? "Mac",+ app: record["app"] as? String ?? "",+ message: record.encryptedValues["message"] as? String ?? "",+ sentAt: record["sentAt"] as? Date ?? record.creationDate ?? .now,+ receivedAt: firstFetchDone ? .now : nil+ ))+ return true+ }++ /// Writes a Pong linked to the latest Ping.+ func sendPong() async {+ guard let ping = pings.first else { return }+ let record = CKRecord(recordType: "Pong",+ recordID: CKRecord.ID(recordName: UUID().uuidString, zoneID: Self.zoneID))+ let repliedAt = Date()+ record["ping"] = CKRecord.Reference(recordID: ping.id, action: .none)+ record["pingSentAt"] = ping.sentAt+ record["repliedAt"] = repliedAt+ record["deviceName"] = UIDevice.current.name+ record.encryptedValues["message"] = "pong for \"\(ping.message)\""+ do {+ _ = try await database.save(record)+ lastPong = String(format: "Pong saved in %.1f s", Date().timeIntervalSince(repliedAt))+ } catch let error as CKError where error.code == .zoneNotFound {+ status = .zoneMissing+ } catch {+ lastPong = "Pong failed: \(error.localizedDescription)"+ }+ }++ private func describe(_ status: CKAccountStatus) -> String {+ switch status {+ case .available: "available"+ case .noAccount: "No iCloud account on this iPhone."+ case .restricted: "iCloud is restricted on this iPhone."+ case .couldNotDetermine: "Couldn't check the iCloud account."+ case .temporarilyUnavailable: "iCloud is temporarily unavailable."+ @unknown default: "Unknown iCloud status."+ }+ }+}diff --git a/NotchBuddy/project.yml b/NotchBuddy/project.ymlindex 94665882..4f7eb58e 100644--- a/NotchBuddy/project.yml+++ b/NotchBuddy/project.yml@@ -6,6 +6,18 @@ options:xcodeVersion: "27.0"createIntermediateGroups: true+# DebugCloud = Debug, but signed with iCloud (CloudKit) and push entitlements+# and compiled with PHONE_LINK, for the iPhone link spike. ReleaseCloud = the+# same for a Developer ID build with its provisioning profile+# (scripts/cloud-test-build.sh); a Developer ID profile only allows the+# Production CloudKit environment, so the iPhone joins it with the+# CoucouPhoneProduction scheme. Debug and Release are unchanged.+configs:+ Debug: debug+ DebugCloud: debug+ Release: release+ ReleaseCloud: release+settings:base:SWIFT_VERSION: "6.0"@@ -16,6 +28,12 @@ settings:Debug:CODE_SIGNING_REQUIRED: NOCODE_SIGNING_ALLOWED: NO+ DebugCloud:+ CODE_SIGNING_REQUIRED: YES+ CODE_SIGNING_ALLOWED: YES+ CODE_SIGN_STYLE: Automatic+ CODE_SIGN_IDENTITY: "Apple Development"+ DEVELOPMENT_TEAM: 256AUJ9555Release:CODE_SIGNING_REQUIRED: YESCODE_SIGNING_ALLOWED: YES@@ -24,6 +42,13 @@ settings:OTHER_CODE_SIGN_FLAGS: "--timestamp"CODE_SIGN_INJECT_BASE_ENTITLEMENTS: NOCODE_SIGN_ENTITLEMENTS: Resources/Coucou.entitlements+ ReleaseCloud:+ CODE_SIGNING_REQUIRED: YES+ CODE_SIGNING_ALLOWED: YES+ CODE_SIGN_IDENTITY: "Developer ID Application"+ DEVELOPMENT_TEAM: 256AUJ9555+ OTHER_CODE_SIGN_FLAGS: "--timestamp"+ CODE_SIGN_INJECT_BASE_ENTITLEMENTS: NOschemes:NotchBuddy:@@ -42,6 +67,40 @@ schemes:config: Debugarchive:config: Release+ NotchBuddyCloud:+ build:+ targets:+ NotchBuddy: all+ run:+ config: DebugCloud+ archive:+ config: Release+ CoucouAppStoreCloud:+ build:+ targets:+ CoucouAppStore: all+ run:+ config: DebugCloud+ archive:+ config: Release+ CoucouPhone:+ build:+ targets:+ CoucouPhone: all+ run:+ config: Debug+ archive:+ config: Release+ # Same iPhone app on the Production CloudKit environment, to talk to the+ # Developer ID build (scripts/cloud-test-build.sh), which can only use Production.+ CoucouPhoneProduction:+ build:+ targets:+ CoucouPhone: all+ run:+ config: DebugCloud+ archive:+ config: Releasetargets:NotchBuddy:@@ -50,6 +109,8 @@ targets:sources:- path: Sourcestype: group+ excludes:+ - "Phone/**"- path: Assets.xcassetsbuildPhase: resources- path: Resources/sounds@@ -79,6 +140,14 @@ targets:ASSETCATALOG_COMPILER_APPICON_NAME: AppIconMACOSX_DEPLOYMENT_TARGET: "15.0"ENABLE_SANDBOX: NO+ configs:+ DebugCloud:+ CODE_SIGN_ENTITLEMENTS: Resources/CoucouCloud.entitlements+ SWIFT_ACTIVE_COMPILATION_CONDITIONS: "DEBUG PHONE_LINK"+ ReleaseCloud:+ CODE_SIGN_ENTITLEMENTS: Resources/CoucouReleaseCloud.entitlements+ SWIFT_ACTIVE_COMPILATION_CONDITIONS: PHONE_LINK+ PROVISIONING_PROFILE_SPECIFIER: "Coucou Developer ID"CoucouAppStore:type: application@@ -86,6 +155,8 @@ targets:sources:- path: Sourcestype: group+ excludes:+ - "Phone/**"- path: Assets.xcassetsbuildPhase: resources- path: Resources/sounds@@ -120,3 +191,52 @@ targets:DEVELOPMENT_TEAM: 256AUJ9555SWIFT_ACTIVE_COMPILATION_CONDITIONS: APPSTORECODE_SIGNING_ALLOWED: YES+ configs:+ DebugCloud:+ CODE_SIGN_ENTITLEMENTS: Resources/CoucouAppStoreCloud.entitlements+ SWIFT_ACTIVE_COMPILATION_CONDITIONS: "APPSTORE PHONE_LINK"++ # iPhone app. Same bundle ID as the Mac App Store build, for universal purchase.+ CoucouPhone:+ type: application+ platform: iOS+ deploymentTarget: "18.0"+ sources:+ - path: Sources/Phone+ type: group+ info:+ path: Resources/InfoPhone.plist+ properties:+ CFBundleName: Coucou+ CFBundleDisplayName: Coucou+ CFBundleIdentifier: fr.louisraille.Coucou+ CFBundleVersion: "1"+ CFBundleShortVersionString: "0.1"+ CFBundlePackageType: APPL+ LSRequiresIPhoneOS: YES+ UILaunchScreen: {}+ UIApplicationSupportsIndirectInputEvents: YES+ UIBackgroundModes:+ - remote-notification+ UISupportedInterfaceOrientations:+ - UIInterfaceOrientationPortrait+ ITSAppUsesNonExemptEncryption: NO+ settings:+ base:+ PRODUCT_BUNDLE_IDENTIFIER: fr.louisraille.Coucou+ PRODUCT_NAME: Coucou+ INFOPLIST_FILE: Resources/InfoPhone.plist+ IPHONEOS_DEPLOYMENT_TARGET: "18.0"+ TARGETED_DEVICE_FAMILY: "1"+ SUPPORTS_MACCATALYST: NO+ CODE_SIGN_STYLE: Automatic+ CODE_SIGN_IDENTITY: "Apple Development"+ CODE_SIGN_ENTITLEMENTS: Resources/CoucouPhone.entitlements+ DEVELOPMENT_TEAM: 256AUJ9555+ CODE_SIGNING_REQUIRED: YES+ CODE_SIGNING_ALLOWED: YES+ ENABLE_HARDENED_RUNTIME: NO+ OTHER_CODE_SIGN_FLAGS: ""+ configs:+ DebugCloud:+ CODE_SIGN_ENTITLEMENTS: Resources/CoucouPhoneProduction.entitlementsdiff --git a/scripts/cloud-test-build.sh b/scripts/cloud-test-build.shnew file mode 100755index 00000000..7491313a--- /dev/null+++ b/scripts/cloud-test-build.sh@@ -0,0 +1,89 @@+#!/usr/bin/env bash+# iPhone plan, step 2: builds the GitHub app (fr.louisraille.NotchBuddy) the+# way release.sh does — Release optimizations, Developer ID signature — plus+# the "Coucou Developer ID" provisioning profile, the iCloud entitlements and+# the PHONE_LINK probe. Not notarized, not published: it only proves that a+# Developer ID build can talk to iCloud. A Developer ID profile only allows the+# Production CloudKit environment: the Ping/Pong schema must be deployed to+# Production in the CloudKit Console first.+#+# ./scripts/cloud-test-build.sh+#+# The normal release (scripts/release.sh, Release configuration) is unchanged.+set -euo pipefail++REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+BUILD_DIR="/tmp/coucou-cloud-test"+APP="$BUILD_DIR/Coucou.app"+PROFILE_NAME="Coucou Developer ID"+APP_ID="256AUJ9555.fr.louisraille.NotchBuddy"+CONTAINER="iCloud.fr.louisraille.Coucou"++die() { echo "error: $*" >&2; exit 1; }++# ── 1. Developer ID identity ──────────────────────────────────────────────────+IDENTITY=$(security find-identity -v -p codesigning | grep "Developer ID Application" | head -1 | sed 's/.*"\(Developer ID Application[^"]*\)".*/\1/' || true)+[ -n "$IDENTITY" ] || die "no 'Developer ID Application' certificate found. Install it via Xcode → Settings → Accounts."+echo "Signing with: $IDENTITY"++# ── 2. Provisioning profile ───────────────────────────────────────────────────+# Xcode looks in both folders depending on its version. Double-clicking a+# downloaded .provisionprofile on macOS doesn't reliably put it in either.+TMP_PLIST=$(mktemp)+trap 'rm -f "$TMP_PLIST"' EXIT+FOUND=""+for dir in "$HOME/Library/Developer/Xcode/UserData/Provisioning Profiles" "$HOME/Library/MobileDevice/Provisioning Profiles"; do+ [ -d "$dir" ] || continue+ for f in "$dir"/*.provisionprofile; do+ [ -f "$f" ] || continue+ security cms -D -i "$f" > "$TMP_PLIST" 2>/dev/null || continue+ NAME=$(/usr/libexec/PlistBuddy -c "Print :Name" "$TMP_PLIST" 2>/dev/null || true)+ [ "$NAME" = "$PROFILE_NAME" ] || continue+ FOUND="$f"+ break 2+ done+done+[ -n "$FOUND" ] || die "no provisioning profile named '$PROFILE_NAME' is installed.+ developer.apple.com → Profiles → + → Developer ID → App ID fr.louisraille.NotchBuddy,+ name it exactly '$PROFILE_NAME' and download it. Then copy it for Xcode:+ mkdir -p ~/Library/Developer/Xcode/UserData/Provisioning\\ Profiles+ cp ~/Downloads/*.provisionprofile ~/Library/Developer/Xcode/UserData/Provisioning\\ Profiles/"+echo "Profile: $FOUND"++PROFILE_APP_ID=$(/usr/libexec/PlistBuddy -c "Print :Entitlements:com.apple.application-identifier" "$TMP_PLIST" 2>/dev/null || true)+[ "$PROFILE_APP_ID" = "$APP_ID" ] || die "the profile is for '$PROFILE_APP_ID', not $APP_ID"+/usr/libexec/PlistBuddy -c "Print :Entitlements:com.apple.developer.icloud-container-identifiers" "$TMP_PLIST" 2>/dev/null | grep -q "$CONTAINER" \+ || die "the profile has no iCloud container $CONTAINER. Turn on iCloud (CloudKit, with that container) on the App ID fr.louisraille.NotchBuddy, then regenerate and reinstall the profile."+EXPIRY=$(/usr/libexec/PlistBuddy -c "Print :ExpirationDate" "$TMP_PLIST")+echo "Profile expires: $EXPIRY"++# ── 3. Build ──────────────────────────────────────────────────────────────────+cd "$REPO_ROOT/NotchBuddy"+xcodegen generate+rm -rf "$BUILD_DIR" && mkdir -p "$BUILD_DIR"+xcodebuild \+ -project NotchBuddy.xcodeproj \+ -scheme NotchBuddy \+ -configuration ReleaseCloud \+ build \+ CODE_SIGN_IDENTITY="$IDENTITY" \+ CONFIGURATION_BUILD_DIR="$BUILD_DIR" \+ -quiet \+ || die "the build failed (see the errors above)"++# ── 4. Checks ─────────────────────────────────────────────────────────────────+[ -f "$APP/Contents/embedded.provisionprofile" ] || die "the profile was not embedded in the app"+codesign --verify --deep --strict "$APP" || die "the signature does not verify"+echo+echo "Entitlements of the built app:"+codesign -d --entitlements - --xml "$APP" 2>/dev/null | plutil -p - || true++echo+echo "✓ Built $APP (Developer ID, not notarized)."+echo+echo "To test:"+echo " 1. Quit any other Coucou (menu bar icon → Quit) and stop it in Xcode."+echo " 2. open $APP"+echo " 3. tail -f ~/Library/Logs/NotchBuddy/nb.log | grep PhoneLink"+echo " 4. Developer ID builds use the Production CloudKit environment: run the iPhone"+echo " app with the CoucouPhoneProduction scheme, pull to refresh, then tap Send pong."