Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Workspace/ResearchScreen.swift3// Description: Deep research: start / resume / re-attach / cancel a detached research run, live phases, plan and sources, cited report, past runs, exports.4import SwiftUI5import AppKit6import UniformTypeIdentifiers7import SPChatCore89// MARK: - Model1011enum ResearchDepth: String, CaseIterable, Identifiable {12 case quick, standard, deep13 var id: String { rawValue }14 var label: String { switch self { case .quick: "Rapide"; case .standard: "Standard"; case .deep: "Approfondie" } }15 var hint: String {16 switch self {17 case .quick: "≈ 3 requêtes · 4 pages · environ 1 min"18 case .standard: "≈ 5 requêtes · 7 pages · 2 à 4 min"19 case .deep: "≈ 8 requêtes · 12 pages · 5 à 10 min"20 }21 }22}2324enum ResearchStatus {25 static let resumable: Set<String> = ["interrupted", "error", "cancelled"]26 static let inProgress: Set<String> = ["planning", "searching", "reading", "synthesizing"]27 static func label(_ s: String) -> String {28 switch s {29 case "complete": "terminé"; case "error": "erreur"; case "cancelled": "annulé"; case "interrupted": "interrompu"30 case "planning": "planification"; case "searching": "recherche"; case "reading": "lecture"; case "synthesizing": "synthèse"31 default: s32 }33 }34 static func color(_ s: String) -> Color {35 switch s {36 case "complete": Palette.success; case "error": Palette.danger; case "interrupted": Palette.warning; case "cancelled": .secondary37 default: Palette.iris38 }39 }40 /// Phases shown to the owner, in order.41 static let phases = ["Plan", "Découverte", "Lecture des sources", "Synthèse"]42}4344struct ResearchSource: Identifiable {45 var n: Int46 var url: String47 var title: String48 var fetched: Bool49 var evidenceCount: Int?50 var failed = false51 var id: Int { n }5253 /// From a `source` event or from a stored source (whose `evidence` is an array).54 init?(_ j: JSONValue) {55 guard let n = j["n"]?.intValue, let url = j["url"]?.stringValue else { return nil }56 self.n = n; self.url = url; title = j["title"]?.stringValue ?? ""57 fetched = j["fetched"]?.boolValue ?? false58 evidenceCount = j["evidence"]?.arrayValue?.count ?? j["evidence"]?.intValue59 failed = j["error"]?.boolValue ?? false60 }6162 /// Only http(s) links may be opened.63 var link: URL? {64 guard let u = LinkPolicy.safeURL(url), let scheme = u.scheme?.lowercased(), scheme == "http" || scheme == "https" else { return nil }65 return u66 }67}6869struct ResearchPlan {70 var subquestions: [String]71 var queries: [String]72 var evidenceNeeded: [String]73 init?(_ j: JSONValue?) {74 guard let j, j.objectValue != nil else { return nil }75 func list(_ k: String) -> [String] { j[k]?.arrayValue?.compactMap(\.stringValue) ?? [] }76 subquestions = list("subquestions"); queries = list("queries"); evidenceNeeded = list("evidence_needed")77 if subquestions.isEmpty && queries.isEmpty && evidenceNeeded.isEmpty { return nil }78 }79}8081/// A row of `GET /api/research` (and the common fields of `GET /api/research/<id>`).82struct ResearchRun: Identifiable {83 var id: String84 var conversationId: String?85 var question: String86 var modelId: String87 var status: String88 var depth: String?89 var costUsd: Double?90 var error: String?91 var createdAt: Date?92 var completedAt: Date?93 var sourceCount: Int?94 /// Id of the server run still executing this research, when there is one.95 var live: String?96 // detail only97 var plan: ResearchPlan?98 var steps: [String] = []99 var sources: [ResearchSource] = []100 var report: String?101102 init?(_ j: JSONValue, live: String? = nil) {103 guard let id = j["id"]?.stringValue else { return nil }104 self.id = id; conversationId = j["conversation_id"]?.stringValue105 question = j["question"]?.stringValue ?? ""; modelId = j["model_id"]?.stringValue ?? ""106 status = j["status"]?.stringValue ?? "?"; depth = j["depth"]?.stringValue107 costUsd = j["cost_usd"]?.doubleValue; error = j["error"]?.stringValue108 createdAt = j["created_at"]?.stringValue.flatMap(ServerDate.parse); completedAt = j["completed_at"]?.stringValue.flatMap(ServerDate.parse)109 sourceCount = j["source_count"]?.intValue110 self.live = live ?? j["live"]?.stringValue111 plan = ResearchPlan(j["plan"])112 steps = j["steps"]?.arrayValue?.compactMap { $0["step"]?.stringValue } ?? []113 sources = (j["sources"]?.arrayValue ?? []).compactMap(ResearchSource.init).sorted { $0.n < $1.n }114 report = j["report_md"]?.stringValue115 }116117 var completedPhases: Int {118 if status == "complete" { return ResearchStatus.phases.count }119 return (steps.contains("plan") ? 1 : 0) + (steps.contains("discovery") ? 1 : 0) + (steps.contains("extraction") ? 1 : 0)120 }121}122123/// State of the run currently followed on screen.124struct ResearchLive {125 var id: String?126 var conversationId: String?127 var question = ""128 var modelId: String?129 var completedPhases = 0130 var plan: ResearchPlan?131 var sources: [ResearchSource] = []132 var report = ""133 var costUsd: Double?134 var error: String?135 var finalStatus: String?136 var resumed = false137}138139@Observable final class ResearchViewModel {140 var question = ""141 var modelId = ""142 var depth: ResearchDepth = .standard143144 private(set) var runs: [ResearchRun] = []145 private(set) var runsLoading = false146 private(set) var runsLoaded = false147 private(set) var runsError: String?148149 private(set) var selectedId: String?150 private(set) var detail: ResearchRun?151 private(set) var detailLoading = false152 private(set) var detailError: String?153154 private(set) var live: ResearchLive?155 private(set) var running = false156 private(set) var stopping = false157 private(set) var reconnecting = false158 /// The stream ended without `end` and could not be re-attached.159 private(set) var connectionLost = false160 var errorText: String?161 private(set) var exporting = false162163 @ObservationIgnored private var task: Task<Void, Never>?164 @ObservationIgnored private var follower: RunFollower?165 @ObservationIgnored private var attachedRunId: String?166 @ObservationIgnored private var reportBuffer = ""167 @ObservationIgnored private var reportDirty = false168169 var questionLength: Int { question.trimmingCharacters(in: .whitespacesAndNewlines).count }170 var canStart: Bool { !running && (5...5000).contains(questionLength) && !modelId.isEmpty }171172 // MARK: Lists173174 func loadRuns(_ api: APIClient) async {175 runsLoading = true; runsError = nil176 do {177 runs = (try await api.json(.get, "/api/research")["runs"]?.arrayValue ?? []).compactMap { ResearchRun($0) }178 runsLoaded = true179 } catch { if (error as? APIError)?.kind != .cancelled { runsError = workspaceErrorText(error) } }180 runsLoading = false181 }182183 /// Opens a saved run; when it is still executing on the server its stream is re-attached.184 func open(_ id: String, env: AppEnvironment, attachIfLive: Bool = true) async {185 guard !running else { return }186 selectedId = id; live = nil; connectionLost = false; detailError = nil187 if detail?.id != id { detail = nil }188 detailLoading = true189 do {190 let j = try await env.api.json(.get, "/api/research/\(id)")191 guard selectedId == id else { return }192 guard let r = j["run"], let run = ResearchRun(r, live: j["live"]?.stringValue) else { throw APIError(.decoding, message: "Réponse inattendue du serveur.") }193 detail = run; detailLoading = false194 if attachIfLive, let liveId = run.live, !running { attach(runId: liveId, run: run, env: env) }195 } catch {196 guard selectedId == id else { return }197 detailLoading = false198 if (error as? APIError)?.kind != .cancelled { detailError = workspaceErrorText(error) }199 }200 }201202 func closeSelection() { guard !running else { return }; selectedId = nil; detail = nil; live = nil; connectionLost = false; detailError = nil }203204 // MARK: Streams205206 func start(env: AppEnvironment) {207 guard canStart else { return }208 let q = question.trimmingCharacters(in: .whitespacesAndNewlines)209 let body = Data(JSONValue.object(["question": .string(q), "modelId": .string(modelId), "depth": .string(depth.rawValue)]).jsonString().utf8)210 selectedId = nil; detail = nil211 follow(initial: ResearchLive(question: q, modelId: modelId), knownRunId: nil, env: env) { try await env.api.openStream(.post, "/api/research", body: body) }212 }213214 /// Resumes an interrupted / failed / cancelled run: the phases already paid for are reused by the server.215 func resume(_ run: ResearchRun, env: AppEnvironment) {216 guard !running else { return }217 follow(initial: ResearchLive(id: run.id, conversationId: run.conversationId, question: run.question, modelId: run.modelId, resumed: true), knownRunId: nil, env: env) {218 try await env.api.openStream(.post, "/api/research/\(run.id)/resume")219 }220 }221222 /// Re-attaches to a run that is still live on the server; every event is replayed from the beginning.223 func attach(runId: String, run: ResearchRun, env: AppEnvironment) {224 guard !running else { return }225 follow(initial: ResearchLive(id: run.id, conversationId: run.conversationId, question: run.question, modelId: run.modelId), knownRunId: runId, env: env) {226 try await env.api.openStream(.get, "/api/chat/stream", query: ["run": runId, "after": "-1"])227 }228 }229230 private func follow(initial: ResearchLive, knownRunId: String?, env: AppEnvironment, open: @escaping () async throws -> APIClient.StreamOpening) {231 live = initial; reportBuffer = ""; reportDirty = false232 running = true; stopping = false; reconnecting = false; connectionLost = false; errorText = nil233 attachedRunId = knownRunId234 let follower = RunFollower(api: env.api); self.follower = follower235 task = Task {236 let flusher = Task { while !Task.isCancelled { try? await Task.sleep(for: .milliseconds(33)); self.flushReport() } }237 var end = RunStreamEnd.cancelled238 do {239 end = try await follower.follow(maxReattach: 12, open: open, onReconnecting: { self.reconnecting = $0 }, handle: { self.handle($0, $1) })240 } catch {241 let api = error as? APIError242 if api?.status == 410 || api?.status == 404 { end = .gone } // finished while we were away243 else if api?.kind != .cancelled { errorText = workspaceErrorText(error) }244 }245 flusher.cancel(); flushReport()246 let id = live?.id247 running = false; stopping = false; reconnecting = false248 self.follower = nil; attachedRunId = nil; task = nil249 switch end {250 case .ended, .gone:251 // the saved row is the truth: report, sources, resumable state252 if let id { await self.open(id, env: env, attachIfLive: false) } else if errorText == nil, live?.error == nil { live = nil }253 if live?.id == nil, errorText != nil { live = nil }254 case .lost:255 connectionLost = true256 case .cancelled:257 if errorText != nil { live = nil; if let id = selectedId { await self.open(id, env: env, attachIfLive: false) } }258 }259 await loadRuns(env.api)260 }261 }262263 private func handle(_ event: String, _ d: JSONValue) {264 guard var l = live else { return }265 switch event {266 case "start":267 l.id = d["id"]?.stringValue ?? l.id; l.conversationId = d["conversationId"]?.stringValue ?? l.conversationId268 l.modelId = d["model"]?.stringValue ?? l.modelId269 if let q = d["question"]?.stringValue { l.question = q }270 l.resumed = d["resumed"]?.boolValue ?? l.resumed271 l.error = nil; l.finalStatus = nil272 if let id = l.id { selectedId = id }273 case "step":274 switch d["step"]?.stringValue {275 case "plan": l.completedPhases = max(l.completedPhases, 1); if let p = ResearchPlan(d["detail"]) { l.plan = p }276 case "discovery": l.completedPhases = max(l.completedPhases, 2)277 case "extraction", "synthesis": l.completedPhases = max(l.completedPhases, 3)278 default: break279 }280 case "source":281 guard var s = ResearchSource(d) else { return }282 if s.evidenceCount == nil { s.evidenceCount = l.sources.first { $0.n == s.n }?.evidenceCount }283 l.sources.removeAll { $0.n == s.n }; l.sources.append(s); l.sources.sort { $0.n < $1.n }284 case "evidence":285 guard let n = d["n"]?.intValue, let i = l.sources.firstIndex(where: { $0.n == n }) else { return }286 l.sources[i].evidenceCount = d["count"]?.intValue287 case "text":288 guard let delta = d["delta"]?.stringValue else { return }289 reportBuffer += delta; reportDirty = true290 if l.completedPhases >= 3 { return }291 l.completedPhases = 3292 case "done":293 l.completedPhases = ResearchStatus.phases.count; l.costUsd = d["costUsd"]?.doubleValue; l.finalStatus = d["status"]?.stringValue ?? "complete"294 l.conversationId = d["conversationId"]?.stringValue ?? l.conversationId295 case "error":296 l.error = d["message"]?.stringValue ?? "Erreur"; l.finalStatus = d["status"]?.stringValue ?? "error"297 default: return298 }299 live = l300 }301302 private func flushReport() {303 guard reportDirty else { return }304 reportDirty = false305 live?.report = reportBuffer306 }307308 /// Cancels the run on the server; the stream then delivers the final `error` (annulé) and `end`.309 func cancel(env: AppEnvironment) {310 guard running, !stopping else { return }311 guard let runId = follower?.runId ?? attachedRunId else { errorText = "La recherche n'a pas encore d'identifiant d'exécution ; réessaie dans un instant."; return }312 stopping = true313 Task {314 do { try await env.api.cancelGeneration(runId: runId, messageId: nil) }315 catch { stopping = false; env.toasts.error(error) }316 }317 }318319 /// Cancels a run that is live on the server but not followed here.320 func cancelDetached(runId: String, env: AppEnvironment) {321 Task {322 do {323 try await env.api.cancelGeneration(runId: runId, messageId: nil)324 env.toasts.show("Annulation demandée")325 try? await Task.sleep(for: .seconds(1))326 if let id = selectedId { await open(id, env: env, attachIfLive: false) }327 await loadRuns(env.api)328 } catch { env.toasts.error(error) }329 }330 }331332 /// The screen went away: only the UI subscription stops, the research continues on the server.333 func detach() { task?.cancel() }334335 func reloadAfterLoss(env: AppEnvironment) {336 Task {337 if let id = live?.id ?? selectedId { connectionLost = false; await open(id, env: env) }338 else { connectionLost = false; live = nil }339 await loadRuns(env.api)340 }341 }342343 // MARK: Saved run actions344345 func export(_ run: ResearchRun, format: String, env: AppEnvironment) {346 guard !exporting else { return }347 exporting = true348 Task {349 defer { exporting = false }350 do {351 let file = try await env.api.download("/api/research/\(run.id)", query: ["format": format])352 let type: UTType = switch format { case "json": .json; case "docx": UTType(filenameExtension: "docx") ?? .data; default: UTType(filenameExtension: "md") ?? .plainText }353 SavePanel.save(file.data, name: file.filename ?? "Recherche.\(format)", type: type, env: env)354 } catch { env.toasts.error(error) }355 }356 }357358 func delete(_ run: ResearchRun, env: AppEnvironment) {359 Task {360 do {361 _ = try await env.api.raw(.delete, "/api/research/\(run.id)")362 if selectedId == run.id { closeSelection() }363 runs.removeAll { $0.id == run.id }364 env.toasts.show("Recherche supprimée")365 } catch { env.toasts.error(error) }366 await loadRuns(env.api)367 }368 }369}370371// MARK: - Screen372373struct ResearchScreen: View {374 @Environment(AppEnvironment.self) private var env375 @State private var model = ResearchViewModel()376 @State private var pendingDelete: ResearchRun?377378 private var models: [AIModel] { env.catalog.selectableModels }379380 var body: some View {381 HStack(spacing: 0) {382 runList.frame(width: 290)383 Divider()384 ScrollView {385 VStack(alignment: .leading, spacing: 16) {386 composer387 if let text = model.errorText { Banner(kind: .error, text: text, onDismiss: { model.errorText = nil }) }388 if model.connectionLost {389 Banner(kind: .warning, text: "Connexion perdue. La recherche continue sur le serveur ; son état enregistré peut être rechargé.",390 actionTitle: "Recharger", action: { model.reloadAfterLoss(env: env) })391 }392 if model.reconnecting { Banner(kind: .info, text: "Connexion interrompue : reconnexion au flux en cours…") }393 content394 }395 .padding(20).frame(maxWidth: 980, alignment: .leading).frame(maxWidth: .infinity)396 }397 }398 .environment(\.transcriptFontSize, 13)399 .accessibilityIdentifier("research-screen")400 .task {401 if !env.catalog.loaded { await env.catalog.load() }402 pickDefaultModel()403 if !model.runsLoaded { await model.loadRuns(env.api) }404 }405 .onChange(of: models.map(\.id)) { pickDefaultModel() }406 .onDisappear { model.detach() }407 .confirmationDialog("Supprimer cette recherche ?", isPresented: Binding(get: { pendingDelete != nil }, set: { if !$0 { pendingDelete = nil } }), presenting: pendingDelete) { run in408 Button("Supprimer", role: .destructive) { model.delete(run, env: env) }409 Button("Annuler", role: .cancel) {}410 } message: { run in411 Text("« \(String(run.question.prefix(120))) » — le rapport et ses sources seront supprimés du serveur. La conversation associée est conservée.")412 }413 }414415 private func pickDefaultModel() {416 if !models.contains(where: { $0.id == model.modelId }) { model.modelId = env.catalog.initialModelId(preferred: nil) ?? "" }417 }418419 // MARK: Past runs420421 private var runList: some View {422 VStack(alignment: .leading, spacing: 0) {423 HStack {424 Text("Recherches").font(.headline)425 Spacer()426 if model.runsLoading { ProgressView().controlSize(.small) }427 IconButton(systemImage: "arrow.clockwise", label: "Actualiser la liste") { Task { await model.loadRuns(env.api) } }428 }429 .padding(.horizontal, 12).padding(.vertical, 10)430 Divider()431 if let error = model.runsError {432 Banner(kind: .error, text: error, actionTitle: "Réessayer", action: { Task { await model.loadRuns(env.api) } }).padding(8)433 }434 if model.runs.isEmpty {435 if model.runsLoading { ProgressView("Chargement…").frame(maxWidth: .infinity, maxHeight: .infinity) }436 else if model.runsError == nil { EmptyStateView(systemImage: "doc.text.magnifyingglass", title: "Aucune recherche", message: "Tes rapports apparaîtront ici.").frame(maxHeight: .infinity) }437 else { Spacer() }438 } else {439 List(model.runs) { run in440 Button { Task { await model.open(run.id, env: env) } } label: { ResearchRunRow(run: run, modelName: env.catalog.displayName(forModel: run.modelId)) }441 .buttonStyle(.plain).disabled(model.running)442 .listRowBackground(run.id == model.selectedId ? Palette.iris.opacity(0.12) : Color.clear)443 .contextMenu {444 Button("Ouvrir") { Task { await model.open(run.id, env: env) } }.disabled(model.running)445 Button("Supprimer…", role: .destructive) { pendingDelete = run }.disabled(run.live != nil || (model.running && model.selectedId == run.id))446 }447 }448 .listStyle(.inset)449 if model.running { Text("Une recherche est suivie en direct : arrête de la suivre pour en ouvrir une autre.").font(.caption2).foregroundStyle(.secondary).padding(8) }450 }451 }452 .background(.background.secondary.opacity(0.5))453 }454455 // MARK: New run456457 private var composer: some View {458 @Bindable var model = model459 let n = model.questionLength460 return VStack(alignment: .leading, spacing: 10) {461 Text("Recherche approfondie").font(.title2.weight(.semibold))462 Text("Le modèle planifie, cherche sur le web, lit les pages, extrait des preuves puis rédige un rapport cité. La recherche tourne sur le serveur : tu peux quitter cet écran et y revenir.")463 .font(.callout).foregroundStyle(.secondary)464 ZStack(alignment: .topLeading) {465 TextEditor(text: $model.question)466 .font(.body).scrollContentBackground(.hidden).frame(minHeight: 70, maxHeight: 180)467 .accessibilityLabel("Question de recherche").accessibilityIdentifier("research-question")468 if model.question.isEmpty { Text("Pose ta question de recherche…").foregroundStyle(.tertiary).padding(.leading, 5).allowsHitTesting(false) }469 }470 .padding(6).background(.background, in: RoundedRectangle(cornerRadius: 8)).overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.separator))471 HStack(spacing: 12) {472 Picker("Modèle", selection: $model.modelId) {473 if models.isEmpty { Text("Aucun modèle vérifié").tag("") }474 ForEach(models) { Text("\($0.shortName) — \(Provider.label($0.provider))").tag($0.id) }475 }476 .fixedSize()477 Picker("Profondeur", selection: $model.depth) { ForEach(ResearchDepth.allCases) { Text($0.label).tag($0) } }478 .pickerStyle(.segmented).fixedSize()479 Spacer()480 Text("\(n) / 5000").font(.caption.monospacedDigit()).foregroundStyle(n > 5000 ? AnyShapeStyle(Palette.danger) : AnyShapeStyle(.secondary))481 Button { model.start(env: env) } label: { Label("Lancer la recherche", systemImage: "play.fill") }482 .buttonStyle(.borderedProminent).keyboardShortcut(.return, modifiers: .command).disabled(!model.canStart)483 .accessibilityIdentifier("research-start")484 }485 .disabled(model.running)486 Text(n > 0 && n < 5 ? "La question doit compter au moins 5 caractères." : n > 5000 ? "La question dépasse 5000 caractères." : model.depth.hint + " · coût facturé selon le modèle choisi")487 .font(.caption).foregroundStyle(n > 5000 ? AnyShapeStyle(Palette.danger) : AnyShapeStyle(.secondary))488 }489 .card()490 }491492 // MARK: Current run493494 @ViewBuilder private var content: some View {495 if let live = model.live {496 ResearchRunView(question: live.question, modelId: live.modelId, status: liveStatus(live), completedPhases: live.completedPhases, active: model.running,497 plan: live.plan, sources: live.sources, report: live.report, costUsd: live.costUsd, error: live.error, note: live.resumed && model.running ? "Reprise : les phases déjà payées sont réutilisées." : nil) {498 if model.running {499 if model.stopping { ProgressView().controlSize(.small) }500 Button(role: .cancel) { model.cancel(env: env) } label: { Label(model.stopping ? "Annulation…" : "Annuler la recherche", systemImage: "stop.fill") }501 .disabled(model.stopping).accessibilityIdentifier("research-cancel")502 Button("Ne plus suivre") { model.detach() }.help("Arrête l'affichage en direct ; la recherche continue sur le serveur.")503 } else if let id = live.id {504 Button("Recharger") { Task { await model.open(id, env: env) } }505 }506 }507 } else if let run = model.detail {508 ResearchRunView(question: run.question, modelId: run.modelId, status: run.status, completedPhases: run.completedPhases, active: false,509 plan: run.plan, sources: run.sources, report: run.report ?? "", costUsd: run.costUsd, error: run.error,510 note: run.live != nil ? "Cette recherche est en cours sur le serveur." : (ResearchStatus.inProgress.contains(run.status) ? "Marquée en cours, mais plus aucune exécution n'est active sur le serveur." : nil)) {511 detailActions(run)512 }513 } else if model.detailLoading {514 ProgressView("Chargement de la recherche…").frame(maxWidth: .infinity, minHeight: 200)515 } else if let error = model.detailError {516 Banner(kind: .error, text: "Impossible d'ouvrir la recherche : \(error)", actionTitle: "Réessayer", action: { if let id = model.selectedId { Task { await model.open(id, env: env) } } })517 } else {518 EmptyStateView(systemImage: "doc.text.magnifyingglass", title: "Lance une recherche ou ouvre un rapport",519 message: "Les rapports citent des sources vérifiables et distinguent preuves, interprétation et spéculation.")520 .frame(maxWidth: .infinity, minHeight: 260)521 }522 }523524 private func liveStatus(_ l: ResearchLive) -> String {525 if let s = l.finalStatus { return s }526 guard model.running else { return model.connectionLost ? "interrupted" : "?" }527 switch l.completedPhases { case 0: return "planning"; case 1: return "searching"; case 2: return "reading"; default: return "synthesizing" }528 }529530 @ViewBuilder private func detailActions(_ run: ResearchRun) -> some View {531 if let liveId = run.live {532 Button { model.attach(runId: liveId, run: run, env: env) } label: { Label("Suivre en direct", systemImage: "dot.radiowaves.left.and.right") }533 Button(role: .cancel) { model.cancelDetached(runId: liveId, env: env) } label: { Label("Annuler la recherche", systemImage: "stop.fill") }534 } else if ResearchStatus.resumable.contains(run.status) {535 Button { model.resume(run, env: env) } label: { Label("Reprendre", systemImage: "arrow.clockwise") }536 .buttonStyle(.borderedProminent).help("Reprend la recherche : le plan et les sources déjà analysées sont réutilisés.")537 }538 if let report = run.report, !report.isEmpty {539 Button { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(report, forType: .string); env.toasts.show("Rapport copié") } label: { Label("Copier", systemImage: "doc.on.doc") }540 }541 Menu {542 Button("Markdown (.md)") { model.export(run, format: "md", env: env) }543 Button("Word (.docx)") { model.export(run, format: "docx", env: env) }544 Button("JSON (plan, étapes, sources, rapport)") { model.export(run, format: "json", env: env) }545 } label: { Label("Exporter", systemImage: "square.and.arrow.up") }546 .fixedSize().disabled(model.exporting)547 if let cid = run.conversationId {548 Button { env.open(conversationId: cid) } label: { Label("Ouvrir la conversation", systemImage: "bubble.left.and.bubble.right") }549 }550 IconButton(systemImage: "trash", label: "Supprimer la recherche", role: .destructive) { pendingDelete = run }.disabled(run.live != nil)551 }552}553554// MARK: - Pieces555556private struct ResearchRunRow: View {557 let run: ResearchRun558 let modelName: String559 var body: some View {560 VStack(alignment: .leading, spacing: 4) {561 Text(run.question).font(.callout).lineLimit(2).frame(maxWidth: .infinity, alignment: .leading)562 HStack(spacing: 6) {563 StatusPill(text: run.live != nil ? "en cours" : ResearchStatus.label(run.status), color: run.live != nil ? Palette.iris : ResearchStatus.color(run.status),564 systemImage: run.live != nil ? "dot.radiowaves.left.and.right" : nil)565 if let n = run.sourceCount, n > 0 { Text("\(n) sources") }566 if let c = run.costUsd, c > 0 { Text(Format.usd(c, digits: 3)) }567 }568 .font(.caption2).foregroundStyle(.secondary)569 HStack(spacing: 6) {570 Text(modelName).lineLimit(1)571 if let d = run.createdAt { Text("· " + Format.relative(d)) }572 }573 .font(.caption2).foregroundStyle(.tertiary)574 }575 .padding(.vertical, 2).contentShape(Rectangle())576 .accessibilityElement(children: .combine)577 }578}579580/// One research run, live or saved: phases, plan, sources, report.581private struct ResearchRunView<Actions: View>: View {582 let question: String583 let modelId: String?584 let status: String585 let completedPhases: Int586 let active: Bool587 let plan: ResearchPlan?588 let sources: [ResearchSource]589 let report: String590 let costUsd: Double?591 let error: String?592 var note: String?593 @ViewBuilder var actions: Actions594 @Environment(AppEnvironment.self) private var env595596 var body: some View {597 VStack(alignment: .leading, spacing: 14) {598 VStack(alignment: .leading, spacing: 10) {599 Text(question).font(.headline).textSelection(.enabled)600 HStack(spacing: 8) {601 if status != "?" { StatusPill(text: ResearchStatus.label(status), color: ResearchStatus.color(status)) }602 if let modelId { ModelBadge(name: env.catalog.displayName(forModel: modelId), provider: env.catalog.model(modelId)?.provider) }603 if let costUsd, costUsd > 0 { MetaChip(systemImage: "dollarsign.circle", text: Format.usd(costUsd, digits: 3), help: "Coût estimé localement") }604 Spacer(minLength: 0)605 }606 phases607 if let note { Label(note, systemImage: "info.circle").font(.caption).foregroundStyle(.secondary) }608 if let error, !error.isEmpty { Banner(kind: status == "cancelled" ? .info : .error, text: error) }609 CompareFlow(spacing: 8) { actions }610 }611 .frame(maxWidth: .infinity, alignment: .leading).card()612613 if let plan { planCard(plan) }614 sourcesCard615 reportCard616 }617 }618619 private var phases: some View {620 HStack(spacing: 14) {621 ForEach(Array(ResearchStatus.phases.enumerated()), id: \.offset) { i, name in622 let done = i < completedPhases623 let current = active && i == completedPhases624 HStack(spacing: 5) {625 if current { ProgressView().controlSize(.mini) }626 else { Image(systemName: done ? "checkmark.circle.fill" : "circle").foregroundStyle(done ? AnyShapeStyle(Palette.success) : AnyShapeStyle(.tertiary)) }627 Text(name).font(.caption.weight(current ? .semibold : .regular)).foregroundStyle(done || current ? .primary : .secondary)628 }629 .accessibilityElement(children: .ignore)630 .accessibilityLabel("\(name) : \(done ? "terminé" : current ? "en cours" : "à venir")")631 }632 }633 }634635 private func planCard(_ plan: ResearchPlan) -> some View {636 VStack(alignment: .leading, spacing: 8) {637 Label("Plan", systemImage: "list.bullet.clipboard").font(.headline)638 planList("Sous-questions", plan.subquestions, numbered: true)639 planList("Requêtes web", plan.queries, numbered: false)640 planList("Preuves recherchées", plan.evidenceNeeded, numbered: false)641 }642 .frame(maxWidth: .infinity, alignment: .leading).card()643 }644645 @ViewBuilder private func planList(_ title: String, _ items: [String], numbered: Bool) -> some View {646 if !items.isEmpty {647 Text(title).font(.caption.weight(.semibold)).foregroundStyle(.secondary)648 VStack(alignment: .leading, spacing: 3) {649 ForEach(Array(items.enumerated()), id: \.offset) { i, item in650 HStack(alignment: .firstTextBaseline, spacing: 6) {651 Text(numbered ? "\(i + 1)." : "•").foregroundStyle(.secondary).monospacedDigit()652 Text(item).textSelection(.enabled)653 }654 .font(.callout)655 }656 }657 }658 }659660 private var sourcesCard: some View {661 VStack(alignment: .leading, spacing: 8) {662 HStack {663 Label("Sources", systemImage: "link").font(.headline)664 Spacer()665 if !sources.isEmpty { Text("\(sources.filter(\.fetched).count) lues / \(sources.count)").font(.caption.monospacedDigit()).foregroundStyle(.secondary) }666 }667 if sources.isEmpty {668 HStack(spacing: 8) {669 if active { ProgressView().controlSize(.small) }670 Text(active ? "Recherche de sources en cours…" : "Aucune source.").font(.callout).foregroundStyle(.secondary)671 }672 } else {673 VStack(alignment: .leading, spacing: 6) {674 ForEach(sources) { s in ResearchSourceRow(source: s) }675 }676 }677 }678 .frame(maxWidth: .infinity, alignment: .leading).card()679 }680681 private var reportCard: some View {682 VStack(alignment: .leading, spacing: 10) {683 Label("Rapport", systemImage: "doc.richtext").font(.headline)684 if !report.isEmpty {685 MarkdownView(text: report).textSelection(.enabled)686 Divider()687 Label("Les affirmations suivies de [n] s'appuient sur les sources numérotées ci-dessus. Les passages étiquetés « Interprétation » ou « Spéculation » sont des jugements du modèle, pas des faits observés.", systemImage: "info.circle")688 .font(.caption).foregroundStyle(.secondary)689 } else if active {690 HStack(spacing: 8) { ProgressView().controlSize(.small); Text(completedPhases < 3 ? "Collecte des preuves…" : "Rédaction de la synthèse…").font(.callout).foregroundStyle(.secondary) }691 } else {692 Text("Pas de rapport.").font(.callout).foregroundStyle(.secondary)693 }694 }695 .frame(maxWidth: .infinity, alignment: .leading).card()696 }697}698699private struct ResearchSourceRow: View {700 let source: ResearchSource701 var body: some View {702 HStack(alignment: .firstTextBaseline, spacing: 8) {703 Text("[\(source.n)]").font(.caption.monospacedDigit()).foregroundStyle(.secondary).frame(width: 30, alignment: .trailing)704 VStack(alignment: .leading, spacing: 1) {705 if let link = source.link {706 Link(destination: link) { Text(source.title.isEmpty ? source.url : source.title).lineLimit(1).multilineTextAlignment(.leading) }707 .font(.callout).help(source.url)708 } else {709 Text(source.title.isEmpty ? source.url : source.title).font(.callout).lineLimit(1).help("Lien non ouvrable (seuls http et https sont permis)")710 }711 Text(source.url).font(.caption2).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle).textSelection(.enabled)712 }713 Spacer(minLength: 6)714 if source.failed { StatusPill(text: "échec", color: Palette.warning) }715 else if source.fetched {716 if let n = source.evidenceCount { StatusPill(text: "\(n) indice\(n > 1 ? "s" : "")", color: n > 0 ? Palette.success : .secondary) }717 else { StatusPill(text: "lue", color: .secondary) }718 } else { StatusPill(text: "non lue", color: .secondary) }719 }720 }721}722