A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Keyboard shortcuts (#205)
Louis9fe8294ec7d5
diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxprojindex 6bd6b0ae..2d2950ec 100644--- a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj@@ -22,6 +22,7 @@186AB8904029767DAA5277CF /* IslandScreenGeometry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78BC1357785CA1B099A33969 /* IslandScreenGeometry.swift */; };18D47AE663EB96BE5638D5F7 /* ClaudePlanCardView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4263B550838CC5614569D13 /* ClaudePlanCardView.swift */; };1969590AFEE6CB21404346F1 /* CalcomPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3104222B3F17BA5E8DEA5277 /* CalcomPoller.swift */; };+ 1EAFEE80A8066B77F9410025 /* ShortcutsSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62CF42AE7611EF212CA0458F /* ShortcutsSettingsView.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 */; };@@ -37,6 +38,7 @@4976F8BF814D6F817370F1D8 /* ChatMarkdownView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFE88A53AEAA637F866D479D /* ChatMarkdownView.swift */; };4B6AC00F22EC75E90E0157D5 /* AppLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F6D7015D6A77AA59323C0E7 /* AppLog.swift */; };4F1E0B3C838DA3CD6F864BC0 /* CalcomPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3104222B3F17BA5E8DEA5277 /* CalcomPoller.swift */; };+ 530443F46F896F037A56F663 /* HotKeyCenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1218B86E249691AF44F819AC /* HotKeyCenter.swift */; };56BE8C733F10A030A638FB60 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C1A7D5CBE2AC084A10C5FF3 /* SettingsView.swift */; };5B9A00AFB0837731FA678E4E /* IslandStateMachine.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8212018F09EA1E96FBD63CD /* IslandStateMachine.swift */; };5C6D0BC8C546718CAA82BF90 /* MusicController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F142FB3952B5F0639383047 /* MusicController.swift */; };@@ -49,6 +51,7 @@651FA3F09608DE5D02D61CCE /* BotCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A29F4C0B02BE91654D02AA0C /* BotCanvasView.swift */; };6697436AA05A3F92C1DD85C3 /* DiffEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DB24C2469551040FBAA4DBF /* DiffEngine.swift */; };68A950E3C23FD612639D9776 /* IslandViewContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA02B08886939FF6FE0475DD /* IslandViewContent.swift */; };+ 6CCEC73ED68E9F253C22D692 /* ShortcutLogic.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA51E5B140C20812641168EA /* ShortcutLogic.swift */; };6D158183870434FEDF07E050 /* LocalChat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8790ACE9F73BD74640A0F20C /* LocalChat.swift */; };6FC65C190ED614C664C9BC17 /* SafeWebURL.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2FDED98F7F6C755A72C97A3 /* SafeWebURL.swift */; };733FCC6A45DE963EF2024B4E /* ChatMarkdownView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFE88A53AEAA637F866D479D /* ChatMarkdownView.swift */; };@@ -61,6 +64,7 @@8C32A0C3EAF536D3836F61D5 /* GreetingCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C581F7B1A9F14B281B60063E /* GreetingCanvasView.swift */; };8D1C01F283FA7806119A1C85 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C1A7D5CBE2AC084A10C5FF3 /* SettingsView.swift */; };8FC5907E9506DC79EB1DDC3C /* ChatMarkdown.swift in Sources */ = {isa = PBXBuildFile; fileRef = D797CC384B5BC70D34F121BC /* ChatMarkdown.swift */; };+ 908043F62E2C31F5FBC0A0C4 /* ShortcutsSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62CF42AE7611EF212CA0458F /* ShortcutsSettingsView.swift */; };94A742758D0FF79124E26B21 /* MochiWardrobe.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0BB15BD82E4A0B729045880 /* MochiWardrobe.swift */; };94E0849D13762C6EC8548FEF /* ClaudePlanCardView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4263B550838CC5614569D13 /* ClaudePlanCardView.swift */; };967B525F7D3837F31D740D18 /* ResendPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61B5FDDE03F5F711146937E2 /* ResendPoller.swift */; };@@ -69,8 +73,10 @@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 */; };+ B733A76DD197F6D6D949284C /* HotKeyCenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1218B86E249691AF44F819AC /* HotKeyCenter.swift */; };BA65FC4A40F7227837C26214 /* DesktopMochiLogic.swift in Sources */ = {isa = PBXBuildFile; fileRef = C086E1932F86B9C2B559BE03 /* DesktopMochiLogic.swift */; };BEC5DDB55B3DA67C61CA8470 /* DesktopMochi.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1DDC96E7967032F5D0BD585 /* DesktopMochi.swift */; };+ C07E9A04E827284FDF33DB16 /* ShortcutLogic.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA51E5B140C20812641168EA /* ShortcutLogic.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 */; };@@ -104,6 +110,7 @@/* End PBXBuildFile section *//* Begin PBXFileReference section */+ 1218B86E249691AF44F819AC /* HotKeyCenter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HotKeyCenter.swift; sourceTree = "<group>"; };15A1A8206F73376F4CAF2057 /* IslandRootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandRootView.swift; sourceTree = "<group>"; };168A9A73B519018FAB0AA465 /* GitHubActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GitHubActivity.swift; sourceTree = "<group>"; };192844E7299DEED5C2372067 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };@@ -118,6 +125,7 @@4F142FB3952B5F0639383047 /* MusicController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MusicController.swift; sourceTree = "<group>"; };506824380E9C80B9BC6DCE72 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };61B5FDDE03F5F711146937E2 /* ResendPoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResendPoller.swift; sourceTree = "<group>"; };+ 62CF42AE7611EF212CA0458F /* ShortcutsSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShortcutsSettingsView.swift; sourceTree = "<group>"; };6FD65943C32E150F1CD65C31 /* UploadSequenceEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UploadSequenceEngine.swift; sourceTree = "<group>"; };71718D1B87A39A4879DD2A9D /* VercelPoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VercelPoller.swift; sourceTree = "<group>"; };78BC1357785CA1B099A33969 /* IslandScreenGeometry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandScreenGeometry.swift; sourceTree = "<group>"; };@@ -153,6 +161,7 @@F4A13AEE6E06F46CEC9D908C /* UserIdentity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserIdentity.swift; sourceTree = "<group>"; };F8D3AD61802A32C4833F3EDA /* GitHubPulse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GitHubPulse.swift; sourceTree = "<group>"; };FA02B08886939FF6FE0475DD /* IslandViewContent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandViewContent.swift; sourceTree = "<group>"; };+ FA51E5B140C20812641168EA /* ShortcutLogic.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShortcutLogic.swift; sourceTree = "<group>"; };/* End PBXFileReference section *//* Begin PBXGroup section */@@ -180,6 +189,7 @@F8D3AD61802A32C4833F3EDA /* GitHubPulse.swift */,C581F7B1A9F14B281B60063E /* GreetingCanvasView.swift */,79D8DD79C3DD9BBC584B3CB2 /* HookServer.swift */,+ 1218B86E249691AF44F819AC /* HotKeyCenter.swift */,15A1A8206F73376F4CAF2057 /* IslandRootView.swift */,78BC1357785CA1B099A33969 /* IslandScreenGeometry.swift */,D8212018F09EA1E96FBD63CD /* IslandStateMachine.swift */,@@ -197,6 +207,8 @@61B5FDDE03F5F711146937E2 /* ResendPoller.swift */,B2FDED98F7F6C755A72C97A3 /* SafeWebURL.swift */,7C1A7D5CBE2AC084A10C5FF3 /* SettingsView.swift */,+ FA51E5B140C20812641168EA /* ShortcutLogic.swift */,+ 62CF42AE7611EF212CA0458F /* ShortcutsSettingsView.swift */,1BE21C2B315D37AA70ED45E9 /* SoundEngine.swift */,2EF78999D68D56ADE4CEFBE2 /* StripePoller.swift */,B241B043223AFBBFB7418A5E /* UploadCanvasView.swift */,@@ -367,6 +379,7 @@C808B654C84D9F71DBF8493A /* GithubPoller.swift in Sources */,8C32A0C3EAF536D3836F61D5 /* GreetingCanvasView.swift in Sources */,2C798C3837A63B9BB561A1A0 /* HookServer.swift in Sources */,+ B733A76DD197F6D6D949284C /* HotKeyCenter.swift in Sources */,CA3321C14A11FED94E48B3E3 /* IslandRootView.swift in Sources */,186AB8904029767DAA5277CF /* IslandScreenGeometry.swift in Sources */,5B9A00AFB0837731FA678E4E /* IslandStateMachine.swift in Sources */,@@ -384,6 +397,8 @@967B525F7D3837F31D740D18 /* ResendPoller.swift in Sources */,6FC65C190ED614C664C9BC17 /* SafeWebURL.swift in Sources */,56BE8C733F10A030A638FB60 /* SettingsView.swift in Sources */,+ C07E9A04E827284FDF33DB16 /* ShortcutLogic.swift in Sources */,+ 1EAFEE80A8066B77F9410025 /* ShortcutsSettingsView.swift in Sources */,60E361FFE84C387E5E3ED1AA /* SoundEngine.swift in Sources */,1558BB00C530B721172F6E65 /* StripePoller.swift in Sources */,62C4EE3F74DAA59764729E62 /* UploadCanvasView.swift in Sources */,@@ -419,6 +434,7 @@C18227D148D99FE6EE3CC51A /* GithubPoller.swift in Sources */,C0E18D0F6F5F6D131E6066B8 /* GreetingCanvasView.swift in Sources */,9DD56C95ECABDDCE23652D50 /* HookServer.swift in Sources */,+ 530443F46F896F037A56F663 /* HotKeyCenter.swift in Sources */,B605F976F4141435F27CF266 /* IslandRootView.swift in Sources */,0D68A4C4E3422487DB7B2262 /* IslandScreenGeometry.swift in Sources */,3756B7E1A55D9CEC8C4D34A4 /* IslandStateMachine.swift in Sources */,@@ -436,6 +452,8 @@EB23ED9F1C12EA8B54A76A91 /* ResendPoller.swift in Sources */,FEFEF1EBAB0E6CA74A33C10B /* SafeWebURL.swift in Sources */,8D1C01F283FA7806119A1C85 /* SettingsView.swift in Sources */,+ 6CCEC73ED68E9F253C22D692 /* ShortcutLogic.swift in Sources */,+ 908043F62E2C31F5FBC0A0C4 /* ShortcutsSettingsView.swift in Sources */,78B3C6814431B2DD9D1F4949 /* SoundEngine.swift in Sources */,E4B9986674F4D425826F15A8 /* StripePoller.swift in Sources */,4117E7C8AA231AAE36E7509D /* UploadCanvasView.swift in Sources */,diff --git a/NotchBuddy/Sources/App/AppDelegate.swift b/NotchBuddy/Sources/App/AppDelegate.swiftindex 6e4c47a6..4c8902ad 100644--- a/NotchBuddy/Sources/App/AppDelegate.swift+++ b/NotchBuddy/Sources/App/AppDelegate.swift@@ -6,6 +6,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {var statusItem: NSStatusItem?private(set) var islandController: IslandWindowController?+ func applicationWillTerminate(_ notification: Notification) {+ HotKeyCenter.shared.unregisterAll()+ }+func applicationDidFinishLaunching(_ notification: Notification) {// Ignore SIGPIPE — prevents crash when nb-hook closes socket before we write responsesignal(SIGPIPE, SIG_IGN)diff --git a/NotchBuddy/Sources/App/AppState.swift b/NotchBuddy/Sources/App/AppState.swiftindex 77fc32cd..d851b21d 100644--- a/NotchBuddy/Sources/App/AppState.swift+++ b/NotchBuddy/Sources/App/AppState.swift@@ -41,6 +41,11 @@ final class AppState: ObservableObject {// Pinned (alerts that stay open, never auto-close)var isPinned: Bool = false+ // Keyboard navigation — index of the selected item within the current card's list (nil = none)+ @Published var cardSelection: Int? = nil+ // Number of navigable items in the card currently on screen (0 = no list)+ @Published var cardItemCount: Int = 0+// Upload progress (0-1) — set to 1.0 only at completion; animation is time-based@Published var uploadProgress: Double = 0diff --git a/NotchBuddy/Sources/App/DesktopMochi.swift b/NotchBuddy/Sources/App/DesktopMochi.swiftindex 9ec7f4ff..b810365c 100644--- a/NotchBuddy/Sources/App/DesktopMochi.swift+++ b/NotchBuddy/Sources/App/DesktopMochi.swift@@ -150,6 +150,18 @@ final class DesktopMochiController {static let panelSize: CGFloat = DesktopMochiLogic.panelSize+ // MARK: - Keyboard shortcut toggle (⌃⌥D)++ /// Fly Mochi to the desktop if not there, or bring him back if he is.+ func flyOutOrHome() {+ if phase == .home {+ UserDefaults.standard.set(true, forKey: DesktopMochiController.enabledKey)+ launchFlyIfNeeded()+ } else if phase == .onDesktop {+ flyHome()+ }+ }+// MARK: - Install (from drag-drop)/// Promote `ghostPanel` (the drag ghost) or create a fresh panel as the desktop Mochi,diff --git a/NotchBuddy/Sources/App/HotKeyCenter.swift b/NotchBuddy/Sources/App/HotKeyCenter.swiftnew file mode 100644index 00000000..2af7ee95--- /dev/null+++ b/NotchBuddy/Sources/App/HotKeyCenter.swift@@ -0,0 +1,148 @@+import AppKit+import Carbon.HIToolbox++// MARK: - C-level event handler+//+// Carbon's InstallEventHandler requires a top-level C-compatible function.+// We store state in nonisolated(unsafe) globals — safe because all mutations+// happen on the main thread (Carbon dispatches hot-key events on the main thread).++private nonisolated(unsafe) var gHotKeyHandler: EventHandlerRef? = nil+private nonisolated(unsafe) var gHotKeyTable: [UInt32: ShortcutAction] = [:]+private nonisolated(unsafe) var gOnAction: ((ShortcutAction) -> Void)? = nil++private func coucouHotKeyEventHandler(+ _: EventHandlerCallRef?,+ _ event: EventRef?,+ _: UnsafeMutableRawPointer?+) -> OSStatus {+ guard let event else { return OSStatus(eventNotHandledErr) }+ var hkid = EventHotKeyID()+ let err = GetEventParameter(+ event,+ EventParamName(kEventParamDirectObject),+ EventParamType(typeEventHotKeyID),+ nil,+ MemoryLayout<EventHotKeyID>.size,+ nil,+ &hkid+ )+ guard err == noErr, let action = gHotKeyTable[hkid.id] else {+ return OSStatus(eventNotHandledErr)+ }+ // Carbon events are dispatched on the main thread.+ MainActor.assumeIsolated { gOnAction?(action) }+ return noErr+}++// MARK: - HotKeyCenter++/// Manages all global keyboard shortcuts via Carbon `RegisterEventHotKey`.+///+/// - No Accessibility permission required.+/// - Works in the App Store sandbox.+/// - The hot-key event is consumed and never forwarded to the front application.+@MainActor+final class HotKeyCenter {+ static let shared = HotKeyCenter()+ private init() {}++ // "COUC" in big-endian — unique signature for Coucou's hot-key IDs+ private let kSignature = OSType(0x434F5543)++ // Live registered refs (action → EventHotKeyRef)+ private var refs: [ShortcutAction: EventHotKeyRef] = [:]++ /// Actions whose `RegisterEventHotKey` call failed (system conflict).+ private(set) var conflicts: Set<ShortcutAction> = []++ // MARK: - Lifecycle++ /// Start the hot-key engine and fire `onAction` whenever the user presses a registered shortcut.+ /// Safe to call more than once — the handler is installed only once.+ func start(onAction: @escaping @MainActor (ShortcutAction) -> Void) {+ gOnAction = onAction++ if gHotKeyHandler == nil {+ var spec = EventTypeSpec(+ eventClass: OSType(kEventClassKeyboard),+ eventKind: UInt32(kEventHotKeyPressed)+ )+ InstallEventHandler(+ GetApplicationEventTarget(),+ coucouHotKeyEventHandler,+ 1, &spec,+ nil, &gHotKeyHandler+ )+ }++ registerAll()+ }++ /// Unregister every hot key. Called on app quit.+ func unregisterAll() {+ for (action, ref) in refs {+ UnregisterEventHotKey(ref)+ let idx = UInt32(ShortcutAction.allCases.firstIndex(of: action)!)+ gHotKeyTable.removeValue(forKey: idx)+ }+ refs.removeAll()+ }++ /// Re-register all shortcuts from the current UserDefaults state.+ func registerAll() {+ unregisterAll()+ conflicts.removeAll()++ for action in ShortcutAction.allCases {+ #if APPSTORE+ if action.isNonAppStore { continue }+ #endif+ if !ShortcutLogic.isEnabled(action) { continue }+ registerOne(action)+ }+ }++ /// Re-register a single action (called after a setting change).+ func reregister(_ action: ShortcutAction) {+ // Remove old registration if present+ if let ref = refs[action] {+ UnregisterEventHotKey(ref)+ let idx = UInt32(ShortcutAction.allCases.firstIndex(of: action)!)+ gHotKeyTable.removeValue(forKey: idx)+ refs.removeValue(forKey: action)+ }+ conflicts.remove(action)++ #if APPSTORE+ if action.isNonAppStore { return }+ #endif+ if !ShortcutLogic.isEnabled(action) { return }+ registerOne(action)+ }++ // MARK: - Private++ private func registerOne(_ action: ShortcutAction) {+ let spec = ShortcutLogic.hotKey(for: action)+ let carbon = ShortcutLogic.carbonModifiers(fromNS: spec.nsFlags)+ let idx = UInt32(ShortcutAction.allCases.firstIndex(of: action)!)+ let hkid = EventHotKeyID(signature: kSignature, id: idx)+ var ref: EventHotKeyRef?++ let status = RegisterEventHotKey(+ UInt32(spec.keyCode),+ carbon,+ hkid,+ GetApplicationEventTarget(),+ 0,+ &ref+ )+ if status == noErr, let ref {+ refs[action] = ref+ gHotKeyTable[idx] = action+ } else {+ conflicts.insert(action)+ }+ }+}diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swiftindex b0831bc1..3947f0d6 100644--- a/NotchBuddy/Sources/App/IslandViewContent.swift+++ b/NotchBuddy/Sources/App/IslandViewContent.swift@@ -166,6 +166,15 @@ struct OverviewView: View {GithubPoller.shared.refreshIfStale()}}+ .onReceive(NotificationCenter.default.publisher(for: .islandToggleDiff)) { _ in+ if let id = activeDiffId {+ withAnimation(.easeIn(duration: 0.16)) { activeDiffId = nil }+ _ = id+ } else if let task = state.focusTask,+ let last = state.sessionDiffs[task.id]?.last {+ withAnimation(.easeIn(duration: 0.16)) { activeDiffId = last.id }+ }+ }}private func openAgentTarget(_ task: AgentTask?) {@@ -1225,6 +1234,17 @@ struct PromptView: View {state.fetchModelsIfNeeded(for: provider)}}+ .onReceive(NotificationCenter.default.publisher(for: .islandSendMessage)) { _ in+ guard state.view == .prompt else { return }+ sendMessage()+ }+ .onReceive(NotificationCenter.default.publisher(for: .islandNewConversation)) { _ in+ guard state.view == .prompt else { return }+ text = ""+ state.chatHistory = []+ ClaudeService.shared.clearConversation()+ focused = true+ }}private func sendMessage() {@@ -2453,6 +2473,7 @@ struct GitHubDetailView: View {let activity: GitHubActivity?let stats: GitHubStats?let onBack: () -> Void+ @ObservedObject private var appState = AppState.sharedprivate var title: String {switch section {@@ -2475,6 +2496,8 @@ struct GitHubDetailView: View {section == .mainCI ? pulse.mainCI : []}+ private var totalItems: Int { items.count + repoItems.count }+var body: some View {if section == .activity {GitHubActivityDetailContent(@@ -2513,18 +2536,20 @@ struct GitHubDetailView: View {} else {ScrollView(.vertical, showsIndicators: false) {VStack(alignment: .leading, spacing: 0) {- ForEach(items, id: \.id) { pr in- GitHubPRRowView(pr: pr, showCI: section == .myPRs)+ ForEach(Array(items.enumerated()), id: \.element.id) { idx, pr in+ GitHubPRRowView(pr: pr, showCI: section == .myPRs,+ selected: appState.cardSelection == idx)}- ForEach(repoItems, id: \.repo) { repo in- GitHubRepoCIRowView(repo: repo)+ ForEach(Array(repoItems.enumerated()), id: \.element.repo) { idx, repo in+ GitHubRepoCIRowView(repo: repo,+ selected: appState.cardSelection == items.count + idx)}}}.frame(maxHeight: 60) // 3 rows × 20 pt; rest scrolls.mask(Group {- if (items.count + repoItems.count) > 3 {+ if totalItems > 3 {LinearGradient(stops: [.init(color: .black, location: 0),@@ -2546,7 +2571,28 @@ struct GitHubDetailView: View {.frame(maxWidth: .infinity, alignment: .topLeading).padding(.top, 4).clipped()- .onAppear { GithubPoller.shared.refreshIfStale() }+ .onAppear {+ GithubPoller.shared.refreshIfStale()+ appState.cardItemCount = totalItems+ }+ .onDisappear { appState.cardItemCount = 0 }+ .onReceive(NotificationCenter.default.publisher(for: .islandActivateCardSelection)) { _ in+ guard let sel = appState.cardSelection else { return }+ if sel < items.count {+ let pr = items[sel]+ if let url = safeWebURL(pr.url), url.host == "github.com" {+ NSWorkspace.shared.open(url)+ }+ } else {+ let repoIdx = sel - items.count+ guard repoIdx < repoItems.count else { return }+ let repo = repoItems[repoIdx]+ let actionsURL = repo.url.hasSuffix("/") ? repo.url + "actions" : repo.url + "/actions"+ if let url = safeWebURL(actionsURL), url.host == "github.com" {+ NSWorkspace.shared.open(url)+ }+ }+ }.onExitCommand { onBack() }}}@@ -2696,6 +2742,7 @@ private func ghCIDot(_ ci: CIState) -> Color {private struct GitHubPRRowView: View {let pr: GitHubPRlet showCI: Bool+ var selected: Bool = falsevar body: some View {Button(action: {@@ -2729,6 +2776,11 @@ private struct GitHubPRRowView: View {}.frame(maxWidth: .infinity, alignment: .leading).frame(height: 20)+ .overlay(+ RoundedRectangle(cornerRadius: 4)+ .fill(Color.white.opacity(0.12))+ .opacity(selected ? 1 : 0)+ )}.buttonStyle(.plain)}@@ -2736,6 +2788,7 @@ private struct GitHubPRRowView: View {private struct GitHubRepoCIRowView: View {let repo: GitHubRepoCI+ var selected: Bool = falseprivate var ciStateWord: String? {switch repo.ci {@@ -2777,6 +2830,11 @@ private struct GitHubRepoCIRowView: View {}.frame(maxWidth: .infinity, alignment: .leading).frame(height: 20)+ .overlay(+ RoundedRectangle(cornerRadius: 4)+ .fill(Color.white.opacity(0.12))+ .opacity(selected ? 1 : 0)+ )}.buttonStyle(.plain)}diff --git a/NotchBuddy/Sources/App/IslandWindowController.swift b/NotchBuddy/Sources/App/IslandWindowController.swiftindex 1b719f0e..c49e37ff 100644--- a/NotchBuddy/Sources/App/IslandWindowController.swift+++ b/NotchBuddy/Sources/App/IslandWindowController.swift@@ -47,6 +47,9 @@ final class IslandWindowController: NSWindowController {private var notchH: CGFloat = IslandConst.notchHeightprivate var hasNotch = true+ // Island-local key monitor (active only when island is key window)+ private var localKeyMonitor: Any?+convenience init() {let screen = Self.notchScreen() ?? NSScreen.main!let geometry = Self.screenGeometry(for: screen)@@ -139,6 +142,8 @@ final class IslandWindowController: NSWindowController {startPolling()startKeyMonitor()+ startLocalKeyMonitor()+ startHotKeys()wireFSM()// Make panel key whenever the prompt/chat view becomes active@@ -365,6 +370,206 @@ final class IslandWindowController: NSWindowController {window?.resignKey()}+ // MARK: - Global hot keys (Carbon)++ private func startHotKeys() {+ HotKeyCenter.shared.start { [weak self] action in+ self?.handleHotKey(action)+ }+ }++ func handleHotKey(_ action: ShortcutAction) {+ switch action {+ case .toggleIsland:+ if state.mode == .expanded {+ collapse()+ } else {+ islandPanel.makeKey()+ expand(to: defaultView())+ }++ case .openChat:+ islandPanel.makeKey()+ expand(to: .prompt)++ case .goToAlert:+ if state.pendingApproval != nil {+ islandPanel.makeKey()+ expand(to: .approval)+ } else if state.pendingQuestion != nil {+ islandPanel.makeKey()+ expand(to: .question)+ } else {+ NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.annoyed)+ SoundEngine.shared.play("error")+ }++ case .jumpToTerminal:+ #if !APPSTORE+ performJumpToTerminal()+ #endif++ case .attachFrontWindow:+ #if !APPSTORE+ performAttachFrontWindow()+ #endif++ case .nextPill:+ cyclePill(by: +1)++ case .prevPill:+ cyclePill(by: -1)++ case .muteToggle:+ state.soundEnabled.toggle()+ if state.soundEnabled { SoundEngine.shared.play("tick") }+ NotificationCenter.default.post(+ name: .triggerEmote,+ object: state.soundEnabled ? BotEmote.happy : BotEmote.annoyed)++ case .desktopToggle:+ DesktopMochiController.shared.flyOutOrHome()++ case .wardrobeToggle:+ if state.mode == .expanded && state.view == .wardrobe {+ collapse()+ } else {+ islandPanel.makeKey()+ expand(to: .wardrobe)+ }+ }+ }++ // MARK: - Island-local shortcuts++ private func startLocalKeyMonitor() {+ localKeyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in+ guard let self, self.islandPanel.isKeyWindow else { return event }+ return self.handleIslandKey(event) ? nil : event+ }+ }++ @discardableResult+ private func handleIslandKey(_ event: NSEvent) -> Bool {+ let raw = event.modifierFlags.intersection([.command, .control, .option, .shift])+ let cmd = raw == .command++ // ⌘→ — next pill+ if cmd && event.keyCode == 124 { cyclePill(by: +1); return true }+ // ⌘← — previous pill+ if cmd && event.keyCode == 123 { cyclePill(by: -1); return true }+ // ⌘↓ — navigate list down+ if cmd && event.keyCode == 125 { navigateCard(by: +1); return true }+ // ⌘↑ — navigate list up+ if cmd && event.keyCode == 126 { navigateCard(by: -1); return true }+ // ⌘O — open selected card item+ if cmd && event.keyCode == 31 { openCardSelection(); return true }+ // ⌘E — toggle diff+ if cmd && event.keyCode == 14 && state.view == .overview {+ NotificationCenter.default.post(name: .islandToggleDiff, object: nil)+ return true+ }+ // ⌘↩ — send chat message+ if cmd && event.keyCode == 36 && state.view == .prompt {+ NotificationCenter.default.post(name: .islandSendMessage, object: nil)+ return true+ }+ // ⌘K — new conversation+ if cmd && event.keyCode == 40 && state.view == .prompt {+ NotificationCenter.default.post(name: .islandNewConversation, object: nil)+ return true+ }+ // ⌘, — open Settings+ if cmd && event.keyCode == 43 {+ NotificationCenter.default.post(name: .openFullSettings, object: nil)+ return true+ }+ // ⌘P — pin / unpin+ if cmd && event.keyCode == 35 {+ state.isPinned.toggle()+ return true+ }+ // ⌘1–⌘9 — switch to pill by number+ let digitCodes: [UInt16: Int] = [18:1,19:2,20:3,21:4,23:5,22:6,26:7,28:8,25:9]+ if cmd, let n = digitCodes[event.keyCode] {+ switchToPill(number: n); return true+ }+ // ⎋ Escape — focused views (.onExitCommand) have first crack; fall back to collapse+ if event.keyCode == 53 && raw.isEmpty {+ let consumed = NSApp.sendAction(Selector(("cancelOperation:")), to: nil, from: nil)+ if !consumed && state.mode == .expanded && !state.isPinned {+ collapse()+ }+ return true+ }+ return false+ }++ // MARK: - Pill cycling helpers++ private func cyclePill(by delta: Int) {+ guard !state.tasks.isEmpty else { return }+ let ids = state.tasks.map { $0.id }+ let cur = ids.firstIndex(of: state.focusId ?? "") ?? 0+ state.setFocus(ids[(cur + delta + ids.count) % ids.count])+ state.cardSelection = nil+ expand(to: .overview)+ }++ private func switchToPill(number: Int) {+ guard number >= 1, number <= state.tasks.count else { return }+ state.setFocus(state.tasks[number - 1].id)+ state.cardSelection = nil+ expand(to: .overview)+ }++ private func navigateCard(by delta: Int) {+ guard state.cardItemCount > 0 else { return }+ state.cardSelection = ShortcutLogic.navigate(+ selection: state.cardSelection, delta: delta, itemCount: state.cardItemCount)+ }++ private func openCardSelection() {+ guard state.cardSelection != nil else { return }+ NotificationCenter.default.post(name: .islandActivateCardSelection, object: nil)+ }++ // MARK: - Terminal jump++ #if !APPSTORE+ private func performJumpToTerminal() {+ guard state.focusTask != nil else {+ SoundEngine.shared.play("error")+ NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.annoyed)+ return+ }+ let terminalBundleIds = ["com.apple.Terminal", "com.googlecode.iterm2",+ "net.kovidgoyal.kitty", "com.mitchellh.ghostty"]+ let activated = terminalBundleIds.compactMap { id in+ NSWorkspace.shared.runningApplications.first { $0.bundleIdentifier == id }+ }.first.map { $0.activate(options: .activateIgnoringOtherApps) }+ if activated == nil {+ NSWorkspace.shared.open(+ URL(fileURLWithPath: "/System/Applications/Utilities/Terminal.app"))+ }+ collapse()+ }++ private func performAttachFrontWindow() {+ guard let app = state.lastExternalApp else {+ SoundEngine.shared.play("error"); return+ }+ guard let ctx = WindowContextCapture.captureActive(from: app) else {+ SoundEngine.shared.play("error"); return+ }+ state.promptContext = ctx+ SoundEngine.shared.play("approve")+ NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.happy)+ islandPanel.makeKey()+ expand(to: .prompt)+ }+ #endif+// MARK: - Keyboard (Escape closes)private func startKeyMonitor() {@@ -543,18 +748,6 @@ final class IslandWindowController: NSWindowController {return event}- // Global hotkey to show island- NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { [weak self] event in- Task { @MainActor in- guard let self, self.state.hotkeyEnabled else { return }- let pressed = event.modifierFlags.intersection([.command, .control, .option, .shift]).rawValue- guard pressed == self.state.hotkeyFlags, event.keyCode == self.state.hotkeyCode else { return }- if self.state.mode == .hidden || self.state.mode == .compact {- self.expand(to: .overview)- }- }- }-// Track last external app for window context capturelet ourBundle = Bundle.main.bundleIdentifier ?? ""NSWorkspace.shared.notificationCenter.addObserver(@@ -930,8 +1123,12 @@ extension Notification.Name {static let botGulp = Notification.Name("notchBuddy.botGulp")static let botMorphTo = Notification.Name("notchBuddy.botMorphTo")static let islandAction = Notification.Name("notchBuddy.islandAction")- static let islandCollapse = Notification.Name("notchBuddy.islandCollapse")- static let openFullSettings = Notification.Name("notchBuddy.openFullSettings")+ static let islandCollapse = Notification.Name("notchBuddy.islandCollapse")+ static let islandSendMessage = Notification.Name("notchBuddy.islandSendMessage")+ static let islandNewConversation = Notification.Name("notchBuddy.islandNewConversation")+ static let islandToggleDiff = Notification.Name("notchBuddy.islandToggleDiff")+ static let islandActivateCardSelection = Notification.Name("notchBuddy.islandActivateCardSelection")+ static let openFullSettings = Notification.Name("notchBuddy.openFullSettings")static let hookReveal = Notification.Name("notchBuddy.hookReveal")static let musicReveal = Notification.Name("notchBuddy.musicReveal")// Greeting ↔ IslandWindowControllerdiff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swiftindex 93c6c852..0291f673 100644--- a/NotchBuddy/Sources/App/SettingsView.swift+++ b/NotchBuddy/Sources/App/SettingsView.swift@@ -134,6 +134,7 @@ struct SettingsView: View {SettingsSidebarRow(title: "Agents", icon: "terminal.fill", color: "#3B9EFF").tag("agents")SettingsSidebarRow(title: "Chat", icon: "bubble.left.and.bubble.right.fill", color: "#E07950").tag("chat")SettingsSidebarRow(title: "Integrations", icon: "puzzlepiece.extension.fill", color: "#7C5CFF").tag("integrations")+ SettingsSidebarRow(title: "Shortcuts", icon: "keyboard.fill", color: "#6366F1").tag("shortcuts")}.listStyle(.sidebar).scrollContentBackground(.hidden)@@ -201,6 +202,7 @@ struct SettingsView: View {case "agents": return "Agents"case "chat": return "Chat"case "integrations": return "Integrations"+ case "shortcuts": return "Shortcuts"default: return "General"}}@@ -211,6 +213,7 @@ struct SettingsView: View {case "agents": agentsSectioncase "chat": chatSectioncase "integrations": integrationsSection+ case "shortcuts": ShortcutsSettingsView()default: generalSection}}@@ -257,13 +260,22 @@ struct SettingsView: View {GroupBox("Hotkey") {VStack(alignment: .leading, spacing: 10) {Toggle("Show island with shortcut", isOn: $state.hotkeyEnabled)+ .onChange(of: state.hotkeyEnabled) { _, _ in+ HotKeyCenter.shared.reregister(.toggleIsland)+ }if state.hotkeyEnabled {HStack(spacing: 8) {Text("Shortcut").frame(width: 70, alignment: .leading)ShortcutRecorderButton(flags: $hotkeyFlags, code: $hotkeyCode)- .onChange(of: hotkeyFlags) { _, v in state.hotkeyFlags = v }- .onChange(of: hotkeyCode) { _, v in state.hotkeyCode = v }+ .onChange(of: hotkeyFlags) { _, v in+ state.hotkeyFlags = v+ HotKeyCenter.shared.reregister(.toggleIsland)+ }+ .onChange(of: hotkeyCode) { _, v in+ state.hotkeyCode = v+ HotKeyCenter.shared.reregister(.toggleIsland)+ }Text("presses this → island opens").font(.system(size: 11)).foregroundColor(.secondary)diff --git a/NotchBuddy/Sources/App/ShortcutLogic.swift b/NotchBuddy/Sources/App/ShortcutLogic.swiftnew file mode 100644index 00000000..7862174d--- /dev/null+++ b/NotchBuddy/Sources/App/ShortcutLogic.swift@@ -0,0 +1,236 @@+import Foundation++// MARK: - Shortcut Action++/// Every keyboard shortcut Coucou knows about.+/// The first 10 cases are *global* (registered with Carbon and effective from any app).+/// Island-local shortcuts are documented in `ShortcutLogic.islandShortcuts` but are+/// not managed here — they are handled by a local NSEvent monitor in IslandWindowController.+enum ShortcutAction: String, CaseIterable, Sendable {+ // MARK: Global (Carbon RegisterEventHotKey)+ case toggleIsland = "toggleIsland" // ⌘⇧N — open / close island (toggle)+ case openChat = "openChat" // ⌃⌥Space — open island on chat, focus field+ case goToAlert = "goToAlert" // ⌃⌥A — jump to pending alert+ case jumpToTerminal = "jumpToTerminal" // ⌃⌥T — focus agent terminal+ case attachFrontWindow = "attachFrontWindow" // ⌃⌥W — attach front window (non-AppStore)+ case nextPill = "nextPill" // ⌃⌥] — next pill, open if closed+ case prevPill = "prevPill" // ⌃⌥[ — previous pill, open if closed+ case muteToggle = "muteToggle" // ⌃⌥M — mute / unmute sounds+ case desktopToggle = "desktopToggle" // ⌃⌥D — send Mochi to desktop / bring back+ case wardrobeToggle = "wardrobeToggle" // ⌃⌥G — open / close wardrobe++ // MARK: UserDefaults keys++ /// Key code storage key. `toggleIsland` reuses the legacy "hotkeyCode" key.+ var udKeyCode: String {+ self == .toggleIsland ? "hotkeyCode" : "shortcut.\(rawValue).keyCode"+ }+ /// Modifier flags storage key. `toggleIsland` reuses the legacy "hotkeyFlags" key.+ var udFlags: String {+ self == .toggleIsland ? "hotkeyFlags" : "shortcut.\(rawValue).flags"+ }+ /// Enabled flag storage key. `toggleIsland` reuses the legacy "hotkeyEnabled" key.+ var udEnabled: String {+ self == .toggleIsland ? "hotkeyEnabled" : "shortcut.\(rawValue).enabled"+ }++ // MARK: Metadata++ var displayName: String {+ switch self {+ case .toggleIsland: return "Open / close island"+ case .openChat: return "Open chat"+ case .goToAlert: return "Go to alert"+ case .jumpToTerminal: return "Jump to terminal"+ case .attachFrontWindow: return "Attach front window"+ case .nextPill: return "Next pill"+ case .prevPill: return "Previous pill"+ case .muteToggle: return "Mute / unmute sounds"+ case .desktopToggle: return "Mochi on / off desktop"+ case .wardrobeToggle: return "Open / close wardrobe"+ }+ }++ /// Whether this action should be omitted from App Store builds.+ var isAppStoreOnly: Bool { false }+ var isNonAppStore: Bool { self == .attachFrontWindow }++ /// Whether the shortcut is enabled by default (all new global shortcuts are on by default;+ /// `toggleIsland` is off by default to match the pre-existing behaviour).+ var enabledByDefault: Bool { self != .toggleIsland }+}++// MARK: - Shortcut Spec++/// A key + modifier combination stored as plain values (no AppKit dependency).+struct ShortcutSpec: Equatable, Hashable, Sendable {+ /// Virtual key code (matching kVK_* constants and NSEvent.keyCode).+ var keyCode: UInt16+ /// NSEvent.ModifierFlags raw value — only the modifier bits (.command / .shift / .option / .control).+ /// Stored and compared as a plain UInt so this file stays AppKit-free.+ var nsFlags: UInt++ // MARK: NSEvent modifier raw values (stable since macOS 10.x; see AppKit/NSEvent.h)+ static let cmdBit: UInt = 1 << 20 // NSEvent.ModifierFlags.command = 1048576+ static let shiftBit: UInt = 1 << 17 // NSEvent.ModifierFlags.shift = 131072+ static let optBit: UInt = 1 << 19 // NSEvent.ModifierFlags.option = 524288+ static let ctrlBit: UInt = 1 << 18 // NSEvent.ModifierFlags.control = 262144+ static let modMask: UInt = cmdBit | shiftBit | optBit | ctrlBit++ /// True when nsFlags contains at least one of ⌘ ⇧ ⌥ ⌃.+ var hasModifier: Bool { nsFlags & ShortcutSpec.modMask != 0 }++ // MARK: Convenience values for the default table++ static let cmdShift: UInt = cmdBit | shiftBit // 1179648+ static let ctrlOpt: UInt = ctrlBit | optBit // 786432+}++// MARK: - Pure logic++/// Stateless helpers for shortcut management — no AppKit, fully unit-testable standalone.+enum ShortcutLogic {++ // MARK: - Default table++ static let defaults: [ShortcutAction: ShortcutSpec] = [+ .toggleIsland: ShortcutSpec(keyCode: 45, nsFlags: ShortcutSpec.cmdShift), // ⌘⇧N+ .openChat: ShortcutSpec(keyCode: 49, nsFlags: ShortcutSpec.ctrlOpt), // ⌃⌥Space+ .goToAlert: ShortcutSpec(keyCode: 0, nsFlags: ShortcutSpec.ctrlOpt), // ⌃⌥A+ .jumpToTerminal: ShortcutSpec(keyCode: 17, nsFlags: ShortcutSpec.ctrlOpt), // ⌃⌥T+ .attachFrontWindow: ShortcutSpec(keyCode: 13, nsFlags: ShortcutSpec.ctrlOpt), // ⌃⌥W+ .nextPill: ShortcutSpec(keyCode: 30, nsFlags: ShortcutSpec.ctrlOpt), // ⌃⌥]+ .prevPill: ShortcutSpec(keyCode: 33, nsFlags: ShortcutSpec.ctrlOpt), // ⌃⌥[+ .muteToggle: ShortcutSpec(keyCode: 46, nsFlags: ShortcutSpec.ctrlOpt), // ⌃⌥M+ .desktopToggle: ShortcutSpec(keyCode: 2, nsFlags: ShortcutSpec.ctrlOpt), // ⌃⌥D+ .wardrobeToggle: ShortcutSpec(keyCode: 5, nsFlags: ShortcutSpec.ctrlOpt), // ⌃⌥G+ ]++ // MARK: - Load / save (UserDefaults)++ /// Current spec for `action`, falling back to the default if not stored.+ static func hotKey(for action: ShortcutAction) -> ShortcutSpec {+ let ud = UserDefaults.standard+ let def = defaults[action]!+ let kc = ud.object(forKey: action.udKeyCode) as? Int ?? Int(def.keyCode)+ let fl = ud.object(forKey: action.udFlags) as? Int ?? Int(def.nsFlags)+ return ShortcutSpec(keyCode: UInt16(kc), nsFlags: UInt(fl))+ }++ static func save(_ spec: ShortcutSpec, for action: ShortcutAction) {+ UserDefaults.standard.set(Int(spec.keyCode), forKey: action.udKeyCode)+ UserDefaults.standard.set(Int(spec.nsFlags), forKey: action.udFlags)+ }++ static func isEnabled(_ action: ShortcutAction) -> Bool {+ UserDefaults.standard.object(forKey: action.udEnabled) as? Bool+ ?? action.enabledByDefault+ }++ static func setEnabled(_ enabled: Bool, for action: ShortcutAction) {+ UserDefaults.standard.set(enabled, forKey: action.udEnabled)+ }++ static func resetToDefault(_ action: ShortcutAction) {+ let def = defaults[action]!+ save(def, for: action)+ setEnabled(action.enabledByDefault, for: action)+ }++ // MARK: - Carbon modifier conversion++ // Carbon modifier bit flags (CarbonCore/Events.h) — no import needed, just constants.+ private static let cCmdKey: UInt32 = 1 << 8 // cmdKey = 256+ private static let cShiftKey: UInt32 = 1 << 9 // shiftKey = 512+ private static let cOptKey: UInt32 = 1 << 11 // optionKey = 2048+ private static let cCtrlKey: UInt32 = 1 << 12 // controlKey = 4096++ /// Convert NSEvent modifier flags (as raw UInt) to Carbon modifier bit mask.+ static func carbonModifiers(fromNS nsFlags: UInt) -> UInt32 {+ let cmd = ShortcutSpec.cmdBit+ let shift = ShortcutSpec.shiftBit+ let opt = ShortcutSpec.optBit+ let ctrl = ShortcutSpec.ctrlBit+ var c: UInt32 = 0+ if nsFlags & cmd != 0 { c |= cCmdKey }+ if nsFlags & shift != 0 { c |= cShiftKey }+ if nsFlags & opt != 0 { c |= cOptKey }+ if nsFlags & ctrl != 0 { c |= cCtrlKey }+ return c+ }++ // MARK: - Conflict detection (within Coucou's own shortcuts)++ /// Returns the set of actions whose (keyCode, nsFlags) pair is shared with another action.+ static func duplicates(in specs: [ShortcutAction: ShortcutSpec]) -> Set<ShortcutAction> {+ var seen: [ShortcutSpec: ShortcutAction] = [:]+ var dups: Set<ShortcutAction> = []+ for (action, spec) in specs {+ if let other = seen[spec] {+ dups.insert(action)+ dups.insert(other)+ } else {+ seen[spec] = action+ }+ }+ return dups+ }++ // MARK: - Display string++ /// Human-readable modifier+key string, e.g. "⌃⌥A" or "⌘⇧N".+ static func displayString(for spec: ShortcutSpec) -> String {+ let f = spec.nsFlags+ var s = ""+ if f & ShortcutSpec.ctrlBit != 0 { s += "⌃" }+ if f & ShortcutSpec.optBit != 0 { s += "⌥" }+ if f & ShortcutSpec.shiftBit != 0 { s += "⇧" }+ if f & ShortcutSpec.cmdBit != 0 { s += "⌘" }+ s += keyCodeToString(spec.keyCode)+ return s+ }++ /// Printable name for the most common virtual key codes.+ static func keyCodeToString(_ code: UInt16) -> String {+ let map: [UInt16: String] = [+ 0:"A", 1:"S", 2:"D", 3:"F", 4:"H", 5:"G", 6:"Z", 7:"X",+ 8:"C", 9:"V", 11:"B", 12:"Q", 13:"W", 14:"E", 15:"R", 16:"Y",+ 17:"T", 31:"O", 32:"U", 33:"[", 34:"I", 35:"P", 37:"L", 38:"J",+ 40:"K", 45:"N", 46:"M", 30:"]", 49:"Space",+ 36:"↩", 51:"⌫", 53:"⎋",+ 123:"←", 124:"→", 125:"↓", 126:"↑",+ 18:"1", 19:"2", 20:"3", 21:"4", 23:"5", 22:"6", 26:"7", 28:"8", 25:"9",+ ]+ return map[code] ?? "·"+ }++ // MARK: - Card navigation (pure, no AppKit dependency)++ /// Compute the next card-selection index.+ /// - Returns `nil` when `itemCount == 0`.+ /// - Clamps to `0 ..< itemCount`.+ /// - `nil` selection + `delta > 0` → first item; `delta < 0` → last item.+ static func navigate(selection: Int?, delta: Int, itemCount: Int) -> Int? {+ guard itemCount > 0 else { return nil }+ if let cur = selection {+ return max(0, min(itemCount - 1, cur + delta))+ }+ return delta > 0 ? 0 : itemCount - 1+ }++ // MARK: - Island-local shortcut table (read-only, shown in Settings)++ /// Descriptive table of island-local shortcuts for the Settings view.+ static let islandShortcuts: [(key: String, description: String)] = [+ ("⌘→ / ⌘←", "Next / previous pill"),+ ("⌘1 – ⌘9", "Switch to pill by number"),+ ("⌘↓ / ⌘↑", "Navigate list items"),+ ("⌘O", "Open selected item"),+ ("⌘E", "Open / close current diff"),+ ("⌘↩", "Send chat message"),+ ("⌘K", "New conversation"),+ ("⌘,", "Open Settings"),+ ("⌘P", "Pin / unpin island"),+ ("⎋", "Close island (if not pinned)"),+ ]+}diff --git a/NotchBuddy/Sources/App/ShortcutsSettingsView.swift b/NotchBuddy/Sources/App/ShortcutsSettingsView.swiftnew file mode 100644index 00000000..ce75985f--- /dev/null+++ b/NotchBuddy/Sources/App/ShortcutsSettingsView.swift@@ -0,0 +1,190 @@+import SwiftUI+import AppKit++// MARK: - ShortcutsSettingsView++/// "Shortcuts" section inside SettingsView.+struct ShortcutsSettingsView: View {+ // Conflicts detected by HotKeyCenter (system already owns that combo)+ @State private var systemConflicts: Set<ShortcutAction> = []+ // Internal duplicates (two Coucou shortcuts share the same combo)+ @State private var internalDups: Set<ShortcutAction> = []++ // Per-action state (enabled flag + current spec)+ @State private var enabled: [ShortcutAction: Bool] = [:]+ @State private var specs: [ShortcutAction: ShortcutSpec] = [:]++ var body: some View {+ VStack(alignment: .leading, spacing: 18) {+ globalSection+ islandSection+ }+ .onAppear { reload() }+ }++ // MARK: - Global shortcuts++ private var globalSection: some View {+ GroupBox("Global shortcuts — work from any app") {+ VStack(alignment: .leading, spacing: 0) {+ ForEach(ShortcutAction.allCases, id: \.self) { action in+ #if APPSTORE+ if action.isNonAppStore { EmptyView(); return }+ #endif+ shortcutRow(action)+ if action != ShortcutAction.allCases.last {+ Divider().padding(.leading, 24)+ }+ }+ Divider().padding(.top, 8)+ HStack {+ Spacer()+ Button("Reset all to defaults") { resetAll() }+ .buttonStyle(.bordered)+ .controlSize(.small)+ }+ .padding(.top, 6)+ }+ .padding(6)+ }+ }++ @ViewBuilder+ private func shortcutRow(_ action: ShortcutAction) -> some View {+ let isEnabled = enabled[action] ?? action.enabledByDefault+ let spec = specs[action] ?? ShortcutLogic.defaults[action]!+ let hasSysConf = systemConflicts.contains(action)+ let hasIntConf = internalDups.contains(action)++ HStack(spacing: 10) {+ Toggle("", isOn: Binding(+ get: { isEnabled },+ set: { v in toggleAction(action, enabled: v) }+ ))+ .labelsHidden()+ .toggleStyle(.checkbox)+ .frame(width: 18)++ Text(action.displayName)+ .font(.system(size: 12))+ .frame(minWidth: 160, alignment: .leading)++ Spacer(minLength: 4)++ ShortcutRecorderButton(flags: specFlagsBinding(action), code: specCodeBinding(action))+ .disabled(!isEnabled)+ .onChange(of: specs[action]) { _, _ in specChanged(action) }++ if hasSysConf {+ conflictTag("System conflict", color: .orange)+ } else if hasIntConf {+ conflictTag("Duplicate", color: .red)+ }+ }+ .padding(.vertical, 5)+ .opacity(isEnabled ? 1 : 0.5)+ }++ private func conflictTag(_ text: String, color: Color) -> some View {+ Text(text)+ .font(.system(size: 10, weight: .medium))+ .foregroundColor(color)+ .padding(.horizontal, 6)+ .padding(.vertical, 2)+ .background(color.opacity(0.1))+ .clipShape(Capsule())+ }++ // MARK: - Island-local shortcuts (read-only)++ private var islandSection: some View {+ GroupBox("Island shortcuts — active when the island is focused") {+ VStack(alignment: .leading, spacing: 0) {+ ForEach(Array(ShortcutLogic.islandShortcuts.enumerated()), id: \.offset) { _, pair in+ HStack(spacing: 10) {+ Text(pair.key)+ .font(.system(size: 11, design: .monospaced))+ .frame(width: 90, alignment: .leading)+ Text(pair.description)+ .font(.system(size: 12))+ .foregroundColor(.secondary)+ Spacer()+ }+ .padding(.vertical, 4)+ if pair.key != ShortcutLogic.islandShortcuts.last?.key {+ Divider().padding(.leading, 100)+ }+ }+ }+ .padding(6)+ }+ }++ // MARK: - Bindings++ private func specFlagsBinding(_ action: ShortcutAction) -> Binding<UInt> {+ Binding(+ get: { (specs[action] ?? ShortcutLogic.defaults[action]!).nsFlags },+ set: { v in+ var s = specs[action] ?? ShortcutLogic.defaults[action]!+ s.nsFlags = v+ specs[action] = s+ }+ )+ }++ private func specCodeBinding(_ action: ShortcutAction) -> Binding<UInt16> {+ Binding(+ get: { (specs[action] ?? ShortcutLogic.defaults[action]!).keyCode },+ set: { v in+ var s = specs[action] ?? ShortcutLogic.defaults[action]!+ s.keyCode = v+ specs[action] = s+ }+ )+ }++ // MARK: - Actions++ private func reload() {+ for action in ShortcutAction.allCases {+ enabled[action] = ShortcutLogic.isEnabled(action)+ specs[action] = ShortcutLogic.hotKey(for: action)+ }+ systemConflicts = HotKeyCenter.shared.conflicts+ updateInternalDups()+ }++ private func toggleAction(_ action: ShortcutAction, enabled v: Bool) {+ enabled[action] = v+ ShortcutLogic.setEnabled(v, for: action)+ HotKeyCenter.shared.reregister(action)+ systemConflicts = HotKeyCenter.shared.conflicts+ }++ private func specChanged(_ action: ShortcutAction) {+ guard let s = specs[action] else { return }+ ShortcutLogic.save(s, for: action)+ HotKeyCenter.shared.reregister(action)+ systemConflicts = HotKeyCenter.shared.conflicts+ updateInternalDups()+ }++ private func resetAll() {+ for action in ShortcutAction.allCases {+ ShortcutLogic.resetToDefault(action)+ HotKeyCenter.shared.reregister(action)+ }+ reload()+ }++ private func updateInternalDups() {+ var all: [ShortcutAction: ShortcutSpec] = [:]+ for action in ShortcutAction.allCases {+ if ShortcutLogic.isEnabled(action) {+ all[action] = ShortcutLogic.hotKey(for: action)+ }+ }+ internalDups = ShortcutLogic.duplicates(in: all)+ }+}diff --git a/README.md b/README.mdindex 0a62dfbc..5ece9ce0 100644--- a/README.md+++ b/README.md@@ -46,6 +46,7 @@ Meet **Mochi**: a soft little squircle with big eyes that pops out of your notch- 🔌 **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.- 👗 **Dress Mochi up** — right-click him for the wardrobe. He also dresses up for the seasons on his own.+- ⌨️ **Keyboard shortcuts** — open the chat, jump to an alert or a terminal, switch pills, mute, send Mochi to the desktop or open the wardrobe from anywhere; all customizable in Settings → Shortcuts.- 🎭 **A real character** — idle breathing, blinks, eyes on a sphere that follow your mouse, emotes, 28 handcrafted sounds, a greeting on launch.- 🫥 **Invisible when idle** — hides away when nothing is running, peeks out when you hover the notch (the top edge of the screen on Windows and Linux).- 🖥️ **Any Mac, notch or not** — on an iMac, a Mac mini, or a MacBook with its lid closed on an external display, Mochi sits in a small bar at the top of the screen.diff --git a/docs/SPEC.md b/docs/SPEC.mdindex 52835728..e2a511a1 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -355,3 +355,55 @@ Détection par `Publishers.CombineLatest($pendingApproval, $pendingQuestion)`- 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.++## 14. Raccourcis clavier++### 14.1 Raccourcis globaux (Carbon `RegisterEventHotKey`)++Ces raccourcis fonctionnent en arrière-plan sans permission Accessibilité.++| Action | Défaut | Clé UserDefaults | Activé par défaut |+|--------|--------|-----------------|-------------------|+| Afficher/masquer l'île (`toggleIsland`) | ⌘⇧N | `hotkeyCode` / `hotkeyFlags` (legacy) | Non |+| Ouvrir le chat (`openChat`) | ⌃⌥Espace | `shortcut.openChat.keyCode` / `.flags` | Oui |+| Aller à l'alerte (`goToAlert`) | ⌃⌥A | `shortcut.goToAlert.keyCode` / `.flags` | Oui |+| Sauter au terminal (`jumpToTerminal`) | ⌃⌥T | `shortcut.jumpToTerminal.keyCode` / `.flags` | Oui |+| Attacher la fenêtre active (`attachFrontWindow`) | ⌃⌥W | `shortcut.attachFrontWindow.keyCode` / `.flags` | Oui (hors App Store) |+| Pilule suivante (`nextPill`) | ⌃⌥] | `shortcut.nextPill.keyCode` / `.flags` | Oui |+| Pilule précédente (`prevPill`) | ⌃⌥[ | `shortcut.prevPill.keyCode` / `.flags` | Oui |+| Couper le son (`toggleMute`) | ⌃⌥M | `shortcut.toggleMute.keyCode` / `.flags` | Oui |+| Mochi sur le bureau (`toggleDesktopMochi`) | ⌃⌥D | `shortcut.toggleDesktopMochi.keyCode` / `.flags` | Oui |+| Ouvrir la garde-robe (`openWardrobe`) | ⌃⌥G | `shortcut.openWardrobe.keyCode` / `.flags` | Oui |++- Si Carbon ne peut pas enregistrer un raccourci (conflit système), l'action est marquée `.conflict` dans `HotKeyCenter` et un indicateur apparaît dans Réglages → Raccourcis.+- `toggleIsland` conserve les clés UserDefaults historiques (`hotkeyCode`, `hotkeyFlags`, `hotkeyEnabled`) pour ne pas casser les préférences existantes.+- Les actions marquées `isNonAppStore` (`attachFrontWindow`) sont omises du build App Store.++### 14.2 Raccourcis locaux (actifs quand l'île a le focus)++Ces raccourcis sont gérés par `NSEvent.addLocalMonitorForEvents`. L'île prend le focus clavier quand elle est ouverte via un raccourci global (jamais au survol ni à l'alerte).++| Raccourci | Action |+|-----------|--------|+| ⌘→ | Pilule suivante |+| ⌘← | Pilule précédente |+| ⌘1…⌘9 | Passe directement à la pilule n° 1–9 |+| ⌘↓ | Descend dans la liste de la carte active |+| ⌘↑ | Monte dans la liste de la carte active |+| ⌘O | Ouvre/développe l'élément sélectionné |+| ⌘E | Modifier le prompt courant |+| ⌘↩ | Envoyer le message (vue Prompt) |+| ⌘K | Nouvelle conversation (vue Prompt) |+| ⌘, | Ouvrir les Réglages |+| ⌘P | Copier le dernier message |+| ⌘⇧D | Afficher/masquer le diff |++### 14.3 Personnalisation++Réglages → Raccourcis (`ShortcutsSettingsView`) :++- Chaque raccourci global dispose d'un toggle (activer/désactiver) et d'un `ShortcutRecorderButton` pour le reconfigurer.+- Les conflits internes (deux actions avec le même raccourci) sont signalés en rouge.+- Les conflits système (Carbon a refusé l'enregistrement) sont signalés en orange.+- Bouton **Tout réinitialiser** remet les valeurs par défaut sur toutes les actions.+- Les raccourcis locaux sont affichés en lecture seule.diff --git a/scripts/test-shortcuts.sh b/scripts/test-shortcuts.shnew file mode 100755index 00000000..bfa4cfff--- /dev/null+++ b/scripts/test-shortcuts.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")/.."+TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/coucou-shortcuts.XXXXXX")"+trap 'rm -rf "$TEST_DIR"' EXIT+swiftc NotchBuddy/Sources/App/ShortcutLogic.swift \+ tests/ShortcutTests.swift -o "$TEST_DIR/shortcut-tests"+"$TEST_DIR/shortcut-tests"diff --git a/tests/ShortcutTests.swift b/tests/ShortcutTests.swiftnew file mode 100644index 00000000..3d98763f--- /dev/null+++ b/tests/ShortcutTests.swift@@ -0,0 +1,235 @@+import Foundation++@main+enum ShortcutTests {+ static func main() {+ testDefaultsExhaustive()+ testAllDefaultsHaveModifier()+ testNoDefaultDuplicates()+ testCarbonModifiers()+ testDisplayString()+ testDuplicateDetection()+ testLoadSaveRoundTrip()+ testLegacyKeysForToggleIsland()+ testEnabledByDefault()+ testKeyCodeToString()+ testCardNavigation()+ print("ShortcutLogic: all cases passed")+ }++ // MARK: - testDefaultsExhaustive++ static func testDefaultsExhaustive() {+ for action in ShortcutAction.allCases {+ precondition(ShortcutLogic.defaults[action] != nil,+ "missing default for \(action.rawValue)")+ }+ precondition(ShortcutLogic.defaults.count == ShortcutAction.allCases.count,+ "defaults table must cover every ShortcutAction")+ }++ // MARK: - testAllDefaultsHaveModifier++ static func testAllDefaultsHaveModifier() {+ for (action, spec) in ShortcutLogic.defaults {+ precondition(spec.hasModifier,+ "default for \(action.rawValue) has no modifier — bare keys not allowed")+ }+ }++ // MARK: - testNoDefaultDuplicates++ static func testNoDefaultDuplicates() {+ let dups = ShortcutLogic.duplicates(in: ShortcutLogic.defaults)+ precondition(dups.isEmpty,+ "duplicate default shortcuts: \(dups.map { $0.rawValue })")+ }++ // MARK: - testCarbonModifiers++ static func testCarbonModifiers() {+ // cmdShift = ⌘⇧+ let cmdShiftCarbon = ShortcutLogic.carbonModifiers(fromNS: ShortcutSpec.cmdShift)+ // Carbon: cmdKey = 256, shiftKey = 512+ precondition(cmdShiftCarbon & 256 != 0, "⌘ must set cmdKey bit in Carbon")+ precondition(cmdShiftCarbon & 512 != 0, "⇧ must set shiftKey bit in Carbon")+ precondition(cmdShiftCarbon & 2048 == 0, "⌘⇧ must not set optionKey")+ precondition(cmdShiftCarbon & 4096 == 0, "⌘⇧ must not set controlKey")++ // ctrlOpt = ⌃⌥+ let ctrlOptCarbon = ShortcutLogic.carbonModifiers(fromNS: ShortcutSpec.ctrlOpt)+ precondition(ctrlOptCarbon & 256 == 0, "⌃⌥ must not set cmdKey")+ precondition(ctrlOptCarbon & 512 == 0, "⌃⌥ must not set shiftKey")+ precondition(ctrlOptCarbon & 2048 != 0, "⌥ must set optionKey bit in Carbon")+ precondition(ctrlOptCarbon & 4096 != 0, "⌃ must set controlKey bit in Carbon")++ // Zero flags → zero Carbon flags+ precondition(ShortcutLogic.carbonModifiers(fromNS: 0) == 0,+ "no modifiers must produce zero Carbon flags")++ // All four modifiers+ let allNS = ShortcutSpec.cmdBit | ShortcutSpec.shiftBit |+ ShortcutSpec.optBit | ShortcutSpec.ctrlBit+ let allCarbon = ShortcutLogic.carbonModifiers(fromNS: allNS)+ precondition(allCarbon & (256 | 512 | 2048 | 4096) == (256 | 512 | 2048 | 4096),+ "all four NS modifiers must map to all four Carbon bits")+ }++ // MARK: - testDisplayString++ static func testDisplayString() {+ // ⌘⇧N+ let cmdShiftN = ShortcutSpec(keyCode: 45, nsFlags: ShortcutSpec.cmdShift)+ let s1 = ShortcutLogic.displayString(for: cmdShiftN)+ precondition(s1.contains("⌘"), "⌘⇧N display must contain ⌘")+ precondition(s1.contains("⇧"), "⌘⇧N display must contain ⇧")+ precondition(s1.contains("N"), "⌘⇧N display must contain N")++ // ⌃⌥A+ let ctrlOptA = ShortcutSpec(keyCode: 0, nsFlags: ShortcutSpec.ctrlOpt)+ let s2 = ShortcutLogic.displayString(for: ctrlOptA)+ precondition(s2.contains("⌃"), "⌃⌥A display must contain ⌃")+ precondition(s2.contains("⌥"), "⌃⌥A display must contain ⌥")+ precondition(s2.contains("A"), "⌃⌥A display must contain A")++ // No duplicate modifiers in the string+ precondition(s1.filter { $0 == "⌘" }.count == 1, "⌘ must appear exactly once")++ // ⌃⌥Space+ let ctrlOptSpace = ShortcutSpec(keyCode: 49, nsFlags: ShortcutSpec.ctrlOpt)+ let s3 = ShortcutLogic.displayString(for: ctrlOptSpace)+ precondition(s3.contains("Space"), "⌃⌥Space display must contain 'Space'")+ }++ // MARK: - testDuplicateDetection++ static func testDuplicateDetection() {+ // No duplicates in an empty dict+ precondition(ShortcutLogic.duplicates(in: [:]).isEmpty,+ "empty map must have no duplicates")++ // Single entry — no duplicate+ let specA = ShortcutSpec(keyCode: 0, nsFlags: ShortcutSpec.ctrlOpt)+ precondition(ShortcutLogic.duplicates(in: [.goToAlert: specA]).isEmpty,+ "single entry must have no duplicate")++ // Two different specs — no duplicate+ let specB = ShortcutSpec(keyCode: 17, nsFlags: ShortcutSpec.ctrlOpt)+ let twoUnique: [ShortcutAction: ShortcutSpec] = [.goToAlert: specA, .jumpToTerminal: specB]+ precondition(ShortcutLogic.duplicates(in: twoUnique).isEmpty,+ "two distinct specs must have no duplicate")++ // Same spec for two actions → both flagged+ let twoSame: [ShortcutAction: ShortcutSpec] = [.goToAlert: specA, .jumpToTerminal: specA]+ let dups = ShortcutLogic.duplicates(in: twoSame)+ precondition(dups.contains(.goToAlert), "first duped action must be flagged")+ precondition(dups.contains(.jumpToTerminal), "second duped action must be flagged")+ precondition(dups.count == 2, "exactly 2 actions must be flagged for one duplicate pair")++ // Same key code but different flags → not a duplicate+ let specC = ShortcutSpec(keyCode: 0, nsFlags: ShortcutSpec.cmdShift)+ let diffFlags: [ShortcutAction: ShortcutSpec] = [.goToAlert: specA, .jumpToTerminal: specC]+ precondition(ShortcutLogic.duplicates(in: diffFlags).isEmpty,+ "same key code with different modifiers must not be a duplicate")+ }++ // MARK: - testLoadSaveRoundTrip++ static func testLoadSaveRoundTrip() {+ // Use a test-only suite to avoid polluting the app UserDefaults+ let suiteName = "com.coucou.ShortcutTests.\(Int.random(in: 10000...99999))"+ guard let ud = UserDefaults(suiteName: suiteName) else {+ preconditionFailure("could not create test UserDefaults suite")+ }++ // Save a custom spec for .openChat+ let custom = ShortcutSpec(keyCode: 5, nsFlags: ShortcutSpec.cmdShift)+ ud.set(Int(custom.keyCode), forKey: ShortcutAction.openChat.udKeyCode)+ ud.set(Int(custom.nsFlags), forKey: ShortcutAction.openChat.udFlags)++ // Load it back using the raw UserDefaults API (same path ShortcutLogic.hotKey uses)+ let loadedKC = ud.object(forKey: ShortcutAction.openChat.udKeyCode) as? Int+ let loadedFl = ud.object(forKey: ShortcutAction.openChat.udFlags) as? Int+ precondition(loadedKC == Int(custom.keyCode), "saved key code must round-trip")+ precondition(loadedFl == Int(custom.nsFlags), "saved flags must round-trip")++ // Cleanup+ ud.removePersistentDomain(forName: suiteName)+ }++ // MARK: - testLegacyKeysForToggleIsland++ static func testLegacyKeysForToggleIsland() {+ precondition(ShortcutAction.toggleIsland.udKeyCode == "hotkeyCode",+ "toggleIsland must use legacy 'hotkeyCode' key")+ precondition(ShortcutAction.toggleIsland.udFlags == "hotkeyFlags",+ "toggleIsland must use legacy 'hotkeyFlags' key")+ precondition(ShortcutAction.toggleIsland.udEnabled == "hotkeyEnabled",+ "toggleIsland must use legacy 'hotkeyEnabled' key")++ // All other actions must NOT use the legacy keys+ for action in ShortcutAction.allCases where action != .toggleIsland {+ precondition(action.udKeyCode != "hotkeyCode",+ "\(action.rawValue) must not reuse legacy hotkeyCode key")+ }+ }++ // MARK: - testEnabledByDefault++ static func testEnabledByDefault() {+ // toggleIsland is OFF by default (existing behaviour)+ precondition(!ShortcutAction.toggleIsland.enabledByDefault,+ "toggleIsland must be disabled by default")++ // All other global shortcuts are ON by default+ for action in ShortcutAction.allCases where action != .toggleIsland {+ precondition(action.enabledByDefault,+ "\(action.rawValue) must be enabled by default")+ }+ }++ // MARK: - testKeyCodeToString++ static func testKeyCodeToString() {+ precondition(ShortcutLogic.keyCodeToString(0) == "A", "keyCode 0 = A")+ precondition(ShortcutLogic.keyCodeToString(45) == "N", "keyCode 45 = N")+ precondition(ShortcutLogic.keyCodeToString(49) == "Space", "keyCode 49 = Space")+ precondition(ShortcutLogic.keyCodeToString(30) == "]", "keyCode 30 = ]")+ precondition(ShortcutLogic.keyCodeToString(33) == "[", "keyCode 33 = [")+ precondition(ShortcutLogic.keyCodeToString(2) == "D", "keyCode 2 = D")+ // Unknown key code returns a placeholder+ let unknown = ShortcutLogic.keyCodeToString(200)+ precondition(!unknown.isEmpty, "unknown key code must return non-empty string")+ }++ // MARK: - testCardNavigation++ static func testCardNavigation() {+ // nil + down → first item+ precondition(ShortcutLogic.navigate(selection: nil, delta: +1, itemCount: 3) == 0,+ "nil+down must select first item")+ // nil + up → last item+ precondition(ShortcutLogic.navigate(selection: nil, delta: -1, itemCount: 3) == 2,+ "nil+up must select last item")+ // clamp at top+ precondition(ShortcutLogic.navigate(selection: 0, delta: -1, itemCount: 3) == 0,+ "selection 0 + up must clamp to 0")+ // clamp at bottom+ precondition(ShortcutLogic.navigate(selection: 2, delta: +1, itemCount: 3) == 2,+ "selection last + down must clamp to last")+ // normal step down+ precondition(ShortcutLogic.navigate(selection: 1, delta: +1, itemCount: 3) == 2,+ "1+down in 3-item list must yield 2")+ // normal step up+ precondition(ShortcutLogic.navigate(selection: 1, delta: -1, itemCount: 3) == 0,+ "1+up in 3-item list must yield 0")+ // delta 0 — no move+ precondition(ShortcutLogic.navigate(selection: 1, delta: 0, itemCount: 3) == 1,+ "delta 0 must not move selection")+ // empty card → nil (navigateCard guards on cardItemCount > 0, but test the pure function)+ precondition(ShortcutLogic.navigate(selection: nil, delta: +1, itemCount: 0) == nil,+ "empty card must return nil")+ precondition(ShortcutLogic.navigate(selection: 0, delta: +1, itemCount: 0) == nil,+ "any selection on empty card must return nil")+ }+}