SPB Git

Repository Public

ResearchPanel.swift 9.6 KB 164 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Knowledge/ResearchPanel.swift3// Description: Research mode: plans sub-questions, retrieves per question, drafts a cited answer and verifies every citation against the sources.4import SwiftUI5import LocalChatAgents6import LocalChatCore78struct ResearchPanel: View {9    @Environment(AppModel.self) private var app10    @State private var question = ""11    @State private var modelID: String?12    @State private var selected: Set<UUID> = []13    @State private var verify = true14    @State private var showModels = false15    @State private var isRunning = false16    @State private var stage = ""17    @State private var plan: [String] = []18    @State private var retrieved: [(question: String, count: Int?)] = []19    @State private var answer = ""20    @State private var result: ResearchResult?21    @State private var errorText: String?22    @State private var task: Task<Void, Never>?2324    private var model: ModelDescriptor? { app.model(modelID ?? app.defaultModelID) }25    private var canRun: Bool { !question.trimmingCharacters(in: .whitespaces).isEmpty && !selected.isEmpty && model != nil }2627    var body: some View {28        ScrollView {29            VStack(alignment: .leading, spacing: DS.S.lg) {30                ScreenTitle("Research mode", subtitle: "A structured, cited answer from your collections")31                VStack(alignment: .leading, spacing: DS.S.md) {32                    TextField("Research question", text: $question, axis: .vertical).lineLimit(2...5).textFieldStyle(.roundedBorder).accessibilityLabel("Research question")33                    Text("Collections").font(DS.F.callout.weight(.medium))34                    if app.collections.isEmpty { Text("Create a collection first.").font(DS.F.caption).foregroundStyle(DS.C.muted) }35                    FlowChips(items: app.collections.map { ($0.id, $0.name, $0.symbol) }, selection: $selected)36                    SettingRow("Model", detail: model?.name ?? "No model available") {37                        Button("Choose…") { showModels = true }.buttonStyle(.lcSecondaryCompact)38                    }39                    Toggle("Verify claims with a second model pass", isOn: $verify).font(DS.F.callout)40                    if model?.backend == .remote { InlineNotice(.warning, "The selected model runs on a remote node: the question and the retrieved passages will be sent to it.") }41                    HStack {42                        if isRunning { ThinkingDots(); Text(stage).font(DS.F.caption).foregroundStyle(DS.C.muted) }43                        Spacer()44                        if isRunning { Button("Cancel") { task?.cancel() }.buttonStyle(.lcDestructive) }45                        else { Button("Run research") { run() }.buttonStyle(.lcPrimary).disabled(!canRun) }46                    }47                }48                .card()49                if let errorText { InlineNotice(.error, errorText) }50                if !plan.isEmpty {51                    VStack(alignment: .leading, spacing: 8) {52                        SectionHeader("Plan", symbol: "list.number")53                        ForEach(Array(plan.enumerated()), id: \.offset) { i, q in54                            HStack(alignment: .firstTextBaseline, spacing: 8) {55                                Text("\(i + 1).").font(DS.F.mono(12)).foregroundStyle(DS.C.accent)56                                Text(q).font(DS.F.callout).foregroundStyle(DS.C.text)57                                Spacer(minLength: 4)58                                if let r = retrieved.first(where: { $0.question == q }) {59                                    if let n = r.count { Pill("\(n) passages", tone: n > 0 ? .ok : .warn) } else { ProgressView().controlSize(.mini) }60                                }61                            }62                        }63                    }64                    .card()65                }66                if !answer.isEmpty {67                    VStack(alignment: .leading, spacing: 10) {68                        HStack { SectionHeader("Answer", symbol: "text.quote"); IconButton("doc.on.doc", label: "Copy answer") { Pasteboard.copy(answer) } }69                        MarkdownView(text: answer)70                    }71                    .card()72                }73                if let result {74                    VStack(alignment: .leading, spacing: 8) {75                        SectionHeader("Verification", symbol: "checkmark.shield")76                        if result.sources.isEmpty { InlineNotice(.warning, "No source was retrieved: this answer is not grounded in your documents.") }77                        else if result.isGrounded && result.uncitedSentences.isEmpty { InlineNotice(.privacy, "Every citation refers to a retrieved source and no unsupported claim was flagged.") }78                        if !result.invalidCitations.isEmpty { InlineNotice(.error, "Citations that match no source: " + result.invalidCitations.map { "[\($0)]" }.joined(separator: ", ")) }79                        ForEach(result.unsupportedClaims, id: \.self) { InlineNotice(.warning, "Unsupported: \($0)") }80                        if !result.uncitedSentences.isEmpty {81                            DisclosureGroup("\(result.uncitedSentences.count) factual-looking sentences without a citation") {82                                ForEach(result.uncitedSentences, id: \.self) { Text("• \($0)").font(DS.F.caption).foregroundStyle(DS.C.text2).frame(maxWidth: .infinity, alignment: .leading) }83                            }84                            .font(DS.F.callout)85                        }86                    }87                    .card()88                    if !result.sources.isEmpty {89                        VStack(alignment: .leading, spacing: 8) {90                            SectionHeader("Sources", symbol: "books.vertical")91                            ForEach(Array(result.sources.enumerated()), id: \.element.id) { i, s in92                                VStack(alignment: .leading, spacing: 3) {93                                    HStack(spacing: 6) {94                                        Text("[\(i + 1)]").font(DS.F.mono(12, weight: .semibold)).foregroundStyle(DS.C.accent)95                                        Text(s.documentName).font(DS.F.callout.weight(.medium)).lineLimit(1)96                                        if let p = s.page { Pill("p. \(p)") }97                                    }98                                    Text(s.excerpt).font(DS.F.caption).foregroundStyle(DS.C.text2).lineLimit(4).textSelection(.enabled)99                                }100                                .padding(.vertical, 3)101                            }102                        }103                        .card()104                    }105                }106            }107            .padding(DS.S.lg).frame(maxWidth: 900, alignment: .leading).frame(maxWidth: .infinity)108        }109        .screenBackground()110        .sheet(isPresented: $showModels) {111            ModelPickerView(selectedID: modelID ?? app.defaultModelID, allowAuto: false) { m in if let m { modelID = m.id }; showModels = false }112                .frame(minWidth: 320, minHeight: 420)113        }114        .onDisappear { task?.cancel() }115    }116117    private func run() {118        guard let model else { return }119        isRunning = true; errorText = nil; plan = []; retrieved = []; answer = ""; result = nil; stage = "Planning…"120        let mode = ResearchMode(generator: app.engine, knowledge: app.knowledge)121        let stream = mode.run(question: question, modelID: model.id, collections: Array(selected), settings: app.preferences.defaultPreset.settings(), verifyWithModel: verify)122        task = Task {123            for await event in stream {124                switch event {125                case .planning: stage = "Planning…"126                case .planned(let p): plan = p127                case .retrieving(let q): stage = "Retrieving…"; retrieved.append((q, nil))128                case .retrieved(let q, let n): if let i = retrieved.firstIndex(where: { $0.question == q }) { retrieved[i].count = n } else { retrieved.append((q, n)) }129                case .drafting: stage = "Writing the answer…"130                case .text(let t): answer += t131                case .verifying: stage = "Verifying citations…"132                case .finished(let r): result = r; answer = r.answer; Haptics.play(.success)133                case .failed(let m): errorText = m; Haptics.play(.error)134                }135            }136            isRunning = false; stage = ""137        }138    }139}140141/// Wrapping multi-select chips.142struct FlowChips: View {143    let items: [(id: UUID, name: String, symbol: String)]144    @Binding var selection: Set<UUID>145    var body: some View {146        LazyVGrid(columns: [GridItem(.adaptive(minimum: 130), spacing: 6)], alignment: .leading, spacing: 6) {147            ForEach(items, id: \.id) { item in148                let on = selection.contains(item.id)149                Button { if on { selection.remove(item.id) } else { selection.insert(item.id) } } label: {150                    HStack(spacing: 5) {151                        Image(systemName: on ? "checkmark.circle.fill" : item.symbol).font(.system(size: 11))152                        Text(item.name).font(DS.F.caption).lineLimit(1)153                        Spacer(minLength: 0)154                    }155                    .padding(.horizontal, 9).padding(.vertical, 6)156                    .foregroundStyle(on ? DS.C.accent : DS.C.text2)157                    .background(on ? DS.C.accent.opacity(0.14) : DS.C.surface2, in: RoundedRectangle(cornerRadius: 8, style: .continuous))158                }159                .buttonStyle(.plain).accessibilityAddTraits(on ? .isSelected : []).accessibilityLabel(item.name)160            }161        }162    }163}164
Files main
Menu

Theme