SPB Git

Repository Public MIT

AgentRunScreen.swift 39.5 KB 751 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/AgentRunScreen.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 AstraPersistence9495extension AgentOutcome {96    var headline: String {97        switch self {98        case .completed: "Completed"99        case .stopped: "Stopped"100        case .budgetExceeded(let kind): "Stopped at the \(kind.label)"101        case .failed: "Failed"102        case .cycleDetected: "Stopped: repeated calls"103        }104    }105106    func explanation(steps: Int, elapsed: TimeInterval) -> String {107        switch self {108        case .completed: "Finished in \(steps == 1 ? "1 step" : "\(steps) steps"), \(AgentFormat.clock(elapsed))."109        case .stopped: "You stopped this run. Nothing else was called after that."110        case .budgetExceeded: "The run reached a limit set in this agent's profile. Raise it there to let the agent go further."111        case .failed(let message): message112        case .cycleDetected(let message): message.prefix(1).uppercased() + message.dropFirst()113        }114    }115}116117/// One agent: the goal, Start, and the live activity of its run with a Stop that always works.118struct AgentRunScreen: View {119    @Environment(AppModel.self) private var app120    let agents: AgentsController121    let profileID: String122    @Binding var path: [AgentRoute]123124    @State private var goal = ""125    @State private var showImporter = false126    @State private var didRunLaunchHook = false127    @FocusState private var goalFocused: Bool128129    private var session: AgentRunSession? { agents.session?.profile.id == profileID ? agents.session : nil }130    private var otherActive: AgentRunSession? {131        guard let active = agents.activeSession, active.profile.id != profileID else { return nil }132        return active133    }134135    var body: some View {136        Group {137            if let profile = session?.profile ?? agents.profile(id: profileID) { screen(profile) }138            else {139                EmptyStateView(symbol: "questionmark.folder", title: "This agent no longer exists", message: "It was deleted. Its past runs are still in the run history.")140                    .frame(maxWidth: .infinity, maxHeight: .infinity)141            }142        }143        .background(Starfield(density: 0.35))144        .navigationBarTitleDisplayMode(.inline)145    }146147    private func screen(_ profile: AgentProfile) -> some View {148        ScrollView {149            VStack(alignment: .leading, spacing: AstraSpace.lg) {150                AgentProfileSummary(profile: agents.profile(id: profileID) ?? profile)151                if let session { running(session) } else { compose(profile) }152            }153            .padding(.horizontal, AstraSpace.page).padding(.vertical, AstraSpace.lg)154        }155        .defaultScrollAnchor(session?.isRunning == true ? .bottom : nil, for: .sizeChanges)156        .scrollDismissesKeyboard(.interactively)157        .navigationTitle(profile.name)158        .toolbar {159            ToolbarItem(placement: .topBarTrailing) {160                Menu {161                    Button { path.append(.edit(profileID)) } label: { Label("Edit agent", systemImage: "slider.horizontal.3") }162                        .disabled(agents.profile(id: profileID) == nil)163                    Button { path.append(.history(profileID)) } label: { Label("Run history", systemImage: "clock.arrow.circlepath") }164                } label: { Image(systemName: "ellipsis.circle") }165                .accessibilityLabel("Agent options").accessibilityIdentifier("agent-run-menu")166            }167        }168        .safeAreaInset(edge: .bottom) { bottomBar(profile) }169        .fileImporter(isPresented: $showImporter, allowedContentTypes: [.text, .pdf, .json, .xml, .commaSeparatedText, .sourceCode], allowsMultipleSelection: true) { result in170            switch result {171            case .success(let urls):172                Task {173                    let problems = await agents.files.grant(urls)174                    if let first = problems.first { app.show(first, .error) }175                }176            case .failure(let error): app.show(AstraError.wrap(error).message, .error)177            }178        }179        .task {180            agents.prepareFiles(for: profileID)181            await runLaunchHook(profile)182        }183    }184185    /// DEBUG only: `-ORIXAgentGoal "<text>"` starts a run with that goal as soon as the screen opens.186    private func runLaunchHook(_ profile: AgentProfile) async {187        #if DEBUG188        guard !didRunLaunchHook, session == nil, let preset = UserDefaults.standard.string(forKey: "ORIXAgentGoal"), !preset.isEmpty else { return }189        didRunLaunchHook = true190        goal = preset191        await agents.start(profile: profile, goal: preset)192        #endif193    }194195    // MARK: Before the run196197    @ViewBuilder private func compose(_ profile: AgentProfile) -> some View {198        if let other = otherActive {199            NoticeCard(.info, title: "\(other.profile.name) is still running", message: "One agent runs at a time. Open it to follow or stop it.",200                       actionTitle: "Open that run") { path.append(.run(other.profile.id)) }201        }202        if let blocker = agents.blocker(for: profile) {203            NoticeCard(.error, title: blocker.title, message: blocker.message, actionTitle: "Open Models") { app.tab = .models }204        }205        VStack(alignment: .leading, spacing: AstraSpace.sm) {206            SectionTitle("Goal")207            TextField("What should this agent do?", text: $goal, axis: .vertical)208                .lineLimit(3...10)209                .font(AstraFont.body)210                .focused($goalFocused)211                .padding(AstraSpace.md)212                .background(AstraColor.surface, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))213                .overlay(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous).strokeBorder(goalFocused ? AstraColor.violet : AstraColor.stroke, lineWidth: 1))214                .accessibilityLabel("Goal")215                .accessibilityIdentifier("agent-goal")216        }217        if profile.allowedTools.contains("read_file") { filesCard }218        Text(limitsLine(profile)).font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary).fixedSize(horizontal: false, vertical: true)219    }220221    private func limitsLine(_ profile: AgentProfile) -> String {222        let budgets = profile.budgets223        var parts = [budgets.maxSteps == 1 ? "1 step" : "\(budgets.maxSteps) steps", budgets.maxToolCalls == 1 ? "1 tool call" : "\(budgets.maxToolCalls) tool calls"]224        if let tokens = budgets.maxTotalTokens { parts.append("\(AgentFormat.count(tokens)) tokens") }225        if let cost = budgets.maxTotalCostUSD { parts.append(CostEstimate.format(cost)) }226        if let time = budgets.wallClockLimit { parts.append(AgentFormat.minutes(time)) }227        return "The run stops by itself at the first of: " + parts.joined(separator: ", ") + ". You can stop it at any moment."228    }229230    private var filesCard: some View {231        AstraCard {232            VStack(alignment: .leading, spacing: AstraSpace.sm) {233                Text("Files shared with this run").font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.textPrimary)234                if agents.files.granted.isEmpty {235                    Text("None. This agent can read only the files you share here, and access ends when the run ends.")236                        .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)237                }238                ForEach(agents.files.granted) { file in239                    HStack(spacing: AstraSpace.sm) {240                        Image(systemName: "doc.text").foregroundStyle(AstraColor.textSecondary).accessibilityHidden(true)241                        VStack(alignment: .leading, spacing: AstraSpace.xxs) {242                            Text(file.name).font(AstraFont.subheadline).foregroundStyle(AstraColor.textPrimary).lineLimit(2)243                            if let size = file.byteCount { Text(AgentFormat.bytes(Int64(size))).font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary) }244                        }245                        Spacer(minLength: 0)246                        IconButton("xmark.circle.fill", label: "Stop sharing \(file.name)", tint: AstraColor.textTertiary) { agents.files.revoke(file.id) }247                    }248                }249                Button { showImporter = true } label: { Label("Share files", systemImage: "plus") }250                    .buttonStyle(AstraSecondaryButtonStyle(compact: true))251                    .accessibilityIdentifier("agent-share-files")252            }253        }254    }255256    // MARK: During and after the run257258    @ViewBuilder private func running(_ session: AgentRunSession) -> some View {259        AstraCard {260            VStack(alignment: .leading, spacing: AstraSpace.xs) {261                Text("Goal").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textTertiary)262                Text(session.goal).font(AstraFont.callout).foregroundStyle(AstraColor.textPrimary).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)263            }264        }265        AgentBudgetMeter(session: session)266        if let error = session.auditError { NoticeCard(.warning, title: "Audit trail incomplete", message: error) }267        if let plan = session.plan, !plan.steps.isEmpty { AgentPlanCard(plan: plan) }268        if session.isRunning, session.profile.allowedTools.contains("read_file") { filesCard }269270        SectionTitle("Activity", detail: session.items.isEmpty ? nil : "\(session.toolCalls) tool \(session.toolCalls == 1 ? "call" : "calls")")271        ForEach(session.items) { item in AgentTimelineRow(item: item).astraAppear() }272        if session.isRunning { liveStatus(session) }273274        if let outcome = session.outcome {275            NoticeCard(outcome.noticeKind, title: outcome.headline, message: outcome.explanation(steps: session.step, elapsed: session.elapsed))276                .accessibilityIdentifier("agent-run-status")277            if outcome == .completed { answerCard(session) }278        }279    }280281    private func liveStatus(_ session: AgentRunSession) -> some View {282        HStack(spacing: AstraSpace.md) {283            OrbitActivity(size: 24).accessibilityHidden(true)284            Text(statusLine(session)).font(AstraFont.subheadline).foregroundStyle(AstraColor.textSecondary)285            Spacer(minLength: 0)286        }287        .padding(.vertical, AstraSpace.xs)288        .accessibilityElement(children: .combine)289        .accessibilityIdentifier("agent-live-status")290    }291292    private func statusLine(_ session: AgentRunSession) -> String {293        if session.stopRequested { return "Stopping" }294        if session.waitingForApproval { return "Waiting for your approval" }295        if let last = session.items.last, case .tool(let tool) = last.content, tool.state == .running { return "Running \(AgentToolCatalog.title(tool.name))" }296        return session.step == 0 ? "Starting" : "Working on step \(session.step)"297    }298299    private func answerCard(_ session: AgentRunSession) -> some View {300        AstraCard {301            VStack(alignment: .leading, spacing: AstraSpace.md) {302                Text("Answer").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textTertiary).accessibilityAddTraits(.isHeader)303                if session.finalText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {304                    Text("The model finished without writing an answer.").font(AstraFont.callout).foregroundStyle(AstraColor.textSecondary)305                } else {306                    AgentMarkdown(text: session.finalText)307                    HStack(spacing: AstraSpace.sm) {308                        Button { Pasteboard.copy(session.finalText); AstraHaptics.tap(); app.show("Copied", .success) } label: { Label("Copy", systemImage: "doc.on.doc") }309                            .buttonStyle(AstraSecondaryButtonStyle(compact: true)).accessibilityIdentifier("agent-answer-copy")310                        ShareLink(item: session.finalText) { Label("Share", systemImage: "square.and.arrow.up") }311                            .buttonStyle(AstraSecondaryButtonStyle(compact: true)).accessibilityIdentifier("agent-answer-share")312                    }313                }314            }315        }316        .accessibilityIdentifier("agent-answer")317    }318319    // MARK: Bottom bar320321    @ViewBuilder private func bottomBar(_ profile: AgentProfile) -> some View {322        VStack(spacing: AstraSpace.sm) {323            if let session {324                if session.isRunning {325                    Button { session.stop(); AstraHaptics.warning() } label: {326                        Label(session.stopRequested ? "Stopping" : "Stop", systemImage: "stop.fill")327                    }328                    .buttonStyle(AstraPrimaryButtonStyle(destructive: true))329                    .accessibilityHint("Stops the run immediately, including a pending approval")330                    .accessibilityIdentifier("agent-stop")331                } else {332                    HStack(spacing: AstraSpace.sm) {333                        Button("Audit trail") { path.append(.audit(session.recordID)) }334                            .buttonStyle(AstraSecondaryButtonStyle()).accessibilityIdentifier("agent-open-audit")335                        Button("New run") { goal = session.goal; agents.clearFinishedSession() }336                            .buttonStyle(AstraPrimaryButtonStyle()).accessibilityIdentifier("agent-new-run")337                    }338                }339            } else {340                Button {341                    goalFocused = false342                    AstraHaptics.send()343                    Task { await agents.start(profile: profile, goal: goal) }344                } label: {345                    HStack(spacing: AstraSpace.sm) {346                        if agents.isStarting { ProgressView().tint(AstraColor.onAccent) }347                        Label("Start", systemImage: "play.fill")348                    }349                }350                .buttonStyle(AstraPrimaryButtonStyle())351                .disabled(goal.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || agents.isStarting || otherActive != nil || agents.blocker(for: profile) != nil)352                .accessibilityIdentifier("agent-start")353            }354        }355        .padding(.horizontal, AstraSpace.page).padding(.top, AstraSpace.md).padding(.bottom, AstraSpace.sm)356        .background(AstraColor.background)357        .overlay(alignment: .top) { Divider().overlay(AstraColor.stroke) }358    }359}360361// MARK: - Profile summary362363/// Model (logo on the left), tools and the warnings that matter before a run.364struct AgentProfileSummary: View {365    @Environment(AppModel.self) private var app366    let profile: AgentProfile367368    var body: some View {369        let info = app.library.info(for: profile.model)370        AstraCard {371            VStack(alignment: .leading, spacing: AstraSpace.md) {372                HStack(spacing: AstraSpace.md) {373                    ProviderLogo(ref: profile.model, vendor: info?.vendor, size: 38)374                    VStack(alignment: .leading, spacing: AstraSpace.xxs) {375                        Text(app.library.displayName(for: profile.model)).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary).lineLimit(2)376                        Text(profile.model.provider.isLocal ? "On this iPhone" : (app.library.endpointName(for: profile.model) ?? profile.model.provider.displayName))377                            .font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary)378                    }379                    Spacer(minLength: 0)380                }381                .accessibilityElement(children: .combine)382                if profile.allowedTools.isEmpty && !profile.planningEnabled {383                    Text("No tools: this agent answers from the model alone.").font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary)384                } else {385                    FlowLayout(spacing: AstraSpace.xs) {386                        if profile.planningEnabled { AstraBadge("Plan", symbol: AgentToolCatalog.symbol(PlanTool.name), tone: .accent) }387                        ForEach(profile.allowedTools, id: \.self) { name in388                            AstraBadge(AgentToolCatalog.title(name), symbol: AgentToolCatalog.symbol(name), tone: AgentToolCatalog.info(name)?.risk.tone ?? .neutral)389                        }390                    }391                }392                if let warning = AgentModelCheck.toolWarning(info: info, profile: profile) {393                    Label(warning, systemImage: "exclamationmark.triangle.fill").font(AstraFont.footnote).foregroundStyle(AstraColor.warning)394                        .fixedSize(horizontal: false, vertical: true)395                }396                if !profile.model.provider.isLocal {397                    Text("Cloud model: the goal and everything the tools return are sent to \(profile.model.provider.displayName).")398                        .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary).fixedSize(horizontal: false, vertical: true)399                }400            }401        }402    }403}404405enum AgentModelCheck {406    /// A warning when the profile needs tools and the model does not declare them. Nil when it does, or when no tool is needed.407    static func toolWarning(info: ModelInfo?, profile: AgentProfile) -> String? {408        guard !profile.allowedTools.isEmpty || profile.planningEnabled else { return nil }409        guard let info else { return "This model's capabilities are not known, so tool support could not be checked." }410        if info.capabilities.contains(.tools) { return nil }411        return "This model does not declare tool support. It may ignore the tools or the provider may reject the request; pick a model with the Tools badge."412    }413}414415// MARK: - Budget meter416417/// Steps, tool calls, tokens, cost and time against the profile's limits. A figure nobody reported is shown as unknown, never as zero.418struct AgentBudgetMeter: View {419    let session: AgentRunSession420    @Environment(\.dynamicTypeSize) private var typeSize421422    var body: some View {423        let budgets = session.profile.budgets424        AstraCard {425            VStack(alignment: .leading, spacing: AstraSpace.md) {426                LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: AstraSpace.md, alignment: .topLeading), count: typeSize.isAccessibilitySize ? 1 : 2),427                          alignment: .leading, spacing: AstraSpace.md) {428                    AgentMeterTile(label: "Steps", symbol: "arrow.triangle.turn.up.right.diamond", value: "\(session.step) of \(budgets.maxSteps)",429                                   fraction: Double(session.step) / Double(max(1, budgets.maxSteps)))430                    AgentMeterTile(label: "Tool calls", symbol: "wrench.and.screwdriver", value: "\(session.toolCalls) of \(budgets.maxToolCalls)",431                                   fraction: budgets.maxToolCalls > 0 ? Double(session.toolCalls) / Double(budgets.maxToolCalls) : nil)432                    tokens(budgets)433                    cost(budgets)434                }435                Divider().overlay(AstraColor.stroke)436                time(budgets)437            }438        }439        .accessibilityIdentifier("agent-budget")440    }441442    private func tokens(_ budgets: AgentBudgets) -> AgentMeterTile {443        guard let total = session.usage.totalTokens else {444            return AgentMeterTile(label: "Tokens", symbol: "number", value: session.hasUsageReport ? "Unknown" : nil,445                                  detail: session.hasUsageReport ? "Not reported by this model" : "No turn finished yet")446        }447        if let limit = budgets.maxTotalTokens {448            return AgentMeterTile(label: "Tokens", symbol: "number", value: AgentFormat.count(total), detail: "of \(AgentFormat.count(limit))",449                                  fraction: Double(total) / Double(max(1, limit)))450        }451        return AgentMeterTile(label: "Tokens", symbol: "number", value: AgentFormat.count(total), detail: "No limit set")452    }453454    private func cost(_ budgets: AgentBudgets) -> AgentMeterTile {455        let limit = budgets.maxTotalCostUSD456        guard let cost = session.cost else {457            return AgentMeterTile(label: "Cost", symbol: "dollarsign.circle", value: nil, detail: "No turn finished yet")458        }459        switch cost.basis {460        case .onDevice:461            return AgentMeterTile(label: "Cost", symbol: "dollarsign.circle", value: "On device", detail: "No provider charge")462        case .unavailable:463            return AgentMeterTile(label: "Cost", symbol: "dollarsign.circle", value: "Unknown",464                                  detail: limit == nil ? "No price or usage for this model" : "The cost limit cannot be enforced")465        default:466            guard let amount = cost.amountUSD else { return AgentMeterTile(label: "Cost", symbol: "dollarsign.circle", value: "Unknown") }467            let basis = cost.basis == .reportedByProvider ? "Reported by the provider" : "Estimate from published prices"468            return AgentMeterTile(label: "Cost", symbol: "dollarsign.circle", value: cost.label, detail: limit.map { "of \(CostEstimate.format($0))" } ?? basis,469                                  fraction: limit.map { amount / max($0, .leastNonzeroMagnitude) })470        }471    }472473    @ViewBuilder private func time(_ budgets: AgentBudgets) -> some View {474        if session.isRunning {475            TimelineView(.periodic(from: .now, by: 1)) { _ in timeRow(budgets) }476        } else { timeRow(budgets) }477    }478479    private func timeRow(_ budgets: AgentBudgets) -> some View {480        let elapsed = AgentFormat.clock(session.elapsed)481        let limit = budgets.wallClockLimit.map(AgentFormat.clock)482        return HStack(spacing: AstraSpace.sm) {483            Image(systemName: "clock").imageScale(.small).foregroundStyle(AstraColor.textTertiary).accessibilityHidden(true)484            Text("Time").font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary)485            Spacer(minLength: AstraSpace.sm)486            Text(limit.map { "\(elapsed) of \($0)" } ?? elapsed).font(AstraFont.metricSmall).foregroundStyle(AstraColor.textPrimary)487        }488        .accessibilityElement(children: .ignore)489        .accessibilityLabel("Time")490        .accessibilityValue(limit.map { "\(elapsed) of \($0)" } ?? elapsed)491    }492}493494struct AgentMeterTile: View {495    var label: String496    var symbol: String497    /// Nil shows an em dash: nothing to report yet.498    var value: String?499    var detail: String?500    var fraction: Double?501502    var body: some View {503        VStack(alignment: .leading, spacing: AstraSpace.xs) {504            HStack(spacing: AstraSpace.xs) {505                Image(systemName: symbol).imageScale(.small)506                Text(label)507            }508            .font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary)509            Text(value ?? "—").font(AstraFont.metricSmall)510                .foregroundStyle(value == nil || value == "Unknown" ? AstraColor.textSecondary : AstraColor.textPrimary)511                .lineLimit(1).minimumScaleFactor(0.7)512            if let fraction { AstraProgressBar(fraction).accessibilityHidden(true) }513            if let detail { Text(detail).font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary).fixedSize(horizontal: false, vertical: true) }514        }515        .frame(maxWidth: .infinity, alignment: .leading)516        .accessibilityElement(children: .ignore)517        .accessibilityLabel(label)518        .accessibilityValue([value ?? "not available yet", detail].compactMap { $0 }.joined(separator: ", "))519    }520}521522// MARK: - Plan523524struct AgentPlanCard: View {525    let plan: AgentPlan526527    var body: some View {528        AstraCard {529            VStack(alignment: .leading, spacing: AstraSpace.md) {530                SectionTitle("Plan", detail: "\(plan.completedCount) of \(plan.steps.count) finished")531                ForEach(plan.steps) { step in532                    HStack(alignment: .firstTextBaseline, spacing: AstraSpace.sm) {533                        Image(systemName: step.status.symbol).foregroundStyle(step.status.color).accessibilityHidden(true)534                        Text(step.title).font(step.status == .inProgress ? AstraFont.subheadline.weight(.semibold) : AstraFont.subheadline)535                            .foregroundStyle(step.status == .done || step.status == .skipped ? AstraColor.textSecondary : AstraColor.textPrimary)536                            .fixedSize(horizontal: false, vertical: true)537                        Spacer(minLength: 0)538                    }539                    .accessibilityElement(children: .ignore)540                    .accessibilityLabel(step.title)541                    .accessibilityValue(step.status.label)542                }543            }544        }545        .accessibilityIdentifier("agent-plan")546    }547}548549// MARK: - Timeline550551struct AgentTimelineRow: View {552    let item: AgentTimelineItem553554    var body: some View {555        switch item.content {556        case .notice(let text):557            NoticeCard(.info, title: "Note", message: text)558        case .step(let number):559            HStack(spacing: AstraSpace.sm) {560                Text("Step \(number)").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary)561                Rectangle().fill(AstraColor.stroke).frame(height: 1)562            }563            .padding(.top, AstraSpace.xs)564            .accessibilityElement(children: .combine)565            .accessibilityAddTraits(.isHeader)566        case .text(let text):567            AgentMarkdown(text: text).padding(.vertical, AstraSpace.xxs)568        case .plan(let plan):569            Label("Plan updated: \(plan.completedCount) of \(plan.steps.count) finished", systemImage: AgentToolCatalog.symbol(PlanTool.name))570                .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary)571        case .tool(let tool):572            AgentToolCard(tool: tool)573        case .delegate(let activity):574            AgentDelegateCard(activity: activity)575        case .warning(let warning):576            NoticeCard(.warning, title: "Close to the \(warning.kind.label)", message: warning.message)577        case .problem(let text):578            NoticeCard(.error, title: "Problem", message: text)579        }580    }581}582583/// One sub-agent: its role and task, what it is doing right now, and its report once it has finished (folded until asked for).584struct AgentDelegateCard: View {585    let activity: AgentDelegateActivity586    @State private var showReport = false587588    private var failed: Bool { if let status = activity.status, status != .completed { return true }; return false }589590    var body: some View {591        AstraCard(padding: AstraSpace.md, radius: AstraRadius.md, tint: failed ? AstraColor.warningSoft : nil) {592            VStack(alignment: .leading, spacing: AstraSpace.sm) {593                HStack(alignment: .top, spacing: AstraSpace.sm) {594                    Image(systemName: activity.role.symbol).foregroundStyle(AstraColor.violet).frame(width: 24).accessibilityHidden(true)595                    VStack(alignment: .leading, spacing: AstraSpace.xxs) {596                        Text("\(activity.role.title) sub-agent").font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.textPrimary)597                        Text(activity.task).font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).lineLimit(showReport ? nil : 3)598                    }599                    Spacer(minLength: AstraSpace.sm)600                    stateMark601                }602                if !activity.tools.isEmpty {603                    FlowLayout(spacing: AstraSpace.xs) {604                        ForEach(Array(activity.tools.enumerated()), id: \.offset) { _, tool in605                            AstraBadge(AgentToolCatalog.title(tool.name), symbol: tool.failed == nil ? "ellipsis" : tool.failed == true ? "xmark" : "checkmark",606                                       tone: tool.failed == true ? .danger : .neutral)607                        }608                    }609                }610                if let status = activity.status {611                    Button {612                        showReport.toggle()613                    } label: {614                        HStack {615                            Text(showReport ? "Hide report" : "Show report").font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.violet)616                            Spacer(minLength: AstraSpace.sm)617                            Text(status.label).font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).lineLimit(1)618                        }619                        .frame(minHeight: AstraSpace.hit).contentShape(Rectangle())620                    }621                    .buttonStyle(.plain)622                    .accessibilityValue(showReport ? "Shown" : "Hidden")623                    if showReport {624                        if activity.report.isEmpty { Text("The sub-agent returned no report.").font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary) }625                        else { AgentMarkdown(text: activity.report) }626                        Text("A sub-agent's report is material for the agent to check, not a verified result.")627                            .font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary)628                    }629                }630            }631        }632        .accessibilityElement(children: .contain)633        .accessibilityLabel("\(activity.role.title) sub-agent")634        .accessibilityValue(activity.status?.label ?? (activity.waitingForApproval ? "Waiting for your approval" : "Working, step \(activity.step)"))635    }636637    @ViewBuilder private var stateMark: some View {638        if let status = activity.status {639            Image(systemName: status == .completed ? "checkmark.circle.fill" : "exclamationmark.circle.fill")640                .foregroundStyle(status == .completed ? AstraColor.success : AstraColor.warning)641                .accessibilityLabel(status == .completed ? "Done" : "Did not finish")642        } else if activity.waitingForApproval {643            AstraBadge("Needs approval", symbol: "hand.raised", tone: .warning)644        } else {645            HStack(spacing: AstraSpace.xs) {646                ProgressView().controlSize(.small)647                Text("Step \(max(1, activity.step))").font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary)648            }649            .accessibilityElement(children: .combine).accessibilityLabel("Working, step \(max(1, activity.step))")650        }651    }652}653654/// One tool call: what was asked, with which (redacted) input, what came back. The output stays folded until asked for.655struct AgentToolCard: View {656    @Environment(AppModel.self) private var app657    let tool: AgentToolActivity658    @State private var showOutput = false659    static let shownOutputCharacters = 8_000660661    private var failed: Bool { tool.isError && tool.state == .finished }662663    var body: some View {664        let info = AgentToolCatalog.info(tool.name)665        AstraCard(padding: AstraSpace.md, radius: AstraRadius.md, tint: failed ? AstraColor.dangerSoft : nil) {666            VStack(alignment: .leading, spacing: AstraSpace.sm) {667                HStack(alignment: .top, spacing: AstraSpace.sm) {668                    Image(systemName: AgentToolCatalog.symbol(tool.name)).foregroundStyle(AstraColor.violet).frame(width: 24).accessibilityHidden(true)669                    VStack(alignment: .leading, spacing: AstraSpace.xxs) {670                        Text(AgentToolCatalog.title(tool.name)).font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.textPrimary)671                        Text(tool.name).font(AstraFont.monoSmall).foregroundStyle(AstraColor.textTertiary).lineLimit(1)672                    }673                    Spacer(minLength: AstraSpace.sm)674                    stateMark675                }676                FlowLayout(spacing: AstraSpace.xs) {677                    if let info { AstraBadge(info.risk.label, symbol: info.risk.symbol, tone: info.risk.tone) }678                    if let approval = tool.approval { AstraBadge(approval.isAllowed ? approval.label : "Denied by you", symbol: approval.isAllowed ? "hand.thumbsup" : "hand.raised", tone: approval.isAllowed ? .neutral : .danger) }679                    if failed && !tool.wasDenied { AstraBadge("Error", symbol: "xmark.octagon", tone: .danger) }680                    if !tool.flagged.isEmpty { AstraBadge("Suspicious content", symbol: "exclamationmark.triangle", tone: .warning) }681                }682                if !tool.flagged.isEmpty { flaggedBanner }683                Text(tool.arguments.serialized()).font(AstraFont.monoSmall).foregroundStyle(AstraColor.textSecondary)684                    .lineLimit(showOutput ? nil : 3).frame(maxWidth: .infinity, alignment: .leading)685                    .accessibilityLabel("Input, secrets masked").accessibilityValue(tool.arguments.serialized())686                if let output = tool.output { outputSection(output) }687            }688        }689        .accessibilityElement(children: .contain)690        .accessibilityLabel("Tool call: \(AgentToolCatalog.title(tool.name))")691    }692693    @ViewBuilder private var stateMark: some View {694        switch tool.state {695        case .requested: AstraBadge("Checking", tone: .neutral)696        case .awaitingApproval: AstraBadge("Needs approval", symbol: "hand.raised", tone: .warning)697        case .running: ProgressView().controlSize(.small).accessibilityLabel("Running")698        case .finished:699            Image(systemName: tool.isError ? "xmark.circle.fill" : "checkmark.circle.fill")700                .foregroundStyle(tool.isError ? AstraColor.danger : AstraColor.success)701                .accessibilityLabel(tool.isError ? (tool.wasDenied ? "Denied" : "Failed") : "Done")702        case .interrupted: AstraBadge("Interrupted", symbol: "stop.circle", tone: .neutral)703        }704    }705706    private var flaggedBanner: some View {707        let kinds = Array(Set(tool.flagged.map(\.category.label))).sorted().joined(separator: "; ")708        return VStack(alignment: .leading, spacing: AstraSpace.xs) {709            NoticeCard(.warning, title: "This result contains text that looks like instructions",710                       message: "It \(kinds). The agent was told to treat it as data, not as orders. Check what it does next.")711            ForEach(tool.flagged, id: \.self) { finding in712                Text("“\(finding.excerpt)”").font(AstraFont.monoSmall).foregroundStyle(AstraColor.textSecondary).lineLimit(3)713                    .accessibilityLabel("Flagged excerpt: \(finding.excerpt)")714            }715        }716        .accessibilityIdentifier("agent-tool-flagged")717    }718719    @ViewBuilder private func outputSection(_ output: String) -> some View {720        Button {721            showOutput.toggle()722        } label: {723            HStack(spacing: AstraSpace.sm) {724                Text(showOutput ? "Hide output" : "Show output").font(AstraFont.footnote.weight(.semibold)).foregroundStyle(AstraColor.violet)725                Text("\(AgentFormat.count(output.count)) characters").font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary)726                Spacer(minLength: 0)727                Image(systemName: showOutput ? "chevron.up" : "chevron.down").font(.caption.weight(.semibold)).foregroundStyle(AstraColor.textTertiary)728            }729            .frame(minHeight: AstraSpace.hit).contentShape(Rectangle())730        }731        .buttonStyle(.plain)732        .accessibilityLabel(tool.isError ? "Error output" : "Output").accessibilityValue(showOutput ? "Shown" : "Hidden")733        .accessibilityIdentifier("agent-tool-output-toggle")734        if showOutput {735            VStack(alignment: .leading, spacing: AstraSpace.sm) {736                Text(output.count > Self.shownOutputCharacters ? String(output.prefix(Self.shownOutputCharacters)) + "\n…" : output)737                    .font(AstraFont.monoSmall).foregroundStyle(tool.isError ? AstraColor.danger : AstraColor.textPrimary)738                    .textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)739                    .padding(AstraSpace.sm)740                    .background(AstraColor.codeBackground, in: RoundedRectangle(cornerRadius: AstraRadius.sm, style: .continuous))741                if output.count > Self.shownOutputCharacters {742                    Text("Showing the first \(AgentFormat.count(Self.shownOutputCharacters)) characters. Copy to get all of it.")743                        .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary)744                }745                Button { Pasteboard.copy(output); AstraHaptics.tap(); app.show("Copied", .success) } label: { Label("Copy output", systemImage: "doc.on.doc") }746                    .buttonStyle(AstraSecondaryButtonStyle(compact: true))747            }748        }749    }750}751
Files main
Menu

Theme