SPB Git

Repository Public

AgentsHomeView.swift 20.5 KB 365 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Features/TradingAgents/AgentsHomeView.swift10// Description      : Root of the trading-agent section: the global kill switch11//                    (state, one-tap engage with a confirmation, never a12//                    passkey; released in the Risk section), the runtime of the13//                    agent workers, and every agent with its mode badge14//                    (SIMULATION / PAPIER / RÉEL), its state as served and its15//                    strategy. On iPad the list and the agent page sit side by16//                    side. Offline: the last synchronized list, read-only.17// Module           : Features18// Repository       : https://git.spboucher.ai/sp-wallet-ios19// 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 SPWalletCore9697@MainActor @Observable98final class AgentsStore {99    var agents = Loaded<[Agent]>()100    var killSwitch = Loaded<AgentKillSwitchState>()101    var runtime: AgentRuntimeStatus?102    var runtimeError: Error?103    var listError: Error?104    var busy = false105    var actionError: Error?106    /** Bumped when something changed an agent, so that an open page reloads. */107    var revision = 0108    /** Headline performance of each running agent, read for the agent's own mode (the key carries the mode). */109    var headline: [String: AgentPerformance] = [:]110111    static func headlineKey(_ a: Agent) -> String { a.id + ":" + a.mode.rawValue }112113    /** One mode-scoped read per paper / live agent, on demand (opening the list, pull to refresh) — not on the periodic refresh. */114    func loadHeadlines(_ model: AppModel) async {115        guard model.canOperate, let list = agents.value else { return }116        let api = AgentsAPI(model.env.client)117        for a in list.prefix(20) where a.mode == .paper || a.mode == .live {118            // the Core refuses an answer of another mode (mode_mismatch): such an agent simply has no headline here119            if let p = try? await api.performance(a.id, mode: a.mode), p.mode == a.mode { headline[Self.headlineKey(a)] = p }120        }121    }122123    func load(_ model: AppModel) async {124        if agents.value == nil, let c = await model.env.cache.load([Agent].self, key: AgentsCacheKey.list) { agents.set(cached: c) }125        if killSwitch.value == nil, let c = await model.env.cache.load(AgentKillSwitchState.self, key: AgentsCacheKey.killSwitch) { killSwitch.set(cached: c) }126        guard model.phase == .ready, !model.offlineBrowsing else { agents.live = false; killSwitch.live = false; return }127        let api = AgentsAPI(model.env.client)128        do {129            let list = try await api.list()130            agents.set(live: list); listError = nil131            await model.env.cache.save(list, key: AgentsCacheKey.list)132        } catch { listError = error; agents.live = false }133        do {134            let r = try await api.runtimeStatus()135            runtime = r; runtimeError = nil136            killSwitch.set(live: r.killSwitch)137            await model.env.cache.save(r.killSwitch, key: AgentsCacheKey.killSwitch)138        } catch { runtimeError = error; killSwitch.live = false }139    }140141    /** No passkey: engaging only removes risk. The state shown afterwards is the server's answer. */142    func engageKillSwitch(_ model: AppModel) async {143        guard !busy else { return }144        busy = true; actionError = nil145        defer { busy = false }146        do {147            let k = try await AgentsAPI(model.env.client).engageKillSwitch()148            killSwitch.set(live: k)149            await model.env.cache.save(k, key: AgentsCacheKey.killSwitch)150            revision += 1151        } catch { actionError = error }152        await load(model)153    }154}155156struct AgentsHomeView: View {157    @Environment(AppModel.self) private var model158    @Environment(Router.self) private var router159    @Environment(\.horizontalSizeClass) private var sizeClass160    @State private var store = AgentsStore()161    @State private var selected: String?162    @State private var creating = false163    @State private var confirmation: AgentConfirmation?164165    var body: some View {166        Group {167            if sizeClass == .regular {168                HStack(spacing: 0) {169                    list.frame(width: 380)170                    Divider()171                    if let id = selected { AgentPageView(agentId: id, store: store).id(id) }172                    else { EmptyState(icon: AppSection.agents.icon, title: String(localized: "Choisis un agent"), message: String(localized: "La liste est à gauche. Un nouvel agent démarre toujours en simulation ou en papier, jamais en réel.")).frame(maxWidth: .infinity, maxHeight: .infinity) }173                }174            } else {175                list.navigationDestination(item: $selected) { id in AgentPageView(agentId: id, store: store).wallet(model) }176            }177        }178        .spPage()179        .navigationTitle(AppSection.agents.title)180        .toolbar {181            ToolbarItem(placement: .primaryAction) {182                Button { creating = true } label: { Label(String(localized: "Nouvel agent"), systemImage: "plus") }183                    .disabled(!model.canOperate).accessibilityIdentifier("agents.create")184            }185        }186        .sheet(isPresented: $creating) {187            AgentCreateFlow { id in creating = false; Task { await store.load(model); selected = id } }.wallet(model)188        }189        .agentConfirmation($confirmation)190        .task(id: store.revision) { await store.load(model); await store.loadHeadlines(model) }191        .task {192            // slow refresh while the list is on screen (the server allows 240 requests a minute for the whole app)193            while !Task.isCancelled { try? await Task.sleep(for: .seconds(30)); if model.canOperate { await store.load(model) } }194        }195    }196197    private var list: some View {198        ScrollView {199            VStack(alignment: .leading, spacing: Theme.Space.section) {200                FreshnessBanner()201                if store.agents.isCached, let at = store.agents.savedAt {202                    Notice(tone: .warn, title: String(localized: "Liste du \(AgentFmt.date(at))"), message: String(localized: "Dernière liste synchronisée. Les états et les modes peuvent avoir changé depuis."), icon: "clock.arrow.circlepath")203                        .accessibilityIdentifier("agents.cached")204                }205                killSwitchCard206                if let e = store.actionError { ErrorNotice(error: e) }207                runtimeCard208                agentsCard209            }210            .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12)211            .frame(maxWidth: 760).frame(maxWidth: .infinity)212        }213        .refreshable { await store.load(model); await store.loadHeadlines(model) }214    }215216    // MARK: kill switch217218    @ViewBuilder private var killSwitchCard: some View {219        let k = store.killSwitch.value220        VStack(alignment: .leading, spacing: 12) {221            HStack(alignment: .top, spacing: 10) {222                Image(systemName: k?.engaged == true ? "hand.raised.fill" : "hand.raised").font(.system(size: 22, weight: .semibold)).foregroundStyle(k?.engaged == true ? Theme.danger : Theme.mute)223                VStack(alignment: .leading, spacing: 3) {224                    Text(String(localized: "Arrêt d’urgence global")).font(.spHeadline).foregroundStyle(Theme.ink)225                    if let k {226                        Text(k.engaged ? String(localized: "ENGAGÉ : aucun agent, clé ou mandat ne peut ajouter de risque.") : String(localized: "Non engagé."))227                            .font(.spCallout.weight(k.engaged ? .semibold : .regular)).foregroundStyle(k.engaged ? Theme.danger : Theme.mute).fixedSize(horizontal: false, vertical: true)228                            .accessibilityIdentifier("agents.kill.state")229                        if store.killSwitch.isCached, let at = store.killSwitch.savedAt { Text(String(localized: "État du \(AgentFmt.date(at)), non actualisé.")).font(.spFootnote).foregroundStyle(Theme.warn) }230                    } else if let e = store.runtimeError {231                        Text(String(localized: "État inconnu : ") + ErrorNotice.detail(e)).font(.spCallout).foregroundStyle(Theme.warn).fixedSize(horizontal: false, vertical: true)232                    } else { Text(String(localized: "Lecture de l’état…")).font(.spCallout).foregroundStyle(Theme.mute) }233                }234                Spacer(minLength: 0)235            }236            if let k, k.engaged {237                VStack(alignment: .leading, spacing: 0) {238                    if let r = k.reason { FieldRow(label: String(localized: "Raison"), value: r) }239                    if let at = k.at { Divider(); FieldRow(label: String(localized: "Engagé le"), value: AgentFmt.date(at)) }240                    if let by = k.by { Divider(); FieldRow(label: String(localized: "Par"), value: by) }241                }242                Notice(tone: .danger, title: String(localized: "Arrêt d’urgence engagé"), message: String(localized: "Il se lève uniquement avec ta clé d’accès, dans « Risque et limites »."), icon: "hand.raised.fill")243                    .accessibilityIdentifier("agents.kill.banner")244                Button { router.go(.risk) } label: { Label(String(localized: "Ouvrir Risque et limites"), systemImage: AppSection.risk.icon) }.buttonStyle(.spSecondary).accessibilityIdentifier("agents.kill.risk")245            } else {246                if k?.readOnly == true { Notice(tone: .warn, title: String(localized: "Mode lecture seule engagé"), message: k?.readOnlyReason) }247                Button {248                    confirmation = AgentConfirmation(title: AgentStopAction.engageKillSwitch.title + " ?", message: AgentStopAction.engageKillSwitch.consequence(agent: nil),249                                                     button: String(localized: "Engager maintenant"), destructive: true) { await store.engageKillSwitch(model) }250                } label: { HStack { if store.busy { ProgressView().tint(Theme.onDanger) } else { Image(systemName: "hand.raised.fill") }; Text(String(localized: "Engager l’arrêt d’urgence")) } }251                    .buttonStyle(.spDestructive).disabled(!model.canOperate || store.busy).accessibilityIdentifier("agents.kill.engage")252                Text(String(localized: "Une confirmation, aucune clé d’accès. Lever l’arrêt se fait dans « Risque et limites », avec la clé d’accès."))253                    .font(.spFootnote).foregroundStyle(Theme.mute)254            }255        }256        .spCard()257    }258259    // MARK: runtime260261    @ViewBuilder private var runtimeCard: some View {262        if let r = store.runtime {263            let failing = r.loops.filter { ($0.failures ?? 0) > 0 || $0.lastError != nil }264            AgentCard(title: String(localized: "Moteur des agents")) {265                HStack(spacing: 8) {266                    Pill(text: r.workers.inProcess ? String(localized: "moteur intégré") : String(localized: "moteur séparé"), tone: .neutral, icon: "gearshape.2.fill")267                    Pill(text: String(localized: "\(r.leases.filter(\.active).count) agent(s) pris en charge"), tone: .neutral)268                }269                VStack(alignment: .leading, spacing: 0) {270                    FieldRow(label: String(localized: "File des tâches"), value: String(localized: "\(r.queue.queued) en attente · \(r.queue.running) en cours · \(r.queue.dead24h) abandonnée(s) en 24 h"), tone: r.queue.dead24h > 0 ? .warn : nil)271                    Divider()272                    FieldRow(label: String(localized: "Boucles"), value: failing.isEmpty ? String(localized: "\(r.loops.count) boucles, aucune erreur rapportée") : failing.map { "\($0.name) : \($0.lastError ?? String(localized: "\($0.failures ?? 0) échec(s)"))" }.joined(separator: "\n"),273                             tone: failing.isEmpty ? nil : .warn)274                }275            }276        } else if let e = store.runtimeError, model.canOperate {277            ErrorNotice(error: e)278        }279    }280281    // MARK: agents282283    @ViewBuilder private var agentsCard: some View {284        if let agents = store.agents.value {285            if agents.isEmpty {286                VStack(spacing: 12) {287                    EmptyState(icon: AppSection.agents.icon, title: String(localized: "Aucun agent"), message: String(localized: "Un agent démarre toujours en simulation ou en papier. Passer en réel demande un mandat que tu approuves avec ta clé d’accès."))288                    Button { creating = true } label: { Label(String(localized: "Créer un agent"), systemImage: "plus") }.buttonStyle(.spPrimary).disabled(!model.canOperate).accessibilityIdentifier("agents.create.first")289                }.spCard()290            } else {291                VStack(alignment: .leading, spacing: 0) {292                    SectionHeader(title: String(localized: "Agents (\(agents.count))")).padding(.bottom, 6)293                    ForEach(Array(agents.enumerated()), id: \.element.id) { i, a in294                        if i > 0 { Divider() }295                        Button { selected = a.id } label: { AgentRow(agent: a, performance: store.headline[AgentsStore.headlineKey(a)], selected: sizeClass == .regular && selected == a.id) }296                            .buttonStyle(.plain).accessibilityIdentifier("agents.row.\(a.name)")297                    }298                }.spCard()299            }300        } else if let e = store.listError {301            ErrorNotice(error: e) { Task { await store.load(model) } }302        } else if model.canOperate {303            ProgressView().frame(maxWidth: .infinity, minHeight: 120)304        } else {305            EmptyState(icon: "wifi.slash", title: String(localized: "Aucune liste synchronisée"), message: String(localized: "Les agents s’afficheront après une première synchronisation en ligne."))306        }307    }308}309310struct AgentRow: View {311    let agent: Agent312    var performance: AgentPerformance?313    var selected = false314315    /** Headline figure with its mode in the same sentence. A research agent has no performance: its backtests are simulations. */316    private var headline: (String, Tone)? {317        switch agent.mode {318        case .research: return (String(localized: "Aucune performance en simulation : les backtests sont dans la page de l’agent."), .neutral)319        case .paper, .live:320            guard let p = performance, p.mode == agent.mode, let f = try? ModeGuard.figure(p.totalReturn, heading: agent.mode) else { return nil }321            let name = AgentModeBadge.name(agent.mode)322            guard let v = f.value else { return (String(localized: "Rendement \(name) : indisponible (\(f.reason ?? "—"))"), .neutral) }323            return (String(localized: "Rendement \(name) : \(AgentFmt.percent(fraction: v)) — \(ModeGuard.label(agent.mode))"), agent.mode == .live ? .danger : .warn)324        case .unknown: return nil325        }326    }327328    private var strategyLine: String {329        var parts = [AgentFmt.family(agent.family)]330        if let t = agent.template { parts.append(String(localized: "gabarit \(t)")) }331        if let v = agent.configVersion { parts.append(String(localized: "config v\(v)")) }332        return parts.joined(separator: " · ")333    }334    private var marketLine: String {335        let where_ = agent.resolvedKind == .spot ? String(localized: "coffre sur \(agent.networkName ?? agent.network)") : (agent.networkName ?? agent.venue ?? agent.network)336        let what = agent.universe.isEmpty ? String(localized: "aucun marché") : agent.universe.joined(separator: ", ")337        return what + " · " + where_338    }339340    var body: some View {341        HStack(alignment: .top, spacing: 12) {342            VStack(alignment: .leading, spacing: 5) {343                Text(agent.name).font(.system(size: 16, weight: .semibold)).foregroundStyle(Theme.ink).lineLimit(2).multilineTextAlignment(.leading)344                ModeBadgeView(badge: AgentModeBadge.of(agent)).accessibilityIdentifier("agents.badge.\(agent.name)")345                StateLabelView(state: agent.state)346                Text(strategyLine).font(.spFootnote).foregroundStyle(Theme.mute).lineLimit(2).multilineTextAlignment(.leading)347                Text(marketLine).font(.spFootnote).foregroundStyle(Theme.mute).lineLimit(2).multilineTextAlignment(.leading)348                if let h = headline { Text(h.0).font(.spFootnote.weight(.medium)).foregroundStyle(h.1.color).lineLimit(3).multilineTextAlignment(.leading) }349                if let s = agent.stopReason, !s.isEmpty { Text(String(localized: "Motif d’arrêt : \(s)")).font(.spFootnote).foregroundStyle(Theme.warn).lineLimit(3).multilineTextAlignment(.leading) }350            }351            Spacer(minLength: 4)352            VStack(alignment: .trailing, spacing: 3) {353                Text(Money.exact(agent.capitalUsdc) + " USD").font(.system(size: 14.5, weight: .semibold)).monospacedDigit().foregroundStyle(Theme.ink)354                Text(agent.mode == .live && agent.tradesRealMoney ? String(localized: "budget") : agent.resolvedKind == .spot ? String(localized: "budget prévu") : String(localized: "capital simulé"))355                    .font(.system(size: 11.5)).foregroundStyle(Theme.mute)356                Image(systemName: "chevron.right").font(.system(size: 12, weight: .semibold)).foregroundStyle(Theme.mute).padding(.top, 6)357            }358        }359        .padding(.vertical, 12).padding(.horizontal, selected ? 8 : 0)360        .background(selected ? Theme.elev : Color.clear, in: RoundedRectangle(cornerRadius: Theme.Radius.small, style: .continuous))361        .contentShape(Rectangle())362        .accessibilityElement(children: .combine)363    }364}365
Files main
Menu

Theme