SPB Git

Repository Public

Transcript.swift 17.2 KB 322 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Chat/Transcript.swift3// Description: The message list: user bubbles, assistant answers with model attribution, reasoning, tool activity, sources, measured metrics, branch navigation and actions.4import SwiftUI5import LocalChatCore67struct Transcript: View {8    @Environment(AppModel.self) private var app9    @Bindable var controller: ChatController10    let speech: SpeechController11    @Binding var editing: ChatMessage?12    var onOpenConversation: ((UUID) -> Void)?13    @State private var pinnedToBottom = true1415    var body: some View {16        ScrollViewReader { proxy in17            ScrollView {18                LazyVStack(alignment: .leading, spacing: 18) {19                    if let summary = controller.conversation.summary { SummaryBanner(summary: summary) { controller.clearSummary() } }20                    ForEach(controller.messages) { message in21                        MessageRow(message: message, controller: controller, speech: speech, editing: $editing, onOpenConversation: onOpenConversation)22                            .id(message.id)23                            .transition(.asymmetric(insertion: .move(edge: .bottom).combined(with: .opacity), removal: .opacity))24                    }25                    if let status = controller.status {26                        HStack(spacing: 8) { ThinkingDots(); Text(status).font(DS.F.caption).foregroundStyle(DS.C.muted) }.padding(.leading, 4)27                    }28                    Color.clear.frame(height: 1).id("bottom")29                }30                .padding(.horizontal, DS.S.lg).padding(.vertical, DS.S.lg)31                .frame(maxWidth: DS.S.column).frame(maxWidth: .infinity)32            }33            .scrollDismissesKeyboard(.interactively)34            .defaultScrollAnchor(.bottom)35            .onChange(of: controller.liveText.count / 24) { if pinnedToBottom { proxy.scrollTo("bottom", anchor: .bottom) } }36            .onChange(of: controller.messages.count) { withAnimation(DS.M.smooth) { proxy.scrollTo("bottom", anchor: .bottom) } }37            .onChange(of: controller.isGenerating) { _, generating in if generating { pinnedToBottom = true } }38            .onScrollPhaseChange { _, phase in if phase == .interacting || phase == .decelerating { pinnedToBottom = false } }39            .overlay(alignment: .bottomTrailing) {40                if !pinnedToBottom && controller.isGenerating {41                    Button { pinnedToBottom = true; withAnimation(DS.M.smooth) { proxy.scrollTo("bottom", anchor: .bottom) } } label: {42                        Image(systemName: "arrow.down").font(.system(size: 12, weight: .bold)).foregroundStyle(.white).frame(width: 32, height: 32).background(DS.G.accent, in: Circle())43                    }44                    .buttonStyle(.plain).padding(14).transition(.scale.combined(with: .opacity)).accessibilityLabel("Scroll to the latest text")45                }46            }47        }48    }49}5051struct SummaryBanner: View {52    let summary: ContextSummary53    let onClear: () -> Void54    @State private var expanded = false55    var body: some View {56        VStack(alignment: .leading, spacing: 6) {57            HStack(spacing: 6) {58                Image(systemName: "rectangle.compress.vertical").foregroundStyle(DS.C.warn)59                Text("Older turns (\(summary.messageCount) messages) are sent to the model as a summary. The original messages are kept.")60                    .font(DS.F.caption).foregroundStyle(DS.C.text2)61                Spacer(minLength: 4)62                Button(expanded ? "Hide" : "Show") { withAnimation(DS.M.snappy) { expanded.toggle() } }.buttonStyle(.plain).font(DS.F.caption).foregroundStyle(DS.C.accent)63                Button("Discard", action: onClear).buttonStyle(.plain).font(DS.F.caption).foregroundStyle(DS.C.muted)64            }65            if expanded { Text(summary.text).font(DS.F.callout).foregroundStyle(DS.C.text2).textSelection(.enabled) }66        }67        .padding(10).background(DS.C.warn.opacity(0.08), in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))68    }69}7071struct MessageRow: View {72    @Environment(AppModel.self) private var app73    let message: ChatMessage74    @Bindable var controller: ChatController75    let speech: SpeechController76    @Binding var editing: ChatMessage?77    var onOpenConversation: ((UUID) -> Void)?78    @State private var hovering = false79    @State private var copied = false8081    private var isStreaming: Bool { controller.streamingMessageID == message.id }82    private var text: String { isStreaming ? controller.liveText : message.content }83    private var reasoning: String? { isStreaming ? (controller.liveReasoning.isEmpty ? nil : controller.liveReasoning) : message.reasoning }8485    var body: some View {86        Group {87            switch message.role {88            case .user: userRow89            case .assistant: assistantRow90            case .tool, .system: EmptyView()91            }92        }93        #if os(macOS)94        .onHover { hovering = $0 }95        #endif96    }9798    // MARK: User99100    private var userRow: some View {101        VStack(alignment: .trailing, spacing: 6) {102            if !message.attachments.isEmpty { AttachmentStrip(attachments: message.attachments).frame(maxWidth: .infinity, alignment: .trailing) }103            if !message.content.isEmpty {104                Text(message.content).font(.system(size: DS.transcriptSize)).foregroundStyle(DS.C.text).textSelection(.enabled)105                    .padding(.horizontal, 14).padding(.vertical, 10)106                    .background(DS.C.userBubble, in: RoundedRectangle(cornerRadius: DS.R.bubble, style: .continuous))107                    .frame(maxWidth: 560, alignment: .trailing)108                    .contextMenu { userActions }109            }110            HStack(spacing: 2) {111                BranchSwitcher(messageID: message.id, controller: controller)112                if hovering || !Platform.isMac {113                    IconButton(copied ? "checkmark" : "doc.on.doc", label: "Copy") { copy(message.content) }114                    IconButton("pencil", label: "Edit as a new branch") { editing = message }.disabled(controller.isGenerating)115                }116            }117            .frame(height: 24)118        }119        .frame(maxWidth: .infinity, alignment: .trailing)120        .accessibilityElement(children: .combine).accessibilityLabel("You: \(message.content)")121    }122123    @ViewBuilder private var userActions: some View {124        Button("Copy", systemImage: "doc.on.doc") { copy(message.content) }125        Button("Edit as a new branch", systemImage: "pencil") { editing = message }.disabled(controller.isGenerating)126        Button("Fork conversation from here", systemImage: "arrow.triangle.branch") { fork() }127        Divider()128        Button("Delete this message and its replies", systemImage: "trash", role: .destructive) { controller.delete(message.id) }.disabled(controller.isGenerating)129    }130131    // MARK: Assistant132133    private var assistantRow: some View {134        VStack(alignment: .leading, spacing: 8) {135            HStack(spacing: 6) {136                ZStack { Circle().fill(DS.G.accent).frame(width: 20, height: 20); Image(systemName: "sparkle").font(.system(size: 10, weight: .bold)).foregroundStyle(.white) }137                Text(message.modelName ?? "Assistant").font(.system(size: 12.5, weight: .semibold)).foregroundStyle(DS.C.text)138                if let backend = message.backend { BackendBadge(backend) }139                if let node = message.remoteNodeName { Pill(node, symbol: "network", tone: .warn) }140                if message.status == .cancelled { Pill("Stopped", tone: .neutral) }141                Spacer(minLength: 0)142            }143            if let reasoning, !reasoning.isEmpty { ReasoningDisclosure(text: reasoning, isLive: isStreaming && text.isEmpty) }144            if isStreaming && !controller.liveToolActivity.isEmpty { ToolActivityList(activities: controller.liveToolActivity) }145            if text.isEmpty && isStreaming {146                if controller.status == nil { ThinkingDots().padding(.vertical, 4) }147            } else if !text.isEmpty {148                MarkdownView(text: text).environment(\.transcriptFontSize, DS.transcriptSize)149                    .overlay(alignment: .bottomTrailing) { if isStreaming { StreamingCursor() } }150            }151            if message.status == .failed {152                InlineNotice(.error, message.errorText ?? "Generation failed.")153            }154            if !message.sources.isEmpty && !isStreaming { SourcesList(sources: message.sources) }155            if !isStreaming {156                HStack(spacing: 2) {157                    BranchSwitcher(messageID: message.id, controller: controller)158                    IconButton(copied ? "checkmark" : "doc.on.doc", label: "Copy answer") { copy(message.content) }159                    IconButton("arrow.clockwise", label: "Regenerate (keeps this answer as another branch)") { controller.regenerate(message.id) }.disabled(controller.isGenerating)160                    IconButton(speech.speakingID == message.id ? "stop.circle" : "speaker.wave.2", label: "Read aloud") { speech.toggleSpeaking(message.content, id: message.id) }161                    Menu {162                        Button("Fork conversation from here", systemImage: "arrow.triangle.branch") { fork() }163                        Button("Copy as Markdown", systemImage: "doc.plaintext") { copy(message.content) }164                        Divider()165                        Button("Delete this answer", systemImage: "trash", role: .destructive) { controller.delete(message.id) }.disabled(controller.isGenerating)166                    } label: { Image(systemName: "ellipsis").font(.system(size: 13, weight: .medium)).frame(width: 28, height: 28).contentShape(Rectangle()) }167                        .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize().foregroundStyle(DS.C.text2)168                    Spacer(minLength: 6)169                    if app.preferences.showMetricsInChat, let metrics = message.metrics { MetricsFootnote(metrics: metrics) }170                }171                .frame(minHeight: 24)172            }173        }174        .frame(maxWidth: .infinity, alignment: .leading)175        .accessibilityElement(children: .contain)176        .accessibilityIdentifier("assistant-message")177    }178179    private func copy(_ string: String) {180        Pasteboard.copy(string); copied = true; Haptics.play(.light)181        Task { try? await Task.sleep(for: .seconds(1.4)); copied = false }182    }183    private func fork() {184        if let new = controller.fork(from: message.id) { onOpenConversation?(new.id) }185    }186}187188/// "‹ 2 / 3 ›" shown when a message has alternatives (edits or regenerations).189struct BranchSwitcher: View {190    let messageID: UUID191    @Bindable var controller: ChatController192    var body: some View {193        let position = controller.tree.branchPosition(of: messageID)194        if position.count > 1 {195            HStack(spacing: 0) {196                IconButton("chevron.left", label: "Previous version") { controller.switchBranch(from: messageID, offset: -1) }.disabled(position.index <= 1 || controller.isGenerating)197                Text("\(position.index) / \(position.count)").font(DS.F.micro).monospacedDigit().foregroundStyle(DS.C.muted)198                IconButton("chevron.right", label: "Next version") { controller.switchBranch(from: messageID, offset: 1) }.disabled(position.index >= position.count || controller.isGenerating)199            }200            .accessibilityElement(children: .contain).accessibilityIdentifier("branch-switcher")201        }202    }203}204205struct MetricsFootnote: View {206    let metrics: GenerationMetrics207    var body: some View {208        HStack(spacing: 8) {209            if let rate = metrics.tokensPerSecond { Label("\(MetricFormat.rate(rate)) tok/s", systemImage: "bolt.fill") }210            if let ttft = metrics.timeToFirstToken { Label(MetricFormat.seconds(ttft), systemImage: "timer") }211            if let n = metrics.completionTokens { Text("\(n) tokens") }212            if let cached = metrics.cachedPromptTokens, cached > 0 { Text("\(cached) cached").help("Prompt tokens reused from the KV cache") }213        }214        .font(DS.F.micro).monospacedDigit().foregroundStyle(DS.C.muted).labelStyle(.titleAndIcon).lineLimit(1)215        .accessibilityElement(children: .combine)216    }217}218219struct ReasoningDisclosure: View {220    let text: String221    let isLive: Bool222    @State private var expanded = false223    var body: some View {224        VStack(alignment: .leading, spacing: 6) {225            Button { withAnimation(DS.M.snappy) { expanded.toggle() } } label: {226                HStack(spacing: 6) {227                    Image(systemName: "brain").font(.system(size: 11)).foregroundStyle(DS.C.accent2)228                    Text(isLive ? "Thinking…" : "Reasoning").font(DS.F.caption).foregroundStyle(DS.C.text2)229                    Image(systemName: "chevron.right").font(.system(size: 8, weight: .bold)).rotationEffect(.degrees(expanded || isLive ? 90 : 0)).foregroundStyle(DS.C.muted)230                }231            }232            .buttonStyle(.plain)233            if expanded || isLive {234                Text(isLive ? String(text.suffix(600)) : text).font(DS.F.callout).foregroundStyle(DS.C.muted).textSelection(.enabled)235                    .padding(.leading, 10).overlay(alignment: .leading) { Rectangle().fill(DS.C.accent2.opacity(0.4)).frame(width: 2) }236                    .frame(maxWidth: .infinity, alignment: .leading)237            }238        }239    }240}241242struct ToolActivityList: View {243    let activities: [ChatController.ToolActivity]244    var body: some View {245        VStack(alignment: .leading, spacing: 6) {246            ForEach(activities) { activity in247                HStack(alignment: .firstTextBaseline, spacing: 8) {248                    if activity.isRunning { ProgressView().controlSize(.mini) }249                    else { Image(systemName: activity.isError ? "xmark.circle.fill" : "checkmark.circle.fill").foregroundStyle(activity.isError ? DS.C.danger : DS.C.ok).font(.system(size: 11)) }250                    VStack(alignment: .leading, spacing: 2) {251                        Text(activity.name).font(DS.F.mono(11.5, weight: .semibold)).foregroundStyle(DS.C.text)252                        Text(activity.arguments).font(DS.F.mono(10.5)).foregroundStyle(DS.C.muted).lineLimit(2)253                        if let output = activity.output { Text(output).font(DS.F.mono(10.5)).foregroundStyle(DS.C.text2).lineLimit(4) }254                    }255                }256            }257        }258        .padding(10).frame(maxWidth: .infinity, alignment: .leading)259        .background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))260    }261}262263struct SourcesList: View {264    let sources: [SourceReference]265    @State private var expanded = false266    var body: some View {267        VStack(alignment: .leading, spacing: 6) {268            Button { withAnimation(DS.M.snappy) { expanded.toggle() } } label: {269                Label("\(sources.count) source\(sources.count == 1 ? "" : "s") from your knowledge", systemImage: "books.vertical").font(DS.F.caption).foregroundStyle(DS.C.ok)270            }271            .buttonStyle(.plain)272            if expanded {273                ForEach(Array(sources.enumerated()), id: \.element.id) { index, source in274                    VStack(alignment: .leading, spacing: 3) {275                        Text("[\(index + 1)] \(source.documentName)\(source.page.map { " · p. \($0)" } ?? "")").font(.system(size: 12, weight: .semibold)).foregroundStyle(DS.C.text)276                        Text(source.excerpt).font(DS.F.caption).foregroundStyle(DS.C.text2).lineLimit(4).textSelection(.enabled)277                    }278                    .padding(8).frame(maxWidth: .infinity, alignment: .leading).background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))279                }280            }281        }282    }283}284285struct AttachmentStrip: View {286    @Environment(AppModel.self) private var app287    let attachments: [Attachment]288    var body: some View {289        HStack(spacing: 6) {290            ForEach(attachments) { attachment in291                if attachment.kind == .image, let data = app.attachments.data(for: attachment), let image = PlatformImageDecoder.image(from: data) {292                    image.resizable().scaledToFill().frame(width: 96, height: 96).clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))293                        .accessibilityLabel("Image \(attachment.fileName)")294                } else {295                    Label(attachment.fileName, systemImage: attachment.kind == .audio ? "waveform" : "doc.text").font(DS.F.caption).lineLimit(1)296                        .padding(.horizontal, 9).padding(.vertical, 6).background(DS.C.surface2, in: Capsule())297                }298            }299        }300    }301}302303enum PlatformImageDecoder {304    static func image(from data: Data) -> Image? {305        #if canImport(UIKit)306        UIImage(data: data).map { Image(uiImage: $0) }307        #else308        NSImage(data: data).map { Image(nsImage: $0) }309        #endif310    }311}312313/// Soft blinking caret at the end of streaming text.314struct StreamingCursor: View {315    @State private var on = false316    var body: some View {317        Capsule().fill(DS.G.accent).frame(width: 7, height: 15).opacity(on ? 1 : 0.25).offset(x: 10, y: -2)318            .onAppear { withAnimation(.easeInOut(duration: 0.55).repeatForever()) { on = true } }319            .accessibilityHidden(true)320    }321}322
Files main
Menu

Theme