Repository Public
1// SP Wallet iOS2// File: Features/Research/ResearchJobView.swift3// Description: One research job: its state as the server reports it, the owner's request and budgets, the live log (polled:4// `log(after:)`), cancellation (the state shown afterwards is the server's answer), and the labelled result.5// A fixed footer reminds that no projection is a guarantee.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SwiftUI10import SPWalletCore1112/** Accumulates log lines across polls: ordered by id, no duplicate, bounded in memory. */13struct ResearchLogBuffer: Equatable {14 private(set) var lines: [ResearchLogLine] = []15 private(set) var lastId: Int64 = 016 /** Lines dropped from the top to stay within `limit` (said on screen). */17 private(set) var dropped = 018 var limit = 6001920 mutating func append(_ new: [ResearchLogLine]) {21 for l in new.sorted(by: { $0.id < $1.id }) where l.id > lastId { lines.append(l); lastId = l.id }22 if lines.count > limit { dropped += lines.count - limit; lines.removeFirst(lines.count - limit) }23 }24}2526struct ResearchJobView: View {27 @Environment(AppModel.self) private var model28 let jobId: String29 var onChange: () -> Void = {}30 @State private var detail: ResearchJobDetail?31 @State private var cachedAt: Date?32 @State private var log = ResearchLogBuffer()33 @State private var logError: Error?34 @State private var error: Error?35 @State private var confirmCancel = false36 @State private var cancelling = false37 @State private var cancelError: Error?38 static let pollInterval: Duration = .seconds(3)3940 private var api: ResearchAPI { ResearchAPI(model.env.client) }41 private var cacheKey: String { "research-job-\(jobId)" }4243 var body: some View {44 ScrollView {45 VStack(alignment: .leading, spacing: Theme.Space.section) {46 FreshnessBanner()47 if let at = cachedAt { Notice(tone: .warn, title: String(localized: "Tâche telle que synchronisée le \(at.formatted(date: .abbreviated, time: .shortened))"), message: String(localized: "Son état réel peut avoir changé."), icon: "clock") }48 if let d = detail {49 header(d)50 request(d.job)51 if d.job.state.isCancellable, !d.job.cancelRequested {52 Button(role: .destructive) { confirmCancel = true } label: { if cancelling { ProgressView() } else { Label(String(localized: "Annuler la tâche"), systemImage: "stop.circle") } }53 .buttonStyle(.spDestructive).disabled(!model.canOperate || cancelling).accessibilityIdentifier("research.cancel")54 }55 if let cancelError { ErrorNotice(error: cancelError) }56 logCard(d.job)57 ResearchResultsView(detail: d)58 if d.results.isEmpty, d.job.state.isFinal { Text(String(localized: "Le serveur n’a enregistré aucun résultat pour cette tâche.")).font(.spFootnote).foregroundStyle(Theme.mute) }59 } else if let error { ErrorNotice(error: error) { Task { await loadDetail() } } }60 else { ProgressView().frame(maxWidth: .infinity).padding(.top, 60) }61 }62 .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 16)63 .frame(maxWidth: 820).frame(maxWidth: .infinity)64 }65 .safeAreaInset(edge: .bottom, spacing: 0) { ResearchFooter().background(.bar) }66 .spPage()67 .navigationTitle(String(localized: "Tâche de recherche")).navigationBarTitleDisplayMode(.inline)68 .refreshable { await loadDetail() }69 .task(id: jobId) { await follow() }70 .confirmationDialog(String(localized: "Annuler cette tâche ?"), isPresented: $confirmCancel, titleVisibility: .visible) {71 Button(String(localized: "Annuler la tâche"), role: .destructive) { Task { await cancel() } }72 } message: { Text(String(localized: "Les jetons déjà consommés restent dépensés.")) }73 }7475 // MARK: data7677 private func loadDetail() async {78 guard model.canOperate else {79 if let c = await model.env.cache.load(ResearchJobDetail.self, key: cacheKey) { detail = c.value; cachedAt = c.savedAt }80 else if detail == nil { error = APIError(status: 0, code: "offline", message: "offline") }81 return82 }83 do { let d = try await api.job(jobId); detail = d; cachedAt = nil; error = nil; await model.env.cache.save(d, key: cacheKey) }84 catch let e { if detail == nil { error = e } }85 }8687 /** Detail, then the log every few seconds until the server says the job is final. Stops with the screen. */88 private func follow() async {89 await loadDetail()90 guard model.canOperate else { return }91 while !Task.isCancelled {92 guard let state = detail?.job.state else { return }93 do {94 let l = try await api.log(jobId, after: log.lastId)95 log.append(l.lines); logError = nil96 if l.state != state { await loadDetail(); onChange() }97 if l.state.isFinal, l.lines.isEmpty { return }98 } catch let e { logError = e; if (e as? APIError)?.isUnauthenticated == true { return } }99 try? await Task.sleep(for: Self.pollInterval)100 }101 }102103 private func cancel() async {104 cancelling = true; defer { cancelling = false }105 do { _ = try await api.cancel(jobId); cancelError = nil; await loadDetail(); onChange() }106 catch let e { cancelError = e }107 }108109 // MARK: blocks110111 private func header(_ d: ResearchJobDetail) -> some View {112 let (label, tone, icon) = ResearchLabels.state(d.job.state)113 return VStack(alignment: .leading, spacing: 10) {114 HStack(spacing: 6) {115 Pill(text: label, tone: tone, icon: icon).accessibilityElement(children: .combine).accessibilityIdentifier("research.state")116 if d.job.cancelRequested, !d.job.state.isFinal { Pill(text: String(localized: "annulation demandée, pas encore effective"), tone: .warn) }117 }118 Text(d.job.mission).font(.system(size: 19, weight: .semibold)).foregroundStyle(Theme.ink).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)119 if let r = d.job.reason, !r.isEmpty { Notice(tone: d.job.state == .failed || d.job.state == .overBudget ? .danger : .info, title: String(localized: "Motif donné par le serveur"), message: r) }120 if d.job.state == .submitted {121 Notice(tone: .info, title: String(localized: "« Soumise » ne veut dire ni approuvée ni rentable"),122 message: String(localized: "Une stratégie attend ton examen. L’approbation se fait dans Agents de trading, avec ta clé d’accès.") + (d.version.map { " " + String(localized: "Version \($0.id) : \($0.status).") } ?? ""))123 }124 if d.dataReady == false, !d.job.state.isFinal { Text(String(localized: "Le jeu de données est en cours de gel.")).font(.spFootnote).foregroundStyle(Theme.mute) }125 if let e = d.dataError { Notice(tone: .danger, title: String(localized: "Données indisponibles"), message: e) }126 }127 }128129 private func request(_ j: ResearchJob) -> some View {130 VStack(alignment: .leading, spacing: 0) {131 SectionHeader(title: String(localized: "Demande")).padding(.bottom, 4)132 FieldRow(label: String(localized: "Marché, symboles, intervalle"), value: "\(j.kind) · \(j.universe.joined(separator: ", ")) · \(j.interval)"); Divider()133 FieldRow(label: String(localized: "Capital VIRTUEL de la simulation"), value: Money.fiat(j.capitalUsd, .usd)); Divider()134 FieldRow(label: String(localized: "Budgets"), value: String(localized: "\(j.budgets.wallSeconds) s · \(j.budgets.maxTrials) essais · \(j.budgets.maxModelTokens) jetons · \(j.budgets.maxModelUsd.formatted()) USD · \(j.budgets.maxDiskMb) Mo")); Divider()135 FieldRow(label: String(localized: "Outils de l’agent"), value: j.tools.isEmpty ? "—" : j.tools.joined(separator: ", ")); Divider()136 FieldRow(label: String(localized: "Stratégie"), value: j.strategy, mono: true); Divider()137 FieldRow(label: String(localized: "Créée"), value: j.createdAt.formatted(date: .abbreviated, time: .standard))138 if let f = j.finishedAt { Divider(); FieldRow(label: String(localized: "Terminée"), value: f.formatted(date: .abbreviated, time: .standard)) }139 if let h = j.heartbeatAt, !j.state.isFinal { Divider(); FieldRow(label: String(localized: "Dernier signe de l’exécuteur"), value: AlertPresentation.age(h)) }140 Divider(); FieldRow(label: String(localized: "Identifiant"), value: j.id, mono: true, copyable: true)141 }.spCard(padding: 16)142 }143144 private func logCard(_ j: ResearchJob) -> some View {145 VStack(alignment: .leading, spacing: 8) {146 HStack {147 Text(String(localized: "Journal")).font(.spHeadline)148 Spacer()149 if !j.state.isFinal, model.canOperate { Pill(text: String(localized: "relevé toutes les 3 s"), tone: .info, icon: "arrow.triangle.2.circlepath") }150 }151 Text(String(localized: "Les lignes « agent » sont le texte brut du processus de l’agent IA : non vérifié. Seules les lignes « serveur » sont les mots du serveur."))152 .font(.system(size: 12)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)153 if log.dropped > 0 { Text(String(localized: "\(log.dropped) lignes plus anciennes non affichées.")).font(.system(size: 12)).foregroundStyle(Theme.mute) }154 if log.lines.isEmpty {155 Text(model.canOperate ? String(localized: "Aucune ligne pour l’instant.") : String(localized: "Le journal n’est pas conservé hors ligne.")).font(.spFootnote).foregroundStyle(Theme.mute)156 } else {157 ScrollViewReader { proxy in158 ScrollView {159 LazyVStack(alignment: .leading, spacing: 3) {160 ForEach(log.lines) { l in161 HStack(alignment: .firstTextBaseline, spacing: 6) {162 Text(Self.streamLabel(l.stream)).font(.system(size: 10, weight: .bold, design: .monospaced)).foregroundStyle(l.isServerLine ? Theme.blue : l.stream == "err" ? Theme.danger : Theme.mute).frame(width: 52, alignment: .leading)163 Text(l.text).font(.system(size: 11.5, design: .monospaced)).foregroundStyle(Theme.ink).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)164 }.id(l.id)165 }166 }.padding(10)167 }168 .frame(maxHeight: 280)169 .background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small, style: .continuous))170 .onChange(of: log.lastId) { _, id in proxy.scrollTo(id, anchor: .bottom) }171 .onAppear { proxy.scrollTo(log.lastId, anchor: .bottom) }172 }173 .accessibilityIdentifier("research.log")174 }175 if let logError { Text(String(localized: "Journal non relevé : ") + ErrorNotice.detail(logError)).font(.system(size: 12)).foregroundStyle(Theme.warn) }176 }.spCard(padding: 16)177 }178179 static func streamLabel(_ s: String) -> String {180 switch s { case "api": String(localized: "serveur"); case "sys": String(localized: "exécut."); case "out": String(localized: "agent"); case "err": String(localized: "agent !"); default: s }181 }182}183