Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Models/CatalogModels.swift3// Description: Model registry, presets, prompts, projects, memories, usage and account DTOs of the chat backend.4import Foundation56// MARK: - Models78public struct AIModel: Sendable, Hashable, Identifiable, Codable {9 public struct Benchmark: Sendable, Hashable, Codable {10 public var tests: Int11 public var passed: Int12 public var qualityScore: Double?13 public var p50LatencyMs: Double?14 public var p50TtftMs: Double?15 public var totalCostUsd: Double?16 public var perTest: [String: String]17 public init(from decoder: Decoder) throws {18 let c = try decoder.container(keyedBy: CodingKeys.self)19 tests = c.flexInt(.tests) ?? 0; passed = c.flexInt(.passed) ?? 0; qualityScore = c.flexDouble(.qualityScore)20 p50LatencyMs = c.flexDouble(.p50LatencyMs); p50TtftMs = c.flexDouble(.p50TtftMs); totalCostUsd = c.flexDouble(.totalCostUsd)21 perTest = c.optional([String: String].self, .perTest) ?? [:]22 }23 enum CodingKeys: String, CodingKey { case tests, passed, qualityScore, p50LatencyMs, p50TtftMs, totalCostUsd, perTest }24 }2526 public var id: String27 /// The API that executes the request: `openai` · `anthropic` · `xai` · `openrouter` (any other value is kept as-is).28 public var provider: String29 public var displayName: String30 public var kind: String31 /// `verified` · `catalog` · `untested` · `unavailable` · `unsupported` (unknown values are kept as-is).32 public var status: String33 public var available: Bool34 public var tested: Bool35 public var unavailableReason: String?36 public var capabilities: [String: JSONValue]37 public var contextWindow: Int?38 public var maxOutputTokens: Int?39 public var pricing: [String: JSONValue]?40 public var benchmark: Benchmark?41 public var hidden: Bool42 public var favorite: Bool43 public var lastVerifiedAt: Date?44 /// `direct`, `openrouter` or `local` (MacLustr AI, the owner's own inference service) — the badge shown next to the model.45 public var route: String46 /// Who made the model (slug of the logo registry when known, else the raw vendor slug) and its display name.47 public var creator: String48 public var creatorName: String49 /// Slug of the bundled logo, or nil → neutral monogram.50 public var logo: String?51 public var description: String?52 /// Derived by the server from facts only (reasoning, vision, long-context, open-weight, free…).53 public var categories: [String]54 public var catalog: CatalogInfo?55 public var lastUsedAt: Date?5657 enum CodingKeys: String, CodingKey { case id, provider, displayName, kind, status, available, tested, unavailableReason, capabilities, contextWindow, maxOutputTokens, pricing, benchmark, hidden, favorite, lastVerifiedAt, route, creator, creatorName, logo, description, categories, catalog, lastUsedAt }5859 public init(id: String, provider: String, displayName: String, kind: String = "chat", status: String = "verified", available: Bool = true, tested: Bool = true,60 capabilities: [String: JSONValue] = [:], contextWindow: Int? = nil, maxOutputTokens: Int? = nil, pricing: [String: JSONValue]? = nil, hidden: Bool = false, favorite: Bool = false,61 route: String? = nil, creator: String? = nil, creatorName: String? = nil, logo: String? = nil, description: String? = nil, categories: [String] = [], catalog: CatalogInfo? = nil, lastUsedAt: Date? = nil) {62 self.id = id; self.provider = provider; self.displayName = displayName; self.kind = kind; self.status = status; self.available = available; self.tested = tested63 self.capabilities = capabilities; self.contextWindow = contextWindow; self.maxOutputTokens = maxOutputTokens; self.pricing = pricing; self.hidden = hidden; self.favorite = favorite64 self.route = route ?? Maker.route(forModelId: id, provider: provider)65 self.creator = creator ?? Maker.slug(forModelId: id, provider: provider); self.creatorName = creatorName ?? Maker.name(self.creator)66 self.logo = logo; self.description = description; self.categories = categories; self.catalog = catalog; self.lastUsedAt = lastUsedAt67 }6869 public init(from decoder: Decoder) throws {70 let c = try decoder.container(keyedBy: CodingKeys.self)71 id = try c.decode(String.self, forKey: .id)72 provider = c.optional(String.self, .provider) ?? "unknown"73 displayName = c.optional(String.self, .displayName) ?? id74 kind = c.optional(String.self, .kind) ?? "chat"75 status = c.optional(String.self, .status) ?? "untested"76 available = c.optional(Bool.self, .available) ?? false77 tested = c.optional(Bool.self, .tested) ?? false78 unavailableReason = c.optional(String.self, .unavailableReason)79 capabilities = c.optional([String: JSONValue].self, .capabilities) ?? [:]80 contextWindow = c.flexInt(.contextWindow)81 maxOutputTokens = c.flexInt(.maxOutputTokens)82 pricing = c.optional([String: JSONValue].self, .pricing)83 benchmark = c.optional(Benchmark.self, .benchmark)84 hidden = c.optional(Bool.self, .hidden) ?? false85 favorite = c.optional(Bool.self, .favorite) ?? false86 lastVerifiedAt = c.optional(Date.self, .lastVerifiedAt)87 // fields added by backend 1.0; an older server (or an older cache) is completed from the id88 route = c.optional(String.self, .route) ?? Maker.route(forModelId: id, provider: provider)89 creator = c.optional(String.self, .creator) ?? Maker.slug(forModelId: id, provider: provider)90 creatorName = c.optional(String.self, .creatorName) ?? Maker.name(creator)91 logo = c.optional(String.self, .logo)92 description = c.optional(String.self, .description)93 categories = c.optional([String].self, .categories) ?? []94 catalog = c.optional(CatalogInfo.self, .catalog)95 lastUsedAt = c.optional(Date.self, .lastUsedAt)96 }9798 /// A model the owner may pick for a conversation: verified, available, and of a conversational kind.99 public var isSelectableForChat: Bool { available && ["chat", "chat-pro", "search"].contains(kind) }100 public func has(_ capability: String) -> Bool { capabilities[capability]?.boolValue == true }101 /// Reasoning efforts accepted by this model, when the provider lists them.102 public var effortLevels: [String]? { capabilities["effortLevels"]?.arrayValue?.compactMap(\.stringValue) }103 /// List price per million tokens. Router models publish a negative sentinel (the price depends on the model picked):104 /// they have no fixed price — see `hasVariablePrice`.105 public var inputPrice: Double? { pricing?["input"]?.doubleValue.flatMap { $0 >= 0 ? $0 : nil } }106 public var outputPrice: Double? { pricing?["output"]?.doubleValue.flatMap { $0 >= 0 ? $0 : nil } }107 public var hasVariablePrice: Bool { (pricing?["input"]?.doubleValue ?? 0) < 0 || (pricing?["output"]?.doubleValue ?? 0) < 0 }108 public var shortName: String {109 var s = displayName110 if s.hasPrefix("Claude ") { s.removeFirst(7) }111 if let r = s.range(of: #" \(\d{4}-\d{2}-\d{2}\)$"#, options: .regularExpression) { s.removeSubrange(r) }112 return s113 }114 public var isOpenRouter: Bool { route == "openrouter" }115 /// Served by MacLustr AI, the owner's own MLX inference service: no per-token cost.116 public var isLocal: Bool { route == "local" }117 public var isDirect: Bool { route == "direct" }118 /// Listed by the OpenRouter catalogue but never run through the local bench: the UI must say so.119 public var isCatalogOnly: Bool { status == "catalog" }120 public var isVerified: Bool { status == "verified" }121 public var cachedInputPrice: Double? { pricing?["cachedInput"]?.doubleValue }122 public var pricingNotes: String? { pricing?["notes"]?.stringValue }123 public var isFree: Bool { categories.contains("free") }124 public var isOpenWeight: Bool { categories.contains("open-weight") }125 /// Input + output price for one million tokens each: a single figure to sort by.126 public var blendedPrice: Double? { guard let i = inputPrice, let o = outputPrice else { return nil }; return i + o }127 /// Date the catalogue says the model was published (OpenRouter `created`).128 public var publishedAt: Date? { catalog?.created.map { Date(timeIntervalSince1970: TimeInterval($0)) } }129}130131/// Metadata published by a route's own catalogue API (OpenRouter `GET /models`). Never hand-written, never guessed.132public struct CatalogInfo: Sendable, Hashable, Codable {133 public struct Reasoning: Sendable, Hashable, Codable {134 public var mandatory: Bool?135 public var efforts: [String]?136 public var defaultEffort: String?137 }138 public var source: String?139 public var slug: String140 public var inputModalities: [String]141 public var outputModalities: [String]142 public var supportedParameters: [String]143 public var tokenizer: String?144 public var huggingFaceId: String?145 public var moderated: Bool?146 public var expirationDate: String?147 public var aliasOf: String?148 public var created: Int?149 public var reasoning: Reasoning?150 /// Extra unit prices as published (USD per unit): image, web_search, cache…151 public var prices: [String: Double]?152 /// Third-party benchmark figures passed through with their source name (e.g. `artificial_analysis`).153 public var benchmarks: JSONValue?154 public var rankedIn: [String]155 /// Facts published by the local route (`source: "local"`): weight quantization, licence, model revision, serving node.156 public var quantization: String?157 public var license: String?158 public var revision: String?159 public var servedBy: String?160161 enum CodingKeys: String, CodingKey { case source, slug, inputModalities, outputModalities, supportedParameters, tokenizer, huggingFaceId, moderated, expirationDate, aliasOf, created, reasoning, prices, benchmarks, rankedIn, quantization, license, revision, servedBy }162 public init(slug: String, inputModalities: [String] = ["text"], outputModalities: [String] = ["text"], supportedParameters: [String] = [], huggingFaceId: String? = nil, created: Int? = nil, rankedIn: [String] = []) {163 self.slug = slug; self.inputModalities = inputModalities; self.outputModalities = outputModalities; self.supportedParameters = supportedParameters; self.huggingFaceId = huggingFaceId; self.created = created; self.rankedIn = rankedIn164 }165 public init(from decoder: Decoder) throws {166 let c = try decoder.container(keyedBy: CodingKeys.self)167 source = c.optional(String.self, .source); slug = c.optional(String.self, .slug) ?? ""168 inputModalities = c.optional([String].self, .inputModalities) ?? []; outputModalities = c.optional([String].self, .outputModalities) ?? []169 supportedParameters = c.optional([String].self, .supportedParameters) ?? []170 tokenizer = c.optional(String.self, .tokenizer); huggingFaceId = c.optional(String.self, .huggingFaceId); moderated = c.optional(Bool.self, .moderated)171 expirationDate = c.optional(String.self, .expirationDate); aliasOf = c.optional(String.self, .aliasOf); created = c.flexInt(.created)172 reasoning = c.optional(Reasoning.self, .reasoning)173 if let raw = c.optional([String: JSONValue].self, .prices) { prices = raw.compactMapValues(\.doubleValue) }174 benchmarks = c.optional(JSONValue.self, .benchmarks); rankedIn = c.optional([String].self, .rankedIn) ?? []175 quantization = c.optional(String.self, .quantization); license = c.optional(String.self, .license); revision = c.optional(String.self, .revision); servedBy = c.optional(String.self, .servedBy)176 }177 /// Names of the third-party benchmark sources (`{"available": [...]}` in lists, full objects in the detail payload).178 public var benchmarkSources: [String] {179 if let a = benchmarks?["available"]?.arrayValue { return a.compactMap(\.stringValue) }180 return benchmarks?.objectValue.map { $0.keys.sorted() } ?? []181 }182}183184/// Maker (creator) helpers. The server sends `creator` / `creatorName` / `logo`; these fallbacks only complete rows185/// decoded from an older payload or built locally, from the model id itself — nothing is guessed beyond the id.186public enum Maker {187 public static let aliases: [String: String] = ["meta-llama": "meta", "mistralai": "mistral", "x-ai": "xai", "aws": "amazon", "moonshotai": "moonshot", "z-ai": "zai", "bytedance-seed": "bytedance",188 "ibm-granite": "ibm", "inference-net": "inference", "aion-labs": "aionlabs", "rekaai": "reka", "dots-studio": "dotsstudio", "arcee-ai": "arcee"]189 public static func route(forModelId id: String, provider: String? = nil) -> String {190 if provider == "openrouter" || id.hasPrefix("or:") { return "openrouter" }191 if provider == "local" || id.hasPrefix("local:") { return "local" }192 return "direct"193 }194 public static func slug(forModelId id: String, provider: String? = nil) -> String {195 // a local id (`local:maclustr-qwen3`) does not name its maker: only the server knows it196 if id.hasPrefix("local:") { return "local" }197 if id.hasPrefix("or:") {198 var vendor = String(id.dropFirst(3).prefix { $0 != "/" }).lowercased()199 if vendor.hasPrefix("~") { vendor.removeFirst() }200 return aliases[vendor] ?? vendor201 }202 if let provider, provider != "openrouter", provider != "unknown" { return provider }203 let l = id.lowercased()204 if l.hasPrefix("claude") { return "anthropic" }205 if l.hasPrefix("gpt") || l.hasPrefix("o1") || l.hasPrefix("o3") || l.hasPrefix("o4") || l.hasPrefix("chatgpt") { return "openai" }206 if l.hasPrefix("grok") { return "xai" }207 return provider ?? "unknown"208 }209 public static func name(_ slug: String) -> String {210 switch slug { case "openai": "OpenAI"; case "anthropic": "Anthropic"; case "xai": "xAI"; case "google": "Google"; case "meta": "Meta"; case "mistral": "Mistral AI"; case "deepseek": "DeepSeek"211 case "openrouter": "OpenRouter"; case "local": "MacLustr AI"; case "unknown": "—"; default: slug.prefix(1).uppercased() + slug.dropFirst() }212 }213}214215public struct ModelCatalog: Sendable, Hashable, Codable {216 public struct OpenRouterState: Sendable, Hashable, Codable {217 public struct Sync: Sendable, Hashable, Codable {218 public var syncedAt: Date?; public var total: Int; public var chat: Int; public var added: Int; public var removed: Int219 enum CodingKeys: String, CodingKey { case syncedAt, total, chat, added, removed }220 public init(from decoder: Decoder) throws {221 let c = try decoder.container(keyedBy: CodingKeys.self)222 syncedAt = c.optional(Date.self, .syncedAt); total = c.flexInt(.total) ?? 0; chat = c.flexInt(.chat) ?? 0; added = c.flexInt(.added) ?? 0; removed = c.flexInt(.removed) ?? 0223 }224 }225 public var configured: Bool226 public var catalog: Sync?227 enum CodingKeys: String, CodingKey { case configured, catalog }228 public init(from decoder: Decoder) throws {229 let c = try decoder.container(keyedBy: CodingKeys.self)230 configured = c.optional(Bool.self, .configured) ?? false; catalog = c.optional(Sync.self, .catalog)231 }232 }233 public var models: [AIModel]234 public var defaultModel: String?235 public var registry: JSONValue?236 /// Model Favorites Dock: up to 8 model ids, synced between the three apps.237 public var dock: [String]238 public var openrouter: OpenRouterState?239 enum CodingKeys: String, CodingKey { case models, defaultModel, registry, dock, openrouter }240 public init(models: [AIModel] = [], defaultModel: String? = nil, registry: JSONValue? = nil, dock: [String] = []) { self.models = models; self.defaultModel = defaultModel; self.registry = registry; self.dock = dock }241 public init(from decoder: Decoder) throws {242 let c = try decoder.container(keyedBy: CodingKeys.self)243 // one unreadable row never hides the rest of the catalogue244 models = (c.optional([Lossy<AIModel>].self, .models) ?? []).compactMap(\.value)245 defaultModel = c.optional(String.self, .defaultModel); registry = c.optional(JSONValue.self, .registry)246 dock = c.optional([String].self, .dock) ?? []; openrouter = c.optional(OpenRouterState.self, .openrouter)247 }248 public var chatModels: [AIModel] { models.filter(\.isSelectableForChat) }249 public func model(_ id: String?) -> AIModel? { guard let id else { return nil }; return models.first { $0.id == id } }250 public var refreshedAt: Date? { registry?["refreshedAt"]?.stringValue.flatMap(ServerDate.parse) }251}252253/// Decodes `T` or nothing: used for arrays where one malformed element must not fail the whole payload.254public struct Lossy<T: Decodable & Sendable>: Decodable, Sendable {255 public let value: T?256 public init(from decoder: Decoder) throws { value = try? T(from: decoder) }257}258259public enum Provider {260 public static func label(_ p: String?) -> String {261 switch p { case "openai": "OpenAI"; case "anthropic": "Anthropic"; case "xai": "xAI"; case "openrouter": "OpenRouter"; case "tavily": "Tavily"; case "local": "MacLustr AI (local)"; case .some(let s): s.capitalized; case .none: "—" }262 }263 public static let known = ["openai", "anthropic", "xai", "openrouter", "local"]264 public static func routeLabel(_ r: String?) -> String { switch r { case "openrouter": "OpenRouter"; case "local": "Local (MacLustr)"; case "direct", .none: "Direct"; case .some(let s): s.capitalized } }265}266267public enum RoutingMode: String, Sendable, Codable, CaseIterable, Hashable {268 case manual, auto, fast, quality, economy269 public var label: String {270 switch self { case .manual: "Manuel"; case .auto: "Automatique"; case .fast: "Rapide"; case .quality: "Qualité"; case .economy: "Économie" }271 }272}273274public enum Effort: String, Sendable, Codable, CaseIterable, Hashable {275 case low, medium, high, xhigh, max276 public var label: String { switch self { case .low: "Faible"; case .medium: "Moyen"; case .high: "Élevé"; case .xhigh: "Très élevé"; case .max: "Maximal" } }277}278279// MARK: - Presets, prompts, projects, memories280281public struct Preset: Sendable, Hashable, Identifiable, Codable {282 public var id: String283 public var name: String284 public var description: String?285 public var icon: String?286 public var builtin: Bool287 public var routingMode: RoutingMode288 public var modelId: String?289 public var effort: Effort?290 public var temperature: Double?291 public var maxOutputTokens: Int?292 public var toolsEnabled: Bool293 public var toolNames: [String]?294 public var systemPrompt: String?295 public var sortOrder: Int296 enum CodingKeys: String, CodingKey {297 case id, name, description, icon, builtin, effort, temperature298 case routingMode = "routing_mode", modelId = "model_id", maxOutputTokens = "max_output_tokens", toolsEnabled = "tools_enabled", toolNames = "tool_names", systemPrompt = "system_prompt", sortOrder = "sort_order"299 }300 public init(id: String, name: String, description: String? = nil, icon: String? = nil, builtin: Bool = false, routingMode: RoutingMode = .manual, modelId: String? = nil, effort: Effort? = nil,301 temperature: Double? = nil, maxOutputTokens: Int? = nil, toolsEnabled: Bool = true, toolNames: [String]? = nil, systemPrompt: String? = nil, sortOrder: Int = 100) {302 self.id = id; self.name = name; self.description = description; self.icon = icon; self.builtin = builtin; self.routingMode = routingMode; self.modelId = modelId; self.effort = effort303 self.temperature = temperature; self.maxOutputTokens = maxOutputTokens; self.toolsEnabled = toolsEnabled; self.toolNames = toolNames; self.systemPrompt = systemPrompt; self.sortOrder = sortOrder304 }305 public init(from decoder: Decoder) throws {306 let c = try decoder.container(keyedBy: CodingKeys.self)307 id = try c.decode(String.self, forKey: .id); name = c.optional(String.self, .name) ?? "Profil"308 description = c.optional(String.self, .description); icon = c.optional(String.self, .icon); builtin = c.optional(Bool.self, .builtin) ?? false309 routingMode = c.optional(RoutingMode.self, .routingMode) ?? .manual; modelId = c.optional(String.self, .modelId); effort = c.optional(Effort.self, .effort)310 temperature = c.flexDouble(.temperature); maxOutputTokens = c.flexInt(.maxOutputTokens); toolsEnabled = c.optional(Bool.self, .toolsEnabled) ?? true311 toolNames = c.optional([String].self, .toolNames); systemPrompt = c.optional(String.self, .systemPrompt); sortOrder = c.flexInt(.sortOrder) ?? 100312 }313 /// Body accepted by `POST /api/presets` and `PATCH /api/presets/:id` (camelCase, see src/lib/schemas.ts).314 public var requestBody: JSONValue {315 .object(["name": .string(name), "description": description.map(JSONValue.string) ?? .null, "icon": icon.map(JSONValue.string) ?? .null, "routingMode": .string(routingMode.rawValue),316 "modelId": modelId.map(JSONValue.string) ?? .null, "effort": effort.map { .string($0.rawValue) } ?? .null, "temperature": temperature.map(JSONValue.number) ?? .null,317 "maxOutputTokens": maxOutputTokens.map { .number(Double($0)) } ?? .null, "toolsEnabled": .bool(toolsEnabled),318 "toolNames": toolNames.map { .array($0.map(JSONValue.string)) } ?? .null, "systemPrompt": systemPrompt.map(JSONValue.string) ?? .null])319 }320}321322public struct Prompt: Sendable, Hashable, Identifiable, Codable {323 public var id: String324 public var title: String325 public var body: String326 public var tags: [String]327 public var favorite: Bool328 public var useCount: Int329 public var lastUsedAt: Date?330 public var updatedAt: Date?331 enum CodingKeys: String, CodingKey { case id, title, body, tags, favorite; case useCount = "use_count", lastUsedAt = "last_used_at", updatedAt = "updated_at" }332 public init(id: String, title: String, body: String, tags: [String] = [], favorite: Bool = false, useCount: Int = 0) { self.id = id; self.title = title; self.body = body; self.tags = tags; self.favorite = favorite; self.useCount = useCount }333 public init(from decoder: Decoder) throws {334 let c = try decoder.container(keyedBy: CodingKeys.self)335 id = try c.decode(String.self, forKey: .id); title = c.optional(String.self, .title) ?? ""; body = c.optional(String.self, .body) ?? ""336 tags = c.optional([String].self, .tags) ?? []; favorite = c.optional(Bool.self, .favorite) ?? false; useCount = c.flexInt(.useCount) ?? 0337 lastUsedAt = c.optional(Date.self, .lastUsedAt); updatedAt = c.optional(Date.self, .updatedAt)338 }339}340341public struct Project: Sendable, Hashable, Identifiable, Codable {342 public var id: String343 public var name: String344 public var description: String?345 public var instructions: String?346 public var defaultModel: String?347 public var color: String?348 public var icon: String?349 public var notes: String?350 public var conversationCount: Int?351 public var fileCount: Int?352 public var createdAt: Date?353 enum CodingKeys: String, CodingKey { case id, name, description, instructions, color, icon, notes; case defaultModel = "default_model", conversationCount = "conversation_count", fileCount = "file_count", createdAt = "created_at" }354 public init(id: String, name: String, description: String? = nil, instructions: String? = nil, defaultModel: String? = nil, color: String? = nil) { self.id = id; self.name = name; self.description = description; self.instructions = instructions; self.defaultModel = defaultModel; self.color = color }355 public init(from decoder: Decoder) throws {356 let c = try decoder.container(keyedBy: CodingKeys.self)357 id = try c.decode(String.self, forKey: .id); name = c.optional(String.self, .name) ?? "Projet"358 description = c.optional(String.self, .description); instructions = c.optional(String.self, .instructions); defaultModel = c.optional(String.self, .defaultModel)359 color = c.optional(String.self, .color); icon = c.optional(String.self, .icon); notes = c.optional(String.self, .notes)360 conversationCount = c.flexInt(.conversationCount); fileCount = c.flexInt(.fileCount); createdAt = c.optional(Date.self, .createdAt)361 }362}363364public struct Memory: Sendable, Hashable, Identifiable, Codable {365 public var id: String366 public var category: String367 public var content: String368 public var source: String369 public var status: String370 public var projectId: String?371 public var sourceTitle: String?372 public var useCount: Int373 public var updatedAt: Date?374 enum CodingKeys: String, CodingKey { case id, category, content, source, status; case projectId = "project_id", sourceTitle = "source_title", useCount = "use_count", updatedAt = "updated_at" }375 public init(id: String, category: String, content: String, source: String = "manual", status: String = "active") { self.id = id; self.category = category; self.content = content; self.source = source; self.status = status; self.useCount = 0 }376 public init(from decoder: Decoder) throws {377 let c = try decoder.container(keyedBy: CodingKeys.self)378 id = try c.decode(String.self, forKey: .id); category = c.optional(String.self, .category) ?? "context"; content = c.optional(String.self, .content) ?? ""379 source = c.optional(String.self, .source) ?? "manual"; status = c.optional(String.self, .status) ?? "active"; projectId = c.optional(String.self, .projectId)380 sourceTitle = c.optional(String.self, .sourceTitle); useCount = c.flexInt(.useCount) ?? 0; updatedAt = c.optional(Date.self, .updatedAt)381 }382}383384// MARK: - Search385386public struct SearchHit: Sendable, Hashable, Identifiable, Codable {387 public var id: String388 public var conversationId: String389 public var role: String390 public var modelId: String?391 public var createdAt: Date?392 public var title: String393 public var snippet: String394 enum CodingKeys: String, CodingKey { case id, role, title, snippet; case conversationId = "conversation_id", modelId = "model_id", createdAt = "created_at" }395 public init(id: String, conversationId: String, role: String, title: String, snippet: String, modelId: String? = nil, createdAt: Date? = nil) {396 self.id = id; self.conversationId = conversationId; self.role = role; self.title = title; self.snippet = snippet; self.modelId = modelId; self.createdAt = createdAt397 }398 public init(from decoder: Decoder) throws {399 let c = try decoder.container(keyedBy: CodingKeys.self)400 id = try c.decode(String.self, forKey: .id); conversationId = c.optional(String.self, .conversationId) ?? ""; role = c.optional(String.self, .role) ?? "assistant"401 modelId = c.optional(String.self, .modelId); createdAt = c.optional(Date.self, .createdAt); title = c.optional(String.self, .title) ?? ""; snippet = c.optional(String.self, .snippet) ?? ""402 }403 /// `ts_headline` marks matches with <b>…</b>; the UI renders them natively, never as HTML.404 public var snippetSegments: [(text: String, highlighted: Bool)] {405 var out: [(String, Bool)] = []; var rest = Substring(snippet); var on = false406 while let r = rest.range(of: on ? "</b>" : "<b>") {407 if r.lowerBound > rest.startIndex { out.append((String(rest[rest.startIndex..<r.lowerBound]), on)) }408 rest = rest[r.upperBound...]; on.toggle()409 }410 if !rest.isEmpty { out.append((String(rest), on)) }411 return out412 }413}414415// MARK: - Settings & usage416417public struct ToolInfo: Sendable, Hashable, Identifiable, Codable {418 public var name: String419 public var description: String?420 public var permission: String?421 public var category: String?422 public var id: String { name }423}424425public struct ServerSettings: Sendable, Hashable, Codable {426 public struct Limits: Sendable, Hashable, Codable { public var maxUploadMb: Int; public var maxFilesPerMessage: Int; public init(maxUploadMb: Int, maxFilesPerMessage: Int) { self.maxUploadMb = maxUploadMb; self.maxFilesPerMessage = maxFilesPerMessage } }427 public var settings: [String: JSONValue]428 public var tools: [ToolInfo]429 public var limits: Limits430 public var integrations: [String: Bool]431 public init(settings: [String: JSONValue] = [:], tools: [ToolInfo] = [], limits: Limits = .init(maxUploadMb: 50, maxFilesPerMessage: 20), integrations: [String: Bool] = [:]) {432 self.settings = settings; self.tools = tools; self.limits = limits; self.integrations = integrations433 }434 public init(from decoder: Decoder) throws {435 let c = try decoder.container(keyedBy: CodingKeys.self)436 settings = c.optional([String: JSONValue].self, .settings) ?? [:]; tools = c.optional([ToolInfo].self, .tools) ?? []437 limits = c.optional(Limits.self, .limits) ?? .init(maxUploadMb: 50, maxFilesPerMessage: 20); integrations = c.optional([String: Bool].self, .integrations) ?? [:]438 }439 enum CodingKeys: String, CodingKey { case settings, tools, limits, integrations }440}441442public struct UsageReport: Sendable, Hashable, Codable {443 public struct Totals: Sendable, Hashable, Codable {444 public var requests: Int; public var cost: Double; public var inputTokens: Int; public var outputTokens: Int; public var cachedTokens: Int; public var reasoningTokens: Int445 public var avgLatency: Int?; public var avgTtft: Int?; public var errors: Int446 enum CodingKeys: String, CodingKey { case requests, cost, errors; case inputTokens = "input_tokens", outputTokens = "output_tokens", cachedTokens = "cached_tokens", reasoningTokens = "reasoning_tokens", avgLatency = "avg_latency", avgTtft = "avg_ttft" }447 public init(from decoder: Decoder) throws {448 let c = try decoder.container(keyedBy: CodingKeys.self)449 requests = c.flexInt(.requests) ?? 0; cost = c.flexDouble(.cost) ?? 0; inputTokens = c.flexInt(.inputTokens) ?? 0; outputTokens = c.flexInt(.outputTokens) ?? 0450 cachedTokens = c.flexInt(.cachedTokens) ?? 0; reasoningTokens = c.flexInt(.reasoningTokens) ?? 0; avgLatency = c.flexInt(.avgLatency); avgTtft = c.flexInt(.avgTtft); errors = c.flexInt(.errors) ?? 0451 }452 }453 public struct Daily: Sendable, Hashable, Codable, Identifiable {454 public var day: Date; public var provider: String; public var cost: Double; public var requests: Int455 public var id: String { "\(day.timeIntervalSince1970)-\(provider)" }456 enum CodingKeys: String, CodingKey { case day, provider, cost, requests }457 public init(from decoder: Decoder) throws {458 let c = try decoder.container(keyedBy: CodingKeys.self)459 day = c.optional(Date.self, .day) ?? Date(); provider = c.optional(String.self, .provider) ?? "?"; cost = c.flexDouble(.cost) ?? 0; requests = c.flexInt(.requests) ?? 0460 }461 }462 public struct ByModel: Sendable, Hashable, Codable, Identifiable {463 public var modelId: String; public var provider: String; public var requests: Int; public var cost: Double; public var inputTokens: Int; public var outputTokens: Int; public var avgLatency: Int?; public var errors: Int464 public var id: String { modelId + provider }465 enum CodingKeys: String, CodingKey { case provider, requests, cost, errors; case modelId = "model_id", inputTokens = "input_tokens", outputTokens = "output_tokens", avgLatency = "avg_latency" }466 public init(from decoder: Decoder) throws {467 let c = try decoder.container(keyedBy: CodingKeys.self)468 modelId = c.optional(String.self, .modelId) ?? "?"; provider = c.optional(String.self, .provider) ?? "?"; requests = c.flexInt(.requests) ?? 0; cost = c.flexDouble(.cost) ?? 0469 inputTokens = c.flexInt(.inputTokens) ?? 0; outputTokens = c.flexInt(.outputTokens) ?? 0; avgLatency = c.flexInt(.avgLatency); errors = c.flexInt(.errors) ?? 0470 }471 }472 public struct ByKind: Sendable, Hashable, Codable, Identifiable {473 public var kind: String; public var requests: Int; public var cost: Double474 public var id: String { kind }475 public init(from decoder: Decoder) throws {476 let c = try decoder.container(keyedBy: CodingKeys.self)477 kind = c.optional(String.self, .kind) ?? "?"; requests = c.flexInt(.requests) ?? 0; cost = c.flexDouble(.cost) ?? 0478 }479 enum CodingKeys: String, CodingKey { case kind, requests, cost }480 }481 public struct Spending: Sendable, Hashable, Codable {482 public struct Limits: Sendable, Hashable, Codable { public var dailyLimitUsd: Double; public var monthlyLimitUsd: Double; public var alertAtPercent: Double }483 public var today: Double; public var month: Double; public var limits: Limits484 }485 /// Which API was billed: `direct` (the maker's own API) or `openrouter`, per provider.486 public struct ByRoute: Sendable, Hashable, Codable, Identifiable {487 public var route: String; public var provider: String; public var requests: Int; public var cost: Double488 /// Part of `cost` that is the amount billed as reported by the provider (the rest is tokens × list price).489 public var costExact: Double490 public var id: String { route + "/" + provider }491 enum CodingKeys: String, CodingKey { case route, provider, requests, cost; case costExact = "cost_exact" }492 public init(from decoder: Decoder) throws {493 let c = try decoder.container(keyedBy: CodingKeys.self)494 provider = c.optional(String.self, .provider) ?? "?"; route = c.optional(String.self, .route) ?? (provider == "openrouter" ? "openrouter" : "direct")495 requests = c.flexInt(.requests) ?? 0; cost = c.flexDouble(.cost) ?? 0; costExact = c.flexDouble(.costExact) ?? 0496 }497 }498 public struct ByConversation: Sendable, Hashable, Codable, Identifiable {499 public var conversationId: String; public var title: String; public var requests: Int; public var cost: Double; public var lastAt: Date?500 public var id: String { conversationId }501 enum CodingKeys: String, CodingKey { case title, requests, cost; case conversationId = "conversation_id", lastAt = "last_at" }502 public init(from decoder: Decoder) throws {503 let c = try decoder.container(keyedBy: CodingKeys.self)504 conversationId = try c.decode(String.self, forKey: .conversationId); title = c.optional(String.self, .title) ?? ""505 requests = c.flexInt(.requests) ?? 0; cost = c.flexDouble(.cost) ?? 0; lastAt = c.optional(Date.self, .lastAt)506 }507 }508 public struct ByProject: Sendable, Hashable, Codable, Identifiable {509 /// Project name; « — » for requests outside any project.510 public var project: String; public var projectId: String?; public var requests: Int; public var cost: Double511 public var id: String { projectId ?? "" }512 enum CodingKeys: String, CodingKey { case project, requests, cost; case projectId = "project_id" }513 public init(from decoder: Decoder) throws {514 let c = try decoder.container(keyedBy: CodingKeys.self)515 project = c.optional(String.self, .project) ?? "—"; projectId = c.optional(String.self, .projectId); requests = c.flexInt(.requests) ?? 0; cost = c.flexDouble(.cost) ?? 0516 }517 }518 /// Cost of a calendar month, whatever the period asked for (last 12 months at most).519 public struct Monthly: Sendable, Hashable, Codable, Identifiable {520 public var month: Date; public var cost: Double521 public var id: Date { month }522 enum CodingKeys: String, CodingKey { case month, cost }523 public init(from decoder: Decoder) throws {524 let c = try decoder.container(keyedBy: CodingKeys.self)525 month = try c.decode(Date.self, forKey: .month); cost = c.flexDouble(.cost) ?? 0526 }527 }528 /// Split of the period's cost between amounts billed as reported by the provider and local estimates.529 public struct CostBasis: Sendable, Hashable, Codable {530 public var exact: Double; public var estimated: Double531 /// The server's definition of the two words — shown verbatim.532 public var note: String?533 enum CodingKeys: String, CodingKey { case exact, estimated, note }534 public init(from decoder: Decoder) throws {535 let c = try decoder.container(keyedBy: CodingKeys.self)536 exact = c.flexDouble(.exact) ?? 0; estimated = c.flexDouble(.estimated) ?? 0; note = c.optional(String.self, .note)537 }538 }539 public struct Range: Sendable, Hashable, Codable { public var from: Date?; public var to: Date? }540541 public var totals: Totals542 public var daily: [Daily]543 public var byModel: [ByModel]544 public var byKind: [ByKind]545 public var spending: Spending546 // Cost Intelligence (API 1.0) — absent on an older server: empty / nil, never a decoding failure.547 public var byRoute: [ByRoute]548 public var byConversation: [ByConversation]549 public var byProject: [ByProject]550 public var monthly: [Monthly]551 public var costBasis: CostBasis?552 public var range: Range?553554 enum CodingKeys: String, CodingKey { case totals, daily, byModel, byKind, spending, byRoute, byConversation, byProject, monthly, costBasis, range }555 public init(from decoder: Decoder) throws {556 let c = try decoder.container(keyedBy: CodingKeys.self)557 totals = try c.decode(Totals.self, forKey: .totals); daily = try c.decode([Daily].self, forKey: .daily)558 byModel = try c.decode([ByModel].self, forKey: .byModel); byKind = try c.decode([ByKind].self, forKey: .byKind)559 spending = try c.decode(Spending.self, forKey: .spending)560 byRoute = (c.optional([Lossy<ByRoute>].self, .byRoute) ?? []).compactMap(\.value)561 byConversation = (c.optional([Lossy<ByConversation>].self, .byConversation) ?? []).compactMap(\.value)562 byProject = (c.optional([Lossy<ByProject>].self, .byProject) ?? []).compactMap(\.value)563 monthly = (c.optional([Lossy<Monthly>].self, .monthly) ?? []).compactMap(\.value)564 costBasis = c.optional(CostBasis.self, .costBasis); range = c.optional(Range.self, .range)565 }566}567568// MARK: - Account569570public struct Passkey: Sendable, Hashable, Identifiable, Codable {571 public var id: String572 public var label: String?573 public var createdAt: Date?574 public var lastUsedAt: Date?575 public var synced: Bool?576 public var deviceType: String?577 public var createdVia: String?578 public var current: Bool579}580581public struct PasskeyOverview: Sendable, Hashable, Codable {582 public struct Recovery: Sendable, Hashable, Codable { public var remaining: Int; public var generatedAt: Date? }583 public var passkeys: [Passkey]584 public var recovery: Recovery585 public var recentAuth: Bool586 public var rpId: String587}588589public struct DeviceSession: Sendable, Hashable, Identifiable, Codable {590 public var id: String591 public var label: String?592 public var createdAt: Date?593 public var lastSeen: Date?594 public var expiresAt: Date?595 public var ip: String?596 public var current: Bool597}598599public struct AuthEvent: Sendable, Hashable, Identifiable, Codable {600 public var id: Int601 public var at: Date602 public var event: String603 public var ip: String?604 public var detail: JSONValue?605 enum CodingKeys: String, CodingKey { case id, at, event, ip, detail }606 public init(from decoder: Decoder) throws {607 let c = try decoder.container(keyedBy: CodingKeys.self)608 id = c.flexInt(.id) ?? 0; at = c.optional(Date.self, .at) ?? Date(); event = c.optional(String.self, .event) ?? "?"; ip = c.optional(String.self, .ip); detail = c.optional(JSONValue.self, .detail)609 }610}611612public struct AuthState: Sendable, Hashable, Codable {613 public var rpId: String614 public var configOk: Bool615 public var signedIn: Bool616 public var enrolment: String?617}618619public struct OwnerSummary: Sendable, Hashable, Codable {620 public var conversations: Int; public var messages: Int; public var projects: Int; public var memories: Int; public var files: Int; public var fileBytes: Int621 enum CodingKeys: String, CodingKey { case conversations, messages, projects, memories, files; case fileBytes = "file_bytes" }622 public init(from decoder: Decoder) throws {623 let c = try decoder.container(keyedBy: CodingKeys.self)624 conversations = c.flexInt(.conversations) ?? 0; messages = c.flexInt(.messages) ?? 0; projects = c.flexInt(.projects) ?? 0625 memories = c.flexInt(.memories) ?? 0; files = c.flexInt(.files) ?? 0; fileBytes = c.flexInt(.fileBytes) ?? 0626 }627}628629public struct HealthReport: Sendable, Hashable, Codable {630 public var ok: Bool631 public var version: String?632 public var modelsAvailable: Int?633 public var activeGenerations: Int?634 public var dbMs: Int?635 public var uptimeSec: Int?636}637638// MARK: - Formatting helpers shared by every screen639640public enum Format {641 public static func tokens(_ n: Int?) -> String {642 guard let n else { return "—" }643 if n >= 1_000_000 { return String(format: "%.1fM", Double(n) / 1_000_000) }644 if n >= 10_000 { return "\(n / 1000)k" }645 if n >= 1000 { return String(format: "%.1fk", Double(n) / 1000) }646 return String(n)647 }648 public static func usd(_ v: Double?, digits: Int = 4) -> String {649 guard let v else { return "—" }650 if v == 0 { return "0 $" }651 return v < 0.01 ? String(format: "%.\(digits)f $", v) : String(format: "%.2f $", v)652 }653 public static func duration(ms: Int?) -> String {654 guard let ms else { return "—" }655 return ms >= 1000 ? String(format: "%.1f s", Double(ms) / 1000) : "\(ms) ms"656 }657 public static func bytes(_ n: Int?) -> String {658 guard let n else { return "" }659 if n >= 1_048_576 { return String(format: n >= 10_485_760 ? "%.0f Mo" : "%.1f Mo", Double(n) / 1_048_576) }660 if n >= 1024 { return "\(Int((Double(n) / 1024).rounded())) Ko" }661 return "\(n) o"662 }663 public static func relative(_ date: Date, now: Date = Date()) -> String {664 let m = Int((now.timeIntervalSince(date) / 60).rounded())665 if m < 1 { return "à l'instant" }666 if m < 60 { return "\(m) min" }667 let h = Int((Double(m) / 60).rounded()); if h < 24 { return "\(h) h" }668 let d = Int((Double(h) / 24).rounded()); if d < 7 { return "\(d) j" }669 return date.formatted(.dateTime.day().month(.abbreviated).locale(Locale(identifier: "fr_CA")))670 }671}672