diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 4c008a5c2c38..5b691ef904fb 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -1,15 +1,15 @@ # cmux-owned Swift file length budget. # Format: max_linesrelative path # Reduce counts as files shrink. CI fails if tracked files exceed this budget. -32733 CLI/cmux.swift -22098 Sources/TerminalController.swift +32752 CLI/cmux.swift +22161 Sources/TerminalController.swift 19955 Sources/Workspace.swift -19251 Sources/ContentView.swift +19245 Sources/ContentView.swift 18044 Sources/AppDelegate.swift 16539 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift 11916 cmuxTests/AppDelegateShortcutRoutingTests.swift -9939 Sources/TabManager.swift +9946 Sources/TabManager.swift 8494 cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift 7737 Sources/Panels/BrowserPanelView.swift 7198 cmuxTests/WorkspaceUnitTests.swift @@ -36,15 +36,15 @@ 2877 Sources/SessionIndexView.swift 2871 cmuxTests/CMUXOpenCommandTests.swift 2654 Sources/Panels/CmuxWebView.swift +2580 Sources/TerminalNotificationStore.swift 2545 cmuxTests/WorkspaceManualUnreadTests.swift 2513 cmuxTests/CommandPaletteSearchEngineTests.swift 2509 Sources/KeyboardShortcutSettings.swift -2378 Sources/TerminalNotificationStore.swift 2327 cmuxTests/CJKIMEInputTests.swift 2290 Sources/FileExplorerView.swift 2260 Sources/TerminalWindowPortal.swift 2208 Sources/Mobile/MobileHostService.swift -2138 Sources/SessionPersistence.swift +2144 Sources/SessionPersistence.swift 2123 cmuxTests/ShortcutAndCommandPaletteTests.swift 2117 cmuxTests/CmuxConfigTests.swift 1996 Sources/KeyboardShortcutSettingsFileStore.swift @@ -61,6 +61,7 @@ 1560 cmuxTests/TextBoxMentionCompletionTests.swift 1498 cmuxTests/OmnibarAndToolsTests.swift 1496 cmuxUITests/MultiWindowNotificationsUITests.swift +1466 cmuxTests/TerminalNotificationClearAllTests.swift 1450 Sources/FileExplorerStore.swift 1410 Sources/CommandPalette/CommandPaletteSearch.swift 1380 cmuxUITests/MenuKeyEquivalentRoutingUITests.swift @@ -68,18 +69,18 @@ 1372 cmuxTests/AppDelegateIssue2907RoutingTests.swift 1365 Sources/Feed/FeedButtonStyleDebugWindowController.swift 1362 Sources/CMUXInstalledExtensionSidebarHostView.swift +1328 Sources/Feed/FeedCoordinator.swift 1313 cmuxTests/MobileHostAuthorizationTests.swift 1285 cmuxUITests/SidebarHelpMenuUITests.swift -1239 Sources/Feed/FeedCoordinator.swift 1197 cmuxTests/CodexAppServerSessionTests.swift 1156 cmuxTests/SidebarOrderingTests.swift 1144 Sources/VaultAgentProcessScanner.swift 1139 cmuxTests/PiVaultAgentPersistenceTests.swift 1107 Sources/AppDelegate+CmuxSSHURL.swift +1096 Sources/GhosttyConfig.swift 1084 cmuxTests/AgentHibernationTests.swift 1068 cmuxTests/FileExplorerStoreTests.swift 1058 cmuxUITests/BonsplitTabDragUITests.swift -1096 Sources/GhosttyConfig.swift 1021 cmuxUITests/TerminalCmdClickUITests.swift 1006 cmuxTests/CmuxSSHURLRequestTests.swift 1000 cmuxTests/CmuxTopSnapshotScopeTests.swift @@ -93,6 +94,7 @@ 924 Sources/DockPanelView.swift 913 cmuxTests/WorkspaceGroupTests.swift 905 Sources/CmuxSSHURLRequest.swift +903 cmuxTests/TerminalNotificationQueueTests.swift 878 Sources/WorkspaceContentView.swift 868 Sources/Panels/BrowserScreenshotSnapshotter.swift 866 Sources/CommandPalette/CommandPaletteSettingsToggle.swift @@ -119,7 +121,6 @@ 705 cmuxUITests/BrowserOmnibarSuggestionsUITests.swift 701 CLI/CMUXCLI+AgentHookDefinitions.swift 698 cmuxTests/RestorableAgentHookProviderResumeTests.swift -697 cmuxTests/TerminalNotificationClearAllTests.swift 696 cmuxTests/UpdatePillReleaseVisibilityTests.swift 693 Sources/Panels/BrowserPopupWindowController.swift 691 cmuxTests/TaskManagerResourcesTests.swift @@ -138,7 +139,6 @@ 630 Packages/CmuxSettings/Sources/CmuxSettings/Values/ShortcutWhenClause.swift 627 Sources/WorkspaceRemoteConfiguration.swift 621 cmuxUITests/RightSidebarChromeHeightUITests.swift -620 cmuxTests/TerminalNotificationQueueTests.swift 619 cmuxTests/FinderFileDropRegressionTests.swift 614 cmuxTests/SessionIndexViewTests.swift 613 Sources/PortScanner.swift @@ -167,8 +167,8 @@ 539 CLI/CodexTeamsApprovalBridge.swift 538 CLI/CMUXCLI+Themes.swift 536 cmuxTests/CmuxConfigContextMenuTests.swift -530 cmuxUITests/AutomationSocketUITests.swift 528 cmuxTests/CLINotifyProcessTestSupport.swift +528 cmuxUITests/AutomationSocketUITests.swift 527 CLI/CLISocketPathResolver.swift 523 Packages/CmuxSettingsUI/Sources/CmuxSettingsUI/Scene/SettingsWindowScene.swift 522 Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttyRuntime.swift @@ -185,3 +185,4 @@ 504 cmuxTests/TerminalNotificationSocketActionTests.swift 502 Sources/CmuxEventPublishing.swift 502 Sources/Settings/ConfigSource.swift +500 Sources/TerminalNotificationQueue.swift diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 3af8f1c25cee..031d12a70b90 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -21972,7 +21972,12 @@ struct CMUXCLI { localized: "cli.claude-hook.notification.title", defaultValue: "Claude Code" ) - let payload = notificationPayload(title: title, subtitle: completion.subtitle, body: completion.body) + let payload = notificationPayload( + title: title, + subtitle: completion.subtitle, + body: completion.body, + structuredAgentStatusKey: Self.claudeCodeStatusKey + ) _ = try? sendV1Command("notify_target_async \(workspaceId) \(surfaceId) \(payload)", client: client) } print("OK") @@ -22117,7 +22122,12 @@ struct CMUXCLI { localized: "cli.claude-hook.notification.title", defaultValue: "Claude Code" ) - let payload = notificationPayload(title: title, subtitle: summary.subtitle, body: summary.body) + let payload = notificationPayload( + title: title, + subtitle: summary.subtitle, + body: summary.body, + structuredAgentStatusKey: Self.claudeCodeStatusKey + ) if let sessionId = parsedInput.sessionId { try? sessionStore.upsert( @@ -24991,8 +25001,17 @@ struct CMUXCLI { .replacingOccurrences(of: "|", with: "¦") } - private func notificationPayload(title: String, subtitle: String, body: String) -> String { - "\(sanitizeNotificationField(title))|\(sanitizeNotificationField(subtitle))|\(sanitizeNotificationField(body))" + private func notificationPayload( + title: String, + subtitle: String, + body: String, + structuredAgentStatusKey: String? = nil + ) -> String { + let payload = "\(sanitizeNotificationField(title))|\(sanitizeNotificationField(subtitle))|\(sanitizeNotificationField(body))" + guard let structuredAgentStatusKey else { return payload } + let trimmedKey = structuredAgentStatusKey.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedKey.isEmpty else { return payload } + return "--agent-status-key=\(trimmedKey) \(payload)" } private func redactClaudeSensitiveSpans(_ value: String) -> String { diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 623d91e36e0b..b098e078db93 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -47459,17 +47459,107 @@ "agent.generic.notification.status.idle": { "extractionState": "manual", "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "خامل" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Neaktivan" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Inaktiv" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Inaktiv" + } + }, "en": { "stringUnit": { "state": "translated", "value": "Idle" } }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Inactivo" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Inactif" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Inattivo" + } + }, "ja": { "stringUnit": { "state": "translated", "value": "待機中" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ទំនេរ" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "유휴" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Inaktiv" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Bezczynny" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Бездействует" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ไม่ได้ใช้งาน" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Boşta" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Неактивний" + } } } }, diff --git a/Sources/AgentHibernation/AgentHibernationLifecycleState.swift b/Sources/AgentHibernation/AgentHibernationLifecycleState.swift index 6d957a31a0da..87adad097c0a 100644 --- a/Sources/AgentHibernation/AgentHibernationLifecycleState.swift +++ b/Sources/AgentHibernation/AgentHibernationLifecycleState.swift @@ -45,27 +45,79 @@ enum AgentHibernationLifecycleState: String, Codable, Sendable, Equatable, CaseI } } -enum AgentHibernationLifecycleStatusKeys { - static let allowedStatusKeys: Set = [ - "amp", - "antigravity", - "claude_code", - "codebuddy", - "codex", - "copilot", - "cursor", - "factory", - "gemini", - "grok", - "hermes-agent", - "kiro", - "opencode", - "pi", - "qoder", - "rovodev", +nonisolated enum AgentHibernationLifecycleStatusKeys { + static let notificationTitleByStatusKey: [String: String] = [ + "amp": "Amp", + "antigravity": "Antigravity", + "claude_code": "Claude Code", + "codebuddy": "CodeBuddy", + "codex": "Codex", + "copilot": "Copilot", + "cursor": "Cursor", + "factory": "Factory", + "gemini": "Gemini", + "grok": "Grok", + "hermes-agent": "Hermes Agent", + "kiro": "Kiro", + "opencode": "OpenCode", + "pi": "Pi", + "qoder": "Qoder", + "rovodev": "Rovo Dev", ] + static let allowedStatusKeys: Set = Set(notificationTitleByStatusKey.keys) + static func isAllowed(_ key: String) -> Bool { allowedStatusKeys.contains(key) } + + static func normalizedAllowedStatusKey(_ key: String?) -> String? { + guard let key else { return nil } + let normalized = key.trimmingCharacters(in: .whitespacesAndNewlines) + guard !normalized.isEmpty, isAllowed(normalized) else { return nil } + return normalized + } + + static func statusKey(forNotificationTitle title: String) -> String? { + statusKeyByNormalizedNotificationTitle[normalizedNotificationTitle(title)] + } + + private static let statusKeyByNormalizedNotificationTitle: [String: String] = { + var result: [String: String] = [:] + var ambiguousTitles = Set() + for (statusKey, title) in notificationTitleByStatusKey { + let normalized = normalizedNotificationTitle(title) + guard !ambiguousTitles.contains(normalized) else { continue } + if result[normalized] != nil { + ambiguousTitles.insert(normalized) + result.removeValue(forKey: normalized) + } else { + result[normalized] = statusKey + } + } + return result + }() + + private static func normalizedNotificationTitle(_ title: String) -> String { + title.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + } +} + +struct StructuredAgentInputNotificationKey: Hashable, Sendable { + let tabId: UUID + let statusKey: String +} + +/// Panel-scoped variant of ``StructuredAgentInputNotificationKey``. +/// +/// The sidebar badge is workspace-level (keyed by `(tabId, statusKey)`), but +/// the per-panel agent lifecycle that gates hibernation is owned by an +/// individual panel. Tracking remaining unread/pending inputs at panel +/// granularity lets an acknowledgement demote the acknowledged panel's +/// lifecycle even when a sibling panel running the same agent still needs +/// input, without prematurely clearing the shared badge. +struct StructuredAgentInputPanelKey: Hashable, Sendable { + let tabId: UUID + let panelId: UUID + let statusKey: String } diff --git a/Sources/Feed/FeedCoordinator.swift b/Sources/Feed/FeedCoordinator.swift index 41d2da1d8187..05dbf0f7a66c 100644 --- a/Sources/Feed/FeedCoordinator.swift +++ b/Sources/Feed/FeedCoordinator.swift @@ -435,8 +435,97 @@ extension FeedCoordinator { return } pendingAttentionStates.removeValue(forKey: target) - let tab = attentionState.workspace + clearResolvedBlockingDecisionOverlay(target, tab: attentionState.workspace) + } + /// Acknowledges any feed-routed "Needs input" attention pending for a panel + /// the user just focused or interacted with, dropping the sidebar badge and + /// per-panel needsInput lifecycle. + /// + /// This is the feed-path analogue of + /// ``TerminalNotificationStore``'s notification acknowledgement: a + /// feed-routed blocking decision (PATH B) surfaces "Needs input" without + /// creating a store notification, so the notification-store mark-read path + /// can never reach it. Focusing the workspace is an explicit "I see it", so + /// the attention badge is collapsed here even though the underlying decision + /// card stays for allow/deny. The decision's later + /// ``concludeBlockingDecisionAttention(_:)`` becomes a safe no-op because + /// the target is already cleared. + /// + /// Targets are force-concluded regardless of refcount (the user has seen the + /// panel). When `panelId` is `nil`, every pending decision in the workspace + /// is acknowledged; otherwise only decisions on that panel are, so sibling + /// panels keep their "Needs input" badge. + /// + /// - Returns: `true` if any pending attention was cleared. + @MainActor + @discardableResult + func acknowledgeBlockingDecisionAttention(workspaceId: UUID, panelId: UUID?) -> Bool { + let targets = pendingAttentionStates.keys.filter { target in + guard target.workspaceId == workspaceId else { return false } + guard let panelId else { return true } + return target.panelId == panelId + } + guard !targets.isEmpty else { return false } + for target in targets { + guard let attentionState = pendingAttentionStates.removeValue(forKey: target) else { continue } + clearResolvedBlockingDecisionOverlay(target, tab: attentionState.workspace) + } + return true + } + + /// Workspace-scoped keys for every feed-routed blocking decision still + /// awaiting a reply. + /// + /// Feed-routed "Needs input" sets the shared sidebar status entry without + /// creating a store notification, so the notification store cannot see it. + /// Exposing the pending set lets the store keep the workspace badge lit when + /// a sibling panel still has an active feed prompt, even as another panel's + /// store notification is acknowledged. + @MainActor + func pendingStructuredAgentInputWorkspaceKeys() -> Set { + var keys = Set() + for target in pendingAttentionStates.keys { + keys.insert( + StructuredAgentInputNotificationKey(tabId: target.workspaceId, statusKey: target.statusKey) + ) + } + return keys + } + + /// Panel-scoped keys for every feed-routed blocking decision still awaiting + /// a reply. + /// + /// Unlike a queued/policy notification (which delivers within a drain tick), + /// a feed prompt persists until the user resolves the decision, so the + /// per-panel lifecycle gate must account for it precisely: an acknowledged + /// panel that still has an active feed prompt must not have its hibernation + /// lifecycle demoted, while a sibling panel's feed prompt must not block it. + @MainActor + func pendingStructuredAgentInputPanelKeys() -> Set { + var keys = Set() + for target in pendingAttentionStates.keys { + guard let panelId = target.panelId else { continue } + keys.insert( + StructuredAgentInputPanelKey( + tabId: target.workspaceId, + panelId: panelId, + statusKey: target.statusKey + ) + ) + } + return keys + } + + /// Clears the sidebar overlay for a blocking decision whose attention has + /// just been removed from ``pendingAttentionStates``. Restores only the + /// parts the feed still owns: the per-panel lifecycle drops to `.running` + /// only if it's still `.needsInput`, and the workspace-level status entry is + /// removed only if no other panel in the workspace still has a pending + /// decision under the same key and the entry still holds our "Needs input" + /// value. Anything an agent hook replaced in the meantime is left untouched. + @MainActor + private func clearResolvedBlockingDecisionOverlay(_ target: AttentionTarget, tab: Workspace) { // 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, diff --git a/Sources/SessionPersistence.swift b/Sources/SessionPersistence.swift index 6b8ffa0ef161..fbe92bb78646 100644 --- a/Sources/SessionPersistence.swift +++ b/Sources/SessionPersistence.swift @@ -1640,6 +1640,7 @@ struct SessionNotificationSnapshot: Codable, Sendable { var title: String var subtitle: String var body: String + var structuredAgentStatusKey: String? var createdAt: TimeInterval var isRead: Bool var paneFlash: Bool? @@ -1650,6 +1651,7 @@ struct SessionNotificationSnapshot: Codable, Sendable { title: String, subtitle: String, body: String, + structuredAgentStatusKey: String? = nil, createdAt: TimeInterval, isRead: Bool, paneFlash: Bool? = nil, @@ -1659,6 +1661,8 @@ struct SessionNotificationSnapshot: Codable, Sendable { self.title = title self.subtitle = subtitle self.body = body + self.structuredAgentStatusKey = AgentHibernationLifecycleStatusKeys + .normalizedAllowedStatusKey(structuredAgentStatusKey) self.createdAt = createdAt self.isRead = isRead self.paneFlash = paneFlash @@ -1671,6 +1675,7 @@ struct SessionNotificationSnapshot: Codable, Sendable { title: notification.title, subtitle: notification.subtitle, body: notification.body, + structuredAgentStatusKey: notification.structuredAgentStatusKey, createdAt: notification.createdAt.timeIntervalSince1970, isRead: notification.isRead, paneFlash: notification.paneFlash, @@ -1684,6 +1689,7 @@ struct SessionNotificationSnapshot: Codable, Sendable { tabId: tabId, surfaceId: surfaceId, panelId: panelId, + structuredAgentStatusKey: structuredAgentStatusKey, title: title, subtitle: subtitle, body: body, diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index 8d948673073f..5e6c088a2c31 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -6551,6 +6551,12 @@ class TabManager: ObservableObject { if let targetPanelId, !notificationSurfaceIds.contains(targetPanelId) { notificationSurfaceIds.append(targetPanelId) } + // Feed-routed blocking decisions (PATH B) surface "Needs input" without a + // store notification, so the mark-read path below can never reach them. + // Acknowledge them on the same focus/interaction signal so clicking into + // the workspace clears the badge (#2576). + let didAcknowledgeBlockingDecisionAttention = FeedCoordinator.shared + .acknowledgeBlockingDecisionAttention(workspaceId: tabId, panelId: targetPanelId) let hasManualPanelUnread = targetPanelId.map { workspace?.manualUnreadPanelIds.contains($0) ?? false } ?? false let hasRestoredPanelUnread = targetPanelId.map { workspace?.hasRestoredUnreadIndicator(panelId: $0) ?? false } ?? false let hasManualWorkspaceUnread = notificationStore.hasManualUnread(forTabId: tabId) @@ -6573,7 +6579,8 @@ class TabManager: ObservableObject { notificationStore.hasVisibleNotificationIndicator(forTabId: tabId, surfaceId: $0) } } - guard hasUnreadNotification || hasFocusedIndicator || canDismissUnreadIndicator else { return false } + guard hasUnreadNotification || hasFocusedIndicator || canDismissUnreadIndicator + || didAcknowledgeBlockingDecisionAttention else { return false } if hasUnreadNotification { if notificationSurfaceIds.isEmpty { notificationStore.markRead(forTabId: tabId, surfaceId: nil) diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index 1981cb495db8..6cc639449357 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -10057,6 +10057,7 @@ class TerminalController { let title = (params["title"] as? String) ?? "Notification" let subtitle = (params["subtitle"] as? String) ?? "" let body = (params["body"] as? String) ?? "" + let structuredAgentStatusKey = v2StructuredAgentStatusKey(params) var result: V2CallResult = .err(code: "internal_error", message: "Failed to notify", data: nil) v2MainSync { @@ -10078,7 +10079,8 @@ class TerminalController { surfaceId: surfaceId, title: title, subtitle: subtitle, - body: body + body: body, + structuredAgentStatusKey: structuredAgentStatusKey ) result = .ok(["workspace_id": ws.id.uuidString, "surface_id": v2OrNull(surfaceId?.uuidString)]) } @@ -10096,6 +10098,7 @@ class TerminalController { let title = (params["title"] as? String) ?? "Notification" let subtitle = (params["subtitle"] as? String) ?? "" let body = (params["body"] as? String) ?? "" + let structuredAgentStatusKey = v2StructuredAgentStatusKey(params) var result: V2CallResult = .err(code: "internal_error", message: "Failed to notify", data: nil) v2MainSync { @@ -10112,7 +10115,8 @@ class TerminalController { surfaceId: surfaceId, title: title, subtitle: subtitle, - body: body + body: body, + structuredAgentStatusKey: structuredAgentStatusKey ) result = .ok(["workspace_id": ws.id.uuidString, "workspace_ref": v2Ref(kind: .workspace, uuid: ws.id), "surface_id": surfaceId.uuidString, "surface_ref": v2Ref(kind: .surface, uuid: surfaceId), "window_id": v2OrNull(v2ResolveWindowId(tabManager: tabManager)?.uuidString), "window_ref": v2Ref(kind: .window, uuid: v2ResolveWindowId(tabManager: tabManager))]) } @@ -10133,6 +10137,7 @@ class TerminalController { let title = (params["title"] as? String) ?? "Notification" let subtitle = (params["subtitle"] as? String) ?? "" let body = (params["body"] as? String) ?? "" + let structuredAgentStatusKey = v2StructuredAgentStatusKey(params) var result: V2CallResult = .err(code: "internal_error", message: "Failed to notify", data: nil) v2MainSync { @@ -10149,13 +10154,20 @@ class TerminalController { surfaceId: surfaceId, title: title, subtitle: subtitle, - body: body + body: body, + structuredAgentStatusKey: structuredAgentStatusKey ) result = .ok(["workspace_id": ws.id.uuidString, "workspace_ref": v2Ref(kind: .workspace, uuid: ws.id), "surface_id": surfaceId.uuidString, "surface_ref": v2Ref(kind: .surface, uuid: surfaceId), "window_id": v2OrNull(v2ResolveWindowId(tabManager: tabManager)?.uuidString), "window_ref": v2Ref(kind: .window, uuid: v2ResolveWindowId(tabManager: tabManager))]) } return result } + private func v2StructuredAgentStatusKey(_ params: [String: Any]) -> String? { + let rawValue = params["agent_status_key"] as? String + ?? params["structured_agent_status_key"] as? String + return AgentHibernationLifecycleStatusKeys.normalizedAllowedStatusKey(rawValue) + } + private func v2NotificationList() -> [String: Any] { var items: [[String: Any]] = [] v2MainSync { @@ -10374,6 +10386,9 @@ class TerminalController { if includeReadState { payload["is_read"] = notification.isRead } + if let structuredAgentStatusKey = notification.structuredAgentStatusKey { + payload["structured_agent_status_key"] = structuredAgentStatusKey + } if let opened { payload["opened"] = opened } @@ -17427,13 +17442,14 @@ class TerminalController { return } let surfaceId = tabManager.focusedSurfaceId(for: tabId) - let (title, subtitle, body) = parseNotificationPayload(args) + let notificationPayload = parseNotificationPayload(args) deliverNotificationSynchronously( tabId: tabId, surfaceId: surfaceId, - title: title, - subtitle: subtitle, - body: body + title: notificationPayload.title, + subtitle: notificationPayload.subtitle, + body: notificationPayload.body, + structuredAgentStatusKey: notificationPayload.structuredAgentStatusKey ) } return result @@ -17459,13 +17475,14 @@ class TerminalController { result = "ERROR: Surface not found" return } - let (title, subtitle, body) = parseNotificationPayload(payload) + let notificationPayload = parseNotificationPayload(payload) deliverNotificationSynchronously( tabId: tabId, surfaceId: surfaceId, - title: title, - subtitle: subtitle, - body: body + title: notificationPayload.title, + subtitle: notificationPayload.subtitle, + body: notificationPayload.body, + structuredAgentStatusKey: notificationPayload.structuredAgentStatusKey ) } return result @@ -17482,7 +17499,7 @@ class TerminalController { let tabArg = parts[0] let panelArg = parts[1] let payload = parts.count > 2 ? parts[2] : "" - let (title, subtitle, body) = parseNotificationPayload(payload) + let notificationPayload = parseNotificationPayload(payload) if let workspaceId = UUID(uuidString: tabArg), let panelId = UUID(uuidString: panelArg) { @@ -17499,9 +17516,10 @@ class TerminalController { deliverNotificationSynchronously( tabId: workspaceId, surfaceId: panelId, - title: title, - subtitle: subtitle, - body: body + title: notificationPayload.title, + subtitle: notificationPayload.subtitle, + body: notificationPayload.body, + structuredAgentStatusKey: notificationPayload.structuredAgentStatusKey ) } return result @@ -17527,9 +17545,10 @@ class TerminalController { deliverNotificationSynchronously( tabId: tab.id, surfaceId: panelId, - title: title, - subtitle: subtitle, - body: body + title: notificationPayload.title, + subtitle: notificationPayload.subtitle, + body: notificationPayload.body, + structuredAgentStatusKey: notificationPayload.structuredAgentStatusKey ) } return result @@ -17556,18 +17575,19 @@ class TerminalController { guard !payload.isEmpty else { return "ERROR: Usage: notify_target_async |<subtitle>|<body>" } - let (title, subtitle, body) = parseNotificationPayload(payload) + let notificationPayload = parseNotificationPayload(payload) #if DEBUG cmuxDebugLog( - "socket.notifyTargetAsync.enqueue workspace=\(tabId.uuidString.prefix(8)) surface=\(surfaceId.uuidString.prefix(8)) titleLen=\(title.count) subtitleLen=\(subtitle.count) bodyLen=\(body.count) coalesces=0" + "socket.notifyTargetAsync.enqueue workspace=\(tabId.uuidString.prefix(8)) surface=\(surfaceId.uuidString.prefix(8)) titleLen=\(notificationPayload.title.count) subtitleLen=\(notificationPayload.subtitle.count) bodyLen=\(notificationPayload.body.count) coalesces=0" ) #endif TerminalMutationBus.shared.enqueueNotification( tabId: tabId, surfaceId: surfaceId, - title: title, - subtitle: subtitle, - body: body, + title: notificationPayload.title, + subtitle: notificationPayload.subtitle, + body: notificationPayload.body, + structuredAgentStatusKey: notificationPayload.structuredAgentStatusKey, coalesces: false ) return "OK" @@ -18318,16 +18338,59 @@ class TerminalController { return nil } - private func parseNotificationPayload(_ args: String) -> (String, String, String) { + private struct ParsedNotificationPayload { + let title: String + let subtitle: String + let body: String + let structuredAgentStatusKey: String? + } + + private func parseNotificationPayload(_ args: String) -> ParsedNotificationPayload { let trimmed = args.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return ("Notification", "", "") } - let parts = trimmed.split(separator: "|", maxSplits: 2, omittingEmptySubsequences: false).map(String.init) + guard !trimmed.isEmpty else { + return ParsedNotificationPayload( + title: "Notification", + subtitle: "", + body: "", + structuredAgentStatusKey: nil + ) + } + let (structuredAgentStatusKey, payloadText) = parseNotificationPayloadOptions(trimmed) + let parts = payloadText.split(separator: "|", maxSplits: 2, omittingEmptySubsequences: false).map(String.init) let title = parts.count > 0 ? parts[0].trimmingCharacters(in: .whitespacesAndNewlines) : "" let subtitle = parts.count > 2 ? parts[1].trimmingCharacters(in: .whitespacesAndNewlines) : "" let body = parts.count > 2 ? parts[2].trimmingCharacters(in: .whitespacesAndNewlines) : (parts.count > 1 ? parts[1].trimmingCharacters(in: .whitespacesAndNewlines) : "") - return (title.isEmpty ? "Notification" : title, subtitle, body) + return ParsedNotificationPayload( + title: title.isEmpty ? "Notification" : title, + subtitle: subtitle, + body: body, + structuredAgentStatusKey: structuredAgentStatusKey + ) + } + + private func parseNotificationPayloadOptions(_ args: String) -> (String?, String) { + let optionPrefixes = [ + "--agent-status-key=", + "--structured-agent-status-key=", + ] + guard let prefix = optionPrefixes.first(where: { args.hasPrefix($0) }) else { + return (nil, args) + } + let valueStart = args.index(args.startIndex, offsetBy: prefix.count) + let remainder = args[valueStart...] + let optionParts = remainder.split( + separator: " ", + maxSplits: 1, + omittingEmptySubsequences: false + ).map(String.init) + guard optionParts.count == 2 else { + return (nil, remainder.trimmingCharacters(in: .whitespacesAndNewlines)) + } + let statusKey = AgentHibernationLifecycleStatusKeys + .normalizedAllowedStatusKey(optionParts[0]) + return (statusKey, optionParts[1].trimmingCharacters(in: .whitespacesAndNewlines)) } private func closeWorkspace(_ tabId: String) -> String { diff --git a/Sources/TerminalNotificationQueue.swift b/Sources/TerminalNotificationQueue.swift index 0840acaa4303..5dd5d25bb595 100644 --- a/Sources/TerminalNotificationQueue.swift +++ b/Sources/TerminalNotificationQueue.swift @@ -10,6 +10,7 @@ fileprivate struct QueuedTerminalNotification: Sendable { let title: String let subtitle: String let body: String + let structuredAgentStatusKey: String? } fileprivate enum TerminalSocketMutation { @@ -37,6 +38,7 @@ final class TerminalMutationBus: @unchecked Sendable { private let lock = NSLock() private var pending: [TerminalSocketMutationEntry] = [] + private var inFlightNotificationDeliveries: [UInt64: QueuedTerminalNotification] = [:] private var drainScheduled = false private var nextSequence: UInt64 = 0 private var currentNotificationGeneration: UInt64 = 0 @@ -51,13 +53,15 @@ final class TerminalMutationBus: @unchecked Sendable { title: String, subtitle: String, body: String, + structuredAgentStatusKey: String? = nil, coalesces: Bool = true ) { enqueueNotification(QueuedTerminalNotification( key: QueuedTerminalNotificationKey(tabId: tabId, surfaceId: surfaceId), title: title, subtitle: subtitle, - body: body + body: body, + structuredAgentStatusKey: structuredAgentStatusKey ), coalesces: coalesces) } @@ -119,6 +123,23 @@ final class TerminalMutationBus: @unchecked Sendable { } } + nonisolated func pendingStructuredAgentInputNotificationKeys() -> Set<StructuredAgentInputNotificationKey> { + lock.lock() + var keys = Set<StructuredAgentInputNotificationKey>() + keys.reserveCapacity(pending.count + inFlightNotificationDeliveries.count) + for entry in pending { + guard case .deliverNotification(let notification) = entry.mutation else { + continue + } + insertStructuredAgentInputNotificationKey(for: notification, into: &keys) + } + for notification in inFlightNotificationDeliveries.values { + insertStructuredAgentInputNotificationKey(for: notification, into: &keys) + } + lock.unlock() + return keys + } + private func enqueueNotification(_ notification: QueuedTerminalNotification, coalesces: Bool) { let shouldScheduleDrain: Bool let removedCount: Int @@ -232,6 +253,20 @@ final class TerminalMutationBus: @unchecked Sendable { lock.unlock() } + private func insertStructuredAgentInputNotificationKey( + for notification: QueuedTerminalNotification, + into keys: inout Set<StructuredAgentInputNotificationKey> + ) { + let statusKey = AgentHibernationLifecycleStatusKeys + .normalizedAllowedStatusKey(notification.structuredAgentStatusKey) + ?? AgentHibernationLifecycleStatusKeys.statusKey(forNotificationTitle: notification.title) + guard let statusKey else { return } + keys.insert(StructuredAgentInputNotificationKey( + tabId: notification.key.tabId, + statusKey: statusKey + )) + } + private func scheduleDrain() { #if DEBUG lock.lock() @@ -311,6 +346,29 @@ final class TerminalMutationBus: @unchecked Sendable { return batch } + private func beginPerformingNotificationDeliveries(in batch: [TerminalSocketMutationEntry]) { + lock.lock() + for entry in batch { + guard case .deliverNotification(let notification) = entry.mutation else { continue } + inFlightNotificationDeliveries[entry.sequence] = notification + } + lock.unlock() + } + + private func finishPerformingNotificationDelivery(sequence: UInt64) { + lock.lock() + inFlightNotificationDeliveries.removeValue(forKey: sequence) + lock.unlock() + } + + private func finishPerformingNotificationDeliveries(in batch: [TerminalSocketMutationEntry]) { + lock.lock() + for entry in batch { + inFlightNotificationDeliveries.removeValue(forKey: entry.sequence) + } + lock.unlock() + } + private func markDrainCompleteIfEmpty() { lock.lock() if pending.isEmpty { @@ -325,6 +383,8 @@ final class TerminalMutationBus: @unchecked Sendable { @MainActor private func perform(_ batch: [TerminalSocketMutationEntry]) { + beginPerformingNotificationDeliveries(in: batch) + defer { finishPerformingNotificationDeliveries(in: batch) } for entry in batch { switch entry.mutation { case .deliverNotification(let notification): @@ -334,6 +394,7 @@ final class TerminalMutationBus: @unchecked Sendable { ) #endif TerminalNotificationStore.shared.deliverQueuedNotification(notification) + finishPerformingNotificationDelivery(sequence: entry.sequence) case .clearAllNotifications: TerminalNotificationStore.shared.clearAll(discardQueuedNotifications: false) case .clearNotificationsForTab(let tabId): @@ -360,7 +421,8 @@ extension TerminalController { surfaceId: UUID?, title: String, subtitle: String, - body: String + body: String, + structuredAgentStatusKey: String? = nil ) { TerminalMutationBus.shared.discardPendingNotifications(forTabId: tabId, surfaceId: surfaceId) #if DEBUG @@ -373,7 +435,8 @@ extension TerminalController { surfaceId: surfaceId, title: title, subtitle: subtitle, - body: body + body: body, + structuredAgentStatusKey: structuredAgentStatusKey ) } } @@ -398,7 +461,8 @@ extension TerminalNotificationStore { surfaceId: notification.key.surfaceId, title: notification.title, subtitle: notification.subtitle, - body: notification.body + body: notification.body, + structuredAgentStatusKey: notification.structuredAgentStatusKey ) } diff --git a/Sources/TerminalNotificationStore.swift b/Sources/TerminalNotificationStore.swift index e42d2861e15c..7c77ebccfbeb 100644 --- a/Sources/TerminalNotificationStore.swift +++ b/Sources/TerminalNotificationStore.swift @@ -775,6 +775,7 @@ struct TerminalNotification: Identifiable, Hashable { let tabId: UUID let surfaceId: UUID? let panelId: UUID? + let structuredAgentStatusKey: String? let title: String let subtitle: String let body: String @@ -788,6 +789,7 @@ struct TerminalNotification: Identifiable, Hashable { tabId: UUID, surfaceId: UUID?, panelId: UUID? = nil, + structuredAgentStatusKey: String? = nil, title: String, subtitle: String, body: String, @@ -800,6 +802,8 @@ struct TerminalNotification: Identifiable, Hashable { self.tabId = tabId self.surfaceId = surfaceId self.panelId = panelId + self.structuredAgentStatusKey = AgentHibernationLifecycleStatusKeys + .normalizedAllowedStatusKey(structuredAgentStatusKey) self.title = title self.subtitle = subtitle self.body = body @@ -901,6 +905,7 @@ final class TerminalNotificationStore: ObservableObject { effects in store.playSuppressedNotificationFeedback(for: notification, effects: effects) } + private var pendingPolicyStructuredAgentInputCounts: [StructuredAgentInputNotificationKey: Int] = [:] private struct NotificationHookFailureThrottleKey: Hashable { let hookId: String let sourcePath: String? @@ -1238,6 +1243,7 @@ final class TerminalNotificationStore: ObservableObject { title: String, subtitle: String, body: String, + structuredAgentStatusKey: String? = nil, cooldownKey: String? = nil, cooldownInterval: TimeInterval? = nil, clickAction: TerminalNotificationClickAction? = nil @@ -1278,11 +1284,13 @@ final class TerminalNotificationStore: ObservableObject { surfaceId: surfaceId, title: title, subtitle: subtitle, - body: body + body: body, + structuredAgentStatusKey: structuredAgentStatusKey ) guard !policyContext.hooks.isEmpty else { applyNotification( request: policyContext.request, + structuredAgentStatusKey: policyContext.structuredAgentStatusKey, effects: TerminalNotificationPolicyEffects(), now: now, cooldownReservation: cooldownReservation, @@ -1291,8 +1299,12 @@ final class TerminalNotificationStore: ObservableObject { return } + let pendingPolicyStructuredAgentInputKey = beginPendingPolicyStructuredAgentInput(policyContext) Task { @MainActor [weak self] in guard let self else { return } + defer { + self.finishPendingPolicyStructuredAgentInput(pendingPolicyStructuredAgentInputKey) + } let authorizedHooks = await NotificationPolicyHookAuthorizer.authorize( policyContext.hooks, globalConfigPath: policyContext.globalConfigPath @@ -1300,6 +1312,7 @@ final class TerminalNotificationStore: ObservableObject { guard !authorizedHooks.isEmpty else { self.applyNotification( request: policyContext.request, + structuredAgentStatusKey: policyContext.structuredAgentStatusKey, effects: TerminalNotificationPolicyEffects(), now: Date(), cooldownReservation: cooldownReservation, @@ -1317,6 +1330,7 @@ final class TerminalNotificationStore: ObservableObject { self.applyNotification( request: policyContext.request, envelope: envelope, + structuredAgentStatusKey: policyContext.structuredAgentStatusKey, now: Date(), cooldownReservation: cooldownReservation, clickAction: clickAction @@ -1324,6 +1338,7 @@ final class TerminalNotificationStore: ObservableObject { case .failure(let failure): self.applyNotification( request: policyContext.request, + structuredAgentStatusKey: policyContext.structuredAgentStatusKey, effects: TerminalNotificationPolicyEffects(), now: Date(), cooldownReservation: cooldownReservation, @@ -1341,10 +1356,38 @@ final class TerminalNotificationStore: ObservableObject { private struct NotificationPolicyContext: Sendable { let request: TerminalNotificationPolicyRequest + let structuredAgentStatusKey: String? let hooks: [CmuxResolvedNotificationHook] let globalConfigPath: String? } + private func beginPendingPolicyStructuredAgentInput( + _ context: NotificationPolicyContext + ) -> StructuredAgentInputNotificationKey? { + guard let statusKey = Self.structuredAgentStatusKey( + explicitStatusKey: context.structuredAgentStatusKey, + title: context.request.title + ) else { + return nil + } + let key = StructuredAgentInputNotificationKey( + tabId: context.request.tabId, + statusKey: statusKey + ) + pendingPolicyStructuredAgentInputCounts[key, default: 0] += 1 + return key + } + + private func finishPendingPolicyStructuredAgentInput(_ key: StructuredAgentInputNotificationKey?) { + guard let key else { return } + let remainingCount = (pendingPolicyStructuredAgentInputCounts[key] ?? 0) - 1 + if remainingCount > 0 { + pendingPolicyStructuredAgentInputCounts[key] = remainingCount + } else { + pendingPolicyStructuredAgentInputCounts.removeValue(forKey: key) + } + } + private func makeCooldownReservation( key: String?, interval: TimeInterval? @@ -1378,7 +1421,8 @@ final class TerminalNotificationStore: ObservableObject { surfaceId: UUID?, title: String, subtitle: String, - body: String + body: String, + structuredAgentStatusKey: String? ) -> NotificationPolicyContext { let appDelegate = AppDelegate.shared let context = appDelegate?.contextContainingTabId(tabId) @@ -1412,6 +1456,8 @@ final class TerminalNotificationStore: ObservableObject { isAppFocused: isAppFocused, isFocusedPanel: isFocusedPanel ), + structuredAgentStatusKey: AgentHibernationLifecycleStatusKeys + .normalizedAllowedStatusKey(structuredAgentStatusKey), hooks: cmuxConfigStore?.notificationHooks(startingFrom: cwd) ?? [], globalConfigPath: cmuxConfigStore?.globalConfigPath ) @@ -1420,6 +1466,7 @@ final class TerminalNotificationStore: ObservableObject { private func applyNotification( request: TerminalNotificationPolicyRequest, envelope: TerminalNotificationPolicyEnvelope, + structuredAgentStatusKey: String?, now: Date, cooldownReservation: NotificationCooldownReservation?, clickAction: TerminalNotificationClickAction? @@ -1437,6 +1484,7 @@ final class TerminalNotificationStore: ObservableObject { isAppFocused: request.isAppFocused, isFocusedPanel: request.isFocusedPanel ), + structuredAgentStatusKey: structuredAgentStatusKey, effects: envelope.effects, now: now, cooldownReservation: cooldownReservation, @@ -1446,6 +1494,7 @@ final class TerminalNotificationStore: ObservableObject { private func applyNotification( request: TerminalNotificationPolicyRequest, + structuredAgentStatusKey: String?, effects: TerminalNotificationPolicyEffects, now: Date, cooldownReservation: NotificationCooldownReservation?, @@ -1460,6 +1509,7 @@ final class TerminalNotificationStore: ObservableObject { tabId: request.tabId, surfaceId: request.surfaceId, panelId: request.panelId, + structuredAgentStatusKey: structuredAgentStatusKey, title: request.title, subtitle: request.subtitle, body: request.body, @@ -1640,12 +1690,143 @@ final class TerminalNotificationStore: ObservableObject { } } + private static func structuredAgentStatusKey( + explicitStatusKey: String?, + title: String + ) -> String? { + AgentHibernationLifecycleStatusKeys.normalizedAllowedStatusKey(explicitStatusKey) + ?? AgentHibernationLifecycleStatusKeys.statusKey(forNotificationTitle: title) + } + + private static func structuredAgentStatusKey(for notification: TerminalNotification) -> String? { + structuredAgentStatusKey( + explicitStatusKey: notification.structuredAgentStatusKey, + title: notification.title + ) + } + + private func acknowledgeStructuredAgentInputStatuses(for notificationsToAcknowledge: [TerminalNotification]) { + let remainingWorkspaceInputs = remainingUnreadStructuredAgentInputKeys() + let remainingPanelInputs = remainingUnreadStructuredAgentInputPanelKeys() + // Queued and policy-hook deliveries can't be panel-scoped cheaply, but + // they resolve within a drain tick, so block lifecycle demotion across + // the whole workspace while one is in flight — the safe direction (an + // agent still awaiting input must never become hibernatable). + let transientWorkspaceInputs = transientWorkspaceStructuredAgentInputKeys() + for notification in notificationsToAcknowledge { + let acknowledgementPanelId = notification.panelId ?? notification.surfaceId + guard let statusKey = Self.structuredAgentStatusKey(for: notification), + let workspace = workspaceForStructuredAgentInputAcknowledgement( + tabId: notification.tabId, + panelId: acknowledgementPanelId + ) else { + continue + } + // The shared sidebar badge is workspace-level: keep it while any + // panel (store, queued, policy, or feed-routed) still needs input + // for this status key. + let demoteWorkspaceBadge = !remainingWorkspaceInputs.contains( + StructuredAgentInputNotificationKey(tabId: notification.tabId, statusKey: statusKey) + ) + // The per-panel lifecycle that gates hibernation is owned by the + // acknowledged panel, so demote it as soon as that panel has no + // remaining unread input — even if a sibling panel still does. + let demotePanelLifecycle: Bool + if let acknowledgementPanelId { + let panelHasRemainingInput = remainingPanelInputs.contains( + StructuredAgentInputPanelKey( + tabId: notification.tabId, + panelId: acknowledgementPanelId, + statusKey: statusKey + ) + ) + let workspaceHasTransientInput = transientWorkspaceInputs.contains( + StructuredAgentInputNotificationKey(tabId: notification.tabId, statusKey: statusKey) + ) + demotePanelLifecycle = !panelHasRemainingInput && !workspaceHasTransientInput + } else { + demotePanelLifecycle = demoteWorkspaceBadge + } + guard demoteWorkspaceBadge || demotePanelLifecycle else { continue } + workspace.acknowledgeStructuredAgentInputStatus( + statusKeys: [statusKey], + panelId: acknowledgementPanelId, + notificationCreatedAt: notification.createdAt, + demoteWorkspaceBadge: demoteWorkspaceBadge, + demotePanelLifecycle: demotePanelLifecycle + ) + } + } + + private func remainingUnreadStructuredAgentInputKeys() -> Set<StructuredAgentInputNotificationKey> { + var keys = Set<StructuredAgentInputNotificationKey>() + keys.reserveCapacity(notifications.count) + for notification in notifications { + guard !notification.isRead, + let statusKey = Self.structuredAgentStatusKey(for: notification) else { + continue + } + keys.insert(StructuredAgentInputNotificationKey(tabId: notification.tabId, statusKey: statusKey)) + } + keys.formUnion(transientWorkspaceStructuredAgentInputKeys()) + keys.formUnion(FeedCoordinator.shared.pendingStructuredAgentInputWorkspaceKeys()) + return keys + } + + /// Workspace-level keys for structured-agent inputs that are pending in a + /// transient (sub-drain-tick) delivery stage — the queue and policy-hook + /// evaluation. These can't be cheaply panel-scoped, so the per-panel + /// lifecycle gate treats them conservatively at workspace granularity. + private func transientWorkspaceStructuredAgentInputKeys() -> Set<StructuredAgentInputNotificationKey> { + var keys = TerminalMutationBus.shared.pendingStructuredAgentInputNotificationKeys() + keys.formUnion(pendingPolicyStructuredAgentInputCounts.keys) + return keys + } + + private func remainingUnreadStructuredAgentInputPanelKeys() -> Set<StructuredAgentInputPanelKey> { + var keys = Set<StructuredAgentInputPanelKey>() + keys.reserveCapacity(notifications.count) + for notification in notifications { + guard !notification.isRead, + let panelId = notification.panelId ?? notification.surfaceId, + let statusKey = Self.structuredAgentStatusKey(for: notification) else { + continue + } + keys.insert( + StructuredAgentInputPanelKey(tabId: notification.tabId, panelId: panelId, statusKey: statusKey) + ) + } + // Feed prompts persist until resolved, so they must be panel-scoped here + // rather than lumped into the transient workspace set. + keys.formUnion(FeedCoordinator.shared.pendingStructuredAgentInputPanelKeys()) + return keys + } + + private func workspaceForStructuredAgentInputAcknowledgement( + tabId: UUID, + panelId: UUID? + ) -> Workspace? { + guard let appDelegate = AppDelegate.shared else { return nil } + if let panelId, + let located = appDelegate.workspaceContainingPanel( + panelId: panelId, + preferredWorkspaceId: tabId + ) { + return located.workspace + } + + let tabManager = appDelegate.tabManagerFor(tabId: tabId) ?? appDelegate.tabManager + return tabManager?.tabs.first(where: { $0.id == tabId }) + } + func markRead(id: UUID) { var updated = notifications guard let index = updated.firstIndex(where: { $0.id == id }) else { return } guard !updated[index].isRead else { return } + let notification = updated[index] updated[index].isRead = true notifications = updated + acknowledgeStructuredAgentInputStatuses(for: [notification]) center.removeDeliveredNotificationsOffMain(withIdentifiers: [id.uuidString]) } @@ -1668,8 +1849,10 @@ final class TerminalNotificationStore: ObservableObject { func markRead(forTabId tabId: UUID) { var updated = notifications var idsToClear: [String] = [] + var notificationsToAcknowledge: [TerminalNotification] = [] for index in updated.indices { if updated[index].tabId == tabId && !updated[index].isRead { + notificationsToAcknowledge.append(updated[index]) updated[index].isRead = true idsToClear.append(updated[index].id.uuidString) } @@ -1682,6 +1865,7 @@ final class TerminalNotificationStore: ObservableObject { clearWorkspacePanelUnread(forTabId: tabId) setPanelDerivedWorkspaceUnread(false, forTabId: tabId) setWorkspaceRestoredUnread(false, forTabId: tabId) + acknowledgeStructuredAgentInputStatuses(for: notificationsToAcknowledge) if !idsToClear.isEmpty { center.removeDeliveredNotificationsOffMain(withIdentifiers: idsToClear) } @@ -1690,9 +1874,11 @@ final class TerminalNotificationStore: ObservableObject { func markRead(forTabId tabId: UUID, surfaceId: UUID?) { var updated = notifications var idsToClear: [String] = [] + var notificationsToAcknowledge: [TerminalNotification] = [] for index in updated.indices { if updated[index].matches(tabId: tabId, surfaceId: surfaceId), !updated[index].isRead { + notificationsToAcknowledge.append(updated[index]) updated[index].isRead = true idsToClear.append(updated[index].id.uuidString) } @@ -1706,6 +1892,7 @@ final class TerminalNotificationStore: ObservableObject { setPanelDerivedWorkspaceUnread(false, forTabId: tabId) setWorkspaceRestoredUnread(false, forTabId: tabId) } + acknowledgeStructuredAgentInputStatuses(for: notificationsToAcknowledge) if !idsToClear.isEmpty { center.removeDeliveredNotificationsOffMain(withIdentifiers: idsToClear) center.removePendingNotificationRequestsOffMain(withIdentifiers: idsToClear) @@ -1769,8 +1956,10 @@ final class TerminalNotificationStore: ObservableObject { var updated = notifications var idsToClear: [String] = [] var tabIdsToClearPanelUnread = panelDerivedUnreadWorkspaceIds + var notificationsToAcknowledge: [TerminalNotification] = [] for index in updated.indices { if !updated[index].isRead { + notificationsToAcknowledge.append(updated[index]) tabIdsToClearPanelUnread.insert(updated[index].tabId) updated[index].isRead = true idsToClear.append(updated[index].id.uuidString) @@ -1783,6 +1972,7 @@ final class TerminalNotificationStore: ObservableObject { clearAllWorkspacePanelUnread(forTabIds: tabIdsToClearPanelUnread) clearPanelDerivedWorkspaceUnread() clearWorkspaceRestoredUnread() + acknowledgeStructuredAgentInputStatuses(for: notificationsToAcknowledge) if !idsToClear.isEmpty { center.removeDeliveredNotificationsOffMain(withIdentifiers: idsToClear) center.removePendingNotificationRequestsOffMain(withIdentifiers: idsToClear) @@ -1798,6 +1988,7 @@ final class TerminalNotificationStore: ObservableObject { notifications = updated if let removed { clearFocusedReadIndicator(forTabId: removed.tabId, surfaceId: removed.surfaceId) + acknowledgeStructuredAgentInputStatuses(for: [removed]) } center.removeDeliveredNotificationsOffMain(withIdentifiers: [id.uuidString]) } @@ -1846,6 +2037,7 @@ final class TerminalNotificationStore: ObservableObject { tabId: notification.tabId, surfaceId: notification.surfaceId, panelId: notification.panelId, + structuredAgentStatusKey: notification.structuredAgentStatusKey, title: notification.title, subtitle: notification.subtitle, body: notification.body, @@ -1860,6 +2052,7 @@ final class TerminalNotificationStore: ObservableObject { func clearAll(discardQueuedNotifications: Bool = true) { if discardQueuedNotifications { TerminalMutationBus.shared.discardPendingNotifications() } + let notificationsToAcknowledge = notifications guard !notifications.isEmpty || !focusedReadIndicatorByTabId.isEmpty || !manualUnreadWorkspaceIds.isEmpty || @@ -1873,6 +2066,7 @@ final class TerminalNotificationStore: ObservableObject { clearPanelDerivedWorkspaceUnread() clearWorkspaceRestoredUnread() focusedReadIndicatorByTabId.removeAll() + acknowledgeStructuredAgentInputStatuses(for: notificationsToAcknowledge) CmuxEventBus.shared.publishNotificationCleared(ids: ids, workspaceId: nil, surfaceId: nil) center.removeDeliveredNotificationsOffMain(withIdentifiers: ids) center.removePendingNotificationRequestsOffMain(withIdentifiers: ids) @@ -1889,8 +2083,10 @@ final class TerminalNotificationStore: ObservableObject { var updated: [TerminalNotification] = [] updated.reserveCapacity(notifications.count) var idsToClear: [String] = [] + var notificationsToAcknowledge: [TerminalNotification] = [] for notification in notifications { if notification.matches(tabId: tabId, surfaceId: surfaceId) { + notificationsToAcknowledge.append(notification) idsToClear.append(notification.id.uuidString) } else { updated.append(notification) @@ -1903,6 +2099,7 @@ final class TerminalNotificationStore: ObservableObject { if surfaceId == nil { setWorkspaceRestoredUnread(false, forTabId: tabId) } + acknowledgeStructuredAgentInputStatuses(for: notificationsToAcknowledge) clearFocusedReadIndicator(forTabId: tabId, surfaceId: surfaceId) if !idsToClear.isEmpty { CmuxEventBus.shared.publishNotificationCleared(ids: idsToClear, workspaceId: tabId, surfaceId: surfaceId) @@ -1926,6 +2123,7 @@ final class TerminalNotificationStore: ObservableObject { tabId: destinationTabId, surfaceId: notification.surfaceId, panelId: notification.panelId, + structuredAgentStatusKey: notification.structuredAgentStatusKey, title: notification.title, subtitle: notification.subtitle, body: notification.body, @@ -1953,8 +2151,10 @@ final class TerminalNotificationStore: ObservableObject { var updated: [TerminalNotification] = [] updated.reserveCapacity(notifications.count) var idsToClear: [String] = [] + var notificationsToAcknowledge: [TerminalNotification] = [] for notification in notifications { if notification.tabId == tabId { + notificationsToAcknowledge.append(notification) idsToClear.append(notification.id.uuidString) } else { updated.append(notification) @@ -1968,6 +2168,7 @@ final class TerminalNotificationStore: ObservableObject { if !idsToClear.isEmpty { replaceNotificationsForClear(updated) } + acknowledgeStructuredAgentInputStatuses(for: notificationsToAcknowledge) clearFocusedReadIndicator(forTabId: tabId) if !idsToClear.isEmpty { CmuxEventBus.shared.publishNotificationCleared(ids: idsToClear, workspaceId: tabId, surfaceId: nil) @@ -2364,6 +2565,7 @@ final class TerminalNotificationStore: ObservableObject { clearPanelDerivedWorkspaceUnread() clearWorkspaceRestoredUnread() focusedReadIndicatorByTabId.removeAll() + pendingPolicyStructuredAgentInputCounts.removeAll() } #endif diff --git a/Sources/Workspace+PanelLifecycle.swift b/Sources/Workspace+PanelLifecycle.swift index 77e161b5ceca..aaeebaaabfcb 100644 --- a/Sources/Workspace+PanelLifecycle.swift +++ b/Sources/Workspace+PanelLifecycle.swift @@ -135,6 +135,93 @@ extension Workspace { return Self.truthyStartupEnvironmentValues.contains(rawValue) } + @discardableResult + func acknowledgeStructuredAgentInputStatus( + statusKeys acknowledgedStatusKeys: Set<String>, + panelId: UUID? = nil, + notificationCreatedAt: Date, + demoteWorkspaceBadge: Bool = true, + demotePanelLifecycle: Bool = true + ) -> Bool { + let candidateStatusKeys: Set<String> + if let panelId { + let panelStatusKeys = Set((agentPIDKeysByPanelId[panelId] ?? []).map { + agentStatusKey(forAgentPIDKey: $0) + }) + candidateStatusKeys = panelStatusKeys.intersection(acknowledgedStatusKeys) + } else { + candidateStatusKeys = acknowledgedStatusKeys + } + + let idleValue = String(localized: "agent.generic.notification.status.idle", defaultValue: "Idle") + var didChange = false + for key in candidateStatusKeys where Self.structuredAgentHookStatusKeys.contains(key) { + // Per-panel lifecycle gates hibernation and is owned by the + // acknowledged panel, so it demotes as soon as that panel is done — + // independent of the shared workspace badge, which stays lit while a + // sibling panel still needs input for the same key. Its re-raise + // protection comes from the caller's panel-level remaining check, so + // it does not consult the shared badge's timestamp (a sibling's + // newer status write must not block this panel). + if demotePanelLifecycle, demoteAcknowledgedAgentLifecycle(statusKey: key, panelId: panelId) { + didChange = true + } + + // The shared badge keeps the author's re-raise guard: only demote it + // when the status was written no later than this notification, so a + // status re-raised after the notification survives acknowledgement. + guard demoteWorkspaceBadge, + let entry = statusEntries[key], + isStructuredAgentInputStatus(entry), + entry.timestamp <= notificationCreatedAt else { + continue + } + statusEntries[key] = SidebarStatusEntry( + key: key, + value: idleValue, + icon: "pause.circle.fill", + color: "#8E8E93" + ) + didChange = true + } + return didChange + } + + /// Drops any `.needsInput` per-panel agent lifecycle for an acknowledged + /// status key to `.idle`, matching the demoted "Idle" sidebar status. + /// + /// Without this the sidebar shows Idle while + /// ``agentHibernationLifecycleState(panelId:fallback:)`` still reports + /// `.needsInput`, leaving hibernation blocked until a later hook clears it. + /// Scoped to `panelId` when the acknowledgement names one; otherwise every + /// panel still stuck on `.needsInput` for the key is demoted. Only entries + /// currently in `.needsInput` are touched, so a concurrent `.running` + /// update from the agent is never clobbered. + @discardableResult + private func demoteAcknowledgedAgentLifecycle(statusKey: String, panelId: UUID?) -> Bool { + let panelIds: [UUID] + if let panelId { + panelIds = [panelId] + } else { + panelIds = agentLifecycleStatesByPanelId.compactMap { panelId, states in + states[statusKey] == .needsInput ? panelId : nil + } + } + var didChange = false + for panelId in panelIds where agentLifecycleStatesByPanelId[panelId]?[statusKey] == .needsInput { + setAgentLifecycle(key: statusKey, panelId: panelId, lifecycle: .idle) + didChange = true + } + return didChange + } + + private func isStructuredAgentInputStatus(_ entry: SidebarStatusEntry) -> Bool { + guard Self.structuredAgentHookStatusKeys.contains(entry.key) else { + return false + } + return entry.icon == "bell.fill" + } + func sidebarStatusEntriesVisibleForDisplay() -> [SidebarStatusEntry] { let visibleStructuredStatusKeys = visibleStructuredAgentStatusKeysByPanel() return statusEntries.values.filter { entry in diff --git a/cmuxTests/TerminalNotificationClearAllTests.swift b/cmuxTests/TerminalNotificationClearAllTests.swift index bd6af331a325..805b02bd191b 100644 --- a/cmuxTests/TerminalNotificationClearAllTests.swift +++ b/cmuxTests/TerminalNotificationClearAllTests.swift @@ -1,5 +1,6 @@ import XCTest import Bonsplit +import CMUXWorkstream import Darwin #if canImport(cmux_DEV) @testable import cmux_DEV @@ -89,11 +90,24 @@ final class TerminalNotificationClearAllTests: XCTestCase { let secondPanel = try XCTUnwrap( workspace.newTerminalSplit(from: firstPanelId, orientation: .horizontal) ) + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Needs input", + icon: "bell.fill", + color: "#4C8DFF", + priority: 100 + ) + workspace.recordAgentPID( + key: "claude_code.session-clear-command", + pid: pid_t(12345), + panelId: firstPanelId, + refreshPorts: false + ) TerminalMutationBus.shared.enqueueNotification( tabId: workspace.id, surfaceId: firstPanelId, - title: "Grok", + title: "Claude Code", subtitle: "Waiting", body: "First" ) @@ -119,6 +133,680 @@ final class TerminalNotificationClearAllTests: XCTestCase { XCTAssertTrue(store.hasUnreadNotification(forTabId: workspace.id, surfaceId: secondPanel.id)) XCTAssertEqual(store.notifications.count, 1) XCTAssertEqual(store.notifications.first?.surfaceId, secondPanel.id) + XCTAssertEqual(workspace.statusEntries["claude_code"]?.value, "Idle") + XCTAssertEqual(workspace.statusEntries["claude_code"]?.icon, "pause.circle.fill") + } + + func testMarkingClaudeNeedsInputNotificationReadDemotesSidebarStatusToIdle() throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + + let workspace = manager.addWorkspace(select: true) + defer { + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + } + + let panelId = try XCTUnwrap(workspace.focusedPanelId) + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Needs input", + icon: "bell.fill", + color: "#4C8DFF", + priority: 100 + ) + workspace.recordAgentPID( + key: "claude_code.session-needs-input", + pid: pid_t(12345), + panelId: panelId, + refreshPorts: false + ) + store.addNotification( + tabId: workspace.id, + surfaceId: panelId, + title: "Claude Code", + subtitle: "Waiting", + body: "Claude needs your input" + ) + + XCTAssertTrue(store.hasUnreadNotification(forTabId: workspace.id, surfaceId: panelId)) + + store.markRead(forTabId: workspace.id, surfaceId: panelId) + + let status = try XCTUnwrap(workspace.statusEntries["claude_code"]) + XCTAssertFalse(store.hasUnreadNotification(forTabId: workspace.id, surfaceId: panelId)) + XCTAssertEqual(status.value, "Idle") + XCTAssertEqual(status.icon, "pause.circle.fill") + XCTAssertEqual(status.color, "#8E8E93") + XCTAssertEqual(status.priority, 0) + } + + func testAcknowledgingClaudeNeedsInputDemotesAgentLifecycleForHibernation() throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + + let workspace = manager.addWorkspace(select: true) + defer { + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + } + + let panelId = try XCTUnwrap(workspace.focusedPanelId) + // Mirror the Claude hook ordering: per-panel lifecycle + sidebar status + // both flip to needs-input before the notification is sent. + workspace.recordAgentPID( + key: "claude_code.session-needs-input", + pid: pid_t(12345), + panelId: panelId, + refreshPorts: false + ) + workspace.setAgentLifecycle(key: "claude_code", panelId: panelId, lifecycle: .needsInput) + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Needs input", + icon: "bell.fill", + color: "#4C8DFF", + priority: 100 + ) + store.addNotification( + tabId: workspace.id, + surfaceId: panelId, + title: "Claude Code", + subtitle: "Waiting", + body: "Claude needs your input" + ) + + XCTAssertEqual( + workspace.agentHibernationLifecycleState(panelId: panelId, fallback: nil), + .needsInput + ) + + store.markRead(forTabId: workspace.id, surfaceId: panelId) + + // The sidebar status demotes to Idle AND the per-panel lifecycle must + // leave needsInput, otherwise agentHibernationLifecycleState keeps + // returning .needsInput and hibernation stays blocked. + XCTAssertEqual(workspace.statusEntries["claude_code"]?.value, "Idle") + XCTAssertNotEqual( + workspace.agentLifecycleStatesByPanelId[panelId]?["claude_code"], + .needsInput + ) + XCTAssertNotEqual( + workspace.agentHibernationLifecycleState(panelId: panelId, fallback: nil), + .needsInput + ) + } + + func testAcknowledgingOnePanelDemotesItsLifecycleButKeepsBadgeForSiblingPanel() throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + + let workspace = manager.addWorkspace(select: true) + defer { + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + } + + let firstPanelId = try XCTUnwrap(workspace.focusedPanelId) + let secondPanel = try XCTUnwrap( + workspace.newTerminalSplit(from: firstPanelId, orientation: .horizontal) + ) + // Two Claude panels in one workspace, both stuck on needs-input. + for (panelId, suffix) in [(firstPanelId, "a"), (secondPanel.id, "b")] { + workspace.recordAgentPID( + key: "claude_code.session-\(suffix)", + pid: pid_t(suffix == "a" ? 111 : 222), + panelId: panelId, + refreshPorts: false + ) + workspace.setAgentLifecycle(key: "claude_code", panelId: panelId, lifecycle: .needsInput) + } + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Needs input", + icon: "bell.fill", + color: "#4C8DFF", + priority: 100 + ) + store.addNotification( + tabId: workspace.id, + surfaceId: firstPanelId, + title: "Claude Code", + subtitle: "Waiting", + body: "First panel needs input" + ) + store.addNotification( + tabId: workspace.id, + surfaceId: secondPanel.id, + title: "Claude Code", + subtitle: "Waiting", + body: "Second panel needs input" + ) + + store.markRead(forTabId: workspace.id, surfaceId: firstPanelId) + + // Badge stays lit because the sibling panel still needs input... + XCTAssertEqual(workspace.statusEntries["claude_code"]?.value, "Needs input") + XCTAssertEqual(workspace.statusEntries["claude_code"]?.icon, "bell.fill") + // ...but the acknowledged panel's lifecycle is demoted so it can hibernate. + XCTAssertNotEqual( + workspace.agentLifecycleStatesByPanelId[firstPanelId]?["claude_code"], + .needsInput + ) + XCTAssertEqual( + workspace.agentLifecycleStatesByPanelId[secondPanel.id]?["claude_code"], + .needsInput + ) + } + + func testAcknowledgingStoreNotificationKeepsLifecycleWhileFeedPromptPendingOnSamePanel() throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = appDelegate.tabManager ?? TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + FeedCoordinatorTestHooks.attentionSurfaceObserver = nil + + let workspace = manager.addWorkspace(select: true) + var feedTarget: FeedCoordinator.AttentionTarget? = nil + defer { + if let feedTarget { + FeedCoordinator.shared.concludeBlockingDecisionAttention(feedTarget) + } + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + FeedCoordinatorTestHooks.attentionSurfaceObserver = nil + } + + let panelId = try XCTUnwrap(workspace.focusedPanelId) + workspace.recordAgentPID( + key: "claude_code.session-feed-vs-store", + pid: pid_t(54321), + panelId: panelId, + refreshPorts: false + ) + + // A live feed-routed blocking decision on this panel (sets lifecycle + // needsInput + sidebar status + pendingAttentionStates, no store notif). + let event = WorkstreamEvent( + sessionId: "claude-feed-vs-store", + hookEventName: .permissionRequest, + source: "claude", + cwd: "/tmp", + toolName: "Bash", + toolInputJSON: #"{"command":"true"}"#, + requestId: "feed-vs-store-request" + ) + feedTarget = try XCTUnwrap( + FeedCoordinator.shared.surfaceBlockingDecisionAttention( + event: event, + resolved: (workspaceId: workspace.id, surfaceId: panelId) + ) + ) + // A separate store notification arrives on the same panel/key. + store.addNotification( + tabId: workspace.id, + surfaceId: panelId, + title: "Claude Code", + subtitle: "Waiting", + body: "Needs input", + structuredAgentStatusKey: "claude_code" + ) + + store.markRead(forTabId: workspace.id, surfaceId: panelId) + + // The store notification is acknowledged, but the feed prompt is still + // outstanding on this panel, so neither the badge nor the per-panel + // lifecycle may clear — the agent is still waiting for input. + XCTAssertEqual(workspace.statusEntries["claude_code"]?.value, "Needs input") + XCTAssertEqual( + workspace.agentLifecycleStatesByPanelId[panelId]?["claude_code"], + .needsInput + ) + } + + func testRemovingClaudeNeedsInputNotificationDemotesSidebarStatusToIdle() throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + + let workspace = manager.addWorkspace(select: true) + defer { + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + } + + let panelId = try XCTUnwrap(workspace.focusedPanelId) + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Needs input", + icon: "bell.fill", + color: "#4C8DFF", + priority: 100 + ) + workspace.recordAgentPID( + key: "claude_code.session-remove", + pid: pid_t(12345), + panelId: panelId, + refreshPorts: false + ) + store.addNotification( + tabId: workspace.id, + surfaceId: panelId, + title: "Claude Code", + subtitle: "Waiting", + body: "Claude needs your input" + ) + let notification = try XCTUnwrap(store.notifications.first) + + store.remove(id: notification.id) + + let status = try XCTUnwrap(workspace.statusEntries["claude_code"]) + XCTAssertTrue(store.notifications.isEmpty) + XCTAssertEqual(status.value, "Idle") + XCTAssertEqual(status.icon, "pause.circle.fill") + XCTAssertEqual(status.color, "#8E8E93") + XCTAssertEqual(status.priority, 0) + } + + func testMarkingClaudeNotificationReadUsesPanelIdBeforeSurfaceId() throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + + let workspace = manager.addWorkspace(select: true) + defer { + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + } + + let panelId = try XCTUnwrap(workspace.focusedPanelId) + let nonPanelSurfaceId = UUID() + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Needs input", + icon: "bell.fill", + color: "#4C8DFF", + priority: 100 + ) + workspace.recordAgentPID( + key: "claude_code.session-panel-precedence", + pid: pid_t(12345), + panelId: panelId, + refreshPorts: false + ) + let notification = TerminalNotification( + id: UUID(), + tabId: workspace.id, + surfaceId: nonPanelSurfaceId, + panelId: panelId, + title: "Claude Code", + subtitle: "Waiting", + body: "Claude needs your input", + createdAt: Date(), + isRead: false + ) + store.replaceNotificationsForTesting([notification]) + + store.markRead(id: notification.id) + + let status = try XCTUnwrap(workspace.statusEntries["claude_code"]) + XCTAssertEqual(status.value, "Idle") + XCTAssertEqual(status.icon, "pause.circle.fill") + XCTAssertEqual(status.color, "#8E8E93") + XCTAssertEqual(status.priority, 0) + } + + func testRemovingOneOfMultipleUnreadClaudeNotificationsKeepsNeedsInputStatus() throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + + let workspace = manager.addWorkspace(select: true) + defer { + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + } + + let panelId = try XCTUnwrap(workspace.focusedPanelId) + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Needs input", + icon: "bell.fill", + color: "#4C8DFF", + priority: 100 + ) + workspace.recordAgentPID( + key: "claude_code.session-multiple-unread", + pid: pid_t(12345), + panelId: panelId, + refreshPorts: false + ) + store.addNotification( + tabId: workspace.id, + surfaceId: panelId, + title: "Claude Code", + subtitle: "Waiting", + body: "First unread prompt" + ) + store.addNotification( + tabId: workspace.id, + surfaceId: panelId, + title: "Claude Code", + subtitle: "Waiting", + body: "Second unread prompt" + ) + let firstNotification = try XCTUnwrap( + store.notifications.first { $0.body == "First unread prompt" } + ) + let secondNotification = try XCTUnwrap( + store.notifications.first { $0.body == "Second unread prompt" } + ) + + store.remove(id: firstNotification.id) + + let status = try XCTUnwrap(workspace.statusEntries["claude_code"]) + XCTAssertEqual(store.notifications.count, 1) + XCTAssertEqual(store.notifications.first?.id, secondNotification.id) + XCTAssertFalse(store.notifications.first?.isRead ?? true) + XCTAssertEqual(status.value, "Needs input") + XCTAssertEqual(status.icon, "bell.fill") + XCTAssertEqual(status.color, "#4C8DFF") + XCTAssertEqual(status.priority, 100) + } + + func testMarkingNonAgentNotificationReadDoesNotDemoteClaudeNeedsInputOnSamePanel() throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + + let workspace = manager.addWorkspace(select: true) + defer { + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + } + + let panelId = try XCTUnwrap(workspace.focusedPanelId) + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Needs input", + icon: "bell.fill", + color: "#4C8DFF", + priority: 100 + ) + workspace.recordAgentPID( + key: "claude_code.session-needs-input", + pid: pid_t(12345), + panelId: panelId, + refreshPorts: false + ) + store.addNotification( + tabId: workspace.id, + surfaceId: panelId, + title: "Build", + subtitle: "Done", + body: "A non-agent notification on the same panel" + ) + + store.markRead(forTabId: workspace.id, surfaceId: panelId) + + let status = try XCTUnwrap(workspace.statusEntries["claude_code"]) + XCTAssertFalse(store.hasUnreadNotification(forTabId: workspace.id, surfaceId: panelId)) + XCTAssertEqual(status.value, "Needs input") + XCTAssertEqual(status.icon, "bell.fill") + XCTAssertEqual(status.color, "#4C8DFF") + XCTAssertEqual(status.priority, 100) + } + + func testMarkingOlderClaudeNotificationReadDoesNotDemoteNewerNeedsInputStatus() throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + + let workspace = manager.addWorkspace(select: true) + defer { + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + } + + let panelId = try XCTUnwrap(workspace.focusedPanelId) + workspace.recordAgentPID( + key: "claude_code.session-needs-input", + pid: pid_t(12345), + panelId: panelId, + refreshPorts: false + ) + store.addNotification( + tabId: workspace.id, + surfaceId: panelId, + title: "Claude Code", + subtitle: "Waiting", + body: "Older prompt notification" + ) + let notification = try XCTUnwrap(store.notifications.first) + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Needs input", + icon: "bell.fill", + color: "#4C8DFF", + priority: 100, + timestamp: notification.createdAt.addingTimeInterval(1) + ) + + store.markRead(id: notification.id) + + let status = try XCTUnwrap(workspace.statusEntries["claude_code"]) + XCTAssertFalse(store.hasUnreadNotification(forTabId: workspace.id, surfaceId: panelId)) + XCTAssertEqual(status.value, "Needs input") + XCTAssertEqual(status.icon, "bell.fill") + XCTAssertEqual(status.color, "#4C8DFF") + XCTAssertEqual(status.priority, 100) + } + + func testMarkingSiblingPanelReadDoesNotDemoteClaudeNeedsInputForOtherPanel() throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + + let workspace = manager.addWorkspace(select: true) + defer { + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + } + + let firstPanelId = try XCTUnwrap(workspace.focusedPanelId) + let secondPanel = try XCTUnwrap( + workspace.newTerminalSplit(from: firstPanelId, orientation: .horizontal) + ) + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Needs input", + icon: "bell.fill", + color: "#4C8DFF", + priority: 100 + ) + workspace.recordAgentPID( + key: "claude_code.session-needs-input", + pid: pid_t(12345), + panelId: secondPanel.id, + refreshPorts: false + ) + store.addNotification( + tabId: workspace.id, + surfaceId: firstPanelId, + title: "Claude Code", + subtitle: "Waiting", + body: "Claude notification on a sibling panel" + ) + + store.markRead(forTabId: workspace.id, surfaceId: firstPanelId) + + let status = try XCTUnwrap(workspace.statusEntries["claude_code"]) + XCTAssertEqual(status.value, "Needs input") + XCTAssertEqual(status.icon, "bell.fill") + XCTAssertEqual(status.color, "#4C8DFF") + XCTAssertEqual(status.priority, 100) } func testClosingPaneRemovesSurfaceNotificationContribution() throws { @@ -694,4 +1382,85 @@ final class TerminalNotificationClearAllTests: XCTestCase { "restored-only" ) } + + /// Regression for #2576: a Claude "Needs input" raised by a feed-routed + /// blocking decision (PATH B — `FeedCoordinator.surfaceBlockingDecisionAttention`) + /// sets the sidebar status + needsInput lifecycle WITHOUT creating a store + /// notification. Focusing/interacting with the panel must still clear it, + /// mirroring the notification-store acknowledgement path. Before the fix, + /// `dismissNotification` bailed out early (no store notification to mark + /// read) and the badge stayed stuck on "Needs input". + func testFocusingWorkspaceClearsFeedRoutedNeedsInputAttention() throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = appDelegate.tabManager ?? TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = true + FeedCoordinatorTestHooks.attentionSurfaceObserver = nil + + let workspace = manager.addWorkspace(select: true) + defer { + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + FeedCoordinatorTestHooks.attentionSurfaceObserver = nil + } + + let panelId = try XCTUnwrap(workspace.focusedPanelId) + + // Seed feed-routed needs-input exactly as a Claude PermissionRequest does. + let event = WorkstreamEvent( + sessionId: "claude-focus-clear-test", + hookEventName: .permissionRequest, + source: "claude", + cwd: "/tmp", + toolName: "Bash", + toolInputJSON: #"{"command":"true"}"#, + requestId: "focus-clear-request" + ) + let target = try XCTUnwrap( + FeedCoordinator.shared.surfaceBlockingDecisionAttention( + event: event, + resolved: (workspaceId: workspace.id, surfaceId: panelId) + ) + ) + + XCTAssertEqual(workspace.statusEntries["claude_code"]?.value, "Needs input") + XCTAssertEqual(workspace.statusEntries["claude_code"]?.icon, "bell.fill") + XCTAssertEqual( + workspace.agentLifecycleStatesByPanelId[panelId]?["claude_code"], + .needsInput + ) + + // Clicking/interacting with the panel acknowledges the attention. This + // returns false and leaves the badge stuck before the fix. + let didDismiss = manager.dismissNotificationOnTerminalInteraction( + tabId: workspace.id, + surfaceId: panelId + ) + + XCTAssertTrue(didDismiss) + XCTAssertNil(workspace.statusEntries["claude_code"]) + XCTAssertNotEqual( + workspace.agentLifecycleStatesByPanelId[panelId]?["claude_code"], + .needsInput + ) + + // Concluding the already-acknowledged decision must be a safe no-op. + FeedCoordinator.shared.concludeBlockingDecisionAttention(target) + XCTAssertNil(workspace.statusEntries["claude_code"]) + } } diff --git a/cmuxTests/TerminalNotificationQueueTests.swift b/cmuxTests/TerminalNotificationQueueTests.swift index 031597cf982a..ef3a5445fd21 100644 --- a/cmuxTests/TerminalNotificationQueueTests.swift +++ b/cmuxTests/TerminalNotificationQueueTests.swift @@ -93,6 +93,289 @@ final class TerminalNotificationQueueTests: XCTestCase { ) } + func testNotifyTargetAsyncAgentStatusKeyAcknowledgesLocalizedTitle() throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = appDelegate.tabManager ?? TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + + let workspace = manager.addWorkspace(select: true) + defer { + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + } + + let focusedPanelId = try XCTUnwrap(workspace.focusedPanelId) + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Needs input", + icon: "bell.fill", + color: "#4C8DFF", + priority: 100 + ) + workspace.recordAgentPID( + key: "claude_code.session-localized-title", + pid: pid_t(12345), + panelId: focusedPanelId, + refreshPorts: false + ) + + let args = """ + \(workspace.id.uuidString) \(focusedPanelId.uuidString) --agent-status-key=claude_code Localized Claude Code|Waiting|Claude needs your input + """ + XCTAssertEqual(TerminalController.debugNotifyTargetQueuedResponseForTesting(args), "OK") + TerminalMutationBus.shared.drainForTesting() + + let notification = try XCTUnwrap(store.notifications.first) + XCTAssertEqual(notification.title, "Localized Claude Code") + + store.markRead(id: notification.id) + + let status = try XCTUnwrap(workspace.statusEntries["claude_code"]) + XCTAssertEqual(status.value, "Idle") + XCTAssertEqual(status.icon, "pause.circle.fill") + XCTAssertEqual(status.color, "#8E8E93") + XCTAssertEqual(status.priority, 0) + } + + func testMarkReadKeepsAgentStatusWhenMatchingQueuedNotificationIsPending() throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = appDelegate.tabManager ?? TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + TerminalMutationBus.shared.setDrainsSuspendedForTesting(true) + + let workspace = manager.addWorkspace(select: true) + defer { + TerminalMutationBus.shared.discardPendingNotifications() + TerminalMutationBus.shared.setDrainsSuspendedForTesting(false) + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + } + + let focusedPanelId = try XCTUnwrap(workspace.focusedPanelId) + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Needs input", + icon: "bell.fill", + color: "#4C8DFF", + priority: 100 + ) + workspace.recordAgentPID( + key: "claude_code.session-queued-needs-input", + pid: pid_t(12345), + panelId: focusedPanelId, + refreshPorts: false + ) + store.addNotification( + tabId: workspace.id, + surfaceId: focusedPanelId, + title: "Claude Code", + subtitle: "Waiting", + body: "Claude needs your input", + structuredAgentStatusKey: "claude_code" + ) + TerminalMutationBus.shared.enqueueNotification( + tabId: workspace.id, + surfaceId: focusedPanelId, + title: "Localized Claude Code", + subtitle: "Waiting", + body: "Claude still needs your input", + structuredAgentStatusKey: "claude_code" + ) + + let deliveredNotification = try XCTUnwrap(store.notifications.first) + store.markRead(id: deliveredNotification.id) + + let statusBeforeQueuedDelivery = try XCTUnwrap(workspace.statusEntries["claude_code"]) + XCTAssertEqual(statusBeforeQueuedDelivery.value, "Needs input") + XCTAssertEqual(statusBeforeQueuedDelivery.icon, "bell.fill") + + TerminalMutationBus.shared.drainForTesting() + + XCTAssertTrue(store.hasUnreadNotification(forTabId: workspace.id, surfaceId: focusedPanelId)) + } + + func testMarkReadKeepsAgentStatusWhenPolicyHookNotificationIsPending() async throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = TabManager() + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "cmux-notification-policy-\(UUID().uuidString)", + isDirectory: true + ) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let configURL = root.appendingPathComponent("cmux.json") + try """ + { + "notifications": { + "hooks": [{ "id": "global", "command": "cat" }] + } + } + """.write(to: configURL, atomically: true, encoding: .utf8) + let cmuxConfigStore = CmuxConfigStore(globalConfigPath: configURL.path, startFileWatchers: false) + cmuxConfigStore.loadAll() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + let asyncNotificationDelivered = expectation(description: "policy hook notification delivered") + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, notification in + if notification.title == "Localized Claude Code" { + asyncNotificationDelivered.fulfill() + } + } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + + let workspace = manager.addWorkspace(select: true) + let windowId = appDelegate.registerMainWindowContextForTesting( + tabManager: manager, + cmuxConfigStore: cmuxConfigStore + ) + defer { + appDelegate.unregisterMainWindowContextForTesting(windowId: windowId) + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + try? FileManager.default.removeItem(at: root) + } + + let focusedPanelId = try XCTUnwrap(workspace.focusedPanelId) + workspace.statusEntries["claude_code"] = SidebarStatusEntry( + key: "claude_code", + value: "Needs input", + icon: "bell.fill", + color: "#4C8DFF", + priority: 100 + ) + workspace.recordAgentPID( + key: "claude_code.session-policy-hook-needs-input", + pid: pid_t(12345), + panelId: focusedPanelId, + refreshPorts: false + ) + store.replaceNotificationsForTesting([ + TerminalNotification( + id: UUID(), + tabId: workspace.id, + surfaceId: focusedPanelId, + panelId: focusedPanelId, + structuredAgentStatusKey: "claude_code", + title: "Claude Code", + subtitle: "Waiting", + body: "Claude needs your input", + createdAt: Date(), + isRead: false + ), + ]) + + store.addNotification( + tabId: workspace.id, + surfaceId: focusedPanelId, + title: "Localized Claude Code", + subtitle: "Waiting", + body: "Claude still needs your input", + structuredAgentStatusKey: "claude_code" + ) + let deliveredNotification = try XCTUnwrap( + store.notifications.first(where: { $0.title == "Claude Code" }) + ) + store.markRead(id: deliveredNotification.id) + + let statusBeforePolicyDelivery = try XCTUnwrap(workspace.statusEntries["claude_code"]) + XCTAssertEqual(statusBeforePolicyDelivery.value, "Needs input") + XCTAssertEqual(statusBeforePolicyDelivery.icon, "bell.fill") + + await fulfillment(of: [asyncNotificationDelivered], timeout: 2.0) + + XCTAssertTrue(store.notifications.contains { notification in + notification.title == "Localized Claude Code" && !notification.isRead + }) + } + + func testNotifyTargetAsyncMalformedAgentStatusOptionPreservesPayloadText() throws { + let store = TerminalNotificationStore.shared + let appDelegate = AppDelegate.shared ?? AppDelegate() + let manager = appDelegate.tabManager ?? TabManager() + + let originalTabManager = appDelegate.tabManager + let originalNotificationStore = appDelegate.notificationStore + let originalAppFocusOverride = AppFocusState.overrideIsFocused + + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + AppFocusState.overrideIsFocused = false + TerminalMutationBus.shared.setDrainsSuspendedForTesting(true) + + let workspace = manager.addWorkspace(select: true) + defer { + TerminalMutationBus.shared.discardPendingNotifications() + TerminalMutationBus.shared.setDrainsSuspendedForTesting(false) + if manager.tabs.contains(where: { $0.id == workspace.id }) { + manager.closeWorkspace(workspace) + } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalNotificationStore + AppFocusState.overrideIsFocused = originalAppFocusOverride + } + + let focusedPanelId = try XCTUnwrap(workspace.focusedPanelId) + let args = """ + \(workspace.id.uuidString) \(focusedPanelId.uuidString) --agent-status-key=claude_codeTitle|Waiting|Body + """ + XCTAssertEqual(TerminalController.debugNotifyTargetQueuedResponseForTesting(args), "OK") + TerminalMutationBus.shared.drainForTesting() + + let notification = try XCTUnwrap(store.notifications.first) + XCTAssertEqual(notification.title, "claude_codeTitle") + XCTAssertEqual(notification.subtitle, "Waiting") + XCTAssertEqual(notification.body, "Body") + XCTAssertNil(notification.structuredAgentStatusKey) + } + func testClearNotificationsDropsQueuedNotifyBeforeDrain() throws { let store = TerminalNotificationStore.shared let appDelegate = AppDelegate.shared ?? AppDelegate() diff --git a/tests/test_claude_hook_stop_last_assistant.py b/tests/test_claude_hook_stop_last_assistant.py index d9e63b3275b1..27816ba6b2aa 100644 --- a/tests/test_claude_hook_stop_last_assistant.py +++ b/tests/test_claude_hook_stop_last_assistant.py @@ -253,7 +253,7 @@ def main() -> int: return 1 notify = notify_commands[-1] - expected_payload = f"notify_target_async {workspace_id} {surface_id} Claude Code|Completed in fun|2" + expected_payload = f"notify_target_async {workspace_id} {surface_id} --agent-status-key=claude_code Claude Code|Completed in fun|2" if notify != expected_payload: print("FAIL: expected stop notification to use final assistant text") print(f"expected={expected_payload!r}")