Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/AppEnvironment.swift3// Description: Dependency container of the app: server, API client, auth, cache and stores. Built once at launch and passed explicitly to every window.4import CryptoKit5import Network6import SwiftUI7import VQuantCore8import VQuantKit9import VQuantUI1011/// What the process was asked to do at launch. Overrides exist for development and automated checks only: a12/// non-production server must be a loopback address, and a session can be injected only in DEBUG builds.13struct LaunchOptions {14 var server = URL(string: "https://vquant.spboucher.ai")!15 var injectedToken: String?16 var inMemory = false17 var section: String?18 var symbol: String?19 /// DEBUG only: a computation or a conversation opened at launch (visual checks).20 var job: String?21 var conversation: String?22 /// DEBUG only: a question sent automatically in a new conversation (end-to-end check of the live view without synthetic input).23 var ask: String?24 var isUITest = false25 /// DEBUG only: writes a PNG of each section to this directory, then quits (visual evidence without synthetic input).26 var tourDirectory: URL?27 // DEBUG only, VQuant Next: what a window opens on (visual checks and UI tests reach every destination with these).28 var theme: String? // -VQTheme light|dark29 var tab: String? // -VQTab <name>: the sub-tab or mode of the section (each section documents its values)30 var project: String? // -VQProject <id>31 var portfolio: String? // -VQPortfolio <id>32 var tool: String? // -VQTool <engine id>33 var workspaceId: String? // -VQWorkspace <research workspace id>34 var palette = false // -VQPalette: the command palette is open at launch35 var paletteQuery: String? // -VQPaletteQuery <text>36 var settingsPane: String? // -VQSettings <pane>: opens the Settings window on that pane37 var extra: [String: String] = [:] // any other -VQX<Name> <value>, read with options.extra["Name"]3839 static func current(arguments: [String] = ProcessInfo.processInfo.arguments, environment: [String: String] = ProcessInfo.processInfo.environment) -> LaunchOptions {40 var o = LaunchOptions()41 #if DEBUG42 func value(_ flag: String) -> String? { arguments.firstIndex(of: flag).flatMap { arguments.indices.contains($0 + 1) ? arguments[$0 + 1] : nil } }43 if let s = value("-VQServer") ?? environment["VQ_SERVER"], let url = URL(string: s), ["localhost", "127.0.0.1"].contains(url.host ?? "") { o.server = url }44 if let t = environment["VQ_DEV_TOKEN"], t.hasPrefix("vqn_") { o.injectedToken = t }45 o.inMemory = arguments.contains("-VQInMemory") || o.injectedToken != nil46 o.section = value("-VQSection"); o.symbol = value("-VQSymbol"); o.job = value("-VQJob"); o.conversation = value("-VQConversation"); o.ask = value("-VQAsk")47 o.isUITest = arguments.contains("-VQUITest")48 o.theme = value("-VQTheme"); o.tab = value("-VQTab"); o.project = value("-VQProject"); o.portfolio = value("-VQPortfolio"); o.tool = value("-VQTool")49 o.workspaceId = value("-VQWorkspace"); o.palette = arguments.contains("-VQPalette"); o.paletteQuery = value("-VQPaletteQuery"); o.settingsPane = value("-VQSettings")50 for (i, a) in arguments.enumerated() where a.hasPrefix("-VQX") && arguments.indices.contains(i + 1) { o.extra[String(a.dropFirst(4))] = arguments[i + 1] }51 if let d = value("-VQTour") { o.tourDirectory = URL(fileURLWithPath: (d as NSString).expandingTildeInPath, isDirectory: true) }52 #endif53 return o54 }55}5657/// Network reachability (NWPathMonitor). Used to explain failures and to pause polling, never to block a request.58@Observable final class Connectivity {59 private(set) var isOnline = true60 @ObservationIgnored private let monitor = NWPathMonitor()6162 init() {63 monitor.pathUpdateHandler = { [weak self] path in64 let online = path.status == .satisfied65 Task { @MainActor in if self?.isOnline != online { self?.isOnline = online } }66 }67 monitor.start(queue: DispatchQueue(label: "ai.spboucher.vquant.connectivity"))68 }69 deinit { monitor.cancel() }70}7172@Observable final class AppEnvironment {73 let options: LaunchOptions74 let api: VQuantAPI75 let auth: AuthService76 let cache: DiskCache77 let tokens: TokenStore78 let connectivity = Connectivity()79 let settings: SettingsStore80 let session: SessionStore81 let market: MarketStore82 let watchlists: WatchlistStore83 let workspace: WorkspaceStore84 let research: ResearchStore85 let quant: QuantStore86 let layouts: LayoutStore87 let toasts = ToastCenter()88 let images: ImageLoader89 /// VQuant Next (backend 6): the shared kit's clients over the same session, and the sync engine's owner.90 let vq: VQNextAPI91 let sync: SyncStore92 /// Stores of the 2.0 features, created on first use (see `store(_:)`), reset at sign-out.93 @ObservationIgnored private var featureStores: [ObjectIdentifier: AnyObject] = [:]9495 static let bundleService = Bundle.main.bundleIdentifier ?? "ai.spboucher.vquant"9697 init(options: LaunchOptions = .current()) {98 self.options = options99 let info = Bundle.main.infoDictionary ?? [:]100 let identity = ClientIdentity(version: info["CFBundleShortVersionString"] as? String ?? "2.0.0", build: info["CFBundleVersion"] as? String ?? "1",101 deviceName: Host.current().localizedName ?? "Mac")102 let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("VQuant", isDirectory: true)103 let host = options.server.host ?? "server"104105 let tokens: TokenStore106 let cache: DiskCache107 let localDir: URL108 if options.inMemory {109 // development checks: nothing is read from or written to the Keychain or the person's real cache110 tokens = MemoryTokenStore(options.injectedToken)111 let tmp = FileManager.default.temporaryDirectory.appendingPathComponent("vquant-dev-\(ProcessInfo.processInfo.processIdentifier)", isDirectory: true)112 cache = try! DiskCache(directory: tmp.appendingPathComponent("cache"), key: SymmetricKey(size: .bits256))113 localDir = tmp114 } else {115 tokens = KeychainTokenStore(service: Self.bundleService + ".session", account: host, requireUserPresence: UserDefaults.standard.bool(forKey: "appLock"))116 cache = try! DiskCache(directory: support.appendingPathComponent("cache-\(host)", isDirectory: true), key: DiskCache.keychainKey(service: Self.bundleService + ".cache"))117 localDir = support118 }119 self.tokens = tokens; self.cache = cache120 let http = URLSessionTransport()121 let client = APIClient(baseURL: options.server, identity: identity, tokens: tokens, transport: http)122 let api = VQuantAPI(client: client)123 self.api = api124 auth = AuthService(api: client, authenticator: SystemPasskeyAuthenticator())125 let settings = SettingsStore(defaults: options.inMemory ? UserDefaults(suiteName: "vquant-dev-\(ProcessInfo.processInfo.processIdentifier)")! : .standard)126 if let t = options.theme.flatMap(AppTheme.init(rawValue:)) { settings.theme = t; settings.themeOverridden = true }127 self.settings = settings128 session = SessionStore(auth: auth, tokens: tokens, cache: cache, settings: settings)129 market = MarketStore(api: api, cache: cache, settings: settings)130 watchlists = WatchlistStore(file: JSONFile(url: localDir.appendingPathComponent("watchlists.json")))131 workspace = WorkspaceStore(api: api, cache: cache)132 research = ResearchStore(api: api, cache: cache, settings: settings)133 quant = QuantStore(api: api, cache: cache, settings: settings)134 layouts = LayoutStore(file: JSONFile(url: localDir.appendingPathComponent("workspaces.json")))135 images = ImageLoader(api: api, cache: cache)136137 let session = session138 client.onUnauthorized { Task { @MainActor in session.serverEndedSession() } }139 let vq = VQNextAPI(transport: MacVQTransport(client: client, http: http, onUnauthorized: { Task { @MainActor in session.serverEndedSession() } }))140 self.vq = vq141 sync = SyncStore(client: vq.client, cache: cache, root: localDir.appendingPathComponent("sync-\(host)", isDirectory: true), inMemory: options.inMemory,142 defaults: settings.defaults, settings: settings, localWatchlists: JSONFile(url: localDir.appendingPathComponent("watchlists.json")), layouts: layouts)143 market.connectivity = connectivity144 research.toasts = toasts; quant.toasts = toasts; research.vq = vq145 }146147 /// Everything a signed-in window needs, loaded once after sign-in and refreshed by the stores themselves.148 func start() {149 if let person = session.account?.id { sync.start(person: person) }150 sync.onHint = { [unowned self] hint in151 // another device (or the server) changed something that is not an object: refresh that list now152 switch hint.topic.known {153 case .sessions?: Task { await self.research.refreshSessions() }154 case .generations?: Task { await self.research.refreshGenerations() }155 case .quantJobs?: Task { await self.quant.refresh() }156 case nil: break157 }158 self.hintObservers.forEach { $0(hint) }159 }160 market.start()161 Task { await workspace.refresh() }162 Task { await research.refreshSessions() }163 research.startPolling(); quant.startPolling()164 }165166 /// Sign-out or lock: polling stops and nothing of the previous person stays in memory.167 func stop(clearCache: Bool) {168 market.stop(); research.stopPolling(); quant.stopPolling()169 workspace.reset(); research.reset(); quant.reset(); market.reset(); images.reset()170 sync.stop(erase: clearCache)171 for s in featureStores.values { (s as? SessionScoped)?.reset() }172 if clearCache { cache.removeAll() }173 }174175 // MARK: feature stores (VQuant Next)176177 /// The single instance of a feature store, created the first time a view asks for it:178 /// `extension AppEnvironment { var lab: LabStore { store { LabStore(app: self) } } }`.179 /// A store that conforms to `SessionScoped` is emptied at sign-out and lock.180 func store<S: AnyObject>(_ make: () -> S) -> S {181 let key = ObjectIdentifier(S.self)182 if let s = featureStores[key] as? S { return s }183 let s = make(); featureStores[key] = s184 return s185 }186187 /// Feature stores register here to hear the sync stream's hints (sessions, generations, quant_jobs).188 @ObservationIgnored var hintObservers: [(VQSyncHint) -> Void] = []189}190191/// A feature store that holds a person's data: emptied at sign-out and lock.192protocol SessionScoped: AnyObject { func reset() }193194extension AppEnvironment {195 /// The theme VQuantUI components read (`.vqTheme(app.vqTheme)`): up/down pair, number format, reduce motion.196 var vqTheme: VQTheme {197 var t = sync.active?.theme ?? VQTheme()198 t.upDown = settings.upDownPair199 t.language = .en // the interface of this app is in English; the kit's built-in vocabulary follows200 return t201 }202}203