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: act from notifications, answer questions, Siri, Control Center + new coucou sound (#241)
Louis30edad4c5c0b
diff --git a/NotchBuddy/Resources/InfoPhone.plist b/NotchBuddy/Resources/InfoPhone.plistindex f376414a..3ce50096 100644--- a/NotchBuddy/Resources/InfoPhone.plist+++ b/NotchBuddy/Resources/InfoPhone.plist@@ -56,6 +56,8 @@<key>UISupportedInterfaceOrientations</key><array><string>UIInterfaceOrientationPortrait</string>+ <string>UIInterfaceOrientationLandscapeLeft</string>+ <string>UIInterfaceOrientationLandscapeRight</string></array></dict></plist>diff --git a/NotchBuddy/Resources/sounds/greeting.wav b/NotchBuddy/Resources/sounds/greeting.wavindex d924a000..27c807d2 100644Binary files a/NotchBuddy/Resources/sounds/greeting.wav and b/NotchBuddy/Resources/sounds/greeting.wav differdiff --git a/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift b/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swiftindex 3ac27f18..21e6a568 100644--- a/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift+++ b/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift@@ -71,6 +71,7 @@ final class CloudProbe {NSApplication.shared.unregisterForRemoteNotifications()SessionPublisher.shared.stop()ApprovalRelay.shared.stop()+ QuestionRelay.shared.stop()ServicePublisher.shared.stop()TurnRecorder.shared.stop()#if !APPSTORE@@ -92,6 +93,7 @@ final class CloudProbe {NSApplication.shared.registerForRemoteNotifications()SessionPublisher.shared.start()ApprovalRelay.shared.start()+ QuestionRelay.shared.start()ServicePublisher.shared.start()TurnRecorder.shared.start()#if !APPSTOREdiff --git a/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swift b/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swiftindex 08378c23..01a12978 100644--- a/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swift+++ b/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swift@@ -344,7 +344,8 @@ final class LiveActivityRelay {tone: MochiActivityState.tone(urgency: urgency),stepIndex: max(0, task.stepIndex),stepCount: task.steps.count,- others: others)+ others: others,+ approval: approval?.pillId == task.id ? approval.map(ApprovalRelay.fingerprint) : nil)}private func log(_ message: String) {diff --git a/NotchBuddy/Sources/App/PhoneLink/QuestionRelay.swift b/NotchBuddy/Sources/App/PhoneLink/QuestionRelay.swiftnew file mode 100644index 00000000..51e02385--- /dev/null+++ b/NotchBuddy/Sources/App/PhoneLink/QuestionRelay.swift@@ -0,0 +1,132 @@+#if PHONE_LINK+import AppKit+import CloudKit+import Combine++// MARK: - Answer Claude's questions from the iPhone+//+// While Claude Code waits on an AskUserQuestion, the session record carries+// the question and its choices (SessionPublisher). The iPhone answers with an+// `Answer` record: the question's fingerprint and the labels picked. This Mac+// looks for answers every 2 s, only while a question waits, and applies one+// only if it matches the question still waiting and every label is one of its+// choices. Answers are single use: deleted as soon as they are read.++@MainActor+final class QuestionRelay {+ static let shared = QuestionRelay()++ private let container = CKContainer(identifier: "iCloud.fr.louisraille.Coucou")+ private var database: CKDatabase { container.privateCloudDatabase }+ private var zoneID: CKRecordZone.ID { SessionSnapshot.zoneID }++ private var cancellable: AnyCancellable?+ private var current: (fingerprint: String, since: Date)?+ private var pollTask: Task<Void, Never>?+ private var changeToken: CKServerChangeToken?++ func start() {+ guard cancellable == nil else { return }+ // @Published sends the new value before the property changes: use the value passed along.+ cancellable = AppState.shared.$pendingQuestion+ .map { $0.map(QuestionPayload.init(ask:)) }+ .removeDuplicates()+ .sink { [weak self] payload in+ MainActor.assumeIsolated { self?.pendingChanged(to: payload) }+ }+ }++ func stop() {+ cancellable = nil+ pendingChanged(to: nil)+ }++ private func pendingChanged(to payload: QuestionPayload?) {+ let fingerprint = payload?.fingerprint+ guard current?.fingerprint != fingerprint else { return }+ pollTask?.cancel()+ pollTask = nil+ current = nil+ guard let fingerprint else { return }+ current = (fingerprint, Date())+ pollTask = Task { [weak self] in+ // The Mac gives the question back to the terminal after 120 s.+ for _ in 0..<62 {+ try? await Task.sleep(for: .seconds(2))+ guard !Task.isCancelled, let self else { return }+ if await self.checkAnswers(for: fingerprint) { return }+ }+ }+ }++ /// Returns true once a matching answer was applied.+ private func checkAnswers(for fingerprint: String) async -> Bool {+ guard current?.fingerprint == fingerprint, let since = current?.since else { return true }+ var found: [(id: CKRecord.ID, fingerprint: String, selections: String)] = []+ do {+ var more = true+ while more {+ let changes = try await database.recordZoneChanges(inZoneWith: zoneID, since: changeToken)+ for (id, result) in changes.modificationResultsByID {+ guard case .success(let mod) = result, mod.record.recordType == "Answer" else { continue }+ let record = mod.record+ let answeredAt = record["answeredAt"] as? Date ?? .distantPast+ guard answeredAt >= since.addingTimeInterval(-5) else { continue }+ found.append((id, record["fingerprint"] as? String ?? "",+ record.encryptedValues["selections"] as? String ?? ""))+ }+ changeToken = changes.changeToken+ more = changes.moreComing+ }+ } catch let error as CKError where error.code == .changeTokenExpired {+ changeToken = nil+ return false+ } catch {+ log("answer check failed: \(error.localizedDescription)")+ return false+ }+ guard !found.isEmpty else { return false }+ let ids = found.map { $0.id }+ Task { _ = try? await database.modifyRecords(saving: [], deleting: ids) }+ guard let match = found.first(where: { $0.fingerprint == fingerprint }) else {+ log("ignored \(found.count) answer(s) for another question")+ return false+ }+ apply(match.selections, fingerprint: fingerprint)+ return true+ }++ private func apply(_ json: String, fingerprint: String) {+ // Check again right before answering the hook.+ guard let pending = AppState.shared.pendingQuestion else {+ log("answer arrived after the question was resolved, ignored")+ return+ }+ let payload = QuestionPayload(ask: pending)+ guard payload.fingerprint == fingerprint else {+ log("answer for an older question, ignored")+ return+ }+ guard let selections = QuestionPayload.decodeSelections(json), payload.accepts(selections) else {+ log("answer with unknown choices, ignored")+ return+ }+ log("answered from the iPhone")+ HookServer.shared.sendQuestionAnswers(AskQuestion.buildAnswers(questions: pending.questions, selections: selections))+ }++ private func log(_ message: String) {+ CloudProbe.shared.log("[question] \(message)")+ }+}++extension QuestionPayload {+ init(ask: AskQuestion) {+ self.init(items: ask.questions.map { item in+ Item(question: item.question, header: item.header,+ options: item.options.map { Option(label: $0.label, description: $0.description) },+ multiSelect: item.multiSelect)+ })+ }+}+#endifdiff --git a/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift b/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swiftindex d4e2e7db..237e1309 100644--- a/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift+++ b/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift@@ -170,6 +170,9 @@ struct SessionSnapshot: Equatable {let approvalCommand: Stringlet approvalFingerprint: Stringlet question: String+ /// The question's choices (QuestionPayload JSON) and its fingerprint, for answering from the iPhone.+ var questionPayload: String = ""+ var questionFingerprint: String = ""static func all(tasks: [AgentTask], approval: ApprovalInfo?,question: AskQuestion?) -> [String: SessionSnapshot] {@@ -180,6 +183,7 @@ struct SessionSnapshot: Equatable {let questionText = task.state == .question? (question?.questions.map(\.question).joined(separator: "\n") ?? ""): ""+ let payload = task.state == .question ? question.map(QuestionPayload.init(ask:)) : nilresult[task.id] = SessionSnapshot(pillId: task.id,name: task.name,@@ -192,7 +196,9 @@ struct SessionSnapshot: Equatable {approvalTool: hasApproval ? (approval?.tool ?? "") : "",approvalCommand: hasApproval ? (approval?.command ?? "") : "",approvalFingerprint: hasApproval ? (approval.map(ApprovalRelay.fingerprint) ?? "") : "",- question: questionText)+ question: questionText,+ questionPayload: payload?.json ?? "",+ questionFingerprint: payload?.fingerprint ?? "")}return result}@@ -228,6 +234,7 @@ struct SessionSnapshot: Equatable {// Identifies the exact request; the iPhone sends it back with its decision.record["approvalFingerprint"] = approvalFingerprintrecord["needsAnswer"] = !question.isEmpty+ record["questionFingerprint"] = questionFingerprintrecord["updatedAt"] = Date()record["macName"] = Host.current().localizedName ?? ""// Whether this Mac runs instructions sent from the iPhone (GitHub build, switch on).@@ -243,6 +250,7 @@ struct SessionSnapshot: Equatable {record.encryptedValues["approvalTool"] = approvalToolrecord.encryptedValues["approvalCommand"] = approvalCommandrecord.encryptedValues["question"] = question+ record.encryptedValues["questionPayload"] = questionPayloadreturn record}}diff --git a/NotchBuddy/Sources/CoucouKit/MochiActivityState.swift b/NotchBuddy/Sources/CoucouKit/MochiActivityState.swiftindex df5569c9..4bb51308 100644--- a/NotchBuddy/Sources/CoucouKit/MochiActivityState.swift+++ b/NotchBuddy/Sources/CoucouKit/MochiActivityState.swift@@ -20,6 +20,9 @@ struct MochiActivityState: Codable, Hashable, Sendable {/// When Mochi left for the iPhone (Unix seconds): the iPhone counts the/// time from it, live. Optional so older pushes still decode.var since: Int? = nil+ /// The fingerprint of the command waiting for your OK (an opaque hash,+ /// never the command): the Lock Screen's Allow and Deny answer this one.+ var approval: String? = nilvar botState: BotState { BotState(rawValue: state) ?? .idle }var isActive: Bool { ["waiting", "question", "working", "error"].contains(tone) }diff --git a/NotchBuddy/Sources/CoucouKit/QuestionPayload.swift b/NotchBuddy/Sources/CoucouKit/QuestionPayload.swiftnew file mode 100644index 00000000..ae2a12e0--- /dev/null+++ b/NotchBuddy/Sources/CoucouKit/QuestionPayload.swift@@ -0,0 +1,64 @@+import CryptoKit+import Foundation++// A question Claude Code asks (AskUserQuestion), as the iPhone gets it: the+// questions with their choices. The Mac writes it, encrypted, in the session+// record; the iPhone answers with an `Answer` record carrying the same+// fingerprint and the labels picked. The Mac only accepts labels that are+// among the choices of the question still waiting.++struct QuestionPayload: Codable, Equatable, Sendable {+ struct Option: Codable, Equatable, Sendable {+ var label: String+ var description: String+ }++ struct Item: Codable, Equatable, Sendable {+ var question: String+ var header: String+ var options: [Option]+ var multiSelect: Bool+ }++ var items: [Item]++ /// Stable identifier of this exact question.+ var fingerprint: String {+ let raw = items.map { item in+ ([item.question, item.multiSelect ? "multi" : "single"] + item.options.map(\.label)).joined(separator: "\u{1F}")+ }.joined(separator: "\u{1E}")+ return SHA256.hash(data: Data(raw.utf8)).map { String(format: "%02x", $0) }.joined()+ }++ var json: String {+ guard let data = try? JSONEncoder().encode(self) else { return "" }+ return String(decoding: data, as: UTF8.self)+ }++ static func decode(_ json: String) -> QuestionPayload? {+ guard !json.isEmpty else { return nil }+ return try? JSONDecoder().decode(QuestionPayload.self, from: Data(json.utf8))+ }++ /// The picks sent back: one list of labels per question.+ static func encodeSelections(_ selections: [[String]]) -> String {+ guard let data = try? JSONEncoder().encode(selections) else { return "[]" }+ return String(decoding: data, as: UTF8.self)+ }++ static func decodeSelections(_ json: String) -> [[String]]? {+ try? JSONDecoder().decode([[String]].self, from: Data(json.utf8))+ }++ /// True when every pick is one of that question's choices, with one pick+ /// per single-choice question.+ func accepts(_ selections: [[String]]) -> Bool {+ guard selections.count == items.count else { return false }+ for (item, picks) in zip(items, selections) {+ let labels = Set(item.options.map(\.label))+ guard !picks.isEmpty, picks.allSatisfy(labels.contains) else { return false }+ if !item.multiSelect && picks.count != 1 { return false }+ }+ return true+ }+}diff --git a/NotchBuddy/Sources/NotificationContent/NotificationViewController.swift b/NotchBuddy/Sources/NotificationContent/NotificationViewController.swiftindex ea59c811..7798e835 100644--- a/NotchBuddy/Sources/NotificationContent/NotificationViewController.swift+++ b/NotchBuddy/Sources/NotificationContent/NotificationViewController.swift@@ -9,66 +9,87 @@ import CloudKit// the system's, under this view.final class NotificationViewController: UIViewController, @preconcurrency UNNotificationContentExtension {- private var host: UIHostingController<ApprovalNotificationView>?+ private let host = UIHostingController(rootView: ApprovalNotificationView(pillId: "integration_claude", title: "", message: ""))++ override func viewDidLoad() {+ super.viewDidLoad()+ view.backgroundColor = UIColor(white: 0.08, alpha: 1)+ host.view.backgroundColor = .clear+ // Pinned with constraints: the extension's view has no size yet here.+ addChild(host)+ host.view.translatesAutoresizingMaskIntoConstraints = false+ view.addSubview(host.view)+ NSLayoutConstraint.activate([+ host.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),+ host.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),+ host.view.topAnchor.constraint(equalTo: view.topAnchor),+ host.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),+ ])+ host.didMove(toParent: self)+ preferredContentSize = CGSize(width: view.bounds.width, height: 200)+ }func didReceive(_ notification: UNNotification) {let content = notification.request.contentlet note = CKNotification(fromRemoteNotificationDictionary: content.userInfo) as? CKQueryNotificationlet pillId = content.userInfo["pillId"] as? String?? note?.recordFields?["pillId"] as? String ?? "integration_claude"- let card = ApprovalNotificationView(pillId: pillId, title: content.title, message: content.body)- if let host {- host.rootView = card- } else {- let host = UIHostingController(rootView: card)- host.view.backgroundColor = .clear- addChild(host)- host.view.frame = self.view.bounds- host.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]- self.view.addSubview(host.view)- host.didMove(toParent: self)- self.host = host- }- preferredContentSize = CGSize(width: self.view.bounds.width, height: 190)+ host.rootView = ApprovalNotificationView(pillId: pillId, title: content.title, message: content.body)+ preferredContentSize = CGSize(width: view.bounds.width, height: 200)}}+/// Mochi in his agent's color, waiting; who asks and the exact command.struct ApprovalNotificationView: View {let pillId: Stringlet title: Stringlet message: Stringprivate var pill: PillDefinition? { PillCatalog.definition(for: pillId) }+ private var color: String { pill?.color ?? "#FFFFFF" }/// The command alone, without the "Waiting for your OK: " the local notification adds.private var command: String {let prefix = "Waiting for your OK: "- return message.hasPrefix(prefix) ? String(message.dropFirst(prefix.count)) : message+ if message.hasPrefix(prefix) { return String(message.dropFirst(prefix.count)) }+ return message == "An agent is waiting for your OK" ? "" : message}var body: some View {- HStack(alignment: .top, spacing: 14) {- MochiLive(state: .approval, bodyHex: pill?.color ?? "#FFFFFF")- .padding(6)- .frame(width: 76, height: 76)- .background(Color(white: 0.16), in: RoundedRectangle(cornerRadius: 18))- VStack(alignment: .leading, spacing: 6) {- Text(title == "Coucou" ? (pill?.name ?? "Coucou") : title)- .font(.headline)- Text("Waiting for your OK")- .font(.subheadline.weight(.semibold))- .foregroundStyle(.orange)+ VStack(alignment: .leading, spacing: 14) {+ HStack(spacing: 14) {+ MochiLive(state: .approval, bodyHex: color)+ .padding(7)+ .frame(width: 60, height: 60)+ .background(Color.mochiTile(hex: color), in: RoundedRectangle(cornerRadius: 16))+ VStack(alignment: .leading, spacing: 4) {+ Text(title.isEmpty || title == "Coucou" ? (pill?.name ?? "Coucou") : title)+ .font(.headline)+ .foregroundStyle(.white)+ .lineLimit(1)+ HStack(spacing: 6) {+ Circle().fill(Color.orange).frame(width: 7, height: 7)+ Text("Waiting for your OK")+ .font(.subheadline.weight(.semibold))+ .foregroundStyle(.orange)+ }+ }+ Spacer(minLength: 0)+ }+ if !command.isEmpty {Text(command)- .font(.footnote.monospaced())+ .font(.callout.monospaced())+ .foregroundStyle(.white).lineLimit(4)- .padding(8)+ .padding(12).frame(maxWidth: .infinity, alignment: .leading)- .background(Color(white: 0.16), in: RoundedRectangle(cornerRadius: 10))+ .background(Color.white.opacity(0.08), in: RoundedRectangle(cornerRadius: 12))+ .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(Color.orange.opacity(0.35), lineWidth: 1))}}- .padding(16)+ .padding(18).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading).background(Color(white: 0.08))- .preferredColorScheme(.dark)+ .environment(\.colorScheme, .dark)}}diff --git a/NotchBuddy/Sources/Phone/AboutView.swift b/NotchBuddy/Sources/Phone/AboutView.swiftindex 82d7b4e9..84b74a22 100644--- a/NotchBuddy/Sources/Phone/AboutView.swift+++ b/NotchBuddy/Sources/Phone/AboutView.swift@@ -6,6 +6,11 @@ import UIKitstruct AboutView: View {let link: PhoneLink@State private var showGuide = false+ @AppStorage(PhoneSettings.notifyDoneKey) private var notifyDone = true+ @AppStorage(PhoneSettings.mochiSoundsKey) private var mochiSounds = true+ @AppStorage(PhoneSettings.quietHoursKey) private var quietHours = false+ @AppStorage(PhoneSettings.quietFromKey) private var quietFrom = 22 * 60+ @AppStorage(PhoneSettings.quietToKey) private var quietTo = 8 * 60private var version: String {let info = Bundle.main.infoDictionary@@ -51,6 +56,23 @@ struct AboutView: View {Button("How to connect your Mac") { showGuide = true }}+ Section {+ Toggle("When an agent finishes or fails", isOn: $notifyDone)+ Toggle("Mochi's sounds", isOn: $mochiSounds)+ .onChange(of: mochiSounds) { link.soundsChanged() }+ Toggle("Quiet hours", isOn: $quietHours)+ if quietHours {+ DatePicker("From", selection: time($quietFrom), displayedComponents: .hourAndMinute)+ DatePicker("To", selection: time($quietTo), displayedComponents: .hourAndMinute)+ }+ } header: {+ Text("Notifications")+ } footer: {+ Text(quietHours+ ? "In the quiet hours, only what waits on you (a command to allow, a question) makes a sound. The rest arrives silently."+ : "Approvals and questions always notify you. Mochi's sounds are the ones he makes in your Mac's notch.")+ }+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")!)@@ -68,6 +90,16 @@ struct AboutView: View {.sheet(isPresented: $showGuide) { OnboardingView() }}+ /// Minutes after midnight, as a time for the pickers.+ private func time(_ minutes: Binding<Int>) -> Binding<Date> {+ Binding {+ Calendar.current.startOfDay(for: .now).addingTimeInterval(TimeInterval(minutes.wrappedValue * 60))+ } set: { date in+ let parts = Calendar.current.dateComponents([.hour, .minute], from: date)+ minutes.wrappedValue = (parts.hour ?? 0) * 60 + (parts.minute ?? 0)+ }+ }+private var iCloudText: String {switch link.status {case .ready: "Linked"@@ -106,7 +138,7 @@ struct OnboardingView: View {icon: "icloud")VStack(alignment: .leading, spacing: 6) {Text("Then, from here").font(.headline)- Text("• Allow or deny a command, with Face ID\n• See what Claude did, file by file\n• Write or dictate the next instruction (GitHub version on the Mac)\n• Mochi in your Dynamic Island when your Mac is locked")+ Text("• Allow or deny a command, right from the Lock Screen\n• Answer Claude's questions\n• See what Claude did, file by file\n• Write or dictate the next instruction, or ask Siri (GitHub version on the Mac)\n• Mochi in your Dynamic Island when your Mac is locked").font(.callout).foregroundStyle(.secondary)}diff --git a/NotchBuddy/Sources/Phone/AgentNotifier.swift b/NotchBuddy/Sources/Phone/AgentNotifier.swiftnew file mode 100644index 00000000..b2a2e3d6--- /dev/null+++ b/NotchBuddy/Sources/Phone/AgentNotifier.swift@@ -0,0 +1,183 @@+import Foundation+import UIKit+import UserNotifications++/// The iPhone's notification settings (Settings → Notifications), kept on the iPhone.+enum PhoneSettings {+ static let notifyDoneKey = "notifyDone"+ static let mochiSoundsKey = "mochiSounds"+ static let quietHoursKey = "quietHours"+ static let quietFromKey = "quietFrom" // minutes after midnight+ static let quietToKey = "quietTo"++ private static var defaults: UserDefaults { .standard }++ /// A notification when an agent finishes or fails (on by default).+ static var notifyDone: Bool { defaults.object(forKey: notifyDoneKey) as? Bool ?? true }+ /// Mochi's own sounds instead of the iPhone's default one (on by default).+ static var mochiSounds: Bool { defaults.object(forKey: mochiSoundsKey) as? Bool ?? true }+ static var quietHours: Bool { defaults.bool(forKey: quietHoursKey) }+ static var quietFrom: Int { defaults.object(forKey: quietFromKey) as? Int ?? 22 * 60 }+ static var quietTo: Int { defaults.object(forKey: quietToKey) as? Int ?? 8 * 60 }++ /// Inside the quiet hours: only what waits on you (approvals, questions) makes a sound.+ static func isQuiet(at date: Date = .now) -> Bool {+ guard quietHours else { return false }+ let parts = Calendar.current.dateComponents([.hour, .minute], from: date)+ let now = (parts.hour ?? 0) * 60 + (parts.minute ?? 0)+ let from = quietFrom, to = quietTo+ if from == to { return false }+ return from < to ? (now >= from && now < to) : (now >= from || now < to)+ }++ /// One of Mochi's sounds (bundled WAV), or the iPhone's default.+ static func sound(_ name: String) -> UNNotificationSound {+ mochiSounds ? UNNotificationSound(named: UNNotificationSoundName("\(name).wav")) : .default+ }+}++/// Notification categories and their actions.+enum NotificationActions {+ // Approvals: Allow and Deny answer right there (iOS asks to unlock first).+ static let approvalCategory = "COUCOU_APPROVAL"+ static let allow = "COUCOU_ALLOW"+ static let review = "COUCOU_REVIEW"+ static let deny = "COUCOU_DENY"+ // An agent finished: reply with the next instruction.+ static let doneReplyCategory = "COUCOU_DONE_REPLY"+ static let doneCategory = "COUCOU_DONE"+ static let reply = "COUCOU_REPLY"+ // A question: one button per choice when it is a single question.+ static let questionCategory = "COUCOU_QUESTION"+ static let pickPrefix = "COUCOU_PICK_"++ /// Categories made for the latest questions, kept next to the fixed ones.+ @MainActor private static var questionCategories: [UNNotificationCategory] = []++ @MainActor static func register() {+ let allow = UNNotificationAction(identifier: allow, title: "Allow",+ options: [.authenticationRequired],+ icon: UNNotificationActionIcon(systemImageName: "faceid"))+ let review = UNNotificationAction(identifier: review, title: "Review",+ options: [.foreground, .authenticationRequired])+ let deny = UNNotificationAction(identifier: deny, title: "Deny",+ options: [.destructive, .authenticationRequired])+ let approval = UNNotificationCategory(identifier: approvalCategory, actions: [allow, review, deny],+ intentIdentifiers: [], options: [])+ let reply = UNTextInputNotificationAction(identifier: reply, title: "Reply",+ options: [.authenticationRequired],+ icon: UNNotificationActionIcon(systemImageName: "arrowshape.turn.up.left"),+ textInputButtonTitle: "Send",+ textInputPlaceholder: "Tell Claude what to do next…")+ let doneReply = UNNotificationCategory(identifier: doneReplyCategory, actions: [reply],+ intentIdentifiers: [], options: [])+ let done = UNNotificationCategory(identifier: doneCategory, actions: [], intentIdentifiers: [], options: [])+ let question = UNNotificationCategory(identifier: questionCategory, actions: [],+ intentIdentifiers: [], options: [])+ UNUserNotificationCenter.current().setNotificationCategories(+ Set([approval, doneReply, done, question] + questionCategories))+ }++ /// A category with one button per choice of this question; nil when it+ /// has several questions or allows several picks (answered in the app).+ @MainActor static func category(for payload: QuestionPayload) -> String? {+ guard payload.items.count == 1, let item = payload.items.first, !item.multiSelect else { return nil }+ let id = "COUCOU_Q_\(payload.fingerprint.prefix(16))"+ let actions = item.options.prefix(4).enumerated().map { index, option in+ UNNotificationAction(identifier: "\(pickPrefix)\(index)", title: option.label,+ options: [.authenticationRequired])+ }+ questionCategories.removeAll { $0.identifier == id }+ questionCategories.append(UNNotificationCategory(identifier: id, actions: Array(actions),+ intentIdentifiers: [], options: []))+ questionCategories = Array(questionCategories.suffix(3))+ register()+ return id+ }+}++/// Local notifications for what happens on the Mac while the app is in the+/// background: an agent finished or failed, or asks a question. Approvals+/// have their own path (PhoneLink). Each event is notified once, and only if+/// it happened in the last 10 minutes.+@MainActor+enum AgentNotifier {+ enum Event {+ case finished(SessionItem)+ case failed(SessionItem)+ case question(SessionItem, QuestionPayload)+ }++ private static let seenKey = "notifiedEvents"++ /// What each session looked like the last time, kept across launches so+ /// an app woken by a push still sees what changed.+ private static var lastSeen: [String: String] {+ get { UserDefaults.standard.dictionary(forKey: seenKey) as? [String: String] ?? [:] }+ set { UserDefaults.standard.set(newValue, forKey: seenKey) }+ }++ /// The event this new session record brings, if any.+ static func event(for session: SessionItem) -> Event? {+ let key: String+ switch session.state {+ case .finished: key = "finished"+ case .error: key = "error"+ default: key = session.questionFingerprint.isEmpty ? session.state.rawValue : "q-\(session.questionFingerprint)"+ }+ let before = lastSeen[session.id]+ lastSeen[session.id] = key+ guard before != key, Date().timeIntervalSince(session.updatedAt) < 600 else { return nil }+ if let payload = session.questionPayload, !session.questionFingerprint.isEmpty, key.hasPrefix("q-") {+ return .question(session, payload)+ }+ if key == "finished" { return .finished(session) }+ if key == "error" { return .failed(session) }+ return nil+ }++ static func post(_ event: Event, turn: TurnSnapshot?) async {+ guard UIApplication.shared.applicationState != .active else { return }+ let content = UNMutableNotificationContent()+ let quiet = PhoneSettings.isQuiet()+ switch event {+ case .finished(let session):+ guard PhoneSettings.notifyDone else { return }+ content.title = "\(session.pillName) · \(session.title)"+ let answer = turn.map(\.finalMessage).flatMap { $0.isEmpty ? nil : $0 } ?? session.finalLine+ content.body = answer.isEmpty ? "Done. What's next?" : "✓ " + String(answer.prefix(220))+ content.sound = quiet ? nil : PhoneSettings.sound("finish")+ content.categoryIdentifier = session.acceptsInstructions+ ? NotificationActions.doneReplyCategory : NotificationActions.doneCategory+ content.userInfo = ["pillId": session.id, "kind": "done"]+ if quiet { content.interruptionLevel = .passive }+ case .failed(let session):+ guard PhoneSettings.notifyDone 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")+ content.categoryIdentifier = session.acceptsInstructions+ ? NotificationActions.doneReplyCategory : NotificationActions.doneCategory+ content.userInfo = ["pillId": session.id, "kind": "done"]+ if quiet { content.interruptionLevel = .passive }+ case .question(let session, let payload):+ // A question blocks the agent like an approval: it rings in the quiet hours too.+ content.title = "\(session.pillName) has a question"+ let first = payload.items.first+ content.body = first.map { item in+ item.question + "\n" + item.options.map { "• \($0.label)" }.joined(separator: "\n")+ } ?? session.question+ content.sound = PhoneSettings.sound("question")+ content.categoryIdentifier = NotificationActions.category(for: payload) ?? NotificationActions.questionCategory+ content.userInfo = ["pillId": session.id, "kind": "question",+ "fingerprint": session.questionFingerprint,+ "options": first?.options.prefix(4).map(\.label) ?? []]+ // Let iOS take the new category before the notification shows.+ try? await Task.sleep(for: .milliseconds(300))+ }+ content.threadIdentifier = content.userInfo["pillId"] as? String ?? "coucou"+ let kind = content.userInfo["kind"] as? String ?? "event"+ let request = UNNotificationRequest(identifier: "\(kind)-\(UUID().uuidString)", content: content, trigger: nil)+ try? await UNUserNotificationCenter.current().add(request)+ }+}diff --git a/NotchBuddy/Sources/Phone/CoucouIntents.swift b/NotchBuddy/Sources/Phone/CoucouIntents.swiftnew file mode 100644index 00000000..801f8767--- /dev/null+++ b/NotchBuddy/Sources/Phone/CoucouIntents.swift@@ -0,0 +1,69 @@+import AppIntents+import Foundation++// Siri and the Shortcuts app: ask where your agents are, or send Claude the+// next instruction. Sending needs the iPhone unlocked by its owner, like the+// instruction field in the app needs Face ID.++struct AgentsStatusIntent: AppIntent {+ static let title: LocalizedStringResource = "Agent status"+ static var description: IntentDescription { IntentDescription("What your agents are doing on your Mac.") }++ @MainActor+ func perform() async throws -> some IntentResult & ProvidesDialog {+ let link = PhoneLink.shared+ await link.refresh()+ let sessions = link.sessions.sortedByUrgency()+ guard let lead = sessions.first else {+ return .result(dialog: "All quiet: no agent session on your Mac.")+ }+ let summary = sessions.summary ?? "All quiet"+ return .result(dialog: "\(summary). \(lead.pillName), \(lead.title): \(lead.statusText).")+ }+}++struct AskClaudeIntent: AppIntent {+ static let title: LocalizedStringResource = "Ask Claude"+ static var description: IntentDescription {+ IntentDescription("Sends the next instruction to your Claude Code session on your Mac.")+ }+ static var authenticationPolicy: IntentAuthenticationPolicy { .requiresAuthentication }++ @Parameter(title: "Instruction", requestValueDialog: "What should Claude do?")+ var instruction: String++ @MainActor+ func perform() async throws -> some IntentResult & ProvidesDialog {+ let link = PhoneLink.shared+ await link.refresh()+ let text = instruction.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !text.isEmpty else { return .result(dialog: "Nothing to send.") }+ // The Claude Code session that last moved and takes instructions.+ guard let session = link.sessions+ .filter({ $0.acceptsInstructions })+ .max(by: { $0.updatedAt < $1.updatedAt }) else {+ return .result(dialog: "No Claude Code session takes instructions. Turn it on in Coucou's Settings on your Mac.")+ }+ guard await link.sendInstruction(text, pillId: session.id) else {+ return .result(dialog: "Couldn't reach iCloud. Nothing was sent.")+ }+ return .result(dialog: "Sent to Claude in \(session.title). Your Mac picks it up within 15 seconds.")+ }+}++struct CoucouShortcuts: AppShortcutsProvider {+ static var appShortcuts: [AppShortcut] {+ AppShortcut(intent: AskClaudeIntent(),+ phrases: ["Ask Claude in \(.applicationName)",+ "Tell Claude with \(.applicationName)",+ "Send an instruction with \(.applicationName)"],+ shortTitle: "Ask Claude",+ systemImageName: "text.bubble")+ AppShortcut(intent: AgentsStatusIntent(),+ phrases: ["What are my agents doing in \(.applicationName)",+ "\(.applicationName) status",+ "Agent status in \(.applicationName)"],+ shortTitle: "Agent status",+ systemImageName: "sparkles")+ }+}diff --git a/NotchBuddy/Sources/Phone/CoucouPhoneApp.swift b/NotchBuddy/Sources/Phone/CoucouPhoneApp.swiftindex 8f9d0520..815e2379 100644--- a/NotchBuddy/Sources/Phone/CoucouPhoneApp.swift+++ b/NotchBuddy/Sources/Phone/CoucouPhoneApp.swift@@ -26,7 +26,7 @@ final class PhoneAppDelegate: NSObject, UIApplicationDelegate, UNUserNotificatiofunc application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {UNUserNotificationCenter.current().delegate = self- ApprovalActions.register()+ NotificationActions.register()LiveActivityLink.shared.start()application.registerForRemoteNotifications()Task { await PhoneLink.shared.start() }@@ -46,7 +46,13 @@ final class PhoneAppDelegate: NSObject, UIApplicationDelegate, UNUserNotificatioTask { @MainActor in PhoneLink.shared.pushError = message }}- // Approval notification actions.+ /// Portrait everywhere, except a diff opened full screen (it can turn sideways).+ func application(_ application: UIApplication,+ supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {+ OrientationLock.mask+ }++ // Notification actions: approvals, replies to a finished agent, answers to a question.//// Completion-handler versions, with the handler always called on the main// thread: with the async versions iOS finished the tap off the main thread@@ -56,30 +62,55 @@ final class PhoneAppDelegate: NSObject, UIApplicationDelegate, UNUserNotificatiowithCompletionHandler completionHandler: @escaping () -> Void) {nonisolated(unsafe) let done = completionHandlerlet request = response.notification.request- guard let fingerprint = PhoneLink.approvalFingerprint(in: request) else {- DispatchQueue.main.async { done() }+ let userInfo = request.content.userInfo+ let action = response.actionIdentifier+ let typed = (response as? UNTextInputNotificationResponse)?.userText ?? ""+ let note = CKNotification(fromRemoteNotificationDictionary: userInfo) as? CKQueryNotification+ let pillId = userInfo["pillId"] as? String ?? note?.recordFields?["pillId"] as? String ?? ""++ if let fingerprint = PhoneLink.approvalFingerprint(in: request) {+ Task { @MainActor in+ await Self.handleApproval(action: action, fingerprint: fingerprint, pillId: pillId)+ done()+ }return}- let note = CKNotification(fromRemoteNotificationDictionary: request.content.userInfo) as? CKQueryNotification- let pillId = request.content.userInfo["pillId"] as? String- ?? note?.recordFields?["pillId"] as? String ?? ""- let denied = response.actionIdentifier == ApprovalActions.deny+ let kind = userInfo["kind"] as? String ?? ""+ let fingerprint = userInfo["fingerprint"] as? String ?? ""+ let options = userInfo["options"] as? [String] ?? []Task { @MainActor in- await Self.handleApproval(denied: denied, fingerprint: fingerprint, pillId: pillId)+ let link = PhoneLink.shared+ switch (kind, action) {+ case ("done", NotificationActions.reply):+ let text = typed.trimmingCharacters(in: .whitespacesAndNewlines)+ if !text.isEmpty { _ = await link.sendInstruction(text, pillId: pillId) }+ case ("question", let picked) where picked.hasPrefix(NotificationActions.pickPrefix):+ let index = Int(picked.dropFirst(NotificationActions.pickPrefix.count)) ?? -1+ if options.indices.contains(index) {+ _ = await link.answer(fingerprint: fingerprint, pillId: pillId, selections: [[options[index]]])+ }+ default:+ // A tap on the notification: open that session.+ if !pillId.isEmpty { link.openPillId = pillId }+ }done()}}@MainActor- private static func handleApproval(denied: Bool, fingerprint: String, pillId: String) async {+ private static func handleApproval(action: String, fingerprint: String, pillId: String) async {let link = PhoneLink.sharedlink.noteICloudAlert(fingerprint)- if denied {+ switch action {+ case NotificationActions.deny:// Awaited so the decision is saved before iOS suspends the app again.let summary = link.sessions.first { $0.approvalFingerprint == fingerprint }?.approvalCommand_ = await link.decide(.deny, fingerprint: fingerprint, pillId: pillId,summary: summary ?? "Denied from the notification")- } else {+ case NotificationActions.allow:+ // Answered right there: iOS had the iPhone unlocked by its owner first.+ _ = await link.allowFromOutside(fingerprint: fingerprint, pillId: pillId, from: "a notification")+ default:// Review, or a tap on the notification: open the command, Allow needs Face ID there.link.reviewFingerprint = fingerprintTask { await link.refresh() }@@ -106,3 +137,9 @@ final class PhoneAppDelegate: NSObject, UIApplicationDelegate, UNUserNotificatio}}}++/// Which way the screen may turn; set by the full-screen diff.+@MainActor+enum OrientationLock {+ static var mask: UIInterfaceOrientationMask = .portrait+}diff --git a/NotchBuddy/Sources/Phone/Decisions.swift b/NotchBuddy/Sources/Phone/Decisions.swiftindex fb4cc338..7af68275 100644--- a/NotchBuddy/Sources/Phone/Decisions.swift+++ b/NotchBuddy/Sources/Phone/Decisions.swift@@ -1,6 +1,5 @@import Foundationimport LocalAuthentication-import UserNotificationsenum Decision: String, Codable, Sendable {case allow, deny@@ -27,24 +26,6 @@ struct DecisionLog: Codable, Identifiable, Sendable {}}-/// Notification actions for approval requests. "Review" opens the app on the-/// command (Allow needs Face ID there); "Deny" works from the notification.-enum ApprovalActions {- static let category = "COUCOU_APPROVAL"- static let review = "COUCOU_REVIEW"- static let deny = "COUCOU_DENY"-- static func register() {- let review = UNNotificationAction(identifier: review, title: "Review",- options: [.foreground, .authenticationRequired])- let deny = UNNotificationAction(identifier: deny, title: "Deny",- options: [.destructive, .authenticationRequired])- let category = UNNotificationCategory(identifier: category, actions: [review, deny],- intentIdentifiers: [], options: [])- UNUserNotificationCenter.current().setNotificationCategories([category])- }-}-/// Face ID (or the passcode) before allowing a command. Never skipped.enum OwnerCheck {static func confirm(reason: String) async -> Bool {diff --git a/NotchBuddy/Sources/Phone/DenyApprovalIntent.swift b/NotchBuddy/Sources/Phone/DenyApprovalIntent.swiftnew file mode 100644index 00000000..4b2eb30a--- /dev/null+++ b/NotchBuddy/Sources/Phone/DenyApprovalIntent.swift@@ -0,0 +1,56 @@+import AppIntents+import Foundation++/// Deny on the Live Activity: answers the command waiting for your OK without+/// opening Coucou. Compiled into the app and the widgets extension; iOS runs+/// it in the app.+struct DenyApprovalIntent: LiveActivityIntent {+ static let title: LocalizedStringResource = "Deny the command"+ static var isDiscoverable: Bool { false }+ static var authenticationPolicy: IntentAuthenticationPolicy { .requiresAuthentication }++ @Parameter(title: "Request") var fingerprint: String+ @Parameter(title: "Agent") var pillId: String++ init() {}++ init(fingerprint: String, pillId: String) {+ self.fingerprint = fingerprint+ self.pillId = pillId+ }++ func perform() async throws -> some IntentResult {+ #if !WIDGET_EXTENSION+ let link = await PhoneLink.shared+ _ = await link.decide(.deny, fingerprint: fingerprint, pillId: pillId, summary: "Denied from the Lock Screen")+ #endif+ return .result()+ }+}++/// Allow on the Live Activity, right where you are: iOS asks to unlock the+/// iPhone (Face ID) if it is locked, then the OK goes to the Mac without+/// opening Coucou. The Mac applies it only to this exact command.+struct AllowApprovalIntent: LiveActivityIntent {+ static let title: LocalizedStringResource = "Allow the command"+ static var isDiscoverable: Bool { false }+ static var authenticationPolicy: IntentAuthenticationPolicy { .requiresAuthentication }++ @Parameter(title: "Request") var fingerprint: String+ @Parameter(title: "Agent") var pillId: String++ init() {}++ init(fingerprint: String, pillId: String) {+ self.fingerprint = fingerprint+ self.pillId = pillId+ }++ func perform() async throws -> some IntentResult {+ #if !WIDGET_EXTENSION+ let link = await PhoneLink.shared+ _ = await link.allowFromOutside(fingerprint: fingerprint, pillId: pillId, from: "the Lock Screen")+ #endif+ return .result()+ }+}diff --git a/NotchBuddy/Sources/Phone/HomeView.swift b/NotchBuddy/Sources/Phone/HomeView.swiftindex c24a2184..dcc30fa2 100644--- a/NotchBuddy/Sources/Phone/HomeView.swift+++ b/NotchBuddy/Sources/Phone/HomeView.swift@@ -12,6 +12,7 @@ struct HomeView: View {ScrollView {VStack(spacing: 16) {NotchHeader(sessions: link.sessions, status: link.status)+ TodayCard(link: link)if link.sessions.isEmpty {EmptySessionsView(status: link.status)} else {@@ -29,6 +30,9 @@ struct HomeView: View {}.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)" })}ServicesList(services: link.services)}@@ -48,6 +52,12 @@ struct HomeView: View {.onOpenURL { url inif 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 {@@ -101,11 +111,13 @@ struct NotchHeader: View {Text(headline).font(.headline).foregroundStyle(.white)+ .contentTransition(.interpolate)if let detail {Text(detail).font(.subheadline).foregroundStyle(.white.opacity(0.6)).lineLimit(1)+ .contentTransition(.interpolate)}}Spacer(minLength: 0)@@ -118,6 +130,7 @@ struct NotchHeader: View {.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 {@@ -161,6 +174,7 @@ struct SessionRow: View {Text(session.statusText).font(.subheadline.weight(session.isWaitingForYou ? .semibold : .regular)).foregroundStyle(session.statusColor)+ .contentTransition(.interpolate)Text(session.updatedAt, style: .relative).font(.caption2).foregroundStyle(.tertiary)@@ -197,3 +211,53 @@ struct EmptySessionsView: View {}}}++/// Today, as this iPhone saw it: turns finished, files and lines changed,+/// commands you answered. Counted on the iPhone, never sent anywhere.+struct TodayCard: View {+ let link: PhoneLink++ private var decisionsToday: Int {+ link.history.filter { Calendar.current.isDateInToday($0.date) }.count+ }++ var body: some View {+ let tally = link.archive.currentTally+ if !tally.isEmpty || decisionsToday > 0 {+ HStack(spacing: 0) {+ stat("\(tally.turns)", tally.turns == 1 ? "turn" : "turns")+ stat("\(tally.files)", tally.files == 1 ? "file" : "files")+ VStack(spacing: 2) {+ HStack(spacing: 4) {+ Text("+\(tally.added)").foregroundStyle(.green)+ Text("−\(tally.removed)").foregroundStyle(.red)+ }+ .font(.headline.monospacedDigit())+ .lineLimit(1)+ .minimumScaleFactor(0.6)+ Text("lines").font(.caption2).foregroundStyle(.secondary)+ }+ .frame(maxWidth: .infinity)+ stat("\(decisionsToday)", decisionsToday == 1 ? "OK given" : "OKs given")+ }+ .padding(.vertical, 12)+ .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))+ .overlay(alignment: .topLeading) {+ Text("TODAY")+ .font(.caption2.weight(.bold))+ .foregroundStyle(.tertiary)+ .padding(.horizontal, 10)+ .offset(y: -16)+ }+ .padding(.top, 10)+ }+ }++ private func stat(_ value: String, _ label: String) -> some View {+ VStack(spacing: 2) {+ Text(value).font(.headline.monospacedDigit())+ Text(label).font(.caption2).foregroundStyle(.secondary)+ }+ .frame(maxWidth: .infinity)+ }+}diff --git a/NotchBuddy/Sources/Phone/InstructionComposer.swift b/NotchBuddy/Sources/Phone/InstructionComposer.swiftindex 2acc86af..0606ca7c 100644--- a/NotchBuddy/Sources/Phone/InstructionComposer.swift+++ b/NotchBuddy/Sources/Phone/InstructionComposer.swift@@ -13,12 +13,14 @@ struct InstructionComposer: View {@State private var sentAt: Date?@State private var error: String?@State private var dictation = Dictation()+ @State private var quickReplies = QuickReplies.load()@FocusState private var focused: Bool/// A bar at the bottom of the session screen, like a chat.var body: some View {VStack(alignment: .leading, spacing: 6) {if session.acceptsInstructions {+ shortcutscomposerstatus} else {@@ -38,6 +40,53 @@ struct InstructionComposer: View {}}+ /// Instructions you send often: a tap puts one in the field (it isn't sent+ /// yet); + keeps what is typed; a long press removes one.+ private var shortcuts: some View {+ ScrollView(.horizontal, showsIndicators: false) {+ HStack(spacing: 6) {+ ForEach(quickReplies, id: \.self) { reply in+ Button {+ text = reply+ focused = true+ Haptics.impact()+ } label: {+ Text(reply)+ .font(.footnote)+ .lineLimit(1)+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ .background(Color(white: 0.16), in: Capsule())+ }+ .buttonStyle(.plain)+ .contextMenu {+ Button(role: .destructive) {+ quickReplies.removeAll { $0 == reply }+ QuickReplies.save(quickReplies)+ } label: {+ Label("Remove", systemImage: "trash")+ }+ }+ }+ let typed = text.trimmingCharacters(in: .whitespacesAndNewlines)+ if !typed.isEmpty && !quickReplies.contains(typed) {+ Button {+ quickReplies.append(typed)+ QuickReplies.save(quickReplies)+ Haptics.success()+ } label: {+ Label("Keep", systemImage: "plus")+ .font(.footnote.weight(.semibold))+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ .background(Color.accentColor.opacity(0.25), in: Capsule())+ }+ .buttonStyle(.plain)+ }+ }+ }+ }+private var composer: some View {HStack(alignment: .bottom, spacing: 8) {TextField("Tell Claude what to do next…", text: $text, axis: .vertical)@@ -209,3 +258,17 @@ final class Dictation: @unchecked Sendable {return await AVAudioApplication.requestRecordPermission()}}++/// The shortcuts above the instruction field, kept on this iPhone.+enum QuickReplies {+ private static let key = "quickReplies"+ static let defaults = ["Continue", "Run the tests", "Fix the errors", "Commit the changes", "Explain what you changed"]++ static func load() -> [String] {+ UserDefaults.standard.stringArray(forKey: key) ?? defaults+ }++ static func save(_ replies: [String]) {+ UserDefaults.standard.set(replies, forKey: key)+ }+}diff --git a/NotchBuddy/Sources/Phone/LastTurnView.swift b/NotchBuddy/Sources/Phone/LastTurnView.swiftindex a028ff96..623b5cd7 100644--- a/NotchBuddy/Sources/Phone/LastTurnView.swift+++ b/NotchBuddy/Sources/Phone/LastTurnView.swift@@ -1,4 +1,5 @@import SwiftUI+import UIKit/// The last turn of a session: your prompt, what the agent did, the files it/// changed (tap for the diff) and its answer.@@ -195,6 +196,10 @@ private struct ActionRow: View {/// A changed file, line by line: removed in red, added in green.struct FileDiffView: View {let file: TurnFile+ /// Shown full screen, where the iPhone can turn sideways for long lines.+ var fullScreen = false+ @State private var showFullScreen = false+ @Environment(\.dismiss) private var dismissvar body: some View {ScrollView([.vertical, .horizontal]) {@@ -222,7 +227,30 @@ struct FileDiffView: View {}.font(.footnote.monospacedDigit().weight(.semibold))}+ ToolbarItem(placement: fullScreen ? .topBarLeading : .topBarTrailing) {+ if fullScreen {+ Button("Done") { dismiss() }+ } else {+ Button { showFullScreen = true } label: {+ Image(systemName: "arrow.up.left.and.arrow.down.right")+ }+ .accessibilityLabel("Full screen")+ }+ }}+ .fullScreenCover(isPresented: $showFullScreen) {+ NavigationStack { FileDiffView(file: file, fullScreen: true) }+ .onAppear { Self.allowLandscape(true) }+ .onDisappear { Self.allowLandscape(false) }+ }+ }++ /// Lets the screen turn while the full-screen diff is open; back to portrait after.+ private static func allowLandscape(_ allowed: Bool) {+ OrientationLock.mask = allowed ? .allButUpsideDown : .portrait+ guard let scene = UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }).first else { return }+ scene.keyWindow?.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations()+ if !allowed { scene.requestGeometryUpdate(.iOS(interfaceOrientations: .portrait)) }}@ViewBuilder private func row(_ line: TurnDiffLine) -> some View {diff --git a/NotchBuddy/Sources/Phone/OpenLeadMochiIntent.swift b/NotchBuddy/Sources/Phone/OpenLeadMochiIntent.swiftnew file mode 100644index 00000000..52ff9a7d--- /dev/null+++ b/NotchBuddy/Sources/Phone/OpenLeadMochiIntent.swift@@ -0,0 +1,13 @@+import AppIntents+import Foundation++/// Opens Coucou on the Mochi that needs you most (Control Center button).+/// Compiled into the app and the widgets extension.+struct OpenLeadMochiIntent: AppIntent {+ static let title: LocalizedStringResource = "Open the agent that needs you"++ func perform() async throws -> some IntentResult & OpensIntent {+ let url = SharedSessions.load().first.map { SharedSession.url(for: $0.id) } ?? URL(string: "coucou://home")!+ return .result(opensIntent: OpenURLIntent(url))+ }+}diff --git a/NotchBuddy/Sources/Phone/PhoneLink.swift b/NotchBuddy/Sources/Phone/PhoneLink.swiftindex a8052790..1f2a819c 100644--- a/NotchBuddy/Sources/Phone/PhoneLink.swift+++ b/NotchBuddy/Sources/Phone/PhoneLink.swift@@ -30,6 +30,9 @@ struct SessionItem: Identifiable {/// The Mac runs instructions sent from here for this session (GitHub build, switch on).let acceptsInstructions: Boollet question: String+ /// The question's choices, when it can be answered from here.+ let questionPayload: QuestionPayload?+ let questionFingerprint: Stringlet finalLine: Stringlet cwd: Stringlet updatedAt: Date@@ -47,6 +50,8 @@ struct SessionItem: Identifiable {approvalFingerprint = record["approvalFingerprint"] as? String ?? ""acceptsInstructions = record["acceptsInstructions"] as? Bool ?? falsequestion = record.encryptedValues["question"] as? String ?? ""+ questionPayload = QuestionPayload.decode(record.encryptedValues["questionPayload"] as? String ?? "")+ questionFingerprint = record["questionFingerprint"] as? String ?? ""finalLine = record.encryptedValues["finalLine"] as? String ?? ""cwd = record.encryptedValues["cwd"] as? String ?? ""updatedAt = record["updatedAt"] as? Date ?? record.modificationDate ?? .now@@ -84,9 +89,13 @@ final class PhoneLink {var services: [String: ServiceSnapshot] = [:]/// 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).+ var archive = TurnArchive.load()var lastPong: String?var pushError: String?var notificationsAllowed: Bool?+ /// A session to open, from a notification, a shortcut or the Control Center.+ var openPillId: String?@ObservationIgnored private let container = CKContainer(identifier: PhoneLink.containerID)@ObservationIgnored private var database: CKDatabase { container.privateCloudDatabase }@@ -95,6 +104,8 @@ final class PhoneLink {@ObservationIgnored private var subscribed = false@ObservationIgnored private var approvalsSubscribed = false@ObservationIgnored private var fetching = false+ /// Things to notify once the fetch is done (finished, failed, questions).+ @ObservationIgnored private var events: [AgentNotifier.Event] = []func start() async {let center = UNUserNotificationCenter.current()@@ -118,12 +129,14 @@ final class PhoneLink {if subscribed && !approvalsSubscribed { await subscribeToApprovals() }_ = await fetchChanges()await notifyNewApprovals()+ await postEvents()}/// Called on a CloudKit push. Returns true when new records arrived.func handlePush() async -> Bool {let gotNew = await fetchChanges()await notifyNewApprovals()+ await postEvents()return gotNew}@@ -146,19 +159,23 @@ final class PhoneLink {/// (ApprovalRelay), with Review and Deny actions. Kept apart from the/// silent subscription so a failure here never stops the sessions.private func subscribeToApprovals() async {+ // A saved subscription keeps its sound: one ID per sound, the other one is deleted.+ let mochi = PhoneSettings.mochiSoundslet approvals = CKQuerySubscription(recordType: "ApprovalRequest", predicate: NSPredicate(value: true),- subscriptionID: "coucou-approvals", options: [.firesOnRecordCreation])+ subscriptionID: mochi ? "coucou-approvals-mochi" : "coucou-approvals",+ options: [.firesOnRecordCreation])approvals.zoneID = Self.zoneIDlet alert = CKSubscription.NotificationInfo()alert.title = "Coucou"alert.alertBody = "An agent is waiting for your OK"- alert.soundName = "default"- alert.category = ApprovalActions.category+ alert.soundName = mochi ? "approval.wav" : "default"+ alert.category = NotificationActions.approvalCategoryalert.shouldSendContentAvailable = truealert.desiredKeys = ["fingerprint", "pillId"]approvals.notificationInfo = alertdo {_ = try await database.modifySubscriptions(saving: [approvals], deleting: [])+ _ = try? await database.modifySubscriptions(saving: [], deleting: [mochi ? "coucou-approvals" : "coucou-approvals-mochi"])approvalsSubscribed = trueapprovalsStatus = "On"} catch {@@ -232,6 +249,9 @@ final class PhoneLink {if record.recordType == TurnSnapshot.recordType {guard let payload = record.encryptedValues["payload"] as? String,let turn = try? JSONDecoder().decode(TurnSnapshot.self, from: Data(payload.utf8)) else { return false }+ let before = archive+ archive.update(from: turns[turn.pillId], to: turn)+ if archive.past != before.past || archive.today != before.today { archive.save() }turns[turn.pillId] = turnreturn false // nothing for the widgets}@@ -245,6 +265,7 @@ final class PhoneLink {let item = SessionItem(record: record)// Services used to come as sessions; they have their own records now.guard PillCatalog.isSession(item.id) else { return false }+ if let event = AgentNotifier.event(for: item) { events.append(event) }sessions.removeAll { $0.id == item.id }sessions.append(item)sessions.sort { $0.updatedAt > $1.updatedAt }@@ -296,8 +317,8 @@ final class PhoneLink {content.body = session.approvalCommand.isEmpty? "An agent is waiting for your OK": "Waiting for your OK: \(session.approvalCommand.prefix(140))"- content.sound = .default- content.categoryIdentifier = ApprovalActions.category+ content.sound = PhoneSettings.sound("approval")+ content.categoryIdentifier = NotificationActions.approvalCategorycontent.userInfo = ["fingerprint": session.approvalFingerprint, "pillId": session.id]let request = UNNotificationRequest(identifier: Self.approvalNotificationID(session.approvalFingerprint),content: content, trigger: nil)@@ -337,11 +358,54 @@ final class PhoneLink {/// The approval fingerprint carried by a notification, local or from iCloud.nonisolated static func approvalFingerprint(in request: UNNotificationRequest) -> String? {let userInfo = request.content.userInfo+ // Finished and question notifications carry a "kind"; approvals don't.+ guard userInfo["kind"] == nil else { return nil }if let fingerprint = userInfo["fingerprint"] as? String { return fingerprint }let note = CKNotification(fromRemoteNotificationDictionary: userInfo) as? CKQueryNotificationreturn note?.recordFields?["fingerprint"] as? String}+ /// Finished, failed and question notifications, after a fetch (in the+ /// background only; the app open shows it all already).+ private func postEvents() async {+ let pending = events+ events = []+ for event in pending {+ let pillId: String+ switch event {+ case .finished(let session), .failed(let session), .question(let session, _): pillId = session.id+ }+ await AgentNotifier.post(event, turn: turns[pillId])+ }+ }++ /// The approval subscription is made again with the new sound.+ func soundsChanged() {+ approvalsSubscribed = false+ Task { await refresh() }+ }++ // MARK: Questions++ /// Answers the question a session waits on. The Mac takes it within ~2 s,+ /// only if it is still the same question and the picks are among its choices.+ func answer(fingerprint: String, pillId: String, selections: [[String]]) async -> Bool {+ let record = CKRecord(recordType: "Answer",+ recordID: CKRecord.ID(recordName: "answer-\(UUID().uuidString)", zoneID: Self.zoneID))+ record["fingerprint"] = fingerprint+ record["pillId"] = pillId+ record["answeredAt"] = Date()+ record["deviceName"] = UIDevice.current.name+ record.encryptedValues["selections"] = QuestionPayload.encodeSelections(selections)+ do {+ _ = try await database.save(record)+ return true+ } catch {+ lastPong = "Answer failed: \(error.localizedDescription)"+ return false+ }+ }+// MARK: Instructions (step B)/// Sends an instruction to continue a session on the Mac. The Mac takes it@@ -392,10 +456,22 @@ final class PhoneLink {}}+ /// Allow from the Live Activity or a notification, without opening the app+ /// (the iPhone was unlocked by its owner: iOS asks for it first).+ func allowFromOutside(fingerprint: String, pillId: String, from place: String) async -> Bool {+ noteICloudAlert(fingerprint)+ let command = sessions.first { $0.approvalFingerprint == fingerprint }?.approvalCommand ?? ""+ let summary = command.isEmpty ? "Allowed from \(place)" : String(command.prefix(200))+ let sent = await decide(.allow, fingerprint: fingerprint, pillId: pillId, summary: summary)+ if sent { UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [Self.approvalNotificationID(fingerprint)]) }+ return sent+ }+/// Hands the sessions to the widgets and asks them to redraw.private func updateWidgets() {SharedSessions.save(sessions.map(\.shared) + services.values.map(\.shared))WidgetCenter.shared.reloadAllTimelines()+ ControlCenter.shared.reloadAllControls()}/// Writes a Pong linked to the latest Ping.diff --git a/NotchBuddy/Sources/Phone/QuestionCard.swift b/NotchBuddy/Sources/Phone/QuestionCard.swiftnew file mode 100644index 00000000..870f4750--- /dev/null+++ b/NotchBuddy/Sources/Phone/QuestionCard.swift@@ -0,0 +1,119 @@+import SwiftUI++/// A question Claude asks (AskUserQuestion), with its choices: pick, then+/// Send. The Mac answers Claude with exactly these choices.+struct QuestionCard: View {+ let link: PhoneLink+ let session: SessionItem+ let payload: QuestionPayload++ @State private var picks: [Set<String>] = []+ @State private var sending = false+ @State private var sent = false+ @State private var error: String?++ private var ready: Bool {+ picks.count == payload.items.count && !picks.contains { $0.isEmpty }+ }++ var body: some View {+ VStack(alignment: .leading, spacing: 14) {+ Text("Question").font(.subheadline.weight(.semibold)).foregroundStyle(.cyan)+ ForEach(Array(payload.items.enumerated()), id: \.offset) { index, item in+ VStack(alignment: .leading, spacing: 8) {+ if !item.header.isEmpty {+ Text(item.header.uppercased())+ .font(.caption2.weight(.bold))+ .foregroundStyle(.secondary)+ }+ Text(item.question).font(.callout.weight(.semibold))+ if item.multiSelect {+ Text("Pick one or more").font(.caption).foregroundStyle(.secondary)+ }+ ForEach(item.options, id: \.label) { option in+ optionRow(option, item: item, index: index)+ }+ }+ }+ if sent {+ Label("Answer sent to your Mac", systemImage: "checkmark.circle.fill")+ .font(.callout.weight(.semibold))+ .foregroundStyle(.green)+ } else {+ Button {+ Task { await send() }+ } label: {+ Label("Send answer", systemImage: "paperplane.fill").frame(maxWidth: .infinity)+ }+ .buttonStyle(.borderedProminent)+ .tint(.cyan)+ .controlSize(.large)+ .disabled(!ready || sending)+ Text("Claude waits about 2 minutes, then asks in the terminal.")+ .font(.caption).foregroundStyle(.secondary)+ }+ if let error {+ Text(error).font(.caption).foregroundStyle(.red)+ }+ }+ .padding(16)+ .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))+ .overlay(RoundedRectangle(cornerRadius: 22).strokeBorder(Color.cyan.opacity(0.7), lineWidth: 1.5))+ .onAppear { reset() }+ .onChange(of: payload) { reset() }+ }++ private func optionRow(_ option: QuestionPayload.Option, item: QuestionPayload.Item, index: Int) -> some View {+ let selected = picks.indices.contains(index) && picks[index].contains(option.label)+ return Button {+ guard picks.indices.contains(index), !sent else { return }+ if item.multiSelect {+ if selected { picks[index].remove(option.label) } else { picks[index].insert(option.label) }+ } else {+ picks[index] = [option.label]+ }+ Haptics.impact()+ } label: {+ HStack(alignment: .top, spacing: 10) {+ Image(systemName: item.multiSelect+ ? (selected ? "checkmark.square.fill" : "square")+ : (selected ? "largecircle.fill.circle" : "circle"))+ .foregroundStyle(selected ? Color.cyan : Color.secondary)+ VStack(alignment: .leading, spacing: 2) {+ Text(option.label).font(.callout).foregroundStyle(.primary)+ if !option.description.isEmpty {+ Text(option.description).font(.caption).foregroundStyle(.secondary)+ }+ }+ Spacer(minLength: 0)+ }+ .padding(12)+ .background(selected ? Color.cyan.opacity(0.16) : Color(white: 0.16), in: RoundedRectangle(cornerRadius: 12))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ }++ private func reset() {+ picks = Array(repeating: [], count: payload.items.count)+ sent = false+ error = nil+ }++ private func send() async {+ sending = true+ defer { sending = false }+ error = nil+ // Keep the order of the choices, as Claude listed them.+ let selections = payload.items.enumerated().map { index, item in+ item.options.map(\.label).filter { picks[index].contains($0) }+ }+ if await link.answer(fingerprint: session.questionFingerprint, pillId: session.id, selections: selections) {+ sent = true+ Haptics.success()+ } else {+ error = link.lastPong ?? "Couldn't reach iCloud."+ Haptics.error()+ }+ }+}diff --git a/NotchBuddy/Sources/Phone/SessionDetailView.swift b/NotchBuddy/Sources/Phone/SessionDetailView.swiftindex f7e6ed51..577bb5de 100644--- a/NotchBuddy/Sources/Phone/SessionDetailView.swift+++ b/NotchBuddy/Sources/Phone/SessionDetailView.swift@@ -1,4 +1,5 @@import SwiftUI+import UIKit/// One session: what the agent is doing, its plan, and what it waits for.struct SessionDetailView: View {@@ -7,6 +8,8 @@ struct SessionDetailView: View {private var session: SessionItem? { link.sessions.first { $0.id == sessionId } }private var turn: TurnSnapshot? { link.turns[sessionId] }+ private var pastTurns: [TurnSnapshot] { link.archive.past[sessionId] ?? [] }+ @State private var shareImage: UIImage?var body: some View {ScrollView {@@ -15,9 +18,13 @@ struct SessionDetailView: View {header(session)if session.needsApproval {ApprovalCard(link: link, session: session)+ .transition(.phaseCard)+ } else if let payload = session.questionPayload, !session.questionFingerprint.isEmpty {+ QuestionCard(link: link, session: session, payload: payload)+ .transition(.phaseCard)} else if !session.question.isEmpty {waiting(title: "Question", text: session.question, monospaced: false, color: .cyan,- footnote: "Answer on your Mac for now.")+ footnote: "Answer on your Mac: this question can't be answered from the iPhone.")}if let turn {LastTurnView(turn: turn, working: session.isWorking)@@ -31,14 +38,19 @@ struct SessionDetailView: View {.textSelection(.enabled)}}+ if !pastTurns.isEmpty { earlierTurns }}.padding(16)+ // A new phase (working, question, waiting, done) slides in instead of jumping.+ .animation(.spring(duration: 0.5, bounce: 0.2),+ value: "\(session.state.rawValue)|\(session.statusText)|\(session.approvalFingerprint)|\(session.questionFingerprint)")} else if let turn {VStack(alignment: .leading, spacing: 16) {Text("This session ended on your Mac. Its last turn:").font(.subheadline).foregroundStyle(.secondary)LastTurnView(turn: turn, working: false)+ if !pastTurns.isEmpty { earlierTurns }}.padding(16)} else {@@ -58,6 +70,62 @@ struct SessionDetailView: View {.navigationTitle(session?.title ?? "Session").navigationBarTitleDisplayMode(.inline).refreshable { await link.refresh() }+ .toolbar {+ // The last turn as a picture, to show what Claude did.+ if let shareImage {+ ToolbarItem(placement: .topBarTrailing) {+ ShareLink(item: Image(uiImage: shareImage),+ preview: SharePreview(turn?.project ?? "Coucou", image: Image(uiImage: shareImage))) {+ Image(systemName: "square.and.arrow.up")+ }+ }+ }+ }+ .task(id: turn?.endedAt) {+ guard let turn, turn.endedAt != nil else { shareImage = nil; return }+ shareImage = TurnShareCard.render(turn: turn, color: session?.color ?? "#4A86E8")+ }+ }++ /// The turns before the latest one, as this iPhone saw them.+ private var earlierTurns: some View {+ card(title: "Earlier turns") {+ VStack(spacing: 0) {+ ForEach(Array(pastTurns.enumerated()), id: \.offset) { index, past in+ NavigationLink {+ ScrollView {+ LastTurnView(turn: past, working: false).padding(16)+ }+ .background(Color.black)+ .navigationTitle(past.startedAt.formatted(date: .abbreviated, time: .shortened))+ .navigationBarTitleDisplayMode(.inline)+ } label: {+ HStack(spacing: 10) {+ VStack(alignment: .leading, spacing: 2) {+ Text(past.headline)+ .font(.callout)+ .lineLimit(2)+ .multilineTextAlignment(.leading)+ Text(past.startedAt, format: .dateTime.hour().minute())+ .font(.caption2)+ .foregroundStyle(.tertiary)+ }+ Spacer(minLength: 6)+ if !past.files.isEmpty {+ Text("\(past.files.count) file\(past.files.count == 1 ? "" : "s")")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ Image(systemName: "chevron.right").font(.caption2).foregroundStyle(.tertiary)+ }+ .padding(.vertical, 8)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ if index < pastTurns.count - 1 { Divider() }+ }+ }+ }}private func header(_ session: SessionItem) -> some View {@@ -73,6 +141,7 @@ struct SessionDetailView: View {Text(session.statusText).font(.subheadline.weight(.semibold)).foregroundStyle(session.statusColor)+ .contentTransition(.interpolate)HStack(spacing: 4) {if !session.macName.isEmpty {Text(session.macName)@@ -153,3 +222,11 @@ struct SessionDetailView: View {.background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))}}++extension AnyTransition {+ /// A card that comes with a phase (an OK to give, a question): drops in from above.+ static var phaseCard: AnyTransition {+ .asymmetric(insertion: .move(edge: .top).combined(with: .opacity),+ removal: .scale(scale: 0.95).combined(with: .opacity))+ }+}diff --git a/NotchBuddy/Sources/Phone/TurnArchive.swift b/NotchBuddy/Sources/Phone/TurnArchive.swiftnew file mode 100644index 00000000..9e3413d8--- /dev/null+++ b/NotchBuddy/Sources/Phone/TurnArchive.swift@@ -0,0 +1,74 @@+import Foundation++/// The turns this iPhone saw before the latest one (4 per session), and+/// today's tally. Built from the Turn records as they come, kept in a file on+/// this iPhone only.+struct TurnArchive: Codable {+ var past: [String: [TurnSnapshot]] = [:]+ var today = DayTally()++ static let keptPerSession = 4++ /// Today: turns finished, files changed, lines added and removed.+ struct DayTally: Codable, Equatable {+ var day = Calendar.current.startOfDay(for: .now)+ var turns = 0+ var files = 0+ var added = 0+ var removed = 0+ /// "pillId|startedAt" of the turns counted, so none counts twice.+ var counted: [String] = []++ var isEmpty: Bool { turns == 0 }+ }++ /// A new version of a session's latest turn arrived.+ mutating func update(from old: TurnSnapshot?, to new: TurnSnapshot) {+ // A new turn started: the previous one joins the past turns.+ if let old, old.startedAt != new.startedAt, !(old.prompt.isEmpty && old.actions.isEmpty) {+ var list = past[old.pillId] ?? []+ list.removeAll { $0.startedAt == old.startedAt }+ list.insert(old, at: 0)+ past[old.pillId] = Array(list.prefix(Self.keptPerSession))+ }+ count(new)+ }++ /// Adds a finished turn to today's tally, once.+ mutating func count(_ turn: TurnSnapshot) {+ let startOfToday = Calendar.current.startOfDay(for: .now)+ if today.day != startOfToday { today = DayTally(day: startOfToday) }+ guard let ended = turn.endedAt, ended >= startOfToday else { return }+ let key = "\(turn.pillId)|\(turn.startedAt.timeIntervalSince1970)"+ guard !today.counted.contains(key) else { return }+ today.counted.append(key)+ today.turns += 1+ today.files += Set(turn.files.map(\.path)).count+ today.added += turn.files.reduce(0) { $0 + $1.added }+ today.removed += turn.files.reduce(0) { $0 + $1.removed }+ }++ /// Today's tally, or an empty one after midnight.+ var currentTally: DayTally {+ today.day == Calendar.current.startOfDay(for: .now) ? today : DayTally()+ }++ // MARK: File++ private static var fileURL: URL? {+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?+ .appendingPathComponent("turn-archive.json")+ }++ static func load() -> TurnArchive {+ guard let url = fileURL, let data = try? Data(contentsOf: url),+ let archive = try? JSONDecoder().decode(TurnArchive.self, from: data) else { return TurnArchive() }+ return archive+ }++ func save() {+ guard let url = Self.fileURL, let data = try? JSONEncoder().encode(self) else { return }+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try? data.write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])+ }+}diff --git a/NotchBuddy/Sources/Phone/TurnShare.swift b/NotchBuddy/Sources/Phone/TurnShare.swiftnew file mode 100644index 00000000..9d99fe6a--- /dev/null+++ b/NotchBuddy/Sources/Phone/TurnShare.swift@@ -0,0 +1,118 @@+import SwiftUI+import UIKit++extension TurnSnapshot {+ /// One line for a turn: what you asked, or what woke the agent up.+ var headline: String {+ if prompt.hasPrefix("<task-notification>") {+ if let start = prompt.range(of: "<summary>"), let end = prompt.range(of: "</summary>"),+ start.upperBound <= end.lowerBound {+ return String(prompt[start.upperBound..<end.lowerBound])+ }+ return "A background task finished"+ }+ let line = prompt.trimmingCharacters(in: .whitespacesAndNewlines)+ return line.isEmpty ? "Turn without a prompt" : line+ }+}++/// A finished turn as a picture: Mochi, what you asked, what changed, the+/// answer. Made on the iPhone when you tap Share; nothing is sent anywhere else.+struct TurnShareCard: View {+ let turn: TurnSnapshot+ let color: String++ private var added: Int { turn.files.reduce(0) { $0 + $1.added } }+ private var removed: Int { turn.files.reduce(0) { $0 + $1.removed } }++ var body: some View {+ VStack(alignment: .leading, spacing: 18) {+ HStack(spacing: 14) {+ MochiStill(state: .finished, bodyHex: color, showBadge: false)+ .padding(8)+ .frame(width: 64, height: 64)+ .background(Color.mochiTile(hex: color), in: RoundedRectangle(cornerRadius: 16))+ VStack(alignment: .leading, spacing: 2) {+ Text(turn.project.isEmpty ? "Claude Code" : turn.project)+ .font(.title3.weight(.bold))+ if let ended = turn.endedAt {+ Text("Done in \(Self.duration(ended.timeIntervalSince(turn.startedAt)))")+ .font(.subheadline)+ .foregroundStyle(.green)+ }+ }+ }+ Text(turn.headline)+ .font(.body)+ .lineLimit(4)+ .padding(14)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Color.accentColor.opacity(0.25), in: RoundedRectangle(cornerRadius: 16))+ HStack(spacing: 18) {+ stat("\(turn.actions.count)", "actions")+ stat("\(turn.files.count)", turn.files.count == 1 ? "file" : "files")+ if !turn.files.isEmpty {+ HStack(spacing: 8) {+ Text("+\(added)").foregroundStyle(.green)+ Text("−\(removed)").foregroundStyle(.red)+ }+ .font(.title3.monospacedDigit().weight(.semibold))+ }+ }+ if !turn.files.isEmpty {+ VStack(alignment: .leading, spacing: 4) {+ ForEach(Array(turn.files.prefix(5).enumerated()), id: \.offset) { _, file in+ HStack {+ Text(file.name).font(.callout.monospaced()).lineLimit(1)+ Spacer()+ Text("+\(file.added) −\(file.removed)")+ .font(.caption.monospacedDigit())+ .foregroundStyle(.secondary)+ }+ }+ if turn.files.count > 5 {+ Text("and \(turn.files.count - 5) more").font(.caption).foregroundStyle(.secondary)+ }+ }+ }+ if !turn.finalMessage.isEmpty {+ Text(turn.finalMessage)+ .font(.callout)+ .foregroundStyle(.white.opacity(0.85))+ .lineLimit(8)+ }+ HStack(spacing: 6) {+ Spacer()+ MochiStill(state: .idle, showBadge: false).frame(width: 18, height: 18)+ Text("Coucou").font(.footnote.weight(.semibold)).foregroundStyle(.secondary)+ }+ }+ .padding(24)+ .frame(width: 390)+ .foregroundStyle(.white)+ .background(Color(white: 0.07))+ .environment(\.colorScheme, .dark)+ }++ private func stat(_ value: String, _ label: String) -> some View {+ VStack(alignment: .leading, spacing: 0) {+ Text(value).font(.title3.monospacedDigit().weight(.semibold))+ Text(label).font(.caption).foregroundStyle(.secondary)+ }+ }++ static func duration(_ seconds: TimeInterval) -> String {+ let formatter = DateComponentsFormatter()+ formatter.allowedUnits = seconds >= 3600 ? [.hour, .minute] : [.minute, .second]+ formatter.unitsStyle = .abbreviated+ formatter.maximumUnitCount = 2+ return formatter.string(from: max(1, seconds)) ?? ""+ }++ @MainActor+ static func render(turn: TurnSnapshot, color: String) -> UIImage? {+ let renderer = ImageRenderer(content: TurnShareCard(turn: turn, color: color))+ renderer.scale = 3+ return renderer.uiImage+ }+}diff --git a/NotchBuddy/Sources/Widgets/CoucouControl.swift b/NotchBuddy/Sources/Widgets/CoucouControl.swiftnew file mode 100644index 00000000..5328155e--- /dev/null+++ b/NotchBuddy/Sources/Widgets/CoucouControl.swift@@ -0,0 +1,53 @@+import AppIntents+import SwiftUI+import WidgetKit++// A Control Center button: the agent that needs you most and what it does;+// a tap opens it in Coucou. The app reloads it with the widgets.++struct CoucouControl: ControlWidget {+ var body: some ControlWidgetConfiguration {+ StaticControlConfiguration(kind: "fr.louisraille.Coucou.lead", provider: LeadProvider()) { lead in+ ControlWidgetButton(action: OpenLeadMochiIntent()) {+ Label(lead.text, systemImage: lead.symbol)+ }+ }+ .displayName("Coucou")+ .description("Your agents at a glance. Opens the one that needs you.")+ }+}++struct LeadStatus: Sendable {+ let text: String+ let symbol: String++ static let quiet = LeadStatus(text: "All quiet", symbol: "moon.zzz.fill")++ init(text: String, symbol: String) {+ self.text = text+ self.symbol = symbol+ }++ init(_ session: SharedSession?) {+ guard let session, session.tone != .idle else { self = .quiet; return }+ text = "\(session.agent): \(session.statusText)"+ switch session.tone {+ case .waiting: symbol = "hand.raised.fill"+ case .question: symbol = "questionmark.bubble.fill"+ case .error: symbol = "exclamationmark.triangle.fill"+ case .working: symbol = "hammer.fill"+ case .done: symbol = "checkmark.circle.fill"+ case .warning: symbol = "exclamationmark.circle.fill"+ case .info: symbol = "bell.fill"+ case .idle: symbol = "moon.zzz.fill"+ }+ }+}++struct LeadProvider: ControlValueProvider {+ var previewValue: LeadStatus { LeadStatus(text: "VS Code: waiting for your OK", symbol: "hand.raised.fill") }++ func currentValue() async throws -> LeadStatus {+ LeadStatus(SharedSessions.load().first)+ }+}diff --git a/NotchBuddy/Sources/Widgets/CoucouWidgets.swift b/NotchBuddy/Sources/Widgets/CoucouWidgets.swiftindex abc54530..4491b2da 100644--- a/NotchBuddy/Sources/Widgets/CoucouWidgets.swift+++ b/NotchBuddy/Sources/Widgets/CoucouWidgets.swift@@ -13,6 +13,7 @@ struct CoucouWidgetBundle: WidgetBundle {ListWidget()LockScreenWidget()MochiLiveActivity()+ CoucouControl()}}@@ -129,8 +130,12 @@ struct SoloView: View {var body: some View {VStack(alignment: .leading, spacing: 4) {- WidgetMochi(state: session?.botState ?? .sleeping)- .frame(width: 56, height: 56)+ ZStack {+ WidgetMochi(state: session?.botState ?? .sleeping)+ .id(session?.state ?? "sleeping")+ .transition(.mochiSwap)+ }+ .frame(width: 56, height: 56)Spacer(minLength: 0)if let session {Text(session.title)@@ -141,7 +146,9 @@ struct SoloView: View {.lineLimit(2).opacity(0.85)HStack(spacing: 4) {- Text(session.statusText).foregroundStyle(session.toneColor)+ Text(session.statusText)+ .foregroundStyle(session.toneColor)+ .contentTransition(.interpolate)Text("·")Text(session.updatedAt, style: .relative)}@@ -227,9 +234,13 @@ struct TeamTile: View {var body: some View {VStack(spacing: 0) {// In his own color, like the little Mochi in the Mac's notch.- WidgetMochi(state: session.botState, bodyHex: session.color, pose: pose)- .padding(.horizontal, 4)- .padding(.top, 2)+ ZStack {+ WidgetMochi(state: session.botState, bodyHex: session.color, pose: pose)+ .id(session.state)+ .transition(.mochiSwap)+ }+ .padding(.horizontal, 4)+ .padding(.top, 2)Text(session.agent).font(.system(size: 9, weight: .semibold)).foregroundStyle(.white.opacity(0.85))@@ -304,6 +315,7 @@ struct ListView: View {.font(.caption.weight(session.isWaitingForYou ? .semibold : .regular)).foregroundStyle(session.toneColor).lineLimit(1)+ .contentTransition(.interpolate)}}Spacer(minLength: 0)@@ -317,29 +329,46 @@ struct LockScreenView: View {@Environment(\.widgetFamily) private var familylet sessions: [SharedSession]+ /// Steps done of the lead session while it works, for the ring and the bar.+ private var progress: Double? {+ guard let lead = sessions.first, lead.isWorking, lead.stepCount > 0 else { return nil }+ return Double(min(lead.stepIndex + 1, lead.stepCount)) / Double(lead.stepCount)+ }+var body: some View {switch family {case .accessoryCircular:+ // The Lock Screen keeps only brightness: Mochi drawn like in the+ // tinted Home Screen, so his face shows.ZStack {AccessoryWidgetBackground()- MochiStill(state: sessions.leadState).padding(6)+ if let progress {+ Gauge(value: progress) { EmptyView() }+ .gaugeStyle(.accessoryCircularCapacity)+ }+ WidgetMochi(state: sessions.leadState, showBadge: false).padding(progress == nil ? 7 : 10)}+ .widgetURL(sessions.first.map { SharedSession.url(for: $0.id) }).containerBackground(for: .widget) { Color.clear }case .accessoryRectangular:HStack(spacing: 6) {- MochiStill(state: sessions.leadState).frame(width: 30, height: 30)- VStack(alignment: .leading, spacing: 0) {+ WidgetMochi(state: sessions.leadState, showBadge: false).frame(width: 32, height: 32)+ VStack(alignment: .leading, spacing: 1) {Text(sessions.summary ?? "All quiet").font(.headline).lineLimit(1)if let lead = sessions.first {Text("\(lead.title) · \(lead.statusText)").font(.caption)- .lineLimit(2)+ .lineLimit(progress == nil ? 2 : 1)+ }+ if let progress {+ ProgressView(value: progress).tint(.white)}}Spacer(minLength: 0)}+ .widgetURL(sessions.first.map { SharedSession.url(for: $0.id) }).containerBackground(for: .widget) { Color.clear }default:Text(sessions.summary.map { "Coucou · \($0)" } ?? "Coucou · all quiet")@@ -379,8 +408,8 @@ extension SharedSession {/// Mochi in a widget. In the tinted (and clear) Home Screen styles iOS keeps/// only each pixel's opacity, so a white Mochi with black eyes turns into a-/// blank shape. There he is drawn by brightness instead: the body shows, the-/// eyes become holes, and you can see his face again.+/// blank shape; on the Lock Screen it keeps only brightness. There he is drawn+/// as a white shape with his eyes cut out, which reads in both.struct WidgetMochi: View {@Environment(\.widgetRenderingMode) private var renderingModevar state: BotState = .idle@@ -392,8 +421,14 @@ struct WidgetMochi: View {if renderingMode == .fullColor {MochiStill(state: state, bodyHex: bodyHex, showBadge: showBadge, pose: pose)} else {- MochiStill(state: state, bodyHex: "#FFFFFF", showBadge: showBadge, pose: pose)- .luminanceToAlpha()+ // White where Mochi is bright, see-through where he is dark (his+ // eyes). The Lock Screen shows brightness, so the mask is filled+ // with white rather than left black.+ Color.white+ .mask {+ MochiStill(state: state, bodyHex: "#FFFFFF", showBadge: showBadge, pose: pose)+ .luminanceToAlpha()+ }.widgetAccentable()}}diff --git a/NotchBuddy/Sources/Widgets/MochiLiveActivity.swift b/NotchBuddy/Sources/Widgets/MochiLiveActivity.swiftindex e3ceeefb..36bd368b 100644--- a/NotchBuddy/Sources/Widgets/MochiLiveActivity.swift+++ b/NotchBuddy/Sources/Widgets/MochiLiveActivity.swift@@ -15,7 +15,7 @@ struct MochiLiveActivity: Widget {let state = context.statereturn DynamicIsland {DynamicIslandExpandedRegion(.leading) {- MochiStill(state: state.botState)+ MochiSwap(state: state).frame(width: 44, height: 44).padding(.leading, 4)}@@ -28,8 +28,10 @@ struct MochiLiveActivity: Widget {.font(.subheadline.weight(.semibold)).foregroundStyle(state.toneColor).lineLimit(1)+ .contentTransition(.interpolate)}.frame(maxWidth: .infinity, alignment: .leading)+ .animation(.phaseChange, value: state)}DynamicIslandExpandedRegion(.trailing) {if state.others > 0 {@@ -40,29 +42,38 @@ struct MochiLiveActivity: Widget {}}DynamicIslandExpandedRegion(.bottom) {- HStack(spacing: 10) {- if state.stepCount > 0 {- StepsBar(index: state.stepIndex, count: state.stepCount, color: state.toneColor)- }- if let since = state.sinceDate, state.isActive {- Text(since, style: .timer)- .font(.caption.monospacedDigit())- .foregroundStyle(.secondary)- .frame(width: 52, alignment: .trailing)+ if let fingerprint = state.approval, state.tone == "waiting" {+ ApprovalButtons(fingerprint: fingerprint, pillId: state.pillId)+ .padding(.horizontal, 4)+ .transition(.phaseIn)+ } else {+ HStack(spacing: 10) {+ if state.stepCount > 0 {+ StepsBar(index: state.stepIndex, count: state.stepCount, color: state.toneColor)+ }+ if let since = state.sinceDate, state.isActive {+ Text(since, style: .timer)+ .font(.caption.monospacedDigit())+ .foregroundStyle(.secondary)+ .frame(width: 52, alignment: .trailing)+ }}+ .padding(.horizontal, 4)+ .transition(.phaseIn)}- .padding(.horizontal, 4)}} compactLeading: {- MochiStill(state: state.botState)+ MochiSwap(state: state).frame(width: 24, height: 24)} compactTrailing: {Text(state.compactText).font(.caption.weight(.semibold)).foregroundStyle(state.toneColor).monospacedDigit()+ .contentTransition(.numericText())+ .animation(.phaseChange, value: state.compactText)} minimal: {- MochiStill(state: state.botState)+ MochiSwap(state: state).frame(width: 22, height: 22)}.keylineTint(state.toneColor)@@ -76,7 +87,7 @@ struct LockScreenActivityView: View {var body: some View {HStack(spacing: 14) {- MochiStill(state: state.botState)+ MochiSwap(state: state).padding(6).frame(width: 52, height: 52).background(Color.mochiTile(hex: state.color), in: RoundedRectangle(cornerRadius: 14))@@ -91,6 +102,9 @@ struct LockScreenActivityView: View {Text(stale ? "Your Mac went quiet" : state.statusText).font(.subheadline.weight(.semibold)).foregroundStyle(stale ? Color.secondary : state.toneColor)+ .lineLimit(1)+ .minimumScaleFactor(0.8)+ .contentTransition(.interpolate)// Counts up live, without any push.if let since = state.sinceDate, state.isActive, !stale {Text("·").foregroundStyle(.secondary)@@ -99,14 +113,82 @@ struct LockScreenActivityView: View {.foregroundStyle(.secondary)}}- if state.stepCount > 0 && !stale {+ if let fingerprint = state.approval, state.tone == "waiting", !stale {+ ApprovalButtons(fingerprint: fingerprint, pillId: state.pillId)+ .padding(.top, 4)+ .transition(.phaseIn)+ } else if state.stepCount > 0 && !stale {StepsBar(index: state.stepIndex, count: state.stepCount, color: state.toneColor)+ .transition(.phaseIn)}}Spacer(minLength: 0)}.foregroundStyle(.white).padding(16)+ // Every change of phase (working, question, waiting, done) moves+ // smoothly instead of jumping.+ .animation(.phaseChange, value: state)+ .animation(.phaseChange, value: stale)+ }+}++/// Mochi with a little pop when his state changes: the old face fades, the+/// new one grows in.+struct MochiSwap: View {+ let state: MochiActivityState++ var body: some View {+ ZStack {+ MochiStill(state: state.botState)+ .id(state.state)+ .transition(.mochiSwap)+ }+ .animation(.phaseChange, value: state.state)+ }+}++extension Animation {+ /// Mochi's phase changes: a soft spring, inside the 2 s iOS allows.+ static var phaseChange: Animation { .spring(duration: 0.6, bounce: 0.3) }+}++extension AnyTransition {+ /// The old face fades out a little bigger, the new one grows in.+ static var mochiSwap: AnyTransition {+ .asymmetric(insertion: .scale(scale: 0.55).combined(with: .opacity),+ removal: .scale(scale: 1.15).combined(with: .opacity))+ }++ /// What appears with a new phase (buttons, steps): slides up and fades in.+ static var phaseIn: AnyTransition {+ .asymmetric(insertion: .move(edge: .bottom).combined(with: .opacity), removal: .opacity)+ }+}++/// Deny answers right away; Allow opens Coucou on the command, where Face ID+/// confirms before anything is sent.+struct ApprovalButtons: View {+ let fingerprint: String+ let pillId: String++ var body: some View {+ HStack(spacing: 8) {+ Button(intent: DenyApprovalIntent(fingerprint: fingerprint, pillId: pillId)) {+ Label("Deny", systemImage: "xmark")+ .font(.subheadline.weight(.semibold))+ .frame(maxWidth: .infinity)+ }+ .buttonStyle(.bordered)+ .tint(.red)+ Button(intent: AllowApprovalIntent(fingerprint: fingerprint, pillId: pillId)) {+ Label("Allow", systemImage: "faceid")+ .font(.subheadline.weight(.semibold))+ .frame(maxWidth: .infinity)+ }+ .buttonStyle(.borderedProminent)+ .tint(.green)+ }}}diff --git a/NotchBuddy/project.yml b/NotchBuddy/project.ymlindex 9be7314e..586f5909 100644--- a/NotchBuddy/project.yml+++ b/NotchBuddy/project.yml@@ -228,6 +228,15 @@ targets:type: group- path: PhoneAssets.xcassetsbuildPhase: resources+ # Mochi's sounds for the iPhone's notifications.+ - path: Resources/sounds/approval.wav+ buildPhase: resources+ - path: Resources/sounds/finish.wav+ buildPhase: resources+ - path: Resources/sounds/question.wav+ buildPhase: resources+ - path: Resources/sounds/error.wav+ buildPhase: resourcesinfo:path: Resources/InfoPhone.plistproperties:@@ -242,8 +251,11 @@ targets:UIApplicationSupportsIndirectInputEvents: YESUIBackgroundModes:- remote-notification+ # Portrait, except a diff opened full screen (PhoneAppDelegate decides).UISupportedInterfaceOrientations:- UIInterfaceOrientationPortrait+ - UIInterfaceOrientationLandscapeLeft+ - UIInterfaceOrientationLandscapeRightITSAppUsesNonExemptEncryption: NONSFaceIDUsageDescription: "Coucou asks for Face ID before allowing a command from your iPhone."NSMicrophoneUsageDescription: "Coucou uses the microphone when you dictate an instruction for Claude Code."@@ -295,6 +307,8 @@ targets:- path: Sources/Phone/SharedSessions.swift- path: Sources/Phone/MacStubs.swift- path: Sources/Phone/MochiActivityAttributes.swift+ - path: Sources/Phone/OpenLeadMochiIntent.swift+ - path: Sources/Phone/DenyApprovalIntent.swiftinfo:path: Resources/InfoWidgets.plistproperties:@@ -309,6 +323,7 @@ targets:settings:base:PRODUCT_BUNDLE_IDENTIFIER: fr.louisraille.Coucou.Widgets+ SWIFT_ACTIVE_COMPILATION_CONDITIONS: "$(inherited) WIDGET_EXTENSION"PRODUCT_NAME: CoucouWidgetsINFOPLIST_FILE: Resources/InfoWidgets.plistIPHONEOS_DEPLOYMENT_TARGET: "18.0"diff --git a/docs/privacy.html b/docs/privacy.htmlindex 6c5a4769..d3ab2ea4 100644--- a/docs/privacy.html+++ b/docs/privacy.html@@ -49,8 +49,9 @@<p>Depending on the version and the features you use, macOS may ask you to allow Automation (Mail, Terminal, Music), Accessibility (to read the title of the window you attach) or Screen Recording (to capture a window you attach). These are only used for the feature you triggered and can be revoked at any time in System Settings → Privacy & Security. The Windows and Linux versions ask for no special permission. On Linux, installing the .deb or .rpm package needs administrator rights; the AppImage doesn't.</p><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 (Face ID is required to allow), 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>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>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>@@ -110,8 +111,9 @@<p>Selon la version et les fonctions utilisées, macOS peut te demander d’autoriser l’Automatisation (Mail, Terminal), l’Accessibilité (lire le titre de la fenêtre que tu attaches) ou l’Enregistrement de l’écran (capturer une fenêtre que tu attaches). Elles ne servent qu’à la fonction que tu as déclenchée et se retirent à tout moment dans Réglages Système → Confidentialité et sécurité. Les versions Windows et Linux ne demandent aucune autorisation particulière. Sous Linux, l’installation du paquet .deb ou .rpm nécessite des droits administrateur ; l’AppImage non.</p><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 (Face ID est demandé pour autoriser), 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>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>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/README.md b/relay/README.mdindex 3c5e8a38..c18fdb6f 100644--- a/relay/README.md+++ b/relay/README.md@@ -8,8 +8,10 @@ key can't ship inside the Mac app. The Mac posts Mochi's state here; the relaysigns and forwards it to Apple.What it sees: the push token of the iPhone's Live Activity and Mochi's state-(agent name, state, "working · 3/7", counts). Never a project name, a command,-a path or a message. It stores nothing and logs nothing.+(agent name, state, "working · 3/7", counts), plus, while a command waits for+your OK, its fingerprint (a SHA-256 hash, so the Lock Screen's Allow and Deny+answer that exact command). Never a project name, a command, a path or a+message. It stores nothing and logs nothing.## Deploy (once)diff --git a/relay/src/index.ts b/relay/src/index.tsindex ed403eda..506c7570 100644--- a/relay/src/index.ts+++ b/relay/src/index.ts@@ -93,6 +93,9 @@ function validate(body: RelayRequest): string | null {const since = body.state["since"];if (since !== undefined && since !== null &&(typeof since !== "number" || !Number.isInteger(since) || since < 1_600_000_000 || since > 4_000_000_000)) return "state.since";+ const approval = body.state["approval"];+ if (approval !== undefined && approval !== null &&+ (typeof approval !== "string" || !/^[0-9a-f]{64}$/.test(approval))) return "state.approval";if (body.dismissAfter !== undefined &&(typeof body.dismissAfter !== "number" || !Number.isInteger(body.dismissAfter) ||body.dismissAfter < 0 || body.dismissAfter > 4 * 3600)) return "dismissAfter";@@ -106,6 +109,8 @@ function buildPayload(body: RelayRequest) {for (const key of [...STATE_STRINGS, ...STATE_NUMBERS]) state[key] = body.state[key];// When Mochi left for the iPhone: the activity counts the time from it.if (typeof body.state["since"] === "number") state["since"] = body.state["since"];+ // The pending command's fingerprint (a hash), for Allow / Deny on the Lock Screen.+ if (typeof body.state["approval"] === "string") state["approval"] = body.state["approval"];const aps: Record<string, unknown> = {timestamp: now,