Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/TradingAgents/MarketMakingView.swift3// Description: Market making as the backend exposes it: the quoting session of ONE mode (paper = simulated fills on real books; live = a venue network), its dead-man switch, breakers, attribution and fills, the owner commands that always work (pull the quotes, flatten the inventory), the go-live checklist with the laboratory's evidence shown as it is, the quoting mandate and its revocation, and the server locks. With a lock closed the live controls are absent.4import SwiftUI5import SPWalletCore67@MainActor @Observable final class MarketMakingStore {8 let model: AppModel9 let api: AgentsAPI10 let id: String11 var mode: AgentMode = .paper { didSet { if oldValue != mode { Task { await refresh() } } } }12 private(set) var views: [AgentMode: MarketMakingView] = [:]13 private(set) var performance: [AgentMode: MarketMakingPerformance] = [:]14 private(set) var fills: [AgentMode: [MarketMakingFill]] = [:]15 private(set) var evidence: MarketMakingEvidence?16 private(set) var bounds: MarketMakingBounds?17 private(set) var errors: [String: String] = [:]18 private(set) var busy: String?19 var actionError: String?20 var notice: String?2122 init(model: AppModel, id: String) { self.model = model; self.id = id; api = AgentsAPI(model.client) }2324 var view: MarketMakingView? { views[mode] }25 private func note<T: Sendable>(_ key: String, _ r: Result<T, Error>) -> T? {26 switch r { case .success(let v): errors[key] = nil; return v; case .failure(let e): errors[key] = model.describe(e); return nil }27 }2829 func refresh() async {30 guard model.phase == .signedIn else { return }31 let api = api, id = id, m = mode32 async let v = Result.catching { try await api.marketMaking(id, mode: m) }33 async let p = Result.catching { try await api.marketMakingPerformance(id, mode: m) }34 async let f = Result.catching { try await api.marketMakingFills(id, mode: m, limit: 200).value }35 if let x = note("view.\(m.rawValue)", await v) { views[m] = x }36 if let x = note("performance.\(m.rawValue)", await p) { performance[m] = x }37 if let x = note("fills.\(m.rawValue)", await f) { fills[m] = x }38 if evidence == nil, let x = note("evidence", await Result.catching { try await api.marketMakingEvidence(locale: "fr") }) { evidence = x }39 if bounds == nil, let x = note("bounds", await Result.catching { try await api.marketMakingBounds() }) { bounds = x }40 }4142 func poll() async {43 await refresh()44 while !Task.isCancelled {45 try? await Task.sleep(for: .seconds(view?.session?.state == "running" ? 5 : 20))46 guard !Task.isCancelled else { return }47 if AppActivity.isActive, !model.isOffline, busy == nil { await refresh() }48 }49 }5051 private func run(_ name: String, requireSession: Bool = true, _ body: () async throws -> String?) async {52 guard busy == nil, requireSession ? model.phase == .signedIn : model.canOperate else { return }53 busy = name; actionError = nil; notice = nil54 do { notice = try await body() } catch { actionError = model.describe(error) }55 busy = nil56 await refresh()57 }5859 private func taken(_ r: MarketMakingCommandResult) -> String {60 let how = switch r.taken { case "engine": "prise par le moteur de la session"; case "queued": "mise en file pour le moteur"; case "direct": "exécutée directement sur la plateforme"; case "nothing": "sans objet : aucune session active et rien sur la plateforme"; default: r.taken }61 return "Commande « \(r.command) » \(how).\(r.note.map { " \($0)" } ?? "")"62 }63 /// Works under every lock and halt; no passkey.64 func pull() async { let api = api, id = id; await run("pull") { self.taken(try await api.pullQuotes(id)) } }65 func flatten() async { let api = api, id = id; await run("flatten") { self.taken(try await api.flattenInventory(id)) } }66 func resume() async { let api = api, id = id; await run("resume", requireSession: false) { self.taken(try await api.resumeQuoting(id)) } }6768 func acknowledge(_ ack: MarketMakingAcknowledgement) async {69 let api = api, id = id70 await run("ack", requireSession: false) { let g = try await api.acknowledgeGoLive(id, ack, locale: "fr"); return "Étape enregistrée. Prochaine étape selon le serveur : \(g.nextStep?.id ?? "aucune")." }71 }7273 /// Final, no passkey: the signer's copy is revoked first; resting quotes are cancelled.74 func revokeMandate(_ mandateId: String) async {75 let mandates = MandatesAPI(model.client)76 await run("revoke") {77 let r = try await mandates.revoke(id: mandateId, cancelOpenOrders: true, detail: "révoqué par le propriétaire depuis l’app macOS")78 return "Mandat de cotation : \(r.mandate.state) / \(r.mandate.phase). \(r.cancelled) annulation(s) demandée(s)." + (r.signerRevoked == false ? " Le signataire n’a PAS encore confirmé sa révocation\(r.signerError.map { " (\($0))" } ?? "") : elle sera redemandée." : r.signerRevoked == true ? " Révoqué au signataire." : "")79 }80 }8182 func recover() async {83 let api = api84 await run("recover", requireSession: false) { let r = try await api.recoverMarketMaking(); return "Réconciliation : \(r.adopted.count) adopté(s), \(r.revoked.count) révoqué(s), \(r.pending.count) en attente." }85 }86}8788struct MarketMakingSection: View {89 let model: AppModel90 let d: AgentDetailStore91 let store: AgentsStore92 @State private var mm: MarketMakingStore?93 @State private var confirm: String?94 @State private var ackEvidence = false95 @State private var ackJurisdiction = false96 @State private var testnetNote = ""97 @State private var ackTestnet = false9899 var body: some View {100 Group {101 if let mm { content(mm) } else { ProgressView() }102 }103 .task { if mm == nil { mm = MarketMakingStore(model: model, id: d.id) }; await mm?.poll() }104 }105106 @ViewBuilder private func content(_ mm: MarketMakingStore) -> some View {107 @Bindable var mm = mm108 let network = mm.view?.session?.network ?? mm.view?.goLive.network109 let kind = ModeKind(mm.mode, liveNetwork: network)110 if let ev = mm.evidence { Banner(.warning, "Énoncé du laboratoire sur la tenue de marché : \(ev.statement)") }111 Card("Session de cotation") {112 Picker("Mode", selection: $mm.mode) { Text("PAPIER").tag(AgentMode.paper); Text("RÉEL").tag(AgentMode.live) }.pickerStyle(.segmented).frame(maxWidth: 260).labelsHidden()113 ModeHeaderBand(kind: kind)114 if let v = mm.view {115 if let s = v.session { session(s, kind) } else { Text("Aucune session en cours dans ce mode.").foregroundStyle(.secondary) }116 Divider()117 Text("Commandes du propriétaire — sans passkey ; retirer et aplanir fonctionnent sous tous les verrous et arrêts").font(.caption).foregroundStyle(.secondary)118 HStack(spacing: 10) {119 ModeButton(title: "Retirer les cotations", kind: kind, systemImage: "arrow.uturn.backward", role: .destructive) { confirm = "pull" }120 ModeButton(title: "Retirer et aplanir l’inventaire", kind: kind, systemImage: "arrow.down.to.line", role: .destructive) { confirm = "flatten" }121 if v.session?.state == "running", v.session?.status?.manual != nil { ModeButton(title: "Reprendre la cotation", kind: kind, systemImage: "play.fill") { Task { await mm.resume() } }.disabled(!model.canOperate) }122 if mm.busy != nil { ProgressView().controlSize(.small) }123 Spacer(minLength: 0)124 }.disabled(model.phase != .signedIn || mm.busy != nil)125 if !v.sessions.isEmpty {126 DisclosureGroup("Sessions passées de ce mode (\(v.sessions.count))") {127 VStack(alignment: .leading, spacing: 4) {128 ForEach(v.sessions.prefix(30)) { s in129 Text("\(Fmt.date(s.startedAt)) → \(Fmt.date(s.endedAt)) · \(s.instrument) · \(s.state)\(s.endReason.map { " — \($0)" } ?? "") · PnL \(s.pnl?.totalUsd ?? "—") USD · \(s.label)").font(.caption).textSelection(.enabled)130 }131 }.padding(.top, 6).modeFramed(kind)132 }133 }134 } else { Unavailable(what: "Session", error: mm.errors["view.\(mm.mode.rawValue)"]) }135 if let n = mm.notice { Banner(.info, n) }136 if let e = mm.actionError { Banner(.danger, e) }137 }138 .confirmationDialog(confirm == "pull" ? "Retirer toutes les cotations ?" : "Retirer les cotations et aplanir l’inventaire ?", isPresented: Binding(get: { confirm != nil }, set: { if !$0 { confirm = nil } }), titleVisibility: .visible) {139 Button(confirm == "pull" ? "Retirer · \(kind.short)" : "Retirer et aplanir · \(kind.short)", role: .destructive) { let c = confirm; Task { if c == "pull" { await mm.pull() } else { await mm.flatten() } } }140 Button("Annuler", role: .cancel) {}141 } message: { Text(confirm == "pull" ? "Toutes les cotations au repos sont retirées maintenant. L’inventaire est conservé." : "Les cotations sont retirées et l’inventaire est fermé avec des ordres réducteurs, au prix du marché (résultat non garanti).") }142143 Card(mm.mode == .paper ? "Attribution sur papier" : "Attribution en réel", trailing: AnyView(ModeTag(kind: kind))) {144 if let p = mm.performance[mm.mode] {145 let k = ModeKind(p.mode, liveNetwork: network)146 VStack(alignment: .leading, spacing: 8) {147 Text(p.label).font(.callout.weight(.medium)).textSelection(.enabled)148 Text("\(p.sessions) session(s) · \(p.fills) exécution(s) · volume \(Fmt.amount(p.volumeUsd, maxFraction: 2)) USD").font(.caption).foregroundStyle(.secondary)149 LazyVGrid(columns: [GridItem(.adaptive(minimum: 170), alignment: .topLeading)], alignment: .leading, spacing: 10) {150 ModeFigure(label: "PnL total", value: "\(Fmt.amount(p.attribution.totalUsd, maxFraction: 2)) USD", kind: k)151 ModeFigure(label: "Capture d’écart", value: "\(Fmt.amount(p.attribution.spreadCaptureUsd, maxFraction: 2)) USD", kind: k)152 ModeFigure(label: "PnL d’inventaire", value: "\(Fmt.amount(p.attribution.inventoryPnlUsd, maxFraction: 2)) USD", kind: k)153 ModeFigure(label: "Frais", value: "\(Fmt.amount(p.attribution.feesUsd, maxFraction: 2)) USD", kind: k)154 ModeFigure(label: "Financement", value: "\(Fmt.amount(p.attribution.fundingUsd, maxFraction: 2)) USD", kind: k)155 ModeFigure(label: "Par volume", value: p.attribution.bpsOfVolume.map { "\($0) pb" }, kind: k, reason: "volume nul")156 }157 ForEach(p.markouts, id: \.horizon) { m in Text("Markout \(m.horizon) : \(m.meanBps.map { "\($0) pb en moyenne" } ?? "indisponible") sur \(m.fills) exécution(s)").font(.callout).monospacedDigit() }158 if let n = p.note { Text(n).font(.caption).foregroundStyle(.secondary).textSelection(.enabled) }159 }.modeFramed(k)160 } else { Unavailable(what: "Attribution", error: mm.errors["performance.\(mm.mode.rawValue)"]) }161 }162163 Card(mm.mode == .paper ? "Exécutions SIMULÉES" : "Exécutions réelles", trailing: AnyView(ModeTag(kind: kind))) {164 if let f = mm.fills[mm.mode] {165 if f.isEmpty { Text("Aucune exécution dans ce mode.").foregroundStyle(.secondary) }166 else {167 Table(f) {168 TableColumn("Date") { x in Text(Fmt.dateSeconds(x.ts)).monospacedDigit() }.width(150)169 TableColumn("Sens") { x in Text(x.side + (x.reduce ? " · réducteur" : "") + (x.maker ? " · maker" : " · taker")) }.width(150)170 TableColumn("Prix") { x in Text(Fmt.amount(x.price, maxFraction: 6)).monospacedDigit() }.width(110)171 TableColumn("Taille") { x in Text(Fmt.amount(x.size, maxFraction: 8)).monospacedDigit() }.width(110)172 TableColumn("Frais") { x in Text(Fmt.amount(x.fee, maxFraction: 6)).monospacedDigit() }.width(90)173 TableColumn("Markouts 1 s / 10 s / 60 s (pb)") { x in Text("\(x.markoutsBps?.s1 ?? "—") / \(x.markoutsBps?.s10 ?? "—") / \(x.markoutsBps?.s60 ?? "—")" + (x.markoutsDone == false ? " (en cours)" : "")).monospacedDigit() }174 }.frame(height: min(CGFloat(f.count) * 28 + 34, 380)).modeFramed(kind)175 }176 } else { Unavailable(what: "Exécutions", error: mm.errors["fills.\(mm.mode.rawValue)"]) }177 }178 mandateCard(mm)179 goLiveCard(mm)180 boundsCard(mm)181 }182183 // MARK: session184185 @ViewBuilder private func session(_ s: MarketMakingSession, _ kind: ModeKind) -> some View {186 let k = ModeKind(s.mode, liveNetwork: s.network)187 VStack(alignment: .leading, spacing: 6) {188 Text(s.label).font(.callout.weight(.semibold)).foregroundStyle(k.color).textSelection(.enabled)189 Field(label: "Instrument / état", value: "\(s.instrument) · \(s.state)\(s.status?.phase.map { " · \($0)" } ?? "")", emphasis: true)190 if s.stale { Banner(.warning, "Session en cours mais son travailleur n’a rien écrit depuis 20 secondes. Dernier battement \(Fmt.relative(s.heartbeatAt)).") }191 if let st = s.status {192 if let r = st.reason, !r.isEmpty { Field(label: "Raison", value: r) }193 Field(label: "Inventaire", value: "\(st.position ?? "—")\(st.positionUsd.map { " (\($0) USD)" } ?? "") · milieu \(st.mid ?? "—")")194 if let m = st.manual { Field(label: "Commande manuelle", value: m == "pull" ? "cotations retirées par vous" : m == "flatten" ? "aplanissement demandé par vous" : m) }195 if let l = st.lock { Field(label: "Verrou", value: l) }196 if let b = st.activeBreakers, !b.isEmpty { Field(label: "Disjoncteurs actifs", value: b.joined(separator: ", ")) }197 if let b = st.blockedSides, !b.isEmpty { Field(label: "Côtés bloqués", value: b.joined(separator: ", ")) }198 if let h = st.halted, !h.isNull, h.boolValue != false { Field(label: "Arrêt", value: JSONFlat.text(h)) }199 if let sw = st.switch {200 Field(label: "Interrupteur d’homme mort", value: "\(sw.armed ? "ARMÉ" : "non armé")\(sw.deadline.map { " · annulation automatique par la plateforme \(Fmt.relative($0)) sans renouvellement" } ?? "")\(sw.lapsesToday.map { " · \($0) déclenchement(s) aujourd’hui" } ?? "")\(sw.venueTriggersPerDay.map { " (plateforme : \($0)/jour" + (sw.signerStopsAt.map { ", le signataire s’arrête à \($0))" } ?? ")") } ?? "")")201 if s.mode == .live, !sw.armed, s.state == "running" { Banner(.danger, "L’interrupteur d’homme mort n’est PAS armé alors que la session réelle est en cours.") }202 }203 if let m = st.mandate { Field(label: "Mandat de cotation", value: "\(m.id) · \(m.phase ?? "—") · expire \(Fmt.relative(m.expiresAt)) · cotations restantes : \(m.quotesLeftHour.map(String.init) ?? "—")/h, \(m.quotesLeftDay.map(String.init) ?? "—")/j") }204 if let q = st.quotes, !q.isEmpty {205 Text("Cotations au repos (\(q.count))").font(.caption.weight(.semibold))206 ForEach(q, id: \.clientId) { x in Text("\(x.side) \(x.size) @ \(x.price) · \(x.state)\(x.distanceBps.map { " · à \($0) pb du milieu" } ?? "")\(x.ageMs.map { " · \(Int($0 / 1000)) s" } ?? "")").font(Theme.monoSmall) }207 }208 }209 if let p = s.pnl {210 HStack(spacing: 10) {211 ModeFigure(label: "PnL de la session", value: p.totalUsd.map { "\($0) USD" }, kind: k, reason: "non rapporté")212 ModeFigure(label: "Capture d’écart", value: p.spreadCaptureUsd.map { "\($0) USD" }, kind: k, reason: "non rapporté")213 ModeFigure(label: "Frais", value: p.feesUsd.map { "\($0) USD" }, kind: k, reason: "non rapporté")214 ModeFigure(label: "Exécutions", value: p.fills.map(String.init), kind: k, reason: "non rapporté")215 }216 }217 if let b = s.breakers, !b.isEmpty {218 DisclosureGroup("Disjoncteurs déclenchés (\(b.count))") { VStack(alignment: .leading, spacing: 3) { ForEach(Array(b.enumerated()), id: \.offset) { _, x in Text("\(Fmt.dateSeconds(x.ts)) · \(x.code) → \(x.action)").font(.caption) } }.padding(.top, 6) }219 }220 if let r = s.refusals, !r.isNull { DisclosureGroup("Refus et budget") { VStack(alignment: .leading) { JSONFacts(value: r, depth: 2); JSONFacts(value: s.budget, depth: 2, empty: "") }.padding(.top, 6) } }221 }.modeFramed(k)222 }223224 // MARK: mandate225226 private func closedLock(_ mm: MarketMakingStore, network: String?) -> MarketMakingBounds.Lock? {227 guard let l = mm.bounds?.locks else { return nil }228 return network == "mainnet" ? l.mainnet.lock : network == "testnet" ? l.testnet.lock : (l.mainnet.lock != nil && l.testnet.lock != nil ? l.testnet.lock : nil)229 }230231 @ViewBuilder private func mandateCard(_ mm: MarketMakingStore) -> some View {232 Card("Mandat de cotation") {233 if let m = (mm.views[.live] ?? mm.view)?.mandate {234 let kind = ModeKind(.live, liveNetwork: mm.view?.goLive.network)235 VStack(alignment: .leading, spacing: 5) {236 Field(label: "Mandat", value: m.id, mono: true)237 Field(label: "État / phase", value: "\(m.state) · \(m.phase ?? "—")", emphasis: true)238 Field(label: "Expiration", value: Fmt.date(m.expiresAt))239 Field(label: "Empreinte", value: m.hash, mono: true)240 if let i = m.integrity { Banner(.danger, "L’approbation enregistrée de ce mandat ne se vérifie plus : \(i)") }241 if let mx = m.quoting?.maxima, !mx.isEmpty { Text("Maxima de cotation").font(.caption.weight(.semibold)); ForEach(mx.keys.sorted(), id: \.self) { k in Field(label: k, value: mx[k]!, mono: true) } }242 if let sec = m.quoting?.section, !sec.isNull { DisclosureGroup("Section de cotation approuvée") { JSONFacts(value: sec, depth: 3).padding(.top, 6) } }243 if let sg = m.signer, !sg.isNull { DisclosureGroup("Ce que le signataire rapporte") { JSONFacts(value: sg, depth: 3).padding(.top, 6) } }244 }.modeFramed(kind)245 if m.state == "active" || m.phase == "active" || m.phase == "wind_down" {246 HStack(alignment: .top) {247 Text("Révoquer est immédiat, définitif et sans passkey : les cotations sont annulées, seuls des ordres réducteurs restent possibles.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)248 Spacer()249 Button(role: .destructive) { Task { await mm.revokeMandate(m.id); await store.refresh() } } label: { Label("Révoquer le mandat", systemImage: "xmark.shield.fill").fontWeight(.semibold) }250 .buttonStyle(.borderedProminent).tint(Theme.negative).controlSize(.large).disabled(model.phase != .signedIn || mm.busy != nil)251 }252 }253 } else { Text("Aucun mandat de cotation pour cet agent.").foregroundStyle(.secondary) }254 Text("Un mandat de cotation autorise le signataire à signer des lots de cotations « post-only » et l’annulation programmée de la plateforme (au plus 7 jours ; homme mort ≤ 120 s). Il ne permet ni retrait ni transfert.").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)255 HStack { Spacer(); Button("Réconcilier les mandats de cotation") { Task { await mm.recover() } }.disabled(!model.canOperate || mm.busy != nil).help("Règle une approbation dont la réponse a été perdue et révoque les mandats orphelins au signataire.") }256 }257 }258259 // MARK: go-live checklist260261 @ViewBuilder private func goLiveCard(_ mm: MarketMakingStore) -> some View {262 Card("Liste de contrôle du passage en réel") {263 if let g = mm.view?.goLive {264 let lock = closedLock(mm, network: g.network), locks = mm.bounds?.locks265 let allClosed = locks.map { $0.mainnet.lock != nil && $0.testnet.lock != nil } ?? false266 Field(label: "Réseau visé", value: g.network ?? "—")267 ForEach(g.steps) { s in268 HStack(alignment: .top, spacing: 8) {269 Image(systemName: s.done ? "checkmark.circle.fill" : "circle").foregroundStyle(s.done ? Theme.positive : .secondary)270 VStack(alignment: .leading, spacing: 1) {271 Text(stepTitle(s.id)).fontWeight(.medium)272 if !s.done, let m = s.missing { Text(m).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true).textSelection(.enabled) }273 }274 }275 }276 if let locks {277 Divider()278 LockRow(name: "tenue de marché · mainnet", open: locks.mainnet.lock == nil, reason: locks.mainnet.lock.map { "\($0.message) [\($0.setting)]" } ?? "réglages consultés : \(locks.mainnet.consulted.joined(separator: ", "))")279 LockRow(name: "tenue de marché · testnet", open: locks.testnet.lock == nil, reason: locks.testnet.lock.map { "\($0.message) [\($0.setting)]" } ?? "réglages consultés : \(locks.testnet.consulted.joined(separator: ", "))")280 } else if let e = mm.errors["bounds"] { Banner(.warning, "État des verrous indisponible : \(e)") }281 Divider()282 if locks == nil || allClosed || lock != nil {283 Label(locks == nil ? "Les verrous du serveur ne sont pas connus : aucune commande de passage en réel n’est proposée." : "Le serveur a fermé la tenue de marché réelle\(lock.map { " : \($0.message)" } ?? "."). Aucune commande de passage en réel n’est proposée.", systemImage: "lock.fill").foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)284 } else if let next = g.nextStep { nextStep(next, mm) }285 else if g.ready { Banner(.info, "La liste de contrôle est complète selon le serveur. L’agent se démarre en réel depuis « Cycle de vie », sous le mandat de cotation en vigueur.") }286 } else { Unavailable(what: "Liste de contrôle", error: mm.errors["view.\(mm.mode.rawValue)"]) }287 }288 }289290 private func stepTitle(_ id: String) -> String {291 switch id {292 case "paper": "Session sur papier d’une durée suffisante"293 case "evidence": "Lecture des résultats du laboratoire et de la simulation"294 case "jurisdiction": "Avis de juridiction"295 case "testnet": "Essai sur le réseau de test"296 case "mandate": "Mandat de cotation approuvé avec la passkey"297 case "locks": "Verrous du serveur ouverts"298 default: id299 }300 }301302 @ViewBuilder private func nextStep(_ s: MarketMakingGoLive.Step, _ mm: MarketMakingStore) -> some View {303 switch s.id {304 case "paper":305 Text("Prochaine étape : faire tourner l’agent sur PAPIER\(mm.evidence.map { " au moins \(Int($0.minPaperMinutes)) minutes" } ?? "") (Cycle de vie → Démarrer · PAPIER).").font(.callout).foregroundStyle(.secondary)306 case "evidence":307 if let ev = mm.evidence {308 Text("Résultats du laboratoire et de la simulation, tels qu’ils sont").font(.callout.weight(.semibold))309 Text(ev.statement).fixedSize(horizontal: false, vertical: true).textSelection(.enabled).padding(10).frame(maxWidth: .infinity, alignment: .leading).background(Theme.warning.opacity(0.1), in: RoundedRectangle(cornerRadius: 8))310 DisclosureGroup("Détail des résultats (backtest et simulation — jamais une promesse)") { JSONFacts(value: ev.evidence, depth: 3).padding(.top, 6).modeFramed(ModeKind(.research)) }311 AckToggle(isOn: $ackEvidence, text: "J’ai lu ces résultats, y compris lorsqu’ils sont négatifs, et je comprends que la tenue de marché réelle peut perdre de l’argent.")312 HStack { Spacer(); Button("Enregistrer cette lecture") { Task { await mm.acknowledge(.evidence(displayed: ev)); ackEvidence = false } }.disabled(!ackEvidence || !model.canOperate || mm.busy != nil) }313 } else { Unavailable(what: "Résultats du laboratoire", error: mm.errors["evidence"]) }314 case "jurisdiction":315 if let ev = mm.evidence {316 Text(ev.jurisdiction.text).font(.callout).fixedSize(horizontal: false, vertical: true).textSelection(.enabled).padding(10).frame(maxWidth: .infinity, alignment: .leading).background(Color.secondary.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))317 AckToggle(isOn: $ackJurisdiction, text: "J’ai lu l’avis de juridiction et je l’accepte.")318 HStack { Spacer(); Button("Enregistrer l’acceptation") { Task { await mm.acknowledge(.jurisdiction(displayed: ev)); ackJurisdiction = false } }.disabled(!ackJurisdiction || !model.canOperate || mm.busy != nil) }319 } else { Unavailable(what: "Avis de juridiction", error: mm.errors["evidence"]) }320 case "testnet":321 TextField("Note sur votre essai sur le réseau de test (facultative)", text: $testnetNote, axis: .vertical).lineLimit(1...3)322 AckToggle(isOn: $ackTestnet, text: "J’atteste avoir moi-même fait tourner cet agent sur le réseau de test de la plateforme.")323 HStack { Spacer(); Button("Enregistrer l’attestation") { Task { await mm.acknowledge(.testnet(note: testnetNote)); ackTestnet = false } }.disabled(!ackTestnet || !model.canOperate || mm.busy != nil) }324 case "mandate":325 Banner(.warning, "Le mandat de cotation ne peut pas être vérifié par cette version de l’app : sa forme signée et sa section de cotation ne sont pas encore recalculées localement avant la passkey. L’app ne propose donc PAS de l’approuver, et il n’existe aucun contournement ici.")326 default:327 Text("Prochaine étape selon le serveur : \(stepTitle(s.id))\(s.missing.map { " — \($0)" } ?? "").").font(.callout).foregroundStyle(.secondary)328 }329 }330331 // MARK: bounds332333 @ViewBuilder private func boundsCard(_ mm: MarketMakingStore) -> some View {334 Card("Bornes de la tenue de marché (serveur)") {335 if let b = mm.bounds {336 DisclosureGroup("Maxima que le signataire applique à un mandat de cotation") { JSONFacts(value: .object(b.signer), depth: 3).padding(.top, 6) }337 DisclosureGroup("Bornes de la section de cotation") { JSONFacts(value: .object(b.section), depth: 3).padding(.top, 6) }338 DisclosureGroup("Disjoncteurs (\(b.breakers.count))") {339 VStack(alignment: .leading, spacing: 3) { ForEach(b.breakers, id: \.code) { x in Text("\(x.code) — par défaut : \(x.default)\(x.alwaysStops ? " · arrête toujours" : "")").font(.callout) } }.padding(.top, 6)340 }341 } else { Unavailable(what: "Bornes", error: mm.errors["bounds"]) }342 }343 }344}345