Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/SPGlassAI/AI/GlassChatBubble.swift8// Module : SPGlassAI9// Repository : https://git.spboucher.ai/sp-glasskit10// Project Website : https://glass.spboucher.ai11// Created : 2026-12-0212// Last Modified : 2026-12-0313//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI42import SPGlassCore43import SPGlassTokens44import SPGlassThemes45import SPGlassEffects46#if os(macOS)47import AppKit48#elseif os(iOS)49import UIKit50#endif5152/// Who wrote a chat message.53public enum GlassChatRole: String, CaseIterable, Sendable {54 case user, assistant, system, tool5556 public var labelKey: GlassL10n.Key {57 switch self {58 case .user: .roleUser59 case .assistant: .roleAssistant60 case .system: .roleSystem61 case .tool: .roleTool62 }63 }6465 /// The localised name shown above the bubble ("You", "Assistant", …).66 public var label: String { GlassL10n.string(labelKey) }6768 /// The user's messages sit on the trailing edge, every other role on the leading edge.69 public var isTrailing: Bool { self == .user }70}7172/// Delivery state of a chat message.73public enum GlassChatMessageState: Equatable, Sendable {74 /// The text is final.75 case complete76 /// The text is still arriving.77 case streaming78 /// The message could not be produced or sent. `reason` is shown next to a warning symbol.79 case failed(reason: String?)80}8182/// A chat message as the host hands it to a ``GlassChatBubble``.83public struct GlassChatMessage: Identifiable, Equatable, Sendable {84 public let id: String85 public var role: GlassChatRole86 public var text: String87 public var state: GlassChatMessageState8889 public init(id: String, role: GlassChatRole, text: String, state: GlassChatMessageState = .complete) {90 self.id = id91 self.role = role92 self.text = text93 self.state = state94 }95}9697/// Sizing and wording rules of ``GlassChatBubble``.98public enum GlassChatBubbleMetrics {99 /// Keeps the width fraction between 0.4 and 1; NaN becomes the default 0.8.100 public static func clampedFraction(_ fraction: Double) -> Double {101 fraction.isNaN ? 0.8 : min(max(fraction, 0.4), 1)102 }103104 /// Largest width of a bubble inside a container.105 public static func maxWidth(container: CGFloat, fraction: Double) -> CGFloat {106 guard container.isFinite, container > 0 else { return 0 }107 return (container * clampedFraction(fraction)).rounded(.down)108 }109110 /// The failure text: the host's reason when it has one, GlassKit's generic message otherwise.111 public static func failureText(reason: String?) -> String {112 let trimmed = reason?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""113 return trimmed.isEmpty ? GlassL10n.string(.errorTitle) : trimmed114 }115116 /// Whether the copy action is offered: there must be something to copy.117 public static func canCopy(_ message: GlassChatMessage) -> Bool {118 !message.text.isEmpty119 }120121 /// Whether the copy button is shown under the bubble: for finished, non-empty messages the user did not122 /// write. The user's own messages keep the context menu only, which keeps a conversation quiet.123 public static func showsCopyButton(_ message: GlassChatMessage) -> Bool {124 canCopy(message) && message.state != .streaming && message.role != .user125 }126}127128/// The blocks a message text is split into for display.129public enum GlassChatBlock: Equatable, Sendable {130 /// Ordinary text.131 case paragraph(String)132 /// The inside of a fenced block (three backticks), with the language written after the opening fence.133 case code(language: String?, text: String)134 /// Consecutive lines that start with ">".135 case quote(String)136}137138/// Splits a message text into paragraphs, fenced code and quotes. Nothing else is interpreted: no inline139/// styles, no links, no HTML.140public enum GlassChatBlocks {141 /// The blocks of `text`, in order. An unterminated fence (a streaming message) is code up to the end.142 public static func parse(_ text: String) -> [GlassChatBlock] {143 var blocks: [GlassChatBlock] = []144 var plain: [String] = []145 var quote: [String] = []146 var code: [String]?147 var language: String?148149 func flushPlain() {150 let joined = plain.joined(separator: "\n").trimmingCharacters(in: .newlines)151 if !joined.isEmpty { blocks.append(.paragraph(joined)) }152 plain = []153 }154 func flushQuote() {155 if !quote.isEmpty { blocks.append(.quote(quote.joined(separator: "\n"))) }156 quote = []157 }158159 for line in text.components(separatedBy: "\n") {160 let trimmed = line.trimmingCharacters(in: .whitespaces)161 if trimmed.hasPrefix("```") {162 if let lines = code {163 blocks.append(.code(language: language, text: lines.joined(separator: "\n")))164 code = nil165 language = nil166 } else {167 flushPlain()168 flushQuote()169 let name = String(trimmed.dropFirst(3)).trimmingCharacters(in: .whitespaces)170 language = name.isEmpty ? nil : String(name.prefix(24))171 code = []172 }173 } else if code != nil {174 code?.append(line)175 } else if trimmed.hasPrefix(">") {176 flushPlain()177 quote.append(String(trimmed.dropFirst()).trimmingCharacters(in: .whitespaces))178 } else {179 flushQuote()180 plain.append(line)181 }182 }183 if let lines = code {184 blocks.append(.code(language: language, text: lines.joined(separator: "\n")))185 }186 flushQuote()187 flushPlain()188 return blocks189 }190}191192/// A chat message on an opaque bubble, aligned by role.193///194/// ```swift195/// GlassChatBubble(GlassChatMessage(id: "1", role: .user, text: "Summarise this page."))196/// GlassChatBubble(reply, onRetry: { resend() }) // reply.state is .streaming, .complete or .failed197/// ```198///199/// The role is written above the bubble, so it does not depend on colour or side. The text is selectable and200/// can be copied with the button under the bubble or the context menu. Fenced code (three backticks) is set in201/// a monospaced inset and lines starting with ">" as a quote; nothing else is interpreted. While `state` is202/// `.streaming` an indicator follows the text and the bubble is marked as updating frequently for assistive203/// technologies.204public struct GlassChatBubble: View {205 @GlassThemed private var theme206 @GlassAccessibility private var accessibility207 private let message: GlassChatMessage208 private let maxWidthFraction: Double209 private let usesMonospacedFont: Bool210 private let rendersBlocks: Bool211 private let onCopy: (@MainActor (String) -> Void)?212 private let onRetry: (@MainActor () -> Void)?213 @State private var copyCount = 0214 @State private var showsCopied = false215216 /// - Parameters:217 /// - message: the message to display.218 /// - maxWidthFraction: largest share of the container's width the bubble may take (0.4…1).219 /// - usesMonospacedFont: for code-like content such as tool output.220 /// - rendersBlocks: sets fenced code and quotes apart (default). When false the text is shown as it is.221 /// - onCopy: receives the text when the user copies. When `nil` the text goes to the system pasteboard.222 /// - onRetry: shows a "Retry" button on failed messages.223 public init(224 _ message: GlassChatMessage,225 maxWidthFraction: Double = 0.8,226 usesMonospacedFont: Bool = false,227 rendersBlocks: Bool = true,228 onCopy: (@MainActor (String) -> Void)? = nil,229 onRetry: (@MainActor () -> Void)? = nil230 ) {231 self.message = message232 self.maxWidthFraction = maxWidthFraction233 self.usesMonospacedFont = usesMonospacedFont234 self.rendersBlocks = rendersBlocks235 self.onCopy = onCopy236 self.onRetry = onRetry237 }238239 private var isStreaming: Bool { message.state == .streaming }240 private var isUser: Bool { message.role == .user }241242 /// Rounded everywhere except the corner nearest to the author, which is tighter.243 private var shape: UnevenRoundedRectangle {244 let radius = CGFloat(min(theme.radii.large, 20))245 let tail: CGFloat = 6246 return UnevenRoundedRectangle(247 topLeadingRadius: radius,248 bottomLeadingRadius: isUser ? radius : tail,249 bottomTrailingRadius: isUser ? tail : radius,250 topTrailingRadius: radius,251 style: .continuous252 )253 }254255 public var body: some View {256 GlassChatWidthLayout(fraction: maxWidthFraction) {257 VStack(alignment: message.role.isTrailing ? .trailing : .leading, spacing: theme.spacing.xxs) {258 VStack(alignment: message.role.isTrailing ? .trailing : .leading, spacing: theme.spacing.xxs) {259 Text(message.role.label)260 .font(theme.font(.caption).weight(.semibold))261 .foregroundStyle(theme.color(.textSecondary))262 .padding(.horizontal, theme.spacing.xxs)263 bubble264 }265 .accessibilityElement(children: .combine)266 .accessibilityAddTraits(isStreaming ? .updatesFrequently : [])267 footer268 }269 }270 .frame(maxWidth: .infinity, alignment: message.role.isTrailing ? .trailing : .leading)271 .task(id: copyCount) {272 guard copyCount > 0 else { return }273 showsCopied = true274 try? await Task.sleep(for: .seconds(1.5))275 if !Task.isCancelled { showsCopied = false }276 }277 }278279 private var foreground: Color {280 isUser ? theme.onColor(.primary) : theme.color(.textPrimary)281 }282283 @ViewBuilder284 private var bubble: some View {285 let content = VStack(alignment: .leading, spacing: theme.spacing.xs) {286 if !message.text.isEmpty {287 if rendersBlocks, !usesMonospacedFont {288 ForEach(Array(GlassChatBlocks.parse(message.text).enumerated()), id: \.offset) { _, block in289 blockView(block)290 }291 } else {292 Text(verbatim: message.text)293 .font(usesMonospacedFont ? theme.font(.callout).monospaced() : theme.font(.body))294 .textSelection(.enabled)295 .multilineTextAlignment(.leading)296 }297 }298 if isStreaming {299 Label {300 Text(GlassL10n.string(.streaming))301 } icon: {302 Image(systemName: "ellipsis")303 .symbolEffect(.variableColor.iterative, isActive: !accessibility.reduceMotion)304 }305 .font(theme.font(.caption).weight(.medium))306 .opacity(0.75)307 }308 }309 .padding(.horizontal, theme.spacing.sm + 2)310 .padding(.vertical, theme.spacing.xs + 2)311312 Group {313 if isUser {314 content315 .foregroundStyle(foreground)316 .background(theme.color(.primary), in: shape)317 } else {318 content319 .foregroundStyle(foreground)320 .glassOpaqueSurface(in: shape)321 }322 }323 .contextMenu {324 if GlassChatBubbleMetrics.canCopy(message) {325 Button(action: copy) {326 Label(GlassL10n.string(.copy), systemImage: "doc.on.doc")327 }328 }329 }330 }331332 @ViewBuilder333 private func blockView(_ block: GlassChatBlock) -> some View {334 switch block {335 case .paragraph(let text):336 Text(verbatim: text)337 .font(theme.font(.body))338 .textSelection(.enabled)339 .multilineTextAlignment(.leading)340 case .code(let language, let text):341 VStack(alignment: .leading, spacing: theme.spacing.xxs) {342 if let language {343 Text(verbatim: language.uppercased())344 .font(.system(.caption2, design: .monospaced, weight: .semibold))345 .tracking(0.6)346 .opacity(0.6)347 }348 // Code keeps its line breaks: long lines scroll sideways instead of wrapping.349 ScrollView(.horizontal) {350 Text(verbatim: text)351 .font(theme.font(.callout).monospaced())352 .textSelection(.enabled)353 .multilineTextAlignment(.leading)354 .fixedSize(horizontal: true, vertical: true)355 }356 .scrollIndicators(.hidden)357 .scrollBounceBehavior(.basedOnSize, axes: .horizontal)358 }359 .padding(theme.spacing.xs + 2)360 .frame(maxWidth: .infinity, alignment: .leading)361 .background(foreground.opacity(isUser ? 0.16 : 0.06), in: RoundedRectangle(cornerRadius: 10, style: .continuous))362 .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(foreground.opacity(0.1), lineWidth: 0.5))363 case .quote(let text):364 Text(verbatim: text)365 .font(theme.font(.body).italic())366 .textSelection(.enabled)367 .multilineTextAlignment(.leading)368 .opacity(0.85)369 .padding(.leading, theme.spacing.sm)370 .overlay(alignment: .leading) {371 Capsule()372 .fill(isUser ? foreground.opacity(0.6) : theme.color(.primary))373 .frame(width: 3)374 }375 }376 }377378 @ViewBuilder379 private var footer: some View {380 if case .failed(let reason) = message.state {381 VStack(alignment: message.role.isTrailing ? .trailing : .leading, spacing: theme.spacing.xxs) {382 Label(GlassChatBubbleMetrics.failureText(reason: reason), systemImage: "exclamationmark.triangle.fill")383 .font(theme.font(.caption).weight(.medium))384 .foregroundStyle(theme.color(.destructive))385 .multilineTextAlignment(.leading)386 .fixedSize(horizontal: false, vertical: true)387 if let onRetry {388 Button(action: onRetry) {389 Label(GlassL10n.string(.retry), systemImage: "arrow.clockwise")390 .font(theme.font(.caption).weight(.semibold))391 }392 .buttonStyle(.borderless)393 .tint(theme.color(.primary))394 }395 }396 .padding(.horizontal, theme.spacing.xxs)397 }398 if GlassChatBubbleMetrics.showsCopyButton(message) {399 Button(action: copy) {400 Label(GlassL10n.string(showsCopied ? .copied : .copy), systemImage: showsCopied ? "checkmark" : "doc.on.doc")401 .labelStyle(.iconOnly)402 .font(.system(size: 13, weight: .medium))403 .foregroundStyle(theme.color(showsCopied ? .success : .textSecondary))404 .contentTransition(.symbolEffect(.replace))405 .frame(width: 30, height: 30)406 .background(theme.color(.textSecondary).opacity(0.1), in: Circle())407 .glassMinimumHitTarget()408 .contentShape(Rectangle())409 }410 .buttonStyle(.plain)411 .help(GlassL10n.string(.copy))412 }413 }414415 private func copy() {416 if let onCopy {417 onCopy(message.text)418 } else {419 GlassPasteboard.copy(message.text)420 }421 copyCount += 1422 }423}424425/// Limits its single child to a fraction of the proposed width and takes the child's size.426struct GlassChatWidthLayout: Layout {427 let fraction: Double428429 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {430 guard let child = subviews.first else { return .zero }431 return child.sizeThatFits(limited(proposal))432 }433434 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {435 subviews.first?.place(at: bounds.origin, anchor: .topLeading, proposal: ProposedViewSize(width: bounds.width, height: bounds.height))436 }437438 private func limited(_ proposal: ProposedViewSize) -> ProposedViewSize {439 guard let width = proposal.width, width.isFinite else { return proposal }440 return ProposedViewSize(width: GlassChatBubbleMetrics.maxWidth(container: width, fraction: fraction), height: proposal.height)441 }442}443444/// Writes plain text to the system pasteboard.445enum GlassPasteboard {446 @MainActor447 static func copy(_ text: String) {448 #if os(macOS)449 NSPasteboard.general.clearContents()450 NSPasteboard.general.setString(text, forType: .string)451 #elseif os(iOS)452 UIPasteboard.general.string = text453 #endif454 }455}456