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:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user