Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatCore/Sources/ConversationTree.swift3// Description: Pure functions over the message tree: active branch, siblings, branch switching.4import Foundation56public struct ConversationTree: Sendable {7 public let messages: [UUID: ChatMessage]8 public let children: [UUID?: [UUID]] // ordered by creation date910 public init(_ all: [ChatMessage]) {11 var byID: [UUID: ChatMessage] = [:]; var kids: [UUID?: [UUID]] = [:]12 for m in all.sorted(by: { ($0.createdAt, $0.id.uuidString) < ($1.createdAt, $1.id.uuidString) }) {13 byID[m.id] = m; kids[m.parentID, default: []].append(m.id)14 }15 messages = byID; children = kids16 }1718 /// Root → leaf path ending at `leaf` (or at the newest leaf when nil / unknown).19 public func path(to leaf: UUID?) -> [ChatMessage] {20 var tip = leaf.flatMap { messages[$0] } ?? newestLeaf()21 var out: [ChatMessage] = []; var guardCount = 022 while let m = tip, guardCount <= messages.count {23 out.append(m); tip = m.parentID.flatMap { messages[$0] }; guardCount += 124 }25 return out.reversed()26 }2728 public func newestLeaf() -> ChatMessage? {29 messages.values.filter { children[$0.id] == nil }.max { $0.createdAt < $1.createdAt }30 }3132 /// Follows the newest child at every level starting from `id`.33 public func leaf(under id: UUID) -> UUID {34 var current = id35 while let next = children[current]?.last { current = next }36 return current37 }3839 public func siblings(of id: UUID) -> [UUID] {40 guard let m = messages[id] else { return [] }41 return children[m.parentID] ?? []42 }4344 /// (1-based position, count) among the alternatives of a message.45 public func branchPosition(of id: UUID) -> (index: Int, count: Int) {46 let s = siblings(of: id)47 return ((s.firstIndex(of: id) ?? 0) + 1, max(1, s.count))48 }4950 /// The leaf to activate when the user steps to the previous / next alternative of `id`.51 public func leafAfterSwitching(from id: UUID, offset: Int) -> UUID? {52 let s = siblings(of: id)53 guard let i = s.firstIndex(of: id) else { return nil }54 let j = i + offset55 guard s.indices.contains(j) else { return nil }56 return leaf(under: s[j])57 }5859 public var branchCount: Int { max(1, messages.values.filter { children[$0.id] == nil }.count) }60}61