Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

Each session apart behind its client's pill; a waiting one pops out

NikitaBulicheve1e8722c61f0
diff --git a/NotchBuddy/Sources/App/ApprovalQueue.swift b/NotchBuddy/Sources/App/ApprovalQueue.swift
index 66127fcd..e90892c7 100644
--- a/NotchBuddy/Sources/App/ApprovalQueue.swift
+++ b/NotchBuddy/Sources/App/ApprovalQueue.swift
@@ -23,6 +23,12 @@ struct QueuedApproval: Equatable, Sendable {
var bundleId: String = ""
/// When the request arrived (for the log: how long it waited).
var received = Date()
+ /// The pill the request shows on when its session popped out of `pillId` (SessionBoard),
+ /// nil when it shows on `pillId` itself.
+ var shownPill: String? = nil
+
+ /// Where the card, the focus and the iPhone find the request.
+ var displayPill: String { shownPill ?? pillId }
}
struct ApprovalQueue: Sendable {
diff --git a/NotchBuddy/Sources/App/HookServer.swift b/NotchBuddy/Sources/App/HookServer.swift
index 52e25c49..fe7b01cd 100644
--- a/NotchBuddy/Sources/App/HookServer.swift
+++ b/NotchBuddy/Sources/App/HookServer.swift
@@ -62,6 +62,7 @@ final class HookServer: @unchecked Sendable {
private var focusBeforeAlert: String? = nil // saved focus while another pill's card shows
private var alertPill: String? = nil // the pill that took the focus for its alert
private var sessions = PillSessionRegistry() // live sessions behind each pill
+ private var board = SessionBoard() // what each of those sessions shows
private init() {}
@@ -103,17 +104,17 @@ final class HookServer: @unchecked Sendable {
if shown.queueCount != approvals.count { state.pendingApproval?.queueCount = approvals.count }
return
}
- state.updateTask(id: head.pillId, state: .approval)
+ syncPill(head.pillId)
state.pendingApproval = ApprovalInfo(sessionId: head.sessionId, tool: head.tool,
command: head.command, inputKey: head.inputKey,
- pillId: head.pillId, id: head.id,
+ pillId: head.displayPill, id: head.id,
queueCount: approvals.count,
projectName: head.projectName)
state.isPinned = true
// Approval always forces the island open — the user must be able to respond.
// Save the focus once, so it comes back when the last request is gone.
if focusBeforeApproval == nil { focusBeforeApproval = state.focusId }
- withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = head.pillId }
+ withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = head.displayPill }
expandIfNeeded(to: .approval)
}
@@ -140,10 +141,10 @@ final class HookServer: @unchecked Sendable {
}
let state = AppState.shared
- if !approvals.hasEntries(forPill: entry.pillId) {
- // A question from another session on this pill may still be waiting.
- state.updateTask(id: entry.pillId, state: questionWaits(onPill: entry.pillId) ? .question : .working)
- clearPillBadge(id: entry.pillId)
+ // The session's pill leaves its approval state; a popped-out one folds back soon after.
+ syncPill(entry.pillId)
+ if !approvals.entries.contains(where: { $0.displayPill == entry.displayPill }) {
+ clearPillBadge(id: entry.displayPill)
}
if approvals.head != nil {
showApprovalHead()
@@ -154,7 +155,7 @@ final class HookServer: @unchecked Sendable {
state.isPinned = false
if let prev = focusBeforeApproval {
focusBeforeApproval = nil
- if state.focusId == entry.pillId, state.tasks.contains(where: { $0.id == prev }) {
+ if state.focusId == entry.displayPill, state.tasks.contains(where: { $0.id == prev }) {
withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = prev }
}
}
@@ -169,15 +170,131 @@ final class HookServer: @unchecked Sendable {
}
}
- // MARK: - Question queue helpers
+ // MARK: - Sessions on the board
+
+ /// A session's key on the board: its id, or for one that sends none its pill and folder
+ /// (the same key the recap and the question queue use).
+ private static func boardKey(_ session: String, pill: String, cwd: String) -> String {
+ (session == "unknown" || session.isEmpty) ? "\(pill)+\(cwd)" : session
+ }
+
+ /// Records what an event says about a session of `pill` on the board.
+ @MainActor
+ private func record(pill: String, session key: String, raw: String, title: String,
+ _ change: (inout BoardSession) -> Void = { _ in }) {
+ board.update(pill: pill, session: key, rawSession: raw, title: title, now: Date(), change)
+ }
- /// True while a question from a session behind `pill` waits for its answer. The pill keeps
- /// its question state meanwhile: the iPhone and the Live Activity read the question from it.
+ /// The sessions of `pill` waiting for you, with what they wait for (a permission first).
@MainActor
- private func questionWaits(onPill pill: String) -> Bool {
- questions.hasEntries(forPill: pill)
+ private func waitingSessions(pill: String) -> [String: BotState] {
+ var waiting: [String: BotState] = [:]
+ for q in questions.entries where q.pillId == pill { waiting[q.sessionId] = .question }
+ for a in approvals.entries where a.pillId == pill {
+ waiting[Self.boardKey(a.sessionId, pill: pill, cwd: a.cwd)] = .approval
+ }
+ return waiting
}
+ /// A session that starts waiting while it shares `pill` with another pops out into a pill
+ /// of its own. Returns that pill, nil when the session stays (it is alone in its pill).
+ @MainActor
+ private func popOutIfShared(pill: String, session key: String, raw: String, title: String) -> String? {
+ record(pill: pill, session: key, raw: raw, title: title)
+ let popped = board.popOut(pill: pill, session: key, now: Date())
+ if let popped { nbLog("\(key.prefix(8)) waits: out of \(pill) into \(popped)") }
+ return popped
+ }
+
+ /// Writes the board to `pill` and to the pills popped out of it: the session the pill
+ /// shows (name, steps, state, last message, terminal), the list the open card shows when
+ /// several share it, each popped-out session's own pill, and the folding back of those
+ /// no longer waiting.
+ @MainActor
+ private func syncPill(_ pill: String) {
+ let state = AppState.shared
+ let now = Date()
+ var gone = board.keep(pill: pill) { sessions.display(pill: pill, session: $0.rawSession) != nil }
+ let waiting = waitingSessions(pill: pill)
+ let (folded, recheck) = board.fold(pill: pill, waiting: Set(waiting.keys), now: now)
+ gone += folded
+ for id in gone where state.tasks.contains(where: { $0.id == id }) {
+ if state.focusId == id { state.focusId = pill }
+ withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.removeTask(id: id) }
+ }
+ if let recheck {
+ DispatchQueue.main.asyncAfter(deadline: .now() + max(0.05, recheck.timeIntervalSince(now))) { [weak self] in
+ self?.syncPill(pill)
+ }
+ }
+ guard let client = state.tasks.first(where: { $0.id == pill }) else { return }
+ for (session, popped) in board.poppedOut(pill: pill) {
+ showPoppedOut(popped, of: client, session: session, waiting: waiting[session])
+ }
+ guard let index = state.tasks.firstIndex(where: { $0.id == pill }) else { return }
+ guard let shown = board.shown(pill: pill, waiting: Set(waiting.keys), now: now),
+ let session = board.session(pill: pill, session: shown) else {
+ if !state.tasks[index].sessionLines.isEmpty { state.tasks[index].sessionLines = [] }
+ return
+ }
+ write(session, waiting: waiting[shown], client: pill, to: index)
+ let lines = board.lines(pill: pill).map { line in
+ SessionLine(id: line.session, title: line.value.title,
+ state: waiting[line.session] ?? line.value.state,
+ lastStep: Self.readableStep(line.value.steps.last ?? ""),
+ isShown: line.session == shown)
+ }
+ if state.tasks[index].sessionLines != lines { state.tasks[index].sessionLines = lines }
+ }
+
+ /// Puts one session's state, steps, last message, title and terminal on the task at `index`.
+ @MainActor
+ private func write(_ session: BoardSession, waiting: BotState?, client: String, to index: Int) {
+ let state = AppState.shared
+ var task = state.tasks[index]
+ task.state = waiting ?? session.state
+ if task.steps != session.steps {
+ task.steps = session.steps
+ task.stepIndex = max(0, session.steps.count - 1)
+ }
+ task.finalLine = session.finalLine
+ // A third-party agent's pill keeps the agent's name; Claude Code's and Codex's take the session's.
+ if !session.title.isEmpty, task.isIntegration || task.pill == "agent_claude-desktop" || task.id != task.pill {
+ task.name = session.title
+ }
+ if let display = sessions.display(pill: client, session: session.rawSession) {
+ if !display.cwd.isEmpty { task.sessionCwd = display.cwd }
+ if task.pill == "integration_claude" { task.hostApp = display.hostApp }
+ if !display.bundleId.isEmpty { task.sessionBundleId = display.bundleId }
+ }
+ if state.tasks[index] != task { state.tasks[index] = task }
+ }
+
+ /// Creates or refreshes the pill a waiting session popped out into, right after its
+ /// client's pills, in the client's color.
+ @MainActor
+ private func showPoppedOut(_ id: String, of client: AgentTask, session: String, waiting: BotState?) {
+ guard let value = board.session(pill: client.id, session: session) else { return }
+ let state = AppState.shared
+ if !state.tasks.contains(where: { $0.id == id }) {
+ var task = AgentTask(id: id, name: value.title, color: client.color, state: waiting ?? value.state,
+ steps: [], source: client.source, isIntegration: client.isIntegration)
+ task.hostApp = client.hostApp
+ let at = (state.tasks.lastIndex(where: { $0.pill == client.pill }) ?? state.tasks.count - 1) + 1
+ withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.tasks.insert(task, at: at) }
+ }
+ guard let index = state.tasks.firstIndex(where: { $0.id == id }) else { return }
+ write(value, waiting: waiting, client: client.id, to: index)
+ }
+
+ /// A step as the open card lists it: a file edit reads "name +3 −1".
+ private static func readableStep(_ step: String) -> String {
+ guard let diff = step.parseDiffStep() else { return step }
+ return "\(diff.filename) +\(diff.added) −\(diff.removed)"
+ }
+
+ // MARK: - Question queue helpers
+
/// Puts the oldest waiting question on the card. When the card already shows it, only
/// the list the card and the iPhone read is refreshed (no sound, no focus change).
@MainActor
@@ -189,7 +306,7 @@ final class HookServer: @unchecked Sendable {
state.pendingQuestion = head.question
state.isPinned = true
if focusBeforeQuestion == nil { focusBeforeQuestion = state.focusId }
- withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = head.pillId }
+ withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.focusId = head.displayPill }
expandIfNeeded(to: .question)
}
@@ -213,17 +330,18 @@ final class HookServer: @unchecked Sendable {
}
let state = AppState.shared
- if !questions.hasEntries(forPill: entry.pillId) {
- let approval = approvals.hasEntries(forPill: entry.pillId)
- state.updateTask(id: entry.pillId, state: approval ? .approval : .working)
- if !approval { clearPillBadge(id: entry.pillId) }
+ // The session's pill leaves its question state; a popped-out one folds back soon after.
+ syncPill(entry.pillId)
+ if !questions.entries.contains(where: { $0.displayPill == entry.displayPill })
+ && !approvals.entries.contains(where: { $0.displayPill == entry.displayPill }) {
+ clearPillBadge(id: entry.displayPill)
}
if questions.head != nil {
showQuestionHead()
return
}
state.waitingQuestions = []
- closeQuestionCard(pill: entry.pillId)
+ closeQuestionCard(pill: entry.displayPill)
}
/// No question left: close the card and give the focus back.
@@ -284,18 +402,19 @@ final class HookServer: @unchecked Sendable {
func releaseQuestionFD() {
guard !questions.isEmpty else { return }
let state = AppState.shared
- for entry in questions.removeAll() {
+ let gone = questions.removeAll()
+ for entry in gone {
let source = questionSources.removeValue(forKey: entry.id)
let fd = entry.fd
Task.detached { [weak self] in
self?.sendLine(fd: fd, text: #"{"permissionDecision":"ask"}"#)
DispatchQueue.main.async { source?.cancel() }
}
- if !approvals.hasEntries(forPill: entry.pillId) { state.updateTask(id: entry.pillId, state: .working) }
}
shownQuestion = nil
state.waitingQuestions = []
state.pendingQuestion = nil
+ for pill in Set(gone.map(\.pillId)) { syncPill(pill) }
}
/// Called by QuestionView "Reply in terminal" button: question `id` (the card's when nil)
@@ -514,7 +633,6 @@ final class HookServer: @unchecked Sendable {
return
}
- let focused = state.focusId == agentId
// The user is looking at the session's terminal: a finish or an error is already in
// front of them, so the pill only takes a badge (no sound, no reveal). Warp exposes
// no active tab, so a sibling session in another tab of the same terminal is quiet too.
@@ -546,7 +664,7 @@ final class HookServer: @unchecked Sendable {
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))
+ removeApproval(id: entry.id, note: handledNote(pill: entry.displayPill))
}
// 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.
@@ -554,15 +672,15 @@ final class HookServer: @unchecked Sendable {
return
}
}
- // A sibling session's event must not take the pill out of its approval state,
- // nor out of the question state while a question waits on it.
- defer {
- if approvals.hasEntries(forPill: agentId) {
- state.updateTask(id: agentId, state: .approval)
- } else if questionWaits(onPill: agentId) {
- state.updateTask(id: agentId, state: .question)
- }
+ // What the event says goes to its session on the board, and the pill shows the board:
+ // the session it shows, its steps and state; a session waiting for you keeps that state.
+ let key = recapSessionId
+ let now = Date()
+ func note(_ change: (inout BoardSession) -> Void = { _ in }) {
+ record(pill: agentId, session: key, raw: sessionId, title: projectName, change)
}
+ func step(_ text: String) { note { $0.appendStep(text) } }
+ defer { syncPill(agentId) }
switch name {
@@ -570,7 +688,7 @@ final class HookServer: @unchecked Sendable {
activeSessionId = sessionId
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 }
+ note { $0.finalLine = nil }
nbLog("SessionStart \(isExternalAgent ? agentId : projectName) (\(sessionId.prefix(8)))")
NotificationCenter.default.post(name: .checkMondayRecap, object: nil)
if state.isPresent { expandIfNeeded(to: .overview) }
@@ -578,17 +696,18 @@ final class HookServer: @unchecked Sendable {
if agentId == "agent_hermes", let platform = payload["platform"] as? String,
!platform.isEmpty, platform != "cli" {
let capitalized = platform.prefix(1).uppercased() + platform.dropFirst()
- appendStep(id: agentId, step: String(capitalized))
+ step(String(capitalized))
}
case "UserPromptSubmit":
activeSessionId = sessionId
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 {
- appendStep(id: agentId, step: String(prompt.prefix(60)))
+ note {
+ $0.state = .thinking
+ $0.finalLine = nil
+ $0.endedAt = nil
+ if let prompt = payload["prompt"] as? String, !prompt.isEmpty { $0.appendStep(String(prompt.prefix(60))) }
}
RecapStore.shared.userPromptSubmit(sessionId: recapSessionId, pillId: agentId, project: projectName)
NotificationCenter.default.post(name: .checkMondayRecap, object: nil)
@@ -597,7 +716,7 @@ final class HookServer: @unchecked Sendable {
case "PreToolUse":
activeSessionId = sessionId
let tool = payload["tool_name"] as? String ?? "Tool"
- if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) { state.tasks[idx].finalLine = nil }
+ note { $0.finalLine = nil }
RecapStore.shared.preToolUse(sessionId: recapSessionId, tool: tool)
// AskUserQuestion is handled via the dedicated --ask hook.
// Skip state/step update here to avoid flickering over the question card.
@@ -605,10 +724,13 @@ final class HookServer: @unchecked Sendable {
upsertTask(pill: agentId, display: display, working: true,
externalAgent: isExternalAgent ? validAgent : nil)
let isQuestion = tool == "ask_question" || tool.hasSuffix(":ask_question")
- state.updateTask(id: agentId, state: isQuestion ? .question : .working)
let input = payload["tool_input"] as? [String: Any] ?? [:]
- let step = localizedStep(tool: tool, input: input)
- appendStep(id: agentId, step: step)
+ let label = localizedStep(tool: tool, input: input)
+ note {
+ $0.state = isQuestion ? .question : .working
+ $0.endedAt = nil
+ $0.appendStep(label)
+ }
if isQuestion {
SoundEngine.shared.play("question")
if state.isPresent { expandIfNeeded(to: .overview) }
@@ -617,105 +739,117 @@ final class HookServer: @unchecked Sendable {
case "PostToolUse":
sessions.note(pill: agentId, display: display, working: true)
- state.updateTask(id: agentId, state: .working)
+ note { $0.state = .working }
// Live diff for Edit / MultiEdit / Write
let diffTool = payload["tool_name"] as? String ?? ""
let diffInput = payload["tool_input"] as? [String: Any] ?? [:]
if let diff = buildFileDiff(tool: diffTool, input: diffInput, pillId: agentId) {
let idx = state.appendSessionDiff(diff, for: agentId)
- let step = String.makeDiffStep(filename: diff.name, added: diff.added, removed: diff.removed, diffId: idx)
- appendStep(id: agentId, step: step)
+ step(String.makeDiffStep(filename: diff.name, added: diff.added, removed: diff.removed, diffId: idx))
RecapStore.shared.recordFileDiff(sessionId: recapSessionId, path: diff.name, added: diff.added, removed: diff.removed)
}
case "PostToolUseFailure":
sessions.note(pill: agentId, display: display, working: true)
- state.updateTask(id: agentId, state: .working)
- appendStep(id: agentId, step: "⚠ failed")
+ note {
+ $0.state = .working
+ $0.appendStep("⚠ failed")
+ }
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") {
- state.updateTask(id: agentId, state: .ratelimit)
+ note { $0.state = .ratelimit }
SoundEngine.shared.play("rate")
} else if message.hasSuffix("?") {
- state.updateTask(id: agentId, state: .question)
- appendStep(id: agentId, step: message)
+ note {
+ $0.state = .question
+ $0.appendStep(message)
+ }
}
case "Stop":
- let scope = sessions.endTurn(pill: agentId, session: sessionId)
- // A turn ending can hand the name to a sibling session that is still working.
- applyDisplayOwner(pill: agentId)
+ // Each session finishes on its own: its sound, its "finished", its last message,
+ // even while a sibling behind the same pill is still working. For a moment the pill
+ // shows the session that finished (SessionBoard.finishMoment), then the busy one again.
+ _ = sessions.endTurn(pill: agentId, session: sessionId)
let rawFinal = (payload["last_assistant_message"] as? String)
?? (payload["message"] as? String) ?? ""
let finalText = DiffEngine.toOneLine(rawFinal)
- // The step log is shared, so the conclusion is worth showing either way.
- if !finalText.isEmpty { appendStep(id: agentId, step: finalText) }
- RecapStore.shared.stop(sessionId: recapSessionId)
- // 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
+ note {
+ $0.state = .finished
+ $0.endedAt = now
+ if !finalText.isEmpty {
+ $0.finalLine = finalText
+ $0.appendStep(finalText)
+ }
}
+ RecapStore.shared.stop(sessionId: recapSessionId)
+ let working = sessions.workingCount(pill: agentId)
+ if working > 0 { nbLog("Stop \(sessionId.prefix(8)) — \(working) other session(s) still working on \(agentId)") }
+ syncPill(agentId)
+ let finished = board.poppedPill(pill: agentId, session: key) ?? agentId
if !terminalInFront { SoundEngine.shared.play("finish") }
- if !terminalInFront && showsAlert(for: agentId, focused: focused) {
+ if !terminalInFront && showsAlert(for: finished, focused: state.focusId == finished) {
expandIfNeeded(to: .finished)
} else {
- setPillBadge(id: agentId, badge: .finished)
+ setPillBadge(id: finished, badge: .finished)
}
- DispatchQueue.main.asyncAfter(deadline: .now() + 5.2) {
- // A session (this one or a sibling) may have started a new turn meanwhile.
+ DispatchQueue.main.asyncAfter(deadline: .now() + SessionBoard.finishMoment) {
+ // The session (or a sibling) may have started a new turn meanwhile.
+ self.board.amend(pill: agentId, session: key) { if $0.state == .finished && $0.endedAt == now { $0.state = .idle } }
+ self.syncPill(agentId)
guard self.sessions.workingCount(pill: agentId) == 0 else { return }
if isExternalAgent {
AppState.shared.removeTask(id: agentId)
} else {
- AppState.shared.updateTask(id: agentId, state: .idle)
self.clearPillBadge(id: agentId)
}
}
case "StopFailure":
RecapStore.shared.stop(sessionId: recapSessionId)
- let failScope = sessions.endTurn(pill: agentId, session: sessionId)
- applyDisplayOwner(pill: agentId)
- guard failScope == .pill else { break }
+ _ = sessions.endTurn(pill: agentId, session: sessionId)
nbLog("StopFailure \(sessionId.prefix(8)) — \(payload.keys.sorted().joined(separator: ", ")): \(Self.stopFailureDetail(payload) ?? "no detail")")
- state.updateTask(id: agentId, state: .error)
// The error view shows what went wrong (finalLine), not the last thing said before it.
- if let idx = state.tasks.firstIndex(where: { $0.id == agentId }) {
- state.tasks[idx].finalLine = Self.stopFailureDetail(payload)
+ note {
+ $0.state = .error
+ $0.endedAt = now
+ $0.finalLine = Self.stopFailureDetail(payload)
}
+ syncPill(agentId)
+ let failed = board.poppedPill(pill: agentId, session: key) ?? agentId
if !terminalInFront { SoundEngine.shared.play("error") }
- if !terminalInFront && showsAlert(for: agentId, focused: focused) {
+ if !terminalInFront && showsAlert(for: failed, focused: state.focusId == failed) {
expandIfNeeded(to: .error)
} else {
- setPillBadge(id: agentId, badge: .error)
+ setPillBadge(id: failed, badge: .error)
}
+ // After the error moment a sibling's work takes the pill again.
+ DispatchQueue.main.asyncAfter(deadline: .now() + SessionBoard.errorMoment + 0.1) { self.syncPill(agentId) }
case "Interrupt":
// Codex: user stopped the turn
RecapStore.shared.stop(sessionId: recapSessionId)
let interruptScope = sessions.endTurn(pill: agentId, session: sessionId)
- applyDisplayOwner(pill: agentId)
+ note { $0.state = .idle }
guard interruptScope == .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.
+ // A popped-out session that ends takes its own pill down; the client's pill goes
+ // only with the last session behind it.
+ if let popped = board.remove(pill: agentId, session: key),
+ state.tasks.contains(where: { $0.id == popped }) {
+ if state.focusId == popped { state.focusId = agentId }
+ withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { state.removeTask(id: popped) }
+ }
guard sessions.endSession(pill: agentId, session: sessionId) == .pill else {
RecapStore.shared.sessionEnd(sessionId: recapSessionId)
nbLog("SessionEnd \(sessionId.prefix(8)) — \(sessions.liveCount(pill: agentId)) session(s) left on \(agentId)")
- applyDisplayOwner(pill: agentId)
break
}
activeSessionId = nil
@@ -725,10 +859,10 @@ final class HookServer: @unchecked Sendable {
RecapStore.shared.sessionEnd(sessionId: recapSessionId)
case "SubagentStart":
- appendStep(id: agentId, step: "+ subagent")
+ step("+ subagent")
case "SubagentStop":
- appendStep(id: agentId, step: "• subagent done")
+ step("• subagent done")
default:
break
@@ -941,10 +1075,16 @@ final class HookServer: @unchecked Sendable {
// 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,
+ // A session that shares its pill with another pops out into a pill of its own while
+ // it waits (SessionBoard), so the request shows under its own title.
+ var entry = QueuedApproval(id: UUID(), fd: fd, sessionId: sessionId, pillId: pillId,
projectName: projectName, cwd: cwd, tool: tool,
command: command, inputKey: inputKey,
hostApp: terminalHost?.bundleId, bundleId: bundleId)
+ if approvals.count < ApprovalQueue.maxPending {
+ entry.shownPill = popOutIfShared(pill: pillId, session: Self.boardKey(sessionId, pill: pillId, cwd: cwd),
+ raw: sessionId, title: projectName)
+ }
guard approvals.enqueue(entry) == .accepted else {
nbLog("PermissionRequest \(tool): \(ApprovalQueue.maxPending) already waiting, asked in the terminal")
Task.detached { [weak self] in
@@ -960,13 +1100,13 @@ final class HookServer: @unchecked Sendable {
cwd: cwd, hostApp: terminalHost?.bundleId,
bundleId: bundleId),
working: true, externalAgent: nil)
- state.updateTask(id: pillId, state: .approval)
+ syncPill(pillId)
SoundEngine.shared.play("approval")
// 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 capturedPillId = entry.displayPill
let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: .main)
source.setEventHandler { [weak self] in
guard let self, self.approvals.contains(id: entryId) else { return }
@@ -1090,9 +1230,15 @@ final class HookServer: @unchecked Sendable {
// Several sessions can wait on a question at once: they queue, the card shows the
// oldest, and each answer goes back to the session that asked. A session asking again
// replaces its own older question; past the cap, the newest goes back to its terminal.
- let entry = QueuedQuestion(id: UUID(), fd: fd,
- sessionId: (sessionId == "unknown" || sessionId.isEmpty) ? "\(pillId)+\(cwd)" : sessionId,
+ // A session that shares its pill with another pops out into a pill of its own while
+ // it waits (SessionBoard), so the question shows under its own title.
+ let key = Self.boardKey(sessionId, pill: pillId, cwd: cwd)
+ var entry = QueuedQuestion(id: UUID(), fd: fd, sessionId: key,
pillId: pillId, projectName: projectName, cwd: cwd, question: parsed)
+ if questions.count < QuestionQueue.maxPending
+ || questions.entries.contains(where: { $0.sessionId == key && $0.pillId == pillId }) {
+ entry.shownPill = popOutIfShared(pill: pillId, session: key, raw: sessionId, title: projectName)
+ }
switch questions.enqueue(entry) {
case .rejectedFull:
nbLog("Question: \(QuestionQueue.maxPending) already waiting, asked in the terminal")
@@ -1118,7 +1264,7 @@ final class HookServer: @unchecked Sendable {
cwd: cwd, hostApp: terminalHost?.bundleId,
bundleId: bundleId),
working: true, externalAgent: nil)
- state.updateTask(id: pillId, state: .question)
+ syncPill(pillId)
SoundEngine.shared.play("approval")
// Monitor fd: if the agent closes the connection (stopped or answered in its own UI),
@@ -1164,20 +1310,6 @@ final class HookServer: @unchecked Sendable {
}
}
- /// Writes the pill's name, cwd and terminal 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 }
- let state = AppState.shared
- state.tasks[idx].name = owner.projectName
- if !owner.cwd.isEmpty { state.tasks[idx].sessionCwd = owner.cwd }
- if PillCatalog.basePillId(pill) == "integration_claude" { state.tasks[idx].hostApp = owner.hostApp }
- if !owner.bundleId.isEmpty { state.tasks[idx].sessionBundleId = owner.bundleId }
- }
-
/// Updates or transiently creates a workspace pill (VS Code or Cursor) task, or a session's
/// own pill. If the task already exists (persistent), just updates name/cwd.
/// If missing (transient), creates it and inserts after the main pill (a session's own
@@ -1232,15 +1364,6 @@ final class HookServer: @unchecked Sendable {
state.tasks[idx].pillBadge = nil
}
- @MainActor
- private func appendStep(id: String, step: String) {
- let state = AppState.shared
- guard let idx = state.tasks.firstIndex(where: { $0.id == id }) else { return }
- state.tasks[idx].steps.append(step)
- if state.tasks[idx].steps.count > 20 { state.tasks[idx].steps.removeFirst() }
- state.tasks[idx].stepIndex = state.tasks[idx].steps.count - 1
- }
-
// MARK: - Project name alias mapping
/// The pill's name: the session's /rename title, else the folder the session started
diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swift
index 3d6120d2..0aeb22cd 100644
--- a/NotchBuddy/Sources/App/IslandViewContent.swift
+++ b/NotchBuddy/Sources/App/IslandViewContent.swift
@@ -154,7 +154,7 @@ struct OverviewView: View {
// Diff overlay — replaces ticker when a diff step is tapped
if let diffId = activeDiffId,
let task = agent,
- let diff = state.sessionDiffs[task.id]?.first(where: { $0.id == diffId }) {
+ let diff = state.sessionDiffs[task.pill]?.first(where: { $0.id == diffId }) {
CardBackground(wash: nil)
DiffCardView(diff: diff, onDismiss: { activeDiffId = nil })
.transition(.opacity)
@@ -214,7 +214,7 @@ struct OverviewView: View {
withAnimation(.easeIn(duration: 0.16)) { activeDiffId = nil }
_ = id
} else if let task = state.focusTask,
- let last = state.sessionDiffs[task.id]?.last {
+ let last = state.sessionDiffs[task.pill]?.last {
withAnimation(.easeIn(duration: 0.16)) { activeDiffId = last.id }
}
}
@@ -441,7 +441,7 @@ struct QuestionView: View {
/// With questions from several sessions waiting, the pill named after the session that asks.
private var asker: AgentTask? {
guard state.waitingQuestions.count > 1, let head = state.waitingQuestions.first,
- var task = state.tasks.first(where: { $0.id == head.pillId }) else { return nil }
+ var task = state.tasks.first(where: { $0.id == head.displayPill }) else { return nil }
if !head.projectName.isEmpty { task.name = head.projectName }
return task
}
diff --git a/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift b/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift
index 75271eb9..34c1c2e6 100644
--- a/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift
+++ b/NotchBuddy/Sources/App/PhoneLink/SessionPublisher.swift
@@ -183,9 +183,10 @@ struct SessionSnapshot: Equatable {
// Services (Stripe, GitHub…) go through ServicePublisher, with their data.
for task in tasks where task.source != .n8n && PillCatalog.isSession(task.id) {
let hasApproval = approval?.pillId == task.id
- // The pill's record carries the first question behind it, as it always has.
+ // The pill's record carries the first question behind it, as it always has; a
+ // session popped out of its pill (SessionBoard) has its own pill, and record.
let question = task.state == .question
- ? questions.first(where: { $0.pillId == task.id && $0.slot == 1 })?.question
+ ? questions.first(where: { $0.phoneRecordId == task.id })?.question
: nil
let questionText = question?.questions.map(\.question).joined(separator: "\n") ?? ""
let payload = question.map(QuestionPayload.init(ask:))
@@ -206,7 +207,7 @@ struct SessionSnapshot: Equatable {
questionFingerprint: payload?.fingerprint ?? "")
// Questions from other sessions behind the same pill get a record of their own
// ("<pill>#q2"…), so each one shows up and is answered on its own.
- for entry in questions where entry.pillId == task.id && entry.slot > 1 {
+ for entry in questions where entry.pillId == task.id && entry.shownPill == nil && entry.slot > 1 {
let payload = QuestionPayload(ask: entry.question)
result[entry.phoneRecordId] = SessionSnapshot(
pillId: entry.phoneRecordId,
diff --git a/NotchBuddy/Sources/App/PillSessionRegistry.swift b/NotchBuddy/Sources/App/PillSessionRegistry.swift
index 2a5aea7e..c1c15718 100644
--- a/NotchBuddy/Sources/App/PillSessionRegistry.swift
+++ b/NotchBuddy/Sources/App/PillSessionRegistry.swift
@@ -148,6 +148,13 @@ struct PillSessionRegistry {
return owner.session == session
}
+ /// What `session` shows behind `pill`: its project name, cwd and terminal. nil if not live there.
+ func display(pill: String, session: String) -> Display? {
+ guard let s = pills[pill]?.sessions[session] else { return nil }
+ return Display(session: session, projectName: s.projectName, cwd: s.cwd,
+ hostApp: s.hostApp, bundleId: s.bundleId)
+ }
+
func liveCount(pill: String) -> Int { pills[pill]?.order.count ?? 0 }
func workingCount(pill: String) -> Int {
diff --git a/NotchBuddy/Sources/App/QuestionQueue.swift b/NotchBuddy/Sources/App/QuestionQueue.swift
index a1201cb5..eb4edee6 100644
--- a/NotchBuddy/Sources/App/QuestionQueue.swift
+++ b/NotchBuddy/Sources/App/QuestionQueue.swift
@@ -22,12 +22,18 @@ struct QueuedQuestion: Equatable, Sendable {
var slot: Int = 1
/// When the question arrived (answers sent before it are not for it).
var received = Date()
+ /// The pill the question shows on when its session popped out of `pillId` (SessionBoard),
+ /// nil when it shows on `pillId` itself.
+ var shownPill: String? = nil
- /// The iPhone record that shows this question: the pill's own for the first question
- /// behind a pill, "<pill>#q<slot>" for the others, so each session's question is answered
- /// on its own (a session's own pill is "<pill>#<n>": the two never meet). The iPhone sends
- /// this id back with its answer.
- var phoneRecordId: String { slot == 1 ? pillId : "\(pillId)#q\(slot)" }
+ /// Where the card and the focus find the question.
+ var displayPill: String { shownPill ?? pillId }
+
+ /// The iPhone record that shows this question: the popped-out pill's own when its session
+ /// popped out, else the pill's own for the first question behind a pill, "<pill>#q<slot>"
+ /// for the others, so each session's question is answered on its own (a popped-out pill is
+ /// "<pill>#<n>": the two never meet). The iPhone sends this id back with its answer.
+ var phoneRecordId: String { shownPill ?? (slot == 1 ? pillId : "\(pillId)#q\(slot)") }
}
struct QuestionQueue: Sendable {
@@ -68,7 +74,8 @@ struct QuestionQueue: Sendable {
return .accepted(replaced: replaced)
}
guard entries.count < maxPending else { return .rejectedFull }
- let taken = Set(entries.filter { $0.pillId == entry.pillId }.map(\.slot))
+ // A popped-out question has its pill's record: the slots count the others only.
+ let taken = Set(entries.filter { $0.pillId == entry.pillId && $0.shownPill == nil }.map(\.slot))
entry.slot = (1...).first { !taken.contains($0) }!
entries.append(entry)
return .accepted(replaced: nil)
diff --git a/NotchBuddy/Sources/CoucouKit/IslandTypes.swift b/NotchBuddy/Sources/CoucouKit/IslandTypes.swift
index 04124796..85b45b35 100644
--- a/NotchBuddy/Sources/CoucouKit/IslandTypes.swift
+++ b/NotchBuddy/Sources/CoucouKit/IslandTypes.swift
@@ -84,12 +84,24 @@ struct AgentTask: Identifiable, Equatable {
var sessionBundleId: String? = nil // app the session runs in (hook bundle_id), for "Open terminal"
var finalLine: String? = nil // last assistant message shown as static text after Stop
var hostApp: String? = nil // bundle id of the terminal running a Claude Code session; nil = VS Code
+ /// The sessions sharing this pill, for the open card; empty while one session (or none) is behind it.
+ var sessionLines: [SessionLine] = []
/// The client pill this task belongs to: its id, or for a session's own pill
/// ("integration_claude#2") the pill of its client. Compare this, not `id`, to a pill ID.
var pill: String { PillCatalog.basePillId(id) }
}
+/// One of several sessions behind a pill, as the open card lists them.
+struct SessionLine: Identifiable, Equatable {
+ var id: String
+ var title: String
+ var state: BotState
+ var lastStep: String
+ /// The session the pill shows (its name, steps and state are the pill's).
+ var isShown: Bool
+}
+
enum AgentSource: Equatable {
case claudeCode
case n8n
diff --git a/tests/QuestionQueueTests.swift b/tests/QuestionQueueTests.swift
index 17055cd1..087835c8 100644
--- a/tests/QuestionQueueTests.swift
+++ b/tests/QuestionQueueTests.swift
@@ -98,6 +98,21 @@ enum QuestionQueueTests {
precondition(answered("Same?", "integration_claude") == nil) // answered already
precondition(answered("Same?", "integration_claude#q2") == s2.id)
+ // A question whose session popped out of its pill shows on (and is answered from) that
+ // pill's record; the slots count the other questions only
+ var out = QuestionQueue()
+ var popped = entry(10, session: "p1")
+ popped.shownPill = "integration_claude#2"
+ _ = out.enqueue(popped)
+ let inside = entry(11, session: "p2")
+ _ = out.enqueue(inside)
+ precondition(out.entry(id: popped.id)?.phoneRecordId == "integration_claude#2")
+ precondition(out.entry(id: popped.id)?.displayPill == "integration_claude#2")
+ precondition(out.entry(id: inside.id)?.phoneRecordId == "integration_claude")
+ precondition(out.entry(id: inside.id)?.displayPill == "integration_claude")
+ precondition(QuestionQueue.question(answering: "q10", onRecord: "integration_claude#2", in: out.entries,
+ fingerprintOf: { $0.questions.map(\.question).joined() })?.id == popped.id)
+
print("QuestionQueue tests: all passed")
}
}