Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Features/Research/ResearchView.swift4// Description: Deep research: question, depth and model, live progress of the server's run (plan, sources read,5// evidence, report streamed), history, resume / stop, exports, and the conversation it produced.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import SwiftUI1213struct ResearchView: View {14 let onOpen: () -> Void15 @Environment(AppEnvironment.self) private var env16 @Environment(\.dismiss) private var dismiss17 @Environment(\.accessibilityReduceMotion) private var reduceMotion18 @State private var session: ResearchSession?19 @State private var runs: [ResearchRun] = []20 @State private var hasLoaded = false21 @State private var listError: String?22 @State private var question = ""23 @State private var depth: ResearchDepth = .quick24 @State private var modelId: String?25 @State private var projectId: String?26 @State private var pickingModel = false27 @State private var path: [Route] = []28 @State private var deleting: ResearchRun?29 @FocusState private var focused: Bool3031 enum Route: Hashable { case live, run(String) }3233 private var effectiveModel: AIModel? { env.catalog.model(modelId ?? env.catalog.effectiveModelId(preferred: env.preferences.modelId)) }34 private var canStart: Bool { question.trimmingCharacters(in: .whitespacesAndNewlines).count >= 5 && effectiveModel != nil && session?.isFollowing != true && env.network.isOnline }3536 var body: some View {37 NavigationStack(path: $path) {38 List {39 Section { form.listRowInsets(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16)).listRowBackground(Color.clear).listRowSeparator(.hidden) }40 if let s = session, s.isFollowing {41 Section {42 Button { path = [.live] } label: { liveRow(s) }.buttonStyle(.plain).accessibilityIdentifier("research.liveRow")43 } header: { sectionHeader(String(localized: "En cours")) }44 }45 if !runs.isEmpty {46 Section { ForEach(runs) { row($0) } } header: { sectionHeader(String(localized: "Historique")) }47 } else if hasLoaded, listError == nil {48 Text("Aucune recherche pour l’instant.").font(.footnote).foregroundStyle(Color.muted).listRowBackground(Color.clear).listRowSeparator(.hidden)49 }50 if let listError { Label(listError, systemImage: "wifi.slash").font(.footnote).foregroundStyle(Color.muted).listRowBackground(Color.clear) }51 }52 .listStyle(.plain)53 .scrollContentBackground(.hidden)54 .background(Color.appBackground)55 .scrollDismissesKeyboard(.interactively)56 .navigationTitle("Recherche approfondie").navigationBarTitleDisplayMode(.inline)57 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } } }58 .navigationDestination(for: Route.self) { route in59 switch route {60 case .live: if let session { ResearchRunView(session: session, runId: nil, open: open, reload: { await load() }) }61 case .run(let id): ResearchRunView(session: session, runId: id, open: open, reload: { await load() })62 }63 }64 .sheet(isPresented: $pickingModel) {65 ModelSheet(purpose: .pick(title: String(localized: "Modèle de synthèse"), current: effectiveModel?.id) { m in modelId = m.id }).presentationDetents([.large])66 }67 .confirmationDialog("Supprimer cette recherche ?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible) {68 Button("Supprimer", role: .destructive) { if let r = deleting { Task { try? await env.api.deleteResearch(r.id); await load() } }; deleting = nil }69 } message: { Text("Le rapport et ses sources sont supprimés du serveur. La conversation créée par la recherche est conservée.") }70 .task {71 if session == nil {72 let s = ResearchSession(api: env.api, waitUntilOnline: { [network = env.network] in await network.waitUntilOnline() })73 s.onFinished = { _ in Task { await load(); await env.conversations.refresh() } }74 session = s75 }76 await load()77 }78 .refreshable { await load() }79 .onDisappear { session?.detach() }80 }81 .accessibilityIdentifier("research.screen")82 }8384 private func sectionHeader(_ t: String) -> some View { Text(t).font(.spMicro).tracking(0.3).textCase(.uppercase).foregroundStyle(Color.textSecondary) }8586 private func load() async {87 do { runs = try await env.api.researchRuns(); listError = nil } catch { if runs.isEmpty { listError = (error as? APIError)?.message ?? String(localized: "Historique indisponible.") } }88 hasLoaded = true89 }9091 private func open(_ conversationId: String) { env.open(conversationId); onOpen(); dismiss() }9293 // MARK: form9495 private var form: some View {96 VStack(alignment: .leading, spacing: 12) {97 TextField("Quelle question veux-tu approfondir ?", text: $question, axis: .vertical)98 .lineLimit(2...6).font(.body).focused($focused)99 .padding(12).cardSurface()100 .accessibilityIdentifier("research.question")101 HStack(spacing: 8) {102 ForEach(ResearchDepth.allCases) { d in103 Button { env.haptics.selection(); withAnimation(Motion.snappy(reduceMotion)) { depth = d } } label: { ChipLabel(text: d.label, selected: depth == d).frame(minHeight: 44) }104 .buttonStyle(PressScale()).accessibilityAddTraits(depth == d ? .isSelected : []).accessibilityHint(d.hint)105 .accessibilityIdentifier("research.depth.\(d.rawValue)")106 }107 }108 Text(depth.hint).font(.caption).foregroundStyle(Color.muted).contentTransition(.opacity)109 HStack(spacing: 8) {110 Button { pickingModel = true } label: {111 ModelChip(model: effectiveModel, markSize: 15, font: .spCaption, showsChevron: true)112 .padding(.horizontal, 10).frame(minHeight: 32).background(Color.surface2, in: .capsule).frame(minHeight: 44).contentShape(.rect)113 }114 .buttonStyle(PressScale(scale: 0.96))115 .accessibilityHint(String(localized: "Choisir le modèle qui planifie et rédige le rapport"))116 .accessibilityIdentifier("research.model")117 if !env.catalog.projects.isEmpty {118 Menu {119 Picker("Projet", selection: $projectId) {120 Text("Aucun projet").tag(String?.none)121 ForEach(env.catalog.projects) { p in Text(p.name).tag(String?.some(p.id)) }122 }123 } label: { ChipLabel(text: env.catalog.project(projectId)?.name ?? String(localized: "Projet"), systemImage: "folder", selected: projectId != nil).frame(minHeight: 44) }124 }125 Spacer(minLength: 0)126 }127 Button {128 guard let m = effectiveModel else { return }129 focused = false; env.haptics.tap()130 session?.start(question: question.trimmingCharacters(in: .whitespacesAndNewlines), modelId: m.id, projectId: projectId, depth: depth)131 question = ""; path = [.live]132 } label: {133 Label("Lancer la recherche", systemImage: "doc.text.magnifyingglass").font(.subheadline.weight(.semibold)).foregroundStyle(.white)134 .frame(maxWidth: .infinity).frame(minHeight: 46).background(canStart ? Color.accentColor : Color.muted.opacity(0.5), in: .rect(cornerRadius: Radius.card, style: .continuous))135 }136 .buttonStyle(PressScale(scale: 0.98)).disabled(!canStart)137 .accessibilityIdentifier("research.start")138 Text("Une recherche lance de vraies recherches web et de vrais appels au modèle, facturés. Elle continue sur le serveur si tu fermes l’app.").font(.caption2).foregroundStyle(Color.muted)139 if let e = session?.error { Banner(kind: .error, text: e) { session?.error = nil } }140 }141 }142143 // MARK: rows144145 private func liveRow(_ s: ResearchSession) -> some View {146 HStack(spacing: 12) {147 PresenceDots().frame(width: 28)148 VStack(alignment: .leading, spacing: 3) {149 Text(s.question).font(.subheadline.weight(.medium)).foregroundStyle(Color.textPrimary).lineLimit(2)150 Text(ResearchProgress.stageLabel(max(s.progress?.stage ?? 0, 1))).font(.caption).foregroundStyle(Color.accentColor)151 }152 Spacer(minLength: 4)153 Image(systemName: "chevron.right").font(.caption2.weight(.bold)).foregroundStyle(Color.muted)154 }155 .frame(minHeight: 48).contentShape(.rect)156 }157158 private func row(_ r: ResearchRun) -> some View {159 NavigationLink(value: Route.run(r.id)) {160 VStack(alignment: .leading, spacing: 5) {161 Text(r.question).font(.subheadline.weight(.medium)).foregroundStyle(Color.textPrimary).lineLimit(2)162 HStack(spacing: 8) {163 ResearchStatusChip(status: r.status, live: r.liveRunId != nil)164 if let n = r.sourceCount, n > 0 { Text(String(localized: "\(n) source(s)")) }165 if let c = r.costUsd, c > 0 { Text("\(Format.usd(c)) \(String(localized: "estimé"))") }166 if let d = r.createdAt { Text(Format.relative(d)) }167 }168 .font(.caption.monospacedDigit()).foregroundStyle(Color.muted).lineLimit(1)169 }170 .padding(.vertical, 4)171 }172 .swipeActions(edge: .trailing) { Button(role: .destructive) { deleting = r } label: { Label("Supprimer", systemImage: "trash") } }173 .accessibilityIdentifier("research.row")174 }175}176177struct ResearchStatusChip: View {178 let status: String179 var live = false180 var body: some View {181 let running = live || ResearchStatus.running.contains(status)182 let color: Color = status == "complete" ? .success : status == "error" ? .danger : status == "interrupted" ? .warning : running ? .accentColor : .muted183 Text(ResearchStatus.label(status)).font(.spMicro).foregroundStyle(color)184 .padding(.horizontal, 7).padding(.vertical, 3).background(color.opacity(0.13), in: .capsule)185 }186}187188/// One run: live (events of the session) or persisted (row of the server). The same layout for both.189struct ResearchRunView: View {190 let session: ResearchSession?191 /// nil = the run the session is following.192 let runId: String?193 let open: (String) -> Void194 let reload: () async -> Void195 @Environment(AppEnvironment.self) private var env196 @Environment(\.openURL) private var openURL197 @Environment(\.accessibilityReduceMotion) private var reduceMotion198 @State private var stored: ResearchRun?199 @State private var loadError: String?200 @State private var showPlan = false201 @State private var exportURL: URL?202 @State private var exporting = false203204 /// The session speaks for this screen when it follows (or just finished) this very run.205 private var live: ResearchProgress? {206 guard let s = session, let p = s.progress else { return nil }207 if runId == nil { return s.isFollowing || s.finished == nil ? p : nil }208 return s.isFollowing && p.researchId == runId ? p : nil209 }210 private var run: ResearchRun? { if runId == nil { return session?.finished ?? stored } else { return (session?.finished?.id == runId ? session?.finished : nil) ?? stored } }211212 private var question: String { run?.question ?? session?.question ?? "" }213 private var status: String { live?.status ?? run?.status ?? "planning" }214 private var stage: Int { if let l = live { return l.stage }; return run?.status == "complete" ? 5 : 0 }215 private var plan: ResearchPlan? { live?.plan ?? run?.plan }216 private var sources: [ResearchSource] { if let l = live, !l.sources.isEmpty { return l.sources }; return run?.sources ?? [] }217 private var report: String { if let l = live, !l.report.isEmpty { return l.report }; return run?.report ?? "" }218 private var isRunning: Bool { live != nil && session?.isFollowing == true }219 private var conversationId: String? { live?.conversationId ?? run?.conversationId }220221 var body: some View {222 ScrollView {223 VStack(alignment: .leading, spacing: 16) {224 header225 if isRunning || stage > 0 { stages }226 if let e = (isRunning ? nil : (run?.error ?? live?.error ?? session.flatMap { runId == nil ? $0.error : nil })) ?? loadError, run?.status != "complete" { Banner(kind: status == "cancelled" ? .info : .warning, text: e) }227 actions228 if let plan { planBlock(plan) }229 if !sources.isEmpty { sourcesBlock }230 if !report.isEmpty { reportBlock }231 else if isRunning, stage < 5 { HStack(spacing: 8) { PresenceDots(); Text("Le rapport s’écrira ici à l’étape de synthèse.").font(.footnote).foregroundStyle(Color.muted) } }232 }233 .padding(16)234 .frame(maxWidth: 760).frame(maxWidth: .infinity)235 }236 .background(Color.appBackground)237 .overlay(alignment: .top) { LumenLine(active: isRunning, cornerRadius: 0) }238 .navigationTitle("Recherche").navigationBarTitleDisplayMode(.inline)239 .sheet(item: Binding(get: { exportURL.map(IdentifiedURL.init) }, set: { exportURL = $0?.url })) { u in ActivityView(items: [u.url]) }240 .task(id: runId) { await loadStored() }241 .accessibilityIdentifier("research.run")242 }243244 private func loadStored() async {245 guard let runId else { return }246 do {247 let r = try await env.api.research(runId); stored = r; loadError = nil248 // still alive on the server and not followed here: re-attach to see it progress249 if let liveId = r.liveRunId, let s = session, !s.isFollowing { s.attach(r, liveRunId: liveId) }250 } catch { loadError = (error as? APIError)?.message ?? String(localized: "Recherche indisponible.") }251 }252253 private var header: some View {254 VStack(alignment: .leading, spacing: 8) {255 Text(question).font(.spTitle).foregroundStyle(Color.textPrimary).fixedSize(horizontal: false, vertical: true)256 HStack(spacing: 8) {257 ResearchStatusChip(status: status, live: isRunning)258 if let m = env.catalog.model(live?.model ?? run?.modelId) { ModelChip(model: m, markSize: 14, font: .spCaption, breathing: isRunning) }259 else if let id = live?.model ?? run?.modelId { Text(id).font(.caption).foregroundStyle(Color.muted).lineLimit(1) }260 if let d = (live?.depth ?? run?.depth).flatMap(ResearchDepth.init(rawValue:)) { Text(d.label).font(.caption).foregroundStyle(Color.muted) }261 }262 let cost = live?.costUsd ?? run?.costUsd263 if let cost, cost > 0 {264 Text(String(localized: "Coût : \(Format.usd(cost)) estimé (jetons × prix de liste ; recherches web non comprises)")).font(.caption2.monospacedDigit()).foregroundStyle(Color.muted)265 }266 }267 }268269 /// Plan → Découverte → Lecture → Preuves → Synthèse, as reported by the server's `step` events.270 private var stages: some View {271 HStack(spacing: 4) {272 ForEach(1...5, id: \.self) { i in273 let done = stage > i || status == "complete", current = stage == i && isRunning274 VStack(spacing: 5) {275 Capsule().fill(done || current ? Color.accentColor : Color.surface2).frame(height: 4)276 .opacity(current && !reduceMotion ? 0.65 : 1)277 Text(ResearchProgress.stageLabel(i)).font(.system(size: 10, weight: current ? .semibold : .medium)).foregroundStyle(done || current ? Color.textPrimary : Color.muted).lineLimit(1).minimumScaleFactor(0.7)278 }279 .frame(maxWidth: .infinity)280 }281 }282 .animation(Motion.smooth(reduceMotion), value: stage)283 .accessibilityElement(children: .ignore)284 .accessibilityLabel(String(localized: "Étape \(max(min(stage, 5), 1)) sur 5 : \(ResearchProgress.stageLabel(max(min(stage, 5), 1)))"))285 .accessibilityIdentifier("research.stages")286 }287288 private var actions: some View {289 ScrollView(.horizontal, showsIndicators: false) {290 HStack(spacing: 8) {291 if isRunning {292 Button { env.haptics.tap(); session?.stop() } label: { ChipLabel(text: String(localized: "Arrêter"), systemImage: "stop.fill").frame(minHeight: 44) }293 .accessibilityIdentifier("research.stop")294 }295 if let c = conversationId, !isRunning {296 Button { open(c) } label: { ChipLabel(text: String(localized: "Ouvrir la conversation"), systemImage: "bubble.left.and.text.bubble.right", selected: true).frame(minHeight: 44) }297 .accessibilityIdentifier("research.open")298 }299 if let r = run, r.isResumable, !isRunning {300 Button { env.haptics.tap(); session?.resume(r) } label: { ChipLabel(text: String(localized: "Reprendre"), systemImage: "arrow.clockwise").frame(minHeight: 44) }301 .accessibilityHint(String(localized: "Les étapes déjà payées sont réutilisées"))302 .accessibilityIdentifier("research.resume")303 }304 if let r = run, r.status == "complete" {305 Menu {306 Button { export(r.id, "md") } label: { Label("Markdown", systemImage: "doc.plaintext") }307 Button { export(r.id, "docx") } label: { Label("Word (.docx)", systemImage: "doc.richtext") }308 Button { export(r.id, "json") } label: { Label("JSON (plan, sources, rapport)", systemImage: "curlybraces") }309 } label: { ChipLabel(text: exporting ? String(localized: "Export…") : String(localized: "Exporter"), systemImage: "square.and.arrow.up").frame(minHeight: 44) }310 .accessibilityIdentifier("research.export")311 Button { UIPasteboard.general.string = r.report; env.haptics.soften() } label: { ChipLabel(text: String(localized: "Copier"), systemImage: "square.on.square").frame(minHeight: 44) }312 }313 }314 .buttonStyle(PressScale())315 }316 }317318 private func export(_ id: String, _ format: String) {319 exporting = true320 Task {321 defer { exporting = false }322 do {323 let data = try await env.api.researchExport(id, format: format)324 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spchat-preview/export", isDirectory: true)325 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)326 let url = dir.appendingPathComponent("Recherche - \(question.replacingOccurrences(of: "/", with: "-").prefix(60)).\(format)")327 try data.write(to: url, options: [.atomic, .completeFileProtectionUnlessOpen])328 exportURL = url329 } catch { loadError = (error as? APIError)?.message ?? String(localized: "Export impossible.") }330 }331 }332333 private func card<Content: View>(@ViewBuilder _ content: () -> Content) -> some View {334 VStack(alignment: .leading, spacing: 10) { content() }.padding(14).frame(maxWidth: .infinity, alignment: .leading).cardSurface()335 }336337 private func planBlock(_ p: ResearchPlan) -> some View {338 card {339 Button { withAnimation(Motion.snappy(reduceMotion)) { showPlan.toggle() } } label: {340 HStack {341 Text("Plan").font(.spHeading).foregroundStyle(Color.textPrimary)342 Text(String(localized: "\(p.subquestions.count) sous-questions · \(p.queries.count) requêtes")).font(.caption).foregroundStyle(Color.muted)343 Spacer()344 Image(systemName: "chevron.right").font(.caption2.weight(.bold)).foregroundStyle(Color.muted).rotationEffect(.degrees(showPlan ? 90 : 0))345 }346 .frame(minHeight: 30).contentShape(.rect)347 }348 .buttonStyle(.plain)349 .accessibilityIdentifier("research.plan")350 if showPlan {351 ForEach(p.subquestions, id: \.self) { q in Label(q, systemImage: "questionmark.circle").font(.footnote).foregroundStyle(Color.textSecondary) }352 if !p.queries.isEmpty {353 Text("Requêtes web").font(.spMicro).foregroundStyle(Color.muted).textCase(.uppercase).padding(.top, 2)354 ForEach(p.queries, id: \.self) { q in Label(q, systemImage: "magnifyingglass").font(.footnote).foregroundStyle(Color.textSecondary) }355 }356 SourceNote(text: String(localized: "Plan rédigé par le modèle au début de la recherche"))357 }358 }359 }360361 private var sourcesBlock: some View {362 card {363 HStack {364 Text("Sources").font(.spHeading).foregroundStyle(Color.textPrimary)365 let read = sources.filter(\.fetched).count366 Text(String(localized: "\(read) lue(s) sur \(live?.found ?? sources.count) trouvée(s)")).font(.caption.monospacedDigit()).foregroundStyle(Color.muted)367 }368 VStack(spacing: 0) {369 ForEach(Array(sources.enumerated()), id: \.element.id) { i, s in370 if i > 0 { Divider() }371 Button { if let u = URL(string: s.url) { openURL(u) } } label: {372 HStack(alignment: .top, spacing: 10) {373 Text("\(s.n)").font(.system(size: 10, weight: .bold).monospacedDigit()).foregroundStyle(s.fetched ? Color.accentColor : Color.muted)374 .frame(minWidth: 18, minHeight: 18).background(s.fetched ? Color.accentSoft : Color.surface2, in: .rect(cornerRadius: 5, style: .continuous))375 VStack(alignment: .leading, spacing: 2) {376 Text(s.title).font(.footnote.weight(.medium)).foregroundStyle(Color.textPrimary).lineLimit(2).multilineTextAlignment(.leading)377 HStack(spacing: 6) {378 Text(s.domain).lineLimit(1)379 if s.failed { Text("· page illisible").foregroundStyle(Color.warning) }380 else if let n = s.evidenceCount { Text(String(localized: "· \(n) preuve(s)")) }381 else if !s.fetched { Text("· non lue") }382 }383 .font(.caption2).foregroundStyle(Color.muted)384 }385 Spacer(minLength: 0)386 }387 .padding(.vertical, 8).contentShape(.rect)388 }389 .buttonStyle(.plain)390 .accessibilityHint(String(localized: "Ouvre la page dans le navigateur"))391 .accessibilityIdentifier("research.source")392 }393 }394 SourceNote(text: String(localized: "Pages trouvées par la recherche web du serveur ; « preuves » = extraits retenus par le modèle d’extraction"))395 }396 }397398 private var reportBlock: some View {399 VStack(alignment: .leading, spacing: 10) {400 Text("Rapport").font(.spHeading).foregroundStyle(Color.textPrimary)401 MarkdownView(text: report).foregroundStyle(Color.textPrimary)402 }403 .accessibilityIdentifier("research.report")404 }405}406