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.

Permission requests queue up instead of pushing each other away

Claudee391a142c98f
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 0211f171..d52b04ff 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -30,6 +30,9 @@ jobs:
- name: Test parallel Claude Code sessions
run: bash scripts/test-session-registry.sh
+ - name: Test approval queue
+ run: bash scripts/test-approval-queue.sh
+
- name: Desktop Mochi and gaze tests
run: bash scripts/test-desktop-mochi.sh
diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
index 9e51bce8..a337e02c 100644
--- a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
@@ -46,6 +46,7 @@
1C2BB61FA83015C42B321E0E /* PillColors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37564F5F041B38C976DF3DEF /* PillColors.swift */; };
1D23613B270FE8B11C5E27A7 /* IslandDisplayChoice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A09E73F1E58019EF6EA2A62 /* IslandDisplayChoice.swift */; };
1D4CE0CCD2B5A0FFE50C7F06 /* TerminalTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87AF6F7A027AB1D46309DD49 /* TerminalTarget.swift */; };
+ 65F11D3911C3240BD89CF1C5 /* ApprovalQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5077E908D307285474CA87C /* ApprovalQueue.swift */; };
9CF7070265B7CDC933FD9776 /* PillSessionRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30A2AD5885FA3226E0337D67 /* PillSessionRegistry.swift */; };
1DAB0704A136FF8E6FB34191 /* ClaudeResponseText.swift in Sources */ = {isa = PBXBuildFile; fileRef = 444604C7E2C530B664849EF9 /* ClaudeResponseText.swift */; };
1DCF28998358810CDBC93F91 /* ClaudeHookDetection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1EA7D927F6BB2667D37AA963 /* ClaudeHookDetection.swift */; };
@@ -126,6 +127,7 @@
65CB53E20B2289CA3AC3E8FE /* TurnSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A1C4152EBDBD7C24CABFFD7 /* TurnSnapshot.swift */; };
6613EB914852E6EEB1FF37BF /* IntentParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = F39753CFF90B494D449CCD95 /* IntentParser.swift */; };
6726F74966EDE7F82BFE89B2 /* TerminalTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87AF6F7A027AB1D46309DD49 /* TerminalTarget.swift */; };
+ 3E808AC02E35ABF5801BEBEC /* ApprovalQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5077E908D307285474CA87C /* ApprovalQueue.swift */; };
11363898DA837388E2823E7F /* PillSessionRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30A2AD5885FA3226E0337D67 /* PillSessionRegistry.swift */; };
68A950E3C23FD612639D9776 /* IslandViewContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA02B08886939FF6FE0475DD /* IslandViewContent.swift */; };
68C3ACC708B69035FD0CB8C4 /* TurnSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A1C4152EBDBD7C24CABFFD7 /* TurnSnapshot.swift */; };
@@ -438,6 +440,7 @@
871CA2BADC67D97C97C7009D /* error.wav */ = {isa = PBXFileReference; lastKnownFileType = audio.wav; path = error.wav; sourceTree = "<group>"; };
8790ACE9F73BD74640A0F20C /* LocalChat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalChat.swift; sourceTree = "<group>"; };
87AF6F7A027AB1D46309DD49 /* TerminalTarget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalTarget.swift; sourceTree = "<group>"; };
+ E5077E908D307285474CA87C /* ApprovalQueue.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApprovalQueue.swift; sourceTree = "<group>"; };
30A2AD5885FA3226E0337D67 /* PillSessionRegistry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PillSessionRegistry.swift; sourceTree = "<group>"; };
888B3E1420BCB6292BDC8117 /* WeeklyRecapView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeeklyRecapView.swift; sourceTree = "<group>"; };
8ACB4350729C6513824D1ADF /* ColorHex.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColorHex.swift; sourceTree = "<group>"; };
@@ -582,6 +585,7 @@
914A792788D403F836BEB570 /* SpotifyViews.swift */,
2EF78999D68D56ADE4CEFBE2 /* StripePoller.swift */,
87AF6F7A027AB1D46309DD49 /* TerminalTarget.swift */,
+ E5077E908D307285474CA87C /* ApprovalQueue.swift */,
30A2AD5885FA3226E0337D67 /* PillSessionRegistry.swift */,
244A7909EEDA4BFF4C2EA9B5 /* TerminalTarget+AppKit.swift */,
B241B043223AFBBFB7418A5E /* UploadCanvasView.swift */,
@@ -1055,6 +1059,7 @@
1558BB00C530B721172F6E65 /* StripePoller.swift in Sources */,
9EA178EA395B116336C1FA10 /* TerminalTarget+AppKit.swift in Sources */,
1D4CE0CCD2B5A0FFE50C7F06 /* TerminalTarget.swift in Sources */,
+ 65F11D3911C3240BD89CF1C5 /* ApprovalQueue.swift in Sources */,
9CF7070265B7CDC933FD9776 /* PillSessionRegistry.swift in Sources */,
8551E592C5FFC6A0A7458A26 /* TurnEndPolicy.swift in Sources */,
0408FE7F86EBEE61CAED32DA /* TurnRecorder.swift in Sources */,
@@ -1248,6 +1253,7 @@
E4B9986674F4D425826F15A8 /* StripePoller.swift in Sources */,
11F14DB97C93CF84DF9D5C43 /* TerminalTarget+AppKit.swift in Sources */,
6726F74966EDE7F82BFE89B2 /* TerminalTarget.swift in Sources */,
+ 3E808AC02E35ABF5801BEBEC /* ApprovalQueue.swift in Sources */,
11363898DA837388E2823E7F /* PillSessionRegistry.swift in Sources */,
ABE0CEF17018F1BAD8F7DBFA /* TurnEndPolicy.swift in Sources */,
CE0A1BD64DF3E08D200691A6 /* TurnRecorder.swift in Sources */,
diff --git a/NotchBuddy/Sources/App/ApprovalQueue.swift b/NotchBuddy/Sources/App/ApprovalQueue.swift
new file mode 100644
index 00000000..e5c02353
--- /dev/null
+++ b/NotchBuddy/Sources/App/ApprovalQueue.swift
@@ -0,0 +1,85 @@
+import Foundation
+
+// MARK: - ApprovalQueue
+// Pure FIFO queue of pending PermissionRequests. No AppKit, no SwiftUI, no I/O:
+// HookServer owns the sockets, timers and UI, and mutates this value on the main actor only.
+// The head is the request currently shown on the approval card.
+
+struct QueuedApproval: Equatable, Sendable {
+ let id: UUID
+ /// Client socket, held open until the user decides. Closed by the owner's dispatch source.
+ let fd: Int32
+ let sessionId: String
+ /// "integration_claude", "agent_cursor" or "agent_codex".
+ let pillId: String
+ let projectName: String
+ let cwd: String
+ let tool: String
+ let command: String
+ /// tool_input serialized with sortedKeys, "" if absent. Used to match PostToolUse.
+ let inputKey: String
+ /// Host app / bundle id of the session, so the card's pill keeps showing where it runs.
+ var hostApp: String? = nil
+ var bundleId: String = ""
+}
+
+struct ApprovalQueue: Sendable {
+ /// Upper bound of simultaneously pending requests. Each one holds a socket and a 115 s timer
+ /// and the card only shows one at a time, so beyond this the newest falls back to its terminal.
+ static let maxPending = 5
+
+ enum EnqueueResult: Equatable, Sendable { case accepted, rejectedFull }
+
+ private(set) var entries: [QueuedApproval] = []
+
+ var head: QueuedApproval? { entries.first }
+ var count: Int { entries.count }
+ var isEmpty: Bool { entries.isEmpty }
+
+ func contains(id: UUID) -> Bool { entries.contains { $0.id == id } }
+
+ /// 1-based position of the entry in the queue, nil if absent.
+ func position(of id: UUID) -> Int? {
+ entries.firstIndex { $0.id == id }.map { $0 + 1 }
+ }
+
+ /// True when the queued requests do not all come from the same session and agent.
+ var hasMixedSources: Bool {
+ guard let first = entries.first else { return false }
+ return entries.contains { $0.sessionId != first.sessionId || $0.pillId != first.pillId }
+ }
+
+ func hasEntries(forPill pillId: String) -> Bool {
+ entries.contains { $0.pillId == pillId }
+ }
+
+ mutating func enqueue(_ entry: QueuedApproval, maxPending: Int = ApprovalQueue.maxPending) -> EnqueueResult {
+ guard entries.count < maxPending else { return .rejectedFull }
+ entries.append(entry)
+ return .accepted
+ }
+
+ /// Removes only the entry with this id. Other entries keep their order.
+ @discardableResult
+ mutating func remove(id: UUID) -> QueuedApproval? {
+ guard let idx = entries.firstIndex(where: { $0.id == id }) else { return nil }
+ return entries.remove(at: idx)
+ }
+
+ /// Entries made moot by a later hook event of the same agent. Matching is per request
+ /// (session + agent, plus tool and input for PostToolUse), never by pill alone.
+ func resolved(byEvent name: String, sessionId: String, pillId: String,
+ tool: String, inputKey: String) -> [QueuedApproval] {
+ switch name {
+ case "PostToolUse", "PostToolUseFailure":
+ return entries.filter {
+ $0.pillId == pillId && $0.sessionId == sessionId
+ && $0.tool == tool && $0.inputKey == inputKey
+ }
+ case "Stop", "StopFailure", "UserPromptSubmit", "SessionEnd", "Interrupt":
+ return entries.filter { $0.pillId == pillId && $0.sessionId == sessionId }
+ default:
+ return []
+ }
+ }
+}
diff --git a/NotchBuddy/Sources/App/HookServer.swift b/NotchBuddy/Sources/App/HookServer.swift
index 3cec178c..3d6c37b0 100644
--- a/NotchBuddy/Sources/App/HookServer.swift
+++ b/NotchBuddy/Sources/App/HookServer.swift
@@ -38,13 +38,17 @@ final class HookServer: @unchecked Sendable {
private var serverFD: Int32 = -1
private let connectionLock = NSLock()
private var connectionCount = 0
- private var pendingApprovalFD: Int32 = -1 // held open while user decides
- private var approvalFDSource: (any DispatchSourceRead)? = nil // monitors pendingApprovalFD
+ /// Permission requests waiting for a click, oldest first; the head is on the card.
+ /// Each one holds its nb-hook connection open until it is answered or dropped.
+ private var approvals = ApprovalQueue()
+ /// One read source per queued request: it notices the client hanging up, and its
+ /// cancel handler is the only place the request's fd is closed.
+ private var approvalSources: [UUID: any DispatchSourceRead] = [:]
private var pendingQuestionFD: Int32 = -1 // held open while user answers AskUserQuestion
private var questionFDSource: (any DispatchSourceRead)? = nil // monitors pendingQuestionFD
/// True when a real nb-hook connection is holding the approval fd open.
- @MainActor var hasRealPendingApproval: Bool { pendingApprovalFD >= 0 }
+ @MainActor var hasRealPendingApproval: Bool { !approvals.isEmpty }
/// True when a real nb-hook connection is holding the question fd open.
@MainActor var hasRealPendingQuestion: Bool { pendingQuestionFD >= 0 }
private var questionPillId: String = "" // pill that owns the pending question
@@ -56,39 +60,104 @@ final class HookServer: @unchecked Sendable {
private init() {}
- // MARK: - Approval fd helpers
+ // MARK: - Approval queue helpers
+ /// Note shown when a request was answered outside Coucou.
@MainActor
- private func cancelApprovalFDSource() {
- approvalFDSource?.cancel()
- approvalFDSource = nil
+ private func handledNote(pill: String) -> String {
+ switch pill {
+ case "agent_cursor": return "Handled in Cursor."
+ case "agent_codex": return "Handled in Codex."
+ case "agent_copilot": return "Handled in Copilot CLI."
+ case "agent_muse": return "Handled in Muse Code."
+ case "agent_hermes": return "Handled in Hermes."
+ default: return "Handled in \(claudeHostName)."
+ }
+ }
+
+ /// Note shown when a request waited too long and went back to the agent.
+ @MainActor
+ private func waitingNote(pill: String) -> String {
+ switch pill {
+ case "agent_cursor": return "Still waiting in Cursor."
+ case "agent_codex": return "Still waiting in Codex."
+ case "agent_copilot": return "Still waiting in Copilot CLI."
+ case "agent_muse": return "Still waiting in Muse Code."
+ case "agent_hermes": return "Still waiting in Hermes."
+ default: return "Still waiting in \(claudeHostName)."
+ }
}
- /// 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.
+ /// Puts the oldest waiting request on the card. When the card already shows it, only
+ /// its "n waiting" count is refreshed (no sound, no focus change).
@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
+ private func showApprovalHead() {
let state = AppState.shared
- let pillId = state.pendingApproval?.pillId ?? "integration_claude"
+ guard let head = approvals.head else { return }
+ if let shown = state.pendingApproval, shown.id == head.id {
+ if shown.queueCount != approvals.count { state.pendingApproval?.queueCount = approvals.count }
+ return
+ }
+ state.updateTask(id: head.pillId, state: .approval)
+ state.pendingApproval = ApprovalInfo(sessionId: head.sessionId, tool: head.tool,
+ command: head.command, inputKey: head.inputKey,
+ pillId: head.pillId, id: head.id,
+ queueCount: approvals.count,
+ projectName: head.projectName)
+ state.isPinned = true
+ // Approval always forces the island open — the user must be able to respond.
+ // Save the focus once, so it comes back when the last request is gone.
+ if focusBeforeApproval == nil { focusBeforeApproval = state.focusId }
+ withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = head.pillId }
+ expandIfNeeded(to: .approval)
+ }
+
+ /// Takes one request out of the queue. With `answer`, the decision is written to its
+ /// nb-hook first; without, the connection just closes and the agent asks again itself.
+ /// The cancel handler of its source closes the fd — never close it directly.
+ /// The next request in line then takes the card; when none is left the card closes,
+ /// with `note` for three seconds if one is given.
+ @MainActor
+ private func removeApproval(id: UUID, answer json: String? = nil, note: String? = nil) {
+ guard let entry = approvals.remove(id: id) else { return }
+ let source = approvalSources.removeValue(forKey: id)
+ if let json {
+ let fd = entry.fd
+ Task.detached { [weak self] in
+ // Write while the fd is still valid, then cancel → the cancel handler closes it.
+ self?.sendLine(fd: fd, text: json)
+ DispatchQueue.main.async { source?.cancel() }
+ }
+ } else {
+ source?.cancel()
+ }
+
+ let state = AppState.shared
+ if !approvals.hasEntries(forPill: entry.pillId) {
+ state.updateTask(id: entry.pillId, state: .working)
+ clearPillBadge(id: entry.pillId)
+ }
+ if approvals.head != nil {
+ showApprovalHead()
+ return
+ }
+ // Last request gone: close the card and give the focus back.
state.pendingApproval = nil
state.isPinned = false
- state.updateTask(id: pillId, state: .working)
- clearPillBadge(id: pillId)
- // Restore focus to the pill that was focused before the approval card appeared.
if let prev = focusBeforeApproval {
focusBeforeApproval = nil
- if state.focusId == pillId, state.tasks.contains(where: { $0.id == prev }) {
+ if state.focusId == entry.pillId, state.tasks.contains(where: { $0.id == prev }) {
withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = prev }
}
}
- state.noteMessage = note
- state.view = .note
- DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
- NotificationCenter.default.post(name: .islandCollapse, object: nil)
+ if let note {
+ state.noteMessage = note
+ state.view = .note
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
+ NotificationCenter.default.post(name: .islandCollapse, object: nil)
+ }
+ } else {
+ state.view = state.tasks.isEmpty ? .empty : .overview
}
}
@@ -419,40 +488,24 @@ final class HookServer: @unchecked Sendable {
if !isExternalAgent { TurnRecorder.shared.record(event: name, payload: payload, pillId: agentId) }
#endif
- // While a permission request is pending, dismiss when the resolving event arrives,
- // then continue normal processing. Only skip normal processing when unresolved.
- if let pending = state.pendingApproval, agentId == pending.pillId,
- pending.sessionId != "demo_session" {
- let handledNote: String
- switch pending.pillId {
- case "agent_cursor": handledNote = "Handled in Cursor."
- case "agent_codex": handledNote = "Handled in Codex."
- case "agent_copilot": handledNote = "Handled in Copilot CLI."
- case "agent_muse": handledNote = "Handled in Muse Code."
- case "agent_hermes": handledNote = "Handled in Hermes."
- default: handledNote = "Handled in \(claudeHostName)."
- }
- var resolved = false
- 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: handledNote)
- resolved = true
- }
- case "Stop", "StopFailure", "UserPromptSubmit", "SessionEnd", "Interrupt":
- // Turn ended or session interrupted — the permission is moot.
- if sessionId == pending.sessionId {
- dismissApprovalCard(note: handledNote)
- resolved = true
- }
- default: break
+ // Waiting permission requests: an event that settles one (its tool finished, or its
+ // turn ended) takes it off the card, then is processed normally.
+ if !approvals.isEmpty {
+ let eventTool = payload["tool_name"] as? String ?? ""
+ let eventKey = Self.approvalInputKey(payload["tool_input"] as? [String: Any] ?? [:])
+ for entry in approvals.resolved(byEvent: name, sessionId: sessionId, pillId: agentId,
+ tool: eventTool, inputKey: eventKey) {
+ removeApproval(id: entry.id, note: handledNote(pill: entry.pillId))
+ }
+ // A session still waiting on a decision is held back (its parallel tool calls
+ // would pull the pill out of its approval state). Other sessions go through.
+ if approvals.entries.contains(where: { $0.pillId == agentId && $0.sessionId == sessionId }) {
+ return
}
- if !resolved { return }
- // Approval dismissed — fall through so the resolving event updates state normally.
+ }
+ // A sibling session's event must not take the pill out of its approval state.
+ defer {
+ if approvals.hasEntries(forPill: agentId) { state.updateTask(id: agentId, state: .approval) }
}
switch name {
@@ -782,19 +835,20 @@ final class HookServer: @unchecked Sendable {
let command = toolInput["command"] as? String ?? 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 = nil
+ // Several requests can wait at once (several sessions or agents): they queue, the
+ // card shows the oldest. Past the cap, the newest goes back to its own terminal.
+ let entry = QueuedApproval(id: UUID(), fd: fd, sessionId: sessionId, pillId: pillId,
+ projectName: projectName, cwd: cwd, tool: tool,
+ command: command, inputKey: inputKey,
+ hostApp: terminalHost?.bundleId, bundleId: bundleId)
+ guard approvals.enqueue(entry) == .accepted else {
+ nbLog("PermissionRequest \(tool): \(ApprovalQueue.maxPending) already waiting, asked in the terminal")
Task.detached { [weak self] in
- // "ask" → nb-hook outputs nothing → Claude Code re-asks
- self?.sendLine(fd: old, text: #"{"permissionDecision":"ask"}"#)
- DispatchQueue.main.async { oldSource?.cancel() }
+ self?.sendLine(fd: fd, text: #"{"permissionDecision":"ask"}"#)
+ close(fd)
}
+ return
}
- pendingApprovalFD = fd
activeSessionId = sessionId
upsertTask(pill: pillId,
@@ -803,65 +857,42 @@ final class HookServer: @unchecked Sendable {
bundleId: bundleId),
working: true, externalAgent: nil)
state.updateTask(id: pillId, state: .approval)
- state.pendingApproval = ApprovalInfo(sessionId: sessionId, tool: tool,
- command: command, inputKey: inputKey, pillId: pillId)
- state.isPinned = true
SoundEngine.shared.play("approval")
- // Approval always forces the island open — user must be able to respond.
- // Save current focus so we can restore it when the card is dismissed.
- if focusBeforeApproval == nil { focusBeforeApproval = state.focusId }
- withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = pillId }
- expandIfNeeded(to: .approval)
-
- // Monitor fd: if the editor closes the connection (handled externally), dismiss the card.
- // The cancel handler closes the fd — never close it anywhere else.
+ // Monitor fd: if the agent closes the connection (answered in its own UI), drop the
+ // request. The cancel handler closes the fd — never close it anywhere else.
+ let entryId = entry.id
let capturedPillId = pillId
let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: .main)
source.setEventHandler { [weak self] in
- guard let self, self.pendingApprovalFD == fd else { return }
- let note: String
- switch capturedPillId {
- case "agent_cursor": note = "Handled in Cursor."
- case "agent_codex": note = "Handled in Codex."
- case "agent_copilot": note = "Handled in Copilot CLI."
- case "agent_muse": note = "Handled in Muse Code."
- case "agent_hermes": note = "Handled in Hermes."
- default: note = "Handled in \(self.claudeHostName)."
- }
- self.dismissApprovalCard(note: note)
+ guard let self, self.approvals.contains(id: entryId) else { return }
+ self.removeApproval(id: entryId, note: self.handledNote(pill: capturedPillId))
}
source.setCancelHandler { close(fd) }
source.resume()
- approvalFDSource = source
+ approvalSources[entryId] = source
- // 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 / Codex re-asks.
+ // Safety timeout — drop without a decision. nb-hook reads EOF from the cancel
+ // handler's close and exits; the agent asks again itself.
// Copilot/Muse use 110s (their relay waits 118s but their hook timeout is 120s, leaving little margin).
let waitTimeout: Double = (isCopilotRequest || isMuseRequest) ? 110 : 115
- let captured = fd
DispatchQueue.main.asyncAfter(deadline: .now() + waitTimeout) { [weak self] in
- guard let self, self.pendingApprovalFD == captured else { return }
- let note: String
- switch capturedPillId {
- case "agent_cursor": note = "Still waiting in Cursor."
- case "agent_codex": note = "Still waiting in Codex."
- case "agent_copilot": note = "Still waiting in Copilot CLI."
- case "agent_muse": note = "Still waiting in Muse Code."
- case "agent_hermes": note = "Still waiting in Hermes."
- default: note = "Still waiting in \(self.claudeHostName)."
- }
- self.dismissApprovalCard(note: note)
+ guard let self, self.approvals.contains(id: entryId) else { return }
+ self.removeApproval(id: entryId, note: self.waitingNote(pill: capturedPillId))
}
+
+ showApprovalHead()
}
- /// Called by ApprovalView buttons. Writes the decision to the waiting nb-hook and cleans up.
+ /// Called by ApprovalView buttons and the iPhone. Writes the decision to the waiting
+ /// nb-hook of request `id` — the one that was on screen. A click that lands after the
+ /// card moved on to another request is ignored, so it can never answer the wrong one.
@MainActor
- func sendApprovalDecision(_ decision: String) {
- // Only intercept a demo card — a real card has a live fd (pendingApprovalFD >= 0).
+ func sendApprovalDecision(_ decision: String, for id: UUID? = nil) {
+ // Only intercept a demo card — a real card has a queued request behind it.
if DemoEngine.shared.isActive,
AppState.shared.pendingApproval?.sessionId == "demo_session",
- pendingApprovalFD < 0 {
+ approvals.isEmpty {
let s = AppState.shared
s.pendingApproval = nil
s.isPinned = false
@@ -869,12 +900,18 @@ final class HookServer: @unchecked Sendable {
DemoEngine.shared.handleApprovalDecision(decision)
return
}
- let fd = pendingApprovalFD
- pendingApprovalFD = -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 = nil
+ guard let head = approvals.head else {
+ // A card with nothing behind it any more: just close it.
+ let s = AppState.shared
+ s.pendingApproval = nil
+ s.isPinned = false
+ s.view = s.tasks.isEmpty ? .empty : .overview
+ return
+ }
+ if let id, id != head.id {
+ nbLog("Approval decision for a request no longer on the card, ignored")
+ return
+ }
let json: String
switch decision {
@@ -883,32 +920,8 @@ final class HookServer: @unchecked Sendable {
case "ask": json = #"{"permissionDecision":"ask"}"#
default: json = #"{"permissionDecision":"deny"}"#
}
-
- if fd >= 0 {
- Task.detached { [weak self] in
- // Write decision while fd is still valid, then cancel source → cancel handler closes fd
- self?.sendLine(fd: fd, text: json)
- DispatchQueue.main.async { source?.cancel() }
- }
- } else {
- source?.cancel()
- }
-
- let state = AppState.shared
- let pillId = state.pendingApproval?.pillId ?? "integration_claude"
- state.pendingApproval = nil
- state.isPinned = false
- RecapStore.shared.recordDecision(pillId: pillId, decision: decision)
- state.updateTask(id: pillId, state: .working)
- clearPillBadge(id: pillId)
- // Restore focus to the pill that was focused before the approval card appeared.
- if let prev = focusBeforeApproval {
- focusBeforeApproval = nil
- if state.focusId == pillId, state.tasks.contains(where: { $0.id == prev }) {
- withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = prev }
- }
- }
- state.view = state.tasks.isEmpty ? .empty : .overview
+ RecapStore.shared.recordDecision(pillId: head.pillId, decision: decision)
+ removeApproval(id: head.id, answer: json)
}
// MARK: - Question request
diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swift
index a0585a17..824d47d6 100644
--- a/NotchBuddy/Sources/App/IslandViewContent.swift
+++ b/NotchBuddy/Sources/App/IslandViewContent.swift
@@ -323,18 +323,37 @@ struct ApprovalView: View {
var approval: ApprovalInfo? { state.pendingApproval }
+ /// The pill, named after the session that asks (several sessions can share a pill).
+ private var asker: AgentTask? {
+ guard var task = state.focusTask else { return nil }
+ if let project = approval?.projectName, !project.isEmpty { task.name = project }
+ return task
+ }
+
var body: some View {
+ // Captured when the card is drawn: a click answers the request that was on screen,
+ // and is ignored if the card has moved on to the next one since.
+ let shownId = approval?.id
ZStack {
CardBackground(wash: .amber)
VStack(alignment: .leading, spacing: 5) {
- AgentWho(task: state.focusTask, label: "needs permission")
+ HStack(spacing: 7) {
+ AgentWho(task: asker, label: "needs permission")
+ // Other requests waiting behind this one: "1/3".
+ if let count = approval?.queueCount, count > 1 {
+ Text(verbatim: "1/\(count)")
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundColor(Color(hex: "#8E939C"))
+ .monospacedDigit()
+ }
+ }
CodeBlock(text: approval?.command ?? approval?.tool ?? "…")
HStack(spacing: 8) {
SecondaryButton("Deny") {
- HookServer.shared.sendApprovalDecision("deny")
+ HookServer.shared.sendApprovalDecision("deny", for: shownId)
}
PrimaryButton("Allow") {
- HookServer.shared.sendApprovalDecision("allow")
+ HookServer.shared.sendApprovalDecision("allow", for: shownId)
}
// Codex, Copilot CLI and Muse Code do not support updatedPermissions
let hideAlways = approval?.pillId == "agent_codex"
@@ -342,7 +361,7 @@ struct ApprovalView: View {
|| approval?.pillId == "agent_muse"
if !hideAlways {
SecondaryButton("Always") {
- HookServer.shared.sendApprovalDecision("always")
+ HookServer.shared.sendApprovalDecision("always", for: shownId)
}
}
}
diff --git a/NotchBuddy/Sources/App/PhoneLink/ApprovalRelay.swift b/NotchBuddy/Sources/App/PhoneLink/ApprovalRelay.swift
index 392cd720..7c49288e 100644
--- a/NotchBuddy/Sources/App/PhoneLink/ApprovalRelay.swift
+++ b/NotchBuddy/Sources/App/PhoneLink/ApprovalRelay.swift
@@ -149,10 +149,10 @@ final class ApprovalRelay {
switch decision {
case "allow":
log("allowed from the iPhone: \(pending.tool)")
- HookServer.shared.sendApprovalDecision("allow")
+ HookServer.shared.sendApprovalDecision("allow", for: pending.id)
case "deny":
log("denied from the iPhone: \(pending.tool)")
- HookServer.shared.sendApprovalDecision("deny")
+ HookServer.shared.sendApprovalDecision("deny", for: pending.id)
default:
log("unknown decision '\(decision)', ignored")
}
diff --git a/NotchBuddy/Sources/CoucouKit/IslandTypes.swift b/NotchBuddy/Sources/CoucouKit/IslandTypes.swift
index 4663eaea..d7c94d08 100644
--- a/NotchBuddy/Sources/CoucouKit/IslandTypes.swift
+++ b/NotchBuddy/Sources/CoucouKit/IslandTypes.swift
@@ -52,6 +52,12 @@ struct ApprovalInfo: Sendable {
var inputKey: String
/// Pill that owns this approval: "integration_claude", "agent_cursor", or "agent_codex".
var pillId: String
+ /// Queued request this card answers (Mac): a decision is only accepted for this id.
+ var id: UUID = UUID()
+ /// Requests waiting, this one included; the card shows the count when above 1.
+ var queueCount: Int = 1
+ /// Project of the session that asks (several sessions can share one pill).
+ var projectName: String = ""
}
// MARK: - Pill badge (shown on pill edge when non-focused task has an alert)
diff --git a/scripts/test-approval-queue.sh b/scripts/test-approval-queue.sh
new file mode 100755
index 00000000..b100510a
--- /dev/null
+++ b/scripts/test-approval-queue.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(dirname "$0")/.."
+TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/coucou-approval-queue.XXXXXX")"
+trap 'rm -rf "$TEST_DIR"' EXIT
+swiftc NotchBuddy/Sources/App/ApprovalQueue.swift \
+ tests/ApprovalQueueTests.swift -o "$TEST_DIR/approval-queue-tests"
+"$TEST_DIR/approval-queue-tests"
diff --git a/tests/ApprovalQueueTests.swift b/tests/ApprovalQueueTests.swift
new file mode 100644
index 00000000..d85d13ef
--- /dev/null
+++ b/tests/ApprovalQueueTests.swift
@@ -0,0 +1,68 @@
+import Foundation
+
+@main
+enum ApprovalQueueTests {
+ static func entry(_ n: Int, session: String = "s1", pill: String = "integration_claude",
+ tool: String = "Bash", key: String = "{}") -> QueuedApproval {
+ QueuedApproval(id: UUID(), fd: Int32(n), sessionId: session, pillId: pill,
+ projectName: "p", cwd: "/", tool: tool, command: "cmd\(n)", inputKey: key)
+ }
+
+ static func main() {
+ // FIFO: head is the oldest, removal of the head promotes the next
+ var q = ApprovalQueue()
+ let a = entry(1), b = entry(2), c = entry(3)
+ for e in [a, b, c] { precondition(q.enqueue(e) == .accepted) }
+ precondition(q.count == 3 && q.head == a)
+ precondition(q.position(of: a.id) == 1 && q.position(of: c.id) == 3)
+ precondition(q.remove(id: a.id) == a)
+ precondition(q.head == b && q.count == 2)
+
+ // Removal on disconnect / timeout of a non-head entry leaves the others untouched
+ precondition(q.remove(id: c.id) == c)
+ precondition(q.head == b && q.count == 1)
+ precondition(q.remove(id: c.id) == nil) // already gone: no-op
+ precondition(q.remove(id: b.id) == b && q.isEmpty && q.head == nil)
+
+ // Cap: the newest is rejected, queue unchanged
+ var full = ApprovalQueue()
+ let all = (1...ApprovalQueue.maxPending).map { entry($0) }
+ for e in all { precondition(full.enqueue(e) == .accepted) }
+ precondition(full.enqueue(entry(99)) == .rejectedFull)
+ precondition(full.entries == all)
+ // Room again after a removal
+ _ = full.remove(id: all[0].id)
+ precondition(full.enqueue(entry(97), maxPending: ApprovalQueue.maxPending) == .accepted)
+
+ // Event matching is per request: session + agent, never the pill alone
+ var m = ApprovalQueue()
+ let s1 = entry(1, session: "s1", tool: "Bash", key: "{\"command\":\"ls\"}")
+ let s2 = entry(2, session: "s2", tool: "Bash", key: "{\"command\":\"ls\"}")
+ let cur = entry(3, session: "s1", pill: "agent_cursor", tool: "Bash", key: "{\"command\":\"ls\"}")
+ for e in [s1, s2, cur] { _ = m.enqueue(e) }
+ let pt = m.resolved(byEvent: "PostToolUse", sessionId: "s1", pillId: "integration_claude",
+ tool: "Bash", inputKey: "{\"command\":\"ls\"}")
+ precondition(pt == [s1])
+ precondition(m.resolved(byEvent: "PostToolUse", sessionId: "s1", pillId: "integration_claude",
+ tool: "Bash", inputKey: "{\"command\":\"pwd\"}").isEmpty)
+ precondition(m.resolved(byEvent: "PostToolUse", sessionId: "s1", pillId: "integration_claude",
+ tool: "Read", inputKey: "{\"command\":\"ls\"}").isEmpty)
+ precondition(m.resolved(byEvent: "Stop", sessionId: "s2", pillId: "integration_claude",
+ tool: "", inputKey: "") == [s2])
+ precondition(m.resolved(byEvent: "Stop", sessionId: "s1", pillId: "agent_cursor",
+ tool: "", inputKey: "") == [cur])
+ precondition(m.resolved(byEvent: "Stop", sessionId: "other", pillId: "integration_claude",
+ tool: "", inputKey: "").isEmpty)
+ precondition(m.resolved(byEvent: "PreToolUse", sessionId: "s1", pillId: "integration_claude",
+ tool: "Bash", inputKey: "{\"command\":\"ls\"}").isEmpty)
+
+ // Mixed sources and per-pill lookup
+ precondition(m.hasMixedSources)
+ precondition(m.hasEntries(forPill: "agent_cursor") && !m.hasEntries(forPill: "agent_codex"))
+ var same = ApprovalQueue()
+ _ = same.enqueue(entry(1)); _ = same.enqueue(entry(2, tool: "Edit"))
+ precondition(!same.hasMixedSources)
+
+ print("pass")
+ }
+}