Repository Public
1// SP Wallet iOS2// File: Features/Security/RiskHomeView.swift3// Description: Risk and limits: the state of the unified risk engine exactly as the server reports it — the two global switches4// (trading halt, read-only), the automatic stops, the server locks by name, the exposure of each book, the limits of5// each mode, the log of decisions. Removing authority (engaging a switch, tightening) takes one confirmation and no6// passkey; giving authority back (release, loosening, switching a stop off) goes through the review of the verified7// intent and the passkey. Offline: the last snapshot, dated, with every action disabled.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import SwiftUI12import SPWalletCore1314/** What is being reviewed before a passkey prompt of the risk engine. */15enum RiskReview: Identifiable {16 /** the release of a switch, with the engagement that was on screen when it was prepared */17 case release(RiskSwitchReleaseApproval, displayed: RiskSwitch)18 /** switching automatic stops off, with the settings in force */19 case auto(AutoKillApproval, current: AutoKillSettings)20 var id: String {21 switch self { case .release(let a, _): "release-" + a.approval.digest.hex; case .auto(let a, _): "auto-" + a.approval.digest.hex }22 }23}2425@MainActor @Observable26final class RiskModel {27 var state = Loaded<RiskState>()28 var busy = false29 var actionError: Error?30 var notice: String?31 var review: RiskReview?32 var reviewError: Error?3334 func load(_ app: AppModel) async {35 state = await SnapshotRead.read(RiskState.self, path: "/risk/state", key: "risk-state", app: app, current: state)36 }3738 /** Engage a switch: one confirmation, no passkey. The switch is shown engaged only when the server's answer says so. */39 func engage(_ kind: RiskSwitchKind, reason: String, app: AppModel) async {40 guard !busy else { return }41 busy = true; actionError = nil; notice = nil42 defer { busy = false }43 let api = RiskAPI(app.env.client)44 let text = reason.trimmingCharacters(in: .whitespacesAndNewlines)45 // the reason is recorded with the engagement and named by the release intent: when none is typed, the app says where it came from46 let sent = text.isEmpty ? "owner, SP Wallet iOS" : text47 do {48 _ = kind == .killSwitch ? try await api.engageKillSwitch(reason: sent) : try await api.engageReadOnly(reason: sent)49 notice = kind == .killSwitch ? String(localized: "Arrêt du trading engagé (confirmé par le serveur).") : String(localized: "Mode lecture seule engagé (confirmé par le serveur).")50 } catch { actionError = error }51 await load(app)52 }5354 func prepareRelease(_ kind: RiskSwitchKind, app: AppModel) async {55 guard !busy, let displayed = state.value?.switches.state(of: kind), state.live else { return }56 busy = true; actionError = nil; notice = nil; reviewError = nil57 defer { busy = false }58 do {59 switch try await RiskAPI(app.env.client).prepareRelease(kind, displayed: displayed) {60 case .notEngaged: notice = String(localized: "Le serveur indique que cet interrupteur n’est plus engagé."); await load(app)61 case .approval(let a): review = .release(a, displayed: displayed)62 }63 } catch { actionError = error; await load(app) }64 }6566 /** Switching a stop ON removes authority: session only. Switching one OFF: the server asks for the passkey over an intent. */67 func setAuto(_ key: String, on: Bool, app: AppModel) async {68 guard !busy, let current = state.value?.auto, state.live else { return }69 busy = true; actionError = nil; notice = nil; reviewError = nil70 defer { busy = false }71 let next = current.setting(key, on)72 let api = RiskAPI(app.env.client)73 do {74 switch try await api.prepareAutoKill(next) {75 case .passkeyNotNeeded:76 _ = try await api.setAutoKill(next)77 notice = String(localized: "Arrêts automatiques mis à jour (rien n’est assoupli : session seule).")78 await load(app)79 case .approval(let a): review = .auto(a, current: current)80 }81 } catch { actionError = error }82 }8384 /** The passkey signs the verified challenge. A lost answer is followed by a read of the state — never by a second signature. */85 func approve(_ app: AppModel) async {86 guard !busy, let review else { return }87 busy = true; reviewError = nil88 defer { busy = false }89 let api = RiskAPI(app.env.client)90 do {91 switch review {92 case .release(let a, _):93 let s = try await api.release(a, with: app.env.passkeys)94 notice = s.state(of: a.kind).on ? String(localized: "Le serveur indique que l’interrupteur est toujours engagé.") : String(localized: "Interrupteur levé (confirmé par le serveur).")95 case .auto(let a, _):96 _ = try await api.approveAutoKill(a, with: app.env.passkeys)97 notice = String(localized: "Arrêts automatiques mis à jour (approuvé par la clé d’accès).")98 }99 self.review = nil100 await load(app)101 } catch PasskeyError.cancelled {102 // dismissed: nothing signed, the review stays open103 } catch let e as APIError where e.isOffline {104 self.review = nil105 await load(app)106 actionError = e107 notice = String(localized: "La réponse du serveur a été perdue. L’état affiché ci-dessous vient d’être relu : vérifie-le avant de recommencer.")108 } catch { reviewError = error }109 }110}111112struct RiskHomeView: View {113 @Environment(AppModel.self) private var model114 @State private var risk = RiskModel()115 @State private var engaging: RiskSwitchKind?116 @State private var reason = ""117 @State private var editing: RiskMode?118119 var body: some View {120 @Bindable var risk = risk121 ScrollView {122 VStack(alignment: .leading, spacing: Theme.Space.section) {123 FreshnessBanner()124 if let s = risk.state.value {125 if !risk.state.live { RiskSnapshotNotice(savedAt: risk.state.savedAt, error: risk.state.error) }126 if let n = risk.notice { Notice(tone: .info, title: n).accessibilityIdentifier("risk.notice") }127 if let e = risk.actionError { ErrorNotice(error: e).accessibilityIdentifier("risk.error") }128 switchCard(.killSwitch, s.switches.killSwitch)129 switchCard(.readOnly, s.switches.readOnly)130 autoCard(s.auto)131 locksCard(s.locks)132 exposureSection(s.exposure)133 limitsCard(s.limits.live)134 limitsCard(s.limits.paper)135 decisionsCard(s.decisions)136 linksCard137 Text(String(localized: "État lu \(Fmt.date(ms: s.ts) ?? "—"). L’arrêt du trading n’est PAS l’arrêt d’urgence du signataire (Sécurité), qui ne se lève que sur la machine du signataire."))138 .font(.system(size: 12)).foregroundStyle(Theme.mute)139 } else if let e = risk.state.error { ErrorNotice(error: e) { Task { await risk.load(model) } }.accessibilityIdentifier("risk.loadError") }140 else if model.offlineBrowsing { EmptyState(icon: AppSection.risk.icon, title: String(localized: "État du risque indisponible hors ligne"), message: String(localized: "Aucun instantané n’a été enregistré sur cet appareil.")) }141 else { ProgressView().frame(maxWidth: .infinity).padding(.top, 60) }142 }143 .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 28)144 .frame(maxWidth: 900).frame(maxWidth: .infinity)145 }146 .spPage()147 .navigationTitle(AppSection.risk.title)148 .refreshable { await risk.load(model) }149 .task { await risk.load(model) }150 .alert(engaging.map(RiskWords.switchTitle) ?? "", isPresented: Binding(get: { engaging != nil }, set: { if !$0 { engaging = nil; reason = "" } })) {151 TextField(String(localized: "Raison (facultative)"), text: $reason).accessibilityIdentifier("risk.engage.reason")152 Button(String(localized: "Engager maintenant"), role: .destructive) {153 if let k = engaging { let r = reason; Task { await risk.engage(k, reason: r, app: model) } }154 engaging = nil; reason = ""155 }.accessibilityIdentifier("risk.engage.confirm")156 Button(String(localized: "Annuler"), role: .cancel) { engaging = nil; reason = "" }157 } message: {158 Text((engaging.map(RiskWords.switchEffect) ?? "") + " " + String(localized: "Aucune clé d’accès n’est demandée pour engager. Lever l’interrupteur exigera ta clé d’accès."))159 }160 .sheet(item: $risk.review) { r in RiskReviewSheet(risk: risk, review: r).wallet(model) }161 .sheet(item: $editing) { mode in162 if let v = mode == .live ? risk.state.value?.limits.live : risk.state.value?.limits.paper {163 RiskLimitsEditor(view: v) { Task { await risk.load(model) } }.wallet(model)164 }165 }166 }167168 // MARK: switches169170 private func switchCard(_ kind: RiskSwitchKind, _ s: RiskSwitch) -> some View {171 let prefix = kind == .killSwitch ? "risk.kill" : "risk.readonly"172 return VStack(alignment: .leading, spacing: 10) {173 HStack(alignment: .top) {174 Text(RiskWords.switchTitle(kind)).font(.spHeadline).foregroundStyle(Theme.ink)175 Spacer()176 Pill(text: s.on ? String(localized: "ENGAGÉ") : String(localized: "non engagé"), tone: s.on ? .danger : .neutral, icon: s.on ? "hand.raised.fill" : "circle")177 .accessibilityIdentifier(prefix + ".state")178 }179 Text(RiskWords.switchEffect(kind)).font(.spFootnote).foregroundStyle(Theme.mute)180 if s.on {181 Notice(tone: .danger, title: kind == .killSwitch ? String(localized: "Arrêt du trading actif") : String(localized: "Lecture seule active"),182 message: [RiskWords.date(ms: s.at).map { String(localized: "Engagé le \($0)") } ?? String(localized: "Date d’engagement non fournie"),183 String(localized: "par \(RiskWords.actor(s.by))"),184 s.reason.map { String(localized: "raison : \($0)") } ?? String(localized: "sans raison enregistrée")].joined(separator: " · "),185 icon: "hand.raised.fill")186 .accessibilityIdentifier(prefix + ".banner")187 Button { Task { await risk.prepareRelease(kind, app: model) } } label: {188 HStack { if risk.busy { ProgressView() }; Label(String(localized: "Lever (revue, puis clé d’accès)"), systemImage: "person.badge.key.fill") }189 }190 .buttonStyle(.spSecondary).disabled(!model.canOperate || !risk.state.live || risk.busy).accessibilityIdentifier(prefix + ".release")191 } else {192 Button { engaging = kind } label: {193 Label(kind == .killSwitch ? String(localized: "Engager l’arrêt du trading") : String(localized: "Engager la lecture seule"), systemImage: kind == .killSwitch ? "hand.raised.fill" : "eye.fill")194 }195 .buttonStyle(.spDestructive).disabled(!model.canOperate || risk.busy).accessibilityIdentifier(prefix + ".engage")196 }197 }.spCard()198 }199200 // MARK: automatic stops201202 private func autoCard(_ auto: AutoKillSettings) -> some View {203 VStack(alignment: .leading, spacing: 8) {204 SectionHeader(title: String(localized: "Arrêts automatiques (livre réel)"))205 Text(String(localized: "Conditions mesurées qui engagent l’arrêt du trading d’elles-mêmes. En activer un est libre ; en désactiver un est un assouplissement : revue puis clé d’accès."))206 .font(.spFootnote).foregroundStyle(Theme.mute)207 ForEach(AutoKillSettings.keys, id: \.self) { key in208 let on = auto.value(key)209 VStack(alignment: .leading, spacing: 6) {210 HStack(alignment: .top) {211 Text(RiskWords.autoTitle(key)).font(.system(size: 15, weight: .semibold)).foregroundStyle(Theme.ink)212 Spacer()213 Pill(text: on ? String(localized: "activé") : String(localized: "désactivé"), tone: on ? .ok : .warn, icon: on ? "checkmark.circle.fill" : "minus.circle")214 .accessibilityIdentifier("risk.auto.\(key).state")215 }216 Text(RiskWords.autoExplanation(key)).font(.spFootnote).foregroundStyle(Theme.mute)217 Button(on ? String(localized: "Désactiver (clé d’accès)") : String(localized: "Activer")) { Task { await risk.setAuto(key, on: !on, app: model) } }218 .buttonStyle(.bordered).font(.spCallout.weight(.semibold)).disabled(!model.canOperate || !risk.state.live || risk.busy)219 .accessibilityIdentifier("risk.auto.\(key).toggle")220 }221 .padding(.vertical, 6)222 if key != AutoKillSettings.keys.last { Divider() }223 }224 }.spCard()225 }226227 // MARK: locks228229 private func locksCard(_ locks: [ExecutionLock]) -> some View {230 VStack(alignment: .leading, spacing: 8) {231 SectionHeader(title: String(localized: "Verrous du serveur"))232 Text(String(localized: "Réglages d’environnement du serveur. Ils ne se modifient pas depuis l’app. « fermé » : ce chemin d’exécution réelle est bloqué."))233 .font(.spFootnote).foregroundStyle(Theme.mute)234 if locks.isEmpty { Text(String(localized: "Le serveur n’a listé aucun verrou.")).font(.spCallout).foregroundStyle(Theme.mute) }235 ForEach(locks) { l in236 VStack(alignment: .leading, spacing: 4) {237 HStack {238 Text(l.id).font(.spMono).foregroundStyle(Theme.ink)239 Spacer()240 Pill(text: l.on ? String(localized: "ouvert") : String(localized: "fermé"), tone: l.on ? .warn : .neutral, icon: l.on ? "lock.open.fill" : "lock.fill")241 }242 if let w = l.why { Text(w).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }243 }244 .padding(.vertical, 5).accessibilityElement(children: .combine).accessibilityIdentifier("risk.lock.\(l.id)")245 }246 }.spCard()247 }248249 // MARK: exposure250251 @ViewBuilder private func exposureSection(_ e: RiskState.Exposure) -> some View {252 RiskExposureCard(exposure: e.live, mode: "live")253 RiskExposureCard(exposure: e.liveTestnet, mode: "live")254 RiskExposureCard(exposure: e.paper, mode: "paper")255 }256257 // MARK: limits258259 private func limitsCard(_ v: RiskLimitsView) -> some View {260 let stored = RiskLimitCatalog.fields.filter { RiskLimitText.text(v.stored, $0.key) != nil }.count261 return VStack(alignment: .leading, spacing: 10) {262 HStack {263 Text(String(localized: "Limites")).font(.spHeadline).foregroundStyle(Theme.ink)264 Pill(text: RiskWords.mode(v.mode.rawValue), tone: RiskWords.modeTone(v.mode.rawValue), icon: RiskWords.modeIcon(v.mode.rawValue))265 Spacer()266 }267 if v.ownerOrdersRefused == true || (v.mode == .live && !v.missing.isEmpty) {268 Notice(tone: .warn, title: String(localized: "Limites de capital manquantes : tes ordres réels qui ajoutent du risque sont refusés"),269 message: v.missing.map(RiskLimitCatalog.title).joined(separator: " · "))270 .accessibilityIdentifier("risk.limits.\(v.mode.rawValue).missing")271 }272 if v.automationOrdersRefused == true, let m = v.missingForAutomation, !m.isEmpty {273 Text(String(localized: "Clés d’API et agents : \(m.count) limite(s) manquante(s), leurs ordres réels à risque sont refusés.")).font(.spFootnote).foregroundStyle(Theme.warn)274 }275 Text(String(localized: "\(stored) limite(s) enregistrée(s) par toi sur \(RiskLimitCatalog.fields.count) connues de cette version."))276 .font(.spFootnote).foregroundStyle(Theme.mute).accessibilityIdentifier("risk.limits.\(v.mode.rawValue).count")277 if !v.storedUnknownFields.isEmpty {278 Notice(tone: .warn, title: String(localized: "Limites que cette version ne sait pas modifier"), message: v.storedUnknownFields.joined(separator: ", "))279 }280 NavigationLink { RiskLimitsDetailView(view: v).wallet(model) } label: {281 HStack { Label(String(localized: "Voir chaque limite et son explication"), systemImage: "list.bullet.rectangle").font(.spCallout.weight(.semibold)); Spacer(); Image(systemName: "chevron.right").foregroundStyle(Theme.mute) }282 .frame(minHeight: 44).contentShape(Rectangle())283 }.accessibilityIdentifier("risk.limits.\(v.mode.rawValue).detail")284 Button { editing = v.mode } label: { Label(String(localized: "Modifier les limites"), systemImage: "slider.horizontal.3") }285 .buttonStyle(.spSecondary).disabled(!model.canOperate || !risk.state.live).accessibilityIdentifier("risk.limits.\(v.mode.rawValue).edit")286 }.spCard()287 }288289 // MARK: decisions290291 private func decisionsCard(_ decisions: [RiskDecision]) -> some View {292 VStack(alignment: .leading, spacing: 6) {293 SectionHeader(title: String(localized: "Journal des décisions"))294 if decisions.isEmpty { Text(String(localized: "Le moteur de risque n’a encore évalué aucun ordre.")).font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("risk.decisions.empty") }295 ForEach(decisions.prefix(5)) { d in RiskDecisionRow(decision: d); if d.id != decisions.prefix(5).last?.id { Divider() } }296 NavigationLink { RiskDecisionsView(initial: decisions).wallet(model) } label: {297 HStack { Label(String(localized: "Tout le journal"), systemImage: "list.bullet.clipboard").font(.spCallout.weight(.semibold)); Spacer(); Image(systemName: "chevron.right").foregroundStyle(Theme.mute) }298 .frame(minHeight: 44).contentShape(Rectangle())299 }.accessibilityIdentifier("risk.decisions.all")300 }.spCard()301 }302303 private var linksCard: some View {304 VStack(alignment: .leading, spacing: 0) {305 NavigationLink { MandateListView().wallet(model) } label: { linkRow(String(localized: "Mandats de trading"), "doc.badge.gearshape", String(localized: "Ce qu’une clé d’API ou un agent peut faire, avec chaque limite")) }306 .accessibilityIdentifier("risk.link.mandates")307 Divider()308 NavigationLink { DeveloperKeysView().wallet(model) } label: { linkRow(String(localized: "Clés d’API et webhooks"), "key.horizontal.fill", String(localized: "Créer, restreindre, révoquer ; secrets montrés une seule fois")) }309 .accessibilityIdentifier("risk.link.developer")310 }.spCard()311 }312313 private func linkRow(_ title: String, _ icon: String, _ sub: String) -> some View {314 HStack(spacing: 12) {315 Image(systemName: icon).foregroundStyle(Theme.blue).frame(width: 28)316 VStack(alignment: .leading, spacing: 2) {317 Text(title).font(.system(size: 15.5, weight: .semibold)).foregroundStyle(Theme.ink)318 Text(sub).font(.spFootnote).foregroundStyle(Theme.mute).multilineTextAlignment(.leading)319 }320 Spacer()321 Image(systemName: "chevron.right").foregroundStyle(Theme.mute)322 }.frame(minHeight: 56).contentShape(Rectangle())323 }324}325326extension RiskMode: @retroactive Identifiable { public var id: String { rawValue } }327328/** Says that what follows is a dated snapshot, and why the live read failed. */329struct RiskSnapshotNotice: View {330 let savedAt: Date?331 let error: APIError?332 var body: some View {333 Notice(tone: .warn, title: String(localized: "Instantané, pas l’état en direct"),334 message: [savedAt.map { String(localized: "Enregistré le \($0.formatted(date: .abbreviated, time: .shortened)).") },335 error.map { $0.isOffline ? String(localized: "Serveur injoignable.") : "\($0.message) (\($0.code))" },336 String(localized: "Les actions sont désactivées tant que l’état n’a pas été relu.")].compactMap { $0 }.joined(separator: " "),337 icon: "clock.badge.exclamationmark")338 .accessibilityIdentifier("snapshot.notice")339 }340}341342/** Exposure of ONE book. Books are never merged; an unreadable book shows its error, never zeros. */343struct RiskExposureCard: View {344 let exposure: RiskExposure345 let mode: String346 var body: some View {347 VStack(alignment: .leading, spacing: 0) {348 HStack {349 Text(RiskWords.book(exposure.book)).font(.spHeadline).foregroundStyle(Theme.ink)350 Spacer()351 Pill(text: RiskWords.mode(mode), tone: RiskWords.modeTone(mode), icon: RiskWords.modeIcon(mode))352 }.padding(.bottom, 6)353 if !exposure.isReadable {354 Notice(tone: .warn, title: String(localized: "Exposition illisible pour ce livre"), message: exposure.error ?? String(localized: "Le serveur n’a pas fourni les fonds propres."))355 } else {356 if let errs = exposure.errors, !errs.isEmpty {357 Notice(tone: .warn, title: String(localized: "Chiffres partiels : des sources n’ont pas répondu"), message: errs.joined(separator: " · ")).padding(.bottom, 6)358 }359 FieldRow(label: String(localized: "Fonds propres"), value: Fmt.usd(exposure.equity)); Divider()360 FieldRow(label: String(localized: "Exposition brute"), value: Fmt.usd(exposure.grossExposure)); Divider()361 FieldRow(label: String(localized: "Levier (exposition brute / fonds propres)"), value: exposure.leverage.map { Money.exact($0) + " ×" } ?? String(localized: "non défini (fonds propres non positifs)"))362 if let p = exposure.pnl?.objectValue {363 ForEach(["realizedToday", "unrealizedToday", "realizedInception", "unrealizedInception"].filter { p[$0]?.stringValue != nil }, id: \.self) { k in364 Divider(); FieldRow(label: Self.pnlLabel(k), value: Fmt.usd(p[k]?.stringValue))365 }366 }367 if let assets = exposure.byAsset, !assets.isEmpty {368 Divider()369 Text(String(localized: "Par actif")).spEyebrow().padding(.top, 10)370 ForEach(assets, id: \.asset) { a in FieldRow(label: a.asset, value: String(localized: "long \(Money.exact(a.long)) · court \(Money.exact(a.short)) · net \(Money.exact(a.net)) USD")) }371 }372 if let venues = exposure.byVenue, !venues.isEmpty {373 Text(String(localized: "Par plateforme")).spEyebrow().padding(.top, 10)374 ForEach(venues, id: \.venue) { v in FieldRow(label: v.venue, value: Fmt.usd(v.gross)) }375 }376 if let ps = exposure.positions, !ps.isEmpty {377 Text(String(localized: "Positions")).spEyebrow().padding(.top, 10)378 ForEach(Array(ps.enumerated()), id: \.offset) { _, p in379 FieldRow(label: "\(p.instrument) · \(p.side)", value: String(localized: "taille \(Money.exact(p.size)) · notionnel \(Money.exact(p.notional)) USD") + (p.liquidationPrice.map { " · " + String(localized: "liquidation \(Money.exact($0))") } ?? ""))380 }381 }382 if let ts = exposure.ts { Text(String(localized: "Lu \(Fmt.date(ms: ts) ?? "")")).font(.system(size: 12)).foregroundStyle(Theme.mute).padding(.top, 8) }383 }384 }385 .spCard()386 .accessibilityIdentifier("risk.exposure.\(exposure.book)")387 }388 static func pnlLabel(_ k: String) -> String {389 switch k {390 case "realizedToday": String(localized: "Résultat réalisé aujourd’hui")391 case "unrealizedToday": String(localized: "Résultat latent aujourd’hui")392 case "realizedInception": String(localized: "Résultat réalisé depuis l’origine")393 case "unrealizedInception": String(localized: "Résultat latent depuis l’origine")394 default: k395 }396 }397}398399/** One evaluation of the risk engine: decision, limit, observed value and threshold — verbatim. */400struct RiskDecisionRow: View {401 let decision: RiskDecision402 var body: some View {403 VStack(alignment: .leading, spacing: 4) {404 HStack(spacing: 6) {405 Pill(text: decision.decision, tone: decision.denied ? .danger : decision.decision == "allow" ? .ok : .neutral, icon: decision.denied ? "xmark.octagon.fill" : "checkmark.circle.fill")406 Pill(text: RiskWords.mode(decision.mode), tone: RiskWords.modeTone(decision.mode), icon: RiskWords.modeIcon(decision.mode))407 if decision.preview { Pill(text: String(localized: "aperçu : rien n’a été placé"), tone: .neutral) }408 Spacer()409 Text("#\(decision.id)").font(.spFootnote).foregroundStyle(Theme.mute)410 }411 Text([decision.kind, decision.venue, decision.instrument, decision.reducing ? String(localized: "réducteur") : nil].compactMap { $0 }.joined(separator: " · "))412 .font(.spCallout.weight(.medium)).foregroundStyle(Theme.ink)413 Text(decision.date.formatted(date: .abbreviated, time: .standard) + " · " + decision.principal.label).font(.spFootnote).foregroundStyle(Theme.mute)414 ForEach(decision.failing, id: \.self) { f in415 VStack(alignment: .leading, spacing: 2) {416 Text(f.id).font(.spMono).foregroundStyle(Theme.danger)417 Text(String(localized: "observé : \(f.observed ?? "—") · seuil : \(f.limit ?? "—")")).font(.spMono).foregroundStyle(Theme.ink)418 Text(f.detail).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)419 }.padding(.top, 2)420 }421 }422 .padding(.vertical, 6)423 .accessibilityElement(children: .combine)424 }425}426427struct RiskDecisionsView: View {428 @Environment(AppModel.self) private var model429 let initial: [RiskDecision]430 @State private var decisions: [RiskDecision]?431 @State private var error: Error?432 @State private var deniedOnly = false433 var body: some View {434 let rows = (decisions ?? initial).filter { !deniedOnly || $0.denied }435 List {436 Section {437 Toggle(String(localized: "Refus seulement"), isOn: $deniedOnly)438 if decisions == nil, model.offlineBrowsing || error != nil { Text(String(localized: "Journal de l’instantané : la lecture complète exige le serveur.")).font(.spFootnote).foregroundStyle(Theme.warn) }439 if let error { ErrorNotice(error: error) }440 }441 if rows.isEmpty { EmptyState(icon: "list.bullet.clipboard", title: String(localized: "Aucune décision à afficher")).listRowBackground(Color.clear) }442 ForEach(rows) { RiskDecisionRow(decision: $0) }443 }444 .navigationTitle(String(localized: "Journal des décisions")).navigationBarTitleDisplayMode(.inline)445 .task { await load() }446 .refreshable { await load() }447 }448 private func load() async {449 guard !model.offlineBrowsing else { return }450 do { decisions = try await RiskAPI(model.env.client).decisions(limit: 200); error = nil } catch let e { error = e }451 }452}453