Open History to see the last commit
1import SwiftUI
2
3struct FeatureComposerApprovalPanel: View {
4 let approval: FeatureApproval
5 let position: Int
6 let total: Int
7 let isResponding: Bool
8 let onDecision: (FeatureApprovalDecision) -> Void
9 let onCancelTurn: () -> Void
10
11 var body: some View {
12 VStack(spacing: 0) {
13 VStack(alignment: .leading, spacing: 0) {
14 HStack(spacing: 8) {
15 Text("Pending approval")
16 .font(T3Typography.eyebrow)
17 .tracking(1.3)
18 .textCase(.uppercase)
19 .foregroundStyle(T3Colors.warning)
20
21 Spacer()
22
23 if total > 1 {
24 Text("\(position)/\(total)")
25 .font(T3Typography.supportingStrong.monospacedDigit())
26 .foregroundStyle(T3Colors.textTertiary)
27 }
28 }
29
30 Text(approval.appName ?? approval.title)
31 .font(T3Typography.navigationTitle)
32 .foregroundStyle(T3Colors.textPrimary)
33 .padding(.top, 5)
34
35 VStack(alignment: .leading, spacing: 5) {
36 Text(detailLabel)
37 .font(T3Typography.supportingStrong)
38 .tracking(0.7)
39 .textCase(.uppercase)
40 .foregroundStyle(T3Colors.textTertiary)
41
42 // A patch or command can be a whole diff. Scroll it so
43 // the decision buttons below never leave the screen.
44 ScrollView {
45 Text(approval.detail)
46 .font(
47 approval.kind == .command
48 ? T3Typography.code
49 : T3Typography.threadBody
50 )
51 .foregroundStyle(T3Colors.textPrimary.opacity(0.92))
52 .lineSpacing(3)
53 .fixedSize(horizontal: false, vertical: true)
54 .textSelection(.enabled)
55 .t3CodeTextSize(approval.kind == .command)
56 .frame(maxWidth: .infinity, alignment: .leading)
57 }
58 .frame(maxHeight: 220)
59 }
60 .padding(10)
61 .frame(maxWidth: .infinity, alignment: .leading)
62 .background(T3Colors.input, in: RoundedRectangle(cornerRadius: 10))
63 .overlay {
64 RoundedRectangle(cornerRadius: 10)
65 .stroke(T3Colors.border, lineWidth: 1)
66 }
67 .padding(.top, 9)
68 }
69 .padding(.horizontal, 15)
70 .padding(.vertical, 12)
71 .background(T3Colors.subtle)
72
73 Divider().overlay(T3Colors.separator)
74
75 VStack(spacing: 9) {
76 LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 7) {
77 ForEach(positiveOptions) { option in
78 approvalButton(
79 option.label,
80 background: option.decision == .allowOnce ? T3Colors.accent : .clear,
81 border: option.decision == .allowOnce ? .clear : T3Colors.border,
82 foreground: option.decision == .allowOnce ? .white : T3Colors.textPrimary,
83 action: { onDecision(option.decision) }
84 )
85 }
86 }
87
88 HStack(spacing: 26) {
89 ForEach(negativeOptions) { option in
90 Button(option.label, role: .destructive) {
91 onDecision(option.decision)
92 }
93 .foregroundStyle(T3Colors.danger)
94 .frame(minHeight: T3Metrics.minimumTapTarget)
95 }
96
97 Button("Cancel turn", action: onCancelTurn)
98 .foregroundStyle(T3Colors.textTertiary)
99 .frame(minHeight: T3Metrics.minimumTapTarget)
100 }
101 .font(T3Typography.supportingStrong)
102 .buttonStyle(.plain)
103 .frame(maxWidth: .infinity)
104 }
105 .padding(.horizontal, 10)
106 .padding(.top, 10)
107 .padding(.bottom, 11)
108 }
109 .disabled(isResponding)
110 .opacity(isResponding ? 0.56 : 1)
111 .accessibilityElement(children: .contain)
112 }
113
114 private func approvalButton(
115 _ title: String,
116 background: Color,
117 border: Color = .clear,
118 foreground: Color = .white,
119 action: @escaping () -> Void
120 ) -> some View {
121 Button(action: action) {
122 Text(title)
123 .font(T3Typography.control.weight(.semibold))
124 .foregroundStyle(foreground)
125 .frame(maxWidth: .infinity)
126 .frame(height: T3Metrics.minimumTapTarget)
127 .background(background, in: RoundedRectangle(cornerRadius: 10))
128 .overlay {
129 RoundedRectangle(cornerRadius: 10)
130 .stroke(border, lineWidth: 1)
131 }
132 }
133 .buttonStyle(.plain)
134 }
135
136 private var detailLabel: String {
137 switch approval.kind {
138 case .command: "Command"
139 case .fileRead: "File access"
140 case .fileChange: "File change"
141 case .mcpElicitation: "App access"
142 case .patch: "Patch"
143 case .other: "Details"
144 }
145 }
146
147 private var options: [FeatureApprovalOption] {
148 approval.options ?? [
149 FeatureApprovalOption(decision: .allowOnce, label: "Approve once"),
150 FeatureApprovalOption(decision: .allowForSession, label: "Allow session"),
151 FeatureApprovalOption(decision: .deny, label: "Decline"),
152 ]
153 }
154
155 private var positiveOptions: [FeatureApprovalOption] {
156 options.filter { $0.decision != .deny && $0.decision != .cancel }
157 }
158
159 private var negativeOptions: [FeatureApprovalOption] {
160 options.filter { $0.decision == .deny || $0.decision == .cancel }
161 }
162}
163
164struct FeatureComposerUserInputPanel: View {
165 let input: FeatureUserInput
166 let isResponding: Bool
167 let onSubmit: ([String: FeatureInputAnswer], [String: [FeatureUploadAttachment]]) async -> Void
168 var onDismiss: (() async -> Void)? = nil
169 var environmentID: String? = nil
170 var attachmentPreferences = FeatureEnvironmentPreferences()
171
172 @State private var answers: [String: FeatureInputAnswer] = [:]
173 @State private var questionIndex = 0
174 @State private var attachmentsByQuestionID: [String: [FeatureDraftAttachment]] = [:]
175 @State private var preparation = FeatureAttachmentPreparationState()
176 @State private var attachmentFlowActive = false
177 @State private var restoredInputID: String?
178 @State private var draftError: String?
179 @State private var draftWrite: Task<Void, Never>?
180 @State private var isSubmittingAnswer = false
181
182 var body: some View {
183 Group {
184 if let question = activeQuestion {
185 VStack(spacing: 0) {
186 VStack(alignment: .leading, spacing: 0) {
187 HStack(spacing: 8) {
188 Text(question.header)
189 .font(T3Typography.eyebrow)
190 .tracking(1.3)
191 .textCase(.uppercase)
192 .foregroundStyle(T3Colors.accent)
193
194 Spacer()
195
196 if input.questions.count > 1 {
197 Text("\(questionIndex + 1)/\(input.questions.count)")
198 .font(T3Typography.supportingStrong.monospacedDigit())
199 .foregroundStyle(T3Colors.textTertiary)
200 }
201 }
202
203 Text(question.question)
204 .font(T3Typography.navigationTitle)
205 .foregroundStyle(T3Colors.textPrimary)
206 .fixedSize(horizontal: false, vertical: true)
207 .padding(.top, 5)
208
209 if question.allowsMultiple {
210 Text("Select one or more options")
211 .font(T3Typography.supporting)
212 .foregroundStyle(T3Colors.textTertiary)
213 .padding(.top, 4)
214 }
215 }
216 .padding(.horizontal, 15)
217 .padding(.vertical, 12)
218 .frame(maxWidth: .infinity, alignment: .leading)
219 .background(T3Colors.subtle)
220
221 Divider().overlay(T3Colors.separator)
222
223 if !question.options.isEmpty {
224 ScrollView {
225 VStack(spacing: 6) {
226 ForEach(
227 Array(question.options.enumerated()),
228 id: \.element.label
229 ) { index, option in
230 optionButton(option, number: index + 1, question: question)
231 .disabled(preparation.isPreparing || attachmentFlowActive)
232 }
233 }
234 .padding(.horizontal, 10)
235 .padding(.top, 10)
236 }
237 .frame(maxHeight: 320)
238 .scrollIndicators(.hidden)
239 }
240
241 if question.canWriteCustomAnswer {
242 HStack(spacing: 8) {
243 if input.supportsAttachments == true {
244 FeatureImageAttachmentPicker(
245 attachments: attachmentBinding(questionID: question.id),
246 preparationState: $preparation,
247 isFlowActive: $attachmentFlowActive,
248 draftOwnerID: "\(input.id):\(question.id)",
249 environmentID: environmentID,
250 imagesAllowed: attachmentPreferences.supportsImageUploads,
251 maximumFileBytes: attachmentPreferences.maxFileAttachmentBytes,
252 maximumCount: max(0, FeatureImageAttachmentLimits.maximumCount - otherAttachmentCount(questionID: question.id))
253 )
254 .disabled(restoredInputID != input.id)
255 }
256 Image(systemName: "pencil")
257 .font(T3Typography.supporting)
258 .foregroundStyle(T3Colors.textTertiary)
259
260 TextField(
261 "Write custom answer",
262 text: answerBinding(for: question),
263 axis: .vertical
264 )
265 .font(T3Typography.composer)
266 .lineLimit(1...4)
267 .submitLabel(.return)
268 }
269 .padding(.horizontal, 12)
270 .frame(minHeight: T3Metrics.minimumTapTarget)
271 .background(
272 T3Colors.input,
273 in: RoundedRectangle(cornerRadius: 11)
274 )
275 .overlay {
276 RoundedRectangle(cornerRadius: 11)
277 .stroke(T3Colors.inputBorder, lineWidth: 1)
278 }
279 .padding(.horizontal, 10)
280 .padding(.top, 7)
281 }
282
283 if !(attachmentsByQuestionID[question.id] ?? []).isEmpty {
284 FeatureAttachmentStrip(attachments: attachmentBinding(questionID: question.id))
285 .padding(.horizontal, 10)
286 }
287 if preparation.isPreparing || isResponding || isSubmittingAnswer {
288 Text(preparation.isPreparing ? preparation.statusLabel : responseStatus)
289 .font(T3Typography.supporting)
290 .foregroundStyle(T3Colors.textSecondary)
291 .padding(.top, 6)
292 }
293 if let draftError {
294 Text(draftError)
295 .font(T3Typography.supporting)
296 .foregroundStyle(T3Colors.danger)
297 .padding(.horizontal, 10)
298 }
299 if let attachmentBlocker {
300 Text(attachmentBlocker)
301 .font(T3Typography.supporting)
302 .foregroundStyle(T3Colors.danger)
303 .padding(.horizontal, 10)
304 }
305
306 HStack(spacing: 8) {
307 if input.canDismiss, let onDismiss {
308 Button("Dismiss") {
309 let pendingWrite = draftWrite
310 isSubmittingAnswer = true
311 Task { @MainActor in
312 defer { isSubmittingAnswer = false }
313 await pendingWrite?.value
314 await onDismiss()
315 }
316 }
317 .font(T3Typography.control)
318 .foregroundStyle(T3Colors.textSecondary)
319 .frame(minHeight: T3Metrics.minimumTapTarget)
320 .accessibilityLabel("Dismiss question without replying")
321 .disabled(preparation.isPreparing || attachmentFlowActive)
322 }
323 if questionIndex > 0 {
324 Button("Back") {
325 questionIndex -= 1
326 }
327 .disabled(preparation.isPreparing || attachmentFlowActive)
328 .font(T3Typography.control.weight(.semibold))
329 .foregroundStyle(T3Colors.textSecondary)
330 .frame(
331 minWidth: T3Metrics.minimumTapTarget,
332 minHeight: T3Metrics.minimumTapTarget
333 )
334 }
335
336 Spacer()
337
338 Button(action: advanceOrSubmit) {
339 Text(isLastQuestion ? "Submit" : "Next question")
340 .font(T3Typography.control.weight(.semibold))
341 .foregroundStyle(.white)
342 .padding(.horizontal, 18)
343 .frame(height: T3Metrics.minimumTapTarget)
344 .background(T3Colors.accent, in: Capsule())
345 }
346 .buttonStyle(.plain)
347 .disabled(!canAdvance)
348 .opacity(canAdvance ? 1 : 0.3)
349 }
350 .padding(.horizontal, 10)
351 .padding(.top, 9)
352 .padding(.bottom, 11)
353 }
354 .disabled(isResponding || isSubmittingAnswer)
355 .opacity(isResponding || isSubmittingAnswer ? 0.56 : 1)
356 }
357 }
358 .onChange(of: input.id) {
359 answers = [:]
360 questionIndex = 0
361 restoredInputID = nil
362 attachmentsByQuestionID = [:]
363 draftError = nil
364 }
365 .task(id: input.id) {
366 let requestID = input.id
367 do {
368 let stored = try await FeatureComposerDraftStore.shared.draft(
369 for: FeatureQuestionAttachmentDraft.key(inputID: requestID)
370 )
371 try Task.checkCancellation()
372 guard requestID == input.id else { return }
373 attachmentsByQuestionID = try FeatureQuestionAttachmentDraft.decode(stored)
374 .filter { questionIDs.contains($0.key) }
375 restoredInputID = requestID
376 } catch is CancellationError {
377 return
378 } catch {
379 restoredInputID = requestID
380 draftError = "Could not restore question attachments."
381 }
382 }
383 .onChange(of: attachmentsByQuestionID) { _, current in
384 guard restoredInputID == input.id else { return }
385 let key = FeatureQuestionAttachmentDraft.key(inputID: input.id)
386 let previousWrite = draftWrite
387 draftWrite = Task {
388 await previousWrite?.value
389 do {
390 try await FeatureComposerDraftStore.shared.setDraft(
391 FeatureQuestionAttachmentDraft.encode(current), for: key
392 )
393 draftError = nil
394 } catch {
395 draftError = "Could not save question attachments. Keep this thread open to send them."
396 }
397 }
398 }
399 .onChange(of: questionIDs) { previousIDs, currentIDs in
400 questionIndex = FeatureComposerQuestionReconciliation.index(
401 current: questionIndex,
402 previousQuestionIDs: previousIDs,
403 currentQuestionIDs: currentIDs
404 )
405 answers = FeatureComposerQuestionReconciliation.answers(
406 answers,
407 currentQuestionIDs: currentIDs
408 )
409 attachmentsByQuestionID = attachmentsByQuestionID.filter { currentIDs.contains($0.key) }
410 }
411 }
412
413 private var activeQuestion: FeatureInputQuestion? {
414 guard input.questions.indices.contains(questionIndex) else { return nil }
415 return input.questions[questionIndex]
416 }
417
418 private var questionIDs: [String] {
419 input.questions.map(\.id)
420 }
421
422 private var isLastQuestion: Bool {
423 questionIndex >= input.questions.count - 1
424 }
425
426 private var canAdvance: Bool {
427 guard let activeQuestion, !isSubmittingAnswer, !preparation.isPreparing, !attachmentFlowActive,
428 restoredInputID == input.id, attachmentBlocker == nil else { return false }
429 return normalizedAnswer(for: activeQuestion.id) != nil || hasAttachments(for: activeQuestion.id)
430 }
431
432 private var normalizedAnswers: [String: FeatureInputAnswer]? {
433 var result: [String: FeatureInputAnswer] = [:]
434 for question in input.questions {
435 if let answer = normalizedAnswer(for: question.id) {
436 result[question.id] = answer
437 } else if !hasAttachments(for: question.id) {
438 return nil
439 }
440 }
441 return result
442 }
443
444 private func optionButton(
445 _ option: FeatureInputOption,
446 number: Int,
447 question: FeatureInputQuestion
448 ) -> some View {
449 let isSelected = isOptionSelected(option.label, for: question)
450
451 return Button {
452 select(option.label, for: question)
453 } label: {
454 HStack(alignment: .center, spacing: 10) {
455 VStack(alignment: .leading, spacing: 2) {
456 Text(option.label)
457 .font(T3Typography.control)
458 .foregroundStyle(T3Colors.textPrimary)
459
460 if !option.detail.isEmpty, option.detail != option.label {
461 Text(option.detail)
462 .font(T3Typography.supporting)
463 .foregroundStyle(T3Colors.textSecondary)
464 .fixedSize(horizontal: false, vertical: true)
465 }
466 }
467
468 Spacer(minLength: 8)
469
470 if isSelected {
471 Image(systemName: "checkmark")
472 .font(T3Typography.supporting.weight(.bold))
473 .foregroundStyle(T3Colors.accent)
474 } else if number <= 9 {
475 Text("\(number)")
476 .font(.caption2.monospacedDigit().weight(.semibold))
477 .foregroundStyle(T3Colors.textTertiary)
478 .frame(width: 20, height: 20)
479 .overlay {
480 RoundedRectangle(cornerRadius: 5)
481 .stroke(T3Colors.border, lineWidth: 1)
482 }
483 }
484 }
485 .padding(.horizontal, 12)
486 .padding(.vertical, 9)
487 .frame(maxWidth: .infinity, minHeight: T3Metrics.minimumTapTarget, alignment: .leading)
488 .background(
489 isSelected ? T3Colors.accent.opacity(0.12) : T3Colors.subtle,
490 in: RoundedRectangle(cornerRadius: 10)
491 )
492 .overlay {
493 RoundedRectangle(cornerRadius: 10)
494 .stroke(
495 isSelected ? T3Colors.accent.opacity(0.46) : Color.clear,
496 lineWidth: 1
497 )
498 }
499 }
500 .buttonStyle(.plain)
501 }
502
503 private func answerBinding(for question: FeatureInputQuestion) -> Binding<String> {
504 Binding(
505 get: {
506 FeatureComposerCustomAnswer.text(
507 in: answers[question.id],
508 for: question
509 )
510 },
511 set: {
512 answers[question.id] = FeatureComposerCustomAnswer.replacingText(
513 in: answers[question.id],
514 with: $0,
515 for: question
516 )
517 }
518 )
519 }
520
521 private func select(_ label: String, for question: FeatureInputQuestion) {
522 answers[question.id] = (answers[question.id] ?? .selections([]))
523 .togglingOption(label, allowsMultiple: question.allowsMultiple)
524 if question.allowsMultiple {
525 return
526 }
527 guard !isLastQuestion else { return }
528 let selectedQuestionID = question.id
529 Task { @MainActor in
530 await Task.yield()
531 guard activeQuestion?.id == selectedQuestionID,
532 !isLastQuestion else {
533 return
534 }
535 questionIndex += 1
536 }
537 }
538
539 private func advanceOrSubmit() {
540 guard canAdvance else { return }
541 if !isLastQuestion {
542 questionIndex += 1
543 } else if let normalizedAnswers {
544 let submitted = attachmentsByQuestionID.filter { hasAttachments(for: $0.key) }
545 .mapValues { $0.map(FeatureUploadAttachment.init) }
546 let pendingWrite = draftWrite
547 isSubmittingAnswer = true
548 Task { @MainActor in
549 defer { isSubmittingAnswer = false }
550 await pendingWrite?.value
551 await onSubmit(normalizedAnswers, submitted)
552 }
553 } else if let unanswered = input.questions.firstIndex(where: {
554 normalizedAnswer(for: $0.id) == nil && !hasAttachments(for: $0.id)
555 }) {
556 questionIndex = unanswered
557 }
558 }
559
560 private func hasAttachments(for questionID: String) -> Bool {
561 input.supportsAttachments == true
562 && input.questions.contains { $0.id == questionID && $0.canWriteCustomAnswer }
563 && !(attachmentsByQuestionID[questionID] ?? []).isEmpty
564 }
565
566 private var responseStatus: String {
567 attachmentsByQuestionID.values.contains { !$0.isEmpty }
568 ? "Uploading attachments and sending answer..."
569 : "Sending answer..."
570 }
571
572 private var attachmentBlocker: String? {
573 if attachmentsByQuestionID.contains(where: { !$0.value.isEmpty && !hasAttachments(for: $0.key) }) {
574 return "Attachments are no longer supported for this question. Remove them to send the answer."
575 }
576 return nil
577 }
578
579 private func otherAttachmentCount(questionID: String) -> Int {
580 attachmentsByQuestionID.reduce(0) { count, entry in
581 count + (entry.key == questionID ? 0 : entry.value.count)
582 }
583 }
584
585 private func attachmentBinding(questionID: String) -> Binding<[FeatureDraftAttachment]> {
586 let requestID = input.id
587 return Binding(
588 get: { attachmentsByQuestionID[questionID] ?? [] },
589 set: { next in
590 guard requestID == input.id else { return }
591 attachmentsByQuestionID[questionID] = next
592 }
593 )
594 }
595
596 private func normalizedAnswer(for questionID: String) -> FeatureInputAnswer? {
597 answers[questionID]?.normalized
598 }
599
600 private func isOptionSelected(_ label: String, for question: FeatureInputQuestion) -> Bool {
601 switch answers[question.id] {
602 case let .text(value):
603 return !question.allowsMultiple && value == label
604 case let .selections(values):
605 return values.contains(label)
606 case nil:
607 return false
608 }
609 }
610}
611
612enum FeatureComposerCustomAnswer {
613 static func text(
614 in answer: FeatureInputAnswer?,
615 for question: FeatureInputQuestion
616 ) -> String {
617 let optionLabels = Set(question.options.map(\.label))
618 switch answer {
619 case let .text(value):
620 return optionLabels.contains(value) ? "" : value
621 case let .selections(values):
622 return values.first(where: { !optionLabels.contains($0) }) ?? ""
623 case nil:
624 return ""
625 }
626 }
627
628 static func replacingText(
629 in answer: FeatureInputAnswer?,
630 with text: String,
631 for question: FeatureInputQuestion
632 ) -> FeatureInputAnswer {
633 guard question.allowsMultiple else { return .text(text) }
634 let optionLabels = Set(question.options.map(\.label))
635 let selectedOptions: [String]
636 if case let .selections(values) = answer {
637 selectedOptions = values.filter(optionLabels.contains)
638 } else {
639 selectedOptions = []
640 }
641 return .selections(text.isEmpty ? selectedOptions : selectedOptions + [text])
642 }
643}
644
645enum FeatureComposerQuestionReconciliation {
646 static func index(
647 current: Int,
648 previousQuestionIDs: [String],
649 currentQuestionIDs: [String]
650 ) -> Int {
651 guard !currentQuestionIDs.isEmpty else { return 0 }
652 if previousQuestionIDs.indices.contains(current),
653 let retained = currentQuestionIDs.firstIndex(
654 of: previousQuestionIDs[current]
655 ) {
656 return retained
657 }
658 return min(max(0, current), currentQuestionIDs.count - 1)
659 }
660
661 static func answers(
662 _ answers: [String: FeatureInputAnswer],
663 currentQuestionIDs: [String]
664 ) -> [String: FeatureInputAnswer] {
665 let liveIDs = Set(currentQuestionIDs)
666 return answers.filter { liveIDs.contains($0.key) }
667 }
668}