From 0199e9a7f02ff31c9a71afb543a09a63c5163ef3 Mon Sep 17 00:00:00 2001 From: maksarsanjeev Date: Wed, 14 Oct 2026 00:18:34 +0300 Subject: [PATCH] Permission requests queue up instead of pushing each other away (upstream #563) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ApprovalQueue (upstream e391a14, after #157 by @Mydao57): up to 5 requests wait in line, the card shows the oldest with «1/N» and the project of the asking session; a click answers the request that was on screen and is ignored if the card moved on. Each request keeps its own hang-up monitor and 115 s timeout and is settled by its own session's events; a sibling session's events are no longer dropped while one waits. BroV keeps its DangerCheck warning per request and the iPhone relay answers the request it was shown. Upstream tests pass: bash scripts/test-approval-queue.sh. Co-Authored-By: Mydao57 <150259698+Mydao57@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- NotchBuddy/Sources/App/ApprovalQueue.swift | 89 ++++++ NotchBuddy/Sources/App/HookServer.swift | 268 +++++++++--------- .../Sources/App/IslandViewContent.swift | 28 +- .../Sources/App/PhoneLink/ApprovalRelay.swift | 4 +- .../Sources/CoucouKit/IslandTypes.swift | 6 + scripts/test-approval-queue.sh | 8 + tests/ApprovalQueueTests.swift | 68 +++++ 7 files changed, 338 insertions(+), 133 deletions(-) create mode 100644 NotchBuddy/Sources/App/ApprovalQueue.swift create mode 100755 scripts/test-approval-queue.sh create mode 100644 tests/ApprovalQueueTests.swift diff --git a/NotchBuddy/Sources/App/ApprovalQueue.swift b/NotchBuddy/Sources/App/ApprovalQueue.swift new file mode 100644 index 0000000..05f9d77 --- /dev/null +++ b/NotchBuddy/Sources/App/ApprovalQueue.swift @@ -0,0 +1,89 @@ +import Foundation + +// MARK: - ApprovalQueue +// +// From upstream Coucou e391a14 (#563, after #157 by @Mydao57), MIT. BroV adds `danger`. +// 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 = "" + /// BroV: why this request looks destructive (DangerCheck), empty when nothing matched. + var danger: [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 970a3fc..0828226 100644 --- a/NotchBuddy/Sources/App/HookServer.swift +++ b/NotchBuddy/Sources/App/HookServer.swift @@ -38,8 +38,12 @@ 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 (upstream #563). + 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 private var questionPillId: String = "" // pill that owns the pending question @@ -50,39 +54,99 @@ final class HookServer: @unchecked Sendable { private init() {} - // MARK: - Approval fd helpers + // MARK: - Approval queue helpers (upstream #563) + /// Note shown when a request was answered outside BroV. @MainActor - private func cancelApprovalFDSource() { - approvalFDSource?.cancel() - approvalFDSource = nil + private func handledNote(pill: String) -> String { + switch pill { + case "agent_cursor": return "Решено в Cursor." + case "agent_codex": return "Решено в Codex." + default: return "Решено в VS Code." + } } - /// 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. + /// Note shown when a request waited too long and went back to the agent. @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 waitingNote(pill: String) -> String { + switch pill { + case "agent_cursor": return "Всё ещё ждёт в Cursor." + case "agent_codex": return "Всё ещё ждёт в Codex." + default: return "Всё ещё ждёт в VS Code." + } + } + + /// 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 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, danger: head.danger, id: head.id, + queueCount: approvals.count, + projectName: head.projectName) + if !head.danger.isEmpty { NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.surprised) } + 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 } } @@ -390,36 +454,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 { - let handledNote: String - switch pending.pillId { - case "agent_cursor": handledNote = "Решено в Cursor." - case "agent_codex": handledNote = "Решено в Codex." - default: handledNote = "Решено в VS Code." + // 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)) } - 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 + // 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) } } // BroV: crash watch + login status. @@ -745,82 +797,68 @@ final class HookServer: @unchecked Sendable { let command = DangerCheck.describe(tool: tool, input: toolInput) let danger = DangerCheck.reasons(tool: tool, input: toolInput) - 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, danger: danger) + 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, display: PillSessionRegistry.Display(session: sessionId, projectName: projectName, cwd: cwd), working: true, externalAgent: nil) state.updateTask(id: pillId, state: .approval) - state.pendingApproval = ApprovalInfo(sessionId: sessionId, tool: tool, - command: command, inputKey: inputKey, pillId: pillId, - danger: danger) - if !danger.isEmpty { NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.surprised) } - 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 = "Решено в Cursor." - case "agent_codex": note = "Решено в Codex." - default: note = "Решено в VS Code." - } - 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 - // 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 / Codex re-asks. - let captured = fd + // 115 s safety timeout per request — drop without a decision. nb-hook reads EOF from + // the cancel handler's close and exits; the agent asks again itself. DispatchQueue.main.asyncAfter(deadline: .now() + 115) { [weak self] in - guard let self, self.pendingApprovalFD == captured else { return } - let note: String - switch capturedPillId { - case "agent_cursor": note = "Всё ещё ждёт в Cursor." - case "agent_codex": note = "Всё ещё ждёт в Codex." - default: note = "Всё ещё ждёт в VS Code." - } - 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) { + func sendApprovalDecision(_ decision: String, for id: UUID? = nil) { Haptic.tap() - 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 { case "allow": json = #"{"permissionDecision":"allow"}"# @@ -828,31 +866,7 @@ 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 - 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 + removeApproval(id: head.id, answer: json) } // MARK: - Question request diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swift index 42535d1..f36425e 100644 --- a/NotchBuddy/Sources/App/IslandViewContent.swift +++ b/NotchBuddy/Sources/App/IslandViewContent.swift @@ -298,12 +298,32 @@ 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 { let danger = approval?.danger ?? [] + // 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: danger.isEmpty ? .amber : .red) VStack(alignment: .leading, spacing: 5) { - AgentWho(task: state.focusTask, label: "просит разрешение") + HStack(spacing: 7) { + AgentWho(task: asker, label: "просит разрешение") + // 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() + .help("Ещё \(count - 1) ждут в очереди") + } + } CodeBlock(text: approval?.command ?? approval?.tool ?? "…") if !danger.isEmpty { HStack(alignment: .top, spacing: 5) { @@ -320,16 +340,16 @@ struct ApprovalView: View { } HStack(spacing: 8) { SecondaryButton("Запретить") { - HookServer.shared.sendApprovalDecision("deny") + HookServer.shared.sendApprovalDecision("deny", for: shownId) } PrimaryButton("Разрешить") { - HookServer.shared.sendApprovalDecision("allow") + HookServer.shared.sendApprovalDecision("allow", for: shownId) } // Codex rejects updatedPermissions, so "Always" is not offered. // Never for a dangerous command: one click must not save a destructive rule. if approval?.pillId != "agent_codex" && danger.isEmpty { SecondaryButton("Всегда") { - 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 0f52846..c4df2ab 100644 --- a/NotchBuddy/Sources/App/PhoneLink/ApprovalRelay.swift +++ b/NotchBuddy/Sources/App/PhoneLink/ApprovalRelay.swift @@ -147,10 +147,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 7c0dc20..166343c 100644 --- a/NotchBuddy/Sources/CoucouKit/IslandTypes.swift +++ b/NotchBuddy/Sources/CoucouKit/IslandTypes.swift @@ -41,6 +41,12 @@ struct ApprovalInfo: Sendable { var pillId: String /// Why this request looks destructive (DangerCheck), empty when nothing matched. var danger: [String] = [] + /// Queued request this card answers: 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 0000000..b100510 --- /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 0000000..d85d13e --- /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") + } +}