Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Core/Models/Message.swift4// Description: Messages and their typed parts (text, reasoning, files, tool calls, artefacts, citations), mirroring the backend.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation1112enum ToolCallStatus: String, Codable, Sendable { case pendingApproval = "pending_approval", running, ok, error, denied }1314struct ToolCall: Hashable, Sendable {15 var id: String16 var name: String17 var input: JSONValue18 var status: ToolCallStatus19 var output: JSONValue?20 var durationMs: Int?21 var error: String?22}2324/// One element of `messages.parts`. Unknown part types are preserved as `.unknown` so newer servers do not break older apps.25enum MessagePart: Hashable, Sendable {26 case text(String)27 case reasoning(text: String, summarized: Bool)28 case image(attachmentId: String, mime: String, name: String?)29 case file(attachmentId: String, mime: String, name: String, size: Int?, pages: Int?)30 case toolCall(ToolCall)31 case artifact(artifactId: String, title: String, artifactType: String, language: String?)32 case citation(url: String, title: String?, snippet: String?)33 case generatedImage(attachmentId: String, prompt: String, model: String)34 case unknown(type: String)35}3637extension MessagePart: Codable {38 private enum K: String, CodingKey { case type, text, summarized, attachmentId, mime, name, size, pages, id, input, status, output, durationMs, error, artifactId, title, artifactType, language, url, snippet, prompt, model }3940 init(from decoder: Decoder) throws {41 let c = try decoder.container(keyedBy: K.self)42 let type = (try? c.decode(String.self, forKey: .type)) ?? ""43 switch type {44 case "text": self = .text(c.flexString(.text) ?? "")45 case "reasoning": self = .reasoning(text: c.flexString(.text) ?? "", summarized: c.flexBool(.summarized) ?? false)46 case "image": self = .image(attachmentId: c.flexString(.attachmentId) ?? "", mime: c.flexString(.mime) ?? "image/jpeg", name: c.flexString(.name))47 case "file": self = .file(attachmentId: c.flexString(.attachmentId) ?? "", mime: c.flexString(.mime) ?? "application/octet-stream", name: c.flexString(.name) ?? "fichier", size: c.flexInt(.size), pages: c.flexInt(.pages))48 case "tool_call":49 self = .toolCall(ToolCall(id: c.flexString(.id) ?? UUID().uuidString, name: c.flexString(.name) ?? "outil",50 input: (try? c.decodeIfPresent(JSONValue.self, forKey: .input)) ?? .null,51 status: (try? c.decode(ToolCallStatus.self, forKey: .status)) ?? .ok,52 output: try? c.decodeIfPresent(JSONValue.self, forKey: .output),53 durationMs: c.flexInt(.durationMs), error: c.flexString(.error)))54 case "artifact": self = .artifact(artifactId: c.flexString(.artifactId) ?? "", title: c.flexString(.title) ?? "Artefact", artifactType: c.flexString(.artifactType) ?? "text", language: c.flexString(.language))55 case "citation": self = .citation(url: c.flexString(.url) ?? "", title: c.flexString(.title), snippet: c.flexString(.snippet))56 case "generated_image": self = .generatedImage(attachmentId: c.flexString(.attachmentId) ?? "", prompt: c.flexString(.prompt) ?? "", model: c.flexString(.model) ?? "")57 default: self = .unknown(type: type)58 }59 }6061 func encode(to encoder: Encoder) throws {62 var c = encoder.container(keyedBy: K.self)63 switch self {64 case .text(let t): try c.encode("text", forKey: .type); try c.encode(t, forKey: .text)65 case .reasoning(let t, let s): try c.encode("reasoning", forKey: .type); try c.encode(t, forKey: .text); try c.encode(s, forKey: .summarized)66 case .image(let id, let mime, let name): try c.encode("image", forKey: .type); try c.encode(id, forKey: .attachmentId); try c.encode(mime, forKey: .mime); try c.encodeIfPresent(name, forKey: .name)67 case .file(let id, let mime, let name, let size, let pages): try c.encode("file", forKey: .type); try c.encode(id, forKey: .attachmentId); try c.encode(mime, forKey: .mime); try c.encode(name, forKey: .name); try c.encodeIfPresent(size, forKey: .size); try c.encodeIfPresent(pages, forKey: .pages)68 case .toolCall(let t): try c.encode("tool_call", forKey: .type); try c.encode(t.id, forKey: .id); try c.encode(t.name, forKey: .name); try c.encode(t.input, forKey: .input); try c.encode(t.status, forKey: .status); try c.encodeIfPresent(t.output, forKey: .output); try c.encodeIfPresent(t.durationMs, forKey: .durationMs); try c.encodeIfPresent(t.error, forKey: .error)69 case .artifact(let id, let title, let type, let lang): try c.encode("artifact", forKey: .type); try c.encode(id, forKey: .artifactId); try c.encode(title, forKey: .title); try c.encode(type, forKey: .artifactType); try c.encodeIfPresent(lang, forKey: .language)70 case .citation(let url, let title, let snippet): try c.encode("citation", forKey: .type); try c.encode(url, forKey: .url); try c.encodeIfPresent(title, forKey: .title); try c.encodeIfPresent(snippet, forKey: .snippet)71 case .generatedImage(let id, let prompt, let model): try c.encode("generated_image", forKey: .type); try c.encode(id, forKey: .attachmentId); try c.encode(prompt, forKey: .prompt); try c.encode(model, forKey: .model)72 case .unknown(let type): try c.encode(type, forKey: .type)73 }74 }75}7677enum MessageRole: String, Codable, Sendable { case user, assistant, system, tool }7879/// End state of a message. `streaming` is transient; every answer ends as complete, cancelled, incomplete (resumable) or error.80enum MessageStatus: String, Sendable {81 case streaming, complete, cancelled, incomplete, error82 init(server: String) { self = MessageStatus(rawValue: server) ?? .complete }83}8485struct TokenUsage: Codable, Hashable, Sendable {86 var input: Int87 var output: Int88 var cached: Int?89 var reasoning: Int?90 /// Set only when the provider reported the exact billed cost of the request (xAI, OpenRouter).91 var costUsd: Double?92 private enum K: String, CodingKey { case input, output, cached, reasoning, costUsd }93 init(input: Int, output: Int, cached: Int? = nil, reasoning: Int? = nil, costUsd: Double? = nil) { self.input = input; self.output = output; self.cached = cached; self.reasoning = reasoning; self.costUsd = costUsd }94 init(from decoder: Decoder) throws {95 let c = try decoder.container(keyedBy: K.self)96 input = c.flexInt(.input) ?? 0; output = c.flexInt(.output) ?? 0; cached = c.flexInt(.cached); reasoning = c.flexInt(.reasoning); costUsd = c.flexDouble(.costUsd)97 }98}99100struct MessageRouting: Codable, Hashable, Sendable {101 var mode: String?102 var selected: String?103 var reason: String?104 var servedBy: String?105}106107/// What the provider really received, and what was dropped (with the reason) — shown in the message details.108struct AppliedParams: Codable, Hashable, Sendable {109 struct Ignored: Codable, Hashable, Sendable { var param: String; var requested: JSONValue?; var reason: String }110 var applied: [String: JSONValue]111 var ignored: [Ignored]112 private enum K: String, CodingKey { case applied, ignored }113 init(applied: [String: JSONValue] = [:], ignored: [Ignored] = []) { self.applied = applied; self.ignored = ignored }114 init(from decoder: Decoder) throws {115 let c = try decoder.container(keyedBy: K.self)116 applied = (try? c.decodeIfPresent([String: JSONValue].self, forKey: .applied)) ?? [:]117 ignored = (try? c.decodeIfPresent([Ignored].self, forKey: .ignored)) ?? []118 }119}120121struct ChatMessage: Identifiable, Hashable, Sendable {122 var id: String123 var conversationId: String124 var parentId: String?125 var role: MessageRole126 var parts: [MessagePart]127 var modelId: String?128 var provider: String?129 var applied: AppliedParams?130 var routing: MessageRouting?131 var usage: TokenUsage?132 var costUsd: Double?133 var latencyMs: Int?134 var ttftMs: Int?135 var status: MessageStatus136 var error: String?137 var errorCode: String?138 var active: Bool139 var createdAt: Date140 /// Smart Follow-Ups proposed by the server after the answer (at most 3).141 var followups: [String] = []142 /// True when the cost shown is the amount billed by the provider; false = estimate from tokens × list price.143 var exactCost: Bool = false144145 /// Sources returned by the web search of this answer, in order, without duplicates.146 var citations: [Citation] {147 var seen = Set<String>(); var out: [Citation] = []148 for p in parts { if case .citation(let url, let title, let snippet) = p, !url.isEmpty, seen.insert(url).inserted { out.append(Citation(url: url, title: title, snippet: snippet)) } }149 return out150 }151 /// Parameters the owner asked for that this model does not accept (shown as an incompatibility notice).152 var ignoredParams: [AppliedParams.Ignored] { applied?.ignored ?? [] }153154 /// Concatenated visible text (what "copy" puts on the pasteboard).155 var text: String {156 parts.compactMap { if case .text(let t) = $0 { return t } else { return nil } }.joined(separator: "\n")157 }158 var reasoningText: String? {159 for p in parts { if case .reasoning(let t, _) = p, !t.isEmpty { return t } }160 return nil161 }162 var isStreaming: Bool { status == .streaming }163 var pendingApprovals: [ToolCall] {164 parts.compactMap { if case .toolCall(let t) = $0, t.status == .pendingApproval { return t } else { return nil } }165 }166}167168extension ChatMessage: Codable {169 private enum K: String, CodingKey {170 case id, conversation_id, parent_id, role, parts, model_id, provider, settings, routing, usage, cost_usd, latency_ms, ttft_ms, status, error, error_code, active, created_at, followups171 }172 private struct SettingsBox: Codable { var applied: AppliedParams? }173174 init(from decoder: Decoder) throws {175 let c = try decoder.container(keyedBy: K.self)176 id = try c.decode(String.self, forKey: .id)177 conversationId = c.flexString(.conversation_id) ?? ""178 parentId = c.flexString(.parent_id)179 role = (try? c.decode(MessageRole.self, forKey: .role)) ?? .assistant180 parts = (try? c.decodeIfPresent([MessagePart].self, forKey: .parts)) ?? []181 modelId = c.flexString(.model_id)182 provider = c.flexString(.provider)183 applied = (try? c.decodeIfPresent(SettingsBox.self, forKey: .settings))?.applied184 routing = try? c.decodeIfPresent(MessageRouting.self, forKey: .routing)185 usage = try? c.decodeIfPresent(TokenUsage.self, forKey: .usage)186 costUsd = c.flexDouble(.cost_usd)187 latencyMs = c.flexInt(.latency_ms)188 ttftMs = c.flexInt(.ttft_ms)189 status = MessageStatus(server: c.flexString(.status) ?? "complete")190 error = c.flexString(.error)191 errorCode = c.flexString(.error_code)192 active = c.flexBool(.active) ?? true193 createdAt = c.flexDate(.created_at) ?? Date()194 followups = (try? c.decodeIfPresent([String].self, forKey: .followups)) ?? []195 exactCost = usage?.costUsd != nil196 }197198 func encode(to encoder: Encoder) throws {199 var c = encoder.container(keyedBy: K.self)200 if !followups.isEmpty { try c.encode(followups, forKey: .followups) }201 try c.encode(id, forKey: .id); try c.encode(conversationId, forKey: .conversation_id); try c.encodeIfPresent(parentId, forKey: .parent_id)202 try c.encode(role, forKey: .role); try c.encode(parts, forKey: .parts); try c.encodeIfPresent(modelId, forKey: .model_id); try c.encodeIfPresent(provider, forKey: .provider)203 if let applied { try c.encode(SettingsBox(applied: applied), forKey: .settings) }204 try c.encodeIfPresent(routing, forKey: .routing); try c.encodeIfPresent(usage, forKey: .usage); try c.encodeIfPresent(costUsd, forKey: .cost_usd)205 try c.encodeIfPresent(latencyMs, forKey: .latency_ms); try c.encodeIfPresent(ttftMs, forKey: .ttft_ms); try c.encode(status.rawValue, forKey: .status)206 try c.encodeIfPresent(error, forKey: .error); try c.encodeIfPresent(errorCode, forKey: .error_code); try c.encode(active, forKey: .active)207 try c.encode(ISO8601.string(createdAt), forKey: .created_at)208 }209}210211/// One source of a web search (a `citation` part).212struct Citation: Identifiable, Hashable, Sendable {213 var url: String214 var title: String?215 var snippet: String?216 var id: String { url }217 /// Host without `www.` (shown as the card caption).218 var domain: String { (URL(string: url)?.host() ?? url).replacingOccurrences(of: #"^www\."#, with: "", options: .regularExpression) }219 var displayTitle: String { (title?.isEmpty == false ? title! : domain) }220}221