Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Research/ResearchCockpit.swift3// Description: The inspector of a research study — Activity · Code · Experiments · Figures · Files · Environment — composed from the shared kit's research views over its study store, plus what is the Mac's own: the workspace file browser with paging, Quick Look, drag to the Finder and Save As.4import QuickLook5import SwiftUI6import UniformTypeIdentifiers7import VQuantCore8import VQuantKit9import VQuantUI1011private typealias P = VQTokens.Palette12private typealias T = VQTokens.Typography1314/// "1 experiment", "2 experiments": the study counts of the header and of the inspector summary.15enum Counted {16 static func text(_ n: Int, _ singular: String) -> String { "\(n) \(singular)\(n == 1 ? "" : "s")" }17}1819/// The six tabs. The app is English-only: titles are English; the case names (and the `inspector.tab.*` identifiers20/// and launch-argument values built on them) keep the names of the original brief.21enum InspectorTab: String, CaseIterable, Identifiable {22 case activite, code, experiences, figures, fichiers, environnement23 var id: String { rawValue }24 var title: String {25 switch self { case .activite: "Activity"; case .code: "Code"; case .experiences: "Experiments"; case .figures: "Figures"; case .fichiers: "Files"; case .environnement: "Environment" }26 }27}2829/// The right-hand side of the research cockpit. Everything it shows comes from the kit's `VQResearchSessionStore`30/// (the generation stream while the study runs, REST afterwards or from another device) and from `StudyStore`31/// reads (network first, encrypted cache offline). The section bodies are the kit's views: this file only arranges32/// them as a Mac inspector.33struct ResearchInspector: View {34 let app: AppEnvironment35 let study: VQResearchSessionStore36 let ref: String37 let load: StudyLoad?38 let isLive: Bool39 @Binding var tab: InspectorTab40 @Binding var selectedFile: String?41 var refresh: () -> Void4243 var body: some View {44 VStack(spacing: 0) {45 tabBar46 Rectangle().fill(P.line).frame(height: 1)47 if case .loaded(let cachedAt?)? = load {48 NoticeBar(kind: .cached, text: "Offline: this study as this Mac last read it (\(Fmt.relative(cachedAt))). Files you opened before stay readable.")49 }50 if let s = study.sandbox, !s.enforced {51 Label("The sandbox is NOT enforced on this server: the agent's code runs without isolation.", systemImage: "exclamationmark.shield.fill")52 .font(T.caption.f.weight(.medium)).foregroundStyle(P.critical).padding(.horizontal, 14).padding(.vertical, 7).frame(maxWidth: .infinity, alignment: .leading)53 .background(P.critical.opacity(0.10)).accessibilityIdentifier("sandbox.notEnforced")54 }55 content56 .researchDataSource(app.studies.source(ref))57 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)58 }59 .background(P.ink1)60 .accessibilityElement(children: .contain).accessibilityIdentifier("research.inspector")61 }6263 private func count(_ t: InspectorTab) -> Int? {64 let c = study.counts65 switch t {66 case .activite: return nil67 case .code: return c.cells68 case .experiences: return c.experiments69 case .figures: return c.figures70 case .fichiers: return study.detail.map { $0.files.filter { !$0.isDirectory }.count }71 case .environnement: return c.runs > 0 ? c.runs : nil72 }73 }7475 private var tabBar: some View {76 ScrollView(.horizontal, showsIndicators: false) {77 HStack(spacing: 0) {78 ForEach(InspectorTab.allCases) { t in79 let on = t == tab80 Button { tab = t } label: {81 VStack(spacing: 5) {82 HStack(spacing: 3) {83 Text(t.title).font(.system(size: 12.5, weight: on ? .semibold : .regular)).lineLimit(1).fixedSize().foregroundStyle(on ? P.text1 : P.text2)84 if let n = count(t), n > 0 { Text("\(n)").font(.system(size: 10, design: .monospaced)).foregroundStyle(P.text3) }85 }86 Rectangle().fill(on ? P.accent : Color.clear).frame(height: 2)87 }88 .padding(.horizontal, 5).padding(.top, 9)89 .contentShape(Rectangle())90 }91 .buttonStyle(.plain)92 .accessibilityIdentifier("inspector.tab.\(t.rawValue)").accessibilityLabel(t.title).accessibilityAddTraits(on ? [.isSelected, .isButton] : .isButton)93 }94 }95 .padding(.leading, 6)96 }97 .background(P.ink1)98 }99100 @ViewBuilder private var content: some View {101 let state = study.state102 switch tab {103 case .activite:104 pane {105 summary106 ForEach(state.budgetHits, id: \.self) { h in107 BudgetNote(event: VQBudgetEvent(json: ["kind": .string(h.kind), "limit": VQJSON(h.limit), "spent": VQJSON(h.spent)]))108 }109 if state.objective != nil || !state.plan.isEmpty { ResearchPlanView(state) }110 if !study.gateFindings.isEmpty { group("Quality gate") { ResearchQualityGateView(study.gateFindings) } }111 if state.timeline.isEmpty {112 VQEmptyState(systemImage: "waveform.path.ecg", title: isLive ? "Waiting for the first step" : "No recorded activity", message: isLive ? "Each step of the study appears here as the agent takes it." : "This workspace holds no execution, experiment or file yet.")113 } else {114 group("Timeline") {115 ResearchTimelineView(state) { item in116 switch item.kind {117 case .execution, .install: tab = .code118 case .experiment: tab = .experiences119 case .figure: tab = .figures120 case .run: tab = .environnement121 case .file: tab = .fichiers122 case .dataset: selectedFile = item.ref; tab = .fichiers123 default: break124 }125 }126 }127 }128 if !state.notes.isEmpty {129 group("Research notes") {130 VStack(alignment: .leading, spacing: 10) {131 ForEach(state.notes) { n in132 VStack(alignment: .leading, spacing: 3) {133 HStack(spacing: 6) {134 Text(n.kind.rawValue.uppercased()).font(T.overline.f).tracking(0.9).foregroundStyle(n.kind == .failure ? P.critical : P.accentText)135 Text(n.title).font(T.bodySm.f.weight(.medium)).foregroundStyle(P.text1)136 }137 Text(n.body).font(T.caption.f).foregroundStyle(P.text2).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)138 }139 }140 }141 }142 }143 }144 case .code:145 pane {146 if state.executions.isEmpty && state.installs.isEmpty && scripts.isEmpty {147 VQEmptyState(systemImage: "chevron.left.forwardslash.chevron.right", title: "No code yet", message: "Notebook cells and scripts appear here with their output, their error and their duration.")148 } else {149 if !scripts.isEmpty {150 group("Scripts · \(scripts.count)") {151 VStack(alignment: .leading, spacing: 2) {152 ForEach(scripts) { f in153 Button { selectedFile = f.path; tab = .fichiers } label: {154 HStack(spacing: 6) {155 Image(systemName: "doc.plaintext").font(.system(size: 11)).foregroundStyle(P.text3)156 Text(f.path).font(.system(size: 12, design: .monospaced)).foregroundStyle(P.text1).lineLimit(1).truncationMode(.middle)157 Spacer(minLength: 6)158 Text(VQFormat.bytes(f.bytes, language: .en)).font(T.numSm.f).foregroundStyle(P.text3)159 }160 .contentShape(Rectangle())161 }162 .buttonStyle(.plain).padding(.vertical, 2).help("Open in Files")163 }164 }165 }166 }167 group("Notebook cells · \(state.executions.count)") {168 ResearchExecutionList(state.executions, installs: state.installs, expanded: Set(state.executions.filter { $0.status != .ok && $0.status != .running }.prefix(1).map(\.key)))169 }170 }171 }172 case .experiences:173 pane {174 let c = study.counts175 let unsettled = state.experiments.filter { $0.status.known?.isFailure == true || $0.status == .inconclusive || $0.status == .abandoned }.count176 Text("\(c.experiments) declared experiment\(c.experiments == 1 ? "" : "s")\(unsettled > 0 ? " · \(unsettled) failed, inconclusive or abandoned" : "") · \(c.executions) execution\(c.executions == 1 ? "" : "s")\(c.failed > 0 ? ", \(c.failed) not ended well" : "")")177 .font(T.numSm.f).foregroundStyle(P.text2)178 if state.experiments.isEmpty {179 VQEmptyState(systemImage: "list.bullet.clipboard", title: "No declared experiment", message: "The agent records an experiment with its hypothesis, method, metrics and outcome — failed and inconclusive ones included.")180 } else { ResearchExperimentsTable(state.experiments) { path in selectedFile = path; tab = .fichiers } }181 }182 case .figures:183 pane {184 if state.figures.isEmpty { VQEmptyState(systemImage: "chart.xyaxis.line", title: "No figure yet", message: "Each figure is checked by the visual linter; its PNG, SVG and PDF exports are kept in the workspace.") }185 else {186 ResearchFiguresGrid(state.figures) { figure, format, data in187 let name = (figure.files.flatMap { format == .png ? $0.png : format == .svg ? $0.svg : $0.pdf }.map { ($0 as NSString).lastPathComponent }) ?? "figure.\(format.rawValue)"188 SavePanel.save(data, name: name, types: [UTType(filenameExtension: format.rawValue) ?? .data])189 }190 }191 }192 case .fichiers:193 WorkspaceFilesTab(app: app, ref: ref, study: study, selection: $selectedFile)194 case .environnement:195 pane {196 ResearchEnvironmentPanel(sandbox: study.sandbox, environment: study.detail?.environment, library: study.detail?.library ?? [])197 if let lock = study.detail?.environment.lockfile {198 Button { selectedFile = lock; tab = .fichiers } label: { Label("Open \(lock)", systemImage: "lock.doc").font(T.caption.f) }.buttonStyle(.link)199 }200 group("Runs · \(state.runs.count)") {201 if state.runs.isEmpty { Text("No background run in this workspace.").font(T.bodySm.f).foregroundStyle(P.text3) }202 else { ResearchRunsList(state.runs.reversed(), expanded: Set(state.runs.filter(\.isRunning).prefix(1).map(\.id))) { run in Task { await study.cancel(run: run) } } }203 }204 }205 }206 }207208 private var scripts: [VQResearchFile] { (study.detail?.files ?? []).filter { !$0.isDirectory && $0.path.hasPrefix("code/") } }209210 private var summary: some View {211 let c = study.counts212 return FlowLayout(spacing: 12) {213 if isLive { VQAIActivity("Study in progress") }214 Text(Counted.text(c.executions, "execution")).font(T.numSm.f).foregroundStyle(P.text2)215 if c.failed > 0 { Label("\(c.failed) failed", systemImage: "xmark.circle").font(T.numSm.f).foregroundStyle(P.critical) }216 Text(Counted.text(c.experiments, "experiment")).font(T.numSm.f).foregroundStyle(P.text2)217 Text(Counted.text(c.figures, "figure")).font(T.numSm.f).foregroundStyle(P.text2)218 if c.runsRunning > 0 { Text("\(c.runsRunning) running in the background").font(T.numSm.f).foregroundStyle(P.accentText) }219 Button(action: refresh) { Image(systemName: "arrow.clockwise").font(.system(size: 10)) }.buttonStyle(.borderless).help("Read the workspace again").accessibilityIdentifier("inspector.refresh")220 if let id = study.workspaceId { Text(id).font(T.numSm.f).foregroundStyle(P.text3).textSelection(.enabled).help("Research workspace on the server") }221 }222 }223224 private func pane<C: View>(@ViewBuilder _ content: () -> C) -> some View {225 ScrollView { VStack(alignment: .leading, spacing: 18) { content() }.padding(16).frame(maxWidth: .infinity, alignment: .topLeading) }226 }227 private func group<C: View>(_ title: String, @ViewBuilder _ content: () -> C) -> some View {228 VStack(alignment: .leading, spacing: 8) {229 VStack(alignment: .leading, spacing: 5) {230 Text(title.uppercased()).font(T.overline.f).tracking(0.9).foregroundStyle(P.text3)231 Rectangle().fill(P.line).frame(height: 1)232 }233 content()234 }235 }236}237238// MARK: - Files239240/// A workspace file that can leave the app: dragged to the Finder (downloaded when the drop asks for it), shared.241nonisolated struct WorkspaceFile: Transferable, Sendable {242 let path: String243 let fetch: @Sendable () async throws -> URL244 var name: String { (path as NSString).lastPathComponent }245 static var transferRepresentation: some TransferRepresentation {246 FileRepresentation(exportedContentType: .data) { file in SentTransferredFile(try await file.fetch()) }247 .suggestedFileName { $0.name }248 }249}250251/// The tree of the workspace (`…/files?recursive=1`) over a preview of the selected file.252struct WorkspaceFilesTab: View {253 let app: AppEnvironment254 let ref: String255 let study: VQResearchSessionStore256 @Binding var selection: String?257 @State private var listed: [VQResearchFile]?258 @State private var listError: String?259 @State private var open: Set<String> = ["code", "data", "artifacts", "artifacts/figures"]260 @State private var pages: [String: Page] = [:]261 @State private var quickLook: URL?262 @SceneStorage("research.treeHeight") private var treeHeight = 230.0263 @State private var lastDrag: CGFloat = 0264 @State private var busy: String?265 @State private var inspections: [String: VQDatasetInspection] = [:]266267 struct Page { var text: String; var to: Int; var total: Int; var truncated: Bool; var loading = false; var error: String? }268 static let pageLines = 400269270 private var files: [VQResearchFile] { listed ?? study.detail?.files ?? [] }271 private var selected: VQResearchFile? { selection.flatMap { p in files.first { $0.path == p && !$0.isDirectory } } }272273 var body: some View {274 Group {275 if files.isEmpty {276 VQEmptyState(systemImage: "folder", title: listError == nil ? "Empty workspace" : "The workspace could not be listed", message: listError ?? "Files the agent writes — code, data, artifacts, logs — appear here.")277 .frame(maxWidth: .infinity, maxHeight: .infinity)278 } else {279 VStack(spacing: 0) {280 ScrollView { VStack(alignment: .leading, spacing: 0) { rows(VQResearchFileTree.build(files), depth: 0) }.padding(8) }281 .frame(height: CGFloat(treeHeight))282 Rectangle().fill(P.line).frame(height: 1)283 .overlay {284 Color.clear.frame(height: 9).contentShape(Rectangle())285 .onHover { inside in if inside { NSCursor.resizeUpDown.push() } else { NSCursor.pop() } }286 .gesture(DragGesture(minimumDistance: 1, coordinateSpace: .global)287 .onChanged { v in treeHeight = min(600, max(100, treeHeight + Double(v.translation.height - lastDrag))); lastDrag = v.translation.height }288 .onEnded { _ in lastDrag = 0 })289 }290 preview.frame(maxWidth: .infinity, maxHeight: .infinity)291 }292 }293 }294 .quickLookPreview($quickLook)295 .task(id: ref) { await list() }296 .onChange(of: study.state.files.count) { _, _ in Task { await list() } }297 .onChange(of: study.detail?.files.count) { _, _ in Task { await list() } }298 .task(id: selection) { if let s = selected, VQResearchFileTree.isTextual(s.path), pages[s.path] == nil { await loadPage(s.path) } }299 }300301 private func list() async {302 do { listed = try await app.studies.files(ref); listError = nil }303 catch is CancellationError {}304 catch { listError = (error as? VQError)?.message ?? error.localizedDescription }305 // a file selected from another tab may sit in a closed folder306 if let s = selection { var parts = s.split(separator: "/").map(String.init); parts.removeLast(); var p = ""; for part in parts { p = p.isEmpty ? part : p + "/" + part; open.insert(p) } }307 }308309 private func loadPage(_ path: String) async {310 let from = (pages[path]?.to ?? 0) + 1311 pages[path, default: Page(text: "", to: 0, total: 0, truncated: false)].loading = true312 do {313 let p = try await app.studies.text(ref, path: path, from: from, limit: Self.pageLines)314 var page = pages[path] ?? Page(text: "", to: 0, total: 0, truncated: false)315 page.text += (page.text.isEmpty || page.text.hasSuffix("\n") ? "" : "\n") + p.text316 page.to = max(p.to, page.to); page.total = p.totalLines; page.truncated = p.truncated; page.loading = false; page.error = nil317 pages[path] = page318 } catch is CancellationError { pages[path]?.loading = false }319 catch { pages[path]?.loading = false; pages[path]?.error = (error as? VQError)?.message ?? error.localizedDescription }320 }321322 private func symbol(_ n: VQResearchFileNode) -> String {323 if n.isDirectory { return open.contains(n.path) ? "folder.fill" : "folder" }324 switch VQResearchFileTree.kind(of: n.path) {325 case .code: return "chevron.left.forwardslash.chevron.right"; case .table, .data: return "tablecells"; case .image: return "photo"326 case .pdf: return "doc.richtext"; case .log: return "text.alignleft"; default: return "doc.text"327 }328 }329330 private func item(_ path: String, bytes: Int) -> WorkspaceFile {331 let studies = app.studies, ref = ref332 return WorkspaceFile(path: path) { try await studies.download(ref, path: path, bytes: bytes) }333 }334335 private func rows(_ list: [VQResearchFileNode], depth: Int) -> AnyView {336 AnyView(ForEach(list) { n in337 let row = Button {338 if n.isDirectory { if open.contains(n.path) { open.remove(n.path) } else { open.insert(n.path) } } else { selection = n.path }339 } label: {340 HStack(spacing: 6) {341 Image(systemName: symbol(n)).font(.system(size: 11)).foregroundStyle(n.isDirectory ? P.text2 : P.text3).frame(width: 16)342 Text(n.name).font(.system(size: 12, design: .monospaced)).foregroundStyle(P.text1).lineLimit(1).truncationMode(.middle)343 if app.studies.cachedReads[ref]?.contains(n.path) == true { Image(systemName: "internaldrive").font(.system(size: 9)).foregroundStyle(P.warn).help("Read from this Mac's cache") }344 Spacer(minLength: 6)345 Text(n.isDirectory ? "\(n.fileCount)" : VQFormat.bytes(n.bytes, language: .en)).font(T.numSm.f).foregroundStyle(P.text3)346 }347 .padding(.leading, CGFloat(depth) * 14).padding(.vertical, 3).padding(.horizontal, 6)348 .background(RoundedRectangle(cornerRadius: 4).fill(selection == n.path ? P.ink4 : Color.clear))349 .contentShape(Rectangle())350 }351 .buttonStyle(.plain)352 .accessibilityIdentifier("file.\(n.path)").accessibilityAddTraits(selection == n.path ? [.isSelected, .isButton] : .isButton)353 if n.isDirectory { row; if open.contains(n.path) { rows(n.children, depth: depth + 1) } }354 else {355 row.draggable(item(n.path, bytes: n.bytes)) { Label(n.name, systemImage: symbol(n)).padding(6).background(P.ink2, in: RoundedRectangle(cornerRadius: 6)) }356 .contextMenu {357 Button("Quick Look") { look(n.path, n.bytes) }358 Button("Save As…") { saveAs(n.path, n.bytes) }359 Divider()360 Button("Copy Path") { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(n.path, forType: .string) }361 }362 }363 })364 }365366 @ViewBuilder private var preview: some View {367 if let f = selected {368 VStack(alignment: .leading, spacing: 0) {369 HStack(spacing: 8) {370 VStack(alignment: .leading, spacing: 1) {371 Text(f.name).font(.system(size: 12, weight: .semibold, design: .monospaced)).foregroundStyle(P.text1).lineLimit(1).truncationMode(.middle)372 Text("\(VQFormat.bytes(f.bytes, language: .en))\(f.modifiedAt.map { " · modified \(Fmt.dateTime($0))" } ?? "")").font(T.numSm.f).foregroundStyle(P.text3)373 }374 Spacer(minLength: 6)375 if busy == f.path { ProgressView().controlSize(.mini) }376 if VQResearchFileTree.isDataset(f.path) {377 Button { inspect(f.path) } label: { Label("Inspect", systemImage: "tablecells.badge.ellipsis") }.help("Profile this dataset on the server").accessibilityIdentifier("file.inspect")378 }379 Button { look(f.path, f.bytes) } label: { Label("Quick Look", systemImage: "eye") }.keyboardShortcut(.space, modifiers: []).help("Quick Look (Space)").accessibilityIdentifier("file.quicklook")380 Button { saveAs(f.path, f.bytes) } label: { Label("Save As…", systemImage: "square.and.arrow.down") }.help("Save a copy on this Mac").accessibilityIdentifier("file.saveas")381 ShareLink(item: item(f.path, bytes: f.bytes), preview: SharePreview(f.name)) { Label("Share", systemImage: "square.and.arrow.up") }382 }383 .labelStyle(.iconOnly).buttonStyle(.borderless)384 .padding(.horizontal, 12).padding(.vertical, 8)385 .draggable(item(f.path, bytes: f.bytes))386 Rectangle().fill(P.line).frame(height: 1)387 ScrollView {388 VStack(alignment: .leading, spacing: 12) {389 if let i = inspections[f.path] { DatasetProfile(inspection: i, maxColumnsHeight: 220).padding(10).background(P.ink2, in: RoundedRectangle(cornerRadius: 8)) }390 if let page = pages[f.path], !page.text.isEmpty {391 ResearchFilePreview(path: f.path, bytes: nil).researchPreload(ResearchPreload(texts: [f.path: page.text]))392 HStack(spacing: 10) {393 Text("Lines 1–\(page.to) of \(page.total)").font(T.numSm.f).foregroundStyle(P.text3)394 if page.truncated || page.to < page.total {395 Button(page.loading ? "Loading…" : "Load the next \(Self.pageLines) lines") { Task { await loadPage(f.path) } }.buttonStyle(.link).font(T.caption.f).disabled(page.loading)396 .accessibilityIdentifier("file.more")397 }398 }399 } else if let e = pages[f.path]?.error {400 Label(e, systemImage: "exclamationmark.triangle").font(T.caption.f).foregroundStyle(P.text3)401 } else if VQResearchFileTree.isTextual(f.path) {402 VQSkeletonText(lines: 6)403 } else {404 ResearchFilePreview(path: f.path, bytes: nil)405 }406 }407 .padding(12).frame(maxWidth: .infinity, alignment: .topLeading)408 }409 }410 .background(P.ink1)411 .accessibilityElement(children: .contain).accessibilityIdentifier("file.preview")412 } else {413 VQEmptyState(systemImage: "doc.text.magnifyingglass", title: "Pick a file", message: "Text is shown by pages; Space opens Quick Look; drag a file to the Finder to copy it.")414 .frame(maxWidth: .infinity, maxHeight: .infinity)415 }416 }417418 private func look(_ path: String, _ bytes: Int) {419 busy = path420 Task { defer { busy = nil }421 do { quickLook = try await app.studies.download(ref, path: path, bytes: bytes) } catch { app.toasts.show((error as? VQError)?.message ?? error.localizedDescription, error: true) } }422 }423 private func saveAs(_ path: String, _ bytes: Int) {424 busy = path425 Task { defer { busy = nil }426 do {427 let d = try await app.studies.data(ref, path: path, bytes: bytes)428 let name = (path as NSString).lastPathComponent429 SavePanel.save(d, name: name, types: [UTType(filenameExtension: (name as NSString).pathExtension) ?? .data])430 } catch { app.toasts.show((error as? VQError)?.message ?? error.localizedDescription, error: true) } }431 }432 private func inspect(_ path: String) {433 busy = path434 Task { defer { busy = nil }435 do { inspections[path] = try await app.studies.inspect(ref, path: path) } catch { app.toasts.show((error as? VQError)?.message ?? error.localizedDescription, error: true) } }436 }437}438