Skip to content

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.

iPhone: all the Mochi, services, last turn with diffs, instructions from the iPhone (#224)

Louis7314790a814d
diff --git a/NotchBuddy/Resources/InfoPhone.plist b/NotchBuddy/Resources/InfoPhone.plist
index bd3eef79..f376414a 100644
--- a/NotchBuddy/Resources/InfoPhone.plist
+++ b/NotchBuddy/Resources/InfoPhone.plist
@@ -18,6 +18,17 @@
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
+ <key>CFBundleURLTypes</key>
+ <array>
+ <dict>
+ <key>CFBundleURLName</key>
+ <string>fr.louisraille.Coucou</string>
+ <key>CFBundleURLSchemes</key>
+ <array>
+ <string>coucou</string>
+ </array>
+ </dict>
+ </array>
<key>CFBundleVersion</key>
<string>2</string>
<key>CoucouAPNsEnvironment</key>
@@ -28,6 +39,10 @@
<true/>
<key>NSFaceIDUsageDescription</key>
<string>Coucou asks for Face ID before allowing a command from your iPhone.</string>
+ <key>NSMicrophoneUsageDescription</key>
+ <string>Coucou uses the microphone when you dictate an instruction for Claude Code.</string>
+ <key>NSSpeechRecognitionUsageDescription</key>
+ <string>Coucou turns your voice into the text of an instruction for Claude Code.</string>
<key>NSSupportsLiveActivities</key>
<true/>
<key>UIApplicationSupportsIndirectInputEvents</key>
diff --git a/NotchBuddy/Sources/App/AppState.swift b/NotchBuddy/Sources/App/AppState.swift
index d851b21d..4a1047e9 100644
--- a/NotchBuddy/Sources/App/AppState.swift
+++ b/NotchBuddy/Sources/App/AppState.swift
@@ -318,6 +318,9 @@ final class AppState: ObservableObject {
@Published var notionLoaded: Bool = false
@Published var notionError: String? = nil
+ // n8n — the last executions, newest first (for the iPhone; the notch shows only the latest)
+ @Published var n8nRuns: [N8nRun] = []
+
// Chat conversation history
@Published var chatHistory: [ChatMessage] = []
@@ -738,6 +741,13 @@ struct CalcomBooking: Identifiable, Equatable {
// MARK: - Notion
+struct N8nRun: Equatable {
+ let workflow: String
+ let detail: String?
+ let success: Bool
+ let date: Date
+}
+
struct NotionPage: Identifiable {
let id: String
let title: String
diff --git a/NotchBuddy/Sources/App/GithubPoller.swift b/NotchBuddy/Sources/App/GithubPoller.swift
index 538ac2e1..4cfb81d1 100644
--- a/NotchBuddy/Sources/App/GithubPoller.swift
+++ b/NotchBuddy/Sources/App/GithubPoller.swift
@@ -29,6 +29,18 @@ final class GithubPoller: @unchecked Sendable {
}
}
+ /// Pull requests, CI and activity are fetched when the GitHub pill is in
+ /// the notch, or when the iPhone sync is on (the iPhone shows GitHub even
+ /// when its pill isn't in the notch).
+ @MainActor private static var isWanted: Bool {
+ if AppState.shared.activeIntegrations.contains("integration_github") { return true }
+ #if PHONE_LINK
+ return UserDefaults.standard.bool(forKey: "iPhoneSyncEnabled")
+ #else
+ return false
+ #endif
+ }
+
// MARK: - Stats (unchanged logic)
private func pollStats() {
@@ -81,7 +93,7 @@ final class GithubPoller: @unchecked Sendable {
DispatchQueue.main.async { [weak self] in
guard let self, !self.pulseInFlight else { return }
guard let token = KeychainStore.shared.get("github-token"),
- AppState.shared.activeIntegrations.contains("integration_github") else {
+ Self.isWanted else {
self.scheduleNextPulse(hasPending: false)
return
}
@@ -131,7 +143,11 @@ final class GithubPoller: @unchecked Sendable {
let old = AppState.shared.githubPulse
let events = GitHubPulse.events(old: old, new: pulse)
AppState.shared.githubPulse = pulse
- AppState.shared.handleGitHubEvents(events)
+ // Badge and sound only for the pill in the notch, not when the
+ // fetch only feeds the iPhone.
+ if AppState.shared.activeIntegrations.contains("integration_github") {
+ AppState.shared.handleGitHubEvents(events)
+ }
}
self.finishPulse(hasPending: pulse.hasPending)
}.resume()
@@ -194,7 +210,7 @@ final class GithubPoller: @unchecked Sendable {
DispatchQueue.main.async { [weak self] in
guard let self, !self.activityInFlight else { return }
guard let token = KeychainStore.shared.get("github-token"),
- AppState.shared.activeIntegrations.contains("integration_github") else {
+ Self.isWanted else {
self.scheduleNextActivity()
return
}
diff --git a/NotchBuddy/Sources/App/HookServer.swift b/NotchBuddy/Sources/App/HookServer.swift
index ca734bfd..26dde14c 100644
--- a/NotchBuddy/Sources/App/HookServer.swift
+++ b/NotchBuddy/Sources/App/HookServer.swift
@@ -377,6 +377,11 @@ final class HookServer: @unchecked Sendable {
let focused = state.focusId == agentId
+ #if PHONE_LINK
+ // The iPhone's "last turn" (prompt, actions, diffs, answer).
+ if !isExternalAgent { TurnRecorder.shared.record(event: name, payload: payload, pillId: agentId) }
+ #endif
+
// While a permission request is pending, dismiss when the resolving event arrives,
// then continue normal processing. Only skip normal processing when unresolved.
if let pending = state.pendingApproval, agentId == pending.pillId {
diff --git a/NotchBuddy/Sources/App/N8nPoller.swift b/NotchBuddy/Sources/App/N8nPoller.swift
index 8a1850a1..3ce76e4c 100644
--- a/NotchBuddy/Sources/App/N8nPoller.swift
+++ b/NotchBuddy/Sources/App/N8nPoller.swift
@@ -227,6 +227,9 @@ final class N8nPoller: @unchecked Sendable {
// Apply workflow filter (empty = all workflows)
if !state.n8nWorkflowFilter.isEmpty && !state.n8nWorkflowFilter.contains(name) { return }
+ state.n8nRuns = Array(([N8nRun(workflow: name, detail: detail, success: success, date: Date())]
+ + state.n8nRuns).prefix(10))
+
guard let idx = state.tasks.firstIndex(where: { $0.id == "integration_n8n" }) else { return }
let focused = state.focusId == "integration_n8n"
diff --git a/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift b/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift
index 1c6dd002..3ac27f18 100644
--- a/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift
+++ b/NotchBuddy/Sources/App/PhoneLink/CloudProbe.swift
@@ -71,6 +71,11 @@ final class CloudProbe {
NSApplication.shared.unregisterForRemoteNotifications()
SessionPublisher.shared.stop()
ApprovalRelay.shared.stop()
+ ServicePublisher.shared.stop()
+ TurnRecorder.shared.stop()
+ #if !APPSTORE
+ InstructionRunner.shared.stop()
+ #endif
LiveActivityRelay.shared.stop()
log("iPhone sync off")
}
@@ -87,6 +92,11 @@ final class CloudProbe {
NSApplication.shared.registerForRemoteNotifications()
SessionPublisher.shared.start()
ApprovalRelay.shared.start()
+ ServicePublisher.shared.start()
+ TurnRecorder.shared.start()
+ #if !APPSTORE
+ InstructionRunner.shared.startIfEnabled()
+ #endif
LiveActivityRelay.shared.startIfEnabled()
// Step 1 Ping/Pong test: off unless asked for, so the Mac stays idle at rest
diff --git a/NotchBuddy/Sources/App/PhoneLink/InstructionRunner.swift b/NotchBuddy/Sources/App/PhoneLink/InstructionRunner.swift
new file mode 100644
index 00000000..b7aa07df
--- /dev/null
+++ b/NotchBuddy/Sources/App/PhoneLink/InstructionRunner.swift
@@ -0,0 +1,182 @@
+#if PHONE_LINK && !APPSTORE
+import AppKit
+import CloudKit
+
+// MARK: - Instructions from the iPhone
+//
+// The iPhone writes an `Instruction` record (text encrypted) for a session.
+// When the user turned it on (Settings → General → iPhone, off by default),
+// this Mac checks every 15 s, takes each instruction once (the record is
+// deleted on read), and continues that same Claude Code conversation in the
+// background: `claude -p <text> --resume <session id>`, in the session's own
+// folder. The folder and the session come from what this Mac saw in the
+// hooks, never from the iPhone. Hooks keep working, so the notch, the iPhone
+// and the permission requests (approved by hand, with Face ID on the phone)
+// follow the run like any other turn.
+// GitHub build only: the App Store build is sandboxed and can't start `claude`.
+
+@MainActor
+final class InstructionRunner {
+ static let shared = InstructionRunner()
+
+ nonisolated static let enabledKey = "iPhoneInstructionsEnabled"
+ nonisolated static var isEnabled: Bool { UserDefaults.standard.bool(forKey: enabledKey) }
+
+ private var database: CKDatabase { CKContainer(identifier: CloudProbe.containerID).privateCloudDatabase }
+ private var pollTask: Task<Void, Never>?
+ private var changeToken: CKServerChangeToken?
+ private var running: [String: Process] = [:] // by session id
+
+ /// Instructions older than this are dropped instead of run.
+ private let maxAge: TimeInterval = 10 * 60
+
+ func setEnabled(_ on: Bool) {
+ UserDefaults.standard.set(on, forKey: Self.enabledKey)
+ if on && CloudProbe.isEnabled { start() } else { stop() }
+ }
+
+ func startIfEnabled() {
+ if Self.isEnabled { start() }
+ }
+
+ func start() {
+ guard pollTask == nil else { return }
+ log("on: checking for instructions every 15 s")
+ pollTask = Task { [weak self] in
+ while !Task.isCancelled {
+ await self?.check()
+ try? await Task.sleep(for: .seconds(15))
+ }
+ }
+ }
+
+ func stop() {
+ guard pollTask != nil else { return }
+ pollTask?.cancel()
+ pollTask = nil
+ log("off")
+ }
+
+ // MARK: Reading
+
+ private func check() async {
+ var found: [CKRecord] = []
+ do {
+ var more = true
+ while more {
+ let changes = try await database.recordZoneChanges(inZoneWith: SessionSnapshot.zoneID, since: changeToken)
+ for (_, result) in changes.modificationResultsByID {
+ if case .success(let mod) = result, mod.record.recordType == "Instruction" { found.append(mod.record) }
+ }
+ changeToken = changes.changeToken
+ more = changes.moreComing
+ }
+ } catch let error as CKError where error.code == .changeTokenExpired {
+ changeToken = nil
+ return
+ } catch {
+ return
+ }
+ guard !found.isEmpty else { return }
+ // Single use: gone from iCloud before anything runs.
+ _ = try? await database.modifyRecords(saving: [], deleting: found.map(\.recordID))
+ for record in found.sorted(by: { ($0["createdAt"] as? Date ?? .distantPast) < ($1["createdAt"] as? Date ?? .distantPast) }) {
+ handle(record)
+ }
+ }
+
+ private func handle(_ record: CKRecord) {
+ let pillId = record["pillId"] as? String ?? ""
+ let createdAt = record["createdAt"] as? Date ?? .distantPast
+ let text = (record.encryptedValues["text"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ guard Self.isEnabled else { log("ignored: instructions are off"); return }
+ guard Date().timeIntervalSince(createdAt) < maxAge else { log("ignored: older than 10 min"); return }
+ guard !text.isEmpty, text.count <= 8000 else { log("ignored: empty or too long"); return }
+ guard pillId == "integration_claude" || pillId == "agent_cursor" else { log("ignored: \(pillId) can't take instructions"); return }
+ guard let session = TurnRecorder.shared.lastSession(for: pillId) else {
+ log("ignored: no Claude Code session seen for \(pillId) yet")
+ return
+ }
+ var isDirectory: ObjCBool = false
+ guard FileManager.default.fileExists(atPath: session.cwd, isDirectory: &isDirectory), isDirectory.boolValue else {
+ log("ignored: the session's folder is gone")
+ return
+ }
+ guard running[session.sessionId] == nil else {
+ log("ignored: an instruction is already running for this session")
+ return
+ }
+ guard let claude = Self.claudeExecutable() else {
+ log("can't find the claude command (looked in ~/.claude/local, Homebrew, /usr/local/bin, ~/.npm-global/bin)")
+ return
+ }
+ run(claude: claude, text: text, sessionId: session.sessionId, cwd: session.cwd, pillId: pillId)
+ }
+
+ // MARK: Running
+
+ private func run(claude: String, text: String, sessionId: String, cwd: String, pillId: String) {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: claude)
+ process.arguments = ["-p", text, "--resume", sessionId]
+ process.currentDirectoryURL = URL(fileURLWithPath: cwd)
+ var env = ProcessInfo.processInfo.environment
+ let home = FileManager.default.homeDirectoryForCurrentUser.path
+ env["PATH"] = [URL(fileURLWithPath: claude).deletingLastPathComponent().path, "/opt/homebrew/bin", "/usr/local/bin",
+ "/usr/bin", "/bin", "/usr/sbin", "/sbin", "\(home)/.local/bin", env["PATH"] ?? ""].joined(separator: ":")
+ // The hooks route events by editor: keep them on the same pill.
+ if pillId == "agent_cursor" {
+ env["__CFBundleIdentifier"] = "com.todesktop.230313mzl4w4u92"
+ } else {
+ env["TERM_PROGRAM"] = "vscode"
+ }
+ process.environment = env
+ process.standardInput = FileHandle.nullDevice
+ // Output goes to a file (a pipe could fill up and stall claude); its
+ // end is logged if the run fails.
+ let logURL = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/Logs/NotchBuddy/instruction-last.log")
+ try? FileManager.default.createDirectory(at: logURL.deletingLastPathComponent(), withIntermediateDirectories: true)
+ FileManager.default.createFile(atPath: logURL.path, contents: nil)
+ let output = try? FileHandle(forWritingTo: logURL)
+ process.standardOutput = output ?? FileHandle.nullDevice
+ process.standardError = output ?? FileHandle.nullDevice
+ process.terminationHandler = { [weak self] finished in
+ try? output?.close()
+ let data = (try? Data(contentsOf: logURL)) ?? Data()
+ let tail = String(decoding: data.suffix(400), as: UTF8.self)
+ .replacingOccurrences(of: "\n", with: " ")
+ let status = finished.terminationStatus
+ Task { @MainActor in
+ self?.running[sessionId] = nil
+ self?.log(status == 0 ? "finished (\(sessionId.prefix(8)))" : "ended with \(status): \(tail)")
+ }
+ }
+ do {
+ try process.run()
+ running[sessionId] = process
+ log("running in \(URL(fileURLWithPath: cwd).lastPathComponent) (\(sessionId.prefix(8))): \(text.count) chars")
+ } catch {
+ log("couldn't start claude: \(error.localizedDescription)")
+ }
+ }
+
+ /// Where `claude` usually lives; the app doesn't get the shell's PATH.
+ static func claudeExecutable() -> String? {
+ let home = FileManager.default.homeDirectoryForCurrentUser.path
+ let candidates = [
+ "\(home)/.claude/local/claude",
+ "\(home)/.local/bin/claude",
+ "/opt/homebrew/bin/claude",
+ "/usr/local/bin/claude",
+ "\(home)/.npm-global/bin/claude",
+ "\(home)/.bun/bin/claude",
+ ]
+ return candidates.first { FileManager.default.isExecutableFile(atPath: $0) }
+ }
+
+ private func log(_ message: String) {
+ CloudProbe.shared.log("[instruction] \(message)")
+ }
+}
+#endif
diff --git a/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swift b/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swift
index 65c15558..0c8a8162 100644
--- a/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swift
+++ b/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swift
@@ -319,7 +319,7 @@ final class LiveActivityRelay {
/// The most urgent session, as the iPhone's Live Activity shows it.
nonisolated static func leadState(tasks: [AgentTask], approval: ApprovalInfo?) -> MochiActivityState? {
let ranked = tasks
- .filter { $0.source != .n8n } // same sessions as SessionPublisher
+ .filter { $0.source != .n8n && PillCatalog.isSession($0.id) } // same sessions as SessionPublisher
.map { task -> (AgentTask, Int) in
let urgency = MochiActivityState.urgency(state: task.state,
waitingForOK: approval?.pillId == task.id,
diff --git a/NotchBuddy/Sources/App/PhoneLink/ServicePublisher.swift b/NotchBuddy/Sources/App/PhoneLink/ServicePublisher.swift
new file mode 100644
index 00000000..7bb6ab9d
--- /dev/null
+++ b/NotchBuddy/Sources/App/PhoneLink/ServicePublisher.swift
@@ -0,0 +1,395 @@
+#if PHONE_LINK
+import AppKit
+import CloudKit
+import Combine
+
+// MARK: - Services on the iPhone
+//
+// One `Service` record per service Mochi (GitHub, Stripe, Vercel, Resend,
+// Cal.com, n8n, Notion), built from the data the Mac's pollers already keep in
+// AppState: no extra API call, no key sent anywhere. The whole snapshot
+// (amounts, titles, emails, links) is one field encrypted with the user's
+// iCloud keys; only the pill ID, the state dot and the date are in clear.
+// Driven by AppState changes (debounced), never by a timer.
+
+@MainActor
+final class ServicePublisher {
+ static let shared = ServicePublisher()
+
+ private let container = CKContainer(identifier: CloudProbe.containerID)
+ private var database: CKDatabase { container.privateCloudDatabase }
+ private var cancellable: AnyCancellable?
+ private var published: [String: ServiceSnapshot] = [:]
+ private var cleanedUp = false
+ private var writing = false
+ private var again = false
+
+ func start() {
+ guard cancellable == nil else { return }
+ let s = AppState.shared
+ let changes: [AnyPublisher<Void, Never>] = [
+ s.$stripePayments.map { _ in () }.eraseToAnyPublisher(),
+ s.$stripeBalance.map { _ in () }.eraseToAnyPublisher(),
+ s.$stripeError.map { _ in () }.eraseToAnyPublisher(),
+ s.$githubPulse.map { _ in () }.eraseToAnyPublisher(),
+ s.$githubActivity.map { _ in () }.eraseToAnyPublisher(),
+ s.$vercelDeployments.map { _ in () }.eraseToAnyPublisher(),
+ s.$resendEmails.map { _ in () }.eraseToAnyPublisher(),
+ s.$calcomBookings.map { _ in () }.eraseToAnyPublisher(),
+ s.$calcomError.map { _ in () }.eraseToAnyPublisher(),
+ s.$notionPages.map { _ in () }.eraseToAnyPublisher(),
+ s.$notionError.map { _ in () }.eraseToAnyPublisher(),
+ s.$n8nRuns.map { _ in () }.eraseToAnyPublisher(),
+ ]
+ cancellable = Publishers.MergeMany(changes)
+ .debounce(for: .seconds(2), scheduler: RunLoop.main)
+ .sink { [weak self] in
+ MainActor.assumeIsolated { self?.publish() }
+ }
+ log("service publisher on")
+ }
+
+ /// Stops and deletes this Mac's services from iCloud.
+ func stop() {
+ cancellable = nil
+ let ids = PillCatalog.phoneServices.map {
+ CKRecord.ID(recordName: ServiceSnapshot.recordName(for: $0), zoneID: SessionSnapshot.zoneID)
+ }
+ published = [:]
+ cleanedUp = false
+ Task { _ = try? await database.modifyRecords(saving: [], deleting: ids, savePolicy: .changedKeys, atomically: false) }
+ log("service publisher off")
+ }
+
+ private func publish() {
+ guard !writing else { again = true; return }
+ writing = true
+ let snapshots = ServiceSnapshots.all(from: AppState.shared)
+ Task {
+ await write(snapshots)
+ writing = false
+ if again { again = false; publish() }
+ }
+ }
+
+ private func write(_ snapshots: [String: ServiceSnapshot]) async {
+ var deletions: [CKRecord.ID] = []
+ if !cleanedUp {
+ // Services this Mac no longer has (key removed since the last run).
+ deletions = PillCatalog.phoneServices.filter { snapshots[$0] == nil }.map {
+ CKRecord.ID(recordName: ServiceSnapshot.recordName(for: $0), zoneID: SessionSnapshot.zoneID)
+ }
+ cleanedUp = true
+ }
+ let changed = snapshots.values.filter { snapshot in
+ guard let old = published[snapshot.pillId] else { return true }
+ return !old.sameContent(as: snapshot)
+ }
+ let removed = published.keys.filter { snapshots[$0] == nil }
+ deletions += removed.map { CKRecord.ID(recordName: ServiceSnapshot.recordName(for: $0), zoneID: SessionSnapshot.zoneID) }
+ guard !changed.isEmpty || !deletions.isEmpty else { return }
+
+ let records = changed.compactMap { record(for: $0) }
+ do {
+ let result = try await database.modifyRecords(saving: records, deleting: deletions,
+ savePolicy: .changedKeys, atomically: false)
+ for (id, outcome) in result.saveResults {
+ guard let pillId = ServiceSnapshot.pillId(fromRecordName: id.recordName) else { continue }
+ if case .success = outcome { published[pillId] = snapshots[pillId] }
+ }
+ for id in removed { published[id] = nil }
+ let names = changed.map { "\($0.pillId.replacingOccurrences(of: "integration_", with: ""))=\($0.tone.rawValue)" }
+ log("published \(changed.count) service(s) [\(names.sorted().joined(separator: ", "))], removed \(deletions.count)")
+ } catch {
+ log("publish failed: \(error.localizedDescription)")
+ }
+ }
+
+ private func record(for snapshot: ServiceSnapshot) -> CKRecord? {
+ guard let json = try? JSONEncoder().encode(snapshot), let payload = String(data: json, encoding: .utf8) else { return nil }
+ let record = CKRecord(recordType: ServiceSnapshot.recordType,
+ recordID: CKRecord.ID(recordName: ServiceSnapshot.recordName(for: snapshot.pillId),
+ zoneID: SessionSnapshot.zoneID))
+ record["pillId"] = snapshot.pillId
+ record["tone"] = snapshot.tone.rawValue
+ record["updatedAt"] = snapshot.updatedAt
+ record["macName"] = Host.current().localizedName ?? ""
+ record.encryptedValues["payload"] = payload
+ return record
+ }
+
+ private func log(_ message: String) {
+ CloudProbe.shared.log("[services] \(message)")
+ }
+}
+
+// MARK: - Building the snapshots
+
+/// One snapshot per service that has data on this Mac. A service without its
+/// key (nothing loaded) is left out, and the iPhone shows "connect it on your Mac".
+@MainActor
+enum ServiceSnapshots {
+ static func all(from s: AppState) -> [String: ServiceSnapshot] {
+ let built = [github(s), stripe(s), vercel(s), resend(s), calcom(s), n8n(s), notion(s)].compactMap { $0 }
+ return Dictionary(uniqueKeysWithValues: built.map { ($0.pillId, $0) })
+ }
+
+ // MARK: GitHub
+
+ static func github(_ s: AppState) -> ServiceSnapshot? {
+ guard let pulse = s.githubPulse else { return nil }
+ func tone(_ ci: CIState) -> ServiceTone {
+ switch ci {
+ case .success: .ok
+ case .failure: .error
+ case .pending: .warning
+ case .unknown: .idle
+ }
+ }
+ func ciLabel(_ ci: CIState) -> String {
+ switch ci {
+ case .success: "checks passed"
+ case .failure: "checks failing"
+ case .pending: "checks running"
+ case .unknown: "no checks"
+ }
+ }
+ func reviewLabel(_ review: ReviewState) -> String {
+ switch review {
+ case .approved: " · approved"
+ case .changesRequested: " · changes requested"
+ case .pending: " · review required"
+ case .unknown: ""
+ }
+ }
+ let failingPR = pulse.myPRs.first { $0.ci == .failure }
+ let failingMain = pulse.mainCI.first { $0.ci == .failure }
+ let pending = pulse.myPRs.contains { $0.ci == .pending } || pulse.mainCI.contains { $0.ci == .pending }
+ let anyGreen = pulse.myPRs.contains { $0.ci == .success } || pulse.mainCI.contains { $0.ci == .success }
+
+ let overall: ServiceTone
+ let reason: String
+ if let main = failingMain {
+ overall = .error
+ reason = "CI failing on \(main.repo) · \(main.branch)"
+ } else if let pr = failingPR {
+ overall = .error
+ reason = "Checks failing on \(pr.repo) #\(pr.number): \(pr.title)"
+ } else if pending {
+ overall = .warning
+ reason = "Checks are running"
+ } else if !pulse.toReview.isEmpty {
+ overall = .warning
+ reason = pulse.toReview.count == 1
+ ? "1 pull request waits for your review"
+ : "\(pulse.toReview.count) pull requests wait for your review"
+ } else if anyGreen {
+ overall = .ok
+ reason = "All checks passed"
+ } else {
+ overall = .idle
+ reason = "Nothing going on"
+ }
+
+ var sections: [ServiceSection] = []
+ if !pulse.myPRs.isEmpty {
+ sections.append(ServiceSection(title: "Your pull requests", items: pulse.myPRs.prefix(8).map {
+ ServiceItem(title: "#\($0.number) \($0.title)",
+ detail: "\($0.repo) · \(ciLabel($0.ci))\(reviewLabel($0.review))\($0.isDraft ? " · draft" : "")",
+ tone: tone($0.ci), url: $0.url)
+ }))
+ }
+ if !pulse.toReview.isEmpty {
+ sections.append(ServiceSection(title: "Waiting for your review", items: pulse.toReview.prefix(8).map {
+ ServiceItem(title: "#\($0.number) \($0.title)", detail: $0.repo, tone: .warning, url: $0.url)
+ }))
+ }
+ if !pulse.mainCI.isEmpty {
+ sections.append(ServiceSection(title: "Default branches", items: pulse.mainCI.prefix(8).map {
+ ServiceItem(title: $0.repo, detail: "\($0.branch) · \(ciLabel($0.ci))", tone: tone($0.ci), url: $0.url)
+ }))
+ }
+ var headline = "\(pulse.myPRs.count) open pull request\(pulse.myPRs.count == 1 ? "" : "s")"
+ if let total = s.githubActivity?.total { headline += " · \(total) contributions this year" }
+ return ServiceSnapshot(pillId: "integration_github", tone: overall, headline: headline, reason: reason,
+ sections: sections, updatedAt: pulse.fetchedAt)
+ }
+
+ // MARK: Stripe
+
+ static func stripe(_ s: AppState) -> ServiceSnapshot? {
+ if let error = s.stripeError, !s.stripeLoaded {
+ return ServiceSnapshot(pillId: "integration_stripe", tone: .error, headline: "Can't reach Stripe",
+ reason: error, sections: [], updatedAt: Date())
+ }
+ guard s.stripeLoaded else { return nil }
+ let currency = s.stripeCurrency.uppercased()
+ func money(_ cents: Int, _ code: String) -> String {
+ String(format: "%.2f %@", Double(cents) / 100, code.uppercased())
+ }
+ let latest = s.stripePayments.first
+ let overall: ServiceTone
+ let reason: String
+ if let error = s.stripeError {
+ overall = .error
+ reason = "Stripe answered with an error: \(error)"
+ } else if let latest {
+ let what = latest.description.map { " · \($0)" } ?? ""
+ switch latest.status {
+ case "succeeded":
+ overall = Date().timeIntervalSince(latest.createdAt) < 86_400 ? .ok : .idle
+ reason = "Last payment received: \(money(latest.amount, latest.currency))\(what)"
+ case "failed":
+ overall = .error
+ reason = "Last payment failed: \(money(latest.amount, latest.currency))\(what)"
+ default:
+ overall = .warning
+ reason = "Last payment pending: \(money(latest.amount, latest.currency))\(what)"
+ }
+ } else {
+ overall = .idle
+ reason = "No payment yet"
+ }
+ let items = s.stripePayments.prefix(10).map {
+ ServiceItem(title: money($0.amount, $0.currency),
+ detail: [$0.description, $0.status].compactMap { $0 }.joined(separator: " · "),
+ tone: $0.isSuccess ? .ok : ($0.status == "failed" ? .error : .warning),
+ date: $0.createdAt)
+ }
+ return ServiceSnapshot(pillId: "integration_stripe", tone: overall,
+ headline: "Balance \(money(s.stripeBalance, currency))", reason: reason,
+ sections: items.isEmpty ? [] : [ServiceSection(title: "Recent payments", items: items)],
+ updatedAt: latest?.createdAt ?? Date())
+ }
+
+ // MARK: Vercel
+
+ static func vercel(_ s: AppState) -> ServiceSnapshot? {
+ let filter = s.vercelProjectFilter
+ let deployments = filter.isEmpty ? s.vercelDeployments : s.vercelDeployments.filter { filter.contains($0.projectName) }
+ guard let latest = deployments.first else { return nil }
+ func tone(_ d: VercelDeployment) -> ServiceTone {
+ d.isSuccess ? .ok : (d.state == "CANCELED" ? .warning : .error)
+ }
+ let branch = latest.branch.map { " · \($0)" } ?? ""
+ let reason: String
+ switch latest.state {
+ case "READY": reason = "Last deploy is live: \(latest.projectName)\(branch)"
+ case "CANCELED": reason = "Last deploy was canceled: \(latest.projectName)\(branch)"
+ default: reason = "Last deploy failed: \(latest.projectName)\(branch)"
+ }
+ let items = deployments.prefix(10).map { d in
+ ServiceItem(title: d.projectName,
+ detail: [d.statusLabel, d.branch, d.commitMessage].compactMap { $0 }.joined(separator: " · "),
+ tone: tone(d), date: d.createdAt,
+ url: d.url.isEmpty ? nil : "https://\(d.url)")
+ }
+ return ServiceSnapshot(pillId: "integration_vercel", tone: tone(latest),
+ headline: "\(latest.projectName) · \(latest.statusLabel)", reason: reason,
+ sections: [ServiceSection(title: "Deployments", items: items)],
+ updatedAt: latest.createdAt)
+ }
+
+ // MARK: Resend
+
+ static func resend(_ s: AppState) -> ServiceSnapshot? {
+ guard let latest = s.resendEmails.first else { return nil }
+ func tone(_ event: String) -> ServiceTone {
+ switch event {
+ case "bounced", "complained", "failed": .error
+ case "delivered", "opened", "clicked": .ok
+ case "delivery_delayed": .warning
+ default: .info
+ }
+ }
+ let reason: String
+ switch tone(latest.lastEvent) {
+ case .error: reason = "Last email \(latest.lastEvent): \(latest.subject)"
+ case .warning: reason = "Last email is delayed: \(latest.subject)"
+ case .ok: reason = "Last email \(latest.lastEvent): \(latest.subject)"
+ default: reason = "Last email \(latest.lastEvent): \(latest.subject)"
+ }
+ let items = s.resendEmails.prefix(10).map {
+ ServiceItem(title: $0.subject, detail: "to \($0.to.joined(separator: ", ")) · \($0.lastEvent)",
+ tone: tone($0.lastEvent), date: $0.createdAt)
+ }
+ let total = s.resendTotal.map { "\($0) emails sent" } ?? "Emails"
+ return ServiceSnapshot(pillId: "integration_resend", tone: tone(latest.lastEvent), headline: total,
+ reason: reason, sections: [ServiceSection(title: "Recent emails", items: items)],
+ updatedAt: latest.createdAt)
+ }
+
+ // MARK: Cal.com
+
+ static func calcom(_ s: AppState) -> ServiceSnapshot? {
+ if let error = s.calcomError, !s.calcomLoaded {
+ return ServiceSnapshot(pillId: "integration_calcom", tone: .error, headline: "Can't reach Cal.com",
+ reason: error, sections: [], updatedAt: Date())
+ }
+ guard s.calcomLoaded else { return nil }
+ let upcoming = s.calcomBookings.filter { $0.endTime > Date() }.sorted { $0.startTime < $1.startTime }
+ let next = upcoming.first { $0.isActive }
+ let time = Date.FormatStyle(date: .abbreviated, time: .shortened)
+ let overall: ServiceTone
+ let reason: String
+ if let next {
+ let soon = next.startTime.timeIntervalSinceNow < 3600
+ overall = soon ? .warning : .info
+ let with = next.attendeeName.map { " with \($0)" } ?? ""
+ reason = "\(soon ? "Starting soon" : "Next"): \(next.title)\(with), \(next.startTime.formatted(time))"
+ } else {
+ overall = .idle
+ reason = "No upcoming booking"
+ }
+ let items = upcoming.prefix(10).map {
+ ServiceItem(title: $0.title,
+ detail: [$0.attendeeName, $0.status.lowercased()].compactMap { $0 }.joined(separator: " · "),
+ tone: $0.isActive ? .info : .idle, date: $0.startTime)
+ }
+ let count = upcoming.filter(\.isActive).count
+ return ServiceSnapshot(pillId: "integration_calcom", tone: overall,
+ headline: "\(count) upcoming booking\(count == 1 ? "" : "s")", reason: reason,
+ sections: items.isEmpty ? [] : [ServiceSection(title: "Upcoming", items: items)],
+ updatedAt: Date())
+ }
+
+ // MARK: n8n
+
+ static func n8n(_ s: AppState) -> ServiceSnapshot? {
+ guard let latest = s.n8nRuns.first else { return nil }
+ let reason = latest.success
+ ? "Last run succeeded: \(latest.workflow)"
+ : "Last run failed: \(latest.workflow)\(latest.detail.map { " · \($0)" } ?? "")"
+ let items = s.n8nRuns.map {
+ ServiceItem(title: $0.workflow, detail: $0.detail ?? ($0.success ? "succeeded" : "failed"),
+ tone: $0.success ? .ok : .error, date: $0.date)
+ }
+ let failed = s.n8nRuns.filter { !$0.success }.count
+ return ServiceSnapshot(pillId: "integration_n8n", tone: latest.success ? .ok : .error,
+ headline: failed == 0 ? "All recent runs succeeded" : "\(failed) failed run\(failed == 1 ? "" : "s")",
+ reason: reason, sections: [ServiceSection(title: "Recent runs", items: items)],
+ updatedAt: latest.date)
+ }
+
+ // MARK: Notion
+
+ static func notion(_ s: AppState) -> ServiceSnapshot? {
+ if let error = s.notionError, !s.notionLoaded {
+ return ServiceSnapshot(pillId: "integration_notion", tone: .error, headline: "Can't reach Notion",
+ reason: error, sections: [], updatedAt: Date())
+ }
+ guard s.notionLoaded else { return nil }
+ let pages = s.notionPages.sorted { $0.lastEditedAt > $1.lastEditedAt }
+ let items = pages.prefix(10).map {
+ ServiceItem(title: [$0.emoji, $0.title].compactMap { $0 }.joined(separator: " "),
+ tone: .info, date: $0.lastEditedAt, url: $0.url)
+ }
+ let reason = pages.first.map { "Last edited: \($0.title)" } ?? "No recent page"
+ let recent = (pages.first?.lastEditedAt.timeIntervalSinceNow ?? -.infinity) > -3600
+ return ServiceSnapshot(pillId: "integration_notion", tone: recent ? .info : .idle,
+ headline: "\(pages.count) recent page\(pages.count == 1 ? "" : "s")", reason: reason,
+ sections: items.isEmpty ? [] : [ServiceSection(title: "Recently edited", items: items)],
+ updatedAt: pages.first?.lastEditedAt ?? Date())
+ }
+}
+#endif
diff --git a/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift b/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift
index 65032fd7..d4e2e7db 100644
--- a/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift
+++ b/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift
@@ -174,7 +174,8 @@ struct SessionSnapshot: Equatable {
static func all(tasks: [AgentTask], approval: ApprovalInfo?,
question: AskQuestion?) -> [String: SessionSnapshot] {
var result: [String: SessionSnapshot] = [:]
- for task in tasks where task.source != .n8n {
+ // Services (Stripe, GitHub…) go through ServicePublisher, with their data.
+ for task in tasks where task.source != .n8n && PillCatalog.isSession(task.id) {
let hasApproval = approval?.pillId == task.id
let questionText = task.state == .question
? (question?.questions.map(\.question).joined(separator: "\n") ?? "")
@@ -229,6 +230,12 @@ struct SessionSnapshot: Equatable {
record["needsAnswer"] = !question.isEmpty
record["updatedAt"] = Date()
record["macName"] = Host.current().localizedName ?? ""
+ // Whether this Mac runs instructions sent from the iPhone (GitHub build, switch on).
+ #if APPSTORE
+ record["acceptsInstructions"] = false
+ #else
+ record["acceptsInstructions"] = InstructionRunner.isEnabled && (pillId == "integration_claude" || pillId == "agent_cursor")
+ #endif
record.encryptedValues["name"] = name
record.encryptedValues["steps"] = steps
record.encryptedValues["cwd"] = cwd
diff --git a/NotchBuddy/Sources/App/PhoneLink/TurnRecorder.swift b/NotchBuddy/Sources/App/PhoneLink/TurnRecorder.swift
new file mode 100644
index 00000000..3aed1ddf
--- /dev/null
+++ b/NotchBuddy/Sources/App/PhoneLink/TurnRecorder.swift
@@ -0,0 +1,217 @@
+#if PHONE_LINK
+import AppKit
+import CloudKit
+
+// MARK: - The last turn, for the iPhone
+//
+// Built from the hook events HookServer already receives: UserPromptSubmit
+// starts a turn, Pre/PostToolUse add actions (commands with their output,
+// edits with their diff), Stop adds the final answer. One encrypted `Turn`
+// record per session pill, replaced at each turn; nothing else is kept.
+// Runs only while the iPhone sync is on; no timer.
+
+@MainActor
+final class TurnRecorder {
+ static let shared = TurnRecorder()
+
+ private let container = CKContainer(identifier: CloudProbe.containerID)
+ private var database: CKDatabase { container.privateCloudDatabase }
+ private var running = false
+ private var turns: [String: TurnSnapshot] = [:]
+ private var dirty: Set<String> = []
+ private var flushTask: Task<Void, Never>?
+
+ // Size limits: a turn stays well under CloudKit's 1 MB per record.
+ private let maxActions = 200
+ private let maxLinesPerFile = 600
+ private let maxTotalLines = 4000
+ private let maxOutput = 1500
+ private let maxFinal = 12_000
+
+ /// The Claude Code session last seen on a pill and its folder, for
+ /// instructions sent from the iPhone (InstructionRunner).
+ func lastSession(for pillId: String) -> (sessionId: String, cwd: String)? {
+ guard let info = sessions[pillId], !info.sessionId.isEmpty, !info.cwd.isEmpty else { return nil }
+ return info
+ }
+ private var sessions: [String: (sessionId: String, cwd: String)] = [:]
+
+ func start() {
+ running = true
+ log("turn recorder on")
+ }
+
+ func stop() {
+ running = false
+ flushTask?.cancel(); flushTask = nil
+ let ids = turns.keys.map {
+ CKRecord.ID(recordName: TurnSnapshot.recordName(for: $0), zoneID: SessionSnapshot.zoneID)
+ }
+ turns = [:]
+ dirty = []
+ if !ids.isEmpty {
+ Task { _ = try? await database.modifyRecords(saving: [], deleting: ids, savePolicy: .changedKeys, atomically: false) }
+ }
+ }
+
+ /// Called by HookServer for every event of a session pill.
+ func record(event: String, payload: [String: Any], pillId: String) {
+ guard running, PillCatalog.isSession(pillId) else { return }
+ let sessionId = payload["session_id"] as? String ?? payload["conversation_id"] as? String ?? ""
+ let cwd = payload["cwd"] as? String ?? ""
+ let now = Date()
+ if !sessionId.isEmpty, !cwd.isEmpty { sessions[pillId] = (sessionId, cwd) }
+
+ switch event {
+ case "UserPromptSubmit":
+ let prompt = payload["prompt"] as? String ?? ""
+ turns[pillId] = TurnSnapshot(pillId: pillId, sessionId: sessionId,
+ project: URL(fileURLWithPath: cwd).lastPathComponent,
+ prompt: String(prompt.prefix(8000)), actions: [], files: [],
+ finalMessage: "", startedAt: now, endedAt: nil)
+
+ case "PreToolUse":
+ let tool = payload["tool_name"] as? String ?? "Tool"
+ guard tool != "AskUserQuestion" else { return }
+ var turn = current(pillId, sessionId: sessionId, cwd: cwd)
+ guard turn.actions.count < maxActions else { return }
+ let input = payload["tool_input"] as? [String: Any] ?? [:]
+ turn.actions.append(TurnAction(tool: tool, summary: Self.summary(tool: tool, input: input), date: now))
+ turns[pillId] = turn
+
+ case "PostToolUse", "PostToolUseFailure":
+ let tool = payload["tool_name"] as? String ?? "Tool"
+ guard tool != "AskUserQuestion" else { return }
+ var turn = current(pillId, sessionId: sessionId, cwd: cwd)
+ let input = payload["tool_input"] as? [String: Any] ?? [:]
+ let summary = Self.summary(tool: tool, input: input)
+ // The matching PreToolUse action, latest first; one is added if it was missed.
+ var index = turn.actions.lastIndex { $0.tool == tool && $0.summary == summary && $0.output.isEmpty && $0.fileIndex == nil }
+ if index == nil, turn.actions.count < maxActions {
+ turn.actions.append(TurnAction(tool: tool, summary: summary, date: now))
+ index = turn.actions.count - 1
+ }
+ guard let index else { return }
+ turn.actions[index].failed = event == "PostToolUseFailure"
+ turn.actions[index].output = Self.output(payload, limit: maxOutput)
+ if event == "PostToolUse", let diff = Self.fileDiff(tool: tool, input: input) {
+ let used = turn.files.reduce(0) { $0 + $1.lines.count }
+ let budget = max(0, min(maxLinesPerFile, maxTotalLines - used))
+ turn.files.append(TurnFile(diff: diff, maxLines: budget))
+ turn.actions[index].fileIndex = turn.files.count - 1
+ }
+ turns[pillId] = turn
+
+ case "Stop", "StopFailure":
+ var turn = current(pillId, sessionId: sessionId, cwd: cwd)
+ let final = (payload["last_assistant_message"] as? String) ?? (payload["message"] as? String) ?? ""
+ turn.finalMessage = String(final.prefix(maxFinal))
+ turn.endedAt = now
+ turns[pillId] = turn
+
+ default:
+ return
+ }
+ dirty.insert(pillId)
+ scheduleFlush(soon: event == "Stop" || event == "StopFailure" || event == "UserPromptSubmit")
+ }
+
+ /// The turn in progress, or a new one when the prompt wasn't seen (Codex, app started mid-turn).
+ private func current(_ pillId: String, sessionId: String, cwd: String) -> TurnSnapshot {
+ if let turn = turns[pillId], turn.endedAt == nil { return turn }
+ return TurnSnapshot(pillId: pillId, sessionId: sessionId,
+ project: URL(fileURLWithPath: cwd).lastPathComponent,
+ prompt: "", actions: [], files: [], finalMessage: "", startedAt: Date(), endedAt: nil)
+ }
+
+ // MARK: Writing
+
+ private func scheduleFlush(soon: Bool) {
+ if soon { flushTask?.cancel(); flushTask = nil }
+ guard flushTask == nil else { return }
+ flushTask = Task {
+ try? await Task.sleep(for: .seconds(soon ? 0.5 : 2))
+ guard !Task.isCancelled else { return }
+ flushTask = nil
+ await flush()
+ }
+ }
+
+ private func flush() async {
+ let ids = dirty
+ dirty = []
+ let records = ids.compactMap { id -> CKRecord? in
+ guard let turn = turns[id], let json = try? JSONEncoder().encode(turn),
+ let payload = String(data: json, encoding: .utf8) else { return nil }
+ let record = CKRecord(recordType: TurnSnapshot.recordType,
+ recordID: CKRecord.ID(recordName: TurnSnapshot.recordName(for: id),
+ zoneID: SessionSnapshot.zoneID))
+ record["pillId"] = id
+ record["updatedAt"] = Date()
+ record.encryptedValues["payload"] = payload
+ return record
+ }
+ guard !records.isEmpty else { return }
+ do {
+ _ = try await database.modifyRecords(saving: records, deleting: [], savePolicy: .allKeys, atomically: false)
+ } catch {
+ log("turn publish failed: \(error.localizedDescription)")
+ }
+ }
+
+ // MARK: Reading the hook payloads
+
+ static func summary(tool: String, input: [String: Any]) -> String {
+ let keys = ["command", "file_path", "path", "pattern", "url", "query", "description", "prompt"]
+ for key in keys {
+ if let value = input[key] as? String, !value.isEmpty { return String(value.prefix(600)) }
+ }
+ return ""
+ }
+
+ /// What a command printed, or the error.
+ static func output(_ payload: [String: Any], limit: Int) -> String {
+ var text = ""
+ if let error = payload["error"] as? String {
+ text = error
+ } else if let response = payload["tool_response"] as? [String: Any] {
+ let stdout = response["stdout"] as? String ?? ""
+ let stderr = response["stderr"] as? String ?? ""
+ text = [stdout, stderr].filter { !$0.isEmpty }.joined(separator: "\n")
+ } else if let response = payload["tool_response"] as? String {
+ text = response
+ }
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ return trimmed.count > limit ? String(trimmed.prefix(limit)) + "\n…" : trimmed
+ }
+
+ static func fileDiff(tool: String, input: [String: Any]) -> FileDiff? {
+ guard let path = input["file_path"] as? String else { return nil }
+ switch tool {
+ case "Edit":
+ guard let old = input["old_string"] as? String, let new = input["new_string"] as? String else { return nil }
+ return DiffEngine.fromEdit(old: old, new: new, path: path)
+ case "MultiEdit":
+ guard let edits = input["edits"] as? [[String: Any]] else { return nil }
+ var added = 0, removed = 0, hunks: [DiffHunk] = [], tooLarge = false
+ for edit in edits {
+ guard let old = edit["old_string"] as? String, let new = edit["new_string"] as? String else { continue }
+ let d = DiffEngine.fromEdit(old: old, new: new, path: path)
+ added += d.added; removed += d.removed
+ hunks += d.hunks
+ tooLarge = tooLarge || d.tooLarge
+ }
+ return FileDiff(path: path, added: added, removed: removed, hunks: hunks, tooLarge: tooLarge, isNewFile: false)
+ case "Write":
+ guard let content = input["content"] as? String else { return nil }
+ return DiffEngine.fromNew(content: content, path: path)
+ default:
+ return nil
+ }
+ }
+
+ private func log(_ message: String) {
+ CloudProbe.shared.log("[turn] \(message)")
+ }
+}
+#endif
diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swift
index c124971b..9a3d0408 100644
--- a/NotchBuddy/Sources/App/SettingsView.swift
+++ b/NotchBuddy/Sources/App/SettingsView.swift
@@ -98,6 +98,7 @@ struct SettingsView: View {
#if PHONE_LINK
@AppStorage("iPhoneSyncEnabled") private var iPhoneSyncEnabled = false
@AppStorage("iPhoneLiveActivityEnabled") private var iPhoneLiveActivityEnabled = false
+ @AppStorage("iPhoneInstructionsEnabled") private var iPhoneInstructionsEnabled = false
#endif
private var appVersion: String {
@@ -311,6 +312,15 @@ struct SettingsView: View {
.font(.system(size: 11))
.foregroundColor(.secondary)
.fixedSize(horizontal: false, vertical: true)
+ #if !APPSTORE
+ Toggle("Let my iPhone send instructions to Claude Code", isOn: $iPhoneInstructionsEnabled)
+ .disabled(!iPhoneSyncEnabled)
+ .onChange(of: iPhoneInstructionsEnabled) { _, on in InstructionRunner.shared.setEnabled(on) }
+ Text("An instruction sent from the iPhone (Face ID required) continues your last Claude Code session in the background, in its folder, with claude --resume. This Mac checks for one every 15 s while this is on.")
+ .font(.system(size: 11))
+ .foregroundColor(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ #endif
}
.padding(6)
}
diff --git a/NotchBuddy/Sources/CoucouKit/MochiStill.swift b/NotchBuddy/Sources/CoucouKit/MochiStill.swift
index c6c53926..c74edce1 100644
--- a/NotchBuddy/Sources/CoucouKit/MochiStill.swift
+++ b/NotchBuddy/Sources/CoucouKit/MochiStill.swift
@@ -10,6 +10,8 @@ struct MochiStill: View {
/// Body color; white by default, like the mockups.
var bodyHex: String = "#FFFFFF"
var showBadge: Bool = true
+ /// Where he looks and how his eyes are, for a still that isn't always the same.
+ var pose: MochiPose = .neutral
var body: some View {
Canvas { context, size in
@@ -18,7 +20,11 @@ struct MochiStill: View {
engine.bodyColor = cgColorFromHex(bodyHex)
engine.state = state
engine.cfg = BotStates[state]!
- if let eye {
+ engine.yaw = pose.yaw
+ engine.pitch = pose.pitch
+ engine.tilt = pose.tilt
+ engine.open = pose.open
+ if let eye = eye ?? pose.eye {
engine.permanentEye = eye
engine.eyeOverride = eye
engine.eyeOverrideUntil = .greatestFiniteMagnitude
@@ -34,6 +40,42 @@ struct MochiStill: View {
}
}
+/// One frame of the little life the Mac's mini Mochi have: looking around,
+/// blinking, a happy squint. Widgets can't animate, so each refresh of the
+/// timeline picks a new pose per Mochi; the system cross-fades between them.
+struct MochiPose: Equatable, Sendable {
+ var yaw: CGFloat = 0
+ var pitch: CGFloat = 0
+ var tilt: CGFloat = 0
+ var open: CGFloat = 1
+ var eye: EyeShape? = nil
+
+ static let neutral = MochiPose()
+
+ static let idlePoses: [MochiPose] = [
+ MochiPose(),
+ MochiPose(yaw: -0.45),
+ MochiPose(yaw: 0.45),
+ MochiPose(yaw: -0.3, pitch: -0.25),
+ MochiPose(yaw: 0.35, pitch: 0.2, tilt: 0.08),
+ MochiPose(pitch: -0.3, tilt: -0.06),
+ MochiPose(eye: .closed), // blink
+ MochiPose(yaw: 0.2, eye: .happy),
+ MochiPose(yaw: -0.5, tilt: -0.1),
+ MochiPose(yaw: 0.15, pitch: 0.25),
+ ]
+
+ /// A pose that differs per Mochi and per tick, the same every time for a
+ /// given pair (so a widget redraw doesn't jump).
+ static func idle(id: String, tick: Int) -> MochiPose {
+ var hash: UInt64 = 5381
+ for byte in id.utf8 { hash = (hash &* 33) &+ UInt64(byte) }
+ hash = (hash &* 31) &+ UInt64(truncatingIfNeeded: tick &* 7919)
+ hash ^= hash >> 13
+ return idlePoses[Int(hash % UInt64(idlePoses.count))]
+ }
+}
+
extension Color {
/// Background for a white Mochi on an agent's color. Very light colors
/// (VS Code's is near-white) would hide him, so they get a dark gray tile.
diff --git a/NotchBuddy/Sources/CoucouKit/ServiceSnapshot.swift b/NotchBuddy/Sources/CoucouKit/ServiceSnapshot.swift
new file mode 100644
index 00000000..66cba845
--- /dev/null
+++ b/NotchBuddy/Sources/CoucouKit/ServiceSnapshot.swift
@@ -0,0 +1,67 @@
+import Foundation
+
+// What the iPhone shows for one service Mochi (GitHub, Stripe, Vercel, Resend,
+// Cal.com, n8n, Notion): its state dot, why it has that color, and the latest
+// items the Mac fetched. The Mac builds it from the data its pollers already
+// keep (ServicePublisher) and writes it to the private iCloud zone, encrypted;
+// the iPhone only reads it. No API key ever leaves the Mac.
+
+enum ServiceTone: String, Codable, Sendable {
+ case ok, warning, error, info, idle
+}
+
+struct ServiceItem: Codable, Equatable, Sendable {
+ var title: String
+ var detail: String = ""
+ var tone: ServiceTone = .idle
+ var date: Date? = nil
+ var url: String? = nil
+}
+
+struct ServiceSection: Codable, Equatable, Sendable {
+ var title: String
+ var items: [ServiceItem]
+}
+
+struct ServiceSnapshot: Codable, Equatable, Sendable {
+ var pillId: String
+ var tone: ServiceTone
+ /// One line under the name ("Balance 1 240,00 EUR", "2 pull requests").
+ var headline: String
+ /// Why the dot has its color ("CI failing on coucou · main").
+ var reason: String
+ var sections: [ServiceSection]
+ var updatedAt: Date
+
+ static let recordType = "Service"
+
+ static func recordName(for pillId: String) -> String { "service-\(pillId)" }
+
+ static func pillId(fromRecordName name: String) -> String? {
+ name.hasPrefix("service-") ? String(name.dropFirst("service-".count)) : nil
+ }
+
+ /// Equal apart from the date: nothing to write again.
+ func sameContent(as other: ServiceSnapshot) -> Bool {
+ var a = self, b = other
+ a.updatedAt = .distantPast
+ b.updatedAt = .distantPast
+ return a == b
+ }
+}
+
+extension PillCatalog {
+ /// The service Mochi the iPhone shows, in this order.
+ static let phoneServices = [
+ "integration_github", "integration_stripe", "integration_vercel", "integration_resend",
+ "integration_calcom", "integration_n8n", "integration_notion",
+ ]
+
+ /// Agent sessions (VS Code, Cursor, Codex…), as opposed to services and chat providers.
+ static func isSession(_ id: String) -> Bool {
+ switch definition(for: id)?.category {
+ case .service, .ai: false
+ default: true
+ }
+ }
+}
diff --git a/NotchBuddy/Sources/CoucouKit/TurnSnapshot.swift b/NotchBuddy/Sources/CoucouKit/TurnSnapshot.swift
new file mode 100644
index 00000000..15f95b0d
--- /dev/null
+++ b/NotchBuddy/Sources/CoucouKit/TurnSnapshot.swift
@@ -0,0 +1,78 @@
+import Foundation
+
+// The last turn of an agent session, for the iPhone: the prompt you sent, what
+// the agent did (commands, reads, searches, edits with their diffs) and its
+// final answer. The Mac builds it from the hook events it already receives
+// (TurnRecorder) and writes it, encrypted, to the private iCloud zone. Only
+// the latest turn per session is kept.
+
+struct TurnAction: Codable, Equatable, Sendable {
+ var tool: String // "Bash", "Edit", "Read"…
+ var summary: String // the command, file or pattern
+ var output: String = "" // what a command printed (trimmed)
+ var failed: Bool = false
+ var date: Date
+ /// Index in `files` when this action changed a file.
+ var fileIndex: Int? = nil
+}
+
+struct TurnDiffLine: Codable, Equatable, Sendable {
+ enum Kind: String, Codable, Sendable { case context, added, removed, gap }
+ var kind: Kind
+ var text: String
+}
+
+struct TurnFile: Codable, Equatable, Sendable {
+ var path: String
+ var added: Int
+ var removed: Int
+ var isNew: Bool
+ var lines: [TurnDiffLine]
+ /// Some lines were left out to keep the turn small.
+ var truncated: Bool = false
+
+ var name: String { URL(fileURLWithPath: path).lastPathComponent }
+}
+
+struct TurnSnapshot: Codable, Equatable, Sendable {
+ var pillId: String
+ var sessionId: String
+ var project: String
+ var prompt: String
+ var actions: [TurnAction]
+ var files: [TurnFile]
+ var finalMessage: String
+ var startedAt: Date
+ var endedAt: Date?
+
+ static let recordType = "Turn"
+
+ static func recordName(for pillId: String) -> String { "turn-\(pillId)" }
+
+ static func pillId(fromRecordName name: String) -> String? {
+ name.hasPrefix("turn-") ? String(name.dropFirst("turn-".count)) : nil
+ }
+}
+
+extension TurnFile {
+ /// The diff lines of a FileDiff (DiffEngine), hunks separated by a gap line.
+ init(diff: FileDiff, maxLines: Int) {
+ var lines: [TurnDiffLine] = []
+ var truncated = diff.tooLarge
+ for (index, hunk) in diff.hunks.enumerated() {
+ if index > 0 { lines.append(TurnDiffLine(kind: .gap, text: "")) }
+ for line in hunk.lines {
+ guard lines.count < maxLines else { truncated = true; break }
+ let kind: TurnDiffLine.Kind
+ switch line.kind {
+ case .added: kind = .added
+ case .removed: kind = .removed
+ case .context: kind = .context
+ }
+ lines.append(TurnDiffLine(kind: kind, text: String(line.text.prefix(400))))
+ }
+ }
+ self.init(path: diff.path, added: diff.added, removed: diff.removed,
+ isNew: diff.isNewFile, lines: lines, truncated: truncated)
+ }
+}
diff --git a/NotchBuddy/Sources/Phone/CoucouPhoneApp.swift b/NotchBuddy/Sources/Phone/CoucouPhoneApp.swift
index e08e8d22..8f9d0520 100644
--- a/NotchBuddy/Sources/Phone/CoucouPhoneApp.swift
+++ b/NotchBuddy/Sources/Phone/CoucouPhoneApp.swift
@@ -47,15 +47,27 @@ final class PhoneAppDelegate: NSObject, UIApplicationDelegate, UNUserNotificatio
}
// Approval notification actions.
+ //
+ // Completion-handler versions, with the handler always called on the main
+ // thread: with the async versions iOS finished the tap off the main thread
+ // and SwiftUI's app delegate crashed ("Call must be made on main thread").
nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,
- didReceive response: UNNotificationResponse) async {
+ didReceive response: UNNotificationResponse,
+ withCompletionHandler completionHandler: @escaping () -> Void) {
+ nonisolated(unsafe) let done = completionHandler
let request = response.notification.request
- guard let fingerprint = PhoneLink.approvalFingerprint(in: request) else { return }
+ guard let fingerprint = PhoneLink.approvalFingerprint(in: request) else {
+ DispatchQueue.main.async { 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
- await Self.handleApproval(denied: denied, fingerprint: fingerprint, pillId: pillId)
+ Task { @MainActor in
+ await Self.handleApproval(denied: denied, fingerprint: fingerprint, pillId: pillId)
+ done()
+ }
}
@MainActor
@@ -69,22 +81,28 @@ final class PhoneAppDelegate: NSObject, UIApplicationDelegate, UNUserNotificatio
summary: summary ?? "Denied from the notification")
} else {
// Review, or a tap on the notification: open the command, Allow needs Face ID there.
- await link.refresh()
link.reviewFingerprint = fingerprint
+ Task { await link.refresh() }
}
}
// Show banners even when the app is open.
nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,
- willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
+ willPresent notification: UNNotification,
+ withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
+ nonisolated(unsafe) let done = completionHandler
// One banner per approval: skip the iCloud alert if the local one is already there.
let request = notification.request
- if let fingerprint = PhoneLink.approvalFingerprint(in: request),
- request.identifier != PhoneLink.approvalNotificationID(fingerprint) {
- let localID = PhoneLink.approvalNotificationID(fingerprint)
- await MainActor.run { PhoneLink.shared.noteICloudAlert(fingerprint) }
- if await PhoneLink.shownApprovals().contains(where: { $0.id == localID }) { return [] }
+ guard let fingerprint = PhoneLink.approvalFingerprint(in: request),
+ request.identifier != PhoneLink.approvalNotificationID(fingerprint) else {
+ DispatchQueue.main.async { done([.banner, .sound]) }
+ return
+ }
+ let localID = PhoneLink.approvalNotificationID(fingerprint)
+ Task { @MainActor in
+ PhoneLink.shared.noteICloudAlert(fingerprint)
+ let shown = await PhoneLink.shownApprovals().contains { $0.id == localID }
+ done(shown ? [] : [.banner, .sound])
}
- return [.banner, .sound]
}
}
diff --git a/NotchBuddy/Sources/Phone/HomeView.swift b/NotchBuddy/Sources/Phone/HomeView.swift
index 3bc2ce15..0ff7b80e 100644
--- a/NotchBuddy/Sources/Phone/HomeView.swift
+++ b/NotchBuddy/Sources/Phone/HomeView.swift
@@ -1,12 +1,13 @@
import SwiftUI
-/// Main screen: the notch on top, then every agent session from the Mac,
-/// most urgent first.
+/// Main screen: the notch on top, every agent session from the Mac (most
+/// urgent first), then every service Mochi.
struct HomeView: View {
let link: PhoneLink
+ @State private var path: [String] = []
var body: some View {
- NavigationStack {
+ NavigationStack(path: $path) {
ScrollView {
VStack(spacing: 16) {
NotchHeader(sessions: link.sessions, status: link.status)
@@ -28,6 +29,7 @@ struct HomeView: View {
.padding(.vertical, 6)
.background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))
}
+ ServicesList(services: link.services)
}
.padding(.horizontal, 16)
.padding(.bottom, 24)
@@ -35,7 +37,15 @@ struct HomeView: View {
.background(Color.black)
.refreshable { await link.refresh() }
.navigationDestination(for: String.self) { id in
- SessionDetailView(link: link, sessionId: id)
+ if PillCatalog.isSession(id) {
+ SessionDetailView(link: link, sessionId: id)
+ } else {
+ ServiceDetailView(link: link, pillId: id)
+ }
+ }
+ // A widget tile was tapped: open that Mochi.
+ .onOpenURL { url in
+ if let id = SharedSession.sessionId(from: url) { path = [id] }
}
.sheet(isPresented: Binding(get: { link.reviewFingerprint != nil },
set: { if !$0 { link.reviewFingerprint = nil } })) {
diff --git a/NotchBuddy/Sources/Phone/InstructionComposer.swift b/NotchBuddy/Sources/Phone/InstructionComposer.swift
new file mode 100644
index 00000000..a671075d
--- /dev/null
+++ b/NotchBuddy/Sources/Phone/InstructionComposer.swift
@@ -0,0 +1,207 @@
+import AVFoundation
+import Speech
+import SwiftUI
+
+/// Write or dictate an instruction for a Claude Code session; Face ID sends
+/// it to the Mac, which continues the conversation in the background.
+struct InstructionComposer: View {
+ let link: PhoneLink
+ let session: SessionItem
+
+ @State private var text = ""
+ @State private var sending = false
+ @State private var sentAt: Date?
+ @State private var error: String?
+ @State private var dictation = Dictation()
+ @FocusState private var focused: Bool
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ Text("Send to Claude").font(.subheadline.weight(.semibold)).foregroundStyle(.secondary)
+ if session.acceptsInstructions {
+ composer
+ status
+ } else {
+ Text("To continue this session from your iPhone, turn on \"Let my iPhone send instructions to Claude Code\" in Coucou's Settings on your Mac (GitHub version), then start a turn in VS Code.")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ }
+ }
+ .padding(16)
+ .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))
+ .onChange(of: dictation.transcript) { _, words in
+ if dictation.isRecording { text = dictation.prefix + words }
+ }
+ }
+
+ private var composer: some View {
+ HStack(alignment: .bottom, spacing: 8) {
+ TextField("Tell Claude what to do next…", text: $text, axis: .vertical)
+ .lineLimit(1...8)
+ .focused($focused)
+ .padding(.horizontal, 12)
+ .padding(.vertical, 9)
+ .background(Color(white: 0.16), in: RoundedRectangle(cornerRadius: 18))
+ Menu {
+ Picker("Dictation language", selection: $dictation.localeID) {
+ ForEach(Dictation.languages, id: \.self) { id in
+ Text(Locale.current.localizedString(forIdentifier: id) ?? id).tag(id)
+ }
+ }
+ } label: {
+ Text(Dictation.shortName(dictation.localeID))
+ .font(.caption2.weight(.bold))
+ .foregroundStyle(.secondary)
+ .frame(width: 26, height: 36)
+ }
+ Button {
+ Task { await dictation.toggle(startingFrom: text) }
+ } label: {
+ Image(systemName: dictation.isRecording ? "stop.circle.fill" : "mic.fill")
+ .font(.title3)
+ .foregroundStyle(dictation.isRecording ? Color.red : Color.secondary)
+ .frame(width: 36, height: 36)
+ }
+ Button {
+ Task { await send() }
+ } label: {
+ Image(systemName: "arrow.up.circle.fill")
+ .font(.system(size: 32))
+ }
+ .disabled(text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || sending)
+ }
+ }
+
+ @ViewBuilder private var status: some View {
+ if let error {
+ Text(error).font(.caption).foregroundStyle(.red)
+ } else if let sentAt {
+ if session.updatedAt > sentAt && (session.isWorking || session.state == .thinking) {
+ Label("Your Mac started it", systemImage: "checkmark.circle.fill")
+ .font(.caption).foregroundStyle(.green)
+ } else {
+ Label("Sent. Your Mac picks it up within 15 s.", systemImage: "paperplane.fill")
+ .font(.caption).foregroundStyle(.secondary)
+ }
+ } else {
+ Text("Face ID sends it. It continues this conversation on your Mac, in its folder.")
+ .font(.caption).foregroundStyle(.secondary)
+ }
+ }
+
+ private func send() async {
+ let instruction = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !instruction.isEmpty else { return }
+ dictation.stop()
+ focused = false
+ sending = true
+ defer { sending = false }
+ error = nil
+ guard await OwnerCheck.confirm(reason: "Send this instruction to Claude Code on your Mac") else {
+ error = "Face ID didn't confirm. Nothing was sent."
+ return
+ }
+ if await link.sendInstruction(instruction, pillId: session.id) {
+ sentAt = .now
+ text = ""
+ } else {
+ error = link.lastPong ?? "Couldn't reach iCloud."
+ }
+ }
+}
+
+/// Speech to text on the iPhone (on-device when available). Not main-actor
+/// bound: the audio tap and the recognizer call back on their own threads;
+/// the published values are only set on the main actor.
+@Observable
+final class Dictation: @unchecked Sendable {
+ var isRecording = false
+ var transcript = ""
+ /// The language heard, chosen next to the mic and remembered.
+ var localeID: String = UserDefaults.standard.string(forKey: "dictationLocale")
+ ?? Locale.preferredLanguages.first ?? "en-US" {
+ didSet { UserDefaults.standard.set(localeID, forKey: "dictationLocale") }
+ }
+
+ /// The iPhone's languages first, then French and English.
+ static var languages: [String] {
+ var ids: [String] = []
+ for id in Locale.preferredLanguages + ["fr-FR", "en-US"] where !ids.contains(id) {
+ if SFSpeechRecognizer(locale: Locale(identifier: id)) != nil { ids.append(id) }
+ }
+ return ids
+ }
+
+ static func shortName(_ id: String) -> String {
+ String(Locale(identifier: id).language.languageCode?.identifier.uppercased().prefix(2) ?? "?")
+ }
+ /// What was typed before dictating, kept in front of the words.
+ var prefix = ""
+
+ @ObservationIgnored private let engine = AVAudioEngine()
+ @ObservationIgnored private var request: SFSpeechAudioBufferRecognitionRequest?
+ @ObservationIgnored private var task: SFSpeechRecognitionTask?
+
+ @MainActor func toggle(startingFrom text: String) async {
+ if isRecording { stop(); return }
+ guard await Self.authorized() else { return }
+ prefix = text.isEmpty || text.hasSuffix(" ") ? text : text + " "
+ transcript = ""
+ start()
+ }
+
+ /// Not main-actor bound, so the audio and speech callbacks made here don't
+ /// inherit the main actor (they run on their own threads).
+ nonisolated private func start() {
+ guard let recognizer = SFSpeechRecognizer(locale: Locale(identifier: localeID)) ?? SFSpeechRecognizer(),
+ recognizer.isAvailable else { return }
+ let request = SFSpeechAudioBufferRecognitionRequest()
+ request.shouldReportPartialResults = true
+ if recognizer.supportsOnDeviceRecognition { request.requiresOnDeviceRecognition = true }
+ do {
+ let session = AVAudioSession.sharedInstance()
+ try session.setCategory(.record, mode: .measurement, options: .duckOthers)
+ try session.setActive(true, options: .notifyOthersOnDeactivation)
+ let input = engine.inputNode
+ input.installTap(onBus: 0, bufferSize: 1024, format: input.outputFormat(forBus: 0)) { buffer, _ in
+ request.append(buffer)
+ }
+ engine.prepare()
+ try engine.start()
+ } catch {
+ engine.inputNode.removeTap(onBus: 0)
+ return
+ }
+ self.request = request
+ isRecording = true
+ task = recognizer.recognitionTask(with: request) { [weak self] result, error in
+ let words = result?.bestTranscription.formattedString
+ let done = error != nil || (result?.isFinal ?? false)
+ Task { @MainActor in
+ guard let self else { return }
+ if let words { self.transcript = words }
+ if done { self.stop() }
+ }
+ }
+ }
+
+ @MainActor func stop() {
+ guard isRecording else { return }
+ engine.stop()
+ engine.inputNode.removeTap(onBus: 0)
+ request?.endAudio()
+ task?.cancel()
+ request = nil
+ task = nil
+ isRecording = false
+ try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
+ }
+
+ private static func authorized() async -> Bool {
+ let speech = await withCheckedContinuation { continuation in
+ SFSpeechRecognizer.requestAuthorization { continuation.resume(returning: $0 == .authorized) }
+ }
+ guard speech else { return false }
+ return await AVAudioApplication.requestRecordPermission()
+ }
+}
diff --git a/NotchBuddy/Sources/Phone/LastTurnView.swift b/NotchBuddy/Sources/Phone/LastTurnView.swift
new file mode 100644
index 00000000..a028ff96
--- /dev/null
+++ b/NotchBuddy/Sources/Phone/LastTurnView.swift
@@ -0,0 +1,303 @@
+import SwiftUI
+
+/// The last turn of a session: your prompt, what the agent did, the files it
+/// changed (tap for the diff) and its answer.
+struct LastTurnView: View {
+ let turn: TurnSnapshot
+ let working: Bool
+ @State private var showAllActions = false
+
+ private let collapsedCount = 12
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 16) {
+ if !turn.prompt.isEmpty { promptCard }
+ if !turn.actions.isEmpty { actionsCard }
+ if !turn.files.isEmpty { filesCard }
+ answerCard
+ }
+ }
+
+ // MARK: Prompt
+
+ /// A background task finishing reaches Claude as a "<task-notification>"
+ /// prompt: shown by its summary rather than as raw XML.
+ private var taskSummary: String? {
+ guard turn.prompt.hasPrefix("<task-notification>") else { return nil }
+ if let start = turn.prompt.range(of: "<summary>"), let end = turn.prompt.range(of: "</summary>"),
+ start.upperBound <= end.lowerBound {
+ return String(turn.prompt[start.upperBound..<end.lowerBound])
+ }
+ return "A background task finished"
+ }
+
+ private var promptCard: some View {
+ VStack(alignment: .trailing, spacing: 6) {
+ if let summary = taskSummary {
+ ExpandableText(text: turn.prompt, collapsedLines: 0, title: summary, monospaced: true)
+ .padding(12)
+ .background(Color(white: 0.16), in: RoundedRectangle(cornerRadius: 16))
+ } else {
+ ExpandableText(text: turn.prompt, collapsedLines: 6)
+ .padding(12)
+ .background(Color.accentColor.opacity(0.25), in: RoundedRectangle(cornerRadius: 16))
+ }
+ Text("\(taskSummary == nil ? "You" : "Background task") · \(turn.startedAt.formatted(date: .omitted, time: .shortened))")
+ .font(.caption2)
+ .foregroundStyle(.tertiary)
+ }
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ }
+
+ // MARK: Actions
+
+ private var actionsCard: some View {
+ let actions = showAllActions ? turn.actions : Array(turn.actions.prefix(collapsedCount))
+ return card(title: "What it did · \(turn.actions.count)") {
+ VStack(alignment: .leading, spacing: 0) {
+ ForEach(Array(actions.enumerated()), id: \.offset) { _, action in
+ ActionRow(action: action, file: action.fileIndex.flatMap { turn.files.indices.contains($0) ? turn.files[$0] : nil })
+ }
+ if turn.actions.count > collapsedCount {
+ Button(showAllActions ? "Show less" : "Show all \(turn.actions.count)") {
+ withAnimation { showAllActions.toggle() }
+ }
+ .font(.footnote.weight(.semibold))
+ .padding(.top, 8)
+ }
+ }
+ }
+ }
+
+ // MARK: Files
+
+ private var filesCard: some View {
+ card(title: "Files changed · \(turn.files.count)") {
+ VStack(spacing: 0) {
+ ForEach(Array(turn.files.enumerated()), id: \.offset) { index, file in
+ NavigationLink {
+ FileDiffView(file: file)
+ } label: {
+ HStack(spacing: 10) {
+ Image(systemName: file.isNew ? "doc.badge.plus" : "doc.text")
+ .foregroundStyle(.secondary)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(file.name).font(.callout.weight(.semibold))
+ Text(file.path).font(.caption2).foregroundStyle(.tertiary).lineLimit(1).truncationMode(.head)
+ }
+ Spacer(minLength: 6)
+ Text("+\(file.added)").font(.caption.monospacedDigit()).foregroundStyle(.green)
+ Text("−\(file.removed)").font(.caption.monospacedDigit()).foregroundStyle(.red)
+ Image(systemName: "chevron.right").font(.caption2).foregroundStyle(.tertiary)
+ }
+ .padding(.vertical, 8)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ if index < turn.files.count - 1 { Divider() }
+ }
+ }
+ }
+ }
+
+ // MARK: Answer
+
+ @ViewBuilder private var answerCard: some View {
+ if !turn.finalMessage.isEmpty {
+ card(title: "Claude's answer") {
+ ExpandableText(text: turn.finalMessage, collapsedLines: 10, markdown: true)
+ }
+ } else if working || turn.endedAt == nil {
+ card(title: "Claude's answer") {
+ HStack(spacing: 8) {
+ ProgressView()
+ Text("Still working…").font(.callout).foregroundStyle(.secondary)
+ }
+ }
+ }
+ }
+
+ private func card<Content: View>(title: String, @ViewBuilder content: () -> Content) -> some View {
+ VStack(alignment: .leading, spacing: 10) {
+ Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(.secondary)
+ content()
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(16)
+ .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))
+ }
+}
+
+/// One tool call; a command opens to show what it printed.
+private struct ActionRow: View {
+ let action: TurnAction
+ let file: TurnFile?
+ @State private var open = false
+
+ private var icon: String {
+ switch action.tool {
+ case "Bash": "terminal"
+ case "Read": "doc.text.magnifyingglass"
+ case "Edit", "MultiEdit": "pencil"
+ case "Write": "doc.badge.plus"
+ case "Grep", "Glob": "magnifyingglass"
+ case "WebFetch", "WebSearch": "globe"
+ case "Task", "Agent": "person.2"
+ case "TodoWrite": "checklist"
+ default: "wrench.and.screwdriver"
+ }
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ Button {
+ if !action.output.isEmpty { withAnimation(.easeOut(duration: 0.2)) { open.toggle() } }
+ } label: {
+ HStack(alignment: .firstTextBaseline, spacing: 10) {
+ Image(systemName: action.failed ? "exclamationmark.triangle.fill" : icon)
+ .font(.footnote)
+ .foregroundStyle(action.failed ? Color.red : Color.secondary)
+ .frame(width: 18)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(action.tool).font(.caption.weight(.semibold)).foregroundStyle(.secondary)
+ Text(file?.name ?? action.summary)
+ .font(action.tool == "Bash" ? .footnote.monospaced() : .footnote)
+ .foregroundStyle(.primary)
+ .lineLimit(open ? nil : 2)
+ .multilineTextAlignment(.leading)
+ }
+ Spacer(minLength: 4)
+ if let file {
+ Text("+\(file.added) −\(file.removed)").font(.caption2.monospacedDigit()).foregroundStyle(.secondary)
+ } else if !action.output.isEmpty {
+ Image(systemName: open ? "chevron.up" : "chevron.down").font(.caption2).foregroundStyle(.tertiary)
+ }
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ if open {
+ ScrollView(.horizontal, showsIndicators: false) {
+ Text(action.output)
+ .font(.caption2.monospaced())
+ .foregroundStyle(.secondary)
+ .textSelection(.enabled)
+ .padding(10)
+ }
+ .background(Color(white: 0.06), in: RoundedRectangle(cornerRadius: 10))
+ .padding(.leading, 28)
+ }
+ }
+ .padding(.vertical, 6)
+ }
+}
+
+/// A changed file, line by line: removed in red, added in green.
+struct FileDiffView: View {
+ let file: TurnFile
+
+ var body: some View {
+ ScrollView([.vertical, .horizontal]) {
+ VStack(alignment: .leading, spacing: 0) {
+ ForEach(Array(file.lines.enumerated()), id: \.offset) { _, line in
+ row(line)
+ }
+ if file.truncated {
+ Text("Some lines were left out to keep it light.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .padding(12)
+ }
+ }
+ .padding(.vertical, 8)
+ }
+ .background(Color.black)
+ .navigationTitle(file.name)
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .topBarTrailing) {
+ HStack(spacing: 6) {
+ Text("+\(file.added)").foregroundStyle(.green)
+ Text("−\(file.removed)").foregroundStyle(.red)
+ }
+ .font(.footnote.monospacedDigit().weight(.semibold))
+ }
+ }
+ }
+
+ @ViewBuilder private func row(_ line: TurnDiffLine) -> some View {
+ switch line.kind {
+ case .gap:
+ Text("⋯")
+ .font(.caption.monospaced())
+ .foregroundStyle(.tertiary)
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+ case .added, .removed, .context:
+ HStack(spacing: 0) {
+ Text(line.kind == .added ? "+" : line.kind == .removed ? "−" : " ")
+ .frame(width: 18)
+ .foregroundStyle(line.kind == .added ? Color.green : line.kind == .removed ? Color.red : Color.secondary)
+ Text(line.text.isEmpty ? " " : line.text)
+ .foregroundStyle(line.kind == .context ? Color.secondary : Color.primary)
+ .fixedSize(horizontal: true, vertical: false)
+ .padding(.trailing, 16)
+ }
+ .font(.caption.monospaced())
+ .padding(.vertical, 1)
+ .padding(.leading, 6)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(line.kind == .added ? Color.green.opacity(0.14)
+ : line.kind == .removed ? Color.red.opacity(0.14) : Color.clear)
+ }
+ }
+}
+
+/// Long text folded to a few lines, with "Show more" / "Show less".
+/// collapsedLines 0 shows only the title until opened.
+struct ExpandableText: View {
+ let text: String
+ var collapsedLines: Int
+ var title: String? = nil
+ var monospaced = false
+ var markdown = false
+ @State private var open = false
+
+ /// Short texts are shown whole, without a button.
+ private var isLong: Bool {
+ collapsedLines == 0 || text.count > collapsedLines * 60 || text.filter(\.isNewline).count >= collapsedLines
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ if let title {
+ Label(title, systemImage: "gearshape.2")
+ .font(.callout.weight(.semibold))
+ }
+ if open || collapsedLines > 0 {
+ content
+ .lineLimit(open || !isLong ? nil : collapsedLines)
+ }
+ if isLong {
+ Button(open ? "Show less" : (collapsedLines == 0 ? "Show details" : "Show more")) {
+ withAnimation(.easeOut(duration: 0.2)) { open.toggle() }
+ }
+ .font(.footnote.weight(.semibold))
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ @ViewBuilder private var content: some View {
+ if markdown {
+ Text(LocalizedStringKey(text))
+ .font(.callout)
+ .textSelection(.enabled)
+ } else {
+ Text(text)
+ .font(monospaced ? .caption.monospaced() : .callout)
+ .foregroundStyle(monospaced ? Color.secondary : Color.primary)
+ .textSelection(.enabled)
+ }
+ }
+}
diff --git a/NotchBuddy/Sources/Phone/PhoneLink.swift b/NotchBuddy/Sources/Phone/PhoneLink.swift
index daa58dac..a8052790 100644
--- a/NotchBuddy/Sources/Phone/PhoneLink.swift
+++ b/NotchBuddy/Sources/Phone/PhoneLink.swift
@@ -27,6 +27,8 @@ struct SessionItem: Identifiable {
let needsApproval: Bool
let approvalCommand: String
let approvalFingerprint: String
+ /// The Mac runs instructions sent from here for this session (GitHub build, switch on).
+ let acceptsInstructions: Bool
let question: String
let finalLine: String
let cwd: String
@@ -43,6 +45,7 @@ struct SessionItem: Identifiable {
needsApproval = record["needsApproval"] as? Bool ?? false
approvalCommand = record.encryptedValues["approvalCommand"] as? String ?? ""
approvalFingerprint = record["approvalFingerprint"] as? String ?? ""
+ acceptsInstructions = record["acceptsInstructions"] as? Bool ?? false
question = record.encryptedValues["question"] as? String ?? ""
finalLine = record.encryptedValues["finalLine"] as? String ?? ""
cwd = record.encryptedValues["cwd"] as? String ?? ""
@@ -77,6 +80,10 @@ final class PhoneLink {
var status: Status = .starting
var pings: [PingItem] = []
var sessions: [SessionItem] = []
+ /// Service Mochi (GitHub, Stripe…) the Mac publishes, by pill ID.
+ var services: [String: ServiceSnapshot] = [:]
+ /// The last turn of each session (prompt, actions, diffs, answer), by pill ID.
+ var turns: [String: TurnSnapshot] = [:]
var lastPong: String?
var pushError: String?
var notificationsAllowed: Bool?
@@ -193,6 +200,15 @@ final class PhoneLink {
sessions.removeAll { "session-\($0.id)" == deletion.recordID.recordName }
gotNew = true
}
+ for deletion in changes.deletions where deletion.recordType == TurnSnapshot.recordType {
+ if let id = TurnSnapshot.pillId(fromRecordName: deletion.recordID.recordName) { turns[id] = nil }
+ }
+ for deletion in changes.deletions where deletion.recordType == ServiceSnapshot.recordType {
+ if let id = ServiceSnapshot.pillId(fromRecordName: deletion.recordID.recordName) {
+ services[id] = nil
+ gotNew = true
+ }
+ }
changeToken = changes.changeToken
more = changes.moreComing
}
@@ -213,8 +229,22 @@ final class PhoneLink {
}
private func add(_ record: CKRecord) -> Bool {
+ 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 }
+ turns[turn.pillId] = turn
+ return false // nothing for the widgets
+ }
+ if record.recordType == ServiceSnapshot.recordType {
+ guard let payload = record.encryptedValues["payload"] as? String,
+ let snapshot = try? JSONDecoder().decode(ServiceSnapshot.self, from: Data(payload.utf8)) else { return false }
+ services[snapshot.pillId] = snapshot
+ return true
+ }
if record.recordType == "Session" {
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 }
sessions.removeAll { $0.id == item.id }
sessions.append(item)
sessions.sort { $0.updatedAt > $1.updatedAt }
@@ -312,6 +342,26 @@ final class PhoneLink {
return note?.recordFields?["fingerprint"] as? String
}
+ // MARK: Instructions (step B)
+
+ /// Sends an instruction to continue a session on the Mac. The Mac takes it
+ /// within ~15 s and deletes it; it never runs twice.
+ func sendInstruction(_ text: String, pillId: String) async -> Bool {
+ let record = CKRecord(recordType: "Instruction",
+ recordID: CKRecord.ID(recordName: "instruction-\(UUID().uuidString)", zoneID: Self.zoneID))
+ record["pillId"] = pillId
+ record["createdAt"] = Date()
+ record["deviceName"] = UIDevice.current.name
+ record.encryptedValues["text"] = text
+ do {
+ _ = try await database.save(record)
+ return true
+ } catch {
+ lastPong = "Instruction failed: \(error.localizedDescription)"
+ return false
+ }
+ }
+
// MARK: Decisions (step 7)
/// Decisions taken on this iPhone, newest first.
@@ -344,7 +394,7 @@ final class PhoneLink {
/// Hands the sessions to the widgets and asks them to redraw.
private func updateWidgets() {
- SharedSessions.save(sessions.map(\.shared))
+ SharedSessions.save(sessions.map(\.shared) + services.values.map(\.shared))
WidgetCenter.shared.reloadAllTimelines()
}
diff --git a/NotchBuddy/Sources/Phone/ServiceStatus.swift b/NotchBuddy/Sources/Phone/ServiceStatus.swift
new file mode 100644
index 00000000..0546181a
--- /dev/null
+++ b/NotchBuddy/Sources/Phone/ServiceStatus.swift
@@ -0,0 +1,58 @@
+import SwiftUI
+
+// How a service Mochi reads on the iPhone: its dot color, a short status, and
+// what the widgets get.
+
+extension ServiceTone {
+ var color: Color {
+ switch self {
+ case .ok: .green
+ case .warning: .orange
+ case .error: .red
+ case .info: Color(red: 0.4, green: 0.7, blue: 1)
+ case .idle: .secondary
+ }
+ }
+
+ var label: String {
+ switch self {
+ case .ok: "all good"
+ case .warning: "needs a look"
+ case .error: "something failed"
+ case .info: "news"
+ case .idle: "quiet"
+ }
+ }
+
+ /// The Mochi face for this tone.
+ var botState: BotState {
+ switch self {
+ case .ok: .finished
+ case .error: .error
+ case .warning: .question
+ case .info, .idle: .idle
+ }
+ }
+}
+
+extension ServiceSnapshot {
+ var name: String { PillCatalog.definition(for: pillId)?.name ?? pillId }
+ var color: String { PillCatalog.definition(for: pillId)?.color ?? "#C0C4CC" }
+
+ /// What the widgets get (SharedSessions).
+ var shared: SharedSession {
+ let tone: SharedSession.Tone
+ let urgency: Int
+ switch self.tone {
+ case .error: tone = .error; urgency = 2
+ case .warning: tone = .warning; urgency = 3
+ case .ok: tone = .done; urgency = 4
+ case .info: tone = .info; urgency = 4
+ case .idle: tone = .idle; urgency = 6
+ }
+ return SharedSession(id: pillId, title: name, agent: name, color: color,
+ state: (self.tone == .ok ? BotState.idle : self.tone.botState).rawValue,
+ statusText: self.tone.label, tone: tone, urgency: urgency,
+ stepIndex: 0, stepCount: 0, currentStep: headline, updatedAt: updatedAt)
+ }
+}
diff --git a/NotchBuddy/Sources/Phone/ServiceViews.swift b/NotchBuddy/Sources/Phone/ServiceViews.swift
new file mode 100644
index 00000000..d6ad1fc6
--- /dev/null
+++ b/NotchBuddy/Sources/Phone/ServiceViews.swift
@@ -0,0 +1,217 @@
+import SwiftUI
+
+/// Every service Mochi, connected on the Mac or not.
+struct ServicesList: View {
+ let services: [String: ServiceSnapshot]
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Services")
+ .font(.footnote.weight(.semibold))
+ .foregroundStyle(.secondary)
+ .padding(.leading, 6)
+ VStack(spacing: 0) {
+ let ids = PillCatalog.phoneServices
+ ForEach(ids, id: \.self) { id in
+ NavigationLink(value: id) {
+ ServiceRow(pillId: id, snapshot: services[id])
+ }
+ .buttonStyle(.plain)
+ if id != ids.last {
+ Divider().padding(.leading, 64)
+ }
+ }
+ }
+ .padding(.vertical, 6)
+ .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))
+ }
+ }
+}
+
+struct ServiceRow: View {
+ let pillId: String
+ let snapshot: ServiceSnapshot?
+
+ private var pill: PillDefinition? { PillCatalog.definition(for: pillId) }
+
+ var body: some View {
+ HStack(spacing: 12) {
+ ServiceMochi(pillId: pillId, tone: snapshot?.tone)
+ .frame(width: 40, height: 40)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(pill?.name ?? pillId)
+ .font(.body.weight(.semibold))
+ .lineLimit(1)
+ Text(snapshot?.headline ?? "Not connected on your Mac")
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ }
+ Spacer(minLength: 8)
+ if let snapshot {
+ VStack(alignment: .trailing, spacing: 2) {
+ HStack(spacing: 5) {
+ Circle().fill(snapshot.tone.color).frame(width: 8, height: 8)
+ Text(snapshot.tone.label)
+ .font(.subheadline)
+ .foregroundStyle(snapshot.tone == .idle ? Color.secondary : snapshot.tone.color)
+ }
+ Text(snapshot.updatedAt, style: .relative)
+ .font(.caption2)
+ .foregroundStyle(.tertiary)
+ }
+ }
+ }
+ .padding(.horizontal, 14)
+ .padding(.vertical, 10)
+ .opacity(snapshot == nil ? 0.55 : 1)
+ .contentShape(Rectangle())
+ }
+}
+
+/// A service Mochi in his own color, like the little ones in the Mac's notch.
+struct ServiceMochi: View {
+ let pillId: String
+ let tone: ServiceTone?
+ var corner: CGFloat = 11
+
+ var body: some View {
+ let color = PillCatalog.definition(for: pillId)?.color ?? "#C0C4CC"
+ MochiStill(state: tone?.botState ?? .sleeping, bodyHex: color)
+ .padding(4)
+ .background(Color(white: 0.16), in: RoundedRectangle(cornerRadius: corner))
+ }
+}
+
+/// One service: why its dot has that color, then what the Mac last fetched.
+struct ServiceDetailView: View {
+ let link: PhoneLink
+ let pillId: String
+
+ private var snapshot: ServiceSnapshot? { link.services[pillId] }
+ private var pill: PillDefinition? { PillCatalog.definition(for: pillId) }
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 16) {
+ header
+ if let snapshot {
+ reasonCard(snapshot)
+ ForEach(Array(snapshot.sections.enumerated()), id: \.offset) { _, section in
+ sectionCard(section)
+ }
+ } else {
+ notConnected
+ }
+ }
+ .padding(16)
+ }
+ .background(Color.black)
+ .navigationTitle(pill?.name ?? "Service")
+ .navigationBarTitleDisplayMode(.inline)
+ .refreshable { await link.refresh() }
+ }
+
+ private var header: some View {
+ HStack(spacing: 16) {
+ ServiceMochi(pillId: pillId, tone: snapshot?.tone, corner: 22)
+ .frame(width: 84, height: 84)
+ VStack(alignment: .leading, spacing: 4) {
+ Text(pill?.name ?? pillId).font(.headline)
+ if let snapshot {
+ Text(snapshot.headline)
+ .font(.subheadline.weight(.semibold))
+ .foregroundStyle(snapshot.tone == .idle ? Color.secondary : snapshot.tone.color)
+ Text(snapshot.updatedAt, style: .relative)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ } else {
+ Text("Not connected").font(.subheadline).foregroundStyle(.secondary)
+ }
+ }
+ Spacer(minLength: 0)
+ }
+ }
+
+ private func reasonCard(_ snapshot: ServiceSnapshot) -> some View {
+ HStack(alignment: .top, spacing: 12) {
+ Circle()
+ .fill(snapshot.tone.color)
+ .frame(width: 12, height: 12)
+ .padding(.top, 4)
+ VStack(alignment: .leading, spacing: 4) {
+ Text(snapshot.tone.label.capitalized)
+ .font(.subheadline.weight(.semibold))
+ .foregroundStyle(snapshot.tone == .idle ? Color.secondary : snapshot.tone.color)
+ Text(snapshot.reason)
+ .font(.callout)
+ .textSelection(.enabled)
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(16)
+ .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))
+ .overlay {
+ if snapshot.tone == .error || snapshot.tone == .warning {
+ RoundedRectangle(cornerRadius: 22).strokeBorder(snapshot.tone.color.opacity(0.7), lineWidth: 1.5)
+ }
+ }
+ }
+
+ private func sectionCard(_ section: ServiceSection) -> some View {
+ VStack(alignment: .leading, spacing: 10) {
+ Text(section.title).font(.subheadline.weight(.semibold)).foregroundStyle(.secondary)
+ ForEach(Array(section.items.enumerated()), id: \.offset) { index, item in
+ itemRow(item)
+ if index < section.items.count - 1 { Divider() }
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(16)
+ .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))
+ }
+
+ @ViewBuilder private func itemRow(_ item: ServiceItem) -> some View {
+ let row = HStack(alignment: .firstTextBaseline, spacing: 10) {
+ Circle()
+ .fill(item.tone.color)
+ .frame(width: 8, height: 8)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(item.title)
+ .font(.callout)
+ .foregroundStyle(.primary)
+ .lineLimit(2)
+ if !item.detail.isEmpty {
+ Text(item.detail)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(3)
+ }
+ }
+ Spacer(minLength: 6)
+ if let date = item.date {
+ Text(date, format: .relative(presentation: .named))
+ .font(.caption2)
+ .foregroundStyle(.tertiary)
+ }
+ }
+ if let link = item.url.flatMap(URL.init(string:)), link.scheme == "https" {
+ Link(destination: link) { row }
+ } else {
+ row
+ }
+ }
+
+ private var notConnected: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Connect \(pill?.name ?? "it") on your Mac")
+ .font(.subheadline.weight(.semibold))
+ Text("Add its key in Coucou's Settings on your Mac and keep the iPhone switch on (Settings → General → iPhone). What the Mac sees shows up here: no key is stored on your iPhone.")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(16)
+ .background(Color(white: 0.11), in: RoundedRectangle(cornerRadius: 22))
+ }
+}
diff --git a/NotchBuddy/Sources/Phone/SessionDetailView.swift b/NotchBuddy/Sources/Phone/SessionDetailView.swift
index 00761187..e5e989a0 100644
--- a/NotchBuddy/Sources/Phone/SessionDetailView.swift
+++ b/NotchBuddy/Sources/Phone/SessionDetailView.swift
@@ -6,6 +6,7 @@ struct SessionDetailView: View {
let sessionId: String
private var session: SessionItem? { link.sessions.first { $0.id == sessionId } }
+ private var turn: TurnSnapshot? { link.turns[sessionId] }
var body: some View {
ScrollView {
@@ -18,8 +19,15 @@ struct SessionDetailView: View {
waiting(title: "Question", text: session.question, monospaced: false, color: .cyan,
footnote: "Answer on your Mac for now.")
}
- if !session.steps.isEmpty { plan(session) }
- if !session.finalLine.isEmpty {
+ if session.id == "integration_claude" || session.id == "agent_cursor" {
+ InstructionComposer(link: link, session: session)
+ }
+ if let turn {
+ LastTurnView(turn: turn, working: session.isWorking)
+ } else if !session.steps.isEmpty {
+ plan(session)
+ }
+ if turn == nil, !session.finalLine.isEmpty {
card(title: "Last message") {
Text(session.finalLine)
.font(.callout)
@@ -36,6 +44,14 @@ struct SessionDetailView: View {
}
}
.padding(16)
+ } 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)
+ }
+ .padding(16)
} else {
Text("This session ended on your Mac.")
.foregroundStyle(.secondary)
diff --git a/NotchBuddy/Sources/Phone/SharedSessions.swift b/NotchBuddy/Sources/Phone/SharedSessions.swift
index 00c84bbd..b75ed977 100644
--- a/NotchBuddy/Sources/Phone/SharedSessions.swift
+++ b/NotchBuddy/Sources/Phone/SharedSessions.swift
@@ -19,10 +19,34 @@ struct SharedSession: Codable, Identifiable, Hashable, Sendable {
enum Tone: String, Codable, Sendable {
case waiting, question, error, working, done, idle
+ /// Services: something to look at (CI running, review asked), or just news.
+ case warning, info
}
var isWaitingForYou: Bool { tone == .waiting || tone == .question }
var isWorking: Bool { tone == .working }
+
+ /// Opens one Mochi in the app, a session or a service (widgets link here).
+ static func url(for id: String) -> URL {
+ URL(string: "coucou://mochi/\(id.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? id)")!
+ }
+
+ /// The pill id in a coucou://mochi/<id> link (coucou://session/<id> from builds before).
+ static func sessionId(from url: URL) -> String? {
+ guard url.scheme == "coucou", url.host == "mochi" || url.host == "session" else { return nil }
+ let id = url.path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
+ return id.isEmpty ? nil : id
+ }
+
+ /// Agents before services when equally urgent: the team shows who codes first.
+ var categoryRank: Int {
+ switch PillCatalog.definition(for: id)?.category {
+ case .workspace: 0
+ case .agent: 1
+ case .service: 2
+ default: 3
+ }
+ }
}
enum SharedSessions {
@@ -43,7 +67,9 @@ enum SharedSessions {
static func load() -> [SharedSession] {
guard let url = fileURL, let data = try? Data(contentsOf: url),
let sessions = try? JSONDecoder().decode([SharedSession].self, from: data) else { return [] }
- return sessions.sorted { ($0.urgency, $1.updatedAt) < ($1.urgency, $0.updatedAt) }
+ return sessions.sorted {
+ ($0.urgency, $0.categoryRank, $1.updatedAt) < ($1.urgency, $1.categoryRank, $0.updatedAt)
+ }
}
}
diff --git a/NotchBuddy/Sources/Widgets/CoucouWidgets.swift b/NotchBuddy/Sources/Widgets/CoucouWidgets.swift
index 54bb2f48..abc54530 100644
--- a/NotchBuddy/Sources/Widgets/CoucouWidgets.swift
+++ b/NotchBuddy/Sources/Widgets/CoucouWidgets.swift
@@ -21,6 +21,8 @@ struct CoucouWidgetBundle: WidgetBundle {
struct SessionsEntry: TimelineEntry {
let date: Date
let sessions: [SharedSession] // most urgent first
+ /// Changes every minute so idle Mochi look around (MochiPose).
+ var tick: Int = 0
}
struct SessionsProvider: TimelineProvider {
@@ -34,8 +36,16 @@ struct SessionsProvider: TimelineProvider {
}
func getTimeline(in context: Context, completion: @escaping (Timeline<SessionsEntry>) -> Void) {
- // No polling: the app calls WidgetCenter.reloadAllTimelines() on every change.
- completion(Timeline(entries: [SessionsEntry(date: .now, sessions: SharedSessions.load())], policy: .never))
+ // The sessions come from the app, which calls reloadAllTimelines() on
+ // every change. The entries only give idle Mochi a new pose each
+ // minute for an hour; no network, nothing read again.
+ let sessions = SharedSessions.load()
+ let start = Date.now
+ let base = Int(start.timeIntervalSince1970 / 60)
+ let entries = (0..<60).map { minute in
+ SessionsEntry(date: start.addingTimeInterval(Double(minute) * 60), sessions: sessions, tick: base + minute)
+ }
+ completion(Timeline(entries: entries, policy: .atEnd))
}
}
@@ -54,8 +64,8 @@ struct SoloWidget: Widget {
struct TeamWidget: Widget {
var body: some WidgetConfiguration {
- StaticConfiguration(kind: "CoucouTeam", provider: SessionsProvider()) { entry in
- TeamView(sessions: Array(entry.sessions.prefix(4)))
+ AppIntentConfiguration(kind: "CoucouTeam", intent: TeamConfiguration.self, provider: TeamProvider()) { entry in
+ TeamView(sessions: entry.sessions, picks: entry.picks, tick: entry.tick)
}
.configurationDisplayName("Team")
.description("Up to four agents at a glance.")
@@ -96,6 +106,8 @@ extension SharedSession {
case .question: .cyan
case .error: .red
case .done: .green
+ case .warning: .orange
+ case .info: Color(red: 0.4, green: 0.7, blue: 1)
case .working, .idle: .white.opacity(0.7)
}
}
@@ -117,7 +129,7 @@ struct SoloView: View {
var body: some View {
VStack(alignment: .leading, spacing: 4) {
- MochiStill(state: session?.botState ?? .sleeping)
+ WidgetMochi(state: session?.botState ?? .sleeping)
.frame(width: 56, height: 56)
Spacer(minLength: 0)
if let session {
@@ -152,6 +164,9 @@ struct SoloView: View {
struct TeamView: View {
let sessions: [SharedSession]
+ /// The Mochi picked for each spot in the widget's settings, nil = automatic.
+ var picks: [String?] = [nil, nil, nil, nil]
+ var tick: Int = 0
var body: some View {
Grid(horizontalSpacing: 8, verticalSpacing: 8) {
@@ -161,20 +176,104 @@ struct TeamView: View {
.containerBackground(for: .widget) { Color(white: 0.08) }
}
+ /// The picked Mochi in their spots, then the most urgent ones from the
+ /// Mac, then the team's regulars, so the four spots are always taken.
+ private var team: [SharedSession] {
+ let chosen = Set(picks.compactMap { $0 })
+ var automatic = sessions.filter { !chosen.contains($0.id) }
+ for id in Self.regulars where !chosen.contains(id) && !automatic.contains(where: { $0.id == id }) {
+ if let filler = SharedSession.regular(id: id) { automatic.append(filler) }
+ }
+ var queue = automatic[...]
+ return (0..<4).compactMap { spot -> SharedSession? in
+ if spot < picks.count, let id = picks[spot] {
+ return sessions.first { $0.id == id } ?? SharedSession.regular(id: id)
+ }
+ return queue.popFirst()
+ }
+ }
+
+ /// Who fills the free spots, in this order.
+ static let regulars = ["integration_github", "integration_stripe", "integration_vercel", "integration_resend",
+ "integration_calcom", "integration_n8n", "integration_notion", "agent_codex"]
+
@ViewBuilder private func tile(_ index: Int) -> some View {
- if sessions.indices.contains(index) {
- let session = sessions[index]
- MochiStill(state: session.botState)
- .padding(8)
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Color.mochiTile(hex: session.color), in: RoundedRectangle(cornerRadius: 16))
+ let team = team
+ if team.indices.contains(index) {
+ let member = team[index]
+ // A tap opens that Mochi in the app.
+ Link(destination: SharedSession.url(for: member.id)) {
+ TeamTile(session: member, tick: tick)
+ }
} else {
- RoundedRectangle(cornerRadius: 16)
- .fill(Color.white.opacity(0.06))
+ EmptyTeamTile(tick: tick, slot: index)
+ }
+ }
+}
+
+/// One Mochi of the team: his face, his name, and a dot for his state.
+struct TeamTile: View {
+ let session: SharedSession
+ var tick: Int = 0
+
+ /// Calm Mochi look around; one who needs you keeps his state's face.
+ private var pose: MochiPose {
+ switch session.tone {
+ case .idle, .done, .working, .info, .warning: MochiPose.idle(id: session.id, tick: tick)
+ default: .neutral
+ }
+ }
+
+ 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)
+ Text(session.agent)
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(.white.opacity(0.85))
+ .lineLimit(1)
+ .minimumScaleFactor(0.7)
+ .padding(.horizontal, 4)
+ .offset(y: -6)
+ Spacer(minLength: 0)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background { TileBackground(color: Color(white: 0.14)).clipShape(RoundedRectangle(cornerRadius: 16)) }
+ .overlay(alignment: .topTrailing) {
+ if session.tone != .idle {
+ Circle()
+ .fill(session.toneColor)
+ .frame(width: 8, height: 8)
+ .overlay(Circle().strokeBorder(Color.black.opacity(0.35), lineWidth: 1))
+ .padding(6)
+ }
+ }
+ .overlay {
+ // Waiting on you: the whole tile is outlined, like the notch.
+ if session.isWaitingForYou {
+ RoundedRectangle(cornerRadius: 16).strokeBorder(session.toneColor, lineWidth: 2)
+ }
}
}
}
+/// A free spot: Mochi asleep, faded, instead of an empty square.
+struct EmptyTeamTile: View {
+ var tick: Int = 0
+ var slot: Int = 0
+
+ var body: some View {
+ WidgetMochi(state: .sleeping, showBadge: false,
+ pose: MochiPose(tilt: (tick + slot) % 2 == 0 ? -0.06 : 0.06))
+ .padding(14)
+ .opacity(0.18)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background { TileBackground(color: Color.white.opacity(0.05)).clipShape(RoundedRectangle(cornerRadius: 16)) }
+ }
+}
+
struct ListView: View {
let sessions: [SharedSession]
@@ -182,17 +281,17 @@ struct ListView: View {
VStack(alignment: .leading, spacing: 6) {
if sessions.isEmpty {
HStack(spacing: 10) {
- MochiStill(state: .sleeping).frame(width: 34, height: 34)
+ WidgetMochi(state: .sleeping).frame(width: 34, height: 34)
Text("All quiet: no agent session").font(.subheadline).opacity(0.7)
}
.frame(maxHeight: .infinity)
}
ForEach(sessions) { session in
HStack(spacing: 8) {
- MochiStill(state: session.botState)
+ WidgetMochi(state: session.botState)
.padding(2)
.frame(width: 24, height: 24)
- .background(Color.mochiTile(hex: session.color), in: RoundedRectangle(cornerRadius: 7))
+ .background { TileBackground(color: Color.mochiTile(hex: session.color)).clipShape(RoundedRectangle(cornerRadius: 7)) }
Text(session.title)
.font(.subheadline.weight(.semibold))
.lineLimit(1)
@@ -252,6 +351,14 @@ struct LockScreenView: View {
// MARK: - Samples (widget gallery)
extension SharedSession {
+ /// A calm Mochi from the catalog, for a free spot of the Team widget.
+ static func regular(id: String) -> SharedSession? {
+ guard let pill = PillCatalog.definition(for: id) else { return nil }
+ return SharedSession(id: pill.id, title: pill.name, agent: pill.name, color: pill.color,
+ state: "idle", statusText: "idle", tone: .idle, urgency: 5,
+ stepIndex: 0, stepCount: 0, currentStep: "", updatedAt: .distantPast)
+ }
+
static let samples: [SharedSession] = [
SharedSession(id: "integration_claude", title: "coucou", agent: "VS Code", color: "#4A86E8",
state: "approval", statusText: "waiting for your OK", tone: .waiting, urgency: 0,
@@ -267,3 +374,42 @@ extension SharedSession {
stepIndex: 0, stepCount: 0, currentStep: "", updatedAt: .now),
]
}
+
+// MARK: - Tinted Home Screen
+
+/// 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.
+struct WidgetMochi: View {
+ @Environment(\.widgetRenderingMode) private var renderingMode
+ var state: BotState = .idle
+ var bodyHex: String = "#FFFFFF"
+ var showBadge: Bool = true
+ var pose: MochiPose = .neutral
+
+ var body: some View {
+ if renderingMode == .fullColor {
+ MochiStill(state: state, bodyHex: bodyHex, showBadge: showBadge, pose: pose)
+ } else {
+ MochiStill(state: state, bodyHex: "#FFFFFF", showBadge: showBadge, pose: pose)
+ .luminanceToAlpha()
+ .widgetAccentable()
+ }
+ }
+}
+
+/// A tile behind a Mochi: its color normally, a faint wash when tinted so it
+/// doesn't become a solid block that hides him.
+struct TileBackground: View {
+ @Environment(\.widgetRenderingMode) private var renderingMode
+ let color: Color
+
+ var body: some View {
+ if renderingMode == .fullColor {
+ color
+ } else {
+ Color.white.opacity(0.12)
+ }
+ }
+}
diff --git a/NotchBuddy/Sources/Widgets/TeamConfiguration.swift b/NotchBuddy/Sources/Widgets/TeamConfiguration.swift
new file mode 100644
index 00000000..99714dde
--- /dev/null
+++ b/NotchBuddy/Sources/Widgets/TeamConfiguration.swift
@@ -0,0 +1,85 @@
+import AppIntents
+import WidgetKit
+
+// The Team widget's settings: which Mochi sits in each of the four spots.
+// "Automatic" fills a spot with the most urgent Mochi not already shown.
+
+enum MochiChoice: String, AppEnum {
+ case automatic
+ case vscode = "integration_claude"
+ case cursor = "agent_cursor"
+ case codex = "agent_codex"
+ case antigravity = "agent_antigravity"
+ case gemini = "agent_gemini"
+ case github = "integration_github"
+ case stripe = "integration_stripe"
+ case vercel = "integration_vercel"
+ case resend = "integration_resend"
+ case calcom = "integration_calcom"
+ case n8n = "integration_n8n"
+ case notion = "integration_notion"
+
+ static let typeDisplayRepresentation: TypeDisplayRepresentation = "Mochi"
+
+ static let caseDisplayRepresentations: [MochiChoice: DisplayRepresentation] = [
+ .automatic: "Automatic",
+ .vscode: "VS Code",
+ .cursor: "Cursor",
+ .codex: "Codex",
+ .antigravity: "Antigravity",
+ .gemini: "Gemini CLI",
+ .github: "GitHub",
+ .stripe: "Stripe",
+ .vercel: "Vercel",
+ .resend: "Resend",
+ .calcom: "Cal.com",
+ .n8n: "n8n",
+ .notion: "Notion",
+ ]
+
+ /// The pill shown, nil for automatic.
+ var pillId: String? { self == .automatic ? nil : rawValue }
+}
+
+struct TeamConfiguration: WidgetConfigurationIntent {
+ static let title: LocalizedStringResource = "Team"
+ static let description = IntentDescription("Pick the Mochi in each spot.")
+
+ @Parameter(title: "Top left", default: .automatic) var spot1: MochiChoice
+ @Parameter(title: "Top right", default: .automatic) var spot2: MochiChoice
+ @Parameter(title: "Bottom left", default: .automatic) var spot3: MochiChoice
+ @Parameter(title: "Bottom right", default: .automatic) var spot4: MochiChoice
+
+ var picks: [String?] { [spot1.pillId, spot2.pillId, spot3.pillId, spot4.pillId] }
+}
+
+struct TeamEntry: TimelineEntry {
+ let date: Date
+ let sessions: [SharedSession]
+ let picks: [String?]
+ var tick: Int = 0
+}
+
+struct TeamProvider: AppIntentTimelineProvider {
+ func placeholder(in context: Context) -> TeamEntry {
+ TeamEntry(date: .now, sessions: SharedSession.samples, picks: [nil, nil, nil, nil])
+ }
+
+ func snapshot(for configuration: TeamConfiguration, in context: Context) async -> TeamEntry {
+ let saved = SharedSessions.load()
+ return TeamEntry(date: .now, sessions: context.isPreview && saved.isEmpty ? SharedSession.samples : saved,
+ picks: configuration.picks)
+ }
+
+ func timeline(for configuration: TeamConfiguration, in context: Context) async -> Timeline<TeamEntry> {
+ // Same as SessionsProvider: a new pose each minute for an hour.
+ let sessions = SharedSessions.load()
+ let start = Date.now
+ let base = Int(start.timeIntervalSince1970 / 60)
+ let entries = (0..<60).map { minute in
+ TeamEntry(date: start.addingTimeInterval(Double(minute) * 60), sessions: sessions,
+ picks: configuration.picks, tick: base + minute)
+ }
+ return Timeline(entries: entries, policy: .atEnd)
+ }
+}
diff --git a/NotchBuddy/project.yml b/NotchBuddy/project.yml
index 722782d6..e419ecaa 100644
--- a/NotchBuddy/project.yml
+++ b/NotchBuddy/project.yml
@@ -243,7 +243,14 @@ targets:
- UIInterfaceOrientationPortrait
ITSAppUsesNonExemptEncryption: NO
NSFaceIDUsageDescription: "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."
+ NSSpeechRecognitionUsageDescription: "Coucou turns your voice into the text of an instruction for Claude Code."
NSSupportsLiveActivities: YES
+ # coucou://session/<id>: the widgets open a session in the app.
+ CFBundleURLTypes:
+ - CFBundleURLName: fr.louisraille.Coucou
+ CFBundleURLSchemes:
+ - coucou
# Which APNs environment the Live Activity tokens belong to (read by the Mac).
CoucouAPNsEnvironment: $(COUCOU_APNS_ENV)
settings:
diff --git a/docs/privacy.html b/docs/privacy.html
index faa3182a..6c5a4769 100644
--- a/docs/privacy.html
+++ b/docs/privacy.html
@@ -49,7 +49,8 @@
<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 &amp; 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. Project names, steps, folders, the last message, pending commands and questions 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 (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>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>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>
@@ -109,7 +110,8 @@
<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. Les noms de projet, étapes, dossiers, dernier message, commandes en attente et questions 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 (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>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>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>