SPB Git

Repository Public

SettingsView.swift 28.2 KB 396 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Settings/SettingsView.swift3// Description: Settings: the window, its sidebar of panes, and the panes that exist since 1.0 (account, Touch ID and passkeys, authorized devices, appearance, market data, charts, research, computation, cache, notifications, shortcuts, network diagnostics, about). The 2.0 panes are in SettingsNextPanes.swift and SettingsInsightPanes.swift.4import SwiftUI5import UserNotifications6import VQuantCore7import VQuantKit8import VQuantUI910/// The panes of the Settings window, in the order of its sidebar. `-VQSettings <rawValue>` (DEBUG) opens one at launch.11enum SettingsPane: String, CaseIterable, Identifiable {12    case account, security, devices, audit13    case models, budgets, memory, usage, research14    case market, providers, sync, cache15    case appearance, charts, computation, notifications, shortcuts16    case network, about17    var id: String { rawValue }18    var title: String {19        switch self {20        case .account: "Account"; case .security: "Touch ID & Passkeys"; case .devices: "Authorized Devices"; case .appearance: "Appearance"; case .market: "Market Data"21        case .charts: "Charts"; case .research: "Research"; case .computation: "Computation"; case .cache: "Cache & Storage"; case .notifications: "Notifications"22        case .shortcuts: "Keyboard Shortcuts"; case .network: "Network Diagnostics"; case .about: "About VQuant"23        case .models: "Models & Routing"; case .budgets: "Budgets"; case .memory: "Memory"; case .usage: "Usage & Cost"; case .audit: "Audit Log"24        case .providers: "Data Providers"; case .sync: "Sync"25        }26    }27    var symbol: String {28        switch self {29        case .account: "person.crop.circle"; case .security: "touchid"; case .devices: "laptopcomputer.and.iphone"; case .appearance: "paintbrush"; case .market: "globe.americas"30        case .charts: "chart.xyaxis.line"; case .research: "sparkles"; case .computation: "function"; case .cache: "internaldrive"; case .notifications: "bell"31        case .shortcuts: "keyboard"; case .network: "network"; case .about: "info.circle"32        case .models: "cpu"; case .budgets: "gauge.with.needle"; case .memory: "brain.head.profile"; case .usage: "chart.bar"; case .audit: "list.bullet.clipboard"33        case .providers: "server.rack"; case .sync: "arrow.triangle.2.circlepath.icloud"34        }35    }36    /// One sentence under the title of the panes added in 2.0.37    var summary: String? {38        switch self {39        case .models: "Which models the server can reach, which one answers by default, and how “Auto” chooses."40        case .budgets: "Limits applied to each analysis unless a request sets its own."41        case .memory: "What the agent remembers about you and your projects, and for how long."42        case .usage: "Tokens and cost of your analyses, as recorded by the server at every model call."43        case .audit: "Sign-ins, revocations, deletions and exports recorded for your account."44        case .providers: "The market-data sources behind the server, checked capability by capability."45        case .sync: "The copy of your account kept on this Mac and the changes waiting to be sent."46        default: nil47        }48    }49    static let groups: [(String, [SettingsPane])] = [50        ("Account", [.account, .security, .devices, .audit]),51        ("Intelligence", [.models, .budgets, .memory, .usage, .research]),52        ("Data", [.market, .providers, .sync, .cache]),53        ("This Mac", [.appearance, .charts, .computation, .notifications, .shortcuts]),54        ("Support", [.network, .about]),55    ]56}5758struct SettingsView: View {59    let app: AppEnvironment60    @State private var pane: SettingsPane6162    init(app: AppEnvironment) {63        self.app = app64        _pane = State(initialValue: app.options.settingsPane.flatMap(SettingsPane.init(rawValue:)) ?? .account)65    }6667    var body: some View {68        NavigationSplitView {69            List {70                ForEach(SettingsPane.groups, id: \.0) { group, panes in71                    Section(group) {72                        ForEach(panes) { p in73                            SelectableRow(isSelected: pane == p) { pane = p } content: {74                                Label { Text(p.title) } icon: { Image(systemName: p.symbol).foregroundStyle(pane == p ? VQTokens.Palette.accentText : VQTokens.Palette.text2) }75                            }76                            .accessibilityIdentifier("settings.pane.\(p.rawValue)")77                        }78                    }79                }80            }81            .listStyle(.sidebar).navigationSplitViewColumnWidth(220)82        } detail: {83            ScrollView {84                VStack(alignment: .leading, spacing: 14) {85                    VStack(alignment: .leading, spacing: 4) {86                        Text(pane.title).font(VQTokens.Typography.displayMd.font).foregroundStyle(VQTokens.Palette.text1).accessibilityIdentifier("settings.title").accessibilityAddTraits(.isHeader)87                        if let s = pane.summary { Text(s).font(.callout).foregroundStyle(VQTokens.Palette.text2).fixedSize(horizontal: false, vertical: true) }88                    }89                    switch pane {90                    case .account: AccountPane(app: app)91                    case .security: SecurityPane(app: app)92                    case .devices: DevicesPane(app: app)93                    case .appearance: appearance94                    case .market: market95                    case .charts: charts96                    case .research: research97                    case .computation: computation98                    case .cache: CachePane(app: app)99                    case .notifications: NotificationsPane(app: app)100                    case .shortcuts: shortcuts101                    case .network: NetworkPane(app: app)102                    case .about: about103                    case .models: ModelsPane(app: app)104                    case .budgets: BudgetsPane(app: app)105                    case .memory: MemoryPane(app: app)106                    case .usage: UsagePane(app: app)107                    case .audit: AuditPane(app: app)108                    case .providers: DataProvidersPane(app: app)109                    case .sync: SyncPane(app: app)110                    }111                }112                .padding(.horizontal, 24).padding(.top, 6).padding(.bottom, 24).frame(maxWidth: .infinity, alignment: .leading)113            }114            .background(VQTokens.Palette.ink0)115            .id(pane)116        }117        .frame(width: 980, height: 660)118        .vqTheme(app.vqTheme)119    }120121    private var s: SettingsStore { app.settings }122123    private var appearance: some View {124        Form {125            Picker("Appearance (this Mac only)", selection: Binding(get: { s.theme }, set: { s.theme = $0 })) { ForEach(AppTheme.allCases) { Text($0.title).tag($0) } }126                .accessibilityIdentifier("settings.appearance.theme")127            Toggle("Colour-vision-safe pair: blue for rising prices, orange for falling", isOn: Binding(get: { s.colorVisionSafe }, set: { s.colorVisionSafe = $0; app.sync.pushSettings() }))128                .accessibilityIdentifier("settings.appearance.cvd")129            Toggle(s.colorVisionSafe ? "Swap the pair: orange for rising prices, blue for falling" : "Red for rising prices, green for falling", isOn: Binding(get: { s.invertUpDown }, set: { s.invertUpDown = $0 }))130            LabeledContent("Preview") {131                HStack(spacing: 14) {132                    HStack(spacing: 3) { Image(systemName: "arrowtriangle.up.fill").font(.system(size: 8)); Text("+1.25 %") }.foregroundStyle(s.upColor)133                    HStack(spacing: 3) { Image(systemName: "arrowtriangle.down.fill").font(.system(size: 8)); Text("−0.80 %") }.foregroundStyle(s.downColor)134                }135                .font(VQTokens.Typography.numMd.font)136            }137            Text("Light or dark is chosen on each device. The colour pair is part of your account: it follows you to the web app and your other devices" + (app.sync.active == nil ? " once this Mac is signed in." : ".") + " A change is never shown by colour alone: an arrow and a sign always accompany it. Swapping the pair stays on this Mac.")138                .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)139            Toggle("Show VQuant in the menu bar", isOn: Binding(get: { s.menuBarExtra }, set: { s.menuBarExtra = $0 }))140                .accessibilityIdentifier("settings.appearance.menubar")141            Text("The menu-bar item shows the market session, a few index quotes with their age, what is running on the server, and a field that opens Research with a question ready. It shows nothing while VQuant is signed out or locked.")142                .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)143        }144    }145146    private var market: some View {147        Form {148            Picker("Refresh quotes", selection: Binding(get: { s.quoteRefresh }, set: { s.quoteRefresh = $0; app.market.start() })) {149                Text("Every 10 seconds").tag(10); Text("Every 30 seconds").tag(30); Text("Every minute").tag(60); Text("Every 5 minutes").tag(300); Text("Manually (⌘R)").tag(0)150            }151            Text("Quotes come from the VQuant server, which proxies Financial Modeling Prep over HTTPS. The backend has no streaming feed: values are polled, and each one is shown with the provider's own timestamp. A quote is labelled “Recent” only when that timestamp is under two minutes old; otherwise “Delayed”, “Historical”, “Cached” (offline) or “Unavailable”. Polling pauses while VQuant is in the background.")152                .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)153        }154    }155156    private var charts: some View {157        Form {158            Picker("Default style", selection: Binding(get: { s.chartStyle }, set: { s.chartStyle = $0 })) { ForEach(ChartStyle.allCases) { Text($0.title).tag($0) } }159            Picker("Default interval", selection: Binding(get: { s.chartInterval }, set: { s.chartInterval = $0 })) { ForEach(BarInterval.allCases) { Text($0.label).tag($0) } }160            Toggle("Show volume", isOn: Binding(get: { s.chartVolume }, set: { s.chartVolume = $0 }))161            Toggle("Logarithmic price scale", isOn: Binding(get: { s.chartLogScale }, set: { s.chartLogScale = $0 }))162            Text("Defaults apply to charts opened from now on. Indicators (moving averages, Bollinger bands, RSI, MACD) are computed on this Mac from the bars the server returned. When more bars are visible than the window has pixels, neighbouring bars are merged for drawing only — highs, lows and volume are preserved, the chart says so, and exports always contain the source bars.")163                .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)164        }165    }166167    private var research: some View {168        VStack(alignment: .leading, spacing: 18) {169            researchDefaults.frame(maxWidth: 660, alignment: .leading)170            SandboxSection(app: app)171        }172    }173174    private var researchDefaults: some View {175        Form {176            Picker("Default mode", selection: Binding(get: { s.researchMode }, set: { s.researchMode = $0; app.sync.pushSettings() })) { ForEach(ResearchMode.allCases) { Text($0.title).tag($0) } }177            Text(s.researchMode.detail).font(.callout).foregroundStyle(.secondary)178            LabeledContent("Default model") { Text(s.researchModel == "auto" ? "Auto" : ResearchModel.name(s.researchModel)).foregroundStyle(.secondary) }179            Text("The default model, “Auto” and the routing strategy are chosen in Models & Routing, from the models the server actually reaches.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)180            Toggle("Show the model's reasoning while it works", isOn: Binding(get: { s.showThinking }, set: { s.showThinking = $0 }))181            TextField("Author on slide decks", text: Binding(get: { s.slidesAuthor }, set: { s.slidesAuthor = $0 }), prompt: Text(app.session.account?.name ?? ""))182            TextField("Organisation on slide decks", text: Binding(get: { s.slidesCompany }, set: { s.slidesCompany = $0 }))183            Text("Model inference, web research and the Python notebook all run on the VQuant server. The agent can read and edit your memory, positions and watches; it has no access to a broker and cannot trade.")184                .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)185            Toggle("Notify when the research agent needs an approval", isOn: Binding(get: { s.notifyOnApproval }, set: { s.notifyOnApproval = $0; if $0 { Notifier.requestAuthorization() } }))186                .accessibilityIdentifier("settings.research.notifyApproval")187            Text("Posted only while VQuant is in the background. Clicking the notification brings VQuant forward on that conversation.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)188        }189    }190191    private var computation: some View {192        Form {193            Picker("Check running jobs", selection: Binding(get: { s.jobPoll }, set: { s.jobPoll = $0 })) { Text("Every 2 seconds").tag(2); Text("Every 5 seconds").tag(5); Text("Every 15 seconds").tag(15) }194            if let cat = app.quant.catalogue {195                LabeledContent("Engines on the server") { Text(cat.tools.map(\.title).joined(separator: ", ")).multilineTextAlignment(.trailing) }196                LabeledContent("Simultaneous computations") { Text("\(cat.maxRunning) per person") }197            }198            Text("Computations run in the server's Python environment (the same engines the research agent uses) as jobs stored on the server with their parameters and code. A running computation cannot be cancelled: the server's engines do not expose it. The VQuant repository contains no component named “Pyrus”; the server-side computation layer it does contain is this Python engine, exposed here as the Quant Engine.")199                .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)200        }201    }202203    private var shortcuts: some View {204        let menu = AppShortcuts.all.filter { !$0.id.hasPrefix("view.section") }.map { ($0.display, $0.title) }205        let rows: [(String, String)] = [("⌘1 … ⌘9", "Go to one of the first nine sections (View menu)")] + menu + [206            ("⌘N", "New window"), ("⌘↩", "Send the question / run the computation"), ("⌃⌘S", "Show or hide the sidebar"), ("⌃⌘F", "Full screen"), ("⌘,", "Settings"),207            ("← →", "Pan the chart"), ("↑ ↓ or + −", "Zoom the chart"), ("0", "Fit the chart"), ("Double-click", "Fit the chart")]208        return Grid(alignment: .leading, horizontalSpacing: 24, verticalSpacing: 6) {209            ForEach(rows, id: \.0) { k, v in210                GridRow { Text(k).font(.system(.body, design: .monospaced)).foregroundStyle(.secondary); Text(v) }211            }212        }213    }214215    private var about: some View {216        let info = Bundle.main.infoDictionary ?? [:]217        return VStack(alignment: .leading, spacing: 8) {218            HStack(spacing: 12) { Sparkle(size: 40); VStack(alignment: .leading) { Text("VQuant for macOS").font(.title3.weight(.semibold)); Text("Version \(info["CFBundleShortVersionString"] as? String ?? "") (\(info["CFBundleVersion"] as? String ?? ""))").foregroundStyle(.secondary) } }219            Text("A native client of the VQuant server at \(app.options.server.host ?? ""). Built with Swift, SwiftUI and AppKit; no web view. Computation, data and model inference stay on the server.").fixedSize(horizontal: false, vertical: true)220            Text("Market and fundamental data: Financial Modeling Prep, through the VQuant server. Nothing shown by this application is investment advice.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)221            Text(info["NSHumanReadableCopyright"] as? String ?? "").font(.caption).foregroundStyle(.tertiary)222        }223    }224}225226private struct AccountPane: View {227    let app: AppEnvironment228    var body: some View {229        Form {230            LabeledContent("Signed in as") { Text(app.session.account.map { "\($0.name) (\($0.id))" } ?? "Not signed in") }231            LabeledContent("Server") { Text(app.options.server.absoluteString).textSelection(.enabled) }232            if let d = app.session.device {233                LabeledContent("This device") { Text(d.label) }234                LabeledContent("Session opened") { Text(Fmt.dateTime(d.created)) }235            }236            if app.session.unverified { Text("The server could not be reached: the session has not been verified since launch.").foregroundStyle(.orange) }237            Text("This is the same account as on vquant.spboucher.ai: same history, memory, portfolio and watches. The session of this Mac is a token kept in the Keychain; it expires after 90 days without use and can be revoked from any signed-in device.")238                .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)239            Button("Sign Out of This Mac", role: .destructive) { Task { await app.session.signOut() } }.disabled(!app.session.isSignedIn)240        }241    }242}243244private struct SecurityPane: View {245    let app: AppEnvironment246    @State private var overview: DeviceOverview?247    @State private var error: String?248    @State private var deleting: PasskeyInfo?249250    var body: some View {251        VStack(alignment: .leading, spacing: 12) {252            Toggle("Require \(app.session.biometryName) to open VQuant", isOn: Binding(get: { app.settings.appLock }, set: { on in Task { if await !app.session.setAppLock(on) { app.toasts.show("The lock setting was not changed.", error: true) } } }))253            Text("When on, the session token is released from the Keychain only after \(app.session.biometryName) (or your Mac password) each time VQuant starts or is unlocked (⌃⌘L). Biometric data never leaves the Secure Enclave and is never seen by VQuant or its server.")254                .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)255            Divider()256            Text("Passkeys of this account").font(.headline)257            if let overview {258                ForEach(overview.passkeys) { p in259                    HStack {260                        Image(systemName: "person.badge.key.fill").foregroundStyle(.secondary)261                        VStack(alignment: .leading) {262                            Text(p.label)263                            Text("\(p.backedUp ? "Synced by its platform (iCloud Keychain or similar)" : "On one device only") · added \(Fmt.dateTime(p.created)) · last used \(Fmt.relative(p.lastUsed))").font(.caption).foregroundStyle(.secondary)264                        }265                        Spacer()266                        Button("Remove…", role: .destructive) { deleting = p }.disabled(overview.passkeys.count <= 1).help(overview.passkeys.count <= 1 ? "The only passkey of the account cannot be removed." : "Asks for a passkey check first")267                    }268                }269            } else if let error { Text(error).foregroundStyle(.secondary) } else { ProgressView() }270            Text("A passkey is created on a new device from a setup link generated on the server (`npm run access:invite invite <person>`). Removing a passkey asks for a fresh passkey check and ends the device sessions opened with it.")271                .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)272        }273        .task { await load() }274        .confirmationDialog("Remove the passkey “\(deleting?.label ?? "")”?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } })) {275            Button("Remove Passkey", role: .destructive) { if let d = deleting { Task { do { try await app.auth.deletePasskey(d.ref); await load() } catch { app.toasts.error(error) } } } }276        } message: { Text("That device will no longer be able to sign in. You will be asked to confirm with your own passkey.") }277    }278    private func load() async { do { overview = try await app.auth.devices(); error = nil } catch { self.error = error.localizedDescription } }279}280281private struct DevicesPane: View {282    let app: AppEnvironment283    @State private var overview: DeviceOverview?284    @State private var error: String?285286    var body: some View {287        VStack(alignment: .leading, spacing: 10) {288            Text("Native applications signed in to this account. Revoking a device signs it out at its next request; it asks for a passkey check first. Browsers signed in to the web app are not listed: the web session is a cookie the server cannot enumerate.")289                .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)290            if let overview {291                ForEach(overview.sessions) { d in292                    HStack {293                        Image(systemName: d.platform == "ios" ? "iphone" : "laptopcomputer").foregroundStyle(.secondary).frame(width: 22)294                        VStack(alignment: .leading) {295                            HStack { Text(d.label); if d.current == true { Text("This Mac").font(.caption).padding(.horizontal, 5).padding(.vertical, 1).background(Color.accentColor.opacity(0.2), in: Capsule()) } }296                            Text("Signed in \(Fmt.dateTime(d.created)) · last active \(Fmt.relative(d.lastUsed))").font(.caption).foregroundStyle(.secondary)297                        }298                        Spacer()299                        if d.current != true { Button("Revoke", role: .destructive) { Task { do { try await app.auth.revokeDevice(d.id); await load() } catch { app.toasts.error(error) } } } }300                    }301                    .padding(.vertical, 2)302                }303                if overview.sessions.isEmpty { Text("No device session.").foregroundStyle(.secondary) }304            } else if let error { Text(error).foregroundStyle(.secondary); Button("Retry") { Task { await load() } } } else { ProgressView() }305        }306        .task { await load() }307    }308    private func load() async { do { overview = try await app.auth.devices(); error = nil } catch { self.error = error.localizedDescription } }309}310311private struct CachePane: View {312    let app: AppEnvironment313    @State private var usage: (files: Int, bytes: Int) = (0, 0)314    var body: some View {315        Form {316            LabeledContent("Cached items") { Text("\(usage.files) · \(ByteCountFormatter.string(fromByteCount: Int64(usage.bytes), countStyle: .file))") }317            Button("Clear Cache") { app.cache.removeAll(); usage = app.cache.usage(); app.toasts.show("Cache cleared.") }318            Text("VQuant keeps the last version of what it showed (quotes, chart series, conversations, reports and figures, portfolio, computation results) so that it stays readable without a connection. Each file is encrypted (AES-GCM) with a key held in the Keychain of this Mac, excluded from backups, and erased at sign-out. Offline, nothing is sent later on your behalf: analyses, computations and edits are refused until the server is reachable. Watchlists and window layouts are kept unencrypted in Application Support.")319                .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)320        }321        .onAppear { usage = app.cache.usage() }322    }323}324325private struct NotificationsPane: View {326    let app: AppEnvironment327    @State private var status = "…"328    var body: some View {329        Form {330            Toggle("Notify when an analysis or a computation finishes", isOn: Binding(get: { app.settings.notifyOnCompletion }, set: { app.settings.notifyOnCompletion = $0; if $0 { Notifier.requestAuthorization() } }))331            Toggle("Notify when the research agent needs an approval", isOn: Binding(get: { app.settings.notifyOnApproval }, set: { app.settings.notifyOnApproval = $0; if $0 { Notifier.requestAuthorization() } }))332                .accessibilityIdentifier("settings.notifications.approval")333            LabeledContent("macOS permission") { Text(status) }334            Text("Notifications are posted by this app when it sees a job finish, or the research agent wait for an approval, while it is in the background; they are local to this Mac. Clicking one brings VQuant forward on the conversation or the computation it is about. The server sends no push notification.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)335        }336        .task {337            let s = await UNUserNotificationCenter.current().notificationSettings()338            status = switch s.authorizationStatus { case .authorized, .provisional, .ephemeral: "Allowed"; case .denied: "Denied in System Settings"; default: "Not requested yet" }339        }340    }341}342343/// Probes each server service with a real request and reports what it answered and how fast.344private struct NetworkPane: View {345    let app: AppEnvironment346    @State private var results: [ServiceHealth] = []347    @State private var running = false348349    var body: some View {350        VStack(alignment: .leading, spacing: 10) {351            HStack {352                Button { Task { await run() } } label: { Label("Run Diagnostics", systemImage: "stethoscope") }.disabled(running)353                if running { ProgressView().controlSize(.small) }354                Spacer()355                Text(app.connectivity.isOnline ? "This Mac has a network connection" : "This Mac is offline").font(.callout).foregroundStyle(app.connectivity.isOnline ? Color.secondary : Palette.red)356            }357            ForEach(results, id: \.name) { r in358                HStack(alignment: .firstTextBaseline) {359                    Image(systemName: r.ok ? "checkmark.circle.fill" : "xmark.circle.fill").foregroundStyle(r.ok ? Palette.green : Palette.red)360                    Text(r.name).frame(width: 190, alignment: .leading)361                    Text(r.detail).foregroundStyle(.secondary).lineLimit(2)362                    Spacer()363                    if let ms = r.latencyMs { Text("\(Int(ms)) ms").monospacedDigit().foregroundStyle(.secondary) }364                }365            }366            if results.isEmpty { Text("Each service is checked with one read-only request; latency is measured on this Mac.").font(.callout).foregroundStyle(.secondary) }367            Text("Server: \(app.options.server.absoluteString). Infrastructure addresses and credentials are not shown or stored by this application.").font(.caption).foregroundStyle(.tertiary)368        }369        .task { if results.isEmpty { await run() } }370    }371372    private func probe(_ name: String, _ work: () async throws -> String) async -> ServiceHealth {373        let t0 = ContinuousClock.now374        do {375            let d = try await work()376            let e = ContinuousClock.now - t0377            return ServiceHealth(name: name, ok: true, detail: d, latencyMs: Double(e.components.seconds) * 1000 + Double(e.components.attoseconds) / 1e15)378        } catch { return ServiceHealth(name: name, ok: false, detail: error.localizedDescription, latencyMs: nil) }379    }380381    private func run() async {382        running = true; defer { running = false }383        let api = app.api384        var out: [ServiceHealth] = []385        out.append(await probe("Server") { let h = try await api.health(); return "up for \(Fmt.duration(TimeInterval(h.uptime)))" })386        out.append(await probe("Authentication") { let s = try await app.auth.session(); return "session valid for \(s.user.name)" })387        out.append(await probe("Market data") { let i = try await api.indices(); return "\(i.count) indices, newest quote \(Fmt.relative(i.compactMap(\.asOf).max()))" })388        out.append(await probe("Symbol search") { "\(try await api.search("AAPL", limit: 3).count) matches for AAPL" })389        out.append(await probe("Research agent jobs") { let g = try await api.generations(); return "\(g.running) running, \(g.generations.count) listed" })390        out.append(await probe("Quant Engine") { let c = try await api.quantCatalogue(); let j = try await api.quantJobs(); return "\(c.tools.count) engines, \(j.running) running" })391        out.append(await probe("Workspace storage") { let w = try await api.workspace(); return "\(w.memories.count) memories, \(w.positions.count) positions, \(w.watches.count) watches" })392        out.append(await probe("Usage counters") { let u = try await api.usage(); return "\(u.sessions.total) conversations on this instance, \(u.errors.lastHour) recent errors" })393        results = out394    }395}396
Files main
Menu

Theme