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: Liquid Glass, tabs, zoom, gestures, icons, Spotlight, Focus, services with actions, intro (#251)
Louis66df17b01ef8
diff --git a/NotchBuddy/PhoneAssets.xcassets/AppIcon-Blue.appiconset/Contents.json b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Blue.appiconset/Contents.jsonnew file mode 100644index 00000000..c7251028--- /dev/null+++ b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Blue.appiconset/Contents.json@@ -0,0 +1,11 @@+{+ "images" : [+ {+ "filename" : "icon-1024.png",+ "idiom" : "universal",+ "platform" : "ios",+ "size" : "1024x1024"+ }+ ],+ "info" : { "author" : "xcode", "version" : 1 }+}diff --git a/NotchBuddy/PhoneAssets.xcassets/AppIcon-Blue.appiconset/icon-1024.png b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Blue.appiconset/icon-1024.pngnew file mode 100644index 00000000..5f5139d4Binary files /dev/null and b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Blue.appiconset/icon-1024.png differdiff --git a/NotchBuddy/PhoneAssets.xcassets/AppIcon-Graphite.appiconset/Contents.json b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Graphite.appiconset/Contents.jsonnew file mode 100644index 00000000..c7251028--- /dev/null+++ b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Graphite.appiconset/Contents.json@@ -0,0 +1,11 @@+{+ "images" : [+ {+ "filename" : "icon-1024.png",+ "idiom" : "universal",+ "platform" : "ios",+ "size" : "1024x1024"+ }+ ],+ "info" : { "author" : "xcode", "version" : 1 }+}diff --git a/NotchBuddy/PhoneAssets.xcassets/AppIcon-Graphite.appiconset/icon-1024.png b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Graphite.appiconset/icon-1024.pngnew file mode 100644index 00000000..4ef6e018Binary files /dev/null and b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Graphite.appiconset/icon-1024.png differdiff --git a/NotchBuddy/PhoneAssets.xcassets/AppIcon-Green.appiconset/Contents.json b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Green.appiconset/Contents.jsonnew file mode 100644index 00000000..c7251028--- /dev/null+++ b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Green.appiconset/Contents.json@@ -0,0 +1,11 @@+{+ "images" : [+ {+ "filename" : "icon-1024.png",+ "idiom" : "universal",+ "platform" : "ios",+ "size" : "1024x1024"+ }+ ],+ "info" : { "author" : "xcode", "version" : 1 }+}diff --git a/NotchBuddy/PhoneAssets.xcassets/AppIcon-Green.appiconset/icon-1024.png b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Green.appiconset/icon-1024.pngnew file mode 100644index 00000000..49bf521bBinary files /dev/null and b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Green.appiconset/icon-1024.png differdiff --git a/NotchBuddy/PhoneAssets.xcassets/AppIcon-Pink.appiconset/Contents.json b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Pink.appiconset/Contents.jsonnew file mode 100644index 00000000..c7251028--- /dev/null+++ b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Pink.appiconset/Contents.json@@ -0,0 +1,11 @@+{+ "images" : [+ {+ "filename" : "icon-1024.png",+ "idiom" : "universal",+ "platform" : "ios",+ "size" : "1024x1024"+ }+ ],+ "info" : { "author" : "xcode", "version" : 1 }+}diff --git a/NotchBuddy/PhoneAssets.xcassets/AppIcon-Pink.appiconset/icon-1024.png b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Pink.appiconset/icon-1024.pngnew file mode 100644index 00000000..b60cf728Binary files /dev/null and b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Pink.appiconset/icon-1024.png differdiff --git a/NotchBuddy/PhoneAssets.xcassets/AppIcon-Purple.appiconset/Contents.json b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Purple.appiconset/Contents.jsonnew file mode 100644index 00000000..c7251028--- /dev/null+++ b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Purple.appiconset/Contents.json@@ -0,0 +1,11 @@+{+ "images" : [+ {+ "filename" : "icon-1024.png",+ "idiom" : "universal",+ "platform" : "ios",+ "size" : "1024x1024"+ }+ ],+ "info" : { "author" : "xcode", "version" : 1 }+}diff --git a/NotchBuddy/PhoneAssets.xcassets/AppIcon-Purple.appiconset/icon-1024.png b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Purple.appiconset/icon-1024.pngnew file mode 100644index 00000000..e71799afBinary files /dev/null and b/NotchBuddy/PhoneAssets.xcassets/AppIcon-Purple.appiconset/icon-1024.png differdiff --git a/NotchBuddy/PhoneAssets.xcassets/AppIcon.appiconset/Contents.json b/NotchBuddy/PhoneAssets.xcassets/AppIcon.appiconset/Contents.jsonindex c7251028..737068e8 100644--- a/NotchBuddy/PhoneAssets.xcassets/AppIcon.appiconset/Contents.json+++ b/NotchBuddy/PhoneAssets.xcassets/AppIcon.appiconset/Contents.json@@ -5,6 +5,20 @@"idiom" : "universal","platform" : "ios","size" : "1024x1024"+ },+ {+ "appearances" : [ { "appearance" : "luminosity", "value" : "dark" } ],+ "filename" : "icon-1024-dark.png",+ "idiom" : "universal",+ "platform" : "ios",+ "size" : "1024x1024"+ },+ {+ "appearances" : [ { "appearance" : "luminosity", "value" : "tinted" } ],+ "filename" : "icon-1024-tinted.png",+ "idiom" : "universal",+ "platform" : "ios",+ "size" : "1024x1024"}],"info" : { "author" : "xcode", "version" : 1 }diff --git a/NotchBuddy/PhoneAssets.xcassets/AppIcon.appiconset/icon-1024-dark.png b/NotchBuddy/PhoneAssets.xcassets/AppIcon.appiconset/icon-1024-dark.pngnew file mode 100644index 00000000..1eadfa60Binary files /dev/null and b/NotchBuddy/PhoneAssets.xcassets/AppIcon.appiconset/icon-1024-dark.png differdiff --git a/NotchBuddy/PhoneAssets.xcassets/AppIcon.appiconset/icon-1024-tinted.png b/NotchBuddy/PhoneAssets.xcassets/AppIcon.appiconset/icon-1024-tinted.pngnew file mode 100644index 00000000..f0eab62aBinary files /dev/null and b/NotchBuddy/PhoneAssets.xcassets/AppIcon.appiconset/icon-1024-tinted.png differdiff --git a/NotchBuddy/PhoneAssets.xcassets/IconPreview-Blue.imageset/Contents.json b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Blue.imageset/Contents.jsonnew file mode 100644index 00000000..d48cf8fa--- /dev/null+++ b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Blue.imageset/Contents.json@@ -0,0 +1,12 @@+{+ "images": [+ {+ "filename": "preview.png",+ "idiom": "universal"+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}\ No newline at end of filediff --git a/NotchBuddy/PhoneAssets.xcassets/IconPreview-Blue.imageset/preview.png b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Blue.imageset/preview.pngnew file mode 100644index 00000000..44ae867cBinary files /dev/null and b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Blue.imageset/preview.png differdiff --git a/NotchBuddy/PhoneAssets.xcassets/IconPreview-Graphite.imageset/Contents.json b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Graphite.imageset/Contents.jsonnew file mode 100644index 00000000..d48cf8fa--- /dev/null+++ b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Graphite.imageset/Contents.json@@ -0,0 +1,12 @@+{+ "images": [+ {+ "filename": "preview.png",+ "idiom": "universal"+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}\ No newline at end of filediff --git a/NotchBuddy/PhoneAssets.xcassets/IconPreview-Graphite.imageset/preview.png b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Graphite.imageset/preview.pngnew file mode 100644index 00000000..45757ad0Binary files /dev/null and b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Graphite.imageset/preview.png differdiff --git a/NotchBuddy/PhoneAssets.xcassets/IconPreview-Green.imageset/Contents.json b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Green.imageset/Contents.jsonnew file mode 100644index 00000000..d48cf8fa--- /dev/null+++ b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Green.imageset/Contents.json@@ -0,0 +1,12 @@+{+ "images": [+ {+ "filename": "preview.png",+ "idiom": "universal"+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}\ No newline at end of filediff --git a/NotchBuddy/PhoneAssets.xcassets/IconPreview-Green.imageset/preview.png b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Green.imageset/preview.pngnew file mode 100644index 00000000..bd8e3fbfBinary files /dev/null and b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Green.imageset/preview.png differdiff --git a/NotchBuddy/PhoneAssets.xcassets/IconPreview-Orange.imageset/Contents.json b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Orange.imageset/Contents.jsonnew file mode 100644index 00000000..d48cf8fa--- /dev/null+++ b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Orange.imageset/Contents.json@@ -0,0 +1,12 @@+{+ "images": [+ {+ "filename": "preview.png",+ "idiom": "universal"+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}\ No newline at end of filediff --git a/NotchBuddy/PhoneAssets.xcassets/IconPreview-Orange.imageset/preview.png b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Orange.imageset/preview.pngnew file mode 100644index 00000000..cc6a1f93Binary files /dev/null and b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Orange.imageset/preview.png differdiff --git a/NotchBuddy/PhoneAssets.xcassets/IconPreview-Pink.imageset/Contents.json b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Pink.imageset/Contents.jsonnew file mode 100644index 00000000..d48cf8fa--- /dev/null+++ b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Pink.imageset/Contents.json@@ -0,0 +1,12 @@+{+ "images": [+ {+ "filename": "preview.png",+ "idiom": "universal"+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}\ No newline at end of filediff --git a/NotchBuddy/PhoneAssets.xcassets/IconPreview-Pink.imageset/preview.png b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Pink.imageset/preview.pngnew file mode 100644index 00000000..57b24807Binary files /dev/null and b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Pink.imageset/preview.png differdiff --git a/NotchBuddy/PhoneAssets.xcassets/IconPreview-Purple.imageset/Contents.json b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Purple.imageset/Contents.jsonnew file mode 100644index 00000000..d48cf8fa--- /dev/null+++ b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Purple.imageset/Contents.json@@ -0,0 +1,12 @@+{+ "images": [+ {+ "filename": "preview.png",+ "idiom": "universal"+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}\ No newline at end of filediff --git a/NotchBuddy/PhoneAssets.xcassets/IconPreview-Purple.imageset/preview.png b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Purple.imageset/preview.pngnew file mode 100644index 00000000..8c2aafedBinary files /dev/null and b/NotchBuddy/PhoneAssets.xcassets/IconPreview-Purple.imageset/preview.png differdiff --git a/NotchBuddy/Resources/InfoPhone.plist b/NotchBuddy/Resources/InfoPhone.plistindex 3ce50096..0c263b33 100644--- a/NotchBuddy/Resources/InfoPhone.plist+++ b/NotchBuddy/Resources/InfoPhone.plist@@ -45,6 +45,10 @@<string>Coucou turns your voice into the text of an instruction for Claude Code.</string><key>NSSupportsLiveActivities</key><true/>+ <key>CADisableMinimumFrameDurationOnPhone</key>+ <true/>+ <key>NSSupportsLiveActivitiesFrequentUpdates</key>+ <true/><key>UIApplicationSupportsIndirectInputEvents</key><true/><key>UIBackgroundModes</key>diff --git a/NotchBuddy/Sources/App/CalcomPoller.swift b/NotchBuddy/Sources/App/CalcomPoller.swiftindex ca08cd71..8f49b3dd 100644--- a/NotchBuddy/Sources/App/CalcomPoller.swift+++ b/NotchBuddy/Sources/App/CalcomPoller.swift@@ -25,7 +25,14 @@ final class CalcomPoller: @unchecked Sendable {let startStr = iso.string(from: today)let endStr = iso.string(from: future)- guard let url = URL(string: "https://api.cal.com/v2/bookings?status=upcoming&start=\(startStr)&end=\(endStr)") else { return }+ // API v2 (2024-08-13) filters on afterStart / beforeEnd; `start` and `end` aren't+ // query parameters there, so they returned nothing.+ var components = URLComponents(string: "https://api.cal.com/v2/bookings")!+ components.queryItems = [URLQueryItem(name: "status", value: "upcoming"),+ URLQueryItem(name: "afterStart", value: startStr),+ URLQueryItem(name: "beforeEnd", value: endStr),+ URLQueryItem(name: "take", value: "50")]+ guard let url = components.url else { return }var req = URLRequest(url: url, timeoutInterval: 10)req.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")req.setValue("2024-08-13", forHTTPHeaderField: "cal-api-version")diff --git a/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift b/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swiftindex 21e6a568..24a65075 100644--- a/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift+++ b/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift@@ -72,6 +72,7 @@ final class CloudProbe {SessionPublisher.shared.stop()ApprovalRelay.shared.stop()QuestionRelay.shared.stop()+ ServiceDetailRunner.shared.stop()ServicePublisher.shared.stop()TurnRecorder.shared.stop()#if !APPSTORE@@ -94,12 +95,15 @@ final class CloudProbe {SessionPublisher.shared.start()ApprovalRelay.shared.start()QuestionRelay.shared.start()+ ServiceDetailRunner.shared.start()ServicePublisher.shared.start()TurnRecorder.shared.start()#if !APPSTOREInstructionRunner.shared.startIfEnabled()#endifLiveActivityRelay.shared.startIfEnabled()+ // The silent database subscription, so the iPhone's requests (services) wake this Mac.+ Task { _ = await prepare() }// Step 1 Ping/Pong test: off unless asked for, so the Mac stays idle at rest// (defaults write fr.louisraille.NotchBuddy phoneLinkPing -bool YES).@@ -180,6 +184,9 @@ final class CloudProbe {return}lastPushAt = Date()+ // A request from the iPhone (a service to read, an action) may be waiting.+ Task { await ServiceDetailRunner.shared.checkNow() }+ guard pingTask != nil else { return } // the Pong fetch is only for the ping testlog("push received")Task { await fetchChanges(source: "push") }}diff --git a/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swift b/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swiftindex 01a12978..80e3dcf0 100644--- a/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swift+++ b/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swift@@ -54,6 +54,13 @@ final class LiveActivityRelay {private var sending = falseprivate var retryTask: Task<Void, Never>?private var retries = 0+ /// The phase a start was sent again for, so it is only tried once each.+ private var restartedFor: String?+ /// A start waiting to see if the Mac stays locked, and an end waiting to+ /// see if it stays unlocked: iOS allows only so many starts an hour, so a+ /// quick lock and unlock doesn't spend one.+ private var lockTask: Task<Void, Never>?+ private var unlockTask: Task<Void, Never>?/// Ends the activity 10 minutes after the agents are done, if nothing restarts.private var doneTask: Task<Void, Never>?@@ -101,6 +108,8 @@ final class LiveActivityRelay {observers.forEach { DistributedNotificationCenter.default().removeObserver($0) }observers = []cancellable = nil+ lockTask?.cancel(); lockTask = nil+ unlockTask?.cancel(); unlockTask = nilif startedAt != nil { finish(dismissAfter: 0) }log("off")}@@ -111,19 +120,50 @@ final class LiveActivityRelay {locked = isLockedif isLocked {log("Mac locked")- if let latest, latest.isActive { begin(latest) }+ unlockTask?.cancel(); unlockTask = nil+ if startedAt != nil {+ // Locked again before the activity left: it carries on.+ flush()+ return+ }+ if let latest, latest.isActive { beginSoon(latest) }} else {log("Mac unlocked")- // Mochi comes back to the notch.- if startedAt != nil { finish(dismissAfter: 0) }+ lockTask?.cancel(); lockTask = nil+ guard startedAt != nil else { return }+ // Mochi comes back to the notch, unless the Mac locks again within 30 s.+ unlockTask = Task {+ try? await Task.sleep(for: .seconds(30))+ guard !Task.isCancelled, !locked else { return }+ unlockTask = nil+ finish(dismissAfter: 0)+ }+ }+ }++ /// Starts right away when an agent needs you; otherwise once the Mac has+ /// stayed locked for 20 s.+ private func beginSoon(_ state: MochiActivityState) {+ if state.tone == "waiting" || state.tone == "question" {+ lockTask?.cancel(); lockTask = nil+ begin(state)+ return+ }+ guard lockTask == nil else { return }+ lockTask = Task {+ try? await Task.sleep(for: .seconds(20))+ lockTask = nil+ guard !Task.isCancelled, locked, startedAt == nil, let latest, latest.isActive else { return }+ begin(latest)}}private func stateChanged(_ lead: MochiActivityState?) {+ if lead?.tone != latest?.tone, let lead { log("phase: \(lead.agent) \(lead.statusText)\(locked ? "" : " (Mac unlocked, stays on the Mac)")") }latest = leadguard locked else { return }if startedAt == nil {- if let lead, lead.isActive { begin(lead) }+ if let lead, lead.isActive { beginSoon(lead) }return}if let lead, lead.isActive {@@ -183,12 +223,30 @@ final class LiveActivityRelay {let targets = await updateTargets(since: startedAt)guard !targets.isEmpty else {sending = false+ // No update token: iOS didn't bring the activity up (it can hold+ // back starts after many in a row). When an agent needs you, start+ // it again with that state, once per request.+ let key = state.approval ?? "\(state.tone)|\(state.statusText)"+ if state.tone == "waiting" || state.tone == "question", restartedFor != key,+ let sentAt = startSent, Date().timeIntervalSince(sentAt) > 15 {+ restartedFor = key+ log("the Live Activity isn't on the iPhone: starting it again for \(state.statusText)")+ begin(state)+ return+ }+ log("update \(state.tone) waits: no update token from the iPhone yet")scheduleRetry()return}+ retries = 0+ let urgent = state.tone == "waiting" || state.tone == "question"for (id, phone) in targets {- await post(event: "update", token: phone.updateToken, env: phone.env, state: state,- urgent: state.tone == "waiting" || state.tone == "question", phoneID: id)+ let ok = await post(event: "update", token: phone.updateToken, env: phone.env, state: state,+ urgent: urgent, phoneID: id)+ // Every change of phase is logged; step counts only when they fail.+ if ok && (urgent || sent?.tone != state.tone) {+ log("update sent: \(state.agent) \(state.statusText)\(state.approval == nil ? "" : " (with Allow / Deny)")")+ }}sent = statesending = falsediff --git a/NotchBuddy/Sources/App/PhoneLink/ServiceDetailRunner.swift b/NotchBuddy/Sources/App/PhoneLink/ServiceDetailRunner.swiftnew file mode 100644index 00000000..154450dd--- /dev/null+++ b/NotchBuddy/Sources/App/PhoneLink/ServiceDetailRunner.swift@@ -0,0 +1,802 @@+#if PHONE_LINK+import AppKit+import CloudKit++// MARK: - Services up close, for the iPhone+//+// When a service's screen opens on the iPhone, it writes a `ServiceAction`+// record of kind "refresh"; to act (redeploy, re-run, merge…) it writes one+// with that action's kind and target. The CloudKit push wakes this Mac (with+// a check every minute in case a push is missed); it takes each request once+// (deleted on read, and only those it could delete), reads the service's API+// with the key in its Keychain and writes a `ServiceDetail` record,+// encrypted. An action runs only if it was offered on an item of the last+// detail sent for that service, and was asked for in the last 5 minutes.+// Nothing that moves money or sends an email is ever offered.++@MainActor+final class ServiceDetailRunner {+ static let shared = ServiceDetailRunner()++ private var database: CKDatabase { CKContainer(identifier: CloudProbe.containerID).privateCloudDatabase }+ private var pollTask: Task<Void, Never>?+ private var changeToken: CKServerChangeToken?+ /// The last detail sent per service: actions are checked against it.+ private var lastDetails: [String: ServiceDetail] = [:]+ private let maxAge: TimeInterval = 5 * 60+ private var checking = false+ private var again = false++ func start() {+ guard pollTask == nil else { return }+ pollTask = Task { [weak self] in+ while !Task.isCancelled {+ await self?.checkNow()+ // In case a push is missed.+ try? await Task.sleep(for: .seconds(60))+ }+ }+ }++ /// Stops and deletes the details this Mac wrote to iCloud.+ func stop() {+ pollTask?.cancel()+ pollTask = nil+ lastDetails = [:]+ let ids = PillCatalog.phoneServices.map {+ CKRecord.ID(recordName: ServiceDetail.recordName(for: $0), zoneID: SessionSnapshot.zoneID)+ }+ Task { _ = try? await database.modifyRecords(saving: [], deleting: ids, savePolicy: .changedKeys, atomically: false) }+ }++ /// From the CloudKit push and the fallback check. One check at a time: two+ /// overlapping checks would share the change token and could run an action twice.+ func checkNow() async {+ guard pollTask != nil else { return }+ guard !checking else { again = true; return }+ checking = true+ repeat {+ again = false+ await check()+ } while again+ checking = false+ }++ // MARK: Requests++ private func check() async {+ var found: [CKRecord] = []+ do {+ var more = true+ while more {+ let changes = try await database.recordZoneChanges(inZoneWith: SessionSnapshot.zoneID, since: changeToken,+ desiredKeys: ["pillId", "kind", "requestedAt", "target"])+ for (_, result) in changes.modificationResultsByID {+ if case .success(let mod) = result, mod.record.recordType == ServiceDetail.requestType {+ found.append(mod.record)+ }+ }+ changeToken = changes.changeToken+ more = changes.moreComing+ }+ } catch let error as CKError where error.code == .changeTokenExpired {+ changeToken = nil+ return+ } catch {+ return+ }+ guard !found.isEmpty else { return }+ // Single use: act only on the requests this Mac actually removed from iCloud.+ guard let removed = try? await database.modifyRecords(saving: [], deleting: found.map(\.recordID),+ savePolicy: .changedKeys, atomically: false) else {+ log("couldn't take \(found.count) request(s) off iCloud; skipped")+ return+ }+ let taken = found.filter {+ guard case .success? = removed.deleteResults[$0.recordID] else { return false }+ return true+ }++ // Several refreshes for one service count once.+ var refreshed: Set<String> = []+ for record in taken.sorted(by: { ($0["requestedAt"] as? Date ?? .distantPast) < ($1["requestedAt"] as? Date ?? .distantPast) }) {+ let pillId = record["pillId"] as? String ?? ""+ let kind = record["kind"] as? String ?? ""+ let target = record.encryptedValues["target"] as? String ?? ""+ let requestedAt = record["requestedAt"] as? Date ?? .distantPast+ guard Date().timeIntervalSince(requestedAt) < maxAge, PillCatalog.phoneServices.contains(pillId) else { continue }+ if kind == ServiceDetail.refreshKind {+ guard refreshed.insert(pillId).inserted else { continue }+ await publish(pillId: pillId, lastAction: lastDetails[pillId]?.lastAction)+ } else {+ await run(kind: kind, target: target, pillId: pillId)+ }+ }+ }++ private func run(kind: String, target: String, pillId: String) async {+ guard let action = lastDetails[pillId]?.offered(kind: kind, target: target),+ ServiceAPI.allowedKinds.contains(kind), kind.hasPrefix(ServiceAPI.prefix(of: pillId)) else {+ log("ignored an action that wasn't offered: \(kind)")+ await publish(pillId: pillId, lastAction: ServiceActionResult(+ title: "Not done", ok: false,+ message: "This action isn't offered any more. The list was refreshed.", date: Date()))+ return+ }+ log("\(action.title) (\(pillId)) asked from the iPhone")+ let result: ServiceActionResult+ do {+ let message = try await ServiceAPI.perform(kind: kind, target: target)+ result = ServiceActionResult(title: action.title, ok: true, message: message, date: Date())+ } catch {+ result = ServiceActionResult(title: action.title, ok: false, message: ServiceAPI.describe(error), date: Date())+ }+ log("\(action.title): \(result.ok ? "done" : "failed, \(result.message)")")+ // Give the service a moment, then show where things are.+ try? await Task.sleep(for: .seconds(2))+ await publish(pillId: pillId, lastAction: result)+ }++ private func publish(pillId: String, lastAction: ServiceActionResult?) async {+ var detail = await ServiceAPI.detail(for: pillId)+ // The iPhone sync was turned off while the API was read: write nothing.+ guard !Task.isCancelled, pollTask != nil else { return }+ detail.lastAction = lastAction+ lastDetails[pillId] = detail+ guard let json = try? JSONEncoder().encode(detail), let payload = String(data: json, encoding: .utf8) else { return }+ let record = CKRecord(recordType: ServiceDetail.recordType,+ recordID: CKRecord.ID(recordName: ServiceDetail.recordName(for: pillId), zoneID: SessionSnapshot.zoneID))+ record["pillId"] = pillId+ record["fetchedAt"] = detail.fetchedAt+ record.encryptedValues["payload"] = payload+ do {+ _ = try await database.modifyRecords(saving: [record], deleting: [], savePolicy: .allKeys)+ } catch {+ log("detail for \(pillId) not saved: \(error.localizedDescription)")+ }+ }++ private func log(_ message: String) {+ CloudProbe.shared.log("[services] \(message)")+ }+}++// MARK: - The services' APIs++enum ServiceAPI {+ struct Failure: Error {+ let status: Int+ let message: String+ }++ /// Every action the iPhone can ask for. Nothing moves money or sends an email.+ static let allowedKinds: Set<String> = [+ "vercel.redeploy", "vercel.promote", "vercel.cancel",+ "github.rerun", "github.approve", "github.merge",+ "n8n.activate", "n8n.deactivate", "n8n.retry",+ ]++ static func prefix(of pillId: String) -> String {+ pillId.replacingOccurrences(of: "integration_", with: "") + "."+ }++ static func describe(_ error: Error) -> String {+ if let failure = error as? Failure {+ switch failure.status {+ case 401:+ if failure.message.localizedCaseInsensitiveContains("restricted") {+ // Resend `restricted_api_key`: a Sending-access key can't read emails or domains.+ return "This key can only send emails. Use a Full access key in Coucou's Settings on your Mac to see them here."+ }+ return "The key was refused (401). Check it in Coucou's Settings on your Mac."+ case 403: return "Not allowed with this key (403). \(failure.message)"+ case 404: return "Not found (404)."+ default: return failure.message.isEmpty ? "Error \(failure.status)" : String(failure.message.prefix(160))+ }+ }+ return error.localizedDescription+ }++ // MARK: HTTP++ private static func request(_ urlString: String, method: String = "GET", headers: [String: String],+ body: [String: Any]? = nil) async throws -> Any {+ guard let url = URL(string: urlString) else { throw Failure(status: 0, message: "Bad address") }+ var request = URLRequest(url: url, timeoutInterval: 15)+ request.httpMethod = method+ for (key, value) in headers { request.setValue(value, forHTTPHeaderField: key) }+ if let body {+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")+ request.httpBody = try JSONSerialization.data(withJSONObject: body)+ }+ let (data, response) = try await URLSession.shared.data(for: request)+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0+ guard (200..<300).contains(status) else {+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any]+ let message = (json?["message"] as? String)+ ?? ((json?["error"] as? [String: Any])?["message"] as? String)+ ?? (json?["error"] as? String)+ ?? String(decoding: data.prefix(200), as: UTF8.self)+ throw Failure(status: status, message: message)+ }+ if data.isEmpty { return [String: Any]() }+ return try JSONSerialization.jsonObject(with: data)+ }++ private static func date(_ value: Any?) -> Date? {+ if let ms = value as? Double { return Date(timeIntervalSince1970: ms > 1e11 ? ms / 1000 : ms) }+ if let ms = value as? Int { return Date(timeIntervalSince1970: ms > 100_000_000_000 ? Double(ms) / 1000 : Double(ms)) }+ guard let text = value as? String else { return nil }+ let fractional = ISO8601DateFormatter()+ fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ if let date = fractional.date(from: text) { return date }+ let plain = ISO8601DateFormatter()+ if let date = plain.date(from: text) { return date }+ // Resend: "2024-05-01 10:00:00.123456+00"+ let formatter = DateFormatter()+ formatter.locale = Locale(identifier: "en_US_POSIX")+ for format in ["yyyy-MM-dd HH:mm:ss.SSSSSSZ", "yyyy-MM-dd HH:mm:ss.SSSZ", "yyyy-MM-dd HH:mm:ssZ"] {+ formatter.dateFormat = format+ if let date = formatter.date(from: text.count > 3 && text.hasSuffix("+00") ? text + "00" : text) { return date }+ }+ return nil+ }++ private static func money(_ cents: Int, _ currency: String) -> String {+ let formatter = NumberFormatter()+ formatter.numberStyle = .currency+ formatter.currencyCode = currency.uppercased()+ // Stripe zero-decimal currencies (docs.stripe.com/currencies#zero-decimal). UGX and ISK stay ×100+ // for backward compatibility; HUF and TWD charges are two-decimal.+ let zeroDecimal: Set<String> = ["bif", "clp", "djf", "gnf", "jpy", "kmf", "krw", "mga", "pyg", "rwf",+ "vnd", "vuv", "xaf", "xof", "xpf"]+ let amount = zeroDecimal.contains(currency.lowercased()) ? Double(cents) : Double(cents) / 100+ return formatter.string(from: NSNumber(value: amount)) ?? "\(amount) \(currency.uppercased())"+ }++ // MARK: Reading++ static func detail(for pillId: String) async -> ServiceDetail {+ do {+ switch pillId {+ case "integration_vercel": return try await vercel()+ case "integration_github": return try await github()+ case "integration_stripe": return try await stripe()+ case "integration_resend": return try await resend()+ case "integration_calcom": return try await calcom()+ case "integration_n8n": return try await n8n()+ case "integration_notion": return try await notion()+ default: return ServiceDetail(pillId: pillId, fetchedAt: Date(), error: "Not available from the iPhone yet.")+ }+ } catch {+ return ServiceDetail(pillId: pillId, fetchedAt: Date(), error: describe(error))+ }+ }++ private static func secret(_ name: String, _ service: String) throws -> String {+ guard let value = KeychainStore.shared.get(name), !value.isEmpty else {+ throw Failure(status: 0, message: "No \(service) key on your Mac. Add it in Coucou's Settings.")+ }+ return value+ }++ // Vercel: deployments (redeploy, promote to production, cancel) and projects.+ private static func vercel() async throws -> ServiceDetail {+ let token = try secret("vercel-token", "Vercel")+ let headers = ["Authorization": "Bearer \(token)", "Accept": "application/json"]+ let deploymentsJSON = try await request("https://api.vercel.com/v6/deployments?limit=20", headers: headers)+ let deployments = (deploymentsJSON as? [String: Any])?["deployments"] as? [[String: Any]] ?? []+ let projectsJSON = try? await request("https://api.vercel.com/v9/projects?limit=20", headers: headers)+ let projects = (projectsJSON as? [String: Any])?["projects"] as? [[String: Any]] ?? []++ var items: [DetailItem] = []+ var ready = 0, failed = 0, building = 0+ for d in deployments {+ guard let uid = d["uid"] as? String else { continue }+ let name = d["name"] as? String ?? "Deployment"+ let state = (d["state"] as? String ?? d["readyState"] as? String ?? "").uppercased()+ let target = d["target"] as? String+ let meta = d["meta"] as? [String: Any] ?? [:]+ let message = meta["githubCommitMessage"] as? String ?? ""+ let branch = meta["githubCommitRef"] as? String ?? ""+ let creator = (d["creator"] as? [String: Any])?["username"] as? String ?? ""+ var tone: ServiceTone = .idle+ var actions: [ServiceActionDef] = []+ switch state {+ case "READY":+ ready += 1+ tone = .ok+ actions.append(ServiceActionDef(kind: "vercel.redeploy", title: "Redeploy", symbol: "arrow.clockwise",+ target: "\(uid)|\(name)|\(target ?? "")"))+ if target != "production" {+ actions.append(ServiceActionDef(kind: "vercel.promote", title: "Promote to production",+ symbol: "arrow.up.circle", target: "\(uid)|\(name)",+ confirm: "A new production build starts from this deployment, using your production environment variables."))+ }+ case "ERROR":+ failed += 1+ tone = .error+ actions.append(ServiceActionDef(kind: "vercel.redeploy", title: "Redeploy", symbol: "arrow.clockwise",+ target: "\(uid)|\(name)|\(target ?? "")"))+ case "BUILDING", "QUEUED", "INITIALIZING":+ building += 1+ tone = .warning+ actions.append(ServiceActionDef(kind: "vercel.cancel", title: "Cancel build", symbol: "xmark.circle",+ target: uid, destructive: true, confirm: "Stop this build?"))+ case "CANCELED": tone = .idle+ default: break+ }+ let subtitle = [branch, message.split(separator: "\n").first.map(String.init) ?? "", creator]+ .filter { !$0.isEmpty }.joined(separator: " · ")+ items.append(DetailItem(title: name, subtitle: subtitle.isEmpty ? state.capitalized : subtitle, tone: tone,+ date: date(d["created"] ?? d["createdAt"]),+ url: (d["url"] as? String).map { "https://\($0)" },+ badge: target == "production" ? "Production" : (state == "READY" ? "Preview" : state.capitalized),+ actions: actions))+ }+ let projectItems = projects.prefix(20).map { p in+ DetailItem(title: p["name"] as? String ?? "Project",+ subtitle: (p["framework"] as? String).map { $0.capitalized } ?? "",+ date: date(p["updatedAt"]))+ }+ var sections = [DetailSection(title: "Deployments", items: items)]+ if !projectItems.isEmpty { sections.append(DetailSection(title: "Projects · \(projectItems.count)", items: Array(projectItems))) }+ return ServiceDetail(pillId: "integration_vercel",+ stats: [DetailStat(label: "Ready", value: "\(ready)", tone: .ok),+ DetailStat(label: "Building", value: "\(building)", tone: building > 0 ? .warning : .idle),+ DetailStat(label: "Failed", value: "\(failed)", tone: failed > 0 ? .error : .idle),+ DetailStat(label: "Projects", value: "\(projects.count)")],+ sections: sections, fetchedAt: Date())+ }++ // GitHub: your pull requests (merge), reviews asked of you (approve), CI runs (re-run failed jobs).+ private static func github() async throws -> ServiceDetail {+ let token = try secret("github-token", "GitHub")+ let headers = ["Authorization": "Bearer \(token)", "Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28"]+ let user = try await request("https://api.github.com/user", headers: headers) as? [String: Any] ?? [:]+ let login = user["login"] as? String ?? ""++ func search(_ query: String) async -> [[String: Any]] {+ var components = URLComponents(string: "https://api.github.com/search/issues")!+ components.queryItems = [URLQueryItem(name: "q", value: query), URLQueryItem(name: "per_page", value: "10"),+ URLQueryItem(name: "sort", value: "updated")]+ let json = try? await request(components.url!.absoluteString, headers: headers)+ return (json as? [String: Any])?["items"] as? [[String: Any]] ?? []+ }+ /// "owner/repo#12" from a search result.+ func pullRef(_ item: [String: Any]) -> String? {+ guard let repoURL = item["repository_url"] as? String, let number = item["number"] as? Int else { return nil }+ let parts = repoURL.split(separator: "/").suffix(2).joined(separator: "/")+ return "\(parts)#\(number)"+ }++ let mine = await search("is:pr is:open author:\(login) archived:false")+ let asked = await search("is:pr is:open review-requested:\(login) archived:false")++ let mineItems = mine.compactMap { item -> DetailItem? in+ guard let ref = pullRef(item) else { return nil }+ let draft = item["draft"] as? Bool ?? false+ return DetailItem(title: item["title"] as? String ?? "Pull request", subtitle: ref,+ tone: draft ? .idle : .info, date: date(item["updated_at"]),+ url: item["html_url"] as? String, badge: draft ? "Draft" : nil,+ actions: draft ? [] : [ServiceActionDef(kind: "github.merge", title: "Squash and merge",+ symbol: "arrow.triangle.merge", target: ref,+ confirm: "Merge \(ref) into its base branch?")])+ }+ let askedItems = asked.compactMap { item -> DetailItem? in+ guard let ref = pullRef(item) else { return nil }+ let author = (item["user"] as? [String: Any])?["login"] as? String ?? ""+ return DetailItem(title: item["title"] as? String ?? "Pull request",+ subtitle: author.isEmpty ? ref : "\(ref) · \(author)", tone: .warning,+ date: date(item["updated_at"]), url: item["html_url"] as? String,+ actions: [ServiceActionDef(kind: "github.approve", title: "Approve", symbol: "checkmark.seal",+ target: ref)])+ }++ // CI on the repos you pushed to last.+ let reposJSON = try? await request("https://api.github.com/user/repos?sort=pushed&per_page=5&affiliation=owner,collaborator",+ headers: headers)+ let repos = (reposJSON as? [[String: Any]] ?? []).compactMap { $0["full_name"] as? String }+ var runItems: [DetailItem] = []+ var failing = 0+ for repo in repos {+ let runsJSON = try? await request("https://api.github.com/repos/\(repo)/actions/runs?per_page=3", headers: headers)+ let runs = (runsJSON as? [String: Any])?["workflow_runs"] as? [[String: Any]] ?? []+ for run in runs {+ guard let id = run["id"] as? Int else { continue }+ let status = run["status"] as? String ?? ""+ let conclusion = run["conclusion"] as? String ?? ""+ var tone: ServiceTone = .idle+ var actions: [ServiceActionDef] = []+ if status != "completed" {+ tone = .warning+ } else if conclusion == "success" {+ tone = .ok+ } else if conclusion == "failure" || conclusion == "timed_out" {+ tone = .error+ failing += 1+ actions.append(ServiceActionDef(kind: "github.rerun", title: "Re-run failed jobs",+ symbol: "arrow.clockwise", target: "\(repo)/\(id)"))+ }+ let label = status == "completed" ? conclusion.replacingOccurrences(of: "_", with: " ") : status.replacingOccurrences(of: "_", with: " ")+ runItems.append(DetailItem(title: run["name"] as? String ?? "Workflow",+ subtitle: "\(repo) · \(run["head_branch"] as? String ?? "")",+ tone: tone, date: date(run["created_at"]),+ url: run["html_url"] as? String, badge: label.capitalized, actions: actions))+ }+ }++ var sections: [DetailSection] = []+ if !askedItems.isEmpty { sections.append(DetailSection(title: "Reviews asked of you", items: askedItems)) }+ sections.append(DetailSection(title: "Your pull requests", items: mineItems,+ footer: mineItems.isEmpty ? "No open pull request." : nil))+ if !runItems.isEmpty { sections.append(DetailSection(title: "CI on your latest repos", items: runItems)) }+ return ServiceDetail(pillId: "integration_github",+ stats: [DetailStat(label: "Your PRs", value: "\(mineItems.count)", tone: .info),+ DetailStat(label: "Reviews", value: "\(askedItems.count)", tone: askedItems.isEmpty ? .idle : .warning),+ DetailStat(label: "CI failing", value: "\(failing)", tone: failing > 0 ? .error : .ok)],+ sections: sections, fetchedAt: Date())+ }++ // Stripe: balance, payments, payouts, subscriptions. Read only.+ private static func stripe() async throws -> ServiceDetail {+ let key = try secret("stripe-api-key", "Stripe")+ let headers = ["Authorization": "Bearer \(key)"]+ let balance = try await request("https://api.stripe.com/v1/balance", headers: headers) as? [String: Any] ?? [:]+ // One entry per currency in each list, in no set order: pair them by currency.+ let availableList = balance["available"] as? [[String: Any]] ?? []+ let pendingList = balance["pending"] as? [[String: Any]] ?? []+ let currency = ((availableList.first ?? pendingList.first)?["currency"] as? String ?? "eur").lowercased()+ func amount(_ list: [[String: Any]]) -> Int {+ list.first { ($0["currency"] as? String)?.lowercased() == currency }?["amount"] as? Int ?? 0+ }+ let available = amount(availableList)+ let pending = amount(pendingList)++ /// A list, or why it couldn't be read (shown instead of a made-up zero).+ func list(_ path: String) async -> ([[String: Any]], [String: Any], String?) {+ do {+ let json = try await request("https://api.stripe.com/v1/\(path)", headers: headers) as? [String: Any] ?? [:]+ return (json["data"] as? [[String: Any]] ?? [], json, nil)+ } catch {+ return ([], [:], describe(error))+ }+ }++ let (charges, _, chargesError) = await list("charges?limit=15")+ let chargeItems = charges.map { c -> DetailItem in+ let status = c["status"] as? String ?? ""+ let refunded = c["refunded"] as? Bool ?? false+ let partlyRefunded = !refunded && (c["amount_refunded"] as? Int ?? 0) > 0+ let uncaptured = !refunded && status == "succeeded" && (c["captured"] as? Bool) == false+ let who = ((c["billing_details"] as? [String: Any])?["name"] as? String)+ ?? (c["receipt_email"] as? String) ?? (c["description"] as? String) ?? ""+ let tone: ServiceTone = refunded ? .idle+ : (uncaptured || partlyRefunded) ? .warning+ : status == "succeeded" ? .ok : status == "failed" ? .error : .warning+ let badge = refunded ? "Refunded" : uncaptured ? "Uncaptured"+ : partlyRefunded ? "Partly refunded" : status.capitalized+ return DetailItem(title: money(c["amount"] as? Int ?? 0, c["currency"] as? String ?? currency),+ subtitle: who, tone: tone, date: date(c["created"]), badge: badge)+ }+ let (payouts, _, payoutsError) = await list("payouts?limit=5")+ let payoutItems = payouts.map { p in+ DetailItem(title: money(p["amount"] as? Int ?? 0, p["currency"] as? String ?? currency),+ subtitle: "Arrives", tone: (p["status"] as? String) == "failed" ? .error : .info,+ date: date(p["arrival_date"]), badge: (p["status"] as? String)?.replacingOccurrences(of: "_", with: " ").capitalized)+ }++ // Active subscriptions, every page (up to 1 000).+ var subs: [[String: Any]] = []+ var moreSubs = false+ var subsError: String?+ var cursor: String?+ for _ in 0..<10 {+ let (page, json, error) = await list("subscriptions?status=active&limit=100" + (cursor.map { "&starting_after=\($0)" } ?? ""))+ if let error { subsError = error; break }+ subs += page+ moreSubs = json["has_more"] as? Bool ?? false+ guard moreSubs, let last = subs.last?["id"] as? String else { break }+ cursor = last+ }+ // Estimated monthly revenue, one total per currency. Metered and tiered+ // prices have no fixed amount per period and discounts aren't applied.+ var monthlyByCurrency: [String: Double] = [:]+ for sub in subs {+ let subCurrency = (sub["currency"] as? String)?.lowercased()+ let items = (sub["items"] as? [String: Any])?["data"] as? [[String: Any]] ?? []+ for item in items {+ let price = item["price"] as? [String: Any] ?? [:]+ let recurring = price["recurring"] as? [String: Any] ?? [:]+ if recurring["usage_type"] as? String == "metered" || price["billing_scheme"] as? String == "tiered" { continue }+ let perUnit = (price["unit_amount"] as? Int).map { Double($0) }+ ?? Double(price["unit_amount_decimal"] as? String ?? "") ?? 0+ let unit = perUnit * Double(item["quantity"] as? Int ?? 1)+ let count = Double(recurring["interval_count"] as? Int ?? 1)+ let perMonth: Double+ switch recurring["interval"] as? String {+ case "year": perMonth = unit / (12 * count)+ case "week": perMonth = unit * 4.345 / count+ case "day": perMonth = unit * 30.4 / count+ default: perMonth = unit / count+ }+ let itemCurrency = subCurrency ?? (price["currency"] as? String)?.lowercased() ?? currency+ monthlyByCurrency[itemCurrency, default: 0] += perMonth+ }+ }+ let largest = monthlyByCurrency.max { $0.value < $1.value }+ let mrrCurrency = monthlyByCurrency[currency] != nil ? currency : (largest?.key ?? currency)+ let monthly = monthlyByCurrency[mrrCurrency] ?? 0++ var sections = [DetailSection(title: "Payments", items: chargeItems, footer: chargesError)]+ if !payoutItems.isEmpty || payoutsError != nil {+ sections.append(DetailSection(title: "Payouts", items: payoutItems, footer: payoutsError))+ }+ if let subsError { sections.append(DetailSection(title: "Subscriptions", items: [], footer: subsError)) }+ return ServiceDetail(pillId: "integration_stripe",+ stats: [DetailStat(label: "Available", value: money(available, currency), tone: .ok),+ DetailStat(label: "Pending", value: money(pending, currency)),+ DetailStat(label: "Subscriptions",+ value: subsError != nil ? "—" : (moreSubs ? "\(subs.count)+" : "\(subs.count)"),+ tone: .info),+ DetailStat(label: "Est. MRR",+ value: subsError != nil ? "—" : money(Int(monthly.rounded()), mrrCurrency),+ tone: .info)],+ sections: sections, fetchedAt: Date())+ }++ // Resend: the latest emails and how they went, and the domains. Read only.+ private static func resend() async throws -> ServiceDetail {+ let key = try secret("resend-api-key", "Resend")+ let headers = ["Authorization": "Bearer \(key)"]+ let emailsJSON = try await request("https://api.resend.com/emails?limit=20", headers: headers)+ let emails = (emailsJSON as? [String: Any])?["data"] as? [[String: Any]] ?? []+ var bounced = 0, delivered = 0+ let emailItems = emails.map { e -> DetailItem in+ let event = e["last_event"] as? String ?? "sent"+ let tone: ServiceTone+ switch event {+ case "delivered", "opened", "clicked": tone = .ok; delivered += 1+ case "bounced", "complained", "failed", "suppressed": tone = .error; bounced += 1+ case "delivery_delayed": tone = .warning+ default: tone = .info+ }+ let to = (e["to"] as? [String])?.joined(separator: ", ") ?? ""+ return DetailItem(title: e["subject"] as? String ?? "(no subject)", subtitle: to, tone: tone,+ date: date(e["created_at"]), badge: event.replacingOccurrences(of: "_", with: " ").capitalized)+ }+ let domainsJSON = try? await request("https://api.resend.com/domains", headers: headers)+ let domains = (domainsJSON as? [String: Any])?["data"] as? [[String: Any]] ?? []+ let domainItems = domains.map { d in+ let status = d["status"] as? String ?? ""+ return DetailItem(title: d["name"] as? String ?? "Domain", subtitle: d["region"] as? String ?? "",+ tone: status == "verified" ? .ok : (status == "failed" ? .error : .warning),+ badge: status.replacingOccurrences(of: "_", with: " ").capitalized)+ }+ var sections = [DetailSection(title: "Latest emails", items: emailItems)]+ if !domainItems.isEmpty { sections.append(DetailSection(title: "Domains", items: domainItems)) }+ return ServiceDetail(pillId: "integration_resend",+ stats: [DetailStat(label: "Delivered", value: "\(delivered)", tone: .ok),+ DetailStat(label: "Bounced", value: "\(bounced)", tone: bounced > 0 ? .error : .idle),+ DetailStat(label: "Domains", value: "\(domains.count)")],+ sections: sections, fetchedAt: Date())+ }++ // Cal.com: upcoming bookings. Read only: cancelling emails the guest and can refund or charge them.+ private static func calcom() async throws -> ServiceDetail {+ let key = try secret("calcom-api-key", "Cal.com")+ let headers = ["Authorization": "Bearer \(key)", "cal-api-version": "2024-08-13"]+ let iso = ISO8601DateFormatter()+ let now = Date()+ var components = URLComponents(string: "https://api.cal.com/v2/bookings")!+ components.queryItems = [URLQueryItem(name: "status", value: "upcoming"),+ URLQueryItem(name: "afterStart", value: iso.string(from: now)),+ URLQueryItem(name: "take", value: "30")]+ let json = try await request(components.url!.absoluteString, headers: headers)+ let bookings = (json as? [String: Any])?["data"] as? [[String: Any]] ?? []+ let calendar = Calendar.current+ var today = 0, week = 0+ let items = bookings.compactMap { b -> DetailItem? in+ guard let start = date(b["start"] ?? b["startTime"]) else { return nil }+ if calendar.isDateInToday(start) { today += 1 }+ if start.timeIntervalSince(now) < 7 * 24 * 3600 { week += 1 }+ let attendee = (b["attendees"] as? [[String: Any]])?.first+ let who = attendee?["name"] as? String ?? attendee?["email"] as? String ?? ""+ let when = start.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute())+ return DetailItem(title: b["title"] as? String ?? "Meeting",+ subtitle: who.isEmpty ? when : "\(when) · \(who)",+ tone: calendar.isDateInToday(start) ? .warning : .info,+ date: start, url: (b["meetingUrl"] as? String) ?? (b["location"] as? String).flatMap { $0.hasPrefix("https://") ? $0 : nil },+ badge: (b["status"] as? String)?.capitalized)+ }+ return ServiceDetail(pillId: "integration_calcom",+ stats: [DetailStat(label: "Today", value: "\(today)", tone: today > 0 ? .warning : .idle),+ DetailStat(label: "Next 7 days", value: "\(week)", tone: .info),+ DetailStat(label: "Upcoming", value: "\(items.count)")],+ sections: [DetailSection(title: "Upcoming bookings", items: items,+ footer: items.isEmpty ? "Nothing booked." : nil)],+ fetchedAt: Date())+ }++ // n8n: workflows (activate, deactivate) and executions (retry a failed one).+ private static func n8n() async throws -> ServiceDetail {+ let key = try secret("n8n-api-key", "n8n")+ let base = try secret("n8n-url", "n8n").trimmingCharacters(in: CharacterSet(charactersIn: "/"))+ let headers = ["X-N8N-API-KEY": key, "Accept": "application/json"]+ // The list comes in pages (at most 250, then `cursor` = the previous `nextCursor`): read+ // them all so the counts are right.+ var workflows: [[String: Any]] = []+ var cursor: String?+ repeat {+ var url = "\(base)/api/v1/workflows?limit=250"+ if let cursor, let encoded = cursor.addingPercentEncoding(withAllowedCharacters: .alphanumerics) {+ url += "&cursor=\(encoded)"+ }+ let page = try await request(url, headers: headers) as? [String: Any]+ workflows += page?["data"] as? [[String: Any]] ?? []+ cursor = page?["nextCursor"] as? String+ } while !(cursor ?? "").isEmpty && workflows.count < 5_000+ var names: [String: String] = [:]+ var active = 0+ let workflowItems = workflows.compactMap { w -> DetailItem? in+ guard let id = (w["id"] as? String) ?? (w["id"] as? Int).map(String.init) else { return nil }+ let name = w["name"] as? String ?? "Workflow"+ names[id] = name+ // Archived workflows are listed but can't be turned on (n8n answers 400).+ if w["isArchived"] as? Bool ?? false { return nil }+ let isActive = w["active"] as? Bool ?? false+ if isActive { active += 1 }+ return DetailItem(title: name, tone: isActive ? .ok : .idle, date: date(w["updatedAt"]),+ url: "\(base)/workflow/\(id)", badge: isActive ? "Active" : "Off",+ actions: [isActive+ ? ServiceActionDef(kind: "n8n.deactivate", title: "Turn off", symbol: "pause.circle",+ target: id, destructive: true, confirm: "Stop \(name) from running?")+ : ServiceActionDef(kind: "n8n.activate", title: "Turn on", symbol: "play.circle", target: id)])+ }+ let executionsJSON = try? await request("\(base)/api/v1/executions?limit=15", headers: headers)+ let executions = (executionsJSON as? [String: Any])?["data"] as? [[String: Any]] ?? []+ var failed = 0+ let executionItems = executions.compactMap { e -> DetailItem? in+ guard let id = (e["id"] as? String) ?? (e["id"] as? Int).map(String.init) else { return nil }+ let workflowId = (e["workflowId"] as? String) ?? (e["workflowId"] as? Int).map(String.init) ?? ""+ let status = e["status"] as? String ?? ((e["finished"] as? Bool ?? false) ? "success" : "error")+ let isFailure = status == "error" || status == "crashed" || status == "failed"+ if isFailure { failed += 1 }+ return DetailItem(title: names[workflowId] ?? "Workflow \(workflowId)", subtitle: "Execution \(id)",+ tone: isFailure ? .error : (status == "success" ? .ok : .warning),+ date: date(e["startedAt"]), url: "\(base)/workflow/\(workflowId)/executions/\(id)",+ badge: status.capitalized,+ actions: isFailure ? [ServiceActionDef(kind: "n8n.retry", title: "Retry", symbol: "arrow.clockwise", target: id)] : [])+ }+ return ServiceDetail(pillId: "integration_n8n",+ stats: [DetailStat(label: "Workflows", value: "\(workflowItems.count)"),+ DetailStat(label: "Active", value: "\(active)", tone: .ok),+ DetailStat(label: "Failed runs", value: "\(failed)", tone: failed > 0 ? .error : .idle)],+ sections: [DetailSection(title: "Latest runs", items: executionItems),+ DetailSection(title: "Workflows",+ items: Array(workflowItems.sorted { ($0.date ?? .distantPast) > ($1.date ?? .distantPast) }.prefix(50)))],+ fetchedAt: Date())+ }++ // Notion: the pages and databases edited last. Read only.+ private static func notion() async throws -> ServiceDetail {+ let key = try secret("notion-api-key", "Notion")+ let headers = ["Authorization": "Bearer \(key)", "Notion-Version": "2022-06-28"]+ let json = try await request("https://api.notion.com/v1/search", method: "POST", headers: headers,+ body: ["sort": ["direction": "descending", "timestamp": "last_edited_time"], "page_size": 25])+ let results = (json as? [String: Any])?["results"] as? [[String: Any]] ?? []+ var pages: [DetailItem] = []+ var databases: [DetailItem] = []+ for object in results {+ let kind = object["object"] as? String ?? "page"+ var title = ""+ if kind == "database" {+ title = ((object["title"] as? [[String: Any]])?.compactMap { $0["plain_text"] as? String }.joined()) ?? ""+ } else if let properties = object["properties"] as? [String: Any] {+ for case let property as [String: Any] in properties.values where property["type"] as? String == "title" {+ title = ((property["title"] as? [[String: Any]])?.compactMap { $0["plain_text"] as? String }.joined()) ?? ""+ }+ }+ var emoji = ""+ if let icon = object["icon"] as? [String: Any], icon["type"] as? String == "emoji" { emoji = (icon["emoji"] as? String ?? "") + " " }+ let item = DetailItem(title: emoji + (title.isEmpty ? "Untitled" : title),+ date: date(object["last_edited_time"]), url: object["url"] as? String,+ badge: (object["archived"] as? Bool ?? false) ? "Archived" : nil)+ if kind == "database" { databases.append(item) } else { pages.append(item) }+ }+ var sections = [DetailSection(title: "Edited lately", items: pages)]+ if !databases.isEmpty { sections.append(DetailSection(title: "Databases", items: databases)) }+ let editedToday = results.filter { date($0["last_edited_time"]).map(Calendar.current.isDateInToday) ?? false }.count+ return ServiceDetail(pillId: "integration_notion",+ stats: [DetailStat(label: "Edited today", value: "\(editedToday)", tone: editedToday > 0 ? .info : .idle),+ DetailStat(label: "Pages", value: "\(pages.count)"),+ DetailStat(label: "Databases", value: "\(databases.count)")],+ sections: sections, fetchedAt: Date())+ }++ // MARK: Acting++ /// Runs one action. Returns a short line for the iPhone.+ static func perform(kind: String, target: String) async throws -> String {+ switch kind {+ case "vercel.redeploy":+ let parts = target.split(separator: "|", omittingEmptySubsequences: false).map(String.init)+ guard parts.count == 3 else { throw Failure(status: 0, message: "Unknown deployment") }+ var body: [String: Any] = ["name": parts[1], "deploymentId": parts[0]]+ if !parts[2].isEmpty { body["target"] = parts[2] }+ let json = try await request("https://api.vercel.com/v13/deployments", method: "POST",+ headers: try vercelHeaders(), body: body)+ let url = (json as? [String: Any])?["url"] as? String+ return url.map { "Building \($0)" } ?? "New deployment started"+ case "vercel.promote":+ // Vercel only promotes production builds in place: a preview is rebuilt for+ // production, as `vercel promote` does.+ let parts = target.split(separator: "|", omittingEmptySubsequences: false).map(String.init)+ guard parts.count == 2 else { throw Failure(status: 0, message: "Unknown deployment") }+ let json = try await request("https://api.vercel.com/v13/deployments", method: "POST",+ headers: try vercelHeaders(),+ body: ["deploymentId": parts[0], "name": parts[1], "target": "production",+ "meta": ["action": "promote"]])+ let url = (json as? [String: Any])?["url"] as? String+ return url.map { "Building \($0) for production" } ?? "Production build started"+ case "vercel.cancel":+ _ = try await request("https://api.vercel.com/v12/deployments/\(target)/cancel", method: "PATCH",+ headers: try vercelHeaders())+ return "Build canceled"+ case "github.rerun":+ // "owner/repo/123"+ let parts = target.split(separator: "/").map(String.init)+ guard parts.count == 3 else { throw Failure(status: 0, message: "Unknown run") }+ _ = try await request("https://api.github.com/repos/\(parts[0])/\(parts[1])/actions/runs/\(parts[2])/rerun-failed-jobs",+ method: "POST", headers: try githubHeaders())+ return "Failed jobs started again"+ case "github.approve", "github.merge":+ // "owner/repo#12"+ let pieces = target.split(separator: "#").map(String.init)+ guard pieces.count == 2 else { throw Failure(status: 0, message: "Unknown pull request") }+ if kind == "github.approve" {+ _ = try await request("https://api.github.com/repos/\(pieces[0])/pulls/\(pieces[1])/reviews", method: "POST",+ headers: try githubHeaders(), body: ["event": "APPROVE"])+ return "Approved"+ }+ _ = try await request("https://api.github.com/repos/\(pieces[0])/pulls/\(pieces[1])/merge", method: "PUT",+ headers: try githubHeaders(), body: ["merge_method": "squash"])+ return "Merged"+ case "n8n.activate", "n8n.deactivate", "n8n.retry":+ let key = try secret("n8n-api-key", "n8n")+ let base = try secret("n8n-url", "n8n").trimmingCharacters(in: CharacterSet(charactersIn: "/"))+ let headers = ["X-N8N-API-KEY": key, "Accept": "application/json"]+ switch kind {+ case "n8n.activate":+ _ = try await request("\(base)/api/v1/workflows/\(target)/activate", method: "POST", headers: headers)+ return "Turned on"+ case "n8n.deactivate":+ _ = try await request("\(base)/api/v1/workflows/\(target)/deactivate", method: "POST", headers: headers)+ return "Turned off"+ default:+ do {+ _ = try await request("\(base)/api/v1/executions/\(target)/retry", method: "POST", headers: headers)+ } catch let failure as Failure where failure.status == 404 || failure.status == 405 {+ // POST /api/v1/executions/{id}/retry only exists from n8n 1.112.0.+ throw Failure(status: 0, message: "Couldn't retry this run. It may have been deleted, or your n8n is older than 1.112, which is needed to retry from the iPhone.")+ }+ return "Running again"+ }+ default:+ throw Failure(status: 0, message: "This action isn't available")+ }+ }++ private static func vercelHeaders() throws -> [String: String] {+ let token = try secret("vercel-token", "Vercel")+ return ["Authorization": "Bearer \(token)", "Accept": "application/json"]+ }++ private static func githubHeaders() throws -> [String: String] {+ let token = try secret("github-token", "GitHub")+ return ["Authorization": "Bearer \(token)", "Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28"]+ }+}+#endifdiff --git a/NotchBuddy/Sources/CoucouKit/ServiceDetail.swift b/NotchBuddy/Sources/CoucouKit/ServiceDetail.swiftnew file mode 100644index 00000000..da4af811--- /dev/null+++ b/NotchBuddy/Sources/CoucouKit/ServiceDetail.swift@@ -0,0 +1,81 @@+import Foundation++// A service seen up close, for the iPhone: figures, lists and what can be+// done from there. When a service's screen opens, the iPhone asks the Mac for+// it (a `ServiceAction` record of kind "refresh"); the Mac reads the service's+// API with the key in its Keychain and writes a `ServiceDetail` record,+// encrypted. An action (redeploy, re-run, merge…) is the same kind of record:+// the Mac runs it only if the iPhone asked for one it offered on that item,+// then writes the detail again with the result. No key ever leaves the Mac.++struct ServiceActionDef: Codable, Equatable, Sendable, Hashable {+ /// What the Mac does, e.g. "vercel.redeploy", "github.merge".+ var kind: String+ var title: String+ var symbol: String+ /// The thing it acts on (deployment id, "owner/repo#12"…).+ var target: String+ var destructive: Bool = false+ /// Asked before doing it, when it can't be undone.+ var confirm: String? = nil+}++struct DetailStat: Codable, Equatable, Sendable {+ var label: String+ var value: String+ var tone: ServiceTone = .idle+}++struct DetailItem: Codable, Equatable, Sendable {+ var title: String+ var subtitle: String = ""+ var tone: ServiceTone = .idle+ var date: Date? = nil+ var url: String? = nil+ /// A short tag on the right ("Production", "Draft", "Active"…).+ var badge: String? = nil+ var actions: [ServiceActionDef] = []+}++struct DetailSection: Codable, Equatable, Sendable {+ var title: String+ var items: [DetailItem]+ var footer: String? = nil+}++struct ServiceActionResult: Codable, Equatable, Sendable {+ var title: String+ var ok: Bool+ var message: String+ var date: Date+}++struct ServiceDetail: Codable, Equatable, Sendable {+ var pillId: String+ var stats: [DetailStat] = []+ var sections: [DetailSection] = []+ var fetchedAt: Date+ /// Why the API couldn't be read (no key, 401…).+ var error: String? = nil+ var lastAction: ServiceActionResult? = nil++ static let recordType = "ServiceDetail"+ static let requestType = "ServiceAction"+ static let refreshKind = "refresh"++ static func recordName(for pillId: String) -> String { "detail-\(pillId)" }++ static func pillId(fromRecordName name: String) -> String? {+ name.hasPrefix("detail-") ? String(name.dropFirst("detail-".count)) : nil+ }++ /// The action offered on one of the items, if the Mac offered it.+ func offered(kind: String, target: String) -> ServiceActionDef? {+ for section in sections {+ for item in section.items {+ if let action = item.actions.first(where: { $0.kind == kind && $0.target == target }) { return action }+ }+ }+ return nil+ }+}diff --git a/NotchBuddy/Sources/Phone/AboutView.swift b/NotchBuddy/Sources/Phone/AboutView.swiftindex 84b74a22..3f40d86e 100644--- a/NotchBuddy/Sources/Phone/AboutView.swift+++ b/NotchBuddy/Sources/Phone/AboutView.swift@@ -11,6 +11,8 @@ struct AboutView: View {@AppStorage(PhoneSettings.quietHoursKey) private var quietHours = false@AppStorage(PhoneSettings.quietFromKey) private var quietFrom = 22 * 60@AppStorage(PhoneSettings.quietToKey) private var quietTo = 8 * 60+ @AppStorage(SpotlightIndex.enabledKey) private var spotlight = true+ @State private var currentIcon = AppIconChoice.currentprivate var version: String {let info = Bundle.main.infoDictionary@@ -73,6 +75,39 @@ struct AboutView: View {: "Approvals and questions always notify you. Mochi's sounds are the ones he makes in your Mac's notch.")}+ Section {+ ScrollView(.horizontal, showsIndicators: false) {+ HStack(spacing: 14) {+ ForEach(AppIconChoice.allCases) { choice in+ Button {+ AppIconChoice.apply(choice)+ currentIcon = choice+ } label: {+ VStack(spacing: 6) {+ Image(choice.previewName)+ .resizable()+ .frame(width: 58, height: 58)+ .clipShape(RoundedRectangle(cornerRadius: 13, style: .continuous))+ .overlay(RoundedRectangle(cornerRadius: 13, style: .continuous)+ .strokeBorder(currentIcon == choice ? Color.accentColor : .clear, lineWidth: 2.5)+ .padding(-4))+ Text(choice.title).font(.caption2).foregroundStyle(.secondary)+ }+ }+ .buttonStyle(.plain)+ }+ }+ .padding(.vertical, 8)+ .padding(.horizontal, 4)+ }+ Toggle("Find my turns in Spotlight", isOn: $spotlight)+ .onChange(of: spotlight) { _, on in if !on { SpotlightIndex.removeAll() } }+ } header: {+ Text("Look")+ } footer: {+ Text("The Home Screen icon follows your choice; dark and tinted icons follow the Home Screen style. Spotlight's index stays on this iPhone.")+ }+Section("Coucou") {Link("Website", destination: URL(string: "https://louis-cfm.github.io/coucou/")!)Link("Support", destination: URL(string: "https://louis-cfm.github.io/coucou/support.html")!)@@ -174,3 +209,33 @@ struct OnboardingView: View {}}}++/// Mochi's colors for the Home Screen icon (alternate app icons).+enum AppIconChoice: String, CaseIterable, Identifiable {+ case orange = "", blue = "AppIcon-Blue", green = "AppIcon-Green", purple = "AppIcon-Purple",+ pink = "AppIcon-Pink", graphite = "AppIcon-Graphite"++ var id: String { rawValue }++ var title: String {+ switch self {+ case .orange: "Orange"+ case .blue: "Blue"+ case .green: "Green"+ case .purple: "Purple"+ case .pink: "Pink"+ case .graphite: "Graphite"+ }+ }++ var previewName: String { "IconPreview-\(title)" }++ @MainActor static var current: AppIconChoice {+ AppIconChoice(rawValue: UIApplication.shared.alternateIconName ?? "") ?? .orange+ }++ @MainActor static func apply(_ choice: AppIconChoice) {+ guard UIApplication.shared.supportsAlternateIcons else { return }+ UIApplication.shared.setAlternateIconName(choice == .orange ? nil : choice.rawValue)+ }+}diff --git a/NotchBuddy/Sources/Phone/AgentNotifier.swift b/NotchBuddy/Sources/Phone/AgentNotifier.swiftindex b2a2e3d6..dec09aec 100644--- a/NotchBuddy/Sources/Phone/AgentNotifier.swift+++ b/NotchBuddy/Sources/Phone/AgentNotifier.swift@@ -9,6 +9,9 @@ enum PhoneSettings {static let quietHoursKey = "quietHours"static let quietFromKey = "quietFrom" // minutes after midnightstatic let quietToKey = "quietTo"+ /// Set by the Coucou Focus filter: only what waits on you notifies.+ static let focusOnlyWaitingKey = "focusOnlyWaiting"+ static var focusOnlyWaiting: Bool { defaults.bool(forKey: focusOnlyWaitingKey) }private static var defaults: UserDefaults { .standard }@@ -142,7 +145,7 @@ enum AgentNotifier {let quiet = PhoneSettings.isQuiet()switch event {case .finished(let session):- guard PhoneSettings.notifyDone else { return }+ guard PhoneSettings.notifyDone, !PhoneSettings.focusOnlyWaiting else { return }content.title = "\(session.pillName) · \(session.title)"let answer = turn.map(\.finalMessage).flatMap { $0.isEmpty ? nil : $0 } ?? session.finalLinecontent.body = answer.isEmpty ? "Done. What's next?" : "✓ " + String(answer.prefix(220))@@ -152,7 +155,7 @@ enum AgentNotifier {content.userInfo = ["pillId": session.id, "kind": "done"]if quiet { content.interruptionLevel = .passive }case .failed(let session):- guard PhoneSettings.notifyDone else { return }+ guard PhoneSettings.notifyDone, !PhoneSettings.focusOnlyWaiting else { return }content.title = "\(session.pillName) · \(session.title)"content.body = session.finalLine.isEmpty ? "Something went wrong." : String(session.finalLine.prefix(220))content.sound = quiet ? nil : PhoneSettings.sound("error")diff --git a/NotchBuddy/Sources/Phone/AppleStyle.swift b/NotchBuddy/Sources/Phone/AppleStyle.swiftnew file mode 100644index 00000000..19200877--- /dev/null+++ b/NotchBuddy/Sources/Phone/AppleStyle.swift@@ -0,0 +1,223 @@+import SwiftUI++// The pieces that make Coucou feel like an Apple app: Liquid Glass on iOS 26+// (a frosted material before), the agent's color moving softly behind a+// session, Apple Pay's drawn checkmark, and symbols that move with the state.++extension View {+ /// A card in glass (iOS 26) or the dark material Coucou used before.+ @ViewBuilder+ func glassCard(cornerRadius: CGFloat = 22, tint: Color? = nil) -> some View {+ if #available(iOS 26.0, *) {+ if let tint {+ glassEffect(.regular.tint(tint.opacity(0.25)), in: RoundedRectangle(cornerRadius: cornerRadius))+ } else {+ glassEffect(.regular, in: RoundedRectangle(cornerRadius: cornerRadius))+ }+ } else {+ background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: cornerRadius))+ }+ }++ /// A small glass shape for pills and fields (iOS 26), a dark fill before.+ @ViewBuilder+ func glassPill<S: Shape>(_ shape: S, interactive: Bool = false, tint: Color? = nil) -> some View {+ if #available(iOS 26.0, *) {+ let base: Glass = interactive ? .regular.interactive() : .regular+ if let tint {+ glassEffect(base.tint(tint.opacity(0.35)), in: shape)+ } else {+ glassEffect(base, in: shape)+ }+ } else {+ background(tint?.opacity(0.25) ?? Color(white: 0.16), in: shape)+ }+ }+}++/// The agent's color, moving slowly like the background of Apple Music. Drawn+/// in code (MeshGradient), 30 frames a second, only while on screen.+struct AgentBackdrop: View {+ let hex: String++ /// A soft glow from the top, fading into black.+ private var colors: [Color] {+ let base = Color(hex: Self.glowHex(for: hex))+ return [base.opacity(0.42), base.opacity(0.26), base.opacity(0.36),+ base.opacity(0.16), base.opacity(0.06), base.opacity(0.14),+ Color.clear, Color.clear, Color.clear]+ }++ /// White and grey agents (VS Code, Cursor) would make a dull grey haze:+ /// they glow in a deep blue instead.+ static func glowHex(for hex: String) -> String {+ let digits = hex.trimmingCharacters(in: CharacterSet(charactersIn: "#"))+ guard digits.count == 6, let value = Int(digits, radix: 16) else { return "#3B5BDB" }+ let r = Double((value >> 16) & 0xFF) / 255, g = Double((value >> 8) & 0xFF) / 255, b = Double(value & 0xFF) / 255+ let high = max(r, g, b), low = min(r, g, b)+ let saturation = high == 0 ? 0 : (high - low) / high+ return saturation < 0.25 ? "#3B5BDB" : hex+ }++ /// The middle points drift a little; the edges stay put.+ private static func points(at t: Float) -> [SIMD2<Float>] {+ let topX: Float = 0.5 + 0.1 * sin(t * 0.31)+ let leftY: Float = 0.5 + 0.08 * cos(t * 0.27)+ let midX: Float = 0.5 + 0.12 * cos(t * 0.23)+ let midY: Float = 0.45 + 0.1 * sin(t * 0.37)+ let rightY: Float = 0.5 + 0.08 * sin(t * 0.29)+ let bottomX: Float = 0.5 + 0.1 * cos(t * 0.33)+ return [+ SIMD2(0, 0), SIMD2(topX, 0), SIMD2(1, 0),+ SIMD2(0, leftY), SIMD2(midX, midY), SIMD2(1, rightY),+ SIMD2(0, 1), SIMD2(bottomX, 1), SIMD2(1, 1),+ ]+ }++ var body: some View {+ TimelineView(.animation(minimumInterval: 1 / 30)) { timeline in+ MeshGradient(width: 3, height: 3,+ points: Self.points(at: Float(timeline.date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: 3600))),+ colors: colors)+ }+ .ignoresSafeArea()+ .accessibilityHidden(true)+ }+}++/// Apple Pay's "Done": a green ring draws itself, then the checkmark.+struct DrawnCheckmark: View {+ var size: CGFloat = 56+ @State private var ring: CGFloat = 0+ @State private var tick: CGFloat = 0++ var body: some View {+ ZStack {+ Circle()+ .trim(from: 0, to: ring)+ .stroke(Color.green, style: StrokeStyle(lineWidth: size * 0.07, lineCap: .round))+ .rotationEffect(.degrees(-90))+ CheckShape()+ .trim(from: 0, to: tick)+ .stroke(Color.green, style: StrokeStyle(lineWidth: size * 0.08, lineCap: .round, lineJoin: .round))+ .padding(size * 0.28)+ }+ .frame(width: size, height: size)+ .onAppear {+ withAnimation(.easeOut(duration: 0.45)) { ring = 1 }+ withAnimation(.easeOut(duration: 0.3).delay(0.35)) { tick = 1 }+ }+ }++ private struct CheckShape: Shape {+ func path(in rect: CGRect) -> Path {+ var path = Path()+ path.move(to: CGPoint(x: rect.minX, y: rect.midY + rect.height * 0.05))+ path.addLine(to: CGPoint(x: rect.minX + rect.width * 0.38, y: rect.maxY - rect.height * 0.12))+ path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY + rect.height * 0.12))+ return path+ }+ }+}++/// A small symbol that moves with the session's state: it breathes while+/// waiting for you, pulses while working, wiggles on an error, bounces when done.+struct StateSymbol: View {+ let session: SessionItem++ var body: some View {+ switch session.urgency {+ case 0:+ Image(systemName: "hand.raised.fill").foregroundStyle(.orange)+ .symbolEffect(.breathe)+ case 1:+ Image(systemName: "questionmark.bubble.fill").foregroundStyle(.cyan)+ .symbolEffect(.breathe)+ case 2:+ Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.red)+ .symbolEffect(.wiggle, options: .repeat(2), value: session.updatedAt)+ case 3:+ Image(systemName: "ellipsis").foregroundStyle(.secondary)+ .symbolEffect(.variableColor.iterative)+ case 4:+ Image(systemName: "checkmark.circle.fill").foregroundStyle(.green)+ .symbolEffect(.bounce, value: session.updatedAt)+ default:+ Image(systemName: "moon.zzz.fill").foregroundStyle(.tertiary)+ }+ }+}++/// Deny and Allow, the iOS way: a quiet Deny, a bright Allow with Face ID.+struct ApprovalChoiceButtons: View {+ var disabled = false+ let deny: () -> Void+ let allow: () -> Void++ var body: some View {+ HStack(spacing: 10) {+ Button(action: deny) {+ Text("Deny")+ .font(.body.weight(.semibold))+ .foregroundStyle(.white)+ .frame(maxWidth: .infinity)+ .padding(.vertical, 13)+ .background(Color.white.opacity(0.14), in: Capsule())+ }+ Button(action: allow) {+ Label("Allow", systemImage: "faceid")+ .font(.body.weight(.semibold))+ .foregroundStyle(.black)+ .frame(maxWidth: .infinity)+ .padding(.vertical, 13)+ .background(Color.white, in: Capsule())+ }+ }+ .buttonStyle(PressableButtonStyle())+ .disabled(disabled)+ .opacity(disabled ? 0.6 : 1)+ }+}++/// Shrinks a little under the finger, like system buttons.+struct PressableButtonStyle: ButtonStyle {+ func makeBody(configuration: Configuration) -> some View {+ configuration.label+ .scaleEffect(configuration.isPressed ? 0.96 : 1)+ .opacity(configuration.isPressed ? 0.85 : 1)+ .animation(.spring(duration: 0.25, bounce: 0.3), value: configuration.isPressed)+ }+}++/// The command waiting for your OK: who asks, the exact command, Deny / Allow.+struct ApprovalPanel: View {+ let session: SessionItem+ var disabled = false+ let deny: () -> Void+ let allow: () -> Void++ var body: some View {+ VStack(alignment: .leading, spacing: 12) {+ HStack(spacing: 8) {+ Circle().fill(Color.orange).frame(width: 8, height: 8)+ .shadow(color: .orange.opacity(0.8), radius: 4)+ Text("\(session.pillName) asks to run")+ .font(.subheadline.weight(.semibold))+ .foregroundStyle(.orange)+ Spacer(minLength: 0)+ Text(session.title)+ .font(.caption)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ }+ Text(session.approvalCommand.isEmpty ? "A permission" : session.approvalCommand)+ .font(.callout.monospaced())+ .foregroundStyle(.white.opacity(0.92))+ .lineLimit(4)+ .frame(maxWidth: .infinity, alignment: .leading)+ .textSelection(.enabled)+ ApprovalChoiceButtons(disabled: disabled, deny: deny, allow: allow)+ }+ .padding(16)+ }+}diff --git a/NotchBuddy/Sources/Phone/ApprovalCard.swift b/NotchBuddy/Sources/Phone/ApprovalCard.swiftindex b6f1324b..a7e8a53b 100644--- a/NotchBuddy/Sources/Phone/ApprovalCard.swift+++ b/NotchBuddy/Sources/Phone/ApprovalCard.swift@@ -17,33 +17,31 @@ struct ApprovalCard: View {.font(.callout.monospaced()).frame(maxWidth: .infinity, alignment: .leading).padding(12)- .background(Color(white: 0.16), in: RoundedRectangle(cornerRadius: 12))+ .background(Color.white.opacity(0.07), 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)+ HStack(spacing: 12) {+ if sent == .allow {+ // Apple Pay's "Done": the ring, then the check, draw themselves.+ DrawnCheckmark(size: 34)+ } else {+ Image(systemName: "xmark.circle.fill").font(.title).foregroundStyle(.red)+ .symbolEffect(.bounce, value: sent)+ }+ Text(sent == .allow ? "Allowed, sent to your Mac" : "Denied, sent to your Mac")+ .font(.callout.weight(.semibold))+ .foregroundStyle(sent == .allow ? .green : .red)+ }+ .transition(.scale(scale: 0.8).combined(with: .opacity))} 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)+ ApprovalChoiceButtons(disabled: sending != nil) {+ Task { await send(.deny) }+ } allow: {+ Task { await send(.allow) }}- .controlSize(.large)- .disabled(sending != nil)Text("Allow asks for Face ID. The request expires after 2 minutes.").font(.caption).foregroundStyle(.secondary)}@@ -52,8 +50,9 @@ struct ApprovalCard: View {}}.padding(16)- .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))- .overlay(RoundedRectangle(cornerRadius: 22).strokeBorder(Color.orange.opacity(0.7), lineWidth: 1.5))+ .glassCard()+ .overlay(RoundedRectangle(cornerRadius: 22).strokeBorder(Color.orange.opacity(0.35), lineWidth: 1))+ .animation(.spring(duration: 0.5, bounce: 0.3), value: sent).onChange(of: session.approvalFingerprint) { sent = nil; error = nil }}diff --git a/NotchBuddy/Sources/Phone/CoucouIntents.swift b/NotchBuddy/Sources/Phone/CoucouIntents.swiftindex 801f8767..d5aa4752 100644--- a/NotchBuddy/Sources/Phone/CoucouIntents.swift+++ b/NotchBuddy/Sources/Phone/CoucouIntents.swift@@ -67,3 +67,24 @@ struct CoucouShortcuts: AppShortcutsProvider {systemImageName: "sparkles")}}++/// A Focus filter: in a Focus (Sleep, Work…), Coucou can keep quiet about+/// finished and failed agents and only notify what waits on you.+struct CoucouFocusFilter: SetFocusFilterIntent {+ static let title: LocalizedStringResource = "Coucou"+ static var description: IntentDescription {+ IntentDescription("Choose what Coucou notifies during this Focus.")+ }++ @Parameter(title: "Only approvals and questions", default: false)+ var onlyWaiting: Bool++ var displayRepresentation: DisplayRepresentation {+ DisplayRepresentation(title: onlyWaiting ? "Only approvals and questions" : "Everything")+ }++ func perform() async throws -> some IntentResult {+ UserDefaults.standard.set(onlyWaiting, forKey: PhoneSettings.focusOnlyWaitingKey)+ return .result()+ }+}diff --git a/NotchBuddy/Sources/Phone/HomeView.swift b/NotchBuddy/Sources/Phone/HomeView.swiftindex dcc30fa2..d077eb69 100644--- a/NotchBuddy/Sources/Phone/HomeView.swift+++ b/NotchBuddy/Sources/Phone/HomeView.swift@@ -1,81 +1,161 @@import SwiftUI+import UIKit++/// The tabs, in glass on iOS 26: the agents, the services, the decisions you+/// took, and a search through every turn.+enum CoucouTab: Hashable { case agents, services, history, search }-/// Main screen: the notch on top, every agent session from the Mac (most-/// urgent first), then every service Mochi.struct HomeView: View {let link: PhoneLink- @State private var path: [String] = []+ @State private var tab: CoucouTab = .agents+ @State private var agentsPath: [String] = []+ @State private var servicesPath: [String] = []+ @State private var introDone = false@AppStorage("onboardingDone") private var onboardingDone = false+ var body: some View {+ TabView(selection: $tab) {+ Tab("Agents", systemImage: "sparkles", value: CoucouTab.agents) {+ AgentsTab(link: link, path: $agentsPath)+ }+ Tab("Services", systemImage: "square.grid.2x2", value: CoucouTab.services) {+ ServicesTab(link: link, path: $servicesPath)+ }+ Tab("History", systemImage: "clock.arrow.circlepath", value: CoucouTab.history) {+ NavigationStack { HistoryView(link: link) }+ }+ Tab(value: CoucouTab.search, role: .search) {+ SearchTab(link: link)+ }+ }+ // A widget tile was tapped: open that Mochi.+ .onOpenURL { url in+ if let id = SharedSession.sessionId(from: url) { open(id) }+ }+ // A notification, Siri, Spotlight or the Control Center asked for a session.+ .onChange(of: link.openPillId) { _, id in+ guard let id else { return }+ open(id)+ link.openPillId = nil+ }+ .onContinueUserActivity(SpotlightIndex.activityType) { activity in+ if let id = SpotlightIndex.pillId(from: activity) { open(id) }+ }+ .sheet(isPresented: Binding(get: { link.reviewFingerprint != nil },+ set: { if !$0 { link.reviewFingerprint = nil } })) {+ if let fingerprint = link.reviewFingerprint {+ ReviewSheet(link: link, fingerprint: fingerprint)+ }+ }+ // First launch: how to connect the Mac.+ .fullScreenCover(isPresented: Binding(get: { !onboardingDone }, set: { if !$0 { onboardingDone = true } })) {+ OnboardingView()+ }+ // The opening: Mochi alone while the app loads, then he flies to his tile.+ .overlay {+ if !introDone {+ IntroView(ready: link.firstSyncDone) { introDone = true }+ .transition(.identity)+ }+ }+ .onAppear {+ // The first launch opens on the setup guide instead.+ if !onboardingDone {+ introDone = true+ IntroLanding.shared.landed = true+ }+ }+ }++ private func open(_ id: String) {+ if PillCatalog.isSession(id) {+ tab = .agents+ agentsPath = [id]+ } else {+ tab = .services+ servicesPath = [id]+ }+ }+}++/// Every agent session from the Mac, most urgent first. Swipe right to allow+/// (Face ID), left to deny; press and hold for a peek at the last turn.+struct AgentsTab: View {+ let link: PhoneLink+ @Binding var path: [String]+ @Namespace private var zoom+var body: some View {NavigationStack(path: $path) {- ScrollView {- VStack(spacing: 16) {- NotchHeader(sessions: link.sessions, status: link.status)+ List {+ Section {+ NotchHeader(link: link)+ // Shrinks and fades as the list scrolls, like Wallet.+ .visualEffect { content, proxy in+ let y = proxy.frame(in: .scrollView).minY+ let pull = min(0, y - 8)+ return content+ .scaleEffect(max(0.86, 1 + pull / 500), anchor: .top)+ .opacity(max(0, 1 + pull / 160))+ }TodayCard(link: link)+ }+ .listRowBackground(Color.clear)+ .listRowInsets(EdgeInsets(top: 6, leading: 0, bottom: 6, trailing: 0))+ .listRowSeparator(.hidden)++ Section {if link.sessions.isEmpty {EmptySessionsView(status: link.status)- } else {- VStack(spacing: 0) {- let sorted = link.sessions.sortedByUrgency()- ForEach(sorted) { session in- NavigationLink(value: session.id) {- SessionRow(session: session)+ .listRowBackground(Color.clear)+ .listRowInsets(EdgeInsets())+ }+ ForEach(link.sessions.sortedByUrgency()) { session in+ NavigationLink(value: session.id) {+ SessionRow(session: session, zoom: zoom)+ }+ .swipeActions(edge: .leading, allowsFullSwipe: true) {+ if session.needsApproval && !session.approvalFingerprint.isEmpty {+ Button {+ Task { _ = await QuickDecision.allow(session, link: link) }+ } label: {+ Label("Allow", systemImage: "faceid")}- .buttonStyle(.plain)- if session.id != sorted.last?.id {- Divider().padding(.leading, 64)+ .tint(.green)+ }+ }+ .swipeActions(edge: .trailing, allowsFullSwipe: true) {+ if session.needsApproval && !session.approvalFingerprint.isEmpty {+ Button(role: .destructive) {+ Task { _ = await QuickDecision.deny(session, link: link) }+ } label: {+ Label("Deny", systemImage: "xmark")}}}- .padding(.vertical, 6)- .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))- // Sessions move to their new place and change status smoothly.- .animation(.spring(duration: 0.5, bounce: 0.2),- value: link.sessions.map { "\($0.id)|\($0.statusText)" })+ .contextMenu {+ SessionMenu(link: link, session: session)+ } preview: {+ SessionPeek(session: session, turn: link.turns[session.id])+ }}- ServicesList(services: link.services)}- .padding(.horizontal, 16)- .padding(.bottom, 24)}+ .listStyle(.insetGrouped)+ .scrollContentBackground(.hidden).background(Color.black)+ // Sessions move to their new place and change status smoothly.+ .animation(.spring(duration: 0.5, bounce: 0.2),+ value: link.sessions.map { "\($0.id)|\($0.statusText)" }).refreshable { await link.refresh() }+ .navigationTitle("Coucou")+ .navigationBarTitleDisplayMode(.inline).navigationDestination(for: String.self) { id in- if PillCatalog.isSession(id) {- SessionDetailView(link: link, sessionId: id)- } else {- ServiceDetailView(link: link, pillId: id)- }- }- // A widget tile was tapped: open that Mochi.- .onOpenURL { url in- if let id = SharedSession.sessionId(from: url) { path = [id] }- }- // A notification, Siri or the Control Center asked for a session.- .onChange(of: link.openPillId) { _, id in- guard let id else { return }- path = [id]- link.openPillId = nil- }- .sheet(isPresented: Binding(get: { link.reviewFingerprint != nil },- set: { if !$0 { link.reviewFingerprint = nil } })) {- if let fingerprint = link.reviewFingerprint {- ReviewSheet(link: link, fingerprint: fingerprint)- }- }- // First launch: how to connect the Mac.- .fullScreenCover(isPresented: Binding(get: { !onboardingDone }, set: { if !$0 { onboardingDone = true } })) {- OnboardingView()+ SessionDetailView(link: link, sessionId: id)+ // The Mochi tile grows into the session, and shrinks back.+ .navigationTransition(.zoom(sourceID: id, in: zoom))}.toolbar {- ToolbarItem(placement: .topBarLeading) {- NavigationLink {- HistoryView(link: link)- } label: {- Image(systemName: "clock.arrow.circlepath")- }- }ToolbarItem(placement: .topBarTrailing) {NavigationLink {AboutView(link: link)@@ -84,8 +164,8 @@ struct HomeView: View {}}#if DEBUG- // Test screens, in builds run from Xcode only (the link test has its own "Kit" button).- ToolbarItem(placement: .topBarTrailing) {+ // Test screens, in builds run from Xcode only.+ ToolbarItem(placement: .topBarLeading) {NavigationLink {LinkTestView(link: link)} label: {@@ -98,15 +178,226 @@ struct HomeView: View {}}-/// The black island at the top: Mochi with the most urgent state and a summary.+/// The service Mochi (GitHub, Stripe…), each with what it saw.+struct ServicesTab: View {+ let link: PhoneLink+ @Binding var path: [String]+ @Namespace private var zoom++ var body: some View {+ NavigationStack(path: $path) {+ ScrollView {+ ServicesList(services: link.services)+ .padding(.horizontal, 16)+ .padding(.vertical, 12)+ }+ .background(Color.black)+ .refreshable { await link.refresh() }+ .navigationTitle("Services")+ .navigationDestination(for: String.self) { id in+ ServiceDetailView(link: link, pillId: id)+ }+ }+ }+}++/// Allow (Face ID) and Deny without opening the session.+@MainActor+enum QuickDecision {+ static func allow(_ session: SessionItem, link: PhoneLink) async -> Bool {+ guard await OwnerCheck.confirm(reason: "Allow this command on your Mac") else {+ Haptics.warning()+ return false+ }+ let summary = session.approvalCommand.isEmpty ? "Permission" : session.approvalCommand+ let sent = await link.decide(.allow, fingerprint: session.approvalFingerprint, pillId: session.id,+ summary: String(summary.prefix(200)))+ if sent { Haptics.success() } else { Haptics.error() }+ return sent+ }++ static func deny(_ session: SessionItem, link: PhoneLink) async -> Bool {+ let summary = session.approvalCommand.isEmpty ? "Permission" : session.approvalCommand+ let sent = await link.decide(.deny, fingerprint: session.approvalFingerprint, pillId: session.id,+ summary: String(summary.prefix(200)))+ if sent { Haptics.impact() } else { Haptics.error() }+ return sent+ }+}++/// What a long press on a session offers.+struct SessionMenu: View {+ let link: PhoneLink+ let session: SessionItem++ var body: some View {+ if session.needsApproval && !session.approvalFingerprint.isEmpty {+ Button {+ Task { _ = await QuickDecision.allow(session, link: link) }+ } label: {+ Label("Allow", systemImage: "faceid")+ }+ Button(role: .destructive) {+ Task { _ = await QuickDecision.deny(session, link: link) }+ } label: {+ Label("Deny", systemImage: "xmark")+ }+ }+ if !session.approvalCommand.isEmpty {+ Button {+ UIPasteboard.general.string = session.approvalCommand+ } label: {+ Label("Copy the command", systemImage: "doc.on.doc")+ }+ }+ if let answer = link.turns[session.id]?.finalMessage, !answer.isEmpty {+ Button {+ UIPasteboard.general.string = answer+ } label: {+ Label("Copy Claude's answer", systemImage: "text.quote")+ }+ }+ Button {+ link.openPillId = session.id+ } label: {+ Label("Open", systemImage: "arrow.up.forward.app")+ }+ }+}++/// The peek of a long press: who, where it is, and the last turn in short.+struct SessionPeek: View {+ let session: SessionItem+ let turn: TurnSnapshot?++ var body: some View {+ VStack(alignment: .leading, spacing: 12) {+ HStack(spacing: 12) {+ MochiStill(state: session.state, bodyHex: session.color)+ .padding(6)+ .frame(width: 48, height: 48)+ .background(Color.mochiTile(hex: session.color), in: RoundedRectangle(cornerRadius: 13))+ VStack(alignment: .leading, spacing: 2) {+ Text(session.title).font(.headline)+ Text(session.statusText).font(.subheadline.weight(.semibold)).foregroundStyle(session.statusColor)+ }+ }+ if session.needsApproval, !session.approvalCommand.isEmpty {+ Text(session.approvalCommand)+ .font(.callout.monospaced())+ .lineLimit(5)+ .padding(10)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Color.white.opacity(0.08), in: RoundedRectangle(cornerRadius: 10))+ }+ if let turn {+ Text(turn.headline)+ .font(.callout)+ .lineLimit(3)+ .padding(10)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Color.accentColor.opacity(0.25), in: RoundedRectangle(cornerRadius: 12))+ HStack(spacing: 14) {+ Label("\(turn.actions.count)", systemImage: "wrench.and.screwdriver")+ Label("\(turn.files.count)", systemImage: "doc.text")+ }+ .font(.caption)+ .foregroundStyle(.secondary)+ if !turn.finalMessage.isEmpty {+ Text(turn.finalMessage).font(.callout).foregroundStyle(.secondary).lineLimit(6)+ }+ }+ }+ .padding(18)+ .frame(width: 340, alignment: .leading)+ .background(Color(white: 0.09))+ .environment(\.colorScheme, .dark)+ }+}++/// The black island at the top: Mochi with the most urgent state and a+/// summary. When a command waits for your OK, Allow and Deny grow out of it+/// (Liquid Glass morphing on iOS 26) and fold back once answered.struct NotchHeader: View {- let sessions: [SessionItem]- let status: PhoneLink.Status+ let link: PhoneLink+ @Namespace private var glass+ @State private var sending = false+ @State private var approved = false++ private var sessions: [SessionItem] { link.sessions }++ /// The session waiting for an OK this iPhone can give.+ private var waiting: SessionItem? {+ sessions.sortedByUrgency().first { $0.needsApproval && !$0.approvalFingerprint.isEmpty }+ }var body: some View {+ Group {+ if #available(iOS 26.0, *) {+ GlassEffectContainer(spacing: 12) {+ VStack(spacing: 12) {+ summary+ .glassEffect(.regular, in: RoundedRectangle(cornerRadius: 28))+ .glassEffectID("island", in: glass)+ if let waiting {+ panel(waiting)+ .glassEffect(.regular, in: RoundedRectangle(cornerRadius: 26))+ .glassEffectID("panel", in: glass)+ }+ }+ }+ } else {+ VStack(spacing: 12) {+ summary+ .background(Color(white: 0.09), in: RoundedRectangle(cornerRadius: 28))+ .overlay(RoundedRectangle(cornerRadius: 28).strokeBorder(Color.white.opacity(0.12), lineWidth: 1))+ if let waiting {+ panel(waiting)+ .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 26))+ .transition(.move(edge: .top).combined(with: .opacity))+ }+ }+ }+ }+ .overlay {+ if approved {+ DrawnCheckmark(size: 64)+ .padding(14)+ .background(.ultraThinMaterial, in: Circle())+ .transition(.scale.combined(with: .opacity))+ }+ }+ .animation(.spring(duration: 0.55, bounce: 0.3), value: waiting?.approvalFingerprint)+ .animation(.spring(duration: 0.5, bounce: 0.2), value: "\(headline)|\(detail ?? "")")+ .animation(.spring(duration: 0.4, bounce: 0.3), value: approved)+ .sensoryFeedback(.success, trigger: approved) { _, new in new }+ }++ private func panel(_ session: SessionItem) -> some View {+ ApprovalPanel(session: session, disabled: sending) {+ Task {+ sending = true+ _ = await QuickDecision.deny(session, link: link)+ sending = false+ }+ } allow: {+ Task {+ sending = true+ if await QuickDecision.allow(session, link: link) {+ approved = true+ try? await Task.sleep(for: .seconds(1.4))+ approved = false+ }+ sending = false+ }+ }+ }++ private var summary: some View {HStack(spacing: 14) {MochiLive(state: sessions.leadState).frame(width: 52, height: 52)+ .introLanding(.header)VStack(alignment: .leading, spacing: 3) {Text(headline).font(.headline)@@ -124,17 +415,10 @@ struct NotchHeader: View {}.padding(.horizontal, 18).padding(.vertical, 14)- .background(Color.black, in: RoundedRectangle(cornerRadius: 28))- .overlay(- RoundedRectangle(cornerRadius: 28)- .strokeBorder(sessions.contains(where: \.isWaitingForYou) ? Color.orange.opacity(0.8) : Color.white.opacity(0.12),- lineWidth: 1.5)- )- .animation(.spring(duration: 0.5, bounce: 0.2), value: "\(headline)|\(detail ?? "")")}private var headline: String {- switch status {+ switch link.status {case .noAccount: return "iCloud not connected"case .failed: return "Can't reach iCloud"default: break@@ -150,13 +434,11 @@ struct NotchHeader: View {struct SessionRow: View {let session: SessionItem+ var zoom: Namespace.ID? = nilvar body: some View {HStack(spacing: 12) {- MochiLive(state: session.state, fps: 20)- .padding(4)- .frame(width: 40, height: 40)- .background(Color.mochiTile(hex: session.color), in: RoundedRectangle(cornerRadius: 11))+ tileVStack(alignment: .leading, spacing: 2) {Text(session.title).font(.body.weight(.semibold))@@ -171,19 +453,42 @@ struct SessionRow: View {}Spacer(minLength: 8)VStack(alignment: .trailing, spacing: 2) {- Text(session.statusText)- .font(.subheadline.weight(session.isWaitingForYou ? .semibold : .regular))- .foregroundStyle(session.statusColor)- .contentTransition(.interpolate)+ HStack(spacing: 5) {+ StateSymbol(session: session).font(.caption)+ Text(session.statusText)+ .font(.subheadline.weight(session.isWaitingForYou ? .semibold : .regular))+ .foregroundStyle(session.statusColor)+ .contentTransition(.interpolate)+ }Text(session.updatedAt, style: .relative).font(.caption2).foregroundStyle(.tertiary)}}- .padding(.horizontal, 14)- .padding(.vertical, 10)+ .padding(.vertical, 4).contentShape(Rectangle())}++ @ViewBuilder private var tile: some View {+ let base = mochi+ .padding(4)+ .frame(width: 40, height: 40)+ .background(Color.mochiTile(hex: session.color), in: RoundedRectangle(cornerRadius: 11))+ if let zoom {+ base.matchedTransitionSource(id: session.id, in: zoom)+ } else {+ base+ }+ }++ /// VS Code's Mochi is where the intro's Mochi lands.+ @ViewBuilder private var mochi: some View {+ if session.id == "integration_claude" {+ MochiLive(state: session.state, fps: 60).introLanding(.tile)+ } else {+ MochiLive(state: session.state, fps: 60)+ }+ }}struct EmptySessionsView: View {@@ -198,7 +503,7 @@ struct EmptySessionsView: View {}.frame(maxWidth: .infinity).padding(24)- .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))+ .glassCard()}private var message: String {@@ -241,7 +546,7 @@ struct TodayCard: View {stat("\(decisionsToday)", decisionsToday == 1 ? "OK given" : "OKs given")}.padding(.vertical, 12)- .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))+ .glassCard().overlay(alignment: .topLeading) {Text("TODAY").font(.caption2.weight(.bold))diff --git a/NotchBuddy/Sources/Phone/InstructionComposer.swift b/NotchBuddy/Sources/Phone/InstructionComposer.swiftindex 0606ca7c..e693d75f 100644--- a/NotchBuddy/Sources/Phone/InstructionComposer.swift+++ b/NotchBuddy/Sources/Phone/InstructionComposer.swift@@ -30,11 +30,16 @@ struct InstructionComposer: View {.foregroundStyle(.secondary)}}- .padding(.horizontal, 16)- .padding(.top, 10)- .padding(.bottom, 8)- .background(.bar)- .overlay(alignment: .top) { Divider() }+ // Floating, like Messages on iOS 26: no bar behind it, the screen+ // fades out underneath.+ .padding(.horizontal, 12)+ .padding(.top, 14)+ .padding(.bottom, 6)+ .background(alignment: .bottom) {+ LinearGradient(colors: [.clear, .black.opacity(0.85), .black], startPoint: .top, endPoint: .bottom)+ .ignoresSafeArea()+ .allowsHitTesting(false)+ }.onChange(of: dictation.transcript) { _, words inif dictation.isRecording { text = dictation.prefix + words }}@@ -52,13 +57,13 @@ struct InstructionComposer: View {Haptics.impact()} label: {Text(reply)- .font(.footnote)+ .font(.footnote.weight(.medium)).lineLimit(1)- .padding(.horizontal, 10)- .padding(.vertical, 6)- .background(Color(white: 0.16), in: Capsule())+ .padding(.horizontal, 12)+ .padding(.vertical, 7)+ .glassPill(Capsule(), interactive: true)}- .buttonStyle(.plain)+ .buttonStyle(PressableButtonStyle()).contextMenu {Button(role: .destructive) {quickReplies.removeAll { $0 == reply }@@ -77,51 +82,64 @@ struct InstructionComposer: View {} label: {Label("Keep", systemImage: "plus").font(.footnote.weight(.semibold))- .padding(.horizontal, 10)- .padding(.vertical, 6)- .background(Color.accentColor.opacity(0.25), in: Capsule())+ .padding(.horizontal, 12)+ .padding(.vertical, 7)+ .glassPill(Capsule(), interactive: true, tint: .accentColor)}- .buttonStyle(.plain)+ .buttonStyle(PressableButtonStyle())}}}}+ /// One glass capsule with the field, the language and the mic inside,+ /// and the send button next to it, like Messages.private var composer: some View {- HStack(alignment: .bottom, spacing: 8) {- TextField("Tell Claude what to do next…", text: $text, axis: .vertical)- .lineLimit(1...8)- .focused($focused)- .padding(.horizontal, 12)- .padding(.vertical, 9)- .background(Color(white: 0.16), in: RoundedRectangle(cornerRadius: 18))- Menu {- Picker("Dictation language", selection: $dictation.localeID) {- ForEach(Dictation.languages, id: \.self) { id in- Text(Locale.current.localizedString(forIdentifier: id) ?? id).tag(id)+ let empty = text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ return HStack(alignment: .bottom, spacing: 8) {+ HStack(alignment: .bottom, spacing: 2) {+ TextField("Tell Claude what to do next…", text: $text, axis: .vertical)+ .lineLimit(1...8)+ .focused($focused)+ .padding(.leading, 16)+ .padding(.vertical, 11)+ Menu {+ Picker("Dictation language", selection: $dictation.localeID) {+ ForEach(Dictation.languages, id: \.self) { id in+ Text(Locale.current.localizedString(forIdentifier: id) ?? id).tag(id)+ }}+ } label: {+ Text(Dictation.shortName(dictation.localeID))+ .font(.caption2.weight(.bold))+ .foregroundStyle(.secondary)+ .frame(width: 28, height: 42)}- } label: {- Text(Dictation.shortName(dictation.localeID))- .font(.caption2.weight(.bold))- .foregroundStyle(.secondary)- .frame(width: 26, height: 36)- }- Button {- Task { await dictation.toggle(startingFrom: text) }- } label: {- Image(systemName: dictation.isRecording ? "stop.circle.fill" : "mic.fill")- .font(.title3)- .foregroundStyle(dictation.isRecording ? Color.red : Color.secondary)- .frame(width: 36, height: 36)+ Button {+ Task { await dictation.toggle(startingFrom: text) }+ } label: {+ Image(systemName: dictation.isRecording ? "waveform" : "mic.fill")+ .font(.body)+ .foregroundStyle(dictation.isRecording ? Color.red : Color.secondary)+ .symbolEffect(.variableColor.iterative, isActive: dictation.isRecording)+ .frame(width: 38, height: 42)+ }+ .padding(.trailing, 4)}+ .glassPill(RoundedRectangle(cornerRadius: 22, style: .continuous))Button {Task { await send() }} label: {- Image(systemName: "arrow.up.circle.fill")- .font(.system(size: 32))+ Image(systemName: "arrow.up")+ .font(.body.weight(.bold))+ .foregroundStyle(empty ? Color.secondary : Color.black)+ .frame(width: 44, height: 44)+ .background(empty ? Color.white.opacity(0.12) : Color.white, in: Circle())+ .contentTransition(.symbolEffect(.replace))}- .disabled(text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || sending)+ .buttonStyle(PressableButtonStyle())+ .disabled(empty || sending)+ .animation(.spring(duration: 0.3), value: empty)}}diff --git a/NotchBuddy/Sources/Phone/IntroView.swift b/NotchBuddy/Sources/Phone/IntroView.swiftnew file mode 100644index 00000000..ef689602--- /dev/null+++ b/NotchBuddy/Sources/Phone/IntroView.swift@@ -0,0 +1,337 @@+import SwiftUI+import QuartzCore++// The opening: Mochi alone on black while the app loads. He pops in and looks+// around like the greeting on the Mac (without the hands): quick glances and+// slow ones, eyes that pop round, shrink or squint to a bar, his body leaning,+// hopping and squashing along. It hides the first iCloud fetch: as soon as+// it's over he finishes with a little hop and flies to his spot on the home+// screen, the VS Code session's tile (or the island at the top), and the home+// screen behind is already up to date.++/// Where the intro's Mochi lands. The tile reports its frame on screen.+@MainActor+@Observable+final class IntroLanding {+ static let shared = IntroLanding()++ var tileFrame: CGRect?+ var headerFrame: CGRect?+ /// The intro is over: the real Mochi on the home screen show again.+ var landed = false++ var target: CGRect? { tileFrame ?? headerFrame }+}++extension View {+ /// Reports this view's frame as the intro's landing spot; hidden until he lands.+ func introLanding(_ kind: IntroLandingKind) -> some View {+ modifier(IntroLandingModifier(kind: kind))+ }+}++enum IntroLandingKind { case tile, header }++private struct IntroLandingModifier: ViewModifier {+ let kind: IntroLandingKind+ private var landing: IntroLanding { .shared }++ func body(content: Content) -> some View {+ content+ .opacity(landing.landed || !isTarget ? 1 : 0)+ .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame in+ switch kind {+ case .tile: landing.tileFrame = frame+ case .header: landing.headerFrame = frame+ }+ }+ .onDisappear {+ if kind == .tile { landing.tileFrame = nil }+ }+ }++ /// Only the spot he actually flies to is hidden.+ private var isTarget: Bool {+ switch kind {+ case .tile: true+ case .header: landing.tileFrame == nil+ }+ }+}++struct IntroView: View {+ /// True once the first iCloud fetch is over.+ let ready: Bool+ let onFinished: () -> Void++ @State private var flightStart: Date?+ @State private var fade = false+ @State private var engine = IntroEngine()+ private var landing: IntroLanding { .shared }++ /// He plays at least this long, even when everything is already there,+ /// and never keeps the app waiting longer than `maximum`.+ private let minimum: TimeInterval = 2.4+ private let maximum: TimeInterval = 6+ private let size: CGFloat = 132++ var body: some View {+ GeometryReader { proxy in+ let center = CGPoint(x: proxy.size.width / 2, y: proxy.size.height / 2)+ let target = landing.target+ let flying = flightStart != nil+ ZStack {+ Color.black+ .opacity(fade ? 0 : 1)+ TimelineView(.animation) { timeline in+ Canvas { context, size in+ let now = timeline.date+ // Over 0.4 s of the flight his face settles back to neutral.+ let settle = flightStart.map { min(1, now.timeIntervalSince($0) / 0.4) } ?? 0+ engine.draw(context: context, size: size, settle: settle)+ }+ }+ .frame(width: flying ? (target?.width ?? size) : size,+ height: flying ? (target?.height ?? size) : size)+ .position(flying ? CGPoint(x: target?.midX ?? center.x, y: target?.midY ?? center.y) : center)+ .opacity(flying && target == nil ? 0 : 1)+ }+ .ignoresSafeArea()+ }+ .ignoresSafeArea()+ .allowsHitTesting(!fade)+ .task {+ try? await Task.sleep(for: .seconds(minimum))+ var waited = minimum+ while !ready && waited < maximum {+ try? await Task.sleep(for: .milliseconds(100))+ waited += 0.1+ }+ // Everything is there: a last hop looking at you, then off he goes.+ engine.finish()+ try? await Task.sleep(for: .milliseconds(480))+ withAnimation(.spring(duration: 0.7, bounce: 0.22)) { flightStart = Date() }+ withAnimation(.easeOut(duration: 0.5).delay(0.12)) { fade = true }+ try? await Task.sleep(for: .milliseconds(700))+ landing.landed = true+ onFinished()+ }+ }+}++/// A damped spring: stiff ones snap (a glance), soft ones drift (a slow look).+private struct Spring {+ var value: CGFloat+ var velocity: CGFloat = 0+ var target: CGFloat+ /// Stiffness and damping of the move in progress.+ var k: CGFloat = 200+ var c: CGFloat = 26++ init(_ value: CGFloat) {+ self.value = value+ target = value+ }++ mutating func go(_ target: CGFloat, _ motion: Motion) {+ self.target = target+ k = motion.k+ c = motion.c+ }++ mutating func step(_ dt: CGFloat) {+ velocity += (k * (target - value) - c * velocity) * dt+ value += velocity * dt+ }+}++/// How a move happens.+private struct Motion {+ var k: CGFloat+ var c: CGFloat+ /// A glance: very fast, a hint of overshoot.+ static let snap = Motion(k: 900, c: 42)+ /// A normal look.+ static let look = Motion(k: 260, c: 28)+ /// A slow, curious drift.+ static let drift = Motion(k: 55, c: 14)+ /// Eyes popping open: bouncy.+ static let pop = Motion(k: 520, c: 16)+ /// Squinting: quick, no bounce.+ static let squint = Motion(k: 700, c: 52)+ /// Reopening after a squint: slow.+ static let ease = Motion(k: 90, c: 17)+}++/// Mochi's face and body for the opening, drawn by the same engine as+/// everywhere else, driven here by a little show of moves. Each move has its+/// own speed, his body follows where he looks (leans, drifts, tilts with the+/// motion) and hops land with a squash, so it never feels mechanical. The+/// eyes stay the same pill and only change size and height: no blink.+@MainActor+final class IntroEngine {+ private let bot: BotEngine = {+ let bot = BotEngine()+ bot.isMini = true+ bot.bodyColor = cgColorFromHex("#FFFFFF")+ bot.setState(.idle, force: true)+ return bot+ }()++ private enum Body { case none, hop, squash, shiver }++ private struct Beat {+ var x: CGFloat = 0, y: CGFloat = 0+ var gaze: Motion = .look+ var eyes: CGFloat = 1, open: CGFloat = 1+ var eyeMotion: Motion = .look+ var body: Body = .none+ /// How long he stays on it.+ var hold: Double+ }++ /// The show, in order, then random moves from `idle` while iCloud is still busy.+ private static let show: [Beat] = [+ Beat(eyes: 1.05, eyeMotion: .pop, hold: 0.42), // hello+ Beat(x: -0.75, y: 0.05, gaze: .snap, hold: 0.5), // glance left+ Beat(x: 0.62, y: 0.16, gaze: .drift, eyes: 0.82, eyeMotion: .drift, hold: 0.75), // slowly to the right+ Beat(x: 0.08, y: -0.45, gaze: .look, eyes: 1.42, eyeMotion: .pop, body: .hop, hold: 0.55), // up, big round eyes+ Beat(x: 0.28, y: 0.04, gaze: .look, eyes: 1.05, open: 0.2, eyeMotion: .squint, body: .squash, hold: 0.5), // a bar+ Beat(x: -0.42, y: 0.32, gaze: .drift, eyes: 0.74, eyeMotion: .ease, hold: 0.55), // small, down left+ Beat(x: 0.7, y: -0.04, gaze: .snap, eyes: 0.9, hold: 0.16), // double take…+ Beat(x: 0, y: 0, gaze: .snap, eyes: 1.25, eyeMotion: .pop, body: .shiver, hold: 0.45), // …at you+ ]+ private static let idle: [Beat] = [+ Beat(x: -0.6, y: -0.2, gaze: .snap, eyes: 1.15, eyeMotion: .pop, hold: 0.5),+ Beat(x: 0.55, y: 0.25, gaze: .drift, eyes: 0.8, eyeMotion: .drift, hold: 0.6),+ Beat(x: 0.15, y: -0.4, gaze: .look, eyes: 1.35, eyeMotion: .pop, body: .hop, hold: 0.5),+ Beat(x: -0.2, y: 0.05, gaze: .look, open: 0.22, eyeMotion: .squint, body: .squash, hold: 0.45),+ Beat(x: 0.7, y: 0, gaze: .snap, hold: 0.35),+ Beat(x: -0.35, y: 0.3, gaze: .drift, eyes: 0.72, eyeMotion: .ease, hold: 0.55),+ ]+ private static let last = Beat(x: 0, y: 0, gaze: .look, eyes: 1.12, eyeMotion: .pop, body: .hop, hold: 10)++ private var yaw = Spring(0), pitch = Spring(0)+ private var eyes = Spring(0.6), open = Spring(1)+ private var sx = Spring(0.25), sy = Spring(0.25)+ private var lean = Spring(0), tilt = Spring(0)+ /// Height off the ground (negative is up) and its speed, with gravity.+ private var oy: CGFloat = 0, oyVelocity: CGFloat = 0+ /// A hop waiting for its crouch to end.+ private var launchAt: Double?+ private var shiverUntil: Double = 0++ private var index = 0+ private var nextBeat: Double?+ private var lastTime: Double?+ private var lastIdle = -1+ private var finishing = false++ init() {+ // He pops in from nothing.+ sx.go(1, .pop)+ sy.go(1, .pop)+ }++ /// The app is ready: back to looking at you, one last hop.+ func finish() {+ guard !finishing else { return }+ finishing = true+ play(Self.last, at: CACurrentMediaTime())+ }++ private func play(_ beat: Beat, at now: Double) {+ yaw.go(beat.x * 0.62, beat.gaze)+ pitch.go(beat.y * 0.5, beat.gaze)+ eyes.go(beat.eyes, beat.eyeMotion)+ open.go(beat.open, beat.open < 0.5 ? .squint : beat.eyeMotion)+ // The body leans the way he looks, a little behind his eyes.+ lean.go(beat.x * 0.14, beat.gaze.k > 500 ? .look : .drift)+ tilt.go(beat.x * 0.07, .drift)+ // A quick glance jolts the body.+ if beat.gaze.k > 500 {+ sx.velocity += 0.9+ sy.velocity -= 0.9+ }+ switch beat.body {+ case .hop:+ // Crouch first, then jump.+ sx.velocity += 2.2+ sy.velocity -= 2.6+ launchAt = now + 0.1+ case .squash:+ sx.velocity += 1.8+ sy.velocity -= 2.0+ case .shiver:+ shiverUntil = now + 0.28+ case .none:+ break+ }+ nextBeat = now + beat.hold+ }++ private func advance(_ now: Double) {+ if finishing { return }+ if index < Self.show.count {+ play(Self.show[index], at: now)+ index += 1+ } else {+ var pick = Int.random(in: 0..<Self.idle.count)+ if pick == lastIdle { pick = (pick + 1) % Self.idle.count }+ lastIdle = pick+ play(Self.idle[pick], at: now)+ }+ }++ private func step(_ now: Double) {+ let dt = CGFloat(min(1.0 / 30, now - (lastTime ?? now)))+ lastTime = now+ if now >= nextBeat ?? 0 { advance(now) }++ if let launch = launchAt, now >= launch {+ launchAt = nil+ oyVelocity = -2.3+ sx.velocity -= 2.4 // stretched in the air+ sy.velocity += 3.0+ }+ // Two half steps: the stiff springs stay stable at any frame rate.+ for _ in 0..<2 {+ let h = dt / 2+ yaw.step(h); pitch.step(h)+ eyes.step(h); open.step(h)+ sx.step(h); sy.step(h)+ lean.step(h); tilt.step(h)+ if oy < 0 || oyVelocity < 0 {+ oyVelocity += 15 * h+ oy += oyVelocity * h+ if oy >= 0 {+ // Landing: squash with the speed he had.+ sx.velocity += oyVelocity * 0.9+ sy.velocity -= oyVelocity * 1.1+ oy = 0+ oyVelocity = 0+ }+ }+ }+ }++ func draw(context: GraphicsContext, size: CGSize, settle: Double) {+ let now = CACurrentMediaTime()+ step(now)+ let keep = CGFloat(1 - settle)+ // A slow breath, on top of the moves.+ let breath = CGFloat(sin(now * 2.4)) * 0.022+ let shiver = now < shiverUntil ? CGFloat(sin(now * 70)) * 0.035 * CGFloat((shiverUntil - now) / 0.28) : 0+ bot.yaw = yaw.value * keep+ bot.pitch = pitch.value * keep+ bot.es = 1 + (eyes.value - 1) * keep+ bot.open = 1 + (open.value - 1) * keep+ bot.ox = (lean.value + shiver) * keep+ bot.oy = oy * keep+ // Leaning into the motion: he tilts with how fast his gaze moves.+ bot.tilt = (tilt.value - yaw.velocity * 0.012) * keep+ bot.sx = 1 + (sx.value - 1 - breath * 0.6) * keep+ bot.sy = 1 + (sy.value - 1 + breath) * keep+ bot.draw(context: context, size: size)+ }+}diff --git a/NotchBuddy/Sources/Phone/LastTurnView.swift b/NotchBuddy/Sources/Phone/LastTurnView.swiftindex 623b5cd7..2aa0a2b8 100644--- a/NotchBuddy/Sources/Phone/LastTurnView.swift+++ b/NotchBuddy/Sources/Phone/LastTurnView.swift@@ -125,7 +125,7 @@ struct LastTurnView: View {}.frame(maxWidth: .infinity, alignment: .leading).padding(16)- .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))+ .glassCard()}}diff --git a/NotchBuddy/Sources/Phone/MochiLive.swift b/NotchBuddy/Sources/Phone/MochiLive.swiftindex 533fa126..0708a9e9 100644--- a/NotchBuddy/Sources/Phone/MochiLive.swift+++ b/NotchBuddy/Sources/Phone/MochiLive.swift@@ -3,18 +3,19 @@ import SwiftUI/// Mochi alive, as in the Mac's notch: he blinks, looks around and reacts to/// his state (a hop when a task finishes). Same BotEngine as the Mac. Draws-/// only while on screen, at a capped frame rate.+/// only while on screen, at the screen's own rate (up to 120 Hz on ProMotion)+/// unless capped.struct MochiLive: View {let state: BotStatevar bodyHex: String = "#FFFFFF"- /// Lower for small, numerous Mochi (list rows).- var fps: Double = 30+ /// A cap for small, numerous Mochi (list rows); nil = the screen's rate.+ var fps: Double? = nil@StateObject private var engine = BotEngine()@State private var visible = falsevar body: some View {- TimelineView(.animation(minimumInterval: 1 / fps, paused: !visible)) { timeline in+ TimelineView(.animation(minimumInterval: fps.map { 1 / $0 }, paused: !visible)) { timeline inCanvas { context, size in_ = timeline.datelet dt = min(0.05, max(0, CACurrentMediaTime() - engine.lastTime))diff --git a/NotchBuddy/Sources/Phone/PhoneLink.swift b/NotchBuddy/Sources/Phone/PhoneLink.swiftindex 1f2a819c..2a0d8b34 100644--- a/NotchBuddy/Sources/Phone/PhoneLink.swift+++ b/NotchBuddy/Sources/Phone/PhoneLink.swift@@ -83,10 +83,14 @@ final class PhoneLink {private static let oldSubscriptionID = "coucou-zone-phone"var status: Status = .starting+ /// The first look at iCloud is over (whatever came of it): the intro can end.+ var firstSyncDone = falsevar pings: [PingItem] = []var sessions: [SessionItem] = []/// Service Mochi (GitHub, Stripe…) the Mac publishes, by pill ID.var services: [String: ServiceSnapshot] = [:]+ /// A service up close (figures, lists, actions), fetched by the Mac when its screen opens.+ var serviceDetails: [String: ServiceDetail] = [:]/// The last turn of each session (prompt, actions, diffs, answer), by pill ID.var turns: [String: TurnSnapshot] = [:]/// Turns seen before the latest one, and today's tally (this iPhone only).@@ -108,9 +112,13 @@ final class PhoneLink {@ObservationIgnored private var events: [AgentNotifier.Event] = []func start() async {- let center = UNUserNotificationCenter.current()- notificationsAllowed = (try? await center.requestAuthorization(options: [.alert, .sound, .badge])) ?? false+ // The fetch starts right away, not after the notification prompt: the+ // intro hides it and should end as soon as everything is there.+ let authorization = Task {+ (try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])) ?? false+ }await refresh()+ notificationsAllowed = await authorization.value}/// Checks the account, makes sure the subscription exists, then fetches new records.@@ -119,10 +127,12 @@ final class PhoneLink {let accountStatus = try await container.accountStatus()guard accountStatus == .available else {status = .noAccount(describe(accountStatus))+ firstSyncDone = truereturn}} catch {status = .noAccount(error.localizedDescription)+ firstSyncDone = truereturn}if !subscribed { await subscribe() }@@ -220,6 +230,9 @@ final class PhoneLink {for deletion in changes.deletions where deletion.recordType == TurnSnapshot.recordType {if let id = TurnSnapshot.pillId(fromRecordName: deletion.recordID.recordName) { turns[id] = nil }}+ for deletion in changes.deletions where deletion.recordType == ServiceDetail.recordType {+ if let id = ServiceDetail.pillId(fromRecordName: deletion.recordID.recordName) { serviceDetails[id] = nil }+ }for deletion in changes.deletions where deletion.recordType == ServiceSnapshot.recordType {if let id = ServiceSnapshot.pillId(fromRecordName: deletion.recordID.recordName) {services[id] = nil@@ -242,6 +255,7 @@ final class PhoneLink {status = .failed(error.localizedDescription)}pings.sort { $0.sentAt > $1.sentAt }+ firstSyncDone = truereturn gotNew}@@ -253,8 +267,15 @@ final class PhoneLink {archive.update(from: turns[turn.pillId], to: turn)if archive.past != before.past || archive.today != before.today { archive.save() }turns[turn.pillId] = turn+ SpotlightIndex.index(turn)return false // nothing for the widgets}+ if record.recordType == ServiceDetail.recordType {+ guard let payload = record.encryptedValues["payload"] as? String,+ let detail = try? JSONDecoder().decode(ServiceDetail.self, from: Data(payload.utf8)) else { return false }+ serviceDetails[detail.pillId] = detail+ return false+ }if record.recordType == ServiceSnapshot.recordType {guard let payload = record.encryptedValues["payload"] as? String,let snapshot = try? JSONDecoder().decode(ServiceSnapshot.self, from: Data(payload.utf8)) else { return false }@@ -406,6 +427,56 @@ final class PhoneLink {}}+ // MARK: Services up close++ /// Asks the Mac to read this service's API now (it answers within ~10 s).+ /// False when no new detail came back in time (Mac asleep, sync off, older build).+ @discardableResult+ func requestServiceDetail(_ pillId: String) async -> Bool {+ let previous = serviceDetails[pillId]?.fetchedAt+ guard await sendServiceRequest(kind: ServiceDetail.refreshKind, target: "", pillId: pillId) else { return false }+ // The new detail usually comes with a push; fetch anyway in case it doesn't.+ for _ in 0..<3 {+ // Screen left (task cancelled): stop rather than fetch back to back.+ do { try await Task.sleep(for: .seconds(6)) } catch { return false }+ _ = await fetchChanges()+ // Only the Mac's answer to this request counts, not an older detail.+ if let detail = serviceDetails[pillId], detail.fetchedAt != previous { return true }+ }+ return false+ }++ /// Asks the Mac to run an action it offered on this service. Face ID first.+ /// True only when the Mac's result for this request came back and it worked.+ func runServiceAction(_ action: ServiceActionDef, pillId: String) async -> Bool {+ guard await OwnerCheck.confirm(reason: "\(action.title) from your Mac") else { return false }+ // The result already shown (from an earlier action) doesn't count for this one.+ let previous = serviceDetails[pillId]?.lastAction+ guard await sendServiceRequest(kind: action.kind, target: action.target, pillId: pillId) else { return false }+ for _ in 0..<6 {+ try? await Task.sleep(for: .seconds(5))+ _ = await fetchChanges()+ if let result = serviceDetails[pillId]?.lastAction, result != previous { return result.ok }+ }+ return false+ }++ private func sendServiceRequest(kind: String, target: String, pillId: String) async -> Bool {+ let record = CKRecord(recordType: ServiceDetail.requestType,+ recordID: CKRecord.ID(recordName: "service-request-\(UUID().uuidString)", zoneID: Self.zoneID))+ record["pillId"] = pillId+ record["kind"] = kind+ record["requestedAt"] = Date()+ record.encryptedValues["target"] = target+ do {+ _ = try await database.save(record)+ return true+ } catch {+ lastPong = "Request failed: \(error.localizedDescription)"+ return false+ }+ }+// MARK: Instructions (step B)/// Sends an instruction to continue a session on the Mac. The Mac takes itdiff --git a/NotchBuddy/Sources/Phone/QuestionCard.swift b/NotchBuddy/Sources/Phone/QuestionCard.swiftindex 870f4750..487e8980 100644--- a/NotchBuddy/Sources/Phone/QuestionCard.swift+++ b/NotchBuddy/Sources/Phone/QuestionCard.swift@@ -57,7 +57,7 @@ struct QuestionCard: View {}}.padding(16)- .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))+ .glassCard(tint: .cyan).overlay(RoundedRectangle(cornerRadius: 22).strokeBorder(Color.cyan.opacity(0.7), lineWidth: 1.5)).onAppear { reset() }.onChange(of: payload) { reset() }diff --git a/NotchBuddy/Sources/Phone/SearchAndSpotlight.swift b/NotchBuddy/Sources/Phone/SearchAndSpotlight.swiftnew file mode 100644index 00000000..931e50d4--- /dev/null+++ b/NotchBuddy/Sources/Phone/SearchAndSpotlight.swift@@ -0,0 +1,129 @@+import CoreSpotlight+import SwiftUI+import UniformTypeIdentifiers++/// The Search tab: every turn this iPhone saw (prompts, answers, file names).+struct SearchTab: View {+ let link: PhoneLink+ @State private var query = ""++ private struct Hit: Identifiable {+ let turn: TurnSnapshot+ let agent: String+ let snippet: String+ var id: String { "\(turn.pillId)|\(turn.startedAt.timeIntervalSince1970)" }+ }++ private var allTurns: [TurnSnapshot] {+ (Array(link.turns.values) + link.archive.past.values.flatMap { $0 })+ .sorted { $0.startedAt > $1.startedAt }+ }++ private var hits: [Hit] {+ let needle = query.trimmingCharacters(in: .whitespaces)+ return allTurns.compactMap { turn in+ let agent = PillCatalog.definition(for: turn.pillId)?.name ?? turn.pillId+ if needle.isEmpty { return Hit(turn: turn, agent: agent, snippet: turn.headline) }+ let fields = [turn.prompt, turn.finalMessage, turn.project, agent] + turn.files.map(\.path)+ guard let field = fields.first(where: { $0.localizedCaseInsensitiveContains(needle) }) else { return nil }+ return Hit(turn: turn, agent: agent, snippet: Self.snippet(of: field, around: needle))+ }+ }++ var body: some View {+ NavigationStack {+ List {+ if allTurns.isEmpty {+ ContentUnavailableView("No turn yet", systemImage: "text.magnifyingglass",+ description: Text("What Claude does on your Mac shows up here, ready to search."))+ } else if hits.isEmpty {+ ContentUnavailableView.search(text: query)+ } else {+ Section(query.isEmpty ? "Recent turns" : "Results") {+ ForEach(hits) { hit in+ NavigationLink {+ ScrollView {+ LastTurnView(turn: hit.turn, working: false).padding(16)+ }+ .background(Color.black)+ .navigationTitle(hit.turn.project.isEmpty ? hit.agent : hit.turn.project)+ .navigationBarTitleDisplayMode(.inline)+ } label: {+ row(hit)+ }+ }+ }+ }+ }+ .navigationTitle("Search")+ .searchable(text: $query, prompt: "Prompts, answers, files")+ }+ }++ private func row(_ hit: Hit) -> some View {+ let pill = PillCatalog.definition(for: hit.turn.pillId)+ return HStack(alignment: .top, spacing: 12) {+ MochiStill(state: .idle, bodyHex: pill?.color ?? "#FFFFFF")+ .padding(4)+ .frame(width: 34, height: 34)+ .background(Color.mochiTile(hex: pill?.color ?? "#3B4A6B"), in: RoundedRectangle(cornerRadius: 9))+ VStack(alignment: .leading, spacing: 3) {+ HStack {+ Text(hit.turn.project.isEmpty ? hit.agent : "\(hit.turn.project) · \(hit.agent)")+ .font(.subheadline.weight(.semibold))+ .lineLimit(1)+ Spacer(minLength: 4)+ Text(hit.turn.startedAt, format: .relative(presentation: .named))+ .font(.caption2)+ .foregroundStyle(.tertiary)+ }+ Text(hit.snippet)+ .font(.callout)+ .foregroundStyle(.secondary)+ .lineLimit(2)+ }+ }+ }++ /// A few words around the match.+ private static func snippet(of text: String, around needle: String) -> String {+ guard let range = text.range(of: needle, options: .caseInsensitive) else { return String(text.prefix(140)) }+ let start = text.index(range.lowerBound, offsetBy: -50, limitedBy: text.startIndex) ?? text.startIndex+ let end = text.index(range.upperBound, offsetBy: 90, limitedBy: text.endIndex) ?? text.endIndex+ let piece = text[start..<end].replacingOccurrences(of: "\n", with: " ")+ return (start > text.startIndex ? "…" : "") + piece + (end < text.endIndex ? "…" : "")+ }+}++/// Finished turns in the iPhone's Spotlight: search a project or a file from+/// the Home Screen and land on its session. The index stays on this iPhone.+enum SpotlightIndex {+ static let enabledKey = "spotlightTurns"+ static let activityType = CSSearchableItemActionType++ static var isEnabled: Bool { UserDefaults.standard.object(forKey: enabledKey) as? Bool ?? true }++ static func index(_ turn: TurnSnapshot) {+ guard isEnabled, turn.endedAt != nil else { return }+ let agent = PillCatalog.definition(for: turn.pillId)?.name ?? "Agent"+ let attributes = CSSearchableItemAttributeSet(contentType: .text)+ attributes.title = turn.project.isEmpty ? agent : "\(turn.project) · \(agent)"+ let answer = turn.finalMessage.isEmpty ? "" : "\n" + String(turn.finalMessage.prefix(300))+ attributes.contentDescription = turn.headline + answer+ attributes.keywords = [agent, turn.project, "Coucou"] + turn.files.map(\.name)+ let item = CSSearchableItem(uniqueIdentifier: "\(turn.pillId)|\(Int(turn.startedAt.timeIntervalSince1970))",+ domainIdentifier: "turns", attributeSet: attributes)+ item.expirationDate = Date().addingTimeInterval(30 * 24 * 3600)+ CSSearchableIndex.default().indexSearchableItems([item])+ }++ static func removeAll() {+ CSSearchableIndex.default().deleteAllSearchableItems()+ }++ /// The session a Spotlight result opens.+ static func pillId(from activity: NSUserActivity) -> String? {+ guard let id = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String else { return nil }+ return id.split(separator: "|").first.map(String.init)+ }+}diff --git a/NotchBuddy/Sources/Phone/ServiceLiveDetail.swift b/NotchBuddy/Sources/Phone/ServiceLiveDetail.swiftnew file mode 100644index 00000000..6caaf126--- /dev/null+++ b/NotchBuddy/Sources/Phone/ServiceLiveDetail.swift@@ -0,0 +1,207 @@+import SwiftUI+import UIKit++/// What the Mac just read from a service's API: figures, lists, and the+/// actions it offers on each item (Face ID, then the Mac does it).+struct ServiceLiveDetail: View {+ let link: PhoneLink+ let pillId: String+ let detail: ServiceDetail++ @State private var running: ServiceActionDef?+ @State private var confirming: ServiceActionDef?+ @State private var sentFeedback = 0+ @Environment(\.openURL) private var openURL++ var body: some View {+ VStack(alignment: .leading, spacing: 16) {+ if let result = detail.lastAction, Date().timeIntervalSince(result.date) < 10 * 60 {+ resultBanner(result)+ .transition(.move(edge: .top).combined(with: .opacity))+ }+ if let error = detail.error {+ Label(error, systemImage: "exclamationmark.triangle.fill")+ .font(.callout)+ .foregroundStyle(.orange)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(16)+ .glassCard()+ }+ if !detail.stats.isEmpty { stats }+ ForEach(Array(detail.sections.enumerated()), id: \.offset) { _, section in+ sectionCard(section)+ }+ Text("Read from your Mac · \(detail.fetchedAt.formatted(.relative(presentation: .named)))")+ .font(.caption2)+ .foregroundStyle(.tertiary)+ .frame(maxWidth: .infinity)+ }+ .animation(.spring(duration: 0.45, bounce: 0.2), value: detail.lastAction)+ .sensoryFeedback(.success, trigger: sentFeedback)+ .confirmationDialog(confirming?.title ?? "", isPresented: Binding(get: { confirming != nil },+ set: { if !$0 { confirming = nil } }),+ titleVisibility: .visible) {+ if let action = confirming {+ Button(action.title, role: action.destructive ? .destructive : nil) { run(action) }+ }+ } message: {+ Text(confirming?.confirm ?? "")+ }+ }++ // MARK: Figures++ /// The figures in one strip, like the Stocks or Fitness summaries.+ private var stats: some View {+ HStack(spacing: 0) {+ ForEach(Array(detail.stats.enumerated()), id: \.offset) { index, stat in+ VStack(spacing: 3) {+ Text(stat.value)+ .font(.headline.monospacedDigit())+ .foregroundStyle(stat.tone == .idle || stat.tone == .ok ? Color.primary : stat.tone.color)+ .lineLimit(1)+ .minimumScaleFactor(0.5)+ .contentTransition(.numericText())+ Text(stat.label)+ .font(.caption2)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ .minimumScaleFactor(0.8)+ }+ .frame(maxWidth: .infinity)+ if index < detail.stats.count - 1 {+ Divider().frame(height: 28)+ }+ }+ }+ .padding(.vertical, 14)+ .padding(.horizontal, 6)+ .glassCard(cornerRadius: 20)+ }++ // MARK: Lists++ private func sectionCard(_ section: DetailSection) -> some View {+ VStack(alignment: .leading, spacing: 10) {+ Text(section.title).font(.subheadline.weight(.semibold)).foregroundStyle(.secondary)+ ForEach(Array(section.items.enumerated()), id: \.offset) { index, item in+ itemRow(item)+ if index < section.items.count - 1 { Divider() }+ }+ if let footer = section.footer {+ Text(footer).font(.caption).foregroundStyle(.secondary)+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(16)+ .glassCard()+ }++ /// One line per item: a tap opens it on the web, its actions sit in the+ /// "…" menu on the right (or a long press), like Mail and Files.+ private func itemRow(_ item: DetailItem) -> some View {+ HStack(alignment: .center, spacing: 10) {+ Circle().fill(item.tone == .idle ? Color.secondary.opacity(0.5) : item.tone.color).frame(width: 7, height: 7)+ VStack(alignment: .leading, spacing: 2) {+ HStack(alignment: .firstTextBaseline, spacing: 6) {+ Text(item.title)+ .font(.callout.weight(.medium))+ .lineLimit(1)+ if let badge = item.badge, !badge.isEmpty {+ Text(badge)+ .font(.caption2.weight(.semibold))+ .foregroundStyle(item.tone == .idle ? Color.secondary : item.tone.color)+ .lineLimit(1)+ .fixedSize()+ }+ }+ HStack(spacing: 4) {+ if !item.subtitle.isEmpty {+ Text(item.subtitle).lineLimit(1)+ }+ if let date = item.date {+ if !item.subtitle.isEmpty { Text("·") }+ Text(date, format: .relative(presentation: .named)).lineLimit(1).fixedSize()+ }+ }+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ Spacer(minLength: 4)+ if !item.actions.isEmpty {+ Menu {+ ForEach(item.actions, id: \.self) { action in+ Button(role: action.destructive ? .destructive : nil) {+ if action.confirm != nil { confirming = action } else { run(action) }+ } label: {+ Label(action.title, systemImage: action.symbol)+ }+ }+ } label: {+ Group {+ if item.actions.contains(where: { $0 == running }) {+ ProgressView().controlSize(.small)+ } else {+ Image(systemName: "ellipsis")+ .font(.callout.weight(.semibold))+ }+ }+ .frame(width: 32, height: 32)+ .glassPill(Circle(), interactive: true)+ }+ .disabled(running != nil)+ } else if item.url != nil {+ Image(systemName: "chevron.right").font(.caption2.weight(.semibold)).foregroundStyle(.tertiary)+ }+ }+ .padding(.vertical, 4)+ .contentShape(Rectangle())+ .onTapGesture {+ if let url = item.url.flatMap(URL.init(string:)), url.scheme == "https" { openURL(url) }+ }+ .contextMenu {+ ForEach(item.actions, id: \.self) { action in+ Button(role: action.destructive ? .destructive : nil) {+ if action.confirm != nil { confirming = action } else { run(action) }+ } label: {+ Label(action.title, systemImage: action.symbol)+ }+ }+ if let url = item.url.flatMap(URL.init(string:)), url.scheme == "https" {+ Button { openURL(url) } label: { Label("Open", systemImage: "safari") }+ Button { UIPasteboard.general.url = url } label: { Label("Copy link", systemImage: "link") }+ }+ }+ }++ private func run(_ action: ServiceActionDef) {+ confirming = nil+ running = action+ Task {+ if await link.runServiceAction(action, pillId: pillId) { sentFeedback += 1 }+ running = nil+ }+ }++ // MARK: Result++ private func resultBanner(_ result: ServiceActionResult) -> some View {+ HStack(alignment: .top, spacing: 12) {+ if result.ok {+ DrawnCheckmark(size: 30)+ } else {+ Image(systemName: "xmark.circle.fill").font(.title2).foregroundStyle(.red)+ }+ VStack(alignment: .leading, spacing: 2) {+ Text(result.title).font(.subheadline.weight(.semibold))+ Text(result.message).font(.callout).foregroundStyle(.secondary)+ }+ Spacer(minLength: 0)+ Text(result.date, format: .relative(presentation: .named))+ .font(.caption2)+ .foregroundStyle(.tertiary)+ }+ .padding(16)+ .glassCard(tint: result.ok ? .green : .red)+ }+}diff --git a/NotchBuddy/Sources/Phone/ServiceViews.swift b/NotchBuddy/Sources/Phone/ServiceViews.swiftindex cb7a02a5..779a572b 100644--- a/NotchBuddy/Sources/Phone/ServiceViews.swift+++ b/NotchBuddy/Sources/Phone/ServiceViews.swift@@ -77,7 +77,7 @@ struct ServiceMochi: View {var body: some View {let color = PillCatalog.definition(for: pillId)?.color ?? "#C0C4CC"- MochiLive(state: tone?.botState ?? .sleeping, bodyHex: color, fps: 20)+ MochiLive(state: tone?.botState ?? .sleeping, bodyHex: color, fps: 60).padding(4).background(Color(white: 0.16), in: RoundedRectangle(cornerRadius: corner))}@@ -90,15 +90,41 @@ struct ServiceDetailView: View {private var snapshot: ServiceSnapshot? { link.services[pillId] }private var pill: PillDefinition? { PillCatalog.definition(for: pillId) }+ /// The Mac didn't answer the last request (asleep, sync off, older build).+ @State private var macSilent = falsevar body: some View {ScrollView {VStack(alignment: .leading, spacing: 16) {headerif let snapshot {- reasonCard(snapshot)- ForEach(Array(snapshot.sections.enumerated()), id: \.offset) { _, section in- sectionCard(section)+ // Why the dot has its color: only worth a card when something needs a look.+ if snapshot.tone == .error || snapshot.tone == .warning || link.serviceDetails[pillId] == nil {+ reasonCard(snapshot)+ }+ // Read live from the service's API by the Mac, with actions.+ if let detail = link.serviceDetails[pillId] {+ ServiceLiveDetail(link: link, pillId: pillId, detail: detail)+ } else {+ HStack(spacing: 10) {+ if macSilent {+ Image(systemName: "moon.zzz").foregroundStyle(.secondary)+ Text("Your Mac didn't answer. Is it awake, with the iPhone switch on? Pull down to try again.")+ .font(.callout)+ .foregroundStyle(.secondary)+ } else {+ ProgressView()+ Text("Asking your Mac for everything \(pill?.name ?? "it") has…")+ .font(.callout)+ .foregroundStyle(.secondary)+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(16)+ .glassCard()+ ForEach(Array(snapshot.sections.enumerated()), id: \.offset) { _, section in+ sectionCard(section)+ }}} else {notConnected@@ -109,7 +135,11 @@ struct ServiceDetailView: View {.background(Color.black).navigationTitle(pill?.name ?? "Service").navigationBarTitleDisplayMode(.inline)- .refreshable { await link.refresh() }+ .task { macSilent = !(await link.requestServiceDetail(pillId)) && link.serviceDetails[pillId] == nil }+ .refreshable {+ macSilent = false+ macSilent = !(await link.requestServiceDetail(pillId)) && link.serviceDetails[pillId] == nil+ }}private var header: some View {@@ -150,7 +180,7 @@ struct ServiceDetailView: View {Spacer(minLength: 0)}.padding(16)- .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))+ .glassCard().overlay {if snapshot.tone == .error || snapshot.tone == .warning {RoundedRectangle(cornerRadius: 22).strokeBorder(snapshot.tone.color.opacity(0.7), lineWidth: 1.5)diff --git a/NotchBuddy/Sources/Phone/SessionDetailView.swift b/NotchBuddy/Sources/Phone/SessionDetailView.swiftindex 577bb5de..bb1fcd45 100644--- a/NotchBuddy/Sources/Phone/SessionDetailView.swift+++ b/NotchBuddy/Sources/Phone/SessionDetailView.swift@@ -59,14 +59,35 @@ struct SessionDetailView: View {.padding(40)}}- .background(Color.black)+ // A tap on the conversation (not on the field below) puts the keyboard away.+ .simultaneousGesture(TapGesture().onEnded {+ UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)+ })+ // The agent's color, moving softly behind the top of the screen.+ .background(alignment: .top) {+ ZStack {+ Color.black+ if let session {+ AgentBackdrop(hex: PillCatalog.definition(for: session.id)?.color ?? session.color)+ .frame(height: 360)+ .mask(LinearGradient(colors: [.black, .black.opacity(0.5), .clear],+ startPoint: .top, endPoint: .bottom))+ .frame(maxHeight: .infinity, alignment: .top)+ }+ }+ .ignoresSafeArea()+ }// The composer stays at the bottom, like a chat..safeAreaInset(edge: .bottom) {if let session, session.id == "integration_claude" || session.id == "agent_cursor" {InstructionComposer(link: link, session: session)}}- .scrollDismissesKeyboard(.interactively)+ // Scrolling puts the keyboard away.+ .scrollDismissesKeyboard(.immediately)+ // A conversation takes the whole screen, like Messages: no tabs below,+ // and the field stays put at the bottom.+ .toolbarVisibility(.hidden, for: .tabBar).navigationTitle(session?.title ?? "Session").navigationBarTitleDisplayMode(.inline).refreshable { await link.refresh() }@@ -219,7 +240,7 @@ struct SessionDetailView: View {}.frame(maxWidth: .infinity, alignment: .leading).padding(16)- .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))+ .glassCard()}}diff --git a/NotchBuddy/project.yml b/NotchBuddy/project.ymlindex 586f5909..44b79efb 100644--- a/NotchBuddy/project.yml+++ b/NotchBuddy/project.yml@@ -261,6 +261,11 @@ targets:NSMicrophoneUsageDescription: "Coucou uses the microphone when you dictate an instruction for Claude Code."NSSpeechRecognitionUsageDescription: "Coucou turns your voice into the text of an instruction for Claude Code."NSSupportsLiveActivities: YES+ # Lets Mochi move at 120 Hz on ProMotion screens, like the Mac's notch.+ CADisableMinimumFrameDurationOnPhone: YES+ # Steps change often while an agent works: without this, iOS holds back+ # updates once its budget is spent, and "waiting for your OK" came late.+ NSSupportsLiveActivitiesFrequentUpdates: YES# coucou://session/<id>: the widgets open a session in the app.CFBundleURLTypes:- CFBundleURLName: fr.louisraille.Coucou@@ -274,6 +279,9 @@ targets:PRODUCT_NAME: CoucouINFOPLIST_FILE: Resources/InfoPhone.plistASSETCATALOG_COMPILER_APPICON_NAME: AppIcon+ # Mochi in other colors, picked in Settings (UIApplication.setAlternateIconName).+ ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES: "AppIcon-Blue AppIcon-Green AppIcon-Purple AppIcon-Pink AppIcon-Graphite"+ ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS: NOCOUCOU_APNS_ENV: productionIPHONEOS_DEPLOYMENT_TARGET: "18.0"TARGETED_DEVICE_FAMILY: "1"diff --git a/docs/privacy.html b/docs/privacy.htmlindex d3ab2ea4..de2bf77d 100644--- a/docs/privacy.html+++ b/docs/privacy.html@@ -51,7 +51,8 @@<h2>9. iPhone app</h2><p>If you turn on <b>Settings → General → iPhone</b> on your Mac (off by default), Coucou writes your agent sessions to your own private iCloud database, which only your devices signed in to your Apple Account can read. For each agent session it also keeps its last turn only: the prompt you sent, the commands it ran and what they printed (trimmed), the file changes it made, and its answer. It also writes what your connected services show in the notch (GitHub pull requests and checks, Stripe payments and balance, Vercel deployments, Resend emails, Cal.com bookings, n8n runs, Notion pages), from data your Mac already fetched: no extra request, and no API key ever leaves your Mac. Project names, steps, folders, the last message, pending commands, questions, the last turn and all that service data are encrypted with your iCloud keys. When you allow or deny a command from the iPhone (allowing needs Face ID in the app, or the iPhone unlocked by you from the Lock Screen or a notification), the decision goes back to your Mac through the same database, and the iPhone keeps a history of your decisions on the iPhone only. Turning the setting off deletes the sessions from iCloud. We have no access to your iCloud data.</p><p>If you turn on <b>Let my iPhone send instructions to Claude Code</b> <i>(macOS, GitHub build)</i>, an instruction you write or dictate on the iPhone (Face ID required) goes to your Mac through the same private iCloud database, encrypted, and is deleted as soon as your Mac reads it. Your Mac then continues your last Claude Code session with it, in that session’s folder. Dictation uses Apple’s speech recognition, on the iPhone when available.</p>-<p>When Claude asks you a question, its choices go to your iPhone in the same encrypted session record, so you can answer there. Your answer (the choices you picked) goes back to your Mac the same way and is deleted as soon as your Mac reads it. Replies typed in a notification, and instructions sent with Siri or the Shortcuts app, travel like the instructions above and need the iPhone unlocked. The earlier turns and the “Today” tally the iPhone shows are kept on the iPhone only.</p>+<p>When Claude asks you a question, its choices go to your iPhone in the same encrypted session record, so you can answer there. Your answer (the choices you picked) goes back to your Mac the same way and is deleted as soon as your Mac reads it. Replies typed in a notification, and instructions sent with Siri or the Shortcuts app, travel like the instructions above and need the iPhone unlocked. The earlier turns and the “Today” tally the iPhone shows are kept on the iPhone only, and so is the Spotlight index of your turns (Settings → Look, on by default, can be turned off).</p>+<p>When you open a service on the iPhone (GitHub, Vercel, Stripe, Resend, Cal.com, n8n, Notion), the iPhone asks your Mac, through your private iCloud, to read that service; your Mac calls its API with the key in its Keychain and writes what it read back to iCloud, encrypted. From there you can ask your Mac to redeploy or cancel a Vercel build, re-run failed GitHub jobs, approve or merge a pull request, or turn an n8n workflow on or off or retry a run, always after Face ID. Nothing that moves money or sends an email can be asked from the iPhone, and no API key ever leaves your Mac.</p><p>If you also turn on <b>Move Mochi to my iPhone’s Dynamic Island when my Mac is locked</b>, then while your Mac is locked and an agent is working, your Mac sends the agent’s name and state (for example “VS Code · working 3/7”) and your iPhone’s Live Activity push token to the Coucou relay, a small server we run on Cloudflare, which forwards it to Apple’s push service to update the Live Activity. The relay never receives a project name, a command, a path or a message, stores nothing and keeps no logs.</p><h2>10. Children</h2>@@ -113,7 +114,8 @@<h2>9. App iPhone</h2><p>Si tu actives <b>Réglages → Général → iPhone</b> sur ton Mac (désactivé par défaut), Coucou écrit tes sessions d’agents dans ta propre base iCloud privée, que seuls tes appareils connectés à ton compte Apple peuvent lire. Pour chaque session d’agent, il garde aussi uniquement son dernier tour : le prompt que tu as envoyé, les commandes lancées et ce qu’elles ont affiché (raccourci), les modifications de fichiers et sa réponse. Il y écrit aussi ce que tes services connectés affichent dans l’encoche (pull requests et checks GitHub, paiements et solde Stripe, déploiements Vercel, e-mails Resend, rendez-vous Cal.com, exécutions n8n, pages Notion), à partir des données que ton Mac a déjà récupérées : aucune requête en plus, et aucune clé d’API ne quitte ton Mac. Les noms de projet, étapes, dossiers, dernier message, commandes en attente, questions, le dernier tour et toutes ces données de services sont chiffrés avec tes clés iCloud. Quand tu autorises ou refuses une commande depuis l’iPhone (autoriser demande Face ID dans l’app, ou l’iPhone déverrouillé par toi depuis l’écran verrouillé ou une notification), la décision revient à ton Mac par la même base, et l’iPhone garde l’historique de tes décisions sur l’iPhone uniquement. Désactiver le réglage supprime les sessions d’iCloud. Le développeur n’a aucun accès à tes données iCloud.</p><p>Si tu actives <b>Let my iPhone send instructions to Claude Code</b> <i>(macOS, version GitHub)</i>, une instruction écrite ou dictée sur l’iPhone (Face ID demandé) passe par la même base iCloud privée, chiffrée, et est supprimée dès que ton Mac la lit. Ton Mac continue alors ta dernière session Claude Code avec elle, dans le dossier de cette session. La dictée utilise la reconnaissance vocale d’Apple, sur l’iPhone quand c’est possible.</p>-<p>Quand Claude te pose une question, ses choix arrivent sur ton iPhone dans le même enregistrement de session chiffré, pour que tu puisses y répondre. Ta réponse (les choix cochés) repart vers ton Mac de la même façon et est supprimée dès que ton Mac la lit. Les réponses tapées dans une notification, et les instructions envoyées avec Siri ou l’app Raccourcis, voyagent comme les instructions ci-dessus et demandent l’iPhone déverrouillé. Les tours précédents et le bilan « Today » affichés sur l’iPhone restent sur l’iPhone.</p>+<p>Quand Claude te pose une question, ses choix arrivent sur ton iPhone dans le même enregistrement de session chiffré, pour que tu puisses y répondre. Ta réponse (les choix cochés) repart vers ton Mac de la même façon et est supprimée dès que ton Mac la lit. Les réponses tapées dans une notification, et les instructions envoyées avec Siri ou l’app Raccourcis, voyagent comme les instructions ci-dessus et demandent l’iPhone déverrouillé. Les tours précédents et le bilan « Today » affichés sur l’iPhone restent sur l’iPhone, tout comme l’index Spotlight de tes tours (Réglages → Look, activé par défaut, désactivable).</p>+<p>Quand tu ouvres un service sur l’iPhone (GitHub, Vercel, Stripe, Resend, Cal.com, n8n, Notion), l’iPhone demande à ton Mac, via ton iCloud privé, de le lire ; ton Mac appelle son API avec la clé de son trousseau et réécrit ce qu’il a lu dans iCloud, chiffré. De là, tu peux demander à ton Mac de redéployer ou d’annuler un build Vercel, de relancer des jobs GitHub en échec, d’approuver ou de merger une pull request, ou d’activer ou de couper un workflow n8n ou de relancer une exécution, toujours après Face ID. Rien qui déplace de l’argent ou envoie un e-mail ne peut être demandé depuis l’iPhone, et aucune clé d’API ne quitte ton Mac.</p><p>Si tu actives aussi <b>Mochi passe sur l’île dynamique de l’iPhone quand le Mac est verrouillé</b>, alors pendant que ton Mac est verrouillé et qu’un agent travaille, ton Mac envoie le nom et l’état de l’agent (par exemple « VS Code · working 3/7 ») et le jeton push Live Activity de ton iPhone au relais Coucou, un petit serveur exploité par le développeur sur Cloudflare, qui le transmet au service de notifications d’Apple pour mettre à jour la Live Activity. Le relais ne reçoit jamais de nom de projet, de commande, de chemin ni de message, ne stocke rien et ne tient aucun journal.</p><h2>10. Enfants</h2>diff --git a/relay/src/index.ts b/relay/src/index.tsindex 506c7570..6b31903e 100644--- a/relay/src/index.ts+++ b/relay/src/index.ts@@ -125,6 +125,12 @@ function buildPayload(body: RelayRequest) {// iOS requires an alert to start a Live Activity from a push.aps["alert"] = { title: "Coucou", body: `${state.agent} · ${state.statusText}` };}+ if (body.event === "update" && body.urgent) {+ // Waiting for your OK or a question: the Dynamic Island opens and the+ // Lock Screen lights up, with Allow / Deny right there. No sound: the+ // approval notification already makes one.+ aps["alert"] = { title: String(state.agent), body: String(state.statusText) };+ }if (body.event === "end") {aps["dismissal-date"] = now + (body.dismissAfter ?? 0);}