// ============================================================================= // SP BOUCHER | SOFTWARE & RESEARCH // ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING // ============================================================================= // // Project : SP GlassKit // File : Sources/SPGlassAI/AI/GlassChatBubble.swift // Module : SPGlassAI // Repository : https://git.spboucher.ai/sp-glasskit // Project Website : https://glass.spboucher.ai // Created : 2026-12-02 // Last Modified : 2026-12-03 // // Author : Simon-Pierre Boucher // Position : Professor of Finance // Institution : Université du Québec en Outaouais (UQO) // Organization : SP Boucher // Website : https://spboucher.ai // Git : https://git.spboucher.ai // // Preferred Contact: contact@spboucher.ai // Development : dev@spboucher.ai // Support : support@spboucher.ai // Security/Admin : admin@spboucher.ai // // Copyright (c) 2026 // Simon-Pierre Boucher // All rights reserved where applicable. This file is governed by the // applicable project license, copyright notices and relevant law. // Existing third-party rights and notices remain unaffected. // // License : MIT // // Do not embed credentials, private keys, access tokens, // certificates or confidential personal information. // // ============================================================================= // END OF SP BOUCHER SOURCE HEADER // ============================================================================= import SwiftUI #if os(macOS) import AppKit #elseif os(iOS) import UIKit #endif /// Who wrote a chat message. public enum GlassChatRole: String, CaseIterable, Sendable { case user, assistant, system, tool public var labelKey: GlassL10n.Key { switch self { case .user: .roleUser case .assistant: .roleAssistant case .system: .roleSystem case .tool: .roleTool } } /// The localised name shown above the bubble ("You", "Assistant", …). public var label: String { GlassL10n.string(labelKey) } /// The user's messages sit on the trailing edge, every other role on the leading edge. public var isTrailing: Bool { self == .user } } /// Delivery state of a chat message. public enum GlassChatMessageState: Equatable, Sendable { /// The text is final. case complete /// The text is still arriving. case streaming /// The message could not be produced or sent. `reason` is shown next to a warning symbol. case failed(reason: String?) } /// A chat message as the host hands it to a ``GlassChatBubble``. public struct GlassChatMessage: Identifiable, Equatable, Sendable { public let id: String public var role: GlassChatRole public var text: String public var state: GlassChatMessageState public init(id: String, role: GlassChatRole, text: String, state: GlassChatMessageState = .complete) { self.id = id self.role = role self.text = text self.state = state } } /// Sizing and wording rules of ``GlassChatBubble``. public enum GlassChatBubbleMetrics { /// Keeps the width fraction between 0.4 and 1; NaN becomes the default 0.8. public static func clampedFraction(_ fraction: Double) -> Double { fraction.isNaN ? 0.8 : min(max(fraction, 0.4), 1) } /// Largest width of a bubble inside a container. public static func maxWidth(container: CGFloat, fraction: Double) -> CGFloat { guard container.isFinite, container > 0 else { return 0 } return (container * clampedFraction(fraction)).rounded(.down) } /// The failure text: the host's reason when it has one, GlassKit's generic message otherwise. public static func failureText(reason: String?) -> String { let trimmed = reason?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" return trimmed.isEmpty ? GlassL10n.string(.errorTitle) : trimmed } /// Whether the copy action is offered: there must be something to copy. public static func canCopy(_ message: GlassChatMessage) -> Bool { !message.text.isEmpty } /// Whether the copy button is shown under the bubble: for finished, non-empty messages the user did not /// write. The user's own messages keep the context menu only, which keeps a conversation quiet. public static func showsCopyButton(_ message: GlassChatMessage) -> Bool { canCopy(message) && message.state != .streaming && message.role != .user } } /// The blocks a message text is split into for display. public enum GlassChatBlock: Equatable, Sendable { /// Ordinary text. case paragraph(String) /// The inside of a fenced block (three backticks), with the language written after the opening fence. case code(language: String?, text: String) /// Consecutive lines that start with ">". case quote(String) } /// Splits a message text into paragraphs, fenced code and quotes. Nothing else is interpreted: no inline /// styles, no links, no HTML. public enum GlassChatBlocks { /// The blocks of `text`, in order. An unterminated fence (a streaming message) is code up to the end. public static func parse(_ text: String) -> [GlassChatBlock] { var blocks: [GlassChatBlock] = [] var plain: [String] = [] var quote: [String] = [] var code: [String]? var language: String? func flushPlain() { let joined = plain.joined(separator: "\n").trimmingCharacters(in: .newlines) if !joined.isEmpty { blocks.append(.paragraph(joined)) } plain = [] } func flushQuote() { if !quote.isEmpty { blocks.append(.quote(quote.joined(separator: "\n"))) } quote = [] } for line in text.components(separatedBy: "\n") { let trimmed = line.trimmingCharacters(in: .whitespaces) if trimmed.hasPrefix("```") { if let lines = code { blocks.append(.code(language: language, text: lines.joined(separator: "\n"))) code = nil language = nil } else { flushPlain() flushQuote() let name = String(trimmed.dropFirst(3)).trimmingCharacters(in: .whitespaces) language = name.isEmpty ? nil : String(name.prefix(24)) code = [] } } else if code != nil { code?.append(line) } else if trimmed.hasPrefix(">") { flushPlain() quote.append(String(trimmed.dropFirst()).trimmingCharacters(in: .whitespaces)) } else { flushQuote() plain.append(line) } } if let lines = code { blocks.append(.code(language: language, text: lines.joined(separator: "\n"))) } flushQuote() flushPlain() return blocks } } /// A chat message on an opaque bubble, aligned by role. /// /// ```swift /// GlassChatBubble(GlassChatMessage(id: "1", role: .user, text: "Summarise this page.")) /// GlassChatBubble(reply, onRetry: { resend() }) // reply.state is .streaming, .complete or .failed /// ``` /// /// The role is written above the bubble, so it does not depend on colour or side. The text is selectable and /// can be copied with the button under the bubble or the context menu. Fenced code (three backticks) is set in /// a monospaced inset and lines starting with ">" as a quote; nothing else is interpreted. While `state` is /// `.streaming` an indicator follows the text and the bubble is marked as updating frequently for assistive /// technologies. public struct GlassChatBubble: View { @GlassThemed private var theme @GlassAccessibility private var accessibility private let message: GlassChatMessage private let maxWidthFraction: Double private let usesMonospacedFont: Bool private let rendersBlocks: Bool private let onCopy: (@MainActor (String) -> Void)? private let onRetry: (@MainActor () -> Void)? @State private var copyCount = 0 @State private var showsCopied = false /// - Parameters: /// - message: the message to display. /// - maxWidthFraction: largest share of the container's width the bubble may take (0.4…1). /// - usesMonospacedFont: for code-like content such as tool output. /// - rendersBlocks: sets fenced code and quotes apart (default). When false the text is shown as it is. /// - onCopy: receives the text when the user copies. When `nil` the text goes to the system pasteboard. /// - onRetry: shows a "Retry" button on failed messages. public init( _ message: GlassChatMessage, maxWidthFraction: Double = 0.8, usesMonospacedFont: Bool = false, rendersBlocks: Bool = true, onCopy: (@MainActor (String) -> Void)? = nil, onRetry: (@MainActor () -> Void)? = nil ) { self.message = message self.maxWidthFraction = maxWidthFraction self.usesMonospacedFont = usesMonospacedFont self.rendersBlocks = rendersBlocks self.onCopy = onCopy self.onRetry = onRetry } private var isStreaming: Bool { message.state == .streaming } private var isUser: Bool { message.role == .user } /// Rounded everywhere except the corner nearest to the author, which is tighter. private var shape: UnevenRoundedRectangle { let radius = CGFloat(min(theme.radii.large, 20)) let tail: CGFloat = 6 return UnevenRoundedRectangle( topLeadingRadius: radius, bottomLeadingRadius: isUser ? radius : tail, bottomTrailingRadius: isUser ? tail : radius, topTrailingRadius: radius, style: .continuous ) } public var body: some View { GlassChatWidthLayout(fraction: maxWidthFraction) { VStack(alignment: message.role.isTrailing ? .trailing : .leading, spacing: theme.spacing.xxs) { VStack(alignment: message.role.isTrailing ? .trailing : .leading, spacing: theme.spacing.xxs) { Text(message.role.label) .font(theme.font(.caption).weight(.semibold)) .foregroundStyle(theme.color(.textSecondary)) .padding(.horizontal, theme.spacing.xxs) bubble } .accessibilityElement(children: .combine) .accessibilityAddTraits(isStreaming ? .updatesFrequently : []) footer } } .frame(maxWidth: .infinity, alignment: message.role.isTrailing ? .trailing : .leading) .task(id: copyCount) { guard copyCount > 0 else { return } showsCopied = true try? await Task.sleep(for: .seconds(1.5)) if !Task.isCancelled { showsCopied = false } } } private var foreground: Color { isUser ? theme.onColor(.primary) : theme.color(.textPrimary) } @ViewBuilder private var bubble: some View { let content = VStack(alignment: .leading, spacing: theme.spacing.xs) { if !message.text.isEmpty { if rendersBlocks, !usesMonospacedFont { ForEach(Array(GlassChatBlocks.parse(message.text).enumerated()), id: \.offset) { _, block in blockView(block) } } else { Text(verbatim: message.text) .font(usesMonospacedFont ? theme.font(.callout).monospaced() : theme.font(.body)) .textSelection(.enabled) .multilineTextAlignment(.leading) } } if isStreaming { Label { Text(GlassL10n.string(.streaming)) } icon: { Image(systemName: "ellipsis") .symbolEffect(.variableColor.iterative, isActive: !accessibility.reduceMotion) } .font(theme.font(.caption).weight(.medium)) .opacity(0.75) } } .padding(.horizontal, theme.spacing.sm + 2) .padding(.vertical, theme.spacing.xs + 2) Group { if isUser { content .foregroundStyle(foreground) .background(theme.color(.primary), in: shape) } else { content .foregroundStyle(foreground) .glassOpaqueSurface(in: shape) } } .contextMenu { if GlassChatBubbleMetrics.canCopy(message) { Button(action: copy) { Label(GlassL10n.string(.copy), systemImage: "doc.on.doc") } } } } @ViewBuilder private func blockView(_ block: GlassChatBlock) -> some View { switch block { case .paragraph(let text): Text(verbatim: text) .font(theme.font(.body)) .textSelection(.enabled) .multilineTextAlignment(.leading) case .code(let language, let text): VStack(alignment: .leading, spacing: theme.spacing.xxs) { if let language { Text(verbatim: language.uppercased()) .font(.system(.caption2, design: .monospaced, weight: .semibold)) .tracking(0.6) .opacity(0.6) } // Code keeps its line breaks: long lines scroll sideways instead of wrapping. ScrollView(.horizontal) { Text(verbatim: text) .font(theme.font(.callout).monospaced()) .textSelection(.enabled) .multilineTextAlignment(.leading) .fixedSize(horizontal: true, vertical: true) } .scrollIndicators(.hidden) .scrollBounceBehavior(.basedOnSize, axes: .horizontal) } .padding(theme.spacing.xs + 2) .frame(maxWidth: .infinity, alignment: .leading) .background(foreground.opacity(isUser ? 0.16 : 0.06), in: RoundedRectangle(cornerRadius: 10, style: .continuous)) .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(foreground.opacity(0.1), lineWidth: 0.5)) case .quote(let text): Text(verbatim: text) .font(theme.font(.body).italic()) .textSelection(.enabled) .multilineTextAlignment(.leading) .opacity(0.85) .padding(.leading, theme.spacing.sm) .overlay(alignment: .leading) { Capsule() .fill(isUser ? foreground.opacity(0.6) : theme.color(.primary)) .frame(width: 3) } } } @ViewBuilder private var footer: some View { if case .failed(let reason) = message.state { VStack(alignment: message.role.isTrailing ? .trailing : .leading, spacing: theme.spacing.xxs) { Label(GlassChatBubbleMetrics.failureText(reason: reason), systemImage: "exclamationmark.triangle.fill") .font(theme.font(.caption).weight(.medium)) .foregroundStyle(theme.color(.destructive)) .multilineTextAlignment(.leading) .fixedSize(horizontal: false, vertical: true) if let onRetry { Button(action: onRetry) { Label(GlassL10n.string(.retry), systemImage: "arrow.clockwise") .font(theme.font(.caption).weight(.semibold)) } .buttonStyle(.borderless) .tint(theme.color(.primary)) } } .padding(.horizontal, theme.spacing.xxs) } if GlassChatBubbleMetrics.showsCopyButton(message) { Button(action: copy) { Label(GlassL10n.string(showsCopied ? .copied : .copy), systemImage: showsCopied ? "checkmark" : "doc.on.doc") .labelStyle(.iconOnly) .font(.system(size: 13, weight: .medium)) .foregroundStyle(theme.color(showsCopied ? .success : .textSecondary)) .contentTransition(.symbolEffect(.replace)) .frame(width: 30, height: 30) .background(theme.color(.textSecondary).opacity(0.1), in: Circle()) .glassMinimumHitTarget() .contentShape(Rectangle()) } .buttonStyle(.plain) .help(GlassL10n.string(.copy)) } } private func copy() { if let onCopy { onCopy(message.text) } else { GlassPasteboard.copy(message.text) } copyCount += 1 } } /// Limits its single child to a fraction of the proposed width and takes the child's size. struct GlassChatWidthLayout: Layout { let fraction: Double func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { guard let child = subviews.first else { return .zero } return child.sizeThatFits(limited(proposal)) } func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { subviews.first?.place(at: bounds.origin, anchor: .topLeading, proposal: ProposedViewSize(width: bounds.width, height: bounds.height)) } private func limited(_ proposal: ProposedViewSize) -> ProposedViewSize { guard let width = proposal.width, width.isFinite else { return proposal } return ProposedViewSize(width: GlassChatBubbleMetrics.maxWidth(container: width, fraction: fraction), height: proposal.height) } } /// Writes plain text to the system pasteboard. enum GlassPasteboard { @MainActor static func copy(_ text: String) { #if os(macOS) NSPasteboard.general.clearContents() NSPasteboard.general.setString(text, forType: .string) #elseif os(iOS) UIPasteboard.general.string = text #endif } }