Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Core/Models/LensArena.swift4// Description: Response Lens and Arena (multi-model comparison): stream events, stored rows and the pure reducers5// that turn the server's SSE vocabulary into view state.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Foundation1213// MARK: Response Lens1415struct LensKind: Identifiable, Hashable, Sendable {16 var id: String17 var label: String18 var usesWeb: Bool19 var symbol: String {20 switch id { case "summary": "text.alignleft"; case "explain": "text.magnifyingglass"; case "keypoints": "list.bullet"; case "table": "tablecells"; case "verify": "checkmark.shield"; default: "sparkles" }21 }22 /// The five lenses of backend 1.0, used until the server's list is loaded.23 static let builtin: [LensKind] = [24 LensKind(id: "summary", label: String(localized: "Résumé"), usesWeb: false), LensKind(id: "explain", label: String(localized: "Explication détaillée"), usesWeb: false),25 LensKind(id: "keypoints", label: String(localized: "Points importants"), usesWeb: false), LensKind(id: "table", label: String(localized: "Tableau"), usesWeb: false),26 LensKind(id: "verify", label: String(localized: "Vérification des sources"), usesWeb: true),27 ]28}2930struct LensSource: Identifiable, Hashable, Sendable {31 var url: String; var title: String?; var claim: String?32 var id: String { url + (claim ?? "") }33 init?(_ j: JSONValue) { guard let u = j.str("url"), !u.isEmpty else { return nil }; url = u; title = j.str("title"); claim = j.str("claim") }34 var citation: Citation { Citation(url: url, title: title, snippet: claim) }35}3637struct StoredLens: Identifiable, Hashable, Sendable {38 var id: String; var lens: String; var modelId: String?; var content: String; var sources: [LensSource]; var costUsd: Double?; var status: String; var createdAt: Date?39 init?(_ j: JSONValue) {40 guard let id = j.str("id") else { return nil }41 self.id = id; lens = j.str("lens") ?? ""; modelId = j.str("model_id"); content = j.str("content") ?? ""; sources = j.list("sources").compactMap(LensSource.init)42 costUsd = j.double("cost_usd"); status = j.str("status") ?? "complete"; createdAt = j.date("created_at")43 }44}4546enum LensEvent: Sendable, Equatable {47 case start(lens: String?, model: String?)48 case step(step: String, label: String)49 case sources([LensSource])50 case text(String)51 /// `verify` rewrites its answer once the sources are confronted: the streamed text is replaced as a whole.52 case replace(String)53 case done(id: String?, content: String?, sources: [LensSource], costUsd: Double?, exactCost: Bool, latencyMs: Int?, status: String?, error: String? = nil)54 case error(String)55 case end56 case other5758 init(sse: SSEEvent) {59 let j = (try? JSONDecoder().decode(JSONValue.self, from: Data(sse.data.utf8))) ?? .null60 switch sse.event {61 case "start": self = .start(lens: j.str("lens"), model: j.str("model"))62 case "step": self = .step(step: j.str("step") ?? "", label: j.str("label") ?? j.str("step") ?? "")63 case "sources": self = .sources(j.list("sources").compactMap(LensSource.init))64 case "text": self = .text(j.str("delta") ?? "")65 case "replace": self = .replace(j.str("content") ?? "")66 case "done": self = .done(id: j.str("id"), content: j.str("content"), sources: j.list("sources").compactMap(LensSource.init), costUsd: j.double("costUsd"), exactCost: j.bool("exactCost") ?? false, latencyMs: j.int("latencyMs"), status: j.str("status"), error: j.str("error"))67 case "error": self = .error(j.str("message") ?? String(localized: "La lentille a échoué."))68 case "end": self = .end69 default: self = .other70 }71 }72}7374/// State of one lens run, built only from the events the server sends.75struct LensRun: Equatable, Sendable {76 struct Step: Identifiable, Equatable, Sendable { var id: Int; var label: String }77 var lens: String78 var model: String?79 var steps: [Step] = []80 var sources: [LensSource] = []81 var text = ""82 var storedId: String?83 var costUsd: Double?84 var exactCost = false85 var latencyMs: Int?86 var error: String?87 var isRunning = true8889 init(lens: String) { self.lens = lens }9091 mutating func apply(_ e: LensEvent) {92 switch e {93 case .start(_, let m): model = m ?? model94 case .step(_, let label): if steps.last?.label != label { steps.append(Step(id: steps.count, label: label)) }95 case .sources(let s): for x in s where !sources.contains(x) { sources.append(x) }96 case .text(let d): text += d97 case .replace(let content): if !content.isEmpty { text = content }98 case .done(let id, let content, let s, let cost, let exact, let latency, let status, let message):99 storedId = id; if let content, !content.isEmpty { text = content }100 if !s.isEmpty { sources = s }101 costUsd = cost; exactCost = exact; latencyMs = latency; isRunning = false102 // `incomplete` = the model stopped early: what was written is kept and the reason is shown103 if let message, !message.isEmpty { error = message }104 else if status == "error", error == nil { error = String(localized: "La lentille a échoué.") }105 case .error(let m): error = m; isRunning = false106 case .end: isRunning = false107 case .other: break108 }109 }110}111112// MARK: Arena113114struct ArenaColumn: Identifiable, Equatable, Sendable {115 var id: String // model id116 var displayName: String117 var provider: String?118 var route: String?119 var creator: String?120 var logo: String?121 /// Cost of the input alone, estimated before sending (labelled « estimé »).122 var estimatedInputCostUsd: Double?123 var estimateBasis: String?124 var text = ""125 var reasoning = ""126 var error: String?127 var isDone = false128 var servedBy: String?129 var inputTokens: Int?130 var outputTokens: Int?131 var costUsd: Double?132 /// True = billed amount reported by the provider (« facturé »); false = estimate (« estimé »).133 var exactCost = false134 var latencyMs: Int?135 var ttftMs: Int?136}137138enum ArenaEvent: Sendable, Equatable {139 /// First event of the stream: the server run (lets « Arrêter » cancel the provider calls for real).140 case run(id: String)141 case start(id: String, columns: [ArenaColumn])142 case text(model: String, delta: String)143 case reasoning(model: String, delta: String)144 case modelError(model: String, message: String)145 case modelDone(ArenaColumn)146 case done(id: String?)147 case error(String)148 case end149 case other150151 init(sse: SSEEvent) {152 let j = (try? JSONDecoder().decode(JSONValue.self, from: Data(sse.data.utf8))) ?? .null153 func column(_ m: JSONValue, idKey: String) -> ArenaColumn? {154 guard let id = m.str(idKey) else { return nil }155 var c = ArenaColumn(id: id, displayName: m.str("displayName") ?? id, provider: m.str("provider"), route: m.str("route"), creator: m.str("creator"), logo: m.str("logo"))156 c.estimatedInputCostUsd = m["estimate"]?.double("inputCostUsd"); c.estimateBasis = m["estimate"]?.str("basis")157 return c158 }159 switch sse.event {160 case "run": self = .run(id: j.str("runId") ?? "")161 case "start": self = .start(id: j.str("id") ?? "", columns: j.list("models").compactMap { column($0, idKey: "id") })162 case "text": self = .text(model: j.str("model") ?? "", delta: j.str("delta") ?? "")163 case "reasoning": self = .reasoning(model: j.str("model") ?? "", delta: j.str("delta") ?? "")164 case "model_error": self = .modelError(model: j.str("model") ?? "", message: j.str("message") ?? String(localized: "Erreur"))165 case "model_done":166 guard var c = column(j, idKey: "modelId") else { self = .other; return }167 c.text = j.str("text") ?? ""; c.reasoning = j.str("reasoning") ?? ""; c.error = j.str("error"); c.isDone = true; c.servedBy = j.str("servedBy")168 c.inputTokens = j["usage"]?.int("input"); c.outputTokens = j["usage"]?.int("output")169 c.costUsd = j.double("costUsd"); c.exactCost = j.bool("exactCost") ?? false; c.latencyMs = j.int("latencyMs"); c.ttftMs = j.int("ttftMs")170 self = .modelDone(c)171 case "done": self = .done(id: j.str("id"))172 case "error": self = .error(j.str("message") ?? String(localized: "La comparaison a échoué."))173 case "end": self = .end174 default: self = .other175 }176 }177}178179struct ArenaJudgement: Equatable, Sendable {180 var judgeModel: String; var text: String; var mapping: [String: String]; var costUsd: Double?; var disclaimer: String?181 init?(_ j: JSONValue) {182 guard let t = j.str("text") else { return nil }183 text = t; judgeModel = j.str("judgeModel") ?? ""; mapping = (j["mapping"]?.objectValue ?? [:]).compactMapValues(\.stringValue); costUsd = j.double("costUsd"); disclaimer = j.str("disclaimer")184 }185}186187/// State of one comparison, built only from the events of `POST /api/compare`.188struct ArenaState: Equatable, Sendable {189 var id: String?190 /// Server run of the comparison while it streams (nil once ended).191 var runId: String?192 var prompt: String193 var columns: [ArenaColumn]194 var isRunning = true195 /// True once the server reported `done`: the comparison row exists (prefer, judge, adopt and export are possible).196 var isStored = false197 var error: String?198 var preferred: String?199 var judgement: ArenaJudgement?200201 init(prompt: String, models: [AIModel]) {202 self.prompt = prompt203 columns = models.map { ArenaColumn(id: $0.id, displayName: $0.displayName, provider: $0.provider, route: $0.route, creator: $0.creator, logo: $0.logo) }204 }205206 var finishedCount: Int { columns.filter(\.isDone).count }207 /// Sum of what is known: billed or estimated costs of the finished columns.208 var totalCostUsd: Double? { let c = columns.compactMap(\.costUsd); return c.isEmpty ? nil : c.reduce(0, +) }209 var allCostsExact: Bool { let done = columns.filter { $0.costUsd != nil }; return !done.isEmpty && done.allSatisfy(\.exactCost) }210 var fastestFirstToken: String? { columns.filter { $0.ttftMs != nil && $0.error == nil }.min { $0.ttftMs! < $1.ttftMs! }?.id }211212 private mutating func mutate(_ model: String, _ body: (inout ArenaColumn) -> Void) {213 guard let i = columns.firstIndex(where: { $0.id == model }) else { return }214 body(&columns[i])215 }216217 mutating func apply(_ e: ArenaEvent) {218 switch e {219 case .run(let id): runId = id.isEmpty ? nil : id220 case .start(let id, let cols):221 self.id = id.isEmpty ? self.id : id222 // the server's order and identity win; text already received for a column is kept223 if !cols.isEmpty { columns = cols.map { c in var n = c; if let old = columns.first(where: { $0.id == c.id }) { n.text = old.text; n.reasoning = old.reasoning }; return n } }224 case .text(let m, let d): mutate(m) { $0.text += d }225 case .reasoning(let m, let d): mutate(m) { $0.reasoning += d }226 case .modelError(let m, let message): mutate(m) { $0.error = message }227 case .modelDone(let done):228 mutate(done.id) { c in229 let estimate = c.estimatedInputCostUsd, basis = c.estimateBasis, reasoning = c.reasoning, streamed = c.text230 c = done; c.estimatedInputCostUsd = estimate; c.estimateBasis = basis231 if c.reasoning.isEmpty { c.reasoning = reasoning }232 if c.text.isEmpty { c.text = streamed }233 }234 case .done(let id): if let id { self.id = id }; isRunning = false; runId = nil; isStored = self.id != nil235 case .error(let m): error = m; isRunning = false; runId = nil236 case .end: isRunning = false; runId = nil237 case .other: break238 }239 }240241 /// The stream ended without `done` (stopped, connection lost): columns still open are closed as they stand.242 mutating func interrupt(reason: String) {243 isRunning = false; runId = nil244 for i in columns.indices where !columns[i].isDone { columns[i].isDone = true; if columns[i].error == nil { columns[i].error = reason } }245 }246}247