SPB Git

Repository Public

NextGen.swift 23.1 KB 456 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Core/Models/NextGen.swift4//  Description: DTOs of backend 1.0 « Next Generation » — providers, model intelligence, branches, timeline, context,5//               constellation, sync feed, advanced search. Built from loose JSON so a newer server never breaks decoding.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import Foundation1213extension JSONValue {14    func str(_ k: String) -> String? { self[k]?.stringValue }15    func int(_ k: String) -> Int? { self[k]?.intValue }16    func double(_ k: String) -> Double? { self[k]?.doubleValue }17    func bool(_ k: String) -> Bool? { self[k]?.boolValue }18    func list(_ k: String) -> [JSONValue] { self[k]?.arrayValue ?? [] }19    func date(_ k: String) -> Date? { self[k]?.stringValue.flatMap(ISO8601.parse) }20    func strings(_ k: String) -> [String] { list(k).compactMap(\.stringValue) }21    /// Re-decodes a loose value into a Codable type (nil when the shape does not fit).22    func decoded<T: Decodable>(_ type: T.Type = T.self) -> T? {23        guard !isNull, let d = try? JSONEncoder().encode(self) else { return nil }24        return try? JSONDecoder().decode(T.self, from: d)25    }26}2728/// Decodes an array element by element: one malformed entry is skipped instead of failing the whole list.29struct LossyArray<Element: Decodable & Sendable>: Decodable, Sendable {30    var elements: [Element] = []31    init(from decoder: Decoder) throws {32        var c = try decoder.unkeyedContainer()33        if let n = c.count { elements.reserveCapacity(n) }34        while !c.isAtEnd {35            if let e = try? c.decode(Element.self) { elements.append(e) } else { _ = try? c.decode(JSONValue.self) }36        }37    }38}3940// MARK: models4142/// `GET /api/models?routes=all`43struct ModelsResponse: Decodable, Sendable {44    var models: [AIModel]45    var defaultModel: String?46    /// Model Favorites Dock (max 8, synced between the three apps).47    var dock: [String]48    var openRouterConfigured: Bool49    var catalogSyncedAt: Date?50    var catalogTotal: Int?5152    private enum K: String, CodingKey { case models, defaultModel, dock, openrouter }53    init(from decoder: Decoder) throws {54        let c = try decoder.container(keyedBy: K.self)55        models = try c.decode(LossyArray<AIModel>.self, forKey: .models).elements56        defaultModel = c.flexString(.defaultModel)57        dock = (try? c.decodeIfPresent([String].self, forKey: .dock)) ?? []58        let o = try? c.decodeIfPresent(JSONValue.self, forKey: .openrouter)59        openRouterConfigured = o?.bool("configured") ?? false60        catalogSyncedAt = o?["catalog"]?.date("syncedAt"); catalogTotal = o?["catalog"]?.int("total")61    }62}6364/// `GET /api/models/detail?id=` — Live Model Intelligence. Every block keeps the `source` the server states for it.65struct ModelDetail: Sendable, Equatable {66    struct Measured: Sendable, Equatable {67        var source: String; var requests: Int; var errors: Int; var p50LatencyMs: Int?; var p50TtftMs: Int?; var tokensPerSec: Double?68        var costUsd: Double?; var inputTokens: Int?; var outputTokens: Int?; var firstUsed: Date?; var lastUsed: Date?69    }70    struct Endpoint: Sendable, Equatable, Identifiable {71        var id: String; var provider: String; var contextLength: Int?; var maxCompletionTokens: Int?; var quantization: String?72        var uptimeLast30m: Double?; var inputPerM: Double?; var outputPerM: Double?; var supportsTools: Bool?73    }74    struct Twin: Sendable, Equatable, Identifiable { var id: String; var route: String; var displayName: String; var priceInput: Double?; var priceOutput: Double?; var status: String? }75    struct BenchmarkSet: Sendable, Equatable, Identifiable {76        struct Figure: Sendable, Equatable, Identifiable { var name: String; var value: Double; var id: String { name } }77        var source: String; var figures: [Figure]; var id: String { source }78    }79    var model: AIModel80    var efforts: [String]81    var acceptsTemperature: Bool?82    var notes: [String: String]83    var measured: Measured?84    var endpointsSource: String?85    var endpoints: [Endpoint]86    var twins: [Twin]87    var benchmarks: [BenchmarkSet]8889    init?(_ j: JSONValue) {90        guard let m: AIModel = j["model"]?.decoded() else { return nil }91        model = m92        efforts = j["params"]?.strings("effort") ?? []93        acceptsTemperature = j["params"]?.bool("temperature")94        notes = (j["params"]?["notes"]?.objectValue ?? [:]).compactMapValues(\.stringValue)95        if let x = j["measured"], !x.isNull, (x.int("requests") ?? 0) > 0 {96            measured = Measured(source: x.str("source") ?? "", requests: x.int("requests") ?? 0, errors: x.int("errors") ?? 0, p50LatencyMs: x.int("p50_latency_ms"), p50TtftMs: x.int("p50_ttft_ms"),97                                tokensPerSec: x.double("tokens_per_sec"), costUsd: x.double("cost_usd"), inputTokens: x.int("input_tokens"), outputTokens: x.int("output_tokens"), firstUsed: x.date("first_used"), lastUsed: x.date("last_used"))98        }99        endpointsSource = j["endpoints"]?.str("source")100        endpoints = (j["endpoints"]?.list("list") ?? []).enumerated().map { i, e in101            Endpoint(id: e.str("tag") ?? "\(i)", provider: e.str("provider") ?? "—", contextLength: e.int("contextLength"), maxCompletionTokens: e.int("maxCompletionTokens"), quantization: e.str("quantization"),102                     uptimeLast30m: e.double("uptimeLast30m"), inputPerM: e.double("inputPerM"), outputPerM: e.double("outputPerM"), supportsTools: e.bool("supportsTools"))103        }104        twins = j.list("twins").compactMap { t in105            guard let id = t.str("id") else { return nil }106            return Twin(id: id, route: t.str("route") ?? "direct", displayName: t.str("display_name") ?? t.str("displayName") ?? id, priceInput: t["pricing"]?.double("input"), priceOutput: t["pricing"]?.double("output"), status: t.str("status"))107        }108        // third-party figures: {source: {metric: number}} — only numbers are shown, under the name of their source109        benchmarks = (m.catalog?.benchmarks?.objectValue ?? [:]).compactMap { source, v in110            guard let o = v.objectValue else { return nil }111            let figs = o.compactMap { k, x -> BenchmarkSet.Figure? in if case .number(let n) = x { return .init(name: k, value: n) } else { return nil } }.sorted { $0.name < $1.name }112            return figs.isEmpty ? nil : BenchmarkSet(source: source, figures: figs)113        }.sorted { $0.source < $1.source }114    }115}116117/// `POST /api/models/route-suggest` — advisory only: the app never switches model by itself.118struct RouteSuggestion: Sendable, Equatable {119    var selected: String120    var reason: String?121    var task: String?122    var basis: String?123    init?(_ j: JSONValue) {124        guard let d = j["decision"], let s = d.str("selected"), !s.isEmpty else { return nil }125        selected = s; reason = d.str("reason"); task = d.str("task"); basis = j.str("basis")126    }127}128129// MARK: providers130131struct ProviderInfo: Identifiable, Sendable, Equatable {132    var id: String133    var name: String134    /// `models` (executes chats) or `tool` (Tavily web search).135    var kind: String136    var route: String?137    var logo: String?138    var configured: Bool139    /// stored (set from an app, encrypted on the server) · env (server environment) · none140    var keySource: String141    /// Last characters only ("…a299"). The key itself never leaves the server.142    var keyHint: String?143    var manageable: Bool144    var validatedAt: Date?145    var modelsTotal: Int?146    var modelsChat: Int?147    var catalogSyncedAt: Date?148    var healthState: String?149    var info: [String: String]150151    init?(_ j: JSONValue) {152        guard let id = j.str("id") else { return nil }153        self.id = id; name = j.str("name") ?? id; kind = j.str("kind") ?? "models"; route = j.str("route"); logo = j.str("logo")154        configured = j.bool("configured") ?? false; keySource = j.str("keySource") ?? "none"; keyHint = j.str("keyHint"); manageable = j.bool("manageable") ?? false155        validatedAt = j.date("validatedAt"); modelsTotal = j["models"]?.int("total"); modelsChat = j["models"]?.int("chat")156        catalogSyncedAt = j["catalog"]?.date("syncedAt"); healthState = j["health"]?.str("state")157        // free-form account facts returned by the provider's own key check (label, usage, limit…): shown as given158        info = (j["info"]?.objectValue ?? [:]).compactMapValues { v in159            switch v { case .string(let s): s; case .number(let n): n.rounded() == n ? String(Int(n)) : String(format: "%.4g", n); case .bool(let b): b ? "oui" : "non"; default: nil }160        }161    }162}163164struct ProvidersResponse: Sendable, Equatable {165    var providers: [ProviderInfo]166    /// The rule behind each derived category (shown in the Explorer).167    var categoryRules: [String: String]168    init(_ j: JSONValue) {169        providers = j.list("providers").compactMap(ProviderInfo.init)170        categoryRules = (j["categoryRules"]?.objectValue ?? [:]).compactMapValues(\.stringValue)171    }172}173174struct ProviderCheck: Sendable, Equatable { var ok: Bool; var message: String }175176// MARK: branches, timeline, context177178struct ConversationTree: Sendable, Equatable {179    struct Node: Identifiable, Sendable, Equatable {180        var id: String; var parentId: String?; var title: String; var branchLabel: String?; var branchMessageId: String?181        var modelId: String?; var messageCount: Int; var lastAt: Date?; var depth: Int182    }183    struct Variant: Identifiable, Sendable, Equatable {184        struct Option: Identifiable, Sendable, Equatable { var id: String; var active: Bool; var model: String?; var status: String?; var createdAt: Date?; var preview: String }185        var parentId: String?; var role: String; var options: [Option]186        var id: String { "\(parentId ?? "∅")|\(role)" }187    }188    var current: String189    var family: [Node]190    var variants: [Variant]191    init(_ j: JSONValue) {192        current = j.str("current") ?? ""193        family = j.list("family").compactMap { n in194            guard let id = n.str("id") else { return nil }195            return Node(id: id, parentId: n.str("parent_id"), title: n.str("title") ?? Conversation.untitled, branchLabel: n.str("branch_label"), branchMessageId: n.str("branch_message_id"),196                        modelId: n.str("model_id"), messageCount: n.int("message_count") ?? 0, lastAt: n.date("last_at"), depth: n.int("depth") ?? 0)197        }198        variants = j.list("variants").map { v in199            Variant(parentId: v.str("parent_id"), role: v.str("role") ?? "assistant", options: v.list("options").compactMap { o in200                guard let id = o.str("id") else { return nil }201                return .init(id: id, active: o.bool("active") ?? false, model: o.str("model"), status: o.str("status"), createdAt: o.date("createdAt"), preview: o.str("preview") ?? "")202            })203        }204    }205}206207/// One recorded event of a conversation (`GET /api/conversations/{id}/timeline`). Nothing is reconstructed client-side.208struct TimelineEvent: Identifiable, Sendable, Equatable {209    enum Kind: String, Sendable { case prompt, response, modelSwitch = "model_switch", tool, file, image, artifact, branch, other }210    var id: Int211    var kind: Kind212    var rawType: String213    var at: Date?214    var messageId: String?215    var active: Bool216    var preview: String?217    var model: String?218    var status: String?219    var costUsd: Double?220    var latencyMs: Int?221    var ttftMs: Int?222    var inputTokens: Int?223    var outputTokens: Int?224    var servedBy: String?225    var citations: Int?226    var from: String?227    var to: String?228    var tool: String?229    var durationMs: Int?230    var name: String?231    var conversationId: String?232    var variant: Int?233    var variants: Int?234235    init(index: Int, _ j: JSONValue) {236        id = index; rawType = j.str("type") ?? ""; kind = Kind(rawValue: rawType) ?? .other237        at = j.date("at"); messageId = j.str("messageId"); active = j.bool("active") ?? true; preview = j.str("preview")238        model = j.str("model"); status = j.str("status"); costUsd = j.double("costUsd"); latencyMs = j.int("latencyMs"); ttftMs = j.int("ttftMs")239        inputTokens = j["usage"]?.int("input"); outputTokens = j["usage"]?.int("output"); servedBy = j["routing"]?.str("servedBy"); citations = j.int("citations")240        from = j.str("from"); to = j.str("to"); tool = j.str("tool"); durationMs = j.int("durationMs")241        name = j.str("name") ?? j.str("filename") ?? j.str("title"); conversationId = j.str("conversationId"); variant = j.int("variant"); variants = j.int("variants")242    }243}244245struct ConversationTimeline: Sendable, Equatable {246    var events: [TimelineEvent]247    var note: String?248    init(_ j: JSONValue) {249        events = j.list("events").enumerated().map { TimelineEvent(index: $0.offset, $0.element) }250        note = j.str("note")251    }252}253254/// Replay cursor over the recorded events of a timeline: steps in order, never past the ends.255struct TimelineReplay: Equatable, Sendable {256    private(set) var position = 0257    let count: Int258    var isPlaying = false259    init(count: Int) { self.count = count }260    var isAtEnd: Bool { count == 0 || position >= count - 1 }261    var progress: Double { count <= 1 ? (count == 0 ? 0 : 1) : Double(position) / Double(count - 1) }262    mutating func step(_ delta: Int) { position = min(max(position + delta, 0), max(count - 1, 0)); if isAtEnd { isPlaying = false } }263    mutating func seek(_ index: Int) { position = min(max(index, 0), max(count - 1, 0)) }264    mutating func togglePlay() { if isAtEnd && !isPlaying { position = 0 }; isPlaying = count > 1 && !isPlaying }265}266267/// `GET /api/conversations/{id}/context` — what the next request will carry. `estimate` is an estimate and labelled so.268struct ContextReport: Sendable, Equatable {269    struct File: Identifiable, Sendable, Equatable { var id: String; var name: String; var detail: String? }270    var modelId: String?271    var modelName: String?272    var contextWindow: Int?273    var measuredSource: String?274    var measuredInput: Int?275    var measuredOutput: Int?276    var measuredCached: Int?277    var measuredReasoning: Int?278    var measuredAt: Date?279    var estimateSource: String?280    var nextRequestTokens: Int?281    var percentOfContext: Double?282    var messageCount: Int283    var userCount: Int284    var assistantCount: Int285    var files: [File]286    var toolsEnabled: Bool287    var tools: [String]288    var conversationUsd: Double?289    var costSource: String?290    var streaming: Bool291292    init(_ j: JSONValue) {293        modelId = j["model"]?.str("id"); modelName = j["model"]?.str("displayName"); contextWindow = j["model"]?.int("contextWindow")294        let m = j["measured"]295        measuredSource = m?.str("source"); measuredInput = m?.int("inputTokens"); measuredOutput = m?.int("outputTokens"); measuredCached = m?.int("cachedTokens"); measuredReasoning = m?.int("reasoningTokens"); measuredAt = m?.date("at")296        estimateSource = j["estimate"]?.str("source"); nextRequestTokens = j["estimate"]?.int("nextRequestTokens"); percentOfContext = j["estimate"]?.double("percentOfContext")297        messageCount = j["messages"]?.int("count") ?? 0; userCount = j["messages"]?.int("user") ?? 0; assistantCount = j["messages"]?.int("assistant") ?? 0298        files = j.list("files").enumerated().map { i, f in299            let facts = [f.int("tokens").map { "≈ \(Format.tokens($0)) jetons" }, f.int("size").map { Format.bytes($0) } ?? f.int("sizeBytes").map { Format.bytes($0) }, f.int("pages").map { "\($0) p." }, f.str("mime")].compactMap { $0 }300            return File(id: f.str("id") ?? "\(i)", name: f.str("name") ?? f.str("filename") ?? "fichier", detail: facts.isEmpty ? nil : facts.joined(separator: " · "))301        }302        toolsEnabled = j["tools"]?.bool("enabled") ?? false; tools = (j["tools"]?.list("list") ?? []).compactMap { $0.str("name") }303        conversationUsd = j["cost"]?.double("conversationUsd"); costSource = j["cost"]?.str("source"); streaming = j.bool("streaming") ?? false304    }305}306307// MARK: constellation308309struct Constellation: Sendable, Equatable {310    struct Node: Identifiable, Sendable, Equatable {311        var id: String; var title: String; var projectId: String?; var projectName: String?; var projectColor: String?; var modelId: String?312        var messages: Int; var costUsd: Double; var parentId: String?; var branchLabel: String?; var pinned: Bool; var favorite: Bool; var lastAt: Date?313    }314    struct Link: Identifiable, Sendable, Equatable {315        var source: String; var target: String; var kind: String; var weight: Double316        var id: String { "\(source)>\(target)>\(kind)" }317    }318    struct ProjectRef: Identifiable, Sendable, Equatable { var id: String; var name: String; var color: String? }319    var nodes: [Node]320    var links: [Link]321    var projects: [ProjectRef]322    /// What each kind of link is based on, in the server's words (shown in the legend).323    var basis: [String: String]324325    init(_ j: JSONValue) {326        nodes = j.list("nodes").compactMap { n in327            guard let id = n.str("id") else { return nil }328            return Node(id: id, title: n.str("title") ?? Conversation.untitled, projectId: n.str("projectId"), projectName: n.str("projectName"), projectColor: n.str("projectColor"), modelId: n.str("modelId"),329                        messages: n.int("messages") ?? 0, costUsd: n.double("costUsd") ?? 0, parentId: n.str("parentId"), branchLabel: n.str("branchLabel"), pinned: n.bool("pinned") ?? false, favorite: n.bool("favorite") ?? false, lastAt: n.date("lastAt"))330        }331        let ids = Set(nodes.map(\.id))332        links = j.list("links").compactMap { l in333            guard let s = l.str("source"), let t = l.str("target"), ids.contains(s), ids.contains(t), s != t else { return nil }334            return Link(source: s, target: t, kind: l.str("kind") ?? "topic", weight: l.double("weight") ?? 0.5)335        }336        projects = j.list("projects").compactMap { p in p.str("id").map { ProjectRef(id: $0, name: p.str("name") ?? "Projet", color: p.str("color")) } }337        basis = (j["basis"]?.objectValue ?? [:]).compactMapValues(\.stringValue)338    }339}340341// MARK: sync feed342343struct SyncEvent: Sendable, Equatable {344    var seq: Int345    /// conversation · message · project · prompt · preset · model · settings · memory · draft · provider · attachment · artifact346    var entity: String347    var id: String?348    var op: String349    init?(_ j: JSONValue) {350        guard let seq = j.int("seq") else { return nil }351        self.seq = seq; entity = j.str("entity") ?? ""; id = j.str("id"); op = j.str("op") ?? "upsert"352    }353    init(seq: Int, entity: String, id: String? = nil, op: String = "upsert") { self.seq = seq; self.entity = entity; self.id = id; self.op = op }354}355356struct SyncPull: Sendable, Equatable {357    var events: [SyncEvent]; var head: Int; var truncated: Bool358    init(_ j: JSONValue) { events = j.list("events").compactMap(SyncEvent.init); head = j.int("head") ?? 0; truncated = j.bool("truncated") ?? false }359}360361/// One event of the long-lived change feed (`GET /api/events`).362enum SyncFeedEvent: Sendable, Equatable {363    case hello(head: Int)364    case change(SyncEvent)365    case resync(head: Int)366    case other367    init(sse: SSEEvent) {368        let j = (try? JSONDecoder().decode(JSONValue.self, from: Data(sse.data.utf8))) ?? .null369        switch sse.event {370        case "hello": self = .hello(head: j.int("head") ?? 0)371        case "change": self = SyncEvent(j).map(SyncFeedEvent.change) ?? .other372        case "resync": self = .resync(head: j.int("head") ?? 0)373        default: self = .other374        }375    }376}377378/// What a batch of change events asks the app to re-read. The event says *what* changed; the server row is the truth.379struct SyncPlan: Equatable, Sendable {380    var conversationList = false381    /// Conversations whose messages or metadata changed (reloaded only if open or cached).382    var conversations: Set<String> = []383    var deletedConversations: Set<String> = []384    /// Messages, files or artefacts changed somewhere: the conversation on screen re-reads itself when idle.385    var openConversation = false386    var models = false387    var catalogData = false      // projects, presets388    var prompts = false389    var settings = false390    var providers = false391    var memory = false392    var drafts: Set<String> = []393    var everything = false394    var isEmpty: Bool { self == SyncPlan() }395396    static let all: SyncPlan = { var p = SyncPlan(); p.everything = true; p.conversationList = true; p.openConversation = true; p.models = true; p.catalogData = true; p.prompts = true; p.settings = true; p.providers = true; p.memory = true; return p }()397398    /// Folds events into the plan and returns the highest sequence number seen (events at or below `cursor` are ignored).399    @discardableResult400    mutating func absorb(_ events: [SyncEvent], cursor: Int) -> Int {401        var head = cursor402        for e in events where e.seq > cursor {403            head = max(head, e.seq)404            switch e.entity {405            case "conversation":406                conversationList = true; openConversation = true407                if let id = e.id { if e.op == "delete" { deletedConversations.insert(id); conversations.remove(id) } else { conversations.insert(id); deletedConversations.remove(id) } }408            case "message", "attachment", "artifact":409                // message ids are not conversation ids: the list is refreshed, and the open conversation re-reads itself410                conversationList = true; openConversation = true411                if let id = e.id, id.hasPrefix("conv_") { conversations.insert(id) }412            case "project", "preset": catalogData = true; if e.entity == "project" { conversationList = true }413            case "prompt": prompts = true414            case "model": models = true415            case "provider": providers = true; models = true416            case "settings": settings = true417            case "memory": memory = true418            case "draft": if let id = e.id { drafts.insert(id) }419            default: break            // an entity this build does not know: nothing to refresh420            }421        }422        return head423    }424}425426// MARK: search427428struct SearchFilters: Equatable, Sendable {429    var modelId: String?430    var provider: String?431    var projectId: String?432    var from: Date?433    var to: Date?434    /// image · pdf · document · any435    var fileType: String?436    var favoritesOnly = false437    var role: String?438    var semantic = true439    var isActive: Bool { self != SearchFilters() }440    var activeCount: Int { [modelId != nil, provider != nil, projectId != nil, from != nil, to != nil, fileType != nil, favoritesOnly, role != nil, !semantic].filter { $0 }.count }441442    func queryItems(_ q: String) -> [URLQueryItem] {443        var items = [URLQueryItem(name: "q", value: q)]444        if let modelId { items.append(.init(name: "model", value: modelId)) }445        if let provider { items.append(.init(name: "provider", value: provider)) }446        if let projectId { items.append(.init(name: "project", value: projectId)) }447        if let from { items.append(.init(name: "from", value: ISO8601.string(from))) }448        if let to { items.append(.init(name: "to", value: ISO8601.string(to))) }449        if let fileType { items.append(.init(name: "fileType", value: fileType)) }450        if favoritesOnly { items.append(.init(name: "favorite", value: "1")) }451        if let role { items.append(.init(name: "role", value: role)) }452        if !semantic { items.append(.init(name: "semantic", value: "0")) }453        return items454    }455}456
Files main
Menu

Theme