Repository Public
1// SP Wallet iOS2// File: Features/Research/ResearchHomeView.swift3// Description: Research jobs: the runner's status as the server reports it, the list of jobs, creation of a job (the owner types4// the mission and every budget — nothing is pre-filled), and the job page. Offline: the last synchronized list,5// dated, with creation and cancellation disabled. iPad: list and job side by side.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SwiftUI10import SPWalletCore1112struct ResearchHomeView: View {13 @Environment(AppModel.self) private var model14 @Environment(\.horizontalSizeClass) private var sizeClass15 @State private var status: ResearchStatus?16 @State private var jobs: [ResearchJob]?17 @State private var cachedAt: Date?18 @State private var error: Error?19 @State private var creating = false20 @State private var selection: String?21 static let cacheKey = "research-jobs"22 static let statusKey = "research-status"2324 private var api: ResearchAPI { ResearchAPI(model.env.client) }2526 var body: some View {27 Group {28 if sizeClass == .regular {29 HStack(spacing: 0) {30 list(split: true).frame(width: 400)31 Divider()32 Group {33 if let id = selection { ResearchJobView(jobId: id, onChange: { Task { await load() } }).id(id) }34 else { VStack { EmptyState(icon: AppSection.research.icon, title: String(localized: "Choisis une tâche"), message: String(localized: "Son journal et son résultat s’affichent ici.")); Spacer(); ResearchFooter() } }35 }.frame(maxWidth: .infinity)36 }37 } else { list(split: false) }38 }39 .spPage()40 .navigationTitle(AppSection.research.title)41 .toolbar {42 ToolbarItem(placement: .topBarTrailing) {43 Button { creating = true } label: { Image(systemName: "plus") }44 .disabled(!model.canOperate || status == nil).accessibilityLabel(String(localized: "Nouvelle tâche de recherche")).accessibilityIdentifier("research.new")45 }46 }47 .sheet(isPresented: $creating) {48 ResearchCreateView(status: status) { job in creating = false; Task { await load(); if sizeClass == .regular { selection = job.id } } }.wallet(model)49 }50 .task { await load() }51 }5253 private func load() async {54 let cache = model.env.cache55 guard model.canOperate else {56 if let c = await cache.load([ResearchJob].self, key: Self.cacheKey) { jobs = c.value; cachedAt = c.savedAt }57 if let c = await cache.load(ResearchStatus.self, key: Self.statusKey) { status = c.value }58 if jobs == nil { error = APIError(status: 0, code: "offline", message: "offline") }59 return60 }61 do {62 async let s = api.status(), j = api.jobs(limit: 100)63 let (st, js) = try await (s, j)64 status = st; jobs = js; cachedAt = nil; error = nil65 await cache.save(js, key: Self.cacheKey); await cache.save(st, key: Self.statusKey)66 } catch let e {67 error = e68 if jobs == nil, let c = await cache.load([ResearchJob].self, key: Self.cacheKey) { jobs = c.value; cachedAt = c.savedAt }69 }70 }7172 @ViewBuilder private func list(split: Bool) -> some View {73 List {74 Section {75 FreshnessBanner().listRowInsets(.init()).listRowBackground(Color.clear)76 if let at = cachedAt {77 Notice(tone: .warn, title: String(localized: "Tâches du \(at.formatted(date: .abbreviated, time: .shortened))"), message: String(localized: "Dernière liste synchronisée. L’état réel des tâches peut avoir changé."), icon: "clock")78 .listRowInsets(.init()).listRowBackground(Color.clear).accessibilityIdentifier("research.cached")79 }80 if let s = status { StatusCard(status: s, cached: cachedAt != nil).listRowInsets(.init()).listRowBackground(Color.clear) }81 }82 if let e = error { Section { ErrorNotice(error: e) { Task { await load() } } } }83 if let jobs {84 if jobs.isEmpty {85 EmptyState(icon: AppSection.research.icon, title: String(localized: "Aucune tâche de recherche"),86 message: String(localized: "Une tâche demande à un agent IA de développer une stratégie ; le serveur la re-mesure ensuite sur des données que l’agent n’a jamais vues.")).listRowBackground(Color.clear)87 } else {88 Section(String(localized: "Tâches")) {89 ForEach(jobs) { j in90 Group {91 if split { Button { selection = j.id } label: { ResearchJobRow(job: j) }.buttonStyle(.plain).listRowBackground(selection == j.id ? Theme.elev : Theme.surface) }92 else { NavigationLink { ResearchJobView(jobId: j.id, onChange: { Task { await load() } }).wallet(model) } label: { ResearchJobRow(job: j) } }93 }.accessibilityIdentifier("research.row")94 }95 }96 }97 } else if error == nil { ProgressView().frame(maxWidth: .infinity).listRowBackground(Color.clear) }98 }99 .listStyle(.insetGrouped).scrollContentBackground(.hidden)100 .safeAreaInset(edge: .bottom, spacing: 0) { if !split { ResearchFooter().background(.bar) } }101 .refreshable { await load() }102 }103}104105/** The fixed sentence of every research screen. */106struct ResearchFooter: View {107 var body: some View {108 Label(ResearchLabels.footer, systemImage: "exclamationmark.shield").font(.system(size: 12.5, weight: .semibold)).foregroundStyle(Theme.mute)109 .frame(maxWidth: .infinity).padding(.vertical, 10).padding(.horizontal, 16).accessibilityIdentifier("research.footer")110 }111}112113private struct StatusCard: View {114 let status: ResearchStatus115 let cached: Bool116 var body: some View {117 VStack(alignment: .leading, spacing: 8) {118 HStack {119 Text(String(localized: "Exécuteur de recherche")).font(.spHeadline)120 Spacer()121 if status.runnerConfigured { Pill(text: String(localized: "configuré"), tone: .ok, icon: "checkmark") } else { Pill(text: String(localized: "non configuré"), tone: .warn, icon: "exclamationmark.triangle.fill") }122 }123 if !status.runnerConfigured { Text(String(localized: "Aucun exécuteur n’est configuré sur le serveur : une tâche créée restera en file d’attente.")).font(.spFootnote).foregroundStyle(Theme.warn).fixedSize(horizontal: false, vertical: true) }124 Text((status.lastRunnerContact.map { String(localized: "Dernier contact de l’exécuteur : \($0.formatted(date: .abbreviated, time: .shortened))") } ?? String(localized: "L’exécuteur ne s’est jamais présenté au serveur."))125 + " · " + String(localized: "\(status.openJobs) tâche(s) ouverte(s) sur \(status.maxOpenJobs) au plus") + (cached ? " · " + String(localized: "instantané") : ""))126 .font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)127 }128 .spCard(padding: 16).accessibilityElement(children: .combine).accessibilityIdentifier("research.status")129 }130}131132struct ResearchJobRow: View {133 let job: ResearchJob134 var body: some View {135 let (label, tone, icon) = ResearchLabels.state(job.state)136 VStack(alignment: .leading, spacing: 5) {137 Text(job.mission).font(.system(size: 15, weight: .semibold)).foregroundStyle(Theme.ink).lineLimit(2)138 HStack(spacing: 6) {139 Pill(text: label, tone: tone, icon: icon)140 if job.cancelRequested, !job.state.isFinal { Pill(text: String(localized: "annulation demandée"), tone: .warn) }141 if job.claimsDiffer == true { Pill(text: String(localized: "chiffres de l’agent ≠ serveur"), tone: .danger, icon: "exclamationmark.triangle.fill") }142 }143 Text("\(job.kind) · \(job.universe.joined(separator: ", ")) · \(job.interval) · " + job.createdAt.formatted(date: .abbreviated, time: .shortened)).font(.system(size: 12)).foregroundStyle(Theme.mute).lineLimit(1)144 }145 .padding(.vertical, 4).contentShape(Rectangle()).accessibilityElement(children: .combine)146 }147}148149// MARK: creation150151/** The creation form's values and their validation against the server's schema (packages/core/src/research-job.ts). Nothing is pre-filled. */152struct ResearchDraft: Equatable {153 var mission = ""154 var kind: String?155 var symbols = ""156 var interval: String?157 var capital = ""158 var minutes = ""159 var maxTrials = ""160 var tokensMillions = ""161 var maxUsd = ""162 var diskMb = ""163 /** nil = not chosen yet; "" = explicitly « no agent » (library draft). */164 var agentId: String?165166 /** Intervals the server accepts: spot jobs run at 1h or 1d (research/routes.ts); for perpetuals the server decides and says so. */167 static func intervals(kind: String?) -> [String] { kind == "spot" ? ["1h", "1d"] : ["1h", "4h", "1d"] }168169 var universe: [String] { symbols.uppercased().split(whereSeparator: { ", ;\n".contains($0) }).map(String.init) }170171 static func number(_ s: String) -> Double? { Double(s.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: ".")) }172 static func integer(_ s: String, _ r: ClosedRange<Int>) -> Int? { Int(s.trimmingCharacters(in: .whitespaces)).flatMap { r.contains($0) ? $0 : nil } }173174 /** The first thing that prevents sending, in the owner's words; nil when the request can be built. */175 var problem: String? {176 let m = mission.trimmingCharacters(in: .whitespacesAndNewlines)177 if m.count < 10 || m.count > 2000 { return String(localized: "La mission doit compter de 10 à 2 000 caractères.") }178 if agentId == nil { return String(localized: "Choisis un agent, ou « aucun agent ».") }179 if kind == nil { return String(localized: "Choisis le type de marché.") }180 let u = universe181 if u.isEmpty || u.count > 12 || Set(u).count != u.count || !u.allSatisfy({ $0.range(of: "^[A-Z0-9]{2,10}$", options: .regularExpression) != nil }) { return String(localized: "De 1 à 12 symboles distincts, 2 à 10 caractères A–Z ou 0–9 chacun.") }182 guard let interval else { return String(localized: "Choisis l’intervalle des barres.") }183 if !Self.intervals(kind: kind).contains(interval) { return String(localized: "Le serveur n’exécute les tâches au comptant qu’en 1h ou 1d.") }184 guard let c = Self.number(capital), c >= 10, c <= 10_000_000 else { return String(localized: "Capital virtuel : de 10 à 10 000 000 USD.") }185 guard let min = Self.number(minutes), min * 60 >= 30, min * 60 <= 86_400, (min * 60).rounded() == min * 60 else { return String(localized: "Durée maximale : de 0,5 à 1 440 minutes.") }186 if Self.integer(maxTrials, 1...5000) == nil { return String(localized: "Essais : de 1 à 5 000.") }187 guard let t = Self.number(tokensMillions), t * 1_000_000 >= 10_000, t * 1_000_000 <= 500_000_000 else { return String(localized: "Jetons du modèle : de 0,01 à 500 millions.") }188 guard let usd = Self.number(maxUsd), usd >= 0.05, usd <= 1000 else { return String(localized: "Coût maximal du modèle : de 0,05 à 1 000 USD.") }189 if Self.integer(diskMb, 16...10_240) == nil { return String(localized: "Disque : de 16 à 10 240 Mo.") }190 return nil191 }192193 /** nil while `problem` is not nil. Every value is the one the owner typed. */194 var request: ResearchJobRequest? {195 guard problem == nil, let kind, let interval, let c = Self.number(capital), let min = Self.number(minutes), let trials = Self.integer(maxTrials, 1...5000),196 let t = Self.number(tokensMillions), let usd = Self.number(maxUsd), let disk = Self.integer(diskMb, 16...10_240) else { return nil }197 return ResearchJobRequest(mission: mission.trimmingCharacters(in: .whitespacesAndNewlines), universe: universe, agentId: agentId.flatMap { $0.isEmpty ? nil : $0 }, kind: kind, interval: interval, capitalUsd: c,198 budgets: .init(wallSeconds: Int(min * 60), maxTrials: trials, maxDiskMb: disk, maxModelTokens: Int((t * 1_000_000).rounded()), maxModelUsd: usd))199 }200}201202struct ResearchCreateView: View {203 @Environment(AppModel.self) private var model204 @Environment(\.dismiss) private var dismiss205 let status: ResearchStatus?206 let created: (ResearchJob) -> Void207 @State private var draft = ResearchDraft()208 @State private var agents: [Agent]?209 @State private var busy = false210 @State private var error: Error?211 @State private var lost = false212213 var body: some View {214 NavigationStack {215 Form {216 if let s = status, !s.runnerConfigured { Section { Notice(tone: .warn, title: String(localized: "Aucun exécuteur configuré"), message: String(localized: "La tâche sera créée mais restera en file d’attente.")) } }217 if let s = status, s.openJobs >= s.maxOpenJobs { Section { Notice(tone: .warn, title: String(localized: "Nombre maximal de tâches ouvertes atteint"), message: String(localized: "\(s.openJobs) sur \(s.maxOpenJobs) : le serveur refusera probablement une nouvelle tâche.")) } }218 Section {219 TextField(String(localized: "Ce que la stratégie doit chercher à faire, dans tes mots"), text: $draft.mission, axis: .vertical).lineLimit(4...10).accessibilityIdentifier("research.mission")220 } header: { Text(String(localized: "Mission")) } footer: { Text(String(localized: "\(draft.mission.trimmingCharacters(in: .whitespacesAndNewlines).count) / 2 000 caractères (10 au moins). Donnée telle quelle à l’agent IA.")) }221 Section {222 Picker(String(localized: "Agent"), selection: $draft.agentId) {223 Text(String(localized: "à choisir")).tag(String?.none)224 Text(String(localized: "Aucun agent (brouillon de bibliothèque)")).tag(String?(""))225 ForEach(agents ?? []) { a in Text(a.name).tag(String?(a.id)) }226 }.accessibilityIdentifier("research.agent")227 Picker(String(localized: "Marché"), selection: $draft.kind) {228 Text(String(localized: "à choisir")).tag(String?.none); Text(String(localized: "Comptant (spot)")).tag(String?("spot")); Text(String(localized: "Perpétuels (perp)")).tag(String?("perp"))229 }.accessibilityIdentifier("research.kind")230 TextField(String(localized: "Symboles, séparés par des virgules"), text: $draft.symbols).textInputAutocapitalization(.characters).autocorrectionDisabled().accessibilityIdentifier("research.symbols")231 Picker(String(localized: "Intervalle"), selection: $draft.interval) {232 Text(String(localized: "à choisir")).tag(String?.none); ForEach(ResearchDraft.intervals(kind: draft.kind), id: \.self) { Text($0).tag(String?($0)) }233 }.accessibilityIdentifier("research.interval")234 .onChange(of: draft.kind) { _, k in if let i = draft.interval, !ResearchDraft.intervals(kind: k).contains(i) { draft.interval = nil } }235 field(String(localized: "Capital virtuel (USD)"), $draft.capital, "research.capital")236 } header: { Text(String(localized: "Cadre de la simulation")) } footer: {237 Text(String(localized: "Avec un agent, son marché, ses symboles et son intervalle remplacent ceux saisis ici (règle du serveur). Le capital est VIRTUEL : aucun fonds n’est engagé par une tâche de recherche."))238 }239 Section {240 field(String(localized: "Durée maximale (minutes)"), $draft.minutes, "research.minutes")241 field(String(localized: "Essais au plus"), $draft.maxTrials, "research.trials")242 field(String(localized: "Jetons du modèle (millions)"), $draft.tokensMillions, "research.tokens")243 field(String(localized: "Coût maximal du modèle (USD)"), $draft.maxUsd, "research.usd")244 field(String(localized: "Disque (Mo)"), $draft.diskMb, "research.disk")245 } header: { Text(String(localized: "Budgets")) } footer: {246 Text(String(localized: "Une tâche consomme des jetons de modèle, donc de l’argent réel, dans la limite de ces budgets. Ils sont appliqués par l’exécuteur depuis l’extérieur de l’agent. Aucun n’est pré-rempli."))247 }248 Section {249 if let p = draft.problem { Text(p).font(.spFootnote).foregroundStyle(Theme.mute).accessibilityIdentifier("research.problem") }250 if lost { Notice(tone: .warn, title: String(localized: "Réponse perdue"), message: String(localized: "La création n’est pas idempotente : vérifie la liste des tâches avant de renvoyer, pour ne pas en créer deux.")) }251 if let error { ErrorNotice(error: error) }252 Button { Task { await submit() } } label: { if busy { ProgressView() } else { Text(String(localized: "Créer la tâche")) } }253 .buttonStyle(.spPrimary).disabled(draft.request == nil || busy || !model.canOperate).listRowInsets(.init()).listRowBackground(Color.clear)254 .accessibilityIdentifier("research.create")255 ResearchFooter().listRowInsets(.init()).listRowBackground(Color.clear)256 }257 }258 .navigationTitle(String(localized: "Nouvelle tâche")).navigationBarTitleDisplayMode(.inline)259 .toolbar { ToolbarItem(placement: .cancellationAction) { Button(String(localized: "Annuler")) { dismiss() } } }260 .task { agents = try? await AgentsAPI(model.env.client).list() }261 }262 }263264 private func field(_ label: String, _ text: Binding<String>, _ id: String) -> some View {265 HStack { Text(label); Spacer(minLength: 8); TextField("", text: text).keyboardType(.decimalPad).multilineTextAlignment(.trailing).frame(maxWidth: 130).accessibilityLabel(label).accessibilityIdentifier(id) }266 }267268 private func submit() async {269 guard let r = draft.request else { return }270 busy = true; defer { busy = false }271 do { let job = try await ResearchAPI(model.env.client).create(r); created(job) }272 catch let e as APIError where e.isOffline { lost = true; error = e }273 catch let e { error = e }274 }275}276