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.

Demo mode for App Review (#276)

Louis20e1f8b9def2
diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
index 79756e6b..fcd1ac75 100644
--- a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
@@ -157,6 +157,7 @@
AD94156F1F9CFF62B35202FB /* ApprovalRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD426E81DF79CA79888059D9 /* ApprovalRelay.swift */; };
ADB4EF797FBD6CC90F8D25D3 /* MochiActivityAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 323F242B14A61A7C071EC115 /* MochiActivityAttributes.swift */; };
ADBB9C15DDA4044625B325BE /* MochiOutfitDrawing.swift in Sources */ = {isa = PBXBuildFile; fileRef = E84E5D91129352E8A1D32AA4 /* MochiOutfitDrawing.swift */; };
+ B0CE5AC8B579866A14BD61D0 /* DemoEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = AEF5BD66B00BB64BB80AF38C /* DemoEngine.swift */; };
B2584220B877056366C8DCAE /* MochiWardrobe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79A7807ADD0963FF260D1FAD /* MochiWardrobe.swift */; };
B2D86BE268D6F4C86BD0C446 /* ChatMarkdown.swift in Sources */ = {isa = PBXBuildFile; fileRef = D797CC384B5BC70D34F121BC /* ChatMarkdown.swift */; };
B314F09AD7924387D0E04B45 /* BotEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66E6F5FC81429871B6F766A8 /* BotEngine.swift */; };
@@ -225,6 +226,7 @@
EF9E6418C3F39F6FE88FD812 /* CoucouPhoneApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D9CEB5655FCA197D6B10A91 /* CoucouPhoneApp.swift */; };
EFAA9936D5C9DE635CFBA2AB /* SharedSessions.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1064AD8471C51AFF4F12258 /* SharedSessions.swift */; };
F06EE0A97CB77096A337AA8B /* sounds in Resources */ = {isa = PBXBuildFile; fileRef = C066E2B991AA4F56B2724263 /* sounds */; };
+ F157D7A9BF878DB2B286B1F7 /* DemoEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = AEF5BD66B00BB64BB80AF38C /* DemoEngine.swift */; };
F1EE04000665E204E02DC5AC /* DenyApprovalIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = D849B1A27AD17AEE1C7FFD1A /* DenyApprovalIntent.swift */; };
F25EB7EF3662AFF99AA1C8A1 /* TeamConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8C1BB0DF7770A6B263995E6 /* TeamConfiguration.swift */; };
F28275101D83F121E582B1B1 /* LiveActivityRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = 136626568FF0C3EAB1D08067 /* LiveActivityRelay.swift */; };
@@ -346,6 +348,7 @@
A83D5410BD030B243ADDCFF4 /* ClaudeService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeService.swift; sourceTree = "<group>"; };
AB78996E9F9A2E8A80D45E54 /* QuestionRelay.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionRelay.swift; sourceTree = "<group>"; };
ADA6A002ABEC0CC57667FBE0 /* MochiLiveActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MochiLiveActivity.swift; sourceTree = "<group>"; };
+ AEF5BD66B00BB64BB80AF38C /* DemoEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoEngine.swift; sourceTree = "<group>"; };
B1DDC96E7967032F5D0BD585 /* DesktopMochi.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DesktopMochi.swift; sourceTree = "<group>"; };
B241B043223AFBBFB7418A5E /* UploadCanvasView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UploadCanvasView.swift; sourceTree = "<group>"; };
B2AA83D80260660475FAB052 /* Localizable.xcstrings */ = {isa = PBXFileReference; lastKnownFileType = text.json.xcstrings; path = Localizable.xcstrings; sourceTree = "<group>"; };
@@ -415,6 +418,7 @@
F4263B550838CC5614569D13 /* ClaudePlanCardView.swift */,
8BF22817EC70748F2D1FB2E7 /* ClaudePlanGauge.swift */,
A83D5410BD030B243ADDCFF4 /* ClaudeService.swift */,
+ AEF5BD66B00BB64BB80AF38C /* DemoEngine.swift */,
B1DDC96E7967032F5D0BD585 /* DesktopMochi.swift */,
C086E1932F86B9C2B559BE03 /* DesktopMochiLogic.swift */,
3232F258523DD8D09B670363 /* FileDropView.swift */,
@@ -790,6 +794,7 @@
2DEB459FBD0BA3CEAAA5FDE9 /* ClaudeService.swift in Sources */,
D45D9C8EAF67FC2F46E9F352 /* CloudProbe.swift in Sources */,
EE3AB10544113500486A9684 /* ColorHex.swift in Sources */,
+ B0CE5AC8B579866A14BD61D0 /* DemoEngine.swift in Sources */,
BEC5DDB55B3DA67C61CA8470 /* DesktopMochi.swift in Sources */,
BA65FC4A40F7227837C26214 /* DesktopMochiLogic.swift in Sources */,
077ECE0906D8E820BD5FA764 /* DiffEngine.swift in Sources */,
@@ -939,6 +944,7 @@
0329E76BA4A8FEEA8A6D76E7 /* ClaudeService.swift in Sources */,
FDF87CF7C5F703EDD9A7CC14 /* CloudProbe.swift in Sources */,
9ECEE890D4486B6E83BD5B7F /* ColorHex.swift in Sources */,
+ F157D7A9BF878DB2B286B1F7 /* DemoEngine.swift in Sources */,
273FC0FA14AAF6CE62FD14AE /* DesktopMochi.swift in Sources */,
C93BA975D35B8CD7473CF995 /* DesktopMochiLogic.swift in Sources */,
4D958F2DDCE9504490FDA357 /* DiffEngine.swift in Sources */,
diff --git a/NotchBuddy/Resources/InfoAppStore.plist b/NotchBuddy/Resources/InfoAppStore.plist
index 57be7782..d856deab 100644
--- a/NotchBuddy/Resources/InfoAppStore.plist
+++ b/NotchBuddy/Resources/InfoAppStore.plist
@@ -32,7 +32,7 @@
<key>CFBundleShortVersionString</key>
<string>1.1</string>
<key>CFBundleVersion</key>
- <string>5</string>
+ <string>6</string>
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
<key>LSApplicationCategoryType</key>
diff --git a/NotchBuddy/Resources/Localizable.xcstrings b/NotchBuddy/Resources/Localizable.xcstrings
index aab463e4..187c2cc5 100644
--- a/NotchBuddy/Resources/Localizable.xcstrings
+++ b/NotchBuddy/Resources/Localizable.xcstrings
@@ -18873,6 +18873,331 @@
}
}
}
+ },
+ "demo.groupbox.title": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Demo"
+ }
+ },
+ "ar": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "تجريبي"
+ }
+ },
+ "bn": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "ডেমো"
+ }
+ },
+ "es": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Demo"
+ }
+ },
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Démo"
+ }
+ },
+ "hi": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "डेमो"
+ }
+ },
+ "id": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Demo"
+ }
+ },
+ "pt-BR": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Demo"
+ }
+ },
+ "ru": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Демо"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "演示"
+ }
+ }
+ }
+ },
+ "demo.description": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Explore all features without an API key or Claude Code. Nothing is written to disk."
+ }
+ },
+ "ar": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "استكشف جميع الميزات بدون مفتاح API أو Claude Code. لا يُكتب شيء على القرص."
+ }
+ },
+ "bn": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "API কী বা Claude Code ছাড়াই সমস্ত ফিচার এক্সপ্লোর করুন। ডিস্কে কিছু লেখা হয় না।"
+ }
+ },
+ "es": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Explora todas las funciones sin clave de API ni Claude Code. Nada se escribe en el disco."
+ }
+ },
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Explore toutes les fonctions sans clé d'API ni Claude Code. Rien n'est écrit sur le disque."
+ }
+ },
+ "hi": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "API कुंजी या Claude Code के बिना सभी सुविधाएँ एक्सप्लोर करें। डिस्क पर कुछ नहीं लिखा जाता।"
+ }
+ },
+ "id": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Jelajahi semua fitur tanpa kunci API atau Claude Code. Tidak ada yang ditulis ke disk."
+ }
+ },
+ "pt-BR": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Explore todos os recursos sem chave de API ou Claude Code. Nada é gravado no disco."
+ }
+ },
+ "ru": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Изучи все функции без API-ключа и Claude Code. Ничего не записывается на диск."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "无需 API 密钥或 Claude Code,探索所有功能。不会写入任何内容到磁盘。"
+ }
+ }
+ }
+ },
+ "demo.start": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Try demo mode"
+ }
+ },
+ "ar": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "تجربة وضع العرض"
+ }
+ },
+ "bn": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "ডেমো মোড চেষ্টা করুন"
+ }
+ },
+ "es": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Probar el modo demo"
+ }
+ },
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Essayer la démo"
+ }
+ },
+ "hi": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "डेमो मोड आज़माएँ"
+ }
+ },
+ "id": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Coba mode demo"
+ }
+ },
+ "pt-BR": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Experimentar modo demo"
+ }
+ },
+ "ru": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Попробовать демо"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "试用演示模式"
+ }
+ }
+ }
+ },
+ "demo.stop": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Stop demo"
+ }
+ },
+ "ar": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "إيقاف العرض"
+ }
+ },
+ "bn": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "ডেমো বন্ধ করুন"
+ }
+ },
+ "es": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Detener demo"
+ }
+ },
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Arrêter la démo"
+ }
+ },
+ "hi": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "डेमो रोकें"
+ }
+ },
+ "id": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Hentikan demo"
+ }
+ },
+ "pt-BR": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Parar demo"
+ }
+ },
+ "ru": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Остановить демо"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "停止演示"
+ }
+ }
+ }
+ },
+ "Demo mode": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Demo mode"
+ }
+ },
+ "ar": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "وضع العرض"
+ }
+ },
+ "bn": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "ডেমো মোড"
+ }
+ },
+ "es": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Modo demo"
+ }
+ },
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Mode démo"
+ }
+ },
+ "hi": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "डेमो मोड"
+ }
+ },
+ "id": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Mode demo"
+ }
+ },
+ "pt-BR": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Modo demo"
+ }
+ },
+ "ru": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Демо-режим"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "演示模式"
+ }
+ }
+ }
}
},
"version": "1.0"
diff --git a/NotchBuddy/Sources/App/AppDelegate.swift b/NotchBuddy/Sources/App/AppDelegate.swift
index 7417a404..a7ec4821 100644
--- a/NotchBuddy/Sources/App/AppDelegate.swift
+++ b/NotchBuddy/Sources/App/AppDelegate.swift
@@ -5,8 +5,10 @@ import SwiftUI
final class AppDelegate: NSObject, NSApplicationDelegate {
var statusItem: NSStatusItem?
private(set) var islandController: IslandWindowController?
+ private var demoMenuItem: NSMenuItem?
func applicationWillTerminate(_ notification: Notification) {
+ DemoEngine.shared.stop()
HotKeyCenter.shared.unregisterAll()
}
@@ -41,6 +43,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
button.image?.isTemplate = true
let menu = NSMenu()
+ menu.delegate = self
+ let demoItem = NSMenuItem(title: NSLocalizedString("Demo mode", comment: ""), action: #selector(toggleDemoMode), keyEquivalent: "")
+ demoMenuItem = demoItem
+ menu.addItem(demoItem)
+ menu.addItem(.separator())
menu.addItem(withTitle: NSLocalizedString("Open Coucou", comment: ""), action: #selector(openIsland), keyEquivalent: "")
menu.addItem(.separator())
menu.addItem(withTitle: NSLocalizedString("Weekly recap", comment: ""), action: #selector(openWeeklyRecap), keyEquivalent: "")
@@ -53,6 +60,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: - Actions
+ @objc private func toggleDemoMode() {
+ if DemoEngine.shared.isActive { DemoEngine.shared.stop() }
+ else { DemoEngine.shared.start() }
+ }
+
@objc private func openIsland() {
islandController?.expand(to: .overview)
}
@@ -199,3 +211,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
#endif
}
}
+
+// MARK: - NSMenuDelegate
+
+extension AppDelegate: NSMenuDelegate {
+ func menuWillOpen(_ menu: NSMenu) {
+ demoMenuItem?.title = DemoEngine.shared.isActive
+ ? NSLocalizedString("demo.stop", comment: "")
+ : NSLocalizedString("Demo mode", comment: "")
+ }
+}
diff --git a/NotchBuddy/Sources/App/AppState.swift b/NotchBuddy/Sources/App/AppState.swift
index 29e9e914..22a097cf 100644
--- a/NotchBuddy/Sources/App/AppState.swift
+++ b/NotchBuddy/Sources/App/AppState.swift
@@ -403,6 +403,8 @@ final class AppState: ObservableObject {
@Published var showPlanInNotch: Bool = false {
didSet { UserDefaults.standard.set(showPlanInNotch, forKey: "showPlanInNotch") }
}
+ // In-memory plan usage override for demo mode. Never persisted. Set by DemoEngine.
+ @Published var demoPlanUsageOverride: PlanUsage? = nil
// Cached relay-installed state — updated at launch, after install/uninstall, on Settings open
@Published var planRelayInstalled: Bool = false
// Transient — reset when island closes or view changes
diff --git a/NotchBuddy/Sources/App/CalcomPoller.swift b/NotchBuddy/Sources/App/CalcomPoller.swift
index 8f49b3dd..c04f6ea7 100644
--- a/NotchBuddy/Sources/App/CalcomPoller.swift
+++ b/NotchBuddy/Sources/App/CalcomPoller.swift
@@ -17,6 +17,7 @@ final class CalcomPoller: @unchecked Sendable {
func pollNow() { poll() }
private func poll() {
+ guard !DemoEngine.isPollerPaused else { return }
guard let key = KeychainStore.shared.get("calcom-api-key") else { return }
let cal = Calendar.current
let today = cal.startOfDay(for: Date())
diff --git a/NotchBuddy/Sources/App/ClaudeService.swift b/NotchBuddy/Sources/App/ClaudeService.swift
index 7ebeee1d..08b7a923 100644
--- a/NotchBuddy/Sources/App/ClaudeService.swift
+++ b/NotchBuddy/Sources/App/ClaudeService.swift
@@ -217,6 +217,12 @@ final class ClaudeService {
// MARK: - Chat (multi-turn, natural text + web search)
func chat(query: String, context: PromptContext?, state: AppState) async {
+ if DemoEngine.shared.isActive {
+ state.stateOverride = .thinking
+ await DemoEngine.shared.streamChatResponse(for: query)
+ state.stateOverride = nil
+ return
+ }
guard state.chatProvider == .anthropic else {
await chatOpenAICompatible(query: query, context: context, state: state)
return
diff --git a/NotchBuddy/Sources/App/DemoEngine.swift b/NotchBuddy/Sources/App/DemoEngine.swift
new file mode 100644
index 00000000..169fbf32
--- /dev/null
+++ b/NotchBuddy/Sources/App/DemoEngine.swift
@@ -0,0 +1,756 @@
+import Foundation
+import SwiftUI
+import Combine
+
+// MARK: - DemoEngine
+// Scripted ~60 s tour of Coucou for App Store review.
+// Zero network calls, nothing written to disk or Keychain.
+
+@MainActor
+final class DemoEngine: ObservableObject {
+
+ static let shared = DemoEngine()
+ private init() {}
+
+ // MARK: Published state
+
+ @Published var isActive: Bool = false
+
+ // Checked from background threads (pollers). Written only from @MainActor.
+ nonisolated(unsafe) private(set) static var isPollerPaused: Bool = false
+
+ // MARK: Private state
+
+ private var demoTask: Task<Void, Never>? = nil
+ private var modeCancellable: AnyCancellable? = nil
+
+ private var visibilityContinuation: CheckedContinuation<Void, Never>? = nil
+ private var approvalContinuation: CheckedContinuation<String, Never>? = nil
+ private var questionContinuation: CheckedContinuation<Void, Never>? = nil
+
+ private var generation: Int = 0 // incremented on each start() to orphan stale closures
+ private var demoInjectedTaskIds: [String] = [] // integration task IDs added by demo
+ private var realTaskIdsAtStart: Set<String> = [] // real task IDs that existed before demo
+ private var demoCycleIndex: Int = 0
+ private let rotatingIntegrationIds = [
+ "integration_stripe", "integration_calcom",
+ "integration_n8n", "integration_notion", "integration_vercel"
+ ]
+ private var demoDiffIds: [String: [Int]] = [:] // [pillId: [diffId]]
+ private var lastApprovalDecision: String = "allow"
+ private var lastQuestionAnswer: String? = nil
+
+ // MARK: Snapshot
+
+ private struct Snapshot {
+ var tasks: [AgentTask]
+ var focusId: String?
+ var chatHistory: [ChatMessage]
+ var stateOverride: BotState?
+ var isPinned: Bool
+ var noteMessage: String?
+ // Integration data
+ var vercelDeployments: [VercelDeployment]
+ var resendEmails: [ResendEmail]
+ var resendTotal: Int?
+ var githubPulse: GitHubPulse?
+ var githubActivity: GitHubActivity?
+ var githubStats: GitHubStats?
+ var stripePayments: [StripePayment]
+ var stripeBalance: Int
+ var stripeDisplayBalance: Int
+ var stripeCurrency: String
+ var stripeLoaded: Bool
+ var stripeError: String?
+ var calcomBookings: [CalcomBooking]
+ var calcomLoaded: Bool
+ var n8nRuns: [N8nRun]
+ var notionPages: [NotionPage]
+ var notionLoaded: Bool
+ // NOTE: pendingApproval and pendingQuestion are intentionally NOT snapshotted.
+ // HookServer's file descriptors are authoritative for real requests.
+ var mode: IslandMode
+ var view: IslandView
+ }
+
+ private var snapshot: Snapshot? = nil
+
+ // MARK: Start
+
+ func start() {
+ guard !isActive else { return }
+ isActive = true
+ DemoEngine.isPollerPaused = true
+ generation += 1
+ demoCycleIndex = 0
+
+ let s = AppState.shared
+
+ // Record which tasks are real (not demo-injected) before demo starts
+ realTaskIdsAtStart = Set(s.tasks.map { $0.id })
+
+ snapshot = Snapshot(
+ tasks: s.tasks,
+ focusId: s.focusId,
+ chatHistory: s.chatHistory,
+ stateOverride: s.stateOverride,
+ isPinned: s.isPinned,
+ noteMessage: s.noteMessage,
+ vercelDeployments: s.vercelDeployments,
+ resendEmails: s.resendEmails,
+ resendTotal: s.resendTotal,
+ githubPulse: s.githubPulse,
+ githubActivity: s.githubActivity,
+ githubStats: s.githubStats,
+ stripePayments: s.stripePayments,
+ stripeBalance: s.stripeBalance,
+ stripeDisplayBalance: s.stripeDisplayBalance,
+ stripeCurrency: s.stripeCurrency,
+ stripeLoaded: s.stripeLoaded,
+ stripeError: s.stripeError,
+ calcomBookings: s.calcomBookings,
+ calcomLoaded: s.calcomLoaded,
+ n8nRuns: s.n8nRuns,
+ notionPages: s.notionPages,
+ notionLoaded: s.notionLoaded,
+ mode: s.mode,
+ view: s.view
+ )
+
+ // Hide all real pills — show only main during demo (integration + Codex added progressively).
+ let mainTask = s.tasks.first(where: { $0.id == s.mainPillId })
+ s.tasks = mainTask.map { [$0] } ?? []
+
+ // Weekly recap: available immediately so the reviewer can share it
+ RecapStore.shared.demoSummaryOverride = demoWeeklySummary()
+
+ // Plan usage override (in-memory, never persisted)
+ #if !APPSTORE
+ let now = Date()
+ s.demoPlanUsageOverride = PlanUsage(
+ fiveHour: PlanWindow(usedPct: 42.0, resetsAt: now.addingTimeInterval(4 * 3600)),
+ sevenDay: PlanWindow(usedPct: 37.0, resetsAt: now.addingTimeInterval(3 * 24 * 3600)),
+ updatedAt: now
+ )
+ #endif
+
+ // Inject integration data (no activeIntegrations setter, no UserDefaults write)
+ injectIntegrationData()
+
+ // Observe mode changes to unblock waitUntilVisible()
+ modeCancellable = s.$mode
+ .dropFirst()
+ .sink { [weak self] mode in
+ MainActor.assumeIsolated {
+ if mode != .hidden, let cont = self?.visibilityContinuation {
+ self?.visibilityContinuation = nil
+ cont.resume()
+ }
+ }
+ }
+
+ // Open island immediately on the demo session
+ NotificationCenter.default.post(name: .hookExpand, object: IslandView.overview)
+
+ let gen = generation
+ demoTask = Task { @MainActor [weak self] in
+ await self?.runDemoLoop(gen: gen)
+ }
+ }
+
+ // MARK: Stop
+
+ func stop() {
+ guard isActive else { return }
+ isActive = false
+ DemoEngine.isPollerPaused = false
+ GithubPoller.shared.triggerPulseNow()
+
+ demoTask?.cancel()
+ demoTask = nil
+ modeCancellable = nil
+
+ // Unblock any waiting continuations so the loop exits cleanly
+ let vc = visibilityContinuation; visibilityContinuation = nil; vc?.resume()
+ let ac = approvalContinuation; approvalContinuation = nil; ac?.resume(returning: "allow")
+ let qc = questionContinuation; questionContinuation = nil; qc?.resume()
+
+ // Clear demo overrides
+ RecapStore.shared.demoSummaryOverride = nil
+ #if !APPSTORE
+ AppState.shared.demoPlanUsageOverride = nil
+ #endif
+
+ let s = AppState.shared
+
+ // Clear demo approval card (never real — real cards have a fd in HookServer)
+ if s.pendingApproval?.sessionId == "demo_session" {
+ s.pendingApproval = nil
+ }
+ // Clear demo question (real questions always have pendingQuestionFD >= 0)
+ if !HookServer.shared.hasRealPendingQuestion {
+ s.pendingQuestion = nil
+ }
+ // Only restore isPinned if no real request is now pending
+ if s.pendingApproval == nil && s.pendingQuestion == nil {
+ s.isPinned = snapshot?.isPinned ?? false
+ }
+
+ guard let snap = snapshot else { return }
+ snapshot = nil
+
+ // Restore AppState (NOT pendingApproval, NOT pendingQuestion — HookServer owns those)
+ s.chatHistory = snap.chatHistory
+ s.stateOverride = snap.stateOverride
+ s.noteMessage = snap.noteMessage
+
+ // Restore integration data
+ s.vercelDeployments = snap.vercelDeployments
+ s.resendEmails = snap.resendEmails
+ s.resendTotal = snap.resendTotal
+ s.githubPulse = snap.githubPulse
+ s.githubActivity = snap.githubActivity
+ s.githubStats = snap.githubStats
+ s.stripePayments = snap.stripePayments
+ s.stripeBalance = snap.stripeBalance
+ s.stripeDisplayBalance = snap.stripeDisplayBalance
+ s.stripeCurrency = snap.stripeCurrency
+ s.stripeLoaded = snap.stripeLoaded
+ s.stripeError = snap.stripeError
+ s.calcomBookings = snap.calcomBookings
+ s.calcomLoaded = snap.calcomLoaded
+ s.n8nRuns = snap.n8nRuns
+ s.notionPages = snap.notionPages
+ s.notionLoaded = snap.notionLoaded
+
+ // Restore tasks: keep real tasks that arrived during the demo, discard demo-only ones.
+ // For tasks that existed before the demo (realTaskIdsAtStart), use the CURRENT version
+ // from AppState (real Claude Code events may have updated them during demo).
+ let demoIds: Set<String> = Set(demoInjectedTaskIds + ["demo_codex"])
+ let currentTasksById = Dictionary(uniqueKeysWithValues: s.tasks.map { ($0.id, $0) })
+ let realNewTasks = s.tasks.filter { task in
+ !snap.tasks.contains(where: { $0.id == task.id }) && !demoIds.contains(task.id)
+ }
+ let mainPillId = s.mainPillId
+ let restoredSnapTasks = snap.tasks.map { snapTask -> AgentTask in
+ // Main pill: always restore from snapshot — demo may have left steps/finalLine mid-cycle.
+ if snapTask.id == mainPillId { return snapTask }
+ // Other real tasks: keep current (may have received real hook events during demo).
+ if realTaskIdsAtStart.contains(snapTask.id), !demoIds.contains(snapTask.id),
+ let current = currentTasksById[snapTask.id] {
+ return current
+ }
+ return snapTask
+ }
+ s.tasks = restoredSnapTasks + realNewTasks
+
+ // Remove only demo diffs; leave real diffs untouched
+ for (pillId, ids) in demoDiffIds {
+ for id in ids {
+ s.sessionDiffs[pillId]?.removeAll { $0.id == id }
+ }
+ if s.sessionDiffs[pillId]?.isEmpty == true {
+ s.sessionDiffs.removeValue(forKey: pillId)
+ }
+ }
+ demoDiffIds = [:]
+ demoInjectedTaskIds = []
+ realTaskIdsAtStart = []
+ demoCycleIndex = 0
+ lastApprovalDecision = "allow"
+ lastQuestionAnswer = nil
+
+ // Restore focus
+ let fid = snap.focusId ?? s.mainPillId
+ s.focusId = s.tasks.contains(where: { $0.id == fid }) ? fid : s.mainPillId
+
+ // Restore view/mode only when no real request is pinned
+ if s.pendingApproval == nil && s.pendingQuestion == nil {
+ s.mode = snap.mode
+ s.view = snap.view
+ }
+
+ NotificationCenter.default.post(name: .islandCollapse, object: nil)
+ }
+
+ // MARK: Integration data injection (no UserDefaults writes)
+
+ private func injectIntegrationData() {
+ let s = AppState.shared
+ let now = Date()
+
+ // GitHub
+ s.githubStats = GitHubStats(totalRepos: 34, totalStars: 127)
+ s.githubPulse = GitHubPulse(
+ login: "demo-user",
+ myPRs: [
+ GitHubPR(id: "my-app/auth#42", title: "feat: OAuth2 PKCE flow",
+ url: "https://github.com/demo/my-app/pull/42",
+ repo: "my-app", number: 42, isDraft: false, ci: .success, review: .approved),
+ GitHubPR(id: "my-app/api#38", title: "fix: rate limit headers",
+ url: "https://github.com/demo/my-app/pull/38",
+ repo: "my-app", number: 38, isDraft: false, ci: .pending, review: .pending),
+ ],
+ toReview: [
+ GitHubPR(id: "my-app/ui#21", title: "refactor: design system tokens",
+ url: "https://github.com/demo/my-app/pull/21",
+ repo: "my-app", number: 21, isDraft: false, ci: .success, review: .pending),
+ ],
+ mainCI: [
+ GitHubRepoCI(repo: "my-app", url: "https://github.com/demo/my-app/actions",
+ branch: "main", ci: .success),
+ ],
+ fetchedAt: now
+ )
+ s.githubActivity = nil
+
+ // Stripe
+ s.stripeCurrency = "eur"
+ s.stripeBalance = 124750
+ s.stripeDisplayBalance = 124750
+ s.stripeLoaded = true
+ s.stripeError = nil
+ s.stripePayments = [
+ StripePayment(id: "py_demo1", amount: 4900, currency: "eur",
+ description: "Pro plan — monthly",
+ createdAt: now.addingTimeInterval(-3600), status: "succeeded"),
+ StripePayment(id: "py_demo2", amount: 9900, currency: "eur",
+ description: "Pro plan — annual",
+ createdAt: now.addingTimeInterval(-7200), status: "succeeded"),
+ StripePayment(id: "py_demo3", amount: 2900, currency: "eur",
+ description: "Starter plan",
+ createdAt: now.addingTimeInterval(-14400), status: "succeeded"),
+ ]
+
+ // Vercel
+ s.vercelDeployments = [
+ VercelDeployment(id: "dpl_demo1", projectName: "my-app",
+ url: "my-app-abc123.vercel.app", state: "READY",
+ createdAt: now.addingTimeInterval(-1800),
+ commitMessage: "feat: auth refactor", branch: "main"),
+ VercelDeployment(id: "dpl_demo2", projectName: "my-app",
+ url: "my-app-prev.vercel.app", state: "READY",
+ createdAt: now.addingTimeInterval(-86400),
+ commitMessage: "fix: mobile nav", branch: "main"),
+ ]
+
+ // Resend
+ s.resendTotal = 1284
+ s.resendEmails = [
+ ResendEmail(id: "re_demo1", to: ["[email protected]"], subject: "Welcome to my-app",
+ createdAt: now.addingTimeInterval(-600), lastEvent: "delivered"),
+ ResendEmail(id: "re_demo2", to: ["[email protected]"], subject: "Your weekly digest",
+ createdAt: now.addingTimeInterval(-3600), lastEvent: "opened"),
+ ]
+
+ // Cal.com
+ let cal = Calendar.current
+ let tomorrow = cal.date(byAdding: .day, value: 1, to: now)!
+ let tomorrowMorning = cal.date(bySettingHour: 10, minute: 0, second: 0, of: tomorrow)!
+ let tomorrowNoon = cal.date(bySettingHour: 14, minute: 30, second: 0, of: tomorrow)!
+ s.calcomBookings = [
+ CalcomBooking(id: 1001, title: "Product demo call",
+ startTime: tomorrowMorning,
+ endTime: tomorrowMorning.addingTimeInterval(3600),
+ status: "ACCEPTED",
+ attendeeName: "Alice Martin",
+ attendeeEmail: "[email protected]",
+ attendeeNotes: "Interested in the Pro plan"),
+ CalcomBooking(id: 1002, title: "Onboarding call",
+ startTime: tomorrowNoon,
+ endTime: tomorrowNoon.addingTimeInterval(1800),
+ status: "ACCEPTED",
+ attendeeName: "Bob Chen",
+ attendeeEmail: "[email protected]",
+ attendeeNotes: nil),
+ ]
+ s.calcomLoaded = true
+
+ // n8n
+ s.n8nRuns = [
+ N8nRun(workflow: "Notify on new Stripe payment", detail: "3 payments processed",
+ success: true, date: now.addingTimeInterval(-300)),
+ ]
+
+ // Notion
+ s.notionPages = [
+ NotionPage(id: "notion_demo1", title: "Product Roadmap Q4",
+ emoji: "🗺️", lastEditedAt: now.addingTimeInterval(-1800),
+ url: "https://notion.so/demo/roadmap"),
+ NotionPage(id: "notion_demo2", title: "Auth Refactor Notes",
+ emoji: "🔐", lastEditedAt: now.addingTimeInterval(-7200),
+ url: "https://notion.so/demo/auth-notes"),
+ ]
+ s.notionLoaded = true
+
+ // Inject GitHub pill only — rotating 4th integration added per cycle.
+ var injected: [String] = []
+ let githubId = "integration_github"
+ if !s.tasks.contains(where: { $0.id == githubId }),
+ let def = PillCatalog.available.first(where: { $0.id == githubId }) {
+ s.tasks.append(AgentTask(id: def.id, name: def.name, color: def.color,
+ state: .idle, steps: [], source: def.source, isIntegration: true))
+ injected.append(githubId)
+ }
+ demoInjectedTaskIds = injected
+ s.syncMode()
+ }
+
+ // MARK: Demo loop
+
+ private func runDemoLoop(gen: Int) async {
+ while !Task.isCancelled {
+ guard self.generation == gen else { return }
+ await runOneDemoCycle(gen: gen)
+ guard !Task.isCancelled, isActive, self.generation == gen else { break }
+ try? await Task.sleep(nanoseconds: 2_000_000_000)
+ }
+ }
+
+ private func runOneDemoCycle(gen: Int) async {
+ guard isActive else { return }
+ let s = AppState.shared
+ let mainPillId = s.mainPillId
+
+ // Inject the rotating 4th integration pill for this cycle.
+ let rotId = rotatingIntegrationIds[demoCycleIndex % rotatingIntegrationIds.count]
+ if !s.tasks.contains(where: { $0.id == rotId }),
+ let def = PillCatalog.available.first(where: { $0.id == rotId }) {
+ let rotState: BotState = (rotId == "integration_n8n") ? .finished : .idle
+ let rotSteps: [String] = (rotId == "integration_n8n")
+ ? ["Notify on new Stripe payment", "3 nodes executed", "Workflow success"]
+ : []
+ s.tasks.append(AgentTask(id: def.id, name: def.name, color: def.color,
+ state: rotState, steps: rotSteps, source: def.source, isIntegration: true))
+ if !demoInjectedTaskIds.contains(rotId) { demoInjectedTaskIds.append(rotId) }
+ }
+ s.syncMode()
+
+ // ── Step 1: Start VS Code session ────────────────────────────────────────
+ await waitUntilVisible()
+ guard isActive, self.generation == gen else { return }
+
+ s.focusId = mainPillId
+ if let idx = s.tasks.firstIndex(where: { $0.id == mainPillId }) {
+ s.tasks[idx].state = .working
+ s.tasks[idx].steps = []
+ s.tasks[idx].stepIndex = 0
+ s.tasks[idx].finalLine = nil
+ }
+
+ // ── Step 2: Session steps with diff ─────────────────────────────────────
+ let oldCode = """
+ const handleSubmit = async (e) => {
+ e.preventDefault()
+ setLoading(true)
+ const result = await signIn(email, password)
+ router.push('/dashboard')
+ setLoading(false)
+ }
+ """
+ let newCode = """
+ const handleSubmit = useCallback(async (e: FormEvent) => {
+ e.preventDefault()
+ setLoading(true)
+ try {
+ const result = await signIn(email, password)
+ if (result.error) throw new Error(result.error)
+ router.push('/dashboard')
+ } catch (err) {
+ setError((err as Error).message)
+ } finally {
+ setLoading(false)
+ }
+ }, [email, password, router])
+ """
+ let diff = DiffEngine.fromEdit(old: oldCode, new: newCode, path: "components/LoginForm.tsx")
+
+ let plainSteps = ["Reading auth/middleware.ts", "Running npm test — 23 tests"]
+ // Step 0
+ await waitUntilVisible(); guard isActive, self.generation == gen else { return }
+ if let idx = s.tasks.firstIndex(where: { $0.id == mainPillId }) {
+ s.tasks[idx].steps.append(plainSteps[0])
+ s.tasks[idx].stepIndex = 0
+ }
+ await sleep(2.0); guard isActive, self.generation == gen else { return }
+
+ // Diff step (index 1)
+ await waitUntilVisible(); guard isActive, self.generation == gen else { return }
+ let diffId = s.appendSessionDiff(diff, for: mainPillId)
+ trackDemoDiff(id: diffId, for: mainPillId)
+ let diffStep = String.makeDiffStep(filename: diff.name, added: diff.added,
+ removed: diff.removed, diffId: diffId)
+ if let idx = s.tasks.firstIndex(where: { $0.id == mainPillId }) {
+ s.tasks[idx].steps.append(diffStep)
+ s.tasks[idx].stepIndex = 1
+ }
+ await sleep(2.0); guard isActive, self.generation == gen else { return }
+
+ // Step 2
+ await waitUntilVisible(); guard isActive, self.generation == gen else { return }
+ if let idx = s.tasks.firstIndex(where: { $0.id == mainPillId }) {
+ s.tasks[idx].steps.append(plainSteps[1])
+ s.tasks[idx].stepIndex = 2
+ }
+ await sleep(2.0); guard isActive, self.generation == gen else { return }
+
+ // ── Step 3: Second session (Codex) ──────────────────────────────────────
+ await waitUntilVisible(); guard isActive, self.generation == gen else { return }
+ if !s.tasks.contains(where: { $0.id == "demo_codex" }) {
+ s.tasks.append(AgentTask(
+ id: "demo_codex", name: "Codex", color: "#E07950", state: .working,
+ steps: ["Reading src/api/routes.ts", "Editing routes.ts (+15 -3)"],
+ source: .agent, isIntegration: false
+ ))
+ s.syncMode()
+ }
+ await sleep(1.5); guard isActive, self.generation == gen else { return }
+
+ // ── Step 4: Permission request ───────────────────────────────────────────
+ // Does NOT call waitUntilVisible — the hookExpand will open the island.
+ // Skip if a real approval is waiting (don't overwrite HookServer's card).
+ var decision = "allow"
+ if !HookServer.shared.hasRealPendingApproval {
+ playSound("approval")
+ s.pendingApproval = ApprovalInfo(
+ sessionId: "demo_session",
+ tool: "Bash",
+ command: "npm test",
+ inputKey: #"{"command":"npm test"}"#,
+ pillId: mainPillId
+ )
+ s.isPinned = true
+ NotificationCenter.default.post(name: .hookExpand, object: IslandView.approval)
+ decision = await waitForApprovalOrTimeout(seconds: 8.0)
+ guard isActive, self.generation == gen else { return }
+ }
+
+ // ── Step 5: AskUserQuestion ──────────────────────────────────────────────
+ await waitUntilVisible(); guard isActive, self.generation == gen else { return }
+ var chosenReporter = "Verbose"
+ if !HookServer.shared.hasRealPendingQuestion {
+ await sleep(0.5); guard isActive, self.generation == gen else { return }
+ playSound("question")
+ s.pendingQuestion = AskQuestion(questions: [
+ AskQuestionItem(
+ question: "Which test reporter format?",
+ header: "Reporter",
+ options: [
+ AskQuestionOption(label: "Verbose", description: "Full output for each test"),
+ AskQuestionOption(label: "Dot", description: "Minimal one-dot-per-test"),
+ AskQuestionOption(label: "JSON", description: "Machine-readable JSON report"),
+ ],
+ multiSelect: false
+ )
+ ])
+ s.isPinned = true
+ NotificationCenter.default.post(name: .hookExpand, object: IslandView.question)
+ await waitForQuestionOrTimeout(seconds: 8.0)
+ chosenReporter = lastQuestionAnswer ?? "Verbose"
+ guard isActive, self.generation == gen else { return }
+ }
+
+ // ── Step 6: Finish primary session ───────────────────────────────────────
+ await waitUntilVisible(); guard isActive, self.generation == gen else { return }
+ await sleep(0.5); guard isActive, self.generation == gen else { return }
+ playSound("finish")
+ if let idx = s.tasks.firstIndex(where: { $0.id == mainPillId }) {
+ s.tasks[idx].state = .finished
+ s.tasks[idx].finalLine = decision == "deny"
+ ? "npm test skipped (denied). Staged — run tests before merge."
+ : "All 23 tests pass (\(chosenReporter)). Auth refactor complete — 94 % coverage."
+ }
+ NotificationCenter.default.post(name: .hookExpand, object: IslandView.finished)
+ await sleep(2.5); guard isActive, self.generation == gen else { return }
+
+ // ── Step 7: Chat ─────────────────────────────────────────────────────────
+ await waitUntilVisible(); guard isActive, self.generation == gen else { return }
+ s.chatHistory = []
+ NotificationCenter.default.post(name: .hookExpand, object: IslandView.prompt)
+ await sleep(1.0); guard isActive, self.generation == gen else { return }
+ s.chatHistory.append(ChatMessage(role: .user, content: "What did you change in LoginForm?"))
+ await sleep(0.4); guard isActive, self.generation == gen else { return }
+ await streamChatResponse(for: "What did you change in LoginForm?", gen: gen)
+ guard isActive, self.generation == gen else { return }
+ await sleep(2.0); guard isActive, self.generation == gen else { return }
+
+ // ── Step 8: Weekly recap ─────────────────────────────────────────────────
+ await waitUntilVisible(); guard isActive, self.generation == gen else { return }
+ NotificationCenter.default.post(name: .hookExpand, object: IslandView.recap)
+ await sleep(5.0); guard isActive, self.generation == gen else { return }
+
+ // ── Step 9: Reset for next cycle ─────────────────────────────────────────
+ s.chatHistory = []
+ s.stateOverride = nil
+ if let idx = s.tasks.firstIndex(where: { $0.id == mainPillId }) {
+ s.tasks[idx].state = .idle
+ s.tasks[idx].steps = []
+ s.tasks[idx].stepIndex = 0
+ s.tasks[idx].finalLine = nil
+ s.tasks[idx].pillBadge = nil
+ }
+ // Remove only demo diffs for mainPill
+ for id in (demoDiffIds[mainPillId] ?? []) {
+ s.sessionDiffs[mainPillId]?.removeAll { $0.id == id }
+ }
+ if s.sessionDiffs[mainPillId]?.isEmpty == true {
+ s.sessionDiffs.removeValue(forKey: mainPillId)
+ }
+ demoDiffIds.removeValue(forKey: mainPillId)
+
+ s.tasks.removeAll { $0.id == "demo_codex" }
+ // Remove rotating integration and advance cycle counter.
+ s.tasks.removeAll { $0.id == rotId }
+ demoInjectedTaskIds.removeAll { $0 == rotId }
+ demoCycleIndex += 1
+
+ if s.pendingApproval?.sessionId == "demo_session" { s.pendingApproval = nil }
+ if !HookServer.shared.hasRealPendingQuestion { s.pendingQuestion = nil }
+ if s.pendingApproval == nil && s.pendingQuestion == nil { s.isPinned = false }
+ s.focusId = mainPillId
+ lastApprovalDecision = "allow"
+ lastQuestionAnswer = nil
+ NotificationCenter.default.post(name: .islandCollapse, object: nil)
+ }
+
+ // MARK: Intercept handlers (called by HookServer)
+
+ func handleApprovalDecision(_ decision: String) {
+ lastApprovalDecision = decision
+ let c = approvalContinuation
+ approvalContinuation = nil
+ c?.resume(returning: decision)
+ }
+
+ func handleQuestionAnswered(answers: [String: Any]) {
+ lastQuestionAnswer = answers.values.first as? String
+ let c = questionContinuation
+ questionContinuation = nil
+ c?.resume()
+ }
+
+ // MARK: Chat streaming
+
+ /// Called by ClaudeService when the user types in chat during a demo.
+ func streamChatResponse(for query: String) async {
+ await streamChatResponse(for: query, gen: self.generation)
+ }
+
+ private func streamChatResponse(for query: String, gen: Int) async {
+ let s = AppState.shared
+ let response = """
+ I refactored LoginForm.tsx to be type-safe and resilient. \
+ The main change is wrapping handleSubmit in useCallback so it only recreates \
+ when its dependencies change, and adding a proper try/catch/finally block so \
+ loading is always reset even on error. An error state now shows the message \
+ inline rather than letting the exception bubble up unhandled. \
+ Coverage went from 79 % to 94 % after the test suite caught two edge \
+ cases the old code missed.
+ """
+ let msg = ChatMessage(role: .assistant, content: "")
+ let msgId = msg.id
+ s.chatHistory.append(msg)
+ let words = response.components(separatedBy: " ")
+ var built = ""
+ for word in words {
+ guard isActive, !Task.isCancelled, self.generation == gen else { break }
+ built += (built.isEmpty ? "" : " ") + word
+ guard let idx = s.chatHistory.firstIndex(where: { $0.id == msgId }) else { break }
+ s.chatHistory[idx].content = built
+ try? await Task.sleep(nanoseconds: 60_000_000)
+ guard isActive, !Task.isCancelled, self.generation == gen else { break }
+ }
+ }
+
+ // MARK: Helpers
+
+ private func trackDemoDiff(id: Int, for pillId: String) {
+ if demoDiffIds[pillId] == nil { demoDiffIds[pillId] = [] }
+ demoDiffIds[pillId]!.append(id)
+ }
+
+ private func playSound(_ name: String) {
+ let s = AppState.shared
+ guard s.soundEnabled, s.mode != .hidden else { return }
+ SoundEngine.shared.play(name)
+ }
+
+ /// Pauses until the island is visible (not hidden), or demo is stopped.
+ /// Observed via Combine publisher — no polling.
+ private func waitUntilVisible() async {
+ guard isActive, AppState.shared.mode == .hidden else { return }
+ await withCheckedContinuation { (cont: CheckedContinuation<Void, Never>) in
+ visibilityContinuation = cont
+ }
+ }
+
+ private func waitForApprovalOrTimeout(seconds: Double) async -> String {
+ let gen = self.generation
+ return await withCheckedContinuation { continuation in
+ self.approvalContinuation = continuation
+ let ns = UInt64(seconds * 1_000_000_000)
+ Task { @MainActor in
+ try? await Task.sleep(nanoseconds: ns)
+ guard self.generation == gen else { return }
+ guard self.isActive else { return }
+ guard let c = self.approvalContinuation else { return }
+ self.approvalContinuation = nil
+ // Auto-dismiss: only clear if still a demo card
+ let s = AppState.shared
+ if s.pendingApproval?.sessionId == "demo_session" {
+ s.pendingApproval = nil
+ s.isPinned = false
+ s.view = s.tasks.isEmpty ? .empty : .overview
+ }
+ c.resume(returning: "allow")
+ }
+ }
+ }
+
+ private func waitForQuestionOrTimeout(seconds: Double) async {
+ let gen = self.generation
+ await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
+ self.questionContinuation = continuation
+ let ns = UInt64(seconds * 1_000_000_000)
+ Task { @MainActor in
+ try? await Task.sleep(nanoseconds: ns)
+ guard self.generation == gen else { return }
+ guard self.isActive else { return }
+ guard let c = self.questionContinuation else { return }
+ self.questionContinuation = nil
+ // Only clear if no real question is pending
+ if !HookServer.shared.hasRealPendingQuestion {
+ let s = AppState.shared
+ s.pendingQuestion = nil
+ s.isPinned = false
+ s.view = s.tasks.isEmpty ? .empty : .overview
+ }
+ c.resume()
+ }
+ }
+ }
+
+ private func sleep(_ seconds: Double) async {
+ try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
+ }
+
+ // MARK: Demo weekly summary
+
+ private func demoWeeklySummary() -> WeeklySummary {
+ let cal = Calendar(identifier: .iso8601)
+ var comps = cal.dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date())
+ comps.weekday = 2
+ let thisMonday = cal.date(from: comps) ?? Date()
+ let lastMonday = cal.date(byAdding: .weekOfYear, value: -1, to: thisMonday) ?? Date()
+ let lastSunday = cal.date(byAdding: .day, value: 6, to: lastMonday) ?? Date()
+ return WeeklySummary(
+ weekStart: lastMonday, weekEnd: lastSunday,
+ totalMinutes: 840, sessionCount: 23,
+ filesChanged: 187, linesAdded: 3412, linesRemoved: 891,
+ commandsRun: 142, questionsAnswered: 31,
+ permissionsAllowed: 58, permissionsDenied: 4,
+ topAgent: "Claude Code", topProject: "my-app",
+ busiestDay: "Wednesday", longestSessionMinutes: 94
+ )
+ }
+}
diff --git a/NotchBuddy/Sources/App/GithubPoller.swift b/NotchBuddy/Sources/App/GithubPoller.swift
index 4cfb81d1..2307d263 100644
--- a/NotchBuddy/Sources/App/GithubPoller.swift
+++ b/NotchBuddy/Sources/App/GithubPoller.swift
@@ -44,6 +44,7 @@ final class GithubPoller: @unchecked Sendable {
// MARK: - Stats (unchanged logic)
private func pollStats() {
+ guard !DemoEngine.isPollerPaused else { return }
guard let token = KeychainStore.shared.get("github-token") else { return }
fetchUser(token: token)
}
@@ -90,6 +91,7 @@ final class GithubPoller: @unchecked Sendable {
/// Dispatches guards + state reads to main, then fires network on background.
private func pollPulse() {
+ guard !DemoEngine.isPollerPaused else { scheduleNextPulse(hasPending: false); return }
DispatchQueue.main.async { [weak self] in
guard let self, !self.pulseInFlight else { return }
guard let token = KeychainStore.shared.get("github-token"),
@@ -207,6 +209,7 @@ final class GithubPoller: @unchecked Sendable {
// MARK: - Activity (contribution calendar, 30 min cadence)
private func pollActivity() {
+ guard !DemoEngine.isPollerPaused else { scheduleNextActivity(); return }
DispatchQueue.main.async { [weak self] in
guard let self, !self.activityInFlight else { return }
guard let token = KeychainStore.shared.get("github-token"),
diff --git a/NotchBuddy/Sources/App/HookServer.swift b/NotchBuddy/Sources/App/HookServer.swift
index 3219d0a5..5084320c 100644
--- a/NotchBuddy/Sources/App/HookServer.swift
+++ b/NotchBuddy/Sources/App/HookServer.swift
@@ -42,6 +42,11 @@ final class HookServer: @unchecked Sendable {
private var approvalFDSource: (any DispatchSourceRead)? = nil // monitors pendingApprovalFD
private var pendingQuestionFD: Int32 = -1 // held open while user answers AskUserQuestion
private var questionFDSource: (any DispatchSourceRead)? = nil // monitors pendingQuestionFD
+
+ /// True when a real nb-hook connection is holding the approval fd open.
+ @MainActor var hasRealPendingApproval: Bool { pendingApprovalFD >= 0 }
+ /// True when a real nb-hook connection is holding the question fd open.
+ @MainActor var hasRealPendingQuestion: Bool { pendingQuestionFD >= 0 }
private var questionPillId: String = "" // pill that owns the pending question
private var questionSessionId: String = "" // sessionId for the pending question (recap tracking)
private var focusBeforeQuestion: String? = nil // saved focus to restore after question
@@ -124,6 +129,14 @@ final class HookServer: @unchecked Sendable {
/// Called by QuestionView. Sends answers JSON and cleans up.
@MainActor
func sendQuestionAnswers(_ answers: [String: Any]) {
+ // Only intercept a demo question — real questions always have a live fd.
+ if DemoEngine.shared.isActive, pendingQuestionFD < 0 {
+ AppState.shared.pendingQuestion = nil
+ AppState.shared.isPinned = false
+ AppState.shared.view = AppState.shared.tasks.isEmpty ? .empty : .overview
+ DemoEngine.shared.handleQuestionAnswered(answers: answers)
+ return
+ }
let fd = pendingQuestionFD
pendingQuestionFD = -1
let source = questionFDSource
@@ -393,7 +406,8 @@ final class HookServer: @unchecked Sendable {
// 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 {
+ if let pending = state.pendingApproval, agentId == pending.pillId,
+ pending.sessionId != "demo_session" {
let handledNote: String
switch pending.pillId {
case "agent_cursor": handledNote = "Handled in Cursor."
@@ -772,6 +786,17 @@ final class HookServer: @unchecked Sendable {
/// Called by ApprovalView buttons. Writes the decision to the waiting nb-hook and cleans up.
@MainActor
func sendApprovalDecision(_ decision: String) {
+ // Only intercept a demo card — a real card has a live fd (pendingApprovalFD >= 0).
+ if DemoEngine.shared.isActive,
+ AppState.shared.pendingApproval?.sessionId == "demo_session",
+ pendingApprovalFD < 0 {
+ let s = AppState.shared
+ s.pendingApproval = nil
+ s.isPinned = false
+ s.view = s.tasks.isEmpty ? .empty : .overview
+ DemoEngine.shared.handleApprovalDecision(decision)
+ return
+ }
let fd = pendingApprovalFD
pendingApprovalFD = -1
// Capture source before nulling — we send the decision first, then cancel the source.
diff --git a/NotchBuddy/Sources/App/IslandRootView.swift b/NotchBuddy/Sources/App/IslandRootView.swift
index eb91f230..c7a1b9eb 100644
--- a/NotchBuddy/Sources/App/IslandRootView.swift
+++ b/NotchBuddy/Sources/App/IslandRootView.swift
@@ -22,6 +22,7 @@ struct IslandRootView: View {
struct IslandContainer: View {
@ObservedObject var state: AppState
+ @ObservedObject private var demoEngine = DemoEngine.shared
@State private var islandWidth: CGFloat = IslandConst.notchWidth
@State private var islandHeight: CGFloat = IslandConst.notchHeight
@State private var cornerRadius: CGFloat = IslandConst.roundedCorner
@@ -106,6 +107,19 @@ struct IslandContainer: View {
CountdownBar(state: state, islandW: islandWidth)
+ if demoEngine.isActive {
+ Text(verbatim: "DEMO")
+ .font(.system(size: 8, weight: .bold, design: .monospaced))
+ .foregroundColor(.black)
+ .padding(.horizontal, 5)
+ .padding(.vertical, 2)
+ .background(Color(hex: "#4ADE80"))
+ .clipShape(Capsule())
+ .position(x: 18, y: islandHeight - 8)
+ .transition(.opacity.combined(with: .scale(scale: 0.8)))
+ .animation(.spring(response: 0.3, dampingFraction: 0.8), value: demoEngine.isActive)
+ }
+
Group {
if state.mode == .compact {
CompactMiniGrid(state: state)
@@ -558,11 +572,11 @@ struct ClaudePlanHeaderPill: View {
@State private var isHovered = false
private var effectiveColor: String {
- ClaudePlanGauge.color(for: state.claudePlanUsage.flatMap { ClaudePlanGauge.dominantPct($0) })
+ ClaudePlanGauge.color(for: (state.demoPlanUsageOverride ?? state.claudePlanUsage).flatMap { ClaudePlanGauge.dominantPct($0) })
}
private var label: String {
- guard let usage = state.claudePlanUsage,
+ guard let usage = state.demoPlanUsageOverride ?? state.claudePlanUsage,
let pct = ClaudePlanGauge.dominantPct(usage) else { return "Claude —" }
return "Claude \(Int(pct.rounded()))%"
}
diff --git a/NotchBuddy/Sources/App/N8nPoller.swift b/NotchBuddy/Sources/App/N8nPoller.swift
index 3ce76e4c..1a8f4c5d 100644
--- a/NotchBuddy/Sources/App/N8nPoller.swift
+++ b/NotchBuddy/Sources/App/N8nPoller.swift
@@ -24,6 +24,7 @@ final class N8nPoller: @unchecked Sendable {
// MARK: - Poll list endpoint
private func poll() {
+ guard !DemoEngine.isPollerPaused else { return }
guard let apiKey = KeychainStore.shared.get("n8n-api-key"),
let rawBase = KeychainStore.shared.get("n8n-url") else {
n8nLog("No API key or URL configured")
diff --git a/NotchBuddy/Sources/App/NotionPoller.swift b/NotchBuddy/Sources/App/NotionPoller.swift
index 1e6b7c3e..b92e0f08 100644
--- a/NotchBuddy/Sources/App/NotionPoller.swift
+++ b/NotchBuddy/Sources/App/NotionPoller.swift
@@ -17,6 +17,7 @@ final class NotionPoller: @unchecked Sendable {
func pollNow() { poll() }
private func poll() {
+ guard !DemoEngine.isPollerPaused else { return }
guard let token = KeychainStore.shared.get("notion-api-key") else { return }
guard let url = URL(string: "https://api.notion.com/v1/search") else { return }
var req = URLRequest(url: url, timeoutInterval: 10)
diff --git a/NotchBuddy/Sources/App/PhoneLink/ApprovalRelay.swift b/NotchBuddy/Sources/App/PhoneLink/ApprovalRelay.swift
index 0f528469..392cd720 100644
--- a/NotchBuddy/Sources/App/PhoneLink/ApprovalRelay.swift
+++ b/NotchBuddy/Sources/App/PhoneLink/ApprovalRelay.swift
@@ -57,6 +57,8 @@ final class ApprovalRelay {
// MARK: Request lifecycle
private func pendingChanged(to approval: ApprovalInfo?) {
+ // Never publish demo approval cards to iCloud
+ if approval?.sessionId == "demo_session" { return }
let fingerprint = approval.map(Self.fingerprint)
if let old = current, old.fingerprint != fingerprint {
pollTask?.cancel()
diff --git a/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swift b/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swift
index 80e3dcf0..0e980319 100644
--- a/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swift
+++ b/NotchBuddy/Sources/App/PhoneLink/LiveActivityRelay.swift
@@ -186,6 +186,7 @@ final class LiveActivityRelay {
// MARK: Sending
private func begin(_ state: MochiActivityState) {
+ guard !DemoEngine.shared.isActive else { return }
let start = Date()
activitySince = Int(start.timeIntervalSince1970)
startedAt = start
@@ -217,6 +218,7 @@ final class LiveActivityRelay {
/// Sends the latest state if it changed, one request at a time.
private func flush() {
+ guard !DemoEngine.shared.isActive else { return }
guard !sending, let startedAt, let state = latest, state != sent else { return }
sending = true
Task {
diff --git a/NotchBuddy/Sources/App/PhoneLink/QuestionRelay.swift b/NotchBuddy/Sources/App/PhoneLink/QuestionRelay.swift
index 51e02385..a60adbbe 100644
--- a/NotchBuddy/Sources/App/PhoneLink/QuestionRelay.swift
+++ b/NotchBuddy/Sources/App/PhoneLink/QuestionRelay.swift
@@ -42,6 +42,8 @@ final class QuestionRelay {
}
private func pendingChanged(to payload: QuestionPayload?) {
+ // Never publish demo questions (they have no real fd in HookServer)
+ if payload != nil, !HookServer.shared.hasRealPendingQuestion { return }
let fingerprint = payload?.fingerprint
guard current?.fingerprint != fingerprint else { return }
pollTask?.cancel()
diff --git a/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift b/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift
index 237e1309..b2edda00 100644
--- a/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift
+++ b/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift
@@ -70,6 +70,7 @@ final class SessionPublisher {
// MARK: Publishing
private func publish(_ snapshots: [String: SessionSnapshot]) {
+ guard !DemoEngine.shared.isActive else { return }
guard !publishing else { pending = snapshots; return }
publishing = true
Task {
diff --git a/NotchBuddy/Sources/App/RecapStore.swift b/NotchBuddy/Sources/App/RecapStore.swift
index 4e5337df..6884f43d 100644
--- a/NotchBuddy/Sources/App/RecapStore.swift
+++ b/NotchBuddy/Sources/App/RecapStore.swift
@@ -67,6 +67,8 @@ final class RecapStore {
static let shared = RecapStore()
private var data = RecapData()
+ /// Set by DemoEngine to inject a fake summary without touching disk.
+ var demoSummaryOverride: WeeklySummary? = nil
/// Keyed by sessionId so concurrent sessions from the same agent are tracked separately.
private var drafts: [String: TurnDraft] = [:]
@@ -153,6 +155,7 @@ final class RecapStore {
/// Returns a summary for the last completed week (Mon–Sun, ISO 8601).
/// Pass a custom `weekStart` (Monday 00:00 local) to query a different week.
func weeklySummary(for weekStart: Date? = nil) -> WeeklySummary? {
+ if let demo = demoSummaryOverride { return demo }
// ISO 8601 calendar: weeks start on Monday regardless of locale.
let cal = Calendar(identifier: .iso8601)
let start: Date
diff --git a/NotchBuddy/Sources/App/ResendPoller.swift b/NotchBuddy/Sources/App/ResendPoller.swift
index a1f6e391..6fbfaced 100644
--- a/NotchBuddy/Sources/App/ResendPoller.swift
+++ b/NotchBuddy/Sources/App/ResendPoller.swift
@@ -15,6 +15,7 @@ final class ResendPoller: @unchecked Sendable {
}
private func poll() {
+ guard !DemoEngine.isPollerPaused else { return }
guard let apiKey = KeychainStore.shared.get("resend-api-key") else { return }
guard let url = URL(string: "https://api.resend.com/emails?limit=100") else { return }
var req = URLRequest(url: url, timeoutInterval: 10)
diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swift
index ac05a984..5fea56ff 100644
--- a/NotchBuddy/Sources/App/SettingsView.swift
+++ b/NotchBuddy/Sources/App/SettingsView.swift
@@ -4,6 +4,7 @@ import AppKit
struct SettingsView: View {
@ObservedObject private var state = AppState.shared
+ @ObservedObject private var demoEngine = DemoEngine.shared
@State private var apiKey: String = KeychainStore.shared.get("anthropic-api-key") ?? ""
// Claude model — dynamic list fetched from the API, static fallback if unavailable
@@ -246,6 +247,21 @@ struct SettingsView: View {
// MARK: - General section
@ViewBuilder private var generalSection: some View {
+ GroupBox(String(localized: "demo.groupbox.title")) {
+ VStack(alignment: .leading, spacing: 8) {
+ Text(String(localized: "demo.description"))
+ .font(.system(size: 11))
+ .foregroundColor(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ Button(demoEngine.isActive ? String(localized: "demo.stop") : String(localized: "demo.start")) {
+ if demoEngine.isActive { DemoEngine.shared.stop() }
+ else { DemoEngine.shared.start() }
+ }
+ .buttonStyle(.borderedProminent)
+ }
+ .padding(6)
+ }
+
GroupBox("Sound") {
VStack(alignment: .leading, spacing: 10) {
Toggle("Enable sounds", isOn: $state.soundEnabled)
diff --git a/NotchBuddy/Sources/App/StripePoller.swift b/NotchBuddy/Sources/App/StripePoller.swift
index 6aeec6c1..ba86eda8 100644
--- a/NotchBuddy/Sources/App/StripePoller.swift
+++ b/NotchBuddy/Sources/App/StripePoller.swift
@@ -26,6 +26,7 @@ final class StripePoller: @unchecked Sendable {
func pollNow() { poll() }
private func poll() {
+ guard !DemoEngine.isPollerPaused else { return }
guard let key = KeychainStore.shared.get("stripe-api-key") else { return }
fetchBalance(key: key)
fetchCharges(key: key)
diff --git a/NotchBuddy/Sources/App/VercelPoller.swift b/NotchBuddy/Sources/App/VercelPoller.swift
index 41b24923..8cfe6088 100644
--- a/NotchBuddy/Sources/App/VercelPoller.swift
+++ b/NotchBuddy/Sources/App/VercelPoller.swift
@@ -23,6 +23,7 @@ final class VercelPoller: @unchecked Sendable {
// MARK: - Poll
private func poll() {
+ guard !DemoEngine.isPollerPaused else { return }
guard let token = KeychainStore.shared.get("vercel-token") else { return }
// Fetch last 5 terminal deployments
diff --git a/NotchBuddy/project.yml b/NotchBuddy/project.yml
index 40951d71..de4a079c 100644
--- a/NotchBuddy/project.yml
+++ b/NotchBuddy/project.yml
@@ -194,7 +194,7 @@ targets:
CFBundleName: Coucou
CFBundleDisplayName: Coucou
CFBundleIdentifier: fr.louisraille.Coucou
- CFBundleVersion: "5"
+ CFBundleVersion: "6"
CFBundleShortVersionString: "1.1"
CFBundlePackageType: APPL
LSUIElement: YES
diff --git a/README.md b/README.md
index 439e499a..48edeba8 100644
--- a/README.md
+++ b/README.md
@@ -114,6 +114,12 @@ macOS releases are published as `v*` tags. See [CHANGELOG.md](CHANGELOG.md) for
Windows 0.1.1 and Linux 0.1.1 (beta) are in Releases under the `windows-v*` and `linux-v*` tags.
+## Demo mode
+
+No API key, no Claude Code, no setup — open **Settings → General → Demo**, click **Try demo mode**, and Coucou walks through a scripted session: a Claude Code session with live steps and a diff you can read, a permission request, an AskUserQuestion, a parallel Codex session, the GitHub, Stripe, Vercel and other integration pills loaded with sample data, the chat with a streamed response, the weekly recap with a share image you can actually save.
+
+Nothing is written to disk during the demo — no Keychain entries, no hook files, no recap history. Your real sessions and keys are saved and restored exactly as they were when you stop.
+
## Install
### App Store