Open History to see the last commit
1import SwiftUI
2import UIKit
3
4public struct FeatureReviewView: View {
5 @SwiftUI.Environment(\.scenePhase) private var scenePhase
6 let client: any FeatureClient
7 let threadID: String
8 /// Comments are ordinary turns. They go through the same queue as the
9 /// composer so an offline comment is kept and retried, not dropped.
10 let sendMessage: (FeatureMessageSubmission) async -> Bool
11
12 @State private var review: FeatureReview?
13 @State private var isLoading = true
14 @State private var errorMessage: String?
15
16 public init(
17 client: any FeatureClient,
18 threadID: String,
19 sendMessage: @escaping (FeatureMessageSubmission) async -> Bool
20 ) {
21 self.client = client
22 self.threadID = threadID
23 self.sendMessage = sendMessage
24 }
25
26 public var body: some View {
27 Group {
28 if isLoading, review == nil {
29 ProgressView("Loading changes…")
30 .frame(maxWidth: .infinity, maxHeight: .infinity)
31 } else if let review {
32 reviewList(review)
33 } else {
34 ContentUnavailableView(
35 "Review unavailable",
36 systemImage: "doc.text.magnifyingglass",
37 description: Text(errorMessage ?? "Changes could not be loaded.")
38 )
39 }
40 }
41 .background(T3Colors.background)
42 .navigationTitle("Review")
43 .navigationBarTitleDisplayMode(.inline)
44 .toolbar {
45 ToolbarItem(placement: .topBarTrailing) {
46 Button {
47 Task { await load() }
48 } label: {
49 Image(systemName: "arrow.clockwise")
50 }
51 .accessibilityLabel("Reload changes")
52 }
53 }
54 .task { await load() }
55 .onChange(of: scenePhase) { _, phase in
56 guard phase == .active, review != nil, !isLoading else { return }
57 Task { await load() }
58 }
59 }
60
61 private func reviewList(_ review: FeatureReview) -> some View {
62 List {
63 Section {
64 HStack {
65 VStack(alignment: .leading, spacing: 3) {
66 Text(review.title)
67 .font(T3Typography.navigationTitle)
68 if let base = review.baseReference {
69 Text(base)
70 .font(T3Typography.tool)
71 .foregroundStyle(T3Colors.textSecondary)
72 }
73 }
74 Spacer()
75 FeatureDiffStatsLabel(additions: review.additions, deletions: review.deletions)
76 }
77 .padding(.vertical, 3)
78
79 if review.isTruncated {
80 Label("Large diff, showing a partial result", systemImage: "exclamationmark.triangle")
81 .font(T3Typography.supporting)
82 .foregroundStyle(.orange)
83 }
84 }
85
86 Section("\(review.files.count) changed \(review.files.count == 1 ? "file" : "files")") {
87 if review.files.isEmpty {
88 ContentUnavailableView(
89 "No changes",
90 systemImage: "checkmark.circle",
91 description: Text("The working tree is clean.")
92 )
93 .listRowBackground(Color.clear)
94 }
95 ForEach(review.files) { file in
96 NavigationLink {
97 FeatureDiffView(
98 client: client,
99 threadID: threadID,
100 file: file,
101 sendMessage: sendMessage
102 )
103 } label: {
104 FeatureReviewFileRow(file: file)
105 }
106 }
107 }
108 }
109 .listStyle(.insetGrouped)
110 .scrollContentBackground(.hidden)
111 .refreshable { await load() }
112 }
113
114 private func load() async {
115 isLoading = true
116 defer { isLoading = false }
117 do {
118 review = try await client.loadReview(threadID: threadID)
119 errorMessage = nil
120 } catch {
121 errorMessage = error.localizedDescription
122 }
123 }
124}
125
126private struct FeatureReviewFileRow: View {
127 let file: FeatureReviewFile
128
129 var body: some View {
130 HStack(spacing: 10) {
131 Text(changeLabel)
132 .font(.caption2.monospaced().weight(.bold))
133 .foregroundStyle(changeColor)
134 .frame(width: 18)
135 VStack(alignment: .leading, spacing: 2) {
136 Text(fileName)
137 .font(T3Typography.homeTitle)
138 .lineLimit(1)
139 if !directory.isEmpty {
140 Text(directory)
141 .font(T3Typography.supporting)
142 .foregroundStyle(T3Colors.textSecondary)
143 .lineLimit(1)
144 }
145 }
146 Spacer()
147 FeatureDiffStatsLabel(additions: file.additions, deletions: file.deletions)
148 }
149 .padding(.vertical, 3)
150 .accessibilityElement(children: .combine)
151 }
152
153 private var fileName: String {
154 file.path.split(separator: "/").last.map(String.init) ?? file.path
155 }
156
157 private var directory: String {
158 let components = file.path.split(separator: "/")
159 return components.dropLast().joined(separator: "/")
160 }
161
162 private var changeLabel: String {
163 switch file.change {
164 case .added: "A"
165 case .modified: "M"
166 case .deleted: "D"
167 case .renamed: "R"
168 case .binary: "B"
169 }
170 }
171
172 private var changeColor: Color {
173 switch file.change {
174 case .added: .green
175 case .deleted: .red
176 case .renamed: .blue
177 case .modified, .binary: .orange
178 }
179 }
180}
181
182struct FeatureDiffStatsLabel: View {
183 let additions: Int
184 let deletions: Int
185
186 var body: some View {
187 HStack(spacing: 5) {
188 if additions > 0 {
189 Text("+\(additions)").foregroundStyle(.green)
190 }
191 if deletions > 0 {
192 Text("−\(deletions)").foregroundStyle(.red)
193 }
194 }
195 .font(T3Typography.tool.monospacedDigit().weight(.medium))
196 .accessibilityElement(children: .combine)
197 .accessibilityLabel("\(additions) additions, \(deletions) deletions")
198 }
199}
200
201private struct FeatureDiffView: View {
202 let client: any FeatureClient
203 let threadID: String
204 let file: FeatureReviewFile
205 let sendMessage: (FeatureMessageSubmission) async -> Bool
206
207 @State private var renderedLines: [FeatureDiffLine]
208 @State private var isHydrating = false
209 @State private var selectedLine: FeatureReviewLineSelection?
210 @State private var isCommenting = false
211 @State private var comment = ""
212 @State private var isSending = false
213 @State private var commentError: String?
214 @FocusState private var isCommentFocused: Bool
215
216 init(
217 client: any FeatureClient,
218 threadID: String,
219 file: FeatureReviewFile,
220 sendMessage: @escaping (FeatureMessageSubmission) async -> Bool
221 ) {
222 self.client = client
223 self.threadID = threadID
224 self.file = file
225 self.sendMessage = sendMessage
226 _renderedLines = State(initialValue: file.lines)
227 }
228
229 var body: some View {
230 Group {
231 if renderedLines.isEmpty, isHydrating {
232 ProgressView("Loading full diff…")
233 .frame(maxWidth: .infinity, maxHeight: .infinity)
234 } else if renderedLines.isEmpty {
235 ContentUnavailableView(
236 file.change == .binary ? "Binary file" : "Diff unavailable",
237 systemImage: file.change == .binary ? "doc.richtext" : "doc.text.magnifyingglass",
238 description: Text("No line-level preview is available.")
239 )
240 } else {
241 GeometryReader { proxy in
242 ScrollView([.horizontal, .vertical]) {
243 LazyVStack(alignment: .leading, spacing: 0) {
244 ForEach(renderedLines) { line in
245 FeatureDiffLineRow(
246 line: line,
247 isSelected: selection(for: line) == selectedLine,
248 minimumWidth: proxy.size.width
249 ) {
250 guard let selection = selection(for: line) else { return }
251 selectedLine = selection
252 openCommentComposer()
253 }
254 }
255 }
256 .frame(minWidth: proxy.size.width, alignment: .leading)
257 .padding(.vertical, 8)
258 }
259 }
260 }
261 }
262 .background(T3Colors.background)
263 .navigationTitle(file.path.split(separator: "/").last.map(String.init) ?? file.path)
264 .navigationBarTitleDisplayMode(.inline)
265 .toolbar {
266 ToolbarItem(placement: .topBarTrailing) {
267 Button {
268 selectedLine = nil
269 openCommentComposer()
270 } label: {
271 Image(systemName: "text.bubble")
272 }
273 .accessibilityLabel("Add file review comment")
274 }
275 }
276 .safeAreaInset(edge: .bottom, spacing: 0) {
277 if isCommenting {
278 commentComposer
279 }
280 }
281 .task(id: file.id) { await hydrate() }
282 }
283
284 private var commentComposer: some View {
285 VStack(alignment: .leading, spacing: 10) {
286 HStack(spacing: 8) {
287 VStack(alignment: .leading, spacing: 2) {
288 Text("REVIEW COMMENT")
289 .font(T3Typography.eyebrow)
290 .foregroundStyle(T3Colors.textTertiary)
291 Text(commentLocation)
292 .font(T3Typography.supporting)
293 .foregroundStyle(T3Colors.textSecondary)
294 .lineLimit(1)
295 }
296 Spacer(minLength: 8)
297 Button {
298 isCommenting = false
299 isCommentFocused = false
300 commentError = nil
301 } label: {
302 Image(systemName: "xmark")
303 .frame(width: T3Metrics.minimumTapTarget, height: T3Metrics.minimumTapTarget)
304 }
305 .buttonStyle(.plain)
306 .foregroundStyle(T3Colors.textSecondary)
307 .accessibilityLabel("Close review comment")
308 }
309
310 TextField(
311 "What should change?",
312 text: $comment,
313 axis: .vertical
314 )
315 .font(T3Typography.composer)
316 .lineLimit(2 ... 6)
317 .focused($isCommentFocused)
318 .padding(.horizontal, 12)
319 .padding(.vertical, 10)
320 .background(T3Colors.input)
321 .clipShape(RoundedRectangle(cornerRadius: 10))
322 .overlay {
323 RoundedRectangle(cornerRadius: 10)
324 .stroke(T3Colors.border, lineWidth: 1)
325 }
326
327 if let commentError {
328 Text(commentError)
329 .font(T3Typography.supporting)
330 .foregroundStyle(T3Colors.danger)
331 }
332
333 HStack(spacing: 10) {
334 Button {
335 UIPasteboard.general.string = reviewDraft.prompt
336 } label: {
337 Label("Copy prompt", systemImage: "doc.on.doc")
338 .frame(maxWidth: .infinity, minHeight: 42)
339 }
340 .buttonStyle(.plain)
341 .foregroundStyle(T3Colors.textSecondary)
342 .background(T3Colors.surfaceRaised)
343 .clipShape(RoundedRectangle(cornerRadius: 9))
344 .disabled(trimmedComment.isEmpty)
345
346 Button {
347 sendComment()
348 } label: {
349 HStack(spacing: 7) {
350 if isSending {
351 ProgressView()
352 .controlSize(.small)
353 } else {
354 Image(systemName: "arrow.up")
355 }
356 Text("Send to agent")
357 }
358 .frame(maxWidth: .infinity, minHeight: 42)
359 }
360 .buttonStyle(.plain)
361 .foregroundStyle(.white)
362 .background(T3Colors.accent)
363 .clipShape(RoundedRectangle(cornerRadius: 9))
364 .disabled(trimmedComment.isEmpty || isSending)
365 }
366 .font(T3Typography.control)
367 }
368 .padding(.horizontal, 14)
369 .padding(.top, 10)
370 .padding(.bottom, 8)
371 .background(T3Colors.surface)
372 .overlay(alignment: .top) {
373 Rectangle()
374 .fill(T3Colors.separator)
375 .frame(height: 1)
376 }
377 }
378
379 private var trimmedComment: String {
380 comment.trimmingCharacters(in: .whitespacesAndNewlines)
381 }
382
383 private var reviewDraft: FeatureReviewCommentDraft {
384 FeatureReviewCommentDraft(filePath: file.path, line: selectedLine, body: comment)
385 }
386
387 private var commentLocation: String {
388 guard let selectedLine else { return file.path }
389 return "\(file.path) · \(selectedLine.side.rawValue) line \(selectedLine.line)"
390 }
391
392 private func selection(for line: FeatureDiffLine) -> FeatureReviewLineSelection? {
393 if let newLine = line.newLine {
394 return FeatureReviewLineSelection(side: .new, line: newLine)
395 }
396 if let oldLine = line.oldLine {
397 return FeatureReviewLineSelection(side: .old, line: oldLine)
398 }
399 return nil
400 }
401
402 private func openCommentComposer() {
403 isCommenting = true
404 commentError = nil
405 Task { @MainActor in
406 await Task.yield()
407 isCommentFocused = true
408 }
409 }
410
411 private func hydrate() async {
412 isHydrating = true
413 defer { isHydrating = false }
414 guard let contents = try? await client.loadReviewFileContents(
415 threadID: threadID,
416 file: file
417 ) else {
418 return
419 }
420 renderedLines = FeatureFullDiffHydrator.lines(for: file, contents: contents)
421 }
422
423 private func sendComment() {
424 guard !trimmedComment.isEmpty, !isSending else { return }
425 let record = reviewDraft.contextRecord(lines: renderedLines)
426 let prompt = reviewDraft.submissionText(contextRecord: record)
427 isSending = true
428 commentError = nil
429 Task {
430 let sent = await sendMessage(
431 FeatureMessageSubmission(threadID: threadID, text: prompt, selection: nil, context: .init(records: [record]))
432 )
433 if sent {
434 comment = ""
435 selectedLine = nil
436 isCommenting = false
437 isCommentFocused = false
438 } else {
439 commentError = "Could not send the comment."
440 }
441 isSending = false
442 }
443 }
444}
445
446private struct FeatureDiffLineRow: View {
447 let line: FeatureDiffLine
448 let isSelected: Bool
449 let minimumWidth: CGFloat
450 let select: () -> Void
451
452 var body: some View {
453 HStack(alignment: .top, spacing: 0) {
454 if line.kind == .hunk {
455 Text(line.text)
456 .foregroundStyle(.blue)
457 .padding(.horizontal, 10)
458 .fixedSize(horizontal: true, vertical: false)
459 } else {
460 lineNumber(line.oldLine)
461 lineNumber(line.newLine)
462 Text(prefix)
463 .foregroundStyle(prefixColor)
464 .frame(width: 18)
465 diffText
466 .fixedSize(horizontal: true, vertical: false)
467 .textSelection(.enabled)
468 .padding(.trailing, 12)
469 }
470 }
471 .font(T3Typography.code)
472 .t3CodeTextSize()
473 .fixedSize(horizontal: true, vertical: false)
474 .frame(
475 minWidth: minimumWidth,
476 minHeight: line.kind == .hunk ? 30 : 22,
477 alignment: .leading
478 )
479 .background(isSelected ? T3Colors.accent.opacity(0.14) : background)
480 .overlay(alignment: .leading) {
481 if isSelected {
482 Rectangle()
483 .fill(T3Colors.accent)
484 .frame(width: 2)
485 }
486 }
487 .contentShape(Rectangle())
488 .onTapGesture(perform: select)
489 .accessibilityAction(named: "Add review comment", select)
490 }
491
492 private func lineNumber(_ value: Int?) -> some View {
493 Text(value.map(String.init) ?? "")
494 .foregroundStyle(.tertiary)
495 .frame(width: 48, alignment: .trailing)
496 .padding(.trailing, 7)
497 .accessibilityHidden(true)
498 }
499
500 private var prefix: String {
501 switch line.kind {
502 case .addition: "+"
503 case .deletion: "−"
504 case .context, .hunk: " "
505 }
506 }
507
508 private var prefixColor: Color {
509 switch line.kind {
510 case .addition: .green
511 case .deletion: .red
512 case .context, .hunk: .secondary
513 }
514 }
515
516 @ViewBuilder
517 private var diffText: some View {
518 if let spans = line.spans, !spans.isEmpty {
519 HStack(spacing: 0) {
520 ForEach(spans.indices, id: \.self) { index in
521 let span = spans[index]
522 Text(verbatim: span.text.isEmpty ? " " : span.text)
523 .foregroundStyle(.primary)
524 .fontWeight(span.kind == .changed ? .semibold : .regular)
525 .background(span.kind == .changed ? changedSpanBackground : Color.clear)
526 }
527 }
528 } else {
529 Text(line.text.isEmpty ? " " : line.text)
530 .foregroundStyle(.primary)
531 }
532 }
533
534 private var changedSpanBackground: Color {
535 switch line.kind {
536 case .addition: Color.green.opacity(0.28)
537 case .deletion: Color.red.opacity(0.28)
538 case .context, .hunk: Color.clear
539 }
540 }
541
542 private var background: Color {
543 switch line.kind {
544 case .addition: Color.green.opacity(0.11)
545 case .deletion: Color.red.opacity(0.11)
546 case .hunk: Color.blue.opacity(0.08)
547 case .context: Color.clear
548 }
549 }
550}