Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet for macOS9// File : Features/TradingAgents/AgentDetailView.swift10// Description : One agent: the header with its mode band, the life-cycle11// controls the server allows for its family (start in12// research or on paper, pause, resume, stop — never a13// passkey), and the sections of the detail. The real mode is14// never a simple "start": it is reached only through the15// mandate section, where the passkey approves a verified16// mandate.17// Module : Features18// Repository : https://git.spboucher.ai/sp-wallet-macos19// Created : 2026-11-1820// Last Modified : 2026-11-1821//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author : Simon-Pierre Boucher27// Position : Professor of Finance28// Institution : Université du Québec en Outaouais (UQO)29// Department : Département des sciences administratives30// Organization : SP Boucher31//32// Website : https://spboucher.ai33// Git : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General : info@spboucher.ai40// Professional : contact@spboucher.ai41// Direct : simon@spboucher.ai42// Research : research@spboucher.ai43// Development : dev@spboucher.ai44// Support : support@spboucher.ai45// Security/Admin : admin@spboucher.ai46// Notifications : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification : Public73// Distribution : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License : None specified (no license file in this repository)87// Maintainer : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import SwiftUI95import SPWalletCore9697struct AgentDetailView: View {98 let model: AppModel99 let store: AgentsStore100 let id: String101 let onBack: () -> Void102103 enum Section: String, CaseIterable { case overview = "Aperçu", strategy = "Stratégie", activity = "Activité", performance = "Performance", vault = "Coffre", perp = "Perpétuels", mm = "Tenue de marché", mandate = "Mandat et risques", config = "Configuration" }104 @State private var d: AgentDetailStore?105 @State private var section: Section = .overview106 @State private var spotFlow: SpotGoLiveFlow?107 @State private var confirmStop = false108 @State private var confirmStartLive = false109110 var body: some View {111 VStack(alignment: .leading, spacing: 16) {112 Button(action: onBack) { Label("Tous les agents", systemImage: "chevron.left") }.buttonStyle(.link)113 if let d {114 if let a = d.agent { header(d, a); controls(d, a); sections(d, a) }115 else if let e = d.error("detail") { Banner(.danger, "Agent indisponible : \(e)"); Button("Réessayer") { Task { await d.refresh() } } }116 else { ProgressView() }117 } else { ProgressView() }118 }119 .task {120 if d == nil { d = AgentDetailStore(model: model, id: id) }121 if spotFlow == nil { spotFlow = SpotGoLiveFlow(model: model) }122 await d?.poll()123 }124 .sheet(isPresented: Binding(get: { spotFlow?.step == .review || spotFlow?.step == .approving }, set: { _ in })) {125 if let f = spotFlow, let a = f.approval { SpotMandateSheet(model: model, flow: f, approval: a) }126 }127 .onChange(of: spotFlow?.step) { _, s in if s == .done { Task { await d?.refresh(); await store.refresh() } } }128 }129130 private func available(_ d: AgentDetailStore, _ a: Agent) -> [Section] {131 Section.allCases.filter { s in132 switch s {133 case .vault: a.hasVault134 case .perp: a.resolvedKind == .perp135 case .mm: d.isMarketMaking136 default: true137 }138 }139 }140141 // MARK: header142143 @ViewBuilder private func header(_ d: AgentDetailStore, _ a: Agent) -> some View {144 let kind = ModeKind(agent: a), s = d.summary145 VStack(alignment: .leading, spacing: 10) {146 HStack(alignment: .firstTextBaseline) {147 Text(a.name).font(.title.weight(.semibold)).textSelection(.enabled)148 Spacer()149 if d.error("detail") != nil { ProvenanceTag(p: .stale, text: "Dernière lecture \(Fmt.relative(d.loadedAt))") }150 Button { Task { await d.refresh() } } label: { Image(systemName: "arrow.clockwise") }.help("Relire sur le serveur")151 }152 ModeHeaderBand(kind: kind)153 if a.tradesRealMoney { Banner(.danger, "Cet agent négocie de l’argent réel sous mandat. Pour l’arrêter : « Arrêter » ci-dessous, « Révoquer le mandat » dans Mandat et risques, ou l’arrêt d’urgence en haut de l’écran — aucun n’exige de passkey.") }154 if !a.mission.isEmpty { Text(a.mission).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }155 VStack(alignment: .leading, spacing: 5) {156 Field(label: "État (serveur)", value: AgentText.phase(a.state) + (s.map { " · \(AgentText.lifecycle($0.state))" } ?? ""), emphasis: true)157 Field(label: "Type", value: "\(AgentText.kind(a.resolvedKind))\((s?.family ?? a.family).map { " · \(AgentText.family($0))" } ?? "")\(a.template.map { " · modèle \($0)" } ?? "")\((s?.engine ?? a.engine).map { " · moteur \($0)" } ?? "")")158 Field(label: "Stratégie", value: s?.strategy.map { "\($0.name) \($0.version) — \($0.kind == "rule" ? "règle intégrée" : "code épinglé par empreinte") · \($0.status)" } ?? (d.overview == nil ? "—" : "aucune version rattachée"))159 Field(label: "Marchés", value: a.universe.isEmpty ? "—" : a.universe.joined(separator: ", "))160 Field(label: a.resolvedKind == .spot ? "Réseau" : "Plateforme", value: "\(a.networkName ?? a.network)\(a.liveNetwork.map { " · réseau réel : \($0)" } ?? "") · pas \(a.interval)")161 Field(label: a.hasVault ? "Capital prévu" : (kind.mode == .live ? "Capital de référence" : "Capital SIMULÉ"), value: "\(Fmt.amount(a.capitalUsdc, maxFraction: 2)) USDC")162 Field(label: "Configuration", value: "version \(s?.configVersion ?? a.configVersion ?? 0)\(a.lastBar.map { " · dernière barre traitée \(Fmt.relative($0))" } ?? "")")163 if let w = d.overview?.worker?.lease { Field(label: "Travailleur", value: "\(w.owner) · battement \(Fmt.relative(w.heartbeatAt)) · \(w.active ? "bail actif" : "bail EXPIRÉ")") }164 if let r = a.stopReason ?? s?.stopReason, !r.isEmpty { Field(label: "Motif d’arrêt", value: r) }165 }166 if let e = d.error("overview") { Banner(.warning, "Vue d’ensemble indisponible : \(e)") }167 }168 }169170 // MARK: life cycle171172 @ViewBuilder private func controls(_ d: AgentDetailStore, _ a: Agent) -> some View {173 let kind = ModeKind(agent: a), s = d.summary174 let lifecycle = s?.state ?? .unknown, winding = s?.isWindingDown == true175 let modes = d.allowedModes176 Card("Cycle de vie") {177 if store.killSwitch?.engaged == true { Banner(.danger, "Arrêt d’urgence engagé : aucun agent ne peut ajouter de risque. Démarrer en réel sera refusé par le serveur.") }178 if winding { Banner(.warning, "Arrêt en cours : le mandat est révoqué, le moteur ferme les positions avec des ordres réducteurs.\(s?.windDown.map { " " + JSONFlat.rows($0).map { "\($0.key) : \($0.value)" }.joined(separator: " · ") } ?? "")") }179 if a.pausedFrom == "LIVE", a.resolvedKind == .spot { Banner(.warning, "Cet agent était en réel quand il a été mis en pause : son mandat a été révoqué au signataire. Le relancer en réel exige un NOUVEAU mandat approuvé avec votre passkey.") }180 if s == nil { Text("Commandes indisponibles tant que la vue d’ensemble du serveur n’est pas lue.").foregroundStyle(.secondary).font(.callout) }181 else {182 HStack(spacing: 10) {183 if lifecycle != .active, !winding {184 ForEach([AgentMode.research, .paper], id: \.self) { m in185 if modes?.contains(m) ?? true { ModeButton(title: "Démarrer", kind: ModeKind(m), systemImage: "play.fill") { Task { await d.start(m) } } }186 }187 if lifecycle == .paused, a.pausedFrom != "LIVE" || a.resolvedKind != .spot {188 ModeButton(title: "Reprendre", kind: a.pausedFrom == "LIVE" ? ModeKind(.live, liveNetwork: a.liveNetwork) : ModeKind(AgentMode(server: a.pausedFrom ?? a.mode.rawValue)), systemImage: "playpause.fill") { Task { await d.resume() } }189 }190 }191 if lifecycle == .active, !winding { ModeButton(title: "Mettre en pause", kind: kind, systemImage: "pause.fill") { Task { await d.pause() } } }192 if lifecycle != .stopped || a.mode == .live { ModeButton(title: winding ? "Redemander l’arrêt" : "Arrêter", kind: kind, systemImage: "stop.fill", prominent: a.mode == .live, role: .destructive) { confirmStop = true } }193 if d.busy != nil { ProgressView().controlSize(.small) }194 Spacer(minLength: 0)195 }.disabled(!model.canOperate || d.busy != nil)196 Text(pauseNote(a)).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)197 liveRow(d, a, s!)198 }199 if let n = d.notice { Banner(.info, n) }200 if let e = d.actionError { Banner(.danger, e) }201 }202 .confirmationDialog("Arrêter l’agent « \(a.name) » ?", isPresented: $confirmStop, titleVisibility: .visible) {203 Button("Arrêter · \(kind.short)", role: .destructive) { Task { await d.stop() } }204 Button("Annuler", role: .cancel) {}205 } message: { Text(stopNote(a)) }206 .confirmationDialog("Démarrer en RÉEL sous le mandat en vigueur ?", isPresented: $confirmStartLive, titleVisibility: .visible) {207 Button("Démarrer · RÉEL", role: .destructive) { Task { await d.startLive() } }208 Button("Annuler", role: .cancel) {}209 } message: { Text("L’agent enverra des ordres réels dans les bornes du mandat que vous avez déjà approuvé avec votre passkey. Ce bouton ne crée ni n’élargit aucun mandat : sans mandat en vigueur, le serveur refuse. Vous pouvez perdre les fonds engagés.") }210 }211212 /// The real mode: its availability as the server states it, and the door to the mandate — never a direct start without one.213 @ViewBuilder private func liveRow(_ d: AgentDetailStore, _ a: Agent, _ s: AgentSummary) -> some View {214 let liveKind = ModeKind(.live, liveNetwork: a.liveNetwork)215 Divider()216 if d.allowedModes?.contains(.live) == false {217 Label("Mode réel indisponible pour cette famille d’agents\(d.overview?.familyModes?.liveReason.map { " : \($0)" } ?? ".")", systemImage: "lock.fill").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)218 } else if !s.live.capable {219 Label("Mode réel indisponible pour cet agent : \(s.live.reason ?? s.live.code ?? "raison non précisée par le serveur")", systemImage: "lock.fill").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)220 } else if a.mode != .live {221 HStack(spacing: 10) {222 ModeButton(title: "Passer en réel : approuver un mandat…", kind: liveKind, systemImage: "touchid") { section = a.resolvedKind == .perp ? .perp : d.isMarketMaking ? .mm : .mandate }223 if let m = s.mandate, s.state != .active || s.mode != .live {224 ModeButton(title: "Démarrer sous le mandat en vigueur", kind: liveKind, systemImage: "play.fill") { confirmStartLive = true }.help("Mandat \(m.kind) \(m.id), déjà approuvé avec votre passkey.")225 }226 Spacer(minLength: 0)227 }.disabled(!model.canOperate || d.busy != nil)228 Text("Le réel n’existe que sous un mandat : ses bornes sont affichées en entier et approuvées avec votre passkey avant tout ordre.").font(.caption).foregroundStyle(.secondary)229 }230 }231232 private func pauseNote(_ a: Agent) -> String {233 switch (a.resolvedKind, a.mode) {234 case (.spot, .live): "Pause en réel : aucun nouvel ordre ET le mandat est révoqué au signataire (reprendre exigera un nouveau mandat). Arrêter révoque aussi le mandat. Aucune de ces commandes ne demande de passkey."235 case (.perp, .live): "Pause en réel : aucune nouvelle exposition ; les positions sont CONSERVÉES sur la plateforme et le mandat reste en vigueur. Arrêter révoque le mandat et ferme les positions avec des ordres réducteurs."236 default: "Démarrer, mettre en pause et arrêter n’ajoutent aucune autorité et ne demandent jamais de passkey."237 }238 }239 private func stopNote(_ a: Agent) -> String {240 guard a.mode == .live else { return "L’agent cesse de fonctionner. Rien n’est signé." }241 if a.resolvedKind == .perp { return "Le mandat est révoqué au signataire et les positions sont fermées avec des ordres réducteurs (résultat non garanti : prix de marché). L’agent reste « arrêt en cours » jusqu’à la fin." }242 if d?.isMarketMaking == true { return "Le mandat de cotation est révoqué ; les cotations sont retirées." }243 return "Le mandat est révoqué au signataire : plus aucun échange ne peut être signé. Les fonds restent dans le coffre ; vous pourrez les rapatrier depuis l’onglet Coffre."244 }245246 // MARK: sections247248 @ViewBuilder private func sections(_ d: AgentDetailStore, _ a: Agent) -> some View {249 let all = available(d, a)250 Picker("Section", selection: $section) { ForEach(all, id: \.self) { Text($0.rawValue).tag($0) } }.pickerStyle(.segmented).labelsHidden()251 switch all.contains(section) ? section : .overview {252 case .overview: AgentOverviewSection(model: model, d: d)253 case .strategy: AgentStrategySection(model: model, d: d, templates: store.templates)254 case .activity: AgentActivitySection(d: d)255 case .performance: AgentPerformanceSection(d: d)256 case .vault: AgentVaultSection(model: model, d: d)257 case .perp: PerpAgentSection(model: model, d: d, store: store)258 case .mm: MarketMakingSection(model: model, d: d, store: store)259 case .mandate: if let f = spotFlow { AgentMandateSection(model: model, d: d, store: store, spotFlow: f) }260 case .config: AgentConfigSection(model: model, d: d)261 }262 }263}264