Permission requests queue up instead of pushing each other away (upstream #563)
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 <noreply@anthropic.com>
This commit is contained in:
@@ -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 []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -38,8 +38,12 @@ final class HookServer: @unchecked Sendable {
|
|||||||
private var serverFD: Int32 = -1
|
private var serverFD: Int32 = -1
|
||||||
private let connectionLock = NSLock()
|
private let connectionLock = NSLock()
|
||||||
private var connectionCount = 0
|
private var connectionCount = 0
|
||||||
private var pendingApprovalFD: Int32 = -1 // held open while user decides
|
/// Permission requests waiting for a click, oldest first; the head is on the card.
|
||||||
private var approvalFDSource: (any DispatchSourceRead)? = nil // monitors pendingApprovalFD
|
/// 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 pendingQuestionFD: Int32 = -1 // held open while user answers AskUserQuestion
|
||||||
private var questionFDSource: (any DispatchSourceRead)? = nil // monitors pendingQuestionFD
|
private var questionFDSource: (any DispatchSourceRead)? = nil // monitors pendingQuestionFD
|
||||||
private var questionPillId: String = "" // pill that owns the pending question
|
private var questionPillId: String = "" // pill that owns the pending question
|
||||||
@@ -50,40 +54,100 @@ final class HookServer: @unchecked Sendable {
|
|||||||
|
|
||||||
private init() {}
|
private init() {}
|
||||||
|
|
||||||
// MARK: - Approval fd helpers
|
// MARK: - Approval queue helpers (upstream #563)
|
||||||
|
|
||||||
|
/// Note shown when a request was answered outside BroV.
|
||||||
@MainActor
|
@MainActor
|
||||||
private func cancelApprovalFDSource() {
|
private func handledNote(pill: String) -> String {
|
||||||
approvalFDSource?.cancel()
|
switch pill {
|
||||||
approvalFDSource = nil
|
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
|
/// Note shown when a request waited too long and went back to the agent.
|
||||||
/// 3-second note, clears approval state, then collapses the island.
|
|
||||||
@MainActor
|
@MainActor
|
||||||
private func dismissApprovalCard(note: String) {
|
private func waitingNote(pill: String) -> String {
|
||||||
// cancelApprovalFDSource() triggers the cancel handler which closes the fd.
|
switch pill {
|
||||||
// Never close the fd here directly — Apple requires it to happen in the cancel handler.
|
case "agent_cursor": return "Всё ещё ждёт в Cursor."
|
||||||
cancelApprovalFDSource()
|
case "agent_codex": return "Всё ещё ждёт в Codex."
|
||||||
pendingApprovalFD = -1
|
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 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.pendingApproval = nil
|
||||||
state.isPinned = false
|
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 {
|
if let prev = focusBeforeApproval {
|
||||||
focusBeforeApproval = nil
|
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 }
|
withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = prev }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if let note {
|
||||||
state.noteMessage = note
|
state.noteMessage = note
|
||||||
state.view = .note
|
state.view = .note
|
||||||
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
|
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
|
||||||
NotificationCenter.default.post(name: .islandCollapse, object: nil)
|
NotificationCenter.default.post(name: .islandCollapse, object: nil)
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
state.view = state.tasks.isEmpty ? .empty : .overview
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Question fd helpers
|
// MARK: - Question fd helpers
|
||||||
@@ -390,36 +454,24 @@ final class HookServer: @unchecked Sendable {
|
|||||||
if !isExternalAgent { TurnRecorder.shared.record(event: name, payload: payload, pillId: agentId) }
|
if !isExternalAgent { TurnRecorder.shared.record(event: name, payload: payload, pillId: agentId) }
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// While a permission request is pending, dismiss when the resolving event arrives,
|
// Waiting permission requests: an event that settles one (its tool finished, or its
|
||||||
// then continue normal processing. Only skip normal processing when unresolved.
|
// turn ended) takes it off the card, then is processed normally.
|
||||||
if let pending = state.pendingApproval, agentId == pending.pillId {
|
if !approvals.isEmpty {
|
||||||
let handledNote: String
|
let eventTool = payload["tool_name"] as? String ?? ""
|
||||||
switch pending.pillId {
|
let eventKey = Self.approvalInputKey(payload["tool_input"] as? [String: Any] ?? [:])
|
||||||
case "agent_cursor": handledNote = "Решено в Cursor."
|
for entry in approvals.resolved(byEvent: name, sessionId: sessionId, pillId: agentId,
|
||||||
case "agent_codex": handledNote = "Решено в Codex."
|
tool: eventTool, inputKey: eventKey) {
|
||||||
default: handledNote = "Решено в VS Code."
|
removeApproval(id: entry.id, note: handledNote(pill: entry.pillId))
|
||||||
}
|
}
|
||||||
var resolved = false
|
// A session still waiting on a decision is held back (its parallel tool calls
|
||||||
switch name {
|
// would pull the pill out of its approval state). Other sessions go through.
|
||||||
case "PostToolUse", "PostToolUseFailure":
|
if approvals.entries.contains(where: { $0.pillId == agentId && $0.sessionId == sessionId }) {
|
||||||
// Only dismiss when this exact tool call finished — same session, tool and input.
|
return
|
||||||
// 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 sibling session's event must not take the pill out of its approval state.
|
||||||
}
|
defer {
|
||||||
if !resolved { return }
|
if approvals.hasEntries(forPill: agentId) { state.updateTask(id: agentId, state: .approval) }
|
||||||
// Approval dismissed — fall through so the resolving event updates state normally.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// BroV: crash watch + login status.
|
// BroV: crash watch + login status.
|
||||||
@@ -745,82 +797,68 @@ final class HookServer: @unchecked Sendable {
|
|||||||
let command = DangerCheck.describe(tool: tool, input: toolInput)
|
let command = DangerCheck.describe(tool: tool, input: toolInput)
|
||||||
let danger = DangerCheck.reasons(tool: tool, input: toolInput)
|
let danger = DangerCheck.reasons(tool: tool, input: toolInput)
|
||||||
|
|
||||||
if pendingApprovalFD >= 0 {
|
// Several requests can wait at once (several sessions or agents): they queue, the
|
||||||
// Displace the previous request: write "ask" then cancel its source.
|
// card shows the oldest. Past the cap, the newest goes back to its own terminal.
|
||||||
// The cancel handler closes the old fd — never close it directly.
|
let entry = QueuedApproval(id: UUID(), fd: fd, sessionId: sessionId, pillId: pillId,
|
||||||
let old = pendingApprovalFD
|
projectName: projectName, cwd: cwd, tool: tool,
|
||||||
let oldSource = approvalFDSource
|
command: command, inputKey: inputKey, danger: danger)
|
||||||
approvalFDSource = nil
|
guard approvals.enqueue(entry) == .accepted else {
|
||||||
|
nbLog("PermissionRequest \(tool): \(ApprovalQueue.maxPending) already waiting, asked in the terminal")
|
||||||
Task.detached { [weak self] in
|
Task.detached { [weak self] in
|
||||||
// "ask" → nb-hook outputs nothing → Claude Code re-asks
|
self?.sendLine(fd: fd, text: #"{"permissionDecision":"ask"}"#)
|
||||||
self?.sendLine(fd: old, text: #"{"permissionDecision":"ask"}"#)
|
close(fd)
|
||||||
DispatchQueue.main.async { oldSource?.cancel() }
|
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
pendingApprovalFD = fd
|
|
||||||
activeSessionId = sessionId
|
activeSessionId = sessionId
|
||||||
|
|
||||||
upsertTask(pill: pillId,
|
upsertTask(pill: pillId,
|
||||||
display: PillSessionRegistry.Display(session: sessionId, projectName: projectName, cwd: cwd),
|
display: PillSessionRegistry.Display(session: sessionId, projectName: projectName, cwd: cwd),
|
||||||
working: true, externalAgent: nil)
|
working: true, externalAgent: nil)
|
||||||
state.updateTask(id: pillId, state: .approval)
|
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")
|
SoundEngine.shared.play("approval")
|
||||||
|
|
||||||
// Approval always forces the island open — user must be able to respond.
|
// Monitor fd: if the agent closes the connection (answered in its own UI), drop the
|
||||||
// Save current focus so we can restore it when the card is dismissed.
|
// request. The cancel handler closes the fd — never close it anywhere else.
|
||||||
if focusBeforeApproval == nil { focusBeforeApproval = state.focusId }
|
let entryId = entry.id
|
||||||
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.
|
|
||||||
let capturedPillId = pillId
|
let capturedPillId = pillId
|
||||||
let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: .main)
|
let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: .main)
|
||||||
source.setEventHandler { [weak self] in
|
source.setEventHandler { [weak self] in
|
||||||
guard let self, self.pendingApprovalFD == fd else { return }
|
guard let self, self.approvals.contains(id: entryId) else { return }
|
||||||
let note: String
|
self.removeApproval(id: entryId, note: self.handledNote(pill: capturedPillId))
|
||||||
switch capturedPillId {
|
|
||||||
case "agent_cursor": note = "Решено в Cursor."
|
|
||||||
case "agent_codex": note = "Решено в Codex."
|
|
||||||
default: note = "Решено в VS Code."
|
|
||||||
}
|
|
||||||
self.dismissApprovalCard(note: note)
|
|
||||||
}
|
}
|
||||||
source.setCancelHandler { close(fd) }
|
source.setCancelHandler { close(fd) }
|
||||||
source.resume()
|
source.resume()
|
||||||
approvalFDSource = source
|
approvalSources[entryId] = source
|
||||||
|
|
||||||
// 115s safety timeout — show a note and cancel without sending a decision.
|
// 115 s safety timeout per request — drop without a decision. nb-hook reads EOF from
|
||||||
// nb-hook reads EOF from the cancel handler's close and exits; Claude Code / Codex re-asks.
|
// the cancel handler's close and exits; the agent asks again itself.
|
||||||
let captured = fd
|
|
||||||
DispatchQueue.main.asyncAfter(deadline: .now() + 115) { [weak self] in
|
DispatchQueue.main.asyncAfter(deadline: .now() + 115) { [weak self] in
|
||||||
guard let self, self.pendingApprovalFD == captured else { return }
|
guard let self, self.approvals.contains(id: entryId) else { return }
|
||||||
let note: String
|
self.removeApproval(id: entryId, note: self.waitingNote(pill: capturedPillId))
|
||||||
switch capturedPillId {
|
|
||||||
case "agent_cursor": note = "Всё ещё ждёт в Cursor."
|
|
||||||
case "agent_codex": note = "Всё ещё ждёт в Codex."
|
|
||||||
default: note = "Всё ещё ждёт в VS Code."
|
|
||||||
}
|
|
||||||
self.dismissApprovalCard(note: note)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Called by ApprovalView buttons. Writes the decision to the waiting nb-hook and cleans up.
|
showApprovalHead()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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
|
@MainActor
|
||||||
func sendApprovalDecision(_ decision: String) {
|
func sendApprovalDecision(_ decision: String, for id: UUID? = nil) {
|
||||||
Haptic.tap()
|
Haptic.tap()
|
||||||
let fd = pendingApprovalFD
|
guard let head = approvals.head else {
|
||||||
pendingApprovalFD = -1
|
// A card with nothing behind it any more: just close it.
|
||||||
// Capture source before nulling — we send the decision first, then cancel the source.
|
let s = AppState.shared
|
||||||
// The cancel handler closes the fd; never close it directly.
|
s.pendingApproval = nil
|
||||||
let source = approvalFDSource
|
s.isPinned = false
|
||||||
approvalFDSource = nil
|
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
|
let json: String
|
||||||
switch decision {
|
switch decision {
|
||||||
case "allow": json = #"{"permissionDecision":"allow"}"#
|
case "allow": json = #"{"permissionDecision":"allow"}"#
|
||||||
@@ -828,31 +866,7 @@ final class HookServer: @unchecked Sendable {
|
|||||||
case "ask": json = #"{"permissionDecision":"ask"}"#
|
case "ask": json = #"{"permissionDecision":"ask"}"#
|
||||||
default: json = #"{"permissionDecision":"deny"}"#
|
default: json = #"{"permissionDecision":"deny"}"#
|
||||||
}
|
}
|
||||||
|
removeApproval(id: head.id, answer: json)
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Question request
|
// MARK: - Question request
|
||||||
|
|||||||
@@ -298,12 +298,32 @@ struct ApprovalView: View {
|
|||||||
|
|
||||||
var approval: ApprovalInfo? { state.pendingApproval }
|
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 {
|
var body: some View {
|
||||||
let danger = approval?.danger ?? []
|
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 {
|
ZStack {
|
||||||
CardBackground(wash: danger.isEmpty ? .amber : .red)
|
CardBackground(wash: danger.isEmpty ? .amber : .red)
|
||||||
VStack(alignment: .leading, spacing: 5) {
|
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 ?? "…")
|
CodeBlock(text: approval?.command ?? approval?.tool ?? "…")
|
||||||
if !danger.isEmpty {
|
if !danger.isEmpty {
|
||||||
HStack(alignment: .top, spacing: 5) {
|
HStack(alignment: .top, spacing: 5) {
|
||||||
@@ -320,16 +340,16 @@ struct ApprovalView: View {
|
|||||||
}
|
}
|
||||||
HStack(spacing: 8) {
|
HStack(spacing: 8) {
|
||||||
SecondaryButton("Запретить") {
|
SecondaryButton("Запретить") {
|
||||||
HookServer.shared.sendApprovalDecision("deny")
|
HookServer.shared.sendApprovalDecision("deny", for: shownId)
|
||||||
}
|
}
|
||||||
PrimaryButton("Разрешить") {
|
PrimaryButton("Разрешить") {
|
||||||
HookServer.shared.sendApprovalDecision("allow")
|
HookServer.shared.sendApprovalDecision("allow", for: shownId)
|
||||||
}
|
}
|
||||||
// Codex rejects updatedPermissions, so "Always" is not offered.
|
// Codex rejects updatedPermissions, so "Always" is not offered.
|
||||||
// Never for a dangerous command: one click must not save a destructive rule.
|
// Never for a dangerous command: one click must not save a destructive rule.
|
||||||
if approval?.pillId != "agent_codex" && danger.isEmpty {
|
if approval?.pillId != "agent_codex" && danger.isEmpty {
|
||||||
SecondaryButton("Всегда") {
|
SecondaryButton("Всегда") {
|
||||||
HookServer.shared.sendApprovalDecision("always")
|
HookServer.shared.sendApprovalDecision("always", for: shownId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -147,10 +147,10 @@ final class ApprovalRelay {
|
|||||||
switch decision {
|
switch decision {
|
||||||
case "allow":
|
case "allow":
|
||||||
log("allowed from the iPhone: \(pending.tool)")
|
log("allowed from the iPhone: \(pending.tool)")
|
||||||
HookServer.shared.sendApprovalDecision("allow")
|
HookServer.shared.sendApprovalDecision("allow", for: pending.id)
|
||||||
case "deny":
|
case "deny":
|
||||||
log("denied from the iPhone: \(pending.tool)")
|
log("denied from the iPhone: \(pending.tool)")
|
||||||
HookServer.shared.sendApprovalDecision("deny")
|
HookServer.shared.sendApprovalDecision("deny", for: pending.id)
|
||||||
default:
|
default:
|
||||||
log("unknown decision '\(decision)', ignored")
|
log("unknown decision '\(decision)', ignored")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,12 @@ struct ApprovalInfo: Sendable {
|
|||||||
var pillId: String
|
var pillId: String
|
||||||
/// Why this request looks destructive (DangerCheck), empty when nothing matched.
|
/// Why this request looks destructive (DangerCheck), empty when nothing matched.
|
||||||
var danger: [String] = []
|
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)
|
// MARK: - Pill badge (shown on pill edge when non-focused task has an alert)
|
||||||
|
|||||||
Executable
+8
@@ -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"
|
||||||
@@ -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")
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user