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 7: allow or deny from the iPhone (#220)
Louis1c65e8bc8f76
diff --git a/NotchBuddy/Resources/InfoPhone.plist b/NotchBuddy/Resources/InfoPhone.plistindex 23a20f93..0e024308 100644--- a/NotchBuddy/Resources/InfoPhone.plist+++ b/NotchBuddy/Resources/InfoPhone.plist@@ -24,6 +24,8 @@<false/><key>LSRequiresIPhoneOS</key><true/>+ <key>NSFaceIDUsageDescription</key>+ <string>Coucou asks for Face ID before allowing a command from your iPhone.</string><key>UIApplicationSupportsIndirectInputEvents</key><true/><key>UIBackgroundModes</key>diff --git a/NotchBuddy/Sources/App/PhoneLink/ApprovalRelay.swift b/NotchBuddy/Sources/App/PhoneLink/ApprovalRelay.swiftnew file mode 100644index 00000000..0f528469--- /dev/null+++ b/NotchBuddy/Sources/App/PhoneLink/ApprovalRelay.swift@@ -0,0 +1,163 @@+#if PHONE_LINK+import AppKit+import CloudKit+import Combine+import CryptoKit++// MARK: - iPhone plan, step 7: approve or deny from the iPhone+//+// While Claude Code (or Cursor, Codex) waits for a permission:+// 1. an `ApprovalRequest` record goes to iCloud; the iPhone's query subscription+// turns it into a notification;+// 2. the Mac looks for a `Decision` record every 2 s — only while a request is+// pending, so nothing runs at rest;+// 3. a decision is applied only if its fingerprint matches the request still+// pending (same session, tool, command and input). A late decision, or one+// meant for another command, is ignored. Only "allow" and "deny" exist: no+// "always" from the phone.+// The request record is deleted as soon as the approval is resolved, on either side.++@MainActor+final class ApprovalRelay {+ static let shared = ApprovalRelay()++ private let container = CKContainer(identifier: "iCloud.fr.louisraille.Coucou")+ private var database: CKDatabase { container.privateCloudDatabase }+ private var zoneID: CKRecordZone.ID { SessionSnapshot.zoneID }++ private var cancellable: AnyCancellable?+ private var current: (fingerprint: String, since: Date)?+ private var pollTask: Task<Void, Never>?+ private var changeToken: CKServerChangeToken?++ /// Stable identifier of one pending request.+ nonisolated static func fingerprint(_ approval: ApprovalInfo) -> String {+ let raw = [approval.pillId, approval.sessionId, approval.tool, approval.command, approval.inputKey]+ .joined(separator: "\u{1F}")+ return SHA256.hash(data: Data(raw.utf8)).map { String(format: "%02x", $0) }.joined()+ }++ func start() {+ guard cancellable == nil else { return }+ // @Published sends the new value before the property changes, so the+ // value is passed along rather than read back from AppState.+ cancellable = AppState.shared.$pendingApproval+ .removeDuplicates { $0.map(Self.fingerprint) == $1.map(Self.fingerprint) }+ .sink { [weak self] approval in+ MainActor.assumeIsolated { self?.pendingChanged(to: approval) }+ }+ log("relay on")+ }++ func stop() {+ cancellable = nil+ pendingChanged(to: nil)+ }++ // MARK: Request lifecycle++ private func pendingChanged(to approval: ApprovalInfo?) {+ let fingerprint = approval.map(Self.fingerprint)+ if let old = current, old.fingerprint != fingerprint {+ pollTask?.cancel()+ pollTask = nil+ current = nil+ let id = requestID(old.fingerprint)+ Task { _ = try? await database.modifyRecords(saving: [], deleting: [id]) }+ }+ guard let fingerprint, let approval, current?.fingerprint != fingerprint else { return }+ current = (fingerprint, Date())+ Task { await publishRequest(approval, fingerprint: fingerprint) }+ pollTask = Task { [weak self] in+ // The Mac dismisses the request after 115 s anyway.+ for _ in 0..<60 {+ try? await Task.sleep(for: .seconds(2))+ guard !Task.isCancelled, let self else { return }+ if await self.checkDecisions(for: fingerprint) { return }+ }+ }+ }++ private func requestID(_ fingerprint: String) -> CKRecord.ID {+ CKRecord.ID(recordName: "approval-\(fingerprint.prefix(32))", zoneID: zoneID)+ }++ private func publishRequest(_ approval: ApprovalInfo, fingerprint: String) async {+ let record = CKRecord(recordType: "ApprovalRequest", recordID: requestID(fingerprint))+ record["pillId"] = approval.pillId+ record["fingerprint"] = fingerprint+ record["createdAt"] = Date()+ record.encryptedValues["tool"] = approval.tool+ record.encryptedValues["command"] = approval.command+ do {+ _ = try await database.modifyRecords(saving: [record], deleting: [], savePolicy: .allKeys)+ log("approval request sent to the iPhone (\(approval.tool))")+ } catch {+ log("approval request failed: \(error.localizedDescription)")+ }+ }++ // MARK: Decisions++ /// Returns true once a matching decision was applied.+ private func checkDecisions(for fingerprint: String) async -> Bool {+ guard current?.fingerprint == fingerprint, let since = current?.since else { return true }+ var found: [(CKRecord.ID, String, String)] = [] // id, fingerprint, decision+ do {+ var more = true+ while more {+ let changes = try await database.recordZoneChanges(inZoneWith: zoneID, since: changeToken)+ for (id, result) in changes.modificationResultsByID {+ guard case .success(let mod) = result, mod.record.recordType == "Decision" else { continue }+ let record = mod.record+ let decidedAt = record["decidedAt"] as? Date ?? .distantPast+ guard decidedAt >= since.addingTimeInterval(-5) else { continue }+ found.append((id, record["fingerprint"] as? String ?? "", record["decision"] as? String ?? ""))+ }+ changeToken = changes.changeToken+ more = changes.moreComing+ }+ } catch let error as CKError where error.code == .changeTokenExpired {+ changeToken = nil+ return false+ } catch {+ log("decision check failed: \(error.localizedDescription)")+ return false+ }+ guard !found.isEmpty else { return false }+ // Decisions are single use.+ let ids = found.map(\.0)+ Task { _ = try? await database.modifyRecords(saving: [], deleting: ids) }++ guard let match = found.first(where: { $0.1 == fingerprint }) else {+ log("ignored \(found.count) decision(s) for another request")+ return false+ }+ apply(match.2, fingerprint: fingerprint)+ return true+ }++ private func apply(_ decision: String, fingerprint: String) {+ // Check again on the main actor, right before answering the hook.+ guard let pending = AppState.shared.pendingApproval,+ Self.fingerprint(pending) == fingerprint else {+ log("decision arrived after the request was resolved, ignored")+ return+ }+ switch decision {+ case "allow":+ log("allowed from the iPhone: \(pending.tool)")+ HookServer.shared.sendApprovalDecision("allow")+ case "deny":+ log("denied from the iPhone: \(pending.tool)")+ HookServer.shared.sendApprovalDecision("deny")+ default:+ log("unknown decision '\(decision)', ignored")+ }+ }++ private func log(_ message: String) {+ CloudProbe.shared.log("[approval] \(message)")+ }+}+#endifdiff --git a/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift b/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swiftindex 43d48ed2..b5771c61 100644--- a/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift+++ b/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift@@ -70,6 +70,7 @@ final class CloudProbe {pollTask?.cancel(); pollTask = nilNSApplication.shared.unregisterForRemoteNotifications()SessionPublisher.shared.stop()+ ApprovalRelay.shared.stop()log("iPhone sync off")}@@ -84,6 +85,7 @@ final class CloudProbe {log("starting (\(appLabel), \(build) build, container \(Self.containerID))")NSApplication.shared.registerForRemoteNotifications()SessionPublisher.shared.start()+ ApprovalRelay.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).diff --git a/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift b/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swiftindex 5bbda7a9..65032fd7 100644--- a/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift+++ b/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift@@ -168,6 +168,7 @@ struct SessionSnapshot: Equatable {let finalLine: Stringlet approvalTool: Stringlet approvalCommand: String+ let approvalFingerprint: Stringlet question: Stringstatic func all(tasks: [AgentTask], approval: ApprovalInfo?,@@ -189,6 +190,7 @@ struct SessionSnapshot: Equatable {finalLine: task.finalLine ?? "",approvalTool: hasApproval ? (approval?.tool ?? "") : "",approvalCommand: hasApproval ? (approval?.command ?? "") : "",+ approvalFingerprint: hasApproval ? (approval.map(ApprovalRelay.fingerprint) ?? "") : "",question: questionText)}return result@@ -196,7 +198,7 @@ struct SessionSnapshot: Equatable {static func placeholder(pillId: String) -> SessionSnapshot {SessionSnapshot(pillId: pillId, name: "", color: "", state: "", stepIndex: -1, steps: [],- cwd: "", finalLine: "", approvalTool: "", approvalCommand: "", question: "")+ cwd: "", finalLine: "", approvalTool: "", approvalCommand: "", approvalFingerprint: "", question: "")}/// Same zone as CloudProbe.zoneID, rebuilt here because that one is main-actor isolated.@@ -222,6 +224,8 @@ struct SessionSnapshot: Equatable {record["stepIndex"] = stepIndexrecord["stepCount"] = steps.countrecord["needsApproval"] = !approvalCommand.isEmpty || !approvalTool.isEmpty+ // Identifies the exact request; the iPhone sends it back with its decision.+ record["approvalFingerprint"] = approvalFingerprintrecord["needsAnswer"] = !question.isEmptyrecord["updatedAt"] = Date()record["macName"] = Host.current().localizedName ?? ""diff --git a/NotchBuddy/Sources/Phone/ApprovalCard.swift b/NotchBuddy/Sources/Phone/ApprovalCard.swiftnew file mode 100644index 00000000..25111d5e--- /dev/null+++ b/NotchBuddy/Sources/Phone/ApprovalCard.swift@@ -0,0 +1,156 @@+import SwiftUI++/// The command an agent waits on, with Allow (Face ID) and Deny.+/// Used in the session screen and in the sheet opened from a notification.+struct ApprovalCard: View {+ let link: PhoneLink+ let session: SessionItem++ @State private var sending: Decision?+ @State private var sent: Decision?+ @State private var error: String?++ var body: some View {+ VStack(alignment: .leading, spacing: 10) {+ Text("Waiting for your OK").font(.subheadline.weight(.semibold)).foregroundStyle(.orange)+ Text(session.approvalCommand.isEmpty ? "The agent asks for a permission." : session.approvalCommand)+ .font(.callout.monospaced())+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(12)+ .background(Color(white: 0.16), in: RoundedRectangle(cornerRadius: 12))+ .textSelection(.enabled)+ if let sent {+ Label(sent == .allow ? "Allowed, sent to your Mac" : "Denied, sent to your Mac",+ systemImage: sent == .allow ? "checkmark.circle.fill" : "xmark.circle.fill")+ .font(.callout.weight(.semibold))+ .foregroundStyle(sent == .allow ? .green : .red)+ } else if session.approvalFingerprint.isEmpty {+ Text("Answer on your Mac. This request can't be answered from the iPhone.")+ .font(.caption).foregroundStyle(.secondary)+ } else {+ HStack(spacing: 10) {+ Button(role: .destructive) { Task { await send(.deny) } } label: {+ Label("Deny", systemImage: "xmark")+ .frame(maxWidth: .infinity)+ }+ .buttonStyle(.bordered)+ .tint(.red)+ Button { Task { await send(.allow) } } label: {+ Label("Allow", systemImage: "faceid")+ .frame(maxWidth: .infinity)+ }+ .buttonStyle(.borderedProminent)+ .tint(.green)+ }+ .controlSize(.large)+ .disabled(sending != nil)+ Text("Allow asks for Face ID. The request expires after 2 minutes.")+ .font(.caption).foregroundStyle(.secondary)+ }+ if let error {+ Text(error).font(.caption).foregroundStyle(.red)+ }+ }+ .padding(16)+ .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))+ .overlay(RoundedRectangle(cornerRadius: 22).strokeBorder(Color.orange.opacity(0.7), lineWidth: 1.5))+ .onChange(of: session.approvalFingerprint) { sent = nil; error = nil }+ }++ private func send(_ decision: Decision) async {+ sending = decision+ defer { sending = nil }+ error = nil+ if decision == .allow {+ guard await OwnerCheck.confirm(reason: "Allow this command on your Mac") else {+ error = "Face ID didn't confirm. Nothing was sent."+ return+ }+ }+ let summary = session.approvalCommand.isEmpty ? "Permission" : session.approvalCommand+ if await link.decide(decision, fingerprint: session.approvalFingerprint, pillId: session.id,+ summary: String(summary.prefix(200))) {+ sent = decision+ } else {+ error = link.lastPong ?? "Couldn't reach iCloud."+ }+ }+}++/// Opened from the "Review" action of an approval notification.+struct ReviewSheet: View {+ let link: PhoneLink+ let fingerprint: String+ @Environment(\.dismiss) private var dismiss++ private var session: SessionItem? { link.sessions.first { $0.approvalFingerprint == fingerprint } }++ var body: some View {+ NavigationStack {+ ScrollView {+ VStack(alignment: .leading, spacing: 16) {+ if let session {+ HStack(spacing: 12) {+ MochiStill(state: session.state)+ .padding(6)+ .frame(width: 52, height: 52)+ .background(Color.mochiTile(hex: session.color), in: RoundedRectangle(cornerRadius: 14))+ VStack(alignment: .leading, spacing: 2) {+ Text("\(session.pillName) · \(session.title)").font(.headline)+ if !session.macName.isEmpty {+ Text(session.macName).font(.caption).foregroundStyle(.secondary)+ }+ }+ }+ ApprovalCard(link: link, session: session)+ } else {+ Text("This request was already answered or has expired.")+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity)+ .padding(40)+ }+ }+ .padding(16)+ }+ .background(Color.black)+ .navigationTitle("Review")+ .navigationBarTitleDisplayMode(.inline)+ .toolbar {+ ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } }+ }+ .refreshable { await link.refresh() }+ }+ }+}++/// Decisions taken on this iPhone.+struct HistoryView: View {+ let link: PhoneLink++ var body: some View {+ List {+ if link.history.isEmpty {+ Text("No decision yet.").foregroundStyle(.secondary)+ }+ ForEach(link.history) { log in+ HStack(alignment: .firstTextBaseline, spacing: 10) {+ Image(systemName: log.decision == .allow ? "checkmark.circle.fill" : "xmark.circle.fill")+ .foregroundStyle(log.decision == .allow ? .green : .red)+ VStack(alignment: .leading, spacing: 2) {+ Text(log.summary)+ .font(.callout.monospaced())+ .lineLimit(3)+ HStack(spacing: 4) {+ Text(PillCatalog.definition(for: log.pillId)?.name ?? log.pillId)+ Text("·")+ Text(log.date, format: .dateTime.day().month().hour().minute())+ }+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ }+ }+ }+ .navigationTitle("History")+ }+}diff --git a/NotchBuddy/Sources/Phone/CoucouPhoneApp.swift b/NotchBuddy/Sources/Phone/CoucouPhoneApp.swiftindex e2a7ea00..94e1482f 100644--- a/NotchBuddy/Sources/Phone/CoucouPhoneApp.swift+++ b/NotchBuddy/Sources/Phone/CoucouPhoneApp.swift@@ -26,6 +26,7 @@ final class PhoneAppDelegate: NSObject, UIApplicationDelegate, UNUserNotificatiofunc application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {UNUserNotificationCenter.current().delegate = self+ ApprovalActions.register()application.registerForRemoteNotifications()Task { await PhoneLink.shared.start() }return true@@ -44,9 +45,45 @@ final class PhoneAppDelegate: NSObject, UIApplicationDelegate, UNUserNotificatioTask { @MainActor in PhoneLink.shared.pushError = message }}- // Show the "Ping from your Mac" banner even when the app is open.+ // Approval notification actions.+ nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,+ didReceive response: UNNotificationResponse) async {+ let request = response.notification.request+ guard let fingerprint = PhoneLink.approvalFingerprint(in: request) else { return }+ let note = CKNotification(fromRemoteNotificationDictionary: request.content.userInfo) as? CKQueryNotification+ let pillId = request.content.userInfo["pillId"] as? String+ ?? note?.recordFields?["pillId"] as? String ?? ""+ let denied = response.actionIdentifier == ApprovalActions.deny+ await Self.handleApproval(denied: denied, fingerprint: fingerprint, pillId: pillId)+ }++ @MainActor+ private static func handleApproval(denied: Bool, fingerprint: String, pillId: String) async {+ let link = PhoneLink.shared+ link.noteICloudAlert(fingerprint)+ if denied {+ // Awaited so the decision is saved before iOS suspends the app again.+ let summary = link.sessions.first { $0.approvalFingerprint == fingerprint }?.approvalCommand+ _ = await link.decide(.deny, fingerprint: fingerprint, pillId: pillId,+ summary: summary ?? "Denied from the notification")+ } else {+ // Review, or a tap on the notification: open the command, Allow needs Face ID there.+ await link.refresh()+ link.reviewFingerprint = fingerprint+ }+ }++ // Show banners even when the app is open.nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {- [.banner, .sound]+ // One banner per approval: skip the iCloud alert if the local one is already there.+ let request = notification.request+ if let fingerprint = PhoneLink.approvalFingerprint(in: request),+ request.identifier != PhoneLink.approvalNotificationID(fingerprint) {+ let localID = PhoneLink.approvalNotificationID(fingerprint)+ await MainActor.run { PhoneLink.shared.noteICloudAlert(fingerprint) }+ if await PhoneLink.shownApprovals().contains(where: { $0.id == localID }) { return [] }+ }+ return [.banner, .sound]}}diff --git a/NotchBuddy/Sources/Phone/Decisions.swift b/NotchBuddy/Sources/Phone/Decisions.swiftnew file mode 100644index 00000000..fb4cc338--- /dev/null+++ b/NotchBuddy/Sources/Phone/Decisions.swift@@ -0,0 +1,56 @@+import Foundation+import LocalAuthentication+import UserNotifications++enum Decision: String, Codable, Sendable {+ case allow, deny+}++/// One decision taken on this iPhone (kept on the iPhone only).+struct DecisionLog: Codable, Identifiable, Sendable {+ var id = UUID()+ let decision: Decision+ let pillId: String+ let summary: String // the command, shortened+ let date: Date++ private static let key = "decisionHistory"++ static func load() -> [DecisionLog] {+ guard let data = UserDefaults.standard.data(forKey: key),+ let logs = try? JSONDecoder().decode([DecisionLog].self, from: data) else { return [] }+ return logs+ }++ static func save(_ logs: [DecisionLog]) {+ if let data = try? JSONEncoder().encode(logs) { UserDefaults.standard.set(data, forKey: key) }+ }+}++/// Notification actions for approval requests. "Review" opens the app on the+/// command (Allow needs Face ID there); "Deny" works from the notification.+enum ApprovalActions {+ static let category = "COUCOU_APPROVAL"+ static let review = "COUCOU_REVIEW"+ static let deny = "COUCOU_DENY"++ static func register() {+ let review = UNNotificationAction(identifier: review, title: "Review",+ options: [.foreground, .authenticationRequired])+ let deny = UNNotificationAction(identifier: deny, title: "Deny",+ options: [.destructive, .authenticationRequired])+ let category = UNNotificationCategory(identifier: category, actions: [review, deny],+ intentIdentifiers: [], options: [])+ UNUserNotificationCenter.current().setNotificationCategories([category])+ }+}++/// Face ID (or the passcode) before allowing a command. Never skipped.+enum OwnerCheck {+ static func confirm(reason: String) async -> Bool {+ let context = LAContext()+ var error: NSError?+ guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else { return false }+ return (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) ?? false+ }+}diff --git a/NotchBuddy/Sources/Phone/HomeView.swift b/NotchBuddy/Sources/Phone/HomeView.swiftindex 7bbed7c6..bfd8aec9 100644--- a/NotchBuddy/Sources/Phone/HomeView.swift+++ b/NotchBuddy/Sources/Phone/HomeView.swift@@ -37,7 +37,20 @@ struct HomeView: View {.navigationDestination(for: String.self) { id inSessionDetailView(link: link, sessionId: id)}+ .sheet(isPresented: Binding(get: { link.reviewFingerprint != nil },+ set: { if !$0 { link.reviewFingerprint = nil } })) {+ if let fingerprint = link.reviewFingerprint {+ ReviewSheet(link: link, fingerprint: fingerprint)+ }+ }.toolbar {+ ToolbarItem(placement: .topBarLeading) {+ NavigationLink {+ HistoryView(link: link)+ } label: {+ Image(systemName: "clock.arrow.circlepath")+ }+ }// Step 1-3 test screens (the link test has its own "Kit" button).ToolbarItem(placement: .topBarTrailing) {NavigationLink {diff --git a/NotchBuddy/Sources/Phone/LinkTestView.swift b/NotchBuddy/Sources/Phone/LinkTestView.swiftindex 79ad9742..78047732 100644--- a/NotchBuddy/Sources/Phone/LinkTestView.swift+++ b/NotchBuddy/Sources/Phone/LinkTestView.swift@@ -13,6 +13,7 @@ struct LinkTestView: View {systemImage: "bell.slash").foregroundStyle(.secondary)}+ LabeledContent("Approval notifications", value: link.approvalsStatus)if let error = link.pushError {Label("Push registration failed: \(error)", systemImage: "exclamationmark.triangle").foregroundStyle(.orange)diff --git a/NotchBuddy/Sources/Phone/PhoneLink.swift b/NotchBuddy/Sources/Phone/PhoneLink.swiftindex 93bbe09e..daa58dac 100644--- a/NotchBuddy/Sources/Phone/PhoneLink.swift+++ b/NotchBuddy/Sources/Phone/PhoneLink.swift@@ -26,6 +26,7 @@ struct SessionItem: Identifiable {let steps: [String]let needsApproval: Boollet approvalCommand: String+ let approvalFingerprint: Stringlet question: Stringlet finalLine: Stringlet cwd: String@@ -41,6 +42,7 @@ struct SessionItem: Identifiable {steps = record.encryptedValues["steps"] as? [String] ?? []needsApproval = record["needsApproval"] as? Bool ?? falseapprovalCommand = record.encryptedValues["approvalCommand"] as? String ?? ""+ approvalFingerprint = record["approvalFingerprint"] as? String ?? ""question = record.encryptedValues["question"] as? String ?? ""finalLine = record.encryptedValues["finalLine"] as? String ?? ""cwd = record.encryptedValues["cwd"] as? String ?? ""@@ -84,6 +86,7 @@ final class PhoneLink {@ObservationIgnored private var changeToken: CKServerChangeToken?@ObservationIgnored private var firstFetchDone = false@ObservationIgnored private var subscribed = false+ @ObservationIgnored private var approvalsSubscribed = false@ObservationIgnored private var fetching = falsefunc start() async {@@ -105,18 +108,22 @@ final class PhoneLink {return}if !subscribed { await subscribe() }+ if subscribed && !approvalsSubscribed { await subscribeToApprovals() }_ = await fetchChanges()+ await notifyNewApprovals()}/// Called on a CloudKit push. Returns true when new records arrived.func handlePush() async -> Bool {- await fetchChanges()+ let gotNew = await fetchChanges()+ await notifyNewApprovals()+ return gotNew}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.+ // Silent: the Mac writes on every session change, a banner each time+ // would be noise. Approvals have their own subscription below.let info = CKSubscription.NotificationInfo()info.shouldSendContentAvailable = truesub.notificationInfo = info@@ -128,6 +135,47 @@ final class PhoneLink {}}+ /// A visible notification for each approval request the Mac sends+ /// (ApprovalRelay), with Review and Deny actions. Kept apart from the+ /// silent subscription so a failure here never stops the sessions.+ private func subscribeToApprovals() async {+ let approvals = CKQuerySubscription(recordType: "ApprovalRequest", predicate: NSPredicate(value: true),+ subscriptionID: "coucou-approvals", options: [.firesOnRecordCreation])+ approvals.zoneID = Self.zoneID+ let alert = CKSubscription.NotificationInfo()+ alert.title = "Coucou"+ alert.alertBody = "An agent is waiting for your OK"+ alert.soundName = "default"+ alert.category = ApprovalActions.category+ alert.shouldSendContentAvailable = true+ alert.desiredKeys = ["fingerprint", "pillId"]+ approvals.notificationInfo = alert+ do {+ _ = try await database.modifySubscriptions(saving: [approvals], deleting: [])+ approvalsSubscribed = true+ approvalsStatus = "On"+ } catch {+ // In the Development environment a query subscription needs the+ // record type to exist: create it once with a throwaway record.+ let seed = CKRecord(recordType: "ApprovalRequest",+ recordID: CKRecord.ID(recordName: "approval-schema", zoneID: Self.zoneID))+ seed["pillId"] = ""+ seed["fingerprint"] = ""+ seed["createdAt"] = Date()+ seed.encryptedValues["tool"] = ""+ seed.encryptedValues["command"] = ""+ do {+ _ = try await database.modifyRecords(saving: [seed], deleting: [], savePolicy: .allKeys)+ _ = try await database.modifyRecords(saving: [], deleting: [seed.recordID])+ _ = try await database.modifySubscriptions(saving: [approvals], deleting: [])+ approvalsSubscribed = true+ approvalsStatus = "On (record type created)"+ } catch {+ approvalsStatus = "Failed: \(error.localizedDescription)"+ }+ }+ }+@discardableResultprivate func fetchChanges() async -> Bool {guard !fetching else { return false }@@ -185,6 +233,115 @@ final class PhoneLink {return true}+ // MARK: Approval notifications (step 7)++ /// State of the "coucou-approvals" subscription, shown on the link test screen.+ var approvalsStatus = "Not set up yet"+ @ObservationIgnored private var notifiedFingerprints: Set<String> = []++ nonisolated static func approvalNotificationID(_ fingerprint: String) -> String { "approval-\(fingerprint)" }++ /// The iCloud alert for an approval doesn't always come. The silent push+ /// that updates the sessions does, so a new approval also gets a local+ /// notification, unless the iCloud one came, or the app is open.+ /// Notifications for requests no longer pending are removed.+ private func notifyNewApprovals() async {+ await removeAnsweredNotifications()+ let fresh = sessions.filter {+ $0.needsApproval && !$0.approvalFingerprint.isEmpty && !notifiedFingerprints.contains($0.approvalFingerprint)+ }+ guard !fresh.isEmpty else { return }+ fresh.forEach { notifiedFingerprints.insert($0.approvalFingerprint) }+ // The app is open: the request is on screen.+ guard UIApplication.shared.applicationState != .active else { return }+ // Give the iCloud alert a moment to land first, then check the request still waits.+ try? await Task.sleep(for: .seconds(3))+ _ = await fetchChanges()+ let shown = await Self.shownApprovals().map { $0.fingerprint }+ for session in fresh where !shown.contains(session.approvalFingerprint) {+ guard pendingFingerprints.contains(session.approvalFingerprint),+ !iCloudAlerted.contains(session.approvalFingerprint) else { continue }+ let content = UNMutableNotificationContent()+ content.title = "\(session.pillName) · \(session.title)"+ content.body = session.approvalCommand.isEmpty+ ? "An agent is waiting for your OK"+ : "Waiting for your OK: \(session.approvalCommand.prefix(140))"+ content.sound = .default+ content.categoryIdentifier = ApprovalActions.category+ content.userInfo = ["fingerprint": session.approvalFingerprint, "pillId": session.id]+ let request = UNNotificationRequest(identifier: Self.approvalNotificationID(session.approvalFingerprint),+ content: content, trigger: nil)+ try? await UNUserNotificationCenter.current().add(request)+ }+ }++ /// Fingerprints of the requests the Mac is still waiting on.+ private var pendingFingerprints: Set<String> {+ Set(sessions.filter(\.needsApproval).map(\.approvalFingerprint).filter { !$0.isEmpty })+ }++ /// Fingerprints whose iCloud alert reached this iPhone (shown or tapped).+ @ObservationIgnored private var iCloudAlerted: Set<String> = []++ func noteICloudAlert(_ fingerprint: String) {+ iCloudAlerted.insert(fingerprint)+ notifiedFingerprints.insert(fingerprint)+ }++ /// Clears the banners of requests answered on the Mac, on the iPhone or expired.+ private func removeAnsweredNotifications() async {+ let pending = pendingFingerprints+ let stale = await Self.shownApprovals().filter { !pending.contains($0.fingerprint) }.map { $0.id }+ if !stale.isEmpty { UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: stale) }+ }++ /// Approval notifications in Notification Center, local or from iCloud.+ nonisolated static func shownApprovals() async -> [(id: String, fingerprint: String)] {+ let delivered = await UNUserNotificationCenter.current().deliveredNotifications()+ return delivered.compactMap { notification in+ let request = notification.request+ return approvalFingerprint(in: request).map { (request.identifier, $0) }+ }+ }++ /// The approval fingerprint carried by a notification, local or from iCloud.+ nonisolated static func approvalFingerprint(in request: UNNotificationRequest) -> String? {+ let userInfo = request.content.userInfo+ if let fingerprint = userInfo["fingerprint"] as? String { return fingerprint }+ let note = CKNotification(fromRemoteNotificationDictionary: userInfo) as? CKQueryNotification+ return note?.recordFields?["fingerprint"] as? String+ }++ // MARK: Decisions (step 7)++ /// Decisions taken on this iPhone, newest first.+ var history: [DecisionLog] = DecisionLog.load()++ /// Set when the user taps "Review" on an approval notification.+ var reviewFingerprint: String?++ /// Sends allow / deny for one exact request. The Mac applies it only if the+ /// fingerprint still matches the request it is waiting on.+ func decide(_ decision: Decision, fingerprint: String, pillId: String, summary: String) async -> Bool {+ let record = CKRecord(recordType: "Decision",+ recordID: CKRecord.ID(recordName: "decision-\(UUID().uuidString)", zoneID: Self.zoneID))+ record["fingerprint"] = fingerprint+ record["pillId"] = pillId+ record["decision"] = decision.rawValue+ record["decidedAt"] = Date()+ record["deviceName"] = UIDevice.current.name+ do {+ _ = try await database.save(record)+ history.insert(DecisionLog(decision: decision, pillId: pillId, summary: summary, date: .now), at: 0)+ history = Array(history.prefix(50))+ DecisionLog.save(history)+ return true+ } catch {+ lastPong = "Decision failed: \(error.localizedDescription)"+ return false+ }+ }+/// Hands the sessions to the widgets and asks them to redraw.private func updateWidgets() {SharedSessions.save(sessions.map(\.shared))diff --git a/NotchBuddy/Sources/Phone/SessionDetailView.swift b/NotchBuddy/Sources/Phone/SessionDetailView.swiftindex bd740d57..00761187 100644--- a/NotchBuddy/Sources/Phone/SessionDetailView.swift+++ b/NotchBuddy/Sources/Phone/SessionDetailView.swift@@ -13,10 +13,7 @@ struct SessionDetailView: View {VStack(alignment: .leading, spacing: 16) {header(session)if session.needsApproval {- waiting(title: "Waiting for your OK",- text: session.approvalCommand.isEmpty ? "The agent asks for a permission." : session.approvalCommand,- monospaced: true, color: .orange,- footnote: "Answer on your Mac for now. Approving from the iPhone comes next.")+ ApprovalCard(link: link, session: session)} else if !session.question.isEmpty {waiting(title: "Question", text: session.question, monospaced: false, color: .cyan,footnote: "Answer on your Mac for now.")diff --git a/NotchBuddy/project.yml b/NotchBuddy/project.ymlindex bf739ad0..1415a517 100644--- a/NotchBuddy/project.yml+++ b/NotchBuddy/project.yml@@ -242,6 +242,7 @@ targets:UISupportedInterfaceOrientations:- UIInterfaceOrientationPortraitITSAppUsesNonExemptEncryption: NO+ NSFaceIDUsageDescription: "Coucou asks for Face ID before allowing a command from your iPhone."settings:base:PRODUCT_BUNDLE_IDENTIFIER: fr.louisraille.Coucou