SPB Git

Repository Public

ResearchWorkspaceViews.swift 35.2 KB 578 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantUI/Research/ResearchWorkspaceViews.swift3// Description: Figures grid (zoom, PNG / SVG / PDF), files browser with previews, environment and sandbox panel, and4//              the convenience container that arranges every piece.5import SwiftUI6import VQuantKit78// MARK: figures910public enum ResearchFigureFormat: String, Sendable, Hashable, CaseIterable { case png, svg, pdf }1112/// The figures of the study. A tile opens the figure large (pinch or scroll to zoom); each export the agent saved13/// (PNG, SVG, PDF) is handed to the app as bytes — the app decides between a save panel and a share sheet.14public struct ResearchFiguresGrid: View {15    private let figures: [VQResearchState.Figure]16    private let onExport: ((VQResearchState.Figure, ResearchFigureFormat, Data) -> Void)?17    @State private var zoomed: VQResearchState.Figure?18    @State private var exporting: String?19    @Environment(\.vqTheme) private var theme20    @Environment(\.researchDataSource) private var source21    @Environment(\.researchPreload) private var preload2223    public init(_ figures: [VQResearchState.Figure], onExport: ((VQResearchState.Figure, ResearchFigureFormat, Data) -> Void)? = nil) { self.figures = figures; self.onExport = onExport }2425    private func path(_ f: VQResearchState.Figure, _ format: ResearchFigureFormat) -> String? {26        switch format { case .png: return f.files?.png; case .svg: return f.files?.svg; case .pdf: return f.files?.pdf }27    }2829    @ViewBuilder private func picture(_ f: VQResearchState.Figure) -> some View {30        if let png = f.files?.png {31            let source = self.source32            ResearchLoader(id: png, preloaded: preload.data[png], load: { try await source.fileData(png) }, content: { data in33                if let image = VQImageData.image(data, label: f.title ?? "Figure") { image.resizable().interpolation(.high).scaledToFit() }34                else { Label(theme.l("Unreadable image"), systemImage: "photo").vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3) }35            }, placeholder: { VQSkeletonChart(height: 120) })36        } else {37            Label(theme.l("Image not kept in the workspace"), systemImage: "photo").vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3)38        }39    }4041    /// The linter's verdict. `fixed` is the ordinary case (nearly every figure gets an automatic contrast repair): it is42    /// shown as quietly as `passed`. Only `issues` asks for attention; "not kept" is for studies older than the record.43    private func lint(_ f: VQResearchState.Figure) -> some View {44        let left = f.lintStatus == nil ? f.openIssues.count : f.findings.filter { $0.severity != "info" }.count45        return Group {46            switch (f.lintStatus?.known, f.lintPassed) {47            case (.passed?, _): Label(theme.l("visual check passed"), systemImage: "checkmark.circle").foregroundStyle(VQP.text3)48            case (.fixed?, _): Label(theme.l("check passed · %lld auto-repairs", f.fixes.count), systemImage: "checkmark.circle").foregroundStyle(VQP.text3)49            case (.issues?, _), (nil, false?): Label(theme.l("%lld defects left", max(1, left)), systemImage: "exclamationmark.triangle").foregroundStyle(VQP.warn)50            case (nil, true?): Label(theme.l("visual check passed"), systemImage: "checkmark.circle").foregroundStyle(VQP.text3)51            case (nil, nil): Label(theme.l("visual check not kept"), systemImage: "circle.dotted").foregroundStyle(VQP.text3)52            }53        }54        .font(.system(size: 11.5))55        .labelStyle(VQCompactLabelStyle())56    }5758    private func exports(_ f: VQResearchState.Figure) -> some View {59        HStack(spacing: 6) {60            ForEach(ResearchFigureFormat.allCases, id: \.self) { format in61                if let p = path(f, format) {62                    Button {63                        exporting = p64                        let source = self.source, cached = preload.data[p]65                        Task {66                            if let data = cached != nil ? cached : try? await source.fileData(p) { onExport?(f, format, data) }67                            exporting = nil68                        }69                    } label: {70                        Text(format.rawValue.uppercased()).font(.system(size: 9.5, weight: .semibold, design: .monospaced)).foregroundStyle(VQP.text2)71                            .padding(.horizontal, 6).padding(.vertical, 3).overlay(RoundedRectangle(cornerRadius: 4).strokeBorder(VQP.lineStrong, lineWidth: 1))72                            .opacity(exporting == p ? 0.4 : 1)73                    }74                    .buttonStyle(.plain).disabled(onExport == nil || exporting != nil)75                    .accessibilityLabel(theme.l("Export as %1$@", "\(format.rawValue.uppercased())"))76                }77            }78        }79    }8081    public var body: some View {82        VStack(alignment: .leading, spacing: VQS.s4) {83            LazyVGrid(columns: [GridItem(.adaptive(minimum: 260, maximum: 520), spacing: VQS.s4, alignment: .top)], alignment: .leading, spacing: VQS.s5) {84                ForEach(Array(figures.enumerated()), id: \.element.key) { i, f in85                    VStack(alignment: .leading, spacing: VQS.s2) {86                        Button { zoomed = f } label: {87                            picture(f).frame(maxWidth: .infinity, minHeight: 120).background(Color.white.opacity(0.001))88                                .clipShape(RoundedRectangle(cornerRadius: VQTokens.Radius.sm, style: .continuous))89                                .overlay(RoundedRectangle(cornerRadius: VQTokens.Radius.sm, style: .continuous).strokeBorder(VQP.line, lineWidth: 1))90                        }91                        .buttonStyle(.plain)92                        .accessibilityLabel(theme.l("Enlarge figure %1$@: %2$@", "\(i + 1)", "\(f.title ?? "")"))93                        Text("FIG. \(i + 1)").font(.system(size: 9.5, weight: .medium, design: .monospaced)).foregroundStyle(VQP.text3)94                        if let title = f.caption ?? f.title { Text(title).font(.system(size: 12.5, design: .serif).italic()).foregroundStyle(VQP.text1).lineLimit(3).fixedSize(horizontal: false, vertical: true) }95                        HStack(alignment: .center) { lint(f); Spacer(minLength: VQS.s2); exports(f) }96                        ForEach(Array((f.lintStatus == nil ? f.openIssues : f.findings.filter { $0.severity != "info" }).prefix(2).enumerated()), id: \.offset) { _, issue in97                            Text(issue.message).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3).lineLimit(3).fixedSize(horizontal: false, vertical: true)98                        }99                    }100                }101            }102            if figures.isEmpty { VQEmptyState(systemImage: "chart.xyaxis.line", title: theme.l("No figure")) }103        }104        .frame(maxWidth: .infinity, alignment: .leading)105        .sheet(item: $zoomed) { f in ResearchFigureZoom(figure: f, picture: { picture(f) }, exports: { exports(f) }, close: { zoomed = nil }) }106    }107}108109struct ResearchFigureZoom<Picture: View, Exports: View>: View {110    let figure: VQResearchState.Figure111    @ViewBuilder let picture: () -> Picture112    @ViewBuilder let exports: () -> Exports113    let close: () -> Void114    @State private var scale: CGFloat = 1115    @State private var base: CGFloat = 1116    @Environment(\.vqTheme) private var theme117118    var body: some View {119        VStack(alignment: .leading, spacing: VQS.s3) {120            HStack(alignment: .firstTextBaseline) {121                Text(figure.title ?? theme.l("Figure")).vqFont(VQTokens.Typography.heading).foregroundStyle(VQP.text1).lineLimit(2)122                Spacer()123                exports()124                Button(theme.l("Close"), action: close).buttonStyle(.vqSecondary).keyboardShortcut(.cancelAction)125            }126            GeometryReader { g in127                ScrollView([.horizontal, .vertical]) {128                    picture().frame(width: g.size.width * scale, height: g.size.height * scale)129                }130                .gesture(MagnifyGesture().onChanged { scale = min(6, max(1, base * $0.magnification)) }.onEnded { _ in base = scale })131                .onTapGesture(count: 2) { scale = scale > 1 ? 1 : 2.5; base = scale }132            }133            HStack {134                Button { scale = max(1, scale / 1.5); base = scale } label: { Image(systemName: "minus.magnifyingglass") }.accessibilityLabel(theme.l("Zoom out"))135                Text(VQFormat.percent(Double(scale), decimals: 0, locale: theme.numberLocale)).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text2).frame(minWidth: 56)136                Button { scale = min(6, scale * 1.5); base = scale } label: { Image(systemName: "plus.magnifyingglass") }.accessibilityLabel(theme.l("Zoom in"))137                Spacer()138                if !figure.issues.isEmpty { Text(figure.issues.map(\.message).joined(separator: " · ")).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3).lineLimit(2) }139            }140        }141        .padding(VQS.s4)142        .frame(minWidth: 320, idealWidth: 900, minHeight: 320, idealHeight: 640)143        .background(VQP.ink0)144    }145}146147// MARK: files148149/// One file of the workspace, shown for what it is: code (coloured), CSV / TSV (a table), text and logs, images;150/// other formats say what they are and offer the bytes.151public struct ResearchFilePreview: View {152    private let path: String153    private let bytes: Int?154    private let onDownload: ((String, Data) -> Void)?155    @Environment(\.vqTheme) private var theme156    @Environment(\.researchDataSource) private var source157    @Environment(\.researchPreload) private var preload158159    public init(path: String, bytes: Int? = nil, onDownload: ((String, Data) -> Void)? = nil) { self.path = path; self.bytes = bytes; self.onDownload = onDownload }160161    @ViewBuilder private func text(_ t: String, truncated: Bool, totalLines: Int?) -> some View {162        switch VQResearchFileTree.kind(of: path) {163        case .code: ResearchCodeView(t, language: path.hasSuffix(".py") ? "python" : "text")164        case .table:165            let table = VQDelimitedText.parse(t, maxRows: 100)166            VQDataTable(path, columns: table.header.enumerated().map { i, h in167                            let numeric = !table.rows.isEmpty && table.rows.allSatisfy { !$0.indices.contains(i) || $0[i].isEmpty || Double($0[i]) != nil }168                            return VQTableColumn(id: "\(i)", title: h.isEmpty ? "—" : h, alignment: numeric ? .trailing : .leading)169                        },170                        rows: table.rows.enumerated().map { r, row in171                            VQTableRow(id: "\(r)", cells: row.map { cell in172                                if let n = Double(cell), cell.contains(".") { return VQTableCell(VQFormat.number(n, decimals: abs(n) >= 100 ? 2 : 4, locale: theme.numberLocale), numeric: true, sortValue: n) }173                                return VQTableCell(cell.isEmpty ? VQFormat.nullText : cell, numeric: Double(cell) != nil, sortValue: Double(cell))174                            })175                        })176            if table.truncated || truncated { Text(theme.l("Preview: the first 100 rows.")).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3) }177        default: ResearchConsoleText(text: t, maxLines: nil)178        }179        if truncated, let totalLines, VQResearchFileTree.kind(of: path) != .table {180            Text(theme.l("Partial preview: the file has %lld lines.", totalLines)).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3)181        }182    }183184    public var body: some View {185        let kind = VQResearchFileTree.kind(of: path)186        let source = self.source187        VStack(alignment: .leading, spacing: VQS.s2) {188            HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {189                Text(path).font(.system(size: 12, weight: .medium, design: .monospaced)).foregroundStyle(VQP.text1).lineLimit(2).truncationMode(.middle).textSelection(.enabled)190                if let bytes { Text(VQFormat.bytes(bytes, language: theme.language)).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text3) }191                Spacer(minLength: VQS.s2)192                if let onDownload {193                    Button { Task { if let d = try? await source.fileData(path) { onDownload(path, d) } } } label: { Label(theme.l("Download"), systemImage: "arrow.down.circle").vqFont(VQTokens.Typography.caption) }194                        .buttonStyle(.plain).foregroundStyle(VQP.text2)195                }196            }197            if VQResearchFileTree.isTextual(path) {198                if let t = preload.texts[path] { text(t, truncated: false, totalLines: nil) }199                else {200                    ResearchLoader(id: path, preloaded: nil as VQResearchFilePreview?, load: { try await source.textFile(path) }, content: { p in201                        VStack(alignment: .leading, spacing: VQS.s2) { text(p.text, truncated: p.truncated, totalLines: p.totalLines) }202                    }, placeholder: { VQSkeletonText(lines: 6) })203                }204            } else if kind == .image, !path.lowercased().hasSuffix(".svg") {205                ResearchLoader(id: path, preloaded: preload.data[path], load: { try await source.fileData(path) }, content: { data in206                    if let image = VQImageData.image(data, label: path) { image.resizable().scaledToFit().frame(maxHeight: 520) }207                }, placeholder: { VQSkeletonChart(height: 160) })208            } else {209                let what: String = {210                    switch kind {211                    case .pdf: return theme.l("PDF document.")212                    case .data: return theme.l("Binary dataset (Parquet, Excel, Feather): use the inspection.")213                    case .image: return theme.l("SVG vector image.")214                    default: return theme.l("Binary file.")215                    }216                }()217                Text(what + " " + theme.l("Download it to open it.")).vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text2)218            }219        }220        .frame(maxWidth: .infinity, alignment: .leading)221    }222}223224/// The workspace tree with a preview of the selected file. Side by side where there is room, stacked otherwise.225public struct ResearchFilesBrowser: View {226    private let nodes: [VQResearchFileNode]227    private let onDownload: ((String, Data) -> Void)?228    @Binding private var selection: String?229    @State private var open: Set<String>230    @Environment(\.vqTheme) private var theme231232    public init(files: [VQResearchFile], selection: Binding<String?>, expanded: Set<String> = ["code", "data", "artifacts"], onDownload: ((String, Data) -> Void)? = nil) {233        self.nodes = VQResearchFileTree.build(files); self._selection = selection; self._open = State(initialValue: expanded); self.onDownload = onDownload234    }235236    private func symbol(_ n: VQResearchFileNode) -> String {237        if n.isDirectory { return open.contains(n.path) ? "folder.fill" : "folder" }238        switch VQResearchFileTree.kind(of: n.path) {239        case .code: return "chevron.left.forwardslash.chevron.right"240        case .table, .data: return "tablecells"241        case .image: return "photo"242        case .pdf: return "doc.richtext"243        case .log: return "text.alignleft"244        default: return "doc.text"245        }246    }247248    private func rows(_ list: [VQResearchFileNode], depth: Int) -> AnyView {249        AnyView(ForEach(list) { n in250            Button {251                if n.isDirectory { if open.contains(n.path) { open.remove(n.path) } else { open.insert(n.path) } } else { selection = n.path }252            } label: {253                HStack(spacing: 6) {254                    Image(systemName: symbol(n)).font(.system(size: 11)).foregroundStyle(n.isDirectory ? VQP.text2 : VQP.text3).frame(width: 16).accessibilityHidden(true)255                    Text(n.name).font(.system(size: 12, design: .monospaced)).foregroundStyle(VQP.text1).lineLimit(1).truncationMode(.middle)256                    Spacer(minLength: 6)257                    Text(n.isDirectory ? "\(n.fileCount)" : VQFormat.bytes(n.bytes, language: theme.language)).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text3)258                }259                .padding(.leading, CGFloat(depth) * 14).padding(.vertical, 3).padding(.horizontal, 6)260                .background(RoundedRectangle(cornerRadius: 4).fill(selection == n.path ? VQP.ink4 : Color.clear))261                .contentShape(Rectangle())262            }263            .buttonStyle(.plain)264            .accessibilityLabel(n.isDirectory ? theme.l("Folder %1$@, %2$@", n.name, theme.l("%lld files", n.fileCount)) : n.name)265            .accessibilityAddTraits(selection == n.path ? .isSelected : [])266            if n.isDirectory, open.contains(n.path) { rows(n.children, depth: depth + 1) }267        })268    }269270    private var tree: some View { VStack(alignment: .leading, spacing: 0) { rows(nodes, depth: 0) } }271272    @ViewBuilder private var preview: some View {273        if let selection { ResearchFilePreview(path: selection, onDownload: onDownload) }274        else { Text(theme.l("Pick a file to show it.")).vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text3) }275    }276277    public var body: some View {278        if nodes.isEmpty { VQEmptyState(systemImage: "folder", title: theme.l("Empty workspace")) }279        else {280            VQSideBySide(leadingWidth: 300, minimumWidth: 720, spacing: VQS.s5) { tree; preview }281        }282    }283}284285// MARK: environment and sandbox286287/// Where the agent's code runs: the sandbox (said plainly when it is NOT enforced), its limits and network, the288/// Python environment of the workspace, the person's code library.289public struct ResearchEnvironmentPanel: View {290    private let sandbox: VQSandboxStatus?291    private let environment: VQResearchEnvironment?292    private let library: [VQLibraryEntry]293    @Environment(\.vqTheme) private var theme294295    public init(sandbox: VQSandboxStatus?, environment: VQResearchEnvironment? = nil, library: [VQLibraryEntry] = []) { self.sandbox = sandbox; self.environment = environment; self.library = library }296297    private func head(_ s: String) -> some View { Text(s).vqFont(VQTokens.Typography.overline).foregroundStyle(VQP.text3) }298    private func pair(_ k: String, _ v: String) -> some View {299        HStack(alignment: .firstTextBaseline) { Text(k).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2); Spacer(minLength: VQS.s2); Text(v).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text1).multilineTextAlignment(.trailing) }300            .accessibilityElement(children: .combine)301    }302    private func limit(_ key: String, _ v: Double) -> (String, String)? {303        let l = theme.numberLocale304        switch key {305        case "cpuSeconds": return (theme.l("CPU time per process"), VQFormat.duration(ms: v * 1000, locale: l).replacingOccurrences(of: " 00 s", with: ""))306        case "memoryMb": return (theme.l("Memory"), VQFormat.bytes(Int(v * 1_048_576), language: theme.language))307        case "wallMs": return v > 0 ? (theme.l("Wall clock per run"), VQFormat.duration(ms: v, locale: l)) : nil308        case "maxProcesses": return (theme.l("Processes"), VQFormat.int(v, locale: l))309        case "fileMb": return (theme.l("Size per file"), VQFormat.bytes(Int(v * 1_048_576), language: theme.language))310        case "diskMb": return (theme.l("Workspace size"), VQFormat.bytes(Int(v * 1_048_576), language: theme.language))311        default: return (key, VQFormat.number(v, decimals: 0, locale: l))312        }313    }314315    public var body: some View {316        VStack(alignment: .leading, spacing: VQS.s5) {317            if let sandbox {318                VStack(alignment: .leading, spacing: VQS.s2) {319                    HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {320                        Image(systemName: sandbox.enforced ? "lock.shield" : "exclamationmark.shield").foregroundStyle(sandbox.enforced ? theme.upDown.up : VQP.critical).accessibilityHidden(true)321                        Text(sandbox.enforced ? theme.l("Sandbox enforced") : theme.l("Sandbox NOT enforced"))322                            .vqFont(VQTokens.Typography.heading).foregroundStyle(sandbox.enforced ? VQP.text1 : VQP.critical)323                        if let m = sandbox.mechanism { Text(m).font(.system(size: 11, design: .monospaced)).foregroundStyle(VQP.text3) }324                    }325                    if !sandbox.enforced {326                        Text(theme.l("On this server the code written by the agent runs without isolation: it is not confined to its workspace. Do not give it anything sensitive."))327                            .vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text1).fixedSize(horizontal: false, vertical: true)328                            .padding(VQS.s3).frame(maxWidth: .infinity, alignment: .leading).background(VQP.ink1).overlay(alignment: .leading) { Rectangle().fill(VQP.critical).frame(width: 2) }329                    }330                    if let note = sandbox.note { Text(note).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2).fixedSize(horizontal: false, vertical: true) }331                }332                ViewThatFits(in: .horizontal) {333                    HStack(alignment: .top, spacing: VQS.s8) { limits(sandbox).frame(maxWidth: 340); network(sandbox).frame(maxWidth: 420, alignment: .leading) }334                    VStack(alignment: .leading, spacing: VQS.s5) { limits(sandbox); network(sandbox) }335                }336            } else {337                Text(theme.l("Sandbox status unknown.")).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3)338            }339            if let environment {340                VStack(alignment: .leading, spacing: VQS.s2) {341                    head(theme.l("Python environment"))342                    VStack(spacing: 2) {343                        pair(theme.l("Distributions installed"), environment.packages.map { VQFormat.int($0, locale: theme.numberLocale) } ?? VQFormat.nullText)344                        pair(theme.l("Lock hash"), environment.hash ?? VQFormat.nullText)345                        pair(theme.l("Lockfile"), environment.lockfile ?? VQFormat.nullText)346                    }347                    .frame(maxWidth: 420)348                    if !environment.overlay.isEmpty {349                        Text(theme.l("Added by this study")).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2)350                        LabFlow(spacing: 6, lineSpacing: 4) {351                            ForEach(environment.overlay, id: \.self) { p in352                                Text(p).font(.system(size: 11, design: .monospaced)).foregroundStyle(VQP.text1).padding(.horizontal, 6).padding(.vertical, 2).background(RoundedRectangle(cornerRadius: 4).fill(VQP.ink3))353                            }354                        }355                    }356                }357            }358            if !library.isEmpty {359                VStack(alignment: .leading, spacing: VQS.s2) {360                    head(theme.l("Code library"))361                    ForEach(library) { m in362                        VStack(alignment: .leading, spacing: 1) {363                            Text("vqlib.\(m.name)").font(.system(size: 12, weight: .medium, design: .monospaced)).foregroundStyle(VQP.text1)364                            if let d = m.description { Text(d).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2) }365                            if !m.exports.isEmpty { Text(m.exports.joined(separator: ", ")).font(.system(size: 11, design: .monospaced)).foregroundStyle(VQP.text3).lineLimit(2) }366                        }367                    }368                }369            }370        }371        .frame(maxWidth: .infinity, alignment: .leading)372    }373374    private func limits(_ s: VQSandboxStatus) -> some View {375        VStack(alignment: .leading, spacing: VQS.s2) {376            head(theme.l("Limits"))377            VStack(spacing: 2) {378                ForEach(["cpuSeconds", "memoryMb", "wallMs", "maxProcesses", "fileMb", "diskMb"] + s.limits.keys.filter { !["cpuSeconds", "memoryMb", "wallMs", "maxProcesses", "fileMb", "diskMb"].contains($0) }.sorted(), id: \.self) { key in379                    if let v = s.limits[key], let (k, text) = limit(key, v) { pair(k, text) }380                }381                pair(theme.l("Largest upload"), VQFormat.bytes(s.uploadMaxBytes, language: theme.language))382            }383        }384    }385    private func network(_ s: VQSandboxStatus) -> some View {386        VStack(alignment: .leading, spacing: VQS.s2) {387            head(theme.l("Network"))388            Text(theme.l("Without asking:")).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2)389            ForEach(s.defaultNetwork, id: \.self) { h in Text("– \(h)").vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text1).fixedSize(horizontal: false, vertical: true) }390            if let open = s.openNetwork {391                Text(theme.l("With your authorisation:")).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2).padding(.top, 2)392                Text("– \(open)").vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text1).fixedSize(horizontal: false, vertical: true)393            }394        }395    }396}397398// MARK: the convenience container399400/// Every piece of a research study in one adaptive view: pending approvals on top, a summary strip, then the sections —401/// a segmented switch in a compact width, the timeline beside the selected section where there is room. The apps that402/// want their own arrangement (an inspector with tabs, columns) compose the pieces directly instead.403public struct ResearchActivityView: View {404    public enum Section: String, CaseIterable, Sendable, Hashable { case timeline, code, experiments, figures, runs, files, environment }405406    private let store: VQResearchSessionStore407    private let sections: [Section]408    private let onExportFigure: ((VQResearchState.Figure, ResearchFigureFormat, Data) -> Void)?409    private let onDownload: ((String, Data) -> Void)?410    private let now: Date?411    @State private var section: Section412    @State private var selectedFile: String?413    @Environment(\.vqTheme) private var theme414    @Environment(\.vqStaticRender) private var isStatic415    @Environment(\.horizontalSizeClass) private var sizeClass416417    public init(store: VQResearchSessionStore, sections: [Section] = Section.allCases, initial: Section = .timeline, selectedFile: String? = nil, now: Date? = nil,418                onExportFigure: ((VQResearchState.Figure, ResearchFigureFormat, Data) -> Void)? = nil, onDownload: ((String, Data) -> Void)? = nil) {419        self.store = store; self.sections = sections; self._section = State(initialValue: initial); self._selectedFile = State(initialValue: selectedFile); self.now = now420        self.onExportFigure = onExportFigure; self.onDownload = onDownload421    }422423    public static func title(_ s: Section, _ language: VQLanguage) -> String {424        switch s {425        case .timeline: return VQL10n.string("Activity", language)426        case .code: return VQL10n.string("Code", language)427        case .experiments: return VQL10n.string("Experiments", language)428        case .figures: return VQL10n.string("Figures", language)429        case .runs: return VQL10n.string("Runs", language)430        case .files: return VQL10n.string("Files", language)431        case .environment: return VQL10n.string("Environment", language)432        }433    }434435    private func count(_ s: Section) -> Int? {436        let c = store.counts437        switch s {438        case .code: return c.cells439        case .experiments: return c.experiments440        case .figures: return c.figures441        case .runs: return c.runs442        case .files: return store.detail?.files.filter { !$0.isDirectory }.count443        default: return nil444        }445    }446447    /// One section's content (what the apps put in a tab or a column).448    @ViewBuilder public func content(_ s: Section) -> some View {449        let state = store.state450        switch s {451        case .timeline:452            VStack(alignment: .leading, spacing: VQS.s5) {453                ResearchPlanView(state)454                if !store.gateFindings.isEmpty {455                    VStack(alignment: .leading, spacing: VQS.s2) { Text(theme.l("Quality gate")).vqFont(VQTokens.Typography.overline).foregroundStyle(VQP.text3); ResearchQualityGateView(store.gateFindings) }456                }457                ResearchTimelineView(state) { item in458                    switch item.kind {459                    case .execution, .install: section = .code460                    case .experiment: section = .experiments461                    case .figure: section = .figures462                    case .run: section = .runs463                    case .file, .dataset: section = .files464                    default: break465                    }466                }467            }468        case .code: ResearchExecutionList(state.executions, installs: state.installs, expanded: Set(state.executions.filter { $0.status != .ok && $0.status != .running }.prefix(1).map(\.key)))469        case .experiments: ResearchExperimentsTable(state.experiments) { path in selectedFile = path; section = .files }470        case .figures: ResearchFiguresGrid(state.figures, onExport: onExportFigure)471        case .runs: ResearchRunsList(state.runs) { run in Task { await store.cancel(run: run) } }472        case .files: ResearchFilesBrowser(files: store.detail?.files ?? [], selection: $selectedFile, onDownload: onDownload)473        case .environment: ResearchEnvironmentPanel(sandbox: store.sandbox, environment: store.detail?.environment, library: store.detail?.library ?? [])474        }475    }476477    private var summary: some View {478        let c = store.counts479        return LabFlow(spacing: 14, lineSpacing: 4) {480            if store.isRunning { VQAIActivity(theme.l("Study in progress")) }481            Text(theme.l("%lld executions", c.executions)).font(.system(size: 12.5).monospacedDigit()).foregroundStyle(VQP.text2)482            if c.failed > 0 { Label(theme.l("%1$@ failed", "\(c.failed)"), systemImage: "xmark.circle").font(.system(size: 12.5).monospacedDigit()).foregroundStyle(VQP.critical) }483            Text(theme.l("%lld experiments", c.experiments)).font(.system(size: 12.5).monospacedDigit()).foregroundStyle(VQP.text2)484            Text(theme.l("%lld figures", c.figures)).font(.system(size: 12.5).monospacedDigit()).foregroundStyle(VQP.text2)485            if c.runsRunning > 0 { Text(theme.l("%1$@ in the background", "\(c.runsRunning)")).font(.system(size: 12.5).monospacedDigit()).foregroundStyle(VQP.accentText) }486            if let b = store.budgetApplied, b.maxCostUsd != nil || b.maxMinutes != nil {487                Text(theme.l("Budget: ") + [b.maxCostUsd.map { VQFormat.cost($0, locale: theme.numberLocale) }, b.maxMinutes.map { "\(VQFormat.number($0, decimals: 0, locale: theme.numberLocale)) min" }].compactMap { $0 }.joined(separator: " · "))488                    .font(.system(size: 12.5).monospacedDigit()).foregroundStyle(VQP.text3)489            }490            if store.generations.last?.status == .interrupted {491                Label(theme.l("interrupted by a server restart"), systemImage: "pause.circle").font(.system(size: 12.5)).foregroundStyle(VQP.warn)492            }493            if let s = store.sandbox, !s.enforced { Label(theme.l("sandbox not enforced"), systemImage: "exclamationmark.shield").font(.system(size: 12.5).monospacedDigit()).foregroundStyle(VQP.critical) }494        }495        .accessibilityElement(children: .combine)496    }497498    private func tab(_ s: Section) -> some View {499        let on = s == section500        return Button { section = s } label: {501            HStack(spacing: 4) {502                Text(Self.title(s, theme.language)).vqFont(VQTokens.Typography.bodySm).fontWeight(on ? .semibold : .regular)503                if let n = count(s), n > 0 { Text("\(n)").vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text3) }504            }505            .foregroundStyle(on ? VQP.text1 : VQP.text2).padding(.horizontal, VQS.s3).padding(.vertical, 5).frame(minHeight: 28)506            .background { if on { RoundedRectangle(cornerRadius: 5, style: .continuous).fill(VQP.ink2).overlay(RoundedRectangle(cornerRadius: 5, style: .continuous).strokeBorder(VQP.lineStrong, lineWidth: 1)) } }507            .contentShape(Rectangle())508        }509        .buttonStyle(.plain).accessibilityAddTraits(on ? .isSelected : [])510    }511512    /// The section switch: one scrolling row on screen; wrapped rows in an off-screen render (which cannot scroll).513    private var picker: some View {514        Group {515            if isStatic { LabFlow(spacing: 2, lineSpacing: 2) { ForEach(sections, id: \.self) { tab($0) } } }516            else { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 2) { ForEach(sections, id: \.self) { tab($0) } } } }517        }518        .padding(2).background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(VQP.ink3))519        .accessibilityElement(children: .contain).accessibilityLabel(theme.l("Sections of the study"))520    }521522    private var body_: some View {523        VStack(alignment: .leading, spacing: VQS.s4) {524            ForEach(store.pendingApprovals) { a in525                ResearchApprovalCard(a, now: now, onApprove: { Task { await store.answer(a, .approve) } }, onRefuse: { Task { await store.answer(a, .deny) } })526            }527            summary528            picker529            content(section)530        }531        .frame(maxWidth: .infinity, alignment: .topLeading)532    }533534    public var body: some View {535        if isStatic { body_ } else { ScrollView { body_.padding(VQS.s4) }.background(VQP.ink0) }536    }537}538539/// Icon and title on one baseline with a small gap (status lines under figures and rows).540struct VQCompactLabelStyle: LabelStyle {541    func makeBody(configuration: Configuration) -> some View {542        HStack(alignment: .firstTextBaseline, spacing: 4) { configuration.icon; configuration.title }543    }544}545546/// Two views side by side when the width allows (the first at a fixed width), stacked otherwise.547struct VQSideBySide: Layout {548    var leadingWidth: CGFloat549    var minimumWidth: CGFloat550    var spacing: CGFloat551552    private func wide(_ width: CGFloat?) -> Bool { (width ?? 0) >= minimumWidth }553554    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {555        guard subviews.count == 2 else { return .zero }556        let width = proposal.width ?? minimumWidth557        if wide(width) {558            let a = subviews[0].sizeThatFits(ProposedViewSize(width: leadingWidth, height: nil))559            let b = subviews[1].sizeThatFits(ProposedViewSize(width: width - leadingWidth - spacing, height: nil))560            return CGSize(width: width, height: max(a.height, b.height))561        }562        let a = subviews[0].sizeThatFits(ProposedViewSize(width: width, height: nil)), b = subviews[1].sizeThatFits(ProposedViewSize(width: width, height: nil))563        return CGSize(width: width, height: a.height + spacing + b.height)564    }565566    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {567        guard subviews.count == 2 else { return }568        if wide(bounds.width) {569            subviews[0].place(at: bounds.origin, proposal: ProposedViewSize(width: leadingWidth, height: nil))570            subviews[1].place(at: CGPoint(x: bounds.minX + leadingWidth + spacing, y: bounds.minY), proposal: ProposedViewSize(width: bounds.width - leadingWidth - spacing, height: nil))571        } else {572            let a = subviews[0].sizeThatFits(ProposedViewSize(width: bounds.width, height: nil))573            subviews[0].place(at: bounds.origin, proposal: ProposedViewSize(width: bounds.width, height: nil))574            subviews[1].place(at: CGPoint(x: bounds.minX, y: bounds.minY + a.height + spacing), proposal: ProposedViewSize(width: bounds.width, height: nil))575        }576    }577}578
Files main
Menu

Theme