SPB Git

Repository Public

ConversationExporter.swift 3.5 KB 50 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Export/ConversationExporter.swift3// Description: Local Markdown / JSON export of a conversation (works offline from the cache; same layout as the server export).4import Foundation56public enum ConversationExporter {7    /// Markdown of the active thread. Tool outputs are summarised, never dumped.8    public static func markdown(_ detail: ConversationDetail, now: Date = Date(), timeZone: TimeZone = TimeZone(identifier: "America/Toronto") ?? .current) -> String {9        let messages = detail.activeMessages10        var style = Date.FormatStyle(date: .numeric, time: .shortened, locale: Locale(identifier: "fr_CA")); style.timeZone = timeZone11        var lines = ["# \(detail.conversation.title)", "", "_Exporté le \(now.formatted(style)) — \(messages.count) messages_", ""]12        for m in messages {13            lines += ["## " + (m.role == .user ? "Vous" : "Assistant" + (m.modelId.map { " (\($0))" } ?? "")), ""]14            for p in m.parts {15                switch p {16                case .text(let t): lines += [t, ""]17                case .toolCall(let c): lines += ["> Outil \(c.name)(\(String(c.input.jsonString().prefix(300)))) → \(c.status.rawValue)", ""]18                case .file(let id, _, let name, _, _): lines += ["> Pièce jointe : \(name.isEmpty ? id : name)", ""]19                case .image(let id, _, let name): lines += ["> Pièce jointe : \(name ?? id)", ""]20                case .generatedImage(_, let prompt, let model): lines += ["> Image générée (\(model)) : \(prompt)", ""]21                case .citation(let url, let title, _): lines += ["> Source : \(title ?? url) — \(url)", ""]22                case .reasoning, .artifact, .unknown: break23                }24            }25            if m.role == .assistant, m.status != .complete { lines += ["> État : \(m.status.rawValue)" + (m.error.map { " — \($0)" } ?? ""), ""] }26            if m.role == .assistant, let u = m.usage {27                let cost = m.costUsd.map { String(format: "%.4f $ (estimation)", $0) } ?? "coût inconnu"28                lines += ["<sub>\(u.input) → \(u.output) jetons · \(cost) · \(m.latencyMs.map(String.init) ?? "?") ms</sub>", ""]29            }30        }31        return lines.joined(separator: "\n")32    }3334    public static func json(_ detail: ConversationDetail, includeInactiveBranches: Bool = false, now: Date = Date()) -> Data {35        struct Envelope: Encodable { let format: String; let version: Int; let exportedAt: Date; let conversation: Conversation; let messages: [Message] }36        let enc = JSONEncoder.api(); enc.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]37        let env = Envelope(format: "chat-spboucher-ai/conversation", version: 1, exportedAt: now, conversation: detail.conversation, messages: includeInactiveBranches ? detail.messages : detail.activeMessages)38        return (try? enc.encode(env)) ?? Data("{}".utf8)39    }4041    /// « Conversation - <titre> - 2026-11-17 », safe as a file name.42    public static func fileName(kind: String = "Conversation", title: String, now: Date = Date()) -> String {43        let clean = title.components(separatedBy: CharacterSet(charactersIn: "/\\:*?\"<>|").union(.controlCharacters)).joined(separator: " ")44            .split(separator: " ", omittingEmptySubsequences: true).joined(separator: " ")45        var day = Date.ISO8601FormatStyle(); day.timeZone = .gmt46        let stamp = String(now.formatted(day).prefix(10))47        return "\(kind) - \(clean.isEmpty ? "sans titre" : String(clean.prefix(50))) - \(stamp)"48    }49}50
Files main
Menu

Theme