SPB Git

Repository Public MIT

GlassAgentPanel.swift 18.0 KB 436 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassAI/AI/GlassAgentPanel.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 SPGlassEffects4647/// Status of an agent task or of one of its steps.48public enum GlassAgentStatus: String, CaseIterable, Sendable {49    case pending, running, succeeded, failed, cancelled5051    public var labelKey: GlassL10n.Key {52        switch self {53        case .pending: .statusPending54        case .running: .statusRunning55        case .succeeded: .statusSucceeded56        case .failed: .statusFailed57        case .cancelled: .statusCancelled58        }59    }6061    /// The localised status word, always shown next to the symbol.62    public var label: String { GlassL10n.string(labelKey) }6364    public var symbolName: String {65        switch self {66        case .pending: "circle.dotted"67        case .running: "arrow.triangle.2.circlepath"68        case .succeeded: "checkmark.circle.fill"69        case .failed: "xmark.octagon.fill"70        case .cancelled: "minus.circle"71        }72    }7374    public var colorToken: GlassColorToken {75        switch self {76        case .pending, .cancelled: .textSecondary77        case .running: .primary78        case .succeeded: .success79        case .failed: .destructive80        }81    }8283    /// Finished one way or another: nothing more will happen.84    public var isTerminal: Bool {85        self == .succeeded || self == .failed || self == .cancelled86    }87}8889/// One observable step of an agent task.90public struct GlassAgentStep: Identifiable, Hashable, Sendable {91    public let id: String92    public var title: String93    public var status: GlassAgentStatus94    /// What the step did or is doing, in the host's words ("Read 3 files").95    public var detail: String?96    /// Why the step failed.97    public var errorMessage: String?9899    public init(id: String, title: String, status: GlassAgentStatus = .pending, detail: String? = nil, errorMessage: String? = nil) {100        self.id = id101        self.title = title102        self.status = status103        self.detail = detail104        self.errorMessage = errorMessage105    }106}107108/// A task run by an agent of the host application.109public struct GlassAgentTask: Identifiable, Hashable, Sendable {110    public let id: String111    public var title: String112    public var status: GlassAgentStatus113    public var steps: [GlassAgentStep]114    /// Why the task failed, when the failure is not tied to one step.115    public var errorMessage: String?116117    public init(id: String, title: String, status: GlassAgentStatus = .pending, steps: [GlassAgentStep] = [], errorMessage: String? = nil) {118        self.id = id119        self.title = title120        self.status = status121        self.steps = steps122        self.errorMessage = errorMessage123    }124125    public var progress: GlassAgentProgress { GlassAgentProgress(steps: steps) }126127    /// A task can be cancelled while it is pending or running.128    public var isCancellable: Bool { !status.isTerminal }129}130131/// Progress of a task: steps that succeeded out of all steps.132public struct GlassAgentProgress: Equatable, Sendable {133    public let completed: Int134    public let total: Int135136    public init(completed: Int, total: Int) {137        self.total = max(total, 0)138        self.completed = min(max(completed, 0), self.total)139    }140141    public init(steps: [GlassAgentStep]) {142        self.init(completed: steps.filter { $0.status == .succeeded }.count, total: steps.count)143    }144145    /// 0…1; 0 when there is no step.146    public var fraction: Double {147        total > 0 ? Double(completed) / Double(total) : 0148    }149150    /// "2 of 5 steps completed".151    public var summary: String {152        GlassL10n.string(.stepsCompleted, completed, total)153    }154}155156/// Tasks of an agent with their steps, status, progress and errors.157///158/// ```swift159/// GlassAgentPanel(tasks: agent.tasks) { task in160///     agent.cancel(task.id)161/// }162/// ```163///164/// The panel displays value types the host updates; it runs nothing. Each task is a card: a status tile, the165/// title, the status in words, a progress bar, and the steps on a rail whose nodes show each step's state.166/// Every status is a symbol and a word, never colour alone. The steps can be folded; they start open for167/// running and failed tasks. A "Cancel" button is shown for pending and running tasks when `onCancel` is given.168public struct GlassAgentPanel: View {169    @GlassThemed private var theme170    @GlassAccessibility private var accessibility171    private let tasks: [GlassAgentTask]172    private let externalExpansion: Binding<Set<GlassAgentTask.ID>>?173    private let onCancel: (@MainActor (GlassAgentTask) -> Void)?174    @State private var internalExpansion: Set<GlassAgentTask.ID>175176    /// - Parameters:177    ///   - tasks: the tasks, in display order.178    ///   - expandedTaskIDs: controls which step lists are open. When `nil` the panel keeps the state itself179    ///     and starts with the running and the failed tasks open.180    ///   - onCancel: called by a task's "Cancel" button.181    public init(182        tasks: [GlassAgentTask],183        expandedTaskIDs: Binding<Set<GlassAgentTask.ID>>? = nil,184        onCancel: (@MainActor (GlassAgentTask) -> Void)? = nil185    ) {186        self.tasks = tasks187        externalExpansion = expandedTaskIDs188        self.onCancel = onCancel189        _internalExpansion = State(initialValue: Set(tasks.filter { $0.status == .running || $0.status == .failed }.map(\.id)))190    }191192    public var body: some View {193        if tasks.isEmpty {194            Label(GlassL10n.string(.noData), systemImage: "tray")195                .font(theme.font(.callout))196                .foregroundStyle(theme.color(.textSecondary))197        } else {198            VStack(alignment: .leading, spacing: theme.spacing.sm) {199                ForEach(tasks) { task in200                    card(task)201                }202            }203        }204    }205206    private func isExpanded(_ id: GlassAgentTask.ID) -> Binding<Bool> {207        let expansion = externalExpansion ?? $internalExpansion208        return Binding(209            get: { expansion.wrappedValue.contains(id) },210            set: { isOn in211                if isOn { expansion.wrappedValue.insert(id) } else { expansion.wrappedValue.remove(id) }212            }213        )214    }215216    private func tint(_ status: GlassAgentStatus) -> Color {217        theme.color(status.colorToken)218    }219220    // MARK: Card221222    private func card(_ task: GlassAgentTask) -> some View {223        let progress = task.progress224        let expanded = isExpanded(task.id)225        return VStack(alignment: .leading, spacing: theme.spacing.sm) {226            header(task)227            if progress.total > 0 {228                progressBar(task, progress: progress)229            }230            if let message = task.errorMessage, !message.isEmpty {231                errorBlock(message)232            }233            if progress.total > 0 {234                Rectangle()235                    .fill(theme.color(.separator))236                    .frame(height: 0.5)237                Button {238                    withAnimation(theme.animation(.fast, reduceMotion: accessibility.reduceMotion)) {239                        expanded.wrappedValue.toggle()240                    }241                } label: {242                    HStack(spacing: theme.spacing.xs) {243                        Text(progress.summary)244                            .font(theme.font(.caption).weight(.semibold))245                            .foregroundStyle(theme.color(.textSecondary))246                        Spacer(minLength: 0)247                        Image(systemName: "chevron.down")248                            .font(.system(size: 11, weight: .bold))249                            .foregroundStyle(theme.color(.textSecondary))250                            .rotationEffect(.degrees(expanded.wrappedValue ? 180 : 0))251                            .accessibilityHidden(true)252                    }253                    .contentShape(Rectangle())254                    .glassMinimumHitTarget()255                }256                .buttonStyle(.plain)257                .padding(.vertical, -theme.spacing.xs)258                .accessibilityValue(Text(GlassL10n.string(expanded.wrappedValue ? .expanded : .collapsed)))259                if expanded.wrappedValue {260                    VStack(alignment: .leading, spacing: 0) {261                        ForEach(Array(task.steps.enumerated()), id: \.element.id) { index, step in262                            stepRow(step, isLast: index == task.steps.count - 1)263                        }264                    }265                }266            }267        }268        .padding(theme.spacing.md)269        .frame(maxWidth: .infinity, alignment: .leading)270        .glassOpaqueSurface(in: theme.shape(\.large), elevated: true)271    }272273    private func header(_ task: GlassAgentTask) -> some View {274        HStack(alignment: .center, spacing: theme.spacing.sm) {275            HStack(alignment: .center, spacing: theme.spacing.sm) {276                Image(systemName: task.status.symbolName)277                    .font(.system(size: 17, weight: .semibold))278                    .foregroundStyle(tint(task.status))279                    .symbolEffect(.pulse, isActive: task.status == .running && !accessibility.reduceMotion)280                    .frame(width: 40, height: 40)281                    .background(tint(task.status).opacity(theme.isDark ? 0.24 : 0.13), in: RoundedRectangle(cornerRadius: 11, style: .continuous))282                    .accessibilityHidden(true)283                VStack(alignment: .leading, spacing: 2) {284                    Text(verbatim: task.title)285                        .font(theme.font(.headline))286                        .foregroundStyle(theme.color(.textPrimary))287                        .multilineTextAlignment(.leading)288                    Text(task.status.label)289                        .font(theme.font(.caption).weight(.semibold))290                        .foregroundStyle(task.status == .pending || task.status == .cancelled ? theme.color(.textSecondary) : tint(task.status))291                }292            }293            .accessibilityElement(children: .combine)294            .accessibilityAddTraits(task.status == .running ? .updatesFrequently : [])295            Spacer(minLength: theme.spacing.xs)296            if let onCancel, task.isCancellable {297                Button(role: .cancel) {298                    onCancel(task)299                } label: {300                    Text(GlassL10n.string(.cancel))301                        .font(theme.font(.callout).weight(.medium))302                        .foregroundStyle(theme.color(.textPrimary))303                        .padding(.horizontal, theme.spacing.sm)304                        .frame(minHeight: 32)305                        .background(theme.color(.textSecondary).opacity(0.14), in: Capsule())306                        .glassMinimumHitTarget()307                        .contentShape(Rectangle())308                }309                .buttonStyle(.plain)310                .accessibilityLabel(Text(verbatim: "\(GlassL10n.string(.cancel)), \(task.title)"))311            }312        }313    }314315    private func progressBar(_ task: GlassAgentTask, progress: GlassAgentProgress) -> some View {316        let color: Color = switch task.status {317        case .failed: theme.color(.destructive)318        case .succeeded: theme.color(.success)319        case .cancelled, .pending: theme.color(.textSecondary)320        case .running: theme.color(.primary)321        }322        return HStack(spacing: theme.spacing.sm) {323            GeometryReader { proxy in324                ZStack(alignment: .leading) {325                    Capsule().fill(theme.color(.textSecondary).opacity(0.18))326                    Capsule()327                        .fill(color)328                        .frame(width: max(proxy.size.width * progress.fraction, progress.fraction > 0 ? 6 : 0))329                }330            }331            .frame(height: 6)332            Text(progress.fraction.formatted(.percent.precision(.fractionLength(0))))333                .font(theme.font(.caption).monospacedDigit().weight(.semibold))334                .foregroundStyle(theme.color(.textSecondary))335        }336        .accessibilityElement(children: .ignore)337        .accessibilityLabel(Text(verbatim: task.title))338        .accessibilityValue(Text(progress.summary))339    }340341    // MARK: Steps342343    private func stepRow(_ step: GlassAgentStep, isLast: Bool) -> some View {344        HStack(alignment: .top, spacing: theme.spacing.sm) {345            VStack(spacing: 2) {346                node(step.status)347                if !isLast {348                    Capsule()349                        .fill(step.status == .succeeded ? theme.color(.success).opacity(0.55) : theme.color(.separator))350                        .frame(width: 2)351                        .frame(maxHeight: .infinity)352                }353            }354            .frame(width: 22)355            .accessibilityHidden(true)356            VStack(alignment: .leading, spacing: 2) {357                Text(verbatim: step.title)358                    .font(theme.font(.callout).weight(step.status == .running ? .semibold : .medium))359                    .foregroundStyle(theme.color(step.status == .pending ? .textSecondary : .textPrimary))360                Text(verbatim: stepCaption(step))361                    .font(theme.font(.caption))362                    .foregroundStyle(theme.color(.textSecondary))363                if let message = step.errorMessage, !message.isEmpty {364                    errorBlock(message)365                        .padding(.top, theme.spacing.xxs)366                }367            }368            .padding(.bottom, isLast ? 0 : theme.spacing.sm)369            .frame(maxWidth: .infinity, alignment: .leading)370        }371        .fixedSize(horizontal: false, vertical: true)372        .accessibilityElement(children: .combine)373        .accessibilityAddTraits(step.status == .running ? .updatesFrequently : [])374    }375376    /// The status word, then what the step did or is doing.377    private func stepCaption(_ step: GlassAgentStep) -> String {378        let detail = step.detail?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""379        return detail.isEmpty ? step.status.label : "\(step.status.label) · \(detail)"380    }381382    /// The node of a step on the rail: its shape and symbol tell the state, the colour only reinforces it.383    @ViewBuilder384    private func node(_ status: GlassAgentStatus) -> some View {385        let side: CGFloat = 22386        switch status {387        case .succeeded:388            Image(systemName: "checkmark")389                .font(.system(size: 10, weight: .heavy))390                .foregroundStyle(theme.onColor(.success))391                .frame(width: side, height: side)392                .background(theme.color(.success), in: Circle())393        case .failed:394            Image(systemName: "xmark")395                .font(.system(size: 10, weight: .heavy))396                .foregroundStyle(theme.onColor(.destructive))397                .frame(width: side, height: side)398                .background(theme.color(.destructive), in: Circle())399        case .running:400            Circle()401                .fill(theme.color(.primary))402                .frame(width: 8, height: 8)403                .frame(width: side, height: side)404                .background(theme.color(.primary).opacity(theme.isDark ? 0.3 : 0.16), in: Circle())405                .overlay(Circle().strokeBorder(theme.color(.primary), lineWidth: 2))406        case .cancelled:407            Image(systemName: "minus")408                .font(.system(size: 10, weight: .heavy))409                .foregroundStyle(theme.color(.textSecondary))410                .frame(width: side, height: side)411                .overlay(Circle().strokeBorder(theme.color(.textSecondary).opacity(0.6), lineWidth: 1.5))412        case .pending:413            Circle()414                .strokeBorder(theme.color(.textSecondary).opacity(0.5), style: StrokeStyle(lineWidth: 1.5, dash: [3, 3]))415                .frame(width: side, height: side)416        }417    }418419    private func errorBlock(_ message: String) -> some View {420        HStack(alignment: .firstTextBaseline, spacing: theme.spacing.xs) {421            Image(systemName: "exclamationmark.triangle.fill")422                .font(.system(size: 12, weight: .semibold))423            Text(verbatim: message)424                .font(theme.font(.caption).weight(.medium))425                .multilineTextAlignment(.leading)426        }427        .foregroundStyle(theme.color(.destructive))428        .padding(.horizontal, theme.spacing.sm)429        .padding(.vertical, theme.spacing.xs)430        .frame(maxWidth: .infinity, alignment: .leading)431        .background(theme.color(.destructive).opacity(theme.isDark ? 0.2 : 0.1), in: RoundedRectangle(cornerRadius: 10, style: .continuous))432        .accessibilityElement(children: .ignore)433        .accessibilityLabel(Text(verbatim: "\(GlassL10n.string(.error)): \(message)"))434    }435}436
Files main
Menu

Theme