Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Agents/AgentStudioScreen.swift3// Description: Agent Studio: configurable local agents (tools, approvals, limits, knowledge), device-local permissions, playground and run history.4import SwiftUI5import UniformTypeIdentifiers6import LocalChatAgents7import LocalChatCore89public struct AgentStudioScreen: View {10 @Environment(AppModel.self) private var app11 private let onStartChat: ((AgentConfiguration) -> Void)?12 @State private var selectedID: UUID?13 @State private var showPermissions = false14 @State private var errorText: String?1516 public init(onStartChat: ((AgentConfiguration) -> Void)? = nil) { self.onStartChat = onStartChat }1718 private var selected: AgentConfiguration? { app.agents.first { $0.id == selectedID } }1920 public var body: some View {21 StudioSplit(showsDetail: selectedID != nil || showPermissions, backTitle: "Agents", onBack: { selectedID = nil; showPermissions = false }) {22 master23 } detail: {24 if showPermissions { AgentPermissionsPanel() }25 else if let agent = selected {26 AgentDetail(agent: agent, onStartChat: onStartChat, onDelete: { delete(agent) }).id(agent.id)27 } else {28 EmptyStateView(symbol: "sparkle", title: "Local agents", message: "An agent is a model with instructions, tools and limits. Tools only run when you enabled them, inside the folders you granted, and risky actions wait for your approval.") {29 Button("New agent") { create() }.buttonStyle(.lcPrimary)30 }31 }32 }33 }3435 private var master: some View {36 ScrollView {37 VStack(alignment: .leading, spacing: DS.S.lg) {38 ScreenTitle("Agents", subtitle: "Multi-step tasks with tools you control") {39 Button { create() } label: { Label("New", systemImage: "plus") }.buttonStyle(.lcPrimaryCompact).accessibilityLabel("New agent")40 }41 if let errorText { InlineNotice(.error, errorText) }42 Button { selectedID = nil; showPermissions = true } label: {43 HStack(spacing: 10) {44 Image(systemName: "lock.shield").foregroundStyle(DS.G.accent).font(.system(size: 16, weight: .semibold))45 VStack(alignment: .leading, spacing: 1) {46 Text("Permissions").font(DS.F.headline).foregroundStyle(DS.C.text)47 Text("\(app.agentSettings.folderPaths.count) folders granted · shell \(app.isShellPermitted && app.agentSettings.allowShell ? "allowed" : "off")").font(DS.F.caption).foregroundStyle(DS.C.muted)48 }49 Spacer(); Image(systemName: "chevron.right").font(.system(size: 11, weight: .semibold)).foregroundStyle(DS.C.muted)50 }51 .card(padding: DS.S.md, elevated: showPermissions)52 }53 .buttonStyle(.plain)54 SectionHeader("Your agents")55 if app.agents.isEmpty { Text("No agent yet.").font(DS.F.callout).foregroundStyle(DS.C.muted) }56 ForEach(app.agents) { agent in57 Button { showPermissions = false; selectedID = agent.id } label: {58 HStack(spacing: 10) {59 Image(systemName: agent.symbol).font(.system(size: 15)).foregroundStyle(DS.C.accent).frame(width: 30, height: 30).background(DS.G.soft, in: RoundedRectangle(cornerRadius: 8, style: .continuous))60 VStack(alignment: .leading, spacing: 2) {61 Text(agent.name).font(DS.F.body.weight(.medium)).foregroundStyle(DS.C.text).lineLimit(1)62 Text("\(agent.enabledTools.count) tools · \(agent.approval.title)").font(DS.F.micro).foregroundStyle(DS.C.muted).lineLimit(1)63 }64 Spacer(minLength: 0)65 }66 .card(padding: DS.S.md, elevated: selectedID == agent.id)67 }68 .buttonStyle(.plain).accessibilityLabel("Agent \(agent.name)")69 }70 }71 .padding(DS.S.lg)72 }73 .screenBackground()74 }7576 private func create() {77 let agent = AgentConfiguration(name: "New agent", instructions: "You are a careful assistant. Use tools when they help, and explain what you did.",78 modelID: app.defaultModelID, enabledTools: Array(ToolPermissions.defaultTools).sorted())79 do { let saved = try app.store.save(agent); app.reloadLists(); showPermissions = false; selectedID = saved.id }80 catch { errorText = error.localizedDescription }81 }8283 private func delete(_ agent: AgentConfiguration) {84 do { try app.store.delete(AgentConfiguration.self, id: agent.id); app.reloadLists(); selectedID = nil } catch { errorText = error.localizedDescription }85 }86}8788// MARK: Detail8990private struct AgentDetail: View {91 @Environment(AppModel.self) private var app92 let agent: AgentConfiguration93 let onStartChat: ((AgentConfiguration) -> Void)?94 let onDelete: () -> Void95 enum Tab: String, Identifiable, CaseIterable { case configure, playground, history; var id: String { rawValue } }96 @State private var tab: Tab = .configure97 @State private var confirmDelete = false9899 var body: some View {100 ScrollView {101 VStack(alignment: .leading, spacing: DS.S.lg) {102 HStack(alignment: .top, spacing: 12) {103 Image(systemName: agent.symbol).font(.system(size: 22)).foregroundStyle(DS.G.accent).frame(width: 48, height: 48).background(DS.G.soft, in: RoundedRectangle(cornerRadius: 12, style: .continuous))104 VStack(alignment: .leading, spacing: 3) {105 Text(agent.name).font(DS.F.title).foregroundStyle(DS.C.text)106 Text(app.model(agent.modelID)?.name ?? "Default model").font(DS.F.caption).foregroundStyle(DS.C.muted)107 }108 Spacer(minLength: 8)109 if let onStartChat { Button { onStartChat(agent) } label: { Label("New chat", systemImage: "bubble.left.and.text.bubble.right") }.buttonStyle(.lcPrimaryCompact).accessibilityLabel("New chat with this agent") }110 Button(role: .destructive) { confirmDelete = true } label: { Image(systemName: "trash").frame(width: 28, height: 28) }.buttonStyle(.plain).foregroundStyle(DS.C.danger).accessibilityLabel("Delete agent")111 }112 StudioTabs(tabs: Tab.allCases, title: { $0.rawValue.capitalized }, symbol: { $0 == .configure ? "slider.horizontal.3" : $0 == .playground ? "play.circle" : "clock.arrow.circlepath" }, selection: $tab)113 switch tab {114 case .configure: AgentEditor(agent: agent)115 case .playground: AgentPlayground(agent: agent)116 case .history: AgentHistory(agent: agent)117 }118 }119 .padding(DS.S.lg).frame(maxWidth: 900, alignment: .leading).frame(maxWidth: .infinity)120 }121 .screenBackground()122 .confirmationDialog("Delete “\(agent.name)”?", isPresented: $confirmDelete, titleVisibility: .visible) {123 Button("Delete agent", role: .destructive, action: onDelete)124 } message: { Text("Conversations that used this agent are kept.") }125 }126}127128// MARK: Editor129130private struct AgentEditor: View {131 @Environment(AppModel.self) private var app132 @State private var draft: AgentConfiguration133 @State private var showModels = false134 @State private var saved = false135 @State private var errorText: String?136 private let original: AgentConfiguration137138 init(agent: AgentConfiguration) { original = agent; _draft = State(initialValue: agent) }139140 private var tools: [any AgentTool] { ToolRegistry.builtIn(shellPermitted: app.isShellPermitted).allTools.filter { $0.platforms.contains(.current) } }141 private var dirty: Bool { draft != original }142143 var body: some View {144 VStack(alignment: .leading, spacing: DS.S.lg) {145 VStack(alignment: .leading, spacing: DS.S.md) {146 SectionHeader("Identity", symbol: "person.text.rectangle")147 TextField("Name", text: $draft.name).textFieldStyle(.roundedBorder).accessibilityLabel("Agent name")148 SymbolPicker(symbol: $draft.symbol)149 Text("Instructions").font(DS.F.callout.weight(.medium))150 TextEditor(text: $draft.instructions).font(DS.F.body).frame(minHeight: 110).scrollContentBackground(.hidden).padding(6)151 .background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous)).accessibilityLabel("Agent instructions")152 SettingRow("Model", detail: app.model(draft.modelID)?.name ?? "Default model of the app") { Button("Choose…") { showModels = true }.buttonStyle(.lcSecondaryCompact) }153 if app.model(draft.modelID)?.backend == .remote { InlineNotice(.warning, "Remote model: prompts, tool results and file contents the agent reads are sent to that node.") }154 else if let m = app.model(draft.modelID), !m.capabilities.contains(.tools) { InlineNotice(.info, "This model does not declare tool calling. Enable “Parse textual tool calls” in Permissions, or choose a tool-capable model.") }155 }156 .card()157158 VStack(alignment: .leading, spacing: DS.S.sm) {159 SectionHeader("Tools", subtitle: "A tool that is off can never run, whatever the model writes", symbol: "wrench.and.screwdriver")160 ForEach(tools, id: \.name) { tool in161 let unavailable = tool.risk == .execute && !app.agentSettings.allowShell162 Toggle(isOn: Binding(get: { draft.enabledTools.contains(tool.name) }, set: { on in163 if on { if !draft.enabledTools.contains(tool.name) { draft.enabledTools.append(tool.name) } } else { draft.enabledTools.removeAll { $0 == tool.name } }164 })) {165 VStack(alignment: .leading, spacing: 3) {166 HStack(spacing: 6) {167 Text(tool.name).font(DS.F.mono(12.5, weight: .semibold)).foregroundStyle(DS.C.text)168 RiskBadge(risk: tool.risk)169 if tool.alwaysRequiresApproval { Pill("Always asks", symbol: "hand.raised", tone: .warn) }170 }171 Text(tool.definition.summary).font(DS.F.caption).foregroundStyle(DS.C.muted).fixedSize(horizontal: false, vertical: true)172 if unavailable { Text("Shell is off in Permissions: this tool will not be offered to the model.").font(DS.F.micro).foregroundStyle(DS.C.warn) }173 }174 }175 .toggleStyle(.switch).padding(.vertical, 3)176 }177 if draft.enabledTools.contains(where: { ["read_file", "list_directory", "search_files", "write_file", "run_shell"].contains($0) }) && app.agentSettings.folderPaths.isEmpty {178 InlineNotice(.warning, "File tools need at least one granted folder (Permissions).")179 }180 }181 .card()182183 VStack(alignment: .leading, spacing: DS.S.sm) {184 SectionHeader("Safety", symbol: "hand.raised")185 Picker("Approval", selection: $draft.approval) { ForEach(ApprovalMode.allCases) { Text($0.title).tag($0) } }.pickerStyle(.segmented).labelsHidden()186 SettingRow("Maximum steps", detail: "\(draft.maxSteps)") { Stepper("", value: $draft.maxSteps, in: 1...40).labelsHidden() }187 SettingRow("Maximum tool calls", detail: "\(draft.maxToolCalls)") { Stepper("", value: $draft.maxToolCalls, in: 0...100).labelsHidden() }188 SettingRow("Time limit", detail: MetricFormat.duration(TimeInterval(draft.timeLimitSeconds))) { Stepper("", value: $draft.timeLimitSeconds, in: 30...3600, step: 30).labelsHidden() }189 }190 .card()191192 VStack(alignment: .leading, spacing: DS.S.sm) {193 SectionHeader("Knowledge", subtitle: "Collections the knowledge_search tool can read", symbol: "books.vertical")194 if app.collections.isEmpty { Text("No collection yet. Create one in the Knowledge Studio.").font(DS.F.caption).foregroundStyle(DS.C.muted) }195 FlowChips(items: app.collections.map { ($0.id, $0.name, $0.symbol) }, selection: Binding(get: { Set(draft.collectionIDs) }, set: { draft.collectionIDs = Array($0) }))196 }197 .card()198199 VStack(alignment: .leading, spacing: DS.S.sm) {200 SectionHeader("Generation", symbol: "dial.medium")201 SettingRow("Temperature", detail: String(format: "%.2f", draft.settings.temperature)) { Slider(value: $draft.settings.temperature, in: 0...1.5, step: 0.05).frame(maxWidth: 200) }202 SettingRow("Context window", detail: "\(draft.settings.contextLength.formatted()) tokens") {203 Picker("", selection: $draft.settings.contextLength) { ForEach([4096, 8192, 16384, 32768, 65536], id: \.self) { Text($0.formatted()).tag($0) } }.labelsHidden().fixedSize()204 }205 SettingRow("Maximum answer", detail: "\(draft.settings.maxTokens.formatted()) tokens per step") {206 Picker("", selection: $draft.settings.maxTokens) { ForEach([512, 1024, 2048, 4096, 8192], id: \.self) { Text($0.formatted()).tag($0) } }.labelsHidden().fixedSize()207 }208 Toggle("Thinking enabled", isOn: $draft.settings.reasoningEnabled).font(DS.F.body)209 }210 .card()211212 if let errorText { InlineNotice(.error, errorText) }213 HStack {214 if saved && !dirty { Label("Saved", systemImage: "checkmark.circle.fill").font(DS.F.caption).foregroundStyle(DS.C.ok) }215 Spacer()216 Button("Revert") { draft = original }.buttonStyle(.lcSecondary).disabled(!dirty)217 Button("Save") { save() }.buttonStyle(.lcPrimary).disabled(!dirty || draft.name.trimmingCharacters(in: .whitespaces).isEmpty).keyboardShortcut("s", modifiers: .command)218 }219 }220 .sheet(isPresented: $showModels) {221 ModelPickerView(selectedID: draft.modelID, allowAuto: false) { m in if let m { draft.modelID = m.id }; showModels = false }.frame(minWidth: 320, minHeight: 420)222 }223 }224225 private func save() {226 do { _ = try app.store.save(draft); saved = true; errorText = nil; app.reloadLists(); Haptics.play(.success) } catch { errorText = error.localizedDescription }227 }228}229230// MARK: Permissions (device-local)231232struct AgentPermissionsPanel: View {233 @Environment(AppModel.self) private var app234 @State private var settings = AgentLocalSettings()235 @State private var picking = false236237 var body: some View {238 ScrollView {239 VStack(alignment: .leading, spacing: DS.S.lg) {240 ScreenTitle("Permissions", subtitle: "Apply to every agent on this device. Never synchronized.")241 VStack(alignment: .leading, spacing: DS.S.sm) {242 HStack {243 SectionHeader("Granted folders", subtitle: "File tools can only read and write inside these folders", symbol: "folder.badge.gearshape")244 Button { picking = true } label: { Label("Add", systemImage: "plus") }.buttonStyle(.lcSecondaryCompact).accessibilityLabel("Grant a folder")245 }246 if settings.folderPaths.isEmpty { Text("No folder granted: file tools will refuse every path.").font(DS.F.caption).foregroundStyle(DS.C.muted) }247 ForEach(Array(settings.folderPaths.enumerated()), id: \.offset) { i, path in248 HStack(spacing: 8) {249 Image(systemName: "folder.fill").foregroundStyle(DS.C.accent)250 Text(path).font(DS.F.mono(11.5)).foregroundStyle(DS.C.text2).lineLimit(2).truncationMode(.middle).textSelection(.enabled)251 Spacer(minLength: 4)252 Button("Revoke") { settings.revoke(at: i); persist() }.buttonStyle(.lcDestructive)253 }254 .padding(.vertical, 2)255 }256 }257 .card()258259 VStack(alignment: .leading, spacing: DS.S.sm) {260 SectionHeader("Shell commands", symbol: "terminal")261 if app.isShellPermitted {262 Toggle("Allow agents to propose shell commands", isOn: Binding(get: { settings.allowShell }, set: { settings.allowShell = $0; persist() })).toggleStyle(.switch)263 InlineNotice(.warning, "Off by default. Every command still needs your approval, each time, whatever the agent's approval mode. Destructive patterns (rm -rf /, sudo, disk formatting, piping downloads into a shell…) are always refused and cannot be approved. Commands run in a granted folder with a time limit.")264 } else {265 InlineNotice(.info, "Shell execution exists only on the Mac. It is not available on iPhone and iPad.")266 }267 }268 .card()269270 VStack(alignment: .leading, spacing: DS.S.sm) {271 SectionHeader("Compatibility", symbol: "curlybraces")272 Toggle("Parse textual tool calls", isOn: Binding(get: { settings.allowTextToolCalls }, set: { settings.allowTextToolCalls = $0; persist() })).toggleStyle(.switch)273 Text("For models without native tool calling: a reply that is a single fenced JSON object {\"tool\": …, \"arguments\": …} is treated as a tool call. The same permissions and approvals apply.").font(DS.F.caption).foregroundStyle(DS.C.muted)274 }275 .card()276 }277 .padding(DS.S.lg).frame(maxWidth: 820, alignment: .leading).frame(maxWidth: .infinity)278 }279 .screenBackground()280 .onAppear { settings = app.agentSettings }281 .fileImporter(isPresented: $picking, allowedContentTypes: [.folder], allowsMultipleSelection: true) { result in282 if case .success(let urls) = result { for url in urls { settings.grant(url) }; persist() }283 }284 }285286 private func persist() { app.agentSettings = settings }287}288