Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Core/Models/Studio.swift4// Description: DTOs of deep research (`/api/research`), the image studio (`/api/images`) and project details, plus5// the pure reducer that turns the research SSE vocabulary into view state. Loose-JSON tolerant.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Foundation1213// MARK: deep research1415enum ResearchDepth: String, CaseIterable, Identifiable, Sendable {16 case quick, standard, deep17 var id: String { rawValue }18 var label: String {19 switch self { case .quick: String(localized: "Rapide"); case .standard: String(localized: "Standard"); case .deep: String(localized: "Approfondie") }20 }21 /// What the server does at this depth (number of web queries and pages read) — same figures as its engine.22 var hint: String {23 switch self {24 case .quick: String(localized: "≈ 3 requêtes · 4 pages · ~1 min")25 case .standard: String(localized: "≈ 5 requêtes · 7 pages · 2 à 4 min")26 case .deep: String(localized: "≈ 8 requêtes · 12 pages · 5 à 10 min")27 }28 }29}3031enum ResearchStatus {32 static let resumable: Set<String> = ["interrupted", "error", "cancelled"]33 static let running: Set<String> = ["planning", "searching", "reading", "synthesizing"]34 static func label(_ s: String) -> String {35 switch s {36 case "complete": String(localized: "terminé"); case "error": String(localized: "erreur"); case "cancelled": String(localized: "annulé"); case "interrupted": String(localized: "interrompu")37 case "planning": String(localized: "planification"); case "searching": String(localized: "recherche"); case "reading": String(localized: "lecture"); case "synthesizing": String(localized: "synthèse")38 default: s39 }40 }41}4243struct ResearchEvidence: Hashable, Sendable { var claim: String; var quote: String; var confidence: String }4445struct ResearchSource: Identifiable, Hashable, Sendable {46 var n: Int47 var url: String48 var title: String49 var snippet: String?50 var fetched: Bool51 /// Number of pieces of evidence extracted from the page (nil = not analysed yet).52 var evidenceCount: Int?53 var evidence: [ResearchEvidence] = []54 var failed = false55 var id: Int { n }56 var domain: String { (URL(string: url)?.host() ?? url).replacingOccurrences(of: #"^www\."#, with: "", options: .regularExpression) }5758 init?(_ j: JSONValue) {59 guard let n = j.int("n"), let url = j.str("url") else { return nil }60 self.n = n; self.url = url; title = j.str("title") ?? url; snippet = j.str("snippet"); fetched = j.bool("fetched") ?? false61 evidence = j.list("evidence").compactMap { e in e.str("claim").map { ResearchEvidence(claim: $0, quote: e.str("quote") ?? "", confidence: e.str("confidence") ?? "") } }62 // the stream sends a count (`evidence: 3`), stored rows send the list63 evidenceCount = j.int("evidence") ?? j.int("evidenceCount") ?? (j["evidence"]?.arrayValue != nil ? evidence.count : (j.bool("analysed") == true ? 0 : nil))64 failed = j.bool("error") ?? false65 }66}6768struct ResearchPlan: Hashable, Sendable {69 var subquestions: [String]; var queries: [String]; var evidenceNeeded: [String]70 init?(_ j: JSONValue?) {71 guard let j, j.objectValue != nil else { return nil }72 subquestions = j.strings("subquestions"); queries = j.strings("queries"); evidenceNeeded = j.strings("evidence_needed")73 if subquestions.isEmpty && queries.isEmpty { return nil }74 }75}7677/// One row of `GET /api/research` (and the header of a full run).78struct ResearchRun: Identifiable, Hashable, Sendable {79 var id: String80 var conversationId: String?81 var question: String82 var modelId: String?83 var status: String84 var depth: String85 /// Estimated by the server from tokens × list price.86 var costUsd: Double?87 var error: String?88 var createdAt: Date?89 var completedAt: Date?90 var sourceCount: Int?91 /// Id of the generation still running on the server for this research, if any.92 var liveRunId: String?93 // only in `GET /api/research/{id}`94 var plan: ResearchPlan?95 var sources: [ResearchSource] = []96 var report: String?9798 var isResumable: Bool { ResearchStatus.resumable.contains(status) && liveRunId == nil }99 var isRunning: Bool { liveRunId != nil || ResearchStatus.running.contains(status) }100101 init?(_ j: JSONValue, live: String? = nil) {102 guard let id = j.str("id") else { return nil }103 self.id = id; conversationId = j.str("conversation_id"); question = j.str("question") ?? ""; modelId = j.str("model_id")104 status = j.str("status") ?? "planning"; depth = j.str("depth") ?? "standard"; costUsd = j.double("cost_usd"); error = j.str("error")105 createdAt = j.date("created_at"); completedAt = j.date("completed_at"); sourceCount = j.int("source_count")106 liveRunId = live ?? j.str("live")107 plan = ResearchPlan(j["plan"])108 sources = j.list("sources").compactMap(ResearchSource.init).sorted { $0.n < $1.n }109 report = j.str("report_md")110 if sourceCount == nil, !sources.isEmpty { sourceCount = sources.count }111 }112}113114enum ResearchEvent: Sendable, Equatable {115 case run(id: String)116 case start(id: String?, conversationId: String?, model: String?, extractor: String?, depth: String?, resumed: Bool)117 case step(step: String, status: String?, plan: ResearchPlan?, found: Int?, reused: Bool)118 case source(ResearchSource)119 case evidence(n: Int, count: Int)120 case text(String)121 case done(conversationId: String?, costUsd: Double?, sources: Int?)122 case error(message: String, status: String?, resumable: Bool)123 case end124 case other125126 init(sse: SSEEvent) {127 let j = (try? JSONDecoder().decode(JSONValue.self, from: Data(sse.data.utf8))) ?? .null128 switch sse.event {129 case "run": self = .run(id: j.str("runId") ?? "")130 case "start": self = .start(id: j.str("id"), conversationId: j.str("conversationId"), model: j.str("model"), extractor: j.str("extractor"), depth: j.str("depth"), resumed: j.bool("resumed") ?? false)131 case "step":132 let step = j.str("step") ?? ""133 self = .step(step: step, status: j.str("status"), plan: step == "plan" ? ResearchPlan(j["detail"]) : nil, found: j["detail"]?.int("found"), reused: j.bool("reused") ?? false)134 case "source": self = ResearchSource(j).map(ResearchEvent.source) ?? .other135 case "evidence": if let n = j.int("n") { self = .evidence(n: n, count: j.int("count") ?? 0) } else { self = .other }136 case "text": self = .text(j.str("delta") ?? "")137 case "done": self = .done(conversationId: j.str("conversationId"), costUsd: j.double("costUsd"), sources: j.int("sources"))138 case "error": self = .error(message: j.str("message") ?? String(localized: "La recherche a échoué."), status: j.str("status"), resumable: j.bool("resumable") ?? false)139 case "end": self = .end140 default: self = .other141 }142 }143}144145/// Live state of one research run, built only from the events the server sends (indexes applied exactly once).146struct ResearchProgress: Equatable, Sendable {147 static let stages = ["plan", "discovery", "retrieval", "extraction", "synthesis"]148 var runId: String?149 var lastIndex = -1150 var researchId: String?151 var conversationId: String?152 var model: String?153 var extractor: String?154 var depth: String?155 var resumed = false156 /// 0 = nothing yet, 1…5 = plan, discovery, retrieval, extraction, synthesis.157 var stage = 0158 var status: String = "planning"159 var plan: ResearchPlan?160 var found: Int?161 var sources: [ResearchSource] = []162 var report = ""163 var costUsd: Double?164 var error: String?165 var resumable = false166 var isComplete = false167 /// The server sent its terminal `end`: the stream is over (the persisted run is then the truth).168 var ended = false169170 static func stageIndex(_ step: String) -> Int { (stages.firstIndex(of: step) ?? -1) + 1 }171 static func stageLabel(_ index: Int) -> String {172 switch index {173 case 1: String(localized: "Plan"); case 2: String(localized: "Découverte"); case 3: String(localized: "Lecture")174 case 4: String(localized: "Preuves"); case 5: String(localized: "Synthèse"); default: ""175 }176 }177178 /// Applies one event; `index` is the SSE `id:` (events replayed after a reconnection are skipped).179 mutating func apply(_ e: ResearchEvent, index: Int? = nil) {180 if let index { if index <= lastIndex { return }; lastIndex = index }181 switch e {182 case .run(let id): if !id.isEmpty { runId = id }183 case .start(let id, let conv, let m, let ex, let d, let r):184 researchId = id ?? researchId; conversationId = conv ?? conversationId; model = m ?? model; extractor = ex ?? extractor; depth = d ?? depth; resumed = r185 error = nil; isComplete = false186 case .step(let step, let s, let p, let f, _):187 stage = max(stage, Self.stageIndex(step))188 if let s { status = s }189 if let p { plan = p }190 if let f { found = f }191 case .source(let s):192 // reading a page implies the retrieval stage even when the server folds it into one loop193 stage = max(stage, 3)194 if let i = sources.firstIndex(where: { $0.n == s.n }) { var n = s; if n.evidenceCount == nil { n.evidenceCount = sources[i].evidenceCount }; sources[i] = n }195 else { sources.append(s); sources.sort { $0.n < $1.n } }196 case .evidence(let n, let count):197 stage = max(stage, 4)198 if let i = sources.firstIndex(where: { $0.n == n }) { sources[i].evidenceCount = count }199 case .text(let d): stage = 5; status = "synthesizing"; report += d200 case .done(let conv, let cost, _): conversationId = conv ?? conversationId; costUsd = cost; status = "complete"; isComplete = true201 case .error(let m, let s, let r): error = m; status = s ?? "error"; resumable = r202 case .end: ended = true203 case .other: break204 }205 }206}207208// MARK: image studio209210struct GeneratedImage: Identifiable, Hashable, Sendable {211 var id: String212 var filename: String213 var prompt: String?214 var model: String?215 var revisedPrompt: String?216 var size: String?217 var quality: String?218 /// Attachment this image was edited from (« retouche »).219 var editedFrom: String?220 var conversationId: String?221 var createdAt: Date?222223 init?(_ j: JSONValue) {224 guard let id = j.str("id") else { return nil }225 self.id = id; filename = j.str("filename") ?? "image.png"226 let m = j["meta"]227 prompt = m?.str("prompt"); model = m?.str("model"); revisedPrompt = m?.str("revisedPrompt"); size = m?.str("size"); quality = m?.str("quality"); editedFrom = m?.str("editedFrom")228 conversationId = j.str("conversation_id"); createdAt = j.date("created_at")229 }230}231232struct ImageGeneration: Sendable, Equatable {233 var attachmentId: String234 var model: String?235 var revisedPrompt: String?236 /// Estimated by the server from the usage the provider reported (nil when not reported).237 var costUsd: Double?238 init?(_ j: JSONValue) {239 guard let id = j.str("attachmentId"), !id.isEmpty else { return nil }240 attachmentId = id; model = j.str("model"); revisedPrompt = j.str("revisedPrompt"); costUsd = j.double("costUsd")241 }242}243244enum ImageOptions {245 /// Sizes and qualities the server passes to the image API (same lists as the web studio).246 static let sizes = ["1024x1024", "1536x1024", "1024x1536"]247 static let qualities = ["low", "medium", "high"]248 static func sizeLabel(_ s: String) -> String {249 switch s { case "1024x1024": String(localized: "Carré"); case "1536x1024": String(localized: "Paysage"); case "1024x1536": String(localized: "Portrait"); default: s.replacingOccurrences(of: "x", with: " × ") }250 }251 static func qualityLabel(_ q: String) -> String {252 switch q { case "low": String(localized: "Basse"); case "medium": String(localized: "Moyenne"); case "high": String(localized: "Haute"); default: q }253 }254 static func payload(prompt: String, model: String?, size: String?, quality: String?, editAttachmentId: String?) -> [String: JSONValue] {255 var o: [String: JSONValue] = ["prompt": .string(String(prompt.trimmingCharacters(in: .whitespacesAndNewlines).prefix(4000)))]256 if let model, !model.isEmpty { o["model"] = .string(model) }257 if let editAttachmentId { o["editAttachmentId"] = .string(editAttachmentId) }258 else { // the edit endpoint of the provider takes neither a size nor a quality259 if let size { o["size"] = .string(size) }260 if let quality { o["quality"] = .string(quality) }261 }262 return o263 }264}265266// MARK: projects267268/// `GET /api/projects/{id}` — the project with what is attached to it.269struct ProjectDetail: Sendable, Equatable {270 var project: Project271 var files: [Attachment]272 var memoryCount: Int273 var artifactCount: Int274 init?(_ j: JSONValue) {275 guard let p: Project = j["project"]?.decoded() else { return nil }276 project = p277 files = j.list("files").compactMap { $0.decoded(Attachment.self) }278 memoryCount = j.list("memories").count; artifactCount = j.list("artifacts").count279 }280}281282/// Body of `PATCH /api/projects/{id}`: only what changed; `.some(nil)` clears a nullable field.283struct ProjectPatch: Equatable, Sendable {284 var name: String?285 var description: String??286 var instructions: String??287 var defaultModel: String??288 var color: String??289 var isEmpty: Bool { self == ProjectPatch() }290291 /// The difference between a project and the edited values (empty text = cleared).292 init(from p: Project, name: String, description: String, instructions: String, defaultModel: String?, color: String?) {293 func clean(_ s: String) -> String? { let t = s.trimmingCharacters(in: .whitespacesAndNewlines); return t.isEmpty ? nil : t }294 let n = String(name.trimmingCharacters(in: .whitespacesAndNewlines).prefix(120))295 if !n.isEmpty, n != p.name { self.name = n }296 let d = clean(description).map { String($0.prefix(2000)) }, i = clean(instructions).map { String($0.prefix(20_000)) }297 if d != clean(p.description ?? "") { self.description = .some(d) }298 if i != clean(p.instructions ?? "") { self.instructions = .some(i) }299 if defaultModel != p.defaultModel { self.defaultModel = .some(defaultModel) }300 if color != p.color { self.color = .some(color) }301 }302 init() {}303304 var payload: [String: JSONValue] {305 var o: [String: JSONValue] = [:]306 if let name { o["name"] = .string(name) }307 if let v = description { o["description"] = v.map(JSONValue.string) ?? .null }308 if let v = instructions { o["instructions"] = v.map(JSONValue.string) ?? .null }309 if let v = defaultModel { o["defaultModel"] = v.map(JSONValue.string) ?? .null }310 if let v = color { o["color"] = v.map(JSONValue.string) ?? .null }311 return o312 }313}314