Files
coucou/NotchBuddy/Sources/App/IslandStateMachine.swift
TatsukichiandClaude Opus 5.5 62691256eb macOS: fold alert-opened island after the auto-close delay (#1253)
An alert (a finished session, an error, a note…) opens the island through
hookExpand → openedExternally(), which cancelled every timer and never
scheduled the home collapse. Only mouseLeft() did, so the finished card
stayed open until the pointer touched the notch.

openedExternally(autoClose:) now schedules the collapse when asked, and
hookExpand asks for it except for approvals and questions, which wait for
an answer. Shortcut-opened and in-progress cards (launch, mail) keep their
current behavior. Three cases added to the auto-close tests.

Fixes #1250

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 21:22:55 +00:00

258 lines
9.7 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Foundation
/// Pure 4-state FSM for island open/close logic.
/// No AppKit / AppState dependencies — communicates via `onTransition`.
@MainActor
final class IslandStateMachine {
enum State: Equatable {
case hidden // island invisible (notch size)
case petit // compact island (notch + ears)
case home // expanded, overview
case coucou // expanded, greeting animation
case listening // expanded, voice listening («OK Coucou» detected)
}
private(set) var state: State = .hidden
/// Fired on every transition: (from, to)
var onTransition: ((State, State) -> Void)?
/// When non-nil and returns true, timers and mouse-leave never auto-collapse or hide the island.
var isHeldOpen: (() -> Bool)?
/// home → petit delay (seconds), kept in sync with the auto-close preference.
var homeToPetitDelay: TimeInterval = 15 {
didSet {
guard homeToPetitDelay != oldValue,
state == .home, homeCollapseWork != nil else { return }
scheduleHomeCollapse()
}
}
/// petit → hidden delay (seconds), kept in sync with the absenceInterval preference.
var petitToHiddenDelay: TimeInterval = 60 {
didSet {
guard petitToHiddenDelay != oldValue,
state == .petit, petitHideWork != nil else { return }
schedulePetitHide()
}
}
/// coucou → petit delay after greeting animation ends (no hover). ~0.6s syncs with canvas collapse.
var greetAutoCollapseDelay: TimeInterval = 0.6
/// coucou → petit delay when mouse is hovering over the greeting.
var greetHoverCollapseDelay: TimeInterval = 10
/// Opt-in (Settings → General → Behavior): hovering the island opens it, and an island
/// opened that way folds shortly after the pointer leaves. Off: hover only peeks (petit).
var openOnHover = false
/// Grace period after the pointer leaves a hover-opened island (no flicker at the edge).
var hoverCloseDelay: TimeInterval = 0.6
/// True while the island is open because of a hover, until the user clicks inside it.
private(set) var openedByHover = false
private var petitHideWork: DispatchWorkItem?
private var homeCollapseWork: DispatchWorkItem?
private var greetCollapseWork: DispatchWorkItem?
private var stateBeforeListening: State = .hidden
// MARK: – Inputs
/// App launched or debug "launch greeting"
func launch() {
cancelTimers()
transition(to: .coucou)
}
/// Mouse entered the island notch area
func mouseEntered() {
if openOnHover, state == .hidden || state == .petit, isHeldOpen?() != true {
cancelTimers()
openedByHover = true
transition(to: .home)
return
}
switch state {
case .hidden:
if isHeldOpen?() == true {
// Island already expanded by an external call — sync FSM state without transition
state = .home
} else {
cancelTimers()
transition(to: .petit)
}
case .petit:
petitHideWork?.cancel()
petitHideWork = nil
case .home:
homeCollapseWork?.cancel()
homeCollapseWork = nil
case .coucou:
// Mouse hovering during greeting — cancel short auto-collapse, extend to hover delay
scheduleGreetCollapse(delay: greetHoverCollapseDelay)
case .listening:
// Voice is active; if openOnHover, expand to show the overview.
if openOnHover {
cancelTimers()
openedByHover = true
transition(to: .home)
}
// else: no timer, island stays compact — voice keeps running.
}
}
/// Mouse left the island notch area
func mouseLeft() {
switch state {
case .hidden:
break
case .petit:
schedulePetitHide()
case .home:
if isHeldOpen?() != true { scheduleHomeCollapse() }
case .coucou:
if isHeldOpen?() != true {
// Interrupt greeting immediately → compact (overrides 10s auto-collapse)
greetCollapseWork?.cancel(); greetCollapseWork = nil
transition(to: .petit)
}
case .listening:
break // never auto-collapse while listening
}
}
/// Compact island clicked.
/// Also accepts `.hidden`: after an alert the island can be on screen while the
/// FSM never saw the mouse enter (it was already there), and the click must still open it.
/// Also accepts `.listening`: the user can open the island while voice is active; voice
/// continues uninterrupted and the island expands to the overview.
func click() {
openedByHover = false
guard state == .petit || state == .hidden || state == .listening else { return }
cancelTimers()
transition(to: .home)
}
/// The app hid the island on its own (e.g. `AppState.syncMode()` when the last
/// task ends). Mirror it without side effects, so the next hover peeks again
/// instead of being swallowed by a FSM that still thinks the island is `.petit`.
func hiddenExternally() {
guard state == .petit else { return }
cancelTimers()
state = .hidden
}
/// The app expanded the island externally (hookExpand for an alert, a shortcut, a card).
/// Cancel timers and sync state to `.home` without firing `onTransition`, so the
/// next hover/mouseLeft behave correctly instead of collapsing the island.
/// `autoClose`: the island opened on its own (an alert), so it folds after the
/// configured delay even if the pointer never comes near the notch — the countdown bar
/// says so. Cards waiting for an answer stay open through `isHeldOpen`.
func openedExternally(autoClose: Bool = false) {
cancelTimers()
openedByHover = false
guard state != .coucou else { return }
state = .home
if autoClose, isHeldOpen?() != true { scheduleHomeCollapse() }
}
/// The app folded the island itself (Escape, Settings, OK button, auto-close).
/// Move to `.petit` right away so hover and click keep working; waiting for the
/// 15 s home timer left the island compact on screen while the FSM still said `.home`.
func collapse() {
openedByHover = false
guard state == .home || state == .coucou || state == .listening else { return }
cancelTimers()
transition(to: .petit)
}
// MARK: – Voice inputs
/// Wake phrase detected: open the island in listening mode from any state.
func voiceWoke() {
stateBeforeListening = state
cancelTimers()
openedByHover = false
transition(to: .listening)
}
/// Command session ended (silence timeout, cancel phrase, or user dismiss).
func voiceFinished() {
guard state == .listening else { return }
let target: State = stateBeforeListening == .home ? .home : .petit
transition(to: target)
if target == .home, isHeldOpen?() != true { scheduleHomeCollapse() }
}
/// Greeting animation finished (called at T.end ≈ 4.60 s).
/// Schedules auto-collapse. Does not override a longer hover timer already running.
func greetComplete() {
guard state == .coucou else { return }
// If mouse entered before this fires (hover timer already running), don't override it
if greetCollapseWork == nil {
scheduleGreetCollapse(delay: greetAutoCollapseDelay)
}
}
private func scheduleGreetCollapse(delay: TimeInterval) {
greetCollapseWork?.cancel()
let item = DispatchWorkItem { [weak self] in
guard let self, self.state == .coucou else { return }
self.transition(to: .petit)
}
greetCollapseWork = item
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: item)
}
/// Non-alert work event: show compact from hidden (HookServer reveal)
func reveal() {
guard state == .hidden else { return }
cancelTimers()
transition(to: .petit)
schedulePetitHide()
}
// MARK: – Timers
private func schedulePetitHide() {
petitHideWork?.cancel()
let item = DispatchWorkItem { [weak self] in
guard let self, self.state == .petit, !(self.isHeldOpen?() ?? false) else { return }
self.transition(to: .hidden)
}
petitHideWork = item
DispatchQueue.main.asyncAfter(deadline: .now() + petitToHiddenDelay, execute: item)
}
private func scheduleHomeCollapse() {
homeCollapseWork?.cancel()
let item = DispatchWorkItem { [weak self] in
guard let self, self.state == .home, !(self.isHeldOpen?() ?? false) else { return }
self.openedByHover = false
self.transition(to: .petit)
}
homeCollapseWork = item
let delay = openedByHover ? hoverCloseDelay : homeToPetitDelay
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: item)
}
/// The user clicked inside the island: a hover-opened island now stays like any open
/// island (normal auto-close) instead of folding as soon as the pointer leaves.
func userInteracted() {
openedByHover = false
}
func cancelTimers() {
petitHideWork?.cancel(); petitHideWork = nil
homeCollapseWork?.cancel(); homeCollapseWork = nil
greetCollapseWork?.cancel(); greetCollapseWork = nil
}
private func transition(to new: State) {
guard new != state else { return }
let old = state
state = new
onTransition?(old, new)
}
}