SPB Git

Repository Public

ResearchViews.swift 51.6 KB 892 lines swift

1//2//  VQuant iOS3//  File: VQuant/Next/ResearchViews.swift4//  Description: The autonomous research agent on iPhone and iPad: the composer (mode, model from the server registry,5//               dataset from Files, budget), the live view of a study (Rapport · Activité · Code · Expériences ·6//               Figures · Fichiers, built from the shared research views of VQuantKit), approval requests, and the7//               view of a study kept on the server. Nothing is computed on the device.8//9//  Author: Simon-Pierre Boucher10//  Contact: contact@spboucher.ai11//1213import PhotosUI14import QuickLook15import SwiftUI16import UniformTypeIdentifiers17import VQuantKit18import VQuantUI1920// MARK: - Composer2122/// A dataset attached to the next study: uploaded into the workspace's `data/` folder, then profiled by the server.23struct AttachedDataset: Identifiable, Equatable {24    enum State: Equatable { case uploading, ready(VQUploadedFile, VQDatasetInspection?), failed(String) }25    let id = UUID()26    var name: String27    var bytes: Int28    var state: State29}3031struct ComposerSheet: View {32    @Environment(AppModel.self) private var model33    @Environment(\.dismiss) private var dismiss34    @Environment(\.horizontalSizeClass) private var sizeClass35    var sessionId: String?36    var history: [Exchange] = []37    @State private var text = ""38    @State private var mode: AnalysisMode = .research39    @State private var modelId = ""40    @State private var limitCost = false41    @State private var maxCost = 3.042    @State private var limitMinutes = false43    @State private var maxMinutes = 30.044    @State private var projectId: String?45    @State private var photo: PhotosPickerItem?46    @State private var imageData: Data?47    @State private var datasets: [AttachedDataset] = []48    /// The workspace created to receive datasets before the first message (its conversation id is then the study's).49    @State private var workspace: (id: String, sessionId: String)?50    @State private var importing = false51    @State private var notice: String?52    @State private var prepared = false53    @FocusState private var focused: Bool5455    private static let suggestions = [56        "Étudie si la volatilité implicite de SPY prévoit mieux la volatilité réalisée qu’un GARCH : conçois le protocole, exécute-le et rapporte les résultats avec leurs limites.",57        "Résume la séance d’aujourd’hui : indices majeurs, secteurs, taux et devises.",58        "Quels sont les risques principaux de mon portefeuille actuel ?",59        "Compare la valorisation de MSFT, GOOGL et META sur 5 ans.",60    ]61    static let datasetTypes: [UTType] = [.commaSeparatedText, .tabSeparatedText, .plainText, .json, .spreadsheet, .data]6263    private var uploading: Bool { datasets.contains { $0.state == .uploading } }64    private var canLaunch: Bool { !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && model.network.isOnline && !uploading }6566    var body: some View {67        NavigationStack {68            Form {69                Section {70                    TextEditor(text: $text).frame(minHeight: 120).focused($focused)71                        .accessibilityLabel("Question pour l’agent").accessibilityIdentifier("composer-text")72                        .symbolDrop { text += (text.isEmpty || text.hasSuffix(" ") ? "" : " ") + $0 + " " }73                        .dropDestination(for: URL.self) { urls, _ in for u in urls where u.isFileURL { attach(u) }; return !urls.isEmpty }74                    if let imageData, let ui = UIImage(data: imageData) {75                        HStack {76                            Image(uiImage: ui).resizable().scaledToFill().frame(width: 56, height: 56).clipShape(RoundedRectangle(cornerRadius: 8))77                            Text("Image jointe").font(.footnote)78                            Spacer()79                            Button("Retirer", role: .destructive) { self.imageData = nil; photo = nil }.font(.footnote)80                        }81                    }82                    ForEach(datasets) { d in DatasetCard(dataset: d) { datasets.removeAll { $0.id == d.id } } }83                    HStack(spacing: 16) {84                        Button { importing = true } label: { Label("Jeu de données", systemImage: "tablecells.badge.ellipsis").frame(minHeight: 44).contentShape(Rectangle()) }85                            .accessibilityIdentifier("composer-dataset")86                        PhotosPicker(selection: $photo, matching: .images) { Label("Image", systemImage: "photo").frame(minHeight: 44).contentShape(Rectangle()) }87                    }88                    .font(.subheadline).buttonStyle(.borderless)89                    if let notice { Label(notice, systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Theme.warning).accessibilityIdentifier("composer-notice") }90                } header: { Text(sessionId == nil ? "Votre question de recherche" : "Suite de l’étude").foregroundStyle(Theme.textSecondary) } footer: {91                    Text("Formats de données : CSV, TSV, TXT, JSON, JSONL, Parquet, XLSX, XLS, Feather. Le fichier est envoyé dans l’espace de travail de l’étude, sur le serveur.").foregroundStyle(Theme.textSecondary)92                }9394                Section {95                    ModePicker(mode: $mode, researchAvailable: model.next.hub.researchAvailable)96                } header: { Text("Mode").foregroundStyle(Theme.textSecondary) } footer: { Text(mode.detail).foregroundStyle(Theme.textSecondary) }9798                Section {99                    NavigationLink {100                        ModelPickerView(selection: $modelId)101                    } label: {102                        LabeledContent("Modèle") { ModelBadge(id: modelId.isEmpty ? nil : modelId) }103                    }104                    .accessibilityIdentifier("composer-model")105                    if mode != .fast {106                        Toggle("Limiter le coût", isOn: $limitCost).accessibilityIdentifier("composer-budget-cost")107                        if limitCost {108                            Stepper(value: $maxCost, in: 0.5...100, step: maxCost < 5 ? 0.5 : 5) { LabeledContent("Coût maximal") { Text(VQFormat.currency(maxCost)).font(.mono(.body)) } }109                        }110                        Toggle("Limiter la durée", isOn: $limitMinutes)111                        if limitMinutes {112                            Stepper(value: $maxMinutes, in: 5...720, step: maxMinutes < 60 ? 5 : 30) { LabeledContent("Durée maximale") { Text("\(Int(maxMinutes)) min").font(.mono(.body)) } }113                        }114                    }115                    if !model.next.studio.projects.isEmpty {116                        Picker("Projet", selection: $projectId) {117                            Text("Aucun").tag(String?.none)118                            ForEach(model.next.studio.projects.prefix(20)) { p in Text(p.data.title).tag(Optional(p.id)) }119                        }120                        .accessibilityIdentifier("composer-project")121                    }122                } header: { Text("Modèle et budget").foregroundStyle(Theme.textSecondary) } footer: {123                    Text(modelId == "auto" ? "Auto : le serveur choisit le modèle selon le mode, le contexte et l’état des fournisseurs, et dit pourquoi." : "Au budget atteint, l’agent conclut avec ce qu’il a. Un dépassement demande votre autorisation.").foregroundStyle(Theme.textSecondary)124                }125126                if text.isEmpty && sessionId == nil {127                    Section("Suggestions") {128                        ForEach(Self.suggestions, id: \.self) { s in Button(s) { text = s }.font(.subheadline).foregroundStyle(.primary) }129                    }130                }131                if !model.network.isOnline {132                    Section { Label("Hors ligne : une étude ne peut pas être lancée. Rien n’est mis en file d’attente.", systemImage: "wifi.slash").font(.footnote).foregroundStyle(Theme.warning) }133                }134            }135            .navigationTitle(mode == .research ? "Nouvelle recherche" : "Nouvelle analyse").navigationBarTitleDisplayMode(.inline)136            .toolbar {137                ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }138                ToolbarItem(placement: .confirmationAction) {139                    Button("Lancer") { launch() }140                        .disabled(!canLaunch)141                        .keyboardShortcut(.return, modifiers: .command)142                        .accessibilityIdentifier("composer-send")143                }144            }145            .fileImporter(isPresented: $importing, allowedContentTypes: Self.datasetTypes, allowsMultipleSelection: true) { result in146                if case .success(let urls) = result { for u in urls { attach(u) } }147            }148            .onAppear(perform: prepare)149            .task {150                if model.next.models.catalog.value == nil { await model.next.models.refresh() }151                if model.next.hub.sandbox == nil { await model.next.hub.refreshSandbox() }152                if !model.next.hub.researchAvailable, mode == .research { mode = model.preferences.defaultMode == .research ? .standard : model.preferences.defaultMode }153            }154            .onChange(of: photo) { _, item in155                Task {156                    guard let raw = try? await item?.loadTransferable(type: Data.self), let ui = UIImage(data: raw) else { return }157                    // Re-encoded as JPEG at a bounded size: the backend accepts bodies up to 10 MB.158                    let side = max(ui.size.width, ui.size.height), scale = min(1, 1600 / side)159                    let size = CGSize(width: ui.size.width * scale, height: ui.size.height * scale)160                    let small = UIGraphicsImageRenderer(size: size).image { _ in ui.draw(in: CGRect(origin: .zero, size: size)) }161                    imageData = small.jpegData(compressionQuality: 0.8)162                }163            }164        }165166    }167168    /// Once: `onAppear` fires again when the model picker is popped, and must not undo what was chosen.169    private func prepare() {170        guard !prepared else { return }171        prepared = true172        let preset = model.router.composerPreset173        mode = preset.mode ?? (sessionId == nil ? .research : model.preferences.defaultMode)174        modelId = model.preferences.defaultModel175        projectId = preset.projectId176        if let c = model.preferences.budgetCostUsd { limitCost = true; maxCost = c }177        if let m = model.preferences.budgetMinutes { limitMinutes = true; maxMinutes = m }178        if !model.router.composerDraft.isEmpty { text = model.router.composerDraft; model.router.composerDraft = "" }179        for u in preset.files { attach(u) }180        model.router.composerPreset = Router.ComposerPreset()181        focused = true182    }183184    /// Reads the picked file, checks it like the server will (extension, size, signature), creates the workspace if185    /// needed, uploads, then asks the server to profile it.186    private func attach(_ url: URL) {187        let name = url.lastPathComponent188        let scoped = url.startAccessingSecurityScopedResource()189        defer { if scoped { url.stopAccessingSecurityScopedResource() } }190        guard let data = try? Data(contentsOf: url, options: .mappedIfSafe) else { notice = "« \(name) » est illisible."; return }191        let limit = model.next.hub.sandbox?.uploadMaxBytes ?? VQDatasetUpload.defaultMaxBytes192        if let refusal = VQDatasetUpload.validate(name: name, size: data.count, head: data.prefix(4096), maxBytes: limit) { notice = refusal.message(.fr); return }193        notice = nil194        if mode != .research { mode = .research }195        let item = AttachedDataset(name: name, bytes: data.count, state: .uploading)196        datasets.append(item)197        Task {198            do {199                if workspace == nil, sessionId == nil {200                    let w = try await model.next.hub.createSession(title: text.isEmpty ? name : String(text.prefix(80)), projectId: projectId)201                    workspace = (w.workspace.id, w.sessionId)202                }203                let target = workspace?.id ?? VQResearchSession.reference(sessionId: sessionId ?? "")204                let file = try await model.next.hub.upload(target, name: name, data: data)205                update(item.id, .ready(file, nil))206                let inspection = try? await model.next.hub.inspect(target, path: file.path)207                update(item.id, .ready(file, inspection))208            } catch let r as VQDatasetUpload.Refusal { update(item.id, .failed(r.message(.fr))) }209            catch let e as VQError { update(item.id, .failed(VQDatasetUpload.message(for: e, .fr))) }210            catch { update(item.id, .failed(nextMessage(error))) }211        }212    }213    private func update(_ id: UUID, _ state: AttachedDataset.State) { if let i = datasets.firstIndex(where: { $0.id == id }) { datasets[i].state = state } }214215    private func launch() {216        var q = String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(10_000))217        let files = datasets.compactMap { d -> String? in if case .ready(let f, _) = d.state { return f.path } else { return nil } }218        if !files.isEmpty { q += "\n\nJeux de données déposés dans l’espace de travail : " + files.joined(separator: ", ") + "." }219        let budget: ChatRequest.Budget? = (mode != .fast && (limitCost || limitMinutes)) ? ChatRequest.Budget(maxCostUsd: limitCost ? maxCost : nil, maxMinutes: limitMinutes ? maxMinutes : nil) : nil220        let c = model.research.start(query: q, mode: mode, sessionId: workspace?.sessionId ?? sessionId, history: history, imageData: imageData, imageMime: imageData == nil ? nil : "image/jpeg",221                                     model: modelId.isEmpty ? nil : modelId, budget: budget, projectId: projectId)222        let compact = sizeClass == .compact223        dismiss()224        // The job id arrives with the first event of the stream; the route is pushed once it is known.225        Task {226            for _ in 0..<100 {227                if let id = c.jobId { model.router.open(.run(id), compact: compact); return }228                if c.run.isFinished { model.router.section = .research; if let e = c.run.error { model.research.submissionError = e }; return }229                try? await Task.sleep(for: .milliseconds(100))230            }231        }232        model.next.hub.startPolling { [research = model.research] in !research.running.isEmpty }233        Task { _ = await model.notifications.requestAuthorization() }234    }235}236237struct ModePicker: View {238    @Binding var mode: AnalysisMode239    var researchAvailable = true240    var body: some View {241        VStack(spacing: 8) {242            // The research mode is offered only when the server has the research agent (its sandbox route answers).243            if researchAvailable { researchRow }244            Picker("Analyse", selection: Binding(get: { mode == .research ? AnalysisMode.standard : mode }, set: { mode = $0 })) {245                ForEach(AnalysisMode.classic) { Text($0.label).tag($0) }246            }247            .pickerStyle(.segmented)248            .opacity(mode == .research ? 0.55 : 1)249            .accessibilityIdentifier("composer-mode")250        }251    }252253    private var researchRow: some View {254            Button { mode = .research } label: {255                HStack(spacing: 10) {256                    Image(systemName: AnalysisMode.research.systemImage).font(.title3).foregroundStyle(Theme.orange).frame(width: 30)257                    VStack(alignment: .leading, spacing: 1) {258                        Text("Recherche autonome").font(.subheadline.weight(.semibold)).foregroundStyle(Color.primary)259                        Text("Espace de travail, code, expériences, contrôle de qualité").font(.caption).foregroundStyle(Theme.textSecondary)260                    }261                    Spacer()262                    Image(systemName: mode == .research ? "largecircle.fill.circle" : "circle").foregroundStyle(mode == .research ? Theme.orange : Theme.textSecondary)263                }264                .frame(minHeight: 44).contentShape(Rectangle())265            }266            .buttonStyle(.plain)267            .accessibilityAddTraits(mode == .research ? [.isSelected] : [])268            .accessibilityIdentifier("mode-research")269    }270}271272/// What the server found in an uploaded dataset: size, rows, columns with their type and missing share.273struct DatasetCard: View {274    let dataset: AttachedDataset275    var onRemove: (() -> Void)?276    var body: some View {277        VStack(alignment: .leading, spacing: 8) {278            HStack(spacing: 8) {279                Image(systemName: "tablecells").foregroundStyle(Theme.orange)280                Text(dataset.name).font(.mono(.footnote, weight: .medium)).lineLimit(1).truncationMode(.middle)281                Spacer()282                Text(Fmt.bytes(dataset.bytes)).font(.mono(.caption)).foregroundStyle(Theme.textSecondary)283                if let onRemove { Button(action: onRemove) { Image(systemName: "xmark.circle.fill").foregroundStyle(Theme.textSecondary) }.buttonStyle(.plain).frame(minWidth: 44, minHeight: 44).accessibilityLabel("Retirer \(dataset.name) de la liste") }284            }285            switch dataset.state {286            case .uploading: HStack(spacing: 8) { ProgressView().controlSize(.small); Text("Envoi vers l’espace de travail…").font(.caption).foregroundStyle(Theme.textSecondary) }287            case .failed(let m): Label(m, systemImage: "exclamationmark.triangle").font(.caption).foregroundStyle(Theme.down)288            case .ready(let file, let inspection):289                Text("Déposé : \(file.path)").font(.mono(.caption2)).foregroundStyle(Theme.textSecondary)290                if let i = inspection { DatasetInspectionView(inspection: i) }291                else { Text("Profil du jeu de données en cours ou indisponible ; l’agent l’inspectera lui-même.").font(.caption).foregroundStyle(Theme.textSecondary) }292            }293        }294        .padding(10).background(Theme.surface2.opacity(0.6), in: RoundedRectangle(cornerRadius: 10))295        .accessibilityElement(children: .contain)296        .accessibilityIdentifier("dataset-card")297    }298}299300struct DatasetInspectionView: View {301    let inspection: VQDatasetInspection302    var body: some View {303        VStack(alignment: .leading, spacing: 6) {304            Text([inspection.format.uppercased(), inspection.rows.map { "\(VQFormat.int($0)) lignes" }, inspection.columnCount.map { "\($0) colonnes" },305                  (inspection.duplicatedRows ?? 0) > 0 ? "\(inspection.duplicatedRows!) lignes dupliquées" : nil].compactMap { $0 }.joined(separator: " · "))306                .font(.caption.weight(.medium))307            if !inspection.timeColumns.isEmpty { Text("Colonnes de temps : \(inspection.timeColumns.joined(separator: ", "))").font(.caption2).foregroundStyle(Theme.textSecondary) }308            ForEach(inspection.columns.prefix(8)) { c in309                HStack {310                    Text(c.name).font(.mono(.caption2, weight: .medium)).lineLimit(1)311                    Spacer(minLength: 6)312                    Text(c.dtype).font(.mono(.caption2)).foregroundStyle(Theme.textSecondary)313                    if c.missing > 0 { Text("\(VQFormat.percent(c.missingShare, decimals: 0)) manquant").font(.caption2).foregroundStyle(Theme.warning) }314                }315            }316            if inspection.columns.count > 8 { Text("… et \(inspection.columns.count - 8) autres colonnes").font(.caption2).foregroundStyle(Theme.textSecondary) }317        }318        .accessibilityElement(children: .combine)319    }320}321322/// The models the server can run, by provider, with the provider's mark. Only selectable models can be chosen.323struct ModelPickerView: View {324    @Environment(AppModel.self) private var model325    @Environment(\.dismiss) private var dismiss326    @Binding var selection: String327328    var body: some View {329        List {330            Section {331                row(id: "auto", title: model.next.models.catalog.value?.auto.label ?? "Auto", detail: "Le serveur choisit et explique son choix", logo: nil)332                row(id: "", title: "Modèle par défaut du serveur", detail: model.next.models.catalog.value.map { model.next.models.label($0.defaultModel) }, logo: nil)333            }334            if let c = model.next.models.catalog.value {335                ForEach(c.providers) { p in336                    Section {337                        if !p.configured { Text("Fournisseur non configuré sur le serveur.").font(.footnote).foregroundStyle(Theme.textSecondary) }338                        else if let e = p.error, !p.ok { Label(e, systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Theme.warning) }339                        ForEach(p.models.filter { $0.selectable || $0.available }) { m in340                            row(id: m.id, title: m.label, detail: Self.detail(m), logo: p.id, enabled: m.selectable)341                        }342                    } header: { HStack(spacing: 6) { VQProviderLogo(provider: p.id, size: 13); Text(p.name) } }343                }344                CachedNotice(at: model.next.models.catalog.cachedAt)345            } else if model.next.models.catalog.isUnavailable {346                StateView(kind: .failed, title: "Registre des modèles indisponible", message: model.next.models.catalog.error) { Task { await model.next.models.refresh() } }347            } else { ProgressView() }348        }349        .navigationTitle("Modèle").navigationBarTitleDisplayMode(.inline)350        .task { await model.next.models.refresh() }351        .accessibilityIdentifier("model-picker")352    }353354    static func detail(_ m: VQModelInfo) -> String {355        var parts: [String] = []356        switch m.tier?.known { case .frontier: parts.append("Pointe"); case .balanced: parts.append("Équilibré"); case .fast: parts.append("Rapide"); case nil: break }357        if let c = m.contextWindow { parts.append("\(VQFormat.compact(Double(c), decimals: 0)) jetons de contexte") }358        if let p = m.pricing, let i = p.inputPerMTok, let o = p.outputPerMTok { parts.append("\(VQFormat.currency(i)) / \(VQFormat.currency(o)) par M jetons") }359        if !m.selectable { parts.append("non utilisable par l’agent") }360        return parts.joined(separator: " · ")361    }362363    private func row(id: String, title: String, detail: String?, logo: String?, enabled: Bool = true) -> some View {364        Button { selection = id; dismiss() } label: {365            HStack(spacing: 10) {366                if id == "auto" { Image(systemName: "wand.and.stars").foregroundStyle(Theme.orange).frame(width: 22) }367                else if let logo { VQProviderLogo(provider: logo, size: 16).frame(width: 22) }368                else { Image(systemName: "server.rack").foregroundStyle(Theme.textSecondary).frame(width: 22) }369                VStack(alignment: .leading, spacing: 2) {370                    Text(title).foregroundStyle(enabled ? Color.primary : Theme.textSecondary)371                    if let detail, !detail.isEmpty { Text(detail).font(.caption).foregroundStyle(Theme.textSecondary) }372                }373                Spacer()374                if selection == id { Image(systemName: "checkmark").foregroundStyle(Theme.orange).accessibilityLabel("Sélectionné") }375            }376            .contentShape(Rectangle())377        }378        .buttonStyle(.plain).disabled(!enabled)379        .accessibilityIdentifier("model-\(id.isEmpty ? "default" : id)")380    }381}382383// MARK: - Approvals384385/// Prominent card on the home screen and at the top of the research space while the agent waits for an answer.386struct ApprovalsCard: View {387    @Environment(AppModel.self) private var model388    @State private var error: String?389    var body: some View {390        let pending = model.next.hub.pending391        if !pending.isEmpty {392            VStack(alignment: .leading, spacing: 12) {393                Label("L’agent attend votre autorisation", systemImage: "hand.raised.fill").font(.serif(.headline)).foregroundStyle(Theme.warning)394                ForEach(pending) { a in395                    ResearchApprovalCard(a, onApprove: { answer(a, .approve) }, onRefuse: { answer(a, .deny) })396                        .accessibilityIdentifier("approval-\(a.id)")397                }398                Text("Sans réponse dans les 15 minutes, la demande est refusée. Chaque réponse est consignée dans le journal du compte.").font(.caption).foregroundStyle(Theme.textSecondary)399            }400            .padding(14)401            .background(Theme.warning.opacity(0.08), in: RoundedRectangle(cornerRadius: Theme.corner, style: .continuous))402            .overlay(RoundedRectangle(cornerRadius: Theme.corner, style: .continuous).strokeBorder(Theme.warning.opacity(0.6), lineWidth: 1))403            .errorAlert($error)404            .accessibilityElement(children: .contain).accessibilityIdentifier("approvals-card")405        }406    }407    private func answer(_ a: VQResearchApproval, _ d: VQResearchApproval.Decision) {408        Task {409            if let e = await model.next.hub.answer(a.id, d) { error = e } else { Haptics.success() }410            model.notifications.clearApproval(a.id)411        }412    }413}414415struct ApprovalsView: View {416    @Environment(AppModel.self) private var model417    var body: some View {418        ScrollView {419            VStack(alignment: .leading, spacing: 16) {420                if model.next.hub.pending.isEmpty {421                    ContentUnavailableView { Label("Aucune demande en attente", systemImage: "hand.raised") } description: {422                        Text("L’agent demande votre accord avant d’ouvrir le réseau au-delà des données de marché, d’envoyer des données à un service externe ou de dépasser un budget. Tout le reste se fait dans son bac à sable, sans vous interrompre.")423                    }424                } else { ApprovalsCard() }425                if let e = model.next.hub.approvalsError { Label(e, systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Theme.warning) }426            }427            .padding(16)428        }429        .background(Theme.background)430        .navigationTitle("Autorisations").navigationBarTitleDisplayMode(.inline)431        .task { await model.next.hub.refreshApprovals() }432        .refreshable { await model.next.hub.refreshApprovals() }433        .accessibilityIdentifier("approvals")434    }435}436437/// iPad: the detail column of the research section when no study is selected.438struct ResearchLanding: View {439    @Environment(AppModel.self) private var model440    var body: some View {441        ScrollView {442            VStack(alignment: .leading, spacing: 18) {443                AskCard(title: "Une question, et l’agent mène l’étude.")444                ApprovalsCard()445                if !model.research.running.isEmpty {446                    EditorialHeader("En cours sur le serveur")447                    ForEach(model.research.running) { g in RouteLink(.run(g.id)) { GenerationRow(generation: g) }.buttonStyle(.plain); Divider() }448                }449                EditorialHeader("Comment travaille l’agent")450                VStack(alignment: .leading, spacing: 10) {451                    point("flask", "Il conçoit le protocole, écrit son code et l’exécute dans un espace de travail persistant du serveur, isolé et sans accès à vos identifiants.")452                    point("list.clipboard", "Chaque exécution et chaque expérience — réussie, échouée ou abandonnée — est inscrite dans un registre.")453                    point("checkmark.seal", "Avant de conclure, un contrôle de qualité vérifie que les nombres cités viennent bien de ce qui a été calculé.")454                    point("hand.raised", "Il vous demande votre accord pour sortir du bac à sable ou dépasser un budget, et pour rien d’autre.")455                }456            }457            .padding(20).frame(maxWidth: 820, alignment: .leading).frame(maxWidth: .infinity)458        }459        .background(Theme.background)460        .navigationTitle("Recherche").navigationBarTitleDisplayMode(.inline)461    }462    private func point(_ image: String, _ text: String) -> some View {463        HStack(alignment: .top, spacing: 10) { Image(systemName: image).foregroundStyle(Theme.orange).frame(width: 24).accessibilityHidden(true); Text(text).font(.callout).fixedSize(horizontal: false, vertical: true) }464    }465}466467// MARK: - The study cockpit (live or stored)468469enum StudyTab: String, CaseIterable, Identifiable {470    case report, activity, code, experiments, figures, files471    var id: String { rawValue }472    var label: String {473        switch self { case .report: "Rapport"; case .activity: "Activité"; case .code: "Code"; case .experiments: "Expériences"; case .figures: "Figures"; case .files: "Fichiers" }474    }475    static let inspector: [StudyTab] = [.activity, .code, .experiments, .figures, .files]476}477478/// One section of a study, built from the shared research views of the kit.479struct StudySection: View {480    let tab: StudyTab481    let store: VQResearchSessionStore482    @Binding var selectedFile: String?483    var onOpenFile: (String) -> Void484    var onExport: (String, Data) -> Void485486    var body: some View {487        let state = store.state488        VStack(alignment: .leading, spacing: 18) {489            switch tab {490            case .report: EmptyView()491            case .activity:492                if state.isEmpty && state.plan.isEmpty {493                    VQEmptyState(systemImage: "list.bullet.indent", title: "Aucune activité de recherche", message: "Cette analyse n’a pas utilisé l’espace de travail de recherche. Son déroulement est dans le rapport.")494                } else {495                    ResearchPlanView(state)496                    if !store.gateFindings.isEmpty {497                        VStack(alignment: .leading, spacing: 8) { Text("Contrôle de qualité".uppercased()).font(.caption2.weight(.semibold)).tracking(0.9).foregroundStyle(Theme.textSecondary); ResearchQualityGateView(store.gateFindings) }498                    }499                    ForEach(Array(state.budgetHits.enumerated()), id: \.offset) { _, b in500                        Label("Budget atteint (\(b.kind == "cost" ? "coût" : "durée")) : \(VQFormat.number(b.spent, decimals: 2)) sur \(VQFormat.number(b.limit, decimals: 2)). L’agent conclut.", systemImage: "gauge.with.dots.needle.67percent")501                            .font(.footnote).foregroundStyle(Theme.warning)502                    }503                    ResearchTimelineView(state)504                    if !state.runs.isEmpty {505                        Text("Exécutions longues".uppercased()).font(.caption2.weight(.semibold)).tracking(0.9).foregroundStyle(Theme.textSecondary)506                        ResearchRunsList(state.runs) { run in Task { await store.cancel(run: run) } }507                    }508                }509            case .code:510                if state.executions.isEmpty && state.installs.isEmpty { VQEmptyState(systemImage: "chevron.left.forwardslash.chevron.right", title: "Aucun code exécuté pour l’instant") }511                else { ResearchExecutionList(state.executions, installs: state.installs, expanded: Set(state.executions.filter { $0.status != .ok && $0.status != .running }.prefix(1).map(\.key))) }512            case .experiments:513                if state.experiments.isEmpty { VQEmptyState(systemImage: "list.clipboard", title: "Aucune expérience déclarée", message: "L’agent inscrit ici ses expériences, y compris celles qui échouent ou qu’il abandonne.") }514                else { ResearchExperimentsTable(state.experiments) { path in onOpenFile(path) } }515            case .figures:516                if state.figures.isEmpty { VQEmptyState(systemImage: "photo.on.rectangle", title: "Aucune figure pour l’instant") }517                else { ResearchFiguresGrid(state.figures) { figure, format, data in onExport((figure.title ?? "figure").replacingOccurrences(of: "/", with: "-") + "." + format.rawValue, data) } }518            case .files:519                ResearchFilesBrowser(files: store.detail?.files ?? [], selection: $selectedFile) { path, data in onExport((path as NSString).lastPathComponent, data) }520                ResearchEnvironmentPanel(sandbox: store.sandbox, environment: store.detail?.environment, library: store.detail?.library ?? [])521            }522        }523        .frame(maxWidth: .infinity, alignment: .topLeading)524    }525}526527/// The layout shared by a live study and a stored one. iPhone: a segmented switch over the six sections. iPad: the528/// report in the main column and the other sections in a resizable inspector.529struct StudyCockpit<Header: View, Report: View>: View {530    @Environment(AppModel.self) private var model531    @Environment(\.horizontalSizeClass) private var sizeClass532    let store: VQResearchSessionStore533    var workspaceId: String?534    @ViewBuilder var header: Header535    @ViewBuilder var report: Report536    @State private var tab: StudyTab = .report537    @State private var inspectorTab: StudyTab = .activity538    @State private var selectedFile: String?539    @State private var preview: URL?540    @State private var alert: String?541542    private var source: ResearchDataSource {543        guard let id = workspaceId ?? store.workspaceId else { return .unavailable }544        let hub = model.next.hub545        let client = hub.client546        return ResearchDataSource(textFile: { try await hub.textFile(id, path: $0).value }, fileData: { try await hub.fileData(id, path: $0) },547                                  runLogs: { try await client.run($0, tail: 8000) }, inspect: { try await client.inspect(id, path: $0) })548    }549550    var body: some View {551        @Bindable var router = model.router552        Group {553            if sizeClass == .regular {554                ScrollView { VStack(alignment: .leading, spacing: 16) { header; approvals; report }.padding(20).frame(maxWidth: 860, alignment: .leading).frame(maxWidth: .infinity) }555                    .inspector(isPresented: $router.showInspector) {556                        VStack(spacing: 0) {557                            picker(StudyTab.inspector, selection: $inspectorTab).padding(.horizontal, 12).padding(.vertical, 8)558                            Divider()559                            ScrollView { section(inspectorTab).padding(14) }560                        }561                        .inspectorColumnWidth(min: 340, ideal: 460, max: 720)562                        .background(Theme.background)563                    }564                    .toolbar {565                        ToolbarItem(placement: .primaryAction) {566                            Button { router.showInspector.toggle() } label: { Label("Inspecteur", systemImage: "sidebar.trailing") }.accessibilityIdentifier("study-inspector-toggle")567                        }568                    }569            } else {570                ScrollView {571                    VStack(alignment: .leading, spacing: 14) {572                        header573                        approvals574                        picker(StudyTab.allCases, selection: $tab)575                        if tab == .report { report } else { section(tab) }576                    }577                    .padding(16)578                }579            }580        }581        .background(Theme.background)582        .researchDataSource(source)583        .quickLookPreview($preview)584        .errorAlert($alert)585    }586587    @ViewBuilder private var approvals: some View {588        ForEach(store.pendingApprovals) { a in589            ResearchApprovalCard(a, onApprove: { answer(a, .approve) }, onRefuse: { answer(a, .deny) }).accessibilityIdentifier("study-approval")590        }591    }592    private func answer(_ a: VQResearchApproval, _ d: VQResearchApproval.Decision) {593        Task {594            let ok = await store.answer(a, d)595            if !ok { alert = store.lastError?.kind == .notFound ? "Cette demande n’est plus en attente (déjà traitée ou expirée)." : store.lastError?.userMessage }596            model.notifications.clearApproval(a.id)597            await model.next.hub.refreshApprovals()598        }599    }600601    private func picker(_ tabs: [StudyTab], selection: Binding<StudyTab>) -> some View {602        ScrollViewReader { proxy in603        ScrollView(.horizontal, showsIndicators: false) {604            HStack(spacing: 4) {605                ForEach(tabs) { t in606                    let on = selection.wrappedValue == t607                    Button { selection.wrappedValue = t } label: {608                        HStack(spacing: 4) {609                            Text(t.label).font(.subheadline.weight(on ? .semibold : .regular))610                            if let n = count(t), n > 0 { Text("\(n)").font(.mono(.caption2)).foregroundStyle(Theme.textSecondary) }611                        }612                        .foregroundStyle(on ? Color.primary : Theme.textSecondary)613                        .padding(.horizontal, 10).frame(minHeight: 44)614                        .background(on ? Theme.surface : .clear, in: RoundedRectangle(cornerRadius: 8, style: .continuous))615                        .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(on ? Theme.border : .clear, lineWidth: 1))616                        .contentShape(Rectangle())617                    }618                    .buttonStyle(.plain).hoverEffect(.highlight)619                    .accessibilityAddTraits(on ? [.isSelected] : [])620                    .accessibilityIdentifier("study-tab-\(t.rawValue)")621                    .id(t)622                }623            }624            .padding(3)625        }626        .onChange(of: selection.wrappedValue) { _, t in withAnimation { proxy.scrollTo(t, anchor: .center) } }627        }628        .background(Theme.surface2.opacity(0.7), in: RoundedRectangle(cornerRadius: 11, style: .continuous))629        .accessibilityElement(children: .contain).accessibilityLabel("Sections de l’étude")630    }631632    private func count(_ t: StudyTab) -> Int? {633        let c = store.counts634        switch t {635        case .code: return c.cells636        case .experiments: return c.experiments637        case .figures: return c.figures638        case .files: return store.detail?.files.filter { !$0.isDirectory }.count639        default: return nil640        }641    }642643    private func section(_ t: StudyTab) -> some View {644        StudySection(tab: t, store: store, selectedFile: $selectedFile, onOpenFile: { path in645            selectedFile = path646            if sizeClass == .regular { inspectorTab = .files } else { tab = .files }647        }, onExport: { name, data in648            // Opened in Quick Look, from where it can be shared, saved to Files or dragged to another app.649            let url = FileManager.default.temporaryDirectory.appendingPathComponent(name)650            do { try data.write(to: url, options: .atomic); preview = url } catch { alert = "Fichier impossible à écrire." }651        })652    }653}654655// MARK: - Live study656657struct RunView: View {658    let jobId: String659    @Environment(AppModel.self) private var model660    @State private var controller: RunController?661    @State private var showSteps = false662    @State private var followUp = false663664    var body: some View {665        Group {666            if let c = controller {667                StudyCockpit(store: c.store, workspaceId: c.store.workspaceId) { header(c) } report: { report(c) }668            } else { StateView(kind: .loading, title: "Connexion à l’étude…") }669        }670        .background(Theme.background)671        .navigationTitle(controller?.mode == AnalysisMode.research.rawValue || controller?.store.workspaceId != nil ? "Étude" : "Analyse").navigationBarTitleDisplayMode(.inline)672        .toolbar {673            if let c = controller, !c.run.isFinished {674                ToolbarItem(placement: .primaryAction) {675                    Button("Arrêter", role: .destructive) { Task { await c.cancel() } }.accessibilityIdentifier("run-stop")676                }677            }678            ToolbarItem(placement: .secondaryAction) { OpenWindowButton(route: .run(jobId)) }679        }680        .task {681            let g = model.research.generations.value?.first { $0.id == jobId }682            controller = model.research.watch(jobId: jobId, query: g?.query ?? "")683            model.notifications.visibleJobId = jobId684            model.next.hub.startPolling { [research = model.research] in !research.running.isEmpty }685        }686        .onDisappear { if model.notifications.visibleJobId == jobId { model.notifications.visibleJobId = nil } }687        .sheet(isPresented: $followUp) {688            if let c = controller { ComposerSheet(sessionId: c.run.sessionId, history: [c.run.exchange]).paperBackground().environment(model).vqTheme(model.preferences.theme).tint(Theme.orange) }689        }690        .accessibilityIdentifier("run")691    }692693    private func header(_ c: RunController) -> some View {694        VStack(alignment: .leading, spacing: 10) {695            if !c.run.query.isEmpty { Text(c.run.query).font(.serif(.title3, weight: .medium)).lineLimit(6).fixedSize(horizontal: false, vertical: true).textSelection(.enabled) }696            HStack(spacing: 8) {697                if c.run.isFinished {698                    JobStatusBadge(text: c.run.error == nil ? "Terminée" : "Interrompue", color: c.run.error == nil ? Theme.up : Theme.down)699                } else {700                    JobStatusBadge(text: c.isConnected ? "Suivi en cours" : "Sur le serveur", color: Theme.orange, running: true)701                }702                if let m = c.mode.flatMap(AnalysisMode.init(rawValue:)) ?? model.research.generations.value?.first(where: { $0.id == jobId }).flatMap({ AnalysisMode(rawValue: $0.mode) }) {703                    Tag(text: m.label, systemImage: m.systemImage)704                }705                if let r = c.routed { ModelBadge(id: r.model) } else if let m = c.requestedModel { ModelBadge(id: m) }706                Spacer(minLength: 0)707                if c.run.toolCount > 0 { Text("\(c.run.toolCount) outils").font(.mono(.caption)).foregroundStyle(Theme.textSecondary) }708            }709            .accessibilityElement(children: .combine)710            .accessibilityIdentifier("run-status")711            if !c.run.isFinished { Text(c.connectionNote ?? (c.run.status.isEmpty ? "L’étude s’exécute sur le serveur." : c.run.status)).font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(2) }712            if let r = c.routed { Text("Modèle choisi par le serveur : \(r.reason)").font(.caption).foregroundStyle(Theme.textSecondary) }713            if let b = c.store.budgetApplied, b.maxCostUsd != nil || b.maxMinutes != nil { Text("Budget appliqué par le serveur : " + [b.maxCostUsd.map { "coût \(VQFormat.currency($0))" }, b.maxMinutes.map { "durée \(VQFormat.number($0, decimals: 0)) min" }].compactMap { $0 }.joined(separator: ", ")).font(.caption).foregroundStyle(Theme.textSecondary) }714            if let u = c.usage { UsageLine(usage: u) }715        }716    }717718    @ViewBuilder private func report(_ c: RunController) -> some View {719        VStack(alignment: .leading, spacing: 14) {720            if !c.run.steps.isEmpty { StepsView(steps: c.run.steps, expanded: $showSteps) }721            ExchangeView(exchange: Exchange(question: "", answer: c.run.answer, toolResults: c.run.toolResults, sources: c.run.sources, pythonCode: c.run.pythonCode.last, figures: c.run.figures), streaming: !c.run.isFinished)722            if !c.provenance.isEmpty { ProvenanceList(sources: c.provenance) }723            if let e = c.run.error {724                Label(e, systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Theme.down)725                    .padding(12).background(Theme.down.opacity(0.1), in: RoundedRectangle(cornerRadius: 10))726            }727            if c.run.isFinished && c.run.answer.isEmpty && c.run.error == nil {728                Label("Ce déroulement n’est plus rejouable (le serveur le garde 20 minutes). Le rapport est dans la conversation, l’espace de travail dans les études.", systemImage: "clock.arrow.circlepath")729                    .font(.footnote).foregroundStyle(Theme.textSecondary)730            }731            if c.run.isFinished { finishedFooter(c) }732            if !c.run.unknownEvents.isEmpty {733                Text("Événements non reconnus par cette version : \(c.run.unknownEvents.joined(separator: ", "))").font(.caption2).foregroundStyle(Theme.textSecondary)734            }735        }736    }737738    @ViewBuilder private func finishedFooter(_ c: RunController) -> some View {739        if !c.run.followups.isEmpty {740            VStack(alignment: .leading, spacing: 8) {741                Text("Pour aller plus loin").font(.subheadline.weight(.semibold))742                ForEach(c.run.followups, id: \.self) { q in743                    Button { model.router.composerDraft = q; followUp = true } label: {744                        Text(q).font(.footnote).multilineTextAlignment(.leading).frame(maxWidth: .infinity, alignment: .leading)745                    }746                    .buttonStyle(QuietButtonStyle())747                }748            }749        }750        FlowLayout(spacing: 8) {751            if let sid = c.run.sessionId {752                RouteLink(.conversation(sid)) { Label("Ouvrir la conversation", systemImage: "text.bubble") }.buttonStyle(QuietButtonStyle())753            }754            if let ws = c.store.workspaceId {755                RouteLink(.researchSession(ws)) { Label("Espace de travail", systemImage: "folder") }.buttonStyle(QuietButtonStyle())756            }757            Button { followUp = true } label: { Label("Poursuivre", systemImage: "arrowshape.turn.up.right") }.buttonStyle(QuietButtonStyle())758                .requiresNetwork(model.network.isOnline)759        }760    }761}762763struct UsageLine: View {764    let usage: VQUsage765    var body: some View {766        Text("Consommation : \(VQFormat.tokens(usage.inputTokens)) jetons en entrée, \(VQFormat.tokens(usage.outputTokens)) en sortie" + (usage.costUsd.map { " · coût \(VQFormat.cost($0))" } ?? " · coût inconnu pour au moins un appel"))767            .font(.mono(.caption2)).foregroundStyle(Theme.textSecondary)768            .accessibilityIdentifier("usage-line")769    }770}771772/// Where the data of an answer came from: one line per tool and symbol set, as the server recorded the calls.773struct ProvenanceList: View {774    let sources: [VQProvenanceSource]775    var body: some View {776        DisclosureGroup("Provenance des données (\(sources.count))") {777            VStack(alignment: .leading, spacing: 6) {778                ForEach(Array(sources.enumerated()), id: \.offset) { _, s in779                    HStack(alignment: .firstTextBaseline) {780                        Image(systemName: s.ok ? "checkmark.circle" : "xmark.circle").foregroundStyle(s.ok ? Theme.up : Theme.down).imageScale(.small)781                        VStack(alignment: .leading, spacing: 1) {782                            Text("\(VQFreshness.providerName(s.provider.rawValue) ?? s.provider.rawValue) · \(s.tool)").font(.caption.weight(.medium))783                            Text([s.symbols.isEmpty ? nil : s.symbols.joined(separator: ", "), "\(s.calls) appel\(s.calls > 1 ? "s" : "")", s.retrievedAt.map { Fmt.dateTime($0) }].compactMap { $0 }.joined(separator: " · "))784                                .font(.caption2).foregroundStyle(Theme.textSecondary)785                        }786                    }787                    .accessibilityElement(children: .combine)788                }789            }790            .padding(.top, 6)791        }792        .font(.subheadline)793        .paperCard(padding: 12)794    }795}796797// MARK: - A study kept on the server798799/// A research workspace: what the server keeps once the generation is over — report, ledger, runs, figures, files.800/// A study started on the Mac or the web opens here like one started on this device.801struct ResearchSessionView: View {802    let workspaceId: String803    @Environment(AppModel.self) private var model804    @State private var store: VQResearchSessionStore?805    @State private var exchanges: [Exchange] = []806    @State private var cachedAt: Date?807    @State private var error: String?808    @State private var followUp = false809810    private var sessionIds: [String] { store?.detail?.session.sessionIds ?? [] }811    private var running: Generation? { model.research.running.first { sessionIds.contains($0.sessionId) } }812813    var body: some View {814        Group {815            if let store, store.detail != nil {816                StudyCockpit(store: store, workspaceId: workspaceId) { header(store) } report: { report(store) }817            } else if let error {818                StateView(kind: .failed, title: "Étude indisponible", message: error) { Task { await load() } }819            } else { StateView(kind: .loading, title: "Chargement de l’étude…") }820        }821        .background(Theme.background)822        .navigationTitle("Étude").navigationBarTitleDisplayMode(.inline)823        .toolbar {824            ToolbarItem(placement: .primaryAction) {825                Button { followUp = true } label: { Label("Poursuivre l’étude", systemImage: "square.and.pencil") }826                    .disabled(sessionIds.isEmpty).requiresNetwork(model.network.isOnline)827                    .accessibilityIdentifier("study-continue")828            }829            ToolbarItem(placement: .secondaryAction) { OpenWindowButton(route: .researchSession(workspaceId)) }830        }831        .task { await load() }832        .refreshable { await load() }833        .sheet(isPresented: $followUp) {834            ComposerSheet(sessionId: sessionIds.last, history: exchanges).paperBackground().environment(model).vqTheme(model.preferences.theme).tint(Theme.orange)835        }836        .accessibilityIdentifier("study")837    }838839    private func load() async {840        let s = store ?? VQResearchSessionStore(client: model.next.hub.client)841        do {842            let d = try await model.next.hub.detail(workspaceId)843            cachedAt = d.isFromCache ? d.fetchedAt : nil844            var conversation: VQJSON?845            if let sid = d.value.session.sessionIds.last {846                conversation = try? await model.next.hub.conversation(sid).value.json847                if let c = try? await model.research.conversation(sid) { exchanges = c.value.exchanges }848            }849            s.install(detail: d.value, conversation: conversation, sandbox: model.next.hub.sandbox)850            store = s; error = nil851            if model.next.hub.sandbox == nil { await model.next.hub.refreshSandbox() }852        } catch { if store == nil { self.error = nextMessage(error) } }853    }854855    private func header(_ s: VQResearchSessionStore) -> some View {856        VStack(alignment: .leading, spacing: 8) {857            Text(s.detail?.session.title?.isEmpty == false ? s.detail!.session.title! : (s.objective ?? "Étude")).font(.serif(.title3, weight: .medium)).lineLimit(5).fixedSize(horizontal: false, vertical: true)858            HStack(spacing: 8) {859                Tag(text: s.detail?.session.kind == .project ? "Projet" : "Étude", systemImage: "flask")860                if let u = s.detail?.session.updatedAt { Text("Mise à jour \(Fmt.relative(u))").font(.caption).foregroundStyle(Theme.textSecondary) }861                CachedNotice(at: cachedAt)862                Spacer(minLength: 0)863            }864            if let g = running {865                RouteLink(.run(g.id)) { Label("Une étude est en cours dans cet espace — la suivre", systemImage: "dot.radiowaves.left.and.right").font(.subheadline.weight(.medium)) }866                    .accessibilityIdentifier("study-follow-live")867            }868            let c = s.counts869            Text("\(c.executions) exécutions\(c.failed > 0 ? " dont \(c.failed) en échec" : "") · \(c.experiments) expériences · \(c.figures) figures · \(c.runs) exécutions longues")870                .font(.mono(.caption2)).foregroundStyle(Theme.textSecondary)871            if let sb = s.sandbox, !sb.enforced {872                Label("Le serveur ne peut pas appliquer son bac à sable sur cet hôte.", systemImage: "exclamationmark.shield").font(.caption).foregroundStyle(Theme.critical)873            }874        }875    }876877    @ViewBuilder private func report(_ s: VQResearchSessionStore) -> some View {878        if exchanges.isEmpty {879            if s.finalReport.isEmpty {880                VQEmptyState(systemImage: "doc.text", title: "Aucun rapport enregistré", message: "L’espace de travail existe, mais aucune réponse n’y est encore rattachée.")881            } else { MarkdownView(text: s.finalReport) }882        } else {883            LazyVStack(alignment: .leading, spacing: 22) {884                ForEach(Array(exchanges.enumerated()), id: \.offset) { i, e in885                    ExchangeView(exchange: e)886                    if i < exchanges.count - 1 { Divider() }887                }888            }889        }890    }891}892
Files main
Menu

Theme