Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Features/Arena/ArenaSession.swift4// Description: One Arena (multi-model comparison): runs `POST /api/compare`, folds its SSE events into view state,5// and carries the follow-up actions — prefer, judge, adopt into a conversation, export.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Foundation12import Observation1314@MainActor15@Observable16final class ArenaSession {17 static let minModels = 218 static let maxModels = 61920 var prompt = ""21 /// Models to compare, in the owner's order (2 to 6, any route).22 private(set) var modelIds: [String] = []23 var effort: Effort?24 /// Conversation the Arena was opened from: an answer can be adopted into it.25 var conversationId: String?26 var projectId: String?2728 /// The comparison on screen (nil before the first run). Built only from server events.29 private(set) var state: ArenaState?30 private(set) var isRunning = false31 private(set) var isJudging = false32 private(set) var isExporting = false33 private(set) var adoptingModel: String?34 /// Model whose answer was adopted into the conversation (confirmed by the server).35 private(set) var adoptedModel: String?36 var error: String?3738 @ObservationIgnored private let api: ChatAPI39 @ObservationIgnored private let model: (String) -> AIModel?40 @ObservationIgnored private var working: ArenaState?41 @ObservationIgnored private var streamTask: Task<Void, Never>?42 @ObservationIgnored private var publishTask: Task<Void, Never>?4344 init(api: ChatAPI, model: @escaping (String) -> AIModel?) { self.api = api; self.model = model }4546 var models: [AIModel] { modelIds.compactMap(model) }47 var canAddModel: Bool { modelIds.count < Self.maxModels && !isRunning }48 var canStart: Bool {49 !isRunning && !prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && (Self.minModels...Self.maxModels).contains(models.count)50 }5152 // MARK: selection5354 /// Replaces the selection: unknown ids and duplicates are dropped, 6 at most.55 func setModels(_ ids: [String]) {56 guard !isRunning else { return }57 var seen = Set<String>()58 modelIds = Array(ids.filter { model($0) != nil && seen.insert($0).inserted }.prefix(Self.maxModels))59 }60 func add(_ id: String) { if canAddModel { setModels(modelIds + [id]) } }61 func remove(_ id: String) { setModels(modelIds.filter { $0 != id }) }6263 // MARK: run6465 func start() {66 guard canStart else { return }67 let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines)68 let ids = models.map(\.id)69 error = nil; adoptedModel = nil70 prompt = "" // the prompt now lives in the comparison (shown above the answers)71 working = ArenaState(prompt: text, models: models)72 isRunning = true73 publish()74 streamTask = Task { [weak self] in await self?.run(prompt: text, ids: ids) }75 }7677 /// Sends the prompt of the comparison on screen again, to the current line-up.78 func rerun() {79 guard !isRunning, let last = state?.prompt, !last.isEmpty else { return }80 prompt = last81 start()82 }8384 private func run(prompt: String, ids: [String]) async {85 do {86 switch try await api.openCompare(prompt: prompt, modelIds: ids, effort: effort, projectId: projectId, conversationId: conversationId) {87 case .json:88 working?.apply(.error(String(localized: "Le serveur n’a pas ouvert de flux de comparaison.")))89 case .events(let bytes):90 for try await sse in SSEStream.events(from: bytes) {91 if Task.isCancelled { return }92 let event = ArenaEvent(sse: sse)93 working?.apply(event)94 switch event {95 case .text, .reasoning: schedulePublish() // high-frequency deltas are coalesced96 default: publish()97 }98 }99 }100 } catch let e as APIError {101 if e.kind == .cancelled || Task.isCancelled { return }102 if working?.isStored != true, working?.columns.contains(where: { !$0.text.isEmpty }) != true { working?.apply(.error(e.status == 402 ? String(localized: "Limite de dépenses atteinte : la comparaison n’a pas été lancée.") : e.message)) }103 } catch { if Task.isCancelled { return } }104 if Task.isCancelled { return }105 // the stream closed: whatever did not report its end is closed as it stands, nothing is invented106 if working?.isRunning == true { working?.interrupt(reason: String(localized: "Connexion interrompue avant la fin de la réponse.")) }107 finish()108 }109110 private func finish() {111 isRunning = false; streamTask = nil112 publish()113 if let e = state?.error, state?.columns.contains(where: { !$0.text.isEmpty }) != true { error = e }114 }115116 /// Stop: the local stream is closed and the server run is cancelled (the provider calls really end).117 func stop() {118 guard isRunning else { return }119 let runId = working?.runId120 streamTask?.cancel(); streamTask = nil121 working?.interrupt(reason: String(localized: "Arrêtée"))122 isRunning = false123 publish()124 if let runId { let api = api; Task { try? await api.cancel(runId: runId, messageId: nil) } }125 }126127 private func schedulePublish() {128 guard publishTask == nil else { return }129 publishTask = Task { [weak self] in130 try? await Task.sleep(for: .milliseconds(40))131 guard let self, !Task.isCancelled else { return }132 self.publishTask = nil133 self.publish()134 }135 }136 private func publish() {137 publishTask?.cancel(); publishTask = nil138 if state != working { state = working }139 }140141 /// Clears the result to write another prompt (the models stay selected).142 func reset() {143 guard !isRunning else { return }144 working = nil; state = nil; error = nil; adoptedModel = nil145 }146147 // MARK: after the run148149 /// A stored comparison exists on the server (the run reported `done`): prefer, judge, adopt and export are possible.150 var isStored: Bool { state?.isStored == true && !isRunning }151152 /// « Préférer » : recorded on the server, shown only once confirmed.153 func prefer(_ modelId: String) async {154 guard isStored, let id = state?.id else { return }155 do { try await api.preferCompare(id: id, model: modelId); working?.preferred = modelId; publish() }156 catch { self.error = (error as? APIError)?.message ?? String(localized: "Préférence non enregistrée.") }157 }158159 /// Asks a model for its opinion on the answers — an opinion, labelled as such by the server.160 func judge(with judgeModel: String) async {161 guard isStored, !isJudging, let id = state?.id else { return }162 isJudging = true; defer { isJudging = false }163 do { working?.judgement = try await api.judgeCompare(id: id, judgeModel: judgeModel); publish() }164 catch { self.error = (error as? APIError)?.message ?? String(localized: "L’évaluation a échoué.") }165 }166167 /// Brings one answer into the conversation the Arena was opened from. Returns true once the server confirmed.168 func adopt(_ modelId: String) async -> Bool {169 guard isStored, adoptingModel == nil, let id = state?.id, let conversationId else { return false }170 adoptingModel = modelId; defer { adoptingModel = nil }171 do { try await api.adopt(conversation: conversationId, comparisonId: id, modelId: modelId); adoptedModel = modelId; return true }172 catch { self.error = (error as? APIError)?.message ?? String(localized: "La réponse n’a pas pu être reprise."); return false }173 }174175 /// Downloads the server's export (Markdown or JSON) into a temporary file for the share sheet.176 func export(format: String) async -> URL? {177 guard isStored, !isExporting, let id = state?.id else { return nil }178 isExporting = true; defer { isExporting = false }179 do {180 let data = try await api.exportCompare(id: id, format: format)181 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spchat-preview/export", isDirectory: true)182 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)183 let url = dir.appendingPathComponent("arene-\(Date().formatted(.iso8601.year().month().day()))-\(id.suffix(6)).\(format)")184 try data.write(to: url, options: [.atomic, .completeFileProtectionUnlessOpen])185 return url186 } catch { self.error = (error as? APIError)?.message ?? String(localized: "Export impossible."); return nil }187 }188189 /// Stops observing (the sheet closed). A run in flight is cancelled on the server too.190 func close() { if isRunning { stop() } }191}192