Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/TradingAgents/AgentPageView.swift10// Description : The page of one agent. Its header says the mode and the11// state as served; its workspaces keep the three modes12// physically apart (Simulation, Papier, Réel — each under13// its own band, each fed by mode-scoped reads only) next to14// the overview, the limits, the vault and market making. The15// bar at the bottom starts, pauses, resumes and stops:16// stopping takes one confirmation and never a passkey, and17// what is shown afterwards is the server's answer.18// Module : Features19// Repository : https://git.spboucher.ai/sp-wallet-ios20// Created : 2026-11-1821// Last Modified : 2026-11-1822//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author : Simon-Pierre Boucher28// Position : Professor of Finance29// Institution : Université du Québec en Outaouais (UQO)30// Department : Département des sciences administratives31// Organization : SP Boucher32//33// Website : https://spboucher.ai34// Git : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General : info@spboucher.ai41// Professional : contact@spboucher.ai42// Direct : simon@spboucher.ai43// Research : research@spboucher.ai44// Development : dev@spboucher.ai45// Support : support@spboucher.ai46// Security/Admin : admin@spboucher.ai47// Notifications : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification : Public74// Distribution : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License : None specified (no license file in this repository)88// Maintainer : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import SwiftUI96import SPWalletCore9798@MainActor @Observable99final class AgentPageModel {100 let id: String101 var detail: AgentDetail?102 var overview: AgentOverview?103 /** Offline: what is left of the last list and the last overview. */104 var cachedAgent: Agent?105 var snapshot: Cached<AgentOverviewSnapshot>?106 var loadError: Error?107 var overviewError: Error?108 var busy: String?109 var outcome: String?110 var actionError: Error?111 var loaded = false112113 init(id: String) { self.id = id }114115 var agent: Agent? { detail?.agent ?? cachedAgent }116 var isLive: Bool { detail != nil }117 var family: String? { overview?.summary.family ?? agent?.family ?? snapshot?.value.family }118 var isMarketMaking: Bool { family == "market_making" }119120 func load(_ model: AppModel, store: AgentsStore) async {121 if cachedAgent == nil { cachedAgent = store.agents.value?.first { $0.id == id } }122 if snapshot == nil { snapshot = await model.env.cache.load(AgentOverviewSnapshot.self, key: AgentsCacheKey.overview(id)) }123 guard model.phase == .ready, !model.offlineBrowsing else { loaded = true; return }124 let api = AgentsAPI(model.env.client)125 async let d: Result<AgentDetail, Error> = { do { return .success(try await api.detail(id)) } catch { return .failure(error) } }()126 async let o: Result<AgentOverview, Error> = { do { return .success(try await api.overview(id)) } catch { return .failure(error) } }()127 switch await d {128 case .success(let v): detail = v; loadError = nil129 case .failure(let e): loadError = e; if (e as? APIError)?.isOffline == true { detail = nil }130 }131 switch await o {132 case .success(let v):133 overview = v; overviewError = nil134 let snap = AgentOverviewSnapshot(v.summary)135 await model.env.cache.save(snap, key: AgentsCacheKey.overview(id))136 case .failure(let e): overviewError = e137 }138 loaded = true139 }140141 /** Runs one owner action; the message shown afterwards is what the server answered, never an assumption. */142 func act(_ key: String, model: AppModel, store: AgentsStore, _ op: () async throws -> String?) async {143 guard busy == nil, model.canOperate else { return }144 busy = key; actionError = nil; outcome = nil145 defer { busy = nil }146 do { outcome = try await op() } catch { actionError = error }147 await load(model, store: store)148 store.revision += 1149 }150}151152enum AgentWorkspace: String, CaseIterable, Identifiable {153 case overview, simulation, paper, live, risk, vault, marketMaking154 var id: String { rawValue }155 var title: String {156 switch self {157 case .overview: String(localized: "Aperçu")158 case .simulation: String(localized: "Simulation")159 case .paper: String(localized: "Papier")160 case .live: String(localized: "Réel")161 case .risk: String(localized: "Risque")162 case .vault: String(localized: "Coffre")163 case .marketMaking: String(localized: "Tenue de marché")164 }165 }166 var icon: String {167 switch self {168 case .overview: "rectangle.grid.1x2"169 case .simulation: "flask.fill"170 case .paper: "doc.plaintext.fill"171 case .live: "bolt.fill"172 case .risk: "gauge.with.dots.needle.67percent"173 case .vault: "lock.rectangle.stack.fill"174 case .marketMaking: "arrow.up.arrow.down.square.fill"175 }176 }177}178179struct AgentPageView: View {180 @Environment(AppModel.self) private var model181 let agentId: String182 let store: AgentsStore183 @State private var page: AgentPageModel184 @State private var workspace: AgentWorkspace = .overview185 @State private var confirmation: AgentConfirmation?186 @State private var liveFlow = false187188 init(agentId: String, store: AgentsStore) {189 self.agentId = agentId; self.store = store190 _page = State(initialValue: AgentPageModel(id: agentId))191 }192193 private var workspaces: [AgentWorkspace] {194 var w: [AgentWorkspace] = [.overview, .simulation, .paper, .live, .risk]195 if page.agent?.hasVault == true { w.append(.vault) }196 if page.isMarketMaking { w.append(.marketMaking) }197 return w198 }199200 var body: some View {201 ScrollView {202 VStack(alignment: .leading, spacing: Theme.Space.section) {203 FreshnessBanner()204 if let a = page.agent {205 header(a)206 if !page.isLive, page.loaded {207 if let e = page.loadError, model.canOperate { ErrorNotice(error: e) { Task { await page.load(model, store: store) } } }208 else { Notice(tone: .warn, title: String(localized: "Dernier aperçu synchronisé"), message: page.snapshot.map { String(localized: "Aperçu du \(AgentFmt.date($0.savedAt)). Aucune action n’est possible hors ligne.") } ?? String(localized: "Seule la dernière liste est disponible hors ligne."), icon: "clock.arrow.circlepath").accessibilityIdentifier("agent.cached") }209 }210 ActionOutcome(text: page.outcome, error: page.actionError)211 content(a)212 } else if let e = page.loadError {213 ErrorNotice(error: e) { Task { await page.load(model, store: store) } }214 } else if page.loaded {215 EmptyState(icon: "wifi.slash", title: String(localized: "Agent indisponible hors ligne"), message: String(localized: "Cet agent n’est pas dans la dernière liste synchronisée."))216 } else { ProgressView().frame(maxWidth: .infinity, minHeight: 200) }217 }218 .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12)219 .frame(maxWidth: 1100).frame(maxWidth: .infinity)220 }221 .spPage()222 .navigationTitle(page.agent?.name ?? String(localized: "Agent")).navigationBarTitleDisplayMode(.inline)223 // the mode, the state and the workspaces stay on screen whatever is scrolled224 .safeAreaInset(edge: .top, spacing: 0) { if let a = page.agent { pinned(a) } }225 .safeAreaInset(edge: .bottom) { if let a = page.agent { controls(a) } }226 .agentConfirmation($confirmation)227 .sheet(isPresented: $liveFlow) { liveSheet.wallet(model) }228 .task(id: store.revision) { await page.load(model, store: store) }229 .refreshable { await page.load(model, store: store) }230 // the answer to an earlier action must not stay on screen as if it described what is shown now231 .onChange(of: workspace) { page.outcome = nil; page.actionError = nil }232 .onChange(of: liveFlow) { page.outcome = nil; page.actionError = nil }233 }234235 // MARK: header236237 private func header(_ a: Agent) -> some View {238 VStack(alignment: .leading, spacing: 8) {239 Text(a.name).font(.spTitle).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)240 if a.mode == .live, !a.tradesRealMoney, a.resolvedKind == .perp {241 Text(String(localized: "Compte de test de la plateforme : les ordres sont réels sur le testnet, l’argent ne l’est pas.")).font(.spFootnote).foregroundStyle(Theme.warn)242 }243 if let s = a.stopReason, !s.isEmpty { Notice(tone: .warn, title: String(localized: "Motif d’arrêt rapporté par le serveur"), message: s) }244 if AgentStateLabel.isWindingDown(a.state) { Notice(tone: .warn, title: String(localized: "Clôture en cours"), message: String(localized: "Le mandat est révoqué ; le moteur ferme les positions par des ordres en réduction seule.")) }245 if store.killSwitch.value?.engaged == true { Notice(tone: .danger, title: String(localized: "Arrêt d’urgence global engagé"), message: String(localized: "Aucun agent ne peut ajouter de risque tant qu’il n’est pas levé dans « Risque et limites »."), icon: "hand.raised.fill") }246 }247 }248249 private func pinned(_ a: Agent) -> some View {250 VStack(alignment: .leading, spacing: 8) {251 HStack(spacing: 8) {252 ModeBadgeView(badge: AgentModeBadge.of(a)).accessibilityIdentifier("agent.badge")253 StateLabelView(state: a.state).accessibilityElement(children: .combine).accessibilityIdentifier("agent.state")254 Spacer(minLength: 0)255 }256 workspacePicker257 }258 .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 8)259 .frame(maxWidth: 1100).frame(maxWidth: .infinity)260 .background(.bar)261 }262263 private var workspacePicker: some View {264 ScrollView(.horizontal, showsIndicators: false) {265 HStack(spacing: 8) {266 ForEach(workspaces) { w in267 let on = w == workspace268 Button { workspace = w } label: {269 Label(w.title, systemImage: w.icon).font(.system(size: 14, weight: .semibold))270 .padding(.horizontal, 13).frame(minHeight: 40)271 .foregroundStyle(on ? Theme.onPrimary : Theme.ink)272 .background(on ? Theme.primary : Theme.elev, in: Capsule())273 }274 .buttonStyle(.plain)275 .accessibilityIdentifier("agent.tab.\(w.rawValue)").accessibilityAddTraits(on ? .isSelected : [])276 }277 }278 }279 }280281 @ViewBuilder private func content(_ a: Agent) -> some View {282 switch workspace {283 case .overview: AgentOverviewWorkspace(page: page)284 case .simulation: AgentSimulationWorkspace(page: page, store: store)285 case .paper: AgentModeWorkspace(page: page, store: store, mode: .paper, startLive: {})286 case .live: AgentModeWorkspace(page: page, store: store, mode: .live, startLive: { liveFlow = true })287 case .risk: AgentRiskWorkspace(page: page, store: store)288 case .vault: AgentVaultWorkspace(page: page, store: store)289 case .marketMaking: AgentMarketMakingWorkspace(page: page, store: store)290 }291 }292293 @ViewBuilder private var liveSheet: some View {294 switch page.detail {295 case .spot(let d): SpotLiveFlow(detail: d) { Task { await page.load(model, store: store); store.revision += 1 } }296 case .perp(let d): PerpLiveFlow(detail: d) { Task { await page.load(model, store: store); store.revision += 1 } }297 default: EmptyView()298 }299 }300301 // MARK: controls — "Arrêter" under the thumb, one confirmation, never a passkey302303 private func stop(_ action: AgentStopAction, _ a: Agent) {304 confirmation = AgentConfirmation(title: action.title + " ?", message: action.consequence(agent: a), button: action.title, destructive: true) {305 await page.act(action.rawValue, model: model, store: store) { try await AgentStopRunner(api: AgentsAPI(model.env.client)).run(action, agent: a) }306 }307 }308309 private func start(_ a: Agent, mode: AgentMode) {310 let from = AgentModeBadge.name(a.mode), to = AgentModeBadge.name(mode)311 let what = mode == .paper312 ? String(localized: "L’agent passe de \(from) à \(to) : il décidera à chaque intervalle et ses ordres seront SIMULÉS sur les marchés du moment. Aucun argent ne bouge, rien n’est signé.")313 : String(localized: "L’agent passe de \(from) à \(to) : il observe et enregistre ses décisions sans passer aucun ordre, même simulé.")314 confirmation = AgentConfirmation(title: String(localized: "Démarrer en \(to) ?"), message: what, button: String(localized: "Démarrer en \(to)")) {315 await page.act("start", model: model, store: store) {316 let s = try await AgentsAPI(model.env.client).start(a.id, mode: mode)317 return AgentModeBadge.name(s.mode) + " · " + AgentStateLabel.of(s.phase).text318 }319 }320 }321322 private func resume(_ a: Agent) {323 let back = a.pausedFrom.map { AgentModeBadge.name(AgentMode(server: $0)) } ?? AgentModeBadge.name(a.mode)324 confirmation = AgentConfirmation(title: String(localized: "Reprendre ?"), message: String(localized: "L’agent reprend dans le mode où il a été mis en pause (\(back)). Reprendre n’ajoute aucune autorité : si ce mode était le réel et que le mandat n’existe plus, le serveur refusera."), button: String(localized: "Reprendre")) {325 await page.act("resume", model: model, store: store) {326 let s = try await AgentsAPI(model.env.client).resume(a.id)327 return AgentModeBadge.name(s.mode) + " · " + AgentStateLabel.of(s.phase).text328 }329 }330 }331332 private func controls(_ a: Agent) -> some View {333 let running = AgentStateLabel.isRunning(a.state), paused = AgentStateLabel.isPaused(a.state), winding = AgentStateLabel.isWindingDown(a.state)334 let modes = page.overview?.familyModes?.modes ?? [.research, .paper]335 return VStack(spacing: 6) {336 if !model.canOperate { Text(String(localized: "Hors ligne : aucune action possible.")).font(.spFootnote).foregroundStyle(Theme.warn) }337 HStack(spacing: 10) {338 if running {339 Button { stop(.pause, a) } label: { Label(String(localized: "Pause"), systemImage: "pause.fill") }.buttonStyle(.spSecondary).accessibilityIdentifier("agent.pause")340 } else if paused {341 Button { resume(a) } label: { Label(String(localized: "Reprendre"), systemImage: "play.fill") }.buttonStyle(.spSecondary).accessibilityIdentifier("agent.resume")342 } else if !winding {343 Menu {344 if modes.contains(.paper) { Button { start(a, mode: .paper) } label: { Label(String(localized: "En PAPIER (ordres simulés)"), systemImage: "doc.plaintext.fill") }.accessibilityIdentifier("agent.start.paper") }345 if modes.contains(.research), a.resolvedKind != .spot || a.mode != .research { Button { start(a, mode: .research) } label: { Label(String(localized: "En SIMULATION (aucun ordre)"), systemImage: "flask.fill") } }346 } label: { Label(String(localized: "Démarrer…"), systemImage: "play.fill").font(.system(size: 16, weight: .semibold)).frame(maxWidth: .infinity, minHeight: 50).foregroundStyle(Theme.ink).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.control, style: .continuous)) }347 .accessibilityIdentifier("agent.start")348 }349 Button { stop(.stop, a) } label: { HStack { if page.busy == AgentStopAction.stop.rawValue { ProgressView().tint(Theme.onDanger) } else { Image(systemName: "stop.fill") }; Text(String(localized: "Arrêter")) } }350 .buttonStyle(.spDestructive).accessibilityIdentifier("agent.stop")351 }352 .disabled(!model.canOperate || page.busy != nil)353 }354 .padding(.horizontal, Theme.Space.gutter).padding(.top, 10).padding(.bottom, 8)355 .frame(maxWidth: 760).frame(maxWidth: .infinity)356 .background(.bar)357 }358}359360// MARK: overview361362struct AgentOverviewWorkspace: View {363 @Environment(AppModel.self) private var model364 let page: AgentPageModel365 @State private var versions: [AgentConfigVersion]?366 @State private var versionsError: Error?367368 var body: some View {369 if let a = page.agent {370 let s = page.overview?.summary371 AgentCard(title: String(localized: "Stratégie")) {372 VStack(alignment: .leading, spacing: 0) {373 if !a.mission.isEmpty { FieldRow(label: String(localized: "Mission"), value: a.mission); Divider() }374 FieldRow(label: String(localized: "Famille"), value: AgentFmt.family(page.family) + (a.template.map { " · " + String(localized: "gabarit \($0)") } ?? ""))375 Divider()376 if let st = s?.strategy {377 FieldRow(label: String(localized: "Stratégie · version"), value: "\(st.name) · v\(st.version) · \(st.kind == "rule" ? String(localized: "règle intégrée") : String(localized: "code du laboratoire épinglé par son empreinte"))")378 Divider()379 FieldRow(label: String(localized: "Empreinte du code (SHA-256)"), value: st.sha256, mono: true, copyable: true)380 Divider()381 FieldRow(label: String(localized: "État de la version"), value: AgentSimulationWorkspace.status(st.status))382 } else if let n = page.snapshot?.value.strategyName, s == nil {383 FieldRow(label: String(localized: "Stratégie · version"), value: "\(n) · v\(page.snapshot?.value.strategyVersion ?? "?")")384 } else {385 FieldRow(label: String(localized: "Stratégie"), value: String(localized: "Aucune version approuvée. Choisis-en une dans « Simulation »."), tone: .warn)386 }387 Divider()388 FieldRow(label: String(localized: "Marchés"), value: a.universe.isEmpty ? "—" : a.universe.joined(separator: ", "))389 Divider()390 FieldRow(label: a.resolvedKind == .spot ? String(localized: "Réseau du coffre") : String(localized: "Plateforme"), value: a.networkName ?? a.network)391 Divider()392 FieldRow(label: String(localized: "Intervalle de décision"), value: a.interval)393 Divider()394 FieldRow(label: a.resolvedKind == .spot ? String(localized: "Budget prévu") : (a.simulation ?? true) ? String(localized: "Capital SIMULÉ") : String(localized: "Capital"), value: Money.exact(a.capitalUsdc) + " USD")395 if let b = a.lastBar { Divider(); FieldRow(label: String(localized: "Dernière décision"), value: AgentFmt.date(b)) }396 }397 }398 if let holdings = a.holdings, !holdings.isEmpty {399 AgentCard(title: String(localized: "Actifs détenus pour chaque marché")) {400 AgentRows(items: holdings) { h in401 FieldRow(label: "\(h.symbol) → \(h.assetSymbol) · \(h.name)" + (h.issuer.map { " · " + $0 } ?? ""), value: h.asset == "native" ? String(localized: "monnaie native du réseau") : h.asset, mono: h.asset != "native", copyable: h.asset != "native")402 }403 }404 }405 if let o = page.overview {406 if let fm = o.familyModes {407 AgentCard(title: String(localized: "Modes possibles pour cette famille")) {408 HStack(spacing: 6) { ForEach(fm.modes, id: \.self) { Pill(text: AgentModeBadge.name($0), tone: $0 == .live ? .danger : $0 == .paper ? .warn : .info) } }409 if let r = fm.liveReason { Notice(tone: .info, title: String(localized: "Mode réel indisponible pour cette famille"), message: r) }410 if !o.summary.live.capable { Notice(tone: .info, title: String(localized: "Cet agent ne peut pas passer en réel"), message: [o.summary.live.reason, o.summary.live.code.map { "(\($0))" }].compactMap { $0 }.joined(separator: " ")) }411 }412 }413 if let rt = o.runtime {414 AgentCard(title: String(localized: "Paramètres en vigueur")) {415 if let rule = rt.rule { FieldRow(label: String(localized: "Règle"), value: rule) }416 FieldRow(label: String(localized: "Plateformes observées"), value: rt.venues.joined(separator: ", "))417 ServerDetail(title: String(localized: "Configuration"), value: rt.config)418 ServerDetail(title: String(localized: "Compteurs"), value: rt.counters)419 ServerDetail(title: String(localized: "Dernière passe"), value: rt.lastPass)420 ServerDetail(title: String(localized: "Retenue en cours"), value: rt.hold)421 }422 }423 AgentCard(title: String(localized: "Moteur")) {424 VStack(alignment: .leading, spacing: 0) {425 FieldRow(label: String(localized: "Moteur"), value: o.summary.engine)426 Divider()427 if let l = o.worker?.lease {428 FieldRow(label: String(localized: "Pris en charge par"), value: l.owner + (l.active ? "" : " · " + String(localized: "bail expiré")), mono: true, tone: l.active ? nil : .warn)429 if let h = l.heartbeatAt { Divider(); FieldRow(label: String(localized: "Dernier signe de vie"), value: AgentFmt.time(h)) }430 } else { FieldRow(label: String(localized: "Pris en charge par"), value: String(localized: "aucun travailleur en ce moment")) }431 }432 if !o.jobs.isEmpty {433 Text(String(localized: "Tâches récentes")).font(.spCallout.weight(.semibold))434 AgentRows(items: o.jobs) { j in JobRow(job: j) }435 }436 }437 } else if let e = page.overviewError, model.canOperate { ErrorNotice(error: e) }438 configVersions439 }440 }441442 @ViewBuilder private var configVersions: some View {443 AgentCard(title: String(localized: "Versions de configuration")) {444 if let versions {445 if versions.isEmpty { Text(String(localized: "Aucune version enregistrée.")).font(.spCallout).foregroundStyle(Theme.mute) }446 AgentRows(items: versions) { v in447 DisclosureGroup {448 FieldRow(label: String(localized: "Empreinte (SHA-256)"), value: v.sha256, mono: true, copyable: true)449 JSONFields(value: v.config)450 } label: {451 VStack(alignment: .leading, spacing: 2) {452 Text("v\(v.version) · \(v.reason)").font(.spBody.weight(.medium)).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)453 Text([v.actor, v.createdAt.map(AgentFmt.date)].compactMap { $0 }.joined(separator: " · ")).font(.spFootnote).foregroundStyle(Theme.mute)454 }455 }.padding(.vertical, 6)456 }457 } else if let versionsError { ErrorNotice(error: versionsError) }458 else if model.canOperate { ProgressView() }459 else { Text(String(localized: "Indisponible hors ligne.")).font(.spCallout).foregroundStyle(Theme.mute) }460 }461 .task(id: page.overview?.summary.configVersion) {462 guard model.canOperate else { return }463 do { versions = try await AgentsAPI(model.env.client).configVersions(page.id); versionsError = nil } catch { versionsError = error }464 }465 }466}467468struct JobRow: View {469 let job: AgentJob470 var body: some View {471 VStack(alignment: .leading, spacing: 3) {472 HStack(spacing: 8) {473 Text(job.kind).font(.spBody.weight(.medium)).foregroundStyle(Theme.ink)474 Pill(text: job.status.label, tone: job.status.tone)475 if job.deadLettered == true { Pill(text: String(localized: "abandonnée"), tone: .danger) }476 }477 Text([job.createdAt.map(AgentFmt.date), job.attempts.map { a in String(localized: "tentative \(a)/\(job.maxAttempts ?? a)") }].compactMap { $0 }.joined(separator: " · ")).font(.spFootnote).foregroundStyle(Theme.mute)478 if let e = job.error, !e.isEmpty { Text(e).font(.spFootnote).foregroundStyle(Theme.danger).fixedSize(horizontal: false, vertical: true).textSelection(.enabled) }479 }480 .padding(.vertical, 7)481 .accessibilityElement(children: .combine)482 }483}484485// MARK: risk486487struct AgentRiskWorkspace: View {488 @Environment(AppModel.self) private var model489 @Environment(Router.self) private var router490 let page: AgentPageModel491 let store: AgentsStore492 @State private var draft: MandateDraft?493 @State private var draftError: Error?494495 var body: some View {496 if let a = page.agent {497 AgentCard(title: String(localized: "Limites en vigueur")) {498 if let r = a.spotRisk {499 VStack(alignment: .leading, spacing: 0) {500 FieldRow(label: String(localized: "Plafond par ordre — imposé par le signataire sous mandat"), value: r.maxOrderUsd.text + " USD")501 Divider(); FieldRow(label: String(localized: "Plafond de volume par jour — imposé par le signataire sous mandat"), value: r.maxDailyUsd.text + " USD")502 Divider(); FieldRow(label: String(localized: "Ordres par jour — imposé par le signataire sous mandat"), value: String(r.maxOrdersPerDay))503 Divider(); FieldRow(label: String(localized: "Durée d’un mandat"), value: String(localized: "\(r.mandateDays) jours"))504 Divider(); FieldRow(label: String(localized: "Glissement toléré par l’agent · garde du mandat"), value: String(localized: "\(r.slippageBps) pb · \(r.mandateSlippageBps) pb"))505 Divider(); FieldRow(label: String(localized: "Exposition maximale — imposée par le moteur seulement"), value: AgentFmt.number(r.maxExposurePct) + " %")506 Divider(); FieldRow(label: String(localized: "Limite de perte — imposée par le moteur seulement"), value: AgentFmt.number(r.maxLossPct) + " %", tone: .warn)507 }508 Text(String(localized: "La limite de perte n’est pas dans le mandat : le signataire ne peut pas l’imposer. C’est le moteur qui arrête l’agent, et un écart de prix peut la dépasser.")).font(.spFootnote).foregroundStyle(Theme.mute)509 } else if let r = a.perpRisk {510 VStack(alignment: .leading, spacing: 0) {511 FieldRow(label: String(localized: "Levier maximal"), value: "\(r.maxLeverage)×")512 Divider(); FieldRow(label: String(localized: "Exposition brute maximale"), value: AgentFmt.number(r.maxGrossExposureX) + " × " + String(localized: "le capital"))513 Divider(); FieldRow(label: String(localized: "Position maximale par contrat"), value: AgentFmt.number(r.maxPositionX) + " × " + String(localized: "le capital"))514 Divider(); FieldRow(label: String(localized: "Perte maximale par jour"), value: AgentFmt.number(r.maxDailyLossPct) + " %")515 Divider(); FieldRow(label: String(localized: "Perte maximale totale"), value: AgentFmt.number(r.maxTotalLossPct) + " %")516 Divider(); FieldRow(label: String(localized: "Glissement toléré"), value: String(localized: "\(r.slippageBps) pb"))517 Divider(); FieldRow(label: String(localized: "Rééquilibrage minimal"), value: AgentFmt.number(r.minTradePct) + " %")518 }519 } else {520 JSONFields(value: page.overview?.summary.riskLimits ?? a.risk)521 Text(String(localized: "Limites telles qu’enregistrées par le serveur.")).font(.spFootnote).foregroundStyle(Theme.mute)522 }523 }524 mandate(a)525 if case .perp(let d)? = page.detail, let acct = d.account {526 AgentCard(title: String(localized: "Garde-fous du compte PAPIER")) {527 if let h = acct.halt { Notice(tone: .danger, title: String(localized: "Disjoncteur du compte papier déclenché"), message: h) }528 ServerDetail(title: String(localized: "Politique du compte simulé"), value: acct.policy)529 }530 }531 AgentCard(title: String(localized: "Arrêt d’urgence global")) {532 let k = page.overview?.killSwitch ?? store.killSwitch.value533 Text(k == nil ? String(localized: "État inconnu.") : k!.engaged ? String(localized: "ENGAGÉ") + (k!.reason.map { " — " + $0 } ?? "") : String(localized: "Non engagé."))534 .font(.spBody.weight(.medium)).foregroundStyle(k?.engaged == true ? Theme.danger : Theme.ink)535 Button { router.go(.risk) } label: { Label(String(localized: "Risque et limites (mandats, levée de l’arrêt)"), systemImage: AppSection.risk.icon) }.buttonStyle(.spSecondary).accessibilityIdentifier("agent.risk.open")536 }537 }538 }539540 @ViewBuilder private func mandate(_ a: Agent) -> some View {541 AgentCard(title: String(localized: "Mandat")) {542 switch page.detail {543 case .spot(let d): SpotMandateStatusView(detail: d)544 case .perp(let d): PerpLiveBlockView(detail: d)545 default:546 if let m = page.overview?.summary.mandate { FieldRow(label: String(localized: "Mandat en vigueur (\(m.kind))"), value: m.id, mono: true, copyable: true) }547 else { Text(String(localized: "Aucun mandat en vigueur pour cet agent.")).font(.spCallout).foregroundStyle(Theme.mute) }548 }549 if let draft {550 Divider()551 Text(String(localized: "Ce qu’un mandat dirait aujourd’hui (lecture seule, rien n’est préparé)")).font(.spCallout.weight(.semibold))552 if !draft.available { Notice(tone: .info, title: String(localized: "Mandat indisponible pour le moment"), message: [draft.reason, draft.code.map { "(\($0))" }].compactMap { $0 }.joined(separator: " ")) }553 if let s = draft.shape { FieldRow(label: String(localized: "Forme canonique"), value: s, mono: true) }554 if let f = draft.fields { JSONFields(value: f) }555 if let p = draft.pending { FieldRow(label: String(localized: "Mandat en attente"), value: "\(p.mandateId) · \(p.state)", mono: true) }556 } else if let draftError, model.canOperate { ErrorNotice(error: draftError) }557 }558 .task(id: store.revision) {559 guard model.canOperate else { return }560 do { draft = try await AgentsAPI(model.env.client).mandateDraft(page.id, locale: "fr"); draftError = nil } catch { draftError = error }561 }562 }563}564565/** The spot mandate as the SIGNER reports it now. */566struct SpotMandateStatusView: View {567 @Environment(AppModel.self) private var model568 let detail: SpotAgentDetail569570 private func amount(_ units: String, asset: String) -> String {571 let h = detail.agent.holdings?.first { $0.asset == asset }572 guard let dec = model.network(detail.agent.network)?.asset(asset)?.decimals, let u = try? BaseUnits(units) else { return units + " " + String(localized: "(unités de base)") + (h.map { " " + $0.assetSymbol } ?? "") }573 return Money.exact(u.formatted(decimals: dec)) + " " + (h?.assetSymbol ?? "")574 }575576 var body: some View {577 if let m = detail.mandateStatus {578 let state: (String, Tone) = m.revoked ? (String(localized: "Révoqué"), .danger) : m.expired ? (String(localized: "Expiré"), .warn) : m.active ? (String(localized: "Actif chez le signataire"), .ok) : (String(localized: "Inactif"), .neutral)579 VStack(alignment: .leading, spacing: 0) {580 FieldRow(label: String(localized: "État rapporté par le signataire"), value: state.0, tone: state.1).accessibilityIdentifier("agent.mandate.state")581 Divider()582 FieldRow(label: String(localized: "Expiration"), value: AgentFmt.date(m.expiry), tone: m.expired ? .warn : nil)583 Divider()584 FieldRow(label: String(localized: "Ordres aujourd’hui"), value: (m.today?.orders.map(String.init) ?? "—") + " / \(m.maxOrdersPerDay)")585 ForEach(m.maxOrder.keys.sorted(), id: \.self) { asset in586 Divider()587 let sold = m.today?.sold?[asset]588 FieldRow(label: String(localized: "\(detail.agent.holdings?.first { $0.asset == asset }?.assetSymbol ?? asset) — plafond par ordre · par jour · vendu aujourd’hui"),589 value: [amount(m.maxOrder[asset] ?? "0", asset: asset), m.maxDaily[asset].map { amount($0, asset: asset) } ?? "—", sold.map { amount($0, asset: asset) } ?? String(localized: "rien")].joined(separator: " · "))590 }591 }592 } else {593 Text(String(localized: "Aucun mandat en vigueur chez le signataire pour cet agent.")).font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("agent.mandate.none")594 }595 }596}597598/** Where a perp agent is (or was) live, under which mandate, and why it left — as served. */599struct PerpLiveBlockView: View {600 let detail: PerpAgentDetail601 var body: some View {602 if let l = detail.live {603 if !l.available { Notice(tone: .info, title: String(localized: "Mandats de dérivés indisponibles sur ce serveur"), message: l.reason) }604 VStack(alignment: .leading, spacing: 0) {605 FieldRow(label: String(localized: "État"), value: l.active ? (l.paused ? String(localized: "Actif, en pause (positions conservées)") : String(localized: "Actif")) : String(localized: "Aucun mandat réel actif"), tone: l.active ? .ok : nil)606 if let n = l.network { Divider(); FieldRow(label: String(localized: "Réseau de la plateforme"), value: n == "mainnet" ? String(localized: "MAINNET") : n == "testnet" ? String(localized: "TESTNET (argent de test)") : n) }607 if let m = l.mandateId { Divider(); FieldRow(label: String(localized: "Mandat"), value: m, mono: true, copyable: true) }608 if let s = l.since { Divider(); FieldRow(label: String(localized: "Depuis"), value: AgentFmt.date(s)) }609 if let c = l.capital { Divider(); FieldRow(label: String(localized: "Valeur du compte à l’approbation"), value: Money.exact(c) + " USDC") }610 if let e = l.exit { Divider(); FieldRow(label: String(localized: "Sortie du réel"), value: "\(e.reason) (\(e.code))" + (e.ts.map { " · " + AgentFmt.date($0) } ?? ""), tone: .warn) }611 }612 ForEach(Array((l.holds ?? []).enumerated()), id: \.offset) { _, h in Notice(tone: .warn, title: String(localized: "Retenue sur \(h.symbol)"), message: "\(h.reason) (\(h.code))") }613 ServerDetail(title: String(localized: "Mandat et compteurs rapportés par le signataire"), value: l.signer)614 } else {615 Text(String(localized: "Aucune information de mandat réel pour cet agent.")).font(.spCallout).foregroundStyle(Theme.mute)616 }617 }618}619