SPB Git

Repository Public MIT

AgentsScreen.swift 26.7 KB 506 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraUI/Sources/Agents/AgentsScreen.swift10// Module           : Agents11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2214//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import SwiftUI89import UniformTypeIdentifiers90import AstraCore91import AstraAgents92import AstraDesign93import AstraPersistence9495enum AgentRoute: Hashable {96    case run(String)97    case edit(String)98    case create99    /// Runs of one profile, or of every profile when nil.100    case history(String?)101    case audit(String)102    case knowledge103}104105/// The Agents tab: profiles, the run in progress, interrupted runs that can be resumed, and the way into Knowledge.106struct AgentsScreen: View {107    @Environment(AppModel.self) private var app108    @State private var path: [AgentRoute] = []109    @State private var showInfo = false110111    var body: some View {112        let agents = AgentsController.shared(for: app)113        NavigationStack(path: $path) {114            AgentsHome(agents: agents, path: $path, showInfo: $showInfo)115                .navigationDestination(for: AgentRoute.self) { route in116                    switch route {117                    case .run(let id): AgentRunScreen(agents: agents, profileID: id, path: $path)118                    case .edit(let id): AgentEditorScreen(agents: agents, existingID: id, path: $path)119                    case .create: AgentEditorScreen(agents: agents, existingID: nil, path: $path)120                    case .history(let id): AgentHistoryScreen(agents: agents, profileID: id, path: $path)121                    case .audit(let id): AgentAuditScreen(agents: agents, runID: id, path: $path)122                    case .knowledge: KnowledgeScreen()123                    }124                }125        }126        .modifier(AgentRunPresentations(agents: agents))127        .sheet(isPresented: $showInfo) { AgentInfoSheet() }128    }129}130131/// The two system presentations a run can ask for from anywhere in the tab: the approval question and the save dialog.132struct AgentRunPresentations: ViewModifier {133    let agents: AgentsController134135    func body(content: Content) -> some View {136        @Bindable var files = agents.files137        // Read here so this body is re-evaluated when a question arrives or is answered.138        let pending = agents.approvals.pending139        content140            .sheet(item: Binding(get: { pending }, set: { value in141                // Swiping the sheet away is a denial of that question, and of no later one.142                if value == nil, let pending { agents.approvals.resolve(.deny(reason: nil), requestID: pending.id) }143            })) { request in144                AgentApprovalSheet(request: request, resolve: { agents.approvals.resolve($0, requestID: request.id) }, stopRun: { agents.stopActiveRun() })145            }146            .fileExporter(isPresented: $files.isExporterPresented, document: agents.files.export?.document, contentTypes: [.data],147                          defaultFilename: agents.files.export?.fileName) { result in148                switch result {149                case .success(let url): agents.files.finishExport(.success(.saved(name: url.lastPathComponent)))150                case .failure: agents.files.finishExport(.failure(ToolError("The file could not be saved to the place you chose.")))151                }152            } onCancellation: {153                agents.files.finishExport(.success(.cancelled))154            }155    }156}157158struct AgentsHome: View {159    @Environment(AppModel.self) private var app160    let agents: AgentsController161    @Binding var path: [AgentRoute]162    @Binding var showInfo: Bool163    @State private var deleting: AgentProfile?164    @State private var didRunLaunchHook = false165166    var body: some View {167        Group {168            if !agents.isLoaded { ProgressView("Loading agents").frame(maxWidth: .infinity, maxHeight: .infinity) }169            else if agents.profiles.isEmpty && !app.library.hasAnyUsableModel && agents.recentRuns.isEmpty { noModelState }170            else { content }171        }172        .background(Starfield(density: 0.5))173        .navigationTitle("Agents")174        .toolbar {175            ToolbarItem(placement: .topBarLeading) {176                Button { showInfo = true } label: { Image(systemName: "info.circle") }177                    .accessibilityLabel("What agents can and cannot do").accessibilityIdentifier("agents-info")178            }179            ToolbarItemGroup(placement: .topBarTrailing) {180                Button { path.append(.knowledge) } label: { Image(systemName: "books.vertical") }181                    .accessibilityLabel("Knowledge").accessibilityIdentifier("agents-knowledge")182                Button { create() } label: { Image(systemName: "plus") }183                    .accessibilityLabel("New agent").accessibilityIdentifier("agent-new")184            }185        }186        .confirmationDialog("Delete “\(deleting?.name ?? "")”?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible) {187            Button("Delete agent", role: .destructive) { if let profile = deleting { perform { try await agents.delete(profile) } } }188            Button("Cancel", role: .cancel) {}189        } message: { Text("Its past runs stay in the history.") }190        .task {191            await agents.load()192            runLaunchHook()193        }194    }195196    private func perform(_ operation: @escaping @MainActor () async throws -> Void) {197        Task {198            do { try await operation() } catch { app.show(AstraError.wrap(error).message, .error) }199        }200    }201202    private func create() {203        guard agents.preferredModel() != nil else { app.show("Add a model in Models before creating an agent.", .error); return }204        path.append(.create)205    }206207    /// DEBUG only: `-ORIXScreen agents-knowledge | agents-editor | agents-run | agents-history | agents-info` opens that screen at launch.208    private func runLaunchHook() {209        #if DEBUG210        guard !didRunLaunchHook, path.isEmpty, let screen = app.options.screen else { return }211        didRunLaunchHook = true212        switch screen {213        case "agents-knowledge": path = [.knowledge]214        case "agents-editor": if let first = agents.profiles.first { path = [.edit(first.id)] }215        case "agents-run": if let first = agents.profiles.first { path = [.run(first.id)] }216        case "agents-history": path = [.history(nil)]217        case "agents-info": showInfo = true218        default: break219        }220        #endif221    }222223    private var noModelState: some View {224        EmptyStateView(symbol: "point.3.connected.trianglepath.dotted", title: "Agents need a model",225                       message: "An agent is a model working through a goal step by step with a small set of tools you allow. Download an on-device model or add a provider key first.") {226            Button("Open Models") { app.tab = .models }.buttonStyle(AstraPrimaryButtonStyle()).accessibilityIdentifier("agents-open-models")227        }228        .frame(maxWidth: .infinity, maxHeight: .infinity)229    }230231    private var content: some View {232        ScrollView {233            VStack(alignment: .leading, spacing: AstraSpace.xl) {234                if let error = agents.loadError {235                    NoticeCard(.error, title: "Agents could not be loaded", message: error, actionTitle: "Try again") { Task { await agents.load() } }236                }237                if let active = agents.activeSession { activeCard(active) }238                if !agents.resumable.isEmpty { resumableSection }239                profilesSection240                if !agents.recentRuns.isEmpty { recentSection }241                footer242            }243            .padding(.horizontal, AstraSpace.page).padding(.vertical, AstraSpace.lg)244        }245        .refreshable { await agents.load() }246    }247248    // MARK: Running and interrupted249250    private func activeCard(_ session: AgentRunSession) -> some View {251        Button { path.append(.run(session.profile.id)) } label: {252            AstraCard(tint: AstraColor.accentSoft) {253                HStack(spacing: AstraSpace.md) {254                    OrbitActivity(size: 28).accessibilityHidden(true)255                    VStack(alignment: .leading, spacing: AstraSpace.xs) {256                        Text("\(session.profile.name) is working").font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary)257                        Text(session.waitingForApproval ? "Waiting for your approval" : "Step \(max(1, session.step)) of at most \(session.profile.budgets.maxSteps)")258                            .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary)259                        Text(session.goal).font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary).lineLimit(2)260                    }261                    Spacer(minLength: 0)262                    Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(AstraColor.textTertiary).accessibilityHidden(true)263                }264            }265        }266        .buttonStyle(.plain)267        .accessibilityElement(children: .combine)268        .accessibilityHint("Opens the run")269        .accessibilityIdentifier("agent-active-run")270    }271272    private var resumableSection: some View {273        VStack(alignment: .leading, spacing: AstraSpace.md) {274            SectionTitle("Interrupted", detail: "The app closed during these runs")275            ForEach(agents.resumable) { item in276                AstraCard {277                    VStack(alignment: .leading, spacing: AstraSpace.md) {278                        VStack(alignment: .leading, spacing: AstraSpace.xs) {279                            Text(item.run.profileName).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary)280                            Text(item.run.goal).font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).lineLimit(3)281                            Text("Saved after step \(item.checkpoint.step) · \(AgentFormat.stamp(item.checkpoint.savedAt))")282                                .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary)283                            if item.profile == nil {284                                Text("This agent was deleted, so the run cannot continue.").font(AstraFont.caption).foregroundStyle(AstraColor.warning)285                            }286                        }287                        ViewThatFits(in: .horizontal) {288                            HStack(spacing: AstraSpace.sm) { resumeButtons(item) }289                            VStack(alignment: .leading, spacing: AstraSpace.sm) { resumeButtons(item) }290                        }291                    }292                }293            }294        }295    }296297    @ViewBuilder private func resumeButtons(_ item: AgentResumableRun) -> some View {298        if let profile = item.profile {299            Button {300                Task { if await agents.resume(item) { path.append(.run(profile.id)) } }301            } label: { Label("Resume", systemImage: "play.fill") }302                .buttonStyle(AstraSecondaryButtonStyle(compact: true))303                .disabled(agents.isStarting || agents.activeSession != nil)304                .accessibilityIdentifier("agent-resume")305        }306        Button { path.append(.audit(item.run.id)) } label: { Label("Audit trail", systemImage: "list.bullet.rectangle") }307            .buttonStyle(AstraSecondaryButtonStyle(compact: true))308        Button(role: .destructive) { Task { await agents.discard(item) } } label: { Label("Discard", systemImage: "xmark") }309            .buttonStyle(AstraSecondaryButtonStyle(compact: true))310            .accessibilityIdentifier("agent-discard")311    }312313    // MARK: Profiles314315    private var profilesSection: some View {316        VStack(alignment: .leading, spacing: AstraSpace.md) {317            SectionTitle("Your agents", detail: agents.profiles.isEmpty ? nil : "\(agents.profiles.count)")318            if agents.profiles.isEmpty {319                AstraCard {320                    VStack(alignment: .leading, spacing: AstraSpace.md) {321                        Text("No agent yet").font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary)322                        Text("Create one: pick a model, write its instructions and choose exactly which tools it may use.")323                            .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)324                        Button("New agent") { create() }.buttonStyle(AstraSecondaryButtonStyle()).accessibilityIdentifier("agent-new-empty")325                    }326                }327            }328            ForEach(agents.profiles) { profile in profileCard(profile) }329        }330    }331332    private func profileCard(_ profile: AgentProfile) -> some View {333        let info = app.library.info(for: profile.model)334        let unavailable = agents.blocker(for: profile) != nil335        let highest = AgentToolCatalog.all.filter { profile.allowedTools.contains($0.name) }.map(\.risk).max { ToolRisk.allCases.firstIndex(of: $0)! < ToolRisk.allCases.firstIndex(of: $1)! }336        return AstraCard(padding: 0) {337            HStack(alignment: .center, spacing: 0) {338                Button { path.append(.run(profile.id)) } label: {339                    HStack(alignment: .top, spacing: AstraSpace.md) {340                        ProviderLogo(ref: profile.model, vendor: info?.vendor, size: 38)341                        VStack(alignment: .leading, spacing: AstraSpace.xs) {342                            Text(profile.name).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary).multilineTextAlignment(.leading)343                            Text(app.library.displayName(for: profile.model)).font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).lineLimit(1)344                            FlowLayout(spacing: AstraSpace.xs) {345                                AstraBadge(profile.allowedTools.count == 1 ? "1 tool" : "\(profile.allowedTools.count) tools", symbol: "wrench.and.screwdriver")346                                if let highest { AstraBadge(highest.label, symbol: highest.symbol, tone: highest.tone) }347                                if unavailable { AstraBadge("Model unavailable", symbol: "exclamationmark.triangle", tone: .warning) }348                            }349                            .padding(.top, AstraSpace.xxs)350                        }351                        Spacer(minLength: 0)352                    }353                    .padding(.leading, AstraSpace.lg).padding(.vertical, AstraSpace.lg)354                    .contentShape(Rectangle())355                }356                .buttonStyle(.plain)357                .accessibilityElement(children: .combine)358                .accessibilityHint("Opens this agent")359                .accessibilityIdentifier("agent-profile-" + profile.name.lowercased().split(whereSeparator: { !$0.isLetter && !$0.isNumber }).joined(separator: "-"))360                Menu {361                    Button { path.append(.edit(profile.id)) } label: { Label("Edit", systemImage: "slider.horizontal.3") }362                    Button { perform { _ = try await agents.duplicate(profile) } } label: { Label("Duplicate", systemImage: "plus.square.on.square") }363                    Button { path.append(.history(profile.id)) } label: { Label("Run history", systemImage: "clock.arrow.circlepath") }364                    Button(role: .destructive) { deleting = profile } label: { Label("Delete", systemImage: "trash") }365                } label: {366                    Image(systemName: "ellipsis.circle").font(.title3).foregroundStyle(AstraColor.textSecondary)367                        .frame(width: AstraSpace.hit + AstraSpace.sm, height: AstraSpace.hit + AstraSpace.sm).contentShape(Rectangle())368                }369                .accessibilityLabel("Actions for \(profile.name)")370                .accessibilityIdentifier("agent-profile-menu")371            }372        }373    }374375    // MARK: Recent runs376377    private var recentSection: some View {378        VStack(alignment: .leading, spacing: AstraSpace.md) {379            SectionTitle("Recent runs")380            AstraCard(padding: 0) {381                VStack(spacing: 0) {382                    ForEach(Array(agents.recentRuns.enumerated()), id: \.element.id) { index, run in383                        if index > 0 { Divider().overlay(AstraColor.stroke).padding(.leading, AstraSpace.lg) }384                        Button { path.append(.audit(run.id)) } label: { AgentRunRow(run: run).padding(AstraSpace.lg).contentShape(Rectangle()) }385                            .buttonStyle(.plain)386                    }387                    Divider().overlay(AstraColor.stroke)388                    Button { path.append(.history(nil)) } label: {389                        HStack {390                            Text("All runs").font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.violet)391                            Spacer()392                            Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(AstraColor.textTertiary).accessibilityHidden(true)393                        }394                        .padding(.horizontal, AstraSpace.lg).frame(minHeight: AstraSpace.hit + AstraSpace.xs).contentShape(Rectangle())395                    }396                    .buttonStyle(.plain)397                    .accessibilityIdentifier("agents-all-runs")398                }399            }400        }401    }402403    private var footer: some View {404        VStack(alignment: .leading, spacing: AstraSpace.sm) {405            Text("An agent only has the tools you tick in its profile. Anything that reads your data, writes a file or reaches a website asks you first, and every run stops at the limits you set.")406                .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary).fixedSize(horizontal: false, vertical: true)407            Button("What agents can and cannot do on iPhone") { showInfo = true }408                .font(AstraFont.footnote.weight(.semibold)).foregroundStyle(AstraColor.violet)409                .frame(minHeight: AstraSpace.hit, alignment: .leading)410                .accessibilityIdentifier("agents-info-link")411        }412    }413}414415/// One stored run in a list: status, goal, when, and the totals that were really recorded.416struct AgentRunRow: View {417    let run: AgentRunRecord418    var showsProfile = true419420    var body: some View {421        VStack(alignment: .leading, spacing: AstraSpace.xs) {422            HStack(alignment: .firstTextBaseline, spacing: AstraSpace.sm) {423                AstraBadge(run.status.label, symbol: run.status.symbol, tone: run.status.tone)424                if showsProfile { Text(run.profileName).font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).lineLimit(1) }425                Spacer(minLength: 0)426            }427            Text(run.goal).font(AstraFont.subheadline).foregroundStyle(AstraColor.textPrimary).lineLimit(2).multilineTextAlignment(.leading)428            Text(detail).font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary)429        }430        .frame(maxWidth: .infinity, alignment: .leading)431        .accessibilityElement(children: .combine)432    }433434    private var detail: String {435        var parts = [AgentFormat.stamp(run.startedAt)]436        parts.append(run.toolCallCount == 1 ? "1 tool call" : "\(run.toolCallCount) tool calls")437        if let tokens = AgentFormat.tokens(run.usage) { parts.append("\(tokens) tokens") }438        return parts.joined(separator: " · ")439    }440}441442/// The honest summary of what an agent is on this platform.443struct AgentInfoSheet: View {444    @Environment(\.dismiss) private var dismiss445446    private let can: [(String, String)] = [447        ("list.bullet.clipboard", "Work through a goal in several steps, keep a visible plan and stop at the limits you set: steps, tool calls, tokens, cost and time."),448        ("doc.text.magnifyingglass", "Search the documents you imported in Knowledge and read the files you share with a run."),449        ("plus.forwardslash.minus", "Compute exactly with the calculator, transform tables, convert units, extract patterns and work with dates."),450        ("globe", "Download a public https page, only when its profile includes web access and you approve the website."),451        ("square.and.arrow.down", "Propose a new file that you save yourself through the system's save dialog."),452    ]453    private let cannot: [(String, String)] = [454        ("iphone.slash", "Control other apps, tap or type on your behalf, read your screen, messages, photos or contacts, or change settings."),455        ("moon.zzz", "Keep working in the background. iOS suspends the app when you leave it; a run interrupted by the app closing can be resumed from its last finished step."),456        ("folder.badge.questionmark", "Browse your files. It sees only the files you hand to a run, and loses access when the run ends."),457        ("terminal", "Run code, open a shell or install anything."),458        ("lock.shield", "Approve its own actions. Only you can allow a call, and nothing a model writes can widen what its profile permits."),459    ]460461    var body: some View {462        NavigationStack {463            ScrollView {464                VStack(alignment: .leading, spacing: AstraSpace.xl) {465                    section("What an agent can do", items: can, tint: AstraColor.success)466                    section("What it cannot do", items: cannot, tint: AstraColor.danger)467                    VStack(alignment: .leading, spacing: AstraSpace.md) {468                        SectionTitle("Why there is no code execution")469                        AstraCard {470                            Text(CodeExecutionPolicy.explanation).font(AstraFont.callout).foregroundStyle(AstraColor.textSecondary)471                                .fixedSize(horizontal: false, vertical: true)472                        }473                    }474                    VStack(alignment: .leading, spacing: AstraSpace.md) {475                        SectionTitle("Where your data goes")476                        AstraCard {477                            Text("With an on-device model, the goal, the tool results and the answer stay on this iPhone. With a cloud model, everything the agent reads (document passages, file contents, web pages) is sent to that provider as part of the conversation, under its terms. Text returned by tools is treated as data: instructions hidden in a document or a page are flagged, never obeyed by the app, but a model can still be misled, which is why sensitive calls ask you first.")478                                .font(AstraFont.callout).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)479                        }480                    }481                }482                .padding(.horizontal, AstraSpace.page).padding(.vertical, AstraSpace.lg)483            }484            .background(AstraColor.background)485            .navigationTitle("Agents on iPhone").navigationBarTitleDisplayMode(.inline)486            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() }.accessibilityIdentifier("agents-info-done") } }487        }488    }489490    private func section(_ title: String, items: [(String, String)], tint: Color) -> some View {491        VStack(alignment: .leading, spacing: AstraSpace.md) {492            SectionTitle(title)493            AstraCard {494                VStack(alignment: .leading, spacing: AstraSpace.md) {495                    ForEach(items, id: \.1) { symbol, text in496                        HStack(alignment: .top, spacing: AstraSpace.md) {497                            Image(systemName: symbol).font(.body.weight(.medium)).foregroundStyle(tint).frame(width: 26).accessibilityHidden(true)498                            Text(text).font(AstraFont.callout).foregroundStyle(AstraColor.textPrimary).fixedSize(horizontal: false, vertical: true)499                        }500                    }501                }502            }503        }504    }505}506
Files main
Menu

Theme