Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Research/ResearchComposer.swift3// Description: The composer of the research agent: the question, the mode (incl. autonomous Research), the model read from the server's registry (or Auto), cost and time budgets, an image, and datasets uploaded into the research workspace with their inspection card.4import SwiftUI5import UniformTypeIdentifiers6import VQuantCore7import VQuantKit8import VQuantUI910private typealias P = VQTokens.Palette11private typealias T = VQTokens.Typography1213/// What a window is composing. One per window; the Research menu acts on it through `ResearchActions`.14@Observable final class ComposerModel {15 var text = ""16 var image: (data: Data, mime: String, name: String)?17 var mode: ResearchMode18 /// A selectable model id of the registry, or `auto`.19 var model: String20 /// Limits of the next analysis; nil = the person's synced default applies on the server.21 var maxCostUsd: Double?22 var maxMinutes: Double?23 var datasets: [AttachedDataset] = []24 /// The conversation id created with its workspace before the first message (a dataset was attached to a new conversation).25 var preparedSessionId: String?26 /// Context handed over by another section (chart, statement, lab): appended to the question in plain words.27 var context = ""28 var projectId: String?29 var modelPickerOpen = false30 var budgetOpen = false31 var importerOpen = false32 var focusTick = 033 /// Incremented to send what is composed (a prepared question asked to be sent at once).34 var sendTick = 035 #if DEBUG36 /// A file attached at launch (`-VQXDataset`), for visual checks of the dataset card.37 var debugDataset: URL?38 #endif3940 init(settings: SettingsStore) { mode = settings.researchMode; model = settings.researchModel }4142 var busyWithDataset: Bool { datasets.contains { $0.phase == .uploading || $0.phase == .inspecting } }43 var budget: ChatBudget? { maxCostUsd == nil && maxMinutes == nil ? nil : ChatBudget(maxCostUsd: maxCostUsd, maxMinutes: maxMinutes) }4445 /// A new conversation: nothing of the previous draft stays.46 func resetDraft(settings: SettingsStore) {47 text = ""; image = nil; datasets = []; preparedSessionId = nil; context = ""; projectId = nil48 mode = settings.researchMode; model = settings.researchModel49 }5051 /// The question as it is sent: what the person wrote, then the context and the attached data in plain words52 /// (the server receives text only: there is no hidden channel).53 func query() -> String {54 var q = text.trimmingCharacters(in: .whitespacesAndNewlines)55 let ctx = context.trimmingCharacters(in: .whitespacesAndNewlines)56 if !ctx.isEmpty { q += "\n\nContext: " + ctx }57 let ready = datasets.compactMap { d -> String? in58 guard let path = d.uploaded?.path else { return nil }59 if let i = d.inspection, let rows = i.rows { return "\(path) (\(rows) rows × \(i.columnCount ?? i.columns.count) columns)" }60 return path61 }62 if !ready.isEmpty { q += "\n\nAttached in the research workspace: " + ready.joined(separator: "; ") + "." }63 return q64 }65}6667// `ResearchActions` (what the Research menu can ask of the window in front) is declared in App/Next/Commands.swift.6869struct Composer: View {70 let app: AppEnvironment71 @Bindable var model: WindowModel72 @Bindable var draft: ComposerModel73 let run: RunController?74 @State private var dropTargeted = false75 @FocusState private var focused: Bool7677 static let datasetTypes: [UTType] = [.commaSeparatedText, .tabSeparatedText, .json, .plainText] + ["jsonl", "parquet", "xlsx", "xls", "feather"].compactMap { UTType(filenameExtension: $0) }7879 private var blocked: String? {80 if !app.connectivity.isOnline { return "Offline: an analysis needs the server." }81 if run?.isActive == true { return "An analysis is running in this conversation." }82 if draft.busyWithDataset { return "Uploading the dataset…" }83 return nil84 }85 private var canSend: Bool { blocked == nil && !draft.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }8687 var body: some View {88 VStack(alignment: .leading, spacing: 8) {89 ForEach(draft.datasets) { d in90 DatasetCard(app: app, dataset: d) { draft.datasets.removeAll { $0.id == d.id } }91 }92 if let image = draft.image {93 HStack(spacing: 6) {94 Image(systemName: "photo").foregroundStyle(P.text2); Text(image.name).lineLimit(1)95 Button { draft.image = nil } label: { Image(systemName: "xmark.circle.fill") }.buttonStyle(.borderless).help("Remove the image")96 }97 .font(T.caption.f)98 }99 if !draft.context.isEmpty {100 HStack(alignment: .firstTextBaseline, spacing: 6) {101 Text("CONTEXT").font(T.overline.f).tracking(0.9).foregroundStyle(P.text3)102 Text(draft.context).font(T.caption.f).foregroundStyle(P.text2).lineLimit(2).help("Appended to your question when it is sent:\n\(draft.context)")103 Button { draft.context = "" } label: { Image(systemName: "xmark.circle.fill") }.buttonStyle(.borderless).help("Send the question without this context")104 }105 .accessibilityIdentifier("composer.context")106 }107 VStack(alignment: .leading, spacing: 0) {108 HStack(alignment: .bottom, spacing: 8) {109 TextField(draft.mode == .research ? "State a research question — the agent designs, codes and checks the study…" : "Ask about a company, a market, a portfolio…", text: $draft.text, axis: .vertical)110 .lineLimit(1...8).textFieldStyle(.plain).font(T.body.f).focused($focused)111 .onSubmit(send)112 .accessibilityIdentifier("composer.text")113 Button(action: send) { Image(systemName: "arrow.up.circle.fill").font(.system(size: 26)) }114 .buttonStyle(.plain).foregroundStyle(canSend ? P.accent : P.text3.opacity(0.5)).disabled(!canSend).keyboardShortcut(.return, modifiers: .command).help("Send (⌘↩)")115 .accessibilityIdentifier("composer.send")116 }117 .padding(.horizontal, 12).padding(.top, 10).padding(.bottom, 8)118 Rectangle().fill(P.line).frame(height: 1)119 controls.padding(.horizontal, 10).padding(.vertical, 7)120 }121 .background(P.ink2, in: RoundedRectangle(cornerRadius: VQTokens.Radius.md, style: .continuous))122 .overlay(RoundedRectangle(cornerRadius: VQTokens.Radius.md, style: .continuous).strokeBorder(dropTargeted ? P.accent : focused ? P.lineStrong : P.line, lineWidth: dropTargeted ? 2 : 1))123 HStack(alignment: .firstTextBaseline, spacing: 8) {124 Text(draft.mode.oneLine).font(T.caption.f).foregroundStyle(P.text3).lineLimit(1)125 .accessibilityIdentifier("composer.modeDetail")126 Spacer(minLength: 8)127 if let blocked { Text(blocked).font(T.caption.f).foregroundStyle(P.text2).lineLimit(1).fixedSize() }128 else if model.sessionId == nil { Text(draft.projectId == nil ? "New conversation" : "New conversation in the project").font(T.caption.f).foregroundStyle(P.text3) }129 }130 }131 .padding(.horizontal, 20).padding(.top, 10).padding(.bottom, 10)132 .background(P.ink0)133 .dropDestination(for: URL.self) { urls, _ in urls.reduce(false) { attach($1) || $0 } } isTargeted: { dropTargeted = $0 }134 .fileImporter(isPresented: $draft.importerOpen, allowedContentTypes: Self.datasetTypes, allowsMultipleSelection: false) { result in135 if case .success(let urls) = result, let url = urls.first { attachDataset(url) }136 }137 .onAppear { focused = true; Task { await app.studies.loadCatalog() } }138 .onChange(of: draft.focusTick) { _, _ in focused = true }139 .onChange(of: draft.sendTick) { _, _ in send() }140 #if DEBUG141 .onChange(of: draft.debugDataset, initial: true) { _, url in if let url { draft.debugDataset = nil; attachDataset(url) } }142 #endif143 }144145 private var controls: some View {146 ViewThatFits(in: .horizontal) {147 HStack(spacing: 8) { modeControl; modelControl; BudgetButton(app: app, draft: draft); Spacer(minLength: 4); attachControls(titles: true) }148 VStack(alignment: .leading, spacing: 6) {149 HStack(spacing: 8) { modeControl; Spacer(minLength: 4); attachControls(titles: true) }150 HStack(spacing: 8) { modelControl; BudgetButton(app: app, draft: draft); Spacer(minLength: 0) }151 }152 VStack(alignment: .leading, spacing: 6) {153 HStack(spacing: 8) { modeControl; Spacer(minLength: 4); attachControls(titles: false) }154 HStack(spacing: 8) { modelControl; BudgetButton(app: app, draft: draft); Spacer(minLength: 0) }155 }156 VStack(alignment: .leading, spacing: 6) {157 HStack(spacing: 8) { modeMenu; Spacer(minLength: 4); attachControls(titles: true) }158 HStack(spacing: 8) { modelControl; BudgetButton(app: app, draft: draft); Spacer(minLength: 0) }159 }160 }161 // anchored on the row, not on the button: the button lives in whichever arrangement fits, and a popover attached162 // to it closed when the arrangement was re-evaluated (the registry arriving changes the label's width)163 .popover(isPresented: $draft.modelPickerOpen, attachmentAnchor: .point(.top), arrowEdge: .top) {164 ModelPicker(app: app, selection: draft.model) { id in draft.model = id; app.settings.researchModel = id; draft.modelPickerOpen = false }.vqTheme(app.vqTheme)165 }166 }167 private var modeControl: some View { ModePicker(selection: Binding(get: { draft.mode }, set: { draft.mode = $0; app.settings.researchMode = $0 }), research: app.studies.researchAvailable == true).fixedSize() }168 /// The same choice in a narrow pane.169 private var modeMenu: some View {170 Picker("Mode", selection: Binding(get: { draft.mode }, set: { draft.mode = $0; app.settings.researchMode = $0 })) { ForEach(ResearchMode.allCases.filter { app.studies.researchAvailable == true || $0 != .research || draft.mode == .research }) { Text($0.short).tag($0) } }171 .labelsHidden().fixedSize().accessibilityIdentifier("mode.menu")172 }173 private var modelControl: some View {174 Button { draft.modelPickerOpen = true } label: {175 HStack(spacing: 5) {176 if draft.model == "auto" { Image(systemName: "wand.and.stars").font(.system(size: 10)).foregroundStyle(P.accentText) }177 else if let p = app.studies.provider(of: draft.model) { VQProviderLogo(provider: p, size: 12) }178 Text(app.studies.modelLabel(draft.model)).font(T.bodySm.f).foregroundStyle(P.text1).lineLimit(1)179 Image(systemName: "chevron.up.chevron.down").font(.system(size: 8, weight: .semibold)).foregroundStyle(P.text3)180 }181 .padding(.horizontal, 8).frame(height: 26)182 .background(P.ink3, in: RoundedRectangle(cornerRadius: 6, style: .continuous))183 .contentShape(Rectangle())184 }185 .buttonStyle(.plain).fixedSize().help("Model — read from the server's registry")186 .accessibilityIdentifier("composer.model")187 }188 private func attachControls(titles: Bool) -> some View {189 HStack(spacing: 8) {190 Button { pickImage() } label: { Image(systemName: "photo.badge.plus") }.buttonStyle(.borderless).help("Attach an image (chart, table, screenshot)")191 .accessibilityIdentifier("composer.image")192 Button { draft.importerOpen = true } label: { Label("Dataset", systemImage: "tablecells.badge.ellipsis").labelStyle(DatasetLabel(titles: titles)).font(T.caption.f) }193 .buttonStyle(.borderless).help("Attach a dataset (CSV, TSV, JSON, Parquet, Excel, Feather): it is uploaded into the research workspace and profiled. You can also drop a file here.")194 .accessibilityIdentifier("composer.dataset")195 }196 .fixedSize()197 }198199 private func send() {200 guard canSend else { return }201 let q = draft.query()202 if let sid = model.sessionId { app.research.dismiss(sid) }203 let sessionId = model.sessionId ?? draft.preparedSessionId204 app.research.ask(q, sessionId: sessionId, key: model.draftKey, mode: draft.mode, model: draft.model, image: draft.image.map { ($0.data, $0.mime) },205 budget: draft.budget, projectId: draft.projectId, preparedSession: draft.preparedSessionId != nil)206 // a conversation created with its workspace is already named: the window shows it at once207 if model.sessionId == nil, let prepared = draft.preparedSessionId { model.sessionId = prepared }208 draft.text = ""; draft.image = nil; draft.datasets = []; draft.preparedSessionId = nil; draft.context = ""209 }210211 private func pickImage() {212 let p = NSOpenPanel(); p.allowedContentTypes = [.png, .jpeg, .gif, .webP]; p.allowsMultipleSelection = false213 if p.runModal() == .OK, let url = p.url { _ = attach(url) }214 }215216 /// A dropped or chosen file: a dataset goes to the research workspace, an image goes with the question.217 @discardableResult func attach(_ url: URL) -> Bool {218 if VQDatasetUpload.extensions.contains(VQDatasetUpload.fileExtension(url.lastPathComponent)) { attachDataset(url); return true }219 guard let type = UTType(filenameExtension: url.pathExtension), [UTType.png, .jpeg, .gif, .webP].contains(where: { type.conforms(to: $0) }), let mime = type.preferredMIMEType else {220 app.toasts.show("Attach an image (PNG, JPEG, GIF, WebP) or a dataset (CSV, TSV, JSON, Parquet, Excel, Feather).", error: true); return false221 }222 let scoped = url.startAccessingSecurityScopedResource(); defer { if scoped { url.stopAccessingSecurityScopedResource() } }223 guard let d = try? Data(contentsOf: url) else { return false }224 // the server accepts request bodies up to 10 MB; base64 adds a third225 guard d.count <= 6_500_000 else { app.toasts.show("This image is too large (limit about 6.5 MB).", error: true); return false }226 draft.image = (d, mime, url.lastPathComponent); return true227 }228229 /// Workspace (created if the conversation has none) → upload → inspection.230 func attachDataset(_ url: URL) {231 let name = url.lastPathComponent232 let scoped = url.startAccessingSecurityScopedResource(); defer { if scoped { url.stopAccessingSecurityScopedResource() } }233 guard let data = try? Data(contentsOf: url, options: .mappedIfSafe) else { app.toasts.show("“\(name)” could not be read.", error: true); return }234 var card = AttachedDataset(name: name, bytes: data.count)235 let id = card.id236 if let refusal = VQDatasetUpload.validate(name: name, size: data.count, head: data.prefix(4096)) { card.phase = .failed(refusal.message(.en)); draft.datasets.append(card); return }237 draft.datasets.append(card)238 if draft.mode != .research, model.sessionId == nil, draft.datasets.count == 1 { draft.mode = .research } // a dataset calls for a study; the person can switch back239 func update(_ change: (inout AttachedDataset) -> Void) { if let i = draft.datasets.firstIndex(where: { $0.id == id }) { change(&draft.datasets[i]) } }240 Task {241 do {242 let sid: String243 if let existing = model.sessionId ?? draft.preparedSessionId {244 // a conversation that never used its workspace has none yet: the server creates it (or returns it)245 sid = try await app.studies.prepareWorkspace(sessionId: existing, title: nil, projectId: draft.projectId)246 } else {247 sid = try await app.studies.prepareWorkspace(sessionId: nil, title: nil, projectId: draft.projectId)248 draft.preparedSessionId = sid249 }250 let file = try await app.studies.upload(sessionId: sid, name: name, data: data)251 update { $0.uploaded = file; $0.phase = .inspecting }252 do {253 let inspection = try await app.studies.inspect(ResearchStore.studyRef(sessionId: sid), path: file.path)254 update { $0.inspection = inspection; $0.phase = .ready }255 } catch { update { $0.inspectionError = (error as? VQError)?.message ?? error.localizedDescription; $0.phase = .ready } }256 } catch { update { $0.phase = .failed(StudyStore.uploadMessage(error)) } }257 }258 }259}260261extension ResearchMode {262 /// One line under the composer.263 var oneLine: String {264 switch self {265 case .fast: "Fast — a short answer in under a minute: one round of data, little reasoning."266 case .standard: "Standard — a full research note with data, computations and figures."267 case .deep: "Deep — a plan, parallel sub-analysts and an independent audit; several minutes."268 case .ultra: "Ultra — two delegation rounds, a contrarian analyst, primary sources; the longest and most expensive."269 case .research: "Research — the agent designs, codes and runs its own study in a sandboxed workspace, keeps an experiment ledger and checks its numbers before answering."270 }271 }272 var short: String { switch self { case .fast: "Fast"; case .standard: "Standard"; case .deep: "Deep"; case .ultra: "Ultra"; case .research: "Research" } }273}274275/// The five modes as one segmented control; Research is the autonomous study.276struct ModePicker: View {277 @Binding var selection: ResearchMode278 /// Research is offered only on a server that has it.279 var research = true280 var body: some View {281 HStack(spacing: 1) {282 ForEach(ResearchMode.allCases.filter { research || $0 != .research || selection == .research }) { m in283 let on = m == selection284 Button { selection = m } label: {285 HStack(spacing: 4) {286 if m == .research { Image(systemName: "flask").font(.system(size: 9.5, weight: .semibold)) }287 Text(m.short).font(T.bodySm.f.weight(on ? .semibold : .regular))288 }289 .foregroundStyle(on ? (m == .research ? P.accentText : P.text1) : P.text2)290 .padding(.horizontal, 9).frame(height: 22)291 .background { if on { RoundedRectangle(cornerRadius: 5, style: .continuous).fill(P.ink2).overlay(RoundedRectangle(cornerRadius: 5, style: .continuous).strokeBorder(P.lineStrong, lineWidth: 1)) } }292 .contentShape(Rectangle())293 }294 .buttonStyle(.plain).help(m.detail)295 .accessibilityIdentifier("mode.\(m.rawValue)").accessibilityAddTraits(on ? [.isSelected, .isButton] : .isButton)296 }297 }298 .padding(2).background(P.ink3, in: RoundedRectangle(cornerRadius: 7, style: .continuous))299 .accessibilityElement(children: .contain).accessibilityLabel("Mode")300 }301}302303/// Cost and time limits of the next analysis; the defaults are the person's synced preference.304struct BudgetButton: View {305 let app: AppEnvironment306 @Bindable var draft: ComposerModel307 @State private var cost = ""308 @State private var minutes = ""309310 private var defaults: VQPreference.Budget? { app.sync.active?.preference.budget }311 private var effectiveCost: Double? { draft.maxCostUsd ?? defaults?.maxCostUsd }312 private var effectiveMinutes: Double? { draft.maxMinutes ?? defaults?.maxMinutes }313 private var label: String {314 let parts = [effectiveCost.map { "$" + Fmt.number($0, digits: 2) }, effectiveMinutes.map { "\(Int($0)) min" }].compactMap { $0 }315 return parts.isEmpty ? "No budget" : parts.joined(separator: " · ")316 }317318 var body: some View {319 Button { cost = draft.maxCostUsd.map { Fmt.number($0, digits: 2) } ?? ""; minutes = draft.maxMinutes.map { String(Int($0)) } ?? ""; draft.budgetOpen = true } label: {320 HStack(spacing: 5) {321 Image(systemName: "gauge.with.dots.needle.33percent").font(.system(size: 10)).foregroundStyle(P.text2)322 Text(label).font(T.numSm.f).foregroundStyle(draft.budget == nil ? P.text2 : P.text1)323 }324 .padding(.horizontal, 8).frame(height: 26)325 .background(P.ink3, in: RoundedRectangle(cornerRadius: 6, style: .continuous))326 .contentShape(Rectangle())327 }328 .buttonStyle(.plain).fixedSize().help("Budget of the next analysis: when a limit is reached the agent is asked to conclude")329 .accessibilityIdentifier("composer.budget")330 .popover(isPresented: $draft.budgetOpen, arrowEdge: .top) {331 VStack(alignment: .leading, spacing: 12) {332 VStack(alignment: .leading, spacing: 2) {333 Text("Budget of this analysis").font(T.heading.f)334 Text("When a limit is reached the agent is told to conclude; nothing further runs after one more round of tools. The cost limit counts known prices only.")335 .font(T.caption.f).foregroundStyle(P.text2).fixedSize(horizontal: false, vertical: true)336 }337 Grid(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 8) {338 GridRow {339 Text("Cost cap").font(T.bodySm.f)340 HStack(spacing: 4) { Text("$").font(T.numSm.f).foregroundStyle(P.text3); TextField(defaults?.maxCostUsd.map { Fmt.number($0, digits: 2) } ?? "none", text: $cost).textFieldStyle(.roundedBorder).frame(width: 90).accessibilityIdentifier("budget.cost") }341 Text("USD, up to 1 000").font(T.caption.f).foregroundStyle(P.text3)342 }343 GridRow {344 Text("Time cap").font(T.bodySm.f)345 HStack(spacing: 4) { Text(" ").font(T.numSm.f); TextField(defaults?.maxMinutes.map { String(Int($0)) } ?? "none", text: $minutes).textFieldStyle(.roundedBorder).frame(width: 90).accessibilityIdentifier("budget.minutes") }346 Text("minutes, up to 240").font(T.caption.f).foregroundStyle(P.text3)347 }348 }349 Text(defaults == nil ? "You have no default budget in your synced preferences." : "Empty fields use your synced default\(defaults?.maxCostUsd == nil && defaults?.maxMinutes == nil ? " (none set)" : "").")350 .font(T.caption.f).foregroundStyle(P.text3)351 HStack {352 Button("Use My Defaults") { draft.maxCostUsd = nil; draft.maxMinutes = nil; draft.budgetOpen = false }353 Spacer()354 Button("Set") { apply(); draft.budgetOpen = false }.keyboardShortcut(.defaultAction).accessibilityIdentifier("budget.set")355 }356 }357 .padding(14).frame(width: 380).vqTheme(app.vqTheme)358 }359 }360361 private func apply() {362 func parse(_ s: String) -> Double? { Double(s.replacingOccurrences(of: ",", with: ".").trimmingCharacters(in: .whitespaces)).flatMap { $0 > 0 ? $0 : nil } }363 draft.maxCostUsd = parse(cost).map { min($0, 1000) }364 draft.maxMinutes = parse(minutes).map { min($0.rounded(), 240) }365 }366}367368/// The models a person can pick, read from the server's registry: Auto first, then each provider's selectable models369/// with tier and stated price. When the registry cannot be read, the list 1.x shipped with — and the reason.370struct ModelPicker: View {371 let app: AppEnvironment372 let selection: String373 let pick: (String) -> Void374 @State private var filter = ""375376 private func matches(_ m: VQModelInfo) -> Bool {377 let q = filter.trimmingCharacters(in: .whitespaces).lowercased()378 return q.isEmpty || m.label.lowercased().contains(q) || m.id.lowercased().contains(q) || m.provider.lowercased().contains(q)379 }380381 var body: some View {382 let studies = app.studies383 VStack(alignment: .leading, spacing: 0) {384 HStack(spacing: 6) {385 Image(systemName: "magnifyingglass").font(.system(size: 11)).foregroundStyle(P.text3)386 TextField("Filter models", text: $filter).textFieldStyle(.plain).font(T.bodySm.f).accessibilityIdentifier("model.filter")387 if studies.catalogLoading { ProgressView().controlSize(.mini) }388 }389 .padding(.horizontal, 12).padding(.vertical, 9)390 Rectangle().fill(P.line).frame(height: 1)391 ScrollView {392 VStack(alignment: .leading, spacing: 0) {393 row(id: "auto", selected: selection == "auto") {394 Image(systemName: "wand.and.stars").font(.system(size: 12)).foregroundStyle(P.accentText).frame(width: 16)395 VStack(alignment: .leading, spacing: 1) {396 Text(studies.catalog?.auto.label ?? "Auto").font(T.bodySm.f.weight(.semibold)).foregroundStyle(P.text1)397 Text("The server routes each request (mode, attachments, your routing preference, prices) and says which model it chose and why.").font(T.caption.f).foregroundStyle(P.text2).fixedSize(horizontal: false, vertical: true)398 }399 }400 if let c = studies.catalog {401 if let at = studies.catalogCachedAt { notice("Offline: the registry as this Mac last received it (\(Fmt.relative(at))).") }402 ForEach(c.providers) { p in403 let models = p.models.filter { $0.selectable && matches($0) }404 if !models.isEmpty || (filter.isEmpty && !p.configured) {405 HStack(spacing: 6) {406 VQProviderLogo(provider: p.id, size: 12)407 Text(p.name.uppercased()).font(T.overline.f).tracking(0.9).foregroundStyle(P.text3)408 Spacer()409 if !p.configured { Text("not configured on the server").font(T.caption.f).foregroundStyle(P.text3) }410 else if !p.ok { Text(p.error ?? "listing unavailable").font(T.caption.f).foregroundStyle(P.warn).lineLimit(1) }411 }412 .padding(.horizontal, 12).padding(.top, 12).padding(.bottom, 4)413 ForEach(models) { m in414 row(id: m.id, selected: selection == m.id) {415 Color.clear.frame(width: 16, height: 1)416 Text(m.label).font(T.bodySm.f).foregroundStyle(P.text1).lineLimit(1)417 if m.id == c.defaultModel { Text("default").font(T.caption.f).foregroundStyle(P.text3) }418 Spacer(minLength: 8)419 if let t = m.tier { Text(t.rawValue).font(T.overline.f).tracking(0.6).foregroundStyle(t == .frontier ? P.accentText : P.text3) }420 Text(price(m)).font(T.numSm.f).foregroundStyle(m.pricing == nil ? P.text3 : P.text2).frame(width: 118, alignment: .trailing)421 }422 }423 }424 }425 Text("Prices are per million tokens (input · output) as the server states them; “not stated” is never filled in.")426 .font(T.caption.f).foregroundStyle(P.text3).padding(12).fixedSize(horizontal: false, vertical: true)427 } else {428 notice(studies.catalogError.map { "The server's model registry could not be read (\($0)). Showing the list this version shipped with; the server falls back to its default model for an id it does not offer." }429 ?? "Reading the server's model registry…")430 if studies.catalogError != nil {431 ForEach(ResearchModel.all.filter { filter.isEmpty || $0.name.lowercased().contains(filter.lowercased()) }, id: \.id) { m in432 row(id: m.id, selected: selection == m.id) {433 if let p = studies.provider(of: m.id) { VQProviderLogo(provider: p, size: 12).frame(width: 16) }434 Text(m.name).font(T.bodySm.f).foregroundStyle(P.text1)435 Spacer()436 }437 }438 }439 }440 }441 .padding(.bottom, 6)442 }443 }444 .frame(width: 460, height: 480)445 .task { await studies.loadCatalog(force: studies.catalog == nil) }446 }447448 private func price(_ m: VQModelInfo) -> String {449 guard let p = m.pricing, let i = p.inputPerMTok, let o = p.outputPerMTok else { return "price not stated" }450 return "$\(Fmt.number(i, digits: 2)) · $\(Fmt.number(o, digits: 2))"451 }452453 private func notice(_ text: String) -> some View {454 Text(text).font(T.caption.f).foregroundStyle(P.warn).padding(.horizontal, 12).padding(.vertical, 8).fixedSize(horizontal: false, vertical: true)455 .accessibilityIdentifier("model.notice")456 }457458 private func row<C: View>(id: String, selected: Bool, @ViewBuilder _ content: () -> C) -> some View {459 Button { pick(id) } label: {460 HStack(alignment: .firstTextBaseline, spacing: 8) {461 content()462 Image(systemName: "checkmark").font(.system(size: 10, weight: .bold)).foregroundStyle(P.accentText).opacity(selected ? 1 : 0)463 }464 .padding(.horizontal, 12).padding(.vertical, 6)465 .background(selected ? P.ink3 : Color.clear)466 .contentShape(Rectangle())467 }468 .buttonStyle(.plain)469 .accessibilityIdentifier("model.\(id)").accessibilityAddTraits(selected ? [.isSelected, .isButton] : .isButton)470 }471}472473/// A dataset in the research workspace: what the server's profile says about it (format, size, columns with type,474/// missing values, distinct values and examples, time columns, duplicated rows, the first rows).475struct DatasetCard: View {476 let app: AppEnvironment477 let dataset: AttachedDataset478 var remove: (() -> Void)?479 @State private var expanded = true480481 var body: some View {482 VStack(alignment: .leading, spacing: 0) {483 HStack(spacing: 8) {484 Image(systemName: "tablecells").foregroundStyle(P.text2)485 Text(dataset.uploaded?.path ?? dataset.name).font(.system(size: 12, weight: .medium, design: .monospaced)).foregroundStyle(P.text1).lineLimit(1).truncationMode(.middle)486 Text(VQFormat.bytes(dataset.bytes, language: .en)).font(T.numSm.f).foregroundStyle(P.text3)487 switch dataset.phase {488 case .uploading: ProgressView().controlSize(.mini); Text("uploading to the research workspace…").font(T.caption.f).foregroundStyle(P.text2)489 case .inspecting: ProgressView().controlSize(.mini); Text("profiling…").font(T.caption.f).foregroundStyle(P.text2)490 case .ready:491 if let i = dataset.inspection { Text(summary(i)).font(T.numSm.f).foregroundStyle(P.text2) }492 else { Text("uploaded · profile unavailable").font(T.caption.f).foregroundStyle(P.warn).help(dataset.inspectionError ?? "") }493 case .failed: EmptyView()494 }495 Spacer(minLength: 6)496 if dataset.inspection != nil { Button { expanded.toggle() } label: { Image(systemName: expanded ? "chevron.up" : "chevron.down").font(.system(size: 10, weight: .semibold)) }.buttonStyle(.borderless).help(expanded ? "Hide the profile" : "Show the profile") }497 if let remove { Button(action: remove) { Image(systemName: "xmark.circle.fill") }.buttonStyle(.borderless).help(dataset.uploaded == nil ? "Dismiss" : "Remove from this question (the file stays in the workspace)") }498 }499 .padding(.horizontal, 12).padding(.vertical, 8)500 if case .failed(let message) = dataset.phase {501 Rectangle().fill(P.line).frame(height: 1)502 Label(message, systemImage: "exclamationmark.triangle").font(T.caption.f).foregroundStyle(P.critical).padding(.horizontal, 12).padding(.vertical, 8).fixedSize(horizontal: false, vertical: true)503 .accessibilityIdentifier("dataset.error")504 }505 if expanded, let i = dataset.inspection {506 Rectangle().fill(P.line).frame(height: 1)507 DatasetProfile(inspection: i).padding(12)508 }509 }510 .background(P.ink1, in: RoundedRectangle(cornerRadius: VQTokens.Radius.md, style: .continuous))511 .overlay(RoundedRectangle(cornerRadius: VQTokens.Radius.md, style: .continuous).strokeBorder(P.line, lineWidth: 1))512 .accessibilityElement(children: .contain).accessibilityIdentifier("dataset.card")513 }514515 private func summary(_ i: VQDatasetInspection) -> String {516 "\(i.format.uppercased()) · \(i.rows.map { VQFormat.int($0, locale: .enCA) } ?? "—") rows × \(i.columnCount ?? i.columns.count) columns"517 }518}519520/// The server's profile of a dataset.521struct DatasetProfile: View {522 let inspection: VQDatasetInspection523 var maxColumnsHeight: CGFloat = 150524525 var body: some View {526 let i = inspection527 VStack(alignment: .leading, spacing: 10) {528 FlowLayout(spacing: 6) {529 chip("\(i.format.uppercased())")530 chip("\(i.rows.map { VQFormat.int($0, locale: .enCA) } ?? "—") rows")531 chip("\(i.columnCount ?? i.columns.count) columns")532 if let m = i.memoryMb { chip(String(format: "%.2f MB in memory", m)) }533 if let d = i.duplicatedRows { chip("\(d) duplicated row\(d == 1 ? "" : "s")", tone: d > 0 ? P.warn : P.text2) }534 if !i.timeColumns.isEmpty { chip("time: " + i.timeColumns.joined(separator: ", "), tone: P.info) }535 let missing = i.columns.filter { $0.missing > 0 }.count536 chip(missing == 0 ? "no missing value" : "\(missing) column\(missing == 1 ? "" : "s") with missing values", tone: missing == 0 ? P.text2 : P.warn)537 if i.truncated, let n = i.rowsProfiled { chip("profiled on the first \(VQFormat.int(n, locale: .enCA)) rows", tone: P.warn) }538 if !i.sheets.isEmpty { chip("sheets: " + i.sheets.joined(separator: ", ")) }539 }540 ScrollView {541 Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 4) {542 GridRow { ForEach(["Column", "Type", "Missing", "Distinct", "Examples / range"], id: \.self) { Text($0).font(T.overline.f).tracking(0.9).foregroundStyle(P.text3) } }543 ForEach(i.columns) { c in544 GridRow {545 Text(c.name).font(.system(size: 12, weight: .medium, design: .monospaced)).foregroundStyle(P.text1).lineLimit(1)546 Text(c.parsesAsDate ? "\(c.dtype) · date" : c.dtype).font(T.numSm.f).foregroundStyle(c.parsesAsDate ? P.info : P.text2)547 Text(c.missing == 0 ? "0" : "\(c.missing) (\(String(format: "%.1f", c.missingShare * 100)) %)").font(T.numSm.f).foregroundStyle(c.missing == 0 ? P.text3 : P.warn).gridColumnAlignment(.trailing)548 Text(c.distinct.map(String.init) ?? "—").font(T.numSm.f).foregroundStyle(P.text2).gridColumnAlignment(.trailing)549 Text(detail(c)).font(T.numSm.f).foregroundStyle(P.text2).lineLimit(1).truncationMode(.tail)550 }551 }552 }553 .frame(maxWidth: .infinity, alignment: .leading)554 }555 .frame(height: min(maxColumnsHeight, CGFloat(i.columns.count) * 20 + 22))556 if !i.head.isEmpty {557 let cols = i.columns.map(\.name)558 VStack(alignment: .leading, spacing: 4) {559 Text("FIRST ROWS").font(T.overline.f).tracking(0.9).foregroundStyle(P.text3)560 ScrollView(.horizontal) {561 Grid(alignment: .trailing, horizontalSpacing: 14, verticalSpacing: 3) {562 GridRow { ForEach(cols, id: \.self) { Text($0).font(.system(size: 10.5, weight: .semibold, design: .monospaced)).foregroundStyle(P.text2) } }563 ForEach(Array(i.head.prefix(4).enumerated()), id: \.offset) { _, row in564 GridRow { ForEach(cols, id: \.self) { c in Text(cell(row[c])).font(T.numSm.f).foregroundStyle(P.text1).lineLimit(1) } }565 }566 }567 .padding(.bottom, 4)568 }569 }570 }571 }572 .accessibilityElement(children: .contain).accessibilityIdentifier("dataset.profile")573 }574575 private func cell(_ v: VQJSON?) -> String {576 guard let v, !v.isNull else { return "—" }577 if let n = v.doubleValue { return n == n.rounded() && abs(n) < 1e12 ? String(Int(n)) : String(format: "%.4g", n) }578 return v.displayString ?? v.text()579 }580 private func detail(_ c: VQDatasetInspection.Column) -> String {581 if c.range.count == 2 { return "\(c.range[0].replacingOccurrences(of: " 00:00:00", with: "")) → \(c.range[1].replacingOccurrences(of: " 00:00:00", with: ""))" }582 if let lo = c.summary["min"], let hi = c.summary["max"], let mean = c.summary["mean"] { return "min \(String(format: "%.4g", lo)) · mean \(String(format: "%.4g", mean)) · max \(String(format: "%.4g", hi))" }583 return c.examples.prefix(3).map { cell($0) }.joined(separator: ", ")584 }585 private func chip(_ text: String, tone: Color = P.text2) -> some View {586 Text(text).font(T.numSm.f).foregroundStyle(tone).padding(.horizontal, 7).padding(.vertical, 3)587 .overlay(RoundedRectangle(cornerRadius: 5, style: .continuous).strokeBorder(P.line, lineWidth: 1))588 }589}590591private struct DatasetLabel: LabelStyle {592 let titles: Bool593 func makeBody(configuration: Configuration) -> some View { HStack(spacing: 4) { configuration.icon; if titles { configuration.title } } }594}595