public import Foundation import Observation public import ParcelCore @MainActor @Observable public final class FeedbackModel { public private(set) var history: FeedbackHistory public private(set) var recent: [FeedbackNotice] = [] public private(set) var pending: [FeedbackNotice] = [] public private(set) var historyError: String? public var current: FeedbackNotice? { pending.first { notice in notice.workspace.map { !inactiveWorkspaces.contains($0) } ?? true } } private var inactiveWorkspaces: Set = [] private var automaticRooms = AutomaticRoomReminders() private struct StackReminder: Equatable { let count: Int let windows: [WindowID]? } private var stackReminders: [WorkspaceKey: [WindowID: StackReminder]] = [:] private var undoActions: [UUID: @MainActor () async throws -> Void] = [:] public func hasUndo(for id: UUID) -> Bool { undoActions[id] != nil } @discardableResult public func receive(_ notice: FeedbackNotice, undo: @escaping @MainActor () async throws -> Void) throws -> Bool { precondition(notice.kind == .message) undoActions[notice.id] = undo let accepted = try receive(notice) if !pending.contains(where: { $0.id == notice.id }) { undoActions[notice.id] = nil } return accepted } public func undo(_ id: UUID) async throws { guard let action = undoActions.removeValue(forKey: id) else { throw FeedbackHistoryError.invalidEntry } do { try await action() dismiss(id) } catch { if pending.contains(where: { $0.id == id }) { undoActions[id] = action } throw error } } public var onChange: (@MainActor () -> Void)? public var onShowAgain: (@MainActor (String) -> Void)? public var onReviewRoomReminder: (@MainActor (FeedbackNotice) throws -> Void)? public var onForgetMinimum: (@MainActor (String) async throws -> Void)? private let save: @MainActor (FeedbackHistory) throws -> Void private let now: @MainActor () -> Date private let calendar: Calendar public init( history: FeedbackHistory = FeedbackHistory(), historyError: String? = nil, calendar: Calendar = .current, now: @escaping @MainActor () -> Date = { Date() }, save: @escaping @MainActor (FeedbackHistory) throws -> Void = { _ in } ) { self.history = history self.historyError = historyError self.calendar = calendar self.now = now self.save = save } @discardableResult public func receive( _ notice: FeedbackNotice, explicitlyRequested: Bool = false, state: State? = nil ) throws -> Bool { if notice.kind == .tilesMerged, let workspace = notice.workspace, let window = notice.window { let reminder = StackReminder( count: notice.count, windows: state?.workspaces[workspace]?.tree?.stacks.first { $0.windows.contains(window) }?.windows .sorted()) if stackReminders[workspace]?[window] == reminder { return current?.coalesces(with: notice) == true } stackReminders[workspace, default: [:]][window] = reminder } if notice.kind != .needsRoom, let current, current.coalesces(with: notice) { return true } if notice.kind == .needsRoom, let bundle = notice.bundleID, !bundle.isEmpty { guard historyError == nil else { throw FeedbackHistoryError.invalidEntry } guard explicitlyRequested || history.shouldShow(for: bundle, at: now(), calendar: calendar) else { return false } var next = history next.record(bundleID: bundle, applicationName: notice.applicationName ?? bundle, at: now()) try save(next) history = next pending.removeAll { $0.kind == .needsRoom && $0.bundleID == bundle } } else if notice.kind != .message { pending.removeAll { $0.kind != .needsRoom && $0.kind != .message } } if explicitlyRequested, notice.kind == .needsRoom { pending.removeAll { $0.kind == .needsRoom } } recent.removeAll { $0.kind == notice.kind && $0.bundleID == notice.bundleID && $0.window == notice.window } recent.insert(notice, at: 0) recent = Array(recent.prefix(20)) let insertion: Int switch notice.kind { case .message: insertion = pending.firstIndex { $0.kind != .message } ?? pending.count case .needsRoom: insertion = pending.firstIndex { $0.kind != .message && $0.kind != .needsRoom } ?? pending.count default: insertion = pending.count } pending.insert(notice, at: insertion) pruneUndoActions() onChange?() return true } public func receiveAutomaticRoomReminders(_ notices: [FeedbackNotice], state: State) throws { precondition(notices.allSatisfy { $0.kind == .needsRoom }) var accepted: [FeedbackNotice] = [] var next = history for notice in notices { guard let application = RoomReminderApplication(notice, state: state), !automaticRooms.contains(notice, state: state) else { continue } if let bundle = application.bundleID { guard historyError == nil else { throw FeedbackHistoryError.invalidEntry } guard next.shouldShow(for: bundle, at: now(), calendar: calendar) else { continue } next.record(bundleID: bundle, applicationName: notice.applicationName ?? bundle, at: now()) } accepted.append(notice) } guard !accepted.isEmpty else { return } if next != history { try save(next) history = next } for notice in accepted { automaticRooms.record(notice, state: state) let application = RoomReminderApplication(notice, state: state) recent.removeAll { $0.kind == .needsRoom && RoomReminderApplication($0, state: state) == application } recent.insert(notice, at: 0) } recent = Array(recent.prefix(20)) updateRoomSummary() onChange?() } private func updateRoomSummary() { let rooms = automaticRooms.unresolved let previous = pending.first(where: \.isRoomSummary) pending.removeAll { $0.isRoomSummary } guard !rooms.isEmpty else { return } let names = Array(Set(rooms.compactMap(\.applicationName))).sorted() let summary = FeedbackNotice( id: previous?.id ?? UUID(), kind: .needsRoom, count: rooms.count, window: nil, workspace: nil, bundleID: nil, applicationName: ListFormatter.localizedString(byJoining: names), layout: nil, limit: nil) let insertion = pending.firstIndex { $0.kind != .message } ?? pending.count pending.insert(summary, at: insertion) } public func dismiss(_ id: UUID) { undoActions[id] = nil pending.removeAll { $0.id == id } onChange?() } public func dismissMessages(kind: String) { let before = pending.count pending.removeAll { $0.kind == .message && $0.messageKind == kind } pruneUndoActions() if pending.count != before { onChange?() } } public func reconcile(_ state: State, active: Bool) { let before = pending let previous = current if automaticRooms.reconcile(state), pending.contains(where: \.isRoomSummary) { updateRoomSummary() } stackReminders = stackReminders.compactMapValues { reminders in let retained = reminders.filter { window, reminder in guard let stack = state.workspaces.values.compactMap(\.tree).flatMap(\.stacks) .first(where: { $0.windows.min() == window }) else { return false } return stack.windows.count == reminder.count && (reminder.windows.map { $0 == stack.windows.sorted() } ?? true) } return retained.isEmpty ? nil : retained } pending.removeAll { notice in guard active || notice.kind == .message else { return true } guard notice.kind == .needsRoom, let window = notice.window, let workspace = notice.workspace else { return false } return state.windows[window]?.isFloating != false || state.workspace(containing: window) != workspace || notice.processIdentifier.map { state.windows[window]?.app.pid != $0 } == true } pruneUndoActions() inactiveWorkspaces = Set(pending.compactMap(\.workspace).filter { !state.isActive($0) }) if pending != before || previous != current { onChange?() } } private func pruneUndoActions() { let retained = Set(pending.map(\.id)) undoActions = undoActions.filter { retained.contains($0.key) } } public func reviewRoomReminder(_ notice: FeedbackNotice) throws { guard let onReviewRoomReminder else { throw RoomReminderError.unavailable } try onReviewRoomReminder(notice) } public func showAgain(_ bundleID: String) { onShowAgain?(bundleID) } public func forgetMinimum(_ bundleID: String) async throws { guard let onForgetMinimum else { throw FeedbackHistoryError.invalidEntry } try await onForgetMinimum(bundleID) var next = history next.forget(bundleID) try save(next) history = next automaticRooms.forget(bundleID) pending.removeAll { $0.bundleID == bundleID } if pending.contains(where: \.isRoomSummary) { updateRoomSummary() } onChange?() } public func resetHistory() throws { let next = FeedbackHistory() try save(next) history = next historyError = nil automaticRooms = AutomaticRoomReminders() onChange?() } }