OpenTalon / app · opentalon.ai / native / Sources / OpenTalon / AgentChat.swift
| 1 | import AppKit |
| 2 | import Observation |
| 3 | import SwiftUI |
| 4 | |
| 5 | @MainActor |
| 6 | @Observable |
| 7 | final class AgentChat { |
| 8 | struct Entry: Identifiable, Codable { |
| 9 | enum Kind: String, Codable { case user, reply, activity, failure } |
| 10 | var id = UUID() |
| 11 | var date = Date() |
| 12 | let kind: Kind |
| 13 | let text: String |
| 14 | } |
| 15 | |
| 16 | struct Conversation: Identifiable, Codable { |
| 17 | var id = UUID() |
| 18 | let agent: Agent |
| 19 | var entries: [Entry] |
| 20 | var title: String { entries.first { $0.kind == .user }?.text ?? "New chat" } |
| 21 | } |
| 22 | |
| 23 | private struct History: Codable { |
| 24 | var conversations: [Conversation] = [] |
| 25 | var selectedID: UUID? |
| 26 | } |
| 27 | |
| 28 | private struct Reply: Decodable { let text: String } |
| 29 | |
| 30 | static let examples = [ |
| 31 | "What are my urgent to-dos?", |
| 32 | "What’s due this week?", |
| 33 | "Which tasks are in progress?", |
| 34 | "What did I finish this week?" |
| 35 | ] |
| 36 | |
| 37 | private let historyFile: URL |
| 38 | private var history: History |
| 39 | private var historyReadable = true |
| 40 | private(set) var agent: Agent? |
| 41 | private(set) var storageError: String? |
| 42 | private(set) var busy = false |
| 43 | private(set) var stopping = false |
| 44 | var draft = "" |
| 45 | |
| 46 | init(profile: URL) { |
| 47 | historyFile = profile.appending(path: "agent-chat-history.json") |
| 48 | history = History() |
| 49 | do { |
| 50 | history = try JSONDecoder().decode(History.self, from: Data(contentsOf: historyFile)) |
| 51 | agent = selected?.agent |
| 52 | } catch let error as CocoaError where error.code == .fileReadNoSuchFile { |
| 53 | // A workspace with no saved chats starts empty. |
| 54 | } catch { |
| 55 | historyReadable = false |
| 56 | storageError = "OpenTalon couldn’t read your saved chats. New chats can still run, but won’t be saved." |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | var conversations: [Conversation] { history.conversations } |
| 61 | var selected: Conversation? { conversations.first { $0.id == history.selectedID } } |
| 62 | var entries: [Entry] { selected?.entries ?? [] } |
| 63 | var recentPrompts: [String] { |
| 64 | let prompts = conversations.flatMap(\.entries).filter { $0.kind == .user }.sorted { $0.date > $1.date } |
| 65 | var seen = Set<String>() |
| 66 | return Array(prompts.filter { seen.insert($0.text).inserted }.prefix(5).map(\.text)) |
| 67 | } |
| 68 | |
| 69 | var canSend: Bool { canSend(draft.trimmingCharacters(in: .whitespacesAndNewlines)) } |
| 70 | |
| 71 | private func canSend(_ message: String) -> Bool { |
| 72 | !busy && agent != nil && !message.isEmpty && message.utf16.count <= 4000 |
| 73 | } |
| 74 | |
| 75 | func selectAgent(_ agent: Agent) { |
| 76 | guard !busy, self.agent != agent else { return } |
| 77 | if selected != nil { newChat(keepDraft: true) } |
| 78 | self.agent = agent |
| 79 | } |
| 80 | |
| 81 | func send(_ prompt: String? = nil, using model: WorkspaceModel) { |
| 82 | let message = (prompt ?? draft).trimmingCharacters(in: .whitespacesAndNewlines) |
| 83 | guard canSend(message), let agent else { return } |
| 84 | let history = Array(entries.compactMap { entry -> [String: String]? in |
| 85 | switch entry.kind { |
| 86 | case .user: ["role": "user", "text": entry.text] |
| 87 | case .reply: ["role": "assistant", "text": entry.text] |
| 88 | case .activity: ["role": "assistant", "text": "Confirmed workspace change: \(entry.text)"] |
| 89 | case .failure: nil |
| 90 | } |
| 91 | }.suffix(16)) |
| 92 | var input: [String: Any] = ["message": message, "history": history, "agent": agent.rawValue] |
| 93 | if let project = model.board?.id { input["projectId"] = project } |
| 94 | if prompt == nil { draft = "" } |
| 95 | busy = true |
| 96 | if selected == nil { |
| 97 | var next = self.history |
| 98 | let conversation = Conversation(agent: agent, entries: [Entry(kind: .user, text: message)]) |
| 99 | next.conversations.insert(conversation, at: 0) |
| 100 | next.selectedID = conversation.id |
| 101 | save(next) |
| 102 | } else { |
| 103 | append(Entry(kind: .user, text: message)) |
| 104 | } |
| 105 | Task { |
| 106 | defer { busy = false; stopping = false } |
| 107 | do { |
| 108 | let reply: Reply = try await model.service.call("native_agent_chat", input) |
| 109 | append(Entry(kind: .reply, text: reply.text)) |
| 110 | } catch { |
| 111 | append(Entry(kind: .failure, text: stopping |
| 112 | ? "Stopped. Any changes already shown in the feed are saved." |
| 113 | : error.localizedDescription)) |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | func stop(using model: WorkspaceModel) { |
| 119 | guard busy, !stopping else { return } |
| 120 | stopping = true |
| 121 | Task { |
| 122 | do { |
| 123 | let _: EmptyResponse = try await model.service.call("native_stop_chat") |
| 124 | } catch { |
| 125 | stopping = false |
| 126 | append(Entry(kind: .failure, text: error.localizedDescription)) |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | func newChat(keepDraft: Bool = false) { |
| 132 | guard !busy else { return } |
| 133 | var next = history |
| 134 | next.selectedID = nil |
| 135 | save(next) |
| 136 | if !keepDraft { draft = "" } |
| 137 | } |
| 138 | |
| 139 | func reopen(_ conversation: Conversation) { |
| 140 | guard !busy, conversations.contains(where: { $0.id == conversation.id }) else { return } |
| 141 | var next = history |
| 142 | next.selectedID = conversation.id |
| 143 | save(next) |
| 144 | agent = conversation.agent |
| 145 | draft = "" |
| 146 | } |
| 147 | |
| 148 | func delete(_ id: UUID) { |
| 149 | guard !busy else { return } |
| 150 | var next = history |
| 151 | next.conversations.removeAll { $0.id == id } |
| 152 | if next.selectedID == id { next.selectedID = nil } |
| 153 | save(next, requireDisk: true) |
| 154 | } |
| 155 | |
| 156 | func deleteAll() { |
| 157 | guard !busy else { return } |
| 158 | save(History(), requireDisk: true) |
| 159 | } |
| 160 | |
| 161 | private func append(_ entry: Entry) { |
| 162 | guard let id = history.selectedID, |
| 163 | let index = conversations.firstIndex(where: { $0.id == id }) else { return } |
| 164 | var next = history |
| 165 | var conversation = next.conversations.remove(at: index) |
| 166 | conversation.entries.append(entry) |
| 167 | next.conversations.insert(conversation, at: 0) |
| 168 | save(next) |
| 169 | } |
| 170 | |
| 171 | private func save(_ next: History, requireDisk: Bool = false) { |
| 172 | guard historyReadable else { |
| 173 | if !requireDisk { history = next } |
| 174 | return |
| 175 | } |
| 176 | do { |
| 177 | try JSONEncoder().encode(next).write(to: historyFile, options: .atomic) |
| 178 | history = next |
| 179 | storageError = nil |
| 180 | } catch { |
| 181 | if !requireDisk { history = next } |
| 182 | storageError = requireDisk ? "Couldn’t delete saved chats. Try again." : "Couldn’t save your chats to this workspace." |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | func record(_ action: String, title: String?) { |
| 187 | let label: String |
| 188 | switch action { |
| 189 | case "create_task": label = "Added task" |
| 190 | case "update_task": label = "Updated task" |
| 191 | case "move_task": label = "Moved task" |
| 192 | case "trash_task": label = "Moved task to Trash" |
| 193 | case "restore_task": label = "Restored task" |
| 194 | case "add_task_activity", "add_task_comment": label = "Added activity" |
| 195 | case "create_board": label = "Created project" |
| 196 | case "rename_board": label = "Renamed project" |
| 197 | case "set_board_icon": label = "Updated project icon" |
| 198 | default: return |
| 199 | } |
| 200 | append(Entry(kind: .activity, text: title.map { "\(label) · \($0)" } ?? label)) |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | struct AgentChatView: View { |
| 205 | private enum Deletion { |
| 206 | case one(UUID), all |
| 207 | } |
| 208 | |
| 209 | @Environment(WorkspaceModel.self) private var model |
| 210 | @Environment(\.palette) private var palette |
| 211 | @FocusState private var focused: Bool |
| 212 | @State private var connection: Connection? |
| 213 | @State private var availableAgents: [Agent] = [] |
| 214 | @State private var showingHistory = false |
| 215 | @State private var confirmingDeletion = false |
| 216 | @State private var deletion: Deletion? |
| 217 | |
| 218 | var body: some View { |
| 219 | @Bindable var chat = model.agentChat |
| 220 | VStack(alignment: .leading, spacing: 14) { |
| 221 | SheetTitle(title: "Ask my agent") |
| 222 | HStack { |
| 223 | if let agent = chat.agent { |
| 224 | if availableAgents.contains(where: { $0 != agent }) { |
| 225 | Menu { |
| 226 | ForEach(availableAgents) { option in |
| 227 | Button { |
| 228 | chat.selectAgent(option) |
| 229 | } label: { |
| 230 | AgentBrandLabel(agent: option) |
| 231 | } |
| 232 | } |
| 233 | } label: { agentLabel(agent) } |
| 234 | .accessibilityLabel("Chat agent") |
| 235 | .accessibilityValue(agent.title) |
| 236 | .disabled(chat.busy) |
| 237 | } else { |
| 238 | agentLabel(agent) |
| 239 | } |
| 240 | } |
| 241 | Spacer() |
| 242 | Button("History", systemImage: "clock") { showingHistory.toggle() } |
| 243 | .disabled(chat.busy || chat.conversations.isEmpty) |
| 244 | .popover(isPresented: $showingHistory, arrowEdge: .bottom) { historyList(chat) } |
| 245 | Button("New chat", systemImage: "plus") { chat.newChat(); focused = true } |
| 246 | .disabled(chat.busy) |
| 247 | } |
| 248 | feed(chat) |
| 249 | if !chat.recentPrompts.isEmpty { recentPrompts(chat) } |
| 250 | if let storageError = chat.storageError { |
| 251 | Text(storageError).font(.caption).foregroundStyle(palette.danger) |
| 252 | } |
| 253 | if let connection, !connection.running { |
| 254 | HStack { |
| 255 | Text("Turn on the local agent connection to chat.").font(.caption) |
| 256 | Spacer() |
| 257 | Button("Open Settings") { model.sheet = .settings } |
| 258 | } |
| 259 | } |
| 260 | TextField("Message your agent", text: $chat.draft, axis: .vertical) |
| 261 | .textFieldStyle(.plain) |
| 262 | .lineLimit(2...5) |
| 263 | .padding(12) |
| 264 | .surface(10) |
| 265 | .focused($focused) |
| 266 | HStack { |
| 267 | if chat.draft.utf16.count > 4000 { |
| 268 | Text("Keep your message to 4,000 characters.") |
| 269 | .font(.caption).foregroundStyle(palette.danger) |
| 270 | } |
| 271 | Spacer() |
| 272 | if chat.busy { |
| 273 | Button(chat.stopping ? "Stopping…" : "Stop", systemImage: "stop.fill") { chat.stop(using: model) } |
| 274 | .disabled(chat.stopping) |
| 275 | } else { |
| 276 | Button("Send", systemImage: "arrow.up") { chat.send(using: model) } |
| 277 | .glassPrimary() |
| 278 | .keyboardShortcut(.return, modifiers: .command) |
| 279 | .disabled(!chat.canSend || !model.canUseAgents) |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | .padding(24) |
| 284 | .frame(width: 600, height: 560) |
| 285 | .task { |
| 286 | let settings: AgentSettings? = try? await model.service.call("get_agent_settings") |
| 287 | let runtimes: [String: RuntimeState]? = try? await model.service.call("agent_runtime_status") |
| 288 | availableAgents = Agent.allCases.filter { runtimes?[$0.rawValue]?.installed == true } |
| 289 | if chat.agent == nil { |
| 290 | let preferred = settings?.defaultAgent ?? .claude |
| 291 | chat.selectAgent(availableAgents.contains(preferred) ? preferred : availableAgents.first ?? preferred) |
| 292 | } |
| 293 | connection = try? await model.service.call("connection_status") |
| 294 | } |
| 295 | .alert(deletionTitle, isPresented: $confirmingDeletion) { |
| 296 | Button("Cancel", role: .cancel) { deletion = nil } |
| 297 | Button("Delete", role: .destructive) { |
| 298 | switch deletion { |
| 299 | case .one(let id): chat.delete(id) |
| 300 | case .all: chat.deleteAll() |
| 301 | case nil: break |
| 302 | } |
| 303 | deletion = nil |
| 304 | } |
| 305 | } message: { |
| 306 | Text("This removes the saved conversation history from this OpenTalon workspace.") |
| 307 | } |
| 308 | .onAppear { focused = true } |
| 309 | } |
| 310 | |
| 311 | private func agentLabel(_ agent: Agent) -> some View { |
| 312 | AgentBrandLabel(agent: agent) |
| 313 | .foregroundStyle(palette.muted) |
| 314 | .font(.subheadline) |
| 315 | } |
| 316 | |
| 317 | private func feed(_ chat: AgentChat) -> some View { |
| 318 | ScrollViewReader { proxy in |
| 319 | ThemedScrollView { |
| 320 | VStack(alignment: .leading, spacing: 12) { |
| 321 | if chat.entries.isEmpty { |
| 322 | Text("Ask about your tasks or tell your agent what to change.") |
| 323 | .foregroundStyle(palette.muted) |
| 324 | if connection?.running == true { |
| 325 | VStack(alignment: .leading, spacing: 8) { |
| 326 | ForEach(AgentChat.examples, id: \.self) { prompt in |
| 327 | promptButton(prompt, chat: chat) |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | } |
| 332 | ForEach(chat.entries) { entry in row(entry) } |
| 333 | if chat.busy { |
| 334 | ProgressView("Waiting for your agent…").controlSize(.small) |
| 335 | } |
| 336 | Color.clear.frame(height: 1).id("chat-end") |
| 337 | } |
| 338 | .padding(14) |
| 339 | .frame(maxWidth: .infinity, alignment: .leading) |
| 340 | } |
| 341 | .onChange(of: chat.entries.count) { proxy.scrollTo("chat-end", anchor: .bottom) } |
| 342 | .onAppear { proxy.scrollTo("chat-end", anchor: .bottom) } |
| 343 | } |
| 344 | .surface(12) |
| 345 | } |
| 346 | |
| 347 | private var deletionTitle: String { |
| 348 | if case .all = deletion { return "Delete all chats?" } |
| 349 | return "Delete this chat?" |
| 350 | } |
| 351 | |
| 352 | private func requestDeletion(_ kind: Deletion) { |
| 353 | deletion = kind |
| 354 | showingHistory = false |
| 355 | confirmingDeletion = true |
| 356 | } |
| 357 | |
| 358 | private func historyList(_ chat: AgentChat) -> some View { |
| 359 | VStack(alignment: .leading, spacing: 10) { |
| 360 | Text("Chat history").font(.headline) |
| 361 | ThemedScrollView { |
| 362 | VStack(alignment: .leading, spacing: 6) { |
| 363 | ForEach(chat.conversations) { conversation in |
| 364 | HStack { |
| 365 | Button { |
| 366 | chat.reopen(conversation) |
| 367 | showingHistory = false |
| 368 | } label: { |
| 369 | HStack(spacing: 8) { |
| 370 | AgentBrandIcon(agent: conversation.agent) |
| 371 | Text(conversation.title).lineLimit(1) |
| 372 | Spacer(minLength: 0) |
| 373 | if chat.selected?.id == conversation.id { |
| 374 | Image(systemName: "checkmark").accessibilityHidden(true) |
| 375 | } |
| 376 | } |
| 377 | .contentShape(Rectangle()) |
| 378 | } |
| 379 | .buttonStyle(.plain) |
| 380 | .help(conversation.title) |
| 381 | Button(role: .destructive) { requestDeletion(.one(conversation.id)) } label: { |
| 382 | Image(systemName: "trash") |
| 383 | } |
| 384 | .accessibilityLabel("Delete \(conversation.title)") |
| 385 | } |
| 386 | .padding(.vertical, 3) |
| 387 | } |
| 388 | } |
| 389 | .padding(3) |
| 390 | } |
| 391 | .frame(height: CGFloat(min(chat.conversations.count, 7) * 35)) |
| 392 | Divider() |
| 393 | Button("Delete all chats…", role: .destructive) { requestDeletion(.all) } |
| 394 | } |
| 395 | .padding(14) |
| 396 | .frame(width: 330) |
| 397 | } |
| 398 | |
| 399 | private func recentPrompts(_ chat: AgentChat) -> some View { |
| 400 | VStack(alignment: .leading, spacing: 6) { |
| 401 | Text("Recent prompts") |
| 402 | .font(.caption.weight(.semibold)) |
| 403 | .foregroundStyle(palette.muted) |
| 404 | ScrollView(.horizontal) { |
| 405 | HStack(spacing: 8) { |
| 406 | ForEach(chat.recentPrompts, id: \.self) { prompt in |
| 407 | promptButton(prompt, chat: chat) |
| 408 | } |
| 409 | } |
| 410 | .padding(.vertical, 2) |
| 411 | } |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | private func promptButton(_ prompt: String, chat: AgentChat) -> some View { |
| 416 | Button { |
| 417 | chat.send(prompt, using: model) |
| 418 | } label: { |
| 419 | Text(prompt) |
| 420 | .lineLimit(1) |
| 421 | .frame(maxWidth: 260) |
| 422 | } |
| 423 | .help(prompt) |
| 424 | .disabled(chat.busy || chat.agent == nil || connection?.running != true) |
| 425 | } |
| 426 | |
| 427 | @ViewBuilder private func row(_ entry: AgentChat.Entry) -> some View { |
| 428 | switch entry.kind { |
| 429 | case .user, .reply: |
| 430 | VStack(alignment: .leading, spacing: 4) { |
| 431 | Text(entry.kind == .user ? "You" : "Agent") |
| 432 | .font(.caption.weight(.semibold)).foregroundStyle(palette.muted) |
| 433 | Text(entry.text).textSelection(.enabled) |
| 434 | } |
| 435 | .frame(maxWidth: .infinity, alignment: .leading) |
| 436 | .padding(10) |
| 437 | .background(entry.kind == .user ? palette.active : palette.well, in: .rect(cornerRadius: 9)) |
| 438 | case .activity: |
| 439 | Label(entry.text, systemImage: "checkmark.circle") |
| 440 | .font(.caption).foregroundStyle(palette.muted) |
| 441 | case .failure: |
| 442 | Label(entry.text, systemImage: "exclamationmark.circle") |
| 443 | .font(.caption).foregroundStyle(palette.danger) |
| 444 | } |
| 445 | } |
| 446 | } |