SPB Git

Repository Public

ResearchResultViews.swift 23.2 KB 385 lines swift

1// SP Wallet iOS2// File: Features/Research/ResearchResultViews.swift3// Description: Native rendering of a research job's result. Each part sits under its own header with the badge of its nature and4//              author (`ResearchProvenance`): observed data, estimate, simulation, or analysis generated by an AI agent5//              (statements, not measurements). What the agent claims and what the server measured are two columns, never one6//              figure. The simulated equity curve is drawn with Swift Charts and labelled as a simulation. Generated text is7//              shown as plain text / limited Markdown with every link turned into inert text.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Charts12import SwiftUI13import SPWalletCore1415// MARK: labels (pure)1617enum ResearchLabels {18    static func nature(_ n: ResearchNature) -> String {19        switch n {20        case .observedData: String(localized: "DONNÉES OBSERVÉES")21        case .estimate: String(localized: "ESTIMATION")22        case .simulation: String(localized: "SIMULATION")23        case .generatedAnalysis: String(localized: "ANALYSE GÉNÉRÉE")24        }25    }26    static func author(_ a: ResearchAuthor) -> String {27        switch a {28        case .agent: String(localized: "par un agent IA : des affirmations, pas des mesures")29        case .server: String(localized: "par le serveur du portefeuille")30        case .runner: String(localized: "par l’exécuteur de la tâche, de l’extérieur de l’agent")31        }32    }33    static func icon(_ n: ResearchNature) -> String {34        switch n { case .observedData: "eye.fill"; case .estimate: "function"; case .simulation: "testtube.2"; case .generatedAnalysis: "sparkles" }35    }36    static func tone(_ n: ResearchNature) -> Tone {37        switch n { case .observedData: .info; case .estimate: .neutral; case .simulation: .neutral; case .generatedAnalysis: .warn }38    }39    static let claimed = String(localized: "affirmé par l’agent")40    static let measured = String(localized: "mesuré par le serveur")41    static let footer = String(localized: "Aucune projection n’est une garantie de résultat.")4243    static func state(_ s: ResearchState) -> (String, Tone, String) {44        switch s {45        case .queued: (String(localized: "En file d’attente"), .neutral, "clock")46        case .preparing: (String(localized: "Préparation des données"), .info, "tray.and.arrow.down")47        case .running: (String(localized: "En cours"), .info, "play.circle.fill")48        case .evaluating: (String(localized: "Évaluation par le serveur"), .info, "checklist")49        case .submitted: (String(localized: "Soumise : à examiner, non approuvée"), .warn, "doc.badge.clock")50        case .failed: (String(localized: "Échouée"), .danger, "xmark.circle.fill")51        case .cancelled: (String(localized: "Annulée"), .neutral, "stop.circle")52        case .overBudget: (String(localized: "Budget dépassé"), .danger, "exclamationmark.triangle.fill")53        case .unknown(let x): (x, .neutral, "questionmark.circle")54        }55    }56    static func metric(_ m: String) -> String {57        switch m {58        case "total_return": String(localized: "Rendement total")59        case "sharpe": String(localized: "Ratio de Sharpe")60        case "max_drawdown": String(localized: "Repli maximal")61        case "trades": String(localized: "Transactions")62        default: m63        }64    }65    static func split(_ s: String) -> String {66        switch s {67        case "train": String(localized: "entraînement")68        case "validation": String(localized: "validation")69        case "inner_test": String(localized: "test interne de l’agent")70        case "test": String(localized: "test hors échantillon")71        default: s72        }73    }74    /** A metric value: ratios of return / drawdown as percentages, the rest as plain numbers; nil = « non fourni », never 0. */75    static func value(_ v: Double?, metric: String) -> String {76        guard let v else { return String(localized: "non fourni") }77        switch metric {78        case "total_return", "max_drawdown": return (v * 100).formatted(.number.precision(.fractionLength(2))) + " %"79        case "trades": return v.formatted(.number.precision(.fractionLength(0)))80        default: return v.formatted(.number.precision(.fractionLength(0...3)))81        }82    }83}8485/** One header of the result screen: exactly one provenance per section. */86struct ResearchSectionModel: Identifiable, Equatable {87    enum Kind: Equatable { case holdout, usage, submission, serverSimulation, serverEstimate, comparison, labReport }88    let kind: Kind89    let title: String90    /** nil only for the comparison, which shows two provenances side by side and says so. */91    let provenance: ResearchProvenance?92    var id: String { title }93}9495/** One comparison line: two cells of two natures. There is deliberately no combined value. */96struct ResearchComparisonRow: Identifiable, Equatable {97    let label: String98    let claimed: String99    let measured: String100    let differs: Bool101    var id: String { label }102}103104enum ResearchSections {105    /** The sections of a job's result, in reading order. The server report is split by nature: its backtests, its statistics, the comparison. */106    static func build(_ d: ResearchJobDetail) -> [ResearchSectionModel] {107        var out: [ResearchSectionModel] = []108        for r in d.results {109            switch r {110            case .holdout: out.append(.init(kind: .holdout, title: String(localized: "Découpage des données"), provenance: r.provenance))111            case .usage: out.append(.init(kind: .usage, title: String(localized: "Ressources consommées"), provenance: r.provenance))112            case .submission: out.append(.init(kind: .submission, title: String(localized: "Ce que l’agent a remis"), provenance: r.provenance))113            case .serverReport(let s):114                out.append(.init(kind: .serverSimulation, title: String(localized: "Backtests du serveur"), provenance: ResearchServerReport.provenance))115                if s.deflatedSharpe != nil || s.sharpeCi != nil { out.append(.init(kind: .serverEstimate, title: String(localized: "Statistiques du serveur"), provenance: ResearchServerReport.estimateProvenance)) }116                if let c = s.comparison, !c.isEmpty { out.append(.init(kind: .comparison, title: String(localized: "Affirmé contre mesuré"), provenance: nil)) }117            case .labReport: out.append(.init(kind: .labReport, title: String(localized: "Rapport de laboratoire"), provenance: r.provenance))118            }119        }120        return out121    }122123    static func comparison(_ rows: [ResearchClaimComparison]) -> [ResearchComparisonRow] {124        rows.map { r in125            ResearchComparisonRow(label: ResearchLabels.metric(r.metric) + " · " + ResearchLabels.split(r.split),126                                  claimed: ResearchLabels.value(r.claimed, metric: r.metric), measured: ResearchLabels.value(r.measured, metric: r.metric), differs: r.differs)127        }128    }129130    /** Points of the SIMULATED equity curve: `[[time, value], …]`, time as epoch seconds or ISO 8601. Anything else is skipped, never interpolated. */131    static func equity(_ v: JSONValue?) -> [(date: Date, value: Double)] {132        guard let a = v?.arrayValue else { return [] }133        let iso = ISO8601DateFormatter()134        return a.compactMap { p in135            guard let pair = p.arrayValue, pair.count >= 2, let y = pair[1].doubleValue else { return nil }136            if let t = pair[0].doubleValue { return (Date(timeIntervalSince1970: t > 1e11 ? t / 1000 : t), y) }137            if let s = pair[0].stringValue, let d = iso.date(from: s) { return (d, y) }138            return nil139        }140    }141}142143/** Text written by an AI agent: inline Markdown only, and no tappable link — a URL is shown as text next to its label. */144enum ResearchText {145    static func render(_ s: String) -> AttributedString {146        guard var a = try? AttributedString(markdown: s, options: .init(allowsExtendedAttributes: false, interpretedSyntax: .inlineOnlyPreservingWhitespace, failurePolicy: .returnPartiallyParsedIfPossible)) else { return AttributedString(s) }147        var out = AttributedString()148        for run in a.runs {149            var piece = AttributedString(a[run.range])150            if let url = run.link {151                piece.link = nil152                let shown = String(piece.characters)153                if shown != url.absoluteString { piece.append(AttributedString(" (\(url.absoluteString))")) }154            }155            piece.imageURL = nil156            out.append(piece)157        }158        a = out159        return a160    }161}162163// MARK: views164165struct ProvenanceBadge: View {166    let provenance: ResearchProvenance167    var body: some View {168        VStack(alignment: .leading, spacing: 3) {169            Pill(text: ResearchLabels.nature(provenance.nature), tone: ResearchLabels.tone(provenance.nature), icon: ResearchLabels.icon(provenance.nature))170            Text(ResearchLabels.author(provenance.author)).font(.system(size: 12)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)171        }172        .accessibilityElement(children: .combine)173    }174}175176struct ResearchResultsView: View {177    let detail: ResearchJobDetail178179    var body: some View {180        ForEach(ResearchSections.build(detail)) { s in181            VStack(alignment: .leading, spacing: 10) {182                Text(s.title).font(.spHeadline).foregroundStyle(Theme.ink).accessibilityAddTraits(.isHeader)183                if let p = s.provenance { ProvenanceBadge(provenance: p) }184                content(s.kind)185            }186            .spCard(padding: 16)187            .accessibilityIdentifier("research.section.\(String(describing: s.kind))")188        }189    }190191    @ViewBuilder private func content(_ k: ResearchSectionModel.Kind) -> some View {192        switch k {193        case .holdout: if let h = detail.holdout { HoldoutBody(h: h) }194        case .usage: if let u = detail.job.usage { UsageBody(u: u, budgets: detail.job.budgets) }195        case .submission: if let s = detail.submission { SubmissionBody(s: s) }196        case .serverSimulation: if let s = detail.server { ServerSimulationBody(s: s) }197        case .serverEstimate: if let s = detail.server { ServerEstimateBody(s: s) }198        case .comparison: if let s = detail.server, let c = s.comparison { ComparisonBody(rows: ResearchSections.comparison(c), claimsDiffer: s.claimsDiffer, problem: s.claimsProblem) }199        case .labReport: if let r = detail.report { LabReportBody(r: r, capitalUsd: detail.job.capitalUsd) }200        }201    }202}203204private struct HoldoutBody: View {205    let h: ResearchHoldout206    var body: some View {207        VStack(alignment: .leading, spacing: 0) {208            FieldRow(label: String(localized: "Données vues par l’agent"), value: "\(h.start) → \(h.devEnd) · " + String(localized: "\(h.devBars) barres")); Divider()209            FieldRow(label: String(localized: "Test du serveur, jamais vu par l’agent"), value: "\(h.devEnd) → \(h.end) · " + String(localized: "\(h.testBars) barres"))210        }211    }212}213214private struct UsageBody: View {215    let u: ResearchUsage216    let budgets: ResearchBudgets217    var body: some View {218        VStack(alignment: .leading, spacing: 0) {219            FieldRow(label: String(localized: "Durée"), value: String(localized: "\(u.wallMs / 1000) s sur \(budgets.wallSeconds) s")); Divider()220            FieldRow(label: String(localized: "Essais"), value: String(localized: "\(u.trials) sur \(budgets.maxTrials)")); Divider()221            FieldRow(label: String(localized: "Jetons du modèle"), value: String(localized: "\(u.modelTokens) sur \(budgets.maxModelTokens)")); Divider()222            FieldRow(label: String(localized: "Coût du modèle (USD)"), value: u.modelUsd.map { $0.formatted(.number.precision(.fractionLength(2...4))) + " " + String(localized: "sur") + " " + budgets.maxModelUsd.formatted() } ?? String(localized: "non rapporté par l’agent")); Divider()223            FieldRow(label: String(localized: "Confinement de l’agent"), value: u.sandbox == "none" ? String(localized: "aucun : l’agent n’était PAS confiné") : u.sandbox, tone: u.sandbox == "none" ? .danger : nil)224            if u.ledgerTampered { Notice(tone: .danger, title: String(localized: "Registre des essais altéré"), message: String(localized: "Le fichier des essais de l’agent a été tronqué ou réécrit pendant sa copie.")) }225        }226    }227}228229private struct SubmissionBody: View {230    let s: ResearchSubmission231    var body: some View {232        VStack(alignment: .leading, spacing: 10) {233            Notice(tone: .warn, title: String(localized: "Texte et chiffres non vérifiés"), message: String(localized: "Tout ce bloc a été écrit par l’agent. Seules les sections « du serveur » sont des mesures."))234            if let c = s.claims {235                if let sum = c.summary, !sum.isEmpty { Text(ResearchText.render(sum)).font(.spCallout).foregroundStyle(Theme.ink).textSelection(.enabled).fixedSize(horizontal: false, vertical: true) }236                ClaimsTable(title: ResearchLabels.claimed, splits: [("train", c.train), ("validation", c.validation), ("inner_test", c.innerTest)])237                if let t = c.trials { FieldRow(label: String(localized: "Essais déclarés par l’agent"), value: String(t)) }238            }239            if let p = s.claimsProblem { Notice(tone: .warn, title: String(localized: "Déclarations de l’agent ignorées"), message: p) }240            ForEach(s.files.keys.sorted(), id: \.self) { name in241                DisclosureGroup {242                    Group {243                        if name.hasSuffix(".md") { Text(ResearchText.render(s.files[name] ?? "")).font(.spCallout) }244                        else { Text(s.files[name] ?? "").font(.system(size: 11.5, design: .monospaced)) }245                    }246                    .foregroundStyle(Theme.ink).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).padding(.top, 6)247                } label: { Text(name).font(.spMono) }248            }249            FieldRow(label: String(localized: "SHA-256 de strategy.py"), value: s.sha256, mono: true, copyable: true)250        }251    }252}253254/** A grid of split × metric for ONE author. */255private struct ClaimsTable: View {256    let title: String257    let splits: [(String, ResearchSplitMetrics?)]258    private static let metrics: [(String, KeyPath<ResearchSplitMetrics, Double?>)] = [("total_return", \.totalReturn), ("sharpe", \.sharpe), ("max_drawdown", \.maxDrawdown), ("trades", \.trades)]259    var body: some View {260        let present = splits.filter { $0.1 != nil }261        if !present.isEmpty {262            VStack(alignment: .leading, spacing: 6) {263                Text(title).spEyebrow()264                Grid(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 6) {265                    GridRow { Text(""); ForEach(present, id: \.0) { Text(ResearchLabels.split($0.0)).font(.system(size: 11.5, weight: .semibold)).foregroundStyle(Theme.mute).gridColumnAlignment(.trailing) } }266                    ForEach(Self.metrics, id: \.0) { m in267                        GridRow {268                            Text(ResearchLabels.metric(m.0)).font(.system(size: 13)).foregroundStyle(Theme.ink)269                            ForEach(present, id: \.0) { sp in Text(ResearchLabels.value(sp.1?[keyPath: m.1], metric: m.0)).font(.system(size: 13, weight: .medium)).monospacedDigit().foregroundStyle(Theme.ink) }270                        }271                    }272                }273            }274        }275    }276}277278private struct ServerSimulationBody: View {279    let s: ResearchServerReport280    var body: some View {281        VStack(alignment: .leading, spacing: 10) {282            if s.isOK { Pill(text: String(localized: "évaluation du serveur : ok"), tone: .ok, icon: "checkmark") }283            else { Notice(tone: .danger, title: String(localized: "Pas de rapport du serveur (\(s.status))"), message: (s.reason ?? "") + " " + String(localized: "Sans lui, la stratégie ne peut pas être approuvée.")) }284            Text(String(localized: "Ce qu’une stratégie AURAIT fait sur des données enregistrées. Ce ne sont pas des résultats de négociation.")).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)285            if let m = s.metrics { ClaimsTable(title: ResearchLabels.measured, splits: [("train", m.train), ("validation", m.validation), ("test", m.test)]) }286            if let b = s.benchmark { ClaimsTable(title: String(localized: "référence passive, même période de test"), splits: [("test", b)]) }287            if let r = s.replication { ClaimsTable(title: String(localized: "évaluation standard refaite par le serveur"), splits: [("train", r.train), ("validation", r.validation), ("inner_test", r.innerTest)]) }288            if let h = s.holdout { FieldRow(label: String(localized: "Période de test"), value: "\(h.testStart) → \(h.testEnd) · " + String(localized: "\(h.bars) barres")) }289            if let t = s.trials {290                FieldRow(label: String(localized: "Essais (tâche + serveur)"), value: "\(t.job) + \(t.server) = \(t.total)")291                if t.ledgerTampered { Notice(tone: .danger, title: String(localized: "Registre des essais altéré")) }292            }293            if s.sandbox == "none" { Notice(tone: .warn, title: String(localized: "Évaluation non confinée"), message: String(localized: "La plateforme n’offrait aucun bac à sable.")) }294            if let c = s.checks, !c.isEmpty { DisclosureGroup(String(localized: "Contrôles du serveur")) { JSONFields(value: .object(c)) }.font(.spCallout) }295        }296    }297}298299private struct ServerEstimateBody: View {300    let s: ResearchServerReport301    var body: some View {302        VStack(alignment: .leading, spacing: 0) {303            Text(String(localized: "Des statistiques avec incertitude, calculées sur les essais et par rééchantillonnage. Pas une prévision.")).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true).padding(.bottom, 4)304            if let d = s.deflatedSharpe { FieldRow(label: String(localized: "Sharpe déflaté (corrigé du nombre d’essais)"), value: d.formatted(.number.precision(.fractionLength(0...3)))) }305            if let ci = s.sharpeCi {306                let lo = ci.first.flatMap { $0 }, hi = ci.count > 1 ? ci[1] : nil307                Divider()308                FieldRow(label: String(localized: "Intervalle de confiance du Sharpe (bootstrap)"),309                         value: "[" + (lo.map { $0.formatted(.number.precision(.fractionLength(0...3))) } ?? String(localized: "borne absente")) + " ; " + (hi.map { $0.formatted(.number.precision(.fractionLength(0...3))) } ?? String(localized: "borne absente")) + "]")310            }311        }312    }313}314315private struct ComparisonBody: View {316    let rows: [ResearchComparisonRow]317    let claimsDiffer: Bool?318    let problem: String?319    var body: some View {320        VStack(alignment: .leading, spacing: 10) {321            Text(String(localized: "Deux colonnes de deux natures, sur les mêmes données : elles ne sont jamais fusionnées ni moyennées.")).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)322            if claimsDiffer == true { Notice(tone: .danger, title: String(localized: "Les chiffres de l’agent diffèrent de ceux du serveur")) }323            if let problem { Notice(tone: .warn, title: String(localized: "Déclarations de l’agent ignorées"), message: problem) }324            ForEach(rows) { r in325                Divider()326                VStack(alignment: .leading, spacing: 6) {327                    HStack(spacing: 8) {328                        Text(r.label).font(.system(size: 13.5, weight: .semibold)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)329                        if r.differs { Label(String(localized: "diffère"), systemImage: "exclamationmark.triangle.fill").font(.system(size: 11.5, weight: .semibold)).foregroundStyle(Theme.danger) }330                    }331                    HStack(alignment: .top, spacing: 12) {332                        cell(ResearchLabels.claimed, .generatedAnalysis, r.claimed)333                        cell(ResearchLabels.measured, .simulation, r.measured)334                    }335                }336            }337        }338    }339340    /** One value with its own author and nature written above it. */341    private func cell(_ author: String, _ nature: ResearchNature, _ value: String) -> some View {342        VStack(alignment: .leading, spacing: 2) {343            Text(author).font(.system(size: 11.5, weight: .semibold)).foregroundStyle(Theme.mute)344            Label(ResearchLabels.nature(nature), systemImage: ResearchLabels.icon(nature)).font(.system(size: 10.5, weight: .semibold)).foregroundStyle(ResearchLabels.tone(nature).color)345            Text(value).font(.system(size: 15, weight: .semibold)).monospacedDigit().foregroundStyle(Theme.ink)346        }347        .frame(maxWidth: .infinity, alignment: .leading)348        .accessibilityElement(children: .combine)349    }350}351352private struct LabReportBody: View {353    let r: ResearchLabReport354    let capitalUsd: Double355    var body: some View {356        let points = ResearchSections.equity(r.equityCurve)357        VStack(alignment: .leading, spacing: 10) {358            if points.count >= 2 {359                Chart {360                    ForEach(Array(points.enumerated()), id: \.offset) { _, p in361                        LineMark(x: .value(String(localized: "Date"), p.date), y: .value(String(localized: "Valeur simulée (USD)"), p.value)).foregroundStyle(Theme.series[0]).interpolationMethod(.linear)362                    }363                }364                .chartYScale(domain: .automatic(includesZero: false))365                .chartXAxis { AxisMarks(values: .automatic(desiredCount: 4)) }366                .chartYAxis { AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) }367                .frame(height: 190)368                .accessibilityLabel(String(localized: "Courbe de valeur simulée du backtest"))369                .accessibilityIdentifier("research.equityChart")370                HStack(alignment: .top, spacing: 8) {371                    Pill(text: ResearchLabels.nature(.simulation), tone: ResearchLabels.tone(.simulation), icon: ResearchLabels.icon(.simulation))372                    Text(String(localized: "Valeur SIMULÉE du backtest sur la période de test, à partir d’un capital virtuel de \(Money.fiat(capitalUsd, .usd)). Ce n’est l’historique d’aucun compte. \(points.count) points, du \(points[0].date.formatted(date: .abbreviated, time: .omitted)) au \(points[points.count - 1].date.formatted(date: .abbreviated, time: .omitted))."))373                        .font(.system(size: 12)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)374                }375            } else { Text(String(localized: "Le rapport ne contient pas de courbe de valeur exploitable.")).font(.spFootnote).foregroundStyle(Theme.mute) }376            ForEach(parts, id: \.0) { title, v in DisclosureGroup(title) { JSONFields(value: v) }.font(.spCallout) }377        }378    }379    private var parts: [(String, JSONValue)] {380        [(String(localized: "Métriques (simulation)"), r.metrics), (String(localized: "Références passives (simulation)"), r.benchmarks), (String(localized: "Robustesse"), r.robustness),381         (String(localized: "Contrôles"), r.checks), (String(localized: "Découpages"), r.splits), (String(localized: "Configuration"), r.config)]382            .compactMap { t, v in v.flatMap { $0.isNull ? nil : (t, $0) } }383    }384}385
Files main
Menu

Theme