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
Keep the permission card in the notch until it is answered (#117)
Louis3186879e9b35
diff --git a/NotchBuddy/Sources/App/HookServer.swift b/NotchBuddy/Sources/App/HookServer.swiftindex 41b71c0d..e5e726cc 100644--- a/NotchBuddy/Sources/App/HookServer.swift+++ b/NotchBuddy/Sources/App/HookServer.swift@@ -37,11 +37,49 @@ final class HookServer: @unchecked Sendable {private var serverFD: Int32 = -1private let connectionLock = NSLock()private var connectionCount = 0- private var pendingApprovalFD: Int32 = -1 // held open while user decides- private var activeSessionId: String? = nil // current Claude Code session+ private var pendingApprovalFD: Int32 = -1 // held open while user decides+ private var approvalFDSource: (any DispatchSourceRead)? = nil // monitors pendingApprovalFD+ private var activeSessionId: String? = nil // current Claude Code sessionprivate init() {}+ // MARK: - Approval fd helpers++ @MainActor+ private func cancelApprovalFDSource() {+ approvalFDSource?.cancel()+ approvalFDSource = nil+ }++ /// Cancels the approval fd source (which closes the fd via its cancel handler), shows a+ /// 3-second note, clears approval state, then collapses the island.+ @MainActor+ private func dismissApprovalCard(note: String) {+ // cancelApprovalFDSource() triggers the cancel handler which closes the fd.+ // Never close the fd here directly — Apple requires it to happen in the cancel handler.+ cancelApprovalFDSource()+ pendingApprovalFD = -1+ let state = AppState.shared+ state.pendingApproval = nil+ state.isPinned = false+ state.updateTask(id: "integration_claude", state: .working)+ clearPillBadge(id: "integration_claude")+ state.noteMessage = note+ state.view = .note+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) {+ NotificationCenter.default.post(name: .islandCollapse, object: nil)+ }+ }++ /// Returns the tool_input serialized as sorted-keys JSON, "" if absent or empty.+ /// Same computation used in processPermissionRequest and processEvent to match PostToolUse.+ private static func approvalInputKey(_ input: [String: Any]) -> String {+ guard !input.isEmpty,+ let data = try? JSONSerialization.data(withJSONObject: input, options: .sortedKeys),+ let str = String(data: data, encoding: .utf8) else { return "" }+ return str+ }+// MARK: - Startfunc start() {@@ -186,6 +224,30 @@ final class HookServer: @unchecked Sendable {let focused = state.focusId == agentId+ // While a permission request is pending on the Claude Code pill, skip events to+ // preserve the .approval state and keep the card visible.+ if state.pendingApproval != nil && agentId == "integration_claude" {+ if let pending = state.pendingApproval {+ switch name {+ case "PostToolUse", "PostToolUseFailure":+ // Only dismiss when this exact tool call finished — same session, tool and input.+ // Other parallel tools finishing must not close the card.+ if sessionId == pending.sessionId,+ (payload["tool_name"] as? String ?? "") == pending.tool,+ Self.approvalInputKey(payload["tool_input"] as? [String: Any] ?? [:]) == pending.inputKey {+ dismissApprovalCard(note: "Handled in VS Code.")+ }+ case "Stop", "StopFailure", "UserPromptSubmit", "SessionEnd":+ // Turn ended or session interrupted — the permission is moot.+ if sessionId == pending.sessionId {+ dismissApprovalCard(note: "Handled in VS Code.")+ }+ default: break+ }+ }+ return+ }+switch name {case "SessionStart":@@ -327,8 +389,8 @@ final class HookServer: @unchecked Sendable {default: isAlert = false}if state.mode == .expanded {- // Only force-switch view for alerts — leave user on their current view otherwise- if isAlert { state.view = view }+ // Don't hijack the approval card for other alerts+ if isAlert && state.pendingApproval == nil { state.view = view }} else if isAlert {// Alerts always force-expandNotificationCenter.default.post(name: .hookExpand, object: view)@@ -375,18 +437,21 @@ final class HookServer: @unchecked Sendable {}let tool = payload["tool_name"] as? String ?? "Tool"- var command = tool- if let input = payload["tool_input"] as? [String: Any] {- command = input["command"] as? String ?? tool- }+ let toolInput = payload["tool_input"] as? [String: Any] ?? [:]+ var command = toolInput["command"] as? String ?? tool+ let inputKey = Self.approvalInputKey(toolInput)nbLog("PermissionRequest \(tool)")if pendingApprovalFD >= 0 {+ // Displace the previous request: write "ask" then cancel its source.+ // The cancel handler closes the old fd — never close it directly.let old = pendingApprovalFD+ let oldSource = approvalFDSource+ approvalFDSource = nilTask.detached { [weak self] in// "ask" → nb-hook outputs nothing → Claude Code re-asksself?.sendLine(fd: old, text: #"{"permissionDecision":"ask"}"#)- close(old)+ DispatchQueue.main.async { oldSource?.cancel() }}}pendingApprovalFD = fd@@ -394,7 +459,8 @@ final class HookServer: @unchecked Sendable {upsertTask(projectName: projectName, cwd: cwd)state.updateTask(id: "integration_claude", state: .approval)- state.pendingApproval = ApprovalInfo(sessionId: sessionId, tool: tool, command: command)+ state.pendingApproval = ApprovalInfo(sessionId: sessionId, tool: tool,+ command: command, inputKey: inputKey)state.isPinned = trueSoundEngine.shared.play("approval")@@ -402,11 +468,23 @@ final class HookServer: @unchecked Sendable {state.focusId = "integration_claude"expandIfNeeded(to: .approval)+ // Monitor fd: if VS Code closes the connection (handled externally), dismiss the card.+ // The cancel handler closes the fd — never close it anywhere else.+ let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: .main)+ source.setEventHandler { [weak self] in+ guard let self, self.pendingApprovalFD == fd else { return }+ self.dismissApprovalCard(note: "Handled in VS Code.")+ }+ source.setCancelHandler { close(fd) }+ source.resume()+ approvalFDSource = source++ // 115s safety timeout — show a note and cancel without sending a decision.+ // nb-hook reads EOF from the cancel handler's close and exits; Claude Code re-asks.let captured = fdDispatchQueue.main.asyncAfter(deadline: .now() + 115) { [weak self] inguard let self, self.pendingApprovalFD == captured else { return }- // "ask" → nb-hook outputs nothing → Claude Code re-asks rather than denying- self.sendApprovalDecision("ask")+ self.dismissApprovalCard(note: "Still waiting in VS Code.")}}@@ -415,6 +493,10 @@ final class HookServer: @unchecked Sendable {func sendApprovalDecision(_ decision: String) {let fd = pendingApprovalFDpendingApprovalFD = -1+ // Capture source before nulling — we send the decision first, then cancel the source.+ // The cancel handler closes the fd; never close it directly.+ let source = approvalFDSource+ approvalFDSource = nillet json: Stringswitch decision {@@ -426,9 +508,12 @@ final class HookServer: @unchecked Sendable {if fd >= 0 {Task.detached { [weak self] in+ // Write decision while fd is still valid, then cancel source → cancel handler closes fdself?.sendLine(fd: fd, text: json)- close(fd)+ DispatchQueue.main.async { source?.cancel() }}+ } else {+ source?.cancel()}let state = AppState.shareddiff --git a/NotchBuddy/Sources/App/IslandStateMachine.swift b/NotchBuddy/Sources/App/IslandStateMachine.swiftindex 4c309bed..a8fe3319 100644--- a/NotchBuddy/Sources/App/IslandStateMachine.swift+++ b/NotchBuddy/Sources/App/IslandStateMachine.swift@@ -17,6 +17,9 @@ final class IslandStateMachine {/// 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). Override for debug.var homeToPetitDelay: TimeInterval = 15/// petit → hidden delay (seconds). Override for debug.@@ -42,8 +45,13 @@ final class IslandStateMachine {func mouseEntered() {switch state {case .hidden:- cancelTimers()- transition(to: .petit)+ 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@@ -64,11 +72,13 @@ final class IslandStateMachine {case .petit:schedulePetitHide()case .home:- scheduleHomeCollapse()+ if isHeldOpen?() != true { scheduleHomeCollapse() }case .coucou:- // Interrupt greeting immediately → compact (overrides 10s auto-collapse)- greetCollapseWork?.cancel(); greetCollapseWork = nil- transition(to: .petit)+ if isHeldOpen?() != true {+ // Interrupt greeting immediately → compact (overrides 10s auto-collapse)+ greetCollapseWork?.cancel(); greetCollapseWork = nil+ transition(to: .petit)+ }}}@@ -90,6 +100,15 @@ final class IslandStateMachine {state = .hidden}+ /// The app expanded the island externally (hookExpand for an alert).+ /// Cancel timers and sync state to `.home` without firing `onTransition`, so the+ /// next hover/mouseLeft behave correctly instead of collapsing the island.+ func openedExternally() {+ cancelTimers()+ guard state != .home && state != .coucou else { return }+ state = .home+ }+/// 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`.@@ -132,7 +151,7 @@ final class IslandStateMachine {private func schedulePetitHide() {petitHideWork?.cancel()let item = DispatchWorkItem { [weak self] in- guard let self, self.state == .petit else { return }+ guard let self, self.state == .petit, !(self.isHeldOpen?() ?? false) else { return }self.transition(to: .hidden)}petitHideWork = item@@ -142,7 +161,7 @@ final class IslandStateMachine {private func scheduleHomeCollapse() {homeCollapseWork?.cancel()let item = DispatchWorkItem { [weak self] in- guard let self, self.state == .home else { return }+ guard let self, self.state == .home, !(self.isHeldOpen?() ?? false) else { return }self.transition(to: .petit)}homeCollapseWork = itemdiff --git a/NotchBuddy/Sources/App/IslandTypes.swift b/NotchBuddy/Sources/App/IslandTypes.swiftindex 5200af8e..324b6dc3 100644--- a/NotchBuddy/Sources/App/IslandTypes.swift+++ b/NotchBuddy/Sources/App/IslandTypes.swift@@ -34,6 +34,8 @@ struct ApprovalInfo: Sendable {var sessionId: Stringvar tool: Stringvar command: String+ /// tool_input serialized to JSON with sortedKeys, "" if absent — used to match PostToolUse.+ var inputKey: String}// MARK: - Pill badge (shown on pill edge when non-focused task has an alert)diff --git a/NotchBuddy/Sources/App/IslandWindowController.swift b/NotchBuddy/Sources/App/IslandWindowController.swiftindex d506297c..122ecfd1 100644--- a/NotchBuddy/Sources/App/IslandWindowController.swift+++ b/NotchBuddy/Sources/App/IslandWindowController.swift@@ -191,6 +191,8 @@ final class IslandWindowController: NSWindowController {) { [weak self] _ inself?.fsm.greetComplete()}++ fsm.isHeldOpen = { AppState.shared.pendingApproval != nil }}// MARK: - 60 Hz polling loop@@ -330,7 +332,10 @@ final class IslandWindowController: NSWindowController {: .spring(response: 0.5, dampingFraction: 0.72)withAnimation(anim) { state.mode = mode }if mode == .expanded { SoundEngine.shared.play("open") }- if prev == .expanded { SoundEngine.shared.play("close"); state.isPinned = false }+ if prev == .expanded {+ SoundEngine.shared.play("close")+ if fsm.isHeldOpen?() != true { state.isPinned = false }+ }}func expand(to view: IslandView) {@@ -344,6 +349,7 @@ final class IslandWindowController: NSWindowController {}func collapse() {+ guard fsm.isHeldOpen?() != true else { return }state.isPinned = falsefinishedPinTimer?.cancel()// Keep the FSM in step with what is on screen (home/coucou → petit now).@@ -369,6 +375,7 @@ final class IslandWindowController: NSWindowController {// Hook server expand requests (alerts only)NotificationCenter.default.addObserver(forName: .hookExpand, object: nil, queue: .main) { [weak self] note inguard let self, let view = note.object as? IslandView else { return }+ self.fsm.openedExternally()self.expand(to: view)}@@ -687,7 +694,8 @@ final class IslandWindowController: NSWindowController {// MARK: - Helpersfunc defaultView() -> IslandView {- state.tasks.isEmpty ? .empty : .overview+ if state.pendingApproval != nil { return .approval }+ return state.tasks.isEmpty ? .empty : .overview}func baseMode() -> IslandMode {