Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Resources/Localizable.xcstrings
Original file line number Diff line number Diff line change
Expand Up @@ -149479,6 +149479,23 @@
}
}
},
"feed.status.needsInput": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Needs input"
}
},
"ja": {
"stringUnit": {
"state": "translated",
"value": "入力待ち"
}
}
}
},
"feed.badge.allowed": {
"extractionState": "manual",
"localizations": {
Expand Down
258 changes: 258 additions & 0 deletions Sources/Feed/FeedCoordinator.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import AppKit
import Bonsplit
import CMUXWorkstream
import Foundation
@preconcurrency import UserNotifications
Expand Down Expand Up @@ -37,6 +38,14 @@ final class FeedCoordinator: @unchecked Sendable {
label: "cmux.feed.pidWatcher", qos: .utility
)

/// Number of in-flight blocking decisions whose needs-input overlay is
/// currently lit, keyed by ``AttentionTarget``. The overlay is cleared
/// only when the last overlapping decision for a target concludes, so two
/// simultaneous decisions on the same panel can't clear each other's
/// badge. Main-actor isolated: read/written only from the `@MainActor`
/// attention methods.
@MainActor private var pendingAttentionCounts: [AttentionTarget: Int] = [:]

private init() {}

/// Must be called once at app launch to install the store.
Expand Down Expand Up @@ -118,6 +127,20 @@ final class FeedCoordinator: @unchecked Sendable {
if let ppid = event.ppid, ppid > 0 {
FeedCoordinator.shared.armPidWatcher(ppid: ppid)
}
// Surface in-app attention (needs-input status + bell +
// workspace elevation) for the blocking decision. This fires
// regardless of app focus, unlike the desktop banner below,
// so the pending decision is visible in the sidebar even
// while the user is in another workspace of the same window.
// The target is recorded on the waiter here — inside the
// ingest `main.sync`, before the card can render and a reply
// can fire — so the overlay is cleared exactly once when the
// decision concludes (no race with `deliverReply`).
if let target = FeedCoordinator.shared.surfaceBlockingDecisionAttention(event: event) {
FeedCoordinator.shared.waiterLock.lock()
FeedCoordinator.shared.waiters[requestId]?.attentionTarget = target
FeedCoordinator.shared.waiterLock.unlock()
}
Comment thread
austinywang marked this conversation as resolved.
Resolved
#if DEBUG
FeedCoordinatorTestHooks.afterBlockingEventIngested?(event, requestId)
#endif
Expand All @@ -139,28 +162,53 @@ final class FeedCoordinator: @unchecked Sendable {
switch waitResult {
case .success:
if let decision = w?.decision {
// `deliverReply` concludes the attention overlay on resolve.
return .resolved(itemId: itemIdSlot.value, decision: decision)
}
cancelNotification(requestId: requestId)
concludeAttentionOnMain(w?.attentionTarget)
expireTimedOutItem(itemIdSlot.value)
return .timedOut(itemId: itemIdSlot.value)
case .timedOut:
cancelNotification(requestId: requestId)
concludeAttentionOnMain(w?.attentionTarget)
expireTimedOutItem(itemIdSlot.value)
return .timedOut(itemId: itemIdSlot.value)
}
}

/// Concludes an attention overlay (if any) on the main actor, hopping if
/// called from the socket worker thread.
private func concludeAttentionOnMain(_ target: AttentionTarget?) {
guard let target else { return }
let conclude: @Sendable () -> Void = { [target] in
MainActor.assumeIsolated {
FeedCoordinator.shared.concludeBlockingDecisionAttention(target)
}
}
if Thread.isMainThread {
conclude()
} else {
DispatchQueue.main.async(execute: conclude)
}
}

/// Called by the `feed.*.reply` handlers. Marks the corresponding
/// item resolved on the main-actor store and wakes any waiter.
func deliverReply(requestId: String, decision: WorkstreamDecision) {
waiterLock.lock()
let attentionTarget = waiters[requestId]?.attentionTarget
if let waiter = waiters[requestId] {
waiter.decision = decision
waiter.semaphore.signal()
}
waiterLock.unlock()

// The user decided: conclude the needs-input overlay so the agent's
// running/idle state shows through (refcounted so an overlapping
// decision on the same panel keeps it lit until it too concludes).
concludeAttentionOnMain(attentionTarget)

let resolve: @Sendable () -> Void = { [requestId, decision] in
MainActor.assumeIsolated {
let store = FeedCoordinator.shared.store
Expand Down Expand Up @@ -226,9 +274,214 @@ final class FeedCoordinator: @unchecked Sendable {
}
}

// MARK: - In-app attention surfacing

extension FeedCoordinator {
/// The blocking-decision hook events that warrant pulling the user's
/// attention to the owning workspace: a tool permission, a plan
/// approval, or a question. Keeping this as one predicate (rather than
/// branching per event at each call site) is what makes the attention
/// surface uniform across every event type and agent routed through
/// `feed.push` — a new blocking event type only has to be added here.
static func isBlockingDecisionEvent(_ hookEventName: WorkstreamEvent.HookEventName) -> Bool {
switch hookEventName {
case .permissionRequest, .exitPlanMode, .askUserQuestion:
return true
default:
return false
}
}

/// Maps a feed `source` (agent id) to the agent-lifecycle status key the
/// sidebar reads. Claude reports under `claude_code`; every other agent
/// keys its status by its own source name. Returning the agent's own key
/// is what lets the existing per-agent resume hooks (e.g. Claude's
/// `pre-tool-use`) clear the needs-input badge once the agent continues.
static func lifecycleStatusKey(forSource source: String) -> String {
source == "claude" ? "claude_code" : source
}
Comment thread
austinywang marked this conversation as resolved.
Resolved

/// Identifies the sidebar slot an attention overlay lights up. Overlays
/// are refcounted by this key so overlapping blocking decisions on the
/// same agent/panel don't clear each other's needs-input badge.
struct AttentionTarget: Hashable, Sendable {
let workspaceId: UUID
let panelId: UUID?
let statusKey: String
}

/// The localized "Needs input" sidebar status the overlay sets. Exposed so
/// ``concludeBlockingDecisionAttention(_:)`` can confirm it's still the
/// value we wrote before clearing it (rather than one an agent hook
/// replaced in the meantime).
static var needsInputStatusValue: String {
String(localized: "feed.status.needsInput", defaultValue: "Needs input")
}

/// Surfaces in-app attention for a blocking feed decision: flips the
/// owning workspace's agent lifecycle to `.needsInput`, sets the
/// "Needs input" sidebar status, elevates the workspace when
/// *Reorder on Notification* is enabled, and rings the bell.
///
/// This is the convergence point the PreToolUse→PermissionRequest
/// migration left behind: the `feed.push` bridge ingested the card and
/// (when inactive) posted a banner, but never drove the same in-app
/// attention path the `cmux hooks <agent> notification` hook uses. Doing
/// it here — once, for every blocking decision — keeps a new event type
/// from silently swallowing.
///
/// The overlay is cleared by ``concludeBlockingDecisionAttention(_:)``
/// when the decision resolves or times out. Clearing is refcounted per
/// ``AttentionTarget`` so overlapping decisions on the same panel keep the
/// badge lit until the last one concludes.
///
/// - Returns: the target to conclude once the decision ends, or `nil` if
/// nothing was surfaced (no resolvable workspace).
@MainActor
func surfaceBlockingDecisionAttention(event: WorkstreamEvent) -> AttentionTarget? {
guard Self.isBlockingDecisionEvent(event.hookEventName) else { return nil }

#if DEBUG
if let observer = FeedCoordinatorTestHooks.attentionSurfaceObserver {
observer(event)
return nil
}
#endif

guard let resolved = Self.resolveAttentionTarget(event: event),
let tabManager = AppDelegate.shared?.tabManagerFor(tabId: resolved.workspaceId),
let tab = tabManager.tabs.first(where: { $0.id == resolved.workspaceId })
else {
#if DEBUG
cmuxDebugLog(
"feed.attention.skip session=\(event.sessionId) hook=\(event.hookEventName.rawValue) workspace=\(event.workspaceId ?? "nil")"
)
#endif
return nil
}

let panelId = Self.resolvePanelId(surfaceId: resolved.surfaceId, tab: tab) ?? tab.focusedPanelId
let statusKey = Self.lifecycleStatusKey(forSource: event.source)
let target = AttentionTarget(
workspaceId: resolved.workspaceId,
panelId: panelId,
statusKey: statusKey
)
pendingAttentionCounts[target, default: 0] += 1

// Needs-input lifecycle drives the sidebar badge + hibernation state.
tab.setAgentLifecycle(key: statusKey, panelId: panelId, lifecycle: .needsInput)
tab.statusEntries[statusKey] = SidebarStatusEntry(
key: statusKey,
value: Self.needsInputStatusValue,
icon: "bell.fill",
color: "#4C8DFF",
timestamp: Date()
)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

// Elevate the workspace so it floats to the top of the sidebar,
// honoring the user's Reorder on Notification preference.
if WorkspaceAutoReorderSettings.isEnabled() {
tabManager.moveTabToTopForNotification(resolved.workspaceId)
}

// Ring the bell (dock bounce while the app is in the background).
NSApp.requestUserAttention(.informationalRequest)

return target
}

/// Concludes a blocking decision's attention overlay. Decrements the
/// per-target refcount and, when it reaches zero, clears the needs-input
/// overlay — but only the parts the feed still owns: the lifecycle is set
/// to `.running` only if it's still `.needsInput`, and the status entry is
/// removed only if it still holds our "Needs input" value. Anything an
/// agent hook replaced in the meantime is left untouched, so a real
/// running/idle/needs-input update from the agent always wins.
@MainActor
func concludeBlockingDecisionAttention(_ target: AttentionTarget) {
guard let count = pendingAttentionCounts[target] else { return }
if count > 1 {
pendingAttentionCounts[target] = count - 1
return
}
pendingAttentionCounts.removeValue(forKey: target)

guard let tabManager = AppDelegate.shared?.tabManagerFor(tabId: target.workspaceId),
let tab = tabManager.tabs.first(where: { $0.id == target.workspaceId })
else { return }
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

// Lifecycle is per-panel, so clearing this panel's needs-input is
// safe even if another panel still needs input.
if let panelId = target.panelId,
tab.agentLifecycleStatesByPanelId[panelId]?[target.statusKey] == .needsInput {
tab.setAgentLifecycle(key: target.statusKey, panelId: panelId, lifecycle: .running)
}

// The status entry is workspace-level (keyed only by statusKey), so it
// is shared across panels running the same agent. Only remove it once
// no other panel in this workspace still has a pending decision under
// the same key — otherwise concluding one panel would wipe another
// panel's active "Needs input" badge.
let anotherPanelStillPending = pendingAttentionCounts.keys.contains {
$0.workspaceId == target.workspaceId && $0.statusKey == target.statusKey
}
if !anotherPanelStillPending,
tab.statusEntries[target.statusKey]?.value == Self.needsInputStatusValue {
tab.statusEntries.removeValue(forKey: target.statusKey)
}
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

/// Resolves the `(workspace, surface)` an attention overlay should target.
/// The workspace prefers the event's live `workspace_id` (the running
/// terminal's CMUX_WORKSPACE_ID, a raw UUID) so a stale hook-session map
/// can't redirect attention to the wrong workspace; it falls back to the
/// session store when the event omits a parseable id. The surface comes
/// from the session store only when its workspace matches the resolved
/// workspace, so a stale entry can't point the panel elsewhere.
private static func resolveAttentionTarget(
event: WorkstreamEvent
) -> (workspaceId: UUID, surfaceId: UUID?)? {
let sessionMatch: (workspaceId: UUID, surfaceId: UUID?)? = {
guard let parsed = FeedJumpResolver.parse(event.sessionId),
let resolved = FeedJumpResolver.lookup(agent: parsed.agent, sessionId: parsed.sessionId),
let workspaceId = UUID(uuidString: resolved.workspaceId)
else { return nil }
return (workspaceId, UUID(uuidString: resolved.surfaceId))
}()

let eventWorkspaceId = event.workspaceId.flatMap {
UUID(uuidString: $0.trimmingCharacters(in: .whitespacesAndNewlines))
}

guard let workspaceId = eventWorkspaceId ?? sessionMatch?.workspaceId else {
return nil
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
// Only trust the session store's surface if it belongs to the
// workspace we're actually targeting.
let surfaceId = (sessionMatch?.workspaceId == workspaceId) ? sessionMatch?.surfaceId : nil
return (workspaceId, surfaceId)
}

/// Maps a surface id from the hook-session store to its owning panel id,
/// tolerating stores that already record the panel id directly.
@MainActor
private static func resolvePanelId(surfaceId: UUID?, tab: Workspace) -> UUID? {
guard let surfaceId else { return nil }
if tab.panels[surfaceId] != nil { return surfaceId }
return tab.panelIdFromSurfaceId(TabID(uuid: surfaceId))
}
}

private final class PendingWaiter: @unchecked Sendable {
let semaphore: DispatchSemaphore
var decision: WorkstreamDecision?
/// The attention overlay target for this decision, if one was surfaced.
/// Set inside the ingest `main.sync` (before the card can render and a
/// reply can fire) and read when the decision concludes, so the
/// needs-input overlay is cleared exactly once. Guarded by
/// `FeedCoordinator.waiterLock`.
var attentionTarget: FeedCoordinator.AttentionTarget?

init(semaphore: DispatchSemaphore) {
self.semaphore = semaphore
Expand All @@ -251,6 +504,11 @@ enum FeedCoordinatorTestHooks {
static var afterBlockingEventIngested: (@Sendable (WorkstreamEvent, String) -> Void)?
static var isAppActiveOverride: (@Sendable () -> Bool)?
static var notificationPostObserver: (@Sendable (WorkstreamEvent, String) -> Void)?
/// Fires when a blocking decision event requests in-app attention
/// surfacing (needs-input status + bell + elevation). When set, the
/// production surfacing is short-circuited so tests can assert the
/// request without a live `TabManager`.
static var attentionSurfaceObserver: (@Sendable (WorkstreamEvent) -> Void)?
}
#endif

Expand Down
Loading
Loading