Repository Public
1//2// VQuant iOS3// File: VQuant/Features/Research/ResearchView.swift4// Description: Research tab: start an analysis, follow server jobs live, read past conversations, browse the library.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import SwiftUI11import VQuantKit12import VQuantUI1314extension AnalysisMode {15 var label: String { switch self { case .fast: "Rapide"; case .standard: "Standard"; case .deep: "Approfondie"; case .ultra: "Ultra"; case .research: "Recherche autonome" } }16 var detail: String {17 switch self {18 case .fast: "Rapport court, environ une minute."19 case .standard: "Analyse complète avec figures."20 case .deep: "Plan, sous-analystes en parallèle, audit indépendant. Plusieurs minutes."21 case .ultra: "Deux tours de délégation, analyste contradicteur, vérification des sources. Le plus long."22 case .research: "L’agent conçoit l’étude, écrit et exécute son code dans un espace de travail persistant du serveur, tient un registre d’expériences et passe un contrôle de qualité."23 }24 }25 var systemImage: String { switch self { case .fast: "hare"; case .standard: "doc.text"; case .deep: "square.stack.3d.up"; case .ultra: "sparkles.rectangle.stack"; case .research: "flask" } }26}2728/// The research space: start a study, answer the agent's approval requests, follow what runs on the server, reopen29/// the studies (workspaces) and the conversations of the account, whichever device started them.30struct ResearchView: View {31 @Environment(AppModel.self) private var model32 @State private var search = ""33 @State private var renaming: ConversationSummary?34 @State private var newTitle = ""35 @State private var error: String?36 @State private var pendingDelete: ConversationSummary?3738 var body: some View {39 List {40 Section { OfflineBanner().listRowInsets(EdgeInsets()) }41 Section {42 Button { model.router.compose(mode: .research) } label: {43 Label("Nouvelle recherche", systemImage: "sparkles").font(.body.weight(.semibold))44 }45 .requiresNetwork(model.network.isOnline)46 .accessibilityIdentifier("new-analysis")47 if !model.next.hub.pending.isEmpty {48 RouteLink(.approvals) {49 Label("\(model.next.hub.pending.count) demande\(model.next.hub.pending.count > 1 ? "s" : "") d’autorisation en attente", systemImage: "hand.raised.fill").foregroundStyle(Theme.warning)50 }51 .accessibilityIdentifier("research-approvals")52 }53 RouteLink(.quant) { Label("Quant Lab", systemImage: "function") }54 RouteLink(.studio) { Label("Research Studio", systemImage: "books.vertical") }55 }5657 let jobs = model.research.generations.value ?? []58 if !jobs.isEmpty {59 Section {60 ForEach(jobs) { g in61 RouteLink(g.status == .running || g.replayable ? Route.run(g.id) : Route.conversation(g.sessionId)) { GenerationRow(generation: g) }62 .accessibilityIdentifier("generation-\(g.id)")63 .swipeActions {64 if g.status == .running {65 Button("Arrêter", role: .destructive) { Task { try? await model.api.cancelGeneration(g.id); await model.research.refreshGenerations() } }66 }67 }68 }69 } header: { Text("Sur le serveur (24 h)") } footer: {70 Text("Une étude continue sur le serveur même si l’application est fermée ; celles lancées sur le Mac ou le web apparaissent ici.").foregroundStyle(Theme.textSecondary)71 }72 }7374 Section {75 let studies = model.next.hub.sessions.value?.sessions ?? []76 if studies.isEmpty {77 Text(model.next.hub.sessions.isLoading ? "Chargement…" : model.next.hub.sessions.error ?? "Aucune étude autonome pour l’instant.").font(.footnote).foregroundStyle(Theme.textSecondary)78 }79 CachedNotice(at: model.next.hub.sessions.cachedAt)80 ForEach(studies.prefix(search.isEmpty ? 30 : 0)) { s in81 RouteLink(.researchSession(s.id)) { StudyRow(session: s) }.accessibilityIdentifier("study-\(s.id)")82 }83 } header: { Text("Études autonomes") }8485 Section("Historique des conversations") {86 let list = model.research.conversations.value ?? []87 if list.isEmpty {88 if model.research.conversations.isLoading { ProgressView() }89 else if model.research.conversations.isUnavailable { StateView(kind: .failed, title: "Historique indisponible", message: model.research.conversations.error?.message) { Task { await model.research.refreshConversations() } } }90 else { Text(search.isEmpty ? "Aucune conversation." : "Aucun résultat.").foregroundStyle(Theme.textSecondary) }91 }92 if model.research.conversations.loaded?.isFromCache == true, let t = model.research.conversations.loaded?.fetchedAt { FreshnessBadge(freshness: .cached(savedAt: t)) }93 ForEach(list) { c in94 RouteLink(.conversation(c.sessionId)) {95 VStack(alignment: .leading, spacing: 3) {96 HStack(spacing: 6) {97 if c.pinned { Image(systemName: "pin.fill").font(.caption2).foregroundStyle(Theme.orange).accessibilityLabel("Épinglée") }98 Text(c.title).lineLimit(2)99 }100 Text(Fmt.dateTime(c.updatedAt)).font(.caption).foregroundStyle(Theme.textSecondary)101 }102 }103 .accessibilityIdentifier("conversation-row")104 .swipeActions(edge: .trailing) {105 Button("Supprimer", role: .destructive) { pendingDelete = c }106 Button("Renommer") { newTitle = c.title; renaming = c }.tint(.gray)107 }108 .swipeActions(edge: .leading) {109 Button(c.pinned ? "Détacher" : "Épingler") { act { try await model.research.setPinned(c.sessionId, !c.pinned) } }.tint(Theme.orange)110 }111 }112 }113 }114 .listStyle(.insetGrouped)115 .navigationTitle("Recherche")116 .searchable(text: $search, prompt: "Rechercher dans l’historique")117 .task(id: search) {118 if !search.isEmpty { try? await Task.sleep(for: .milliseconds(350)); if Task.isCancelled { return } }119 await model.research.refreshConversations(search: search)120 }121 .task { await model.research.refreshGenerations(); model.research.startPolling(); await model.next.hub.refreshSessions(); await model.next.hub.refreshApprovals() }122 .refreshable { await model.research.refreshGenerations(); await model.research.refreshConversations(search: search); await model.next.hub.refreshSessions(); await model.next.hub.refreshApprovals() }123 .onChange(of: model.research.conversations.value) { _, list in if search.isEmpty, let list { Spotlight.index(conversations: list) } }124 .alert("Renommer", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {125 TextField("Titre", text: $newTitle)126 Button("Enregistrer") { if let c = renaming { let t = newTitle; act { try await model.research.rename(c.sessionId, title: t) } } }127 Button("Annuler", role: .cancel) {}128 }129 .confirmationDialog("Supprimer cette conversation ?", isPresented: Binding(get: { pendingDelete != nil }, set: { if !$0 { pendingDelete = nil } }), titleVisibility: .visible) {130 Button("Supprimer définitivement", role: .destructive) { if let c = pendingDelete { act { try await model.research.delete(c.sessionId) } } }131 } message: { Text("Elle sera effacée du serveur, pour tous vos appareils.") }132 .errorAlert($error)133 .errorAlert(Bindable(model.research).submissionError)134 .accessibilityIdentifier("research")135 }136137 private func act(_ work: @escaping () async throws -> Void) {138 Task { do { try await work() } catch let e { error = APIError.from(e).message } }139 }140}141142struct StepsView: View {143 let steps: [AnalysisRun.Step]144 @Binding var expanded: Bool145146 var body: some View {147 DisclosureGroup(isExpanded: $expanded) {148 VStack(alignment: .leading, spacing: 8) {149 ForEach(steps) { s in150 HStack(alignment: .top, spacing: 8) {151 icon(s).frame(width: 18)152 VStack(alignment: .leading, spacing: 2) {153 HStack {154 Text(s.title).font(.footnote.weight(.medium))155 if let d = s.durationMs { Text(Fmt.duration(d / 1000)).font(.caption2).foregroundStyle(Theme.textSecondary) }156 }157 if let input = s.input, !input.isNull, input.objectValue?.isEmpty == false {158 Text(input.prettyPrinted(limit: 220)).font(.system(.caption2, design: .monospaced)).foregroundStyle(Theme.textSecondary).lineLimit(4)159 }160 if let d = s.detail { Text(d).font(.caption).foregroundStyle(s.state == .failed ? Theme.down : Theme.textSecondary).lineLimit(6) }161 }162 }163 .accessibilityElement(children: .combine)164 }165 }166 .padding(.top, 6)167 } label: {168 Label("Déroulement (\(steps.count) étape\(steps.count > 1 ? "s" : ""))", systemImage: "list.bullet.indent").font(.subheadline.weight(.medium))169 }170 .padding(12)171 .background(Theme.surface, in: RoundedRectangle(cornerRadius: 12, style: .continuous))172 }173174 @ViewBuilder private func icon(_ s: AnalysisRun.Step) -> some View {175 switch s.state {176 case .running: ProgressView().controlSize(.mini)177 case .done: Image(systemName: s.kind == .agent ? "person.fill.checkmark" : s.kind == .plan ? "list.number" : "checkmark.circle.fill").font(.caption).foregroundStyle(Theme.up)178 case .failed: Image(systemName: "xmark.circle.fill").font(.caption).foregroundStyle(Theme.down)179 }180 }181}182183// MARK: - Conversation184185struct ConversationView: View {186 let sessionId: String187 @Environment(AppModel.self) private var model188 @State private var conversation: Conversation?189 @State private var origin: DataOrigin?190 @State private var error: String?191 @State private var followUp = false192 @State private var exporting = false193 @State private var share: ChartScreen.ShareItem?194 @State private var alert: String?195196 var body: some View {197 ScrollView {198 if let c = conversation {199 LazyVStack(alignment: .leading, spacing: 22) {200 if case .cache(let t)? = origin { FreshnessBadge(freshness: .cached(savedAt: t)) }201 ForEach(Array(c.exchanges.enumerated()), id: \.offset) { i, e in202 ExchangeView(exchange: e)203 HStack {204 Button { exportPDF(e) } label: { Label("PDF", systemImage: "doc.richtext") }.requiresNetwork(model.network.isOnline)205 ShareLink(item: e.answer, subject: Text(e.question)) { Label("Texte", systemImage: "square.and.arrow.up") }206 }207 .buttonStyle(.bordered).font(.footnote)208 if i < c.exchanges.count - 1 { Divider() }209 }210 if c.exchanges.isEmpty { StateView(kind: .empty, title: "Conversation vide", systemImage: "text.bubble") }211 if let job = model.research.running.first(where: { $0.sessionId == sessionId }) {212 RouteLink(.run(job.id)) { Label("Une analyse est en cours dans cette conversation", systemImage: "server.rack") }.font(.footnote)213 }214 }215 .padding(16)216 } else if let error {217 StateView(kind: .failed, title: "Conversation indisponible", message: error) { Task { await load() } }218 } else { StateView(kind: .loading, title: "Chargement…") }219 }220 .background(Theme.background)221 .navigationTitle(conversation?.title ?? "Conversation").navigationBarTitleDisplayMode(.inline)222 .toolbar {223 ToolbarItem(placement: .primaryAction) {224 Button { followUp = true } label: { Label("Poursuivre", systemImage: "square.and.pencil") }225 .disabled(conversation == nil).requiresNetwork(model.network.isOnline)226 .accessibilityIdentifier("conversation-followup")227 }228 }229 .overlay { if exporting { ProgressView("Mise en page du PDF sur le serveur…").padding(20).background(.regularMaterial, in: RoundedRectangle(cornerRadius: 14)) } }230 .task { await load() }231 .refreshable { await load() }232 .sheet(isPresented: $followUp) { ComposerSheet(sessionId: sessionId, history: conversation?.exchanges ?? []).environment(model) }233 .sheet(item: $share) { ActivityView(items: [$0.url]) }234 .errorAlert($alert)235 .accessibilityIdentifier("conversation")236 }237238 private func load() async {239 do { let l = try await model.research.conversation(sessionId); conversation = l.value; origin = l.origin; error = nil }240 catch let e { let a = APIError.from(e); if a.kind != .cancelled { error = a.message } }241 }242243 private func exportPDF(_ e: Exchange) {244 exporting = true245 Task {246 defer { exporting = false }247 do {248 let data = try await model.api.pdf(question: e.question, answer: e.answer)249 let url = FileManager.default.temporaryDirectory.appendingPathComponent("VQuant-\(Int(Date().timeIntervalSince1970)).pdf")250 try data.write(to: url, options: .atomic)251 share = .init(url: url)252 } catch let err { alert = APIError.from(err).message }253 }254 }255}256257// MARK: - Library (shared reports)258259struct LibraryView: View {260 @Environment(AppModel.self) private var model261 var body: some View {262 List {263 let list = model.research.library.value ?? []264 if list.isEmpty {265 if model.research.library.isLoading { ProgressView() }266 else if model.research.library.isUnavailable { StateView(kind: .failed, title: "Bibliothèque indisponible", message: model.research.library.error?.message) { Task { await model.research.refreshLibrary() } } }267 else { StateView(kind: .empty, title: "Aucun rapport partagé", message: "Les rapports partagés depuis le site apparaissent ici.", systemImage: "books.vertical") }268 }269 ForEach(list) { r in270 RouteLink(.sharedReport(r.shareId)) {271 VStack(alignment: .leading, spacing: 4) {272 Text(r.question).font(.subheadline.weight(.medium)).lineLimit(2)273 Text(ReportText.plain(r.answer, limit: 160)).font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(3)274 Text(Fmt.day(r.createdAt)).font(.caption2).foregroundStyle(Theme.textSecondary)275 }276 }277 }278 }279 .navigationTitle("Bibliothèque")280 .task { await model.research.refreshLibrary() }281 .refreshable { await model.research.refreshLibrary() }282 }283}284285struct SharedReportView: View {286 let shareId: String287 @Environment(AppModel.self) private var model288 @State private var report: SharedReport?289 @State private var error: String?290 var body: some View {291 ScrollView {292 if let report { ExchangeView(exchange: report.exchange).padding(16) }293 else if let error { StateView(kind: .failed, title: "Rapport indisponible", message: error) }294 else { StateView(kind: .loading, title: "Chargement…") }295 }296 .background(Theme.background)297 .navigationTitle("Rapport").navigationBarTitleDisplayMode(.inline)298 .task {299 do { report = try await model.api.sharedReport(shareId) } catch let e { error = APIError.from(e).message }300 }301 }302}303