Compare commits

...

4 Commits

Author SHA1 Message Date
maksarsanjeev 7c4e9abc46 Dictation in the chat (upstream #334, #353, 3b0e987)
MacDictation: on-device speech recognition when available; «Automatic» listens with up to
three recognizers in the user's languages (macOS languages, keyboard layouts, English) and
keeps the most confident transcript; a fixed language from the mic's right-click menu.
🎤 next to the chat input; sending while dictating takes the final words first.
Hardened runtime gets com.apple.security.device.audio-input; Info.plist gets the
microphone and speech-recognition usage strings (in Russian).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 00:20:21 +03:00
maksarsanjeev 0199e9a7f0 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>
2026-10-14 00:18:34 +03:00
maksarsanjeev c0447ca327 Several Claude Code sessions on one pill no longer clobber each other (upstream #562)
PillSessionRegistry (upstream 5652ea8, after #245 by @TheodoreRiant) tracks the live
sessions behind each pill: only the last session takes the card and its diffs down, a
Stop finishes the pill only when no sibling is mid-turn, the 5.2 s idle reset is skipped
when a new turn started, and the oldest live session owns the name and folder (passed on
when it ends). Upstream tests pass on our copy: bash scripts/test-session-registry.sh.

Co-Authored-By: TheodoreRiant <57949703+TheodoreRiant@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 00:16:01 +03:00
maksarsanjeev 08949d136c Memoji follows every mouse move (from upstream b5b04c2)
The look target came from the island poll (10–30 Hz), so the head turned in steps;
mouse-moved monitors now update it on every move. The upstream step-debt frame clock fix
(956413f) doesn't apply: BroV never had that clock, its engine steps by real elapsed time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 00:13:48 +03:00
15 changed files with 1188 additions and 145 deletions
+3
View File
@@ -5,5 +5,8 @@
<!-- Hardened runtime: BroV drives Terminal, Music and Mail through Apple Events. -->
<key>com.apple.security.automation.apple-events</key>
<true/>
<!-- Hardened runtime: the mic in the chat (dictation). -->
<key>com.apple.security.device.audio-input</key>
<true/>
</dict>
</plist>
+4
View File
@@ -33,6 +33,10 @@
<string>BroV jumps to your terminal, sends mail and controls Music.</string>
<key>NSHighResolutionCapable</key>
<true/>
<key>NSMicrophoneUsageDescription</key>
<string>BroV слушает микрофон, когда ты диктуешь сообщение в чат.</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>BroV превращает твой голос в текст сообщения в чате.</string>
<key>NSSupportsAutomaticGraphicsSwitching</key>
<true/>
</dict>
@@ -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 []
}
}
}
+216 -139
View File
@@ -38,50 +38,115 @@ 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
private var focusBeforeQuestion: String? = nil // saved focus to restore after question
private var activeSessionId: String? = nil // current Claude Code session
private var focusBeforeApproval: String? = nil // saved focus to restore after approval
private var sessions = PillSessionRegistry() // live sessions behind each pill (upstream #562)
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
}
}
@@ -376,42 +441,37 @@ final class HookServer: @unchecked Sendable {
}
let focused = state.focusId == agentId
// Several sessions can share one pill (it is chosen from the client, not from the
// session). The registry tells a turn-ending event whether it may touch the pill,
// and which session owns the project name shown on it.
let display = PillSessionRegistry.Display(
session: sessionId,
projectName: isExternalAgent ? (validAgent ?? projectName) : projectName,
cwd: isExternalAgent ? "" : cwd)
#if PHONE_LINK
// The iPhone's "last turn" (prompt, actions, diffs, answer).
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.
@@ -432,7 +492,8 @@ final class HookServer: @unchecked Sendable {
case "SessionStart":
activeSessionId = sessionId
if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd) }
upsertTask(pill: agentId, display: display, working: false,
externalAgent: isExternalAgent ? validAgent : nil)
if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
nbLog("SessionStart \(isExternalAgent ? agentId : projectName) (\(sessionId.prefix(8)))")
if state.isPresent { expandIfNeeded(to: .overview) }
@@ -440,7 +501,8 @@ final class HookServer: @unchecked Sendable {
case "UserPromptSubmit":
activeSessionId = sessionId
if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd) }
upsertTask(pill: agentId, display: display, working: true,
externalAgent: isExternalAgent ? validAgent : nil)
if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
state.updateTask(id: agentId, state: .thinking)
if let prompt = payload["prompt"] as? String, !prompt.isEmpty {
@@ -455,7 +517,8 @@ final class HookServer: @unchecked Sendable {
// AskUserQuestion is handled via the dedicated --ask hook.
// Skip state/step update here to avoid flickering over the question card.
guard tool != "AskUserQuestion" else { break }
if isExternalAgent { upsertExternalAgent(id: agentId, name: validAgent!) } else { upsertWorkspaceTask(id: agentId, projectName: projectName, cwd: cwd) }
upsertTask(pill: agentId, display: display, working: true,
externalAgent: isExternalAgent ? validAgent : nil)
state.updateTask(id: agentId, state: .working)
let input = payload["tool_input"] as? [String: Any] ?? [:]
let step = frenchStep(tool: tool, input: input)
@@ -463,6 +526,7 @@ final class HookServer: @unchecked Sendable {
nbLog("PreToolUse \(tool)")
case "PostToolUse":
sessions.note(pill: agentId, display: display, working: true)
state.updateTask(id: agentId, state: .working)
// Live diff for Edit / MultiEdit / Write
let diffTool = payload["tool_name"] as? String ?? ""
@@ -474,10 +538,12 @@ final class HookServer: @unchecked Sendable {
}
case "PostToolUseFailure":
sessions.note(pill: agentId, display: display, working: true)
state.updateTask(id: agentId, state: .working)
appendStep(id: agentId, step: "⚠ ошибка")
case "Notification":
sessions.note(pill: agentId, display: display, working: false)
let message = payload["message"] as? String ?? ""
let lower = message.lowercased()
if lower.contains("rate limit") || lower.contains("limite d") {
@@ -489,15 +555,21 @@ final class HookServer: @unchecked Sendable {
}
case "Stop":
state.updateTask(id: agentId, state: .finished)
let scope = sessions.endTurn(pill: agentId, session: sessionId)
let rawFinal = (payload["last_assistant_message"] as? String)
?? (payload["message"] as? String) ?? ""
let finalText = DiffEngine.toOneLine(rawFinal)
if !finalText.isEmpty {
appendStep(id: agentId, step: finalText)
if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) {
state.tasks[idx].finalLine = finalText
}
// The step log is shared, so the conclusion is worth showing either way.
if !finalText.isEmpty { appendStep(id: agentId, step: finalText) }
// Another session is still mid-turn behind this pill: the finished state, the
// sound and the idle reset below would land on its work. Its own Stop comes later.
guard scope == .pill else {
nbLog("Stop \(sessionId.prefix(8)) — \(sessions.workingCount(pill: agentId)) session(s) still working on \(agentId)")
break
}
state.updateTask(id: agentId, state: .finished)
if !finalText.isEmpty, let idx = state.tasks.firstIndex(where: { $0.id == agentId }) {
state.tasks[idx].finalLine = finalText
}
SoundEngine.shared.play("finish")
if focused {
@@ -506,6 +578,8 @@ final class HookServer: @unchecked Sendable {
setPillBadge(id: agentId, badge: .finished)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5.2) {
// A session (this one or a sibling) may have started a new turn meanwhile.
guard self.sessions.workingCount(pill: agentId) == 0 else { return }
if isExternalAgent {
AppState.shared.removeTask(id: agentId)
} else {
@@ -515,6 +589,7 @@ final class HookServer: @unchecked Sendable {
}
case "StopFailure":
guard sessions.endTurn(pill: agentId, session: sessionId) == .pill else { break }
state.updateTask(id: agentId, state: .error)
SoundEngine.shared.play("error")
if focused {
@@ -525,11 +600,18 @@ final class HookServer: @unchecked Sendable {
case "Interrupt":
// Codex: user stopped the turn
guard sessions.endTurn(pill: agentId, session: sessionId) == .pill else { break }
activeSessionId = nil
state.updateTask(id: agentId, state: .idle)
clearPillBadge(id: agentId)
case "SessionEnd":
// Only the last session behind the pill may take the card and its diffs down.
guard sessions.endSession(pill: agentId, session: sessionId) == .pill else {
nbLog("SessionEnd \(sessionId.prefix(8)) — \(sessions.liveCount(pill: agentId)) session(s) left on \(agentId)")
applyDisplayOwner(pill: agentId)
break
}
activeSessionId = nil
if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
state.clearSessionDiffs(for: agentId)
@@ -566,6 +648,32 @@ final class HookServer: @unchecked Sendable {
/// Creates a dynamic pill for a third-party agent on first event, then no-ops.
/// ID format: "agent_<name>" — never collides with "integration_*" pills.
/// Inserted right after integration_claude so it appears in the visible prefix(4).
/// Records the session an event came from, then refreshes its card. `externalAgent`
/// is the validated `coucou_agent` name for a third-party agent pill, nil for a
/// workspace pill.
@MainActor
private func upsertTask(pill: String, display: PillSessionRegistry.Display,
working: Bool, externalAgent: String?) {
sessions.note(pill: pill, display: display, working: working)
if let externalAgent {
upsertExternalAgent(id: pill, name: externalAgent)
} else {
upsertWorkspaceTask(id: pill, projectName: display.projectName, cwd: display.cwd,
session: display.session)
}
}
/// Writes the pill's name and cwd from the session that owns it: used when the owner
/// ends and a sibling session inherits the card.
@MainActor
private func applyDisplayOwner(pill: String) {
guard let owner = sessions.displayOwner(of: pill),
let idx = AppState.shared.tasks.firstIndex(where: { $0.id == pill }),
!owner.projectName.isEmpty else { return }
AppState.shared.tasks[idx].name = owner.projectName
if !owner.cwd.isEmpty { AppState.shared.tasks[idx].sessionCwd = owner.cwd }
}
@MainActor
private func upsertExternalAgent(id: String, name: String) {
let state = AppState.shared
@@ -689,80 +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
upsertWorkspaceTask(id: pillId, projectName: projectName, cwd: cwd)
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"}"#
@@ -770,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
@@ -851,7 +923,9 @@ final class HookServer: @unchecked Sendable {
activeSessionId = sessionId
questionPillId = pillId
upsertWorkspaceTask(id: pillId, projectName: projectName, cwd: cwd)
upsertTask(pill: pillId,
display: PillSessionRegistry.Display(session: sessionId, projectName: projectName, cwd: cwd),
working: true, externalAgent: nil)
state.updateTask(id: pillId, state: .question)
state.pendingQuestion = parsed
state.isPinned = true
@@ -890,9 +964,12 @@ final class HookServer: @unchecked Sendable {
/// If the task already exists (persistent), just updates name/cwd.
/// If missing (transient), creates it and inserts after the main pill.
@MainActor
private func upsertWorkspaceTask(id: String, projectName: String, cwd: String = "") {
private func upsertWorkspaceTask(id: String, projectName: String, cwd: String = "", session: String) {
let state = AppState.shared
if let idx = state.tasks.firstIndex(where: { $0.id == id }) {
// Name and cwd belong to the session that owns the pill (the oldest one still
// running): a second session under the same client can't rename the card.
guard sessions.ownsDisplay(pill: id, session: session) else { return }
state.tasks[idx].name = projectName
if !cwd.isEmpty { state.tasks[idx].sessionCwd = cwd }
return
+85 -4
View File
@@ -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)
}
}
}
@@ -1169,10 +1189,43 @@ struct MailView: View {
// MARK: - Prompt (chat)
/// The mic's right-click menu: Automatic (the user's languages) or one fixed language.
private struct DictationLanguageMenu: View {
@Bindable var dictation: MacDictation
var body: some View {
let automatic = MacDictation.automaticLocales().map(\.identifier)
Picker("Язык диктовки", selection: $dictation.language) {
Text("Автоматически (" + automatic.map(MacDictation.name(of:)).joined(separator: ", ") + ")")
.tag(MacDictation.automatic)
ForEach(quickChoices(automatic), id: \.self) { id in
Text(MacDictation.name(of: id)).tag(id)
}
}
.pickerStyle(.inline)
Menu("Другие языки") {
Picker("Язык диктовки", selection: $dictation.language) {
ForEach(MacDictation.allLanguages, id: \.self) { id in
Text(MacDictation.name(of: id)).tag(id)
}
}
.pickerStyle(.inline)
.labelsHidden()
}
}
/// Automatic's languages, plus the fixed one when it is another.
private func quickChoices(_ automatic: [String]) -> [String] {
let chosen = dictation.language
return chosen == MacDictation.automatic || automatic.contains(chosen) ? automatic : automatic + [chosen]
}
}
struct PromptView: View {
@ObservedObject var state: AppState
@State private var text: String = ""
@FocusState private var focused: Bool
@State private var dictation = MacDictation()
@State private var showModelPicker = false
var body: some View {
@@ -1267,6 +1320,26 @@ struct PromptView: View {
.focused($focused)
.onSubmit { sendMessage() }
// Dictate instead of typing (on-device speech recognition when available).
Button {
Task {
if dictation.isRecording { text = await dictation.finish() }
else { await dictation.start(from: text) }
}
} label: {
Image(systemName: dictation.isRecording ? "mic.fill" : "mic")
.font(.system(size: 11, weight: .semibold))
.foregroundColor(dictation.isRecording ? Color(hex: "#F4505E") : Color(hex: "#8E939C"))
.frame(width: 18, height: 18)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.help(dictation.isRecording ? "Остановить диктовку" : "Диктовать (правый клик — выбрать язык)")
.contextMenu { DictationLanguageMenu(dictation: dictation) }
.onChange(of: dictation.transcript) { _, _ in
if dictation.isRecording { text = dictation.text }
}
Button(action: sendMessage) {
Image(systemName: "arrow.up")
.font(.system(size: 11, weight: .semibold))
@@ -1325,6 +1398,14 @@ struct PromptView: View {
}
private func sendMessage() {
// Still dictating: take the final words (and the right language) before sending.
if dictation.isRecording {
Task {
text = await dictation.finish()
sendMessage()
}
return
}
let query = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !query.isEmpty else { return }
text = ""
@@ -303,6 +303,7 @@ final class IslandWindowController: NSWindowController {
}
// Mouse in screen coords (Y flipped, origin top-left) for Bot look-at
Self.islandScreenFrame = panel.screen?.frame
let screenH = panel.screen?.frame.height ?? NSScreen.main!.frame.height
let newPos = CGPoint(x: mouse.x - (panel.screen?.frame.minX ?? 0), y: screenH - mouse.y)
let cur = AppState.shared.mousePosition
@@ -363,6 +364,21 @@ final class IslandWindowController: NSWindowController {
private var lastMouse: CGPoint = .zero
/// Mochi's look target from the current mouse position, in the same coordinates the poll
/// uses (the island's screen, y from its top).
/// Frame of the screen the island is on, kept by the poll.
static var islandScreenFrame: CGRect?
static func trackMouseLook() {
let app = AppState.shared
guard app.mode != .hidden || app.mochiOnDesktop else { return }
guard let frame = islandScreenFrame ?? NSScreen.main?.frame else { return }
let mouse = NSEvent.mouseLocation
let pos = CGPoint(x: mouse.x - frame.minX, y: frame.height - mouse.y)
let cur = app.mousePosition
if abs(pos.x - cur.x) > 1 || abs(pos.y - cur.y) > 1 { app.mousePosition = pos }
}
// MARK: - Bot-head hover (love emote — mirrors prototype botHover())
private func botHoverIn(mousePos: CGPoint) {
@@ -719,6 +735,17 @@ final class IslandWindowController: NSWindowController {
self?.handleDizzy()
}
// Eye tracking at the mouse's own rate (from upstream b5b04c2): the look target
// followed the island poll (10–30 Hz), so the head turned in steps. Nothing runs while
// the mouse is still; a hidden island skips the work.
NSEvent.addGlobalMonitorForEvents(matching: [.mouseMoved, .leftMouseDragged]) { _ in
MainActor.assumeIsolated { IslandWindowController.trackMouseLook() }
}
NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved, .leftMouseDragged]) { event in
MainActor.assumeIsolated { IslandWindowController.trackMouseLook() }
return event
}
// Window attach drag.
// Uses MainActor.assumeIsolated (synchronous) to avoid race with pollFrame().
// Global mouseUp is the reliable fallback when cursor is outside our panel frame.
+301
View File
@@ -0,0 +1,301 @@
#if !APPSTORE
import AVFoundation
import Carbon
import Speech
/// Speech to text for the notch chat, on-device when the Mac supports it.
/// From upstream Coucou (#334, #353, review fixes 3b0e987), MIT.
///
/// Apple's recognizer only understands one language per request, so "Automatic" (the default)
/// listens with up to three recognizers at once — the user's languages (macOS languages,
/// keyboard layouts, then English) — shows the one that won last time while you speak, and when
/// you stop keeps the transcript the recognizers were the most confident about. A fixed language
/// can be chosen from the mic's right-click menu.
///
/// Not main-actor bound, because the audio tap and the recognizers call back on their own
/// threads; the published values are set on the main actor.
@Observable
final class MacDictation: @unchecked Sendable {
static let automatic = "auto"
private static let languageKey = "dictationLanguage"
/// The language that won the last automatic dictation: shown first next time.
private static let lastHeardKey = "dictationLastLocale"
private static let maxCandidates = 3
var isRecording = false
var transcript = ""
/// What was typed before dictating, kept in front of the words.
var prefix = ""
/// `automatic` or a locale identifier (the mic's right-click menu).
var language: String = UserDefaults.standard.string(forKey: MacDictation.languageKey) ?? MacDictation.automatic {
didSet { UserDefaults.standard.set(language, forKey: Self.languageKey) }
}
@ObservationIgnored private let engine = AVAudioEngine()
@ObservationIgnored private var candidates: [Candidate] = []
/// The candidate whose words are shown while speaking.
@ObservationIgnored private var lead = 0
@ObservationIgnored private var finishing: CheckedContinuation<Void, Never>?
@ObservationIgnored private var isFinishing = false
@ObservationIgnored private var tapInstalled = false
/// The text field's content: what was typed, then the words heard so far.
var text: String { prefix + transcript }
/// One recognizer listening in one language.
private final class Candidate {
let locale: Locale
let recognizer: SFSpeechRecognizer
let request = SFSpeechAudioBufferRecognitionRequest()
var task: SFSpeechRecognitionTask?
var words = ""
/// Mean confidence of the words (Apple fills it in on the final result).
var confidence: Float = 0
var finished = false
init(locale: Locale, recognizer: SFSpeechRecognizer) {
self.locale = locale
self.recognizer = recognizer
request.shouldReportPartialResults = true
if recognizer.supportsOnDeviceRecognition { request.requiresOnDeviceRecognition = true }
}
}
// MARK: Start / finish
@MainActor func start(from text: String) async {
guard !isRecording, await Self.authorized() else { return }
let built = Self.makeCandidates(language == Self.automatic ? Self.automaticLocales() : [Locale(identifier: language)])
guard !built.isEmpty, Self.startEngine(engine, feeding: built.map(\.request)) else { return }
tapInstalled = true
prefix = text.isEmpty || text.hasSuffix(" ") ? text : text + " "
transcript = ""
candidates = built
lead = 0
isRecording = true
NotificationCenter.default.post(name: .dictationDidStart, object: nil)
for (index, candidate) in built.enumerated() {
candidate.task = Self.recognize(candidate) { [weak self] words, confidence, final, failed in
Task { @MainActor in
self?.update(index, words: words, confidence: confidence, final: final, failed: failed)
}
}
}
}
/// Stops listening and returns the field's text with the most likely transcript.
@MainActor func finish() async -> String {
guard isRecording else { return text }
isFinishing = true
stopEngine()
candidates.forEach { $0.request.endAudio() }
// With several languages, wait a moment for the final results: they carry the confidence.
if candidates.count > 1, !candidates.allSatisfy(\.finished) {
await withCheckedContinuation { continuation in
finishing = continuation
Task { @MainActor [weak self] in
try? await Task.sleep(for: .milliseconds(1200))
self?.resumeFinishing()
}
}
}
if let best = bestCandidate() {
transcript = best.words
if candidates.count > 1 {
UserDefaults.standard.set(best.locale.identifier, forKey: Self.lastHeardKey)
}
}
tearDown()
return text
}
/// Cancels without waiting (the view went away).
@MainActor func stop() {
guard isRecording || !candidates.isEmpty else { return }
tearDown()
}
@MainActor private func stopEngine() {
engine.stop()
if tapInstalled { engine.inputNode.removeTap(onBus: 0) }
tapInstalled = false
}
@MainActor private func tearDown() {
stopEngine()
candidates.forEach { $0.request.endAudio(); $0.task?.cancel() }
candidates = []
lead = 0
NotificationCenter.default.post(name: .dictationDidEnd, object: nil)
isRecording = false
isFinishing = false
resumeFinishing()
}
@MainActor private func resumeFinishing() {
finishing?.resume()
finishing = nil
}
// MARK: Results
@MainActor private func update(_ index: Int, words: String?, confidence: Float, final: Bool, failed: Bool) {
guard index < candidates.count else { return }
let candidate = candidates[index]
if let words { candidate.words = words }
if confidence > 0 { candidate.confidence = confidence }
if final || failed { candidate.finished = true }
if isFinishing {
if candidates.allSatisfy(\.finished) { resumeFinishing() }
return
}
// A recognizer that gives up while you speak (no model, busy…) hands over to the next one.
if index == lead, candidate.finished, candidate.words.isEmpty,
let next = candidates.firstIndex(where: { !$0.finished }) {
lead = next
transcript = candidates[next].words
return
}
// When Apple reports confidences while speaking, follow the clearly better language.
let current = candidates[lead]
if index != lead, candidate.confidence > current.confidence + 0.15,
candidate.words.split(separator: " ").count >= 3 {
lead = index
}
if index == lead { transcript = candidate.words }
if candidates.allSatisfy(\.finished) { tearDown() }
}
@MainActor private func bestCandidate() -> Candidate? {
guard lead < candidates.count else { return nil }
let leader = candidates[lead]
let best = candidates
.filter { !$0.words.isEmpty }
.max { $0.confidence < $1.confidence }
guard let best, best.confidence > leader.confidence else { return leader }
return best
}
// MARK: Audio and recognizers (off the main actor: they call back on their own threads)
nonisolated private static func startEngine(_ engine: AVAudioEngine, feeding requests: [SFSpeechAudioBufferRecognitionRequest]) -> Bool {
let input = engine.inputNode
input.installTap(onBus: 0, bufferSize: 1024, format: input.outputFormat(forBus: 0)) { buffer, _ in
for request in requests { request.append(buffer) }
}
engine.prepare()
do { try engine.start() } catch {
input.removeTap(onBus: 0)
return false
}
return true
}
nonisolated private static func recognize(
_ candidate: Candidate,
report: @escaping @Sendable (String?, Float, Bool, Bool) -> Void
) -> SFSpeechRecognitionTask {
candidate.recognizer.recognitionTask(with: candidate.request) { result, error in
let words = result?.bestTranscription.formattedString
let segments = result?.bestTranscription.segments ?? []
let confidence = segments.isEmpty ? 0 : segments.map(\.confidence).reduce(0, +) / Float(segments.count)
report(words, confidence, result?.isFinal ?? false, error != nil)
}
}
/// Recognizers that can run now. Extra languages in Automatic only listen on-device,
/// so the audio never goes to Apple in a language you didn't speak.
private static func makeCandidates(_ locales: [Locale]) -> [Candidate] {
var out: [Candidate] = []
for locale in locales {
guard let recognizer = SFSpeechRecognizer(locale: locale), recognizer.isAvailable else { continue }
if !out.isEmpty && !recognizer.supportsOnDeviceRecognition { continue }
out.append(Candidate(locale: locale, recognizer: recognizer))
}
if out.isEmpty, let fallback = SFSpeechRecognizer(), fallback.isAvailable {
out.append(Candidate(locale: fallback.locale, recognizer: fallback))
}
return out
}
// MARK: Languages
/// The languages Automatic listens for: last winner, macOS languages, keyboard layouts,
/// Coucou's own language, then English — one per language, up to three.
static func automaticLocales() -> [Locale] {
var ids: [String] = []
if let last = UserDefaults.standard.string(forKey: lastHeardKey) { ids.append(last) }
// The Mac's languages (not Coucou's override in Settings → General → Language).
ids += (CFPreferencesCopyValue("AppleLanguages" as CFString, kCFPreferencesAnyApplication,
kCFPreferencesCurrentUser, kCFPreferencesAnyHost) as? [String]) ?? []
ids += keyboardLanguages()
ids += Locale.preferredLanguages
ids.append("en-US")
let supported = Array(SFSpeechRecognizer.supportedLocales())
var seen = Set<String>()
var out: [Locale] = []
for id in ids {
guard let locale = match(id, in: supported) else { continue }
let language = locale.language.languageCode?.identifier ?? locale.identifier
guard seen.insert(language).inserted else { continue }
out.append(locale)
if out.count == maxCandidates { break }
}
return out
}
/// Every language the recognizer knows, by name.
static var allLanguages: [String] {
SFSpeechRecognizer.supportedLocales()
.map(\.identifier)
.sorted { name(of: $0).localizedCaseInsensitiveCompare(name(of: $1)) == .orderedAscending }
}
static func name(of identifier: String) -> String {
let name = Locale.current.localizedString(forIdentifier: identifier) ?? identifier
return name.prefix(1).uppercased() + name.dropFirst()
}
/// "fr" or "fr_FR" → the recognizer locale for it, preferring the Mac's region.
private static func match(_ id: String, in supported: [Locale]) -> Locale? {
let wanted = id.replacingOccurrences(of: "_", with: "-").lowercased()
if let exact = supported.first(where: { $0.identifier.replacingOccurrences(of: "_", with: "-").lowercased() == wanted }) {
return exact
}
let language = Locale(identifier: id).language.languageCode?.identifier
let sameLanguage = supported.filter { $0.language.languageCode?.identifier == language }
let region = Locale(identifier: id).region ?? Locale.current.region
return sameLanguage.first { $0.region == region }
?? sameLanguage.min { $0.identifier < $1.identifier }
}
/// The main language of each enabled keyboard layout ("fr" for AZERTY, "en" for ABC…).
private static func keyboardLanguages() -> [String] {
let filter = ["TISPropertyInputSourceCategory": "TISCategoryKeyboardInputSource"] as CFDictionary
guard let list = TISCreateInputSourceList(filter, false)?.takeRetainedValue() as? [TISInputSource] else { return [] }
return list.compactMap { source in
guard let raw = TISGetInputSourceProperty(source, "TISPropertyInputSourceLanguages" as CFString) else { return nil }
let languages = Unmanaged<CFArray>.fromOpaque(raw).takeUnretainedValue() as? [String]
return languages?.first
}
}
private static func authorized() async -> Bool {
let speech = await withCheckedContinuation { continuation in
SFSpeechRecognizer.requestAuthorization { continuation.resume(returning: $0 == .authorized) }
}
guard speech else { return false }
return await AVAudioApplication.requestRecordPermission()
}
}
// MARK: - Dictation notification names
// Defined here so both MacDictation and VoiceEngine can reference them without
// cross-file ordering issues in SourceKit.
extension Notification.Name {
static let dictationDidStart = Notification.Name("notchBuddy.dictationDidStart")
static let dictationDidEnd = Notification.Name("notchBuddy.dictationDidEnd")
}
#endif
@@ -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")
}
@@ -0,0 +1,162 @@
import Foundation
// MARK: - PillSessionRegistry
//
// From upstream Coucou 5652ea8 (#562, after #245 by @TheodoreRiant), MIT. Unchanged.
/// Keeps track of the agent sessions living behind each pill.
///
/// A pill is picked from the client that sent the event — bundle ID,
/// `term_program`, `coucou_agent` — never from the session. Two `claude`
/// started in two projects under VS Code therefore land on the same
/// `integration_claude`, while `AppState.tasks` holds one entry per pill.
/// Without a session set, the first session to end wipes the card and the
/// diffs the second one is still filling.
///
/// A value type on purpose: the hook server owns one copy and every change
/// goes through a `mutating` call, so no other object can alias the state.
struct PillSessionRegistry {
/// A session unheard of for this long counts as gone. A `SessionEnd` that
/// never arrives — a killed terminal, a crash — would otherwise pin a card
/// to a session nobody is running any more.
static let maxSilence: TimeInterval = 12 * 3600
/// A session mid-turn emits a hook event every few seconds, so this long
/// without one means its `Stop` went missing. Stops counting it as working,
/// which is what keeps a sibling session from staying stuck out of its
/// finished state. Longer than any tool call Claude Code will wait on.
static let maxTurnSilence: TimeInterval = 30 * 60
/// How far a terminal event is allowed to reach.
enum TerminalScope: Equatable {
/// No other session is mid-turn behind this pill, so the pill may
/// follow: finished state, sound, badge, card removal.
case pill
/// Another session is still working — leave the pill as it is.
case sessionOnly
}
/// What a pill shows while a session owns it.
struct Display: Equatable {
var session: String
var projectName: String
var cwd: String
/// Terminal the session runs in (bundle id), for "Open terminal".
var hostApp: String? = nil
/// Bundle id of the client (VS Code, Cursor…) that sent the event.
var bundleId: String = ""
}
private struct Session {
var projectName: String
var cwd: String
var hostApp: String?
var bundleId: String
var isWorking: Bool
var lastSeen: Date
}
private struct Pill {
/// Live sessions, oldest first. The first one owns name and cwd.
var order: [String] = []
var sessions: [String: Session] = [:]
}
private var pills: [String: Pill] = [:]
// MARK: - Recording activity
/// Records the session that sent an event as live behind `pill`.
/// `working` says whether the event means the session is mid-turn: a
/// `PreToolUse` does, a `SessionStart` or a stray notification does not.
mutating func note(pill: String, display: Display, working: Bool, now: Date = Date()) {
var p = pills[pill] ?? Pill()
sweep(&p, now: now)
if p.sessions[display.session] == nil {
p.order.append(display.session)
}
var session = p.sessions[display.session]
?? Session(projectName: display.projectName, cwd: display.cwd,
hostApp: display.hostApp, bundleId: display.bundleId,
isWorking: false, lastSeen: now)
session.projectName = display.projectName
if !display.cwd.isEmpty { session.cwd = display.cwd }
if display.hostApp != nil { session.hostApp = display.hostApp }
if !display.bundleId.isEmpty { session.bundleId = display.bundleId }
if working { session.isWorking = true }
session.lastSeen = now
p.sessions[display.session] = session
pills[pill] = p
}
// MARK: - Terminal events
/// Ends a session's turn without ending the session: a `Stop` closes a
/// turn, and the user can send another prompt right after.
///
/// A session we have never seen stays untracked — Coucou can start in the
/// middle of one, and a session we only ever heard stop owns nothing.
mutating func endTurn(pill: String, session: String, now: Date = Date()) -> TerminalScope {
var p = pills[pill] ?? Pill()
sweep(&p, now: now)
p.sessions[session]?.isWorking = false
p.sessions[session]?.lastSeen = now
if p.order.isEmpty { pills.removeValue(forKey: pill) } else { pills[pill] = p }
return p.sessions.values.contains(where: \.isWorking) ? .sessionOnly : .pill
}
/// Drops a session for good. `.pill` only when it was the last one live,
/// so the card and the diffs survive a sibling session ending.
mutating func endSession(pill: String, session: String, now: Date = Date()) -> TerminalScope {
var p = pills[pill] ?? Pill()
sweep(&p, now: now)
p.order.removeAll { $0 == session }
p.sessions.removeValue(forKey: session)
guard !p.order.isEmpty else {
pills.removeValue(forKey: pill)
return .pill
}
pills[pill] = p
return .sessionOnly
}
// MARK: - Reading
/// The session whose project name and cwd the pill shows. Ownership goes
/// to the oldest live session and only moves on when that one ends, so a
/// single name field stops flipping between two parallel sessions.
func displayOwner(of pill: String) -> Display? {
guard let p = pills[pill], let id = p.order.first,
let session = p.sessions[id] else { return nil }
return Display(session: id, projectName: session.projectName, cwd: session.cwd,
hostApp: session.hostApp, bundleId: session.bundleId)
}
/// Whether this session may write the pill's name and cwd. True when the
/// pill has no live session yet, so a first event is never dropped.
func ownsDisplay(pill: String, session: String) -> Bool {
guard let owner = displayOwner(of: pill) else { return true }
return owner.session == session
}
func liveCount(pill: String) -> Int { pills[pill]?.order.count ?? 0 }
func workingCount(pill: String) -> Int {
pills[pill]?.sessions.values.filter(\.isWorking).count ?? 0
}
// MARK: - Silence sweep
private func sweep(_ pill: inout Pill, now: Date) {
for (id, session) in pill.sessions.map({ ($0.key, $0.value) }) {
let silence = now.timeIntervalSince(session.lastSeen)
if silence > Self.maxSilence {
pill.sessions.removeValue(forKey: id)
pill.order.removeAll { $0 == id }
} else if session.isWorking, silence > Self.maxTurnSilence {
pill.sessions[id]?.isWorking = false
}
}
}
}
@@ -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)
+2
View File
@@ -72,6 +72,8 @@ targets:
CFBundleShortVersionString: "0.1.0"
CFBundlePackageType: APPL
LSUIElement: YES
NSMicrophoneUsageDescription: "BroV слушает микрофон, когда ты диктуешь сообщение в чат."
NSSpeechRecognitionUsageDescription: "BroV превращает твой голос в текст сообщения в чате."
NSHighResolutionCapable: YES
NSSupportsAutomaticGraphicsSwitching: YES
NSAppleEventsUsageDescription: "BroV jumps to your terminal, sends mail and controls Music."
+8
View File
@@ -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"
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/coucou-session-registry.XXXXXX")"
trap 'rm -rf "$TEST_DIR"' EXIT
swiftc NotchBuddy/Sources/App/PillSessionRegistry.swift \
tests/PillSessionRegistryTests.swift -o "$TEST_DIR/session-registry-tests"
"$TEST_DIR/session-registry-tests"
+68
View File
@@ -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")
}
}
+207
View File
@@ -0,0 +1,207 @@
import Foundation
@main
enum PillSessionRegistryTests {
static var failures = 0
static func check(_ label: String, _ got: Bool) {
if got { print(" ✓ \(label)") }
else { print(" ✗ \(label)"); failures += 1 }
}
static let claude = "integration_claude"
static func display(_ session: String, _ project: String, _ cwd: String = "")
-> PillSessionRegistry.Display {
PillSessionRegistry.Display(session: session, projectName: project, cwd: cwd)
}
static func main() {
// ── one session alone: the pill follows it all the way ──────────────────
print("\nSingle session")
do {
var reg = PillSessionRegistry()
reg.note(pill: claude, display: display("a", "coucou", "/tmp/coucou"), working: false)
check("one live session", reg.liveCount(pill: claude) == 1)
check("not working after SessionStart", reg.workingCount(pill: claude) == 0)
reg.note(pill: claude, display: display("a", "coucou", "/tmp/coucou"), working: true)
check("working after a tool call", reg.workingCount(pill: claude) == 1)
check("Stop reaches the pill", reg.endTurn(pill: claude, session: "a") == .pill)
check("still live between turns", reg.liveCount(pill: claude) == 1)
check("SessionEnd reaches the pill",
reg.endSession(pill: claude, session: "a") == .pill)
check("pill is empty", reg.liveCount(pill: claude) == 0)
}
// ── two sessions on one pill: this is the defect ────────────────────────
// Negative cases: an implementation that always answers .pill fails here.
print("\nTwo sessions behind one pill")
do {
var reg = PillSessionRegistry()
reg.note(pill: claude, display: display("a", "coucou", "/a"), working: true)
reg.note(pill: claude, display: display("b", "lokil", "/b"), working: true)
check("both live", reg.liveCount(pill: claude) == 2)
check("both working", reg.workingCount(pill: claude) == 2)
check("A's Stop must not touch the pill while B works",
reg.endTurn(pill: claude, session: "a") == .sessionOnly)
check("B still working", reg.workingCount(pill: claude) == 1)
check("A's SessionEnd must not remove the card",
reg.endSession(pill: claude, session: "a") == .sessionOnly)
check("B alone now", reg.liveCount(pill: claude) == 1)
check("B's Stop reaches the pill", reg.endTurn(pill: claude, session: "b") == .pill)
check("B's SessionEnd reaches the pill",
reg.endSession(pill: claude, session: "b") == .pill)
}
// ── a resting sibling does not hold the pill back ───────────────────────
print("\nResting sibling")
do {
var reg = PillSessionRegistry()
reg.note(pill: claude, display: display("a", "coucou"), working: true)
reg.note(pill: claude, display: display("b", "lokil"), working: true)
_ = reg.endTurn(pill: claude, session: "b")
check("A's Stop reaches the pill once B rests",
reg.endTurn(pill: claude, session: "a") == .pill)
check("A's SessionEnd still spares B's card",
reg.endSession(pill: claude, session: "a") == .sessionOnly)
}
// ── name and cwd: owned by one session, handed over when it leaves ──────
print("\nDisplay ownership")
do {
var reg = PillSessionRegistry()
reg.note(pill: claude, display: display("a", "coucou", "/a"), working: true)
reg.note(pill: claude, display: display("b", "lokil", "/b"), working: true)
check("oldest session owns the name", reg.displayOwner(of: claude)?.session == "a")
check("name is A's", reg.displayOwner(of: claude)?.projectName == "coucou")
check("A may write the card", reg.ownsDisplay(pill: claude, session: "a"))
check("B may not rename the card under A",
!reg.ownsDisplay(pill: claude, session: "b"))
// B keeps working; the name must not flip.
reg.note(pill: claude, display: display("b", "lokil", "/b"), working: true)
check("name still A's after more B events",
reg.displayOwner(of: claude)?.projectName == "coucou")
_ = reg.endSession(pill: claude, session: "a")
check("B inherits the display", reg.displayOwner(of: claude)?.session == "b")
check("name is now B's", reg.displayOwner(of: claude)?.projectName == "lokil")
check("cwd is now B's", reg.displayOwner(of: claude)?.cwd == "/b")
check("B may write the card now", reg.ownsDisplay(pill: claude, session: "b"))
}
// ── empty cwd must not erase a known one ────────────────────────────────
print("\nPartial payloads")
do {
var reg = PillSessionRegistry()
reg.note(pill: claude, display: display("a", "coucou", "/a"), working: true)
reg.note(pill: claude, display: display("a", "coucou", ""), working: false)
check("cwd kept when the event carries none",
reg.displayOwner(of: claude)?.cwd == "/a")
check("working flag is sticky inside a turn", reg.workingCount(pill: claude) == 1)
}
// ── pills are independent ──────────────────────────────────────────────
print("\nSeparate pills")
do {
var reg = PillSessionRegistry()
reg.note(pill: claude, display: display("a", "coucou"), working: true)
reg.note(pill: "agent_cursor", display: display("b", "lokil"), working: true)
check("Cursor's Stop reaches its own pill",
reg.endTurn(pill: "agent_cursor", session: "b") == .pill)
check("Claude untouched", reg.workingCount(pill: claude) == 1)
check("an unknown pill is empty", reg.liveCount(pill: "agent_codex") == 0)
}
// ── sessions we never saw start ─────────────────────────────────────────
print("\nUntracked sessions")
do {
var reg = PillSessionRegistry()
check("a Stop from nowhere reaches the pill",
reg.endTurn(pill: claude, session: "ghost") == .pill)
check("it owns nothing", reg.liveCount(pill: claude) == 0)
check("a SessionEnd from nowhere reaches the pill",
reg.endSession(pill: claude, session: "ghost") == .pill)
reg.note(pill: claude, display: display("a", "coucou"), working: true)
check("a Stop from nowhere spares a working session",
reg.endTurn(pill: claude, session: "ghost") == .sessionOnly)
check("a SessionEnd from nowhere spares a live session",
reg.endSession(pill: claude, session: "ghost") == .sessionOnly)
}
// ── a Stop that never arrives must not hold the other session back ─────
print("\nTurn silence")
do {
var reg = PillSessionRegistry()
let start = Date(timeIntervalSince1970: 1_000_000)
reg.note(pill: claude, display: display("a", "coucou"), working: true, now: start)
reg.note(pill: claude, display: display("b", "lokil"), working: true, now: start)
let soon = start.addingTimeInterval(PillSessionRegistry.maxTurnSilence - 60)
reg.note(pill: claude, display: display("b", "lokil"), working: true, now: soon)
check("A still working just under the limit",
reg.endTurn(pill: claude, session: "b", now: soon) == .sessionOnly)
let late = start.addingTimeInterval(PillSessionRegistry.maxTurnSilence + 60)
reg.note(pill: claude, display: display("b", "lokil"), working: true, now: late)
check("silent A no longer counts as working",
reg.workingCount(pill: claude) == 1)
check("B's Stop reaches the pill again",
reg.endTurn(pill: claude, session: "b", now: late) == .pill)
check("A is still live", reg.liveCount(pill: claude) == 2)
check("A still owns the display", reg.displayOwner(of: claude)?.session == "a")
}
// ── a SessionEnd that never arrives must not pin the card forever ──────
print("\nSilence sweep")
do {
var reg = PillSessionRegistry()
let start = Date(timeIntervalSince1970: 1_000_000)
reg.note(pill: claude, display: display("a", "coucou"), working: true, now: start)
reg.note(pill: claude, display: display("b", "lokil"), working: true, now: start)
let later = start.addingTimeInterval(PillSessionRegistry.maxSilence + 60)
reg.note(pill: claude, display: display("b", "lokil"), working: true, now: later)
check("silent A swept", reg.liveCount(pill: claude) == 1)
check("B owns the display", reg.displayOwner(of: claude)?.session == "b")
check("B's SessionEnd clears the pill",
reg.endSession(pill: claude, session: "b", now: later) == .pill)
}
// ── the terminal ("Open terminal") follows the display owner ────────────
print("\nTerminal of the owner")
do {
var reg = PillSessionRegistry()
reg.note(pill: claude,
display: PillSessionRegistry.Display(session: "a", projectName: "coucou",
cwd: "/tmp/coucou",
hostApp: "com.googlecode.iterm2"),
working: true)
reg.note(pill: claude,
display: PillSessionRegistry.Display(session: "b", projectName: "lokil",
cwd: "/tmp/lokil",
hostApp: "com.apple.Terminal"),
working: true)
check("A's terminal shown", reg.displayOwner(of: claude)?.hostApp == "com.googlecode.iterm2")
_ = reg.endSession(pill: claude, session: "a")
check("B's terminal once A ends", reg.displayOwner(of: claude)?.hostApp == "com.apple.Terminal")
check("B's folder once A ends", reg.displayOwner(of: claude)?.cwd == "/tmp/lokil")
}
// ── finish ─────────────────────────────────────────────────────────────
if failures == 0 {
print("\nAll tests passed.")
exit(0)
} else {
print("\n\(failures) test(s) failed.")
exit(1)
}
}
}