SPB Git

Repository Public

Notifier.swift 7.2 KB 135 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/Notifier.swift3// Description: System notifications of the app (a job or an analysis finished in the background, an approval is needed), what happens when one is clicked, and the router that brings a main window to the place a notification, the menu-bar extra or a launch argument asks for.4import AppKit5import SwiftUI6import UserNotifications7import VQuantCore89/// Local notifications. Nothing is pushed by the server: the app posts them itself when it sees, while it is in the10/// background, that something finished or that the research agent waits for an approval.11enum Notifier {12    /// Set once by `AppEnvironment.wire()`: the toggles of Settings ▸ Notifications.13    private(set) static weak var settings: SettingsStore?14    private static let delegate = NotificationDelegate()1516    /// Installs the click handler. Called at launch, before any notification can be answered.17    static func configure(settings: SettingsStore) {18        self.settings = settings19        UNUserNotificationCenter.current().delegate = delegate20    }2122    static func requestAuthorization() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { _, _ in } }2324    /// Posts a notification now. `route` says what a click opens.25    static func post(title: String, body: String, id: String, route: NotificationRoute? = nil) {26        let c = UNMutableNotificationContent(); c.title = title; c.body = String(body.prefix(140)); c.sound = .default27        if let route { c.userInfo = route.userInfo }28        UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: id, content: c, trigger: nil))29    }3031    /// An analysis or a research run ended while the app was in the background (`notifyOnCompletion`).32    static func analysisFinished(question: String, sessionId: String?, failed: Bool, id: String) {33        guard settings?.notifyOnCompletion ?? true, !NSApp.isActive else { return }34        post(title: failed ? "Analysis interrupted" : "Analysis finished", body: question, id: id, route: .conversation(sessionId))35    }3637    /// A quant job ended while the app was in the background (`notifyOnCompletion`).38    static func jobFinished(title: String, subject: String, jobId: String, failed: Bool) {39        guard settings?.notifyOnCompletion ?? true, !NSApp.isActive else { return }40        post(title: failed ? "Computation failed" : "Computation finished", body: "\(title) · \(subject)", id: jobId, route: .quantJob(jobId))41    }4243    /// The research agent waits for the person's approval (a network-open run, a budget override…) in the44    /// conversation `sessionId`. Posted only while the app is in the background and when Settings allows it45    /// (`notifyOnApproval`); clicking it brings VQuant forward on that conversation. Returns whether it was posted.46    @discardableResult47    static func approvalNeeded(title: String, body: String, sessionId: String) -> Bool {48        guard settings?.notifyOnApproval ?? true, !NSApp.isActive else { return false }49        // one notification per conversation: a second request replaces the first instead of stacking50        post(title: title, body: body, id: "approval-\(sessionId)", route: .approval(sessionId: sessionId))51        return true52    }5354    /// Withdraws the approval notification of a conversation (answered in the app, or the run ended).55    static func clearApproval(sessionId: String) {56        UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["approval-\(sessionId)"])57    }58}5960/// Answers the system: banners are shown only while the app is in the background, and a click is routed.61private final class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {62    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {63        // in the foreground the window itself shows the result or the approval request64        await MainActor.run { NSApp.isActive } ? [] : [.banner, .sound, .list]65    }6667    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {68        guard response.actionIdentifier == UNNotificationDefaultActionIdentifier else { return }69        let info = response.notification.request.content.userInfo70        let kind = info[NotificationRoute.kindKey] as? String, id = info[NotificationRoute.idKey] as? String71        await MainActor.run {72            var payload: [AnyHashable: Any] = [:]73            if let kind { payload[NotificationRoute.kindKey] = kind }74            if let id { payload[NotificationRoute.idKey] = id }75            WindowRouter.open(NotificationRoute(userInfo: payload).map(WindowRouter.Destination.notification) ?? .front)76        }77    }78}7980/// Brings a main window forward on a given place. Windows register their `WindowModel` here (weakly); the frontmost81/// one is used, and when no main window is open one is created and takes the destination as it appears.82enum WindowRouter {83    enum Destination {84        /// Just bring the app forward.85        case front86        case notification(NotificationRoute)87        /// A question for the Research composer (the menu-bar extra's quick ask). It is never sent by itself.88        case ask(AskDraft)89        case conversation(String)90        case quantJob(String)91        case section(AppSection)92    }9394    private static let models = NSHashTable<WindowModel>.weakObjects()95    /// Waiting for a window that is being opened.96    private(set) static var pending: Destination?9798    /// Called by each main window when its model exists; a destination that was waiting is applied to it.99    static func register(_ model: WindowModel) {100        models.add(model)101        if let d = pending { pending = nil; apply(d, to: model) }102    }103104    /// The model of the key or main window, else of the frontmost visible main window.105    static var frontmost: WindowModel? {106        let all = models.allObjects.filter { $0.window?.isVisible == true }107        if let m = all.first(where: { $0.window?.isKeyWindow == true }) ?? all.first(where: { $0.window?.isMainWindow == true }) { return m }108        for w in NSApp.orderedWindows { if let m = all.first(where: { $0.window === w }) { return m } }109        return models.allObjects.first { $0.window != nil }110    }111112    static func open(_ destination: Destination) {113        NSApp.activate(ignoringOtherApps: true)114        if let m = frontmost {115            m.window?.deminiaturize(nil)116            m.window?.makeKeyAndOrderFront(nil)117            apply(destination, to: m)118        } else {119            pending = destination120            MainWindowOpener.open?()121        }122    }123124    static func apply(_ destination: Destination, to model: WindowModel) {125        switch destination {126        case .front: break127        case .notification(.conversation(let id)): if let id { model.openConversation(id) } else { model.show(.research) }128        case .notification(.approval(let id)), .conversation(let id): model.openConversation(id)129        case .notification(.quantJob(let id)), .quantJob(let id): model.openQuantJob(id)130        case .ask(let draft): model.ask(draft)131        case .section(let s): model.show(s)132        }133    }134}135
Files main
Menu

Theme