Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Quant/LabView.swift3// Description: The Quant Lab section: the catalogue of the server's engines by category, and the workbench (parameters or computations on the left, the selected result on the right). Navigation state lives in the window model (`quantTool`, `quantJobId`).4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89private typealias P = VQTokens.Palette10private typealias S = VQTokens.Space11private typealias T = VQTokens.Typography1213/// Per-window state of the section that is not navigation (which tab of the left column, what is compared).14@Observable final class LabWindowState {15 enum LeftTab: String { case parameters, jobs }16 var leftTab: LeftTab = .parameters17 /// The second job of a side-by-side comparison (nil = no comparison).18 var compareWith: String?19 var reviewOpen = false20 var query = ""21 var category: String?22 /// A slice of a long result (chain analytics, backtest), by engine.23 var slice: [String: String] = [:]24 var launchConsumed = false25}2627struct QuantView: View {28 let app: AppEnvironment29 @Bindable var model: WindowModel30 @State private var state = LabWindowState()31 @SceneStorage("lab.leftWidth") private var leftWidth: Double = 38032 @State private var dragStart: Double?3334 private var lab: LabStore { app.lab }35 /// The tool on the bench: the one picked, else the tool of the selected job.36 private var tool: VQLabTool? {37 if let id = model.quantTool, let t = lab.tool(id) { return t }38 if let id = model.quantJobId, let j = lab.job(id) { return lab.tool(j.tool) }39 return nil40 }4142 var body: some View {43 Group {44 if lab.catalog == nil {45 if let e = lab.error {46 Color.clear.frame(maxWidth: .infinity, maxHeight: .infinity)47 .overlay { VQEmptyState(systemImage: "exclamationmark.triangle", title: "The Quant Lab could not be loaded", message: e) { Button("Retry") { Task { await lab.refresh() } } } }48 } else {49 VStack(alignment: .leading, spacing: S.s6) { VQSkeletonText(lines: 2); VQSkeletonRows(rows: 6, columns: 3) }.padding(S.s8).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)50 }51 } else if model.quantTool == nil && model.quantJobId == nil {52 LabCatalogueView(app: app, model: model, state: state)53 } else {54 workbench55 }56 }57 .background(P.ink0)58 .task {59 await lab.refresh()60 consumeLaunchArguments()61 }62 .onChange(of: model.quantJobId) { _, id in63 state.compareWith = nil64 if id != nil, model.quantTool == nil { state.leftTab = .jobs }65 }66 .sheet(isPresented: $state.reviewOpen) {67 if let id = model.quantJobId, let job = lab.job(id) { LabReviewSheet(app: app, job: job).vqTheme(app.vqTheme) }68 }69 }7071 /// A plain row with a draggable divider, not `HSplitView`: the split view re-negotiates the minimum size of its72 /// children on every layout pass, and a pane whose height depends on its width (wrapped text pinned above a73 /// scroll view) sent AppKit into an endless constraint update (crash seen on macOS 27 with the comparison open).74 private var workbench: some View {75 HStack(spacing: 0) {76 VStack(spacing: 0) {77 benchHeader78 Rectangle().fill(P.line).frame(height: 1)79 switch state.leftTab {80 case .parameters:81 if let tool { LabFormView(app: app, model: model, state: state, tool: tool).id(tool.id) }82 else { Color.clear.frame(maxWidth: .infinity, maxHeight: .infinity).overlay { VQEmptyState(title: "No engine", message: "This computation's engine is not in the catalogue of this server any more.") } }83 case .jobs: LabJobList(app: app, model: model, state: state, toolFilter: nil)84 }85 }86 .frame(width: leftWidth)87 .background(P.ink1)88 Rectangle().fill(P.line).frame(width: 1)89 .overlay {90 Color.clear.frame(width: 9).contentShape(Rectangle())91 .onHover { inside in if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() } }92 .gesture(DragGesture(minimumDistance: 1, coordinateSpace: .global).onChanged { g in93 if dragStart == nil { dragStart = leftWidth }94 leftWidth = min(520, max(330, (dragStart ?? leftWidth) + g.translation.width))95 }.onEnded { _ in dragStart = nil })96 }97 .accessibilityHidden(true)98 LabResultPane(app: app, model: model, state: state, tool: tool)99 .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)100 .clipped()101 }102 }103104 private var benchHeader: some View {105 VStack(alignment: .leading, spacing: S.s3) {106 HStack(spacing: S.s2) {107 Button { model.quantTool = nil; model.quantJobId = nil } label: {108 HStack(spacing: 3) { Image(systemName: "chevron.left").font(.system(size: 10, weight: .semibold)); Text("Catalogue") }109 .vqFont(T.caption).foregroundStyle(P.text2).contentShape(Rectangle())110 }111 .buttonStyle(.plain).accessibilityIdentifier("lab.back").help("Back to the catalogue of engines")112 Spacer()113 if let tool { LabSchemaChip(tool: tool) }114 }115 if let tool {116 VStack(alignment: .leading, spacing: 2) {117 Text(tool.title).vqFont(T.title).foregroundStyle(P.text1).lineLimit(1).accessibilityAddTraits(.isHeader)118 Text(LabCategory.title(tool.category?.rawValue) + (tool.version.map { " · v\($0)" } ?? "")).vqFont(T.overline).foregroundStyle(P.text3)119 }120 }121 VQSegmentedControl("Left column", selection: $state.leftTab, options: [.init(.parameters, "Parameters"), .init(.jobs, lab.runningCount > 0 ? "Computations · \(lab.runningCount) running" : "Computations")])122 .accessibilityIdentifier("lab.lefttab")123 }124 .padding(.horizontal, S.s4).padding(.top, S.s3).padding(.bottom, S.s3)125 .frame(maxWidth: .infinity, alignment: .leading)126 }127128 /// DEBUG launch arguments (captures and UI tests): `-VQTool <id>`, `-VQTab parameters|jobs`,129 /// `-VQXLabCompare <jobId>`, `-VQXLabReview 1`, `-VQXLabQuery <text>`, `-VQXLabCategory <category>`,130 /// `-VQXLabSlice <id>`; the form reads `-VQXLabMode`, `-VQXLabParams <json>`, `-VQXLabRun 1`, `-VQXLabAll 1`.131 private func consumeLaunchArguments() {132 guard !state.launchConsumed else { return }133 state.launchConsumed = true134 let o = app.options135 if model.quantTool == nil, let t = o.tool, lab.tool(t) != nil, model.quantJobId == nil || o.extra["LabRun"] != nil { model.quantTool = t }136 if let tab = (model.launchTab ?? o.tab).flatMap(LabWindowState.LeftTab.init(rawValue:)) { state.leftTab = tab }137 else if model.quantJobId != nil, model.quantTool == nil { state.leftTab = .jobs }138 if let q = o.extra["LabQuery"] { state.query = q }139 if let c = o.extra["LabCategory"] { state.category = c }140 if let c = o.extra["LabCompare"] { state.compareWith = c }141 if let s = o.extra["LabSlice"], let id = model.quantJobId, let j = lab.job(id) { state.slice[j.tool] = s }142 if o.extra["LabReview"] != nil, model.quantJobId != nil { state.reviewOpen = true }143 }144}145146// MARK: - shared small pieces147148enum LabCategory {149 static let order = ["volatility", "risk", "econometrics", "options", "backtest", "portfolio", "simulation"]150 static func title(_ raw: String?) -> String {151 switch raw {152 case "volatility": "Volatility"; case "risk": "Risk"; case "econometrics": "Econometrics"; case "options": "Options"153 case "backtest": "Backtest"; case "portfolio": "Portfolio"; case "simulation": "Simulation"154 case nil, "other"?: "Other"155 case let other?: other.capitalized156 }157 }158 static func blurb(_ raw: String) -> String {159 switch raw {160 case "volatility": "Conditional and realized volatility, forecasts."161 case "risk": "Value at Risk, expected shortfall, drawdowns, stress."162 case "econometrics": "Regressions, factors, panels, time series, events."163 case "options": "Pricing, Greeks, strategies, listed chains."164 case "backtest": "Strategies on daily bars, with costs and validation."165 case "portfolio": "Allocation, risk contribution, optimisation, scenarios."166 case "simulation": "Monte Carlo paths and bootstrap inference."167 default: ""168 }169 }170 static func symbol(_ raw: String?) -> String {171 switch raw {172 case "volatility": "waveform.path.ecg"; case "risk": "gauge.with.dots.needle.33percent"; case "econometrics": "chart.dots.scatter"173 case "options": "arrow.triangle.branch"; case "backtest": "clock.arrow.circlepath"; case "portfolio": "chart.pie"; case "simulation": "dice"174 default: "function"175 }176 }177}178179/// `lab/1` (the generic result schema, with provenance and methodology) or `legacy` (one of the six 1.x tools).180struct LabSchemaChip: View {181 let tool: VQLabTool182 var body: some View {183 Text(tool.isLab ? tool.resultSchema : "legacy")184 .font(.system(size: 10, weight: .medium, design: .monospaced))185 .foregroundStyle(tool.isLab ? P.accentText : P.text3)186 .padding(.horizontal, 6).padding(.vertical, 2)187 .overlay { RoundedRectangle(cornerRadius: 4, style: .continuous).strokeBorder(tool.isLab ? P.accentText.opacity(0.45) : P.lineStrong, lineWidth: 1) }188 .help(tool.isLab ? "Result in the generic lab/1 schema: summary, figures, tables, diagnostics, assumptions, methodology and provenance." : "One of the six 1.x tools: its result has its own shape and is shown by the 1.x views, with the Python code that ran.")189 .accessibilityLabel(tool.isLab ? "Result schema \(tool.resultSchema)" : "Legacy tool")190 }191}192193/// Status of a job: glyph and word, never colour alone. A running lab job shows its progress as a ring.194struct LabStatusGlyph: View {195 let job: VQQuantJob196 let app: AppEnvironment197 var size: CGFloat = 14198 var body: some View {199 Group {200 switch job.status.known {201 case .running?:202 if let p = job.progress, p > 0 {203 ZStack {204 Circle().stroke(P.ink4, lineWidth: 2)205 Circle().trim(from: 0, to: min(1, max(0.03, p))).stroke(P.accent, style: StrokeStyle(lineWidth: 2, lineCap: .round)).rotationEffect(.degrees(-90))206 }.padding(1)207 } else { ProgressView().controlSize(.mini).accessibilityHidden(true) }208 case .done?: Image(systemName: "checkmark.circle.fill").foregroundStyle(app.settings.upColor)209 case .error?: Image(systemName: "xmark.circle.fill").foregroundStyle(P.critical)210 case .cancelled?: Image(systemName: "stop.circle").foregroundStyle(P.text3)211 case .interrupted?, nil: Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(P.warn)212 }213 }214 .font(.system(size: size - 1))215 .frame(width: size, height: size)216 // one SwiftUI-only element: a label set on an AppKit-backed child (the spinner) sent SwiftUI's accessibility217 // into endless recursion on macOS 27 (crash under XCUITest, 2026-11-20)218 .accessibilityElement(children: .ignore)219 .accessibilityLabel(LabStatusGlyph.word(job))220 }221 static func word(_ job: VQQuantJob) -> String {222 switch job.status.known {223 case .running?: job.progress.map { $0 > 0 ? "Running, \(Int(($0 * 100).rounded())) %" : "Running" } ?? "Running"224 case .done?: "Done"; case .error?: "Failed"; case .cancelled?: "Cancelled"; case .interrupted?: "Interrupted"225 case nil: job.status.rawValue.capitalized226 }227 }228}229230// MARK: - Catalogue231232struct LabCatalogueView: View {233 let app: AppEnvironment234 @Bindable var model: WindowModel235 @Bindable var state: LabWindowState236237 private var lab: LabStore { app.lab }238 private func matches(_ t: VQLabTool) -> Bool {239 (state.category == nil || t.category?.rawValue == state.category)240 && LabCatalogueSearch.matches(state.query, fields: [t.id, t.title, t.summary, t.category?.rawValue ?? ""] + t.params.map(\.label))241 }242 private var groups: [(category: String, tools: [VQLabTool])] {243 let by = lab.catalog?.byCategory ?? []244 let known = LabCategory.order.compactMap { c in by.first { $0.category == c } }245 let others = by.filter { !LabCategory.order.contains($0.category) }246 return (known + others).map { ($0.category, $0.tools.filter(matches)) }.filter { !$0.tools.isEmpty }247 }248249 var body: some View {250 HStack(spacing: 0) {251 ScrollView {252 VStack(alignment: .leading, spacing: S.s8) {253 header254 if groups.isEmpty {255 VQEmptyState(systemImage: "magnifyingglass", title: "No engine matches", message: "Nothing in the catalogue matches “\(state.query)”\(state.category.map { " in \(LabCategory.title($0))" } ?? "").") {256 Button("Clear the filter") { state.query = ""; state.category = nil }257 }258 }259 ForEach(groups, id: \.category) { g in260 VStack(alignment: .leading, spacing: S.s4) {261 VQSectionHeader(LabCategory.title(g.category), overline: LabCategory.blurb(g.category)) {262 Text("\(g.tools.count) \(g.tools.count == 1 ? "engine" : "engines")").vqFont(T.numSm).foregroundStyle(P.text3)263 }264 LazyVGrid(columns: [GridItem(.adaptive(minimum: 280, maximum: 460), spacing: S.s4, alignment: .top)], alignment: .leading, spacing: S.s4) {265 ForEach(g.tools) { t in LabToolCard(tool: t, running: lab.jobs.filter { $0.tool == t.id && $0.isRunning }.count) { model.openLabTool(t.id) } }266 }267 }268 }269 if let u = lab.catalog?.unavailable, !u.isEmpty { unavailable(u) }270 }271 .padding(.horizontal, S.s8).padding(.vertical, S.s6)272 .frame(maxWidth: 1180, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)273 }274 if !lab.jobs.isEmpty {275 Rectangle().fill(P.line).frame(width: 1)276 VStack(spacing: 0) {277 HStack {278 Text("Recent computations").vqFont(T.heading).foregroundStyle(P.text1)279 Spacer()280 if lab.runningCount > 0 { Text("\(lab.runningCount)/\(lab.maxRunning) running").vqFont(T.numSm).foregroundStyle(P.accentText) }281 }282 .padding(.horizontal, S.s4).padding(.vertical, S.s3)283 Rectangle().fill(P.line).frame(height: 1)284 LabJobList(app: app, model: model, state: state, toolFilter: nil)285 }286 .frame(width: 320)287 .background(P.ink1)288 }289 }290 }291292 private var header: some View {293 VStack(alignment: .leading, spacing: S.s4) {294 VStack(alignment: .leading, spacing: S.s1) {295 Text("Quant Lab").vqFont(T.displayLg).foregroundStyle(P.text1).accessibilityAddTraits(.isHeader)296 Text("\(lab.catalog?.tools.count ?? 0) engines run on the VQuant server, in isolated Python processes. Every result states its data, its assumptions, its method and the code to reproduce it.")297 .vqFont(T.body).foregroundStyle(P.text2).frame(maxWidth: 720, alignment: .leading).fixedSize(horizontal: false, vertical: true)298 }299 VStack(alignment: .leading, spacing: S.s3) {300 HStack(spacing: S.s3) {301 HStack(spacing: 6) {302 Image(systemName: "magnifyingglass").foregroundStyle(P.text3).font(.system(size: 12))303 TextField("Search engines, methods, parameters", text: $state.query).textFieldStyle(.plain).vqFont(T.bodySm).accessibilityIdentifier("lab.search")304 if !state.query.isEmpty { Button { state.query = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(P.text3) }.buttonStyle(.plain).help("Clear") }305 }306 .padding(.horizontal, S.s2).frame(width: 300, height: 30)307 .background(RoundedRectangle(cornerRadius: 6.5, style: .continuous).fill(P.ink2))308 .overlay { RoundedRectangle(cornerRadius: 6.5, style: .continuous).strokeBorder(P.line, lineWidth: 1) }309 if lab.fromCache { Label("Offline — catalogue from this Mac's cache", systemImage: "icloud.slash").vqFont(T.caption).foregroundStyle(P.warn) }310 }311 ScrollView(.horizontal, showsIndicators: false) {312 HStack(spacing: 6) {313 chip("All", nil)314 ForEach(LabCategory.order.filter { c in lab.catalog?.tools.contains { $0.category?.rawValue == c } ?? false }, id: \.self) { chip(LabCategory.title($0), $0) }315 }316 }317 }318 }319 }320321 private func chip(_ title: String, _ value: String?) -> some View {322 let on = state.category == value323 return Button { state.category = value } label: {324 Text(title).vqFont(T.caption).fontWeight(on ? .semibold : .regular).foregroundStyle(on ? P.text1 : P.text2)325 .padding(.horizontal, S.s3).frame(height: 26)326 .background(Capsule().fill(on ? P.ink3 : Color.clear))327 .overlay { Capsule().strokeBorder(on ? P.lineStrong : P.line, lineWidth: 1) }328 .contentShape(Capsule())329 }330 .buttonStyle(.plain)331 .accessibilityIdentifier("lab.category.\(value ?? "all")")332 .accessibilityAddTraits(on ? [.isSelected] : [])333 }334335 private func unavailable(_ u: [String: String]) -> some View {336 VStack(alignment: .leading, spacing: S.s3) {337 VQSectionHeader("Unavailable engines", overline: "Declared by the server, not offered right now")338 ForEach(u.keys.sorted(), id: \.self) { id in339 HStack(alignment: .firstTextBaseline, spacing: S.s3) {340 Image(systemName: "nosign").foregroundStyle(P.warn).font(.system(size: 12)).accessibilityHidden(true)341 Text(id).font(.system(size: 12, design: .monospaced)).foregroundStyle(P.text1).frame(width: 170, alignment: .leading)342 Text(u[id] ?? "").vqFont(T.bodySm).foregroundStyle(P.text2).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)343 Spacer(minLength: 0)344 }345 .padding(.vertical, 6)346 .overlay(alignment: .bottom) { Rectangle().fill(P.line).frame(height: 1) }347 .accessibilityElement(children: .combine)348 }349 }350 }351}352353private struct LabToolCard: View {354 let tool: VQLabTool355 let running: Int356 let action: () -> Void357 @State private var hover = false358359 var body: some View {360 Button(action: action) {361 VStack(alignment: .leading, spacing: S.s2) {362 HStack(alignment: .firstTextBaseline, spacing: S.s2) {363 Text(tool.title).vqFont(T.title).foregroundStyle(P.text1).lineLimit(1)364 Spacer(minLength: S.s2)365 if running > 0 { HStack(spacing: 4) { ProgressView().controlSize(.mini).accessibilityHidden(true); Text("\(running)").vqFont(T.numSm).foregroundStyle(P.accentText) }.help("\(running) running") }366 }367 Text(tool.summary).vqFont(T.bodySm).foregroundStyle(P.text2).lineLimit(3).multilineTextAlignment(.leading)368 .frame(maxWidth: .infinity, minHeight: 56, alignment: .topLeading)369 HStack(spacing: S.s2) {370 LabSchemaChip(tool: tool)371 if let v = tool.version { Text("v\(v)").vqFont(T.numSm).foregroundStyle(P.text3) }372 Text("\(tool.params.filter { $0.type != .group }.count) parameters").vqFont(T.caption).foregroundStyle(P.text3)373 Spacer(minLength: 0)374 Image(systemName: "arrow.right").font(.system(size: 11, weight: .semibold)).foregroundStyle(hover ? P.accentText : P.text3).accessibilityHidden(true)375 }376 }377 .padding(S.s4)378 .frame(maxWidth: .infinity, alignment: .topLeading)379 .background(RoundedRectangle(cornerRadius: VQTokens.Radius.md, style: .continuous).fill(hover ? P.ink2 : P.ink1))380 .overlay { RoundedRectangle(cornerRadius: VQTokens.Radius.md, style: .continuous).strokeBorder(hover ? P.lineStrong : P.line, lineWidth: 1) }381 .contentShape(RoundedRectangle(cornerRadius: VQTokens.Radius.md, style: .continuous))382 }383 .buttonStyle(.plain)384 .onHover { hover = $0 }385 .accessibilityIdentifier("lab.tool.\(tool.id)")386 .accessibilityLabel("\(tool.title), \(tool.isLab ? "lab engine" : "legacy tool")\(tool.version.map { ", version \($0)" } ?? "")")387 .accessibilityHint(tool.summary)388 }389}390391/// A progress bar drawn in SwiftUI (determinate, or a travelling segment when the engine reports nothing).392/// Not `ProgressView`: see `LabStatusGlyph` about AppKit-backed controls and accessibility on macOS 27.393struct LabProgressBar: View {394 var value: Double?395 var height: CGFloat = 4396 @Environment(\.accessibilityReduceMotion) private var reduceMotion397398 var body: some View {399 GeometryReader { g in400 ZStack(alignment: .leading) {401 Capsule().fill(P.ink4)402 if let value {403 Capsule().fill(P.accent).frame(width: max(height, g.size.width * min(1, max(0, value))))404 } else if reduceMotion {405 Capsule().fill(P.accent.opacity(0.5))406 } else {407 TimelineView(.animation(minimumInterval: 1 / 30)) { t in408 let phase = t.date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: 1.6) / 1.6409 Capsule().fill(P.accent).frame(width: g.size.width * 0.28).offset(x: (g.size.width * 1.28) * phase - g.size.width * 0.28)410 }411 }412 }413 .clipShape(Capsule())414 }415 .frame(height: height)416 .accessibilityElement(children: .ignore)417 .accessibilityLabel("Progress")418 .accessibilityValue(value.map { "\(Int(($0 * 100).rounded())) percent" } ?? "not reported yet")419 }420}421