SPB Git

Repository Public

AgentPlayground.swift 16.8 KB 310 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Agents/AgentPlayground.swift3// Description: Runs an agent on a task with a live execution log, human approval checkpoints, cancellation and a persisted run history.4import SwiftUI5import Observation6import LocalChatAgents7import LocalChatCore89@MainActor @Observable10final class AgentRunModel {11    struct Entry: Identifiable, Hashable {12        enum Kind: Hashable { case step(Int), text, tool, notice, failure }13        var id = UUID()14        var kind: Kind15        var text = ""16        var callID: String?17        var toolName = ""18        var arguments = ""19        var output: String?20        var isError = false21        var isRunning = false22        var duration: TimeInterval?23        var decision: String?24    }25    var entries: [Entry] = []26    var isRunning = false27    var pending: ApprovalRequest?28    var totals: AgentTotals?29    var history: [AgentRunLog] = []30    var errorText: String?3132    @ObservationIgnored private var task: Task<Void, Never>?33    @ObservationIgnored private var continuation: CheckedContinuation<ApprovalDecision, Never>?3435    func loadHistory(_ app: AppModel, agent: AgentConfiguration) { history = app.agentLogs.list(agentID: agent.id, limit: 100) }3637    func run(agent: AgentConfiguration, taskText: String, _ app: AppModel) {38        guard !isRunning else { return }39        guard let modelID = agent.modelID ?? app.defaultModelID, app.model(modelID) != nil else { errorText = "No model is available for this agent. Choose one in Configure."; return }40        entries = []; totals = nil; errorText = nil; isRunning = true41        let setup = app.makeAgentRunner(for: agent)42        let stream = setup.runner.run(agent: agent, modelID: modelID, messages: [.user(taskText)], permissions: setup.permissions, options: setup.options) { [weak self] request in43            await self?.ask(request) ?? .deny(reason: "The playground was closed.")44        }45        task = Task { [weak self] in46            for await event in stream { self?.handle(event, app) }47            guard let self else { return }48            self.isRunning = false; self.pending = nil49            self.loadHistory(app, agent: agent)50        }51    }5253    func cancel() {54        task?.cancel()55        continuation?.resume(returning: .deny(reason: "Cancelled by the user.")); continuation = nil; pending = nil56        entries.append(Entry(kind: .notice, text: "Cancelled."))57    }5859    func resolve(_ decision: ApprovalDecision) {60        continuation?.resume(returning: decision); continuation = nil; pending = nil61    }6263    private func ask(_ request: ApprovalRequest) async -> ApprovalDecision {64        Haptics.play(.warning)65        pending = request66        return await withCheckedContinuation { continuation = $0 }67    }6869    private func toolIndex(_ id: String) -> Int? { entries.lastIndex { $0.callID == id } }7071    private func handle(_ event: AgentEvent, _ app: AppModel) {72        switch event {73        case .stepStarted(let n): entries.append(Entry(kind: .step(n)))74        case .text(let t):75            if let last = entries.indices.last, entries[last].kind == .text { entries[last].text += t } else { entries.append(Entry(kind: .text, text: t)) }76        case .reasoning: break77        case .toolRequested(let call):78            entries.append(Entry(kind: .tool, callID: call.id, toolName: call.name, arguments: call.arguments.serialized(pretty: true), isRunning: true))79        case .approvalNeeded: if let i = entries.indices.last, entries[i].kind == .tool { entries[i].decision = "Waiting for approval" }80        case .toolDenied(let id, let reason):81            if let i = toolIndex(id) { entries[i].isRunning = false; entries[i].isError = true; entries[i].decision = "Denied"; entries[i].output = reason }82        case .toolStarted(let id, _): if let i = toolIndex(id) { entries[i].decision = "Running" }83        case .toolFinished(let id, _, let output, let duration):84            if let i = toolIndex(id) { entries[i].isRunning = false; entries[i].isError = output.isError; entries[i].output = output.text; entries[i].duration = duration; entries[i].decision = output.isError ? "Failed" : "Done" }85        case .limitReached(let limit):86            entries.append(Entry(kind: .notice, text: "Stopped: the agent reached its \(limit == .steps ? "step" : limit == .toolCalls ? "tool-call" : "time") limit."))87        case .finished(_, let t, let log): totals = t; try? app.agentLogs.save(log); Haptics.play(.success)88        case .failed(let message, let log): entries.append(Entry(kind: .failure, text: message)); totals = log.totals; try? app.agentLogs.save(log); Haptics.play(.error)89        }90    }91}9293struct AgentPlayground: View {94    @Environment(AppModel.self) private var app95    let agent: AgentConfiguration96    @State private var run = AgentRunModel()97    @State private var taskText = ""9899    var body: some View {100        @Bindable var run = run101        VStack(alignment: .leading, spacing: DS.S.md) {102            VStack(alignment: .leading, spacing: 10) {103                TextField("Describe a task for \(agent.name)…", text: $taskText, axis: .vertical).lineLimit(2...6).textFieldStyle(.roundedBorder).accessibilityLabel("Agent task")104                HStack {105                    if run.isRunning { ThinkingDots(); Text("Running").font(DS.F.caption).foregroundStyle(DS.C.muted) }106                    else if agent.enabledTools.isEmpty { Text("No tool is enabled: the agent will only answer.").font(DS.F.caption).foregroundStyle(DS.C.muted) }107                    Spacer()108                    if run.isRunning { Button("Cancel") { run.cancel() }.buttonStyle(.lcDestructive) }109                    else { Button { run.run(agent: agent, taskText: taskText, app) } label: { Label("Run", systemImage: "play.fill") }.buttonStyle(.lcPrimary).disabled(taskText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) }110                }111            }112            .card()113            if let e = run.errorText { InlineNotice(.error, e) }114            if let t = run.totals {115                TileGrid(minimum: 110) {116                    MetricTile("Steps", value: "\(t.steps)", symbol: "arrow.triangle.branch")117                    MetricTile("Tool calls", value: "\(t.toolCalls)", symbol: "wrench.and.screwdriver")118                    MetricTile("Tokens", value: (t.promptTokens + t.completionTokens).formatted(), symbol: "number", footnote: "\(t.promptTokens.formatted()) in · \(t.completionTokens.formatted()) out")119                    MetricTile("Duration", value: MetricFormat.seconds(t.duration), symbol: "timer")120                }121            }122            ForEach(run.entries) { LogEntryView(entry: $0) }123        }124        .sheet(item: $run.pending) { request in AgentApprovalSheet(request: request) { run.resolve($0) }.interactiveDismissDisabled() }125        .onDisappear { if run.isRunning { run.cancel() } }126    }127}128129struct LogEntryView: View {130    let entry: AgentRunModel.Entry131    var body: some View {132        switch entry.kind {133        case .step(let n):134            HStack(spacing: 8) { Text("STEP \(n)").font(DS.F.micro).kerning(0.6).foregroundStyle(DS.C.muted); Rectangle().fill(DS.C.border).frame(height: 1) }.padding(.top, 4)135        case .text: MarkdownView(text: entry.text).card(padding: DS.S.md)136        case .notice: InlineNotice(.warning, entry.text)137        case .failure: InlineNotice(.error, entry.text)138        case .tool:139            ToolCallCard(name: entry.toolName, arguments: entry.arguments, output: entry.output, isError: entry.isError, isRunning: entry.isRunning, duration: entry.duration, decision: entry.decision)140        }141    }142}143144struct ToolCallCard: View {145    let name: String; let arguments: String; let output: String?; let isError: Bool; let isRunning: Bool; let duration: TimeInterval?; let decision: String?146    @State private var expanded = true147    var body: some View {148        VStack(alignment: .leading, spacing: 8) {149            HStack(spacing: 8) {150                Image(systemName: "wrench.and.screwdriver.fill").font(.system(size: 11)).foregroundStyle(isError ? DS.C.danger : DS.C.accent)151                Text(name).font(DS.F.mono(12.5, weight: .semibold)).foregroundStyle(DS.C.text)152                if let decision { Pill(decision, tone: isError ? .danger : isRunning ? .accent : .ok) }153                if isRunning { ProgressView().controlSize(.mini) }154                Spacer()155                if let duration { Text(MetricFormat.seconds(duration)).font(DS.F.mono(10.5)).foregroundStyle(DS.C.muted) }156                IconButton(expanded ? "chevron.up" : "chevron.down", label: expanded ? "Collapse" : "Expand") { withAnimation(DS.M.snappy) { expanded.toggle() } }157            }158            if expanded {159                Text(arguments).font(DS.F.mono(11.5)).foregroundStyle(DS.C.text2).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)160                    .padding(8).background(DS.C.surface2, in: RoundedRectangle(cornerRadius: 8, style: .continuous))161                if let output {162                    Text(output.count > 4000 ? String(output.prefix(4000)) + "\n… (\(output.count - 4000) more characters)" : output)163                        .font(DS.F.mono(11.5)).foregroundStyle(isError ? DS.C.danger : DS.C.text).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)164                        .padding(8).background((isError ? DS.C.danger : DS.C.ok).opacity(0.07), in: RoundedRectangle(cornerRadius: 8, style: .continuous))165                }166            }167        }168        .card(padding: DS.S.md)169        .accessibilityElement(children: .contain).accessibilityLabel("Tool call \(name)")170    }171}172173/// Human approval checkpoint for one tool call.174struct AgentApprovalSheet: View {175    let request: ApprovalRequest176    let decide: (ApprovalDecision) -> Void177    @State private var reason = ""178179    var body: some View {180        VStack(alignment: .leading, spacing: DS.S.lg) {181            HStack(spacing: 10) {182                Image(systemName: "hand.raised.fill").font(.system(size: 22)).foregroundStyle(request.risk >= .write ? DS.C.warn : DS.C.accent)183                VStack(alignment: .leading, spacing: 2) {184                    Text("Approval needed").font(DS.F.title)185                    Text("The agent wants to use a tool.").font(DS.F.caption).foregroundStyle(DS.C.muted)186                }187            }188            HStack(spacing: 8) {189                Text(request.toolName).font(DS.F.mono(13, weight: .semibold))190                RiskBadge(risk: request.risk)191            }192            Text(request.summary).font(DS.F.callout).foregroundStyle(DS.C.text).fixedSize(horizontal: false, vertical: true)193            ScrollView {194                Text(request.arguments.serialized(pretty: true)).font(DS.F.mono(12)).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).padding(10)195            }196            .frame(maxHeight: 220).background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))197            if request.risk == .execute { InlineNotice(.warning, "This runs a command on your Mac. Read it carefully: it is never approved automatically.") }198            TextField("Reason for denying (optional, sent to the model)", text: $reason).textFieldStyle(.roundedBorder)199            ViewThatFits(in: .horizontal) {200                HStack { buttons }201                VStack(alignment: .trailing, spacing: 8) { buttons }202            }203        }204        .padding(DS.S.xl).frame(minWidth: 320, idealWidth: 500)205        .presentationDetents([.large])206    }207208    @ViewBuilder private var buttons: some View {209        Button("Deny") { decide(.deny(reason: reason.isEmpty ? nil : reason)) }.buttonStyle(.lcDestructive).keyboardShortcut(.cancelAction)210        Spacer(minLength: 0)211        if request.canApproveForRun { Button("Approve for this run") { decide(.approveForRun) }.buttonStyle(.lcSecondaryCompact) }212        Button("Approve") { decide(.approve) }.buttonStyle(.lcPrimaryCompact)213    }214}215216struct RiskBadge: View {217    let risk: ToolRisk218    var body: some View {219        let tone: Pill.Tone = switch risk { case .safe: .ok; case .read: .accent; case .write: .warn; case .execute: .danger }220        let symbol = switch risk { case .safe: "checkmark.shield"; case .read: "eye"; case .write: "square.and.pencil"; case .execute: "terminal" }221        Pill(risk.label, symbol: symbol, tone: tone)222    }223}224225// MARK: History226227struct AgentHistory: View {228    @Environment(AppModel.self) private var app229    let agent: AgentConfiguration230    @State private var logs: [AgentRunLog] = []231    @State private var opened: AgentRunLog?232233    var body: some View {234        VStack(alignment: .leading, spacing: DS.S.md) {235            if logs.isEmpty { Text("No run yet. Use the playground, or chat with this agent.").font(DS.F.callout).foregroundStyle(DS.C.muted).padding(.vertical, DS.S.lg) }236            else { HStack { Spacer(); Button("Delete all") { for l in logs { app.agentLogs.delete(l.id) }; reload() }.buttonStyle(.lcDestructive) } }237            ForEach(logs) { log in238                Button { opened = log } label: {239                    HStack(alignment: .top, spacing: 10) {240                        outcomePill(log.outcome)241                        VStack(alignment: .leading, spacing: 3) {242                            Text(log.task).font(DS.F.callout).foregroundStyle(DS.C.text).lineLimit(2).multilineTextAlignment(.leading)243                            Text("\(log.startedAt.formatted(date: .abbreviated, time: .shortened)) · \(log.totals.steps) steps · \(log.totals.toolCalls) tool calls").font(DS.F.micro).foregroundStyle(DS.C.muted)244                        }245                        Spacer(minLength: 4)246                        Image(systemName: "chevron.right").font(.system(size: 11, weight: .semibold)).foregroundStyle(DS.C.muted)247                    }248                    .card(padding: DS.S.md)249                }250                .buttonStyle(.plain)251                .contextMenu { Button(role: .destructive) { app.agentLogs.delete(log.id); reload() } label: { Label("Delete", systemImage: "trash") } }252            }253        }254        .onAppear(perform: reload)255        .sheet(item: $opened) { log in RunLogView(log: log) { app.agentLogs.delete(log.id); opened = nil; reload() } }256    }257258    private func reload() { logs = app.agentLogs.list(agentID: agent.id, limit: 200) }259}260261@ViewBuilder func outcomePill(_ outcome: AgentRunLog.Outcome) -> some View {262    switch outcome {263    case .running: Pill("Running", tone: .accent)264    case .completed: Pill("Completed", symbol: "checkmark", tone: .ok)265    case .limitReached: Pill("Limit", symbol: "exclamationmark.triangle", tone: .warn)266    case .cancelled: Pill("Cancelled", tone: .neutral)267    case .failed: Pill("Failed", symbol: "xmark", tone: .danger)268    }269}270271struct RunLogView: View {272    @Environment(\.dismiss) private var dismiss273    let log: AgentRunLog274    let onDelete: () -> Void275276    var body: some View {277        VStack(spacing: 0) {278            HStack {279                VStack(alignment: .leading, spacing: 2) {280                    Text(log.agentName).font(DS.F.headline)281                    Text(log.startedAt.formatted(date: .abbreviated, time: .standard)).font(DS.F.caption).foregroundStyle(DS.C.muted)282                }283                Spacer()284                Button("Delete", role: .destructive, action: onDelete).buttonStyle(.lcDestructive)285                Button("Done") { dismiss() }.buttonStyle(.lcPrimaryCompact)286            }287            .padding(DS.S.lg)288            Rectangle().fill(DS.C.border).frame(height: 1)289            ScrollView {290                VStack(alignment: .leading, spacing: DS.S.md) {291                    HStack(spacing: 6) { outcomePill(log.outcome); Pill(log.modelID, symbol: "cpu"); Pill(MetricFormat.seconds(log.totals.duration), symbol: "timer") }292                    if case .failed(let message) = log.outcome { InlineNotice(.error, message) }293                    Text(log.task).font(DS.F.callout).foregroundStyle(DS.C.text).textSelection(.enabled).card(padding: DS.S.md, elevated: true)294                    ForEach(log.steps, id: \.index) { step in295                        HStack(spacing: 8) { Text("STEP \(step.index)").font(DS.F.micro).kerning(0.6).foregroundStyle(DS.C.muted); Rectangle().fill(DS.C.border).frame(height: 1) }296                        if !step.text.isEmpty { MarkdownView(text: step.text).card(padding: DS.S.md) }297                        ForEach(step.toolCalls) { call in298                            ToolCallCard(name: call.name, arguments: call.arguments.serialized(pretty: true), output: call.output ?? call.denialReason, isError: call.isError || call.decision == .denied || call.decision == .rejected,299                                         isRunning: false, duration: call.duration, decision: call.decision.rawValue)300                        }301                    }302                }303                .padding(DS.S.lg)304            }305        }306        .frame(minWidth: 320, idealWidth: 640, minHeight: 420, idealHeight: 640)307        .screenBackground()308    }309}310
Files main
Menu

Theme