Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Quant/LabResultPane.swift3// Description: The right side of the Quant Lab workbench: a running job with its progress and cancellation, a failed or cancelled job explained, and a finished result — `lab/1` through the shared kit's renderer, the six legacy tools through their 1.x views — with export, copy, comparison, filing in a project, automated review and a question to the agent.4import SwiftUI5import UniformTypeIdentifiers6import VQuantCore7import VQuantKit8import VQuantUI910private typealias P = VQTokens.Palette11private typealias S = VQTokens.Space12private typealias T = VQTokens.Typography1314struct LabResultPane: View {15 let app: AppEnvironment16 @Bindable var model: WindowModel17 @Bindable var state: LabWindowState18 let tool: VQLabTool?1920 @State private var showCode = false21 @State private var integrityExpanded = false22 /// A job id the server does not know (opened from a stale link or deleted elsewhere).23 @State private var missing: String?24 @Environment(\.colorScheme) private var scheme2526 private var lab: LabStore { app.lab }27 private var job: VQQuantJob? { model.quantJobId.flatMap { lab.job($0) } }28 private var locale: VQNumberLocale { app.vqTheme.numberLocale }2930 var body: some View {31 Group {32 if let id = model.quantJobId {33 if let job { content(job) }34 else if missing == id { Color.clear.frame(maxWidth: .infinity, maxHeight: .infinity).overlay { VQEmptyState(systemImage: "questionmark.circle", title: "Computation not found", message: "Job \(id) is not in your list on this server: it may have been deleted from another device.") { Button("Back to the Engine") { model.quantJobId = nil } } } }35 else { skeleton }36 } else if let tool { LabToolIntro(app: app, model: model, state: state, tool: tool) }37 else { Color.clear.frame(maxWidth: .infinity, maxHeight: .infinity).overlay { VQEmptyState(systemImage: "function", title: "Quant Lab", message: "Pick an engine in the catalogue.") } }38 }39 .background(P.ink0)40 .task(id: "\(model.quantJobId ?? "")|\(job?.status.rawValue ?? "")") { if let id = model.quantJobId { let d = await lab.detail(id); missing = d == nil ? id : nil } }41 .task(id: state.compareWith) { if let c = state.compareWith { await lab.detail(c) } }42 }4344 private var skeleton: some View {45 VStack(alignment: .leading, spacing: S.s6) { VQSkeletonText(lines: 3); VQSkeletonChart(); VQSkeletonRows() }.padding(S.s8).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)46 }4748 @ViewBuilder private func content(_ job: VQQuantJob) -> some View {49 VStack(spacing: 0) {50 actionBar(job)51 Rectangle().fill(P.line).frame(height: 1)52 if job.tool == "backtest", let r = job.labResult, r.success {53 // look-ahead and survivorship stay in view above the result, whatever is scrolled or compared54 LabIntegrityBanner(statement: LabShape.integrity(r, job: job), expanded: $integrityExpanded, app: app)55 Rectangle().fill(P.line).frame(height: 1)56 }57 if job.status == .done, let otherId = state.compareWith {58 if let other = lab.details[otherId] { LabCompareView(app: app, a: job, b: other) { state.compareWith = nil } swap: { model.quantJobId = otherId; DispatchQueue.main.async { state.compareWith = job.id } } }59 else { skeleton }60 } else {61 ScrollView {62 VStack(alignment: .leading, spacing: S.s6) {63 if let note = lab.cancelNotes[job.id] { cancelNote(note, job) }64 switch job.status.known {65 case .running?: running(job)66 case .done?: done(job)67 default: failed(job)68 }69 }70 .padding(.horizontal, S.s8).padding(.vertical, S.s6)71 .frame(maxWidth: 1180, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)72 }73 }74 }75 }7677 // MARK: action bar7879 private func actionBar(_ job: VQQuantJob) -> some View {80 Group {81 if job.status == .done, job.result != nil {82 // labelled actions when the whole title fits beside them, icons otherwise (the title then truncates)83 ViewThatFits(in: .horizontal) {84 HStack(spacing: S.s2) { barTitle(job).fixedSize(); Spacer(minLength: S.s3); actions(job, labels: true) }85 HStack(spacing: S.s2) { barTitle(job); Spacer(minLength: S.s2); actions(job, labels: false) }86 }87 } else {88 HStack(spacing: S.s2) {89 barTitle(job)90 Spacer(minLength: S.s2)91 if job.isRunning {92 Button("Cancel") { Task { await lab.cancel(job.id) } }.controlSize(.small).accessibilityIdentifier("lab.cancel")93 .help(job.cancellable ? "Stop the engine's process on the server" : "Legacy tools cannot be stopped; the server will say so")94 } else {95 Button("Edit and Run Again") { LabJobActions.reuse(job, app: app, model: model, state: state) }.controlSize(.small).disabled(lab.tool(job.tool) == nil)96 Button("Delete", role: .destructive) { delete(job) }.controlSize(.small)97 }98 }99 }100 }101 .padding(.horizontal, S.s4).frame(height: 44).frame(maxWidth: .infinity)102 .background(.bar)103 }104105 private func barTitle(_ job: VQQuantJob) -> some View {106 HStack(spacing: S.s2) {107 LabStatusGlyph(job: job, app: app)108 Text([lab.title(job.tool), job.subject].filter { !$0.isEmpty }.joined(separator: " · ")).vqFont(T.heading).foregroundStyle(P.text1).lineLimit(1).truncationMode(.tail)109 }110 }111112 private func delete(_ job: VQQuantJob) {113 Task { await lab.delete(job.id); if model.quantJobId == job.id { if model.quantTool == nil { model.quantTool = job.tool }; model.quantJobId = nil } }114 }115116 @ViewBuilder private func actions(_ job: VQQuantJob, labels: Bool) -> some View {117 HStack(spacing: labels ? S.s2 : 2) {118 compareMenu(job, labels)119 projectMenu(job, labels)120 barButton("Request review", "checkmark.seal", labels) { state.reviewOpen = true }121 .help("Automated review of this result — not a human peer review").accessibilityIdentifier("lab.review")122 barButton("Ask the Agent", "sparkles", labels) { model.ask(LabShape.ask(job, title: lab.title(job.tool), locale: locale)) }123 .help("Ask the research agent about this result (opens a new conversation with the job as context)").accessibilityIdentifier("lab.ask")124 exportMenu(job, labels)125 Menu {126 Button("Copy Headline and Summary") { VQPasteboard.copy(LabShape.plainText(job, title: lab.title(job.tool), locale: locale)); app.toasts.show("Copied.") }127 Button("Copy Result as JSON") { if let r = job.result { VQPasteboard.copy(r.text(pretty: true)); app.toasts.show("Copied.") } }128 Button("Copy Job ID") { VQPasteboard.copy(job.id) }129 Divider()130 if job.code != nil { Button(showCode ? "Hide the Code" : "Show the Code") { showCode.toggle() } }131 Button("Edit These Parameters and Run Again") { LabJobActions.reuse(job, app: app, model: model, state: state) }.disabled(lab.tool(job.tool) == nil)132 Divider()133 Button("Delete", role: .destructive) { delete(job) }134 } label: { Image(systemName: "ellipsis.circle") }135 .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize().help("Copy, code, run again, delete").accessibilityIdentifier("lab.more")136 }137 }138139 private func barButton(_ title: String, _ symbol: String, _ labels: Bool, _ action: @escaping () -> Void) -> some View {140 Button(action: action) { barLabel(title, symbol, labels) }.buttonStyle(.borderless)141 }142 private func barLabel(_ title: String, _ symbol: String, _ labels: Bool) -> some View {143 HStack(spacing: 4) { Image(systemName: symbol).font(.system(size: 12)); if labels { Text(title).vqFont(T.caption).lineLimit(1).fixedSize() } }144 .foregroundStyle(P.text1).padding(.horizontal, labels ? 6 : 5).frame(height: 26).contentShape(Rectangle())145 }146147 private func compareMenu(_ job: VQQuantJob, _ labels: Bool) -> some View {148 let others = lab.jobs.filter { $0.tool == job.tool && $0.id != job.id && $0.status == .done }.prefix(15)149 return Menu {150 if state.compareWith != nil { Button("Stop Comparing") { state.compareWith = nil }; Divider() }151 Section("Another result of \(lab.title(job.tool))") {152 ForEach(Array(others)) { o in153 Button([o.subject, o.variant, LabFormat.started(o.startedAt)].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")) { state.compareWith = o.id }154 }155 if others.isEmpty { Text("No other finished result of this engine") }156 }157 } label: { barLabel("Compare", "rectangle.split.2x1", labels) }158 .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()159 .help("Compare with another result of the same engine, side by side").accessibilityIdentifier("lab.compare")160 }161162 private func projectMenu(_ job: VQQuantJob, _ labels: Bool) -> some View {163 let projects = app.sync.active?.projects.items ?? []164 return Menu {165 Section("Add this result to a project") {166 ForEach(projects) { p in167 let has = p.data.items.contains { $0.type == .quantJob && $0.ref == job.id }168 Button {169 Task { let added = await lab.addToProject(job, projectId: p.id); app.toasts.show(added ? "Added to “\(p.data.title)”." : "Already in “\(p.data.title)”.") }170 } label: { if has { Label(p.data.title, systemImage: "checkmark") } else { Text(p.data.title) } }171 .disabled(has)172 }173 if projects.isEmpty { Text(app.sync.active == nil ? "Sync is off" : "No project yet — create one in Research Studio") }174 }175 } label: { barLabel("Add to Project", "folder.badge.plus", labels) }176 .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()177 .help("File this result in a Research Studio project (synced)").accessibilityIdentifier("lab.project")178 }179180 private func exportMenu(_ job: VQQuantJob, _ labels: Bool) -> some View {181 let base = "vquant-\(job.tool)-\(job.subject.replacingOccurrences(of: ", ", with: "-").replacingOccurrences(of: " ", with: "-"))"182 return Menu {183 if let r = job.labResult, r.success {184 Button("Whole Result as PDF…") { LabExport.save(VQExport.pdf(LabExport.document(r), width: 1040, colorScheme: .light, theme: app.vqTheme), name: base + ".pdf", type: .pdf, app: app) }185 Button("Whole Result as PNG…") { LabExport.save(VQExport.png(LabExport.document(r), width: 1040, colorScheme: scheme, theme: app.vqTheme), name: base + ".png", type: .png, app: app) }186 if !r.charts.isEmpty {187 Menu("Figure") {188 ForEach(Array(r.charts.enumerated()), id: \.offset) { i, c in189 Menu("Fig. \(i + 1) — \(c.title)") {190 Button("PNG…") { LabExport.save(VQExport.png(chart: c, colorScheme: scheme, theme: app.vqTheme), name: "\(base)-\(c.id).png", type: .png, app: app) }191 Button("PDF…") { LabExport.save(VQExport.pdf(chart: c, colorScheme: .light, theme: app.vqTheme), name: "\(base)-\(c.id).pdf", type: .pdf, app: app) }192 Button("Data as CSV…") { LabExport.save(Data(VQExport.csv(chart: c).utf8), name: "\(base)-\(c.id).csv", type: .commaSeparatedText, app: app) }193 }194 }195 }196 }197 if !r.tables.isEmpty {198 Menu("Table as CSV") {199 ForEach(r.tables) { t in Button("\(t.title)…") { LabExport.save(Data(LabExport.csv(t).utf8), name: "\(base)-\(t.id).csv", type: .commaSeparatedText, app: app) } }200 }201 }202 Divider()203 }204 if let r = job.result { Button("Result as JSON…") { LabExport.save(r.data(pretty: true), name: base + ".json", type: .json, app: app) } }205 if let code = job.labResult?.provenance?.reproduce ?? job.code { Button(job.labResult != nil ? "Reproduce Snippet (Python)…" : "Python Code…") { LabExport.save(Data(code.utf8), name: base + ".py", type: .pythonScript, app: app) } }206 } label: { barLabel("Export", "square.and.arrow.up", labels) }207 .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()208 .help("PDF, PNG, CSV, JSON, Python").accessibilityIdentifier("lab.export")209 }210211 // MARK: states212213 private func cancelNote(_ text: String, _ job: VQQuantJob) -> some View {214 HStack(alignment: .firstTextBaseline, spacing: S.s2) {215 Image(systemName: "info.circle").foregroundStyle(P.info).font(.system(size: 12))216 Text(text).vqFont(T.bodySm).foregroundStyle(P.text1).fixedSize(horizontal: false, vertical: true)217 Spacer(minLength: S.s2)218 Button { lab.cancelNotes[job.id] = nil } label: { Image(systemName: "xmark").font(.system(size: 10, weight: .semibold)).foregroundStyle(P.text3) }.buttonStyle(.plain).help("Dismiss")219 }220 .padding(S.s3).frame(maxWidth: 760, alignment: .leading)221 .overlay(alignment: .leading) { Rectangle().fill(P.info).frame(width: 2) }222 .background(P.ink1)223 .accessibilityIdentifier("lab.cancelnote")224 }225226 private func jobLine(_ j: VQQuantJob) -> some View {227 HStack(alignment: .firstTextBaseline, spacing: S.s2) {228 if let src = j.labResult?.provenance?.data.first {229 VQProvenanceChip(kind: .historical, provider: src.provider, asOf: src.retrievedAt.flatMap(VQISODate.parse))230 }231 Text("Job \(j.id) · started \(Fmt.dateTime(j.startedAt))\(j.duration().map { " · ran \(LabFormat.duration($0))" } ?? "")\(j.engineVersion.map { " · engine v\($0)" } ?? "") · computed by the VQuant server")232 .vqFont(T.caption).foregroundStyle(P.text3).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)233 .accessibilityIdentifier("lab.result.jobline")234 }235 }236237 private func running(_ j: VQQuantJob) -> some View {238 VStack(alignment: .leading, spacing: S.s4) {239 Text(lab.title(j.tool) + (j.subject.isEmpty ? "" : " — \(j.subject)")).vqFont(T.displayMd).foregroundStyle(P.text1)240 TimelineView(.periodic(from: .now, by: 1)) { t in241 VStack(alignment: .leading, spacing: S.s2) {242 if let p = j.progress {243 HStack(spacing: S.s3) {244 LabProgressBar(value: p, height: 6).frame(maxWidth: 420).accessibilityIdentifier("lab.progress")245 Text("\(Int((p * 100).rounded())) %").vqFont(T.numMd).foregroundStyle(P.text1).frame(width: 52, alignment: .trailing).accessibilityHidden(true)246 }247 } else {248 LabProgressBar(value: nil, height: 6).frame(maxWidth: 420).accessibilityIdentifier("lab.progress")249 Text(lab.tool(j.tool)?.isLab == false ? "Legacy tools do not report progress." : "The engine has not reported progress yet.").vqFont(T.caption).foregroundStyle(P.text3)250 }251 Text("Running on the server since \(Fmt.time(j.startedAt)) · \(LabFormat.duration(j.duration(now: t.date))) elapsed\(j.engineVersion.map { " · engine v\($0)" } ?? "")")252 .vqFont(T.numSm).foregroundStyle(P.text2)253 }254 }255 Text("You can keep working: the result appears here when the engine finishes, on every device signed in to your account. Lab runs are stopped by the server after 10 minutes.")256 .vqFont(T.bodySm).foregroundStyle(P.text2).frame(maxWidth: 620, alignment: .leading).fixedSize(horizontal: false, vertical: true)257 HStack(spacing: S.s3) {258 Button { Task { await lab.cancel(j.id) } } label: { Label("Cancel the Computation", systemImage: "stop.fill") }.accessibilityIdentifier("lab.cancel.main")259 if !j.cancellable { Text("This is a legacy tool: it cannot be stopped once started.").vqFont(T.caption).foregroundStyle(P.text3) }260 }261 paramsBlock(j)262 }263 }264265 private func failed(_ j: VQQuantJob) -> some View {266 let (title, symbol, color): (String, String, Color) = {267 switch j.status.known {268 case .cancelled?: ("Cancelled", "stop.circle", P.text2)269 case .interrupted?: ("Interrupted", "exclamationmark.triangle", P.warn)270 case .error?: ("The computation failed", "xmark.octagon", P.critical)271 default: ("Finished with the status “\(j.status.rawValue)”", "questionmark.circle", P.warn)272 }273 }()274 let message: String = {275 switch j.status.known {276 case .cancelled?: "It was stopped before it finished. A cancelled computation keeps no result."277 case .interrupted?: j.error ?? "The server restarted while this computation was running. Nothing was saved: run it again."278 default: j.failureMessage ?? "The engine gave no reason."279 }280 }()281 return VStack(alignment: .leading, spacing: S.s4) {282 HStack(spacing: S.s2) { Image(systemName: symbol).font(.system(size: 20)).foregroundStyle(color); Text(title).vqFont(T.displayMd).foregroundStyle(P.text1) }283 Text(message).vqFont(T.body).foregroundStyle(P.text1).textSelection(.enabled).frame(maxWidth: 760, alignment: .leading).fixedSize(horizontal: false, vertical: true)284 .accessibilityIdentifier("lab.failure")285 jobLine(j)286 paramsBlock(j)287 }288 }289290 /// The validated input the server recorded with the job (defaults written out).291 private func paramsBlock(_ j: VQQuantJob) -> some View {292 VStack(alignment: .leading, spacing: S.s2) {293 Text("Recorded parameters").vqFont(T.overline).foregroundStyle(P.text3)294 LazyVGrid(columns: [GridItem(.adaptive(minimum: 230), spacing: S.s5, alignment: .topLeading)], alignment: .leading, spacing: 3) {295 ForEach(j.params.keys.sorted(), id: \.self) { k in296 HStack(alignment: .firstTextBaseline, spacing: S.s2) {297 Text(k).vqFont(T.caption).foregroundStyle(P.text2)298 Spacer(minLength: S.s2)299 Text(LabCompare.paramText(j.params[k]!.core)).vqFont(T.numSm).foregroundStyle(P.text1).lineLimit(1).truncationMode(.middle)300 }301 }302 }303 }304 .padding(.top, S.s2).frame(maxWidth: 820, alignment: .leading)305 }306307 @ViewBuilder private func done(_ j: VQQuantJob) -> some View {308 let reviews = lab.reviews(of: j.id)309 if let r = j.labResult {310 jobLine(j)311 if !reviews.isEmpty { LabReviewStrip(review: reviews[0].data) { state.reviewOpen = true } }312 if r.success {313 let slices = LabSlice.available(engine: r.engine, mode: j.params["mode"]?.stringValue, chartIds: r.charts.map(\.id), tableIds: r.tables.map(\.id))314 let slice = slices.first { $0.id == state.slice[j.tool] }315 if !slices.isEmpty {316 VQSegmentedControl("Part of the result", selection: Binding(get: { slice?.id ?? "" }, set: { state.slice[j.tool] = $0.isEmpty ? nil : $0 }),317 options: [.init("", "Everything")] + slices.map { .init($0.id, $0.title) })318 .accessibilityIdentifier("lab.slices")319 }320 if let slice {321 LabResultView(LabShape.sliced(r, slice), options: LabShape.options(hidden: [.summary, .diagnostics, .assumptions, .methodology, .provenance], app: app))322 } else if r.engine == "options_lab", let mode = j.params["mode"]?.stringValue.flatMap(LabOptionsMode.init(rawValue:)), let hero = LabOptionsHero(result: r, mode: mode, app: app) {323 hero324 LabResultView(hero.remaining, options: LabShape.options(hidden: [], app: app))325 } else {326 LabResultView(r, options: LabShape.options(hidden: [], app: app))327 }328 } else { LabResultView(r) }329 } else if let result = j.result {330 // one of the six legacy tools: its 1.x native view, fed from the job's raw result331 VStack(alignment: .leading, spacing: S.s2) {332 Text("\(lab.title(j.tool)) · \(j.subject)").vqFont(T.displayMd).foregroundStyle(P.text1)333 Text("Engine \(j.tool) · \(LabShape.paramSummary(j))").font(.caption.monospaced()).foregroundStyle(P.text2).textSelection(.enabled)334 jobLine(j)335 }336 if !reviews.isEmpty { LabReviewStrip(review: reviews[0].data) { state.reviewOpen = true } }337 QuantResultView(app: app, tool: j.tool, result: result.core)338 if showCode, let code = j.code { CodeBlock(language: "python", text: code) }339 } else if lab.details[j.id] != nil {340 VQEmptyState(systemImage: "tray", title: "No result", message: "The server holds no result for this job.")341 } else { VQSkeletonText(lines: 3); VQSkeletonChart(); VQSkeletonRows() }342 }343}344345// MARK: - Engine intro (nothing selected yet)346347private struct LabToolIntro: View {348 let app: AppEnvironment349 @Bindable var model: WindowModel350 @Bindable var state: LabWindowState351 let tool: VQLabTool352353 var body: some View {354 let jobs = app.lab.jobs.filter { $0.tool == tool.id }355 ScrollView {356 VStack(alignment: .leading, spacing: S.s6) {357 VStack(alignment: .leading, spacing: S.s2) {358 Text(LabCategory.title(tool.category?.rawValue) + (tool.version.map { " · v\($0)" } ?? "")).vqFont(T.overline).foregroundStyle(P.text3)359 Text(tool.title).vqFont(T.displayLg).foregroundStyle(P.text1)360 Text(tool.summary).vqFont(T.body).lineSpacing(4).foregroundStyle(P.text2).frame(maxWidth: 720, alignment: .leading).fixedSize(horizontal: false, vertical: true)361 }362 VStack(alignment: .leading, spacing: S.s3) {363 VQSectionHeader("What a run gives you")364 Text(tool.isLab365 ? "A result in the generic lab/1 schema: a one-sentence headline, summary figures each marked observed, calculated, assumption or forecast, figures and tables, statistical diagnostics with their verdict, the assumptions, the methodology, and the provenance — data sources, software versions and a Python snippet that reproduces the core computation."366 : "One of the six tools of VQuant 1.x. Its result keeps its own shape and is shown by the 1.x views, with the engine, the recorded parameters and the Python code the server ran. It reports no progress and cannot be cancelled once started.")367 .vqFont(T.bodySm).foregroundStyle(P.text2).frame(maxWidth: 720, alignment: .leading).fixedSize(horizontal: false, vertical: true)368 Text("Set the parameters on the left, then Run on the Server (⌘↩). Nothing is computed on this Mac.").vqFont(T.bodySm).foregroundStyle(P.text2)369 }370 VStack(alignment: .leading, spacing: S.s2) {371 VQSectionHeader("Computations with this engine") { Text("\(jobs.count)").vqFont(T.numSm).foregroundStyle(P.text3) }372 if jobs.isEmpty { Text("None yet.").vqFont(T.bodySm).foregroundStyle(P.text3) }373 else { LabJobList(app: app, model: model, state: state, toolFilter: tool.id).frame(height: min(420, CGFloat(jobs.count) * 54 + 12)) }374 }375 }376 .padding(.horizontal, S.s8).padding(.vertical, S.s6)377 .frame(maxWidth: 900, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)378 }379 }380}381382// MARK: - Export helpers383384@MainActor enum LabExport {385 /// The whole result laid out for a document: every section open, no row limit.386 static func document(_ r: VQLabResult) -> some View {387 var o = LabResultView.Options(); o.expanded = true388 return LabResultView(r, options: o)389 }390 static func save(_ data: Data?, name: String, type: UTType, app: AppEnvironment) {391 guard let data else { app.toasts.show("The export could not be rendered.", error: true); return }392 if SavePanel.save(data, name: name, types: [type]) != nil { app.toasts.show("Saved \(name).") }393 }394 /// A table's source values (not the formatted text): numbers in plain decimal notation.395 static func csv(_ t: VQLabResult.Table) -> String {396 func field(_ s: String) -> String { s.contains(",") || s.contains("\"") || s.contains("\n") ? "\"" + s.replacingOccurrences(of: "\"", with: "\"\"") + "\"" : s }397 func cell(_ v: VQJSON?) -> String {398 switch v {399 case .number(let n)?: return VQJSON.number(n).text()400 case .string(let s)?: return s401 case .bool(let b)?: return b ? "true" : "false"402 case .null?, nil: return ""403 case let other?: return other.text()404 }405 }406 let header = t.columns.map { field($0.label) }.joined(separator: ",")407 return ([header] + t.rows.map { r in t.columns.map { field(cell(r[$0.key])) }.joined(separator: ",") }).joined(separator: "\n") + "\n"408 }409}410