SPB Git

Repository Public MIT

MessageViews.swift 17.8 KB 357 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraUI/Sources/Chat/MessageViews.swift10// Module           : Chat11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import SwiftUI89import AstraCore90import AstraDesign91import AstraPersistence9293/// Actions a message row can trigger. Kept as one value so rows stay cheap to compare.94struct MessageActions {95    var copy: (String) -> Void96    var regenerate: (String) -> Void97    var regenerateWith: (String) -> Void98    var edit: (MessageRecord) -> Void99    var bookmark: (String) -> Void100    var delete: (String) -> Void101    var branch: (String, Int) -> Void102    var retry: () -> Void103    var openModels: () -> Void104}105106// MARK: - User turn107108struct UserMessageView: View {109    let message: MessageRecord110    let attachments: [AttachmentRecord]111    let branch: BranchPosition?112    let actions: MessageActions113    let imageURL: (AttachmentRecord) -> URL?114    @Environment(\.transcriptFontSize) private var size115116    var body: some View {117        VStack(alignment: .trailing, spacing: 6) {118            if !attachments.isEmpty { AttachmentStrip(attachments: attachments, imageURL: imageURL) }119            if !message.text.isEmpty {120                Text(message.text)121                    .font(.system(size: size))122                    .foregroundStyle(AstraColor.textPrimary)123                    .textSelection(.enabled)124                    .padding(.horizontal, 14).padding(.vertical, 10)125                    .background(AstraColor.accentSoft, in: RoundedRectangle(cornerRadius: AstraRadius.bubble, style: .continuous))126                    .overlay(RoundedRectangle(cornerRadius: AstraRadius.bubble, style: .continuous).strokeBorder(AstraColor.violet.opacity(0.22), lineWidth: 1))127                    .contextMenu {128                        Button { actions.copy(message.text) } label: { Label("Copy", systemImage: "doc.on.doc") }129                        Button { actions.edit(message) } label: { Label("Edit and resend", systemImage: "pencil") }130                        Button { actions.bookmark(message.id) } label: { Label(message.bookmarked ? "Remove bookmark" : "Bookmark", systemImage: message.bookmarked ? "bookmark.slash" : "bookmark") }131                        Divider()132                        Button(role: .destructive) { actions.delete(message.id) } label: { Label("Delete from here", systemImage: "trash") }133                    }134            }135            if let branch, branch.count > 1 { BranchSwitcher(position: branch) { actions.branch(message.id, $0) } }136        }137        .frame(maxWidth: .infinity, alignment: .trailing)138        .padding(.leading, 44)139        .accessibilityElement(children: .combine)140        .accessibilityLabel("You: \(message.text)")141        .accessibilityAction(named: "Edit and resend") { actions.edit(message) }142        .accessibilityAction(named: "Copy") { actions.copy(message.text) }143    }144}145146struct BranchSwitcher: View {147    let position: BranchPosition148    let move: (Int) -> Void149    var body: some View {150        HStack(spacing: 2) {151            Button { move(-1) } label: { Image(systemName: "chevron.left").frame(width: 32, height: 32).contentShape(Rectangle()) }152                .disabled(position.index == 0).accessibilityLabel("Previous version")153            Text("\(position.index + 1) / \(position.count)").font(AstraFont.micro.monospacedDigit()).foregroundStyle(AstraColor.textSecondary)154                .accessibilityLabel("Version \(position.index + 1) of \(position.count)")155            Button { move(1) } label: { Image(systemName: "chevron.right").frame(width: 32, height: 32).contentShape(Rectangle()) }156                .disabled(position.index >= position.count - 1).accessibilityLabel("Next version")157        }158        .font(.caption.weight(.semibold))159        .foregroundStyle(AstraColor.textSecondary)160        .buttonStyle(.plain)161    }162}163164struct AttachmentStrip: View {165    let attachments: [AttachmentRecord]166    let imageURL: (AttachmentRecord) -> URL?167    var body: some View {168        FlowLayout(spacing: 6) {169            ForEach(attachments) { a in170                if a.kind == .image, let url = imageURL(a) {171                    LocalImage(url: url)172                        .frame(width: 96, height: 96)173                        .clipShape(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))174                        .overlay(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous).strokeBorder(AstraColor.stroke, lineWidth: 1))175                        .accessibilityLabel("Image \(a.filename)")176                } else {177                    HStack(spacing: 6) {178                        Image(systemName: a.kind == .pdf ? "doc.richtext" : "doc.text").foregroundStyle(AstraColor.cyan)179                        VStack(alignment: .leading, spacing: 1) {180                            Text(a.filename).font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textPrimary).lineLimit(1)181                            Text(ByteCountFormatter.string(fromByteCount: Int64(a.byteSize), countStyle: .file)).font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary)182                        }183                    }184                    .padding(.horizontal, 10).padding(.vertical, 8)185                    .background(AstraColor.surfaceRaised, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))186                    .frame(maxWidth: 220)187                    .accessibilityElement(children: .combine)188                }189            }190        }191    }192}193194/// Decodes a local image file off the main thread, downsampled to the size it is shown at.195struct LocalImage: View {196    let url: URL197    @State private var image: Image?198    var body: some View {199        ZStack {200            AstraColor.surfaceRaised201            if let image { image.resizable().scaledToFill() }202        }203        .task(id: url) { image = await ImageLoader.thumbnail(url: url, maxPixel: 400) }204    }205}206207// MARK: - Assistant turn208209struct AssistantMessageView: View {210    let message: MessageRecord211    let text: String212    let reasoning: String213    let isStreaming: Bool214    let isLoadingModel: Bool215    let modelName: String216    let reportedModel: String?217    let servedBy: String?218    let branch: BranchPosition?219    let actions: MessageActions220    @State private var showReasoning = false221    @State private var showDetails = false222223    var body: some View {224        VStack(alignment: .leading, spacing: 10) {225            header226            if !reasoning.isEmpty { reasoningBlock }227            if !text.isEmpty {228                MarkdownView(text: text)229                    .foregroundStyle(AstraColor.textPrimary)230            } else if isStreaming {231                HStack(spacing: 8) {232                    OrbitActivity(size: 22)233                    Text(isLoadingModel ? "Loading the model into memory…" : (reasoning.isEmpty ? "Waiting for the first token…" : "Thinking…"))234                        .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary)235                }236                .padding(.vertical, 2)237            }238            if !message.toolCalls.isEmpty, !isStreaming {239                ForEach(message.toolCalls) { call in240                    Label("Requested tool: \(call.name)", systemImage: "wrench.and.screwdriver").font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary)241                }242            }243            if let error = message.error, !isStreaming, error != .cancelled { errorCard(error) }244            if !isStreaming { footer }245        }246        .frame(maxWidth: .infinity, alignment: .leading)247        .contextMenu { if !isStreaming { menuItems } }248    }249250    private var header: some View {251        HStack(spacing: 8) {252            ProviderLogo(ref: message.model ?? ModelRef(provider: .openAI, modelID: ""), vendor: nil, size: 24)253            Text(modelName).font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary).lineLimit(1)254            if isStreaming { OrbitActivity(size: 16).opacity(text.isEmpty ? 0 : 1) }255            if message.bookmarked { Image(systemName: "bookmark.fill").font(.caption2).foregroundStyle(AstraColor.violet).accessibilityLabel("Bookmarked") }256            Spacer(minLength: 0)257        }258        .accessibilityElement(children: .combine)259        .accessibilityLabel("Answer from \(modelName)")260        .accessibilityAddTraits(.isHeader)261    }262263    private var reasoningBlock: some View {264        VStack(alignment: .leading, spacing: 6) {265            Button { withAnimation(AstraMotion.standard) { showReasoning.toggle() } } label: {266                HStack(spacing: 6) {267                    Image(systemName: "brain").imageScale(.small)268                    Text(isStreaming && text.isEmpty ? "Thinking…" : "Reasoning summary")269                    Image(systemName: "chevron.right").imageScale(.small).rotationEffect(.degrees(showReasoning ? 90 : 0))270                }271                .font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary)272                .frame(minHeight: 36).contentShape(Rectangle())273            }274            .buttonStyle(.plain)275            .accessibilityHint(showReasoning ? "Collapses the summary" : "Shows the summary the model provided")276            if showReasoning {277                Text(reasoning).font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).textSelection(.enabled)278                    .padding(10).frame(maxWidth: .infinity, alignment: .leading)279                    .background(AstraColor.surfaceSunken, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))280            }281        }282    }283284    private func errorCard(_ error: AstraError) -> some View {285        let needsKey: Bool = { if case .missingCredential = error { return true }; if case .unauthorized = error { return true }; return false }()286        return NoticeCard(.error, title: error.title, message: error.message,287                          actionTitle: needsKey ? "Open Models" : (error.isTransient || text.isEmpty ? "Try again" : nil),288                          action: needsKey ? actions.openModels : actions.retry)289    }290291    @ViewBuilder private var footer: some View {292        VStack(alignment: .leading, spacing: 6) {293            HStack(spacing: 2) {294                if let branch, branch.count > 1 { BranchSwitcher(position: branch) { actions.branch(message.id, $0) } }295                footerButton("doc.on.doc", "Copy answer") { actions.copy(text) }296                footerButton("arrow.clockwise", "Regenerate") { actions.regenerate(message.id) }297                footerButton(message.bookmarked ? "bookmark.fill" : "bookmark", message.bookmarked ? "Remove bookmark" : "Bookmark") { actions.bookmark(message.id) }298                footerButton("info.circle", "Answer details") { withAnimation(AstraMotion.standard) { showDetails.toggle() } }299                Spacer(minLength: 0)300                if message.status == .stopped { AstraBadge("Stopped", symbol: "stop.fill", tone: .warning) }301                else if message.stopReason == .maxTokens { AstraBadge("Output limit", symbol: "scissors", tone: .warning) }302            }303            if showDetails { details.astraAppear(edge: .top) }304        }305    }306307    private func footerButton(_ symbol: String, _ label: String, action: @escaping () -> Void) -> some View {308        Button(action: action) {309            Image(systemName: symbol).font(.system(size: 14, weight: .medium)).foregroundStyle(AstraColor.textTertiary)310                .frame(width: 38, height: 38).contentShape(Rectangle())311        }312        .buttonStyle(.plain).accessibilityLabel(label)313    }314315    /// Measured facts only. Anything the provider or runtime did not report shows as an em dash.316    private var details: some View {317        VStack(alignment: .leading, spacing: 10) {318            LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())], alignment: .leading, spacing: 10) {319                MetricTile("First token", value: message.timeToFirstToken.map { String(format: "%.2f", $0) }, unit: "s")320                MetricTile("Total", value: message.totalTime.map { String(format: "%.1f", $0) }, unit: "s")321                MetricTile("Speed", value: message.tokensPerSecond.map { String(format: "%.1f", $0) }, unit: "tok/s")322                MetricTile("Input", value: message.usage?.inputTokens.map(String.init), unit: "tok")323                MetricTile("Output", value: message.usage?.outputTokens.map(String.init), unit: "tok")324                MetricTile("Cost", value: message.cost.map(\.label))325            }326            VStack(alignment: .leading, spacing: 3) {327                if let reported = reportedModel, !reported.isEmpty { detailLine("Answered by", reported) }328                if let servedBy, !servedBy.isEmpty { detailLine("Served by", servedBy) }329                if let cached = message.usage?.cachedInputTokens, cached > 0 { detailLine("Cached input", "\(cached) tok") }330                if let r = message.usage?.reasoningTokens, r > 0 { detailLine("Reasoning", "\(r) tok") }331                if let stop = message.stopReason { detailLine("Ended", stop.label) }332                if let cost = message.cost, cost.basis == .estimatedFromUsage, let asOf = cost.pricingAsOf { detailLine("Price basis", "Published prices of \(asOf); an estimate, not a bill") }333            }334        }335        .padding(12)336        .background(AstraColor.surface, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))337        .overlay(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous).strokeBorder(AstraColor.stroke, lineWidth: 1))338    }339340    private func detailLine(_ label: String, _ value: String) -> some View {341        HStack(alignment: .firstTextBaseline, spacing: 6) {342            Text(label).font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary).frame(width: 84, alignment: .leading)343            Text(value).font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).textSelection(.enabled)344        }345        .accessibilityElement(children: .combine)346    }347348    @ViewBuilder private var menuItems: some View {349        Button { actions.copy(text) } label: { Label("Copy", systemImage: "doc.on.doc") }350        Button { actions.regenerate(message.id) } label: { Label("Regenerate", systemImage: "arrow.clockwise") }351        Button { actions.regenerateWith(message.id) } label: { Label("Regenerate with another model…", systemImage: "arrow.triangle.branch") }352        Button { actions.bookmark(message.id) } label: { Label(message.bookmarked ? "Remove bookmark" : "Bookmark", systemImage: message.bookmarked ? "bookmark.slash" : "bookmark") }353        Divider()354        Button(role: .destructive) { actions.delete(message.id) } label: { Label("Delete from here", systemImage: "trash") }355    }356}357
Files main
Menu

Theme