SPB Git

Repository Public

RsJobsTab.swift 10.0 KB 192 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet for macOS9// File             : Features/Research/RsJobsTab.swift10// Description      : The automated research jobs: whether the server's research11//                    runner is available (and the server's reason when it is12//                    not), the list of jobs with their real state, creation,13//                    and the selected job's page. Results are AI-generated14//                    analysis and backtests and are labelled so on every block.15// Module           : Features16// Repository       : https://git.spboucher.ai/sp-wallet-macos17// Created          : 2026-11-1818// Last Modified    : 2026-11-1819//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : None specified (no license file in this repository)85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import SwiftUI93import SPWalletCore9495struct RsJobsTab: View {96    let model: AppModel97    @State private var data: RsJobsModel?98    @State private var creating = false99100    var body: some View {101        Group {102            if let data {103                // an HStack, not an HSplitView (see Features/Assets/AssetsView.swift: the AppKit split view breaks the window's layout)104                HStack(spacing: 0) {105                    list(data).frame(width: 380)106                    Divider()107                    Group {108                        if data.selectedId != nil { RsJobDetailView(model: model, data: data) }109                        else { EmptyState(symbol: "sparkles.rectangle.stack", title: "Sélectionnez une recherche", detail: "Chaque recherche montre séparément ce que l’agent IA affirme, ce que le serveur a mesuré lui-même en backtest, et les données observées.") }110                    }.frame(maxWidth: .infinity, maxHeight: .infinity)111                }112            } else { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }113        }114        .task {115            let d = data ?? RsJobsModel(model: model); data = d116            await d.refresh()117            while !Task.isCancelled {118                try? await Task.sleep(for: .seconds(d.hasOpenJobs ? 15 : 60))119                guard !Task.isCancelled else { return }120                if AppActivity.isActive, !model.isOffline { await d.refresh() }121            }122        }123        .sheet(isPresented: $creating) { if let data { RsJobCreateSheet(model: model, jobs: data) { creating = false } } }124    }125126    private func list(_ data: RsJobsModel) -> some View {127        @Bindable var data = data128        return VStack(alignment: .leading, spacing: 0) {129            VStack(alignment: .leading, spacing: 8) {130                RsRunnerStatus(data: data)131                HStack {132                    Button { creating = true } label: { Label("Nouvelle recherche…", systemImage: "plus") }.disabled(!data.canCreate)133                    Spacer()134                    if data.loading { ProgressView().controlSize(.small) }135                    Button { Task { await data.refresh() } } label: { Image(systemName: "arrow.clockwise") }.disabled(data.loading)136                }137                if let e = data.jobsError { Banner(data.jobs.isEmpty ? .danger : .warning, data.jobs.isEmpty ? e : "Liste non rafraîchie (\(e)) — lue \(Fmt.relative(data.jobsAt)).") }138            }.padding(14)139            Divider()140            List(data.jobs, selection: $data.selectedId) { j in141                VStack(alignment: .leading, spacing: 3) {142                    HStack(spacing: 6) {143                        RsJobStateDot(state: j.state)144                        Text(RsJobText.state(j.state)).font(.callout.weight(.medium)).lineLimit(1)145                        Spacer()146                        Text(Fmt.relative(j.createdAt)).font(.caption).foregroundStyle(.secondary)147                    }148                    Text(verbatim: j.mission).font(.callout).lineLimit(2).foregroundStyle(.secondary)149                    HStack(spacing: 6) {150                        Text("\(j.kind == "perp" ? "Perp." : "Comptant") · \(j.universe.joined(separator: ", ")) · \(j.interval)").font(.caption).foregroundStyle(.secondary).lineLimit(1)151                        if j.cancelRequested && !j.state.isFinal { Text("annulation demandée").font(.caption).foregroundStyle(Theme.warning) }152                        if j.claimsDiffer == true { Text("affirmations ≠ mesures").font(.caption).foregroundStyle(Theme.warning) }153                    }154                }.padding(.vertical, 3).tag(j.id)155            }156            .overlay { if data.jobs.isEmpty && data.jobsError == nil && !data.loading { EmptyState(symbol: "tray", title: "Aucune recherche", detail: "Les recherches lancées apparaîtront ici avec leur état réel.") } }157        }158    }159}160161struct RsJobStateDot: View {162    let state: ResearchState163    var body: some View {164        let color: Color = switch state { case .submitted: Theme.positive; case .failed, .overBudget: Theme.negative; case .cancelled: .secondary; case .queued: Theme.warning; default: .blue }165        Circle().fill(color).frame(width: 8, height: 8).accessibilityHidden(true)166    }167}168169/// Whether the research runner is available, from the server: its capability, its last contact, the open-job quota.170private struct RsRunnerStatus: View {171    let data: RsJobsModel172    var body: some View {173        VStack(alignment: .leading, spacing: 4) {174            if let s = data.status {175                HStack(spacing: 6) {176                    Image(systemName: s.runnerConfigured ? "cpu.fill" : "cpu").foregroundStyle(s.runnerConfigured ? Theme.positive : Theme.warning)177                    Text(s.runnerConfigured ? "Exécuteur de recherche : activé sur le serveur" : "Exécuteur de recherche : désactivé sur le serveur").fontWeight(.medium)178                }179                if !s.runnerConfigured {180                    Text(data.runnerCapability?.why ?? "Aucun secret d’exécuteur n’est configuré sur le serveur : les recherches créées restent en file d’attente.").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)181                    if let m = data.runnerCapability?.missing, !m.isEmpty { Text("Réglage en cause : \(m.joined(separator: ", "))").font(.caption.monospaced()).foregroundStyle(.secondary) }182                } else {183                    Text(s.lastRunnerContact.map { "Dernier contact d’un exécuteur : \(Fmt.relative($0)) (\(Fmt.date($0)))" } ?? "Activé, mais aucun exécuteur ne s’est encore manifesté : les recherches attendront en file.")184                        .font(.caption).foregroundStyle(s.lastRunnerContact == nil ? Theme.warning : .secondary).fixedSize(horizontal: false, vertical: true)185                }186                Text("Recherches ouvertes : \(s.openJobs) / \(s.maxOpenJobs)\(s.labCommit.map { " · laboratoire \($0.prefix(10))" } ?? " · version du laboratoire inconnue")").font(.caption).foregroundStyle(.secondary)187            } else if let e = data.statusError { OpsUnavailable(what: "État du service de recherche", reason: e) }188            else { ProgressView().controlSize(.small) }189        }190    }191}192
Files main
Menu

Theme