SPB Git

Repository Public MIT

AgentHistoryScreen.swift 19.1 KB 401 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/AgentHistoryScreen.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 AstraCore90import AstraAgents91import AstraDesign92import AstraPersistence9394/// Stored runs, most recent first, for one agent or for all of them.95struct AgentHistoryScreen: View {96    @Environment(AppModel.self) private var app97    let agents: AgentsController98    let profileID: String?99    @Binding var path: [AgentRoute]100101    @State private var runs: [AgentRunRecord] = []102    @State private var isLoading = true103    @State private var error: String?104    @State private var deleting: AgentRunRecord?105106    private var title: String { profileID.flatMap(agents.profile(id:))?.name ?? "Run history" }107108    var body: some View {109        Group {110            if isLoading { ProgressView("Loading runs").frame(maxWidth: .infinity, maxHeight: .infinity) }111            else if let error {112                EmptyStateView(symbol: "exclamationmark.triangle", title: "The history could not be loaded", message: error) {113                    Button("Try again") { Task { await load() } }.buttonStyle(AstraPrimaryButtonStyle())114                }115                .frame(maxWidth: .infinity, maxHeight: .infinity)116            } else if runs.isEmpty {117                EmptyStateView(symbol: "clock.arrow.circlepath", title: "No run yet", message: "Every run is recorded here with its audit trail: each step, tool call, approval and result.")118                    .frame(maxWidth: .infinity, maxHeight: .infinity)119            } else { list }120        }121        .background(Starfield(density: 0.35))122        .navigationTitle(title).navigationBarTitleDisplayMode(.inline)123        .task { await load() }124        .confirmationDialog("Delete this run and its audit trail?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible) {125            Button("Delete run", role: .destructive) { if let run = deleting { delete(run) } }126            Button("Cancel", role: .cancel) {}127        }128    }129130    private var list: some View {131        List {132            Section {133                ForEach(runs) { run in134                    Button { path.append(.audit(run.id)) } label: { AgentRunRow(run: run, showsProfile: profileID == nil).contentShape(Rectangle()) }135                        .buttonStyle(.plain)136                        .swipeActions(edge: .trailing, allowsFullSwipe: false) {137                            Button(role: .destructive) { deleting = run } label: { Label("Delete", systemImage: "trash") }138                        }139                        .listRowBackground(AstraColor.surface)140                }141            } footer: { Text("Stored on this iPhone only. Secrets found in arguments and results were masked before being saved.") }142        }143        .listStyle(.insetGrouped)144        .scrollContentBackground(.hidden)145        .refreshable { await load() }146    }147148    private func load() async {149        do { runs = try await agents.runs(profileID: profileID); error = nil }150        catch let failure { error = AstraError.wrap(failure).message }151        isLoading = false152    }153154    private func delete(_ run: AgentRunRecord) {155        Task {156            do { try await agents.deleteRun(id: run.id); runs.removeAll { $0.id == run.id } }157            catch { app.show(AstraError.wrap(error).message, .error) }158        }159    }160}161162/// The stored audit trail of one run, exactly as it was written while the run happened.163struct AgentAuditScreen: View {164    @Environment(AppModel.self) private var app165    let agents: AgentsController166    let runID: String167    @Binding var path: [AgentRoute]168169    @State private var run: AgentRunRecord?170    @State private var steps: [AgentStepRecord] = []171    @State private var isLoading = true172    @State private var error: String?173    @State private var confirmDelete = false174    @State private var exported: ExportedFile?175176    private var isLive: Bool { agents.activeSession?.recordID == runID }177178    var body: some View {179        Group {180            if isLoading { ProgressView("Loading the audit trail").frame(maxWidth: .infinity, maxHeight: .infinity) }181            else if let run { trail(run) }182            else {183                EmptyStateView(symbol: "questionmark.folder", title: "This run is not available", message: error ?? "It was deleted.")184                    .frame(maxWidth: .infinity, maxHeight: .infinity)185            }186        }187        .background(Starfield(density: 0.35))188        .navigationTitle("Audit trail").navigationBarTitleDisplayMode(.inline)189        .toolbar {190            ToolbarItem(placement: .topBarTrailing) {191                Menu {192                    Button { export() } label: { Label("Export as Markdown", systemImage: "square.and.arrow.up") }.disabled(run == nil)193                    Button(role: .destructive) { confirmDelete = true } label: { Label("Delete run", systemImage: "trash") }.disabled(run == nil || isLive)194                } label: { Image(systemName: "ellipsis.circle") }195                .accessibilityLabel("Run options").accessibilityIdentifier("agent-audit-menu")196            }197        }198        // Reloads when the live run of this record moves on, so the trail of a run in progress stays current.199        .task(id: isLive ? agents.activeSession?.items.count ?? 0 : -1) { await load() }200        .sheet(item: $exported) { file in ShareSheet(items: [file.url]) }201        .confirmationDialog("Delete this run and its audit trail?", isPresented: $confirmDelete, titleVisibility: .visible) {202            Button("Delete run", role: .destructive) { delete() }203            Button("Cancel", role: .cancel) {}204        }205    }206207    private func load() async {208        do {209            run = try await app.store.agentRun(id: runID)210            steps = try await app.store.agentSteps(runID: runID)211            error = nil212        } catch let failure { error = AstraError.wrap(failure).message }213        isLoading = false214    }215216    private func delete() {217        Task {218            do { try await agents.deleteRun(id: runID); if !path.isEmpty { path.removeLast() } }219            catch { app.show(AstraError.wrap(error).message, .error) }220        }221    }222223    private func export() {224        guard let run else { return }225        do { exported = try ExportedFile.write(Self.markdown(run: run, steps: steps), name: "agent-run-" + run.profileName, ext: "md") }226        catch { app.show(AstraError.wrap(error).message, .error) }227    }228229    private func trail(_ run: AgentRunRecord) -> some View {230        ScrollView {231            VStack(alignment: .leading, spacing: AstraSpace.lg) {232                summary(run)233                if isLive { NoticeCard(.info, title: "This run is in progress", message: "New events appear here as they are recorded.") }234                SectionTitle("Events", detail: "\(steps.count)")235                if steps.isEmpty {236                    Text("Nothing was recorded before this run ended.").font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary)237                }238                ForEach(steps) { step in AgentAuditRow(step: step) }239            }240            .padding(.horizontal, AstraSpace.page).padding(.vertical, AstraSpace.lg)241        }242    }243244    private func summary(_ run: AgentRunRecord) -> some View {245        AstraCard {246            VStack(alignment: .leading, spacing: AstraSpace.md) {247                HStack(spacing: AstraSpace.sm) {248                    AstraBadge(run.status.label, symbol: run.status.symbol, tone: run.status.tone)249                    Text(run.profileName).font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.textPrimary).lineLimit(1)250                    Spacer(minLength: 0)251                }252                Text(run.goal).font(AstraFont.callout).foregroundStyle(AstraColor.textPrimary).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)253                VStack(alignment: .leading, spacing: AstraSpace.xs) {254                    if let model = run.model { fact("Model", app.library.displayName(for: model)) }255                    fact("Started", AgentFormat.stamp(run.startedAt))256                    if let finished = run.finishedAt { fact("Ended", AgentFormat.stamp(finished)) }257                    fact("Tool calls", "\(run.toolCallCount)")258                    fact("Tokens", AgentFormat.tokens(run.usage) ?? "Not reported")259                    fact("Cost", run.costUSD.map { $0 == 0 && (run.model?.provider.isLocal ?? false) ? "On device" : CostEstimate.format($0) } ?? "Unknown")260                }261                if let message = run.error, !message.isEmpty {262                    Label(message, systemImage: "exclamationmark.triangle.fill").font(AstraFont.footnote).foregroundStyle(AstraColor.warning)263                        .fixedSize(horizontal: false, vertical: true)264                }265                if let result = run.result, !result.isEmpty {266                    Divider().overlay(AstraColor.stroke)267                    Text(run.status == .completed ? "Answer" : "Last text from the model").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textTertiary)268                    AgentMarkdown(text: result)269                }270            }271        }272    }273274    private func fact(_ label: String, _ value: String) -> some View {275        HStack(alignment: .firstTextBaseline) {276            Text(label).font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary)277            Spacer(minLength: AstraSpace.md)278            Text(value).font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).multilineTextAlignment(.trailing)279        }280        .accessibilityElement(children: .combine)281    }282283    static func markdown(run: AgentRunRecord, steps: [AgentStepRecord]) -> String {284        var lines = ["# Agent run: \(run.profileName)", "", "- Status: \(run.status.label)", "- Started: \(AgentFormat.stamp(run.startedAt))"]285        if let finished = run.finishedAt { lines.append("- Ended: \(AgentFormat.stamp(finished))") }286        if let model = run.model { lines.append("- Model: \(model.modelID) (\(model.provider.displayName))") }287        lines.append("- Tool calls: \(run.toolCallCount)")288        lines.append("- Tokens: \(AgentFormat.tokens(run.usage) ?? "not reported")")289        lines.append("- Cost: \(run.costUSD.map(CostEstimate.format) ?? "unknown")")290        lines += ["", "## Goal", "", run.goal, "", "## Events", ""]291        for step in steps {292            var head = "\(step.ordinal + 1). **\(step.kind.auditTitle)**"293            if let tool = step.toolName { head += " `\(tool)`" }294            if let approval = step.approval { head += " (\(approval.rawValue))" }295            lines.append(head + " · " + step.createdAt.formatted(date: .omitted, time: .standard))296            if !step.text.isEmpty { lines += ["", step.text] }297            if let input = step.inputJSON { lines += ["", "Input:", "```json", input, "```"] }298            if let output = step.output {299                lines += ["", output["isError"]?.boolValue == true ? "Error output:" : "Output:", "```", output["text"]?.stringValue ?? output.serialized(), "```"]300            }301            lines.append("")302        }303        if let result = run.result, !result.isEmpty { lines += ["## Result", "", result, ""] }304        return lines.joined(separator: "\n")305    }306}307308extension AgentStepKind {309    var auditTitle: String {310        switch self {311        case .plan: "Plan"312        case .modelMessage: "Model"313        case .toolCall: "Tool call"314        case .toolResult: "Tool result"315        case .approvalRequest: "Approval asked"316        case .approvalDecision: "Your answer"317        case .memoryRead: "Memory read"318        case .memoryWrite: "Memory write"319        case .note: "Note"320        case .error: "Stopped"321        case .final: "Finished"322        }323    }324}325326/// One stored audit event.327struct AgentAuditRow: View {328    let step: AgentStepRecord329330    private var time: String { step.createdAt.formatted(date: .omitted, time: .standard) }331332    var body: some View {333        switch step.kind {334        case .toolCall:335            AgentToolCard(tool: activity)336        case .note where step.text.hasPrefix("Step "):337            HStack(spacing: AstraSpace.sm) {338                Text(step.text).font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary)339                Rectangle().fill(AstraColor.stroke).frame(height: 1)340                Text(time).font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary)341            }342            .accessibilityElement(children: .combine).accessibilityAddTraits(.isHeader)343        case .modelMessage:344            VStack(alignment: .leading, spacing: AstraSpace.xs) {345                caption("Model")346                if !step.text.isEmpty { AgentMarkdown(text: step.text) }347                if let usage = step.usage, let line = usageLine(usage) { Text(line).font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary) }348            }349        case .approvalRequest:350            AstraCard(padding: AstraSpace.md, radius: AstraRadius.md) {351                VStack(alignment: .leading, spacing: AstraSpace.xs) {352                    HStack(spacing: AstraSpace.sm) {353                        caption("Approval asked" + (step.toolName.map { " for \(AgentToolCatalog.title($0))" } ?? ""))354                        Spacer(minLength: 0)355                        switch step.approval {356                        case .approved, .autoApproved: AstraBadge("Allowed", symbol: "hand.thumbsup", tone: .success)357                        case .denied: AstraBadge("Denied", symbol: "hand.raised", tone: .danger)358                        case .expired, nil: AstraBadge("No answer", tone: .neutral)359                        }360                    }361                    Text(step.text).font(AstraFont.footnote).foregroundStyle(AstraColor.textPrimary).fixedSize(horizontal: false, vertical: true)362                }363            }364        case .error:365            NoticeCard(.warning, title: step.text.isEmpty ? "Stopped" : step.text)366        case .final:367            NoticeCard(.success, title: step.text.isEmpty ? "Completed" : step.text)368        default:369            VStack(alignment: .leading, spacing: AstraSpace.xxs) {370                caption(step.kind.auditTitle)371                Text(step.text).font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)372            }373            .accessibilityElement(children: .combine)374        }375    }376377    private func caption(_ text: String) -> some View {378        Text("\(text) · \(time)").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textTertiary)379    }380381    private func usageLine(_ usage: TokenUsage) -> String? {382        var parts: [String] = []383        if let input = usage.inputTokens { parts.append("\(AgentFormat.count(input)) tokens in") }384        if let output = usage.outputTokens { parts.append("\(AgentFormat.count(output)) out") }385        return parts.isEmpty ? nil : parts.joined(separator: " · ")386    }387388    /// The stored call in the shape the live timeline uses, so both look the same.389    private var activity: AgentToolActivity {390        let output = step.output391        let flagged: [InjectionFinding] = (output?["flagged"]?.arrayValue ?? []).compactMap { item in392            guard let category = item["category"]?.stringValue.flatMap(InjectionFinding.Category.init(rawValue:)) else { return nil }393            return InjectionFinding(category: category, excerpt: item["excerpt"]?.stringValue ?? "")394        }395        // A call without a recorded result is one the run never finished (it was stopped or the app closed).396        return AgentToolActivity(callID: step.id, name: step.toolName ?? "tool", arguments: step.input ?? .object([:]),397                                 state: step.outputJSON == nil ? .interrupted : .finished, output: output?["text"]?.stringValue ?? step.outputJSON,398                                 isError: output?["isError"]?.boolValue ?? false, flagged: flagged)399    }400}401
Files main
Menu

Theme