From 5b169990f8a45f254614ee2c318b597a96261af7 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Fri, 31 Jul 2026 06:38:10 -0700 Subject: [PATCH] feat(ios): rebuild the thread composer --- .../Chat/FeatureComposerRequestViews.swift | 360 ++++++++++++++++ .../Features/Chat/FeatureComposerView.swift | 385 ++++++++++++++---- .../Features/Chat/ImageAttachmentViews.swift | 199 +++++++-- .../Features/Chat/ThreadDetailView.swift | 190 +-------- 4 files changed, 872 insertions(+), 262 deletions(-) create mode 100644 apps/swift-ios/Features/Chat/FeatureComposerRequestViews.swift diff --git a/apps/swift-ios/Features/Chat/FeatureComposerRequestViews.swift b/apps/swift-ios/Features/Chat/FeatureComposerRequestViews.swift new file mode 100644 index 0000000000..f491571922 --- /dev/null +++ b/apps/swift-ios/Features/Chat/FeatureComposerRequestViews.swift @@ -0,0 +1,360 @@ +import SwiftUI + +struct FeatureComposerApprovalPanel: View { + let approval: FeatureApproval + let position: Int + let total: Int + let isResponding: Bool + let onDecision: (FeatureApprovalDecision) -> Void + let onCancelTurn: () -> Void + + var body: some View { + VStack(spacing: 0) { + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 8) { + Text("Pending approval") + .font(.caption2.weight(.bold)) + .tracking(1.3) + .textCase(.uppercase) + .foregroundStyle(T3Colors.warning) + + Spacer() + + if total > 1 { + Text("\(position)/\(total)") + .font(.caption2.monospacedDigit().weight(.semibold)) + .foregroundStyle(T3Colors.textTertiary) + } + } + + Text(approval.title) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(T3Colors.textPrimary) + .padding(.top, 5) + + VStack(alignment: .leading, spacing: 5) { + Text(detailLabel) + .font(.system(size: 10, weight: .semibold)) + .tracking(0.7) + .textCase(.uppercase) + .foregroundStyle(T3Colors.textTertiary) + + Text(approval.detail) + .font(approval.kind == .command ? .caption.monospaced() : .callout) + .foregroundStyle(Color.white.opacity(0.84)) + .fixedSize(horizontal: false, vertical: true) + .textSelection(.enabled) + } + .padding(10) + .frame(maxWidth: .infinity, alignment: .leading) + .background(.black.opacity(0.46), in: RoundedRectangle(cornerRadius: 10)) + .overlay { + RoundedRectangle(cornerRadius: 10) + .stroke(Color.white.opacity(0.08), lineWidth: 1) + } + .padding(.top, 9) + } + .padding(.horizontal, 15) + .padding(.vertical, 12) + .background(Color.white.opacity(0.024)) + + Divider().overlay(T3Colors.separator) + + VStack(spacing: 9) { + HStack(spacing: 7) { + approvalButton( + "Approve once", + background: T3Colors.accent, + action: { onDecision(.allowOnce) } + ) + + approvalButton( + "Always allow", + background: Color.clear, + border: Color.white.opacity(0.14), + action: { onDecision(.allowForSession) } + ) + } + + HStack(spacing: 26) { + Button("Decline", role: .destructive) { + onDecision(.deny) + } + .foregroundStyle(T3Colors.danger) + + Button("Cancel turn", action: onCancelTurn) + .foregroundStyle(T3Colors.textTertiary) + } + .font(.caption.weight(.semibold)) + .buttonStyle(.plain) + .frame(maxWidth: .infinity) + } + .padding(.horizontal, 10) + .padding(.top, 10) + .padding(.bottom, 11) + } + .disabled(isResponding) + .opacity(isResponding ? 0.56 : 1) + .accessibilityElement(children: .contain) + } + + private func approvalButton( + _ title: String, + background: Color, + border: Color = .clear, + action: @escaping () -> Void + ) -> some View { + Button(action: action) { + Text(title) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.white) + .frame(maxWidth: .infinity) + .frame(height: T3Metrics.minimumTapTarget) + .background(background, in: RoundedRectangle(cornerRadius: 10)) + .overlay { + RoundedRectangle(cornerRadius: 10) + .stroke(border, lineWidth: 1) + } + } + .buttonStyle(.plain) + } + + private var detailLabel: String { + switch approval.kind { + case .command: "Command" + case .fileRead: "File access" + case .fileChange: "File change" + case .patch: "Patch" + case .other: "Details" + } + } +} + +struct FeatureComposerUserInputPanel: View { + let input: FeatureUserInput + let isResponding: Bool + let onSubmit: ([String: String]) -> Void + + @State private var answers: [String: String] = [:] + @State private var questionIndex = 0 + + var body: some View { + if let question = activeQuestion { + VStack(spacing: 0) { + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 8) { + Text(question.header) + .font(.caption2.weight(.bold)) + .tracking(1.3) + .textCase(.uppercase) + .foregroundStyle(Color.indigo.opacity(0.95)) + + Spacer() + + if input.questions.count > 1 { + Text("\(questionIndex + 1)/\(input.questions.count)") + .font(.caption2.monospacedDigit().weight(.semibold)) + .foregroundStyle(T3Colors.textTertiary) + } + } + + Text(question.question) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(T3Colors.textPrimary) + .fixedSize(horizontal: false, vertical: true) + .padding(.top, 5) + + } + .padding(.horizontal, 15) + .padding(.vertical, 12) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Color.white.opacity(0.024)) + + Divider().overlay(T3Colors.separator) + + ScrollView { + VStack(spacing: 6) { + ForEach(Array(question.options.enumerated()), id: \.element.label) { index, option in + optionButton(option, number: index + 1, question: question) + } + } + .padding(.horizontal, 10) + .padding(.top, 10) + } + .frame(maxHeight: 252) + .scrollIndicators(.hidden) + + HStack(spacing: 8) { + Image(systemName: "pencil") + .font(.caption) + .foregroundStyle(T3Colors.textTertiary) + + TextField( + "Write custom answer", + text: answerBinding(for: question.id) + ) + .font(.subheadline) + .submitLabel(.next) + .onSubmit(advanceOrSubmit) + } + .padding(.horizontal, 12) + .frame(minHeight: T3Metrics.minimumTapTarget) + .background(Color.white.opacity(0.025), in: RoundedRectangle(cornerRadius: 11)) + .overlay { + RoundedRectangle(cornerRadius: 11) + .stroke(Color.white.opacity(0.09), lineWidth: 1) + } + .padding(.horizontal, 10) + .padding(.top, 7) + + HStack(spacing: 8) { + if questionIndex > 0 { + Button("Back") { + questionIndex -= 1 + } + .font(.subheadline.weight(.semibold)) + .foregroundStyle(T3Colors.textSecondary) + .frame(minWidth: T3Metrics.minimumTapTarget, minHeight: 36) + } + + Spacer() + + Button(action: advanceOrSubmit) { + Text(isLastQuestion ? "Submit" : "Next question") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.white) + .padding(.horizontal, 18) + .frame(height: 36) + .background(T3Colors.accent, in: Capsule()) + } + .buttonStyle(.plain) + .disabled(!canAdvance) + .opacity(canAdvance ? 1 : 0.3) + } + .padding(.horizontal, 10) + .padding(.top, 9) + .padding(.bottom, 11) + } + .disabled(isResponding) + .opacity(isResponding ? 0.56 : 1) + .onChange(of: input.id) { + answers = [:] + questionIndex = 0 + } + } + } + + private var activeQuestion: FeatureInputQuestion? { + guard input.questions.indices.contains(questionIndex) else { return nil } + return input.questions[questionIndex] + } + + private var isLastQuestion: Bool { + questionIndex >= input.questions.count - 1 + } + + private var canAdvance: Bool { + guard let activeQuestion else { return false } + return normalizedAnswer(for: activeQuestion.id) != nil + } + + private var allQuestionsAnswered: Bool { + input.questions.allSatisfy { normalizedAnswer(for: $0.id) != nil } + } + + private func optionButton( + _ option: FeatureInputOption, + number: Int, + question: FeatureInputQuestion + ) -> some View { + let isSelected = answers[question.id] == option.label + + return Button { + select(option.label, for: question) + } label: { + HStack(alignment: .center, spacing: 10) { + VStack(alignment: .leading, spacing: 2) { + Text(option.label) + .font(.subheadline.weight(.medium)) + .foregroundStyle(Color.white.opacity(0.9)) + + if !option.detail.isEmpty, option.detail != option.label { + Text(option.detail) + .font(.caption) + .foregroundStyle(T3Colors.textSecondary) + .fixedSize(horizontal: false, vertical: true) + } + } + + Spacer(minLength: 8) + + if isSelected { + Image(systemName: "checkmark") + .font(.caption.weight(.bold)) + .foregroundStyle(Color.indigo.opacity(0.95)) + } else if number <= 9 { + Text("\(number)") + .font(.caption2.monospacedDigit().weight(.semibold)) + .foregroundStyle(T3Colors.textTertiary) + .frame(width: 20, height: 20) + .overlay { + RoundedRectangle(cornerRadius: 5) + .stroke(Color.white.opacity(0.14), lineWidth: 1) + } + } + } + .padding(.horizontal, 12) + .padding(.vertical, 9) + .frame(maxWidth: .infinity, minHeight: T3Metrics.minimumTapTarget, alignment: .leading) + .background( + isSelected ? Color.indigo.opacity(0.12) : Color.white.opacity(0.045), + in: RoundedRectangle(cornerRadius: 10) + ) + .overlay { + RoundedRectangle(cornerRadius: 10) + .stroke( + isSelected ? Color.indigo.opacity(0.46) : Color.clear, + lineWidth: 1 + ) + } + } + .buttonStyle(.plain) + } + + private func answerBinding(for questionID: String) -> Binding { + Binding( + get: { answers[questionID] ?? "" }, + set: { answers[questionID] = $0 } + ) + } + + private func select(_ label: String, for question: FeatureInputQuestion) { + answers[question.id] = label + guard !isLastQuestion else { return } + Task { @MainActor in + await Task.yield() + questionIndex += 1 + } + } + + private func advanceOrSubmit() { + guard canAdvance else { return } + if !isLastQuestion { + questionIndex += 1 + } else if allQuestionsAnswered { + onSubmit(answers) + } else if let unanswered = input.questions.firstIndex(where: { + normalizedAnswer(for: $0.id) == nil + }) { + questionIndex = unanswered + } + } + + private func normalizedAnswer(for questionID: String) -> String? { + guard let value = answers[questionID]?.trimmingCharacters(in: .whitespacesAndNewlines), + !value.isEmpty else { + return nil + } + return value + } +} diff --git a/apps/swift-ios/Features/Chat/FeatureComposerView.swift b/apps/swift-ios/Features/Chat/FeatureComposerView.swift index 1cecec6283..21c222e3a5 100644 --- a/apps/swift-ios/Features/Chat/FeatureComposerView.swift +++ b/apps/swift-ios/Features/Chat/FeatureComposerView.swift @@ -1,89 +1,298 @@ import SwiftUI struct FeatureComposerView: View { - @Binding var text: String - @Binding var selection: FeatureSelection? - @Binding var attachments: [FeatureDraftAttachment] - let providers: [FeatureProvider] - let threadSelection: FeatureSelection? - let isSending: Bool - let isWorking: Bool - let focused: FocusState.Binding - let onSend: () -> Void - let onStop: () -> Void + @Binding private var text: String + @Binding private var selection: FeatureSelection? + @Binding private var attachments: [FeatureDraftAttachment] + + private let providers: [FeatureProvider] + private let threadSelection: FeatureSelection? + private let isSending: Bool + private let isWorking: Bool + private let focused: FocusState.Binding + private let runtimeMode: FeatureRuntimeMode? + private let contextUsage: Double? + private let pendingApprovals: [FeatureApproval] + private let pendingUserInputs: [FeatureUserInput] + private let isResolvingRequest: Bool + private let onSend: () -> Void + private let onStop: () -> Void + private let onRuntimeModeChange: ((FeatureRuntimeMode) -> Void)? + private let onApprovalDecision: ((String, FeatureApprovalDecision) -> Void)? + private let onUserInputSubmit: ((String, [String: String]) -> Void)? + + init( + text: Binding, + selection: Binding, + attachments: Binding<[FeatureDraftAttachment]>, + providers: [FeatureProvider], + threadSelection: FeatureSelection?, + isSending: Bool, + isWorking: Bool, + focused: FocusState.Binding, + onSend: @escaping () -> Void, + onStop: @escaping () -> Void, + runtimeMode: FeatureRuntimeMode? = nil, + contextUsage: Double? = nil, + onRuntimeModeChange: ((FeatureRuntimeMode) -> Void)? = nil, + pendingApprovals: [FeatureApproval] = [], + pendingUserInputs: [FeatureUserInput] = [], + isResolvingRequest: Bool = false, + onApprovalDecision: ((String, FeatureApprovalDecision) -> Void)? = nil, + onUserInputSubmit: ((String, [String: String]) -> Void)? = nil + ) { + _text = text + _selection = selection + _attachments = attachments + self.providers = providers + self.threadSelection = threadSelection + self.isSending = isSending + self.isWorking = isWorking + self.focused = focused + self.onSend = onSend + self.onStop = onStop + self.runtimeMode = runtimeMode + self.contextUsage = contextUsage + self.onRuntimeModeChange = onRuntimeModeChange + self.pendingApprovals = pendingApprovals + self.pendingUserInputs = pendingUserInputs + self.isResolvingRequest = isResolvingRequest + self.onApprovalDecision = onApprovalDecision + self.onUserInputSubmit = onUserInputSubmit + } var body: some View { - VStack(spacing: 7) { - FeatureAttachmentStrip(attachments: $attachments) - - HStack(alignment: .bottom, spacing: 9) { - FeatureImageAttachmentPicker( - attachments: $attachments, - isEnabled: DailyUXModelOptions.supportsImages( - selection: selection, - providers: providers - ) + VStack(spacing: 0) { + if let approval = pendingApprovals.first, let onApprovalDecision { + FeatureComposerApprovalPanel( + approval: approval, + position: 1, + total: pendingApprovals.count, + isResponding: isResolvingRequest, + onDecision: { decision in + onApprovalDecision(approval.id, decision) + }, + onCancelTurn: onStop ) - .padding(.leading, 2) - .padding(.bottom, 1) - - TextField("Message agent", text: $text, axis: .vertical) - .lineLimit(1...7) - .focused(focused) - .submitLabel(.send) - .onSubmit { - if canSend { onSend() } + } else if let input = pendingUserInputs.first, let onUserInputSubmit { + FeatureComposerUserInputPanel( + input: input, + isResponding: isResolvingRequest, + onSubmit: { answers in + onUserInputSubmit(input.id, answers) } - .padding(.vertical, 11) + ) + } else if isExpanded { + expandedComposer + } else { + collapsedComposer + } + } + .background(Color(white: 0.052).opacity(0.98), in: composerShape) + .overlay { + composerShape + .stroke(Color.white.opacity(0.105), lineWidth: 1) + } + .clipShape(composerShape) + .padding(.horizontal, 10) + .padding(.top, 10) + .padding(.bottom, 8) + .background { + LinearGradient( + colors: [.clear, .black.opacity(0.94), .black], + startPoint: .top, + endPoint: .bottom + ) + .ignoresSafeArea() + } + } - Button(action: isWorking && textIsEmpty ? onStop : onSend) { - Image(systemName: isWorking && textIsEmpty ? "stop.fill" : "arrow.up") - .font(.system(size: 14, weight: .bold)) - .foregroundStyle(.black) - .frame(width: 32, height: 32) - .background(.white, in: Circle()) - } - .disabled((!isWorking && !canSend) || isSending) + private var collapsedComposer: some View { + HStack(spacing: 4) { + FeatureImageAttachmentPicker( + attachments: $attachments, + isEnabled: imagesAllowed + ) + + Button { + focused.wrappedValue = true + } label: { + Text(isWorking ? "Message to queue…" : "Ask anything…") + .font(.body) + .foregroundStyle(T3Colors.textTertiary) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .frame(minHeight: T3Metrics.minimumTapTarget) + .accessibilityLabel("Message agent") + .accessibilityHint("Opens the message editor") + + submitButton .padding(.trailing, 7) - .padding(.bottom, 7) - .accessibilityLabel(isWorking && textIsEmpty ? "Stop agent" : "Send") - .accessibilityIdentifier( - isWorking && textIsEmpty ? "thread-stop" : "message-send" - ) - } - .background(T3Colors.input, in: RoundedRectangle(cornerRadius: 18)) - .overlay { - RoundedRectangle(cornerRadius: 18) - .stroke(T3Colors.border, lineWidth: 1) + } + .padding(.leading, 3) + .padding(.vertical, 5) + } + + private var expandedComposer: some View { + VStack(spacing: 0) { + if !attachments.isEmpty { + FeatureAttachmentStrip(attachments: $attachments) + .padding(.horizontal, 12) + .padding(.top, 3) + + Divider() + .overlay(T3Colors.separator) + .padding(.horizontal, 13) } - HStack { - ProviderModelPicker( - providers: providers, - selection: $selection, - style: .compact, - threadSelection: threadSelection + TextField( + isWorking ? "Message to queue…" : "Ask anything…", + text: $text, + axis: .vertical + ) + .font(.body) + .lineLimit(1...7) + .focused(focused) + .submitLabel(.send) + .onSubmit { + if canSend { onSend() } + } + .padding(.horizontal, 15) + .padding(.top, 12) + .padding(.bottom, 5) + .frame(minHeight: 57, alignment: .top) + + if !attachments.isEmpty, !imagesAllowed { + Label("Choose a model that accepts images", systemImage: "exclamationmark.circle") + .font(.caption) + .foregroundStyle(T3Colors.warning) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 15) + .padding(.bottom, 4) + } + + composerFooter + } + } + + private var composerFooter: some View { + HStack(spacing: 2) { + FeatureImageAttachmentPicker( + attachments: $attachments, + isEnabled: imagesAllowed + ) + + ProviderModelPicker( + providers: providers, + selection: $selection, + style: .compact, + threadSelection: threadSelection + ) + .frame(maxWidth: 156, alignment: .leading) + .layoutPriority(2) + + if let runtimeMode, let onRuntimeModeChange { + runtimeModePicker( + runtimeMode: runtimeMode, + onChange: onRuntimeModeChange ) - Spacer() - if !attachments.isEmpty, !imagesAllowed { - Text("Choose an image model") - .font(.caption2) - .foregroundStyle(T3Colors.warning) - } else if !attachments.isEmpty { - Text("\(attachments.count) image\(attachments.count == 1 ? "" : "s")") - .font(.caption2.monospacedDigit()) - .foregroundStyle(T3Colors.textTertiary) + } + + Spacer(minLength: 0) + + if let contextUsage { + FeatureContextMeter(usage: contextUsage) + } + + submitButton + .padding(.leading, 4) + } + .padding(.horizontal, 7) + .padding(.top, 2) + .padding(.bottom, 8) + } + + private func runtimeModePicker( + runtimeMode: FeatureRuntimeMode, + onChange: @escaping (FeatureRuntimeMode) -> Void + ) -> some View { + Menu { + ForEach(FeatureRuntimeMode.allCases, id: \.self) { mode in + Button { + onChange(mode) + } label: { + if mode == runtimeMode { + Label(runtimeModeLabel(mode), systemImage: "checkmark") + } else { + Text(runtimeModeLabel(mode)) + } } } - .padding(.horizontal, 3) + } label: { + ViewThatFits(in: .horizontal) { + HStack(spacing: 6) { + Image(systemName: "lock") + Text(runtimeModeLabel(runtimeMode)) + .lineLimit(1) + Image(systemName: "chevron.down") + .font(.system(size: 8, weight: .bold)) + } + + Image(systemName: "lock") + .frame(width: 30) + } + .font(.caption.weight(.medium)) + .foregroundStyle(T3Colors.textSecondary) + .frame(minHeight: 30) + .contentShape(Rectangle()) } - .padding(.horizontal, 12) - .padding(.top, 9) - .padding(.bottom, 7) - .background(.black.opacity(0.97)) - .overlay(alignment: .top) { - Divider().opacity(0.4) + .buttonStyle(.plain) + .frame(maxWidth: 116) + .accessibilityLabel("Access mode") + .accessibilityValue(runtimeModeLabel(runtimeMode)) + } + + private var submitButton: some View { + Button(action: showsStop ? onStop : onSend) { + Group { + if isSending { + ProgressView() + .controlSize(.small) + .tint(.white) + } else { + Image(systemName: showsStop ? "stop.fill" : "arrow.up") + .font(.system(size: showsStop ? 11 : 14, weight: .bold)) + } + } + .foregroundStyle(.white) + .frame(width: 34, height: 34) + .background(showsStop ? T3Colors.danger : T3Colors.accent, in: Circle()) } + .buttonStyle(.plain) + .disabled(submitDisabled) + .opacity(submitDisabled ? 0.3 : 1) + .frame(width: T3Metrics.minimumTapTarget, height: T3Metrics.minimumTapTarget) + .contentShape(Rectangle()) + .accessibilityLabel(showsStop ? "Stop agent" : "Send") + .accessibilityIdentifier(showsStop ? "thread-stop" : "message-send") + } + + private var composerShape: RoundedRectangle { + RoundedRectangle(cornerRadius: 22, style: .continuous) + } + + private var isExpanded: Bool { + focused.wrappedValue || !textIsEmpty || !attachments.isEmpty + } + + private var showsStop: Bool { + isWorking + } + + private var submitDisabled: Bool { + isSending || (!showsStop && !canSend) } private var textIsEmpty: Bool { @@ -99,4 +308,40 @@ struct FeatureComposerView: View { private var imagesAllowed: Bool { DailyUXModelOptions.supportsImages(selection: selection, providers: providers) } + + private func runtimeModeLabel(_ mode: FeatureRuntimeMode) -> String { + switch mode { + case .approvalRequired: "Supervised" + case .autoAcceptEdits: "Auto-accept edits" + case .automatic: "Auto" + case .fullAccess: "Full access" + } + } +} + +private struct FeatureContextMeter: View { + let usage: Double + + var body: some View { + ZStack { + Circle() + .stroke(Color.white.opacity(0.13), lineWidth: 2) + Circle() + .trim(from: 0, to: clampedUsage) + .stroke( + T3Colors.textSecondary, + style: StrokeStyle(lineWidth: 2, lineCap: .round) + ) + .rotationEffect(.degrees(-90)) + } + .frame(width: 18, height: 18) + .frame(width: 30, height: T3Metrics.minimumTapTarget) + .accessibilityElement() + .accessibilityLabel("Context used") + .accessibilityValue("\(Int((clampedUsage * 100).rounded())) percent") + } + + private var clampedUsage: Double { + min(max(usage, 0), 1) + } } diff --git a/apps/swift-ios/Features/Chat/ImageAttachmentViews.swift b/apps/swift-ios/Features/Chat/ImageAttachmentViews.swift index 9f66498879..b4e4baeee7 100644 --- a/apps/swift-ios/Features/Chat/ImageAttachmentViews.swift +++ b/apps/swift-ios/Features/Chat/ImageAttachmentViews.swift @@ -11,6 +11,8 @@ struct FeatureImageAttachmentPicker: View { @State private var selection: [PhotosPickerItem] = [] @State private var isLoading = false + @State private var isCameraPresented = false + @State private var isFileImporterPresented = false @State private var errorMessage: String? init( @@ -24,24 +26,60 @@ struct FeatureImageAttachmentPicker: View { } var body: some View { - PhotosPicker( - selection: $selection, - maxSelectionCount: max(1, maximumCount - attachments.count), - matching: .images - ) { - Image(systemName: isLoading ? "ellipsis" : "photo") + Menu { + PhotosPicker( + selection: $selection, + maxSelectionCount: max(1, remainingCount), + matching: .images + ) { + Label("Photo Library", systemImage: "photo.on.rectangle") + } + + Button { + isCameraPresented = true + } label: { + Label("Camera", systemImage: "camera") + } + .disabled(!UIImagePickerController.isSourceTypeAvailable(.camera)) + + Button { + isFileImporterPresented = true + } label: { + Label("Files", systemImage: "folder") + } + } label: { + Image(systemName: isLoading ? "ellipsis" : "paperclip") .font(.system(size: 17, weight: .medium)) .foregroundStyle(T3Colors.textSecondary) .frame(width: T3Metrics.minimumTapTarget, height: T3Metrics.minimumTapTarget) .contentShape(Rectangle()) } - .disabled(!isEnabled || isLoading || attachments.count >= maximumCount) - .opacity(isEnabled ? 1 : 0.3) - .accessibilityLabel(isLoading ? "Adding images" : "Add images") + .buttonStyle(.plain) + .disabled(!canAdd) + .opacity(canAdd ? 1 : 0.3) + .accessibilityLabel(attachmentAccessibilityLabel) .accessibilityIdentifier("image-attachment-picker") - .accessibilityHint(isEnabled ? "" : "The selected model does not accept images") + .accessibilityHint(attachmentAccessibilityHint) .onChange(of: selection) { - loadSelection() + loadPhotoSelection() + } + .fullScreenCover(isPresented: $isCameraPresented) { + FeatureCameraPicker( + onCapture: loadCapturedImage, + onCancel: { isCameraPresented = false } + ) + .ignoresSafeArea() + } + .fileImporter( + isPresented: $isFileImporterPresented, + allowedContentTypes: [.image], + allowsMultipleSelection: true, + onCompletion: loadFiles + ) + .onChange(of: attachments.count) { + if attachments.count >= maximumCount { + selection = [] + } } .alert( "Couldn’t add image", @@ -56,7 +94,27 @@ struct FeatureImageAttachmentPicker: View { } } - private func loadSelection() { + private var remainingCount: Int { + max(0, maximumCount - attachments.count) + } + + private var canAdd: Bool { + isEnabled && !isLoading && remainingCount > 0 + } + + private var attachmentAccessibilityLabel: String { + if isLoading { return "Adding attachment" } + if remainingCount == 0 { return "Attachment limit reached" } + return "Add attachment" + } + + private var attachmentAccessibilityHint: String { + if !isEnabled { return "The selected model does not accept images" } + if remainingCount == 0 { return "Remove an attachment before adding another" } + return "Choose a photo, take a photo, or browse image files" + } + + private func loadPhotoSelection() { let items = selection guard !items.isEmpty else { return } selection = [] @@ -64,19 +122,12 @@ struct FeatureImageAttachmentPicker: View { Task { defer { isLoading = false } - for item in items.prefix(maximumCount - attachments.count) { + for item in items.prefix(remainingCount) { do { guard let data = try await item.loadTransferable(type: Data.self) else { continue } - let ordinal = attachments.count + 1 - let attachment = try await Task.detached(priority: .userInitiated) { - try FeatureImageProcessor.attachment( - from: data, - ordinal: ordinal - ) - }.value - attachments.append(attachment) + try await appendImage(data) } catch { errorMessage = error.localizedDescription break @@ -84,6 +135,64 @@ struct FeatureImageAttachmentPicker: View { } } } + + private func loadCapturedImage(_ image: UIImage) { + isCameraPresented = false + guard canAdd else { return } + isLoading = true + + Task { + defer { isLoading = false } + do { + let data = try await Task.detached(priority: .userInitiated) { + guard let data = image.jpegData(compressionQuality: 0.94) else { + throw FeatureImageAttachmentError.encodingFailed + } + return data + }.value + try await appendImage(data) + } catch { + errorMessage = error.localizedDescription + } + } + } + + private func loadFiles(_ result: Result<[URL], Error>) { + switch result { + case .failure(let error): + errorMessage = error.localizedDescription + case .success(let urls): + guard !urls.isEmpty, canAdd else { return } + isLoading = true + + Task { + defer { isLoading = false } + for url in urls.prefix(remainingCount) { + do { + let data = try await Task.detached(priority: .userInitiated) { + let hasAccess = url.startAccessingSecurityScopedResource() + defer { + if hasAccess { url.stopAccessingSecurityScopedResource() } + } + return try Data(contentsOf: url, options: .mappedIfSafe) + }.value + try await appendImage(data) + } catch { + errorMessage = error.localizedDescription + break + } + } + } + } + } + + private func appendImage(_ data: Data) async throws { + let ordinal = attachments.count + 1 + let attachment = try await Task.detached(priority: .userInitiated) { + try FeatureImageProcessor.attachment(from: data, ordinal: ordinal) + }.value + attachments.append(attachment) + } } struct FeatureAttachmentStrip: View { @@ -124,9 +233,9 @@ private struct FeatureAttachmentThumbnail: View { .foregroundStyle(T3Colors.textSecondary) } } - .frame(width: 66, height: 66) + .frame(width: 58, height: 58) .background(T3Colors.surface) - .clipShape(RoundedRectangle(cornerRadius: 9)) + .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) Button(action: onRemove) { Image(systemName: "xmark") @@ -154,6 +263,50 @@ private struct FeatureAttachmentThumbnail: View { } } +private struct FeatureCameraPicker: UIViewControllerRepresentable { + let onCapture: (UIImage) -> Void + let onCancel: () -> Void + + func makeCoordinator() -> Coordinator { + Coordinator(onCapture: onCapture, onCancel: onCancel) + } + + func makeUIViewController(context: Context) -> UIImagePickerController { + let controller = UIImagePickerController() + controller.sourceType = .camera + controller.cameraCaptureMode = .photo + controller.delegate = context.coordinator + return controller + } + + func updateUIViewController(_ controller: UIImagePickerController, context: Context) {} + + final class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate { + private let onCapture: (UIImage) -> Void + private let onCancel: () -> Void + + init(onCapture: @escaping (UIImage) -> Void, onCancel: @escaping () -> Void) { + self.onCapture = onCapture + self.onCancel = onCancel + } + + func imagePickerController( + _ picker: UIImagePickerController, + didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] + ) { + guard let image = info[.originalImage] as? UIImage else { + onCancel() + return + } + onCapture(image) + } + + func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { + onCancel() + } + } +} + enum FeatureImageProcessor { private static let maximumDimension: CGFloat = 2_048 private static let maximumEncodedBytes = 10 * 1_024 * 1_024 diff --git a/apps/swift-ios/Features/Chat/ThreadDetailView.swift b/apps/swift-ios/Features/Chat/ThreadDetailView.swift index c4e97a5bb5..3eab756141 100644 --- a/apps/swift-ios/Features/Chat/ThreadDetailView.swift +++ b/apps/swift-ios/Features/Chat/ThreadDetailView.swift @@ -207,22 +207,9 @@ public struct ThreadDetailView: View { .id(message.id) } - ForEach(detail.approvals) { approval in - ApprovalRequestView(model: model, approval: approval) - .id("approval-\(approval.id)") - } - - ForEach(detail.userInputs) { input in - UserInputRequestView(model: model, input: input) - .id("user-input-\(input.id)") - } - if detail.thread.state == .working || detail.thread.state == .queued { StreamingStatusView( - state: detail.thread.state, - onStop: { - Task { await model.cancelTurn(threadID: thread.id) } - } + state: detail.thread.state ) .id("streaming-status") } @@ -256,6 +243,19 @@ public struct ThreadDetailView: View { onSend: send, onStop: { Task { await model.cancelTurn(threadID: thread.id) } + }, + runtimeMode: currentThread.runtimeMode, + onRuntimeModeChange: { mode in + Task { await model.setRuntimeMode(thread.id, mode: mode) } + }, + pendingApprovals: detail.approvals, + pendingUserInputs: detail.userInputs, + isResolvingRequest: model.isPerformingAction, + onApprovalDecision: { id, decision in + Task { await model.resolveApproval(id, decision: decision) } + }, + onUserInputSubmit: { id, answers in + Task { await model.resolveUserInput(id, answers: answers) } } ) } @@ -319,93 +319,6 @@ private enum FeatureThreadToolSurface: String, Identifiable { var id: String { rawValue } } -private struct UserInputRequestView: View { - @Bindable var model: FeatureRootModel - let input: FeatureUserInput - @State private var answers: [String: String] = [:] - @State private var isSubmitting = false - - var body: some View { - VStack(alignment: .leading, spacing: 14) { - Label("Input requested", systemImage: "questionmark.bubble") - .font(.subheadline.weight(.semibold)) - .foregroundStyle(.indigo) - - ForEach(input.questions) { question in - VStack(alignment: .leading, spacing: 8) { - Text(question.header) - .font(.caption.weight(.semibold)) - .foregroundStyle(.secondary) - Text(question.question) - .font(.callout) - - if !question.options.isEmpty { - ForEach(question.options, id: \.label) { option in - Button { - answers[question.id] = option.label - } label: { - HStack(alignment: .top, spacing: 9) { - Image( - systemName: answers[question.id] == option.label - ? "checkmark.circle.fill" - : "circle" - ) - VStack(alignment: .leading, spacing: 2) { - Text(option.label) - if !option.detail.isEmpty { - Text(option.detail) - .font(.caption) - .foregroundStyle(.secondary) - } - } - Spacer() - } - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - } - } - - TextField( - question.options.isEmpty ? "Your answer" : "Or type another answer", - text: Binding( - get: { answers[question.id] ?? "" }, - set: { answers[question.id] = $0 } - ), - axis: .vertical - ) - .lineLimit(1...4) - .textFieldStyle(.roundedBorder) - } - } - - Button(isSubmitting ? "Submitting…" : "Submit") { - isSubmitting = true - Task { - await model.resolveUserInput(input.id, answers: answers) - isSubmitting = false - } - } - .buttonStyle(.borderedProminent) - .tint(.white) - .foregroundStyle(.black) - .disabled( - isSubmitting - || input.questions.contains { - answers[$0.id]?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - != false - } - ) - } - .padding(13) - .background(Color.indigo.opacity(0.1), in: RoundedRectangle(cornerRadius: 12)) - .overlay { - RoundedRectangle(cornerRadius: 12) - .stroke(Color.indigo.opacity(0.35), lineWidth: 1) - } - } -} - struct FeatureMessageView: View { let message: FeatureMessage @@ -654,77 +567,16 @@ private struct FeatureAttachmentPreview: View { struct StreamingStatusView: View { let state: FeatureThreadState - let onStop: () -> Void var body: some View { HStack(spacing: 9) { - ProgressView() - .controlSize(.small) - Text(state == .queued ? "Queued" : "Agent is working") - .font(.footnote) - .foregroundStyle(.secondary) - Spacer() - Button("Stop", role: .destructive, action: onStop) - .font(.footnote.weight(.semibold)) + Image(systemName: state == .queued ? "clock" : "circle.dotted") + .foregroundStyle(T3Colors.statusRunning) + Text(state == .queued ? "Queued" : "Agent working") + .foregroundStyle(T3Colors.textSecondary) } - .padding(.vertical, 6) - .accessibilityElement(children: .contain) - } -} - -struct ApprovalRequestView: View { - @Bindable var model: FeatureRootModel - let approval: FeatureApproval - - var body: some View { - VStack(alignment: .leading, spacing: 12) { - Label(approval.title, systemImage: icon) - .font(.subheadline.weight(.semibold)) - .foregroundStyle(.orange) - - Text(approval.detail) - .font(approval.kind == .command ? .caption.monospaced() : .callout) - .foregroundStyle(.secondary) - .textSelection(.enabled) - - HStack(spacing: 8) { - Button("Deny", role: .destructive) { - decide(.deny) - } - .buttonStyle(.bordered) - Spacer() - Button("Always Allow") { - decide(.allowForSession) - } - .buttonStyle(.bordered) - Button("Allow") { - decide(.allowOnce) - } - .buttonStyle(.borderedProminent) - .tint(.white) - .foregroundStyle(.black) - } - .font(.footnote.weight(.semibold)) - } - .padding(13) - .background(Color.orange.opacity(0.09), in: RoundedRectangle(cornerRadius: 12)) - .overlay { - RoundedRectangle(cornerRadius: 12) - .stroke(Color.orange.opacity(0.3), lineWidth: 1) - } - .accessibilityElement(children: .contain) - } - - private var icon: String { - switch approval.kind { - case .command: "terminal" - case .fileRead: "doc.text.magnifyingglass" - case .fileChange, .patch: "doc.badge.ellipsis" - case .other: "exclamationmark.shield" - } - } - - private func decide(_ decision: FeatureApprovalDecision) { - Task { await model.resolveApproval(approval.id, decision: decision) } + .font(.caption.monospaced().weight(.medium)) + .padding(.vertical, 4) + .accessibilityElement(children: .combine) } }