Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Apps/GlassStudio/Kit/Descriptors/AIDescriptors.swift8// Module : GlassStudio9// 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 SPGlassKit4344extension ComponentCatalog {45 static var aiDescriptors: [ComponentDescriptor] {46 [glassChatBubble, glassPromptBar, glassThinkingIndicator, glassModelPicker, glassAgentPanel]47 }4849 // MARK: Chat bubble5051 private static func chatState(_ values: InspectorValues) -> GlassChatMessageState {52 switch values.choice("state") {53 case "streaming": .streaming54 case "failed": .failed(reason: values.text("reason").isEmpty ? nil : values.text("reason"))55 default: .complete56 }57 }5859 /// "Retry" is offered on failed messages only; in the preview it does nothing.60 private static func retryAction(_ values: InspectorValues) -> (@MainActor () -> Void)? {61 guard values.choice("state") == "failed" else { return nil }62 return {}63 }6465 private static var glassChatBubble: ComponentDescriptor {66 ComponentDescriptor(67 "glass-chat-bubble",68 fields: [69 .choice("role", "Role", options: [.init("user", "User"), .init("assistant", "Assistant"), .init("system", "System"), .init("tool", "Tool")], default: "assistant"),70 .text("text", "Message", default: "Occupancy held at 94 % over the quarter. Net rent rose 2.1 %, slightly under plan.", maxLength: 400),71 .choice("state", "State", options: [.init("complete", "Complete"), .init("streaming", "Streaming"), .init("failed", "Failed")]),72 .text("reason", "Failure reason", default: "The connection was interrupted before the end of the answer.", maxLength: 120),73 .number("width", "Maximum width", in: 0.4...1, step: 0.1, default: 0.8),74 .toggle("monospaced", "Monospaced font"),75 ],76 variants: [77 ComponentVariant("user", "User", ["role": .choice("user"), "text": .text("Can you sum up the Harbour Yard note in two points?")]),78 ComponentVariant("streaming", "Streaming", ["state": .choice("streaming"), "text": .text("Occupancy held at 94 % over the quarter. Net rent")]),79 ComponentVariant("failed", "Failed", ["state": .choice("failed"), "text": .text("Occupancy held at 94 % over the")]),80 ComponentVariant("code", "Code and quote", ["text": .text("The note says:\n> Net rent rose 2.1 % over the quarter.\nAs a filter:\n```swift\nlet growth = rent\n .change(over: .quarter)\n```")]),81 ],82 isComposable: true,83 prefersStage: false,84 preview: { values in85 AIConversationPreview(86 message: GlassChatMessage(id: "1", role: GlassChatRole(rawValue: values.choice("role")) ?? .assistant, text: values.text("text"), state: chatState(values)),87 maxWidthFraction: values.number("width"),88 usesMonospacedFont: values.bool("monospaced"),89 onRetry: retryAction(values)90 )91 },92 snippet: { values in93 var message = ["id: \"1\"", "role: \(SwiftLiteral.enumCase(values.choice("role"), fallback: "assistant"))", "text: \(SwiftLiteral.string(values.text("text")))"]94 switch values.choice("state") {95 case "streaming": message.append("state: .streaming")96 case "failed": message.append("state: .failed(reason: \(values.text("reason").isEmpty ? "nil" : SwiftLiteral.string(values.text("reason"))))")97 default: break98 }99 var arguments = ["GlassChatMessage(\(message.joined(separator: ", ")))"]100 if abs(values.number("width") - 0.8) > 0.001 { arguments.append("maxWidthFraction: \(SwiftLiteral.number(values.number("width")))") }101 if values.bool("monospaced") { arguments.append("usesMonospacedFont: true") }102 if values.choice("state") == "failed" { arguments.append("onRetry: {\n // send the message again\n }") }103 return "GlassChatBubble(\n\(arguments.map { " " + $0 }.joined(separator: ",\n"))\n)"104 }105 )106 }107108 // MARK: Prompt bar109110 /// Fictitious attachments.111 private static let sampleAttachments = [112 GlassPromptAttachment(id: "a1", name: "facade-options.pdf", systemImage: "doc.richtext"),113 GlassPromptAttachment(id: "a2", name: "site-plan.png", systemImage: "photo"),114 GlassPromptAttachment(id: "a3", name: "cost-notes.txt", systemImage: "doc.text"),115 ]116117 private static var glassPromptBar: ComponentDescriptor {118 ComponentDescriptor(119 "glass-prompt-bar",120 fields: [121 .text("draft", "Draft", default: "Compare the two facade options and list what drives the cost of each.", maxLength: 400),122 .text("placeholder", "Placeholder", default: "Ask about this project", maxLength: 60),123 .toggle("responding", "Responding"),124 .number("attachments", "Attachments", in: 0...3, default: 2),125 .toggle("attach", "Attachment button", default: true),126 .toggle("accessory", "Model chip", default: true),127 .number("maxLines", "Maximum lines", in: 1...10, default: 6),128 ],129 variants: [130 ComponentVariant("empty", "Empty", ["draft": .text(""), "attachments": .number(0)]),131 ComponentVariant("responding", "Responding", ["responding": .bool(true), "draft": .text("")]),132 ComponentVariant("minimal", "Editor only", ["attachments": .number(0), "attach": .bool(false), "accessory": .bool(false), "draft": .text("")]),133 ],134 isComposable: true,135 prefersStage: true,136 preview: { values in137 AISampleLabelled(isOnStage: true) {138 AIPromptBarPreview(139 draft: values.text("draft"),140 placeholder: values.text("placeholder"),141 isResponding: values.bool("responding"),142 attachments: Array(sampleAttachments.prefix(Int(values.number("attachments")))),143 showsAttachButton: values.bool("attach"),144 showsAccessory: values.bool("accessory"),145 maxLines: Int(values.number("maxLines"))146 )147 .id(values)148 }149 },150 snippet: { values in151 var arguments = ["text: .constant(\(SwiftLiteral.string(values.text("draft"))))"]152 if !values.text("placeholder").isEmpty { arguments.append("placeholder: \(SwiftLiteral.string(values.text("placeholder")))") }153 if values.bool("responding") { arguments.append("isResponding: true") }154 let attachments = sampleAttachments.prefix(Int(values.number("attachments")))155 if !attachments.isEmpty {156 let rows = attachments.map { " GlassPromptAttachment(id: \(SwiftLiteral.string($0.id)), name: \(SwiftLiteral.string($0.name)), systemImage: \(SwiftLiteral.string($0.systemImage)))," }157 arguments.append("attachments: [\n\(rows.joined(separator: "\n"))\n]")158 }159 if values.number("maxLines") != 6 { arguments.append("lineLimit: 1...\(SwiftLiteral.number(values.number("maxLines")))") }160 var code = "GlassPromptBar(\(arguments.joined(separator: ", "))) { prompt in\n // send the prompt\n} onStop: {\n // cancel the response\n}"161 if values.bool("attach") { code += " onAttach: {\n // present your own file or photo picker\n}" }162 if !attachments.isEmpty { code += " onRemoveAttachment: { attachment in\n // remove the attachment\n}" }163 if values.bool("accessory") {164 code += " accessory: {\n GlassModelPicker(models: [GlassModelInfo(id: \"sample-large\", name: \"Sample Large\", provider: \"Example Cloud\", availability: .remote)], selection: .constant(\"sample-large\"))\n}"165 }166 return code167 }168 )169 }170171 // MARK: Thinking indicator172173 private static let activityKinds = ["thinking", "searching", "reading", "writing", "waiting"]174175 private static func activityKind(_ values: InspectorValues) -> GlassActivityKind {176 switch values.choice("kind") {177 case "searching": .searching178 case "reading": .reading179 case "writing": .writing180 case "waiting": .waiting181 case "custom": .custom(systemImage: values.text("symbol").isEmpty ? "ellipsis" : values.text("symbol"))182 default: .thinking183 }184 }185186 private static var glassThinkingIndicator: ComponentDescriptor {187 ComponentDescriptor(188 "glass-thinking-indicator",189 fields: [190 .choice("kind", "Activity", options: [191 .init("thinking", "Thinking"), .init("searching", "Searching"), .init("reading", "Reading"),192 .init("writing", "Writing"), .init("waiting", "Waiting"), .init("custom", "Custom symbol"),193 ]),194 .text("label", "Label", default: "Comparing the two options", maxLength: 120),195 .choice("style", "Style", options: [.init("chip", "Chip"), .init("plain", "Plain")]),196 .text("symbol", "Custom symbol", default: "arrow.down.circle", maxLength: 40),197 .toggle("announces", "Announce changes", default: true),198 ],199 variants: [200 ComponentVariant("searching", "Searching", ["kind": .choice("searching"), "label": .text("Searching the project files")]),201 ComponentVariant("custom", "Custom symbol", ["kind": .choice("custom"), "label": .text("Downloading the drawings")]),202 ComponentVariant("plain", "Plain", ["style": .choice("plain"), "kind": .choice("reading"), "label": .text("Reading facade-options.pdf")]),203 ComponentVariant("default", "Default label", ["label": .text("")]),204 ],205 isComposable: true,206 prefersStage: false,207 preview: { values in208 AIThinkingPreview {209 GlassThinkingIndicator(210 activityKind(values),211 label: values.text("label").isEmpty ? nil : values.text("label"),212 announcesChanges: values.bool("announces"),213 style: GlassThinkingIndicatorStyle(rawValue: values.choice("style")) ?? .chip214 )215 }216 },217 snippet: { values in218 var arguments: [String] = []219 if values.choice("kind") == "custom" {220 arguments.append(".custom(systemImage: \(SwiftLiteral.string(values.text("symbol").isEmpty ? "ellipsis" : values.text("symbol"))))")221 } else if values.choice("kind") != "thinking", activityKinds.contains(values.choice("kind")) {222 arguments.append(SwiftLiteral.enumCase(values.choice("kind"), fallback: "thinking"))223 }224 if !values.text("label").isEmpty { arguments.append("label: \(SwiftLiteral.string(values.text("label")))") }225 if !values.bool("announces") { arguments.append("announcesChanges: false") }226 if values.choice("style") == "plain" { arguments.append("style: .plain") }227 return "GlassThinkingIndicator(\(arguments.joined(separator: ", ")))"228 }229 )230 }231232 // MARK: Model picker233234 private struct SampleModel {235 let info: GlassModelInfo236 /// The Swift source of `info`'s capabilities and availability.237 let capabilities: String238 let availability: String239 }240241 /// Fictitious models and providers.242 private static let sampleModels = [243 SampleModel(info: GlassModelInfo(id: "sample-nano", name: "Sample Nano", provider: "On this device", capabilities: [.text], availability: .local), capabilities: "[.text]", availability: ".local"),244 SampleModel(info: GlassModelInfo(id: "sample-large", name: "Sample Large", provider: "Example Cloud", capabilities: [.text, .vision, .tools, .reasoning], availability: .remote), capabilities: "[.text, .vision, .tools, .reasoning]", availability: ".remote"),245 SampleModel(info: GlassModelInfo(id: "sample-vision", name: "Sample Vision", provider: "On this device", capabilities: [.text, .vision], availability: .unavailable(reason: "Not downloaded")), capabilities: "[.text, .vision]", availability: ".unavailable(reason: \"Not downloaded\")"),246 SampleModel(info: GlassModelInfo(id: "sample-code", name: "Sample Code", provider: "Example Cloud", capabilities: [.text, .code, .tools], availability: .remote), capabilities: "[.text, .code, .tools]", availability: ".remote"),247 SampleModel(info: GlassModelInfo(id: "sample-voice", name: "Sample Voice", provider: "Example Cloud", capabilities: [.audio], availability: .unavailable(reason: "Sign-in required")), capabilities: "[.audio]", availability: ".unavailable(reason: \"Sign-in required\")"),248 ]249250 private static func models(_ values: InspectorValues) -> [SampleModel] {251 Array(sampleModels.filter { values.bool("unavailable") || $0.info.availability.isSelectable }.prefix(Int(values.number("count"))))252 }253254 private static var glassModelPicker: ComponentDescriptor {255 ComponentDescriptor(256 "glass-model-picker",257 fields: [258 .text("title", "Title", default: "", maxLength: 40),259 .choice("selection", "Selected model", options: [.init("none", "None")] + sampleModels.filter(\.info.availability.isSelectable).map { .init($0.info.id, $0.info.name) }, default: "sample-nano"),260 .choice("style", "Style", options: [.init("list", "List"), .init("menu", "Menu")]),261 .number("count", "Models", in: 0...5, default: 4),262 .toggle("unavailable", "Include unavailable models", default: true),263 ],264 variants: [265 ComponentVariant("menu", "Menu", ["style": .choice("menu"), "selection": .choice("sample-large")]),266 ComponentVariant("none", "No selection", ["selection": .choice("none"), "title": .text("Choose a sample model")]),267 ComponentVariant("available", "Available only", ["unavailable": .bool(false), "selection": .choice("sample-large")]),268 ComponentVariant("empty", "Empty list", ["count": .number(0), "selection": .choice("none")]),269 ],270 isComposable: true,271 prefersStage: false,272 preview: { values in273 AISampleLabelled {274 AIPreviewState(values.choice("selection") == "none" ? String?.none : values.choice("selection")) { selection in275 GlassModelPicker(276 values.text("title").isEmpty ? nil : LocalizedStringKey(values.text("title")),277 models: models(values).map(\.info),278 selection: selection,279 style: values.choice("style") == "menu" ? .menu : .list280 )281 }282 .id(values)283 }284 },285 snippet: { values in286 let rows = models(values).map {287 " GlassModelInfo(id: \(SwiftLiteral.string($0.info.id)), name: \(SwiftLiteral.string($0.info.name)), provider: \(SwiftLiteral.string($0.info.provider)),\($0.capabilities == "[.text]" ? "" : " capabilities: \($0.capabilities),") availability: \($0.availability)),"288 }289 var arguments: [String] = []290 if !values.text("title").isEmpty { arguments.append(SwiftLiteral.string(values.text("title"))) }291 arguments.append("models: " + (rows.isEmpty ? "[]" : "[\n\(rows.joined(separator: "\n"))\n]"))292 arguments.append("selection: .constant(\(values.choice("selection") == "none" ? "nil" : SwiftLiteral.string(values.choice("selection"))))")293 if values.choice("style") != "menu" { arguments.append("style: .list") }294 return "GlassModelPicker(\(arguments.joined(separator: ", ")))"295 }296 )297 }298299 // MARK: Agent panel300301 private static let sampleSteps: [(title: String, detail: String?)] = [302 ("Collect the site notes", "12 notes found"), ("Group by topic", "Topic 3 of 5"), ("Write the digest", nil), ("Send for review", nil),303 ]304305 /// The status of step `index` of a task with `status`: the second step (or the only one) is the current one.306 private static func stepStatus(task status: GlassAgentStatus, index: Int, count: Int) -> GlassAgentStatus {307 let current = min(1, count - 1)308 switch status {309 case .pending: return .pending310 case .succeeded: return .succeeded311 case .running, .failed: return index < current ? .succeeded : (index == current ? status : .pending)312 case .cancelled: return index < current ? .succeeded : .cancelled313 }314 }315316 private static func sampleTask(_ values: InspectorValues) -> GlassAgentTask {317 let status = GlassAgentStatus(rawValue: values.choice("status")) ?? .running318 let count = Int(values.number("steps"))319 return GlassAgentTask(320 id: "t1",321 title: values.text("title"),322 status: status,323 steps: sampleSteps.prefix(count).enumerated().map { index, step in324 GlassAgentStep(id: "s\(index + 1)", title: step.title, status: stepStatus(task: status, index: index, count: count), detail: step.detail)325 },326 errorMessage: values.text("error").isEmpty ? nil : values.text("error")327 )328 }329330 private static var glassAgentPanel: ComponentDescriptor {331 ComponentDescriptor(332 "glass-agent-panel",333 fields: [334 .text("title", "Task title", default: "Prepare the weekly site digest", maxLength: 80),335 .choice("status", "Task status", options: [336 .init("pending", "Pending"), .init("running", "Running"), .init("succeeded", "Succeeded"),337 .init("failed", "Failed"), .init("cancelled", "Cancelled"),338 ], default: "running"),339 .number("steps", "Steps", in: 0...4, default: 4),340 .text("error", "Error message", default: "", maxLength: 120),341 .toggle("cancel", "Cancel button", default: true),342 ],343 variants: [344 ComponentVariant("failed", "Failed", ["status": .choice("failed"), "title": .text("Rename the survey files"), "steps": .number(3), "error": .text("A file with this name already exists.")]),345 ComponentVariant("succeeded", "Succeeded", ["status": .choice("succeeded"), "steps": .number(2)]),346 ComponentVariant("queued", "Queued", ["status": .choice("pending"), "steps": .number(0), "title": .text("Export the drawings as PDF")]),347 ComponentVariant("cancelled", "Cancelled", ["status": .choice("cancelled")]),348 ],349 isComposable: true,350 prefersStage: false,351 preview: { values in352 AISampleLabelled {353 AIPreviewState([sampleTask(values)]) { tasks in354 // Nothing runs: "Cancel" only edits the sample values.355 GlassAgentPanel(tasks: tasks.wrappedValue, onCancel: cancelAction(values, tasks: tasks))356 }357 .id(values)358 }359 },360 snippet: { values in361 let task = sampleTask(values)362 let steps = task.steps.map { step in363 var arguments = ["id: \(SwiftLiteral.string(step.id))", "title: \(SwiftLiteral.string(step.title))"]364 if step.status != .pending { arguments.append("status: .\(step.status.rawValue)") }365 if let detail = step.detail { arguments.append("detail: \(SwiftLiteral.string(detail))") }366 return " GlassAgentStep(\(arguments.joined(separator: ", "))),"367 }368 var arguments = ["id: \"t1\"", "title: \(SwiftLiteral.string(task.title))"]369 if task.status != .pending { arguments.append("status: .\(task.status.rawValue)") }370 if !steps.isEmpty { arguments.append("steps: [\n\(steps.joined(separator: "\n"))\n ]") }371 if let error = task.errorMessage { arguments.append("errorMessage: \(SwiftLiteral.string(error))") }372 var code = "GlassAgentPanel(tasks: [\n GlassAgentTask(\(arguments.joined(separator: ", "))),\n])"373 if values.bool("cancel") { code += " { task in\n // cancel the task\n}" }374 return code375 }376 )377 }378379 private static func cancelAction(_ values: InspectorValues, tasks: Binding<[GlassAgentTask]>) -> (@MainActor (GlassAgentTask) -> Void)? {380 guard values.bool("cancel") else { return nil }381 return { task in382 tasks.wrappedValue = tasks.wrappedValue.map { cancelled($0, id: task.id) }383 }384 }385386 private static func cancelled(_ task: GlassAgentTask, id: String) -> GlassAgentTask {387 guard task.id == id else { return task }388 var copy = task389 copy.status = .cancelled390 copy.steps = copy.steps.map { step in391 var step = step392 if !step.status.isTerminal { step.status = .cancelled }393 return step394 }395 return copy396 }397}398