Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Tests/SPGlassAITests/GlassAITests.swift8// Module : Tests9// Repository : https://git.spboucher.ai/sp-glasskit10// Project Website : https://glass.spboucher.ai11// Created : 2026-12-0212// Last Modified : 2026-12-0213//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 Testing43import SPGlassCore44import SPGlassTokens45@testable import SPGlassAI46#if canImport(AppKit)47import AppKit48#endif4950@Suite("Chat bubble")51struct GlassChatBubbleTests {52 @Test func onlyTheUserSitsOnTheTrailingEdge() {53 #expect(GlassChatRole.allCases.filter(\.isTrailing) == [.user])54 }5556 @Test func everyRoleHasItsOwnLabel() {57 let labels = GlassChatRole.allCases.map(\.label)58 #expect(Set(labels).count == GlassChatRole.allCases.count)59 #expect(labels.allSatisfy { !$0.isEmpty })60 }6162 @Test func theBubbleWidthIsAFractionOfTheContainer() {63 #expect(GlassChatBubbleMetrics.maxWidth(container: 400, fraction: 0.8) == 320)64 #expect(GlassChatBubbleMetrics.maxWidth(container: 400, fraction: 0.1) == 160)65 #expect(GlassChatBubbleMetrics.maxWidth(container: 400, fraction: 3) == 400)66 #expect(GlassChatBubbleMetrics.maxWidth(container: 400, fraction: .nan) == 320)67 #expect(GlassChatBubbleMetrics.maxWidth(container: 0, fraction: 0.8) == 0)68 #expect(GlassChatBubbleMetrics.maxWidth(container: .infinity, fraction: 0.8) == 0)69 #expect(GlassChatBubbleMetrics.maxWidth(container: 333, fraction: 0.8) == 266)70 }7172 @Test func failuresUseTheHostReasonOrAGenericMessage() {73 #expect(GlassChatBubbleMetrics.failureText(reason: " Network lost ") == "Network lost")74 #expect(GlassChatBubbleMetrics.failureText(reason: nil) == GlassL10n.string(.errorTitle))75 #expect(GlassChatBubbleMetrics.failureText(reason: " ") == GlassL10n.string(.errorTitle))76 }7778 @Test func emptyMessagesCannotBeCopied() {79 #expect(!GlassChatBubbleMetrics.canCopy(GlassChatMessage(id: "1", role: .assistant, text: "", state: .streaming)))80 #expect(GlassChatBubbleMetrics.canCopy(GlassChatMessage(id: "2", role: .tool, text: "{ \"ok\": true }")))81 }8283 @Test func messagesAreValuesThatStreamByMutation() {84 var message = GlassChatMessage(id: "m", role: .assistant, text: "", state: .streaming)85 message.text += "مرحبا 👋 "86 message.text += "e\u{301}"87 message.state = .complete88 #expect(message == GlassChatMessage(id: "m", role: .assistant, text: "مرحبا 👋 e\u{301}"))89 #expect(GlassChatMessageState.failed(reason: "x") != .failed(reason: nil))90 }91}9293@Suite("Prompt bar")94struct GlassPromptBarTests {95 @Test func sendingNeedsNonBlankTextAndNoResponseInProgress() {96 #expect(GlassPromptInput.canSend(text: "Hello", isResponding: false))97 #expect(!GlassPromptInput.canSend(text: "Hello", isResponding: true))98 #expect(!GlassPromptInput.canSend(text: "", isResponding: false))99 #expect(!GlassPromptInput.canSend(text: " \n\t ", isResponding: false))100 #expect(GlassPromptInput.canSend(text: "\n 👍 \n", isResponding: false))101 #expect(GlassPromptInput.trimmed("\n Draft with\nlines \n") == "Draft with\nlines")102 }103104 @Test func returnSendsAndModifiedReturnInsertsALineBreak() {105 #expect(GlassPromptInput.returnKeyAction(shift: false, option: false, canSend: true) == .submit)106 #expect(GlassPromptInput.returnKeyAction(shift: false, option: false, canSend: false) == .ignore)107 #expect(GlassPromptInput.returnKeyAction(shift: true, option: false, canSend: true) == .insertNewline)108 #expect(GlassPromptInput.returnKeyAction(shift: false, option: true, canSend: true) == .insertNewline)109 #expect(GlassPromptInput.returnKeyAction(shift: true, option: true, canSend: false) == .insertNewline)110 }111112 @Test func lineBreaksGoToTheInsertionPoint() {113 let text = "Hello world"114 let middle = text.index(text.startIndex, offsetBy: 5)115 let inserted = GlassPromptInput.insertingNewline(in: text, replacing: middle..<middle)116 #expect(inserted.text == "Hello\n world")117 #expect(inserted.cursorOffset == 6)118119 let end = text.index(text.startIndex, offsetBy: 11)120 let replaced = GlassPromptInput.insertingNewline(in: text, replacing: middle..<end)121 #expect(replaced.text == "Hello\n")122 #expect(replaced.cursorOffset == 6)123124 let appended = GlassPromptInput.insertingNewline(in: text, replacing: nil)125 #expect(appended.text == "Hello world\n")126 #expect(appended.cursorOffset == 12)127128 let emoji = "👩👩👧👦ok"129 let afterFamily = emoji.index(after: emoji.startIndex)130 let unicode = GlassPromptInput.insertingNewline(in: emoji, replacing: afterFamily..<afterFamily)131 #expect(unicode.text == "👩👩👧👦\nok")132 #expect(unicode.cursorOffset == 2)133 }134135 @Test func aStaleSelectionFallsBackToAppending() {136 let longer = "A much longer earlier draft"137 let stale = longer.index(longer.startIndex, offsetBy: 20)..<longer.endIndex138 let result = GlassPromptInput.insertingNewline(in: "Hi", replacing: stale)139 #expect(result.text == "Hi\n")140 #expect(result.cursorOffset == 3)141 }142143 @Test func lineLimitsAreSanitised() {144 #expect(GlassPromptInput.sanitizedLineLimit(1...6) == 1...6)145 #expect(GlassPromptInput.sanitizedLineLimit(0...0) == 1...1)146 #expect(GlassPromptInput.sanitizedLineLimit(-3...4) == 1...4)147 #expect(GlassPromptInput.sanitizedLineLimit(5...5) == 5...5)148 }149150 @Test func attachmentsAreIdentifiedByTheHost() {151 let attachment = GlassPromptAttachment(id: "a", name: "Sample report.pdf")152 #expect(attachment.systemImage == "paperclip")153 #expect(attachment != GlassPromptAttachment(id: "b", name: "Sample report.pdf"))154 }155}156157@Suite("Thinking indicator")158struct GlassThinkingIndicatorTests {159 @Test func theLabelComesFromTheHostOrIsGeneric() {160 #expect(GlassActivityAnnouncement.resolvedLabel(" Searching the sample library ") == "Searching the sample library")161 #expect(GlassActivityAnnouncement.resolvedLabel(nil) == GlassL10n.string(.working))162 #expect(GlassActivityAnnouncement.resolvedLabel(" ") == GlassL10n.string(.working))163 }164165 @Test func onlyRealChangesAreAnnounced() {166 #expect(GlassActivityAnnouncement.shouldAnnounce(from: "Reading", to: "Writing"))167 #expect(!GlassActivityAnnouncement.shouldAnnounce(from: "Reading", to: "Reading "))168 #expect(!GlassActivityAnnouncement.shouldAnnounce(from: nil, to: ""))169 #expect(GlassActivityAnnouncement.shouldAnnounce(from: nil, to: "Reading"))170 }171172 @Test func announcementsArePolite() {173 let announcement = GlassActivityAnnouncement.attributed("Writing the summary")174 #expect(String(announcement.characters) == "Writing the summary")175 #expect(announcement.accessibilitySpeechAnnouncementPriority == .low)176 }177178 @Test func everyKindHasADistinctSymbol() {179 let symbols = GlassActivityKind.standard.map(\.symbolName)180 #expect(Set(symbols).count == GlassActivityKind.standard.count)181 #expect(GlassActivityKind.custom(systemImage: "globe").symbolName == "globe")182 }183}184185@Suite("Model picker")186struct GlassModelPickerTests {187 private let models = [188 GlassModelInfo(id: "r-large", name: "Sample Large", provider: "Remote Lab", capabilities: [.text, .vision, .tools], availability: .remote),189 GlassModelInfo(id: "l-10", name: "Sample 10", provider: "Device", capabilities: [.text], availability: .local),190 GlassModelInfo(id: "l-2", name: "Sample 2", provider: "Device", capabilities: [.text, .code], availability: .local),191 GlassModelInfo(id: "l-0", name: "Sample 0", provider: "Device", capabilities: [.text], availability: .unavailable(reason: "Not downloaded")),192 GlassModelInfo(id: "r-mini", name: "Sample Mini", provider: "Remote Lab", capabilities: [], availability: .remote),193 GlassModelInfo(id: "l-2", name: "Duplicate identifier", provider: "Other", availability: .remote),194 ]195196 @Test func modelsAreGroupedByProviderAndSorted() {197 let groups = GlassModelCatalog.grouped(models)198 #expect(groups.map(\.provider) == ["Device", "Remote Lab"])199 // Selectable first, numeric-aware names, unavailable last.200 #expect(groups[0].models.map(\.id) == ["l-2", "l-10", "l-0"])201 #expect(groups[1].models.map(\.id) == ["r-large", "r-mini"])202 }203204 @Test func groupingIsStableWhateverTheInputOrder() {205 #expect(GlassModelCatalog.grouped(models.dropLast().reversed()) == GlassModelCatalog.grouped(Array(models.dropLast())))206 #expect(GlassModelCatalog.grouped([]).isEmpty)207 }208209 @Test func unavailableModelsCannotBeSelected() {210 #expect(GlassModelCatalog.selection(afterPicking: models[1], current: "r-large") == "l-10")211 #expect(GlassModelCatalog.selection(afterPicking: models[3], current: "r-large") == "r-large")212 #expect(GlassModelCatalog.selection(afterPicking: models[3], current: nil) == nil)213 #expect(!GlassModelAvailability.unavailable(reason: "x").isSelectable)214 #expect(GlassModelAvailability.local.isSelectable && GlassModelAvailability.remote.isSelectable)215 }216217 @Test func subtitlesGiveAvailabilityThenCapabilitiesOrTheReason() {218 let large = GlassModelCatalog.subtitle(for: models[0])219 #expect(large.hasPrefix(GlassL10n.string(.modelRemote)))220 #expect(large.contains(GlassL10n.string(.capabilityVision)))221 #expect(large.contains(GlassL10n.string(.capabilityTools)))222 #expect(GlassModelCatalog.subtitle(for: models[4]) == GlassL10n.string(.modelRemote))223 let missing = GlassModelCatalog.subtitle(for: models[3])224 #expect(missing.hasPrefix(GlassL10n.string(.modelUnavailable)))225 #expect(missing.hasSuffix("Not downloaded"))226 }227228 @Test func capabilitiesKeepTheirDisplayOrder() {229 let capabilities: GlassModelCapabilities = [.code, .text, .audio]230 #expect(capabilities.descriptors.map(\.capability) == [.text, .audio, .code])231 #expect(GlassModelCapabilities.allDescriptors.count == 6)232 #expect(Set(GlassModelCapabilities.allDescriptors.map(\.symbolName)).count == 6)233 #expect(GlassModelCapabilities([]).descriptors.isEmpty)234 }235236 @Test func lookingUpTheSelection() {237 #expect(GlassModelCatalog.model(withID: "r-mini", in: models)?.name == "Sample Mini")238 #expect(GlassModelCatalog.model(withID: "missing", in: models) == nil)239 #expect(GlassModelCatalog.model(withID: nil, in: models) == nil)240 }241}242243@Suite("Agent panel")244struct GlassAgentPanelTests {245 @Test func progressCountsSucceededSteps() {246 let steps = [247 GlassAgentStep(id: "1", title: "Collect", status: .succeeded),248 GlassAgentStep(id: "2", title: "Analyse", status: .running),249 GlassAgentStep(id: "3", title: "Report", status: .pending),250 GlassAgentStep(id: "4", title: "Publish", status: .failed, errorMessage: "Sample failure"),251 ]252 let progress = GlassAgentTask(id: "t", title: "Sample task", status: .running, steps: steps).progress253 #expect(progress.completed == 1)254 #expect(progress.total == 4)255 #expect(progress.fraction == 0.25)256 #expect(progress.summary.contains("1"))257 #expect(progress.summary.contains("4"))258 }259260 @Test func progressIsBounded() {261 #expect(GlassAgentProgress(steps: []).fraction == 0)262 #expect(GlassAgentProgress(completed: 9, total: 3) == GlassAgentProgress(completed: 3, total: 3))263 #expect(GlassAgentProgress(completed: -2, total: 3).completed == 0)264 #expect(GlassAgentProgress(completed: 1, total: -1).total == 0)265 #expect(GlassAgentProgress(completed: 3, total: 3).fraction == 1)266 }267268 @Test func onlyUnfinishedTasksCanBeCancelled() {269 let cancellable = GlassAgentStatus.allCases.filter { GlassAgentTask(id: "t", title: "T", status: $0).isCancellable }270 #expect(cancellable == [.pending, .running])271 }272273 @Test func everyStatusHasAWordAndASymbolOfItsOwn() {274 #expect(Set(GlassAgentStatus.allCases.map(\.label)).count == 5)275 #expect(Set(GlassAgentStatus.allCases.map(\.symbolName)).count == 5)276 #expect(GlassAgentStatus.failed.colorToken == .destructive)277 #expect(GlassAgentStatus.succeeded.colorToken == .success)278 }279}280281#if canImport(AppKit)282@Suite("AI symbols")283struct GlassAISymbolTests {284 @Test func everySymbolExistsInSFSymbols() {285 var names = GlassActivityKind.standard.map(\.symbolName)286 names += GlassAgentStatus.allCases.map(\.symbolName)287 names += GlassModelCapabilities.allDescriptors.map(\.symbolName)288 names += [GlassModelAvailability.local, .remote, .unavailable(reason: "")].map(\.symbolName)289 names += ["cpu", "doc.on.doc", "checkmark", "ellipsis", "exclamationmark.triangle.fill", "plus", "stop.circle.fill", "arrow.up.circle.fill", "xmark.circle.fill", "tray", GlassPromptAttachment(id: "a", name: "a").systemImage]290 for name in names {291 #expect(NSImage(systemSymbolName: name, accessibilityDescription: nil) != nil, "Unknown SF Symbol \(name)")292 }293 }294}295#endif296