SPB Git

Repository Public

ReportViews.swift 18.1 KB 390 lines swift

1//2//  VQuant iOS3//  File: VQuant/Features/Research/ReportViews.swift4//  Description: Native rendering of a research report: Markdown blocks, tables, server figures, VQuant markers,5//               sources, and the audit trail (tools, parameters, Python code).6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import SwiftUI1213// MARK: - Markdown1415struct MarkdownView: View {16    let text: String17    /// base64 copies of figures kept with the conversation, by server path.18    var embedded: [String: String] = [:]1920    var body: some View {21        // Parsing is cached per text: a streaming report re-parses only when it grows.22        MarkdownBlocksView(blocks: MarkdownCache.shared.blocks(text), embedded: embedded)23    }24}2526@MainActor27final class MarkdownCache {28    static let shared = MarkdownCache()29    private var store: [Int: (String, [MarkdownBlock])] = [:]30    func blocks(_ text: String) -> [MarkdownBlock] {31        let key = text.hashValue32        if let hit = store[key], hit.0 == text { return hit.1 }33        let blocks = MarkdownParser.parse(text)34        if store.count > 64 { store.removeAll(keepingCapacity: true) }35        store[key] = (text, blocks)36        return blocks37    }38}3940struct MarkdownBlocksView: View {41    let blocks: [MarkdownBlock]42    var embedded: [String: String] = [:]43    var body: some View {44        VStack(alignment: .leading, spacing: 12) {45            ForEach(Array(blocks.enumerated()), id: \.offset) { _, block in MarkdownBlockView(block: block, embedded: embedded) }46        }47        .frame(maxWidth: .infinity, alignment: .leading)48    }49}5051struct MarkdownBlockView: View {52    let block: MarkdownBlock53    var embedded: [String: String] = [:]5455    var body: some View {56        switch block {57        case .heading(let level, let text):58            InlineText(text).font(headingFont(level)).fontWeight(.semibold).padding(.top, level <= 2 ? 6 : 2)59                .accessibilityAddTraits(.isHeader)60        case .paragraph(let text):61            if let img = ReportText.image(in: text) { FigureView(reference: img, embedded: embedded[img.url]) }62            else { InlineText(text).font(.body).lineSpacing(3) }63        case .code(let language, let code, _):64            CodeBlock(language: language, code: code)65        case .quote(let inner):66            HStack(alignment: .top, spacing: 10) {67                RoundedRectangle(cornerRadius: 2).fill(Theme.orange.opacity(0.7)).frame(width: 3)68                MarkdownBlocksView(blocks: inner, embedded: embedded).foregroundStyle(Theme.textSecondary)69            }70        case .list(let ordered, let start, let items):71            VStack(alignment: .leading, spacing: 6) {72                ForEach(Array(items.enumerated()), id: \.offset) { i, item in73                    HStack(alignment: .firstTextBaseline, spacing: 8) {74                        Group {75                            if let checked = item.checked { Image(systemName: checked ? "checkmark.square" : "square") }76                            else { Text(ordered ? "\(start + i)." : "•") }77                        }78                        .font(.body.monospacedDigit()).foregroundStyle(Theme.textSecondary).frame(minWidth: 18, alignment: .trailing)79                        MarkdownBlocksView(blocks: item.blocks, embedded: embedded)80                    }81                }82            }83        case .table(let header, let alignments, let rows):84            MarkdownTable(header: header, alignments: alignments, rows: rows)85        case .math(let latex):86            ScrollView(.horizontal, showsIndicators: false) { Text(latex).font(.system(.callout, design: .monospaced)).padding(10) }87                .background(Theme.surface2, in: RoundedRectangle(cornerRadius: 8))88                .accessibilityLabel("Formule : \(latex)")89        case .rule:90            Divider()91        }92    }9394    private func headingFont(_ level: Int) -> Font {95        switch level { case 1: .title2; case 2: .title3; case 3: .headline; default: .subheadline }96    }97}9899/// Inline Markdown (bold, italic, code, links) with VQuant markers drawn as SF Symbols.100struct InlineText: View {101    let source: String102    init(_ source: String) { self.source = source }103104    var body: some View {105        ReportText.pieces(source).reduce(Text("")) { acc, piece in106            switch piece {107            case .text(let t): return acc + Text(Self.attributed(t))108            case .marker(let name):109                let m = ReportText.markers[name]!110                return acc + Text(Image(systemName: m.symbol)).foregroundStyle(Self.markerColor(name)).accessibilityLabel(m.label)111            }112        }113        .textSelection(.enabled)114        .fixedSize(horizontal: false, vertical: true)115    }116117    static func attributed(_ s: String) -> AttributedString {118        let opts = AttributedString.MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace, failurePolicy: .returnPartiallyParsedIfPossible)119        var a = (try? AttributedString(markdown: s, options: opts)) ?? AttributedString(s)120        for run in a.runs where run.link != nil {121            // Only web links are tappable; anything else the model wrote stays plain text.122            if let scheme = run.link?.scheme, scheme == "https" || scheme == "http" { a[run.range].foregroundColor = Theme.orange } else { a[run.range].link = nil }123        }124        return a125    }126127    static func markerColor(_ name: String) -> Color {128        switch name {129        case "up", "bull", "check": Theme.up130        case "down", "bear", "cross", "risk": Theme.down131        case "warn", "idea", "gold": Theme.warning132        case "flat", "clock", "silver": Theme.textSecondary133        default: Theme.orange134        }135    }136}137138struct MarkdownTable: View {139    let header: [String]140    let alignments: [ColumnAlignment]141    let rows: [[String]]142143    var body: some View {144        ScrollView(.horizontal, showsIndicators: true) {145            Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 8) {146                GridRow {147                    ForEach(Array(header.enumerated()), id: \.offset) { i, h in148                        InlineText(h).font(.footnote.weight(.semibold)).gridColumnAlignment(alignment(i))149                    }150                }151                Divider().gridCellUnsizedAxes(.horizontal)152                ForEach(Array(rows.enumerated()), id: \.offset) { _, row in153                    GridRow(alignment: .top) {154                        ForEach(Array(header.indices), id: \.self) { i in155                            InlineText(i < row.count ? row[i] : "").font(.footnote.monospacedDigit()).frame(maxWidth: 260, alignment: frameAlignment(i))156                        }157                    }158                }159            }160            .padding(12)161        }162        .background(Theme.surface, in: RoundedRectangle(cornerRadius: 10, style: .continuous))163        .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(Theme.border, lineWidth: 0.5))164        .accessibilityElement(children: .contain)165        .accessibilityLabel("Tableau de \(rows.count) lignes : \(header.joined(separator: ", "))")166    }167    private func alignment(_ i: Int) -> HorizontalAlignment {168        guard i < alignments.count else { return .leading }169        switch alignments[i] { case .leading: return .leading; case .center: return .center; case .trailing: return .trailing }170    }171    private func frameAlignment(_ i: Int) -> Alignment {172        guard i < alignments.count else { return .leading }173        switch alignments[i] { case .leading: return .leading; case .center: return .center; case .trailing: return .trailing }174    }175}176177struct CodeBlock: View {178    var language: String?179    let code: String180    var body: some View {181        VStack(alignment: .leading, spacing: 0) {182            HStack {183                Text(language ?? "code").font(.caption2.weight(.semibold)).foregroundStyle(Theme.textSecondary)184                Spacer()185                Button { UIPasteboard.general.string = code; Haptics.tap() } label: { Label("Copier", systemImage: "doc.on.doc").font(.caption2) }186            }187            .padding(.horizontal, 10).padding(.vertical, 6)188            Divider()189            ScrollView(.horizontal, showsIndicators: false) {190                Text(code).font(.system(.caption, design: .monospaced)).textSelection(.enabled).padding(10)191            }192        }193        .background(Theme.surface2, in: RoundedRectangle(cornerRadius: 10, style: .continuous))194    }195}196197// MARK: - Figures198199/// Images produced by the server's Python tools. Decoded off the main actor and kept in memory.200actor FigureStore {201    static let shared = FigureStore()202    private var cache = NSCache<NSString, UIImage>()203    private var inflight: [String: Task<UIImage?, Never>] = [:]204205    func image(path: String, embedded: String?, api: VQuantAPI, disk: DiskCache) async -> UIImage? {206        if let hit = cache.object(forKey: path as NSString) { return hit }207        if let t = inflight[path] { return await t.value }208        let task = Task<UIImage?, Never> {209            var data: Data?210            if path.hasPrefix("/figures/") || path.hasPrefix("/plots/") {211                data = try? await api.file(path)212                if let data { await disk.save("figure:\(path)", data) }      // kept for offline reading of the report213                else { data = await disk.load("figure:\(path)")?.data }214            }215            // The file left the server (old conversation): fall back to the copy stored with the conversation.216            if data == nil, let embedded { data = Data(base64Encoded: embedded.components(separatedBy: ",").last ?? embedded) }217            return data.flatMap { UIImage(data: $0) }218        }219        inflight[path] = task220        let img = await task.value221        inflight[path] = nil222        if let img { cache.setObject(img, forKey: path as NSString) }223        return img224    }225}226227struct FigureView: View {228    let reference: ReportText.ImageReference229    var embedded: String?230    @Environment(AppModel.self) private var model231    @State private var image: UIImage?232    @State private var failed = false233    @State private var zoomed = false234235    var body: some View {236        VStack(alignment: .leading, spacing: 6) {237            if let image {238                Image(uiImage: image).resizable().aspectRatio(contentMode: .fit)239                    .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))240                    .onTapGesture { zoomed = true }241                    .draggable(Image(uiImage: image))             // a figure can be dragged out to Notes, Mail, Files…242                    .hoverEffect(.lift)243                    .accessibilityLabel(reference.alt.isEmpty ? "Figure du rapport" : "Figure : \(reference.alt)")244                    .accessibilityAddTraits(.isButton)245            } else if failed {246                Label("Figure indisponible (\(model.network.isOnline ? "le fichier n’est plus sur le serveur" : "hors ligne"))", systemImage: "photo.badge.exclamationmark")247                    .font(.footnote).foregroundStyle(Theme.textSecondary).frame(maxWidth: .infinity, minHeight: 80).background(Theme.surface2, in: RoundedRectangle(cornerRadius: 10))248            } else {249                ProgressView().frame(maxWidth: .infinity, minHeight: 160).background(Theme.surface2, in: RoundedRectangle(cornerRadius: 10))250            }251            if !reference.alt.isEmpty { Text(reference.alt).font(.caption).foregroundStyle(Theme.textSecondary) }252        }253        .task(id: reference.url) {254            image = await FigureStore.shared.image(path: reference.url, embedded: embedded, api: model.api, disk: model.cache)255            failed = image == nil256        }257        .fullScreenCover(isPresented: $zoomed) { if let image { FigureZoom(image: image, caption: reference.alt) } }258    }259}260261struct FigureZoom: View {262    let image: UIImage263    let caption: String264    @Environment(\.dismiss) private var dismiss265    @State private var scale: CGFloat = 1266    @State private var base: CGFloat = 1267268    var body: some View {269        NavigationStack {270            ScrollView([.horizontal, .vertical]) {271                Image(uiImage: image).resizable().aspectRatio(contentMode: .fit)272                    .containerRelativeFrame([.horizontal, .vertical]) { length, _ in length * scale }273            }274            .gesture(MagnifyGesture().onChanged { scale = min(6, max(1, base * $0.magnification)) }.onEnded { _ in base = scale })275            .onTapGesture(count: 2) { withAnimation { scale = scale > 1 ? 1 : 2.5; base = scale } }276            .background(.black)277            .navigationTitle(caption.isEmpty ? "Figure" : caption).navigationBarTitleDisplayMode(.inline)278            .toolbar {279                ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } }280                ToolbarItem(placement: .primaryAction) { ShareLink(item: Image(uiImage: image), preview: SharePreview(caption.isEmpty ? "Figure VQuant" : caption, image: Image(uiImage: image))) }281            }282        }283    }284}285286// MARK: - A complete exchange287288/// A question and its report, with sources and the audit trail.289struct ExchangeView: View {290    let exchange: Exchange291    var streaming = false292293    private var embedded: [String: String] {294        var map: [String: String] = [:]295        for batch in exchange.figures { for (i, url) in batch.figureUrls.enumerated() where i < batch.figures.count && !batch.figures[i].hasPrefix("/") { map[url] = batch.figures[i] } }296        return map297    }298299    /// The question card is drawn only when there is a question: the live study view shows the question in its own300    /// header and passes none here, and a block with nothing in it must not be rendered.301    static func showsQuestion(_ exchange: Exchange) -> Bool { !exchange.question.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }302    /// Likewise for the answer: no Markdown block for an empty answer.303    static func showsAnswer(_ exchange: Exchange) -> Bool { !exchange.answer.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }304305    var body: some View {306        VStack(alignment: .leading, spacing: 14) {307            if Self.showsQuestion(exchange) {308                Text(exchange.question)309                    .font(.callout.weight(.medium))310                    .padding(12).frame(maxWidth: .infinity, alignment: .leading)311                    .background(Theme.surface2, in: RoundedRectangle(cornerRadius: 12, style: .continuous))312                    .textSelection(.enabled)313                    .accessibilityLabel("Question : \(exchange.question)")314                    .accessibilityIdentifier("exchange-question")315            }316            if exchange.answer.isEmpty && streaming {317                HStack(spacing: 8) { ProgressView().controlSize(.small); Text("L’agent travaille sur le serveur…").font(.footnote).foregroundStyle(Theme.textSecondary) }318            } else if Self.showsAnswer(exchange) {319                MarkdownView(text: exchange.answer, embedded: embedded)320            }321            if !streaming {322                // Figures the report did not place inline are still shown: nothing the tools produced is hidden.323                let inline = Set(ReportText.images(in: exchange.answer).map(\.url))324                let extra = exchange.figures.flatMap(\.figureUrls).filter { !inline.contains($0) }325                if !extra.isEmpty {326                    DisclosureGroup("Figures supplémentaires (\(extra.count))") {327                        ForEach(extra, id: \.self) { FigureView(reference: .init(alt: "", url: $0), embedded: embedded[$0]) }328                    }329                    .font(.subheadline)330                }331                if !exchange.sources.isEmpty { SourcesView(sources: exchange.sources) }332                AuditTrail(exchange: exchange)333            }334        }335    }336}337338struct SourcesView: View {339    let sources: [SourceLink]340    var body: some View {341        DisclosureGroup("Sources (\(sources.count))") {342            VStack(alignment: .leading, spacing: 8) {343                ForEach(sources) { s in344                    if let url = URL(string: s.url), url.scheme == "https" || url.scheme == "http" {345                        Link(destination: url) {346                            VStack(alignment: .leading, spacing: 2) {347                                Text(s.title).font(.footnote.weight(.medium)).multilineTextAlignment(.leading)348                                Text(url.host() ?? s.url).font(.caption2).foregroundStyle(Theme.textSecondary)349                            }350                            .frame(maxWidth: .infinity, alignment: .leading)351                        }352                    }353                }354            }355            .padding(.top, 6)356        }357        .font(.subheadline)358    }359}360361/// What the report rests on: each tool the agent called with what it returned, and the Python code it ran.362struct AuditTrail: View {363    let exchange: Exchange364    var body: some View {365        if !exchange.toolResults.isEmpty || exchange.pythonCode?.isEmpty == false {366            DisclosureGroup("Données et calculs (\(exchange.toolResults.count) appel\(exchange.toolResults.count > 1 ? "s" : ""))") {367                VStack(alignment: .leading, spacing: 8) {368                    ForEach(Array(exchange.toolResults.enumerated()), id: \.offset) { _, t in369                        DisclosureGroup(t.tool) {370                            ScrollView(.horizontal, showsIndicators: false) {371                                Text(t.result.prettyPrinted(limit: 4000)).font(.system(.caption2, design: .monospaced)).textSelection(.enabled)372                            }373                        }374                        .font(.footnote)375                    }376                    if let code = exchange.pythonCode, !code.isEmpty { CodeBlock(language: "python", code: code) }377                    ForEach(exchange.figures.filter { !($0.output ?? "").isEmpty }) { b in378                        DisclosureGroup("Sortie du carnet\(b.description.map { " — \($0)" } ?? "")") {379                            ScrollView(.horizontal, showsIndicators: false) { Text(b.output ?? "").font(.system(.caption2, design: .monospaced)).textSelection(.enabled) }380                        }381                        .font(.footnote)382                    }383                }384                .padding(.top, 6)385            }386            .font(.subheadline)387        }388    }389}390
Files main
Menu

Theme