Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Quant/LabReviewSheet.swift3// Description: "Request review": the automated review of a Quant Lab result (CONTRACT §5.3) — deterministic checks first, then the reviewer model's findings and its verdict, read from the synced `review` object. Every surface says "Automated review — not a human peer review".4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89private typealias P = VQTokens.Palette10private typealias S = VQTokens.Space11private typealias T = VQTokens.Typography1213enum LabReviewWording {14 /// The label every review surface carries (the server's `disclaimer` says the same).15 static let label = "Automated review — not a human peer review"16}1718/// The line that always sits above a review, in the sheet and on the result.19struct LabReviewLabel: View {20 var body: some View {21 HStack(spacing: 6) {22 Image(systemName: "cpu").font(.system(size: 11, weight: .semibold)).accessibilityHidden(true)23 Text(LabReviewWording.label).vqFont(T.overline)24 }25 .foregroundStyle(P.warn)26 .accessibilityIdentifier("lab.review.label")27 }28}2930/// On a result that has been reviewed: one line, labelled, that opens the review.31struct LabReviewStrip: View {32 let review: VQReview33 let open: () -> Void34 var body: some View {35 Button(action: open) {36 HStack(spacing: S.s3) {37 LabReviewLabel()38 Text(summary).vqFont(T.caption).foregroundStyle(P.text2).lineLimit(1)39 Spacer(minLength: S.s2)40 Text("Open").vqFont(T.caption).foregroundStyle(P.accentText)41 }42 .padding(.horizontal, S.s3).padding(.vertical, S.s2)43 .frame(maxWidth: 820, alignment: .leading)44 .background(P.ink1).overlay { Rectangle().strokeBorder(P.line, lineWidth: 1) }45 .contentShape(Rectangle())46 }47 .buttonStyle(.plain)48 .accessibilityIdentifier("lab.review.strip")49 }50 private var summary: String {51 let checks = review.checks52 let n = { (s: VQReview.Check.Severity) in checks.filter { $0.severity == s }.count }53 switch review.status.known {54 case .running?: return "In progress — \(checks.count) check\(checks.count == 1 ? "" : "s") so far"55 case .error?: return "The reviewer did not finish — \(checks.count) deterministic check\(checks.count == 1 ? "" : "s") available"56 default: return "\(checks.count) findings: \(n(.error)) error\(n(.error) == 1 ? "" : "s"), \(n(.warning)) warning\(n(.warning) == 1 ? "" : "s"), \(n(.info)) informational"57 }58 }59}6061struct LabReviewSheet: View {62 let app: AppEnvironment63 let job: VQQuantJob64 @Environment(\.dismiss) private var dismiss65 @State private var selected: String?66 @State private var starting = false67 @State private var failure: String?68 @State private var confirming = false6970 private var lab: LabStore { app.lab }71 private var reviews: [VQObject<VQReview>] { lab.reviews(of: job.id) }72 private var current: VQObject<VQReview>? { reviews.first { $0.id == selected } ?? reviews.first }73 private var locale: VQNumberLocale { app.vqTheme.numberLocale }7475 var body: some View {76 VStack(spacing: 0) {77 header78 Rectangle().fill(P.line).frame(height: 1)79 ScrollView {80 VStack(alignment: .leading, spacing: S.s6) {81 if let r = current { review(r) }82 else if lab.pendingReviews[job.id] != nil { VQAIActivity("The review was started", detail: "Its deterministic checks arrive first, through sync.").padding(.top, S.s4) }83 else { invitation }84 if let failure { Label(failure, systemImage: "exclamationmark.triangle.fill").vqFont(T.bodySm).foregroundStyle(P.critical).fixedSize(horizontal: false, vertical: true) }85 }86 .padding(S.s6).frame(maxWidth: .infinity, alignment: .leading)87 }88 Rectangle().fill(P.line).frame(height: 1)89 footer90 }91 .frame(width: 760, height: 720)92 .background(P.ink0)93 .accessibilityIdentifier("lab.review.sheet")94 }9596 private var header: some View {97 VStack(alignment: .leading, spacing: S.s2) {98 HStack { LabReviewLabel(); Spacer(); if reviews.count > 1 { picker } }99 Text("Review of \(lab.title(job.tool))\(job.subject.isEmpty ? "" : " · \(job.subject)")").vqFont(T.title).foregroundStyle(P.text1).lineLimit(2)100 Text("Job \(job.id)").vqFont(T.numSm).foregroundStyle(P.text3).textSelection(.enabled)101 }102 .padding(.horizontal, S.s6).padding(.vertical, S.s4)103 .frame(maxWidth: .infinity, alignment: .leading)104 .background(.bar)105 }106107 private var picker: some View {108 Picker("", selection: Binding(get: { current?.id ?? "" }, set: { selected = $0 })) {109 ForEach(reviews) { r in Text(Fmt.dateTime(r.data.startedAt ?? r.createdAt)).tag(r.id) }110 }111 .labelsHidden().controlSize(.small).fixedSize().help("This result was reviewed more than once")112 }113114 private var footer: some View {115 HStack(spacing: S.s3) {116 Text("Deterministic checks compare the text with the stored numbers; the reviewer model can be wrong. Neither replaces a person's review.")117 .vqFont(T.caption).foregroundStyle(P.text3).fixedSize(horizontal: false, vertical: true)118 Spacer(minLength: S.s3)119 if current != nil { Button(starting ? "Starting…" : "Review Again…") { confirming = true }.disabled(starting || current?.data.status == .running || !app.connectivity.isOnline) }120 Button("Done") { dismiss() }.keyboardShortcut(.defaultAction).accessibilityIdentifier("lab.review.done")121 }122 .padding(.horizontal, S.s6).padding(.vertical, S.s3)123 .confirmationDialog("Start an automated review?", isPresented: $confirming) {124 Button("Start the Review") { start() }125 Button("Cancel", role: .cancel) {}126 } message: { Text("The server runs deterministic checks, then a reviewer model that re-queries the data. The model's usage is billed to your account like an analysis.") }127 }128129 private var invitation: some View {130 VStack(alignment: .leading, spacing: S.s4) {131 Text("This result has not been reviewed.").vqFont(T.heading).foregroundStyle(P.text1)132 Text("A review runs in two steps on the server. First deterministic checks: the numbers quoted in the text against the stored results, sample sizes, the backtest engine's look-ahead flags, missing provenance, the wording of p-values and significance. Then a reviewer model re-queries the data with tools and writes its findings and a verdict.")133 .vqFont(T.bodySm).foregroundStyle(P.text2).fixedSize(horizontal: false, vertical: true)134 Text("The second step calls a language model: its usage is billed to your account like an analysis. At most two reviews run at once.")135 .vqFont(T.bodySm).foregroundStyle(P.text2).fixedSize(horizontal: false, vertical: true)136 Button { confirming = true } label: { Label(starting ? "Starting…" : "Start the Automated Review…", systemImage: "checkmark.seal") }137 .disabled(starting || !app.connectivity.isOnline || job.status != .done).accessibilityIdentifier("lab.review.start")138 }139 .frame(maxWidth: 620, alignment: .leading)140 }141142 private func start() {143 starting = true; failure = nil144 Task {145 defer { starting = false }146 do { try await lab.startReview(of: job) }147 catch let e as VQError {148 switch e.kind {149 case .rateLimited: failure = "Two reviews are already running for your account, which is the server's limit. Wait for one to finish."150 case .notFound: failure = "The server found no result to review for this job."151 case .network: failure = "The VQuant server cannot be reached: no review was started."152 default: failure = e.userMessage153 }154 } catch { failure = error.localizedDescription }155 }156 }157158 // MARK: a review159160 @ViewBuilder private func review(_ object: VQObject<VQReview>) -> some View {161 let r = object.data162 let deterministic = r.checks.filter { !$0.isFromReviewerModel }, model = r.checks.filter(\.isFromReviewerModel)163 HStack(spacing: S.s3) {164 status(r)165 Spacer(minLength: 0)166 Text(meta(r)).vqFont(T.numSm).foregroundStyle(P.text3).multilineTextAlignment(.trailing)167 }168 if r.status == .error {169 Label("The reviewer did not finish: \(r.error ?? "no reason given"). The deterministic checks below remain.", systemImage: "exclamationmark.triangle.fill")170 .vqFont(T.bodySm).foregroundStyle(P.critical).fixedSize(horizontal: false, vertical: true)171 }172 section("Deterministic checks", "Run first, without a model", deterministic, empty: "None recorded.")173 if r.status == .running { VQAIActivity("Reviewer model at work", detail: "It re-queries the data with tools; its findings are appended here.") }174 if !model.isEmpty || r.status == .done { section("Reviewer findings", r.model.map { "Model \($0)" } ?? "Reviewer model", model, empty: "The reviewer reported no finding.") }175 if let v = r.verdict, !v.isEmpty {176 VStack(alignment: .leading, spacing: S.s3) {177 VQSectionHeader("Verdict", overline: "Written by the reviewer model")178 VQMarkdownText(v).frame(maxWidth: 680, alignment: .leading)179 }180 }181 if let d = r.disclaimer, !d.isEmpty { Text(d).vqFont(T.caption).foregroundStyle(P.text3) }182 }183184 private func status(_ r: VQReview) -> some View {185 let (word, symbol, color): (String, String, Color) = {186 switch r.status.known {187 case .running?: ("In progress", "hourglass", P.info)188 case .done?: ("Finished", "checkmark.circle", P.text2)189 case .error?: ("Reviewer failed", "xmark.octagon", P.critical)190 case nil: (r.status.rawValue.capitalized, "questionmark.circle", P.warn)191 }192 }()193 return Label(word, systemImage: symbol).vqFont(T.bodySm).fontWeight(.medium).foregroundStyle(color)194 }195196 private func meta(_ r: VQReview) -> String {197 var parts: [String] = []198 if let s = r.startedAt { parts.append(Fmt.dateTime(s)) }199 if let s = r.startedAt, let f = r.finishedAt { parts.append("ran \(LabFormat.duration(f.timeIntervalSince(s)))") }200 if let u = r.usage {201 parts.append("\(VQFormat.tokens(u.inputTokens, locale: locale)) in · \(VQFormat.tokens(u.outputTokens, locale: locale)) out")202 if let c = u.costUsd { parts.append(VQFormat.cost(c, locale: locale)) }203 }204 return parts.joined(separator: " · ")205 }206207 private func severity(_ c: VQReview.Check) -> (symbol: String, color: Color, word: String) {208 switch c.severity.known {209 case .error?: ("xmark.octagon.fill", P.critical, "Error")210 case .warning?: ("exclamationmark.triangle.fill", P.warn, "Warning")211 case .info?: ("checkmark.circle", P.text3, "Info")212 case nil: ("circle.dotted", P.text3, c.severity.rawValue.capitalized)213 }214 }215216 private func section(_ title: String, _ overline: String, _ checks: [VQReview.Check], empty: String) -> some View {217 VStack(alignment: .leading, spacing: S.s2) {218 VQSectionHeader(title, overline: overline) { Text("\(checks.count)").vqFont(T.numSm).foregroundStyle(P.text3) }219 if checks.isEmpty { Text(empty).vqFont(T.bodySm).foregroundStyle(P.text3) }220 ForEach(Array(checks.enumerated()), id: \.offset) { _, c in221 let s = severity(c)222 HStack(alignment: .firstTextBaseline, spacing: S.s3) {223 Image(systemName: s.symbol).font(.system(size: 12)).foregroundStyle(s.color).frame(width: 16).accessibilityHidden(true)224 VStack(alignment: .leading, spacing: 3) {225 HStack(spacing: S.s2) {226 Text(s.word).vqFont(T.overline).foregroundStyle(s.color)227 Text(c.category.rawValue).vqFont(T.overline).foregroundStyle(P.text3)228 Text(c.id).font(.system(size: 9.5, design: .monospaced)).foregroundStyle(P.text3)229 }230 Text(c.finding).vqFont(T.bodySm).foregroundStyle(P.text1).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)231 if let e = c.evidence, !e.isEmpty {232 (Text("Evidence ").fontWeight(.semibold) + Text(VQMarkdown.attributed(e))).vqFont(T.caption).foregroundStyle(P.text2).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)233 }234 }235 Spacer(minLength: 0)236 }237 .padding(.vertical, S.s2)238 .overlay(alignment: .bottom) { Rectangle().fill(P.line).frame(height: 1) }239 .accessibilityElement(children: .combine)240 }241 }242 }243}244