Repository Public
1//2// VQuant iOS3// File: VQuant/Platform/Intents.swift4// Description: App Intents for Siri, Shortcuts and Spotlight: open an asset, the watchlist or the research workspace,5// and check the state of server jobs. No intent changes account data or starts paid work.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import AppIntents12import Foundation13import VQuantKit1415/// Lets intents reach the running app's model.16@MainActor17final class AppIntentsBridge {18 static let shared = AppIntentsBridge()19 weak var model: AppModel?20 /// A destination requested before the scene was ready.21 var pending: URL?2223 func open(_ url: URL) {24 if let model { model.router.handle(url, compact: UIDevice.current.userInterfaceIdiom == .phone) } else { pending = url }25 }26}2728import UIKit2930struct OpenAssetIntent: AppIntent {31 static let title: LocalizedStringResource = "Voir un actif"32 static let description = IntentDescription("Ouvre la fiche d’un actif dans VQuant.")33 static let openAppWhenRun = true3435 @Parameter(title: "Symbole", description: "Par exemple AAPL ou ^GSPC")36 var symbol: String3738 static var parameterSummary: some ParameterSummary { Summary("Voir \(\.$symbol) dans VQuant") }3940 @MainActor41 func perform() async throws -> some IntentResult {42 guard let s = WatchlistFile.normalise(symbol), let url = URL(string: "vquant://asset/\(s.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? s)") else {43 throw $symbol.needsValueError("Quel symbole ?")44 }45 AppIntentsBridge.shared.open(url)46 return .result()47 }48}4950struct OpenWatchlistIntent: AppIntent {51 static let title: LocalizedStringResource = "Ouvrir la liste de suivi"52 static let description = IntentDescription("Ouvre les marchés et la liste de suivi de VQuant.")53 static let openAppWhenRun = true54 @MainActor func perform() async throws -> some IntentResult {55 AppIntentsBridge.shared.open(URL(string: "vquant://markets")!)56 return .result()57 }58}5960struct OpenResearchIntent: AppIntent {61 static let title: LocalizedStringResource = "Ouvrir la recherche"62 static let description = IntentDescription("Ouvre l’espace de recherche de VQuant.")63 static let openAppWhenRun = true64 @MainActor func perform() async throws -> some IntentResult {65 AppIntentsBridge.shared.open(URL(string: "vquant://research")!)66 return .result()67 }68}6970/// Reads the state of the server jobs and says it. Counts and statuses only: no report text and no amounts are71/// spoken or shown outside the app.72struct CheckJobsIntent: AppIntent {73 static let title: LocalizedStringResource = "État des calculs"74 static let description = IntentDescription("Indique combien d’analyses et de calculs VQuant sont en cours ou terminés sur le serveur.")75 static let openAppWhenRun = false7677 func perform() async throws -> some IntentResult & ProvidesDialog {78 let config = AppConfiguration.current()79 let tokens = KeychainTokenStore(origin: config.baseURL.absoluteString)80 guard tokens.load() != nil else { return .result(dialog: "Ouvrez VQuant pour vous connecter.") }81 let api = VQuantAPI(client: APIClient(baseURL: config.baseURL, tokens: tokens, clientTag: AppConfiguration.clientTag))82 do {83 async let g = api.generations()84 async let q = api.quantJobs()85 let (gen, jobs) = try await (g, q)86 return .result(dialog: IntentDialog(stringLiteral: Self.sentence(generations: gen.generations, jobs: jobs.jobs)))87 } catch {88 let e = APIError.from(error)89 return .result(dialog: IntentDialog(stringLiteral: e.kind == .unauthorized ? "La session a expiré. Ouvrez VQuant pour vous reconnecter." : "Le serveur VQuant est injoignable pour le moment."))90 }91 }9293 /// The spoken summary, built only from what the server returned.94 static func sentence(generations: [Generation], jobs: [QuantJob], now: Date = Date()) -> String {95 let ra = generations.filter { $0.status == .running }.count, rq = jobs.filter { $0.status == .running }.count96 let day = now.addingTimeInterval(-86_400)97 let da = generations.filter { $0.status == .done && ($0.finishedAt ?? .distantPast) > day }.count98 let dq = jobs.filter { $0.status == .done && ($0.finished ?? .distantPast) > day }.count99 let failed = generations.filter { $0.status == .error && ($0.finishedAt ?? .distantPast) > day }.count + jobs.filter { ($0.status == .error || $0.status == .interrupted) && ($0.finished ?? .distantPast) > day }.count100 func n(_ c: Int, _ one: String, _ many: String) -> String { c == 1 ? "1 \(one)" : "\(c) \(many)" }101 var parts: [String] = []102 if ra + rq == 0 { parts.append("Rien n’est en cours sur le serveur") } else {103 parts.append("En cours : " + [ra > 0 ? n(ra, "analyse", "analyses") : nil, rq > 0 ? n(rq, "calcul", "calculs") : nil].compactMap { $0 }.joined(separator: " et "))104 }105 if da + dq > 0 { parts.append("terminés depuis 24 heures : " + [da > 0 ? n(da, "analyse", "analyses") : nil, dq > 0 ? n(dq, "calcul", "calculs") : nil].compactMap { $0 }.joined(separator: " et ")) }106 if failed > 0 { parts.append(n(failed, "tâche en échec", "tâches en échec")) }107 return parts.joined(separator: " ; ") + "."108 }109}110111/// "Lance une recherche" — opens the composer in research mode with the question. The study itself is started by112/// the person in the app (model, budget and dataset are chosen there): Siri never spends on its own.113struct StartResearchIntent: AppIntent {114 static let title: LocalizedStringResource = "Lancer une recherche"115 static let description = IntentDescription("Ouvre VQuant sur une nouvelle recherche autonome avec votre question.")116 static let openAppWhenRun = true117118 @Parameter(title: "Question", description: "Ce que l’agent doit étudier")119 var question: String120121 static var parameterSummary: some ParameterSummary { Summary("Rechercher \(\.$question) avec VQuant") }122123 @MainActor124 func perform() async throws -> some IntentResult {125 var c = URLComponents(); c.scheme = "vquant"; c.host = "ask"; c.queryItems = [URLQueryItem(name: "q", value: String(question.prefix(4000)))]126 if let url = c.url { AppIntentsBridge.shared.open(url) }127 return .result()128 }129}130131/// "Cours de …" — answers with the quote the server returns now (provider and time said), without opening the app.132struct QuoteIntent: AppIntent {133 static let title: LocalizedStringResource = "Cours d’un actif"134 static let description = IntentDescription("Donne le dernier cours d’un actif tel que le serveur VQuant le relève, avec sa source et son heure.")135 static let openAppWhenRun = false136137 @Parameter(title: "Symbole", description: "Par exemple AAPL ou ^GSPC")138 var symbol: String139140 static var parameterSummary: some ParameterSummary { Summary("Cours de \(\.$symbol)") }141142 func perform() async throws -> some IntentResult & ProvidesDialog {143 guard let s = WatchlistFile.normalise(symbol) else { throw $symbol.needsValueError("Quel symbole ?") }144 let config = AppConfiguration.current()145 let tokens = KeychainTokenStore(origin: config.baseURL.absoluteString)146 guard tokens.load() != nil else { return .result(dialog: "Ouvrez VQuant pour vous connecter.") }147 let kit = KitAPI(transport: IOSVQTransport(client: APIClient(baseURL: config.baseURL, tokens: tokens, clientTag: AppConfiguration.clientTag)))148 do {149 let r = try await kit.data.quotes([s])150 guard let q = r[s], let price = q.price else { return .result(dialog: IntentDialog(stringLiteral: "Le serveur ne fournit aucune cotation pour \(s).")) }151 return .result(dialog: IntentDialog(stringLiteral: Self.sentence(q, price: price, freshness: r.freshness)))152 } catch {153 let e = error as? VQError154 return .result(dialog: IntentDialog(stringLiteral: e?.isLocked == true ? "La session a expiré. Ouvrez VQuant pour vous reconnecter." : "Le serveur VQuant est injoignable pour le moment."))155 }156 }157158 /// Built only from what the server returned; says the freshness in the contract's words (never "en direct").159 static func sentence(_ q: VQQuote, price: Double, freshness: VQFreshness?) -> String {160 var parts = ["\(q.name ?? q.symbol) : \(VQFormat.number(price, decimals: 2))" + (q.currency.map { " \($0)" } ?? "")]161 if let c = q.changePct { parts.append("\(c >= 0 ? "en hausse" : "en baisse") de \(VQFormat.number(abs(c), decimals: 2)) %") }162 let kind = (q.freshness?.known ?? freshness?.kind.known)?.label(.fr).lowercased()163 let source = [kind.map { "cours \($0)" }, VQFreshness.providerName(q.provider ?? freshness?.provider).map { "source \($0)" }, q.providerTimestamp.map { "à \(VQFormat.time($0, language: .fr))" }].compactMap { $0 }.joined(separator: ", ")164 return parts.joined(separator: ", ") + (source.isEmpty ? "." : " (\(source)).")165 }166}167168/// A research project of the account, for "Ouvrir un projet". Read from the synced replica (works offline).169struct ProjectEntity: AppEntity {170 static let typeDisplayRepresentation: TypeDisplayRepresentation = "Projet de recherche"171 static let defaultQuery = ProjectQuery()172 var id: String173 var title: String174 var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(title)") }175}176177struct ProjectQuery: EntityQuery {178 @MainActor private func all() -> [ProjectEntity] {179 (AppIntentsBridge.shared.model?.next.studio.projects ?? []).map { ProjectEntity(id: $0.id, title: $0.data.title) }180 }181 @MainActor func entities(for identifiers: [String]) async throws -> [ProjectEntity] { all().filter { identifiers.contains($0.id) } }182 @MainActor func suggestedEntities() async throws -> [ProjectEntity] { all() }183}184185struct OpenProjectIntent: AppIntent {186 static let title: LocalizedStringResource = "Ouvrir un projet"187 static let description = IntentDescription("Ouvre un projet du Research Studio dans VQuant.")188 static let openAppWhenRun = true189190 @Parameter(title: "Projet")191 var project: ProjectEntity192193 static var parameterSummary: some ParameterSummary { Summary("Ouvrir \(\.$project)") }194195 @MainActor196 func perform() async throws -> some IntentResult {197 if let url = URL(string: "vquant://project/\(project.id)") { AppIntentsBridge.shared.open(url) }198 return .result()199 }200}201202struct VQuantShortcuts: AppShortcutsProvider {203 static var appShortcuts: [AppShortcut] {204 AppShortcut(intent: StartResearchIntent(), phrases: ["Lance une recherche \(.applicationName)", "Nouvelle recherche \(.applicationName)"], shortTitle: "Nouvelle recherche", systemImageName: "sparkles")205 AppShortcut(intent: QuoteIntent(), phrases: ["Cours d’un actif \(.applicationName)", "Donne-moi un cours \(.applicationName)"], shortTitle: "Cours", systemImageName: "dollarsign.circle")206 AppShortcut(intent: OpenProjectIntent(), phrases: ["Ouvre un projet \(.applicationName)"], shortTitle: "Projet", systemImageName: "books.vertical")207 AppShortcut(intent: CheckJobsIntent(), phrases: ["État des calculs \(.applicationName)", "Où en sont mes analyses \(.applicationName)"], shortTitle: "État des calculs", systemImageName: "server.rack")208 AppShortcut(intent: OpenWatchlistIntent(), phrases: ["Ouvre ma liste de suivi \(.applicationName)"], shortTitle: "Liste de suivi", systemImageName: "star")209 AppShortcut(intent: OpenResearchIntent(), phrases: ["Ouvre la recherche \(.applicationName)"], shortTitle: "Recherche", systemImageName: "sparkles")210 AppShortcut(intent: OpenAssetIntent(), phrases: ["Voir un actif dans \(.applicationName)"], shortTitle: "Voir un actif", systemImageName: "chart.xyaxis.line")211 }212}213