SPB Git

Repository Public

ChatModels.swift 26.4 KB 442 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Models/ChatModels.swift3// Description: Conversations, messages and message parts as exchanged with the chat backend (and stored in the local cache).4import Foundation56// MARK: - Conversation78public struct Conversation: Sendable, Hashable, Identifiable, Codable {9    public var id: String10    public var projectId: String?11    public var title: String12    public var modelId: String?13    public var settings: JSONValue14    public var pinned: Bool15    public var favorite: Bool16    public var archivedAt: Date?17    public var parentId: String?18    /// Name given to this branch, and the message of the parent conversation it forks from.19    public var branchLabel: String?20    public var branchMessageId: String?21    public var mode: String22    public var messageCount: Int23    public var totalCostUsd: Double24    public var lastMessageAt: Date?25    public var createdAt: Date26    public var updatedAt: Date27    public var projectName: String?28    public var projectColor: String?29    public var hasDraft: Bool30    public var streaming: Bool3132    enum CodingKeys: String, CodingKey {33        case id, title, settings, pinned, favorite, mode, streaming34        case projectId = "project_id", modelId = "model_id", archivedAt = "archived_at", parentId = "parent_id", branchLabel = "branch_label", branchMessageId = "branch_message_id"35        case messageCount = "message_count", totalCostUsd = "total_cost_usd", lastMessageAt = "last_message_at"36        case createdAt = "created_at", updatedAt = "updated_at", projectName = "project_name", projectColor = "project_color", hasDraft = "has_draft"37    }3839    public init(id: String, projectId: String? = nil, title: String, modelId: String? = nil, settings: JSONValue = .object([:]), pinned: Bool = false, favorite: Bool = false,40                archivedAt: Date? = nil, parentId: String? = nil, mode: String = "chat", messageCount: Int = 0, totalCostUsd: Double = 0, lastMessageAt: Date? = nil,41                createdAt: Date = Date(), updatedAt: Date = Date(), projectName: String? = nil, projectColor: String? = nil, hasDraft: Bool = false, streaming: Bool = false) {42        self.id = id; self.projectId = projectId; self.title = title; self.modelId = modelId; self.settings = settings; self.pinned = pinned; self.favorite = favorite43        self.archivedAt = archivedAt; self.parentId = parentId; self.mode = mode; self.messageCount = messageCount; self.totalCostUsd = totalCostUsd; self.lastMessageAt = lastMessageAt44        self.createdAt = createdAt; self.updatedAt = updatedAt; self.projectName = projectName; self.projectColor = projectColor; self.hasDraft = hasDraft; self.streaming = streaming45    }4647    public init(from decoder: Decoder) throws {48        let c = try decoder.container(keyedBy: CodingKeys.self)49        id = try c.decode(String.self, forKey: .id)50        projectId = c.optional(String.self, .projectId)51        title = c.optional(String.self, .title) ?? "Nouvelle conversation"52        modelId = c.optional(String.self, .modelId)53        settings = c.optional(JSONValue.self, .settings) ?? .object([:])54        pinned = c.optional(Bool.self, .pinned) ?? false55        favorite = c.optional(Bool.self, .favorite) ?? false56        archivedAt = c.optional(Date.self, .archivedAt)57        parentId = c.optional(String.self, .parentId)58        branchLabel = c.optional(String.self, .branchLabel); branchMessageId = c.optional(String.self, .branchMessageId)59        mode = c.optional(String.self, .mode) ?? "chat"60        messageCount = c.flexInt(.messageCount) ?? 061        totalCostUsd = c.flexDouble(.totalCostUsd) ?? 062        lastMessageAt = c.optional(Date.self, .lastMessageAt)63        createdAt = c.optional(Date.self, .createdAt) ?? Date()64        updatedAt = c.optional(Date.self, .updatedAt) ?? createdAt65        projectName = c.optional(String.self, .projectName)66        projectColor = c.optional(String.self, .projectColor)67        hasDraft = c.optional(Bool.self, .hasDraft) ?? false68        streaming = c.optional(Bool.self, .streaming) ?? false69    }7071    public var isArchived: Bool { archivedAt != nil }72    /// Moment used to order the list (same rule as the server: last message, else creation).73    public var sortDate: Date { lastMessageAt ?? createdAt }74}7576// MARK: - Message parts7778public enum ToolCallStatus: String, Sendable, Codable, Hashable {79    case pendingApproval = "pending_approval", running, ok, error, denied80}8182public struct ToolCall: Sendable, Hashable, Codable {83    public var id: String84    public var name: String85    public var input: JSONValue86    public var status: ToolCallStatus87    public var output: JSONValue?88    public var durationMs: Int?89    public var error: String?90    public init(id: String, name: String, input: JSONValue, status: ToolCallStatus, output: JSONValue? = nil, durationMs: Int? = nil, error: String? = nil) {91        self.id = id; self.name = name; self.input = input; self.status = status; self.output = output; self.durationMs = durationMs; self.error = error92    }93}9495/// One element of a message. Unknown kinds sent by a newer server are preserved (`unknown`) and never dropped.96public enum MessagePart: Sendable, Hashable, Codable {97    case text(String)98    case reasoning(text: String, summarized: Bool)99    case image(attachmentId: String, mime: String, name: String?)100    case file(attachmentId: String, mime: String, name: String, size: Int?, pages: Int?)101    case toolCall(ToolCall)102    case artifact(artifactId: String, title: String, artifactType: String, language: String?)103    case citation(url: String, title: String?, snippet: String?)104    case generatedImage(attachmentId: String, prompt: String, model: String)105    case unknown(JSONValue)106107    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 }108109    public init(from decoder: Decoder) throws {110        let c = try decoder.container(keyedBy: K.self)111        let type = c.optional(String.self, .type) ?? ""112        switch type {113        case "text": self = .text(c.optional(String.self, .text) ?? "")114        case "reasoning": self = .reasoning(text: c.optional(String.self, .text) ?? "", summarized: c.optional(Bool.self, .summarized) ?? false)115        case "image": self = .image(attachmentId: try c.decode(String.self, forKey: .attachmentId), mime: c.optional(String.self, .mime) ?? "image/png", name: c.optional(String.self, .name))116        case "file": self = .file(attachmentId: try c.decode(String.self, forKey: .attachmentId), mime: c.optional(String.self, .mime) ?? "application/octet-stream", name: c.optional(String.self, .name) ?? "fichier", size: c.flexInt(.size), pages: c.flexInt(.pages))117        case "tool_call":118            self = .toolCall(ToolCall(id: try c.decode(String.self, forKey: .id), name: c.optional(String.self, .name) ?? "?", input: c.optional(JSONValue.self, .input) ?? .null,119                                      status: c.optional(ToolCallStatus.self, .status) ?? .error, output: c.optional(JSONValue.self, .output), durationMs: c.flexInt(.durationMs), error: c.optional(String.self, .error)))120        case "artifact": self = .artifact(artifactId: try c.decode(String.self, forKey: .artifactId), title: c.optional(String.self, .title) ?? "Artefact", artifactType: c.optional(String.self, .artifactType) ?? "text", language: c.optional(String.self, .language))121        case "citation": self = .citation(url: c.optional(String.self, .url) ?? "", title: c.optional(String.self, .title), snippet: c.optional(String.self, .snippet))122        case "generated_image": self = .generatedImage(attachmentId: try c.decode(String.self, forKey: .attachmentId), prompt: c.optional(String.self, .prompt) ?? "", model: c.optional(String.self, .model) ?? "")123        default: self = .unknown(try JSONValue(from: decoder))124        }125    }126127    public func encode(to encoder: Encoder) throws {128        if case .unknown(let v) = self { try v.encode(to: encoder); return }129        var c = encoder.container(keyedBy: K.self)130        switch self {131        case .text(let t): try c.encode("text", forKey: .type); try c.encode(t, forKey: .text)132        case .reasoning(let t, let s): try c.encode("reasoning", forKey: .type); try c.encode(t, forKey: .text); try c.encode(s, forKey: .summarized)133        case .image(let a, let m, let n): try c.encode("image", forKey: .type); try c.encode(a, forKey: .attachmentId); try c.encode(m, forKey: .mime); try c.encodeIfPresent(n, forKey: .name)134        case .file(let a, let m, let n, let s, let p): try c.encode("file", forKey: .type); try c.encode(a, forKey: .attachmentId); try c.encode(m, forKey: .mime); try c.encode(n, forKey: .name); try c.encodeIfPresent(s, forKey: .size); try c.encodeIfPresent(p, forKey: .pages)135        case .toolCall(let t):136            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)137            try c.encodeIfPresent(t.output, forKey: .output); try c.encodeIfPresent(t.durationMs, forKey: .durationMs); try c.encodeIfPresent(t.error, forKey: .error)138        case .artifact(let a, let t, let ty, let l): try c.encode("artifact", forKey: .type); try c.encode(a, forKey: .artifactId); try c.encode(t, forKey: .title); try c.encode(ty, forKey: .artifactType); try c.encodeIfPresent(l, forKey: .language)139        case .citation(let u, let t, let s): try c.encode("citation", forKey: .type); try c.encode(u, forKey: .url); try c.encodeIfPresent(t, forKey: .title); try c.encodeIfPresent(s, forKey: .snippet)140        case .generatedImage(let a, let p, let m): try c.encode("generated_image", forKey: .type); try c.encode(a, forKey: .attachmentId); try c.encode(p, forKey: .prompt); try c.encode(m, forKey: .model)141        case .unknown: break142        }143    }144145    public var textValue: String? { if case .text(let t) = self { return t }; return nil }146    public var isToolCall: Bool { if case .toolCall = self { return true }; return false }147}148149// MARK: - Message150151public enum MessageRole: String, Sendable, Codable, Hashable { case user, assistant, system, tool }152153/// End state of an answer. The server guarantees exactly one of complete · cancelled · incomplete · error once streaming stops.154public enum MessageStatus: Sendable, Hashable, Codable {155    case complete, streaming, cancelled, incomplete, error, other(String)156    public init(rawValue: String) {157        switch rawValue {158        case "complete": self = .complete159        case "streaming": self = .streaming160        case "cancelled": self = .cancelled161        case "incomplete": self = .incomplete162        case "error": self = .error163        default: self = .other(rawValue)164        }165    }166    public var rawValue: String {167        switch self {168        case .complete: "complete"; case .streaming: "streaming"; case .cancelled: "cancelled"; case .incomplete: "incomplete"; case .error: "error"169        case .other(let s): s170        }171    }172    public init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }173    public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }174}175176public struct TokenUsage: Sendable, Hashable, Codable {177    public var input: Int178    public var output: Int179    public var cached: Int?180    public var reasoning: Int?181    /// Set only when the provider reported the exact billed cost of the request (xAI, OpenRouter).182    public var costUsd: Double?183    enum CodingKeys: String, CodingKey { case input, output, cached, reasoning, costUsd }184    public 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 }185    public init(from decoder: Decoder) throws {186        let c = try decoder.container(keyedBy: CodingKeys.self)187        input = c.flexInt(.input) ?? 0; output = c.flexInt(.output) ?? 0; cached = c.flexInt(.cached); reasoning = c.flexInt(.reasoning); costUsd = c.flexDouble(.costUsd)188    }189}190191public struct Routing: Sendable, Hashable, Codable {192    public var mode: String?193    public var selected: String?194    public var reason: String?195    public var servedBy: String?196    public init(mode: String? = nil, selected: String? = nil, reason: String? = nil, servedBy: String? = nil) { self.mode = mode; self.selected = selected; self.reason = reason; self.servedBy = servedBy }197}198199/// Which requested parameters were really sent to the model, and which were ignored (with the reason).200public struct AppliedParameters: Sendable, Hashable, Codable {201    public struct Ignored: Sendable, Hashable, Codable { public var param: String; public var requested: JSONValue; public var reason: String }202    public var applied: [String: JSONValue]203    public var ignored: [Ignored]204    public init(applied: [String: JSONValue] = [:], ignored: [Ignored] = []) { self.applied = applied; self.ignored = ignored }205    public init(from decoder: Decoder) throws {206        let c = try decoder.container(keyedBy: CodingKeys.self)207        applied = c.optional([String: JSONValue].self, .applied) ?? [:]208        ignored = c.optional([Ignored].self, .ignored) ?? []209    }210    enum CodingKeys: String, CodingKey { case applied, ignored }211}212213public struct Message: Sendable, Hashable, Identifiable, Codable {214    public var id: String215    public var conversationId: String216    public var parentId: String?217    public var role: MessageRole218    public var parts: [MessagePart]219    public var text: String220    public var modelId: String?221    public var provider: String?222    public var settings: JSONValue?223    public var routing: Routing?224    public var usage: TokenUsage?225    public var costUsd: Double?226    public var latencyMs: Int?227    public var ttftMs: Int?228    public var status: MessageStatus229    public var error: String?230    public var errorCode: String?231    public var stopReason: String?232    public var active: Bool233    public var createdAt: Date234    /// Smart Follow-Ups proposed by the server after the answer (at most three).235    public var followups: [String]?236    /// The `usage` event said the cost is the amount billed by the provider (otherwise it is an estimate).237    public var exactCost: Bool?238239    enum CodingKeys: String, CodingKey {240        case id, role, parts, text, provider, settings, routing, usage, status, error, active, followups, exactCost241        case conversationId = "conversation_id", parentId = "parent_id", modelId = "model_id", costUsd = "cost_usd", latencyMs = "latency_ms", ttftMs = "ttft_ms"242        case errorCode = "error_code", stopReason = "stop_reason", createdAt = "created_at"243    }244245    public init(id: String, conversationId: String, parentId: String? = nil, role: MessageRole, parts: [MessagePart], text: String? = nil, modelId: String? = nil, provider: String? = nil,246                settings: JSONValue? = nil, routing: Routing? = nil, usage: TokenUsage? = nil, costUsd: Double? = nil, latencyMs: Int? = nil, ttftMs: Int? = nil,247                status: MessageStatus = .complete, error: String? = nil, errorCode: String? = nil, stopReason: String? = nil, active: Bool = true, createdAt: Date = Date()) {248        self.id = id; self.conversationId = conversationId; self.parentId = parentId; self.role = role; self.parts = parts249        self.text = text ?? parts.compactMap(\.textValue).joined(separator: "\n")250        self.modelId = modelId; self.provider = provider; self.settings = settings; self.routing = routing; self.usage = usage; self.costUsd = costUsd251        self.latencyMs = latencyMs; self.ttftMs = ttftMs; self.status = status; self.error = error; self.errorCode = errorCode; self.stopReason = stopReason; self.active = active; self.createdAt = createdAt252    }253254    public init(from decoder: Decoder) throws {255        let c = try decoder.container(keyedBy: CodingKeys.self)256        id = try c.decode(String.self, forKey: .id)257        conversationId = c.optional(String.self, .conversationId) ?? ""258        parentId = c.optional(String.self, .parentId)259        role = c.optional(MessageRole.self, .role) ?? .assistant260        parts = c.optional([MessagePart].self, .parts) ?? []261        text = c.optional(String.self, .text) ?? parts.compactMap(\.textValue).joined(separator: "\n")262        modelId = c.optional(String.self, .modelId)263        provider = c.optional(String.self, .provider)264        settings = c.optional(JSONValue.self, .settings)265        routing = c.optional(Routing.self, .routing)266        usage = c.optional(TokenUsage.self, .usage)267        costUsd = c.flexDouble(.costUsd)268        latencyMs = c.flexInt(.latencyMs)269        ttftMs = c.flexInt(.ttftMs)270        status = c.optional(MessageStatus.self, .status) ?? .complete271        error = c.optional(String.self, .error)272        errorCode = c.optional(String.self, .errorCode)273        stopReason = c.optional(String.self, .stopReason)274        active = c.optional(Bool.self, .active) ?? true275        createdAt = c.optional(Date.self, .createdAt) ?? Date()276        followups = c.optional([String].self, .followups)277        exactCost = c.optional(Bool.self, .exactCost)278    }279280    /// The cost shown is the amount billed by the provider (reported in `usage.costUsd` or by the `usage` event).281    public var isCostExact: Bool { exactCost == true || usage?.costUsd != nil }282    /// Cost wording for an answer: « local · 0 $ » on the local route (nothing is billed), else the amount with283    /// « facturé » (reported by the provider) or « estimé » (tokens × catalogue price).284    public func costLabel(route: String?) -> String? {285        if route == "local" { return "local · 0 $" }286        guard let c = costUsd else { return nil }287        return "\(Format.usd(c)) \(isCostExact ? "facturé" : "estimé")"288    }289    /// Sources returned by `web_search` for this answer, in order, without duplicates.290    public var citations: [Citation] {291        var seen = Set<String>(); var out: [Citation] = []292        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)) } }293        return out294    }295    /// Concatenated visible text (text parts only), as the server computes `messages.text`.296    public var visibleText: String { parts.compactMap(\.textValue).joined(separator: "\n") }297    public var reasoningText: String? { for p in parts { if case .reasoning(let t, _) = p, !t.isEmpty { return t } }; return nil }298    public var appliedParameters: AppliedParameters? {299        guard let a = settings?["applied"], let data = try? JSONEncoder().encode(a) else { return nil }300        return try? JSONDecoder().decode(AppliedParameters.self, from: data)301    }302    public var isOptimistic: Bool { id.hasPrefix("tmp_") }303}304305/// One web source of an answer (`citation` part).306public struct Citation: Sendable, Hashable, Identifiable {307    public var url: String308    public var title: String?309    public var snippet: String?310    public var id: String { url }311    public init(url: String, title: String? = nil, snippet: String? = nil) { self.url = url; self.title = title; self.snippet = snippet }312    /// Host without `www.` — shown as the caption of a source card.313    public var domain: String {314        guard let host = URLComponents(string: url)?.host?.lowercased() else { return url }315        return host.hasPrefix("www.") ? String(host.dropFirst(4)) : host316    }317}318319public struct SiblingCount: Sendable, Hashable, Codable {320    public var parentId: String?321    public var role: String322    public var n: Int323    enum CodingKeys: String, CodingKey { case parentId = "parent_id", role, n }324}325326// MARK: - Attachments & artefacts327328public struct Attachment: Sendable, Hashable, Identifiable, Codable {329    public var id: String330    public var filename: String331    public var mime: String332    public var sizeBytes: Int?333    public var kind: String?334    public var pageCount: Int?335    public var messageId: String?336    public var indexStatus: String?337    public var indexError: String?338    public var chunkCount: Int?339    public var chars: Int?340    public var conversationId: String?341    public var projectId: String?342    public var conversationTitle: String?343    public var createdAt: Date?344345    enum CodingKeys: String, CodingKey {346        case id, filename, mime, kind, chars, size, pages347        case sizeBytes = "size_bytes", pageCount = "page_count", messageId = "message_id", indexStatus = "index_status", indexError = "index_error", chunkCount = "chunk_count"348        case conversationId = "conversation_id", projectId = "project_id", conversationTitle = "conversation_title", createdAt = "created_at"349    }350    public init(id: String, filename: String, mime: String, sizeBytes: Int? = nil, pageCount: Int? = nil) { self.id = id; self.filename = filename; self.mime = mime; self.sizeBytes = sizeBytes; self.pageCount = pageCount }351    public init(from decoder: Decoder) throws {352        let c = try decoder.container(keyedBy: CodingKeys.self)353        id = try c.decode(String.self, forKey: .id)354        filename = c.optional(String.self, .filename) ?? "fichier"355        mime = c.optional(String.self, .mime) ?? "application/octet-stream"356        sizeBytes = c.flexInt(.sizeBytes) ?? c.flexInt(.size)357        kind = c.optional(String.self, .kind)358        pageCount = c.flexInt(.pageCount) ?? c.flexInt(.pages)359        messageId = c.optional(String.self, .messageId)360        indexStatus = c.optional(String.self, .indexStatus)361        indexError = c.optional(String.self, .indexError)362        chunkCount = c.flexInt(.chunkCount)363        chars = c.flexInt(.chars)364        conversationId = c.optional(String.self, .conversationId)365        projectId = c.optional(String.self, .projectId)366        conversationTitle = c.optional(String.self, .conversationTitle)367        createdAt = c.optional(Date.self, .createdAt)368    }369    public func encode(to encoder: Encoder) throws {370        var c = encoder.container(keyedBy: CodingKeys.self)371        try c.encode(id, forKey: .id); try c.encode(filename, forKey: .filename); try c.encode(mime, forKey: .mime)372        try c.encodeIfPresent(sizeBytes, forKey: .sizeBytes); try c.encodeIfPresent(kind, forKey: .kind); try c.encodeIfPresent(pageCount, forKey: .pageCount)373        try c.encodeIfPresent(messageId, forKey: .messageId); try c.encodeIfPresent(indexStatus, forKey: .indexStatus); try c.encodeIfPresent(indexError, forKey: .indexError)374        try c.encodeIfPresent(chunkCount, forKey: .chunkCount); try c.encodeIfPresent(chars, forKey: .chars); try c.encodeIfPresent(conversationId, forKey: .conversationId)375        try c.encodeIfPresent(projectId, forKey: .projectId); try c.encodeIfPresent(conversationTitle, forKey: .conversationTitle); try c.encodeIfPresent(createdAt, forKey: .createdAt)376    }377    public var isImage: Bool { mime.hasPrefix("image/") }378    /// The message part that references this file in a user message.379    public var asPart: MessagePart {380        isImage ? .image(attachmentId: id, mime: mime, name: filename) : .file(attachmentId: id, mime: mime, name: filename, size: sizeBytes, pages: pageCount)381    }382}383384public struct Artifact: Sendable, Hashable, Identifiable, Codable {385    public var id: String386    public var rootId: String?387    public var version: Int388    public var type: String389    public var language: String?390    public var title: String391    public var saved: Bool392    public var messageId: String?393    public var content: String?394    public var createdAt: Date?395    enum CodingKeys: String, CodingKey { case id, version, type, language, title, saved, content; case rootId = "root_id", messageId = "message_id", createdAt = "created_at" }396    public init(id: String, rootId: String? = nil, version: Int = 1, type: String, language: String? = nil, title: String, saved: Bool = false, messageId: String? = nil, content: String? = nil, createdAt: Date? = nil) {397        self.id = id; self.rootId = rootId; self.version = version; self.type = type; self.language = language; self.title = title; self.saved = saved; self.messageId = messageId; self.content = content; self.createdAt = createdAt398    }399    public init(from decoder: Decoder) throws {400        let c = try decoder.container(keyedBy: CodingKeys.self)401        id = try c.decode(String.self, forKey: .id)402        rootId = c.optional(String.self, .rootId); version = c.flexInt(.version) ?? 1; type = c.optional(String.self, .type) ?? "text"403        language = c.optional(String.self, .language); title = c.optional(String.self, .title) ?? "Artefact"; saved = c.optional(Bool.self, .saved) ?? false404        messageId = c.optional(String.self, .messageId); content = c.optional(String.self, .content); createdAt = c.optional(Date.self, .createdAt)405    }406}407408/// Everything `GET /api/conversations/:id?all=1` returns.409public struct ConversationDetail: Sendable, Hashable, Codable {410    public var conversation: Conversation411    /// Every message of the tree (active and inactive branches).412    public var messages: [Message]413    public var siblings: [SiblingCount]414    public var attachments: [Attachment]415    public var artifacts: [Artifact]416    public var draft: String?417    public var liveRun: String?418419    public init(conversation: Conversation, messages: [Message], siblings: [SiblingCount] = [], attachments: [Attachment] = [], artifacts: [Artifact] = [], draft: String? = nil, liveRun: String? = nil) {420        self.conversation = conversation; self.messages = messages; self.siblings = siblings; self.attachments = attachments; self.artifacts = artifacts; self.draft = draft; self.liveRun = liveRun421    }422    public init(from decoder: Decoder) throws {423        let c = try decoder.container(keyedBy: CodingKeys.self)424        conversation = try c.decode(Conversation.self, forKey: .conversation)425        messages = c.optional([Message].self, .messages) ?? []426        siblings = c.optional([SiblingCount].self, .siblings) ?? []427        attachments = c.optional([Attachment].self, .attachments) ?? []428        artifacts = c.optional([Artifact].self, .artifacts) ?? []429        draft = c.optional(String.self, .draft)430        liveRun = c.optional(String.self, .liveRun)431    }432    enum CodingKeys: String, CodingKey { case conversation, messages, siblings, attachments, artifacts, draft, liveRun }433434    /// The thread currently displayed.435    public var activeMessages: [Message] { messages.filter(\.active) }436437    /// Versions of the same turn (same parent, same role), oldest first — used for the ◀ 2/3 ▶ navigation.438    public func versions(of message: Message) -> [Message] {439        messages.filter { $0.parentId == message.parentId && $0.role == message.role }.sorted { $0.createdAt < $1.createdAt }440    }441}442
Files main
Menu

Theme