SPB Git

Repository Public

BranchesPanel.swift 15.5 KB 270 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Chat/Panels/BranchesPanel.swift3// Description: Branches tab: the conversation's family tree (jump, rename a branch, fork from the last message) and the variants of its turns (activate one).4import SwiftUI5import SPChatCore67/// Loads `GET /api/conversations/{id}/tree` and performs the branch operations on the server.8@Observable final class BranchesModel {9    private(set) var tree: ConversationTree?10    private(set) var isLoading = false11    private(set) var error: String?12    private(set) var conversationId: String?13    /// Variant being activated / conversation being renamed (rows show progress and refuse a second click).14    private(set) var busyId: String?15    @ObservationIgnored private var generation = 01617    func load(conversationId id: String?, api: APIClient) async {18        if id != conversationId { tree = nil; error = nil; conversationId = id }19        guard let id else { isLoading = false; return }20        generation += 1; let mine = generation21        isLoading = true22        do {23            let t = try await api.conversationTree(id)24            guard mine == generation else { return }25            tree = t; error = nil26        } catch {27            guard mine == generation, APIError.from(error).kind != .cancelled else { return }28            self.error = APIError.from(error).message29        }30        if mine == generation { isLoading = false }31    }3233    /// Names a branch (`PATCH /api/conversations/{id} {branchLabel}`); an empty label clears it.34    func rename(_ id: String, label: String, env: AppEnvironment) async throws {35        let trimmed = label.trimmingCharacters(in: .whitespacesAndNewlines)36        busyId = id; defer { busyId = nil }37        let updated = try await env.api.updateConversation(id, ConversationPatch(branchLabel: .some(trimmed.isEmpty ? nil : trimmed)))38        if env.conversations.conversation(id) != nil { env.conversations.upsert(updated) }39        if let conversationId { await load(conversationId: conversationId, api: env.api) }40    }4142    /// Shows another variant of a turn in the thread.43    func activate(_ option: ConversationTree.VariantGroup.Option, chat: ChatViewModel, env: AppEnvironment) async {44        guard !option.active, busyId == nil, !chat.isStreaming, let id = chat.conversationId else { return }45        busyId = option.id; defer { busyId = nil }46        if let message = chat.detail?.messages.first(where: { $0.id == option.id }) { await chat.showVersion(message) }47        else {48            do { try await env.api.activateBranch(conversationId: id, messageId: option.id); await chat.reload(attach: false) } catch { env.toasts.error(error); return }49        }50        await load(conversationId: id, api: env.api)51    }5253    /// Forks the thread at `messageId` into a new conversation and returns its id.54    func fork(conversationId id: String, at messageId: String, label: String, env: AppEnvironment) async throws -> String {55        busyId = id; defer { busyId = nil }56        let c = try await env.api.forkConversation(id, at: messageId, label: label)57        await env.conversations.refresh()58        return c.id59    }60}6162struct BranchesPanel: View {63    let chat: ChatViewModel64    @Bindable var window: WindowModel65    let model: BranchesModel66    @Environment(AppEnvironment.self) private var env67    @State private var renaming: ConversationTree.Node?68    @State private var labelText = ""69    @State private var showFork = false70    @State private var forkLabel = ""7172    private struct Trigger: Hashable { var conversation: String?; var messages: Int; var last: String?; var streaming: Bool }73    private var trigger: Trigger { Trigger(conversation: chat.conversationId, messages: chat.messages.count, last: chat.messages.last?.id, streaming: chat.isStreaming) }74    /// Last settled message of the displayed thread: where « Nouvelle branche ici… » forks.75    private var forkPoint: Message? { chat.messages.last { !$0.isOptimistic && $0.status != .streaming } }7677    var body: some View {78        Group {79            if chat.conversationId == nil {80                PanelPlaceholder(systemImage: PanelTab.branches.systemImage, title: "Nouvelle conversation", message: "Les branches et les variantes apparaîtront ici.")81            } else if let tree = model.tree {82                ScrollView {83                    VStack(spacing: 0) {84                        familySection(tree)85                        if !tree.variants.isEmpty { variantsSection(tree.variants) }86                    }87                    .padding(.bottom, DS.S.xl)88                }89            } else if let error = model.error {90                PanelPlaceholder(systemImage: "exclamationmark.triangle", title: "Branches indisponibles", message: error, actionTitle: "Réessayer") { Task { await reload() } }91            } else {92                Color.clear.frame(maxWidth: .infinity, maxHeight: .infinity)93            }94        }95        .overlay(alignment: .top) { PanelLoadingLine(active: model.isLoading && model.tree == nil) }96        .task(id: trigger) { await reload() }97        .alert("Nom de la branche", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } }), presenting: renaming) { node in98            TextField("Nom (vide pour l'effacer)", text: $labelText)99            Button("Enregistrer") { let text = labelText; Task { do { try await model.rename(node.id, label: text, env: env) } catch { env.toasts.error(error) } } }100            Button("Annuler", role: .cancel) {}101        } message: { node in Text("« \(node.title) »") }102        .alert("Nouvelle branche", isPresented: $showFork) {103            TextField("Nom de la branche (facultatif)", text: $forkLabel)104            Button("Créer") { fork() }105            Button("Annuler", role: .cancel) {}106        } message: { Text("Le fil est copié jusqu'au dernier message dans une nouvelle conversation.") }107        .accessibilityIdentifier("panel-branches")108    }109110    private func reload() async { await model.load(conversationId: chat.conversationId, api: env.api) }111112    private func fork() {113        guard let id = chat.conversationId, let point = forkPoint else { return }114        let label = forkLabel115        Task {116            do { let newId = try await model.fork(conversationId: id, at: point.id, label: label, env: env); window.open(newId); env.toasts.show("Branche créée") } catch { env.toasts.error(error) }117        }118    }119120    // MARK: Family121122    private func familySection(_ tree: ConversationTree) -> some View {123        PanelSection(tree.hasBranches ? "Famille (\(tree.family.count))" : "Famille") {124            VStack(spacing: 2) {125                ForEach(tree.family) { node in126                    FamilyRow(node: node, isCurrent: node.id == (tree.current ?? chat.conversationId), busy: model.busyId == node.id,127                              open: { if node.id != chat.conversationId { window.open(node.id) } },128                              rename: { labelText = node.branchLabel ?? ""; renaming = node })129                }130            }131            .padding(.horizontal, -DS.S.m)132            if !tree.hasBranches { Text("Cette conversation n'a pas encore de branche.").font(DS.F.caption).foregroundStyle(DS.C.muted) }133            Button { forkLabel = ""; showFork = true } label: { Label("Nouvelle branche ici…", systemImage: "arrow.triangle.branch") }134                .buttonStyle(ChipStyle()).disabled(forkPoint == nil || chat.isStreaming || model.busyId != nil)135                .help("Copier le fil jusqu'au dernier message dans une nouvelle conversation").accessibilityIdentifier("branch-new")136        }137    }138139    // MARK: Variants140141    private func variantsSection(_ groups: [ConversationTree.VariantGroup]) -> some View {142        PanelSection("Variantes des tours (\(groups.count))") {143            ForEach(groups) { group in144                VStack(alignment: .leading, spacing: DS.S.xs) {145                    Text(groupTitle(group)).font(DS.F.caption).foregroundStyle(DS.C.text2).lineLimit(2).fixedSize(horizontal: false, vertical: true)146                    VStack(spacing: 2) {147                        ForEach(Array(group.options.enumerated()), id: \.element.id) { i, option in148                            VariantRow(option: option, position: i + 1, total: group.options.count, isUser: group.role == "user", busy: model.busyId == option.id, disabled: chat.isStreaming || model.busyId != nil) {149                                Task { await model.activate(option, chat: chat, env: env) }150                            }151                        }152                    }153                    .padding(.horizontal, -DS.S.m)154                }155                .padding(.bottom, DS.S.xs)156            }157        }158    }159160    /// « Réponses à « Donne trois faits… » » — the turn is named by the message its variants answer.161    private func groupTitle(_ g: ConversationTree.VariantGroup) -> String {162        let kind = g.role == "user" ? "Versions de la question" : "Réponses"163        guard let pid = g.parentId, let parent = chat.detail?.messages.first(where: { $0.id == pid }) else { return g.role == "user" ? kind : "\(kind) du tour" }164        let text = PanelFormat.plain(parent.visibleText)165        let quote = text.count > 70 ? String(text.prefix(70)) + "…" : text166        return g.role == "user" ? "\(kind) après « \(quote) »" : "\(kind) à « \(quote) »"167    }168}169170private struct FamilyRow: View {171    let node: ConversationTree.Node172    let isCurrent: Bool173    let busy: Bool174    let open: () -> Void175    let rename: () -> Void176    @Environment(AppEnvironment.self) private var env177    @State private var hovering = false178179    var body: some View {180        HStack(spacing: DS.S.xs) {181            Button(action: open) {182                HStack(alignment: .top, spacing: DS.S.s) {183                    Image(systemName: node.isRoot ? "bubble.left" : "arrow.turn.down.right").font(.system(size: 10, weight: .medium)).foregroundStyle(isCurrent ? DS.C.accent : DS.C.muted)184                        .frame(width: 14, height: 16).padding(.leading, CGFloat(min(node.depth, 6)) * 14)185                    VStack(alignment: .leading, spacing: 3) {186                        HStack(spacing: DS.S.s) {187                            Text(node.branchLabel ?? node.title).font(DS.F.ui).foregroundStyle(isCurrent ? DS.C.accent : DS.C.text).lineLimit(1)188                            if isCurrent { Text("ACTUELLE").font(.system(size: 9, weight: .semibold)).tracking(0.5).foregroundStyle(DS.C.accent).fixedSize() }189                        }190                        if node.branchLabel != nil { Text(node.title).font(.system(size: 10.5)).foregroundStyle(DS.C.muted).lineLimit(1) }191                        HStack(spacing: DS.S.s) {192                            if let m = node.modelId { ModelChip(identity: env.catalog.identity(for: m, short: true), markSize: 12, font: .system(size: 10.5, weight: .medium)) }193                            Text([PanelFormat.messages(node.messageCount), node.lastAt.map { Format.relative($0) }].compactMap { $0 }.joined(separator: " · "))194                                .font(.system(size: 10.5).monospacedDigit()).foregroundStyle(DS.C.muted).lineLimit(1).fixedSize()195                        }196                    }197                    Spacer(minLength: 0)198                }199                .contentShape(Rectangle())200            }201            .buttonStyle(.plain)202            .help(isCurrent ? "Conversation affichée" : "Ouvrir « \(node.title) »")203            .accessibilityElement(children: .ignore)204            .accessibilityLabel("\(node.isRoot ? "Conversation d'origine" : "Branche") \(node.branchLabel ?? node.title), \(PanelFormat.messages(node.messageCount))" + (isCurrent ? ", actuelle" : ""))205            .accessibilityAddTraits(isCurrent ? [.isSelected, .isButton] : .isButton)206            if busy { ProgressView().controlSize(.small).frame(width: 22, height: 22) }207            else { IconButton(systemImage: "pencil", label: "Nommer la branche « \(node.branchLabel ?? node.title) »", action: rename).foregroundStyle(DS.C.muted).opacity(hovering || isCurrent ? 1 : 0.45) }208        }209        .padding(.horizontal, DS.S.m).padding(.vertical, 6)210        .background(isCurrent ? DS.C.accentSoft : (hovering ? DS.C.surface2 : .clear), in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))211        .onHover { hovering = $0 }212        .contextMenu { Button("Ouvrir", action: open).disabled(isCurrent); Button("Nommer la branche…", action: rename) }213        .accessibilityIdentifier("branch-\(node.id)")214    }215}216217private struct VariantRow: View {218    let option: ConversationTree.VariantGroup.Option219    let position: Int220    let total: Int221    let isUser: Bool222    let busy: Bool223    let disabled: Bool224    let activate: () -> Void225    @Environment(AppEnvironment.self) private var env226    @State private var hovering = false227228    var body: some View {229        Button(action: activate) {230            HStack(alignment: .top, spacing: DS.S.m) {231                ZStack {232                    Circle().strokeBorder(option.active ? DS.C.accent : DS.C.borderStrong, lineWidth: 1.5).frame(width: 12, height: 12)233                    if option.active { Circle().fill(DS.C.accent).frame(width: 6, height: 6) }234                }235                .padding(.top, 2).accessibilityHidden(true)236                VStack(alignment: .leading, spacing: 3) {237                    HStack(spacing: DS.S.s) {238                        if let m = option.model, !isUser { ModelChip(identity: env.catalog.identity(for: m, short: true), markSize: 13, font: DS.F.caption) }239                        else { Text("Version \(position)").font(DS.F.caption).foregroundStyle(DS.C.text) }240                        Spacer(minLength: 0)241                        Text("\(position)/\(total)").font(DS.F.micro.monospacedDigit()).foregroundStyle(DS.C.muted)242                    }243                    if let p = preview { Text(p).font(.system(size: 11)).foregroundStyle(DS.C.text2).lineLimit(2).multilineTextAlignment(.leading).frame(maxWidth: .infinity, alignment: .leading) }244                    Text([statusLabel, option.createdAt.map { PanelFormat.dateTime($0) }].compactMap { $0 }.joined(separator: " · ")).font(.system(size: 10.5).monospacedDigit()).foregroundStyle(DS.C.muted).lineLimit(1)245                }246                if busy { ProgressView().controlSize(.small) }247            }248            .padding(.horizontal, DS.S.m).padding(.vertical, 6)249            .background(option.active ? DS.C.accentSoft : (hovering ? DS.C.surface2 : .clear), in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))250            .contentShape(Rectangle())251        }252        .buttonStyle(.plain).disabled(disabled && !option.active).allowsHitTesting(!option.active)253        .onHover { hovering = $0 }254        .help(option.active ? "Variante affichée dans le fil" : "Afficher cette variante dans le fil")255        .accessibilityElement(children: .ignore)256        .accessibilityLabel("Variante \(position) sur \(total)" + (option.model.map { ", " + env.catalog.identity(for: $0).accessibilityText } ?? "") + (option.active ? ", affichée" : ""))257        .accessibilityAddTraits(option.active ? [.isSelected, .isButton] : .isButton)258        .accessibilityIdentifier("variant-\(option.id)")259    }260261    private var preview: String? {262        guard let p = option.preview else { return nil }263        let flat = PanelFormat.plain(p)264        return flat.isEmpty ? nil : flat265    }266    private var statusLabel: String? {267        switch option.status { case "complete", nil: option.active ? "affichée" : nil; case "error": "erreur"; case "cancelled": "interrompue"; case "incomplete": "incomplète"; case "streaming": "en cours"; case .some(let s): s }268    }269}270
Files main
Menu

Theme