Repository Public
1//2// VQuant iOS3// File: VQuant/App/AppModel.swift4// Description: Composition root: session state, services and stores, application lifecycle, sign-in and sign-out.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation11import Observation12import SwiftUI13import VQuantKit14import WidgetKit1516@MainActor17@Observable18final class AppModel {19 enum SessionState: Equatable {20 case signedOut21 /// A token is on the device; `verified` turns true once the server confirmed it during this launch.22 case signedIn(Account, verified: Bool)23 }2425 let configuration: AppConfiguration26 let client: APIClient27 let api: VQuantAPI28 let cache: DiskCache29 let fetcher: CachedFetcher30 let passkeys: PasskeyService31 let lock: AppLock32 let network = NetworkMonitor()33 let preferences: Preferences34 let router = Router()35 let market: MarketStore36 let research: ResearchStore37 let quant: QuantStore38 let workspace: WorkspaceStore39 let watchlist: WatchlistStore40 /// Everything VQuant Next adds: the kit API of backend 6, the sync centre and the new stores.41 let next: NextServices42 let notifications = NotificationCenterBridge()4344 private(set) var session: SessionState = .signedOut45 private(set) var device: DeviceSession?46 private(set) var isBusy = false47 var authError: String?48 /// Set when the server refused the stored session (revoked from another device, 90 idle days, key rotation).49 var sessionEndedNotice: String?5051 private let tokens: SessionTokenStore52 private let cacheKey = KeychainCacheKey()53 private let defaults: UserDefaults54 private var quoteTask: Task<Void, Never>?5556 init(configuration: AppConfiguration = .current(), defaults: UserDefaults = .standard) {57 self.configuration = configuration58 self.defaults = defaults59 let origin = configuration.baseURL.absoluteString60 if let injected = configuration.injectedToken {61 tokens = MemoryTokenStore(injected) // test runs never touch the Keychain item of the real account62 } else {63 tokens = KeychainTokenStore(origin: origin)64 }65 client = APIClient(baseURL: configuration.baseURL, tokens: tokens, clientTag: AppConfiguration.clientTag)66 api = VQuantAPI(client: client)67 let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("vquant-cache", isDirectory: true)68 cache = DiskCache(directory: dir, keyProvider: configuration.injectedToken == nil ? cacheKey as CacheKeyProvider : FixedCacheKey())69 fetcher = CachedFetcher(cache: cache)70 passkeys = PasskeyService(client: client, relyingParty: configuration.relyingParty)71 preferences = Preferences(defaults: defaults)72 lock = AppLock(defaults: configuration.isUITest ? UserDefaults(suiteName: "vquant.uitest.\(UUID().uuidString)") ?? defaults : defaults)73 market = MarketStore(api: api, fetcher: fetcher)74 research = ResearchStore(api: api, fetcher: fetcher, cache: cache)75 quant = QuantStore(api: api, fetcher: fetcher)76 workspace = WorkspaceStore(api: api, fetcher: fetcher)77 // Test runs use a fixed key and their own replica directory: they never read the real account's replica.78 let syncKeys: CacheKeyProvider = configuration.injectedToken == nil ? cacheKey : FixedCacheKey(Data(repeating: 0x5A, count: 32))79 next = NextServices(client: client, cache: cache, keys: syncKeys, defaults: defaults, isTest: configuration.injectedToken != nil)80 watchlist = WatchlistStore(sync: next.sync, defaults: defaults)81 market.kit = next.vq82 research.kit = next.vq8384 if tokens.load() != nil {85 let name = defaults.string(forKey: "account.name") ?? ""86 let id = defaults.string(forKey: "account.id") ?? ""87 session = .signedIn(Account(id: id, name: name), verified: false)88 if !id.isEmpty { next.sync.start(person: id) } // offline launch: the replica of the last known person89 }90 client.onUnauthorized { [weak self] in Task { @MainActor in self?.sessionRefusedByServer() } }91 research.onRunFinished = { [weak self] run in self?.analysisFinished(run) }92 research.onApproval = { [weak self] a in self?.next.hub.note(a) }93 quant.onJobFinished = { [weak self] job in self?.quantJobFinished(job) }94 next.lab.onJobFinished = { [weak self] job in self?.labJobFinished(job) }95 next.hub.onApprovalRequested = { [weak self] a in self?.approvalRequested(a) }96 next.sync.onHint = { [weak self] hint in self?.serverHint(hint) }97 next.sync.onObjectsChanged = { [weak self] kinds in self?.objectsChanged(kinds) }98 // Installed here, not in a scene: an "Autoriser" / "Refuser" tapped on a notification can start the app in the99 // background, without any window.100 notifications.install()101 notifications.onApprovalDecision = { [weak self] id, approve in102 guard let self else { return }103 _ = await self.next.hub.answer(id, approve ? .approve : .deny)104 self.notifications.clearApproval(id)105 }106 }107108 /// The portfolio shown and valued: the selected synced portfolio (`main` unless the person chose another).109 var positions: [Position] { next.portfolios.positions }110111 var isSignedIn: Bool { if case .signedIn = session { true } else { false } }112 var account: Account? { if case .signedIn(let a, _) = session { a } else { nil } }113114 // MARK: launch and lifecycle115116 /// Confirms the stored session with the server. Offline, the app opens on its device copies and says so.117 func bootstrap() async {118 guard isSignedIn else { return }119 do {120 let s = try await api.session()121 device = s.device122 remember(s.user)123 session = .signedIn(s.user, verified: true)124 next.sync.start(person: s.user.id)125 } catch {126 // 401 is handled by `sessionRefusedByServer`. Any other failure (offline, server down) keeps the session:127 // the next request will settle it.128 }129 await cache.trim()130 }131132 func sceneBecameActive() {133 lock.isObscured = false134 lock.willEnterForeground()135 guard isSignedIn else { return }136 research.becameActive()137 next.lab.startPolling()138 next.sync.becameActive()139 Task { await bootstrapIfUnverified(); await refreshHome() }140 }141142 func sceneResignedActive() { lock.isObscured = true }143144 func sceneEnteredBackground() {145 lock.didEnterBackground()146 stopQuotePolling()147 research.enteredBackground()148 next.lab.stopPolling(); next.hub.stopPolling()149 next.sync.enteredBackground()150 writeWidgetSnapshot()151 BackgroundRefresh.schedule()152 }153154 private func bootstrapIfUnverified() async {155 if case .signedIn(_, verified: false) = session { await bootstrap() }156 }157158 /// Everything the home dashboard shows, fetched concurrently.159 func refreshHome() async {160 guard isSignedIn else { return }161 async let a: Void = market.refreshOverview()162 async let b: Void = market.refreshQuotes(watchlist.symbols)163 async let c: Void = workspace.refresh()164 async let d: Void = research.refreshGenerations()165 async let e: Void = research.refreshConversations()166 async let f: Void = next.lab.refreshJobs()167 async let g: Void = next.terminal.refreshOverview()168 async let h: Void = next.hub.refreshSessions()169 async let i: Void = next.hub.refreshApprovals()170 _ = await (a, b, c, d, e, f, g, h, i)171 await market.refreshQuotes(next.portfolios.allSymbols)172 if !research.running.isEmpty { next.hub.startPolling { [weak self] in !(self?.research.running.isEmpty ?? true) } }173 writeWidgetSnapshot()174 }175176 /// The sync stream said a server-side list changed (another device started or finished something).177 private func serverHint(_ hint: VQSyncHint) {178 guard isSignedIn else { return }179 switch hint.topic.known {180 case .generations: Task { await research.refreshGenerations(); await next.hub.refreshApprovals() }181 case .sessions: Task { await research.refreshConversations(); await next.hub.refreshSessions() }182 case .quantJobs: Task { await next.lab.refreshJobs() }183 case nil: break184 }185 }186187 private func objectsChanged(_ kinds: Set<VQObjectKind>) {188 if kinds.contains(.watchlist) || kinds.contains(.portfolio) {189 Task { await market.refreshQuotes(watchlist.symbols + next.portfolios.allSymbols); writeWidgetSnapshot() }190 }191 if kinds.contains(.preference) { applySyncedPreference() }192 if kinds.contains(.project) { indexResearch() }193 if kinds.contains(.watchlist) { Spotlight.index(watchlist: watchlist.entries) }194 }195196 private func indexResearch() {197 Spotlight.index(projects: next.studio.projects.map { ($0.id, $0.data.title, $0.data.question) },198 studies: (next.hub.sessions.value?.sessions ?? []).map { ($0.id, $0.title ?? "Étude") })199 }200201 /// `preference/default` is the account's; the device follows it for what it shares with the web and the Mac.202 private func applySyncedPreference() {203 guard let p = next.sync.preferences[next.sync.preferenceId]?.data else { return }204 preferences.apply(p)205 }206207 /// Writes the shared preferences of this device to the account (called when the person changes one).208 func pushPreference() {209 let id = next.sync.preferenceId210 var p = next.sync.preferences[id]?.data ?? VQPreference()211 preferences.write(to: &p)212 Task { await next.sync.preferences.save(p, id: id) }213 }214215 /// Refreshes the given quotes on a timer while a market screen is visible. Battery-aware: slower when the market216 /// is closed, on Low Power Mode or on a constrained network; stopped when the app leaves the foreground.217 func startQuotePolling(_ symbols: @escaping @MainActor () -> [String]) {218 stopQuotePolling()219 quoteTask = Task { [weak self] in220 while !Task.isCancelled {221 guard let self else { return }222 var interval = Double(self.preferences.refreshInterval)223 if self.market.usMarketOpen == false { interval = max(interval, 300) }224 if ProcessInfo.processInfo.isLowPowerModeEnabled || self.network.isConstrained { interval = max(interval, 120) }225 if self.network.isExpensive && self.preferences.reduceDataOnCellular { interval = max(interval, 60) }226 try? await Task.sleep(for: .seconds(interval))227 if Task.isCancelled { return }228 guard self.network.isOnline else { continue }229 await self.market.refreshQuotes(symbols())230 }231 }232 }233 func stopQuotePolling() { quoteTask?.cancel(); quoteTask = nil }234235 // MARK: authentication236237 func signIn() async {238 await authenticate { try await self.passkeys.signIn(deviceName: AppConfiguration.deviceName) }239 }240241 /// Accepts a setup link (`https://vquant.spboucher.ai/setup/<token>`) or the bare token.242 func enrol(invitation: String) async {243 guard let token = Self.inviteToken(from: invitation) else { authError = "Ce lien d’invitation n’est pas reconnu."; return }244 await authenticate { try await self.passkeys.enrol(inviteToken: token, deviceName: AppConfiguration.deviceName) }245 }246247 nonisolated static func inviteToken(from text: String) -> String? {248 let t = text.trimmingCharacters(in: .whitespacesAndNewlines)249 let candidate: String250 if let r = t.range(of: "/setup/") { candidate = String(t[r.upperBound...].prefix { $0 != "?" && $0 != "#" && $0 != "/" }) } else { candidate = t }251 let ok = candidate.count >= 32 && candidate.count <= 128 && candidate.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "_" || $0 == "-") }252 return ok ? candidate : nil253 }254255 private func authenticate(_ ceremony: @escaping () async throws -> SignInResult) async {256 guard !isBusy else { return }257 isBusy = true; authError = nil; sessionEndedNotice = nil258 defer { isBusy = false }259 do {260 let result = try await ceremony()261 tokens.save(result.token)262 device = result.device263 remember(result.user)264 session = .signedIn(result.user, verified: true)265 lock.enableByDefaultAfterSignIn()266 next.sync.start(person: result.user.id)267 Haptics.success()268 await refreshHome()269 } catch let e as PasskeyError {270 if e.kind != .cancelled { authError = e.message }271 } catch { authError = APIError.from(error).message }272 }273274 /// Fresh passkey verification, then the sensitive operation. Used for revoking a device or a passkey.275 func withFreshVerification(_ operation: @escaping () async throws -> Void) async throws {276 do { try await operation() }277 catch let e as APIError where e.kind == .reauthRequired {278 try await passkeys.reauthenticate()279 try await operation()280 }281 }282283 /// Signs out: revokes the device session on the server, then erases everything this app stored on the device.284 func signOut() async {285 isBusy = true286 _ = await next.sync.syncNow() // send what is still queued while the session is valid287 try? await api.logout() // offline: the local wipe still happens; the token dies after 90 idle days or by revocation from another device288 wipeLocalData()289 isBusy = false290 }291292 private func sessionRefusedByServer() {293 guard isSignedIn else { return }294 wipeLocalData()295 sessionEndedNotice = "Cette session n’est plus valide (révoquée ou expirée). Connectez-vous de nouveau avec votre clé d’accès."296 }297298 private func wipeLocalData() {299 tokens.clear()300 stopQuotePolling()301 research.reset(); quant.reset(); workspace.reset(); market.reset()302 next.reset()303 let cache = self.cache304 Task { await cache.removeAll() }305 cacheKey.destroy()306 defaults.removeObject(forKey: "account.name"); defaults.removeObject(forKey: "account.id")307 defaults.removeObject(forKey: BackgroundRefresh.trackedKey)308 lock.reset()309 device = nil310 session = .signedOut311 router.paths = [:]; router.section = .home312 WidgetSnapshot(fetchedAt: Date(), signedIn: false).save(to: SharedContainer.snapshotURL)313 WidgetCenter.shared.reloadAllTimelines()314 Spotlight.removeAll()315 }316317 private func remember(_ a: Account) {318 defaults.set(a.name, forKey: "account.name"); defaults.set(a.id, forKey: "account.id")319 }320321 // MARK: completion events322323 private func analysisFinished(_ run: AnalysisRun) {324 guard preferences.notifyAnalyses else { return }325 notifications.notifyAnalysis(jobId: run.jobId, sessionId: run.sessionId, query: run.query, failed: run.error != nil)326 }327 private func quantJobFinished(_ job: QuantJob) {328 guard preferences.notifyQuant else { return }329 notifications.notifyQuant(job: job, title: quant.tool(job.tool)?.title ?? job.tool)330 }331 private func labJobFinished(_ job: VQQuantJob) {332 guard preferences.notifyQuant else { return }333 notifications.notifyLab(job: job, title: next.lab.title(job.tool))334 }335 private func approvalRequested(_ approval: VQResearchApproval) {336 notifications.notifyApproval(approval)337 }338339 // MARK: widgets340341 /// Leaves the latest real values for the widgets, with the time they were fetched.342 func writeWidgetSnapshot() {343 guard isSignedIn else { return }344 func row(_ q: Quote) -> WidgetSnapshot.Row { .init(symbol: q.symbol, name: q.name, price: q.price, changePercent: q.changePercent) }345 var snap = WidgetSnapshot(fetchedAt: Date())346 snap.indices = (market.indices.value ?? []).prefix(6).map(row)347 snap.watchlist = watchlist.symbols.compactMap { market.quotes[$0]?.value }.prefix(8).map(row)348 snap.jobs = (research.generations.value ?? []).prefix(4).map { .init(id: $0.id, query: $0.query, status: $0.status.rawValue, step: $0.step, startedAt: $0.startedAt) }349 snap.research = next.hub.sessions.value?.sessions.prefix(3).map { .init(id: $0.id, title: $0.title ?? "Étude", updatedAt: $0.updatedAt ?? Date()) } ?? []350 snap.watchlistName = watchlist.active?.data.name351 snap.pendingApprovals = next.hub.pending.count352 let lines = PortfolioMath.lines(positions: positions, quotes: market.quotes.mapValues(\.value))353 if !lines.isEmpty, !preferences.hideAmountsInWidgets {354 let t = PortfolioMath.totals(lines)355 snap.portfolioValue = t.value; snap.portfolioDayPercent = t.dayGainPercent.map { $0 * 100 }356 }357 // The snapshot's own time is the oldest fetch among what it contains: a widget must not look fresher than its data.358 let times = [market.indices.loaded?.fetchedAt] + watchlist.symbols.map { market.quotes[$0]?.fetchedAt }359 if let oldest = times.compactMap({ $0 }).min() { snap.fetchedAt = oldest }360 snap.save(to: SharedContainer.snapshotURL)361 WidgetCenter.shared.reloadAllTimelines()362 BackgroundRefresh.track(analyses: research.running.map(\.id), quant: next.lab.running.map(\.id), defaults: defaults)363 }364}365