SPB Git

Repository Public

AppSupport.swift 18.0 KB 341 lines swift

1//2//  VQuant iOS3//  File: VQuant/App/AppSupport.swift4//  Description: Configuration of the backend origin, network reachability, user preferences and navigation state.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import Foundation11import Network12import Observation13import SwiftUI14import UIKit15import VQuantKit16import VQuantUI1718/// Where the app talks to. Release builds always use the origin written in Info.plist (HTTPS). Debug builds accept19/// an override through the launch environment so tests can target a development copy of the backend.20struct AppConfiguration: Sendable {21    var baseURL: URL22    var relyingParty: String23    /// A device token injected by the test runner (debug builds only).24    var injectedToken: String?25    var isUITest = false26    /// A `vquant://` destination to open at launch (debug builds: screenshots and UI tests).27    var initialURL: URL?2829    static func current() -> AppConfiguration {30        let plist = (Bundle.main.object(forInfoDictionaryKey: "VQuantBaseURL") as? String).flatMap(URL.init(string:)) ?? URL(string: "https://vquant.spboucher.ai")!31        var c = AppConfiguration(baseURL: plist, relyingParty: "vquant.spboucher.ai")32        #if DEBUG33        let env = ProcessInfo.processInfo.environment34        if let s = env["VQUANT_BASE_URL"], let u = URL(string: s) { c.baseURL = u }35        c.injectedToken = env["VQUANT_TEST_TOKEN"]36        c.isUITest = env["VQUANT_UITEST"] == "1"37        c.initialURL = env["VQUANT_OPEN_URL"].flatMap(URL.init(string:))38        #endif39        return c40    }4142    static var appVersion: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "2.0.0" }43    static var build: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "2" }44    /// `vquant-ios/2.0.0 (2)` — the server derives the platform and the device label from it; a 2.x header unlocks45    /// the lab engines and the new job statuses (CONTRACT §4.1).46    static var clientTag: String { "vquant-ios/\(appVersion) (\(build))" }47    @MainActor static var deviceName: String { UIDevice.current.userInterfaceIdiom == .pad ? "iPad" : "iPhone" }48}4950/// Reachability from NWPathMonitor. The app never guesses that it is online: requests fail fast and say so.51@MainActor52@Observable53final class NetworkMonitor {54    private(set) var isOnline = true55    private(set) var isExpensive = false56    private(set) var isConstrained = false57    private let monitor = NWPathMonitor()5859    init() {60        monitor.pathUpdateHandler = { [weak self] path in61            let online = path.status == .satisfied, expensive = path.isExpensive, constrained = path.isConstrained62            Task { @MainActor in63                self?.isOnline = online; self?.isExpensive = expensive; self?.isConstrained = constrained64            }65        }66        monitor.start(queue: DispatchQueue(label: "ai.spboucher.vquant.network"))67    }68}6970/// Preferences stored on the device (UserDefaults). Nothing here is a secret.71@MainActor72@Observable73final class Preferences {74    enum Appearance: String, CaseIterable, Identifiable {75        case system, light, dark76        var id: String { rawValue }77        var label: String { switch self { case .system: "Système"; case .light: "Clair"; case .dark: "Sombre" } }78        var scheme: ColorScheme? { switch self { case .system: nil; case .light: .light; case .dark: .dark } }79    }80    private let d: UserDefaults8182    var appearance: Appearance { didSet { d.set(appearance.rawValue, forKey: "pref.appearance") } }83    var chartConfiguration: ChartConfiguration { didSet { if let data = try? JSONEncoder().encode(chartConfiguration) { d.set(data, forKey: "pref.chart") } } }84    var chartRange: ChartRange { didSet { d.set(chartRange.rawValue, forKey: "pref.range") } }85    /// Seconds between quote refreshes while a market screen is visible and the market is open.86    var refreshInterval: Int { didSet { d.set(refreshInterval, forKey: "pref.refresh") } }87    var reduceDataOnCellular: Bool { didSet { d.set(reduceDataOnCellular, forKey: "pref.cellular") } }88    var defaultMode: AnalysisMode { didSet { d.set(defaultMode.rawValue, forKey: "pref.mode") } }89    var notifyAnalyses: Bool { didSet { d.set(notifyAnalyses, forKey: "pref.notify.analyses") } }90    var notifyQuant: Bool { didSet { d.set(notifyQuant, forKey: "pref.notify.quant") } }91    /// Hides amounts in the widgets and covers the app in the app switcher.92    var hideAmountsInWidgets: Bool { didSet { d.set(hideAmountsInWidgets, forKey: "pref.privacy.widgets") } }93    var keepOfflineCopies: Bool { didSet { d.set(keepOfflineCopies, forKey: "pref.offline") } }94    var hapticsEnabled: Bool { didSet { d.set(hapticsEnabled, forKey: "pref.haptics") } }95    // Shared with the web and the Mac through `preference/default` (see `apply` / `write`).96    /// Model asked for by default: `auto` (the server's router decides), a model id, or empty = the server's default.97    var defaultModel: String { didSet { d.set(defaultModel, forKey: "pref.model") } }98    /// Limits of one research study (nil = none on this side; the server keeps its own).99    var budgetCostUsd: Double? { didSet { d.set(budgetCostUsd, forKey: "pref.budget.cost") } }100    var budgetMinutes: Double? { didSet { d.set(budgetMinutes, forKey: "pref.budget.minutes") } }101    /// Blue / orange instead of green / red for gains and losses (colour-vision-safe pair of the design system).102    var colourVisionSafe: Bool { didSet { d.set(colourVisionSafe, forKey: "pref.cvd") } }103104    /// What the kit's components read from the environment.105    var theme: VQTheme { VQTheme(upDown: colourVisionSafe ? .cvd : .classic, numberLocale: .frCA, language: .fr, reduceMotion: UIAccessibility.isReduceMotionEnabled) }106107    /// The account's preference object wins for the keys it carries; keys it does not have keep the device's value.108    /// Light / dark appearance is a per-device choice: `preference.theme` is neither applied nor written here.109    func apply(_ p: VQPreference) {110        if let m = p.defaultMode.flatMap(AnalysisMode.init(rawValue:)), m != defaultMode { defaultMode = m }111        if let m = p.defaultModel, m != defaultModel { defaultModel = m }112        if let c = p.upDownColors { let cvd = c == .cvd; if cvd != colourVisionSafe { colourVisionSafe = cvd } }113        if let b = p.budget {114            if b.maxCostUsd != budgetCostUsd { budgetCostUsd = b.maxCostUsd }115            if b.maxMinutes != budgetMinutes { budgetMinutes = b.maxMinutes }116        }117    }118    /// Writes this device's shared choices into the preference object (unknown keys of the object are kept).119    func write(to p: inout VQPreference) {120        p.defaultMode = defaultMode.rawValue121        p.defaultModel = defaultModel.isEmpty ? nil : defaultModel122        p.upDownColors = .known(colourVisionSafe ? .cvd : .classic)123        if budgetCostUsd != nil || budgetMinutes != nil || p.budget != nil { p.budget = VQPreference.Budget(maxCostUsd: budgetCostUsd, maxMinutes: budgetMinutes) }124    }125126    init(defaults d: UserDefaults = .standard) {127        self.d = d128        appearance = Appearance(rawValue: d.string(forKey: "pref.appearance") ?? "") ?? .system129        chartConfiguration = (d.data(forKey: "pref.chart").flatMap { try? JSONDecoder().decode(ChartConfiguration.self, from: $0) }) ?? ChartConfiguration()130        chartRange = ChartRange(rawValue: d.string(forKey: "pref.range") ?? "") ?? .quarter131        refreshInterval = d.object(forKey: "pref.refresh") as? Int ?? 30132        reduceDataOnCellular = d.object(forKey: "pref.cellular") as? Bool ?? true133        defaultMode = AnalysisMode(rawValue: d.string(forKey: "pref.mode") ?? "") ?? .standard134        notifyAnalyses = d.object(forKey: "pref.notify.analyses") as? Bool ?? true135        notifyQuant = d.object(forKey: "pref.notify.quant") as? Bool ?? true136        hideAmountsInWidgets = d.object(forKey: "pref.privacy.widgets") as? Bool ?? true137        keepOfflineCopies = d.object(forKey: "pref.offline") as? Bool ?? true138        hapticsEnabled = d.object(forKey: "pref.haptics") as? Bool ?? true139        defaultModel = d.string(forKey: "pref.model") ?? ""140        budgetCostUsd = d.object(forKey: "pref.budget.cost") as? Double141        budgetMinutes = d.object(forKey: "pref.budget.minutes") as? Double142        colourVisionSafe = d.object(forKey: "pref.cvd") as? Bool ?? false143    }144}145146/// Sections of the app: the five tabs of the iPhone, and the sidebar of the iPad.147enum AppSection: String, CaseIterable, Identifiable, Hashable, Codable {148    case home, markets, research, portfolio, more149    // iPad sidebar only (on the iPhone they are destinations of the "Plus" tab)150    case quant, studio, workspaces, agent, library, settings151    var id: String { rawValue }152153    static let phoneTabs: [AppSection] = [.home, .markets, .research, .portfolio, .more]154    /// In the order of the sidebar; ⌘1…⌘9 and ⌘0 follow this order.155    static let padSidebar: [AppSection] = [.home, .research, .markets, .quant, .portfolio, .studio, .workspaces, .agent, .library, .settings]156157    var title: String {158        switch self {159        case .home: "Accueil"; case .markets: "Marchés"; case .research: "Recherche"; case .portfolio: "Portefeuilles"; case .more: "Plus"160        case .quant: "Quant Lab"; case .studio: "Studio"; case .workspaces: "Espaces de travail"; case .agent: "Agent"; case .library: "Bibliothèque"; case .settings: "Réglages"161        }162    }163    var systemImage: String {164        switch self {165        case .home: "house"; case .markets: "chart.xyaxis.line"; case .research: "sparkles"; case .portfolio: "briefcase"; case .more: "ellipsis.circle"166        case .quant: "function"; case .studio: "books.vertical"; case .workspaces: "rectangle.split.3x1"; case .agent: "brain"; case .library: "tray.full"; case .settings: "gearshape"167        }168    }169    /// iPad: sections laid out in three columns (sidebar, list, detail). The others use two.170    var hasListColumn: Bool {171        switch self { case .research, .markets, .quant, .portfolio, .studio, .workspaces, .library: true; default: false }172    }173}174175/// A destination pushed on a navigation stack (or shown in the detail column, or in its own window on the iPad).176enum Route: Hashable, Codable {177    case asset(String)178    case conversation(String)179    case run(String)                      // a live analysis or research study, by generation id180    case quantTool(String)                // `toolId` or `toolId|SYMBOL[,SYMBOL]`181    case quantJob(String)182    case sharedReport(String)183    case quant, agent, library, settings, search184    // 2.0185    case researchSession(String)          // a research workspace (`s-…`, `p-…`), finished or not186    case approvals187    case terminal188    case statements(String)189    case chart(String)                    // the chart workstation of a symbol190    case quickCalc(String)                // option | var | sizing191    case portfolios192    case portfolio(String)193    case studio194    case project(String)195    case note(String)196    case review(String)197    case workspaces198    case workspace(String)199    case usage, syncStatus, dataHealth200}201202@MainActor203@Observable204final class Router {205    var section: AppSection = .home206    var paths: [AppSection: [Route]] = [:]207    /// iPad: what the detail column of each three-column section shows (the item selected in the list column).208    var padDetail: [AppSection: Route] = [:]209    var showComposer = false210    var composerDraft = ""211    /// Preset of the next composer: research mode, a project, a dataset dropped on the app.212    var composerPreset = ComposerPreset()213    var showSearch = false214    /// iPad: the inspector of the research cockpit.215    var showInspector = true216217    struct ComposerPreset: Equatable {218        var mode: AnalysisMode?219        var projectId: String?220        var files: [URL] = []221    }222223    func path(_ s: AppSection) -> Binding<[Route]> {224        Binding(get: { self.paths[s] ?? [] }, set: { self.paths[s] = $0 })225    }226227    func section(for route: Route, compact: Bool) -> AppSection {228        switch route {229        case .asset, .search, .terminal, .statements, .chart, .dataHealth: return .markets230        case .conversation, .run, .researchSession, .approvals: return .research231        case .sharedReport, .library: return compact ? .research : .library232        case .quantTool, .quantJob, .quant, .quickCalc: return compact ? .research : .quant233        case .portfolios, .portfolio: return .portfolio234        case .studio, .project, .note, .review: return compact ? .more : .studio235        case .workspaces, .workspace: return compact ? .more : .workspaces236        case .agent: return compact ? .more : .agent237        case .settings, .usage, .syncStatus: return compact ? .more : .settings238        }239    }240241    /// Opens a destination in the section it belongs to (deep links, Shortcuts, notifications, widgets, search).242    func open(_ route: Route, compact: Bool) {243        let target = section(for: route, compact: compact)244        section = target245        // A route that *is* a section root on the iPad just selects the section.246        if !compact {247            switch route {248            case .quant, .library, .agent, .settings, .studio, .workspaces, .portfolios: paths[target] = []; return249            default: break250            }251            if target.hasListColumn { padDetail[target] = route; paths[target] = []; return }252        }253        var p = paths[target] ?? []254        if p.last != route { p.append(route) }255        paths[target] = p256    }257258    func compose(mode: AnalysisMode? = nil, draft: String = "", projectId: String? = nil, files: [URL] = []) {259        composerPreset = ComposerPreset(mode: mode, projectId: projectId, files: files)260        if !draft.isEmpty { composerDraft = draft }261        showComposer = true262    }263264    /// `vquant://asset/AAPL`, `vquant://conversation/<id>`, `vquant://analysis/<jobId>`, `vquant://quant/<jobId>`,265    /// `vquant://research[/<workspaceId>]`, `vquant://project/<id>`, `vquant://approvals`, `vquant://ask?q=…`.266    func handle(_ url: URL, compact: Bool) {267        guard url.scheme == "vquant", let host = url.host() else { return }268        let arg = url.pathComponents.dropFirst().first269        func id(_ s: String?) -> String? { s.flatMap { $0.count <= 64 && !$0.isEmpty ? $0 : nil } }270        switch host {271        case "asset": if let s = arg.flatMap(WatchlistFile.normalise) { open(.asset(s), compact: compact) }272        case "conversation": if let i = id(arg) { open(.conversation(i), compact: compact) }273        case "analysis": if let i = id(arg) { open(.run(i), compact: compact) }274        case "quant": if let i = id(arg) { open(.quantJob(i), compact: compact) } else { open(.quant, compact: compact) }275        case "research": if let i = id(arg) { open(.researchSession(i), compact: compact) } else { section = .research }276        case "project": if let i = id(arg) { open(.project(i), compact: compact) } else { open(.studio, compact: compact) }277        case "workspace": if let i = id(arg) { open(.workspace(i), compact: compact) }278        case "approvals": open(.approvals, compact: compact)279        case "terminal": open(.terminal, compact: compact)280        case "statements": if let s = arg.flatMap(WatchlistFile.normalise) { open(.statements(s), compact: compact) }281        case "chart": if let s = arg.flatMap(WatchlistFile.normalise) { open(.chart(s), compact: compact) }282        case "lab": if let i = id(arg) { open(.quantTool(i), compact: compact) } else { open(.quant, compact: compact) }283        case "calc": open(.quickCalc(id(arg) ?? "option"), compact: compact)284        case "studio": open(.studio, compact: compact)285        case "note": if let i = id(arg) { open(.note(i), compact: compact) }286        case "workspaces": open(.workspaces, compact: compact)287        case "portfolios": if let i = id(arg) { open(.portfolio(i), compact: compact) } else { open(.portfolios, compact: compact) }288        case "usage": open(.usage, compact: compact)289        case "sync": open(.syncStatus, compact: compact)290        case "settings": open(.settings, compact: compact)291        case "search": showSearch = true292        case "home": section = .home293        case "ask":294            let q = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "q" }?.value ?? ""295            compose(mode: .research, draft: String(q.prefix(4000)))296        case "portfolio": section = .portfolio297        case "markets": section = .markets298        default: break299        }300    }301}302303/// iPad list columns set this: a row then selects its destination for the detail column instead of pushing it.304private struct PadSelectKey: EnvironmentKey { static let defaultValue: (@MainActor (Route) -> Void)? = nil }305extension EnvironmentValues {306    var padSelect: (@MainActor (Route) -> Void)? {307        get { self[PadSelectKey.self] }308        set { self[PadSelectKey.self] = newValue }309    }310}311312/// A row that leads to a destination: a navigation link on the iPhone and inside a detail stack, a selection in an313/// iPad list column. Symbols and studies can be dragged out of it.314struct RouteLink<Label: View>: View {315    let route: Route316    @ViewBuilder var label: Label317    @Environment(\.padSelect) private var select318    @Environment(AppModel.self) private var model319320    init(_ route: Route, @ViewBuilder label: () -> Label) { self.route = route; self.label = label() }321322    var body: some View {323        if let select {324            Button { select(route) } label: { label.frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()) }325                .buttonStyle(.plain)326                .listRowBackground(isSelected ? Theme.surface2 : nil)327                .accessibilityAddTraits(isSelected ? [.isSelected] : [])328                .hoverEffect(.highlight)329        } else {330            NavigationLink(value: route) { label }331        }332    }333    private var isSelected: Bool { model.router.padDetail[model.router.section] == route }334}335336enum Haptics {337    @MainActor static func tap() { UIImpactFeedbackGenerator(style: .light).impactOccurred() }338    @MainActor static func success() { UINotificationFeedbackGenerator().notificationOccurred(.success) }339    @MainActor static func warning() { UINotificationFeedbackGenerator().notificationOccurred(.warning) }340}341
Files main
Menu

Theme