Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantUI/Research/ResearchViews.swift3// Description: The pieces of the research activity, each its own view so the apps arrange them natively: plan,4// timeline, code executions, experiments, runs, quality gate, approval card. None of them scrolls by5// itself: put them in the app's own scroll container (or use `ResearchActivityView`).6import SwiftUI7import VQuantKit89/// Content already in memory, read before the data source is asked (a cache in the apps; fixtures in previews and10/// off-screen renders, where nothing can be awaited).11public struct ResearchPreload: Sendable {12 public var texts: [String: String]13 public var data: [String: Data]14 public var logs: [String: VQRunLogs]15 public var inspections: [String: VQDatasetInspection]16 public init(texts: [String: String] = [:], data: [String: Data] = [:], logs: [String: VQRunLogs] = [:], inspections: [String: VQDatasetInspection] = [:]) {17 self.texts = texts; self.data = data; self.logs = logs; self.inspections = inspections18 }19}2021public extension EnvironmentValues {22 @Entry var researchPreload = ResearchPreload()23}2425public extension View {26 func researchPreload(_ preload: ResearchPreload) -> some View { environment(\.researchPreload, preload) }27}2829// MARK: plan3031/// The objective and the steps the agent keeps current.32public struct ResearchPlanView: View {33 private let objective: String?34 private let plan: [VQResearchState.PlanStep]35 private let revisions: Int36 @Environment(\.vqTheme) private var theme3738 public init(objective: String?, plan: [VQResearchState.PlanStep], revisions: Int = 0) { self.objective = objective; self.plan = plan; self.revisions = revisions }39 public init(_ state: VQResearchState) { self.init(objective: state.objective, plan: state.plan, revisions: state.planRevisions) }4041 public var body: some View {42 VStack(alignment: .leading, spacing: VQS.s3) {43 if let objective, !objective.isEmpty {44 VStack(alignment: .leading, spacing: 2) {45 Text(theme.l("Objective")).vqFont(VQTokens.Typography.overline).foregroundStyle(VQP.text3)46 Text(objective).vqFont(VQTokens.Typography.bodySm).lineSpacing(3).foregroundStyle(VQP.text1).lineLimit(8).fixedSize(horizontal: false, vertical: true)47 }48 }49 if plan.isEmpty {50 Text(theme.l("No plan is recorded for this study.")).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3)51 } else {52 VStack(alignment: .leading, spacing: VQS.s2) {53 HStack {54 Text(theme.l("Plan")).vqFont(VQTokens.Typography.overline).foregroundStyle(VQP.text3)55 if revisions > 0 { Text(theme.l("revised %1$@×", "\(revisions)")).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3) }56 }57 ForEach(Array(plan.enumerated()), id: \.offset) { i, step in58 HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {59 Image(systemName: step.status == .done ? "checkmark.circle.fill" : step.status == .inProgress ? "circle.lefthalf.filled" : "circle")60 .font(.system(size: 12)).foregroundStyle(step.status == .done ? theme.upDown.up : step.status == .inProgress ? VQP.accentText : VQP.text3).accessibilityHidden(true)61 Text("\(i + 1). \(step.title)").vqFont(VQTokens.Typography.bodySm).foregroundStyle(step.status == .pending ? VQP.text2 : VQP.text1).fixedSize(horizontal: false, vertical: true)62 }63 .accessibilityElement(children: .ignore)64 .accessibilityLabel(step.title)65 .accessibilityValue(step.status == .done ? theme.l("done (step)") : step.status == .inProgress ? theme.l("in progress") : theme.l("pending"))66 }67 }68 }69 }70 .frame(maxWidth: .infinity, alignment: .leading)71 }72}7374// MARK: timeline7576/// The decisions timeline: every step of the study in order, each pointing at its entity.77public struct ResearchTimelineView: View {78 private let state: VQResearchState79 private let limit: Int?80 private let onSelect: ((VQResearchState.TimelineItem) -> Void)?81 @Environment(\.vqTheme) private var theme8283 /// - Parameter limit: show only the last `limit` entries (a live feed); nil = all.84 public init(_ state: VQResearchState, limit: Int? = nil, onSelect: ((VQResearchState.TimelineItem) -> Void)? = nil) { self.state = state; self.limit = limit; self.onSelect = onSelect }8586 struct Row { var symbol: String; var title: String; var detail: String?; var color: Color; var failed: Bool }8788 private func row(_ item: VQResearchState.TimelineItem) -> Row? {89 let t = theme90 switch item.kind {91 case .workspace: return Row(symbol: "folder", title: t.l("Research workspace opened"), detail: item.ref, color: VQP.text2, failed: false)92 case .dataset:93 let d = state.datasets.first { $0.path == item.ref }94 let shape = d.flatMap { d in d.rows.map { "\(VQFormat.int($0, locale: t.numberLocale)) × \(d.columns ?? 0)" } }95 return Row(symbol: "tablecells", title: t.l("Dataset profiled"), detail: [item.ref, shape].compactMap { $0 }.joined(separator: " · "), color: VQP.text2, failed: false)96 case .plan: return Row(symbol: "list.bullet.clipboard", title: item.ref == "0" ? t.l("Plan drawn up") : t.l("Plan revised"), detail: t.l("%lld steps", state.plan.count), color: VQP.text2, failed: false)97 case .file:98 let path = item.ref.split(separator: ":", maxSplits: 1).last.map(String.init) ?? item.ref99 let f = state.files.first { $0.path == path }100 let verb: String = { switch f?.action.known { case .patch?: return t.l("File patched"); case .delete?: return t.l("File deleted"); case .library?: return t.l("Module saved to the library"); default: return t.l("File written") } }()101 return Row(symbol: "doc.text", title: verb, detail: path, color: VQP.text2, failed: false)102 case .execution:103 guard let x = state.execution(item.ref) else { return nil }104 let bad = x.status != .ok && x.status != .running105 return Row(symbol: bad ? "xmark.circle" : x.status == .running ? "circle.dotted" : "chevron.left.forwardslash.chevron.right", title: x.title ?? t.l("Code cell"),106 detail: [bad ? t.l("failed") : nil, researchDuration(x.durationMs, t)].compactMap { $0 }.joined(separator: " · "), color: bad ? VQP.critical : VQP.text2, failed: bad)107 case .install:108 guard let i = state.installs.first(where: { $0.key == item.ref }) else { return nil }109 return Row(symbol: "shippingbox", title: t.l("Installed %1$@", "\(i.spec)"), detail: i.ok ? nil : t.l("failed"), color: i.ok ? VQP.text2 : VQP.critical, failed: !i.ok)110 case .run:111 guard let r = state.runs.first(where: { $0.id == item.ref }) else { return nil }112 let bad = r.status != .done && r.status != .running113 return Row(symbol: bad ? "xmark.circle" : r.isRunning ? "circle.dotted" : "play.circle", title: r.label ?? r.code ?? t.l("Run"),114 detail: [r.code, r.duration.map { VQFormat.duration(ms: $0 * 1000, locale: t.numberLocale) }].compactMap { $0 }.joined(separator: " · "), color: bad ? VQP.critical : VQP.text2, failed: bad)115 case .experiment:116 guard let x = state.experiments.first(where: { $0.id == item.ref }) else { return nil }117 let st = x.status.known ?? .ok118 return Row(symbol: st == .ok ? "flask" : st == .abandoned || st == .inconclusive ? "arrow.uturn.backward.circle" : "xmark.circle", title: x.title ?? t.l("Experiment"),119 detail: st == .ok ? t.l("experiment recorded") : ResearchStatusBadgeLabel.text(st, t.language), color: st == .ok ? VQP.text2 : st.isFailure ? VQP.critical : VQP.warn, failed: st != .ok)120 case .note:121 guard let n = state.notes.first(where: { $0.id == item.ref }) else { return nil }122 return Row(symbol: "note.text", title: n.title, detail: n.kind.rawValue, color: VQP.text2, failed: false)123 case .figure:124 guard let f = state.figure(item.ref) else { return nil }125 let open = max(1, f.lintStatus == nil ? f.openIssues.count : f.findings.filter { $0.severity != "info" }.count)126 return Row(symbol: "chart.xyaxis.line", title: f.caption ?? f.title ?? t.l("Figure"), detail: f.lintPassed == false ? t.l("%lld defects left", open) : nil, color: f.lintPassed == false ? VQP.warn : VQP.text2, failed: false)127 case .approval:128 guard let a = state.approvals.first(where: { $0.id == item.ref }) else { return nil }129 return Row(symbol: "hand.raised", title: a.title(t.language), detail: a.statusLabel(t.language), color: a.status == .pending ? VQP.accentText : VQP.text2, failed: false)130 case .gate:131 guard let g = state.gates.first(where: { ($0.generationId ?? "0") == item.ref }) else { return nil }132 let open = g.findings.filter(\.isOpen).count133 return Row(symbol: g.passed ? "checkmark.seal" : "exclamationmark.triangle", title: t.l("Quality gate"), detail: g.passed ? t.l("nothing to report") : t.l("%lld open findings", open), color: g.passed ? theme.upDown.up : VQP.warn, failed: false)134 case .budget: return Row(symbol: "gauge.with.dots.needle.67percent", title: t.l("Budget reached"), detail: item.ref, color: VQP.warn, failed: false)135 }136 }137138 public var body: some View {139 let items = limit.map { Array(state.timeline.suffix($0)) } ?? state.timeline140 VStack(alignment: .leading, spacing: 0) {141 if items.count < state.timeline.count {142 Text(theme.l("… %lld earlier steps", state.timeline.count - items.count)).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3).padding(.bottom, VQS.s2)143 }144 ForEach(items) { item in145 if let r = row(item) {146 HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {147 Image(systemName: r.symbol).font(.system(size: 11.5, weight: .medium)).foregroundStyle(r.color).frame(width: 18).accessibilityHidden(true)148 VStack(alignment: .leading, spacing: 1) {149 Text(r.title).vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text1).lineLimit(2).fixedSize(horizontal: false, vertical: true)150 if let d = r.detail, !d.isEmpty { Text(d).vqFont(VQTokens.Typography.caption).foregroundStyle(r.failed ? r.color : VQP.text3).lineLimit(1).truncationMode(.middle) }151 }152 Spacer(minLength: VQS.s2)153 if let at = item.at { Text(VQFormat.time(at, language: theme.language)).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text3) }154 }155 .padding(.vertical, 5)156 .overlay(alignment: .bottom) { Rectangle().fill(VQP.line).frame(height: VQTokens.hairline) }157 .contentShape(Rectangle())158 .onTapGesture { onSelect?(item) }159 .accessibilityElement(children: .combine)160 .accessibilityAddTraits(onSelect == nil ? [] : .isButton)161 }162 }163 if state.timeline.isEmpty {164 VQEmptyState(systemImage: "clock", title: theme.l("Nothing yet"), message: theme.l("The steps of the study will appear here as the agent works."))165 }166 }167 .frame(maxWidth: .infinity, alignment: .leading)168 }169}170171enum ResearchStatusBadgeLabel {172 static func text(_ s: VQLedgerStatus, _ language: VQLanguage) -> String {173 switch s {174 case .running: return VQL10n.string("running", language)175 case .ok: return VQL10n.string("ok", language)176 case .failed: return VQL10n.string("failed", language)177 case .timeout: return VQL10n.string("timed out", language)178 case .killed: return VQL10n.string("killed (limit)", language)179 case .interrupted: return VQL10n.string("interrupted", language)180 case .inconclusive: return VQL10n.string("inconclusive", language)181 case .abandoned: return VQL10n.string("abandoned", language)182 }183 }184}185186// MARK: code executions187188/// The cells the agent executed, failed ones included. A row opens on its code, its console output and its error.189public struct ResearchExecutionList: View {190 private let executions: [VQResearchState.Execution]191 private let installs: [VQResearchState.Install]192 @State private var open: Set<String>193 @Environment(\.vqTheme) private var theme194 @Environment(\.researchDataSource) private var source195 @Environment(\.researchPreload) private var preload196197 /// - Parameter expanded: keys of the rows open at first (failed cells are worth opening).198 public init(_ executions: [VQResearchState.Execution], installs: [VQResearchState.Install] = [], expanded: Set<String> = []) {199 self.executions = executions; self.installs = installs; self._open = State(initialValue: expanded)200 }201202 @ViewBuilder private func code(_ x: VQResearchState.Execution) -> some View {203 // The stream cuts long cells short ("…"): the whole cell is read from the workspace when the row is opened,204 // the truncated text standing in until it arrives (and staying if it cannot be read).205 let complete = x.codeIsTruncated ? nil : x.code206 if let code = complete ?? x.codePath.flatMap({ preload.texts[$0] }) { ResearchCodeView(code.trimmingCharacters(in: .newlines), maxLines: 60) }207 else if let path = x.codePath {208 let source = self.source209 let partial = x.code210 ResearchLoader(id: path, preloaded: nil as String?, load: {211 do { return try await source.textFile(path).text } catch { if let partial { return partial }; throw error }212 }, content: { ResearchCodeView($0.trimmingCharacters(in: .newlines), maxLines: 60) }, placeholder: {213 if let partial { ResearchCodeView(partial.trimmingCharacters(in: .newlines), maxLines: 60) } else { VQSkeletonText(lines: 4) }214 })215 } else if let code = x.code { ResearchCodeView(code.trimmingCharacters(in: .newlines), maxLines: 60) }216 }217218 public var body: some View {219 VStack(alignment: .leading, spacing: 0) {220 if !installs.isEmpty {221 LabFlow(spacing: 8, lineSpacing: 4) {222 ForEach(installs) { i in223 Label(i.spec, systemImage: i.ok ? "shippingbox" : "exclamationmark.triangle").vqFont(VQTokens.Typography.caption).foregroundStyle(i.ok ? VQP.text2 : VQP.critical)224 .padding(.horizontal, 7).padding(.vertical, 3).overlay(Capsule().strokeBorder(VQP.lineStrong, lineWidth: 1))225 .accessibilityLabel(theme.l("Package installed: %1$@", "\(i.spec)") + (i.ok ? "" : theme.l(", failed")))226 }227 }228 .padding(.bottom, VQS.s3)229 }230 ForEach(Array(executions.enumerated()), id: \.element.key) { n, x in231 let isOpen = open.contains(x.key)232 VStack(alignment: .leading, spacing: VQS.s2) {233 Button { if isOpen { open.remove(x.key) } else { open.insert(x.key) } } label: {234 HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {235 Text(String(format: "%02d", n + 1)).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text3)236 ResearchStatusBadge(x.status, compact: true, language: theme.language)237 Text(x.title ?? theme.l("Code cell")).vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text1).lineLimit(3).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)238 Spacer(minLength: VQS.s2)239 if !x.figureKeys.isEmpty { Label("\(x.figureKeys.count)", systemImage: "chart.xyaxis.line").vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3).labelStyle(.titleAndIcon) }240 if let l = x.lines { Text(theme.l("%1$@ ln", "\(l)")).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text3) }241 if let d = researchDuration(x.durationMs, theme) { Text(d).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text2) }242 Image(systemName: isOpen ? "chevron.down" : "chevron.right").font(.system(size: 10, weight: .semibold)).foregroundStyle(VQP.text3).accessibilityHidden(true)243 }244 .contentShape(Rectangle())245 }246 .buttonStyle(.plain)247 .accessibilityLabel((x.title ?? theme.l("Code cell")) + ", " + ResearchStatusBadgeLabel.text(x.status, theme.language))248 .accessibilityHint(isOpen ? theme.l("Collapse") : theme.l("Show the code and the output"))249 if isOpen {250 code(x)251 if let output = x.output, !output.isEmpty { ResearchConsoleText(text: output) }252 if let error = x.error, !error.isEmpty { ResearchConsoleText(text: error, isError: true) }253 if x.output == nil, x.error == nil, x.status == .ok {254 Text(theme.l("No console output.")).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3)255 }256 } else if x.status != .ok, x.status != .running, let error = x.error {257 // a failure is never hidden: its last line shows even when the row is closed258 Text(error.split(separator: "\n").last(where: { $0.contains("Error") || $0.contains("Exception") }).map(String.init) ?? error.split(separator: "\n").first.map(String.init) ?? error)259 .font(.system(size: 11, design: .monospaced)).foregroundStyle(VQP.critical).lineLimit(2).padding(.leading, 44)260 }261 }262 .padding(.vertical, 6)263 .overlay(alignment: .bottom) { Rectangle().fill(VQP.line).frame(height: VQTokens.hairline) }264 }265 if executions.isEmpty {266 VQEmptyState(systemImage: "chevron.left.forwardslash.chevron.right", title: theme.l("No code executed"))267 }268 }269 .frame(maxWidth: .infinity, alignment: .leading)270 }271}272273// MARK: experiments274275/// The experiment ledger as declared by the agent. Failed, inconclusive and abandoned entries are listed with the others.276public struct ResearchExperimentsTable: View {277 private let experiments: [VQLedgerEntry]278 private let onOpenArtifact: ((String) -> Void)?279 @Environment(\.vqTheme) private var theme280281 public init(_ experiments: [VQLedgerEntry], onOpenArtifact: ((String) -> Void)? = nil) { self.experiments = experiments; self.onOpenArtifact = onOpenArtifact }282283 private func metric(_ v: VQJSON) -> String {284 if let n = v.doubleValue { return n.rounded() == n && abs(n) < 1e9 ? VQFormat.int(n, locale: theme.numberLocale) : VQFormat.number(n, decimals: abs(n) >= 100 ? 2 : 3, locale: theme.numberLocale) }285 return v.displayString ?? v.text()286 }287288 public var body: some View {289 VStack(alignment: .leading, spacing: 0) {290 ForEach(experiments) { x in291 let status = x.status.known ?? .ok292 VStack(alignment: .leading, spacing: VQS.s2) {293 HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {294 if let seq = x.seq { Text("#\(seq)").vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text3) }295 Text(x.title ?? theme.l("Untitled experiment")).vqFont(VQTokens.Typography.heading).foregroundStyle(VQP.text1).fixedSize(horizontal: false, vertical: true)296 Spacer(minLength: VQS.s2)297 ResearchStatusBadge(status, language: theme.language)298 }299 if let h = x.hypothesis { labelled(theme.l("Hypothesis"), h) }300 if let m = x.method { labelled(theme.l("Method"), m) }301 if let metrics = x.metrics, !metrics.isEmpty {302 // numbers in a grid; values that are text (lists of models, "a/b/c" triples) on their own lines303 let numeric = metrics.keys.sorted().filter { metrics[$0]?.doubleValue != nil }304 let textual = metrics.keys.sorted().filter { metrics[$0]?.doubleValue == nil }305 if !numeric.isEmpty {306 LazyVGrid(columns: [GridItem(.adaptive(minimum: 150, maximum: 320), spacing: VQS.s4, alignment: .topLeading)], alignment: .leading, spacing: 3) {307 ForEach(numeric, id: \.self) { key in308 HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {309 Text(key).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2).lineLimit(2)310 Spacer(minLength: 4)311 Text(metric(metrics[key]!)).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text1)312 }313 .accessibilityElement(children: .combine)314 }315 }316 }317 ForEach(textual, id: \.self) { key in318 HStack(alignment: .firstTextBaseline, spacing: VQS.s3) {319 Text(key).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2).frame(width: 200, alignment: .leading)320 Text(metric(metrics[key]!)).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text1).fixedSize(horizontal: false, vertical: true).frame(maxWidth: .infinity, alignment: .leading)321 }322 .accessibilityElement(children: .combine)323 }324 }325 if let notes = x.notes ?? x.error {326 // the agent's own account: the reason of a failed, inconclusive or abandoned experiment is here327 Text(notes).vqFont(VQTokens.Typography.caption).foregroundStyle(status == .ok ? VQP.text2 : VQP.text1).fixedSize(horizontal: false, vertical: true)328 .padding(.leading, VQS.s2).overlay(alignment: .leading) { Rectangle().fill(status == .ok ? VQP.lineStrong : status.isFailure ? VQP.critical : VQP.warn).frame(width: 2) }329 }330 if !x.artifacts.isEmpty {331 LabFlow(spacing: 6, lineSpacing: 4) {332 ForEach(x.artifacts, id: \.self) { path in333 Button { onOpenArtifact?(path) } label: {334 Label(path.split(separator: "/").last.map(String.init) ?? path, systemImage: "paperclip").vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2).lineLimit(1)335 }336 .buttonStyle(.plain).disabled(onOpenArtifact == nil)337 .accessibilityLabel(theme.l("Artifact %1$@", "\(path)"))338 }339 }340 }341 }342 .padding(.vertical, VQS.s3)343 .overlay(alignment: .bottom) { Rectangle().fill(VQP.line).frame(height: VQTokens.hairline) }344 .accessibilityElement(children: .contain)345 }346 if experiments.isEmpty {347 VQEmptyState(systemImage: "flask", title: theme.l("No experiment recorded"), message: theme.l("The agent records its experiments here, including the ones that fail or that it abandons."))348 }349 }350 .frame(maxWidth: .infinity, alignment: .leading)351 }352353 private func labelled(_ label: String, _ text: String) -> some View {354 VStack(alignment: .leading, spacing: 1) {355 Text(label).vqFont(VQTokens.Typography.overline).foregroundStyle(VQP.text3)356 Text(text).vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text1).fixedSize(horizontal: false, vertical: true)357 }358 }359}360361// MARK: runs362363/// Background and parallel runs. A row opens on the end of its logs; a running one can be cancelled.364public struct ResearchRunsList: View {365 private let runs: [VQResearchRun]366 private let onCancel: ((VQResearchRun) -> Void)?367 @State private var open: Set<String>368 @Environment(\.vqTheme) private var theme369 @Environment(\.researchDataSource) private var source370 @Environment(\.researchPreload) private var preload371372 public init(_ runs: [VQResearchRun], expanded: Set<String> = [], onCancel: ((VQResearchRun) -> Void)? = nil) { self.runs = runs; self.onCancel = onCancel; self._open = State(initialValue: expanded) }373374 public var body: some View {375 VStack(alignment: .leading, spacing: 0) {376 ForEach(runs) { run in377 let isOpen = open.contains(run.id)378 VStack(alignment: .leading, spacing: VQS.s2) {379 Button { if isOpen { open.remove(run.id) } else { open.insert(run.id) } } label: {380 HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {381 ResearchStatusBadge(run: run.status, compact: true, language: theme.language)382 VStack(alignment: .leading, spacing: 1) {383 Text(run.label ?? run.code ?? run.id).vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text1).lineLimit(2).multilineTextAlignment(.leading)384 Text(([run.code].compactMap { $0 } + run.args).joined(separator: " ")).font(.system(size: 11, design: .monospaced)).foregroundStyle(VQP.text3).lineLimit(1).truncationMode(.middle)385 }386 Spacer(minLength: VQS.s2)387 if run.network == .open { Label(theme.l("open network"), systemImage: "network").vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.warn) }388 if let d = run.duration { Text(VQFormat.duration(ms: d * 1000, locale: theme.numberLocale)).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text2) }389 Image(systemName: isOpen ? "chevron.down" : "chevron.right").font(.system(size: 10, weight: .semibold)).foregroundStyle(VQP.text3).accessibilityHidden(true)390 }391 .contentShape(Rectangle())392 }393 .buttonStyle(.plain)394 .accessibilityHint(theme.l("Show the end of the logs"))395 if run.isRunning {396 HStack(spacing: VQS.s2) {397 VQProgressBar(run.progress).frame(maxWidth: 220).accessibilityLabel(theme.l("Progress"))398 Text(run.progress.map { VQFormat.percent($0, decimals: 0, locale: theme.numberLocale) } ?? "—").vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text2)399 if let onCancel { Button(theme.l("Stop")) { onCancel(run) }.buttonStyle(.vqSecondary) }400 }401 }402 if let error = run.error, !error.isEmpty { ResearchConsoleText(text: error, isError: true, maxLines: 8) }403 if isOpen {404 let source = self.source405 ResearchLoader(id: run.id, preloaded: preload.logs[run.id], load: { try await source.runLogs(run.id) }, content: { logs in406 VStack(alignment: .leading, spacing: VQS.s2) {407 if !logs.stdout.isEmpty { ResearchConsoleText(text: logs.stdout.trimmingCharacters(in: .newlines)) }408 if !logs.stderr.isEmpty { ResearchConsoleText(text: logs.stderr.trimmingCharacters(in: .newlines), isError: run.status != .done) }409 if logs.stdout.isEmpty, logs.stderr.isEmpty { Text(theme.l("Empty logs.")).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3) }410 }411 }, placeholder: { VQSkeletonText(lines: 3) })412 }413 }414 .padding(.vertical, 6)415 .overlay(alignment: .bottom) { Rectangle().fill(VQP.line).frame(height: VQTokens.hairline) }416 }417 if runs.isEmpty { VQEmptyState(systemImage: "play.circle", title: theme.l("No background run")) }418 }419 .frame(maxWidth: .infinity, alignment: .leading)420 }421}422423// MARK: quality gate424425/// The findings of the quality gate (and figure defects), open ones first. The gate does not withhold an answer.426public struct ResearchQualityGateView: View {427 private let findings: [VQQualityGateFinding]428 @Environment(\.vqTheme) private var theme429 public init(_ findings: [VQQualityGateFinding]) { self.findings = findings }430431 public var body: some View {432 VStack(alignment: .leading, spacing: 0) {433 ForEach(Array(findings.enumerated()), id: \.offset) { _, f in434 let sev = f.severity.known ?? .info435 HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {436 Image(systemName: sev == .info ? "checkmark.circle" : sev == .warning ? "exclamationmark.triangle" : "xmark.octagon").font(.system(size: 12, weight: .medium))437 .foregroundStyle(sev == .info ? theme.upDown.up : sev == .warning ? VQP.warn : VQP.critical).frame(width: 18).accessibilityHidden(true)438 VStack(alignment: .leading, spacing: 2) {439 Text(f.finding).vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text1).fixedSize(horizontal: false, vertical: true)440 if let e = f.evidence, !e.isEmpty { Text(e).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3).lineLimit(4).fixedSize(horizontal: false, vertical: true) }441 }442 }443 .frame(maxWidth: .infinity, alignment: .leading)444 .padding(.vertical, 6)445 .overlay(alignment: .bottom) { Rectangle().fill(VQP.line).frame(height: VQTokens.hairline) }446 .accessibilityElement(children: .combine)447 .accessibilityLabel((sev == .info ? theme.l("Checked: ") : sev == .warning ? theme.l("Warning: ") : theme.l("Error: ")) + f.finding)448 }449 if findings.isEmpty {450 Text(theme.l("The quality gate runs in research mode only, once, before the final answer."))451 .vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3)452 }453 }454 .frame(maxWidth: .infinity, alignment: .leading)455 }456}457458// MARK: approval card459460/// An authorisation the agent is waiting for: what, why, how long is left, and the two answers.461public struct ResearchApprovalCard: View {462 private let approval: VQResearchApproval463 private let fixedNow: Date?464 private let onApprove: () -> Void465 private let onRefuse: () -> Void466 @Environment(\.vqTheme) private var theme467468 /// - Parameter now: a fixed clock (previews, snapshots); otherwise the card ticks every second.469 public init(_ approval: VQResearchApproval, now: Date? = nil, onApprove: @escaping () -> Void, onRefuse: @escaping () -> Void) {470 self.approval = approval; self.fixedNow = now; self.onApprove = onApprove; self.onRefuse = onRefuse471 }472473 private func card(_ now: Date) -> some View {474 let c = approval.countdown(now: now)475 let answerable = approval.isAnswerable(now: now)476 return VStack(alignment: .leading, spacing: VQS.s3) {477 HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {478 Image(systemName: "hand.raised").foregroundStyle(VQP.accentText).accessibilityHidden(true)479 Text(approval.title(theme.language)).vqFont(VQTokens.Typography.heading).foregroundStyle(VQP.text1).fixedSize(horizontal: false, vertical: true)480 Spacer(minLength: VQS.s2)481 if approval.status == .pending, c.remaining != nil {482 Text(c.expired ? theme.l("expired") : c.label).vqFont(VQTokens.Typography.numMd).foregroundStyle(c.urgent || c.expired ? VQP.critical : VQP.text2)483 .accessibilityLabel(c.expired ? theme.l("Request expired") : theme.l("Time left %1$@", "\(c.label)"))484 }485 }486 if let reason = approval.reason, !reason.isEmpty {487 VStack(alignment: .leading, spacing: 1) {488 Text(theme.l("Why")).vqFont(VQTokens.Typography.overline).foregroundStyle(VQP.text3)489 Text(reason).vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text1).fixedSize(horizontal: false, vertical: true)490 }491 }492 let details = approval.details(theme.language, locale: theme.numberLocale)493 if !details.isEmpty {494 VStack(alignment: .leading, spacing: 2) {495 ForEach(Array(details.enumerated()), id: \.offset) { _, d in496 HStack(alignment: .firstTextBaseline) {497 Text(d.label).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2)498 Spacer(minLength: VQS.s2)499 Text(d.value).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text1).multilineTextAlignment(.trailing)500 }501 .accessibilityElement(children: .combine)502 }503 }504 }505 Text(approval.scope(theme.language)).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2).fixedSize(horizontal: false, vertical: true)506 if approval.status == .pending {507 if c.remaining != nil {508 GeometryReader { g in509 ZStack(alignment: .leading) {510 Capsule().fill(VQP.ink3)511 Capsule().fill(c.urgent ? VQP.critical : VQP.accent).frame(width: g.size.width * (1 - c.elapsedShare))512 }513 }514 .frame(height: 3).accessibilityHidden(true)515 }516 HStack(spacing: VQS.s2) {517 Button(action: onApprove) { Text(theme.l("Approve")).frame(minWidth: 72) }.buttonStyle(.vqPrimary).disabled(!answerable)518 Button(action: onRefuse) { Text(theme.l("Refuse")).frame(minWidth: 72) }.buttonStyle(.vqSecondary).disabled(!answerable)519 Spacer(minLength: 0)520 Text(c.expired ? theme.l("Unanswered for 15 minutes, the request counts as a refusal.") : theme.l("Without an answer, it counts as a refusal."))521 .vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3).multilineTextAlignment(.trailing)522 }523 } else {524 HStack(spacing: 6) {525 Image(systemName: approval.status == .approved ? "checkmark.circle" : approval.status == .denied ? "xmark.circle" : "clock.badge.xmark").font(.system(size: 12, weight: .medium))526 Text((approval.status == .approved ? theme.l("Approved") : approval.status == .denied ? theme.l("Refused") : theme.l("Expired unanswered (counts as a refusal)"))527 + (approval.resolvedAt.map { " · " + VQFormat.time($0, language: theme.language) } ?? ""))528 .vqFont(VQTokens.Typography.bodySm)529 }530 .foregroundStyle(approval.status == .approved ? theme.upDown.up : approval.status == .denied ? VQP.critical : VQP.text2)531 .accessibilityElement(children: .combine)532 }533 }534 .padding(VQS.s4)535 .background(RoundedRectangle(cornerRadius: VQTokens.Radius.lg, style: .continuous).fill(VQP.ink2))536 .overlay(RoundedRectangle(cornerRadius: VQTokens.Radius.lg, style: .continuous).strokeBorder(approval.status == .pending ? VQP.accent.opacity(0.7) : VQP.line, lineWidth: 1))537 .accessibilityElement(children: .contain)538 .accessibilityLabel(theme.l("Authorisation request"))539 }540541 public var body: some View {542 if let fixedNow { card(fixedNow) }543 else if approval.status == .pending { TimelineView(.periodic(from: .now, by: 1)) { context in card(context.date) } }544 else { card(Date()) }545 }546}547