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.

Mochi on the desktop (#198)

Louis2b02b9156595
diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
index aa91f517..6bd6b0ae 100644
--- a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
@@ -24,6 +24,7 @@
1969590AFEE6CB21404346F1 /* CalcomPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3104222B3F17BA5E8DEA5277 /* CalcomPoller.swift */; };
1F11EC4E6F604C612A1ADAD1 /* AppState.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2E4F18AA940EFF7E047B9F7 /* AppState.swift */; };
2132477000FD77F7EB234DAA /* FileDropView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3232F258523DD8D09B670363 /* FileDropView.swift */; };
+ 273FC0FA14AAF6CE62FD14AE /* DesktopMochi.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1DDC96E7967032F5D0BD585 /* DesktopMochi.swift */; };
2875610F701376BD65573386 /* WindowContextCapture.swift in Sources */ = {isa = PBXBuildFile; fileRef = E91B733ADC638E14E9BB6EFA /* WindowContextCapture.swift */; };
2C798C3837A63B9BB561A1A0 /* HookServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79D8DD79C3DD9BBC584B3CB2 /* HookServer.swift */; };
2CC2E3B688B15BBEB3AE3BCE /* WindowContextCapture.swift in Sources */ = {isa = PBXBuildFile; fileRef = E91B733ADC638E14E9BB6EFA /* WindowContextCapture.swift */; };
@@ -68,12 +69,15 @@
B2D86BE268D6F4C86BD0C446 /* ChatMarkdown.swift in Sources */ = {isa = PBXBuildFile; fileRef = D797CC384B5BC70D34F121BC /* ChatMarkdown.swift */; };
B3EC9CF3C8BD629C3530E8F1 /* sounds in Resources */ = {isa = PBXBuildFile; fileRef = C066E2B991AA4F56B2724263 /* sounds */; };
B605F976F4141435F27CF266 /* IslandRootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15A1A8206F73376F4CAF2057 /* IslandRootView.swift */; };
+ BA65FC4A40F7227837C26214 /* DesktopMochiLogic.swift in Sources */ = {isa = PBXBuildFile; fileRef = C086E1932F86B9C2B559BE03 /* DesktopMochiLogic.swift */; };
+ BEC5DDB55B3DA67C61CA8470 /* DesktopMochi.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1DDC96E7967032F5D0BD585 /* DesktopMochi.swift */; };
C0E18D0F6F5F6D131E6066B8 /* GreetingCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C581F7B1A9F14B281B60063E /* GreetingCanvasView.swift */; };
C18227D148D99FE6EE3CC51A /* GithubPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CB8B6E5E9DA6164F979E88F /* GithubPoller.swift */; };
C1A29371181553FB4169E195 /* DiffEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DB24C2469551040FBAA4DBF /* DiffEngine.swift */; };
C24D863967D8D32D828ED4B1 /* BotEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4540F630F8BA04AFFFA3979 /* BotEngine.swift */; };
C61DDE2EC5FDDB39E4AA3B34 /* IslandWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D710BD7834228045869D0184 /* IslandWindowController.swift */; };
C808B654C84D9F71DBF8493A /* GithubPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CB8B6E5E9DA6164F979E88F /* GithubPoller.swift */; };
+ C93BA975D35B8CD7473CF995 /* DesktopMochiLogic.swift in Sources */ = {isa = PBXBuildFile; fileRef = C086E1932F86B9C2B559BE03 /* DesktopMochiLogic.swift */; };
C940B651C6CA952D99388E04 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 192844E7299DEED5C2372067 /* AppDelegate.swift */; };
CA3321C14A11FED94E48B3E3 /* IslandRootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15A1A8206F73376F4CAF2057 /* IslandRootView.swift */; };
CD8DECA66B9E09C97E469DB9 /* BotCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A29F4C0B02BE91654D02AA0C /* BotCanvasView.swift */; };
@@ -127,12 +131,14 @@
A14A61070D293AB4BBA303F7 /* NotchBuddy.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = NotchBuddy.app; sourceTree = BUILT_PRODUCTS_DIR; };
A29F4C0B02BE91654D02AA0C /* BotCanvasView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotCanvasView.swift; sourceTree = "<group>"; };
A83D5410BD030B243ADDCFF4 /* ClaudeService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeService.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>"; };
B2FDED98F7F6C755A72C97A3 /* SafeWebURL.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SafeWebURL.swift; sourceTree = "<group>"; };
B89DA1A0C21AE3535A1760BB /* N8nPoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = N8nPoller.swift; sourceTree = "<group>"; };
BE03E03D1804B0B92C5C2DAD /* NotionPoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotionPoller.swift; sourceTree = "<group>"; };
BFE88A53AEAA637F866D479D /* ChatMarkdownView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatMarkdownView.swift; sourceTree = "<group>"; };
C066E2B991AA4F56B2724263 /* sounds */ = {isa = PBXFileReference; lastKnownFileType = folder; name = sounds; path = Resources/sounds; sourceTree = SOURCE_ROOT; };
+ C086E1932F86B9C2B559BE03 /* DesktopMochiLogic.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DesktopMochiLogic.swift; sourceTree = "<group>"; };
C0BB15BD82E4A0B729045880 /* MochiWardrobe.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MochiWardrobe.swift; sourceTree = "<group>"; };
C2E4F18AA940EFF7E047B9F7 /* AppState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppState.swift; sourceTree = "<group>"; };
C581F7B1A9F14B281B60063E /* GreetingCanvasView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GreetingCanvasView.swift; sourceTree = "<group>"; };
@@ -165,6 +171,8 @@
F4263B550838CC5614569D13 /* ClaudePlanCardView.swift */,
8BF22817EC70748F2D1FB2E7 /* ClaudePlanGauge.swift */,
A83D5410BD030B243ADDCFF4 /* ClaudeService.swift */,
+ B1DDC96E7967032F5D0BD585 /* DesktopMochi.swift */,
+ C086E1932F86B9C2B559BE03 /* DesktopMochiLogic.swift */,
3DB24C2469551040FBAA4DBF /* DiffEngine.swift */,
3232F258523DD8D09B670363 /* FileDropView.swift */,
168A9A73B519018FAB0AA465 /* GitHubActivity.swift */,
@@ -350,6 +358,8 @@
94E0849D13762C6EC8548FEF /* ClaudePlanCardView.swift in Sources */,
D861479F6E7EAD07A6AC2105 /* ClaudePlanGauge.swift in Sources */,
2DEB459FBD0BA3CEAAA5FDE9 /* ClaudeService.swift in Sources */,
+ BEC5DDB55B3DA67C61CA8470 /* DesktopMochi.swift in Sources */,
+ BA65FC4A40F7227837C26214 /* DesktopMochiLogic.swift in Sources */,
6697436AA05A3F92C1DD85C3 /* DiffEngine.swift in Sources */,
E776C7D1DE5C62EA8D4BA3E3 /* FileDropView.swift in Sources */,
D9FF132804EB458F6FA69116 /* GitHubActivity.swift in Sources */,
@@ -400,6 +410,8 @@
18D47AE663EB96BE5638D5F7 /* ClaudePlanCardView.swift in Sources */,
E9C21D11BCB72C392436D19E /* ClaudePlanGauge.swift in Sources */,
0329E76BA4A8FEEA8A6D76E7 /* ClaudeService.swift in Sources */,
+ 273FC0FA14AAF6CE62FD14AE /* DesktopMochi.swift in Sources */,
+ C93BA975D35B8CD7473CF995 /* DesktopMochiLogic.swift in Sources */,
C1A29371181553FB4169E195 /* DiffEngine.swift in Sources */,
2132477000FD77F7EB234DAA /* FileDropView.swift in Sources */,
63093DC288B68F7F17249517 /* GitHubActivity.swift in Sources */,
diff --git a/NotchBuddy/Sources/App/AppDelegate.swift b/NotchBuddy/Sources/App/AppDelegate.swift
index d3517c13..6e4c47a6 100644
--- a/NotchBuddy/Sources/App/AppDelegate.swift
+++ b/NotchBuddy/Sources/App/AppDelegate.swift
@@ -105,6 +105,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
NotionPoller.shared.start()
NotificationCenter.default.addObserver(self, selector: #selector(openSettingsFromNotification(_:)),
name: .openFullSettings, object: nil)
+ // After the greeting ends, fly Mochi back to the desktop if it was there at last quit
+ NotificationCenter.default.addObserver(forName: .greetComplete, object: nil, queue: .main) { _ in
+ DesktopMochiController.shared.launchFlyIfNeeded()
+ }
#if !APPSTORE
_ = MusicController.shared
#endif
diff --git a/NotchBuddy/Sources/App/AppState.swift b/NotchBuddy/Sources/App/AppState.swift
index 7953f272..77fc32cd 100644
--- a/NotchBuddy/Sources/App/AppState.swift
+++ b/NotchBuddy/Sources/App/AppState.swift
@@ -29,6 +29,9 @@ final class AppState: ObservableObject {
// Bot drag-attach state (hides original bot while ghost follows cursor)
@Published var isDraggingBot: Bool = false
+ // Desktop Mochi: true while Mochi lives on the desktop instead of the notch
+ @Published var mochiOnDesktop: Bool = false
+
// Mouse tracking
var mousePosition: CGPoint = .zero
var lastMouseMove: Date = .now
diff --git a/NotchBuddy/Sources/App/BotCanvasView.swift b/NotchBuddy/Sources/App/BotCanvasView.swift
index a0374815..e80be390 100644
--- a/NotchBuddy/Sources/App/BotCanvasView.swift
+++ b/NotchBuddy/Sources/App/BotCanvasView.swift
@@ -5,6 +5,9 @@ import SwiftUI
struct BotCanvasView: View {
@ObservedObject var state: AppState
var particleOverhang: CGFloat = 0
+ /// When set, overrides island-based eye-tracking (used by desktop Mochi).
+ /// CGPoint in the same coord space as state.mousePosition (y-down from screen top).
+ var lookOriginOverride: CGPoint? = nil
// One engine per view instance (main bot)
@StateObject private var engine = BotEngine()
@@ -147,6 +150,9 @@ struct BotCanvasView: View {
}
private func lookX(state: AppState, size: CGSize) -> CGFloat {
+ if let origin = lookOriginOverride {
+ return tanh((state.mousePosition.x - origin.x) / 260)
+ }
let screen = NSScreen.main ?? NSScreen.screens[0]
let (islandW, islandH) = islandSize(mode: state.mode, view: state.view,
progress: state.uploadProgress,
@@ -160,6 +166,9 @@ struct BotCanvasView: View {
}
private func lookY(state: AppState, size: CGSize) -> CGFloat {
+ if let origin = lookOriginOverride {
+ return -tanh((state.mousePosition.y - origin.y) / 200)
+ }
let (islandW, islandH) = islandSize(mode: state.mode, view: state.view,
progress: state.uploadProgress,
nw: state.notchWidth, nh: state.notchHeight)
diff --git a/NotchBuddy/Sources/App/DesktopMochi.swift b/NotchBuddy/Sources/App/DesktopMochi.swift
new file mode 100644
index 00000000..9ec7f4ff
--- /dev/null
+++ b/NotchBuddy/Sources/App/DesktopMochi.swift
@@ -0,0 +1,732 @@
+import AppKit
+import SwiftUI
+import Combine
+
+// MARK: - Desktop bot view state
+
+/// Observable bridge so DesktopMochiController can update view-level state without
+/// coupling to SwiftUI @State.
+@MainActor
+final class DesktopBotViewState: ObservableObject {
+ /// Drop to 10 fps when sleeping (saves energy).
+ @Published var isSleeping: Bool = false
+ /// Pause entirely (screen sleep / lock).
+ @Published var paused: Bool = false
+ /// Bot center in the same coord space as AppState.mousePosition (y-down from screen top).
+ /// Updated every poll frame; Canvas reads it inside TimelineView — @Published not needed.
+ var lookOrigin: CGPoint = .zero
+}
+
+// MARK: - Desktop bot view
+
+/// Full Mochi character rendered inside the desktop floating panel.
+struct DesktopBotView: View {
+ @ObservedObject var appState: AppState
+ /// Engine owned by DesktopMochiController; controller calls methods on it directly.
+ let engine: BotEngine
+ @ObservedObject var viewState: DesktopBotViewState
+
+ var body: some View {
+ TimelineView(.animation(
+ minimumInterval: viewState.isSleeping ? 1.0 / 10.0 : 1.0 / 30.0,
+ paused: viewState.paused
+ )) { timeline in
+ Canvas { ctx, size in
+ let now = timeline.date.timeIntervalSinceReferenceDate
+ let dt = min(0.05, now - engine.lastTime)
+
+ // Eye tracking based on the panel's own screen position
+ engine.lookX = tanh((appState.mousePosition.x - viewState.lookOrigin.x) / 260)
+ engine.lookY = -tanh((appState.mousePosition.y - viewState.lookOrigin.y) / 200)
+
+ // Desktop Mochi is always the "main" Mochi — always dressed
+ engine.setOutfit(appState.resolvedOutfit, animated: true)
+
+ // Dance when music plays (same rules as compact mode)
+ let dancing: Bool = {
+ #if !APPSTORE
+ guard appState.musicPlaying else { return false }
+ guard appState.activeIntegrations.contains("integration_music") else { return false }
+ let allowed: Set<BotState> = [.idle, .working, .thinking, .searching, .finished]
+ return allowed.contains(appState.effectiveState)
+ #else
+ return false
+ #endif
+ }()
+ engine.setDancing(dancing)
+ engine.update(dt: dt)
+
+ var c = ctx
+ engine.applyDance(&c, size: size)
+
+ // Rigid roll when outfit is present (matches BotCanvasView)
+ if engine.outfit != .none && engine.outfitPresence > 0.05 && abs(engine.roll) > 0.001 {
+ let center = engine.bodyCenter(size: size)
+ var rigidCtx = c
+ rigidCtx.translateBy(x: center.x, y: center.y)
+ rigidCtx.rotate(by: .radians(engine.roll))
+ rigidCtx.translateBy(x: -center.x, y: -center.y)
+ engine.drawHandsBehind(context: rigidCtx, size: size)
+ engine.drawOutfitBehind(context: rigidCtx, size: size)
+ engine.draw(context: rigidCtx, size: size)
+ engine.drawOutfitFront(context: rigidCtx, size: size)
+ } else {
+ engine.drawHandsBehind(context: c, size: size)
+ engine.drawOutfitBehind(context: c, size: size)
+ engine.draw(context: c, size: size)
+ engine.drawOutfitFront(context: c, size: size)
+ }
+ engine.drawHandsAndExtras(context: c, size: size)
+ }
+ }
+ .onChange(of: appState.effectiveState) { _, newState in
+ engine.setState(newState)
+ }
+ .onAppear {
+ engine.setState(appState.effectiveState, force: true)
+ engine.setOutfit(appState.resolvedOutfit, animated: false)
+ }
+ }
+}
+
+// MARK: - Desktop Mochi controller
+
+/// Manages the "Mochi on the desktop" floating panel.
+///
+/// Life cycle:
+/// - **Install from drag**: `IslandWindowController.finishDrag` calls `install(ghostPanel:at:)`.
+/// - **Launch restore**: `AppDelegate` observes `.greetComplete` → `launchFlyIfNeeded()`.
+/// - **Alert**: `pendingApproval`/`pendingQuestion` goes non-nil → surprised emote →
+/// `retractForAlert()` (panel gone, flag stays true) → both nil → `launchFlyIfNeeded()`.
+/// - **User flies home**: double-click → `flyHome()` → full teardown.
+@MainActor
+final class DesktopMochiController {
+ static let shared = DesktopMochiController()
+ private init() {
+ observeScreenSleep()
+ observeScreenLock()
+ observeAlerts() // permanent — lives for the lifetime of the singleton
+ }
+
+ private var panel: NSPanel?
+ private var engine: BotEngine?
+ private var viewState: DesktopBotViewState?
+ private var frameTimer: Timer?
+
+ // Alert state machine
+ private var phase: DesktopPhase = .home
+
+ // Desktop drag repositioning
+ private var isDragging = false
+ private var dragMouseStart: NSPoint = .zero
+ private var dragOriginAtStart: NSPoint = .zero
+
+ // Deferred single-click slap
+ private var pendingSlapWorkItem: DispatchWorkItem?
+
+ // Sleep detection
+ private var lastAgentActive: Date = .distantPast
+ private var isSleeping = false
+
+ // Screen sleep / lock
+ private var screenSleeping = false
+
+ // Lifecycle subscriptions (cleared on retractForAlert + fullTearDown)
+ private var cancellables: Set<AnyCancellable> = []
+ // Alert subscription — permanent, only released with the singleton
+ private var alertSubscription: AnyCancellable?
+
+ // Event monitors
+ private var mouseDownMonitor: Any?
+ private var mouseDraggedMonitor: Any?
+ private var mouseUpMonitor: Any?
+ private var globalMouseUpMonitor: Any?
+ private var rightClickMonitor: Any?
+
+ // UserDefaults keys
+ private static let posXKey = "desktopMochiX"
+ private static let posYKey = "desktopMochiY"
+ private static let enabledKey = "mochiOnDesktop"
+
+ static let panelSize: CGFloat = DesktopMochiLogic.panelSize
+
+ // MARK: - Install (from drag-drop)
+
+ /// Promote `ghostPanel` (the drag ghost) or create a fresh panel as the desktop Mochi,
+ /// centered on `screenPoint`. Called by `IslandWindowController.finishDrag`.
+ func install(ghostPanel: NSPanel?, at screenPoint: NSPoint) {
+ guard panel == nil, phase == .home else { ghostPanel?.close(); return }
+ let s = DesktopMochiController.panelSize
+
+ let p: NSPanel
+ if let ghost = ghostPanel {
+ p = ghost
+ } else {
+ p = makeBlankPanel()
+ p.setFrame(NSRect(x: screenPoint.x - s/2, y: screenPoint.y - s/2, width: s, height: s),
+ display: false)
+ }
+
+ // Build engine + hosting view (autoresizingMask lets it grow with the panel animation)
+ let eng = BotEngine()
+ eng.setState(AppState.shared.effectiveState, force: true)
+ eng.setOutfit(AppState.shared.resolvedOutfit, animated: false)
+ self.engine = eng
+
+ let vs = DesktopBotViewState()
+ vs.lookOrigin = lookOriginFor(panel: p)
+ vs.paused = screenSleeping
+ self.viewState = vs
+
+ let hosting = NSHostingView(rootView:
+ DesktopBotView(appState: AppState.shared, engine: eng, viewState: vs))
+ hosting.frame = CGRect(origin: .zero, size: p.frame.size)
+ hosting.autoresizingMask = [.width, .height]
+ p.contentView = hosting
+
+ p.level = .floating
+ p.collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle, .fullScreenAuxiliary]
+ p.ignoresMouseEvents = true
+ if !p.isVisible { p.orderFront(nil) }
+
+ // Squash emote + sound on landing
+ eng.triggerEmote(.happy, duration: 0.6, silent: true)
+ SoundEngine.shared.play("pop")
+
+ // Animate from current (ghost) size to 120 × 120, centered on drop point
+ let targetOrigin = clampToVisibleFrame(NSPoint(x: screenPoint.x - s/2, y: screenPoint.y - s/2))
+ NSAnimationContext.runAnimationGroup({ ctx in
+ ctx.duration = 0.25
+ ctx.timingFunction = CAMediaTimingFunction(controlPoints: 0.17, 0.67, 0.38, 1.3)
+ p.animator().setFrame(NSRect(origin: targetOrigin, size: CGSize(width: s, height: s)),
+ display: true)
+ }, completionHandler: {
+ Task { @MainActor in
+ self.panel = p
+ self.phase = .onDesktop
+ AppState.shared.mochiOnDesktop = true
+ UserDefaults.standard.set(true, forKey: DesktopMochiController.enabledKey)
+ self.persistPosition()
+ // Alert may have fired during the animation (observeAlerts skipped: phase wasn't .onDesktop)
+ let alertNow = AppState.shared.pendingApproval != nil || AppState.shared.pendingQuestion != nil
+ if DesktopMochiLogic.shouldRetractOnLanding(alertActive: alertNow) {
+ self.engine?.triggerEmote(.surprised)
+ self.phase = .retracting
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.45) { [weak self] in
+ guard let self else { return }
+ switch self.phase {
+ case .retracting: self.retractForAlert()
+ case .alertResolvedDuringRetract: self.phase = .home; self.launchFlyIfNeeded()
+ default: break
+ }
+ }
+ } else {
+ self.startPolling()
+ self.addEventMonitors()
+ self.observeLifecycle()
+ }
+ }
+ })
+ }
+
+ // MARK: - Launch fly (app-start restore or alert return)
+
+ /// Fly a new panel from the notch to the saved desktop position.
+ /// Called by AppDelegate after `.greetComplete`, and by the alert-return path.
+ func launchFlyIfNeeded() {
+ guard UserDefaults.standard.bool(forKey: DesktopMochiController.enabledKey) else { return }
+ guard phase == .home else { return }
+ guard panel == nil else { return }
+ // Alert active: don't fly yet — park in .atNotchForAlert so observeAlerts restores us when it clears
+ if AppState.shared.pendingApproval != nil || AppState.shared.pendingQuestion != nil {
+ phase = .atNotchForAlert
+ return
+ }
+
+ phase = .flyingOut
+ let s = DesktopMochiController.panelSize
+ let screen = IslandWindowController.notchScreen() ?? NSScreen.main!
+ let startOrigin = NSPoint(x: screen.frame.midX - s/2, y: screen.frame.maxY - s)
+ let target = loadSavedPosition()
+
+ let p = makeBlankPanel()
+ p.setFrame(NSRect(origin: startOrigin, size: CGSize(width: s, height: s)), display: false)
+
+ let eng = BotEngine()
+ eng.setState(AppState.shared.effectiveState, force: true)
+ eng.setOutfit(AppState.shared.resolvedOutfit, animated: false)
+ self.engine = eng
+
+ let vs = DesktopBotViewState()
+ vs.lookOrigin = lookOriginFor(panel: p)
+ vs.paused = screenSleeping
+ self.viewState = vs
+
+ let hosting = NSHostingView(rootView:
+ DesktopBotView(appState: AppState.shared, engine: eng, viewState: vs))
+ hosting.frame = CGRect(x: 0, y: 0, width: s, height: s)
+ hosting.autoresizingMask = [.width, .height]
+ p.contentView = hosting
+ p.alphaValue = 0
+ p.orderFront(nil)
+
+ AppState.shared.mochiOnDesktop = true
+
+ NSAnimationContext.runAnimationGroup({ ctx in
+ ctx.duration = 0.45
+ ctx.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
+ p.animator().alphaValue = 1
+ p.animator().setFrame(NSRect(origin: target, size: CGSize(width: s, height: s)), display: true)
+ }, completionHandler: {
+ Task { @MainActor in
+ self.panel = p
+ self.phase = .onDesktop
+ UserDefaults.standard.set(true, forKey: DesktopMochiController.enabledKey)
+ self.persistPosition()
+ // Alert may have fired during the flight (observeAlerts skipped: phase was .flyingOut)
+ let alertNow = AppState.shared.pendingApproval != nil || AppState.shared.pendingQuestion != nil
+ if DesktopMochiLogic.shouldRetractOnLanding(alertActive: alertNow) {
+ self.engine?.triggerEmote(.surprised)
+ self.phase = .retracting
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.45) { [weak self] in
+ guard let self else { return }
+ switch self.phase {
+ case .retracting: self.retractForAlert()
+ case .alertResolvedDuringRetract: self.phase = .home; self.launchFlyIfNeeded()
+ default: break
+ }
+ }
+ } else {
+ self.startPolling()
+ self.addEventMonitors()
+ self.observeLifecycle()
+ }
+ }
+ })
+ }
+
+ // MARK: - Fly home (user-initiated: double-click)
+
+ /// Animate panel to notch then fully tear down.
+ func flyHome() {
+ guard let p = panel else { return }
+ phase = .home
+ pendingSlapWorkItem?.cancel()
+ stopPolling()
+ removeEventMonitors()
+ cancellables.removeAll()
+ isSleeping = false
+ let s = DesktopMochiController.panelSize
+ let screen = IslandWindowController.notchScreen() ?? NSScreen.main!
+ let targetOrigin = NSPoint(x: screen.frame.midX - s/2, y: screen.frame.maxY - s)
+ NSAnimationContext.runAnimationGroup({ ctx in
+ ctx.duration = 0.45
+ ctx.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
+ p.animator().setFrame(NSRect(origin: targetOrigin, size: CGSize(width: s, height: s)),
+ display: true)
+ }, completionHandler: {
+ Task { @MainActor in
+ SoundEngine.shared.play("peek")
+ self.fullTearDown()
+ }
+ })
+ }
+
+ // MARK: - Retract for alert (panel flies home; comes back after alert resolves)
+
+ /// Close panel and show notch Mochi for the alert. UserDefaults flag stays true so
+ /// `launchFlyIfNeeded` restores Mochi once the alert is dismissed.
+ private func retractForAlert() {
+ guard let p = panel else { return }
+ stopPolling()
+ removeEventMonitors()
+ cancellables.removeAll()
+ pendingSlapWorkItem?.cancel()
+ isSleeping = false
+
+ let s = DesktopMochiController.panelSize
+ let screen = IslandWindowController.notchScreen() ?? NSScreen.main!
+ let targetOrigin = NSPoint(x: screen.frame.midX - s/2, y: screen.frame.maxY - s)
+ NSAnimationContext.runAnimationGroup({ ctx in
+ ctx.duration = 0.45
+ ctx.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
+ p.animator().setFrame(NSRect(origin: targetOrigin, size: CGSize(width: s, height: s)),
+ display: true)
+ }, completionHandler: {
+ Task { @MainActor in
+ p.close()
+ self.panel = nil
+ self.engine = nil
+ self.viewState = nil
+ self.isDragging = false
+ AppState.shared.mochiOnDesktop = false
+ // UserDefaults flag stays TRUE so launchFlyIfNeeded works
+ if self.phase == .alertResolvedDuringRetract {
+ self.phase = .home
+ self.launchFlyIfNeeded()
+ } else {
+ self.phase = .atNotchForAlert
+ }
+ }
+ })
+ }
+
+ // MARK: - Uninstall (immediate, no animation)
+
+ func uninstall() {
+ stopPolling()
+ removeEventMonitors()
+ fullTearDown()
+ }
+
+ private func fullTearDown() {
+ phase = .home
+ cancellables.removeAll()
+ pendingSlapWorkItem?.cancel()
+ panel?.close()
+ panel = nil
+ engine = nil
+ viewState = nil
+ isDragging = false
+ isSleeping = false
+ AppState.shared.mochiOnDesktop = false
+ UserDefaults.standard.set(false, forKey: DesktopMochiController.enabledKey)
+ }
+
+ // MARK: - Panel factory
+
+ private func makeBlankPanel() -> NSPanel {
+ let p = NSPanel(contentRect: .zero,
+ styleMask: [.borderless, .nonactivatingPanel],
+ backing: .buffered, defer: false)
+ p.backgroundColor = .clear
+ p.isOpaque = false
+ p.hasShadow = false
+ return p
+ }
+
+ // MARK: - Lifecycle observation (active while panel is live on desktop)
+
+ private func observeLifecycle() {
+ cancellables.removeAll()
+
+ // effectiveState → .finished: joy jump (only when on desktop, not retracting)
+ Publishers.CombineLatest(AppState.shared.$stateOverride, AppState.shared.$tasks)
+ .map { _, _ in AppState.shared.effectiveState }
+ .removeDuplicates()
+ .dropFirst()
+ .receive(on: DispatchQueue.main)
+ .sink { [weak self] newState in
+ guard let self, self.phase == .onDesktop else { return }
+ if newState == .finished {
+ self.engine?.triggerEmote(.happy, duration: 1.2, silent: true)
+ }
+ }
+ .store(in: &cancellables)
+ }
+
+ // MARK: - Alert observation (permanent — installed once at init)
+
+ private func observeAlerts() {
+ alertSubscription = Publishers.CombineLatest(
+ AppState.shared.$pendingApproval,
+ AppState.shared.$pendingQuestion
+ )
+ .map { a, q in a != nil || q != nil }
+ .removeDuplicates()
+ .dropFirst()
+ .receive(on: DispatchQueue.main)
+ .sink { [weak self] alertActive in
+ guard let self else { return }
+
+ if alertActive {
+ guard self.phase == .onDesktop else { return }
+ self.engine?.triggerEmote(.surprised)
+ self.phase = .retracting
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.45) { [weak self] in
+ guard let self else { return }
+ switch self.phase {
+ case .retracting:
+ self.retractForAlert()
+ case .alertResolvedDuringRetract:
+ // Alert cleared before animation started — no need to retract
+ self.phase = .home
+ self.launchFlyIfNeeded()
+ default:
+ break
+ }
+ }
+ } else {
+ switch self.phase {
+ case .atNotchForAlert:
+ self.phase = .home
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [weak self] in
+ self?.launchFlyIfNeeded()
+ }
+ case .retracting:
+ // Alert resolved while waiting to retract — mark it
+ self.phase = .alertResolvedDuringRetract
+ default:
+ break
+ }
+ }
+ }
+ }
+
+ // MARK: - 60 Hz polling (only while panel is live)
+
+ private func startPolling() {
+ frameTimer?.invalidate()
+ frameTimer = Timer.scheduledTimer(withTimeInterval: 1.0/60.0, repeats: true) { [weak self] _ in
+ guard let self else { return }
+ Task { @MainActor in self.pollFrame() }
+ }
+ RunLoop.main.add(frameTimer!, forMode: .common)
+ }
+
+ private func stopPolling() {
+ frameTimer?.invalidate()
+ frameTimer = nil
+ }
+
+ private func pollFrame() {
+ guard let p = panel else { return }
+ let mouse = NSEvent.mouseLocation
+ let pf = p.frame
+ let local = CGPoint(x: mouse.x - pf.minX, y: mouse.y - pf.minY)
+ let s = DesktopMochiController.panelSize
+
+ // Toggle click-through
+ let overBody = DesktopMochiLogic.isOverBody(localPoint: local, panelSize: s)
+ let needsMouse = overBody || isDragging
+ if p.ignoresMouseEvents == needsMouse {
+ p.ignoresMouseEvents = !needsMouse
+ }
+
+ // Update eye-tracking origin every frame
+ viewState?.lookOrigin = lookOriginFor(panel: p)
+
+ // Sleep detection
+ let agentActive = AppState.shared.effectiveState != .idle &&
+ AppState.shared.effectiveState != .sleeping
+ if agentActive { lastAgentActive = .now }
+ let dist = hypot(mouse.x - pf.midX, mouse.y - pf.midY)
+ let interval = Date.now.timeIntervalSince(lastAgentActive)
+ let shouldSleep = DesktopMochiLogic.shouldSleep(lastAgentActiveInterval: interval,
+ mouseDistanceToPanelCenter: dist)
+ if shouldSleep != isSleeping {
+ isSleeping = shouldSleep
+ viewState?.isSleeping = shouldSleep
+ engine?.setState(isSleeping ? .sleeping : AppState.shared.effectiveState)
+ }
+ }
+
+ // MARK: - Event monitors
+
+ private func addEventMonitors() {
+ mouseDownMonitor = NSEvent.addLocalMonitorForEvents(matching: .leftMouseDown) { [weak self] event in
+ guard let self else { return event }
+ MainActor.assumeIsolated {
+ guard event.window === self.panel else { return }
+ self.dragMouseStart = NSEvent.mouseLocation
+ self.dragOriginAtStart = self.panel?.frame.origin ?? .zero
+ }
+ return event
+ }
+
+ mouseDraggedMonitor = NSEvent.addLocalMonitorForEvents(matching: .leftMouseDragged) { [weak self] event in
+ guard let self else { return event }
+ MainActor.assumeIsolated {
+ let m = NSEvent.mouseLocation
+ if !self.isDragging {
+ let dist = hypot(m.x - self.dragMouseStart.x, m.y - self.dragMouseStart.y)
+ guard self.dragMouseStart != .zero, dist > 3 else { return }
+ self.isDragging = true
+ }
+ guard let p = self.panel else { return }
+ let dx = m.x - self.dragMouseStart.x
+ let dy = m.y - self.dragMouseStart.y
+ let newOrigin = self.clampToVisibleFrame(
+ NSPoint(x: self.dragOriginAtStart.x + dx, y: self.dragOriginAtStart.y + dy))
+ p.setFrameOrigin(newOrigin)
+ self.viewState?.lookOrigin = self.lookOriginFor(panel: p)
+ }
+ return event
+ }
+
+ // Local mouseUp (cursor still within panel)
+ mouseUpMonitor = NSEvent.addLocalMonitorForEvents(matching: .leftMouseUp) { [weak self] event in
+ guard let self else { return event }
+ MainActor.assumeIsolated {
+ let wasDragging = self.isDragging
+ self.isDragging = false
+ self.dragMouseStart = .zero
+ if wasDragging {
+ self.handleDragRelease(at: NSEvent.mouseLocation)
+ } else if event.window === self.panel {
+ self.handleClick(clickCount: event.clickCount)
+ }
+ }
+ return event
+ }
+
+ // Global mouseUp (cursor moved outside panel during drag)
+ globalMouseUpMonitor = NSEvent.addGlobalMonitorForEvents(matching: .leftMouseUp) { [weak self] _ in
+ Task { @MainActor in
+ guard let self, self.isDragging else { return }
+ self.isDragging = false
+ self.dragMouseStart = .zero
+ self.handleDragRelease(at: NSEvent.mouseLocation)
+ }
+ }
+
+ rightClickMonitor = NSEvent.addLocalMonitorForEvents(matching: .rightMouseDown) { [weak self] event in
+ guard let self else { return event }
+ MainActor.assumeIsolated {
+ guard event.window === self.panel else { return }
+ NotificationCenter.default.post(name: .openWardrobeFromDesktop, object: nil)
+ }
+ return event
+ }
+ }
+
+ // MARK: - Click / drag helpers
+
+ private func handleClick(clickCount: Int) {
+ if clickCount >= 2 {
+ pendingSlapWorkItem?.cancel()
+ flyHome()
+ } else {
+ pendingSlapWorkItem?.cancel()
+ let item = DispatchWorkItem { [weak self] in self?.engine?.slap() }
+ pendingSlapWorkItem = item
+ DispatchQueue.main.asyncAfter(deadline: .now() + NSEvent.doubleClickInterval, execute: item)
+ }
+ }
+
+ private func handleDragRelease(at mouse: NSPoint) {
+ let islandController = (NSApp.delegate as? AppDelegate)?.islandController
+ let inNotchZone = islandController?.window?.frame.contains(mouse) == true
+
+ if inNotchZone {
+ flyHome()
+ return
+ }
+
+ #if !APPSTORE
+ if let ctx = islandController?.windowContextAtPoint(mouse) {
+ // Attach window context; Mochi returns to pre-drag position
+ AppState.shared.promptContext = ctx
+ SoundEngine.shared.play("approve")
+ engine?.triggerEmote(.happy, duration: 0.6, silent: true)
+ let origin = clampToVisibleFrame(dragOriginAtStart)
+ panel?.setFrameOrigin(origin)
+ persistPosition()
+ islandController?.expand(to: .prompt)
+ return
+ }
+ #endif
+ // Elsewhere: keep new position
+ persistPosition()
+ }
+
+ private func removeEventMonitors() {
+ if let m = mouseDownMonitor { NSEvent.removeMonitor(m); mouseDownMonitor = nil }
+ if let m = mouseDraggedMonitor { NSEvent.removeMonitor(m); mouseDraggedMonitor = nil }
+ if let m = mouseUpMonitor { NSEvent.removeMonitor(m); mouseUpMonitor = nil }
+ if let m = globalMouseUpMonitor { NSEvent.removeMonitor(m); globalMouseUpMonitor = nil }
+ if let m = rightClickMonitor { NSEvent.removeMonitor(m); rightClickMonitor = nil }
+ }
+
+ // MARK: - Screen sleep / wake
+
+ private func observeScreenSleep() {
+ NSWorkspace.shared.notificationCenter.addObserver(
+ forName: NSWorkspace.screensDidSleepNotification, object: nil, queue: .main
+ ) { [weak self] _ in
+ Task { @MainActor in
+ self?.screenSleeping = true
+ self?.viewState?.paused = true
+ }
+ }
+ NSWorkspace.shared.notificationCenter.addObserver(
+ forName: NSWorkspace.screensDidWakeNotification, object: nil, queue: .main
+ ) { [weak self] _ in
+ Task { @MainActor in
+ self?.screenSleeping = false
+ self?.viewState?.paused = false
+ }
+ }
+ }
+
+ // MARK: - Screen lock / unlock
+
+ private func observeScreenLock() {
+ DistributedNotificationCenter.default().addObserver(
+ forName: NSNotification.Name("com.apple.screenIsLocked"), object: nil, queue: .main
+ ) { [weak self] _ in
+ Task { @MainActor in
+ self?.screenSleeping = true
+ self?.viewState?.paused = true
+ }
+ }
+ DistributedNotificationCenter.default().addObserver(
+ forName: NSNotification.Name("com.apple.screenIsUnlocked"), object: nil, queue: .main
+ ) { [weak self] _ in
+ Task { @MainActor in
+ self?.screenSleeping = false
+ self?.viewState?.paused = false
+ }
+ }
+ }
+
+ // MARK: - Position helpers
+
+ private func lookOriginFor(panel: NSPanel) -> CGPoint {
+ let screen = panel.screen ?? NSScreen.main!
+ return DesktopMochiLogic.lookOrigin(
+ panelMinX: panel.frame.minX,
+ panelMinY: panel.frame.minY,
+ screenMinX: screen.frame.minX,
+ screenHeight: screen.frame.height,
+ panelSize: DesktopMochiController.panelSize)
+ }
+
+ private func clampToVisibleFrame(_ origin: NSPoint) -> NSPoint {
+ let screen = NSScreen.screens.min(by: {
+ let da = hypot(origin.x - $0.visibleFrame.midX, origin.y - $0.visibleFrame.midY)
+ let db = hypot(origin.x - $1.visibleFrame.midX, origin.y - $1.visibleFrame.midY)
+ return da < db
+ }) ?? NSScreen.main!
+ let pt = DesktopMochiLogic.clampOrigin(
+ CGPoint(x: origin.x, y: origin.y),
+ panelSize: DesktopMochiController.panelSize,
+ visibleFrame: screen.visibleFrame,
+ margin: DesktopMochiLogic.clampMargin)
+ return NSPoint(x: pt.x, y: pt.y)
+ }
+
+ private func loadSavedPosition() -> NSPoint {
+ let ud = UserDefaults.standard
+ guard ud.object(forKey: DesktopMochiController.posXKey) != nil else {
+ return defaultPosition()
+ }
+ let x = CGFloat(ud.double(forKey: DesktopMochiController.posXKey))
+ let y = CGFloat(ud.double(forKey: DesktopMochiController.posYKey))
+ return clampToVisibleFrame(NSPoint(x: x, y: y))
+ }
+
+ private func defaultPosition() -> NSPoint {
+ let s = DesktopMochiController.panelSize
+ let margin = DesktopMochiLogic.clampMargin
+ let vf = (NSScreen.main ?? NSScreen.screens[0]).visibleFrame
+ return NSPoint(x: vf.maxX - s - margin, y: vf.minY + margin)
+ }
+
+ private func persistPosition() {
+ guard let p = panel else { return }
+ let o = p.frame.origin
+ UserDefaults.standard.set(Double(o.x), forKey: DesktopMochiController.posXKey)
+ UserDefaults.standard.set(Double(o.y), forKey: DesktopMochiController.posYKey)
+ }
+}
diff --git a/NotchBuddy/Sources/App/DesktopMochiLogic.swift b/NotchBuddy/Sources/App/DesktopMochiLogic.swift
new file mode 100644
index 00000000..3f7fad76
--- /dev/null
+++ b/NotchBuddy/Sources/App/DesktopMochiLogic.swift
@@ -0,0 +1,73 @@
+import Foundation
+import CoreGraphics
+
+// MARK: - Alert state machine phase
+
+/// Phase of the desktop Mochi lifecycle.
+enum DesktopPhase: Equatable {
+ /// No panel on screen; `UserDefaults["mochiOnDesktop"]` is `false`.
+ case home
+ /// Panel animating from notch to saved desktop position.
+ case flyingOut
+ /// Panel live on the desktop — normal operating state.
+ case onDesktop
+ /// `pendingApproval`/`pendingQuestion` just went non-nil; panel animating toward notch.
+ case retracting
+ /// Alert cleared while retract animation was still running.
+ case alertResolvedDuringRetract
+ /// Retract complete; notch Mochi is showing the alert.
+ case atNotchForAlert
+}
+
+// MARK: - Pure geometry / logic (no AppKit — fully unit-testable)
+
+/// Stateless helpers for `DesktopMochiController`.
+enum DesktopMochiLogic {
+ static let panelSize: CGFloat = 120
+ static let sleepTimeout: TimeInterval = 120
+ static let sleepMouseDistance: CGFloat = 150
+ static let clampMargin: CGFloat = 24
+ static let bodyRadiusFraction: CGFloat = 0.24
+
+ /// Whether Mochi should enter sleeping state.
+ static func shouldSleep(lastAgentActiveInterval: TimeInterval,
+ mouseDistanceToPanelCenter: CGFloat) -> Bool {
+ lastAgentActiveInterval > sleepTimeout && mouseDistanceToPanelCenter >= sleepMouseDistance
+ }
+
+ /// Hit-test the circular body inside a square panel (AppKit y-up local coords).
+ static func isOverBody(localPoint: CGPoint, panelSize: CGFloat) -> Bool {
+ let cx = panelSize / 2
+ let cy = panelSize / 2
+ let r = panelSize * bodyRadiusFraction
+ let dx = localPoint.x - cx
+ let dy = localPoint.y - cy
+ return dx * dx + dy * dy <= r * r
+ }
+
+ /// Eye-tracking origin: panel center in screen-space with y-down from top of screen.
+ /// Matches the coordinate space of `AppState.mousePosition`.
+ static func lookOrigin(panelMinX: CGFloat,
+ panelMinY: CGFloat,
+ screenMinX: CGFloat,
+ screenHeight: CGFloat,
+ panelSize: CGFloat) -> CGPoint {
+ let cx = panelMinX + panelSize / 2
+ let cy = panelMinY + panelSize / 2
+ return CGPoint(x: cx - screenMinX, y: screenHeight - cy)
+ }
+
+ /// Whether Mochi should immediately retract after landing (alert was active during the flight).
+ static func shouldRetractOnLanding(alertActive: Bool) -> Bool { alertActive }
+
+ /// Clamp a panel origin so the panel stays inside `visibleFrame` with `margin` on each side.
+ static func clampOrigin(_ origin: CGPoint,
+ panelSize: CGFloat,
+ visibleFrame: CGRect,
+ margin: CGFloat) -> CGPoint {
+ CGPoint(
+ x: min(max(origin.x, visibleFrame.minX + margin), visibleFrame.maxX - panelSize - margin),
+ y: min(max(origin.y, visibleFrame.minY + margin), visibleFrame.maxY - panelSize - margin)
+ )
+ }
+}
diff --git a/NotchBuddy/Sources/App/IslandRootView.swift b/NotchBuddy/Sources/App/IslandRootView.swift
index aa809e84..2d30e1ce 100644
--- a/NotchBuddy/Sources/App/IslandRootView.swift
+++ b/NotchBuddy/Sources/App/IslandRootView.swift
@@ -300,14 +300,14 @@ struct BotPlacement: View {
let uploadCx = 36 + CGFloat(t * (2 - t)) * 526
BotCanvasView(state: state, particleOverhang: 0)
.frame(width: canvasSize, height: canvasSize)
- .opacity(state.isDraggingBot ? 0 : opacity)
+ .opacity(state.isDraggingBot || state.mochiOnDesktop ? 0 : opacity)
.position(x: uploadCx, y: cy)
}
.transition(.scale(scale: 0.01, anchor: .center).combined(with: .opacity))
} else {
BotCanvasView(state: state, particleOverhang: overhang)
.frame(width: canvasSize, height: canvasSize + overhang)
- .opacity(state.isDraggingBot ? 0 : opacity)
+ .opacity(state.isDraggingBot || state.mochiOnDesktop ? 0 : opacity)
.position(x: cx, y: cy - overhang / 2)
.animation(.spring(response: 0.5, dampingFraction: 0.72), value: cx)
.animation(.spring(response: 0.5, dampingFraction: 0.72), value: cy)
diff --git a/NotchBuddy/Sources/App/IslandWindowController.swift b/NotchBuddy/Sources/App/IslandWindowController.swift
index 9847e5a2..1b719f0e 100644
--- a/NotchBuddy/Sources/App/IslandWindowController.swift
+++ b/NotchBuddy/Sources/App/IslandWindowController.swift
@@ -405,6 +405,18 @@ final class IslandWindowController: NSWindowController {
self?.collapse()
}
+ // Wardrobe open/close from desktop Mochi right-click (does NOT post .hookExpand)
+ NotificationCenter.default.addObserver(forName: .openWardrobeFromDesktop, object: nil, queue: .main) { [weak self] _ in
+ guard let self else { return }
+ if self.state.mode == .expanded && self.state.view == .wardrobe {
+ withAnimation(.spring(response: 0.3, dampingFraction: 0.8)) {
+ self.state.view = .overview
+ }
+ } else {
+ self.expand(to: .wardrobe)
+ }
+ }
+
// .botDizzy — posted by BotEngine.slap() on 3rd hit; show confused view + recover after 3.3s
NotificationCenter.default.addObserver(forName: .botDizzy, object: nil, queue: .main) { [weak self] _ in
self?.handleDizzy()
@@ -423,6 +435,8 @@ final class IslandWindowController: NSWindowController {
self.botHovering = false
// Drag only starts when clicking directly on the bot head
guard self.isBotHit(event.locationInWindow) else { return }
+ // Notch Mochi is invisible when on desktop — no drag, no slap
+ guard !self.state.mochiOnDesktop else { return }
self.attachDragStart = NSEvent.mouseLocation
// Post slap only when expanded
guard self.state.mode == .expanded else { return }
@@ -451,13 +465,38 @@ final class IslandWindowController: NSWindowController {
self.inAttachDrag = false
self.attachDragStart = nil
self.state.stateOverride = nil
- self.hideDragGhost()
+
#if !APPSTORE
- if let ctx = self.windowContextAtPoint(mouse) {
+ let windowCtx = self.windowContextAtPoint(mouse)
+ let inNotchZone = self.window?.frame.contains(mouse) == true
+
+ if let ctx = windowCtx {
+ // Drop on a window → attach context as before
+ self.hideDragGhost()
self.state.promptContext = ctx
SoundEngine.shared.play("approve")
NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.happy)
self.expand(to: .prompt)
+ } else if !inNotchZone {
+ // Drop outside notch zone → install Mochi on the desktop.
+ // Prevent hideDragGhost from closing the ghost panel so we can promote it.
+ let ghost = self.dragGhostPanel
+ self.dragGhostPanel = nil // nil first so hideDragGhost skips close
+ self.hideDragGhost() // resets isDraggingBot, closes highlight panel
+ DesktopMochiController.shared.install(ghostPanel: ghost, at: mouse)
+ } else {
+ // Drop back in notch zone → Mochi returns to notch
+ self.hideDragGhost()
+ }
+ #else
+ let inNotchZoneAS = self.window?.frame.contains(mouse) == true
+ if !inNotchZoneAS {
+ let ghost = self.dragGhostPanel
+ self.dragGhostPanel = nil
+ self.hideDragGhost()
+ DesktopMochiController.shared.install(ghostPanel: ghost, at: mouse)
+ } else {
+ self.hideDragGhost()
}
#endif
}
@@ -492,6 +531,7 @@ final class IslandWindowController: NSWindowController {
guard let self else { return event }
MainActor.assumeIsolated {
guard self.wasInIsland, self.isBotHit(event.locationInWindow) else { return }
+ guard !self.state.mochiOnDesktop else { return }
if self.state.mode == .expanded && self.state.view == .wardrobe {
withAnimation(.spring(response: 0.3, dampingFraction: 0.8)) {
self.state.view = .overview
@@ -680,7 +720,7 @@ final class IslandWindowController: NSWindowController {
// MARK: - Window context at screen point (for drag-attach)
- private func windowContextAtPoint(_ screenPoint: NSPoint) -> PromptContext? {
+ func windowContextAtPoint(_ screenPoint: NSPoint) -> PromptContext? {
let screen = window?.screen ?? NSScreen.main
// CGWindowList uses top-left origin; NSEvent.mouseLocation uses bottom-left
let screenMaxY = screen?.frame.maxY ?? NSScreen.main!.frame.maxY
@@ -898,6 +938,7 @@ extension Notification.Name {
static let greetComplete = Notification.Name("notchBuddy.greetComplete")
static let greetingHover = Notification.Name("notchBuddy.greetingHover")
static let greetingInterrupt = Notification.Name("notchBuddy.greetingInterrupt")
+ static let openWardrobeFromDesktop = Notification.Name("notchBuddy.openWardrobeFromDesktop")
}
// MARK: - islandSize (takes real notch dimensions)
diff --git a/README.md b/README.md
index ce820cec..ce8334d2 100644
--- a/README.md
+++ b/README.md
@@ -41,6 +41,7 @@ Meet **Mochi**: a soft little squircle with big eyes that pops out of your notch
- 📊 **Claude plan usage** *(macOS, GitHub build)* — a small pill in the notch header shows your 5-hour and weekly Claude plan limits. Enable it from Settings → Agents → Plan usage. Pro and Max plans only.
- 📋 **Declare the tools you use** — open Settings → Active pills and pick your main workspace tool (VS Code, Cursor, Codex or Antigravity), then toggle up to 4 more: Gemini CLI, Anthropic, Google AI, OpenAI, Ollama, LM Studio and service integrations *(macOS)*.
- 📎 **Drop a file on the notch** — Mochi turns into a box and swallows it, then ask a question about it or send it by email *(email: macOS, Mail.app)*.
+- 🖥️ **Mochi on the desktop** — drag Mochi out of the island to set him loose on your desktop: he floats as a 120 pt companion, follows your cursor, wears his outfit, reacts to alerts by flying home and flying back, and comes back where you left him on next launch.
- 🪟 **Drag Mochi onto any window** — attach that window as context for Claude *(macOS)*.
- 🔌 **Integrations** — Stripe payments, n8n workflows, GitHub (open PRs, reviews requested, CI status), Vercel deployments, Resend emails, Notion, Cal.com. Each one gets its own little colored Mochi.
- 🎵 **Apple Music pill** *(macOS, GitHub build)* — add the Apple Music pill in Settings → Active pills to see what's playing and control playback from the notch; Mochi dances while it plays.
diff --git a/docs/SPEC.md b/docs/SPEC.md
index d8077f50..52835728 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -293,3 +293,65 @@ Chaque jalon se termine par build + capture + comparaison aux références + com
- Hidden = 0 % CPU ; compact < 3 % ; mémoire < 100 Mo.
- La démo (⌃⌥⌘D) se filme d'une traite sans intervention.
+## 13. Mochi sur le bureau
+
+Mochi peut quitter l'island et vivre comme une icône flottante sur le bureau. Il conserve tout son comportement (tenue, émotes, suivi des yeux, danse) et réagit aux alertes.
+
+### Pose et panneau
+
+- **Panneau** : `NSPanel` borderless non-activating, niveau `.floating`, `collectionBehavior [.canJoinAllSpaces, .stationary, .ignoresCycle, .fullScreenAuxiliary]`, taille 120 × 120 pt.
+- **Clics traversants** : `ignoresMouseEvents` activé par défaut ; désactivé à 60 Hz uniquement quand le curseur est sur le corps (rayon ≈ 24 % de la taille du panneau). Position bornée à `screen.visibleFrame` avec une marge de 24 pt.
+- Le panneau est toujours au niveau `.floating` — en dessous des panneaux de menu et de l'island, au-dessus des fenêtres normales.
+
+### Installation
+
+- **Depuis le glisser** : quand l'utilisateur lâche Mochi hors de la zone notch et hors de toute fenêtre, `IslandWindowController.finishDrag` cède le panneau fantôme au `DesktopMochiController`. Le panneau s'agrandit vers 120 × 120 (animation ressort ~0,25 s), son contenu remplacé par `DesktopBotView`. Son de bienvenue : `pop`. Atterrissage avec émote `happy`.
+- **Retour dans la zone notch** : lâcher dans le cadre du panneau island → Mochi retourne à la notch sans s'installer sur le bureau.
+- **Au démarrage** (si `UserDefaults["mochiOnDesktop"] == true`) : le greeting se joue normalement, puis à `greetComplete` un nouveau panneau part de la notch et vole vers la position sauvegardée (animation 0,45 s).
+
+### Interactions
+
+| Geste | Effet |
+|---|---|
+| Clic simple | Slap (`engine.slap()`) — différé de `NSEvent.doubleClickInterval` |
+| Double-clic | Annule le slap en attente ; vol vers la notch (`flyHome()`), island réapparaît |
+| Clic droit | Ouvre/ferme la garde-robe (`.openWardrobeFromDesktop`, sans `.hookExpand`) |
+| Glisser → zone notch | Vol vers la notch (`flyHome()`) |
+| Glisser → fenêtre (GitHub) | Attache le contexte, Mochi revient à sa position initiale, island ouvre `.prompt` |
+| Glisser → ailleurs | Repositionne le panneau (borné au `visibleFrame`) |
+
+### Personnage complet
+
+- Respiration, clignements, suivi des yeux depuis la position du panneau (pas depuis l'island).
+- Tenue : toujours celle de `state.resolvedOutfit` (main Mochi = toujours habillé).
+- Danse : mêmes règles que le mode compact (musique + intégration active + état autorisé).
+- 30 fps actif, 10 fps au repos (`TimelineView` adapte `minimumInterval` selon `isSleeping`).
+
+### Absences de la notch
+
+Quand `AppState.mochiOnDesktop == true`, `BotPlacement` masque le bonhomme de la notch (opacité 0, même règle que `isDraggingBot`).
+
+### Alertes
+
+Détection par `Publishers.CombineLatest($pendingApproval, $pendingQuestion)` — seules les transitions nil↔non-nil déclenchent l'action. La notification `.hookExpand` n'est pas utilisée (elle part aussi pour `.finished`, `.error`, le glisser de fichier, etc.).
+
+1. `pendingApproval` ou `pendingQuestion` passe à non-`nil` → émote `surprised` sur le Mochi du bureau.
+2. Après 0,45 s, `retractForAlert()` : le panneau vole vers la notch et se ferme ; `mochiOnDesktop` passe à `false` (le bonhomme de la notch réapparaît pour l'alerte) ; `UserDefaults["mochiOnDesktop"]` reste `true`.
+3. Quand `pendingApproval` **et** `pendingQuestion` sont tous deux `nil`, `launchFlyIfNeeded()` renvole Mochi vers la position sauvegardée après 0,6 s.
+4. Si l'alerte se résout pendant l'animation de retrait, le panneau ne s'ouvre pas sur la notch — Mochi repart directement vers le bureau.
+
+### `.finished`
+
+Émote `happy` (saut de joie) sur le Mochi du bureau. Détecté par `Publishers.CombineLatest($stateOverride, $tasks)` → `effectiveState` ; ne déclenche pas de retrait vers la notch.
+
+### Sommeil
+
+- 2 min sans activité d'agent ET souris à plus de 150 pt → `engine.setState(.sleeping)`, `TimelineView` passe à 10 fps.
+- Réveil à l'approche de la souris ou à la réception d'un événement d'agent.
+- Pause complète lors du sommeil écran (`NSWorkspace.screensDidSleepNotification`) ou du verrouillage de session (`com.apple.screenIsLocked`).
+
+### Persistance
+
+- Position et état sauvegardés dans `UserDefaults` (clés : `desktopMochiX`, `desktopMochiY`, `mochiOnDesktop`).
+- Position bornée au `visibleFrame` du meilleur écran disponible au chargement ; si aucun écran ne convient, coin bas-droit de l'écran principal avec 24 pt de marge.
+
diff --git a/scripts/test-desktop-mochi.sh b/scripts/test-desktop-mochi.sh
new file mode 100755
index 00000000..b36c7893
--- /dev/null
+++ b/scripts/test-desktop-mochi.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(dirname "$0")/.."
+TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/coucou-desktop.XXXXXX")"
+trap 'rm -rf "$TEST_DIR"' EXIT
+swiftc NotchBuddy/Sources/App/DesktopMochiLogic.swift \
+ tests/DesktopMochiTests.swift -o "$TEST_DIR/desktop-mochi-tests"
+"$TEST_DIR/desktop-mochi-tests"
diff --git a/tests/DesktopMochiTests.swift b/tests/DesktopMochiTests.swift
new file mode 100644
index 00000000..b2d5e029
--- /dev/null
+++ b/tests/DesktopMochiTests.swift
@@ -0,0 +1,129 @@
+import Foundation
+
+@main
+enum DesktopMochiTests {
+ static func main() {
+ testShouldSleep()
+ testIsOverBody()
+ testLookOrigin()
+ testClampOrigin()
+ testShouldRetractOnLanding()
+ print("DesktopMochiLogic: all cases passed")
+ }
+
+ // MARK: - shouldSleep
+
+ static func testShouldSleep() {
+ // Agent recently active → awake regardless of mouse distance
+ precondition(!DesktopMochiLogic.shouldSleep(lastAgentActiveInterval: 5, mouseDistanceToPanelCenter: 300),
+ "active agent must not sleep")
+
+ // Long idle but mouse near panel → awake
+ precondition(!DesktopMochiLogic.shouldSleep(lastAgentActiveInterval: 200, mouseDistanceToPanelCenter: 50),
+ "mouse near panel must not sleep")
+
+ // Long idle AND mouse far → sleep
+ precondition(DesktopMochiLogic.shouldSleep(lastAgentActiveInterval: 200, mouseDistanceToPanelCenter: 200),
+ "long idle + far mouse must sleep")
+
+ // Exactly at timeout boundary → still awake (strictly greater than)
+ precondition(!DesktopMochiLogic.shouldSleep(lastAgentActiveInterval: 120, mouseDistanceToPanelCenter: 300),
+ "exactly at timeout must not sleep")
+
+ // Just past timeout boundary + far mouse → sleep
+ precondition(DesktopMochiLogic.shouldSleep(lastAgentActiveInterval: 120.1, mouseDistanceToPanelCenter: 300),
+ "just over timeout must sleep")
+
+ // Far mouse at exact distance threshold → sleep
+ precondition(DesktopMochiLogic.shouldSleep(lastAgentActiveInterval: 200, mouseDistanceToPanelCenter: 150),
+ "at distance threshold must sleep")
+ }
+
+ // MARK: - isOverBody
+
+ static func testIsOverBody() {
+ let s: CGFloat = 120
+ let r = s * DesktopMochiLogic.bodyRadiusFraction // 28.8
+
+ // Center → inside
+ precondition(DesktopMochiLogic.isOverBody(localPoint: CGPoint(x: 60, y: 60), panelSize: s),
+ "center must be inside body")
+
+ // Just inside radius
+ precondition(DesktopMochiLogic.isOverBody(localPoint: CGPoint(x: 60 + r - 0.5, y: 60), panelSize: s),
+ "inside radius must hit")
+
+ // Just outside radius
+ precondition(!DesktopMochiLogic.isOverBody(localPoint: CGPoint(x: 60 + r + 0.5, y: 60), panelSize: s),
+ "outside radius must miss")
+
+ // Corner → outside
+ precondition(!DesktopMochiLogic.isOverBody(localPoint: CGPoint(x: 0, y: 0), panelSize: s),
+ "corner must miss")
+
+ // Diagonal at radius — distance = r/√2 from each axis
+ let diag = r / sqrt(2.0) - 0.5
+ precondition(DesktopMochiLogic.isOverBody(localPoint: CGPoint(x: 60 + diag, y: 60 + diag), panelSize: s),
+ "diagonal inside must hit")
+ }
+
+ // MARK: - lookOrigin
+
+ static func testLookOrigin() {
+ // Panel at (200, 300) on a 1440×900 screen starting at x=0
+ let o = DesktopMochiLogic.lookOrigin(panelMinX: 200, panelMinY: 300,
+ screenMinX: 0, screenHeight: 900,
+ panelSize: 120)
+ // cx = 200 + 60 = 260 → x = 260 - 0 = 260
+ precondition(o.x == 260, "lookOrigin x must be panel center relative to screen left")
+ // cy = 300 + 60 = 360 → y = 900 - 360 = 540
+ precondition(o.y == 540, "lookOrigin y must be flipped from bottom-left to top-left")
+
+ // Panel on a secondary screen starting at x=1440
+ let o2 = DesktopMochiLogic.lookOrigin(panelMinX: 1540, panelMinY: 100,
+ screenMinX: 1440, screenHeight: 1080,
+ panelSize: 120)
+ // cx = 1540 + 60 = 1600 → x = 1600 - 1440 = 160
+ precondition(o2.x == 160, "lookOrigin x must be relative to screen minX")
+ // cy = 100 + 60 = 160 → y = 1080 - 160 = 920
+ precondition(o2.y == 920, "lookOrigin y on secondary screen")
+ }
+
+ // MARK: - shouldRetractOnLanding
+
+ static func testShouldRetractOnLanding() {
+ precondition(DesktopMochiLogic.shouldRetractOnLanding(alertActive: true),
+ "must retract when alert is active on landing")
+ precondition(!DesktopMochiLogic.shouldRetractOnLanding(alertActive: false),
+ "must not retract when no alert on landing")
+ }
+
+ // MARK: - clampOrigin
+
+ static func testClampOrigin() {
+ // Typical macOS visible frame (below menu bar)
+ let vf = CGRect(x: 0, y: 23, width: 1440, height: 877) // maxX=1440, maxY=900
+ let s: CGFloat = 120
+ let m: CGFloat = 24
+
+ // Normal position — within bounds
+ let normal = DesktopMochiLogic.clampOrigin(CGPoint(x: 600, y: 400), panelSize: s, visibleFrame: vf, margin: m)
+ precondition(normal == CGPoint(x: 600, y: 400), "in-bounds origin must be unchanged")
+
+ // Too far left
+ let left = DesktopMochiLogic.clampOrigin(CGPoint(x: -50, y: 400), panelSize: s, visibleFrame: vf, margin: m)
+ precondition(left.x == vf.minX + m, "too-left must clamp to minX + margin")
+
+ // Too far right
+ let right = DesktopMochiLogic.clampOrigin(CGPoint(x: 2000, y: 400), panelSize: s, visibleFrame: vf, margin: m)
+ precondition(right.x == vf.maxX - s - m, "too-right must clamp to maxX - panelSize - margin")
+
+ // Too low
+ let low = DesktopMochiLogic.clampOrigin(CGPoint(x: 400, y: -50), panelSize: s, visibleFrame: vf, margin: m)
+ precondition(low.y == vf.minY + m, "too-low must clamp to minY + margin")
+
+ // Too high
+ let high = DesktopMochiLogic.clampOrigin(CGPoint(x: 400, y: 2000), panelSize: s, visibleFrame: vf, margin: m)
+ precondition(high.y == vf.maxY - s - m, "too-high must clamp to maxY - panelSize - margin")
+ }
+}