SPB Git

Repository Public

SystemIntegration.swift 13.7 KB 230 lines swift

1//2//  VQuant iOS3//  File: VQuant/Platform/SystemIntegration.swift4//  Description: Local notifications for finished server jobs, the background refresh that detects them, and Spotlight indexing.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import BackgroundTasks11@preconcurrency import CoreSpotlight12import Foundation13import UserNotifications14import VQuantKit15import WidgetKit1617/// Notifications are local: the VQuant backend has no push channel (no APNs integration), so a completion is announced18/// when this device observes it — while the app is open, or during a background refresh granted by iOS. Each one19/// reports a state actually read from the server.20@MainActor21final class NotificationCenterBridge: NSObject, UNUserNotificationCenterDelegate {22    nonisolated static let analysisCategory = "ANALYSIS_DONE"23    nonisolated static let quantCategory = "QUANT_DONE"24    nonisolated static let approvalCategory = "RESEARCH_APPROVAL"25    nonisolated static let approveAction = "APPROVE"26    nonisolated static let denyAction = "DENY"27    /// Set by the app: answers an approval request from the notification's buttons (true = approve).28    var onApprovalDecision: (@MainActor (String, Bool) async -> Void)?29    /// Set by the app: opens the destination of a tapped notification.30    var onOpen: (@MainActor (URL) -> Void)?31    /// Job currently on screen: no banner for what the user is looking at.32    var visibleJobId: String?3334    func install() {35        let center = UNUserNotificationCenter.current()36        center.delegate = self37        center.setNotificationCategories([38            UNNotificationCategory(identifier: Self.analysisCategory, actions: [], intentIdentifiers: []),39            UNNotificationCategory(identifier: Self.quantCategory, actions: [], intentIdentifiers: []),40            // The agent waits 15 minutes for an answer. "Approve" asks the device to be unlocked first; both actions41            // run without opening the app.42            UNNotificationCategory(identifier: Self.approvalCategory, actions: [43                UNNotificationAction(identifier: Self.approveAction, title: "Autoriser", options: [.authenticationRequired]),44                UNNotificationAction(identifier: Self.denyAction, title: "Refuser", options: [.destructive]),45            ], intentIdentifiers: []),46        ])47    }4849    func authorizationStatus() async -> UNAuthorizationStatus { await UNUserNotificationCenter.current().notificationSettings().authorizationStatus }5051    @discardableResult52    func requestAuthorization() async -> Bool {53        (try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])) ?? false54    }5556    func notifyAnalysis(jobId: String?, sessionId: String?, query: String, failed: Bool) {57        if let jobId, jobId == visibleJobId { return }58        let url = sessionId.map { "vquant://conversation/\($0)" } ?? "vquant://research"59        Self.post(id: "analysis-\(jobId ?? UUID().uuidString)", title: failed ? "Analyse interrompue" : "Analyse terminée", body: String(query.prefix(140)), url: url, category: Self.analysisCategory)60    }6162    func notifyQuant(job: QuantJob, title: String) {63        if job.id == visibleJobId { return }64        let symbol = job.params["symbol"]?.stringValue ?? job.params["symbols"]?.arrayValue?.compactMap(\.stringValue).joined(separator: ", ") ?? ""65        Self.post(id: "quant-\(job.id)", title: job.status == .done ? "Calcul terminé" : "Calcul en échec", body: [title, symbol].filter { !$0.isEmpty }.joined(separator: " · "),66                  url: "vquant://quant/\(job.id)", category: Self.quantCategory)67    }6869    func notifyLab(job: VQQuantJob, title: String) {70        if job.id == visibleJobId { return }71        let symbol = job.params["symbol"]?.stringValue ?? job.params["symbols"]?.arrayValue?.compactMap(\.stringValue).joined(separator: ", ") ?? ""72        let heading = job.status == .done ? "Calcul terminé" : job.status == .cancelled ? "Calcul annulé" : "Calcul en échec"73        Self.post(id: "quant-\(job.id)", title: heading, body: [title, symbol].filter { !$0.isEmpty }.joined(separator: " · "), url: "vquant://quant/\(job.id)", category: Self.quantCategory)74    }7576    /// The research agent asks for an authorisation (open network, data leaving, higher budget). Local notification:77    /// it is posted when this device learns of the request — on a live stream, at a poll, or at a background refresh.78    func notifyApproval(_ a: VQResearchApproval) {79        let content = UNMutableNotificationContent()80        content.title = "L’agent demande une autorisation"81        content.subtitle = a.title(.fr)82        content.body = String((a.reason ?? a.scope(.fr)).prefix(220))83        content.sound = .default84        content.categoryIdentifier = Self.approvalCategory85        content.interruptionLevel = .timeSensitive86        content.userInfo = ["url": "vquant://approvals", "approval": a.id]87        content.threadIdentifier = Self.approvalCategory88        UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: "approval-\(a.id)", content: content, trigger: nil))89    }90    func clearApproval(_ id: String) { UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["approval-\(id)"]) }9192    nonisolated static func post(id: String, title: String, body: String, url: String, category: String) {93        let content = UNMutableNotificationContent()94        content.title = title; content.body = body; content.sound = .default95        content.categoryIdentifier = category96        content.userInfo = ["url": url]97        content.threadIdentifier = category98        UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: id, content: content, trigger: nil))99    }100101    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {102        [.banner, .list, .sound]103    }104105    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {106        let info = response.notification.request.content.userInfo107        let action = response.actionIdentifier108        if let approval = info["approval"] as? String, action == Self.approveAction || action == Self.denyAction {109            await self.decide(approval, approve: action == Self.approveAction)110            return111        }112        guard let s = info["url"] as? String, let url = URL(string: s) else { return }113        await MainActor.run { self.onOpen?(url) }114    }115}116117/// Background refresh. iOS decides when (and whether) it runs; it is a convenience, never a dependency: computations118/// run on the server regardless. When it runs it checks the jobs that were running when the app left the foreground119/// and announces those that ended.120extension NotificationCenterBridge {121    fileprivate func decide(_ id: String, approve: Bool) async { await onApprovalDecision?(id, approve) }122}123124enum BackgroundRefresh {125    static let identifier = "ai.spboucher.vquant.refresh"126    static let trackedKey = "background.tracked"127128    struct Tracked: Codable { var analyses: [String] = []; var quant: [String] = [] }129130    static func track(analyses: [String], quant: [String], defaults: UserDefaults = .standard) {131        if let d = try? JSONEncoder().encode(Tracked(analyses: analyses, quant: quant)) { defaults.set(d, forKey: trackedKey) }132    }133    static func tracked(_ defaults: UserDefaults = .standard) -> Tracked {134        defaults.data(forKey: trackedKey).flatMap { try? JSONDecoder().decode(Tracked.self, from: $0) } ?? Tracked()135    }136137    static func schedule(defaults: UserDefaults = .standard) {138        let t = tracked(defaults)139        let request = BGAppRefreshTaskRequest(identifier: identifier)140        // Sooner when something is running; otherwise an occasional refresh of the widget data.141        request.earliestBeginDate = Date(timeIntervalSinceNow: (t.analyses.isEmpty && t.quant.isEmpty) ? 3600 : 120)142        try? BGTaskScheduler.shared.submit(request)143    }144145    /// What ended since the app was last active. Pure: decided from the tracked ids and the server's lists.146    static func finished(tracked: Tracked, generations: [Generation], jobs: [QuantJob]) -> (analyses: [Generation], quant: [QuantJob], still: Tracked) {147        let endedA = generations.filter { tracked.analyses.contains($0.id) && $0.status != .running }148        let endedQ = jobs.filter { tracked.quant.contains($0.id) && $0.status != .running }149        let still = Tracked(analyses: generations.filter { $0.status == .running }.map(\.id), quant: jobs.filter { $0.status == .running }.map(\.id))150        return (endedA, endedQ, still)151    }152153    /// The work of one background refresh (also what the app's `.backgroundTask` runs).154    static func run(api: VQuantAPI, notifyAnalyses: Bool, notifyQuant: Bool, defaults: UserDefaults = .standard) async {155        let t = tracked(defaults)156        async let g = try? api.generations().generations157        async let q = try? api.quantJobs().jobs158        async let idx = try? api.indices()159        let (generations, jobs, indices) = await (g, q, idx)160        if let generations, let jobs {161            let r = finished(tracked: t, generations: generations, jobs: jobs)162            if notifyAnalyses {163                for a in r.analyses {164                    NotificationCenterBridge.post(id: "analysis-\(a.id)", title: a.status == .done ? "Analyse terminée" : a.status == .cancelled ? "Analyse arrêtée" : "Analyse interrompue",165                                                  body: String(a.query.prefix(140)), url: "vquant://conversation/\(a.sessionId)", category: NotificationCenterBridge.analysisCategory)166                }167            }168            if notifyQuant {169                for j in r.quant {170                    NotificationCenterBridge.post(id: "quant-\(j.id)", title: j.status == .done ? "Calcul terminé" : "Calcul en échec", body: j.tool, url: "vquant://quant/\(j.id)", category: NotificationCenterBridge.quantCategory)171                }172            }173            track(analyses: r.still.analyses, quant: r.still.quant, defaults: defaults)174        }175        // Widgets: only values fetched now replace the snapshot.176        if var snap = WidgetSnapshot.load(from: SharedContainer.snapshotURL), snap.signedIn, let indices {177            snap.indices = indices.prefix(6).map { .init(symbol: $0.symbol, name: $0.name, price: $0.price, changePercent: $0.changePercent) }178            if let generations { snap.jobs = generations.prefix(4).map { .init(id: $0.id, query: $0.query, status: $0.status.rawValue, step: $0.step, startedAt: $0.startedAt) } }179            // The watchlist rows keep their own (older) values, so the snapshot time stays the older one unless there is no watchlist.180            if snap.watchlist.isEmpty { snap.fetchedAt = Date() }181            snap.save(to: SharedContainer.snapshotURL)182            WidgetCenter.shared.reloadAllTimelines()183        }184        schedule(defaults: defaults)185    }186}187188/// Spotlight: watchlist symbols and conversation titles (titles only; no report text, no amounts).189enum Spotlight {190    static let domainAssets = "ai.spboucher.vquant.assets"191    static let domainConversations = "ai.spboucher.vquant.conversations"192193    static func index(watchlist: [WatchlistFile.Entry]) {194        let items = watchlist.map { e -> CSSearchableItem in195            let a = CSSearchableItemAttributeSet(contentType: .content)196            a.title = e.symbol; a.contentDescription = e.name ?? "Actif suivi dans VQuant"; a.keywords = ["VQuant", e.symbol] + (e.name.map { [$0] } ?? [])197            return CSSearchableItem(uniqueIdentifier: "vquant://asset/\(e.symbol)", domainIdentifier: domainAssets, attributeSet: a)198        }199        CSSearchableIndex.default().deleteSearchableItems(withDomainIdentifiers: [domainAssets]) { _ in CSSearchableIndex.default().indexSearchableItems(items) }200    }201202    static func index(conversations: [ConversationSummary]) {203        let items = conversations.prefix(200).map { c -> CSSearchableItem in204            let a = CSSearchableItemAttributeSet(contentType: .content)205            a.title = c.title; a.contentDescription = "Analyse VQuant"; a.contentModificationDate = c.updatedAt206            return CSSearchableItem(uniqueIdentifier: "vquant://conversation/\(c.sessionId)", domainIdentifier: domainConversations, attributeSet: a)207        }208        CSSearchableIndex.default().deleteSearchableItems(withDomainIdentifiers: [domainConversations]) { _ in CSSearchableIndex.default().indexSearchableItems(items) }209    }210211    static let domainProjects = "ai.spboucher.vquant.projects"212    /// Research projects and studies of the account (titles only).213    static func index(projects: [(id: String, title: String, question: String?)], studies: [(id: String, title: String)]) {214        var items = projects.map { p -> CSSearchableItem in215            let a = CSSearchableItemAttributeSet(contentType: .content)216            a.title = p.title; a.contentDescription = p.question ?? "Projet de recherche VQuant"; a.keywords = ["VQuant", "projet"]217            return CSSearchableItem(uniqueIdentifier: "vquant://project/\(p.id)", domainIdentifier: domainProjects, attributeSet: a)218        }219        items += studies.prefix(100).map { s -> CSSearchableItem in220            let a = CSSearchableItemAttributeSet(contentType: .content)221            a.title = s.title; a.contentDescription = "Étude autonome VQuant"; a.keywords = ["VQuant", "étude", "recherche"]222            return CSSearchableItem(uniqueIdentifier: "vquant://research/\(s.id)", domainIdentifier: domainProjects, attributeSet: a)223        }224        let all = items225        CSSearchableIndex.default().deleteSearchableItems(withDomainIdentifiers: [domainProjects]) { _ in CSSearchableIndex.default().indexSearchableItems(all) }226    }227228    static func removeAll() { CSSearchableIndex.default().deleteAllSearchableItems() }229}230
Files main
Menu

Theme