Branchwell

OpenTalon / app / native / Sources / OpenTalon / TaskDetails.swift

1import AppKit
2import CompanionCore
3import SwiftUI
4import UniformTypeIdentifiers
5
6private struct TaskDraft: Equatable {
7 var title: String
8 var notes: String
9 var criteria: String
10 var priority: Priority
11 var issueType: IssueType
12 var due: String?
13
14 init(_ item: WorkItem) {
15 title = item.title
16 notes = item.notes
17 criteria = item.definitionOfDone
18 priority = item.priority
19 issueType = item.kind
20 due = item.dueDate
21 }
22
23 func changes(from saved: Self) -> [String: Any] {
24 var fields: [String: Any] = [:]
25 if title != saved.title { fields["title"] = title }
26 if notes != saved.notes { fields["notes"] = notes }
27 if criteria != saved.criteria { fields["definitionOfDone"] = criteria }
28 if issueType != saved.issueType { fields["issueType"] = issueType.rawValue }
29 if priority != saved.priority { fields["priority"] = priority.rawValue }
30 if due != saved.due { fields["dueDate"] = due.map { $0 as Any } ?? NSNull() }
31 return fields
32 }
33}
34
35private struct DueDateControl: View {
36 @Environment(\.palette) private var palette
37 @Binding var due: String?
38 @State private var date = Date()
39 @State private var showingCalendar = false
40
41 var body: some View {
42 Button {
43 date = due.flatMap(CalendarDay.date) ?? .now
44 showingCalendar = true
45 } label: {
46 Label {
47 Text(due.map(CalendarDay.label) ?? "Set due date")
48 } icon: {
49 Image(systemName: "calendar").foregroundStyle(palette.actionAccent)
50 }
51 }
52 .accessibilityLabel("Due date")
53 .accessibilityValue(due.map(CalendarDay.label) ?? "No due date")
54 .accessibilityHint("Opens a calendar")
55 .popover(isPresented: $showingCalendar, arrowEdge: .bottom) {
56 VStack(alignment: .trailing, spacing: 10) {
57 DatePicker("Due date", selection: $date, displayedComponents: .date)
58 .datePickerStyle(.graphical)
59 .labelsHidden()
60 .accessibilityLabel("Due date")
61 HStack {
62 Button("Cancel") { showingCalendar = false }
63 Button("Save") {
64 due = CalendarDay.key(date)
65 showingCalendar = false
66 }
67 .keyboardShortcut(.defaultAction)
68 }
69 }
70 .frame(width: 238)
71 .padding(13)
72 .background(palette.panel)
73 .onExitCommand { showingCalendar = false }
74 }
75 }
76}
77
78struct TaskDetails: View {
79 private struct PlanEdit: Identifiable {
80 let id: String
81 let markdown: String
82 let reference: String
83 let context: String
84 }
85 @State private var planEdit: PlanEdit?
86 @State private var showHistory = false
87 @State private var confirmForceComplete = false
88 @Environment(WorkspaceModel.self) private var model
89 @Environment(\.palette) private var palette
90 let item: WorkItem
91 @State private var draft: TaskDraft
92 @State private var saved: TaskDraft
93 @State private var revision: Int
94 @State private var saving = false
95 @State private var commentDirty = false
96 @State private var error: String?
97 @State private var conflict: WorkItem?
98 @State private var autosave: Task<Void, Never>?
99 @State private var copiedTaskID: UUID?
100
101 init(item: WorkItem) {
102 self.item = item
103 _draft = State(initialValue: TaskDraft(item))
104 _saved = State(initialValue: TaskDraft(item))
105 _revision = State(initialValue: item.revision)
106 }
107
108 private var dirty: Bool { draft != saved }
109 private var valid: Bool { !draft.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
110
111 var body: some View {
112 VStack(alignment: .leading, spacing: 0) {
113 HStack {
114 Text("Task details").font(.system(size: 12, weight: .semibold)).foregroundStyle(palette.muted)
115 Spacer()
116 Button(copiedTaskID == nil ? "Copy task ID" : "Copied",
117 systemImage: copiedTaskID == nil ? "doc.on.doc" : "checkmark") {
118 let pasteboard = NSPasteboard.general
119 pasteboard.clearContents()
120 if pasteboard.setString(item.reference, forType: .string) { copiedTaskID = UUID() }
121 }
122 .help("Copy the full task ID to the clipboard")
123 IconButton(symbol: "xmark", label: "Close task details") {
124 if model.canLeave() { model.selection = nil }
125 }
126 }
127 .padding(.horizontal, 17)
128 .padding(.vertical, 9)
129 Rectangle().fill(palette.line).frame(height: 1)
130 ThemedScrollView(track: palette.panel) {
131 VStack(alignment: .leading, spacing: 16) {
132 editFields
133 VStack(alignment: .leading, spacing: 9) {
134 Text("Plan").font(.headline)
135 Button {
136 planEdit = PlanEdit(id: item.id, markdown: item.planMarkdown ?? "", reference: item.reference,
137 context: "\(draft.title)\n\(draft.notes)\nDefinition of done: \(draft.criteria)")
138 } label: {
139 Label((item.planMarkdown ?? "").isEmpty ? "Create plan" : TaskPlan.filename(reference: item.reference), systemImage: "doc.text")
140 }
141 .help((item.planMarkdown ?? "").isEmpty ? "Create a Markdown plan for this task" : "Open the attached Markdown plan")
142 .accessibilityIdentifier("taskPlan")
143 if !(item.planMarkdown ?? "").isEmpty {
144 Text("Markdown document · Open to preview or edit")
145 .font(.caption).foregroundStyle(palette.muted)
146 }
147 }
148 DesktopTaskFiles(taskID: item.id)
149 if let error {
150 Text(error).font(.caption).foregroundStyle(palette.danger)
151 }
152 if let conflict {
153 HStack {
154 Button("Use saved text") { load(conflict) }
155 Button("Keep my edits") {
156 revision = conflict.revision
157 saved = TaskDraft(conflict)
158 self.conflict = nil
159 error = nil
160 beginSave()
161 }
162 }
163 } else if dirty || saving {
164 HStack {
165 Button(saving ? "Saving…" : "Save now") { beginSave() }
166 .disabled(saving || !valid)
167 Button("Use saved text") { load(item) }.disabled(saving)
168 }
169 } else {
170 Label("Saved", systemImage: "checkmark").font(.caption).foregroundStyle(palette.muted)
171 }
172 if let run = model.workspace?.agentRuns.first(where: { $0.taskId == item.id }) {
173 RunDetails(run: run, taskRevision: item.revision)
174 }
175 if item.status != .done, item.status == .sent || model.workspace?.agentAssignments[item.id] != nil {
176 Button("Mark Done Anyway") { confirmForceComplete = true }
177 .disabled(dirty || saving || commentDirty)
178 }
179 Button("View revision history", systemImage: "clock.arrow.circlepath") { showHistory = true }
180 .disabled(dirty || saving).accessibilityIdentifier("taskHistory")
181 TaskActivitySection(taskID: item.id)
182 TaskComments(item: item, dirty: $commentDirty)
183 Divider()
184 HStack {
185 Button("Move to Trash", role: .destructive) { model.trash(item) }
186 .disabled(dirty || saving || commentDirty)
187 Spacer()
188 }
189 }
190 .padding(17)
191 }
192 }
193 .background(palette.panel)
194 .sheet(isPresented: $showHistory) {
195 MacTaskHistoryView(itemID: item.id).frame(minWidth: 600, minHeight: 650)
196 }
197 .sheet(item: $planEdit) { edit in
198 PlanDocumentView(markdown: edit.markdown,
199 draft: UserDefaults.standard.string(forKey: "planDraft." + edit.id),
200 reference: edit.reference, context: edit.context,
201 colors: OpenTalonColors(theme: palette.theme)) { markdown in
202 try await model.mutate("set_task_plan", ["id": edit.id, "expectedMarkdown": edit.markdown, "markdown": markdown])
203 } persistDraft: { markdown in
204 UserDefaults.standard.set(markdown, forKey: "planDraft." + edit.id)
205 }
206 .frame(width: 680, height: 720)
207 }
208 .alert("Mark this task done anyway?", isPresented: $confirmForceComplete) {
209 Button("Cancel", role: .cancel) {}
210 Button("Mark Done") {
211 model.perform { try await model.mutate("force_complete_task", ["id": item.id]) }
212 }
213 } message: {
214 Text("This stops any active agent run and moves the task to Done.")
215 }
216 .task(id: copiedTaskID) {
217 guard let copiedTaskID else { return }
218 do { try await Task.sleep(for: .seconds(2)) } catch { return }
219 if self.copiedTaskID == copiedTaskID { self.copiedTaskID = nil }
220 }
221 .onChange(of: draft) { _, _ in
222 syncDirty()
223 scheduleSave()
224 }
225 .onChange(of: saving) { _, _ in syncDirty() }
226 .onChange(of: commentDirty) { _, _ in syncDirty() }
227 .onChange(of: item.revision) { _, _ in
228 guard !saving, revision != item.revision else { return }
229 if !dirty || TaskDraft(item) == saved { revision = item.revision }
230 if !dirty || TaskDraft(item) == draft { load(item) }
231 else if TaskDraft(item) != saved {
232 conflict = item
233 error = "This task changed while you were editing it."
234 }
235 }
236 .onDisappear {
237 autosave?.cancel()
238 model.draftDirty = false
239 }
240 }
241
242 private var editFields: some View {
243 VStack(alignment: .leading, spacing: 14) {
244 TextField("Task title", text: $draft.title, axis: .vertical)
245 .lineLimit(1...3).font(.system(size: 22, weight: .semibold))
246 .textFieldStyle(.plain)
247 .accessibilityLabel("Task title")
248 VStack(alignment: .leading, spacing: 4) {
249 Text("Task ID").font(.caption.weight(.semibold))
250 Text(item.reference)
251 .font(.system(.caption, design: .monospaced))
252 .textSelection(.enabled)
253 .fixedSize(horizontal: false, vertical: true)
254 }
255 .foregroundStyle(palette.muted)
256 Grid(alignment: .leading, horizontalSpacing: 9, verticalSpacing: 10) {
257 GridRow {
258 property("Status")
259 BoardDropdown(selection: Binding(get: { item.status }, set: { model.move(item, to: $0) }),
260 title: "Status", symbol: item.status.symbol, choices: model.editableStatuses,
261 compact: true, label: \.rawValue)
262 .disabled(dirty || saving || commentDirty)
263 }
264 GridRow {
265 property("Project")
266 BoardDropdown(selection: Binding(get: { item.boardId }, set: { model.move(item, to: item.status, board: $0) }),
267 title: "Project", symbol: "folder", choices: model.boards.map(\.id),
268 compact: true, label: model.projectName)
269 .disabled(dirty || saving || commentDirty)
270 }
271 GridRow {
272 property("Issue type")
273 BoardDropdown(selection: $draft.issueType, title: "Issue type", symbol: draft.issueType.symbol,
274 choices: IssueType.allCases, compact: true, label: \.rawValue)
275 }
276 GridRow {
277 property("Priority")
278 BoardDropdown(selection: $draft.priority, title: "Priority", symbol: "flag",
279 choices: Priority.allCases, compact: true, label: \.label)
280 }
281 GridRow {
282 property("Due date")
283 HStack(spacing: 5) {
284 DueDateControl(due: $draft.due)
285 if draft.due != nil {
286 IconButton(symbol: "xmark", label: "Clear due date") { draft.due = nil }
287 }
288 }
289 }
290 GridRow {
291 property("Order")
292 if item.status == .todo {
293 Text("Urgent first, newest first")
294 .font(.caption).foregroundStyle(palette.muted)
295 } else {
296 HStack(spacing: 5) {
297 let siblings = model.tasks.filter { !$0.deleted && $0.boardId == item.boardId && $0.status == item.status }
298 .sorted { $0.position < $1.position }
299 let index = siblings.firstIndex { $0.id == item.id } ?? 0
300 IconButton(symbol: "arrow.up", label: "Move task up") {
301 guard index > 0 else { return }
302 model.move(item, to: item.status, anchor: siblings[index - 1].id)
303 }.disabled(index == 0 || dirty || commentDirty)
304 IconButton(symbol: "arrow.down", label: "Move task down") {
305 guard index + 1 < siblings.count else { return }
306 model.move(item, to: item.status, anchor: siblings[index + 1].id, before: false)
307 }.disabled(index + 1 >= siblings.count || dirty || commentDirty)
308 }
309 }
310 }
311 }
312 Divider()
313 editor("Notes", text: $draft.notes, height: 130)
314 editor("Definition of done", text: $draft.criteria, height: 68)
315 }
316 .disabled(saving)
317 }
318
319 private func property(_ title: String) -> some View {
320 Text(title).foregroundStyle(palette.muted).font(.system(size: 12))
321 }
322
323 private func editor(_ title: String, text: Binding<String>, height: CGFloat) -> some View {
324 VStack(alignment: .leading, spacing: 7) {
325 Text(title).font(.system(size: 12, weight: .semibold))
326 TextEditor(text: text)
327 .font(.system(size: 12))
328 .scrollContentBackground(.hidden)
329 .padding(5)
330 .frame(height: height)
331 .surface()
332 .accessibilityLabel(title)
333 }
334 }
335
336 private func syncDirty() {
337 model.draftDirty = dirty || saving || commentDirty
338 if !model.draftDirty && model.banner == "Save or discard your task changes before leaving." {
339 model.banner = nil
340 }
341 }
342
343 private func load(_ latest: WorkItem) {
344 autosave?.cancel()
345 draft = TaskDraft(latest)
346 saved = draft
347 revision = latest.revision
348 conflict = nil
349 error = nil
350 syncDirty()
351 }
352
353 private func scheduleSave() {
354 autosave?.cancel()
355 guard dirty, valid, !saving, conflict == nil, error == nil else { return }
356 autosave = Task {
357 do { try await Task.sleep(for: .milliseconds(350)) }
358 catch { return }
359 beginSave()
360 }
361 }
362
363 private func beginSave() {
364 autosave?.cancel()
365 guard dirty, valid, !saving, conflict == nil else { return }
366 var fields = draft.changes(from: saved)
367 fields["id"] = item.id
368 fields["expectedRevision"] = revision
369 saving = true
370 error = nil
371 syncDirty()
372 Task {
373 defer { saving = false; syncDirty() }
374 do {
375 let result: ItemResponse = try await model.write("update_task", fields)
376 load(result.task)
377 } catch let failure as ServiceFailure {
378 conflict = failure.current
379 error = failure.message
380 } catch let failure {
381 error = failure.localizedDescription
382 }
383 }
384 }
385}
386
387private struct DesktopTaskFiles: View {
388 private struct FileList: Decodable { let attachments: [TaskFile] }
389 private struct Attached: Decodable { let attachment: TaskFile }
390 private struct Contents: Decodable { let base64: Data }
391
392 @Environment(WorkspaceModel.self) private var model
393 @Environment(\.palette) private var palette
394 @State private var attachments: [TaskFile] = []
395 @State private var chooseFile = false
396 @State private var adding = false
397 @State private var opening: String?
398 @State private var fileError: String?
399 let taskID: String
400
401 var body: some View {
402 VStack(alignment: .leading, spacing: 9) {
403 Text("Files").font(.headline)
404 ForEach(attachments) { file in
405 Button {
406 Task { await open(file) }
407 } label: {
408 Label {
409 Text(file.name)
410 Text(file.sizeLabel).font(.caption).foregroundStyle(palette.muted)
411 } icon: {
412 Image(systemName: opening == file.id ? "arrow.down.circle" : "doc")
413 }
414 }
415 .disabled(opening != nil)
416 .accessibilityIdentifier("taskFile-\(file.name)")
417 }
418 Button(adding ? "Attaching…" : "Add file…", systemImage: "paperclip") { chooseFile = true }
419 .disabled(adding)
420 .accessibilityIdentifier("addTaskFile")
421 if let fileError { Text(fileError).font(.caption).foregroundStyle(palette.danger) }
422 }
423 .frame(maxWidth: .infinity, alignment: .leading)
424 .task(id: model.workspace?.revision) {
425 do { try await load() }
426 catch where !Task.isCancelled { fileError = error.localizedDescription }
427 catch {}
428 }
429 .fileImporter(isPresented: $chooseFile, allowedContentTypes: [.data]) { result in
430 Task { await attach(result) }
431 }
432 }
433
434 private func load() async throws {
435 let result: FileList = try await model.service.call("list_task_files", ["taskId": taskID])
436 guard !Task.isCancelled else { return }
437 attachments = result.attachments
438 }
439
440 private func attach(_ result: Result<URL, Error>) async {
441 adding = true
442 fileError = nil
443 defer { adding = false }
444 do {
445 let file = try await TaskFilePayload.importFile(result.get())
446 let saved: Attached = try await model.service.call("attach_task_file", [
447 "taskId": taskID, "name": file.name, "contentType": file.contentType,
448 "base64": file.bytes.base64EncodedString(), "requestKey": "mac:" + UUID().uuidString,
449 ])
450 if !attachments.contains(saved.attachment) { attachments.append(saved.attachment) }
451 } catch { fileError = error.localizedDescription }
452 }
453
454 private func open(_ file: TaskFile) async {
455 opening = file.id
456 fileError = nil
457 defer { opening = nil }
458 do {
459 let contents: Contents = try await model.service.call("read_task_file", ["taskId": taskID, "fileId": file.id])
460 let directory = URL.cachesDirectory.appending(path: "OpenTalon/TaskFiles", directoryHint: .isDirectory)
461 let url = try file.preview(contents.base64, in: directory)
462 guard NSWorkspace.shared.open(url) else {
463 fileError = "No app can open this file. Use Finder to choose an app."
464 NSWorkspace.shared.activateFileViewerSelecting([url])
465 return
466 }
467 } catch { fileError = error.localizedDescription }
468 }
469}
470
471private struct RunDetails: View {
472 @Environment(WorkspaceModel.self) private var model
473 @Environment(\.palette) private var palette
474 let run: AgentRun
475 let taskRevision: Int
476 @State private var stopping = false
477 @State private var opening = false
478 @State private var resumeCommand: String?
479 @State private var copied = false
480 @State private var sessionInUse = false
481 @State private var recovery: TaskAgentRecovery.Availability?
482 @State private var showContinuation = false
483 @State private var continuation = ""
484 @State private var queuing = false
485
486 var body: some View {
487 VStack(alignment: .leading, spacing: 9) {
488 HStack {
489 AgentBrandLabel(agent: run.agent).fontWeight(.semibold)
490 Spacer()
491 Text(run.statusLabel).foregroundStyle(palette.muted)
492 }
493 if !run.summary.isEmpty { Text(run.summary).textSelection(.enabled) }
494 if let approval = run.approval {
495 Divider()
496 Text(approval.title).fontWeight(.semibold)
497 ThemedScrollView(track: palette.panel) { Text(approval.details).font(.system(size: 11, design: .monospaced)).textSelection(.enabled) }
498 .frame(maxHeight: 135)
499 HStack {
500 Button("Deny") { answer(approval, allow: false) }
501 if approval.canApprove && model.canUseAgents { Button("Allow once") { answer(approval, allow: true) } }
502 }
503 }
504 HStack {
505 if run.threadId != nil && run.agent.opensConversations && (run.agent == .codex || !run.active) {
506 Button(action: openConversation) {
507 AgentBrandLabel(agent: run.agent, title: run.agent == .claude ? "Open in Claude" : "Open conversation")
508 }
509 .disabled(opening)
510 }
511 if run.active {
512 Button("Stop run", role: .destructive) { stopping = true }
513 }
514 if model.canUseAgents && recovery?.actions.contains("queue") == true {
515 Button(recovery?.requiresReopen == true ? "Reopen and resume agent" : "Resume agent") {
516 continuation = ""
517 showContinuation = true
518 }
519 }
520 }
521 if run.agent == .claude && run.threadId != nil && run.active {
522 Text("Stop this run before opening it in Claude.")
523 .font(.caption).foregroundStyle(palette.muted)
524 }
525 }
526 .font(.system(size: 12))
527 .padding(12)
528 .surface()
529 .confirmationDialog("Stop this agent run?", isPresented: $stopping, titleVisibility: .visible) {
530 Button("Stop run", role: .destructive) { perform("stop_agent_run") }
531 }
532 .task(id: "\(run.id):\(run.state):\(taskRevision):\(model.canUseAgents)") {
533 recovery = nil
534 if model.canUseAgents && !run.active {
535 let result: TaskAgentRecovery? = try? await model.service.call("get_task_agent_run", ["taskId": run.taskId])
536 if result?.run?.id == run.id { recovery = result?.recovery }
537 }
538 }
539 .sheet(isPresented: $showContinuation) {
540 VStack(alignment: .leading, spacing: 14) {
541 SheetTitle(title: "Resume agent") { showContinuation = false }
542 Text("Finish any open turn in the provider before resuming. Your instructions will go to the existing conversation.")
543 .foregroundStyle(palette.muted)
544 TextEditor(text: $continuation).font(.body).frame(minHeight: 112).surface(9)
545 .accessibilityLabel("Continuation instructions")
546 HStack {
547 Spacer()
548 Button("Cancel") { showContinuation = false }.keyboardShortcut(.cancelAction)
549 Button(queuing ? "Queuing…" : "Resume") { queueContinuation() }
550 .glassPrimary()
551 .disabled(queuing || continuation.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || continuation.count > 10_000)
552 }
553 }
554 .padding(24)
555 .frame(width: 510)
556 .foregroundStyle(palette.text)
557 .buttonStyle(GlassActionStyle())
558 .background(palette.panel)
559 }
560 .sheet(isPresented: Binding(
561 get: { resumeCommand != nil },
562 set: { if !$0 { resumeCommand = nil } }
563 )) {
564 if let resumeCommand {
565 VStack(alignment: .leading, spacing: 14) {
566 SheetTitle(title: "Resume in Claude") { self.resumeCommand = nil }
567 Text("Open the Claude CLI in the folder below and paste the command into its prompt.")
568 .foregroundStyle(palette.muted)
569 .fixedSize(horizontal: false, vertical: true)
570 Text(run.workingFolder)
571 .font(.callout)
572 .textSelection(.enabled)
573 Text(resumeCommand)
574 .font(.system(.callout, design: .monospaced))
575 .textSelection(.enabled)
576 .frame(maxWidth: .infinity, alignment: .leading)
577 .padding(12)
578 .surface(9)
579 if sessionInUse {
580 Text("This session is already open. Run `/desktop` in that session to move it into Claude Desktop.")
581 .font(.callout)
582 .foregroundStyle(palette.muted)
583 }
584 HStack {
585 Spacer()
586 Button("Done") { self.resumeCommand = nil }
587 .keyboardShortcut(.cancelAction)
588 Button(copied ? "Copied" : "Copy Command",
589 systemImage: copied ? "checkmark" : "doc.on.doc") {
590 let pasteboard = NSPasteboard.general
591 pasteboard.clearContents()
592 copied = pasteboard.setString(resumeCommand, forType: .string)
593 }
594 .glassPrimary()
595 }
596 }
597 .padding(24)
598 .frame(width: 510)
599 .foregroundStyle(palette.text)
600 .buttonStyle(GlassActionStyle())
601 .background(palette.panel)
602 }
603 }
604 }
605
606 private func queueContinuation() {
607 queuing = true
608 model.perform {
609 defer { queuing = false }
610 let _: EmptyResponse = try await model.service.call("recover_agent_run", [
611 "taskId": run.taskId, "expectedRunId": run.id, "expectedRevision": taskRevision,
612 "mode": "queue", "message": continuation, "reopenClosed": recovery?.requiresReopen == true,
613 "requestKey": UUID().uuidString
614 ])
615 showContinuation = false
616 try await model.refresh()
617 }
618 }
619
620 private func openConversation() {
621 opening = true
622 model.perform {
623 defer { opening = false }
624 do {
625 let _: EmptyResponse = try await model.service.call("open_agent_thread", ["runId": run.id])
626 } catch let failure as ServiceFailure where run.agent == .claude
627 && ["THREAD_OPEN_FAILED", "THREAD_IN_USE"].contains(failure.code) {
628 guard let threadId = run.threadId else { throw failure }
629 copied = false
630 sessionInUse = failure.code == "THREAD_IN_USE"
631 resumeCommand = "/resume \(threadId)"
632 }
633 }
634 }
635
636 private func perform(_ name: String, fields: [String: Any] = [:]) {
637 model.perform {
638 var input = fields
639 input["runId"] = run.id
640 let _: EmptyResponse = try await model.service.call(name, input)
641 try await model.refresh()
642 }
643 }
644
645 private func answer(_ approval: AgentRun.Approval, allow: Bool) {
646 perform("answer_agent_approval", fields: ["approvalId": approval.id, "allow": allow])
647 }
648}
649
650
651private struct MacTaskHistoryView: View {
652 @Environment(WorkspaceModel.self) private var model
653 @Environment(\.palette) private var palette
654 @State private var page: TaskHistoryPage?
655 let itemID: String
656
657 var body: some View {
658 TaskHistoryView(page: page, colors: OpenTalonColors(theme: palette.theme)) { before in
659 var input: [String: Any] = ["id": itemID, "limit": 20]
660 input["beforeVersion"] = before
661 let result: TaskHistoryPage = try await model.service.call("get_task_history", input)
662 page = before == nil ? result : page?.merging(result) ?? result
663 } restore: { entry in
664 let current: ItemResponse = try await model.service.call("get_task", ["id": itemID])
665 guard current.task.revision == page?.revision else {
666 throw ServiceFailure(code: "CONFLICT", message: "This task changed. Close history and review the latest task before restoring.")
667 }
668 try await model.mutate("restore_task_revision", ["id": itemID, "historyID": entry.id,
669 "expectedRevision": current.task.revision])
670 page = try await model.service.call("get_task_history", ["id": itemID, "limit": 20])
671 return "Revision restored. Newer versions remain in history."
672 }
673 }
674}