Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatCore/Sources/Chat.swift3// Description: Conversation tree (messages keep their parent, so edits and regenerations are branches), folders, templates and workspaces.4import Foundation56public struct Attachment: Codable, Sendable, Hashable, Identifiable {7 public enum Kind: String, Codable, Sendable { case image, document, audio }8 public var id: UUID9 public var kind: Kind10 public var fileName: String11 public var mimeType: String12 public var byteCount: Int13 public var storedName: String // file name inside the attachments directory14 public var extractedText: String? // documents: text given to the model15 public init(id: UUID = UUID(), kind: Kind, fileName: String, mimeType: String, byteCount: Int, storedName: String, extractedText: String? = nil) {16 self.id = id; self.kind = kind; self.fileName = fileName; self.mimeType = mimeType; self.byteCount = byteCount17 self.storedName = storedName; self.extractedText = extractedText18 }19}2021public struct SourceReference: Codable, Sendable, Hashable, Identifiable {22 public var id: UUID23 public var documentID: UUID24 public var documentName: String25 public var chunkIndex: Int26 public var page: Int?27 public var excerpt: String28 public var score: Double29 public init(id: UUID = UUID(), documentID: UUID, documentName: String, chunkIndex: Int, page: Int? = nil, excerpt: String, score: Double) {30 self.id = id; self.documentID = documentID; self.documentName = documentName; self.chunkIndex = chunkIndex; self.page = page31 self.excerpt = excerpt; self.score = score32 }33}3435public struct ToolResultRecord: Codable, Sendable, Hashable {36 public var callID: String37 public var name: String38 public var output: String39 public var isError: Bool40 public init(callID: String, name: String, output: String, isError: Bool = false) { self.callID = callID; self.name = name; self.output = output; self.isError = isError }41}4243public struct ChatMessage: Codable, Sendable, Hashable, Identifiable {44 public enum Role: String, Codable, Sendable { case system, user, assistant, tool }45 public enum Status: String, Codable, Sendable { case complete, streaming, cancelled, failed }4647 public var id: UUID48 public var conversationID: UUID49 public var parentID: UUID? // nil for the first message; siblings share a parent (branches)50 public var role: Role51 public var content: String52 public var reasoning: String?53 public var attachments: [Attachment]54 public var toolCalls: [ToolInvocation]55 public var toolResult: ToolResultRecord?56 public var sources: [SourceReference]57 public var modelID: String? // which model produced an assistant message58 public var modelName: String?59 public var backend: BackendKind?60 public var remoteNodeName: String? // set when the answer was computed off-device61 public var metrics: GenerationMetrics?62 public var status: Status63 public var errorText: String?64 public var createdAt: Date65 public var editedAt: Date?6667 public init(id: UUID = UUID(), conversationID: UUID, parentID: UUID?, role: Role, content: String, reasoning: String? = nil,68 attachments: [Attachment] = [], toolCalls: [ToolInvocation] = [], toolResult: ToolResultRecord? = nil,69 sources: [SourceReference] = [], modelID: String? = nil, modelName: String? = nil, backend: BackendKind? = nil,70 remoteNodeName: String? = nil, metrics: GenerationMetrics? = nil, status: Status = .complete, errorText: String? = nil,71 createdAt: Date = Date(), editedAt: Date? = nil) {72 self.id = id; self.conversationID = conversationID; self.parentID = parentID; self.role = role; self.content = content73 self.reasoning = reasoning; self.attachments = attachments; self.toolCalls = toolCalls; self.toolResult = toolResult74 self.sources = sources; self.modelID = modelID; self.modelName = modelName; self.backend = backend75 self.remoteNodeName = remoteNodeName; self.metrics = metrics; self.status = status; self.errorText = errorText76 self.createdAt = createdAt; self.editedAt = editedAt77 }78}7980/// A compacted view of older turns. The original messages are never modified or deleted.81public struct ContextSummary: Codable, Sendable, Hashable {82 public var text: String83 public var coversThroughMessageID: UUID // last message (on the active branch) folded into the summary84 public var messageCount: Int85 public var modelID: String?86 public var createdAt: Date87 public init(text: String, coversThroughMessageID: UUID, messageCount: Int, modelID: String?, createdAt: Date = Date()) {88 self.text = text; self.coversThroughMessageID = coversThroughMessageID; self.messageCount = messageCount; self.modelID = modelID; self.createdAt = createdAt89 }90}9192public enum CompactionPolicy: String, Codable, Sendable, CaseIterable, Identifiable {93 case off, truncate, summarize94 public var id: String { rawValue }95 public var title: String { switch self { case .off: "Off"; case .truncate: "Drop oldest turns"; case .summarize: "Summarize older turns" } }96}9798public struct Conversation: Codable, Sendable, Hashable, Identifiable {99 public var id: UUID100 public var title: String101 public var folderID: UUID?102 public var tags: [String]103 public var isFavorite: Bool104 public var isArchived: Bool105 public var systemPrompt: String106 public var modelID: String?107 public var settings: GenerationSettings108 public var preset: InferencePreset?109 public var activeLeafID: UUID? // tip of the branch shown to the user110 public var summary: ContextSummary?111 public var compaction: CompactionPolicy112 public var collectionIDs: [UUID] // knowledge collections attached to the conversation113 public var agentID: UUID?114 public var workspaceID: UUID?115 public var autoRoute: Bool // let the router pick the model per message116 public var createdAt: Date117 public var updatedAt: Date118 public var deletedAt: Date? // tombstone for sync119120 public init(id: UUID = UUID(), title: String = "New chat", folderID: UUID? = nil, tags: [String] = [], isFavorite: Bool = false,121 isArchived: Bool = false, systemPrompt: String = "", modelID: String? = nil, settings: GenerationSettings = .default,122 preset: InferencePreset? = .balanced, activeLeafID: UUID? = nil, summary: ContextSummary? = nil,123 compaction: CompactionPolicy = .summarize, collectionIDs: [UUID] = [], agentID: UUID? = nil, workspaceID: UUID? = nil,124 autoRoute: Bool = false, createdAt: Date = Date(), updatedAt: Date = Date(), deletedAt: Date? = nil) {125 self.id = id; self.title = title; self.folderID = folderID; self.tags = tags; self.isFavorite = isFavorite; self.isArchived = isArchived126 self.systemPrompt = systemPrompt; self.modelID = modelID; self.settings = settings; self.preset = preset; self.activeLeafID = activeLeafID127 self.summary = summary; self.compaction = compaction; self.collectionIDs = collectionIDs; self.agentID = agentID128 self.workspaceID = workspaceID; self.autoRoute = autoRoute; self.createdAt = createdAt; self.updatedAt = updatedAt; self.deletedAt = deletedAt129 }130}131132public struct ChatFolder: Codable, Sendable, Hashable, Identifiable {133 public var id: UUID134 public var name: String135 public var symbol: String136 public var sortIndex: Int137 public var updatedAt: Date138 public var deletedAt: Date?139 public init(id: UUID = UUID(), name: String, symbol: String = "folder", sortIndex: Int = 0, updatedAt: Date = Date(), deletedAt: Date? = nil) {140 self.id = id; self.name = name; self.symbol = symbol; self.sortIndex = sortIndex; self.updatedAt = updatedAt; self.deletedAt = deletedAt141 }142}143144public struct PromptTemplate: Codable, Sendable, Hashable, Identifiable {145 public enum Kind: String, Codable, Sendable { case system, user }146 public var id: UUID147 public var name: String148 public var kind: Kind149 public var body: String // may contain {{variables}}150 public var symbol: String151 public var isBuiltIn: Bool152 public var updatedAt: Date153 public var deletedAt: Date?154 public init(id: UUID = UUID(), name: String, kind: Kind, body: String, symbol: String = "text.quote", isBuiltIn: Bool = false,155 updatedAt: Date = Date(), deletedAt: Date? = nil) {156 self.id = id; self.name = name; self.kind = kind; self.body = body; self.symbol = symbol; self.isBuiltIn = isBuiltIn157 self.updatedAt = updatedAt; self.deletedAt = deletedAt158 }159 public var variables: [String] {160 var found: [String] = []161 var rest = body[...]162 while let open = rest.range(of: "{{"), let close = rest[open.upperBound...].range(of: "}}") {163 let name = rest[open.upperBound..<close.lowerBound].trimmingCharacters(in: .whitespaces)164 if !name.isEmpty, !found.contains(name) { found.append(name) }165 rest = rest[close.upperBound...]166 }167 return found168 }169 public func rendered(_ values: [String: String]) -> String {170 var out = body171 for name in variables {172 for form in ["{{\(name)}}", "{{ \(name) }}"] { out = out.replacingOccurrences(of: form, with: values[name] ?? "") }173 }174 return out175 }176}177178/// A saved setup: model, prompts, parameters, tools and knowledge collections.179public struct ModelWorkspace: Codable, Sendable, Hashable, Identifiable {180 public var id: UUID181 public var name: String182 public var symbol: String183 public var modelID: String?184 public var systemPrompt: String185 public var settings: GenerationSettings186 public var preset: InferencePreset?187 public var enabledTools: [String]188 public var collectionIDs: [UUID]189 public var agentID: UUID?190 public var updatedAt: Date191 public var deletedAt: Date?192 public init(id: UUID = UUID(), name: String, symbol: String = "square.stack.3d.up", modelID: String? = nil, systemPrompt: String = "",193 settings: GenerationSettings = .default, preset: InferencePreset? = .balanced, enabledTools: [String] = [],194 collectionIDs: [UUID] = [], agentID: UUID? = nil, updatedAt: Date = Date(), deletedAt: Date? = nil) {195 self.id = id; self.name = name; self.symbol = symbol; self.modelID = modelID; self.systemPrompt = systemPrompt; self.settings = settings196 self.preset = preset; self.enabledTools = enabledTools; self.collectionIDs = collectionIDs; self.agentID = agentID197 self.updatedAt = updatedAt; self.deletedAt = deletedAt198 }199}200201public enum BuiltInTemplates {202 public static let all: [PromptTemplate] = [203 t("B0000000-0000-4000-8000-000000000001", "Concise assistant", .system, "You are a precise assistant. Answer directly, in the user's language, and say so when you are not sure.", "text.alignleft"),204 t("B0000000-0000-4000-8000-000000000002", "Senior engineer", .system, "You are a senior software engineer. Give working code, explain trade-offs briefly, and point out edge cases.", "chevron.left.forwardslash.chevron.right"),205 t("B0000000-0000-4000-8000-000000000003", "Research analyst", .system, "You are a careful research analyst. Separate facts from interpretation, cite the provided sources as [n], and list what is still unknown.", "doc.text.magnifyingglass"),206 t("B0000000-0000-4000-8000-000000000004", "Summarize", .user, "Summarize the following text in {{length}}:\n\n{{text}}", "text.redaction"),207 t("B0000000-0000-4000-8000-000000000005", "Translate", .user, "Translate the following text to {{language}}, keeping the tone:\n\n{{text}}", "character.bubble"),208 t("B0000000-0000-4000-8000-000000000006", "Explain code", .user, "Explain what this code does, step by step, then list possible bugs:\n\n```\n{{code}}\n```", "curlybraces"),209 t("B0000000-0000-4000-8000-000000000007", "Rewrite", .user, "Rewrite the following text to be {{style}}, without changing its meaning:\n\n{{text}}", "pencil.line"),210 ]211 private static func t(_ id: String, _ name: String, _ kind: PromptTemplate.Kind, _ body: String, _ symbol: String) -> PromptTemplate {212 PromptTemplate(id: UUID(uuidString: id)!, name: name, kind: kind, body: body, symbol: symbol, isBuiltIn: true, updatedAt: Date(timeIntervalSince1970: 0))213 }214}215