Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Models/PanelModels.swift3// Description: DTOs and endpoints of a conversation's contextual panel: Context Inspector report, timeline (Replay), family tree and variants, stored Response Lenses.4import Foundation56private extension KeyedDecodingContainer {7 /// Server dates arrive as ISO 8601 strings with milliseconds, or with microseconds and an offset (`…090407-05:00`).8 func serverDate(_ key: Key) -> Date? { optional(String.self, key).flatMap(ServerDate.parse) }9 func string(_ key: Key) -> String? {10 if let s = optional(String.self, key) { return s }11 if let n = flexDouble(key) { return n.rounded() == n ? String(Int(n)) : String(n) }12 return nil13 }14}1516// MARK: - Context Inspector1718/// `GET /api/conversations/{id}/context?model=` — what the next request of this conversation would carry.19/// `measured` is reported by the provider for the last answer; `estimate` is a computation and must be shown as one.20public struct ContextReport: Sendable, Hashable, Decodable {21 public struct Model: Sendable, Hashable, Decodable {22 public var id: String23 public var displayName: String24 public var provider: String?25 public var route: String?26 public var creator: String?27 public var creatorName: String?28 public var logo: String?29 public var contextWindow: Int?30 public var maxOutputTokens: Int?31 public var status: String?32 enum CodingKeys: String, CodingKey { case id, displayName, provider, route, creator, creatorName, logo, contextWindow, maxOutputTokens, status }33 public init(id: String, displayName: String? = nil, contextWindow: Int? = nil, maxOutputTokens: Int? = nil) { self.id = id; self.displayName = displayName ?? id; self.contextWindow = contextWindow; self.maxOutputTokens = maxOutputTokens }34 public init(from decoder: Decoder) throws {35 let c = try decoder.container(keyedBy: CodingKeys.self)36 id = c.optional(String.self, .id) ?? ""37 displayName = c.optional(String.self, .displayName) ?? id38 provider = c.optional(String.self, .provider); route = c.optional(String.self, .route)39 creator = c.optional(String.self, .creator); creatorName = c.optional(String.self, .creatorName); logo = c.optional(String.self, .logo)40 contextWindow = c.flexInt(.contextWindow); maxOutputTokens = c.flexInt(.maxOutputTokens); status = c.optional(String.self, .status)41 }42 }4344 /// Token counts reported by the provider for the last answer.45 public struct Measured: Sendable, Hashable, Decodable {46 public var source: String?47 public var inputTokens: Int?48 public var outputTokens: Int?49 public var cachedTokens: Int?50 public var reasoningTokens: Int?51 /// Model that produced the measured answer (may differ from the model selected for the next turn).52 public var model: String?53 public var at: Date?54 enum CodingKeys: String, CodingKey { case source, inputTokens, outputTokens, cachedTokens, reasoningTokens, model, at }55 public init(from decoder: Decoder) throws {56 let c = try decoder.container(keyedBy: CodingKeys.self)57 source = c.optional(String.self, .source); model = c.optional(String.self, .model); at = c.serverDate(.at)58 inputTokens = c.flexInt(.inputTokens); outputTokens = c.flexInt(.outputTokens); cachedTokens = c.flexInt(.cachedTokens); reasoningTokens = c.flexInt(.reasoningTokens)59 }60 }6162 public struct Estimate: Sendable, Hashable, Decodable {63 public var source: String?64 public var nextRequestTokens: Int?65 /// Percentage (0…100) of the model's context window, as computed by the server.66 public var percentOfContext: Double?67 public var images: Int?68 enum CodingKeys: String, CodingKey { case source, nextRequestTokens, percentOfContext, images }69 public init(from decoder: Decoder) throws {70 let c = try decoder.container(keyedBy: CodingKeys.self)71 source = c.optional(String.self, .source); nextRequestTokens = c.flexInt(.nextRequestTokens); percentOfContext = c.flexDouble(.percentOfContext); images = c.flexInt(.images)72 }73 /// Gauge position (0…1).74 public var fraction: Double? { percentOfContext.map { min(max($0 / 100, 0), 1) } }75 }7677 public struct MessageCounts: Sendable, Hashable, Decodable {78 public var count: Int79 public var user: Int?80 public var assistant: Int?81 enum CodingKeys: String, CodingKey { case count, user, assistant }82 public init(count: Int = 0, user: Int? = nil, assistant: Int? = nil) { self.count = count; self.user = user; self.assistant = assistant }83 public init(from decoder: Decoder) throws {84 let c = try decoder.container(keyedBy: CodingKeys.self)85 count = c.flexInt(.count) ?? 0; user = c.flexInt(.user); assistant = c.flexInt(.assistant)86 }87 }8889 /// A file carried by the conversation. The server's field names are read tolerantly (`filename` / `name`, `size_bytes` / `sizeBytes` / `size`).90 public struct File: Sendable, Hashable, Decodable, Identifiable {91 public var id: String92 public var filename: String93 public var mime: String?94 public var sizeBytes: Int?95 public var tokens: Int?96 public var kind: String?97 /// Characters of extracted text (nil for a file without text, e.g. an image).98 public var chars: Int?99 public var pageCount: Int?100 /// `indexed` · `skipped` · … (kept as sent).101 public var indexStatus: String?102 enum CodingKeys: String, CodingKey { case id, filename, name, mime, sizeBytes, size_bytes, size, tokens, estimatedTokens, kind, chars, page_count, index_status }103 public init(from decoder: Decoder) throws {104 let c = try decoder.container(keyedBy: CodingKeys.self)105 filename = c.optional(String.self, .filename) ?? c.optional(String.self, .name) ?? "Fichier"106 id = c.optional(String.self, .id) ?? filename107 mime = c.optional(String.self, .mime); kind = c.optional(String.self, .kind)108 sizeBytes = c.flexInt(.sizeBytes) ?? c.flexInt(.size_bytes) ?? c.flexInt(.size)109 tokens = c.flexInt(.tokens) ?? c.flexInt(.estimatedTokens)110 chars = c.flexInt(.chars); pageCount = c.flexInt(.page_count); indexStatus = c.optional(String.self, .index_status)111 }112 }113114 public struct Tools: Sendable, Hashable, Decodable {115 public struct Tool: Sendable, Hashable, Decodable, Identifiable {116 public var name: String117 public var category: String?118 public var id: String { name }119 enum CodingKeys: String, CodingKey { case name, category }120 public init(from decoder: Decoder) throws {121 // a bare string is accepted as a tool name122 if let s = try? decoder.singleValueContainer().decode(String.self) { name = s; category = nil; return }123 let c = try decoder.container(keyedBy: CodingKeys.self)124 name = c.optional(String.self, .name) ?? "?"; category = c.optional(String.self, .category)125 }126 }127 public var enabled: Bool128 public var list: [Tool]129 enum CodingKeys: String, CodingKey { case enabled, list }130 public init(enabled: Bool = false, list: [Tool] = []) { self.enabled = enabled; self.list = list }131 public init(from decoder: Decoder) throws {132 let c = try decoder.container(keyedBy: CodingKeys.self)133 enabled = c.optional(Bool.self, .enabled) ?? false134 list = (c.optional([Lossy<Tool>].self, .list) ?? []).compactMap(\.value)135 }136 }137138 public struct Cost: Sendable, Hashable, Decodable {139 public var conversationUsd: Double?140 public var source: String?141 enum CodingKeys: String, CodingKey { case conversationUsd, source }142 public init(conversationUsd: Double? = nil, source: String? = nil) { self.conversationUsd = conversationUsd; self.source = source }143 public init(from decoder: Decoder) throws {144 let c = try decoder.container(keyedBy: CodingKeys.self)145 conversationUsd = c.flexDouble(.conversationUsd); source = c.optional(String.self, .source)146 }147 }148149 public var model: Model?150 public var measured: Measured?151 public var estimate: Estimate?152 public var messages: MessageCounts153 public var files: [File]154 public var tools: Tools155 public var cost: Cost156 public var streaming: Bool157158 enum CodingKeys: String, CodingKey { case model, measured, estimate, messages, files, tools, cost, streaming }159 public init(from decoder: Decoder) throws {160 let c = try decoder.container(keyedBy: CodingKeys.self)161 model = c.optional(Model.self, .model); measured = c.optional(Measured.self, .measured); estimate = c.optional(Estimate.self, .estimate)162 messages = c.optional(MessageCounts.self, .messages) ?? MessageCounts()163 files = (c.optional([Lossy<File>].self, .files) ?? []).compactMap(\.value)164 tools = c.optional(Tools.self, .tools) ?? Tools()165 cost = c.optional(Cost.self, .cost) ?? Cost()166 streaming = c.optional(Bool.self, .streaming) ?? false167 }168}169170// MARK: - Timeline171172/// One recorded event of a conversation (`GET /api/conversations/{id}/timeline`). The `type` is kept as sent: an173/// unknown type is rendered generically, never dropped.174public struct TimelineEvent: Sendable, Hashable, Decodable, Identifiable {175 public enum Kind: String, Sendable, Hashable, CaseIterable { case prompt, response, modelSwitch = "model_switch", tool, file, image, artifact, branch, unknown }176177 /// Position in the server's list (the list order is the replay order).178 public var index: Int = 0179 public var id: Int { index }180 public var type: String181 public var at: Date?182 public var messageId: String?183 /// False for a variant of a turn that is not the one displayed.184 public var active: Bool185 /// Server id of the underlying record (tool execution, artefact, attachment), when sent.186 public var recordId: String?187 public var preview: String?188 public var chars: Int?189 public var attachments: Int?190 // response191 public var model: String?192 public var provider: String?193 public var status: String?194 public var usage: TokenUsage?195 public var costUsd: Double?196 public var latencyMs: Int?197 public var ttftMs: Int?198 public var routing: Routing?199 public var citations: Int?200 public var variant: Int?201 public var variants: Int?202 // model_switch203 public var from: String?204 public var to: String?205 // tool206 public var tool: String?207 public var durationMs: Int?208 // branch209 public var conversationId: String?210 // artifact / file / image / branch211 public var title: String?212 public var artifactType: String?213 public var version: Int?214 public var filename: String?215 public var mime: String?216 public var sizeBytes: Int?217218 enum CodingKeys: String, CodingKey {219 case type, at, messageId, active, id, preview, chars, attachments, model, provider, status, usage, costUsd, latencyMs, ttftMs, routing, citations, variant, variants220 case from, to, tool, durationMs, conversationId, title, artifactType, version, filename, name, mime, sizeBytes, size221 }222223 public init(type: String, at: Date? = nil, messageId: String? = nil, active: Bool = true, index: Int = 0) { self.type = type; self.at = at; self.messageId = messageId; self.active = active; self.index = index }224225 public init(from decoder: Decoder) throws {226 let c = try decoder.container(keyedBy: CodingKeys.self)227 type = c.optional(String.self, .type) ?? "unknown"228 at = c.serverDate(.at); messageId = c.optional(String.self, .messageId); active = c.optional(Bool.self, .active) ?? true229 recordId = c.string(.id); preview = c.optional(String.self, .preview); chars = c.flexInt(.chars); attachments = c.flexInt(.attachments)230 model = c.optional(String.self, .model); provider = c.optional(String.self, .provider); status = c.optional(String.self, .status)231 usage = c.optional(TokenUsage.self, .usage); costUsd = c.flexDouble(.costUsd); latencyMs = c.flexInt(.latencyMs); ttftMs = c.flexInt(.ttftMs)232 routing = c.optional(Routing.self, .routing); citations = c.flexInt(.citations); variant = c.flexInt(.variant); variants = c.flexInt(.variants)233 from = c.optional(String.self, .from); to = c.optional(String.self, .to)234 tool = c.optional(String.self, .tool); durationMs = c.flexInt(.durationMs)235 conversationId = c.optional(String.self, .conversationId)236 title = c.optional(String.self, .title); artifactType = c.optional(String.self, .artifactType); version = c.flexInt(.version)237 filename = c.optional(String.self, .filename) ?? c.optional(String.self, .name); mime = c.optional(String.self, .mime)238 sizeBytes = c.flexInt(.sizeBytes) ?? c.flexInt(.size)239 }240241 public var kind: Kind { Kind(rawValue: type) ?? .unknown }242 /// The cost is the amount billed by the provider when it is reported inside `usage` (same rule as `Message.isCostExact`).243 public var isCostExact: Bool { usage?.costUsd != nil }244 /// Model that answered, as recorded by the routing (`servedBy` is the upstream provider, kept apart).245 public var servedBy: String? { routing?.servedBy }246}247248public struct ConversationTimeline: Sendable, Hashable, Decodable {249 public struct Header: Sendable, Hashable, Decodable {250 public var id: String?251 public var title: String?252 public var createdAt: Date?253 public var parentId: String?254 public var branchLabel: String?255 enum CodingKeys: String, CodingKey { case id, title, createdAt, parentId, branchLabel }256 public init() {}257 public init(from decoder: Decoder) throws {258 let c = try decoder.container(keyedBy: CodingKeys.self)259 id = c.optional(String.self, .id); title = c.optional(String.self, .title); createdAt = c.serverDate(.createdAt)260 parentId = c.optional(String.self, .parentId); branchLabel = c.optional(String.self, .branchLabel)261 }262 }263 public var conversation: Header264 public var events: [TimelineEvent]265 /// The server's statement about how the timeline was built — shown as-is under the list.266 public var note: String?267268 enum CodingKeys: String, CodingKey { case conversation, events, note }269 public init(conversation: Header = Header(), events: [TimelineEvent] = [], note: String? = nil) {270 self.conversation = conversation; self.note = note271 self.events = events.enumerated().map { i, e in var e = e; e.index = i; return e }272 }273 public init(from decoder: Decoder) throws {274 let c = try decoder.container(keyedBy: CodingKeys.self)275 conversation = c.optional(Header.self, .conversation) ?? Header()276 note = c.optional(String.self, .note)277 events = (c.optional([Lossy<TimelineEvent>].self, .events) ?? []).compactMap(\.value).enumerated().map { i, e in var e = e; e.index = i; return e }278 }279}280281// MARK: - Family tree and variants282283/// `GET /api/conversations/{id}/tree` — the conversation's family (root, branches, sub-branches) and the variants284/// (regenerations, edits) of its turns.285public struct ConversationTree: Sendable, Hashable, Decodable {286 public struct Node: Sendable, Hashable, Decodable, Identifiable {287 public var id: String288 public var parentId: String?289 public var title: String290 public var branchLabel: String?291 public var branchMessageId: String?292 public var modelId: String?293 public var messageCount: Int294 public var archivedAt: Date?295 public var lastAt: Date?296 public var createdAt: Date?297 public var depth: Int298 enum CodingKeys: String, CodingKey {299 case id, title, depth300 case parentId = "parent_id", branchLabel = "branch_label", branchMessageId = "branch_message_id", modelId = "model_id", messageCount = "message_count"301 case archivedAt = "archived_at", lastAt = "last_at", createdAt = "created_at"302 }303 public init(from decoder: Decoder) throws {304 let c = try decoder.container(keyedBy: CodingKeys.self)305 id = try c.decode(String.self, forKey: .id)306 parentId = c.optional(String.self, .parentId); title = c.optional(String.self, .title) ?? "Sans titre"307 branchLabel = c.optional(String.self, .branchLabel).flatMap { $0.isEmpty ? nil : $0 }308 branchMessageId = c.optional(String.self, .branchMessageId); modelId = c.optional(String.self, .modelId)309 messageCount = c.flexInt(.messageCount) ?? 0; depth = max(0, c.flexInt(.depth) ?? 0)310 archivedAt = c.serverDate(.archivedAt); lastAt = c.serverDate(.lastAt); createdAt = c.serverDate(.createdAt)311 }312 public var isRoot: Bool { parentId == nil }313 }314315 /// The versions of one turn (same parent message, same role).316 public struct VariantGroup: Sendable, Hashable, Decodable, Identifiable {317 public struct Option: Sendable, Hashable, Decodable, Identifiable {318 public var id: String319 public var active: Bool320 public var model: String?321 public var status: String?322 public var createdAt: Date?323 public var preview: String?324 enum CodingKeys: String, CodingKey { case id, active, model, status, createdAt, preview }325 public init(from decoder: Decoder) throws {326 let c = try decoder.container(keyedBy: CodingKeys.self)327 id = try c.decode(String.self, forKey: .id)328 active = c.optional(Bool.self, .active) ?? false; model = c.optional(String.self, .model); status = c.optional(String.self, .status)329 createdAt = c.serverDate(.createdAt); preview = c.optional(String.self, .preview)330 }331 }332 public var parentId: String?333 public var role: String334 public var options: [Option]335 public var id: String { (parentId ?? "root") + ":" + role }336 enum CodingKeys: String, CodingKey { case parentId = "parent_id", role, options }337 public init(from decoder: Decoder) throws {338 let c = try decoder.container(keyedBy: CodingKeys.self)339 parentId = c.optional(String.self, .parentId); role = c.optional(String.self, .role) ?? "assistant"340 options = (c.optional([Lossy<Option>].self, .options) ?? []).compactMap(\.value)341 }342 }343344 public var current: String?345 public var family: [Node]346 public var variants: [VariantGroup]347 enum CodingKeys: String, CodingKey { case current, family, variants }348 public init(from decoder: Decoder) throws {349 let c = try decoder.container(keyedBy: CodingKeys.self)350 current = c.optional(String.self, .current)351 family = (c.optional([Lossy<Node>].self, .family) ?? []).compactMap(\.value)352 variants = (c.optional([Lossy<VariantGroup>].self, .variants) ?? []).compactMap(\.value)353 }354 /// A conversation alone in its family has no branch to show.355 public var hasBranches: Bool { family.count > 1 }356}357358// MARK: - Response Lens (stored)359360public struct LensKind: Sendable, Hashable, Decodable, Identifiable {361 public var id: String362 public var label: String363 /// The lens runs real web searches (`verify`).364 public var usesWeb: Bool365 enum CodingKeys: String, CodingKey { case id, label, usesWeb }366 public init(id: String, label: String, usesWeb: Bool = false) { self.id = id; self.label = label; self.usesWeb = usesWeb }367 public init(from decoder: Decoder) throws {368 let c = try decoder.container(keyedBy: CodingKeys.self)369 id = try c.decode(String.self, forKey: .id)370 label = c.optional(String.self, .label) ?? id; usesWeb = c.optional(Bool.self, .usesWeb) ?? false371 }372}373374/// A source checked by the `verify` lens.375public struct LensSource: Sendable, Hashable, Decodable, Identifiable {376 public var url: String377 public var title: String?378 /// The statement of the answer this source was checked against.379 public var claim: String?380 public var id: String { url + "|" + (claim ?? "") }381 enum CodingKeys: String, CodingKey { case url, title, claim }382 public init(url: String, title: String? = nil, claim: String? = nil) { self.url = url; self.title = title; self.claim = claim }383 public init(from decoder: Decoder) throws {384 let c = try decoder.container(keyedBy: CodingKeys.self)385 url = c.optional(String.self, .url) ?? ""; title = c.optional(String.self, .title); claim = c.optional(String.self, .claim)386 }387 public var domain: String {388 guard let host = URL(string: url)?.host else { return url }389 return host.hasPrefix("www.") ? String(host.dropFirst(4)) : host390 }391}392393/// A lens kept by the server for a message — from the list (`snake_case` columns) or from the `done` event of a run (`camelCase`).394public struct StoredLens: Sendable, Hashable, Decodable, Identifiable {395 public var id: String396 public var lens: String397 public var modelId: String?398 public var content: String399 public var sources: [LensSource]400 public var usage: TokenUsage?401 public var costUsd: Double?402 /// Sent by the `done` event only: true when the provider reported the billed amount.403 public var exactCost: Bool?404 public var latencyMs: Int?405 public var status: String?406 public var error: String?407 public var createdAt: Date?408409 enum CodingKeys: String, CodingKey {410 case id, lens, content, sources, usage, status, error, model, costUsd, exactCost, latencyMs, createdAt411 case modelId = "model_id", cost_usd, latency_ms, created_at412 }413 public init(id: String, lens: String, modelId: String? = nil, content: String = "", sources: [LensSource] = [], costUsd: Double? = nil, exactCost: Bool? = nil, latencyMs: Int? = nil, status: String? = nil, createdAt: Date? = nil) {414 self.id = id; self.lens = lens; self.modelId = modelId; self.content = content; self.sources = sources; self.costUsd = costUsd; self.exactCost = exactCost; self.latencyMs = latencyMs; self.status = status; self.createdAt = createdAt415 }416 public init(from decoder: Decoder) throws {417 let c = try decoder.container(keyedBy: CodingKeys.self)418 id = c.optional(String.self, .id) ?? ""419 lens = c.optional(String.self, .lens) ?? ""420 modelId = c.optional(String.self, .modelId) ?? c.optional(String.self, .model)421 content = c.optional(String.self, .content) ?? ""422 sources = (c.optional([Lossy<LensSource>].self, .sources) ?? []).compactMap(\.value).filter { !$0.url.isEmpty }423 usage = c.optional(TokenUsage.self, .usage)424 costUsd = c.flexDouble(.cost_usd) ?? c.flexDouble(.costUsd)425 exactCost = c.optional(Bool.self, .exactCost)426 latencyMs = c.flexInt(.latency_ms) ?? c.flexInt(.latencyMs)427 status = c.optional(String.self, .status); error = c.optional(String.self, .error)428 createdAt = c.serverDate(.created_at) ?? c.serverDate(.createdAt)429 }430 /// « facturé » when the provider reported the amount, otherwise the cost is an estimate at the catalogue price.431 public var isCostExact: Bool { exactCost ?? (usage?.costUsd != nil) }432 public var isEmpty: Bool { content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && sources.isEmpty }433}434435public struct LensList: Sendable, Hashable, Decodable {436 public var kinds: [LensKind]437 public var lenses: [StoredLens]438 enum CodingKeys: String, CodingKey { case kinds, lenses }439 public init(kinds: [LensKind] = [], lenses: [StoredLens] = []) { self.kinds = kinds; self.lenses = lenses }440 public init(from decoder: Decoder) throws {441 let c = try decoder.container(keyedBy: CodingKeys.self)442 kinds = (c.optional([Lossy<LensKind>].self, .kinds) ?? []).compactMap(\.value)443 lenses = (c.optional([Lossy<StoredLens>].self, .lenses) ?? []).compactMap(\.value).filter { !$0.id.isEmpty }444 }445 public func label(for lens: String) -> String { kinds.first { $0.id == lens }?.label ?? lens }446}447448// MARK: - Endpoints449450public extension APIClient {451 /// Context Inspector. `model`: the model selected for the next turn (the estimate is computed against its window).452 func conversationContext(_ id: String, model: String? = nil) async throws -> ContextReport {453 try await decode(ContextReport.self, .get, "/api/conversations/\(id)/context", query: ["model": model])454 }455 func conversationTimeline(_ id: String) async throws -> ConversationTimeline { try await decode(ConversationTimeline.self, .get, "/api/conversations/\(id)/timeline") }456 func conversationTree(_ id: String) async throws -> ConversationTree { try await decode(ConversationTree.self, .get, "/api/conversations/\(id)/tree") }457 /// Lens kinds offered by the server and the lenses stored for this answer.458 func lenses(messageId: String) async throws -> LensList { try await decode(LensList.self, .get, "/api/lens", query: ["messageId": messageId]) }459 func deleteLens(_ id: String) async throws { _ = try await raw(.delete, "/api/lens", query: ["id": id]) }460 /// Starts a lens run (`POST /api/lens`, SSE). Real model call — and real web searches for `verify`.461 func openLens(messageId: String, lens: String, modelId: String? = nil) async throws -> StreamOpening {462 var o: [String: JSONValue] = ["messageId": .string(messageId), "lens": .string(lens)]463 if let modelId { o["modelId"] = .string(modelId) }464 return try await openStream(.post, "/api/lens", body: Data(JSONValue.object(o).jsonString().utf8), timeout: 120)465 }466}467