Branchwell

OpenTalon / app / native / Sources / OpenTalon / MacTaskAssistant.swift

1import CompanionCore
2import Observation
3import SwiftUI
4
5@MainActor
6@Observable
7final class MacTaskAssistant {
8 struct Review {
9 let task: WorkItem
10 let operation: String
11 }
12
13 let history: TaskAssistantHistory
14 var draft = ""
15 var error: String?
16 var review: Review?
17 private(set) var busy = false
18 @ObservationIgnored private var generation: Task<Void, Never>?
19 @ObservationIgnored private var results: [TaskAssistantCommand: String] = [:]
20
21 static let examples = ["What are my urgent tasks?", "Which tasks are in progress?",
22 "Create a task with a plan to review my weekly goals", "What did I finish this week?"]
23
24 init(profile: URL) {
25 history = TaskAssistantHistory(file: profile.appending(path: "on-device-chat-history.json"))
26 }
27
28 func send(_ prompt: String? = nil, using model: WorkspaceModel) {
29 let message = (prompt ?? draft).trimmingCharacters(in: .whitespacesAndNewlines)
30 guard !busy, review == nil, history.canWrite, !message.isEmpty, message.utf16.count <= 2_000 else { return }
31 guard #available(macOS 26, *) else { error = "Apple Intelligence requires macOS 26 or later."; return }
32 if let reason = TaskDrafting.unavailableReason { error = reason; return }
33 error = nil
34 do { try history.append(.init(role: "user", text: message)) }
35 catch { self.error = error.localizedDescription; return }
36 draft = ""
37 let recent = (history.current?.messages.dropLast().suffix(6) ?? [])
38 .map { "\($0.role): \($0.text)" }.joined(separator: "\n")
39 busy = true
40 results = [:]
41 generation = Task {
42 defer { busy = false; generation = nil }
43 do {
44 try await model.refresh()
45 let response = try await OnDeviceTaskAssistant.respond(to: message, history: recent,
46 search: { try self.search($0, using: model) },
47 execute: { try await self.execute($0, requestedBy: message, using: model) })
48 try Task.checkCancellation()
49 if history.current?.messages.last?.text != response {
50 try history.append(.init(role: "assistant", text: response))
51 }
52 } catch is CancellationError {
53 try? history.append(.init(role: "assistant", text: "Stopped. Any changes already listed in App activity remain saved."))
54 } catch {
55 self.error = error.localizedDescription
56 }
57 }
58 }
59
60 func stop() { generation?.cancel() }
61
62 func search(_ query: String, using model: WorkspaceModel) throws -> String {
63 let query = TaskReference.normalized(in: query) ?? query.trimmingCharacters(in: .whitespacesAndNewlines)
64 let words = query.split(whereSeparator: \.isWhitespace).map(String.init)
65 .filter { !["task", "tasks", "my", "the", "all"].contains($0.lowercased()) }
66 let matches = model.tasks.filter { task in
67 guard !task.deleted else { return false }
68 if query.isEmpty { return task.archivedAt == nil && task.status != .done }
69 let fields = [task.id, task.reference, task.title, model.projectName(task.boardId), task.notes,
70 task.status.rawValue, task.priority.rawValue, task.kind.rawValue,
71 task.priority == .urgent ? "critical" : "", task.archivedAt == nil ? "" : "archived"]
72 return words.allSatisfy { word in fields.contains { $0.localizedStandardContains(word) } }
73 }.sorted { ($0.createdAt, $0.id) > ($1.createdAt, $1.id) }
74 let records: [[String: Any]] = matches.prefix(8).map { task in
75 ["id": task.id, "taskID": task.reference, "title": task.title,
76 "projectID": task.boardId, "projectName": model.projectName(task.boardId),
77 "status": task.status.rawValue, "priority": task.priority.rawValue, "issueType": task.kind.rawValue,
78 "dueDate": task.dueDate ?? "", "archived": task.archivedAt != nil,
79 "notes": matches.count == 1 ? String(task.notes.prefix(800)) : "Search by task ID to read notes.",
80 "planMarkdown": matches.count == 1 ? String((task.planMarkdown ?? "").prefix(2_000)) : "Search by task ID to read the plan.",
81 "planCharacters": (task.planMarkdown ?? "").utf16.count]
82 }
83 let data: [String: Any] = ["projects": model.boards.prefix(20).map { ["id": $0.id, "name": $0.name] },
84 "tasks": records, "matchingCount": matches.count, "shownCount": records.count]
85 return String(decoding: try JSONSerialization.data(withJSONObject: data), as: UTF8.self)
86 }
87
88 func execute(_ command: TaskAssistantCommand, requestedBy message: String, using model: WorkspaceModel) async throws -> String {
89 try Task.checkCancellation()
90 try command.validateIntent(message)
91 guard model.canLeave(), review == nil, results.count < 8 else {
92 throw Failure("Finish the current edit or review before making more changes.")
93 }
94 if let previous = results[command] { return previous }
95 let result: String
96 var taskID: String?
97 if command.operation == "createProject" {
98 let name = command.value.trimmingCharacters(in: .whitespacesAndNewlines)
99 guard !name.isEmpty, name.utf16.count <= 100, message.localizedStandardContains(name) else {
100 throw Failure("Include the new project’s name in your request.")
101 }
102 let response: BoardResponse = try await model.write("create_board", ["name": name])
103 result = "Created project \(response.board.name)."
104 } else if command.operation == "create" {
105 let title = command.value.trimmingCharacters(in: .whitespacesAndNewlines)
106 guard !title.isEmpty, title.utf16.count <= 500, let first = model.boards.first else {
107 throw Failure("A task needs a title of up to 500 characters and an available project.")
108 }
109 let projectID = command.projectID(in: model.boards.map { PhoneProject(id: $0.id, name: $0.name) }, requestedBy: message)
110 let project = model.boards.first { $0.id == projectID }
111 let personal = model.boards.first { $0.name.caseInsensitiveCompare("Personal") == .orderedSame }
112 var newProject: String?
113 if project == nil && !command.project.isEmpty {
114 guard command.project.utf16.count <= 100, message.localizedStandardContains(command.project) else {
115 throw Failure("Couldn’t match project “\(command.project)”. Use an existing project name or include the exact new name in your request.")
116 }
117 newProject = command.project
118 } else if project == nil && personal == nil { newProject = "Personal" }
119 var fields: [String: Any] = ["boardId": project?.id ?? personal?.id ?? first.id,
120 "title": title, "notes": command.notes, "status": WorkStatus.todo.rawValue,
121 "priority": TaskDrafting.capturePriority(in: message).rawValue,
122 "issueType": IssueType.inferred(from: message).rawValue]
123 if TaskPlan.requested(in: message), !command.planMarkdown.isEmpty {
124 try TaskPlan.validate(command.planMarkdown)
125 fields["planMarkdown"] = command.planMarkdown
126 }
127 let task = try await model.saveNewTask(fields, newProjectName: newProject)
128 taskID = task.id
129 result = "Created \(task.reference): \(task.title)."
130 } else {
131 guard let task = model.tasks.first(where: {
132 $0.id == command.taskID || $0.reference.caseInsensitiveCompare(command.taskID) == .orderedSame
133 }), !task.deleted else { throw Failure("That task isn’t available. Search again using its task ID.") }
134 taskID = task.id
135 var fields = task.write
136 switch command.operation {
137 case "project":
138 guard model.boards.contains(where: { $0.id == command.value }) else { throw Failure("Choose an existing project returned by search.") }
139 fields["boardId"] = command.value
140 try await model.mutate("move_task", fields)
141 case "priority":
142 guard let priority = Priority(rawValue: command.value) else { throw Failure("Choose a valid priority.") }
143 fields["priority"] = priority.rawValue
144 try await model.mutate("update_task", fields)
145 case "issueType":
146 guard let type = IssueType(rawValue: command.value) else { throw Failure("Choose Issue or Bug.") }
147 fields["issueType"] = type.rawValue
148 try await model.mutate("update_task", fields)
149 case "status":
150 guard let status = WorkStatus(rawValue: command.value), status != .sent else { throw Failure("Use Send to agent to choose an agent and model.") }
151 if status == .done && (task.status == .sent || model.workspace?.agentAssignments[task.id] != nil) {
152 review = Review(task: task, operation: "done")
153 return try record(command, "Review Mark Done for \(task.reference). Nothing has changed yet.", taskID: task.id)
154 }
155 fields["status"] = status.rawValue
156 try await model.mutate("move_task", fields)
157 case "dueDate":
158 guard command.value.isEmpty || CalendarDay.date(command.value).map(CalendarDay.key) == command.value else { throw Failure("Choose a valid YYYY-MM-DD date.") }
159 fields["dueDate"] = command.value.isEmpty ? NSNull() : command.value as Any
160 try await model.mutate("update_task", fields)
161 case "title", "notes", "definitionOfDone":
162 if command.operation == "title" && (command.value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || command.value.utf16.count > 500) {
163 throw Failure("Keep the title between 1 and 500 characters.")
164 }
165 if command.operation == "definitionOfDone" && command.value.utf16.count > 10_000 { throw Failure("Keep the definition of done to 10,000 characters.") }
166 fields[command.operation] = command.value
167 try await model.mutate("update_task", fields)
168 case "plan":
169 guard (task.planMarkdown ?? "").utf16.count <= 2_000 else { throw Failure("Open the task’s Plan editor to revise this complete, longer document.") }
170 try TaskPlan.validate(command.planMarkdown)
171 guard !command.planMarkdown.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw Failure("The proposed plan is empty. The saved plan is unchanged.") }
172 try history.append(.init(role: "plan", text: "Review the proposed plan for \(task.reference). The saved plan is unchanged.",
173 taskID: task.id, planMarkdown: command.planMarkdown, expectedMarkdown: task.planMarkdown ?? ""))
174 result = "Plan proposal ready. Open Review plan to apply and save it."
175 results[command] = result
176 return result
177 case "send":
178 try model.requireAgentConnection()
179 fields["status"] = WorkStatus.sent.rawValue
180 fields["boardId"] = task.boardId
181 fields["requestKey"] = "mac:" + UUID().uuidString
182 model.pendingSend = (name: "move_task", input: fields, title: task.title)
183 model.sheet = .send
184 return try record(command, "Send dialog opened for \(task.reference). Choose the agent, model and optional revision request, then Send.", taskID: task.id)
185 case "archive", "trash":
186 review = Review(task: task, operation: command.operation)
187 return try record(command, "Review \(command.operation) for \(task.reference). Nothing has changed yet.", taskID: task.id)
188 default: throw Failure("That action isn’t supported.")
189 }
190 result = "\(task.reference): \(command.operation) saved."
191 }
192 return try record(command, result, taskID: taskID)
193 }
194
195 private func record(_ command: TaskAssistantCommand, _ result: String, taskID: String?) throws -> String {
196 try history.append(.init(role: "action", text: result, taskID: taskID))
197 results[command] = result
198 return result
199 }
200
201 func confirmReview(using model: WorkspaceModel) async throws {
202 guard let review else { return }
203 guard model.tasks.first(where: { $0.id == review.task.id })?.revision == review.task.revision else {
204 throw Failure("This task changed. Cancel this review and ask again using its current details.")
205 }
206 if review.operation == "done" {
207 try await model.mutate("force_complete_task", ["id": review.task.id])
208 } else {
209 try await model.mutate("companion_organize_task", ["id": review.task.id, "destination": review.operation])
210 }
211 try history.append(.init(role: "action", text: "\(review.task.reference): \(review.operation) confirmed and saved.", taskID: review.task.id))
212 self.review = nil
213 }
214
215 struct Failure: LocalizedError {
216 let text: String
217 init(_ text: String) { self.text = text }
218 var errorDescription: String? { text }
219 }
220}
221
222struct MacTaskAssistantView: View {
223 @Environment(WorkspaceModel.self) private var model
224 @Environment(\.palette) private var palette
225 @State private var deletion: UUID?
226 @State private var deletingAll = false
227 @State private var confirmingDeletion = false
228 @State private var proposal: TaskAssistantHistory.Message?
229 @State private var reviewing = false
230 @FocusState private var focused: Bool
231 private var assistant: MacTaskAssistant { model.taskAssistant }
232
233 var body: some View {
234 @Bindable var assistant = assistant
235 VStack(alignment: .leading, spacing: 16) {
236 HStack {
237 Button("Back", systemImage: "chevron.left") { assistant.stop(); model.navigate(.dashboard) }
238 Text("Ask OpenTalon").font(palette.display(28)).accessibilityAddTraits(.isHeader)
239 Spacer()
240 Menu("History") {
241 ForEach(assistant.history.chats) { chat in
242 Button(chat.title) { attempt { try assistant.history.select(chat.id) } }
243 }
244 Divider()
245 Button("Delete this chat…") { deletion = assistant.history.current?.id; deletingAll = false; confirmingDeletion = true }
246 .disabled(assistant.history.current == nil)
247 Button("Delete all chat history…") { deletingAll = true; confirmingDeletion = true }
248 .disabled(assistant.history.chats.isEmpty && assistant.history.error == nil)
249 }
250 .disabled(assistant.busy || assistant.review != nil)
251 Button("New chat", systemImage: "plus") { attempt { try assistant.history.newChat(); assistant.draft = "" } }
252 .disabled(assistant.busy || assistant.review != nil || !assistant.history.canWrite)
253 }
254 Label("Apple Intelligence · On this device", systemImage: "sparkles")
255 .font(.caption).foregroundStyle(palette.actionAccent)
256 ScrollViewReader { scroll in
257 ThemedScrollView {
258 LazyVStack(alignment: .leading, spacing: 14) {
259 if (assistant.history.current?.messages ?? []).isEmpty {
260 Text("Manage your tasks by chatting").font(.title3.bold())
261 Text("Find tasks, change priorities, move work between projects, or draft a plan.")
262 .foregroundStyle(palette.muted)
263 ForEach(MacTaskAssistant.examples, id: \.self) { example in
264 Button(example) { assistant.send(example, using: model) }
265 .disabled(TaskDrafting.unavailableReason != nil || !assistant.history.canWrite)
266 }
267 }
268 ForEach(assistant.history.current?.messages ?? []) { entry in
269 message(entry).id(entry.id)
270 }
271 if assistant.busy { ProgressView("Working on this device…") }
272 Color.clear.frame(height: 1).id("end")
273 }.padding(2)
274 }
275 .onChange(of: assistant.history.current?.messages.count) { _, _ in scroll.scrollTo("end", anchor: .bottom) }
276 }
277 if let review = assistant.review {
278 VStack(alignment: .leading, spacing: 12) {
279 Text("\(review.operation == "done" ? "Mark Done" : review.operation.capitalized): \(review.task.title)").fontWeight(.semibold)
280 Text("Any active agent run will stop. Your task remains recoverable.").font(.caption).foregroundStyle(palette.muted)
281 HStack {
282 Button("Cancel") { assistant.review = nil }
283 Button("Confirm \(review.operation == "done" ? "Mark Done" : review.operation.capitalized)") {
284 reviewing = true
285 Task { defer { reviewing = false }; do { try await assistant.confirmReview(using: model) } catch { assistant.error = error.localizedDescription } }
286 }
287 }.disabled(assistant.busy || reviewing)
288 }.padding(16).frame(maxWidth: .infinity, alignment: .leading).surface(12)
289 }
290 if let error = assistant.error ?? assistant.history.error {
291 HStack(alignment: .top, spacing: 12) {
292 Image(systemName: "exclamationmark.bubble").foregroundStyle(palette.actionAccent)
293 VStack(alignment: .leading, spacing: 5) {
294 Text("Request needs attention").font(.callout.weight(.semibold))
295 Text(error).font(.callout).foregroundStyle(palette.muted).textSelection(.enabled)
296 if let request = assistant.history.current?.messages.last(where: { $0.role == "user" })?.text {
297 Button("Edit request") { assistant.draft = request; assistant.error = nil; focused = true }
298 }
299 }
300 Spacer()
301 Button("Dismiss") { assistant.error = nil }
302 .disabled(assistant.error == nil)
303 }.padding(14).frame(maxWidth: .infinity, alignment: .leading).surface(12)
304 }
305 if let reason = TaskDrafting.unavailableReason { Text(reason).font(.callout).foregroundStyle(palette.muted) }
306 TextField("Ask about your tasks or request an edit", text: $assistant.draft, axis: .vertical)
307 .textFieldStyle(.plain).lineLimit(2...5).padding(12).surface(12).focused($focused)
308 .accessibilityIdentifier("assistant.message")
309 HStack {
310 Text("Your tasks stay on this device for AI processing.").font(.caption).foregroundStyle(palette.muted)
311 Spacer()
312 if assistant.busy { Button("Stop") { assistant.stop() } }
313 else {
314 Button("Send", systemImage: "arrow.up") { assistant.send(using: model) }
315 .disabled(assistant.draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || assistant.draft.utf16.count > 2_000 ||
316 TaskDrafting.unavailableReason != nil || !assistant.history.canWrite || assistant.review != nil)
317 .keyboardShortcut(.return, modifiers: .command).accessibilityIdentifier("assistant.send")
318 }
319 }
320 }
321 .padding(26).frame(maxWidth: 980).frame(maxWidth: .infinity).background(palette.canvas)
322 .onDisappear { assistant.stop() }
323 .alert(deletingAll ? "Delete all chat history?" : "Delete this chat?", isPresented: $confirmingDeletion) {
324 Button("Cancel", role: .cancel) {}
325 Button("Delete", role: .destructive) {
326 attempt { if deletingAll { try assistant.history.deleteAll() } else if let deletion { try assistant.history.deleteChat(deletion) } }
327 }
328 } message: { Text("Only this workspace’s on-device chats are deleted. Your tasks and plans stay unchanged.") }
329 .sheet(item: $proposal) { entry in
330 if let id = entry.taskID, let task = model.tasks.first(where: { $0.id == id }),
331 let original = entry.expectedMarkdown, let candidate = entry.planMarkdown {
332 PlanDocumentView(markdown: original, proposal: candidate, reference: task.reference,
333 context: task.title + "\n" + task.notes, colors: OpenTalonColors(theme: palette.theme)) { markdown in
334 try await model.mutate("set_task_plan", ["id": id, "expectedMarkdown": original, "markdown": markdown])
335 try assistant.history.append(.init(role: "action", text: "\(task.reference): plan saved.", taskID: id))
336 }.frame(width: 680, height: 720)
337 }
338 }
339 }
340
341 private func attempt(_ action: () throws -> Void) {
342 do { try action() } catch { assistant.error = error.localizedDescription }
343 }
344
345 private func message(_ entry: TaskAssistantHistory.Message) -> some View {
346 VStack(alignment: .leading, spacing: 8) {
347 Text(entry.role == "user" ? "You" : entry.role == "action" ? "App activity" : "OpenTalon")
348 .font(.caption.bold()).foregroundStyle(palette.muted)
349 Text(entry.text).textSelection(.enabled).accessibilityIdentifier("assistantMessage-" + entry.role)
350 if let id = entry.taskID, let task = model.tasks.first(where: { $0.id == id && !$0.deleted }) {
351 HStack {
352 Button("Open task", systemImage: "arrow.right") { model.navigate(.board(task.boardId)); model.select(task) }
353 if entry.planMarkdown != nil {
354 Button("Review plan") {
355 if (task.planMarkdown ?? "") == entry.expectedMarkdown { proposal = entry }
356 else { assistant.error = "The saved plan changed. Ask for a fresh revision; this proposal remains in your chat." }
357 }
358 }
359 }
360 }
361 }.padding(16).frame(maxWidth: .infinity, alignment: .leading).surface(12)
362 }
363}