SPB Git

Repository Public

ResearchViews.swift 50.1 KB 795 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Research/ResearchViews.swift3// Description: The research agent, centre of the product: conversations and studies, the transcript with reports and figures, the live view of an analysis running on the server, and — for a study — the research cockpit (report on the left, inspector on the right).4import SwiftUI5import UniformTypeIdentifiers6import VQuantCore7import VQuantKit8import VQuantUI910private typealias P = VQTokens.Palette11private typealias T = VQTokens.Typography1213/// What the list on the left shows.14enum ResearchScope: String, CaseIterable { case conversations, studies }1516/// A generation whose trace is shown.17struct TraceTarget: Identifiable { var generationId: String?; var sessionId: String?; var id: String { (generationId ?? "latest") + (sessionId ?? "") } }1819struct ResearchView: View {20    let app: AppEnvironment21    @Bindable var model: WindowModel22    @State private var search = ""23    @State private var draft: ComposerModel24    @State private var scope: ResearchScope = .conversations25    /// A study selected in the list that has no conversation yet (a project workspace, or one created for an upload).26    @State private var workspaceId: String?27    @State private var tab: InspectorTab = .activite28    @State private var selectedFile: String?29    @State private var trace: TraceTarget?30    @State private var seenDraftKey: UUID?31    @SceneStorage("research.inspector") private var inspectorShown = true32    @SceneStorage("research.listWidth") private var listWidth = 200.033    @SceneStorage("research.inspectorWidth") private var inspectorWidth = 462.03435    init(app: AppEnvironment, model: WindowModel) {36        self.app = app; self.model = model37        _draft = State(initialValue: ComposerModel(settings: app.settings))38    }3940    private var run: RunController? { model.sessionId.flatMap { app.research.run(for: $0) } ?? app.research.pendingRun(model.draftKey) }41    /// The study on screen: the conversation's, or the workspace picked in Studies.42    private var ref: String? { model.sessionId.map(ResearchStore.studyRef(sessionId:)) ?? workspaceId }43    private var study: VQResearchSessionStore? { run?.study ?? ref.flatMap { app.research.studies[$0] } }44    private var hasStudy: Bool {45        if run?.isResearch == true { return true }46        if let s = study, !s.state.isEmpty || s.detail != nil { return true }47        return false48    }4950    var body: some View {51        GeometryReader { geo in52            // three columns sized by this view (NSSplitView sizes its panes at their fitting width, which overflowed the53            // window once the inspector was added): the report keeps at least 380 pt, the list gives way first54            let showInspector = hasStudy && inspectorShown && study != nil && ref != nil55            let total = geo.size.width56            let inspector = showInspector ? min(max(340, CGFloat(inspectorWidth)), max(340, total - 380 - 180)) : 057            let list = min(max(180, CGFloat(listWidth)), max(180, total - 380 - inspector))58            if total < 600 { Color.clear } else {59            HStack(spacing: 0) {60                SessionList(app: app, model: model, search: $search, scope: $scope, workspaceId: $workspaceId, draft: draft)61                    .frame(width: list)62                ColumnDivider { d in listWidth = Double(min(360, max(180, list + d))) }63                ConversationPane(app: app, model: model, draft: draft, run: run, study: hasStudy ? study : nil, studyLoad: ref.flatMap { app.research.studyLoads[$0] }, workspaceId: workspaceId,64                                 inspectorShown: $inspectorShown, tab: $tab, trace: $trace)65                    .frame(maxWidth: .infinity)66                if showInspector, let study, let ref {67                    ColumnDivider { d in inspectorWidth = Double(min(760, max(340, inspector - d))) }68                    ResearchInspector(app: app, study: study, ref: ref, load: app.research.studyLoads[ref], isLive: run?.isActive == true, tab: $tab, selectedFile: $selectedFile) {69                        Task { await app.research.loadStudy(ref: ref, sessionId: model.sessionId, force: true) }70                    }71                    .frame(width: inspector)72                }73            }74            }75        }76        // a constant minimum: a size that depends on what is shown made the window's split view loop on its constraints77        .frame(minWidth: 760, minHeight: 420)78        .background(P.ink0)79        .sheet(item: Binding(get: { app.research.presentedApproval }, set: { app.research.presentedApproval = $0 })) { a in ApprovalSheet(app: app, approval: a).vqTheme(app.vqTheme) }80        .sheet(item: $trace) { t in TraceSheet(app: app, generationId: t.generationId, sessionId: t.sessionId).vqTheme(app.vqTheme) }81        .focusedSceneValue(\.researchActions, ResearchActions(82            newStudy: { draft.resetDraft(settings: app.settings); draft.mode = .research; workspaceId = nil; model.openConversation(nil); draft.focusTick += 1 },83            attachDataset: { draft.importerOpen = true },84            stop: run?.isActive == true ? { if let run { Task { await app.research.stop(run) } } } : nil,85            toggleInspector: { inspectorShown.toggle() }))86        .task(id: search) {87            if !search.isEmpty { try? await Task.sleep(for: .milliseconds(350)) }88            if !Task.isCancelled { await app.research.refreshSessions(search: search) }89        }90        .task {91            await debugLaunch()92            await app.studies.refreshWorkspaces()93            await app.research.refreshApprovals()94        }95        .task(id: workspaceId) {96            // a study without a conversation: its workspace is read by its own id97            if model.sessionId == nil, let w = workspaceId { await app.research.loadStudy(ref: w) }98        }99        .onChange(of: model.draftKey, initial: true) { _, _ in syncDraft() }100        .onChange(of: model.pendingAsk, initial: true) { _, _ in syncDraft() }101    }102103    /// A new conversation starts from an empty draft; a question prepared elsewhere in the window (chart, statement,104    /// lab, studio, menu bar) fills it: text in the composer, context appended in plain words when sent.105    private func syncDraft() {106        if let ask = model.pendingAsk {107            draft.resetDraft(settings: app.settings)108            draft.text = ask.text; draft.context = ask.context; draft.projectId = ask.projectId109            if let m = ask.mode { draft.mode = m }110            model.pendingAsk = nil; seenDraftKey = model.draftKey111            draft.focusTick += 1112            if ask.sendImmediately { draft.sendTick += 1 }113        } else if seenDraftKey != model.draftKey {114            if seenDraftKey != nil, model.sessionId == nil { let project = workspaceProject; draft.resetDraft(settings: app.settings); draft.projectId = project }115            seenDraftKey = model.draftKey116        }117    }118    /// A project workspace picked in Studies: a new conversation is filed in that project.119    private var workspaceProject: String? { workspaceId.flatMap { w in app.studies.workspaces.first { $0.id == w && $0.kind == .project }?.ref } }120121    /// DEBUG launch arguments of this section (visual checks and UI tests; none of them calls a model):122    /// `-VQTab studies` · `-VQXInspector <activite|code|experiences|figures|fichiers|environnement>` · `-VQXFile <path>` ·123    /// `-VQXStudyFixture <dir>` (recorded study) [`-VQXStudyEvents <n>`: the first n recorded events as a running study] ·124    /// `-VQXApproval 1` (a recorded-shape approval request) · `-VQXModelPicker 1` · `-VQXTrace 1` · `-VQXMode <mode>` ·125    /// `-VQXModel <id|auto>` · `-VQXDraft <text>` · `-VQXDataset <file>` (uploads it to the test backend) · `-VQXBudget 1` · `-VQXBudgetCost <usd>` · `-VQXStudy <workspace id>` ·126    /// `-VQXSend 1` (SENDS the draft through the composer: a model is called — live verification only).127    private func debugLaunch() async {128        #if DEBUG129        let x = app.options.extra130        if model.launchTab == "studies" { scope = .studies; model.launchTab = nil }131        if let t = x["Inspector"].flatMap(InspectorTab.init(rawValue:)) { tab = t }132        if let f = x["File"] { selectedFile = f }133        if let m = x["Mode"].flatMap(ResearchMode.init(rawValue:)) { draft.mode = m }134        if let m = x["Model"] { draft.model = m }135        if let m = x["DefaultModel"] { app.settings.researchModel = m; draft.model = m }   // restores the synced default after a test changed it136        if let t = x["Draft"] { draft.text = t }137        if let dir = x["StudyFixture"], app.studies.fixture == nil, let f = StudyFixture(directory: URL(fileURLWithPath: (dir as NSString).expandingTildeInPath, isDirectory: true)) {138            app.studies.fixture = f139            app.research.debugInstall(conversation: f.conversation)140            let s = app.research.study(sessionId: f.sessionId)141            s.install(detail: VQResearchSessionDetail(json: f.detail), conversation: f.conversation, sandbox: VQSandboxStatus(json: f.sandbox))142            app.research.debugMark(ref: ResearchStore.studyRef(sessionId: f.sessionId), .loaded(cachedAt: nil))143            if let n = x["StudyEvents"].flatMap(Int.init) {144                let fresh = VQResearchSessionStore(client: nil)145                app.research.debugRun(sessionId: f.sessionId, question: f.events.first?["query"]?.stringValue ?? "", mode: "research", events: Array(f.events.prefix(n)), study: fresh)146            }147            model.sessionId = f.sessionId148        }149        if x["Approval"] != nil {150            let a: VQJSON = ["type": "approval_request", "approval": ["id": "fixture-approval", "action": "open_network", "reason": "Download the FRED series CPIAUCSL and UNRATE to extend the sample to 2026 (the workspace only holds data to 2009Q3).",151                                                                     "detail": ["host": "api.stlouisfed.org", "script": "code/fetch_fred.py", "purpose": "extend the macro sample"], "status": "pending",152                                                                     "createdAt": .number((Date().timeIntervalSince1970 - 190) * 1000)]]153            if let asked = a["approval"].map(VQResearchApproval.init(json:)) { app.research.noteApproval(asked, ref: nil, present: true) }154        }155        if x["ModelPicker"] != nil { try? await Task.sleep(for: .milliseconds(800)); draft.modelPickerOpen = true }156        if x["Budget"] != nil { try? await Task.sleep(for: .milliseconds(800)); draft.budgetOpen = true }157        if x["Trace"] != nil { try? await Task.sleep(for: .milliseconds(800)); trace = TraceTarget(generationId: nil, sessionId: model.sessionId) }158        if let path = x["Dataset"] { draft.debugDataset = URL(fileURLWithPath: (path as NSString).expandingTildeInPath) }159        if let c = x["BudgetCost"].flatMap(Double.init) { draft.maxCostUsd = c }160        if let every = x["TabCycle"].flatMap(Double.init), every >= 2 {161            // captures of a live study on each tab without synthetic input: the inspector moves to the next tab every n seconds162            Task { while !Task.isCancelled { try? await Task.sleep(for: .seconds(every)); let all = InspectorTab.allCases; tab = all[((all.firstIndex(of: tab) ?? 0) + 1) % all.count] } }163        }164        if let st = x["Study"] { scope = .studies; workspaceId = st; if st.hasPrefix("s-") { model.sessionId = String(st.dropFirst(2)) } }165        if x["Send"] != nil, !draft.text.isEmpty {166            // the composer's own send, once what is attached has been uploaded and profiled (live verification without synthetic input)167            try? await Task.sleep(for: .seconds(2))168            for _ in 0..<120 where draft.busyWithDataset || (x["Dataset"] != nil && draft.datasets.first?.phase != .ready) { try? await Task.sleep(for: .milliseconds(500)) }169            if x["Dataset"] == nil || draft.datasets.first?.phase == .ready { draft.sendTick += 1 }170        }171        #endif172    }173}174175/// A hairline between two columns that can be dragged.176private struct ColumnDivider: View {177    let drag: (CGFloat) -> Void178    @State private var last: CGFloat = 0179    var body: some View {180        Rectangle().fill(P.line).frame(width: 1)181            .overlay {182                Color.clear.frame(width: 9).contentShape(Rectangle())183                    .onHover { inside in if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() } }184                    .gesture(DragGesture(minimumDistance: 1, coordinateSpace: .global)185                        .onChanged { v in drag(v.translation.width - last); last = v.translation.width }186                        .onEnded { _ in last = 0 })187            }188            .accessibilityHidden(true)189    }190}191192private struct SessionList: View {193    let app: AppEnvironment194    @Bindable var model: WindowModel195    @Binding var search: String196    @Binding var scope: ResearchScope197    @Binding var workspaceId: String?198    let draft: ComposerModel199    @State private var renaming: SessionSummary?200    @State private var newTitle = ""201    @State private var deleting: SessionSummary?202203    var body: some View {204        VStack(spacing: 0) {205            HStack(spacing: 8) {206                HStack(spacing: 1) {207                    ForEach(ResearchScope.allCases, id: \.self) { sc in208                        let on = sc == scope209                        Button { scope = sc } label: {210                            Text(sc == .conversations ? "Conversations" : "Studies").font(.system(size: 12, weight: on ? .semibold : .regular)).foregroundStyle(on ? P.text1 : P.text2).lineLimit(1)211                                .padding(.horizontal, 8).frame(height: 22)212                                .background { if on { RoundedRectangle(cornerRadius: 5, style: .continuous).fill(P.ink2).overlay(RoundedRectangle(cornerRadius: 5, style: .continuous).strokeBorder(P.lineStrong, lineWidth: 1)) } }213                                .contentShape(Rectangle())214                        }215                        .buttonStyle(.plain).accessibilityIdentifier("scope.\(sc.rawValue)").accessibilityAddTraits(on ? [.isSelected, .isButton] : .isButton)216                    }217                }218                .padding(2).background(P.ink3, in: RoundedRectangle(cornerRadius: 7, style: .continuous)).fixedSize()219                Spacer(minLength: 0)220                Button { workspaceId = nil; model.openConversation(nil) } label: { Image(systemName: "square.and.pencil") }.buttonStyle(.borderless).help("New conversation (⌥⌘N)")221                    .accessibilityIdentifier("research.new")222            }223            .padding(.horizontal, 10).padding(.top, 10).padding(.bottom, 6)224            if scope == .conversations {225                TextField("Search conversations", text: $search).textFieldStyle(.roundedBorder).padding(.horizontal, 10).padding(.bottom, 8)226                if app.research.sessionsFromCache { Text("Offline — list from this Mac's cache").font(T.caption.f).foregroundStyle(P.warn).padding(.bottom, 4) }227                conversations228            } else { studies }229        }230        .background(P.ink1)231        .alert("Rename Conversation", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {232            TextField("Title", text: $newTitle)233            Button("Rename") { if let r = renaming { Task { await app.research.rename(r.sessionId, newTitle) } } }234            Button("Cancel", role: .cancel) {}235        }236        .confirmationDialog("Delete “\(deleting?.title ?? "")”?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } })) {237            Button("Delete Conversation", role: .destructive) {238                if let d = deleting { Task { await app.research.delete(d.sessionId); if model.sessionId == d.sessionId { model.openConversation(nil) } } }239            }240        } message: { Text("The conversation is deleted on the server, for every device. This cannot be undone.") }241        .onChange(of: scope) { _, s in if s == .studies { Task { await app.studies.refreshWorkspaces() } } }242    }243244    private var conversations: some View {245        List {246            ForEach(app.research.sessions) { s in247                SelectableRow(isSelected: model.sessionId == s.sessionId) { workspaceId = nil; model.sessionId = s.sessionId } content: { HStack(spacing: 6) {248                    if app.research.run(for: s.sessionId)?.isActive == true { ProgressView().controlSize(.mini) }249                    else if s.pinned { Image(systemName: "pin.fill").font(.caption2).foregroundStyle(.secondary) }250                    VStack(alignment: .leading, spacing: 1) {251                        Text(s.title).lineLimit(2)252                        HStack(spacing: 5) {253                            Text(Fmt.relative(s.updated)).font(.caption2).foregroundStyle(.tertiary)254                            if app.studies.workspace(ofSession: s.sessionId) != nil { Label("study", systemImage: "flask").labelStyle(.titleAndIcon).font(.caption2).foregroundStyle(P.accentText) }255                        }256                    }257                } }258                .accessibilityIdentifier("session.\(s.sessionId)")259                .contextMenu {260                    Button(s.pinned ? "Unpin" : "Pin") { Task { await app.research.pin(s.sessionId, !s.pinned) } }261                    Button("Rename…") { newTitle = s.title; renaming = s }262                    Divider()263                    Button("Delete…", role: .destructive) { deleting = s }264                }265            }266        }267        .listStyle(.inset).scrollContentBackground(.hidden)268        .overlay { if app.research.sessions.isEmpty { EmptyState(symbol: "bubble.left.and.text.bubble.right", title: search.isEmpty ? "No conversation yet" : "No match", detail: app.research.sessionsError) } }269    }270271    /// Research workspaces of the person, newest first: session- or project-bound, with the conversations they hold.272    private var studies: some View {273        let list = app.studies.workspaces274        return VStack(spacing: 0) {275            if let at = app.studies.workspacesCachedAt { Text("Offline — studies as last received (\(Fmt.relative(at)))").font(T.caption.f).foregroundStyle(P.warn).padding(.bottom, 4) }276            List {277                ForEach(list) { w in278                    let running = w.sessionIds.contains { id in app.research.generations.contains { $0.sessionId == id && $0.status == .running } }279                    SelectableRow(isSelected: workspaceId == w.id || (model.sessionId.map { w.sessionIds.contains($0) || ($0 == w.ref && w.kind == .session) } ?? false)) { open(w) } content: {280                        VStack(alignment: .leading, spacing: 3) {281                            Text(w.title ?? (w.kind == .project ? "Project workspace" : "Untitled study")).lineLimit(2)282                            HStack(spacing: 6) {283                                if running { ProgressView().controlSize(.mini) }284                                Text(w.kind == .project ? "PROJECT" : "SESSION").font(T.overline.f).tracking(0.8).foregroundStyle(w.kind == .project ? P.info : P.text3).fixedSize()285                                Text(Fmt.relative(w.updatedAt) + (w.sessionIds.count > 1 ? " · \(w.sessionIds.count) conversations" : w.sessionIds.isEmpty ? " · no conversation yet" : "")).font(.caption2).foregroundStyle(.tertiary).lineLimit(1)286                            }287                        }288                    }289                    .accessibilityIdentifier("study.\(w.id)")290                    .contextMenu {291                        ForEach(w.sessionIds, id: \.self) { id in292                            Button("Open “\(app.research.sessions.first { $0.sessionId == id }?.title ?? id)”") { workspaceId = w.id; model.sessionId = id }293                        }294                        Button("Copy Workspace ID") { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(w.id, forType: .string) }295                    }296                }297            }298            .listStyle(.inset).scrollContentBackground(.hidden)299            .overlay {300                if list.isEmpty {301                    if !app.studies.workspacesLoaded { ProgressView() }302                    else { EmptyState(symbol: "flask", title: "No study yet", detail: app.studies.workspacesError ?? "A study starts when the agent uses its research workspace: pick the Research mode or attach a dataset.") }303                }304            }305        }306    }307308    /// Opens a study on its latest conversation; one that has none yet opens on its workspace with an empty composer.309    private func open(_ w: VQResearchSession) {310        workspaceId = w.id311        if let last = w.sessionIds.last { model.sessionId = last }312        else if w.kind == .session { model.sessionId = w.ref }313        else { model.openConversation(nil); draft.projectId = w.ref }314    }315}316317private struct ConversationPane: View {318    let app: AppEnvironment319    @Bindable var model: WindowModel320    let draft: ComposerModel321    let run: RunController?322    /// The study of this conversation when it has one (the cockpit is then shown).323    let study: VQResearchSessionStore?324    let studyLoad: StudyLoad?325    let workspaceId: String?326    @Binding var inspectorShown: Bool327    @Binding var tab: InspectorTab328    @Binding var trace: TraceTarget?329    @State private var loading = false330331    private var conversation: Cached<Conversation>? { model.sessionId.flatMap { app.research.conversations[$0] } }332333    var body: some View {334        VStack(spacing: 0) {335            if study != nil || conversation != nil || run != nil { header }336            if let c = conversation, c.fromCache { NoticeBar(kind: .cached, text: "Offline: this conversation was last received \(Fmt.relative(c.fetchedAt)).") }337            ScrollViewReader { proxy in338                ScrollView {339                    LazyVStack(alignment: .leading, spacing: 22) {340                        if let turns = conversation?.value.turns, let sid = model.sessionId {341                            // once the server has saved the answer of the run on screen, that turn exists twice (saved and live):342                            // the live form is kept (it carries the activity and the follow-ups) and the saved copy is not repeated343                            let duplicated = run.map { r in r.state.finished && turns.last?.question == r.question && turns.last?.answer == r.state.answer } ?? false344                            ForEach(Array(turns.enumerated()), id: \.offset) { i, t in345                                if !(duplicated && i == turns.count - 1) {346                                    TurnView(app: app, model: model, turn: t, meta: app.research.meta(sid, turn: i), sessionId: sid, isLast: i == turns.count - 1 && run == nil, trace: $trace) { tab = .activite; inspectorShown = true }347                                        .id("turn-\(i)")348                                }349                            }350                        }351                        if let run { RunView(app: app, model: model, run: run, draft: draft, trace: $trace, hasInspector: study != nil) { tab = .activite; inspectorShown = true }.id("run") }352                        if conversation == nil, run == nil {353                            if loading { ProgressView().frame(maxWidth: .infinity).padding(40) }354                            else if study != nil { StudyWelcome(title: app.studies.workspaces.first { $0.id == workspaceId }?.title) }355                            else { Welcome(app: app, model: model, draft: draft) }356                        }357                        Color.clear.frame(height: 1).id("end")358                    }359                    .padding(.horizontal, 28).padding(.vertical, 20)360                    .frame(maxWidth: 900, alignment: .leading).frame(maxWidth: .infinity)361                }362                .onChange(of: run?.state.answer.count) { _, _ in if run?.isActive == true { proxy.scrollTo("end", anchor: .bottom) } }363                // a stored conversation opens on the start of its latest answer (a report is read from its top)364                .onChange(of: conversation?.value.turns.count) { _, n in if let n, n > 0, run == nil { proxy.scrollTo("turn-\(n - 1)", anchor: .top) } }365            }366            ApprovalBanner(app: app)367            Rectangle().fill(P.line).frame(height: 1)368            Composer(app: app, model: model, draft: draft, run: run)369        }370        .background(P.ink0)371        .task {372            #if DEBUG373            if let q = app.options.ask, model.sessionId == nil, app.research.pendingRun(model.draftKey) == nil {374                app.research.ask(q, sessionId: nil, key: model.draftKey, mode: .fast, model: "claude-haiku-5-5")375            }376            #endif377        }378        .task(id: model.sessionId) {379            guard let id = model.sessionId else { return }380            #if DEBUG381            if app.studies.fixture != nil { return }382            #endif383            loading = conversation == nil && run == nil384            await app.research.loadConversation(id)385            loading = false386            // a job running for this conversation (started on another device, or before this app was reopened) is followed here too387            if app.research.run(for: id) == nil {388                await app.research.refreshGenerations()389                if let g = app.research.generations.first(where: { $0.sessionId == id && $0.status == .running }) { app.research.attach(g) }390            }391            // …and its research workspace, when it has one, is read by REST (ledger, runs, files, environment)392            await app.research.loadStudy(ref: ResearchStore.studyRef(sessionId: id), sessionId: id)393        }394        .task(id: run?.isActive == true ? model.sessionId : nil) {395            // while a study runs, what the stream does not carry (notes in full, environment, pending approvals) is re-read now and then396            guard run?.isActive == true, let id = model.sessionId else { return }397            while !Task.isCancelled {398                try? await Task.sleep(for: .seconds(20))399                if Task.isCancelled { break }400                if run?.study.workspaceId != nil { await app.research.loadStudy(ref: ResearchStore.studyRef(sessionId: id), sessionId: id, force: true) }401            }402        }403        .onChange(of: run?.state.sessionId, initial: true) { _, sid in404            // a new conversation has been named by the server: the window now shows that conversation405            if model.sessionId == nil, let sid { model.sessionId = sid; app.research.adopt(model.draftKey) }406        }407    }408409    private var title: String {410        if let id = model.sessionId, let t = app.research.sessions.first(where: { $0.sessionId == id })?.title, !t.isEmpty { return t }411        if let t = conversation?.value.title, !t.isEmpty { return t }412        if let w = app.studies.workspaces.first(where: { $0.id == workspaceId || (model.sessionId != nil && $0.sessionIds.contains(model.sessionId!)) }), let t = w.title { return t }413        if let q = run?.question { return String(q.prefix(90)) }414        return study != nil ? "Study" : "Conversation"415    }416417    /// The masthead of the conversation: what it is, where it stands, and the cockpit's controls.418    private var header: some View {419        HStack(alignment: .center, spacing: 10) {420            VStack(alignment: .leading, spacing: 3) {421                Text(title).font(T.title.f).foregroundStyle(P.text1).lineLimit(1).truncationMode(.tail)422                HStack(spacing: 8) {423                    if study != nil { Label("RESEARCH STUDY", systemImage: "flask").font(T.overline.f).tracking(0.9).foregroundStyle(P.accentText) }424                    if run?.isActive == true { HStack(spacing: 4) { ProgressView().controlSize(.mini); Text("running on the server").font(T.caption.f).foregroundStyle(P.text2) } }425                    if let s = study {426                        let c = s.counts427                        Text([Counted.text(c.executions, "execution"), Counted.text(c.experiments, "experiment"), Counted.text(c.figures, "figure")].joined(separator: " · ")).font(T.numSm.f).foregroundStyle(P.text3).lineLimit(1)428                    }429                    if case .loaded(let at?)? = studyLoad { Label("cached \(Fmt.relative(at))", systemImage: "internaldrive").font(T.caption.f).foregroundStyle(P.warn) }430                    if case .failed(let m)? = studyLoad { Label("workspace unreadable", systemImage: "exclamationmark.triangle").font(T.caption.f).foregroundStyle(P.warn).help(m) }431                }432            }433            Spacer(minLength: 8)434            if model.sessionId != nil, conversation != nil {435                Button { trace = TraceTarget(generationId: nil, sessionId: model.sessionId) } label: { Label("Trace", systemImage: "list.bullet.indent") }436                    .help("Execution trace of the latest analysis of this conversation").accessibilityIdentifier("conversation.trace")437            }438            if study != nil {439                Button { inspectorShown.toggle() } label: { Label("Inspector", systemImage: "sidebar.right") }440                    .help(inspectorShown ? "Hide the inspector (⌥⌘I)" : "Show the inspector (⌥⌘I)").keyboardShortcut("i", modifiers: [.option, .command])441                    .accessibilityIdentifier("conversation.inspector")442            }443        }444        .labelStyle(.iconOnly).buttonStyle(.borderless)445        .padding(.horizontal, 28).padding(.vertical, 12)446        .background(P.ink0)447        .overlay(alignment: .bottom) { Rectangle().fill(P.line).frame(height: 1) }448    }449}450451private struct Welcome: View {452    let app: AppEnvironment453    let model: WindowModel454    let draft: ComposerModel455    var body: some View {456        VStack(spacing: 12) {457            Sparkle(size: 40)458            Text("Ask the research agent").font(T.displayMd.f).foregroundStyle(P.text1)459            Text("The agent runs on the VQuant server: market and fundamental data, web sources, a Python notebook, and — in deep modes — parallel sub-analysts and an independent audit. In Research mode it designs, codes and runs its own study in a sandboxed workspace, with an experiment ledger and a quality gate. An analysis continues on the server if you close this window.")460                .font(T.bodySm.f).foregroundStyle(P.text2).multilineTextAlignment(.center).frame(maxWidth: 580)461            Button { draft.mode = .research; draft.importerOpen = true } label: { Label("Start a study from a dataset…", systemImage: "tablecells.badge.ellipsis") }462                .buttonStyle(.link).font(T.bodySm.f).accessibilityIdentifier("welcome.dataset")463        }464        .frame(maxWidth: .infinity).padding(.top, 60)465    }466}467468/// A study opened on its workspace: there is no message in this window yet.469private struct StudyWelcome: View {470    let title: String?471    var body: some View {472        VStack(spacing: 10) {473            Image(systemName: "flask").font(.system(size: 30, weight: .light)).foregroundStyle(P.accentText)474            Text(title ?? "Research workspace").font(T.title.f).foregroundStyle(P.text1)475            Text("This workspace holds no conversation in this window yet. Its files, ledger, runs and environment are in the inspector; a question asked below continues the study in the same workspace.")476                .font(T.bodySm.f).foregroundStyle(P.text2).multilineTextAlignment(.center).frame(maxWidth: 520)477        }478        .frame(maxWidth: .infinity).padding(.top, 60)479    }480}481482/// What an answer states about itself: model, tokens and cost, provenance, trace, and the outcome of the research gate.483private struct AnswerFooter: View {484    let app: AppEnvironment485    let usage: VQUsage?486    let modelId: String?487    let provenance: [VQProvenanceSource]488    let generationId: String?489    let sessionId: String?490    let research: VQMessageResearch?491    @Binding var trace: TraceTarget?492    var openActivity: () -> Void493494    var body: some View {495        if usage != nil || modelId != nil || !provenance.isEmpty || generationId != nil || research != nil {496            FlowLayout(spacing: 14) {497                UsageLine(app: app, usage: usage, model: modelId ?? usage?.byModel.first(where: { $0.role == .lead })?.model)498                ProvenanceButton(app: app, sources: provenance)499                if let generationId {500                    Button { trace = TraceTarget(generationId: generationId, sessionId: sessionId) } label: { Label("Trace", systemImage: "list.bullet.indent").font(T.caption.f).foregroundStyle(P.text2) }501                        .buttonStyle(.plain).help("Plan, agents, tool calls and usage of this generation").accessibilityIdentifier("answer.trace")502                }503                if let r = research {504                    Button(action: openActivity) {505                        HStack(spacing: 5) {506                            Image(systemName: "flask").font(.system(size: 10))507                            Text("\(r.executionsTotal) execution\(r.executionsTotal == 1 ? "" : "s")\(r.executionsFailed > 0 ? " · \(r.executionsFailed) failed" : "") · \(r.experiments.count) experiment\(r.experiments.count == 1 ? "" : "s")")508                            if let g = r.qualityGate {509                                let open = g.filter(\.isOpen).count510                                Text(open == 0 ? "· gate passed" : "· gate: \(open) open finding\(open == 1 ? "" : "s")").foregroundStyle(open == 0 ? P.text2 : P.warn)511                            }512                        }513                        .font(T.caption.f).foregroundStyle(P.text2)514                    }515                    .buttonStyle(.plain).help("Open the study's activity").accessibilityIdentifier("answer.research")516                }517            }518            .padding(.top, 2)519        }520    }521}522523/// A saved exchange.524private struct TurnView: View {525    let app: AppEnvironment526    let model: WindowModel527    let turn: Turn528    let meta: TurnMeta529    let sessionId: String530    let isLast: Bool531    @Binding var trace: TraceTarget?532    var openActivity: () -> Void533    @State private var showCode = false534535    var body: some View {536        VStack(alignment: .leading, spacing: 12) {537            QuestionBubble(text: turn.question)538            MarkdownView(app: app, source: turn.answer)539            // figures the report does not place itself540            let placed = turn.answer541            ForEach(turn.customPythonFigures.flatMap(\.figureUrls).filter { !placed.contains($0) }, id: \.self) { FigureView(app: app, path: $0, caption: "") }542            if !turn.sources.isEmpty { SourcesView(sources: turn.sources) }543            AnswerFooter(app: app, usage: meta.extras.usage, modelId: meta.extras.model, provenance: meta.extras.provenance, generationId: meta.extras.generationId, sessionId: sessionId, research: meta.research, trace: $trace, openActivity: openActivity)544            HStack(spacing: 12) {545                if !turn.toolResults.isEmpty { Text("\(turn.toolResults.count) tool call\(turn.toolResults.count == 1 ? "" : "s"): \(Array(Set(turn.toolResults.map(\.tool))).sorted().prefix(6).joined(separator: ", "))").font(.caption).foregroundStyle(.tertiary).lineLimit(1) }546                if let code = turn.pythonCode, !code.isEmpty { Button(showCode ? "Hide Python" : "Show Python") { showCode.toggle() }.buttonStyle(.link).font(.caption) }547                Spacer()548                ReportActions(app: app, question: turn.question, answer: turn.answer, sources: turn.sources, figures: turn.customPythonFigures)549            }550            if showCode, let code = turn.pythonCode { CodeBlock(language: "python", text: code) }551        }552    }553}554555struct QuestionBubble: View {556    let text: String557    @State private var expanded = false558    private var isLong: Bool { text.count > 420 }559    var body: some View {560        VStack(alignment: .trailing, spacing: 4) {561            // no accessibility label here: a label on (or around) selectable text reaches its platform element and macOS 27562            // recurses resolving it — the app crashed under XCUITest as soon as a stored conversation was on screen (2026-11-20)563            Text(text).textSelection(.enabled).lineLimit(isLong && !expanded ? 5 : nil)564            if isLong { Button(expanded ? "Show less" : "Show the whole question") { expanded.toggle() }.buttonStyle(.link).font(.caption) }565        }566        .padding(.horizontal, 12).padding(.vertical, 8)567        .background(VQTokens.Palette.accent.opacity(0.12), in: RoundedRectangle(cornerRadius: 10))568        .frame(maxWidth: .infinity, alignment: .trailing)569    }570}571572struct SourcesView: View {573    let sources: [WebSource]574    @State private var open = false575    var body: some View {576        DisclosureGroup("\(sources.count) source\(sources.count == 1 ? "" : "s")", isExpanded: $open) {577            VStack(alignment: .leading, spacing: 4) {578                ForEach(sources) { s in579                    if let url = URL(string: s.url), url.scheme == "https" || url.scheme == "http" {580                        Link(destination: url) { HStack(alignment: .firstTextBaseline) { Text(s.title).lineLimit(1); Text(url.host ?? "").font(.caption).foregroundStyle(.secondary) } }581                    } else { Text(s.title) }582                }583            }.padding(.top, 4)584        }585        .font(.callout)586    }587}588589590/// The analysis as it runs: what the agent is doing, its plan, its tools and sub-analysts, and the report as it is written.591struct RunView: View {592    let app: AppEnvironment593    let model: WindowModel594    let run: RunController595    var draft: ComposerModel?596    @Binding var trace: TraceTarget?597    /// The research inspector is on screen: the activity is detailed there, so it starts folded here.598    var hasInspector = false599    var openActivity: () -> Void = {}600    @State private var showActivity: Bool?601602    var body: some View {603        let s = run.state604        VStack(alignment: .leading, spacing: 12) {605            QuestionBubble(text: run.question)606            HStack(spacing: 8) {607                switch run.phase {608                case .connecting: ProgressView().controlSize(.small); Text("Starting on the server…")609                case .streaming: if !s.finished { ProgressView().controlSize(.small) }; Text(s.finished ? "Finished" : (s.status.isEmpty ? "Working…" : s.status))610                case .reconnecting(let n): ProgressView().controlSize(.small); Text("Connection lost — reconnecting (attempt \(n)). The analysis continues on the server.").foregroundStyle(.orange)611                case .finished: Image(systemName: s.error == nil ? "checkmark.circle.fill" : "exclamationmark.triangle.fill").foregroundStyle(s.error == nil ? Palette.green : Palette.red); Text(s.error == nil ? "Finished" : "Interrupted")612                case .lost(let m): Image(systemName: "wifi.exclamationmark").foregroundStyle(.orange); Text(m).foregroundStyle(.orange)613                }614                Spacer()615                if run.isActive, s.jobId != nil { Button("Stop", role: .destructive) { Task { await app.research.stop(run) } }.help("Stops the analysis on the server").accessibilityIdentifier("run.stop") }616                if let b = run.budget, !b.isEmpty {617                    Text([b.maxCostUsd.map { "≤ $" + Fmt.number($0, digits: 2) }, b.maxMinutes.map { "≤ \(Int($0)) min" }].compactMap { $0 }.joined(separator: " · ")).font(T.numSm.f).foregroundStyle(P.text3).help("Budget of this analysis")618                }619                Text(ResearchMode(rawValue: run.mode)?.title ?? run.mode).font(.caption).padding(.horizontal, 6).padding(.vertical, 2).background(Color.secondary.opacity(0.12), in: Capsule())620            }621            .font(.callout)622            .accessibilityElement(children: .combine)623624            RouteLine(app: app, requested: run.requestedModel, route: run.route, waiting: run.isActive && s.answer.isEmpty)625            ForEach(Array(run.budgetHits.enumerated()), id: \.offset) { _, b in BudgetNote(event: b) }626627            if !s.plan.isEmpty || !s.tools.isEmpty || !s.agents.isEmpty {628                DisclosureGroup(isExpanded: Binding(get: { showActivity ?? !hasInspector }, set: { showActivity = $0 })) {629                    VStack(alignment: .leading, spacing: 8) {630                        if !s.plan.isEmpty {631                            VStack(alignment: .leading, spacing: 3) {632                                ForEach(s.plan, id: \.self) { step in633                                    Label(step.title, systemImage: step.status == "done" ? "checkmark.circle.fill" : step.status == "in_progress" ? "circle.dotted.circle" : "circle")634                                        .foregroundStyle(step.status == "done" ? Palette.green : step.status == "in_progress" ? Color.accentColor : .secondary).font(.callout)635                                }636                            }637                        }638                        if !s.agents.isEmpty {639                            VStack(alignment: .leading, spacing: 4) {640                                ForEach(s.agents) { a in641                                    HStack(alignment: .firstTextBaseline, spacing: 6) {642                                        if a.finished { Image(systemName: a.ok ? "checkmark.circle.fill" : "xmark.circle.fill").foregroundStyle(a.ok ? Palette.green : Palette.red) } else { ProgressView().controlSize(.mini) }643                                        VStack(alignment: .leading, spacing: 1) {644                                            Text("\(a.name) · \(a.tools.count) tool call\(a.tools.count == 1 ? "" : "s")").font(.callout)645                                            if !a.preview.isEmpty { Text(a.preview).font(.caption).foregroundStyle(.secondary).lineLimit(2) }646                                        }647                                    }648                                }649                            }650                        }651                        if !s.tools.isEmpty {652                            FlowLayout(spacing: 5) { ForEach(s.tools) { ToolChip(tool: $0) } }653                        }654                    }655                    .padding(.top, 4)656                } label: { Text("Activity · \(s.tools.count) tool call\(s.tools.count == 1 ? "" : "s")\(s.agents.isEmpty ? "" : " · \(s.agents.count) sub-analysts")").font(.callout.weight(.medium)) }657                .padding(10).background(P.ink1, in: RoundedRectangle(cornerRadius: 8)).overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(P.line))658            }659660            if app.settings.showThinking, !s.thinking.isEmpty, s.answer.isEmpty {661                Text(s.thinking.suffix(600)).font(.caption).foregroundStyle(.secondary).italic().lineLimit(6)662            }663            // text written after the quality gate (a correction or a stated limitation) is part of the same answer664            if !s.answer.isEmpty { MarkdownView(app: app, source: s.answer) }665            let placed = s.answer666            ForEach(s.figures.flatMap(\.figureUrls).filter { !placed.contains($0) }, id: \.self) { FigureView(app: app, path: $0, caption: "") }667            if let gate = run.study.state.gates.last(where: { $0.generationId == s.jobId }) ?? (run.isResearch ? run.study.state.gates.last : nil) {668                let open = gate.findings.filter(\.isOpen).count669                Button(action: openActivity) {670                    Label(open == 0 ? "Quality gate passed: the numbers quoted are traceable to the executions of this study." : "Quality gate: \(open) open finding\(open == 1 ? "" : "s") — the agent was told and amended or qualified its answer above.",671                          systemImage: open == 0 ? "checkmark.seal" : "exclamationmark.triangle")672                        .font(T.caption.f).foregroundStyle(open == 0 ? P.text2 : P.warn)673                }674                .buttonStyle(.plain).help("Open the findings in the inspector").accessibilityIdentifier("run.gate")675            }676            if let e = s.error {677                VStack(alignment: .leading, spacing: 2) { Text(e); if let d = s.errorDetail, !d.isEmpty { Text(d).font(.caption).foregroundStyle(.secondary) } }678                    .font(.callout).padding(10).frame(maxWidth: .infinity, alignment: .leading).background(Palette.red.opacity(0.10), in: RoundedRectangle(cornerRadius: 8))679            }680            if s.finished {681                if !s.sources.isEmpty { SourcesView(sources: s.sources) }682                AnswerFooter(app: app, usage: run.usage, modelId: run.route?.model ?? (run.requestedModel == "auto" ? nil : run.requestedModel), provenance: run.provenance,683                             generationId: s.jobId == "fixture" ? nil : s.jobId, sessionId: s.sessionId, research: nil, trace: $trace, openActivity: openActivity)684                if !s.answer.isEmpty { HStack { Spacer(); ReportActions(app: app, question: run.question, answer: s.answer, sources: s.sources, figures: s.figures) } }685                if !s.followups.isEmpty, let sid = s.sessionId {686                    VStack(alignment: .leading, spacing: 5) {687                        Text("Follow up").font(.caption).foregroundStyle(.secondary)688                        ForEach(s.followups, id: \.self) { q in689                            Button {690                                app.research.dismiss(sid)691                                app.research.ask(q, sessionId: sid, key: model.draftKey, mode: draft?.mode ?? app.settings.researchMode, model: draft?.model ?? app.settings.researchModel, budget: draft?.budget)692                            } label: {693                                Label(q, systemImage: "arrow.turn.down.right").frame(maxWidth: .infinity, alignment: .leading)694                            }.buttonStyle(.bordered)695                        }696                    }697                }698            }699            if !s.unknownEvents.isEmpty {700                Text("This version did not recognise \(s.unknownEvents.values.reduce(0, +)) event(s) from the server (\(s.unknownEvents.keys.sorted().joined(separator: ", "))).").font(.caption2).foregroundStyle(.tertiary)701            }702        }703    }704}705706private struct ToolChip: View {707    let tool: ToolActivity708    var body: some View {709        HStack(spacing: 4) {710            switch tool.state {711            case .running: ProgressView().controlSize(.mini)712            case .done: Image(systemName: "checkmark").foregroundStyle(Palette.green)713            case .empty: Image(systemName: "minus.circle").foregroundStyle(.orange)714            case .failed: Image(systemName: "xmark").foregroundStyle(Palette.red)715            }716            Text(tool.tool).lineLimit(1)717            if let ms = tool.durationMs { Text(ms < 1000 ? "\(Int(ms)) ms" : String(format: "%.1f s", ms / 1000)).foregroundStyle(.tertiary) }718        }719        .font(.caption.monospaced())720        .padding(.horizontal, 7).padding(.vertical, 3)721        .background(Color.secondary.opacity(0.10), in: Capsule())722        .help(help)723    }724    private var help: String {725        var s = tool.input.map { String(data: $0.data(pretty: true), encoding: .utf8) ?? "" } ?? ""726        if case .failed(let e) = tool.state { s += "\n\nError: \(e)" }727        if case .empty = tool.state { s += "\n\nThe tool returned no data." }728        return String(s.prefix(1200))729    }730}731732/// Wrapping row of chips.733struct FlowLayout: Layout {734    var spacing: CGFloat = 6735    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {736        let w = proposal.width ?? 600737        var x: CGFloat = 0, y: CGFloat = 0, rowH: CGFloat = 0738        for v in subviews { let s = v.sizeThatFits(.unspecified); if x + s.width > w, x > 0 { x = 0; y += rowH + spacing; rowH = 0 }; x += s.width + spacing; rowH = max(rowH, s.height) }739        return CGSize(width: w, height: y + rowH)740    }741    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {742        var x = bounds.minX, y = bounds.minY, rowH: CGFloat = 0743        for v in subviews {744            let s = v.sizeThatFits(.unspecified)745            if x + s.width > bounds.maxX, x > bounds.minX { x = bounds.minX; y += rowH + spacing; rowH = 0 }746            v.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(s)); x += s.width + spacing; rowH = max(rowH, s.height)747        }748    }749}750751/// Copy, share and server-rendered exports of a report.752struct ReportActions: View {753    let app: AppEnvironment754    let question: String755    let answer: String756    let sources: [WebSource]757    let figures: [FigureBatch]758    @State private var busy: String?759760    var body: some View {761        HStack(spacing: 6) {762            if let busy { ProgressView().controlSize(.mini); Text(busy).font(.caption).foregroundStyle(.secondary) }763            Button { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(answer, forType: .string); app.toasts.show("Report copied as Markdown.") } label: { Image(systemName: "doc.on.doc") }.help("Copy as Markdown")764            Menu {765                Button("PDF Report…") { export("Rendering the PDF on the server…", "pdf", .pdf) { try await app.api.renderPDF(question: question, answer: answer) } }766                Button("Word Document…") { export("Rendering the document on the server…", "docx", UTType(filenameExtension: "docx") ?? .data) { try await app.api.renderDOCX(question: question, answer: answer) } }767                Button("Slides (PDF)…") {768                    let author = app.settings.slidesAuthor.isEmpty ? (app.session.account?.name ?? "VQuant") : app.settings.slidesAuthor769                    export("Building the slides on the server…", "slides.pdf", .pdf) { try await app.api.renderSlides(question: question, answer: answer, author: author, company: app.settings.slidesCompany, figureUrls: figures.flatMap(\.figureUrls)) }770                }771                Button("Markdown File…") { SavePanel.save(Data("# \(question)\n\n\(answer)\n".utf8), name: fileName("md"), types: [UTType(filenameExtension: "md") ?? .plainText]) }772                Divider()773                Button("Publish to Shared Reports") {774                    busy = "Publishing…"775                    Task { defer { busy = nil }776                        do { let id = try await app.api.share(question: question, answer: answer, sources: sources, figures: figures); app.toasts.show("Published as shared report \(id).") } catch { app.toasts.error(error) } }777                }778            } label: { Image(systemName: "square.and.arrow.up") }.menuStyle(.borderlessButton).frame(width: 34).help("Export or share")779        }780        .buttonStyle(.borderless)781        .disabled(busy != nil)782    }783784    private func fileName(_ ext: String) -> String {785        let base = question.prefix(48).map { $0.isLetter || $0.isNumber ? $0 : "-" }786        return "VQuant-" + String(base).replacingOccurrences(of: "--", with: "-") + "." + ext787    }788    private func export(_ label: String, _ ext: String, _ type: UTType, _ make: @escaping () async throws -> Data) {789        busy = label790        Task { defer { busy = nil }791            do { let d = try await make(); SavePanel.save(d, name: fileName(ext), types: [type]) } catch { app.toasts.error(error) } }792    }793}794795
Files main
Menu

Theme