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/TradingAgentsView.swift10// Description : Entry of the trading-agents section: the emergency stop11// always on top, then two tabs — the agents (list, engine12// runtime, server locks, one agent's detail) and the13// programmable trading API (keys, webhooks, usage). Nothing14// here starts, funds or authorizes anything by being15// displayed.16// Module : Features17// Repository : https://git.spboucher.ai/sp-wallet-macos18// Created : 2026-11-1819// Last Modified : 2026-11-1820//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author : Simon-Pierre Boucher26// Position : Professor of Finance27// Institution : Université du Québec en Outaouais (UQO)28// Department : Département des sciences administratives29// Organization : SP Boucher30//31// Website : https://spboucher.ai32// Git : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General : info@spboucher.ai39// Professional : contact@spboucher.ai40// Direct : simon@spboucher.ai41// Research : research@spboucher.ai42// Development : dev@spboucher.ai43// Support : support@spboucher.ai44// Security/Admin : admin@spboucher.ai45// Notifications : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification : Public72// Distribution : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License : None specified (no license file in this repository)86// Maintainer : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import SwiftUI94import SPWalletCore9596struct TradingAgentsView: View {97 let model: AppModel98 enum Tab: String, CaseIterable { case agents = "Agents", api = "API de trading" }99 @State private var tab: Tab = .agents100 @State private var store: AgentsStore?101 @State private var selected: String?102 @State private var creating = false103104 var body: some View {105 Page("Agents de trading", subtitle: "Des stratégies automatiques, toujours bornées. Recherche et papier sont des simulations ; le réel n’existe que sous un mandat que vous approuvez avec votre passkey et révoquez sans elle.") {106 if let store {107 KillSwitchBar(model: model, store: store)108 if !model.canOperate { Banner(.warning, model.isOffline ? "Portefeuille injoignable : lecture seule des dernières données, aucune opération possible." : "Session requise : aucune opération possible.") }109 Picker("Section", selection: $tab) { ForEach(Tab.allCases, id: \.self) { Text($0.rawValue).tag($0) } }.pickerStyle(.segmented).labelsHidden().frame(maxWidth: 360)110 switch tab {111 case .agents:112 if let id = selected { AgentDetailView(model: model, store: store, id: id) { selected = nil } .id(id) }113 else { AgentsListView(model: model, store: store, onOpen: { selected = $0 }, onCreate: { creating = true }) }114 case .api: TradingAPIView(model: model, locks: store.locks)115 }116 } else { ProgressView() }117 }118 .task {119 if store == nil { store = AgentsStore(model: model) }120 await store?.poll()121 }122 .sheet(isPresented: $creating) {123 if let store { AgentCreateSheet(model: model, store: store) { created in creating = false; if let created { selected = created }; Task { await store.refresh() } } }124 }125 .sheet(isPresented: Binding(get: { store?.release != nil }, set: { _ in })) {126 if let store, let a = store.release { KillSwitchReleaseSheet(store: store, approval: a) }127 }128 }129}130131/// The global emergency stop of every agent, key and mandate. Engage: one click and a confirmation, never a passkey. Release: the passkey.132struct KillSwitchBar: View {133 let model: AppModel134 let store: AgentsStore135 @State private var confirming = false136137 var body: some View {138 let k = store.killSwitch139 VStack(alignment: .leading, spacing: 8) {140 HStack(alignment: .top, spacing: 12) {141 Image(systemName: k?.engaged == true ? "hand.raised.fill" : "hand.raised").font(.title2).foregroundStyle(k?.engaged == true ? Theme.negative : .secondary)142 VStack(alignment: .leading, spacing: 2) {143 if let k {144 Text(k.engaged ? "ARRÊT D’URGENCE ENGAGÉ" : "Arrêt d’urgence : non engagé").font(.headline).foregroundStyle(k.engaged ? Theme.negative : .primary)145 if k.engaged {146 Text("Aucun agent, aucune clé et aucun mandat ne peut ajouter de risque. Les annulations et les ordres strictement réducteurs passent encore.").font(.callout).fixedSize(horizontal: false, vertical: true)147 Text("Engagé \(Fmt.date(k.at))\(k.by.map { " par \($0)" } ?? "")\(k.reason.map { " — \($0)" } ?? "")").font(.caption).foregroundStyle(.secondary).textSelection(.enabled)148 } else {149 Text("Un clic et une confirmation, sans passkey : plus aucun agent, clé ou mandat ne peut ajouter de risque. Le lever exige votre passkey.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)150 }151 if k.readOnly { Text("Mode lecture seule actif\(k.readOnlyReason.map { " : \($0)" } ?? "") — seules les annulations passent.").font(.caption).foregroundStyle(Theme.warning) }152 } else {153 Text("Arrêt d’urgence : état inconnu").font(.headline)154 Text(store.runtimeError ?? "L’état n’a pas encore été lu sur le serveur. Il n’est pas présumé levé.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)155 }156 }157 Spacer(minLength: 8)158 if store.killBusy { ProgressView().controlSize(.small) }159 if k?.engaged == true {160 Button { Task { await store.prepareRelease() } } label: { Label("Lever avec la passkey…", systemImage: "touchid") }.disabled(!model.canOperate || store.killBusy)161 } else {162 // engaging is allowed even when the last state read is unknown: it only removes authority163 Button(role: .destructive) { confirming = true } label: { Label("Arrêt d’urgence", systemImage: "hand.raised.fill").fontWeight(.semibold) }164 .buttonStyle(.borderedProminent).tint(Theme.negative).controlSize(.large).disabled(model.phase != .signedIn || store.killBusy)165 .help("Engage l’arrêt d’urgence global des agents. Aucune passkey n’est demandée.")166 }167 }168 if let e = store.killError, store.release == nil { Banner(.danger, e) }169 }170 .padding(14).frame(maxWidth: .infinity, alignment: .leading)171 .background((k?.engaged == true ? Theme.negative : Color.secondary).opacity(k?.engaged == true ? 0.12 : 0.06), in: RoundedRectangle(cornerRadius: Theme.corner))172 .overlay(RoundedRectangle(cornerRadius: Theme.corner).strokeBorder((k?.engaged == true ? Theme.negative : Theme.stroke).opacity(0.6)))173 .confirmationDialog("Engager l’arrêt d’urgence des agents ?", isPresented: $confirming, titleVisibility: .visible) {174 Button("Engager l’arrêt d’urgence", role: .destructive) { Task { await store.engageKillSwitch() } }175 Button("Annuler", role: .cancel) {}176 } message: {177 Text("Effet immédiat pour tous les agents, toutes les clés d’API et tous les mandats : plus aucun nouveau risque. Les positions ouvertes ne sont PAS fermées par ce bouton ; les annulations et les ordres réducteurs restent possibles. Lever l’arrêt exigera votre passkey.")178 }179 }180}181182/// Release of the kill switch: the fields of the verified release intent, then the passkey.183struct KillSwitchReleaseSheet: View {184 let store: AgentsStore185 let approval: RiskSwitchReleaseApproval186 @State private var understood = false187188 var body: some View {189 let i = approval.intent190 SheetScaffold(title: "Lever l’arrêt d’urgence", width: 680, height: 560) {191 Banner(.warning, "Lever l’arrêt redonne aux mandats en vigueur la possibilité d’ajouter du risque. Les agents arrêtés ou en pause ne repartent pas seuls.")192 ReviewLines(lines: [193 ReviewLine(label: "Opération", value: "Levée de l’arrêt d’urgence global (\(i.kind.rawValue))", style: .strong),194 ReviewLine(label: "Engagé le", value: Fmt.dateSeconds(AgentText.ms(i.engagedAt))),195 ReviewLine(label: "Engagé par", value: i.engagedBy ?? "—"),196 ReviewLine(label: "Raison enregistrée", value: i.reason ?? "—"),197 ReviewLine(label: "Intention préparée le", value: Fmt.dateSeconds(AgentText.ms(i.createdAt))),198 ReviewLine(label: "Nonce", value: i.nonce, style: .address),199 ])200 BindingProof(digest: approval.approval.digest, expiry: i.expiry)201 AckToggle(isOn: $understood, text: "Je comprends que les mandats encore en vigueur pourront de nouveau engager du risque dès la levée.")202 } footer: {203 if let e = store.killError { Banner(.danger, e) }204 HStack {205 Button("Annuler") { store.cancelRelease() }.disabled(store.releasing)206 Spacer()207 if store.releasing { ProgressView().controlSize(.small); Text("Passkey…").foregroundStyle(.secondary) }208 Button { Task { await store.approveRelease() } } label: { Label("Lever avec la passkey", systemImage: "touchid") }209 .buttonStyle(.borderedProminent).controlSize(.large).disabled(!understood || store.releasing)210 }211 }212 .interactiveDismissDisabled()213 }214}215216struct AgentsListView: View {217 let model: AppModel218 let store: AgentsStore219 let onOpen: (String) -> Void220 let onCreate: () -> Void221222 var body: some View {223 Card("Agents", trailing: AnyView(HStack(spacing: 10) {224 if store.agentsFromCache { ProvenanceTag(p: .stale, text: "Données du \(Fmt.date(store.agentsAt))") }225 if store.loading { ProgressView().controlSize(.small) }226 Button { Task { await store.refresh() } } label: { Image(systemName: "arrow.clockwise") }.help("Relire sur le serveur").disabled(model.phase != .signedIn)227 Button { onCreate() } label: { Label("Nouvel agent…", systemImage: "plus") }.disabled(!model.canOperate)228 })) {229 if let e = store.agentsError { Banner(.danger, "Liste indisponible : \(e)") }230 if let agents = store.agents {231 if agents.isEmpty { EmptyState(symbol: "cpu", title: "Aucun agent", detail: "Un agent se crée en recherche ou en simulation, avec toutes ses limites. Rien ne peut être négocié en réel tant que vous n’avez pas approuvé un mandat avec votre passkey.") }232 else { VStack(spacing: 8) { ForEach(agents) { a in AgentRow(agent: a, lease: store.runtime?.leases.first { $0.agentId == a.id }) { onOpen(a.id) } } } }233 } else if store.agentsError == nil { ProgressView() }234 HStack(spacing: 8) { ForEach([AgentMode.research, .paper, .live], id: \.self) { ModeTag(kind: ModeKind($0)) }; ModeTag(kind: ModeKind(.live, liveNetwork: "testnet")) }235 Text("La couleur et l’étiquette du mode accompagnent chaque agent, chaque chiffre et chaque bouton. Les chiffres de modes différents ne sont jamais additionnés.").font(.caption).foregroundStyle(.secondary)236 }237 RuntimeCard(store: store)238 LocksCard(store: store)239 }240}241242/// One agent in the list: the mode band on the leading edge, then name, state, strategy family, markets, network or venue.243struct AgentRow: View {244 let agent: Agent245 let lease: AgentRuntimeStatus.Lease?246 let open: () -> Void247248 var body: some View {249 let kind = ModeKind(agent: agent)250 Button(action: open) {251 HStack(spacing: 12) {252 VStack(alignment: .leading, spacing: 4) {253 HStack(spacing: 8) {254 Text(agent.name).font(.headline).lineLimit(1)255 ModeTag(kind: kind)256 if agent.tradesRealMoney { Label("Argent réel engagé", systemImage: "exclamationmark.triangle.fill").font(.caption.weight(.semibold)).foregroundStyle(kind.color) }257 }258 Text("\(AgentText.phase(agent.state)) · \(AgentText.kind(agent.resolvedKind))\(agent.family.map { " · \(AgentText.family($0))" } ?? "")\(agent.template.map { " · modèle \($0)" } ?? "")").font(.callout).foregroundStyle(.secondary).lineLimit(1)259 Text("Marchés : \(agent.universe.isEmpty ? "—" : agent.universe.joined(separator: ", ")) · \(agent.resolvedKind == .spot ? "Réseau" : "Plateforme") : \(agent.networkName ?? agent.network) · pas \(agent.interval)").font(.caption).foregroundStyle(.secondary).lineLimit(1)260 if let r = agent.stopReason, !r.isEmpty { Text("Motif d’arrêt : \(r)").font(.caption).foregroundStyle(Theme.warning).lineLimit(2) }261 }262 Spacer(minLength: 8)263 VStack(alignment: .trailing, spacing: 3) {264 Text("\(Fmt.amount(agent.capitalUsdc, maxFraction: 2)) USDC").monospacedDigit().fontWeight(.medium)265 Text(agent.hasVault ? "capital prévu (coffre)" : "capital \(kind.mode == .live ? "de référence" : "simulé")").font(.caption).foregroundStyle(.secondary)266 if let lease { Text(lease.active ? "Travailleur actif · \(Fmt.relative(lease.heartbeatAt))" : "Bail expiré").font(.caption2).foregroundStyle(lease.active ? Color.secondary : Theme.warning) }267 }268 Image(systemName: "chevron.right").foregroundStyle(.tertiary)269 }270 .padding(.vertical, 8).padding(.trailing, 10).modeFramed(kind)271 .background(kind.color.opacity(0.05), in: RoundedRectangle(cornerRadius: 8))272 .contentShape(Rectangle())273 }274 .buttonStyle(.plain)275 .accessibilityLabel("\(agent.name), mode \(kind.title), \(AgentText.phase(agent.state))")276 }277}278279/// The agent engine as the server reports it: workers, loops with their last pass, leases, queue.280struct RuntimeCard: View {281 let store: AgentsStore282 var body: some View {283 Card("Moteur des agents (état du serveur)") {284 if let r = store.runtime {285 HStack(alignment: .top, spacing: 24) {286 VStack(alignment: .leading, spacing: 4) {287 Field(label: "Travailleurs", value: "\(r.workers.inProcess ? "dans le processus de l’API" : "processus séparé")\(r.workers.mode.map { " · réglage : \($0)" } ?? "")")288 Field(label: "File de tâches", value: "\(r.queue.queued) en attente · \(r.queue.running) en cours · \(r.queue.dead24h) abandonnée(s) en 24 h")289 if let ms = r.queue.oldestQueuedMs { Field(label: "Plus ancienne en attente", value: "\(Int(ms / 1000)) s") }290 Field(label: "Baux", value: r.leases.isEmpty ? "aucun agent tenu par un travailleur" : "\(r.leases.filter(\.active).count) actif(s) sur \(r.leases.count)")291 }292 }293 if r.queue.dead24h > 0 { Banner(.warning, "\(r.queue.dead24h) tâche(s) abandonnée(s) après épuisement des tentatives dans les dernières 24 h.") }294 if !r.loops.isEmpty {295 Divider()296 Text("Boucles").font(.caption).foregroundStyle(.secondary)297 ForEach(r.loops, id: \.name) { l in298 HStack(alignment: .firstTextBaseline, spacing: 10) {299 Image(systemName: l.lastError == nil ? "checkmark.circle" : "exclamationmark.triangle.fill").foregroundStyle(l.lastError == nil ? Theme.positive : Theme.warning)300 Text(l.name).font(Theme.monoSmall).frame(width: 220, alignment: .leading)301 Text("dernière passe réussie : \(Fmt.relative(l.lastOkAt))\(l.runs.map { " · \($0) passes" } ?? "")\(l.failures.map { $0 > 0 ? " · \($0) échec(s)" : "" } ?? "")").font(.callout).foregroundStyle(.secondary)302 Spacer(minLength: 0)303 }304 if let e = l.lastError { Text("Dernière erreur (\(Fmt.relative(l.lastErrorAt))) : \(e)").font(.caption).foregroundStyle(Theme.warning).textSelection(.enabled) }305 }306 }307 if !r.leases.isEmpty {308 Divider()309 Text("Baux des travailleurs").font(.caption).foregroundStyle(.secondary)310 ForEach(r.leases, id: \.agentId) { l in311 HStack(spacing: 10) {312 Image(systemName: l.active ? "circle.fill" : "circle").font(.caption2).foregroundStyle(l.active ? Theme.positive : Theme.warning)313 Text(store.agents?.first { $0.id == l.agentId }?.name ?? Fmt.short(l.agentId)).frame(width: 220, alignment: .leading).lineLimit(1)314 Text("\(l.owner) · battement \(Fmt.relative(l.heartbeatAt)) · \(l.active ? "expire \(Fmt.relative(l.expiresAt))" : "EXPIRÉ")").font(.callout).foregroundStyle(.secondary).lineLimit(1)315 Spacer(minLength: 0)316 }317 }318 }319 } else if let e = store.runtimeError { Banner(.danger, "État du moteur indisponible : \(e)") }320 else { ProgressView() }321 }322 }323}324325/// The server locks that gate real execution. A closed lock means the corresponding live controls do not exist in this app.326struct LocksCard: View {327 let store: AgentsStore328 static let relevant = ["deriv_live_mainnet", "deriv_mandate_mainnet", "deriv_mm_mainnet", "deriv_mm_testnet", "trading_api_execution", "broadcast", "workers"]329 var body: some View {330 Card("Verrous du serveur") {331 if let locks = store.locks {332 let shown = locks.filter { Self.relevant.contains($0.id) }, rest = locks.filter { !Self.relevant.contains($0.id) }333 ForEach(shown.isEmpty ? locks : shown) { l in LockRow(name: l.id, open: l.on, reason: l.why) }334 if !shown.isEmpty, !rest.isEmpty { DisclosureGroup("Autres capacités du serveur (\(rest.count))") { VStack(alignment: .leading, spacing: 6) { ForEach(rest) { l in LockRow(name: l.id, open: l.on, reason: l.why) } }.padding(.top, 6) } }335 Text("Ces réglages appartiennent au serveur. Quand un verrou est fermé, les commandes réelles correspondantes sont absentes de cette app ; seul l’état et sa raison sont affichés.").font(.caption).foregroundStyle(.secondary)336 } else if let e = store.locksError { Banner(.warning, "État des verrous indisponible : \(e) Les commandes réelles restent soumises au refus du serveur.") }337 else { ProgressView() }338 }339 }340}341