Branchwell

OpenTalon / app / native / Sources / OpenTalon / TaskComments.swift

1import AppKit
2import CompanionCore
3import ImageIO
4import SwiftUI
5import UniformTypeIdentifiers
6
7private struct CommentsResponse: Decodable { let comments: [WorkComment] }
8private struct CommentCheck: Decodable { let queued: Int }
9
10struct TaskComments: View {
11 @Environment(WorkspaceModel.self) private var model
12 @Environment(\.palette) private var palette
13 let item: WorkItem
14 @Binding var dirty: Bool
15 @State private var comments: [WorkComment] = []
16 @State private var text = ""
17 @State private var images: [DraftImage] = []
18 @State private var posting = false
19 @State private var feedback: String?
20 @State private var requestKey = UUID().uuidString
21 @State private var zoom: DraftImage?
22 @State private var linkedComment: WorkComment?
23 @State private var composing = false
24 @FocusState private var commentFocused: Bool
25
26 private var assigned: Bool { model.workspace?.agentAssignments[item.id] != nil }
27 private var hasDraft: Bool { !text.isEmpty || !images.isEmpty }
28
29 var body: some View {
30 VStack(alignment: .leading, spacing: 9) {
31 HStack {
32 Text(TaskRevisionRequestCopy.heading).font(.system(size: 13, weight: .semibold))
33 Spacer()
34 if assigned && item.status == .working && model.canUseAgents {
35 Button("Check now") {
36 model.perform {
37 let result: CommentCheck = try await model.service.call("check_task_comments")
38 feedback = result.queued == 0 ? "No pending revision requests." : "Revision requests queued."
39 await load()
40 }
41 }.buttonStyle(.link).font(.caption)
42 }
43 }
44 if comments.isEmpty {
45 Text("No revision requests yet.").font(.caption).foregroundStyle(palette.muted)
46 }
47 ForEach(comments) { comment in commentCard(comment) }
48 if composing {
49 composer
50 } else {
51 Button {
52 composing = true
53 } label: {
54 Label(TaskRevisionRequestCopy.add, systemImage: "plus")
55 }
56 .buttonStyle(GlassActionStyle())
57 }
58 Text(assigned && item.status == .working && model.canUseAgents
59 ? "OpenTalon sends requests to the assigned agent at its next five-minute check."
60 : "Requests stay with this task for the next agent run.")
61 .font(.caption).foregroundStyle(palette.muted)
62 if let feedback { Text(feedback).font(.caption).foregroundStyle(palette.muted) }
63 }
64 .disabled(posting)
65 .task(id: model.workspace?.revision) { await load() }
66 .onChange(of: text) { _, _ in draftChanged() }
67 .onChange(of: images.map(\.id)) { _, _ in draftChanged() }
68 .onChange(of: posting) { _, _ in dirty = hasDraft || posting }
69 .sheet(item: $linkedComment) { comment in
70 TaskActivityPanel(taskID: item.id, commentID: comment.id)
71 }
72 .sheet(item: $zoom) { image in
73 VStack(alignment: .trailing) {
74 HStack {
75 Text(image.name).lineLimit(1)
76 Spacer()
77 Button("Done") { zoom = nil }
78 }
79 if let full = image.image {
80 Image(nsImage: full).resizable().scaledToFit().frame(maxHeight: 520)
81 }
82 }
83 .padding(18).frame(width: 680)
84 }
85 }
86
87 private var composer: some View {
88 VStack(alignment: .leading, spacing: 9) {
89 TextEditor(text: $text)
90 .scrollContentBackground(.hidden)
91 .overlay(alignment: .topLeading) {
92 if text.isEmpty {
93 Text(TaskRevisionRequestCopy.example)
94 .foregroundStyle(palette.muted)
95 .padding(.leading, 5)
96 .allowsHitTesting(false)
97 .accessibilityHidden(true)
98 }
99 }
100 .padding(5)
101 .frame(height: 68)
102 .surface()
103 .accessibilityLabel(TaskRevisionRequestCopy.field)
104 .accessibilityHint(TaskRevisionRequestCopy.example)
105 .focused($commentFocused)
106 .onAppear { commentFocused = true }
107 if !images.isEmpty {
108 HStack {
109 ForEach(images) { image in
110 VStack(spacing: 3) {
111 if let thumbnail = image.image {
112 Image(nsImage: thumbnail).resizable().scaledToFit().frame(width: 63, height: 43)
113 }
114 Button("Remove", role: .destructive) { images.removeAll { $0.id == image.id } }
115 .buttonStyle(.link).font(.caption2)
116 }
117 }
118 }
119 }
120 HStack(spacing: 5) {
121 IconButton(symbol: "paperclip", label: "Attach screenshots", action: attach)
122 .disabled(images.count >= 3)
123 IconButton(symbol: "clipboard", label: "Paste screenshot", action: paste)
124 .disabled(images.count >= 3)
125 Button(hasDraft ? "Discard" : "Cancel") { closeComposer() }
126 .buttonStyle(.link).font(.caption)
127 Spacer(minLength: 0)
128 Button(posting ? "Sending…" : TaskRevisionRequestCopy.send, action: post)
129 .disabled(text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && images.isEmpty)
130 }
131 }
132 }
133
134 private func commentCard(_ comment: WorkComment) -> some View {
135 VStack(alignment: .leading, spacing: 7) {
136 HStack(spacing: 6) {
137 Text(comment.agent?.title ?? "You").fontWeight(.semibold)
138 Text(Self.dateLabel(comment.createdAt)).foregroundStyle(palette.muted)
139 }
140 .font(.caption2)
141 if !comment.text.isEmpty { Text(comment.text).font(.system(size: 12)).textSelection(.enabled) }
142 if !comment.images.isEmpty {
143 HStack(spacing: 6) {
144 ForEach(comment.images) { image in
145 SavedScreenshot(image: image) { zoom = $0 }
146 }
147 }
148 }
149 if comment.actedOnAt != nil, comment.activityID != nil {
150 Button("Acted on · View activity", systemImage: "checkmark.circle") { linkedComment = comment }
151 .buttonStyle(.link).font(.caption).foregroundStyle(palette.accent)
152 .accessibilityIdentifier("commentActivity-" + comment.id)
153 } else if comment.delivery != "local" {
154 Text(comment.delivery.replacingOccurrences(of: "-", with: " ").capitalized)
155 .font(.caption2).foregroundStyle(palette.muted)
156 }
157 if comment.delivery == "needs-review" {
158 Button("Retry delivery") {
159 model.perform {
160 try await model.mutate("retry_task_comment", ["id": comment.id])
161 await load()
162 }
163 }.font(.caption)
164 }
165 }
166 .frame(maxWidth: .infinity, alignment: .leading)
167 .padding(9)
168 .surface()
169 }
170
171 private static func dateLabel(_ value: String) -> String {
172 let formatter = ISO8601DateFormatter()
173 formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
174 return formatter.date(from: value)?.formatted(date: .abbreviated, time: .shortened) ?? value
175 }
176
177 private func load() async {
178 do {
179 let result: CommentsResponse = try await model.service.call("list_task_comments", ["taskId": item.id])
180 if !Task.isCancelled { comments = result.comments.filter { $0.source == "user" } }
181 } catch { if !Task.isCancelled { feedback = error.localizedDescription } }
182 }
183
184 private func draftChanged() {
185 dirty = hasDraft || posting
186 requestKey = UUID().uuidString
187 }
188
189 private func closeComposer() {
190 composing = false
191 commentFocused = false
192 text = ""
193 images = []
194 dirty = false
195 requestKey = UUID().uuidString
196 }
197
198 private func attach() {
199 model.perform {
200 let panel = NSOpenPanel()
201 panel.title = "Attach screenshots to your revision request"
202 panel.allowsMultipleSelection = true
203 panel.allowedContentTypes = [.png, .jpeg, .webP]
204 guard await panel.begin() == .OK else { return }
205 guard panel.urls.count <= 3 - images.count else {
206 throw attachmentFailure("Attach up to three screenshots per revision request.")
207 }
208 let files = panel.urls
209 let prepared = try await Task.detached {
210 try files.map { url -> DraftImage in
211 let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
212 guard size <= 25 * 1024 * 1024 else {
213 throw attachmentFailure("Choose screenshots smaller than 25 MB.")
214 }
215 return try prepareImage(Data(contentsOf: url), name: url.lastPathComponent)
216 }
217 }.value
218 guard prepared.count <= 3 - images.count else { return }
219 images.append(contentsOf: prepared)
220 }
221 }
222
223 private func paste() {
224 do {
225 let board = NSPasteboard.general
226 guard let data = board.data(forType: .png) ?? board.data(forType: .tiff) else {
227 throw attachmentFailure("Copy a screenshot to the clipboard first.")
228 }
229 images.append(try prepareImage(data, name: "Clipboard screenshot.png"))
230 } catch { feedback = error.localizedDescription }
231 }
232
233 private func post() {
234 guard !posting else { return }
235 posting = true
236 dirty = true
237 let fields: [String: Any] = [
238 "taskId": item.id, "text": text, "images": images.map(\.fields),
239 "notifyAgent": assigned && model.canUseAgents, "requestKey": requestKey
240 ]
241 Task {
242 defer { posting = false; dirty = hasDraft }
243 do {
244 try await model.mutate("add_user_comment", fields)
245 closeComposer()
246 feedback = assigned && item.status == .working ? "Revision request saved for the next agent check." : "Revision request saved for the next agent run."
247 await load()
248 } catch { feedback = error.localizedDescription }
249 }
250 }
251}
252
253private struct SavedScreenshot: View {
254 @Environment(WorkspaceModel.self) private var model
255 let image: CommentImage
256 var open: (DraftImage) -> Void
257 @State private var loaded: DraftImage?
258 @State private var failed = false
259 var body: some View {
260 Button {
261 if let loaded { open(loaded) }
262 } label: {
263 if let bitmap = loaded?.image {
264 Image(nsImage: bitmap).resizable().scaledToFit().frame(width: 72, height: 48)
265 } else {
266 Image(systemName: failed ? "exclamationmark.triangle" : "photo").frame(width: 72, height: 48)
267 }
268 }
269 .buttonStyle(.plain)
270 .disabled(loaded == nil)
271 .help(image.name)
272 .accessibilityLabel("Enlarge \(image.name)")
273 .task(id: image.id) {
274 do { loaded = try await model.service.call("read_comment_image", ["imageId": image.id]) }
275 catch { failed = true }
276 }
277 }
278}
279
280private func attachmentFailure(_ message: String) -> ServiceFailure {
281 ServiceFailure(code: "IMAGE", message: message)
282}
283
284private func prepareImage(_ data: Data, name: String) throws -> DraftImage {
285 let options: [CFString: Any] = [
286 kCGImageSourceCreateThumbnailFromImageAlways: true,
287 kCGImageSourceCreateThumbnailWithTransform: true,
288 kCGImageSourceThumbnailMaxPixelSize: 5000,
289 ]
290 guard let source = CGImageSourceCreateWithData(data as CFData, nil),
291 let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else {
292 throw attachmentFailure("Choose a PNG, JPEG, or WebP screenshot.")
293 }
294 let limit = 2 * 1024 * 1024
295 let bitmap = NSBitmapImageRep(cgImage: image)
296 var bytes = bitmap.representation(using: .png, properties: [:])
297 var ext = "png"
298 if (bytes?.count ?? Int.max) > limit {
299 bytes = bitmap.representation(using: .jpeg, properties: [.compressionFactor: 0.85])
300 ext = "jpg"
301 }
302 guard let bytes, bytes.count <= limit else {
303 throw attachmentFailure("This screenshot is too large. Crop it or choose a smaller image.")
304 }
305 let stem = String((name as NSString).deletingPathExtension.prefix(190))
306 return DraftImage(name: "\(stem).\(ext)", mimeType: ext == "png" ? "image/png" : "image/jpeg",
307 data: bytes.base64EncodedString())
308}