From 246bf25f50295b456517123ecce5e6ce9e368fda Mon Sep 17 00:00:00 2001 From: Austin Wang Date: Fri, 18 Sep 2026 20:44:42 -0700 Subject: [PATCH 1/3] Test Cloud notification dismiss parity across the two sidebars Regression tests for manaflow-ai/cmux#13000: a Cloud notification must have one read state. Rows come off the daemon feed, become local records through the provider's placement and delivery, and every dismissal path (click into the pane, workspace visit, banner click, `clear_notifications`, mark-all-read, a dismissal while the machine's sync is gone) must clear the store record, the left sidebar summary, the pane ring, and the Cloud tree workspace and terminal rows at once, including after a stale daemon snapshot and a provider rebuild from durable state. Also covers a gate-dropped identical repeat row, a burst over the per-machine admission rate, a remote workspace with no local workspace (which must not stack onto another workspace's badge), and a workspace-level row read by visiting the workspace (manaflow-ai/cmux#12387, as a CmuxNotifications package test). The suite is a focused non-tolerant CI gate (ci.yml, cmux_unit_test_shard.py), since the sharded app-host step tolerates Swift Testing failures. To compile the tests against the real pieces, this commit also extracts the provider's placement and delivery into `CloudNotificationPlacementResolver` and `CloudNotificationLocalDelivery` with their current behavior, types the deliverer's result as `CloudNotificationDeliveryOutcome` with the current mapping, makes `CloudNotificationSyncHub` constructible with an injected store/gate (moved to its own file), adds the store's read-target observer hook with no consumer yet, and moves the store's settings enums to `TerminalNotificationStoreSettings.swift` to stay within the file budget. No behavior changes; the new tests fail on the behavior assertions. Co-Authored-By: Claude Fable 5.1 --- .github/workflows/ci.yml | 17 + .../NotificationDismissalModelTests.swift | 43 +- .../CloudNotificationLocalDelivery.swift | 63 +++ .../Cloud/CloudNotificationPlacement.swift | 69 +++ Sources/Cloud/CloudNotificationSync.swift | 159 ++---- Sources/Cloud/CloudNotificationSyncHub.swift | 128 +++++ ...CmuxTuiSurfaceProvider+Notifications.swift | 98 ++-- Sources/TerminalNotificationStore.swift | 117 +---- .../TerminalNotificationStoreSettings.swift | 112 +++++ cmux.xcodeproj/project.pbxproj | 20 + .../CloudNotificationDismissParityTests.swift | 459 ++++++++++++++++++ .../CloudNotificationSyncStoreTests.swift | 6 +- cmuxTests/CloudNotificationSyncTests.swift | 4 +- cmuxTests/CloudSidebarNotificationTests.swift | 6 +- cmuxTests/CloudSidebarScaleTests.swift | 4 +- scripts/ci/cmux_unit_test_shard.py | 1 + tests/test_ci_cmux_unit_test_shard.py | 1 + 17 files changed, 1020 insertions(+), 287 deletions(-) create mode 100644 Sources/Cloud/CloudNotificationLocalDelivery.swift create mode 100644 Sources/Cloud/CloudNotificationPlacement.swift create mode 100644 Sources/Cloud/CloudNotificationSyncHub.swift create mode 100644 Sources/TerminalNotificationStoreSettings.swift create mode 100644 cmuxTests/CloudNotificationDismissParityTests.swift diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1bb7ad1ce765..3a2bc63c1954 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1053,6 +1053,23 @@ jobs: -only-testing:cmuxTests/BrowserSystemProxyMirrorTests \ test-without-building + - name: Run Cloud notification dismiss parity regression + if: ${{ matrix.shard == fromJSON(env.CMUX_APP_HOST_FOCUSED_REGRESSION_SHARD) }} + run: | + # Focused gate for https://github.com/manaflow-ai/cmux/issues/13000. + # The tolerant full-suite step accepts ordinary Swift Testing + # failures, so keep the one-read-state contract between the local + # store, the left sidebar, and the Cloud tree on a non-tolerant + # only-testing invocation. + set -euo pipefail + scripts/ci/run-in-console-session.sh \ + scripts/ci/run-app-host-xcodebuild.sh \ + -xctestrun "$CMUX_APP_HOST_XCTESTRUN" \ + -destination "platform=macOS" \ + CMUX_SKIP_ZIG_BUILD=1 \ + -only-testing:cmuxTests/CloudNotificationDismissParityTests \ + test-without-building + - name: Run agent restore admission regression if: ${{ matrix.shard == fromJSON(env.CMUX_APP_HOST_FOCUSED_REGRESSION_SHARD) }} run: | diff --git a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift index 37dedaeb7af4..61dbcfd25511 100644 --- a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift +++ b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift @@ -98,6 +98,14 @@ private final class FakeHost: NotificationDismissalHosting { func storeMarkRead(workspaceId: UUID, surfaceId: UUID?) { log.append("markRead:\(short(surfaceId))") + // The store's own mark-read is a real mutation: the next read of the + // same target finds nothing left, as the workspace-visit path that + // marks the focused surface and then the workspace level relies on. + if let surfaceId { + unreadNotificationSurfaces.remove(surfaceId) + } else { + workspaceWideUnread.remove(workspaceId) + } } func storeClearManualUnread(workspaceId: UUID) -> Bool { @@ -112,7 +120,7 @@ private final class FakeHost: NotificationDismissalHosting { func storeClearRestoredUnreadIndicator(workspaceId: UUID) -> Bool { log.append("storeClearRestoredUnread") - return restoredWorkspaceUnread.contains(workspaceId) + return restoredWorkspaceUnread.remove(workspaceId) != nil } func storeClearFocusedReadIndicator(workspaceId: UUID, surfaceId: UUID?) { @@ -125,6 +133,7 @@ private final class FakeHost: NotificationDismissalHosting { func workspaceClearRestoredUnreadIndicator(workspaceId: UUID, panelId: UUID) { log.append("panelClearRestoredUnread") + restoredPanelUnread.remove(panelId) } func workspaceTriggerNotificationDismissFlash(workspaceId: UUID, panelId: UUID) { @@ -419,4 +428,36 @@ struct NotificationDismissalModelTests { )) #expect(host.log.contains("markRead:nil")) } + + /// manaflow-ai/cmux#12387: a notification posted without a surface has no + /// pane to focus, so the workspace becoming the visible one is how it is + /// seen. Visiting must read it alongside the focused surface's records. + @Test func visitingWorkspaceReadsWorkspaceLevelNotifications() { + let (model, host, workspaceId, panelId) = makeModel() + host.unreadNotificationSurfaces = [panelId] + host.workspaceWideUnread = [workspaceId] + + model.dismissFocusedPanelNotificationIfActive(workspaceId: workspaceId, context: .activeFocus) + + let prefix = String(panelId.uuidString.prefix(4)) + #expect(host.log == [ + "markRead:\(prefix)", "clearFocusedRead:\(prefix)", "notificationFlash", + "markRead:nil", "clearFocusedRead:nil", + ]) + #expect(host.workspaceWideUnread.isEmpty) + + // A workspace with only workspace-level records, and no focused + // surface at all, is read by the visit alone. + let bare = UUID() + host.selectedWorkspaceId = bare + host.workspaceWideUnread = [bare] + host.log.removeAll() + model.dismissFocusedPanelNotificationIfActive(workspaceId: bare, context: .explicitWorkspaceResume) + #expect(host.log == ["markRead:nil", "clearFocusedRead:nil"]) + + // Nothing left: a second visit is a no-op, not a repeated mutation. + host.log.removeAll() + model.dismissFocusedPanelNotificationIfActive(workspaceId: bare, context: .explicitWorkspaceResume) + #expect(host.log.isEmpty) + } } diff --git a/Sources/Cloud/CloudNotificationLocalDelivery.swift b/Sources/Cloud/CloudNotificationLocalDelivery.swift new file mode 100644 index 000000000000..38d803cee866 --- /dev/null +++ b/Sources/Cloud/CloudNotificationLocalDelivery.swift @@ -0,0 +1,63 @@ +import Foundation + +/// What became of a row handed to the local notification store. +enum CloudNotificationDeliveryOutcome: Equatable, Sendable { + /// A local record exists; the row is consumed. + case delivered + /// Nothing here could take the row yet (no store, a placement that + /// vanished between resolution and delivery); the next fold retries it. + case declined + /// This Mac will never show the row (an admission drop, a muted + /// workspace): it is consumed and acknowledged as read at once, so no + /// indicator anywhere waits for a dismissal that cannot happen. + case suppressed +} + +/// Turns one of a machine's notification rows into a local notification +/// record on the target the placement resolver chose. Owned by the machine's +/// provider; everything it reads arrives through closures so tests drive it +/// against the real store without a link. +@MainActor +struct CloudNotificationLocalDelivery { + let machineID: String + var store: @MainActor () -> TerminalNotificationStore? + /// The hub's admission gate, shared across every live machine. + var admit: @MainActor (CloudVMNotificationRow) -> CloudMachineNotificationGate.Decision + var machineName: @MainActor () -> String + /// The process title of a terminal from the accepted graph, for the + /// subtitle when the producer gave none. + var terminalTitle: @MainActor (_ terminalID: String) -> String? + + func deliver(_ row: CloudVMNotificationRow, to target: CloudNotificationDeliveryTarget) -> CloudNotificationDeliveryOutcome { + guard let store = store() else { return .declined } + // Dropped rows remain consumed by the sync so subsequent catalog folds + // cannot replay a flood. + guard admit(row) == .allowed else { return .delivered } + let terminalTitle = row.terminalID.flatMap(terminalTitle) ?? "" + let machineName = machineName() + let subtitle: String + if let explicit = row.subtitle { + // The producer's own subtitle wins, as `cmux notify --subtitle` does locally. + subtitle = explicit + } else if terminalTitle.isEmpty { + subtitle = machineName + } else { + subtitle = String( + format: String(localized: "cloudNotification.subtitle.machine", defaultValue: "%@ on %@"), + terminalTitle, + machineName + ) + } + let recorded = store.addNotification( + tabId: target.workspaceID, + surfaceId: target.panelID, + title: row.title, + subtitle: subtitle, + body: row.body, + retargetsToLiveSurfaceOwner: target.panelID != nil, + correlationKey: CloudNotificationCorrelation.key(machineID: machineID, notificationID: row.id), + origin: .cloudVM(machineID: machineID) + ) != nil + return recorded ? .delivered : .declined + } +} diff --git a/Sources/Cloud/CloudNotificationPlacement.swift b/Sources/Cloud/CloudNotificationPlacement.swift new file mode 100644 index 000000000000..3cc3bab711ec --- /dev/null +++ b/Sources/Cloud/CloudNotificationPlacement.swift @@ -0,0 +1,69 @@ +import Foundation + +/// Which local notification records a read action covers, in the local +/// store's own terms. Mirrors `TerminalNotification.matches(tabId:surfaceId:)`: +/// `.workspace` covers every record in the workspace, `.surface` with a nil +/// surface covers only the workspace-level records, and `.all` covers +/// everything. Cloud rows are placed with the same vocabulary, so a read of a +/// target also covers the rows that would land there. +enum NotificationReadTarget: Equatable, Sendable { + case all + case workspace(UUID) + case surface(workspaceID: UUID, surfaceID: UUID?) +} + +extension CloudNotificationDeliveryTarget { + /// Whether a read of `target` covers a row placed here, by the rule the + /// store applies to its own records. + func isCovered(by target: NotificationReadTarget) -> Bool { + switch target { + case .all: + return true + case .workspace(let workspaceID): + return self.workspaceID == workspaceID + case .surface(let workspaceID, let surfaceID): + return self.workspaceID == workspaceID && panelID == surfaceID + } + } +} + +/// A local workspace bound to a machine, as the placement resolver sees it. +struct CloudNotificationBoundWorkspace: Equatable, Sendable { + let workspaceID: UUID + let remoteWorkspaceID: String? +} + +/// Where one of a machine's notifications lands on this Mac, resolved from the +/// catalog as it is right now, never from the placement at delivery time. The +/// same resolver answers both "where does this row go" at delivery and "which +/// rows does a read of this workspace or pane cover" at dismissal, so the two +/// can never disagree. +@MainActor +struct CloudNotificationPlacementResolver { + let machine: SurfaceMachineID + /// Local panes showing a resource of this machine. + var projections: @MainActor (SurfaceResourceID) -> [SurfaceProjection] + /// The remote workspace whose tab shows the terminal, from the accepted graph. + var remoteWorkspaceID: @MainActor (_ terminalID: String) -> String? + /// Local workspaces bound to the machine, in sidebar order. + var boundWorkspaces: @MainActor () -> [CloudNotificationBoundWorkspace] + + /// The pane showing the terminal when one is open on this Mac, else the + /// local workspace bound to the terminal's remote workspace, else any local + /// workspace bound to the machine. No local placement means the row stays + /// undelivered until one exists; the Cloud tree still shows the dot. + func target(for row: CloudVMNotificationRow) -> CloudNotificationDeliveryTarget? { + if let terminalID = row.terminalID { + let resource = SurfaceResourceID(machine: machine, kind: .terminal, key: terminalID) + if let projection = projections(resource).first { + return CloudNotificationDeliveryTarget(workspaceID: projection.workspaceID, panelID: projection.panelID) + } + } + let bound = boundWorkspaces() + if let remoteWorkspaceID = row.terminalID.flatMap(remoteWorkspaceID), + let exact = bound.first(where: { $0.remoteWorkspaceID == remoteWorkspaceID }) { + return CloudNotificationDeliveryTarget(workspaceID: exact.workspaceID, panelID: nil) + } + return bound.first.map { CloudNotificationDeliveryTarget(workspaceID: $0.workspaceID, panelID: nil) } + } +} diff --git a/Sources/Cloud/CloudNotificationSync.swift b/Sources/Cloud/CloudNotificationSync.swift index e5ec70c961f9..ef6d2460bd93 100644 --- a/Sources/Cloud/CloudNotificationSync.swift +++ b/Sources/Cloud/CloudNotificationSync.swift @@ -1,4 +1,3 @@ -import Combine import Foundation // Cloud notifications: the VM's cmux-tui daemon is the source of truth. @@ -236,9 +235,9 @@ struct CloudNotificationDeliveryTarget: Equatable, Sendable { /// `notification.ack` round trip over the link. @MainActor final class CloudNotificationSync { - /// Returns false when the store declined the notification (muted - /// workspace, no store); the row then stays undelivered for a later fold. - typealias Deliverer = @MainActor (CloudVMNotificationRow, CloudNotificationDeliveryTarget) -> Bool + /// A declined row stays undelivered for a later fold; a suppressed row is + /// consumed and read in the same fold (see `CloudNotificationDeliveryOutcome`). + typealias Deliverer = @MainActor (CloudVMNotificationRow, CloudNotificationDeliveryTarget) -> CloudNotificationDeliveryOutcome typealias TargetResolver = @MainActor (CloudVMNotificationRow) -> CloudNotificationDeliveryTarget? typealias AckSender = @MainActor (CloudNotificationSyncState.PendingAck) async throws -> Void typealias UnreadObserver = @MainActor (Set) -> Void @@ -264,11 +263,16 @@ final class CloudNotificationSync { /// key after its provider is gone. private var retired = false + /// The idempotency key of one `notification.ack` batch. + nonisolated static func mintAckKey() -> String { + "mac-ack-\(UUID().uuidString.lowercased())" + } + init( machineID: String, clientID: String, store: CloudNotificationSyncStore, - newKey: @escaping () -> String = { "mac-ack-\(UUID().uuidString.lowercased())" }, + newKey: @escaping () -> String = CloudNotificationSync.mintAckKey, resolveTarget: @escaping TargetResolver, deliver: @escaping Deliverer, send: @escaping AckSender, @@ -312,12 +316,27 @@ final class CloudNotificationSync { withdraw(plan.removed) } var undelivered: [String] = [] - for (row, target) in placed where !deliver(row, target) { - undelivered.append(row.id) + var suppressed: [String] = [] + for (row, target) in placed { + switch deliver(row, target) { + case .delivered: + break + case .declined: + undelivered.append(row.id) + case .suppressed: + suppressed.append(row.id) + } } - if !undelivered.isEmpty { + if !undelivered.isEmpty || !suppressed.isEmpty { + // Built on the current state, not `next`: a delivery can re-enter + // through the store and commit in between. var declined = state declined.delivered.removeAll { undelivered.contains($0) } + if !suppressed.isEmpty { + declined = CloudNotificationSyncReducer.recordRead( + ids: suppressed, rows: rows, clientID: clientID, state: declined, newKey: newKey + ) + } commit(declined) } requestFlush() @@ -338,6 +357,29 @@ final class CloudNotificationSync { requestFlush() } + /// Local reads by target: every unread row whose current placement the + /// read covers is acknowledged, whether or not it ever became a local + /// record (an admission drop, a row placed elsewhere before the terminal + /// was opened here). Returns the ids so the caller can mirror the read + /// onto local records that live on another workspace. + @discardableResult + func noteRead(coveredBy target: NotificationReadTarget) -> [String] { + guard !retired else { return [] } + let pending = state.pendingIDs + let read = state.readIDs + var ids: [String] = [] + for row in rows where !row.isRead(by: clientID) && !read.contains(row.id) && !pending.contains(row.id) { + if case .all = target { + ids.append(row.id) + } else if let placement = resolveTarget(row), placement.isCovered(by: target) { + ids.append(row.id) + } + } + guard !ids.isEmpty else { return [] } + noteRead(notificationIDs: ids) + return ids + } + /// The link came back. Anything still pending is retried now. func linkDidConnect() { guard !retired else { return } @@ -416,104 +458,3 @@ final class CloudNotificationSync { } } } - -extension Notification.Name { - /// Posted on the main actor after a machine's unread terminal set changes. - static let cmuxCloudNotificationUnreadDidChange = Notification.Name("cmux.cloudNotifications.unreadDidChange") -} - -/// App-wide registry of per-machine syncs. Owns the one subscription on the -/// notification store that turns local reads into acknowledgements, and the -/// unread index the Cloud tree renders. -@MainActor -final class CloudNotificationSyncHub { - static let shared = CloudNotificationSyncHub() - let persistenceStore = CloudNotificationSyncStore() - private var syncs: [String: CloudNotificationSync] = [:] - private var notificationGate = CloudMachineNotificationGate() - - /// One admission budget across all live machine providers. Dropped rows remain - /// consumed by the sync so subsequent catalog folds cannot replay a flood. - func admit(_ row: CloudVMNotificationRow, machineID: String) -> Bool { - notificationGate.admit(machineID: machineID, event: CloudMachineNotificationEvent( - id: row.id, terminalID: row.terminalID, title: row.title, body: row.body - )) == .allowed - } - private(set) var unreadTerminalIDs: [String: Set] = [:] - private var storeSubscription: AnyCancellable? - private var unreadCloudKeys: Set? - - func register(_ sync: CloudNotificationSync) { - syncs[sync.machineID] = sync - observeStoreIfNeeded() - } - - func unregister(machineID: String) { - syncs.removeValue(forKey: machineID) - if unreadTerminalIDs.removeValue(forKey: machineID) != nil { - NotificationCenter.default.post(name: .cmuxCloudNotificationUnreadDidChange, object: nil) - } - } - - func sync(machineID: String) -> CloudNotificationSync? { - syncs[machineID] - } - - func setUnread(_ terminalIDs: Set, machineID: String) { - if terminalIDs.isEmpty { - guard unreadTerminalIDs.removeValue(forKey: machineID) != nil else { return } - } else { - guard unreadTerminalIDs[machineID] != terminalIDs else { return } - unreadTerminalIDs[machineID] = terminalIDs - } - #if DEBUG - cmuxDebugLog("cloud.notifications.unread machine=\(machineID) terminals=\(terminalIDs.count)") - #endif - NotificationCenter.default.post(name: .cmuxCloudNotificationUnreadDidChange, object: nil) - } - - /// Correlation keys of cloud notifications that were unread in `previous` - /// and are read or gone in `current`. A dismissal counts as a read: the - /// person chose not to see it again, on this Mac and on the machine. - static func newlyReadKeys(previous: Set, current: [TerminalNotification]) -> (read: Set, unread: Set) { - var unread = Set() - for notification in current where !notification.isRead { - if let key = notification.correlationKey, key.hasPrefix(CloudNotificationCorrelation.prefix) { - unread.insert(key) - } - } - return (previous.subtracting(unread), unread) - } - - private func observeStoreIfNeeded() { - guard storeSubscription == nil, let store = AppDelegate.shared?.notificationStore else { return } - storeSubscription = store.$notifications - .receive(on: RunLoop.main) - .sink { [weak self] notifications in - MainActor.assumeIsolated { - self?.storeDidChange(notifications) - } - } - } - - func storeDidChange(_ notifications: [TerminalNotification]) { - guard let previous = unreadCloudKeys else { - // First observation seeds the baseline. Rows restored from the - // durable feed history as already-read never become acks here; - // the daemon already has them or they were read elsewhere. - unreadCloudKeys = Self.newlyReadKeys(previous: [], current: notifications).unread - return - } - let (read, unread) = Self.newlyReadKeys(previous: previous, current: notifications) - unreadCloudKeys = unread - guard !read.isEmpty else { return } - var byMachine: [String: [String]] = [:] - for key in read { - guard let parsed = CloudNotificationCorrelation.parse(key) else { continue } - byMachine[parsed.machineID, default: []].append(parsed.notificationID) - } - for (machineID, ids) in byMachine { - syncs[machineID]?.noteRead(notificationIDs: ids) - } - } -} diff --git a/Sources/Cloud/CloudNotificationSyncHub.swift b/Sources/Cloud/CloudNotificationSyncHub.swift new file mode 100644 index 000000000000..f3b174a66e94 --- /dev/null +++ b/Sources/Cloud/CloudNotificationSyncHub.swift @@ -0,0 +1,128 @@ +import Combine +import Foundation + +extension Notification.Name { + /// Posted on the main actor after a machine's unread terminal set changes. + static let cmuxCloudNotificationUnreadDidChange = Notification.Name("cmux.cloudNotifications.unreadDidChange") +} + +/// App-wide registry of per-machine syncs. Owns the one subscription on the +/// notification store that turns local reads into acknowledgements, and the +/// unread index the Cloud tree renders. +@MainActor +final class CloudNotificationSyncHub { + static let shared = CloudNotificationSyncHub() + let persistenceStore: CloudNotificationSyncStore + private var syncs: [String: CloudNotificationSync] = [:] + private var notificationGate: CloudMachineNotificationGate + + /// Defaults resolve here rather than as default arguments: the store is + /// main-actor isolated and cannot be constructed in a default-argument + /// context. + init( + persistenceStore: CloudNotificationSyncStore? = nil, + gate: CloudMachineNotificationGate = CloudMachineNotificationGate() + ) { + self.persistenceStore = persistenceStore ?? CloudNotificationSyncStore() + notificationGate = gate + } + + /// One admission budget across all live machine providers. + func admit(_ row: CloudVMNotificationRow, machineID: String) -> CloudMachineNotificationGate.Decision { + notificationGate.admit(machineID: machineID, event: CloudMachineNotificationEvent( + id: row.id, terminalID: row.terminalID, title: row.title, body: row.body + )) + } + private(set) var unreadTerminalIDs: [String: Set] = [:] + private var storeSubscription: AnyCancellable? + private weak var store: TerminalNotificationStore? + private var unreadCloudKeys: Set? + + func register(_ sync: CloudNotificationSync) { + syncs[sync.machineID] = sync + observeStoreIfNeeded() + } + + func unregister(machineID: String) { + syncs.removeValue(forKey: machineID) + if unreadTerminalIDs.removeValue(forKey: machineID) != nil { + NotificationCenter.default.post(name: .cmuxCloudNotificationUnreadDidChange, object: nil) + } + } + + func sync(machineID: String) -> CloudNotificationSync? { + syncs[machineID] + } + + func setUnread(_ terminalIDs: Set, machineID: String) { + if terminalIDs.isEmpty { + guard unreadTerminalIDs.removeValue(forKey: machineID) != nil else { return } + } else { + guard unreadTerminalIDs[machineID] != terminalIDs else { return } + unreadTerminalIDs[machineID] = terminalIDs + } + #if DEBUG + cmuxDebugLog("cloud.notifications.unread machine=\(machineID) terminals=\(terminalIDs.count)") + #endif + NotificationCenter.default.post(name: .cmuxCloudNotificationUnreadDidChange, object: nil) + } + + /// Correlation keys of cloud notifications that were unread in `previous` + /// and are read or gone in `current`. A dismissal counts as a read: the + /// person chose not to see it again, on this Mac and on the machine. + static func newlyReadKeys(previous: Set, current: [TerminalNotification]) -> (read: Set, unread: Set) { + var unread = Set() + for notification in current where !notification.isRead { + if let key = notification.correlationKey, key.hasPrefix(CloudNotificationCorrelation.prefix) { + unread.insert(key) + } + } + return (previous.subtracting(unread), unread) + } + + private func observeStoreIfNeeded() { + guard store == nil, let store = AppDelegate.shared?.notificationStore else { return } + attach(store: store) + } + + /// Binds the hub to the local store: local records that become read or + /// are dismissed acknowledge their rows. + func attach(store: TerminalNotificationStore) { + guard self.store !== store else { return } + self.store = store + unreadCloudKeys = nil + storeSubscription = store.$notifications + .receive(on: RunLoop.main) + .sink { [weak self] notifications in + MainActor.assumeIsolated { + self?.storeDidChange(notifications) + } + } + } + + func storeDidChange(_ notifications: [TerminalNotification]) { + guard let previous = unreadCloudKeys else { + // First observation seeds the baseline. Rows restored from the + // durable feed history as already-read never become acks here; + // the daemon already has them or they were read elsewhere. + unreadCloudKeys = Self.newlyReadKeys(previous: [], current: notifications).unread + return + } + let (read, unread) = Self.newlyReadKeys(previous: previous, current: notifications) + unreadCloudKeys = unread + guard !read.isEmpty else { return } + var byMachine: [String: [String]] = [:] + for key in read { + guard let parsed = CloudNotificationCorrelation.parse(key) else { continue } + byMachine[parsed.machineID, default: []].append(parsed.notificationID) + } + for (machineID, ids) in byMachine { + noteRead(notificationIDs: ids, machineID: machineID) + } + } + + /// Reads by daemon row id. + func noteRead(notificationIDs ids: [String], machineID: String) { + syncs[machineID]?.noteRead(notificationIDs: ids) + } +} diff --git a/Sources/Surfaces/CmuxTuiSurfaceProvider+Notifications.swift b/Sources/Surfaces/CmuxTuiSurfaceProvider+Notifications.swift index 886ed0489bdd..0f35dd1a365f 100644 --- a/Sources/Surfaces/CmuxTuiSurfaceProvider+Notifications.swift +++ b/Sources/Surfaces/CmuxTuiSurfaceProvider+Notifications.swift @@ -7,11 +7,12 @@ extension CmuxTuiSurfaceProvider { // policy disables Cloud, so no policy check is repeated here. let machineID = self.machineID let clientID = CloudTuiClientPaths().notificationClientID() + let hub = CloudNotificationSyncHub.shared let sync = CloudNotificationSync( machineID: machineID, - clientID: clientID, store: CloudNotificationSyncHub.shared.persistenceStore, + clientID: clientID, store: hub.persistenceStore, resolveTarget: { [weak self] row in self?.notificationDeliveryTarget(for: row) }, - deliver: { [weak self] row, target in self?.deliverNotification(row, to: target) ?? false }, + deliver: { [weak self] row, target in self?.deliverNotification(row, to: target) ?? .declined }, send: { [weak self] batch in // A vanished provider must not report success: the batch stays // pending in the durable state for the replacement sync. @@ -28,7 +29,7 @@ extension CmuxTuiSurfaceProvider { )) }, unreadChanged: { terminalIDs in - CloudNotificationSyncHub.shared.setUnread(terminalIDs, machineID: machineID) + hub.setUnread(terminalIDs, machineID: machineID) }, withdraw: { ids in // `cmux notify --clear` on the machine, or ledger eviction: @@ -41,7 +42,7 @@ extension CmuxTuiSurfaceProvider { } ) notificationSync = sync - CloudNotificationSyncHub.shared.register(sync) + hub.register(sync) notificationPlacementObserver = NotificationCenter.default.addObserver( forName: SurfaceCatalog.didChangeNotification, object: nil, @@ -63,63 +64,40 @@ extension CmuxTuiSurfaceProvider { cmuxDebugLog("cloud.notifications.sync machine=\(machineID) revision=\((state.cursor?.revision).map(String.init) ?? "nil") rows=\(rows.count) unreadTerminals=\(notificationSync.unreadTerminalIDs.count) pending=\(notificationSync.state.pendingAcks.count)") #endif } - /// The pane showing the terminal when one is open on this Mac, else the - /// local workspace bound to the terminal's remote workspace, else any - /// local workspace bound to the machine. No local placement means the row - /// stays undelivered until one exists; the Cloud tree still shows the dot. - func notificationDeliveryTarget(for row: CloudVMNotificationRow) -> CloudNotificationDeliveryTarget? { - if let terminalID = row.terminalID { - let resourceID = SurfaceResourceID(machine: machine, kind: .terminal, key: terminalID) - if let projection = catalog.projections(of: resourceID).first { - return CloudNotificationDeliveryTarget(workspaceID: projection.workspaceID, panelID: projection.panelID) - } - } - let remoteWorkspaceID = row.terminalID.flatMap { terminalID -> String? in - guard let state = cloudState else { return nil } - for tab in state.tabs where tab.contentID == terminalID { - guard let pane = state.lookupIndex.pane(id: tab.paneID), - let screen = state.lookupIndex.screen(id: pane.screenID) else { continue } - return screen.workspaceID + /// Placement from the catalog as it is right now; see + /// `CloudNotificationPlacementResolver`. + var notificationPlacementResolver: CloudNotificationPlacementResolver { + CloudNotificationPlacementResolver( + machine: machine, + projections: { [catalog] in catalog.projections(of: $0) }, + remoteWorkspaceID: { [weak self] terminalID in + guard let state = self?.cloudState else { return nil } + for tab in state.tabs where tab.contentID == terminalID { + guard let pane = state.lookupIndex.pane(id: tab.paneID), + let screen = state.lookupIndex.screen(id: pane.screenID) else { continue } + return screen.workspaceID + } + return nil + }, + boundWorkspaces: { [machineID] in + (AppDelegate.shared?.tabManager?.tabs ?? []).compactMap { workspace in + guard let binding = workspace.cloudVMBinding, binding.vmID == machineID else { return nil } + return CloudNotificationBoundWorkspace(workspaceID: workspace.id, remoteWorkspaceID: binding.remoteWorkspaceID) + } } - return nil - } - let bound = (AppDelegate.shared?.tabManager?.tabs ?? []).filter { $0.cloudVMBinding?.vmID == machineID } - if let remoteWorkspaceID, - let exact = bound.first(where: { $0.cloudVMBinding?.remoteWorkspaceID == remoteWorkspaceID }) { - return CloudNotificationDeliveryTarget(workspaceID: exact.id, panelID: nil) - } - if let any = bound.first { - return CloudNotificationDeliveryTarget(workspaceID: any.id, panelID: nil) - } - return nil + ) } - func deliverNotification(_ row: CloudVMNotificationRow, to target: CloudNotificationDeliveryTarget) -> Bool { - guard let store = AppDelegate.shared?.notificationStore else { return false } - guard CloudNotificationSyncHub.shared.admit(row, machineID: machineID) else { return true } - let terminalTitle = row.terminalID.flatMap { cloudState?.lookupIndex.terminal(id: $0)?.title } ?? "" - let machineName = summary.preferredName - let subtitle: String - if let explicit = row.subtitle { - // The producer's own subtitle wins, as `cmux notify --subtitle` does locally. - subtitle = explicit - } else if terminalTitle.isEmpty { - subtitle = machineName - } else { - subtitle = String( - format: String(localized: "cloudNotification.subtitle.machine", defaultValue: "%@ on %@"), - terminalTitle, - machineName - ) - } - return store.addNotification( - tabId: target.workspaceID, - surfaceId: target.panelID, - title: row.title, - subtitle: subtitle, - body: row.body, - retargetsToLiveSurfaceOwner: target.panelID != nil, - correlationKey: CloudNotificationCorrelation.key(machineID: machineID, notificationID: row.id), - origin: .cloudVM(machineID: machineID) - ) != nil + func notificationDeliveryTarget(for row: CloudVMNotificationRow) -> CloudNotificationDeliveryTarget? { + notificationPlacementResolver.target(for: row) + } + func deliverNotification(_ row: CloudVMNotificationRow, to target: CloudNotificationDeliveryTarget) -> CloudNotificationDeliveryOutcome { + let machineID = self.machineID + return CloudNotificationLocalDelivery( + machineID: machineID, + store: { AppDelegate.shared?.notificationStore }, + admit: { CloudNotificationSyncHub.shared.admit($0, machineID: machineID) }, + machineName: { [summary] in summary.preferredName }, + terminalTitle: { [weak self] in self?.cloudState?.lookupIndex.terminal(id: $0)?.title } + ).deliver(row, to: target) } } diff --git a/Sources/TerminalNotificationStore.swift b/Sources/TerminalNotificationStore.swift index 4a8927ebd4e8..daf4d4e1d9c6 100644 --- a/Sources/TerminalNotificationStore.swift +++ b/Sources/TerminalNotificationStore.swift @@ -23,113 +23,6 @@ extension TerminalNotificationStore { phoneForwardingEnabled && categoryAllowsDelivery } } -enum NotificationBadgeSettings { - static let dockBadgeEnabledKey = "notificationDockBadgeEnabled" - static let defaultDockBadgeEnabled = true - - static func isDockBadgeEnabled(defaults: UserDefaults = .standard) -> Bool { - if defaults.object(forKey: dockBadgeEnabledKey) == nil { - return defaultDockBadgeEnabled - } - return defaults.bool(forKey: dockBadgeEnabledKey) - } -} - -enum NotificationPaneRingSettings { - static let enabledKey = "notificationPaneRingEnabled" - static let defaultEnabled = true -} - -enum NotificationPaneFlashSettings { - static let enabledKey = "notificationPaneFlashEnabled" - static let defaultEnabled = true - - static func isEnabled(defaults: UserDefaults = .standard) -> Bool { - if defaults.object(forKey: enabledKey) == nil { - return defaultEnabled - } - return defaults.bool(forKey: enabledKey) - } -} - -enum TaggedRunBadgeSettings { - static let environmentKey = "CMUX_TAG" - private static let maxTagLength = 10 - - static func normalizedTag(from env: [String: String] = ProcessInfo.processInfo.environment) -> String? { - normalizedTag(env[environmentKey]) - } - - static func normalizedTag(_ rawTag: String?) -> String? { - guard var tag = rawTag?.trimmingCharacters(in: .whitespacesAndNewlines), !tag.isEmpty else { - return nil - } - if tag.count > maxTagLength { - tag = String(tag.prefix(maxTagLength)) - } - return tag - } -} - -enum AppFocusState { - static var overrideIsFocused: Bool? - - static func isAppActive() -> Bool { - if let overrideIsFocused { - return overrideIsFocused - } - return NSApp.isActive - } - - static func isAppFocused() -> Bool { - if let overrideIsFocused { - return overrideIsFocused - } - guard NSApp.isActive else { return false } - guard let keyWindow = NSApp.keyWindow, keyWindow.isKeyWindow else { return false } - // Only treat the app as "focused" for notification suppression when a main terminal window - // is key. If Settings/About/debug panels are key, we still want notifications to show. - if let raw = keyWindow.identifier?.rawValue { - return raw == "cmux.main" || raw.hasPrefix("cmux.main.") - } - return false - } - -} - -enum NotificationAuthorizationState: Equatable, Sendable { - case unknown - case notDetermined - case authorized - case denied - case provisional - case ephemeral - - var statusLabel: String { - switch self { - case .unknown, .notDetermined: - return "Not Requested" - case .authorized: - return "Allowed" - case .denied: - return "Denied" - case .provisional: - return "Deliver Quietly" - case .ephemeral: - return "Temporary" - } - } - - var allowsDelivery: Bool { - switch self { - case .authorized, .provisional, .ephemeral: - return true - case .unknown, .notDetermined, .denied: - return false - } - } -} - @MainActor final class TerminalNotificationStore: ObservableObject { private struct TabSurfaceKey: Hashable { @@ -369,6 +262,10 @@ final class TerminalNotificationStore: ObservableObject { /// `@Published`) so its updates stay independent of the store's own /// `objectWillChange`. let sidebarUnread = SidebarUnreadModel() + /// Observes every read or clear applied by target, so unread indicators + /// keyed by other identities (the Cloud tree's remote terminals) follow the + /// dismissal even when no local record exists for what they show. + var readTargetObserver: (@MainActor (NotificationReadTarget) -> Void)? // Workspace panels own their manual unread state on Workspace. Dock panels // have no Workspace owner, so their surface-scoped state lives here beside // the cross-container unread projection. @@ -1914,6 +1811,7 @@ final class TerminalNotificationStore: ObservableObject { } func markRead(forTabId tabId: UUID) { + defer { readTargetObserver?(.workspace(tabId)) } inFlightPolicyRequests.discard(forTabId: tabId, surfaceId: nil) notificationFeedHistory.markRead(inWorkspace: tabId) var updated = notifications @@ -1943,6 +1841,7 @@ final class TerminalNotificationStore: ObservableObject { } func markRead(forTabId tabId: UUID, surfaceId: UUID?) { + defer { readTargetObserver?(.surface(workspaceID: tabId, surfaceID: surfaceId)) } inFlightPolicyRequests.discard(forTabId: tabId, surfaceId: surfaceId) notificationFeedHistory.markRead(inWorkspace: tabId, surfaceId: surfaceId) var updated = notifications @@ -2086,6 +1985,7 @@ final class TerminalNotificationStore: ObservableObject { } func markAllRead() { + defer { readTargetObserver?(.all) } notificationFeedHistory.markAllRead() var updated = notifications var idsToClear: [String] = [] @@ -2242,6 +2142,7 @@ final class TerminalNotificationStore: ObservableObject { private func replaceNotificationsForClear(_ next: [TerminalNotification]) { suppressNotificationDiffPublishing = true; notifications = next; suppressNotificationDiffPublishing = false } func clearAll(discardQueuedNotifications: Bool = true, throughNotificationGeneration: UInt64? = nil) { + defer { readTargetObserver?(.all) } inFlightPolicyRequests.discardAll(through: throughNotificationGeneration) if discardQueuedNotifications { TerminalMutationBus.shared.discardPendingNotifications() } guard !notifications.isEmpty || @@ -2272,6 +2173,7 @@ final class TerminalNotificationStore: ObservableObject { surfaceId: UUID?, discardQueuedNotifications: Bool = true, throughNotificationGeneration: UInt64? = nil ) { + defer { readTargetObserver?(.surface(workspaceID: tabId, surfaceID: surfaceId)) } let liveTabId = surfaceId.flatMap { AppDelegate.shared?.agentNotificationDeliveryTarget(claimedTabId: tabId, surfaceId: $0)?.tabId } ?? tabId let tabIds = Set([tabId, liveTabId]) inFlightPolicyRequests.discard(forTabId: tabId, surfaceId: surfaceId, through: throughNotificationGeneration) @@ -2379,6 +2281,7 @@ final class TerminalNotificationStore: ObservableObject { } } func clearNotifications(forTabId tabId: UUID, discardQueuedNotifications: Bool = true, throughNotificationGeneration: UInt64? = nil) { + defer { readTargetObserver?(.workspace(tabId)) } inFlightPolicyRequests.discard(forTabId: tabId, surfaceId: nil, through: throughNotificationGeneration) if discardQueuedNotifications { TerminalMutationBus.shared.discardPendingNotificationsForClear(tabId: tabId, surfaceId: nil) } let hadFocusedReadIndicator = focusedReadIndicatorByTabId[tabId] != nil diff --git a/Sources/TerminalNotificationStoreSettings.swift b/Sources/TerminalNotificationStoreSettings.swift new file mode 100644 index 000000000000..c9eaa47da1a6 --- /dev/null +++ b/Sources/TerminalNotificationStoreSettings.swift @@ -0,0 +1,112 @@ +import AppKit +import Foundation + +// Settings and focus helpers the notification store reads. Extracted from +// TerminalNotificationStore.swift, which sits at its file-length budget. + +enum NotificationBadgeSettings { + static let dockBadgeEnabledKey = "notificationDockBadgeEnabled" + static let defaultDockBadgeEnabled = true + + static func isDockBadgeEnabled(defaults: UserDefaults = .standard) -> Bool { + if defaults.object(forKey: dockBadgeEnabledKey) == nil { + return defaultDockBadgeEnabled + } + return defaults.bool(forKey: dockBadgeEnabledKey) + } +} + +enum NotificationPaneRingSettings { + static let enabledKey = "notificationPaneRingEnabled" + static let defaultEnabled = true +} + +enum NotificationPaneFlashSettings { + static let enabledKey = "notificationPaneFlashEnabled" + static let defaultEnabled = true + + static func isEnabled(defaults: UserDefaults = .standard) -> Bool { + if defaults.object(forKey: enabledKey) == nil { + return defaultEnabled + } + return defaults.bool(forKey: enabledKey) + } +} + +enum TaggedRunBadgeSettings { + static let environmentKey = "CMUX_TAG" + private static let maxTagLength = 10 + + static func normalizedTag(from env: [String: String] = ProcessInfo.processInfo.environment) -> String? { + normalizedTag(env[environmentKey]) + } + + static func normalizedTag(_ rawTag: String?) -> String? { + guard var tag = rawTag?.trimmingCharacters(in: .whitespacesAndNewlines), !tag.isEmpty else { + return nil + } + if tag.count > maxTagLength { + tag = String(tag.prefix(maxTagLength)) + } + return tag + } +} + +enum AppFocusState { + static var overrideIsFocused: Bool? + + static func isAppActive() -> Bool { + if let overrideIsFocused { + return overrideIsFocused + } + return NSApp.isActive + } + + static func isAppFocused() -> Bool { + if let overrideIsFocused { + return overrideIsFocused + } + guard NSApp.isActive else { return false } + guard let keyWindow = NSApp.keyWindow, keyWindow.isKeyWindow else { return false } + // Only treat the app as "focused" for notification suppression when a main terminal window + // is key. If Settings/About/debug panels are key, we still want notifications to show. + if let raw = keyWindow.identifier?.rawValue { + return raw == "cmux.main" || raw.hasPrefix("cmux.main.") + } + return false + } + +} + +enum NotificationAuthorizationState: Equatable, Sendable { + case unknown + case notDetermined + case authorized + case denied + case provisional + case ephemeral + + var statusLabel: String { + switch self { + case .unknown, .notDetermined: + return "Not Requested" + case .authorized: + return "Allowed" + case .denied: + return "Denied" + case .provisional: + return "Deliver Quietly" + case .ephemeral: + return "Temporary" + } + } + + var allowsDelivery: Bool { + switch self { + case .authorized, .provisional, .ephemeral: + return true + case .unknown, .notDetermined, .denied: + return false + } + } +} diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index c5376f05448e..bbfa515331ac 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -775,7 +775,11 @@ 4E25D4EB1F1D488A809C9C96 /* CloudNativeLayoutProjectionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DFD749234584EA0BC041370 /* CloudNativeLayoutProjectionTests.swift */; }; 7829E36E90E948BB82360052 /* CloudNightlyOverrideTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCD9CDECAE2049469F5CAB46 /* CloudNightlyOverrideTests.swift */; }; 16D0D1DB9FE54DB29743A98A /* CloudNotificationCorrelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 503C99BC313F48A48235DB1A /* CloudNotificationCorrelation.swift */; }; + 4EFC91B414CF5D9FEA440819 /* CloudNotificationDismissParityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB8894FC01353CA3B8C9326F /* CloudNotificationDismissParityTests.swift */; }; + 06A7D527A380A87E00C122EE /* CloudNotificationLocalDelivery.swift in Sources */ = {isa = PBXBuildFile; fileRef = D792B1E5CE28BAFC121F6781 /* CloudNotificationLocalDelivery.swift */; }; + ED7A8BCBA7C0A396EAC81DAB /* CloudNotificationPlacement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D5BAD7EE4528BF8811C31A6 /* CloudNotificationPlacement.swift */; }; 8B79FDC5C0ADF0CE973B31F2 /* CloudNotificationSync.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCC5CAAFB9D2DBB5186E02EE /* CloudNotificationSync.swift */; }; + 0E06E7885C78B752A9AB83E2 /* CloudNotificationSyncHub.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE060F2CFED4B9FF6EB09FFF /* CloudNotificationSyncHub.swift */; }; A12545000000000000000001 /* CloudNotificationSyncPendingAck.swift in Sources */ = {isa = PBXBuildFile; fileRef = A12545000000000000000002 /* CloudNotificationSyncPendingAck.swift */; }; A12481400000000000000001 /* CloudNotificationSyncPersistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = A12481400000000000000002 /* CloudNotificationSyncPersistence.swift */; }; 7032CCF3EC7D4E27A1BE5C19 /* CloudNotificationSyncState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5554C1784C19461FBF5BF408 /* CloudNotificationSyncState.swift */; }; @@ -3398,6 +3402,7 @@ 596100000000000000000007 /* TerminalNotificationStore+NativeNotificationDeliveryTesting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 596100000000000000000006 /* TerminalNotificationStore+NativeNotificationDeliveryTesting.swift */; }; A5F10000000000000000000D /* TerminalNotificationStore+WorkspaceNotifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5F10000000000000000000E /* TerminalNotificationStore+WorkspaceNotifications.swift */; }; A5001095 /* TerminalNotificationStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001092 /* TerminalNotificationStore.swift */; }; + FF476B958A52306DA7251184 /* TerminalNotificationStoreSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90D990B0BBCB364F2953D267 /* TerminalNotificationStoreSettings.swift */; }; 0A110711000000000000001C /* TerminalOutputTeeCallback.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A110711000000000000001D /* TerminalOutputTeeCallback.swift */; }; 0A110711000000000000001E /* TerminalOutputTeeContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A110711000000000000001F /* TerminalOutputTeeContext.swift */; }; C71500060000000000000001 /* TerminalPaneBackgroundView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C71500050000000000000001 /* TerminalPaneBackgroundView.swift */; }; @@ -4739,7 +4744,11 @@ 5DFD749234584EA0BC041370 /* CloudNativeLayoutProjectionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CloudNativeLayoutProjectionTests.swift"; sourceTree = ""; }; DCD9CDECAE2049469F5CAB46 /* CloudNightlyOverrideTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudNightlyOverrideTests.swift; sourceTree = ""; }; 503C99BC313F48A48235DB1A /* CloudNotificationCorrelation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudNotificationCorrelation.swift; sourceTree = ""; }; + CB8894FC01353CA3B8C9326F /* CloudNotificationDismissParityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudNotificationDismissParityTests.swift; sourceTree = ""; }; + D792B1E5CE28BAFC121F6781 /* CloudNotificationLocalDelivery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudNotificationLocalDelivery.swift; sourceTree = ""; }; + 6D5BAD7EE4528BF8811C31A6 /* CloudNotificationPlacement.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudNotificationPlacement.swift; sourceTree = ""; }; FCC5CAAFB9D2DBB5186E02EE /* CloudNotificationSync.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudNotificationSync.swift; sourceTree = ""; }; + BE060F2CFED4B9FF6EB09FFF /* CloudNotificationSyncHub.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudNotificationSyncHub.swift; sourceTree = ""; }; A12545000000000000000002 /* CloudNotificationSyncPendingAck.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudNotificationSyncPendingAck.swift; sourceTree = ""; }; A12481400000000000000002 /* CloudNotificationSyncPersistence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudNotificationSyncPersistence.swift; sourceTree = ""; }; 5554C1784C19461FBF5BF408 /* CloudNotificationSyncState.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudNotificationSyncState.swift; sourceTree = ""; }; @@ -7235,6 +7244,7 @@ 596100000000000000000006 /* TerminalNotificationStore+NativeNotificationDeliveryTesting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "TerminalNotificationStore+NativeNotificationDeliveryTesting.swift"; sourceTree = ""; }; A5F10000000000000000000E /* TerminalNotificationStore+WorkspaceNotifications.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "TerminalNotificationStore+WorkspaceNotifications.swift"; sourceTree = ""; }; A5001092 /* TerminalNotificationStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalNotificationStore.swift; sourceTree = ""; }; + 90D990B0BBCB364F2953D267 /* TerminalNotificationStoreSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalNotificationStoreSettings.swift; sourceTree = ""; }; 0A110711000000000000001D /* TerminalOutputTeeCallback.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalOutputTeeCallback.swift; sourceTree = ""; }; 0A110711000000000000001F /* TerminalOutputTeeContext.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalOutputTeeContext.swift; sourceTree = ""; }; C71500050000000000000001 /* TerminalPaneBackgroundView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalPaneBackgroundView.swift; sourceTree = ""; }; @@ -8385,6 +8395,7 @@ 503C99BC313F48A48235DB1A /* CloudNotificationCorrelation.swift */, A12545000000000000000002 /* CloudNotificationSyncPendingAck.swift */, FCC5CAAFB9D2DBB5186E02EE /* CloudNotificationSync.swift */, + BE060F2CFED4B9FF6EB09FFF /* CloudNotificationSyncHub.swift */, 5554C1784C19461FBF5BF408 /* CloudNotificationSyncState.swift */, A12481100000000000000002 /* CloudTreeNodeContentSnapshot.swift */, A12481200000000000000002 /* CloudTreeRowUpdate.swift */, @@ -8448,6 +8459,8 @@ A1B2C3D4E5F6071827364950 /* CloudMachineSurfacePresentation.swift */, 1CE0A82A4E20E446A21A97BB /* CloudTreeNode.swift */, 8EDC6087D41DC9E2271BC886 /* CloudMachineNotificationGate.swift */, + D792B1E5CE28BAFC121F6781 /* CloudNotificationLocalDelivery.swift */, + 6D5BAD7EE4528BF8811C31A6 /* CloudNotificationPlacement.swift */, DB3D5091A5F87B6B672DF34C /* CloudMachineNotificationEvent.swift */, 1652962DDCD1CB279278F8D4 /* CloudMachineCache.swift */, 352B2228561CD8C4B042302A /* CloudActivationPolicy.swift */, @@ -9751,6 +9764,7 @@ D79020000000000000000002 /* TerminalNotification+NavigationSnapshot.swift */, A5C0B1E00000000000000002 /* TerminalNotification+Clipboard.swift */, A5001092 /* TerminalNotificationStore.swift */, + 90D990B0BBCB364F2953D267 /* TerminalNotificationStoreSettings.swift */, 468110000000000000000008 /* TerminalNotificationClickAction.swift */, A5F10000000000000000000E /* TerminalNotificationStore+WorkspaceNotifications.swift */, A5001099 /* TerminalNotificationScrollPosition.swift */, @@ -11270,6 +11284,7 @@ BBC170FBE7AEBB71A5BE2922 /* CloudTerminalAttachmentRecoveryTests.swift */, EF70B0862D206C62CA5ACF65 /* CloudManualMirrorSocketFixture.swift */, 64CB7AF7545F56E95A91B154 /* CloudNotificationSyncTests.swift */, + CB8894FC01353CA3B8C9326F /* CloudNotificationDismissParityTests.swift */, A12481000000000000000002 /* CloudSidebarScaleTests.swift */, A12481700000000000000002 /* SidebarDerivedStateScaleTests.swift */, A12481600000000000000002 /* CloudNotificationSyncStoreTests.swift */, @@ -12829,7 +12844,10 @@ C11324810000000000000001 /* CloudManualMirrorMaterialization.swift in Sources */, A014F45D702B4F71A5E9FB18 /* CloudManualMirrorPresentation.swift in Sources */, 16D0D1DB9FE54DB29743A98A /* CloudNotificationCorrelation.swift in Sources */, + 06A7D527A380A87E00C122EE /* CloudNotificationLocalDelivery.swift in Sources */, + ED7A8BCBA7C0A396EAC81DAB /* CloudNotificationPlacement.swift in Sources */, 8B79FDC5C0ADF0CE973B31F2 /* CloudNotificationSync.swift in Sources */, + 0E06E7885C78B752A9AB83E2 /* CloudNotificationSyncHub.swift in Sources */, A12545000000000000000001 /* CloudNotificationSyncPendingAck.swift in Sources */, A12481400000000000000001 /* CloudNotificationSyncPersistence.swift in Sources */, 7032CCF3EC7D4E27A1BE5C19 /* CloudNotificationSyncState.swift in Sources */, @@ -14470,6 +14488,7 @@ B7F0000A /* TerminalNotificationStore+Mute.swift in Sources */, A5F10000000000000000000D /* TerminalNotificationStore+WorkspaceNotifications.swift in Sources */, A5001095 /* TerminalNotificationStore.swift in Sources */, + FF476B958A52306DA7251184 /* TerminalNotificationStoreSettings.swift in Sources */, 0A110711000000000000001C /* TerminalOutputTeeCallback.swift in Sources */, 0A110711000000000000001E /* TerminalOutputTeeContext.swift in Sources */, C71500060000000000000001 /* TerminalPaneBackgroundView.swift in Sources */, @@ -15373,6 +15392,7 @@ BC9AC2D1065E4E88A48074BC /* CloudNameAuthorityTests.swift in Sources */, 4E25D4EB1F1D488A809C9C96 /* CloudNativeLayoutProjectionTests.swift in Sources */, 7829E36E90E948BB82360052 /* CloudNightlyOverrideTests.swift in Sources */, + 4EFC91B414CF5D9FEA440819 /* CloudNotificationDismissParityTests.swift in Sources */, A12481600000000000000001 /* CloudNotificationSyncStoreTests.swift in Sources */, B71758C265B0439845140478 /* CloudNotificationSyncTests.swift in Sources */, 287771C476C483CE2E40E0F6 /* CloudOperationRecorderTests.swift in Sources */, diff --git a/cmuxTests/CloudNotificationDismissParityTests.swift b/cmuxTests/CloudNotificationDismissParityTests.swift new file mode 100644 index 000000000000..378b79d8b30d --- /dev/null +++ b/cmuxTests/CloudNotificationDismissParityTests.swift @@ -0,0 +1,459 @@ +import AppKit +import Foundation +import Testing +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +/// One read state per Cloud notification (manaflow-ai/cmux#13000). Rows come +/// off a machine's daemon feed, become local records through the provider's +/// own placement and delivery pieces, and every dismissal path the app +/// exposes must clear every indicator at once: the local record, the left +/// sidebar's per-workspace summary, the pane ring, and the Cloud tree's +/// workspace and terminal rows, including after the daemon replays a stale +/// snapshot and after the machine's sync is rebuilt from durable state. +@Suite("Cloud notification dismiss parity", .serialized) +@MainActor +struct CloudNotificationDismissParityTests { + @Test("Clicking into the pane clears the ring and the Cloud tree dot, even with a deduplicated repeat row") + func paneFocusClearsTheCloudTreeDot() async throws { + let harness = try ParityHarness() + defer { harness.close() } + let first = harness.row("finished-1", terminal: "term_a", title: "Codex finished", createdAt: 1) + // Same terminal, same text, one second later: the admission gate's + // identical-content window drops it, exactly like a hook that fires + // twice for one completion. + let repeat_ = harness.row("finished-2", terminal: "term_a", title: "Codex finished", createdAt: 2) + harness.apply([first, repeat_]) + + #expect(harness.store.notifications.filter { !$0.isRead }.count == 1) + #expect(harness.leftBadge == 1) + #expect(harness.store.hasVisibleNotificationIndicator(forTabId: harness.workspace.id, surfaceId: harness.panelID)) + #expect(harness.treeDots() == ["ws_1", "term_a"]) + + // The user clicks into the pane. + #expect(harness.manager.dismissNotificationOnDirectInteraction(tabId: harness.workspace.id, surfaceId: harness.panelID)) + + harness.expectEverythingRead(terminals: ["term_a"]) + await harness.flush() + #expect(harness.ackedIDs == Set([first.id, repeat_.id]), "both rows are acknowledged to the machine") + + // A stale snapshot from the daemon still carries both rows as unread. + harness.apply([first, repeat_]) + harness.expectEverythingRead(terminals: ["term_a"]) + + // The provider is rebuilt (sleep, feature toggle, relaunch) from the + // durable state and folds the same rows again. + harness.rebuildSync() + harness.apply([first, repeat_]) + harness.expectEverythingRead(terminals: ["term_a"]) + #expect(harness.store.notifications.count == 1, "nothing was delivered twice") + } + + @Test("Visiting the workspace reads a row placed at the workspace level (no pane shows its terminal)") + func visitingTheWorkspaceReadsWorkspaceLevelRows() async throws { + let harness = try ParityHarness() + defer { harness.close() } + AppFocusState.overrideIsFocused = true + let row = harness.row("b-1", terminal: "term_b", title: "Claude finished", createdAt: 1) + harness.apply([row]) + let record = try #require(harness.store.notifications.first) + #expect(record.tabId == harness.workspace.id) + #expect(record.surfaceId == nil, "term_b is not projected here, so the row lands on the workspace") + #expect(harness.leftBadge == 1) + #expect(harness.treeDots() == ["ws_1", "term_b"]) + + // Workspace selection's side effect: the focused pane and, since + // manaflow-ai/cmux#12387, the workspace level are dismissed. + harness.manager.notificationDismissal.dismissFocusedPanelNotificationIfActive( + workspaceId: harness.workspace.id, context: .explicitWorkspaceResume + ) + + harness.expectEverythingRead(terminals: ["term_b"]) + await harness.flush() + #expect(harness.ackedIDs == [row.id]) + } + + @Test("A remote workspace with no local workspace keeps its dot but never stacks onto another workspace's badge") + func unopenedRemoteWorkspaceRowsStayOffTheLocalBadge() async throws { + let harness = try ParityHarness() + defer { harness.close() } + let row = harness.row("c-1", terminal: "term_c", title: "Codex finished", createdAt: 1) + harness.apply([row]) + + #expect(harness.store.notifications.isEmpty, "no local home for ws_2 yet") + #expect(harness.leftBadge == 0, "the bound workspace's badge counts only its own remote workspace") + #expect(harness.treeDots() == ["ws_2", "term_c"]) + + // Opening ws_2 locally gives the row its home on the next fold. + let opened = harness.manager.addWorkspace(select: false) + opened.cloudVMBinding = WorkspaceCloudVMBinding(vmID: harness.machine.rawValue, isBase: false, remoteWorkspaceID: "ws_2") + harness.apply([row]) + #expect(harness.store.notifications.map(\.tabId) == [opened.id]) + #expect(harness.leftBadge == 0) + #expect(harness.store.unreadCount(forTabId: opened.id) == 1) + #expect(harness.treeDots() == ["ws_2", "term_c"]) + + // Mark all read clears the machine too. + harness.store.markAllRead() + harness.expectEverythingRead(terminals: ["term_c"]) + #expect(harness.store.unreadCount(forTabId: opened.id) == 0) + await harness.flush() + #expect(harness.ackedIDs == [row.id]) + harness.manager.closeWorkspace(opened) + } + + @Test("Rows over the admission rate are delivered on a later fold instead of leaving an undismissable dot") + func rateLimitedRowsAreThrottledNotLost() async throws { + let harness = try ParityHarness() + defer { harness.close() } + let rows = (1...7).map { harness.row("burst-\($0)", terminal: "term_a", title: "finished \($0)", createdAt: UInt64($0)) } + harness.apply(rows) + #expect(harness.store.notifications.count == 5, "the machine budget admits five in one tick") + #expect(harness.treeDots() == ["ws_1", "term_a"]) + + // Two seconds later the bucket has refilled and the next fold delivers the rest. + harness.clock.now += 2_000_000_000 + harness.apply(rows) + #expect(harness.store.notifications.count == 7) + #expect(harness.leftBadge == 7) + + #expect(harness.manager.dismissNotificationOnDirectInteraction(tabId: harness.workspace.id, surfaceId: harness.panelID)) + harness.expectEverythingRead(terminals: ["term_a"]) + await harness.flush() + #expect(harness.ackedIDs == Set(rows.map(\.id))) + } + + @Test("A dismissal while the machine's sync is gone is acknowledged when the sync comes back") + func dismissalWhileTheSyncIsGoneSurvivesRestore() async throws { + let harness = try ParityHarness() + defer { harness.close() } + let row = harness.row("asleep-1", terminal: "term_a", title: "Codex finished", createdAt: 1) + harness.apply([row]) + #expect(harness.treeDots() == ["ws_1", "term_a"]) + + // The provider is suspended (feature flag off, machine asleep) before the user reads it. + harness.suspendSync() + #expect(harness.treeDots().isEmpty, "a suspended machine shows no dots") + #expect(harness.manager.dismissNotificationOnDirectInteraction(tabId: harness.workspace.id, surfaceId: harness.panelID)) + let recordsRead = harness.store.notifications.allSatisfy(\.isRead) + #expect(recordsRead) + // The store subscription writes the read into the machine's durable + // state, since no sync is live to take it. + harness.spinStoreSubscription { !harness.persistence.load(machineID: harness.machine.rawValue).pendingAcks.isEmpty } + #expect(!harness.persistence.load(machineID: harness.machine.rawValue).pendingAcks.isEmpty) + + harness.rebuildSync() + harness.apply([row]) + harness.expectEverythingRead(terminals: ["term_a"]) + await harness.flush() + #expect(harness.ackedIDs == [row.id], "the read taken while the sync was gone still reaches the machine") + } + + @Test("`cmux notify --clear` on the pane clears every indicator, including a deduplicated repeat row") + func clearThroughTheSocketPathClearsEverything() async throws { + let harness = try ParityHarness() + defer { harness.close() } + let first = harness.row("clear-1", terminal: "term_a", title: "Build done", createdAt: 1) + let repeat_ = harness.row("clear-2", terminal: "term_a", title: "Build done", createdAt: 2) + harness.apply([first, repeat_]) + #expect(harness.leftBadge == 1) + + // The socket `clear_notifications` handler's store call. + harness.store.clearNotifications(forTabId: harness.workspace.id, surfaceId: harness.panelID) + + #expect(harness.store.notifications.isEmpty) + harness.expectEverythingRead(terminals: ["term_a"]) + await harness.flush() + #expect(harness.ackedIDs == Set([first.id, repeat_.id])) + } + + @Test("Clicking the banner reads its row through the store subscription") + func clickingTheBannerReadsItsRow() async throws { + let harness = try ParityHarness() + defer { harness.close() } + let row = harness.row("click-1", terminal: "term_a", title: "Codex finished", createdAt: 1) + harness.apply([row]) + let record = try #require(harness.store.notifications.first) + + harness.store.markRead(id: record.id) + harness.spinStoreSubscription { harness.hub.unreadTerminalIDs[harness.machine.rawValue] == nil } + + harness.expectEverythingRead(terminals: ["term_a"]) + await harness.flush() + #expect(harness.ackedIDs == [row.id]) + } +} + +/// The two sidebars, the store, and one machine wired the way the app wires +/// them: the shared store, a tab manager with a local workspace bound to the +/// machine's `ws_1` whose focused pane projects `term_a`, a catalog holding the +/// machine's graph (`ws_1`: `term_a`, `term_b`; `ws_2`: `term_c`), the +/// provider's placement resolver and local delivery, and a hub attached to +/// the store with an injectable admission clock. +@MainActor +private final class ParityHarness { + let machine = SurfaceMachineID.cloud("parity-machine") + let store: TerminalNotificationStore + let manager: TabManager + let workspace: Workspace + let panelID: UUID + let catalog: SurfaceCatalog + let provider: CloudPlacementTestProvider + let state: CloudVMState + let defaults: UserDefaults + let defaultsName: String + let persistence: CloudNotificationSyncStore + let hub: CloudNotificationSyncHub + let clock: AdmissionClock + private(set) var sync: CloudNotificationSync? + private var acks: [[String]] = [] + private let restore: @MainActor () -> Void + + final class AdmissionClock { + var now: UInt64 = 1 + } + + init() throws { + let store = TerminalNotificationStore.shared + let defaultsName = "cmux.tests.cloud-dismiss-parity.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: defaultsName)) + let clock = AdmissionClock() + let manager = TabManager() + self.store = store + self.defaultsName = defaultsName + self.defaults = defaults + self.clock = clock + self.manager = manager + let originalAppDelegate = AppDelegate.shared + let appDelegate = originalAppDelegate ?? AppDelegate() + let originalTabManager = appDelegate.tabManager + let originalStore = appDelegate.notificationStore + let originalFocus = AppFocusState.overrideIsFocused + let originalObserver = store.readTargetObserver + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + store.configureSuppressedNotificationFeedbackHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + if AppDelegate.shared == nil { AppDelegate.shared = appDelegate } + AppFocusState.overrideIsFocused = false + restore = { + for workspace in manager.tabs { manager.closeWorkspace(workspace) } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + store.resetSuppressedNotificationFeedbackHandlerForTesting() + store.readTargetObserver = originalObserver + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalStore + AppDelegate.shared = originalAppDelegate + AppFocusState.overrideIsFocused = originalFocus + defaults.removePersistentDomain(forName: defaultsName) + } + + workspace = try #require(manager.selectedWorkspace) + panelID = try #require(workspace.focusedPanelId) + workspace.cloudVMBinding = WorkspaceCloudVMBinding(vmID: machine.rawValue, isBase: false, remoteWorkspaceID: "ws_1") + + catalog = SurfaceCatalog() + provider = CloudPlacementTestProvider(machine: machine) + state = try Self.graph(machine: machine) + let info = SurfaceMachineInfo( + id: machine, name: "Fixture", status: "running", image: nil, hasDesktop: false, + memoryMb: nil, diskMb: nil, linkState: .connected, linkError: nil, + cpuPercent: nil, memoryUsedMb: nil, diskUsedMb: nil, + remoteWorkspaces: state.workspaces.map { + SurfaceRemoteWorkspace(id: $0.id, name: $0.name, index: $0.index, focused: $0.focused) + } + ) + provider.info = info + catalog.register(provider) + catalog.replaceCloudState(state, resources: CmuxTuiSnapshotParser.resources(from: state), info: info) + catalog.record(SurfaceProjection( + resource: SurfaceResourceID(machine: machine, kind: .terminal, key: "term_a"), + workspaceID: workspace.id, panelID: panelID, remoteWorkspaceID: "ws_1", remoteTabID: "tab_a" + )) + + persistence = CloudNotificationSyncStore(defaults: defaults) + hub = CloudNotificationSyncHub( + persistenceStore: persistence, + gate: CloudMachineNotificationGate(now: { clock.now }) + ) + hub.attach(store: store) + rebuildSync() + } + + func close() { + sync?.retire() + hub.unregister(machineID: machine.rawValue) + restore() + } + + // MARK: Machine graph + + private static func graph(machine: SurfaceMachineID) throws -> CloudVMState { + func tab(_ key: String, pane: String, index: Int) -> [String: Any] { + ["id": "tab_\(key)", "pane_id": pane, "index": index, "focused": index == 0, + "name": "", "content_kind": "terminal", "content_id": "term_\(key)"] + } + let document: [String: Any] = [ + "cursor": ["generation": "fixture", "revision": "1"], + "workspaces": [ + ["id": "ws_1", "name": "issue-1", "index": 0, "focused": true], + ["id": "ws_2", "name": "issue-2", "index": 1, "focused": false], + ], + "screens": [ + ["id": "screen_1", "workspace_id": "ws_1", "layout": [ + "version": 1, "screen_id": "screen_1", + "root": ["kind": "leaf", "pane_id": "pane_1", "tab_ids": ["tab_a", "tab_b"]], + ]], + ["id": "screen_2", "workspace_id": "ws_2", "layout": [ + "version": 1, "screen_id": "screen_2", + "root": ["kind": "leaf", "pane_id": "pane_2", "tab_ids": ["tab_c"]], + ]], + ], + "panes": [["id": "pane_1", "screen_id": "screen_1"], ["id": "pane_2", "screen_id": "screen_2"]], + "tabs": [tab("a", pane: "pane_1", index: 0), tab("b", pane: "pane_1", index: 1), tab("c", pane: "pane_2", index: 0)], + "terminals": ["a", "b", "c"].map { ["id": "term_\($0)", "title": "agent \($0)", "lifecycle": "running"] }, + "browsers": [], "agents": [], + ] + return try #require(CmuxTuiSnapshotParser.state(fromSnapshot: document, machine: machine)) + } + + func row(_ id: String, terminal: String, title: String, createdAt: UInt64) -> CloudVMNotificationRow { + CloudVMNotificationRow( + id: "notification_\(id)", title: title, subtitle: nil, body: "", level: "info", + createdAtMs: createdAt, terminalID: terminal, readBy: [] + ) + } + + // MARK: Sync lifecycle + + /// The provider's placement resolver and local delivery over this fixture. + private func makeSync() -> CloudNotificationSync { + let resolver = CloudNotificationPlacementResolver( + machine: machine, + projections: { [catalog] in catalog.projections(of: $0) }, + remoteWorkspaceID: { [state] terminalID in + for tab in state.tabs where tab.contentID == terminalID { + guard let pane = state.lookupIndex.pane(id: tab.paneID), + let screen = state.lookupIndex.screen(id: pane.screenID) else { continue } + return screen.workspaceID + } + return nil + }, + boundWorkspaces: { [manager, machine] in + manager.tabs.compactMap { workspace in + guard let binding = workspace.cloudVMBinding, binding.vmID == machine.rawValue else { return nil } + return CloudNotificationBoundWorkspace(workspaceID: workspace.id, remoteWorkspaceID: binding.remoteWorkspaceID) + } + } + ) + let delivery = CloudNotificationLocalDelivery( + machineID: machine.rawValue, + store: { [store] in store }, + admit: { [hub, machine] in hub.admit($0, machineID: machine.rawValue) }, + machineName: { "Fixture" }, + terminalTitle: { [state] in state.lookupIndex.terminal(id: $0)?.title } + ) + let machineID = machine.rawValue + let hub = hub + return CloudNotificationSync( + machineID: machineID, + clientID: "mac-parity", + store: persistence, + resolveTarget: { resolver.target(for: $0) }, + deliver: { delivery.deliver($0, to: $1) }, + send: { [weak self] batch in self?.acks.append(batch.ids) }, + unreadChanged: { hub.setUnread($0, machineID: machineID) }, + withdraw: { [store] ids in + let removed = Set(ids) + for notification in store.notifications where notification.correlationKey.map({ + CloudNotificationCorrelation.matches($0, machineID: machineID, notificationIDs: removed) + }) == true { + store.remove(id: notification.id) + } + } + ) + } + + /// A fresh sync from the durable state, as a provider rebuild does. + func rebuildSync() { + sync?.retire() + let next = makeSync() + sync = next + hub.register(next) + } + + /// The provider is suspended: its sync retires and leaves the hub. + func suspendSync() { + sync?.retire() + sync = nil + hub.unregister(machineID: machine.rawValue) + } + + func apply(_ rows: [CloudVMNotificationRow]) { + sync?.apply(rows: rows) + } + + func flush() async { + await sync?.flushPendingReads() + } + + var ackedIDs: Set { Set(acks.flatMap { $0 }) } + + /// The hub observes the store's `$notifications` publication on the main + /// run loop. Runs that loop until `predicate` holds; the deadline bounds + /// only the failure path. + func spinStoreSubscription(until predicate: () -> Bool) { + let deadline = Date().addingTimeInterval(10) + while !predicate(), Date() < deadline { + RunLoop.main.run(until: Date().addingTimeInterval(0.01)) + } + } + + // MARK: Indicators + + /// The left sidebar's badge for the bound workspace, from the coalesced + /// sidebar projection the workspace rows render. + var leftBadge: Int { + store.sidebarUnread.summaryByWorkspaceId[workspace.id]?.unreadCount ?? 0 + } + + /// Cloud tree rows carrying the attention dot, built from the catalog and + /// the hub's unread index exactly as the Machines panel builds them. + func treeDots() -> Set { + let nodes = CloudTreeNodeBuilder.nodes( + machines: [], snapshot: catalog.snapshot, localWorkspaces: [], + unreadTerminalIDs: hub.unreadTerminalIDs, includeLocalMachine: false + ) + var dots = Set() + for node in CloudTreeNodeBuilder.flattened(nodes) where node.hasUnreadAttention { + switch node.kind { + case .terminal(let row): + dots.insert(row.resource.id.key) + case .workspace: + for id in ["ws_1", "ws_2"] where node.id == CloudTreeNodeBuilder.nodeID(workspace: id, machine: machine) { + dots.insert(id) + } + default: + dots.insert(node.id) + } + } + return dots + } + + /// Every indicator for the workspace and the given terminals reports read. + func expectEverythingRead(terminals: [String], sourceLocation: SourceLocation = #_sourceLocation) { + let recordsRead = store.notifications.allSatisfy(\.isRead) + #expect(recordsRead, "store records", sourceLocation: sourceLocation) + #expect(leftBadge == 0, "left sidebar badge", sourceLocation: sourceLocation) + #expect(store.unreadCount(forTabId: workspace.id) == 0, "workspace unread count", sourceLocation: sourceLocation) + #expect(!store.hasVisibleNotificationIndicator(forTabId: workspace.id, surfaceId: panelID), "pane ring", sourceLocation: sourceLocation) + #expect(hub.unreadTerminalIDs[machine.rawValue] == nil, "hub unread index", sourceLocation: sourceLocation) + #expect(sync?.unreadTerminalIDs.isEmpty == true, "sync unread set", sourceLocation: sourceLocation) + #expect(treeDots().isEmpty, "Cloud tree dots \(treeDots()) for \(terminals)", sourceLocation: sourceLocation) + } +} diff --git a/cmuxTests/CloudNotificationSyncStoreTests.swift b/cmuxTests/CloudNotificationSyncStoreTests.swift index 49ee3725ef73..2d9de182d579 100644 --- a/cmuxTests/CloudNotificationSyncStoreTests.swift +++ b/cmuxTests/CloudNotificationSyncStoreTests.swift @@ -30,7 +30,7 @@ struct CloudNotificationSyncStoreTests { CloudNotificationSync( machineID: "machine", clientID: "mac", store: store, resolveTarget: { _ in .init(workspaceID: UUID(), panelID: nil) }, - deliver: { _, _ in deliveries += 1; return true }, send: { _ in } + deliver: { _, _ in deliveries += 1; return .delivered }, send: { _ in } ) } let row = CloudVMNotificationRow( @@ -81,7 +81,7 @@ struct CloudNotificationSyncStoreTests { var sent = 0 let sync = CloudNotificationSync( machineID: "machine", clientID: "mac", store: store, - newKey: { "ack-key" }, resolveTarget: { _ in nil }, deliver: { _, _ in true }, + newKey: { "ack-key" }, resolveTarget: { _ in nil }, deliver: { _, _ in .delivered }, send: { batch in let data = try #require(defaults.data(forKey: CloudNotificationSyncStore.key(machineID: "machine"))) let saved = try JSONDecoder().decode(CloudNotificationSyncState.self, from: data) @@ -107,7 +107,7 @@ struct CloudNotificationSyncStoreTests { let sync = CloudNotificationSync( machineID: "machine", clientID: "mac", store: store, resolveTarget: { _ in .init(workspaceID: UUID(), panelID: nil) }, - deliver: { _, _ in true }, send: { _ in }, unreadChanged: { unreadChanges.append($0) } + deliver: { _, _ in .delivered }, send: { _ in }, unreadChanged: { unreadChanges.append($0) } ) defer { sync.retire() } var row = CloudVMNotificationRow( diff --git a/cmuxTests/CloudNotificationSyncTests.swift b/cmuxTests/CloudNotificationSyncTests.swift index 383cca2e0a4c..5397207c726d 100644 --- a/cmuxTests/CloudNotificationSyncTests.swift +++ b/cmuxTests/CloudNotificationSyncTests.swift @@ -381,9 +381,9 @@ struct CloudNotificationSyncTests { newKey: { keyCounter += 1; return "k\(keyCounter)" }, resolveTarget: { _ in effects.hasPlacement ? CloudNotificationDeliveryTarget(workspaceID: workspace, panelID: nil) : nil }, deliver: { row, _ in - if effects.declineDelivery { return false } + if effects.declineDelivery { return .declined } effects.delivered.append(row.id) - return true + return .delivered }, send: { batch in if effects.sendFails { throw CancellationError() } diff --git a/cmuxTests/CloudSidebarNotificationTests.swift b/cmuxTests/CloudSidebarNotificationTests.swift index 7d9580375d0d..6ebd8b95f2ac 100644 --- a/cmuxTests/CloudSidebarNotificationTests.swift +++ b/cmuxTests/CloudSidebarNotificationTests.swift @@ -25,7 +25,7 @@ struct CloudSidebarNotificationTests { deliver: { notification, resolved in deliveries.append(resolved) owner.raiseNotification(resource: SurfaceResourceID(machine: fixture.machine, kind: .terminal, key: notification.terminalID!), nodes: fixture.nodes()) - return true + return .delivered }, send: { _ in } ) defer { sync.retire() } @@ -48,7 +48,7 @@ struct CloudSidebarNotificationTests { #expect(!read.contains { $0.hasUnreadDescendant }) sync.retire() let restarted = CloudNotificationSync(machineID: fixture.machine.rawValue, clientID: "fixture-client", store: persistence, - resolveTarget: { _ in target }, deliver: { _, _ in Issue.record("Replay delivered twice"); return true }, send: { _ in }) + resolveTarget: { _ in target }, deliver: { _, _ in Issue.record("Replay delivered twice"); return .delivered }, send: { _ in }) defer { restarted.retire() } restarted.apply(rows: [row]) #expect(restarted.unreadTerminalIDs.isEmpty) @@ -66,7 +66,7 @@ struct CloudSidebarNotificationTests { var delivered = 0 let sync = CloudNotificationSync(machineID: "retired", clientID: "fixture-client", store: persistence, resolveTarget: { _ in CloudNotificationDeliveryTarget(workspaceID: UUID(), panelID: nil) }, - deliver: { _, _ in delivered += 1; return true }, send: { _ in }) + deliver: { _, _ in delivered += 1; return .delivered }, send: { _ in }) sync.retire() sync.apply(rows: [notification("late", terminal: "term_ws_1")]) sync.noteRead(notificationIDs: ["late"]) diff --git a/cmuxTests/CloudSidebarScaleTests.swift b/cmuxTests/CloudSidebarScaleTests.swift index 40e5508ed456..eade9211ae76 100644 --- a/cmuxTests/CloudSidebarScaleTests.swift +++ b/cmuxTests/CloudSidebarScaleTests.swift @@ -21,7 +21,7 @@ struct CloudSidebarScaleTests { let store = CloudNotificationSyncStore(defaults: defaults) let sync = CloudNotificationSync( machineID: "scale", clientID: "mac-scale", store: store, - resolveTarget: { _ in nil }, deliver: { _, _ in true }, send: { _ in } + resolveTarget: { _ in nil }, deliver: { _, _ in .delivered }, send: { _ in } ) defer { sync.retire() } // Each workspace emits a catalog delta that does not change notifications. @@ -42,7 +42,7 @@ struct CloudSidebarScaleTests { machineID: "scale", clientID: "mac-scale", store: store, resolveTarget: { _ in .init(workspaceID: UUID(), panelID: nil) }, - deliver: { _, _ in true }, send: { _ in } + deliver: { _, _ in .delivered }, send: { _ in } ) defer { sync.retire() } sync.apply(rows: [CloudVMNotificationRow( diff --git a/scripts/ci/cmux_unit_test_shard.py b/scripts/ci/cmux_unit_test_shard.py index e7691a9c35dc..80cc6386f44d 100755 --- a/scripts/ci/cmux_unit_test_shard.py +++ b/scripts/ci/cmux_unit_test_shard.py @@ -38,6 +38,7 @@ "cmuxTests/AgentRestoreLiveOwnerAdmissionTests", "cmuxTests/BrowserSystemProxyMirrorTests", "cmuxTests/CLISSHSessionAttachAnchorTests", + "cmuxTests/CloudNotificationDismissParityTests", "cmuxTests/GhosttyTerminalViewVisibilityPolicyTests", "cmuxTests/GhosttyOptionAsAltModsTests", "cmuxTests/GhosttyNumericLocaleTests", diff --git a/tests/test_ci_cmux_unit_test_shard.py b/tests/test_ci_cmux_unit_test_shard.py index 027326438cbe..80af1abd9111 100644 --- a/tests/test_ci_cmux_unit_test_shard.py +++ b/tests/test_ci_cmux_unit_test_shard.py @@ -350,6 +350,7 @@ def main() -> int: "-only-testing:cmuxTests/AgentRestoreLiveOwnerAdmissionTests", "-only-testing:cmuxTests/BrowserSystemProxyMirrorTests", "-only-testing:cmuxTests/CLISSHSessionAttachAnchorTests", + "-only-testing:cmuxTests/CloudNotificationDismissParityTests", "-only-testing:cmuxTests/GhosttyTerminalViewVisibilityPolicyTests", "-only-testing:cmuxTests/GhosttyOptionAsAltModsTests", "-only-testing:cmuxTests/GlobalSearchShortcutBehaviorTests", From 7452629a4efeab78c29d710aded20d41e2f20aa2 Mon Sep 17 00:00:00 2001 From: Austin Wang Date: Fri, 18 Sep 2026 20:44:44 -0700 Subject: [PATCH 2/3] Dismiss Cloud notifications everywhere at once Fixes manaflow-ai/cmux#13000 and manaflow-ai/cmux#12387. The Cloud tree dot was a projection of daemon rows minus this client's read state, bridged to the local store only by a diff of local records. Rows that never became a record (admission-gate drops, muted workspaces) or whose record was placed on another workspace before the terminal was opened here were invisible to that bridge, so the dot outlived the dismissal; reads taken while the machine's sync was unregistered were dropped; workspace-level records were never read by visiting the workspace. - The store reports every read/clear by target (`readTargetObserver`) and the hub translates it through the same placement resolver the delivery uses, acknowledging every unread row whose current placement the read covers and reading its records wherever they live. The tree's unread index changes synchronously inside the dismissal. - Delivery outcomes: gate duplicates and store declines are suppressed (consumed and read in the same fold); rate-limited rows are declined and delivered on a later fold once the bucket refills, throttled rather than lost. - Placement no longer falls back to any workspace bound to the machine for a row whose remote workspace is known: a terminal in a remote workspace not opened locally keeps only its Cloud tree dot until it is opened, so a workspace row badges only its own notifications. - Reads for a machine without a live sync are written to its durable state as a pending acknowledgement for the replacement sync. - Visiting a workspace also dismisses its workspace-level (no-surface) notifications with the same context (#12387). Co-Authored-By: Claude Fable 5.1 --- .../NotificationDismissalModel.swift | 10 +++- .../CloudNotificationLocalDelivery.swift | 23 +++++++-- .../Cloud/CloudNotificationPlacement.swift | 32 +++++++----- Sources/Cloud/CloudNotificationSyncHub.swift | 49 +++++++++++++++++-- 4 files changed, 91 insertions(+), 23 deletions(-) diff --git a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationDismissalModel.swift b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationDismissalModel.swift index bff0285ccfd2..2d72bc1d0354 100644 --- a/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationDismissalModel.swift +++ b/Packages/macOS/CmuxNotifications/Sources/CmuxNotifications/NotificationDismissalModel.swift @@ -55,8 +55,14 @@ public final class NotificationDismissalModel: NotificationDismissing { let shouldSuppressFlash = suppressFocusFlash suppressFocusFlash = false guard !shouldSuppressFlash else { return } - guard let surfaceId = host?.focusedSurfaceId(in: workspaceId) else { return } - dismissPanelNotificationOnFocus(workspaceId: workspaceId, panelId: surfaceId, context: context) + if let surfaceId = host?.focusedSurfaceId(in: workspaceId) { + dismissPanelNotificationOnFocus(workspaceId: workspaceId, panelId: surfaceId, context: context) + } + // Workspace-level notifications (no surface) have no pane to focus: + // the workspace becoming the visible, active one is how they are seen + // (manaflow-ai/cmux#12387). Same context, so the restored/manual + // indicator policy is unchanged. + _ = dismissNotification(workspaceId: workspaceId, surfaceId: nil, context: context) } public func dismissPanelNotificationOnFocus( diff --git a/Sources/Cloud/CloudNotificationLocalDelivery.swift b/Sources/Cloud/CloudNotificationLocalDelivery.swift index 38d803cee866..71922bc0ff92 100644 --- a/Sources/Cloud/CloudNotificationLocalDelivery.swift +++ b/Sources/Cloud/CloudNotificationLocalDelivery.swift @@ -30,9 +30,21 @@ struct CloudNotificationLocalDelivery { func deliver(_ row: CloudVMNotificationRow, to target: CloudNotificationDeliveryTarget) -> CloudNotificationDeliveryOutcome { guard let store = store() else { return .declined } - // Dropped rows remain consumed by the sync so subsequent catalog folds - // cannot replay a flood. - guard admit(row) == .allowed else { return .delivered } + switch admit(row) { + case .allowed: + break + case .duplicateID, .identicalContent: + // A repeat of something this Mac already showed (or a row the + // store declined on an earlier fold). Nothing will ever show it, + // so it must not stay unread anywhere: read it now. + return .suppressed + case .machineRate, .fleetRate: + // Over budget right now. The row keeps its dot and is retried on + // the next fold, when the bucket has refilled; the burst is + // spread out, not lost. Tokens are only taken by admitted rows, + // so a retry never costs anything. + return .declined + } let terminalTitle = row.terminalID.flatMap(terminalTitle) ?? "" let machineName = machineName() let subtitle: String @@ -58,6 +70,9 @@ struct CloudNotificationLocalDelivery { correlationKey: CloudNotificationCorrelation.key(machineID: machineID, notificationID: row.id), origin: .cloudVM(machineID: machineID) ) != nil - return recorded ? .delivered : .declined + // The store declines for a muted workspace: an admission decision + // of its own, so the row is read here too rather than left as a dot + // that no local dismissal can reach. + return recorded ? .delivered : .suppressed } } diff --git a/Sources/Cloud/CloudNotificationPlacement.swift b/Sources/Cloud/CloudNotificationPlacement.swift index 3cc3bab711ec..7e386a912834 100644 --- a/Sources/Cloud/CloudNotificationPlacement.swift +++ b/Sources/Cloud/CloudNotificationPlacement.swift @@ -49,21 +49,27 @@ struct CloudNotificationPlacementResolver { var boundWorkspaces: @MainActor () -> [CloudNotificationBoundWorkspace] /// The pane showing the terminal when one is open on this Mac, else the - /// local workspace bound to the terminal's remote workspace, else any local - /// workspace bound to the machine. No local placement means the row stays - /// undelivered until one exists; the Cloud tree still shows the dot. + /// local workspace standing for the terminal's remote workspace. A + /// terminal in a remote workspace the person has not opened here has no + /// local home: the row stays undelivered until one exists and the Cloud + /// tree dot is its indicator, instead of stacking onto whichever local + /// workspace happens to be bound to the machine (a workspace row then + /// badges the whole machine's notifications, manaflow-ai/cmux#13000). + /// Only a machine-level row, one no remote workspace's tab shows, lands + /// on any local workspace bound to the machine. func target(for row: CloudVMNotificationRow) -> CloudNotificationDeliveryTarget? { - if let terminalID = row.terminalID { - let resource = SurfaceResourceID(machine: machine, kind: .terminal, key: terminalID) - if let projection = projections(resource).first { - return CloudNotificationDeliveryTarget(workspaceID: projection.workspaceID, panelID: projection.panelID) - } - } let bound = boundWorkspaces() - if let remoteWorkspaceID = row.terminalID.flatMap(remoteWorkspaceID), - let exact = bound.first(where: { $0.remoteWorkspaceID == remoteWorkspaceID }) { - return CloudNotificationDeliveryTarget(workspaceID: exact.workspaceID, panelID: nil) + guard let terminalID = row.terminalID else { + return bound.first.map { CloudNotificationDeliveryTarget(workspaceID: $0.workspaceID, panelID: nil) } + } + let resource = SurfaceResourceID(machine: machine, kind: .terminal, key: terminalID) + if let projection = projections(resource).first { + return CloudNotificationDeliveryTarget(workspaceID: projection.workspaceID, panelID: projection.panelID) + } + guard let remoteWorkspaceID = remoteWorkspaceID(terminalID) else { + return bound.first.map { CloudNotificationDeliveryTarget(workspaceID: $0.workspaceID, panelID: nil) } } - return bound.first.map { CloudNotificationDeliveryTarget(workspaceID: $0.workspaceID, panelID: nil) } + return bound.first { $0.remoteWorkspaceID == remoteWorkspaceID } + .map { CloudNotificationDeliveryTarget(workspaceID: $0.workspaceID, panelID: nil) } } } diff --git a/Sources/Cloud/CloudNotificationSyncHub.swift b/Sources/Cloud/CloudNotificationSyncHub.swift index f3b174a66e94..012b94df300b 100644 --- a/Sources/Cloud/CloudNotificationSyncHub.swift +++ b/Sources/Cloud/CloudNotificationSyncHub.swift @@ -85,8 +85,9 @@ final class CloudNotificationSyncHub { attach(store: store) } - /// Binds the hub to the local store: local records that become read or - /// are dismissed acknowledge their rows. + /// Binds the hub to the local store. Local records that become read or + /// are dismissed acknowledge their rows, and every read or clear the + /// store applies by target is mirrored onto the rows placed there. func attach(store: TerminalNotificationStore) { guard self.store !== store else { return } self.store = store @@ -98,6 +99,32 @@ final class CloudNotificationSyncHub { self?.storeDidChange(notifications) } } + store.readTargetObserver = { [weak self] target in + self?.noteRead(coveredBy: target) + } + } + + /// A read the store applied by target (a focused pane, a visited + /// workspace, mark-all-read, `cmux notify --clear`). Every machine + /// acknowledges the rows whose current placement the read covers, so the + /// Cloud tree dot follows the dismissal even for rows that never became a + /// local record; records for those rows that live on another workspace + /// (placed there before the terminal was opened here) are read with them. + func noteRead(coveredBy target: NotificationReadTarget) { + var readByMachine: [String: Set] = [:] + for sync in syncs.values { + let ids = sync.noteRead(coveredBy: target) + if !ids.isEmpty { readByMachine[sync.machineID] = Set(ids) } + } + guard !readByMachine.isEmpty, let store else { return } + let ids = store.notifications.compactMap { notification -> UUID? in + guard !notification.isRead, let key = notification.correlationKey, + let source = CloudNotificationCorrelation.parse(key), + readByMachine[source.machineID]?.contains(source.notificationID) == true else { return nil } + return notification.id + } + guard !ids.isEmpty else { return } + store.markNotificationFeedRead(ids: Set(ids)) } func storeDidChange(_ notifications: [TerminalNotification]) { @@ -121,8 +148,22 @@ final class CloudNotificationSyncHub { } } - /// Reads by daemon row id. + /// Reads by daemon row id. Without a live sync for the machine (asleep, + /// feature-suspended, between providers) the read is written to the + /// durable state directly, so the replacement sync loads it as a pending + /// acknowledgement instead of restoring the row as unread. func noteRead(notificationIDs ids: [String], machineID: String) { - syncs[machineID]?.noteRead(notificationIDs: ids) + if let sync = syncs[machineID] { + sync.noteRead(notificationIDs: ids) + return + } + let state = persistenceStore.load(machineID: machineID) + // No rows are known here, so the client id (only consulted against a + // row's `read_by`) does not take part in the decision. + let next = CloudNotificationSyncReducer.recordRead( + ids: ids, rows: [], clientID: "", state: state, newKey: CloudNotificationSync.mintAckKey + ) + guard next != state else { return } + persistenceStore.save(next, machineID: machineID) } } From 614c3ed5d4d58ab08e57e40dffef84176eefcbf2 Mon Sep 17 00:00:00 2001 From: Austin Wang Date: Fri, 18 Sep 2026 21:08:43 -0700 Subject: [PATCH 3/3] Decide mute before admission and fail closed on unmapped terminals Review follow-ups on manaflow-ai/cmux#13004: - `CloudNotificationLocalDelivery` decides workspace mute explicitly, before the admission gate, and only that decision suppresses (reads) the row. Any other store decline is transient (the pane's live owner vanished between placement and delivery) and is declined for the next fold instead of being acknowledged without a record. - `CloudNotificationPlacementResolver` returns no placement for a terminal row the accepted graph places in no workspace, instead of treating an unknown placement as a machine-level one and badging an unrelated bound workspace. Only rows without a terminal use the bound-workspace fallback. - Parity tests for both; the harness moves to its own file. - The dismissal-model fake host mutates its manual-unread state on clear, like the store, so repeated dismissals are modeled faithfully. Co-Authored-By: Claude Fable 5.1 --- .../NotificationDismissalModelTests.swift | 5 +- .../CloudNotificationLocalDelivery.swift | 17 +- .../Cloud/CloudNotificationPlacement.swift | 10 +- cmux.xcodeproj/project.pbxproj | 4 + ...loudNotificationDismissParityHarness.swift | 279 +++++++++++++++ .../CloudNotificationDismissParityTests.swift | 320 +++--------------- 6 files changed, 346 insertions(+), 289 deletions(-) create mode 100644 cmuxTests/CloudNotificationDismissParityHarness.swift diff --git a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift index 61dbcfd25511..3c58e218330f 100644 --- a/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift +++ b/Packages/macOS/CmuxNotifications/Tests/CmuxNotificationsTests/NotificationDismissalModelTests.swift @@ -110,12 +110,12 @@ private final class FakeHost: NotificationDismissalHosting { func storeClearManualUnread(workspaceId: UUID) -> Bool { log.append("storeClearManualUnread") - return manualWorkspaceUnread.contains(workspaceId) + return manualWorkspaceUnread.remove(workspaceId) != nil } func storeClearManualUnread(workspaceId: UUID, surfaceId: UUID) -> Bool { log.append("storeClearManualUnread:\(short(surfaceId))") - return manualSurfaceUnread.contains(surfaceId) + return manualSurfaceUnread.remove(surfaceId) != nil } func storeClearRestoredUnreadIndicator(workspaceId: UUID) -> Bool { @@ -129,6 +129,7 @@ private final class FakeHost: NotificationDismissalHosting { func workspaceClearManualUnread(workspaceId: UUID, panelId: UUID) { log.append("panelClearManualUnread") + manualPanelUnread.remove(panelId) } func workspaceClearRestoredUnreadIndicator(workspaceId: UUID, panelId: UUID) { diff --git a/Sources/Cloud/CloudNotificationLocalDelivery.swift b/Sources/Cloud/CloudNotificationLocalDelivery.swift index 71922bc0ff92..2baf9b614339 100644 --- a/Sources/Cloud/CloudNotificationLocalDelivery.swift +++ b/Sources/Cloud/CloudNotificationLocalDelivery.swift @@ -30,6 +30,15 @@ struct CloudNotificationLocalDelivery { func deliver(_ row: CloudVMNotificationRow, to target: CloudNotificationDeliveryTarget) -> CloudNotificationDeliveryOutcome { guard let store = store() else { return .declined } + // Workspace mute is an admission decision of the person's own: the + // row is read here rather than left as a dot no local dismissal can + // reach. Decided before the gate so a muted row costs no budget. + let admissionWorkspaceID = store.notificationMuteAdmissionTabID( + claimedTabId: target.workspaceID, + surfaceId: target.panelID, + retargetsToLiveSurfaceOwner: target.panelID != nil + ) + guard !store.isWorkspaceNotificationsMuted(forTabId: admissionWorkspaceID) else { return .suppressed } switch admit(row) { case .allowed: break @@ -70,9 +79,9 @@ struct CloudNotificationLocalDelivery { correlationKey: CloudNotificationCorrelation.key(machineID: machineID, notificationID: row.id), origin: .cloudVM(machineID: machineID) ) != nil - // The store declines for a muted workspace: an admission decision - // of its own, so the row is read here too rather than left as a dot - // that no local dismissal can reach. - return recorded ? .delivered : .suppressed + // Any other decline is transient (the pane's live owner vanished + // between placement and delivery): the next fold re-resolves it. A + // second attempt meets the gate's duplicate-id rule and is read. + return recorded ? .delivered : .declined } } diff --git a/Sources/Cloud/CloudNotificationPlacement.swift b/Sources/Cloud/CloudNotificationPlacement.swift index 7e386a912834..6b0f0d0971c4 100644 --- a/Sources/Cloud/CloudNotificationPlacement.swift +++ b/Sources/Cloud/CloudNotificationPlacement.swift @@ -55,8 +55,10 @@ struct CloudNotificationPlacementResolver { /// tree dot is its indicator, instead of stacking onto whichever local /// workspace happens to be bound to the machine (a workspace row then /// badges the whole machine's notifications, manaflow-ai/cmux#13000). - /// Only a machine-level row, one no remote workspace's tab shows, lands - /// on any local workspace bound to the machine. + /// Only a machine-level row (no terminal) lands on any local workspace + /// bound to the machine. A terminal the accepted graph places in no + /// workspace fails closed the same way: an unknown placement is not a + /// machine-level one. func target(for row: CloudVMNotificationRow) -> CloudNotificationDeliveryTarget? { let bound = boundWorkspaces() guard let terminalID = row.terminalID else { @@ -66,9 +68,7 @@ struct CloudNotificationPlacementResolver { if let projection = projections(resource).first { return CloudNotificationDeliveryTarget(workspaceID: projection.workspaceID, panelID: projection.panelID) } - guard let remoteWorkspaceID = remoteWorkspaceID(terminalID) else { - return bound.first.map { CloudNotificationDeliveryTarget(workspaceID: $0.workspaceID, panelID: nil) } - } + guard let remoteWorkspaceID = remoteWorkspaceID(terminalID) else { return nil } return bound.first { $0.remoteWorkspaceID == remoteWorkspaceID } .map { CloudNotificationDeliveryTarget(workspaceID: $0.workspaceID, panelID: nil) } } diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index bbfa515331ac..58cdbd4d4343 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -775,6 +775,7 @@ 4E25D4EB1F1D488A809C9C96 /* CloudNativeLayoutProjectionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DFD749234584EA0BC041370 /* CloudNativeLayoutProjectionTests.swift */; }; 7829E36E90E948BB82360052 /* CloudNightlyOverrideTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCD9CDECAE2049469F5CAB46 /* CloudNightlyOverrideTests.swift */; }; 16D0D1DB9FE54DB29743A98A /* CloudNotificationCorrelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 503C99BC313F48A48235DB1A /* CloudNotificationCorrelation.swift */; }; + E0AB5F18239F64CBC2B24AEA /* CloudNotificationDismissParityHarness.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD78BAE063E70755F45861C9 /* CloudNotificationDismissParityHarness.swift */; }; 4EFC91B414CF5D9FEA440819 /* CloudNotificationDismissParityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB8894FC01353CA3B8C9326F /* CloudNotificationDismissParityTests.swift */; }; 06A7D527A380A87E00C122EE /* CloudNotificationLocalDelivery.swift in Sources */ = {isa = PBXBuildFile; fileRef = D792B1E5CE28BAFC121F6781 /* CloudNotificationLocalDelivery.swift */; }; ED7A8BCBA7C0A396EAC81DAB /* CloudNotificationPlacement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D5BAD7EE4528BF8811C31A6 /* CloudNotificationPlacement.swift */; }; @@ -4744,6 +4745,7 @@ 5DFD749234584EA0BC041370 /* CloudNativeLayoutProjectionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CloudNativeLayoutProjectionTests.swift"; sourceTree = ""; }; DCD9CDECAE2049469F5CAB46 /* CloudNightlyOverrideTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudNightlyOverrideTests.swift; sourceTree = ""; }; 503C99BC313F48A48235DB1A /* CloudNotificationCorrelation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudNotificationCorrelation.swift; sourceTree = ""; }; + CD78BAE063E70755F45861C9 /* CloudNotificationDismissParityHarness.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudNotificationDismissParityHarness.swift; sourceTree = ""; }; CB8894FC01353CA3B8C9326F /* CloudNotificationDismissParityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudNotificationDismissParityTests.swift; sourceTree = ""; }; D792B1E5CE28BAFC121F6781 /* CloudNotificationLocalDelivery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudNotificationLocalDelivery.swift; sourceTree = ""; }; 6D5BAD7EE4528BF8811C31A6 /* CloudNotificationPlacement.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudNotificationPlacement.swift; sourceTree = ""; }; @@ -11285,6 +11287,7 @@ EF70B0862D206C62CA5ACF65 /* CloudManualMirrorSocketFixture.swift */, 64CB7AF7545F56E95A91B154 /* CloudNotificationSyncTests.swift */, CB8894FC01353CA3B8C9326F /* CloudNotificationDismissParityTests.swift */, + CD78BAE063E70755F45861C9 /* CloudNotificationDismissParityHarness.swift */, A12481000000000000000002 /* CloudSidebarScaleTests.swift */, A12481700000000000000002 /* SidebarDerivedStateScaleTests.swift */, A12481600000000000000002 /* CloudNotificationSyncStoreTests.swift */, @@ -15392,6 +15395,7 @@ BC9AC2D1065E4E88A48074BC /* CloudNameAuthorityTests.swift in Sources */, 4E25D4EB1F1D488A809C9C96 /* CloudNativeLayoutProjectionTests.swift in Sources */, 7829E36E90E948BB82360052 /* CloudNightlyOverrideTests.swift in Sources */, + E0AB5F18239F64CBC2B24AEA /* CloudNotificationDismissParityHarness.swift in Sources */, 4EFC91B414CF5D9FEA440819 /* CloudNotificationDismissParityTests.swift in Sources */, A12481600000000000000001 /* CloudNotificationSyncStoreTests.swift in Sources */, B71758C265B0439845140478 /* CloudNotificationSyncTests.swift in Sources */, diff --git a/cmuxTests/CloudNotificationDismissParityHarness.swift b/cmuxTests/CloudNotificationDismissParityHarness.swift new file mode 100644 index 000000000000..ea74f515e117 --- /dev/null +++ b/cmuxTests/CloudNotificationDismissParityHarness.swift @@ -0,0 +1,279 @@ +import AppKit +import Foundation +import Testing +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +/// The two sidebars, the store, and one machine wired the way the app wires +/// them: the shared store, a tab manager with a local workspace bound to the +/// machine's `ws_1` whose focused pane projects `term_a`, a catalog holding the +/// machine's graph (`ws_1`: `term_a`, `term_b`; `ws_2`: `term_c`), the +/// provider's placement resolver and local delivery, and a hub attached to +/// the store with an injectable admission clock. +@MainActor +final class CloudNotificationDismissParityHarness { + let machine = SurfaceMachineID.cloud("parity-machine") + let store: TerminalNotificationStore + let manager: TabManager + let workspace: Workspace + let panelID: UUID + let catalog: SurfaceCatalog + let provider: CloudPlacementTestProvider + let state: CloudVMState + let defaults: UserDefaults + let defaultsName: String + let persistence: CloudNotificationSyncStore + let hub: CloudNotificationSyncHub + let clock: AdmissionClock + private(set) var sync: CloudNotificationSync? + private var acks: [[String]] = [] + private let restore: @MainActor () -> Void + + final class AdmissionClock { + var now: UInt64 = 1 + } + + init() throws { + let store = TerminalNotificationStore.shared + let defaultsName = "cmux.tests.cloud-dismiss-parity.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: defaultsName)) + let clock = AdmissionClock() + let manager = TabManager() + self.store = store + self.defaultsName = defaultsName + self.defaults = defaults + self.clock = clock + self.manager = manager + let originalAppDelegate = AppDelegate.shared + let appDelegate = originalAppDelegate ?? AppDelegate() + let originalTabManager = appDelegate.tabManager + let originalStore = appDelegate.notificationStore + let originalFocus = AppFocusState.overrideIsFocused + let originalObserver = store.readTargetObserver + store.replaceNotificationsForTesting([]) + store.configureNotificationDeliveryHandlerForTesting { _, _ in } + store.configureSuppressedNotificationFeedbackHandlerForTesting { _, _ in } + appDelegate.tabManager = manager + appDelegate.notificationStore = store + if AppDelegate.shared == nil { AppDelegate.shared = appDelegate } + AppFocusState.overrideIsFocused = false + restore = { + for workspace in manager.tabs { manager.closeWorkspace(workspace) } + store.replaceNotificationsForTesting([]) + store.resetNotificationDeliveryHandlerForTesting() + store.resetSuppressedNotificationFeedbackHandlerForTesting() + store.readTargetObserver = originalObserver + appDelegate.tabManager = originalTabManager + appDelegate.notificationStore = originalStore + AppDelegate.shared = originalAppDelegate + AppFocusState.overrideIsFocused = originalFocus + defaults.removePersistentDomain(forName: defaultsName) + } + + workspace = try #require(manager.selectedWorkspace) + panelID = try #require(workspace.focusedPanelId) + workspace.cloudVMBinding = WorkspaceCloudVMBinding(vmID: machine.rawValue, isBase: false, remoteWorkspaceID: "ws_1") + + catalog = SurfaceCatalog() + provider = CloudPlacementTestProvider(machine: machine) + state = try Self.graph(machine: machine) + let info = SurfaceMachineInfo( + id: machine, name: "Fixture", status: "running", image: nil, hasDesktop: false, + memoryMb: nil, diskMb: nil, linkState: .connected, linkError: nil, + cpuPercent: nil, memoryUsedMb: nil, diskUsedMb: nil, + remoteWorkspaces: state.workspaces.map { + SurfaceRemoteWorkspace(id: $0.id, name: $0.name, index: $0.index, focused: $0.focused) + } + ) + provider.info = info + catalog.register(provider) + catalog.replaceCloudState(state, resources: CmuxTuiSnapshotParser.resources(from: state), info: info) + catalog.record(SurfaceProjection( + resource: SurfaceResourceID(machine: machine, kind: .terminal, key: "term_a"), + workspaceID: workspace.id, panelID: panelID, remoteWorkspaceID: "ws_1", remoteTabID: "tab_a" + )) + + persistence = CloudNotificationSyncStore(defaults: defaults) + hub = CloudNotificationSyncHub( + persistenceStore: persistence, + gate: CloudMachineNotificationGate(now: { clock.now }) + ) + hub.attach(store: store) + rebuildSync() + } + + func close() { + sync?.retire() + hub.unregister(machineID: machine.rawValue) + restore() + } + + // MARK: Machine graph + + private static func graph(machine: SurfaceMachineID) throws -> CloudVMState { + func tab(_ key: String, pane: String, index: Int) -> [String: Any] { + ["id": "tab_\(key)", "pane_id": pane, "index": index, "focused": index == 0, + "name": "", "content_kind": "terminal", "content_id": "term_\(key)"] + } + let document: [String: Any] = [ + "cursor": ["generation": "fixture", "revision": "1"], + "workspaces": [ + ["id": "ws_1", "name": "issue-1", "index": 0, "focused": true], + ["id": "ws_2", "name": "issue-2", "index": 1, "focused": false], + ], + "screens": [ + ["id": "screen_1", "workspace_id": "ws_1", "layout": [ + "version": 1, "screen_id": "screen_1", + "root": ["kind": "leaf", "pane_id": "pane_1", "tab_ids": ["tab_a", "tab_b"]], + ]], + ["id": "screen_2", "workspace_id": "ws_2", "layout": [ + "version": 1, "screen_id": "screen_2", + "root": ["kind": "leaf", "pane_id": "pane_2", "tab_ids": ["tab_c"]], + ]], + ], + "panes": [["id": "pane_1", "screen_id": "screen_1"], ["id": "pane_2", "screen_id": "screen_2"]], + "tabs": [tab("a", pane: "pane_1", index: 0), tab("b", pane: "pane_1", index: 1), tab("c", pane: "pane_2", index: 0)], + "terminals": ["a", "b", "c"].map { ["id": "term_\($0)", "title": "agent \($0)", "lifecycle": "running"] }, + "browsers": [], "agents": [], + ] + return try #require(CmuxTuiSnapshotParser.state(fromSnapshot: document, machine: machine)) + } + + func row(_ id: String, terminal: String, title: String, createdAt: UInt64) -> CloudVMNotificationRow { + CloudVMNotificationRow( + id: "notification_\(id)", title: title, subtitle: nil, body: "", level: "info", + createdAtMs: createdAt, terminalID: terminal, readBy: [] + ) + } + + // MARK: Sync lifecycle + + /// The provider's placement resolver and local delivery over this fixture. + private func makeSync() -> CloudNotificationSync { + let resolver = CloudNotificationPlacementResolver( + machine: machine, + projections: { [catalog] in catalog.projections(of: $0) }, + remoteWorkspaceID: { [state] terminalID in + for tab in state.tabs where tab.contentID == terminalID { + guard let pane = state.lookupIndex.pane(id: tab.paneID), + let screen = state.lookupIndex.screen(id: pane.screenID) else { continue } + return screen.workspaceID + } + return nil + }, + boundWorkspaces: { [manager, machine] in + manager.tabs.compactMap { workspace in + guard let binding = workspace.cloudVMBinding, binding.vmID == machine.rawValue else { return nil } + return CloudNotificationBoundWorkspace(workspaceID: workspace.id, remoteWorkspaceID: binding.remoteWorkspaceID) + } + } + ) + let delivery = CloudNotificationLocalDelivery( + machineID: machine.rawValue, + store: { [store] in store }, + admit: { [hub, machine] in hub.admit($0, machineID: machine.rawValue) }, + machineName: { "Fixture" }, + terminalTitle: { [state] in state.lookupIndex.terminal(id: $0)?.title } + ) + let machineID = machine.rawValue + let hub = hub + return CloudNotificationSync( + machineID: machineID, + clientID: "mac-parity", + store: persistence, + resolveTarget: { resolver.target(for: $0) }, + deliver: { delivery.deliver($0, to: $1) }, + send: { [weak self] batch in self?.acks.append(batch.ids) }, + unreadChanged: { hub.setUnread($0, machineID: machineID) }, + withdraw: { [store] ids in + let removed = Set(ids) + for notification in store.notifications where notification.correlationKey.map({ + CloudNotificationCorrelation.matches($0, machineID: machineID, notificationIDs: removed) + }) == true { + store.remove(id: notification.id) + } + } + ) + } + + /// A fresh sync from the durable state, as a provider rebuild does. + func rebuildSync() { + sync?.retire() + let next = makeSync() + sync = next + hub.register(next) + } + + /// The provider is suspended: its sync retires and leaves the hub. + func suspendSync() { + sync?.retire() + sync = nil + hub.unregister(machineID: machine.rawValue) + } + + func apply(_ rows: [CloudVMNotificationRow]) { + sync?.apply(rows: rows) + } + + func flush() async { + await sync?.flushPendingReads() + } + + var ackedIDs: Set { Set(acks.flatMap { $0 }) } + + /// The hub observes the store's `$notifications` publication on the main + /// run loop. Runs that loop until `predicate` holds; the deadline bounds + /// only the failure path. + func spinStoreSubscription(until predicate: () -> Bool) { + let deadline = Date().addingTimeInterval(10) + while !predicate(), Date() < deadline { + RunLoop.main.run(until: Date().addingTimeInterval(0.01)) + } + } + + // MARK: Indicators + + /// The left sidebar's badge for the bound workspace, from the coalesced + /// sidebar projection the workspace rows render. + var leftBadge: Int { + store.sidebarUnread.summaryByWorkspaceId[workspace.id]?.unreadCount ?? 0 + } + + /// Cloud tree rows carrying the attention dot, built from the catalog and + /// the hub's unread index exactly as the Machines panel builds them. + func treeDots() -> Set { + let nodes = CloudTreeNodeBuilder.nodes( + machines: [], snapshot: catalog.snapshot, localWorkspaces: [], + unreadTerminalIDs: hub.unreadTerminalIDs, includeLocalMachine: false + ) + var dots = Set() + for node in CloudTreeNodeBuilder.flattened(nodes) where node.hasUnreadAttention { + switch node.kind { + case .terminal(let row): + dots.insert(row.resource.id.key) + case .workspace: + for id in ["ws_1", "ws_2"] where node.id == CloudTreeNodeBuilder.nodeID(workspace: id, machine: machine) { + dots.insert(id) + } + default: + dots.insert(node.id) + } + } + return dots + } + + /// Every indicator for the workspace and the given terminals reports read. + func expectEverythingRead(terminals: [String], sourceLocation: SourceLocation = #_sourceLocation) { + let recordsRead = store.notifications.allSatisfy(\.isRead) + #expect(recordsRead, "store records", sourceLocation: sourceLocation) + #expect(leftBadge == 0, "left sidebar badge", sourceLocation: sourceLocation) + #expect(store.unreadCount(forTabId: workspace.id) == 0, "workspace unread count", sourceLocation: sourceLocation) + #expect(!store.hasVisibleNotificationIndicator(forTabId: workspace.id, surfaceId: panelID), "pane ring", sourceLocation: sourceLocation) + #expect(hub.unreadTerminalIDs[machine.rawValue] == nil, "hub unread index", sourceLocation: sourceLocation) + #expect(sync?.unreadTerminalIDs.isEmpty == true, "sync unread set", sourceLocation: sourceLocation) + #expect(treeDots().isEmpty, "Cloud tree dots \(treeDots()) for \(terminals)", sourceLocation: sourceLocation) + } +} diff --git a/cmuxTests/CloudNotificationDismissParityTests.swift b/cmuxTests/CloudNotificationDismissParityTests.swift index 378b79d8b30d..90593d72951b 100644 --- a/cmuxTests/CloudNotificationDismissParityTests.swift +++ b/cmuxTests/CloudNotificationDismissParityTests.swift @@ -19,7 +19,7 @@ import Testing struct CloudNotificationDismissParityTests { @Test("Clicking into the pane clears the ring and the Cloud tree dot, even with a deduplicated repeat row") func paneFocusClearsTheCloudTreeDot() async throws { - let harness = try ParityHarness() + let harness = try CloudNotificationDismissParityHarness() defer { harness.close() } let first = harness.row("finished-1", terminal: "term_a", title: "Codex finished", createdAt: 1) // Same terminal, same text, one second later: the admission gate's @@ -54,7 +54,7 @@ struct CloudNotificationDismissParityTests { @Test("Visiting the workspace reads a row placed at the workspace level (no pane shows its terminal)") func visitingTheWorkspaceReadsWorkspaceLevelRows() async throws { - let harness = try ParityHarness() + let harness = try CloudNotificationDismissParityHarness() defer { harness.close() } AppFocusState.overrideIsFocused = true let row = harness.row("b-1", terminal: "term_b", title: "Claude finished", createdAt: 1) @@ -78,7 +78,7 @@ struct CloudNotificationDismissParityTests { @Test("A remote workspace with no local workspace keeps its dot but never stacks onto another workspace's badge") func unopenedRemoteWorkspaceRowsStayOffTheLocalBadge() async throws { - let harness = try ParityHarness() + let harness = try CloudNotificationDismissParityHarness() defer { harness.close() } let row = harness.row("c-1", terminal: "term_c", title: "Codex finished", createdAt: 1) harness.apply([row]) @@ -107,7 +107,7 @@ struct CloudNotificationDismissParityTests { @Test("Rows over the admission rate are delivered on a later fold instead of leaving an undismissable dot") func rateLimitedRowsAreThrottledNotLost() async throws { - let harness = try ParityHarness() + let harness = try CloudNotificationDismissParityHarness() defer { harness.close() } let rows = (1...7).map { harness.row("burst-\($0)", terminal: "term_a", title: "finished \($0)", createdAt: UInt64($0)) } harness.apply(rows) @@ -128,7 +128,7 @@ struct CloudNotificationDismissParityTests { @Test("A dismissal while the machine's sync is gone is acknowledged when the sync comes back") func dismissalWhileTheSyncIsGoneSurvivesRestore() async throws { - let harness = try ParityHarness() + let harness = try CloudNotificationDismissParityHarness() defer { harness.close() } let row = harness.row("asleep-1", terminal: "term_a", title: "Codex finished", createdAt: 1) harness.apply([row]) @@ -154,7 +154,7 @@ struct CloudNotificationDismissParityTests { @Test("`cmux notify --clear` on the pane clears every indicator, including a deduplicated repeat row") func clearThroughTheSocketPathClearsEverything() async throws { - let harness = try ParityHarness() + let harness = try CloudNotificationDismissParityHarness() defer { harness.close() } let first = harness.row("clear-1", terminal: "term_a", title: "Build done", createdAt: 1) let repeat_ = harness.row("clear-2", terminal: "term_a", title: "Build done", createdAt: 2) @@ -170,290 +170,54 @@ struct CloudNotificationDismissParityTests { #expect(harness.ackedIDs == Set([first.id, repeat_.id])) } - @Test("Clicking the banner reads its row through the store subscription") - func clickingTheBannerReadsItsRow() async throws { - let harness = try ParityHarness() + @Test("A muted workspace reads its rows at once instead of leaving a dot nothing can dismiss") + func mutedWorkspaceRowsAreReadNotStranded() async throws { + let harness = try CloudNotificationDismissParityHarness() defer { harness.close() } - let row = harness.row("click-1", terminal: "term_a", title: "Codex finished", createdAt: 1) + harness.workspace.isMuted = true + let row = harness.row("muted-1", terminal: "term_a", title: "Codex finished", createdAt: 1) harness.apply([row]) - let record = try #require(harness.store.notifications.first) - - harness.store.markRead(id: record.id) - harness.spinStoreSubscription { harness.hub.unreadTerminalIDs[harness.machine.rawValue] == nil } + #expect(harness.store.notifications.isEmpty, "mute admits nothing locally") harness.expectEverythingRead(terminals: ["term_a"]) await harness.flush() - #expect(harness.ackedIDs == [row.id]) + #expect(harness.ackedIDs == [row.id], "the machine learns this client will never show it") } -} - -/// The two sidebars, the store, and one machine wired the way the app wires -/// them: the shared store, a tab manager with a local workspace bound to the -/// machine's `ws_1` whose focused pane projects `term_a`, a catalog holding the -/// machine's graph (`ws_1`: `term_a`, `term_b`; `ws_2`: `term_c`), the -/// provider's placement resolver and local delivery, and a hub attached to -/// the store with an injectable admission clock. -@MainActor -private final class ParityHarness { - let machine = SurfaceMachineID.cloud("parity-machine") - let store: TerminalNotificationStore - let manager: TabManager - let workspace: Workspace - let panelID: UUID - let catalog: SurfaceCatalog - let provider: CloudPlacementTestProvider - let state: CloudVMState - let defaults: UserDefaults - let defaultsName: String - let persistence: CloudNotificationSyncStore - let hub: CloudNotificationSyncHub - let clock: AdmissionClock - private(set) var sync: CloudNotificationSync? - private var acks: [[String]] = [] - private let restore: @MainActor () -> Void - - final class AdmissionClock { - var now: UInt64 = 1 - } - - init() throws { - let store = TerminalNotificationStore.shared - let defaultsName = "cmux.tests.cloud-dismiss-parity.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: defaultsName)) - let clock = AdmissionClock() - let manager = TabManager() - self.store = store - self.defaultsName = defaultsName - self.defaults = defaults - self.clock = clock - self.manager = manager - let originalAppDelegate = AppDelegate.shared - let appDelegate = originalAppDelegate ?? AppDelegate() - let originalTabManager = appDelegate.tabManager - let originalStore = appDelegate.notificationStore - let originalFocus = AppFocusState.overrideIsFocused - let originalObserver = store.readTargetObserver - store.replaceNotificationsForTesting([]) - store.configureNotificationDeliveryHandlerForTesting { _, _ in } - store.configureSuppressedNotificationFeedbackHandlerForTesting { _, _ in } - appDelegate.tabManager = manager - appDelegate.notificationStore = store - if AppDelegate.shared == nil { AppDelegate.shared = appDelegate } - AppFocusState.overrideIsFocused = false - restore = { - for workspace in manager.tabs { manager.closeWorkspace(workspace) } - store.replaceNotificationsForTesting([]) - store.resetNotificationDeliveryHandlerForTesting() - store.resetSuppressedNotificationFeedbackHandlerForTesting() - store.readTargetObserver = originalObserver - appDelegate.tabManager = originalTabManager - appDelegate.notificationStore = originalStore - AppDelegate.shared = originalAppDelegate - AppFocusState.overrideIsFocused = originalFocus - defaults.removePersistentDomain(forName: defaultsName) - } - workspace = try #require(manager.selectedWorkspace) - panelID = try #require(workspace.focusedPanelId) - workspace.cloudVMBinding = WorkspaceCloudVMBinding(vmID: machine.rawValue, isBase: false, remoteWorkspaceID: "ws_1") + @Test("A terminal the graph places in no workspace fails closed instead of badging an unrelated workspace") + func unmappedTerminalRowsHaveNoLocalHome() async throws { + let harness = try CloudNotificationDismissParityHarness() + defer { harness.close() } + // The daemon knows the terminal but no tab shows it. + let row = harness.row("detached-1", terminal: "term_detached", title: "Build done", createdAt: 1) + harness.apply([row]) - catalog = SurfaceCatalog() - provider = CloudPlacementTestProvider(machine: machine) - state = try Self.graph(machine: machine) - let info = SurfaceMachineInfo( - id: machine, name: "Fixture", status: "running", image: nil, hasDesktop: false, - memoryMb: nil, diskMb: nil, linkState: .connected, linkError: nil, - cpuPercent: nil, memoryUsedMb: nil, diskUsedMb: nil, - remoteWorkspaces: state.workspaces.map { - SurfaceRemoteWorkspace(id: $0.id, name: $0.name, index: $0.index, focused: $0.focused) - } - ) - provider.info = info - catalog.register(provider) - catalog.replaceCloudState(state, resources: CmuxTuiSnapshotParser.resources(from: state), info: info) - catalog.record(SurfaceProjection( - resource: SurfaceResourceID(machine: machine, kind: .terminal, key: "term_a"), - workspaceID: workspace.id, panelID: panelID, remoteWorkspaceID: "ws_1", remoteTabID: "tab_a" + #expect(harness.store.notifications.isEmpty) + #expect(harness.leftBadge == 0) + #expect(harness.hub.unreadTerminalIDs[harness.machine.rawValue] == ["term_detached"], "the row stays unread on the machine side") + // Nothing consumed it: a later fold with a placement delivers it. + harness.catalog.record(SurfaceProjection( + resource: SurfaceResourceID(machine: harness.machine, kind: .terminal, key: "term_detached"), + workspaceID: harness.workspace.id, panelID: harness.panelID, remoteWorkspaceID: "ws_1", remoteTabID: "tab_d" )) - - persistence = CloudNotificationSyncStore(defaults: defaults) - hub = CloudNotificationSyncHub( - persistenceStore: persistence, - gate: CloudMachineNotificationGate(now: { clock.now }) - ) - hub.attach(store: store) - rebuildSync() - } - - func close() { - sync?.retire() - hub.unregister(machineID: machine.rawValue) - restore() - } - - // MARK: Machine graph - - private static func graph(machine: SurfaceMachineID) throws -> CloudVMState { - func tab(_ key: String, pane: String, index: Int) -> [String: Any] { - ["id": "tab_\(key)", "pane_id": pane, "index": index, "focused": index == 0, - "name": "", "content_kind": "terminal", "content_id": "term_\(key)"] - } - let document: [String: Any] = [ - "cursor": ["generation": "fixture", "revision": "1"], - "workspaces": [ - ["id": "ws_1", "name": "issue-1", "index": 0, "focused": true], - ["id": "ws_2", "name": "issue-2", "index": 1, "focused": false], - ], - "screens": [ - ["id": "screen_1", "workspace_id": "ws_1", "layout": [ - "version": 1, "screen_id": "screen_1", - "root": ["kind": "leaf", "pane_id": "pane_1", "tab_ids": ["tab_a", "tab_b"]], - ]], - ["id": "screen_2", "workspace_id": "ws_2", "layout": [ - "version": 1, "screen_id": "screen_2", - "root": ["kind": "leaf", "pane_id": "pane_2", "tab_ids": ["tab_c"]], - ]], - ], - "panes": [["id": "pane_1", "screen_id": "screen_1"], ["id": "pane_2", "screen_id": "screen_2"]], - "tabs": [tab("a", pane: "pane_1", index: 0), tab("b", pane: "pane_1", index: 1), tab("c", pane: "pane_2", index: 0)], - "terminals": ["a", "b", "c"].map { ["id": "term_\($0)", "title": "agent \($0)", "lifecycle": "running"] }, - "browsers": [], "agents": [], - ] - return try #require(CmuxTuiSnapshotParser.state(fromSnapshot: document, machine: machine)) - } - - func row(_ id: String, terminal: String, title: String, createdAt: UInt64) -> CloudVMNotificationRow { - CloudVMNotificationRow( - id: "notification_\(id)", title: title, subtitle: nil, body: "", level: "info", - createdAtMs: createdAt, terminalID: terminal, readBy: [] - ) - } - - // MARK: Sync lifecycle - - /// The provider's placement resolver and local delivery over this fixture. - private func makeSync() -> CloudNotificationSync { - let resolver = CloudNotificationPlacementResolver( - machine: machine, - projections: { [catalog] in catalog.projections(of: $0) }, - remoteWorkspaceID: { [state] terminalID in - for tab in state.tabs where tab.contentID == terminalID { - guard let pane = state.lookupIndex.pane(id: tab.paneID), - let screen = state.lookupIndex.screen(id: pane.screenID) else { continue } - return screen.workspaceID - } - return nil - }, - boundWorkspaces: { [manager, machine] in - manager.tabs.compactMap { workspace in - guard let binding = workspace.cloudVMBinding, binding.vmID == machine.rawValue else { return nil } - return CloudNotificationBoundWorkspace(workspaceID: workspace.id, remoteWorkspaceID: binding.remoteWorkspaceID) - } - } - ) - let delivery = CloudNotificationLocalDelivery( - machineID: machine.rawValue, - store: { [store] in store }, - admit: { [hub, machine] in hub.admit($0, machineID: machine.rawValue) }, - machineName: { "Fixture" }, - terminalTitle: { [state] in state.lookupIndex.terminal(id: $0)?.title } - ) - let machineID = machine.rawValue - let hub = hub - return CloudNotificationSync( - machineID: machineID, - clientID: "mac-parity", - store: persistence, - resolveTarget: { resolver.target(for: $0) }, - deliver: { delivery.deliver($0, to: $1) }, - send: { [weak self] batch in self?.acks.append(batch.ids) }, - unreadChanged: { hub.setUnread($0, machineID: machineID) }, - withdraw: { [store] ids in - let removed = Set(ids) - for notification in store.notifications where notification.correlationKey.map({ - CloudNotificationCorrelation.matches($0, machineID: machineID, notificationIDs: removed) - }) == true { - store.remove(id: notification.id) - } - } - ) - } - - /// A fresh sync from the durable state, as a provider rebuild does. - func rebuildSync() { - sync?.retire() - let next = makeSync() - sync = next - hub.register(next) - } - - /// The provider is suspended: its sync retires and leaves the hub. - func suspendSync() { - sync?.retire() - sync = nil - hub.unregister(machineID: machine.rawValue) - } - - func apply(_ rows: [CloudVMNotificationRow]) { - sync?.apply(rows: rows) - } - - func flush() async { - await sync?.flushPendingReads() - } - - var ackedIDs: Set { Set(acks.flatMap { $0 }) } - - /// The hub observes the store's `$notifications` publication on the main - /// run loop. Runs that loop until `predicate` holds; the deadline bounds - /// only the failure path. - func spinStoreSubscription(until predicate: () -> Bool) { - let deadline = Date().addingTimeInterval(10) - while !predicate(), Date() < deadline { - RunLoop.main.run(until: Date().addingTimeInterval(0.01)) - } + harness.apply([row]) + #expect(harness.store.notifications.count == 1) + #expect(harness.leftBadge == 1) } - // MARK: Indicators - - /// The left sidebar's badge for the bound workspace, from the coalesced - /// sidebar projection the workspace rows render. - var leftBadge: Int { - store.sidebarUnread.summaryByWorkspaceId[workspace.id]?.unreadCount ?? 0 - } + @Test("Clicking the banner reads its row through the store subscription") + func clickingTheBannerReadsItsRow() async throws { + let harness = try CloudNotificationDismissParityHarness() + defer { harness.close() } + let row = harness.row("click-1", terminal: "term_a", title: "Codex finished", createdAt: 1) + harness.apply([row]) + let record = try #require(harness.store.notifications.first) - /// Cloud tree rows carrying the attention dot, built from the catalog and - /// the hub's unread index exactly as the Machines panel builds them. - func treeDots() -> Set { - let nodes = CloudTreeNodeBuilder.nodes( - machines: [], snapshot: catalog.snapshot, localWorkspaces: [], - unreadTerminalIDs: hub.unreadTerminalIDs, includeLocalMachine: false - ) - var dots = Set() - for node in CloudTreeNodeBuilder.flattened(nodes) where node.hasUnreadAttention { - switch node.kind { - case .terminal(let row): - dots.insert(row.resource.id.key) - case .workspace: - for id in ["ws_1", "ws_2"] where node.id == CloudTreeNodeBuilder.nodeID(workspace: id, machine: machine) { - dots.insert(id) - } - default: - dots.insert(node.id) - } - } - return dots - } + harness.store.markRead(id: record.id) + harness.spinStoreSubscription { harness.hub.unreadTerminalIDs[harness.machine.rawValue] == nil } - /// Every indicator for the workspace and the given terminals reports read. - func expectEverythingRead(terminals: [String], sourceLocation: SourceLocation = #_sourceLocation) { - let recordsRead = store.notifications.allSatisfy(\.isRead) - #expect(recordsRead, "store records", sourceLocation: sourceLocation) - #expect(leftBadge == 0, "left sidebar badge", sourceLocation: sourceLocation) - #expect(store.unreadCount(forTabId: workspace.id) == 0, "workspace unread count", sourceLocation: sourceLocation) - #expect(!store.hasVisibleNotificationIndicator(forTabId: workspace.id, surfaceId: panelID), "pane ring", sourceLocation: sourceLocation) - #expect(hub.unreadTerminalIDs[machine.rawValue] == nil, "hub unread index", sourceLocation: sourceLocation) - #expect(sync?.unreadTerminalIDs.isEmpty == true, "sync unread set", sourceLocation: sourceLocation) - #expect(treeDots().isEmpty, "Cloud tree dots \(treeDots()) for \(terminals)", sourceLocation: sourceLocation) + harness.expectEverythingRead(terminals: ["term_a"]) + await harness.flush() + #expect(harness.ackedIDs == [row.id]) } }