Open History to see the last commit
1import AVFoundation
2import SwiftUI
3import UIKit
4
5struct FeatureModelRefreshError: LocalizedError {
6 var errorDescription: String? { "Couldn’t refresh models." }
7}
8
9struct FeatureComposerUploadStatus {
10 var preparingCount = 0
11 var uploadingCount = 0
12 var failures: [(UUID, String)] = []
13
14 init(states: [(UUID, FeatureAttachmentUploadState?)]) {
15 for (id, state) in states {
16 switch state {
17 case .some(.ready): break
18 case let .some(.failed(message)): failures.append((id, message))
19 case .some(.uploading): uploadingCount += 1
20 case .some(.queued), .none: preparingCount += 1
21 }
22 }
23 }
24
25 var blocksSend: Bool {
26 preparingCount > 0 || uploadingCount > 0 || !failures.isEmpty
27 }
28}
29
30struct FeatureComposerView: View {
31 @SwiftUI.Environment(\.scenePhase) private var scenePhase
32 @SwiftUI.Environment(\.isEnabled) private var isEnabled
33 @State private var isManuallyExpanded = false
34 @State private var isAttachmentFlowActive = false
35 @State private var isModelPickerPresented = false
36 @State private var isTraitsPickerPresented = false
37 @State private var restoresFocusAfterModelPickerDismissal = false
38 @State private var attachmentPreparation = FeatureAttachmentPreparationState()
39 @State private var pathEntries: [FeatureComposerPathEntry] = []
40 @State private var isPathSearchLoading = false
41 @State private var pathSearchError: String?
42 @State private var textSelectionRequest: FeatureComposerTextSelectionRequest?
43 @State private var imageIntakeErrorMessage: String?
44 @State private var pastedTextErrorMessage: String?
45 @State private var pastedTextTask: Task<Void, Never>?
46 @State private var pastedTextGeneration = UUID()
47 @State private var contextImportTask: Task<Void, Never>?
48 @State private var contextImportID: UUID?
49 @State private var textRevision: UInt64 = 0
50 @State private var textObservation = FeatureComposerTextObservation()
51 @State private var voiceInputController = FeatureVoiceInputController()
52 @Binding private var text: String
53 @Binding private var selection: FeatureSelection?
54 @Binding private var attachments: [FeatureDraftAttachment]
55 @Binding private var context: OrchestrationMessageContext?
56
57 private let providers: [FeatureProvider]
58 private let draftOwnerID: String
59 private let environmentID: String?
60 private let draftStorageKey: String?
61 private let environmentIsConnected: Bool
62 private let contextAttachmentResolver: (any FeatureContextAttachmentResolving)?
63 private let attachmentUploads: FeatureAttachmentUploadCoordinator
64 private let attachmentPreferences: FeatureEnvironmentPreferences
65 private let onRefreshModels: (() async throws -> Void)?
66 private let draftSaveError: String?
67 private let onRetryDraftSave: (() -> Void)?
68 private let onInputPreparationChange: ((Bool) -> Void)?
69 private let threadSelection: FeatureSelection?
70 private let materializesDefaultSelection: Bool
71 private let isSending: Bool
72 private let isWorking: Bool
73 @Binding private var focused: Bool
74 private let contextUsage: Double?
75 private let forceExpanded: Bool
76 private let pendingApprovals: [FeatureApproval]
77 private let pendingUserInputs: [FeatureUserInput]
78 private let resolvingRequestIDs: Set<String>
79 private let powerFeatures: FeatureComposerPowerFeatures
80 private let onSend: () -> Void
81 private let onStop: () -> Void
82 private let showsKeyboardDismissControl: Bool
83 private let onDismissKeyboard: (() -> Void)?
84 private let onApprovalDecision: ((String, FeatureApprovalDecision) -> Void)?
85 private let onUserInputSubmit: ((String, [String: FeatureInputAnswer], [String: [FeatureUploadAttachment]]) async -> Void)?
86 private let onUserInputDismiss: ((String) async -> Void)?
87
88 init(
89 text: Binding<String>,
90 selection: Binding<FeatureSelection?>,
91 attachments: Binding<[FeatureDraftAttachment]>,
92 draftOwnerID: String,
93 environmentID: String?,
94 draftStorageKey: String?,
95 environmentIsConnected: Bool,
96 attachmentUploads: FeatureAttachmentUploadCoordinator,
97 attachmentPreferences: FeatureEnvironmentPreferences,
98 providers: [FeatureProvider],
99 threadSelection: FeatureSelection?,
100 materializesDefaultSelection: Bool = true,
101 isSending: Bool,
102 isWorking: Bool,
103 focused: Binding<Bool>,
104 onSend: @escaping () -> Void,
105 onStop: @escaping () -> Void,
106 contextUsage: Double? = nil,
107 forceExpanded: Bool = false,
108 pendingApprovals: [FeatureApproval] = [],
109 pendingUserInputs: [FeatureUserInput] = [],
110 resolvingRequestIDs: Set<String> = [],
111 powerFeatures: FeatureComposerPowerFeatures = .disabled,
112 showsKeyboardDismissControl: Bool = false,
113 onDismissKeyboard: (() -> Void)? = nil,
114 onApprovalDecision: ((String, FeatureApprovalDecision) -> Void)? = nil,
115 onUserInputSubmit: ((String, [String: FeatureInputAnswer], [String: [FeatureUploadAttachment]]) async -> Void)? = nil,
116 onUserInputDismiss: ((String) async -> Void)? = nil,
117 onRefreshModels: (() async throws -> Void)? = nil,
118 draftSaveError: String? = nil,
119 onRetryDraftSave: (() -> Void)? = nil,
120 context: Binding<OrchestrationMessageContext?> = .constant(nil),
121 onInputPreparationChange: ((Bool) -> Void)? = nil,
122 contextAttachmentResolver: (any FeatureContextAttachmentResolving)? = nil
123 ) {
124 _text = text
125 _selection = selection
126 _attachments = attachments
127 _context = context
128 self.contextAttachmentResolver = contextAttachmentResolver
129 self.draftOwnerID = draftOwnerID
130 self.environmentID = environmentID
131 self.draftStorageKey = draftStorageKey
132 self.environmentIsConnected = environmentIsConnected
133 self.attachmentUploads = attachmentUploads
134 self.attachmentPreferences = attachmentPreferences
135 self.onInputPreparationChange = onInputPreparationChange
136 self.onRefreshModels = onRefreshModels
137 self.draftSaveError = draftSaveError
138 self.onRetryDraftSave = onRetryDraftSave
139 self.providers = providers
140 self.threadSelection = threadSelection
141 self.materializesDefaultSelection = materializesDefaultSelection
142 self.isSending = isSending
143 self.isWorking = isWorking
144 _focused = focused
145 self.onSend = onSend
146 self.onStop = onStop
147 self.contextUsage = contextUsage
148 self.forceExpanded = forceExpanded
149 self.pendingApprovals = pendingApprovals
150 self.pendingUserInputs = pendingUserInputs
151 self.resolvingRequestIDs = resolvingRequestIDs
152 self.powerFeatures = powerFeatures
153 self.showsKeyboardDismissControl = showsKeyboardDismissControl
154 self.onDismissKeyboard = onDismissKeyboard
155 self.onApprovalDecision = onApprovalDecision
156 self.onUserInputSubmit = onUserInputSubmit
157 self.onUserInputDismiss = onUserInputDismiss
158 }
159
160 var body: some View {
161 composerSurface
162 .overlay(alignment: .top) {
163 if showsCommandMenu, let trigger = composerTrigger {
164 // Offset by the menu's deterministic height so it sits
165 // fully above the composer and the active `$`/`@`/`/`
166 // token stays readable while typing. An alignment-guide
167 // override here never actually moved the menu, which
168 // left it covering the text entry.
169 FeatureComposerCommandPopover(
170 triggerKind: trigger.kind,
171 items: commandMenuItems,
172 isLoading: isPathSearchLoading,
173 errorMessage: pathSearchError,
174 pathSearchAvailable: powerFeatures.searchPaths != nil,
175 onSelect: selectCommandItem
176 )
177 .offset(
178 y: -(FeatureComposerCommandPopover.height(
179 forItemCount: commandMenuItems.count
180 ) + 12)
181 )
182 }
183 }
184 .padding(.horizontal, 12)
185 .padding(.top, 12)
186 .padding(.bottom, 10)
187 .background {
188 LinearGradient(
189 colors: [
190 .clear,
191 T3Colors.background.opacity(0.94),
192 T3Colors.background,
193 ],
194 startPoint: .top,
195 endPoint: .bottom
196 )
197 .ignoresSafeArea()
198 }
199 .onChange(of: focused) {
200 if FeatureComposerCollapsePolicy.shouldCollapse(
201 isFocused: focused,
202 textIsEmpty: textIsEmpty,
203 attachmentsAreEmpty: attachments.isEmpty,
204 isAttachmentFlowActive: isAttachmentFlowActive
205 || isModelPickerPresented
206 || isTraitsPickerPresented,
207 isPreparingAttachments: attachmentPreparation.isPreparing
208 ) {
209 isManuallyExpanded = false
210 }
211 }
212 .task(id: pathSearchRequest) {
213 await updatePathSearch()
214 }
215 .onAppear {
216 synchronizeVoiceDraft(ownerChanged: false)
217 }
218 .onDisappear {
219 voiceInputController.cancel()
220 pastedTextTask?.cancel()
221 pastedTextGeneration = UUID()
222 contextImportTask?.cancel()
223 }
224 .onChange(of: text) { previous, _ in
225 textRevision &+= 1
226 synchronizeVoiceDraft(ownerChanged: false)
227 removeUnlinkedContextAttachments(previousText: previous)
228 }
229 .onChange(of: attachments) { previous, _ in
230 removeDeletedAttachmentReferences(previousAttachments: previous)
231 }
232 .onChange(of: draftOwnerID) {
233 synchronizeVoiceDraft(ownerChanged: true)
234 pastedTextTask?.cancel()
235 pastedTextGeneration = UUID()
236 contextImportTask?.cancel()
237 }
238 .onChange(of: environmentID) {
239 contextImportTask?.cancel()
240 pastedTextTask?.cancel()
241 pastedTextGeneration = UUID()
242 }
243 .onChange(of: voiceInputController.pendingCommit?.id) {
244 applyPendingVoiceCommit()
245 }
246 .onChange(of: scenePhase) { _, phase in
247 if phase == .background {
248 voiceInputController.appMovedToBackground()
249 }
250 }
251 .onReceive(NotificationCenter.default.publisher(
252 for: AVAudioSession.interruptionNotification
253 )) { notification in
254 guard let rawType = notification.userInfo?[AVAudioSessionInterruptionTypeKey]
255 as? UInt,
256 AVAudioSession.InterruptionType(rawValue: rawType) == .began else { return }
257 voiceInputController.recordingWasInterrupted()
258 }
259 .alert(
260 "Couldn’t add image",
261 isPresented: Binding(
262 get: { imageIntakeErrorMessage != nil },
263 set: { if !$0 { imageIntakeErrorMessage = nil } }
264 )
265 ) {
266 Button("OK") { imageIntakeErrorMessage = nil }
267 } message: {
268 Text(imageIntakeErrorMessage ?? "")
269 }
270 .alert(
271 "Clipboard error",
272 isPresented: Binding(
273 get: { pastedTextErrorMessage != nil },
274 set: { if !$0 { pastedTextErrorMessage = nil } }
275 )
276 ) {
277 Button("OK") { pastedTextErrorMessage = nil }
278 } message: {
279 Text(pastedTextErrorMessage ?? "")
280 }
281 }
282
283 private var composerSurface: some View {
284 composerSurfaceContent
285 .frame(maxWidth: T3Metrics.readingWidth)
286 .frame(maxWidth: .infinity)
287 }
288
289 private var composerSurfaceContent: some View {
290 VStack(spacing: 0) {
291 if let approval = pendingApprovals.first, let onApprovalDecision {
292 FeatureComposerApprovalPanel(
293 approval: approval,
294 position: 1,
295 total: pendingApprovals.count,
296 isResponding: resolvingRequestIDs.contains(approval.id),
297 onDecision: { decision in
298 onApprovalDecision(approval.id, decision)
299 },
300 onCancelTurn: onStop
301 )
302 } else if let input = pendingUserInputs.first, let onUserInputSubmit {
303 FeatureComposerUserInputPanel(
304 input: input,
305 isResponding: resolvingRequestIDs.contains(input.id),
306 onSubmit: { answers, attachments in
307 await onUserInputSubmit(input.id, answers, attachments)
308 },
309 onDismiss: onUserInputDismiss.map { dismiss in { await dismiss(input.id) } },
310 environmentID: environmentID,
311 attachmentPreferences: attachmentPreferences
312 )
313 } else if isExpanded {
314 expandedComposer
315 } else {
316 collapsedComposer
317 }
318 }
319 .background(T3Colors.input.opacity(0.98), in: composerShape)
320 .overlay {
321 composerShape
322 .stroke(T3Colors.inputBorder, lineWidth: 1)
323 }
324 .clipShape(composerShape)
325 .onChange(of: attachmentPreparation.isPreparing || isAttachmentFlowActive || voiceInputController.isBusy || contextImportID != nil, initial: true) { _, busy in
326 onInputPreparationChange?(busy)
327 }
328 .modifier(
329 FeatureComposerImageDrop(
330 isEnabled: imagesAllowed && !voiceInputController.isBusy && contextImportID == nil,
331 shape: composerShape,
332 onDropImages: attachDroppedImages
333 )
334 )
335 }
336
337 private var collapsedComposer: some View {
338 HStack(spacing: 4) {
339 Button {
340 isManuallyExpanded = true
341 Task { @MainActor in
342 await Task.yield()
343 focused = true
344 }
345 } label: {
346 Text(composerPlaceholder)
347 .font(T3Typography.composer)
348 .foregroundStyle(T3Colors.textTertiary)
349 .frame(maxWidth: .infinity, alignment: .leading)
350 .contentShape(Rectangle())
351 }
352 .buttonStyle(.plain)
353 .frame(minHeight: T3Metrics.minimumTapTarget)
354 .accessibilityLabel("Message agent")
355 .accessibilityHint("Opens the message editor")
356
357 submitButton
358 .padding(.trailing, 7)
359
360 if voiceInputController.isSupported {
361 voiceInputButton
362 .padding(.trailing, 3)
363 }
364 }
365 .padding(.leading, 14)
366 .padding(.vertical, 7)
367 }
368
369 private var expandedComposer: some View {
370 VStack(spacing: 0) {
371 if !attachments.isEmpty {
372 FeatureAttachmentStrip(attachments: $attachments)
373 .padding(.horizontal, 12)
374 .padding(.top, 3)
375 .padding(.bottom, 8)
376 .fixedSize(horizontal: false, vertical: true)
377
378 Divider()
379 .overlay(T3Colors.separator)
380 .padding(.horizontal, 13)
381 }
382
383 // Return is always editing input. Sending is deliberately
384 // button-only, which is UITextView's native return behavior.
385 ZStack(alignment: .topLeading) {
386 FeatureComposerTextInput(
387 text: $text,
388 focused: $focused,
389 placeholder: composerPlaceholder,
390 acceptsImages: imagesAllowed,
391 isReadOnly: voiceInputController.isBusy || !isEnabled || contextImportID != nil,
392 skills: powerFeatures.enabledSkills,
393 selectionRequest: textSelectionRequest,
394 onSelectionChange: handleTextSelectionChange,
395 onPasteImages: attachImageProviders,
396 onDismissKeyboard: onDismissKeyboard,
397 maximumPastedTextBytes: maximumPastedTextBytes,
398 onPasteTextAttachment: attachPastedText,
399 onPasteTextError: { pastedTextErrorMessage = $0 },
400 draftOwnerID: draftOwnerID,
401 onCopyContext: copyContext,
402 onPasteContext: pasteContext
403 )
404 .padding(.horizontal, 16)
405 .padding(.top, 14)
406
407 if text.isEmpty {
408 Text(composerPlaceholder)
409 .font(T3Typography.composer)
410 .foregroundStyle(T3Colors.textTertiary)
411 .padding(.horizontal, 16)
412 .padding(.top, 14)
413 .allowsHitTesting(false)
414 .accessibilityHidden(true)
415 }
416 }
417 .padding(.bottom, 7)
418 .frame(minHeight: 62, alignment: .top)
419 .layoutPriority(1)
420 .clipped()
421
422 if let attachmentBlocker {
423 Label(attachmentBlocker, systemImage: "exclamationmark.circle")
424 .font(T3Typography.supporting)
425 .foregroundStyle(T3Colors.warning)
426 .frame(maxWidth: .infinity, alignment: .leading)
427 .padding(.horizontal, 15)
428 .padding(.bottom, 4)
429 }
430
431 if attachmentPreparation.isPreparing {
432 Label(attachmentPreparation.statusLabel, systemImage: "hourglass")
433 .font(T3Typography.supporting)
434 .foregroundStyle(T3Colors.textSecondary)
435 .frame(maxWidth: .infinity, alignment: .leading)
436 .padding(.horizontal, 15)
437 .padding(.bottom, 4)
438 .accessibilityIdentifier("attachment-preparing")
439 }
440
441 if contextImportID != nil {
442 HStack {
443 Text("Importing context")
444 Spacer()
445 Button("Cancel paste") { contextImportTask?.cancel() }
446 }
447 .font(T3Typography.supporting)
448 .padding(.horizontal, 15)
449 .padding(.bottom, 4)
450 }
451
452 if let draftSaveError {
453 HStack(spacing: 8) {
454 Text(draftSaveError).lineLimit(3)
455 Spacer(minLength: 0)
456 if let onRetryDraftSave {
457 Button("Retry", action: onRetryDraftSave)
458 }
459 }
460 .font(T3Typography.supporting)
461 .foregroundStyle(T3Colors.danger)
462 .padding(.horizontal, 15)
463 .padding(.bottom, 4)
464 .accessibilityIdentifier("composer-draft-save-error")
465 } else if uploadStatus.blocksSend {
466 uploadStatusView(uploadStatus)
467 }
468
469 if voiceInputController.phase == .error {
470 voiceInputError
471 }
472
473 composerFooter
474 .disabled(contextImportID != nil)
475 .fixedSize(horizontal: false, vertical: true)
476 .layoutPriority(1)
477 }
478 }
479
480 private var composerFooter: some View {
481 Group {
482 if voiceInputController.isBusy {
483 voiceInputFooter
484 } else {
485 standardComposerFooter
486 }
487 }
488 }
489
490 private var standardComposerFooter: some View {
491 HStack(spacing: 2) {
492 if FeatureComposerKeyboardDismissPolicy.showsDismissControl(
493 isFocused: focused,
494 isEnabled: showsKeyboardDismissControl,
495 canDismiss: onDismissKeyboard != nil
496 ) {
497 dismissKeyboardButton
498 }
499
500 FeatureImageAttachmentPicker(
501 attachments: $attachments,
502 preparationState: $attachmentPreparation,
503 isFlowActive: $isAttachmentFlowActive,
504 draftOwnerID: draftOwnerID,
505 environmentID: environmentID,
506 imagesAllowed: imagesAllowed,
507 maximumFileBytes: attachmentPreferences.maxFileAttachmentBytes
508 )
509
510 ProviderModelPicker(
511 providers: providers,
512 selection: $selection,
513 style: .compact,
514 threadSelection: threadSelection,
515 materializesDefaultSelection: materializesDefaultSelection,
516 onRefresh: onRefreshModels,
517 onPresentationChange: handleModelPickerPresentation
518 )
519 .frame(maxWidth: 220, alignment: .leading)
520 .layoutPriority(1)
521
522 if let traitsControl {
523 traitsPicker(traitsControl)
524 .frame(minWidth: 28, maxWidth: 148, alignment: .trailing)
525 .fixedSize(horizontal: true, vertical: false)
526 .layoutPriority(2)
527 }
528
529 Spacer(minLength: 0)
530
531 if voiceInputController.isSupported {
532 voiceInputButton
533 }
534
535 if let contextUsage {
536 FeatureContextMeter(usage: contextUsage)
537 }
538
539 submitButton
540 .padding(.leading, 4)
541 }
542 .padding(.horizontal, 7)
543 .padding(.top, 2)
544 .padding(.bottom, 8)
545 }
546
547 private var dismissKeyboardButton: some View {
548 Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down", action: dismissKeyboard)
549 .labelStyle(.iconOnly)
550 .font(.system(size: 15, weight: .medium))
551 .foregroundStyle(T3Colors.textSecondary)
552 .frame(width: T3Metrics.minimumTapTarget, height: T3Metrics.minimumTapTarget)
553 .contentShape(Rectangle())
554 .buttonStyle(.plain)
555 .accessibilityHint("Keeps your draft and shows the thread")
556 .accessibilityIdentifier("composer-dismiss-keyboard")
557 }
558
559 private func dismissKeyboard() {
560 onDismissKeyboard?()
561 }
562
563 private var voiceInputButton: some View {
564 Button(action: startVoiceInput) {
565 Image(systemName: "mic")
566 .font(.system(size: 15, weight: .semibold))
567 .foregroundStyle(T3Colors.textSecondary)
568 .frame(width: T3Metrics.minimumTapTarget, height: T3Metrics.minimumTapTarget)
569 .contentShape(Rectangle())
570 }
571 .buttonStyle(.plain)
572 .accessibilityLabel("Start voice input")
573 .accessibilityIdentifier("voice-input-start")
574 }
575
576 private var voiceInputFooter: some View {
577 HStack(spacing: 8) {
578 voiceInputStatus
579 .font(T3Typography.supporting)
580 .foregroundStyle(T3Colors.textSecondary)
581
582 Spacer(minLength: 0)
583
584 Button("Cancel") {
585 voiceInputController.cancel()
586 }
587 .font(T3Typography.supporting)
588 .foregroundStyle(T3Colors.textSecondary)
589 .frame(minHeight: T3Metrics.minimumTapTarget)
590
591 if voiceInputController.phase == .recording {
592 Button("Stop") {
593 voiceInputController.stop()
594 }
595 .font(T3Typography.supporting.weight(.semibold))
596 .foregroundStyle(.white)
597 .padding(.horizontal, 12)
598 .frame(minHeight: 34)
599 .background(T3Colors.accent, in: Capsule())
600 .frame(minHeight: T3Metrics.minimumTapTarget)
601 .accessibilityLabel("Stop recording and transcribe")
602 }
603 }
604 .padding(.horizontal, 12)
605 .padding(.top, 2)
606 .padding(.bottom, 8)
607 }
608
609 @ViewBuilder
610 private var voiceInputStatus: some View {
611 switch voiceInputController.phase {
612 case .preparing:
613 Text("Preparing")
614 case .recording:
615 TimelineView(.periodic(from: .now, by: 1)) { context in
616 Text("Recording \(voiceRecordingDuration(at: context.date))")
617 .monospacedDigit()
618 }
619 case .transcribing:
620 Text("Transcribing")
621 case .idle, .error:
622 EmptyView()
623 }
624 }
625
626 private var voiceInputError: some View {
627 HStack(spacing: 8) {
628 Text(voiceInputController.errorMessage ?? "Voice input failed.")
629 .font(T3Typography.supporting)
630 .foregroundStyle(T3Colors.danger)
631 .frame(maxWidth: .infinity, alignment: .leading)
632
633 if let action = voiceInputController.errorAction {
634 Button(action == .settings ? "Settings" : "Retry") {
635 if action == .settings,
636 let url = URL(string: UIApplication.openSettingsURLString) {
637 UIApplication.shared.open(url)
638 } else {
639 startVoiceInput()
640 }
641 }
642 .font(T3Typography.supporting.weight(.semibold))
643 }
644
645 Button("Dismiss") {
646 voiceInputController.cancel()
647 }
648 .font(T3Typography.supporting)
649 .foregroundStyle(T3Colors.textSecondary)
650 }
651 .padding(.horizontal, 15)
652 .padding(.bottom, 4)
653 }
654
655 /// The popover keeps all descriptor sections together and preserves their
656 /// catalog order, including option descriptions that a system Menu would
657 /// flatten away.
658 private func traitsPicker(_ control: FeatureComposerTraitsControl) -> some View {
659 Button {
660 isTraitsPickerPresented.toggle()
661 } label: {
662 traitsPickerLabel(control)
663 .frame(
664 minWidth: T3Metrics.minimumTapTarget,
665 minHeight: T3Metrics.minimumTapTarget
666 )
667 .contentShape(Rectangle())
668 }
669 .buttonStyle(.plain)
670 .popover(
671 isPresented: $isTraitsPickerPresented,
672 attachmentAnchor: .rect(.bounds),
673 arrowEdge: .bottom
674 ) {
675 FeatureComposerTraitsMenu(control: control) { descriptorID, choiceID in
676 selection = control.selection(choosing: choiceID, in: descriptorID)
677 isTraitsPickerPresented = false
678 }
679 .presentationCompactAdaptation(.popover)
680 }
681 .accessibilityLabel("Model traits")
682 .accessibilityValue(control.triggerLabel)
683 .accessibilityIdentifier("composer-traits-picker")
684 }
685
686 private func traitsPickerLabel(_ control: FeatureComposerTraitsControl) -> some View {
687 HStack(spacing: 3) {
688 if control.showsFastModeIcon {
689 Image(systemName: "bolt.fill")
690 .font(.system(size: 10, weight: .semibold))
691 .accessibilityHidden(true)
692 }
693 Text(control.triggerLabel)
694 .lineLimit(1)
695 .truncationMode(.tail)
696 Image(systemName: "chevron.up.chevron.down")
697 .font(.system(size: 8, weight: .bold))
698 .fixedSize()
699 }
700 .font(T3Typography.supporting)
701 .foregroundStyle(T3Colors.textSecondary)
702 .contentShape(Rectangle())
703 }
704
705 private var submitButton: some View {
706 Button(action: performPrimaryAction) {
707 Image(systemName: submitSymbol)
708 .font(.system(size: showsStop ? 11 : 14, weight: .bold))
709 .foregroundStyle(.white)
710 .frame(width: 34, height: 34)
711 .background(showsStop ? T3Colors.danger : T3Colors.accent, in: Circle())
712 .frame(width: T3Metrics.minimumTapTarget, height: T3Metrics.minimumTapTarget)
713 .contentShape(Rectangle())
714 }
715 .buttonStyle(.plain)
716 .disabled(submitDisabled)
717 .opacity(submitDisabled ? 0.3 : 1)
718 .accessibilityLabel(submitAccessibilityLabel)
719 .accessibilityIdentifier(showsStop ? "thread-stop" : "message-send")
720 }
721
722 private var composerPlaceholder: String {
723 isWorking ? "Queue a message…" : "Ask anything…"
724 }
725
726 private var submitSymbol: String {
727 if isSending { return "ellipsis" }
728 return showsStop ? "stop.fill" : "arrow.up"
729 }
730
731 private var submitAccessibilityLabel: String {
732 if isSending { return "Sending message" }
733 if showsStop { return "Stop agent" }
734 return isWorking ? "Queue message" : "Send message"
735 }
736
737 private var composerShape: RoundedRectangle {
738 RoundedRectangle(cornerRadius: 22, style: .continuous)
739 }
740
741 private var isExpanded: Bool {
742 forceExpanded
743 || isManuallyExpanded
744 || focused
745 || !textIsEmpty
746 || !attachments.isEmpty
747 || attachmentPreparation.isPreparing
748 || voiceInputController.isBusy
749 || voiceInputController.phase == .error
750 }
751
752 private var showsStop: Bool {
753 isWorking && textIsEmpty && attachments.isEmpty
754 }
755
756 private var submitDisabled: Bool {
757 isSending || (!showsStop && !canSend)
758 }
759
760 private var textIsEmpty: Bool {
761 text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
762 }
763
764 private var canSend: Bool {
765 guard composerTrigger?.kind != .model else { return false }
766 return FeatureComposerSubmissionEligibility.canSend(
767 text: text,
768 attachmentCount: attachments.count,
769 imagesAllowed: imagesAllowed,
770 filesAllowed: attachmentPreferences.maxFileAttachmentBytes != nil,
771 containsImages: attachments.contains { $0.mimeType.hasPrefix("image/") },
772 containsFiles: attachments.contains { !$0.mimeType.hasPrefix("image/") },
773 isSending: isSending,
774 preparationState: attachmentPreparation
775 ) && !uploadStatus.blocksSend
776 }
777
778 private var imagesAllowed: Bool {
779 DailyUXModelOptions.supportsImages(
780 selection: selection ?? threadSelection,
781 providers: providers
782 )
783 }
784
785 private var attachmentBlocker: String? {
786 if attachments.contains(where: { !$0.mimeType.hasPrefix("image/") }),
787 attachmentPreferences.maxFileAttachmentBytes == nil {
788 return "This environment does not accept file attachments"
789 }
790 if attachments.contains(where: { $0.mimeType.hasPrefix("image/") }), !imagesAllowed {
791 return "Choose a model that accepts images"
792 }
793 return nil
794 }
795
796 private var applicableUploadStates: [(UUID, FeatureAttachmentUploadState?)] {
797 guard environmentIsConnected, let environmentID, draftStorageKey != nil else { return [] }
798 return attachments.compactMap { attachment in
799 let isImage = attachment.mimeType.hasPrefix("image/")
800 let uploadsHere = isImage
801 ? attachmentPreferences.supportsImageUploads
802 : attachmentPreferences.maxFileAttachmentBytes != nil
803 guard uploadsHere else { return nil }
804 return (
805 attachment.id,
806 attachmentUploads.state(
807 environmentID: environmentID,
808 attachmentID: attachment.id
809 )
810 )
811 }
812 }
813
814 private var uploadStatus: FeatureComposerUploadStatus {
815 FeatureComposerUploadStatus(states: applicableUploadStates)
816 }
817
818 private func uploadStatusView(_ status: FeatureComposerUploadStatus) -> some View {
819 VStack(alignment: .leading, spacing: 4) {
820 if status.preparingCount > 0 {
821 Text("Preparing \(status.preparingCount) attachment\(status.preparingCount == 1 ? "" : "s")")
822 }
823 if status.uploadingCount > 0 {
824 Text("Uploading \(status.uploadingCount) attachment\(status.uploadingCount == 1 ? "" : "s")")
825 }
826 ForEach(status.failures, id: \.0) { failure in
827 HStack(spacing: 8) {
828 Text(failure.1).lineLimit(2)
829 Spacer(minLength: 0)
830 Button("Retry") {
831 guard let environmentID else { return }
832 attachmentUploads.retry(
833 environmentID: environmentID,
834 attachmentID: failure.0
835 )
836 }
837 }
838 }
839 }
840 .font(T3Typography.supporting)
841 .foregroundStyle(status.failures.isEmpty ? T3Colors.textSecondary : T3Colors.danger)
842 .frame(maxWidth: .infinity, alignment: .leading)
843 .padding(.horizontal, 15)
844 .padding(.bottom, 4)
845 .accessibilityIdentifier("attachment-upload-status")
846 }
847
848 private var traitsControl: FeatureComposerTraitsControl? {
849 FeatureComposerTraitsControl.resolve(
850 explicit: selection,
851 inherited: threadSelection,
852 providers: providers,
853 materializesDefaultSelection: materializesDefaultSelection
854 )
855 }
856
857 /// Trigger detection walks the whole draft with character indices and is
858 /// read from several computed properties per body evaluation, so one parse
859 /// per keystroke is memoized instead of four.
860 private final class TriggerMemo {
861 var text: String?
862 var trigger: FeatureComposerTrigger?
863 }
864
865 @State private var triggerMemo = TriggerMemo()
866
867 private var composerTrigger: FeatureComposerTrigger? {
868 if triggerMemo.text == text { return triggerMemo.trigger }
869 let trigger = FeatureComposerTriggerParser.detect(in: text)
870 triggerMemo.text = text
871 triggerMemo.trigger = trigger
872 return trigger
873 }
874
875 private var commandMenuItems: [FeatureComposerMenuItem] {
876 guard let composerTrigger else { return [] }
877 return FeatureComposerMenuBuilder.items(
878 trigger: composerTrigger,
879 providers: providers,
880 currentSelection: selection,
881 threadSelection: threadSelection,
882 powerFeatures: powerFeatures,
883 pathEntries: pathEntries
884 )
885 }
886
887 private var showsCommandMenu: Bool {
888 isExpanded
889 && !voiceInputController.isBusy
890 && pendingApprovals.isEmpty
891 && pendingUserInputs.isEmpty
892 && composerTrigger != nil
893 }
894
895 private var pathSearchRequest: FeatureComposerPathSearchRequest? {
896 guard let trigger = composerTrigger,
897 trigger.kind == .path,
898 powerFeatures.searchPaths != nil else {
899 return nil
900 }
901 let query = trigger.query.trimmingCharacters(in: .whitespacesAndNewlines)
902 guard !query.isEmpty else { return nil }
903 return FeatureComposerPathSearchRequest(
904 scopeID: powerFeatures.pathSearchScopeID,
905 query: query
906 )
907 }
908
909 @MainActor
910 private func updatePathSearch() async {
911 guard let request = pathSearchRequest, let searchPaths = powerFeatures.searchPaths else {
912 pathEntries = []
913 isPathSearchLoading = false
914 pathSearchError = nil
915 return
916 }
917
918 pathEntries = []
919 pathSearchError = nil
920 isPathSearchLoading = true
921 do {
922 try await Task.sleep(for: .milliseconds(140))
923 let result = try await searchPaths(request.query)
924 guard !Task.isCancelled else { return }
925 pathEntries = result
926 isPathSearchLoading = false
927 } catch is CancellationError {
928 return
929 } catch {
930 guard !Task.isCancelled else { return }
931 pathSearchError = "Couldn’t search files."
932 isPathSearchLoading = false
933 }
934 }
935
936 private func contextReference(label: String, payload: ComposerContextRecord.Payload) throws -> String {
937 let record = ComposerContextRecord(label: label, payload: payload)
938 context = try FeatureComposerContext.merge(ComposerContextReferences.referenced(context, text: text), .init(records: [record]))
939 return ComposerContextReferences.format(record) + " "
940 }
941
942 private func selectCommandItem(_ item: FeatureComposerMenuItem) {
943 guard let trigger = composerTrigger else { return }
944 let replacement: String
945 do {
946 switch item {
947 case .modelCommand:
948 replacement = "/model "
949 case let .model(nextSelection, _, _):
950 selection = nextSelection
951 replacement = ""
952 case let .providerCommand(command):
953 replacement = "/\(command.name) "
954 case let .skill(skill):
955 if skill.userInvocationOnly == true {
956 replacement = skill.invocation
957 } else {
958 replacement = try contextReference(label: skill.invocationDisplayName, payload: .skill(.init(name: skill.name)))
959 }
960 case let .path(entry):
961 replacement = try contextReference(label: entry.name, payload: .mention(.init(path: entry.path)))
962 }
963 } catch {
964 pathSearchError = error.localizedDescription
965 return
966 }
967 let nextCursorLocation = FeatureComposerTextSelectionPolicy.cursorLocation(
968 afterReplacing: trigger.range,
969 in: text,
970 with: replacement
971 )
972 text = FeatureComposerTriggerParser.replacing(
973 trigger.range,
974 in: text,
975 with: replacement
976 )
977 // Publish the text first so the representable cannot consume and clamp
978 // this request against the pre-replacement draft.
979 textSelectionRequest = FeatureComposerTextSelectionRequest(
980 location: nextCursorLocation
981 )
982 pathEntries = []
983 pathSearchError = nil
984 Task { @MainActor in
985 await Task.yield()
986 focused = true
987 }
988 }
989
990 private func performPrimaryAction() {
991 if showsStop {
992 onStop()
993 } else if FeatureComposerSubmissionPolicy.allowsSend(for: .explicitButton),
994 canSend {
995 onSend()
996 }
997 }
998
999 private func startVoiceInput() {
1000 synchronizeVoiceDraft(ownerChanged: false)
1001 voiceInputController.start()
1002 }
1003
1004 private func handleTextSelectionChange(_ selection: NSRange) {
1005 textObservation.selection = selection
1006 voiceInputController.updateSelection(selection)
1007 }
1008
1009 private func synchronizeVoiceDraft(ownerChanged: Bool) {
1010 let snapshot = FeatureVoiceDraftSnapshot(
1011 ownerID: draftOwnerID,
1012 text: text,
1013 revision: textRevision,
1014 selection: textObservation.selection
1015 )
1016 if ownerChanged {
1017 voiceInputController.ownerChanged(to: snapshot)
1018 } else {
1019 voiceInputController.updateDraft(snapshot)
1020 }
1021 }
1022
1023 private func applyPendingVoiceCommit() {
1024 guard let commit = voiceInputController.pendingCommit else { return }
1025 textSelectionRequest = FeatureComposerTextSelectionRequest(
1026 location: commit.caretLocation
1027 )
1028 text = commit.text
1029 voiceInputController.consumePendingCommit()
1030 }
1031
1032 private func voiceRecordingDuration(at date: Date) -> String {
1033 let seconds = max(0, Int(date.timeIntervalSince(
1034 voiceInputController.recordingStartedAt ?? date
1035 )))
1036 return String(format: "%02d:%02d", seconds / 60, seconds % 60)
1037 }
1038
1039 private func handleModelPickerPresentation(_ isPresented: Bool) {
1040 if isPresented {
1041 restoresFocusAfterModelPickerDismissal = focused
1042 isManuallyExpanded = true
1043 isModelPickerPresented = true
1044 return
1045 }
1046
1047 isModelPickerPresented = false
1048 guard restoresFocusAfterModelPickerDismissal else { return }
1049 restoresFocusAfterModelPickerDismissal = false
1050 Task { @MainActor in
1051 await Task.yield()
1052 focused = true
1053 }
1054 }
1055
1056 /// Attaches images arriving from the text view's paste menu or a drag
1057 /// from another app through the same preparation pipeline the attachment
1058 /// picker uses, so sending stays blocked until every image is processed.
1059 private func attachImageProviders(_ providers: [NSItemProvider]) {
1060 guard imagesAllowed, !providers.isEmpty, contextImportID == nil else { return }
1061
1062 guard let plan = FeatureComposerImageIntakePlan.forProviders(
1063 providerCount: providers.count,
1064 attachmentCount: attachments.count,
1065 pendingCount: attachmentPreparation.pendingItemCount
1066 ) else {
1067 imageIntakeErrorMessage = "You can attach up to eight images."
1068 return
1069 }
1070 if plan.droppedCount > 0 {
1071 imageIntakeErrorMessage =
1072 "Some images were not attached because the eight-image limit was reached."
1073 }
1074
1075 let accepted = Array(providers.prefix(plan.acceptedCount))
1076 // Begin every provider request while the paste or drop callback still
1077 // owns access to its item providers. Image processing can finish
1078 // asynchronously after the callback returns.
1079 let loads = accepted.map { provider in
1080 Result { try FeatureImageItemProviderLoader.start(from: provider) }
1081 }
1082 let operation = attachmentPreparation.begin(itemCount: accepted.count)
1083 Task { @MainActor in
1084 defer { attachmentPreparation.finish(operation) }
1085 for (offset, load) in loads.enumerated() {
1086 do {
1087 let data = try await load.get().data()
1088 let attachment = try await Task.detached(priority: .userInitiated) {
1089 try FeatureImageProcessor.attachment(
1090 from: data,
1091 ordinal: plan.firstOrdinal + offset
1092 )
1093 }.value
1094 attachments.append(attachment)
1095 } catch {
1096 imageIntakeErrorMessage = error.localizedDescription
1097 }
1098 }
1099 }
1100 }
1101
1102 private var maximumPastedTextBytes: Int? {
1103 FeaturePastedText.maximumAttachmentBytes(
1104 advertisedMaximum: attachmentPreferences.maxFileAttachmentBytes,
1105 attachmentCount: attachments.count,
1106 pendingCount: attachmentPreparation.pendingItemCount
1107 )
1108 }
1109
1110 private func copyContext(_ selectedText: String) throws -> Bool {
1111 try FeatureContextClipboard.write(
1112 text: selectedText,
1113 source: environmentID.map { .init(environmentId: $0) },
1114 context: context, attachments: attachments
1115 )
1116 }
1117
1118 private func pasteContext(_ content: ComposerContextClipboard.Content, _ originalText: String, _ range: NSRange) {
1119 guard contextImportID == nil, !voiceInputController.isBusy else { return }
1120 pastedTextTask?.cancel()
1121 pastedTextGeneration = UUID()
1122 let originalContext = context
1123 let originalAttachments = attachments
1124 let owner = draftOwnerID
1125 let environment = environmentID
1126 let importID = UUID()
1127 contextImportID = importID
1128 let importer = FeatureContextClipboardImporter(resolver: contextAttachmentResolver)
1129 contextImportTask = Task { @MainActor in
1130 defer {
1131 if contextImportID == importID {
1132 contextImportID = nil
1133 contextImportTask = nil
1134 }
1135 }
1136 do {
1137 guard range.location != NSNotFound, NSMaxRange(range) <= originalText.utf16.count else {
1138 throw ComposerContextClipboardError.draftChanged
1139 }
1140 let remainingText = (originalText as NSString).replacingCharacters(in: range, with: "")
1141 let remainingContext = ComposerContextReferences.referenced(originalContext, text: remainingText)
1142 let removedIDs = FeatureContextClipboardEdit.unlinkedAttachmentIDs(
1143 context: originalContext, previousText: originalText, text: remainingText
1144 )
1145 let remainingAttachmentCount = originalAttachments.filter {
1146 !removedIDs.contains($0.id.uuidString.lowercased())
1147 }.count
1148 let result = try await importer.importContent(
1149 content, attachmentCount: remainingAttachmentCount + attachmentPreparation.pendingItemCount,
1150 contextCount: remainingContext?.records.count ?? 0,
1151 imagesAllowed: imagesAllowed,
1152 maximumFileBytes: attachmentPreferences.maxFileAttachmentBytes
1153 )
1154 var committed = false
1155 defer { if !committed { result.discardFiles(using: importer.fileStore) } }
1156 try Task.checkCancellation()
1157 guard owner == draftOwnerID, environment == environmentID, text == originalText,
1158 context == originalContext, attachments == originalAttachments,
1159 textObservation.selection == range else { throw ComposerContextClipboardError.draftChanged }
1160 for attachment in result.attachments {
1161 if attachment.mimeType.hasPrefix("image/") {
1162 guard imagesAllowed else { throw FeatureAttachmentIntakeError.imagesUnsupported }
1163 } else {
1164 guard let maximum = attachmentPreferences.maxFileAttachmentBytes else { throw FileAttachmentError.unsupported }
1165 guard attachment.byteCount <= maximum else {
1166 throw FileAttachmentError.tooLarge(actualBytes: attachment.byteCount, maximumBytes: maximum)
1167 }
1168 }
1169 }
1170 let edit = try FeatureContextClipboardEdit.apply(
1171 text: originalText, selection: range, context: originalContext,
1172 attachments: originalAttachments, imported: result
1173 )
1174 context = edit.context
1175 text = edit.text
1176 textSelectionRequest = FeatureComposerTextSelectionRequest(location: edit.cursor)
1177 attachments = edit.attachments
1178 committed = true
1179 } catch {
1180 if owner == draftOwnerID, environment == environmentID {
1181 pastedTextErrorMessage = error is CancellationError
1182 ? "Paste cancelled. Your draft has not changed."
1183 : error.localizedDescription
1184 }
1185 }
1186 }
1187 }
1188
1189 private func removeUnlinkedContextAttachments(previousText: String) {
1190 let removedIDs = FeatureContextClipboardEdit.unlinkedAttachmentIDs(
1191 context: context, previousText: previousText, text: text
1192 )
1193 guard !removedIDs.isEmpty else { return }
1194 attachments.removeAll { removedIDs.contains($0.id.uuidString.lowercased()) }
1195 }
1196
1197 private func removeDeletedAttachmentReferences(previousAttachments: [FeatureDraftAttachment]) {
1198 let removedIDs = Set(previousAttachments.map { $0.id.uuidString.lowercased() })
1199 .subtracting(attachments.map { $0.id.uuidString.lowercased() })
1200 guard !removedIDs.isEmpty else { return }
1201 var removedContextIDs = Set((context?.records ?? []).filter {
1202 $0.attachment.map { removedIDs.contains($0.attachmentId.lowercased()) } ?? false
1203 }.map(\.contextId))
1204 for record in context?.records ?? [] {
1205 if case let .previewAnnotation(annotation) = record.payload,
1206 let screenshot = annotation.screenshotContextId, removedContextIDs.contains(screenshot) {
1207 removedContextIDs.insert(record.contextId)
1208 }
1209 }
1210 guard !removedContextIDs.isEmpty else { return }
1211 text = ComposerContextReferences.replace(text) { reference in
1212 removedContextIDs.contains(reference.contextId) ? "" : (text as NSString).substring(with: reference.range)
1213 }
1214 }
1215
1216 private func attachPastedText(_ pastedText: String, commitSelection: @escaping @MainActor () -> Bool) {
1217 guard !voiceInputController.isBusy, contextImportID == nil, !pastedText.isEmpty,
1218 let maximumPastedTextBytes,
1219 pastedText.utf8.count <= maximumPastedTextBytes else {
1220 pastedTextErrorMessage = "Could not attach pasted text. Your draft has not changed."
1221 return
1222 }
1223 pastedTextTask?.cancel()
1224 let generation = UUID()
1225 pastedTextGeneration = generation
1226 let fileName = FeaturePastedText.nextFileName(existingNames: attachments.map(\.filename))
1227 let fileStore = ManagedAttachmentFileStore()
1228 let operation = attachmentPreparation.begin(itemCount: 1)
1229 pastedTextTask = Task { @MainActor in
1230 defer {
1231 attachmentPreparation.finish(operation)
1232 if pastedTextGeneration == generation { pastedTextTask = nil }
1233 }
1234 do {
1235 try Task.checkCancellation()
1236 let attachment = try await Task.detached(priority: .userInitiated) {
1237 try FeaturePastedText.attachment(text: pastedText, fileName: fileName, maximumBytes: maximumPastedTextBytes, fileStore: fileStore)
1238 }.value
1239 var adopted = false
1240 defer {
1241 if !adopted, let file = attachment.ownedFile {
1242 try? fileStore.removeOwnedFile(fileName: file.fileName)
1243 }
1244 }
1245 guard !Task.isCancelled, pastedTextGeneration == generation else { return }
1246 guard attachments.count + attachmentPreparation.pendingItemCount <= FeatureImageAttachmentLimits.maximumCount,
1247 commitSelection() else {
1248 pastedTextErrorMessage = "The draft changed while the file was prepared. Paste again to add it."
1249 return
1250 }
1251 attachments.append(attachment)
1252 adopted = true
1253 } catch {
1254 guard !Task.isCancelled, pastedTextGeneration == generation else { return }
1255 pastedTextErrorMessage = error.localizedDescription
1256 }
1257 }
1258 }
1259
1260 /// A drop is refused outright when images are not accepted, so the drag
1261 /// session shows the system's "not allowed" badge instead of a dead drop.
1262 private func attachDroppedImages(_ providers: [NSItemProvider]) -> Bool {
1263 guard imagesAllowed, !providers.isEmpty, contextImportID == nil else { return false }
1264 attachImageProviders(providers)
1265 return true
1266 }
1267}
1268
1269enum FeatureComposerKeyboardDismissPolicy {
1270 static func showsDismissControl(isFocused: Bool, isEnabled: Bool, canDismiss: Bool) -> Bool {
1271 isFocused && isEnabled && canDismiss
1272 }
1273}
1274
1275private struct FeatureComposerTraitsMenu: View {
1276 let control: FeatureComposerTraitsControl
1277 let onSelect: (String, String) -> Void
1278
1279 var body: some View {
1280 ScrollView {
1281 VStack(spacing: 0) {
1282 ForEach(Array(control.sections.enumerated()), id: \.element.id) { index, section in
1283 if index > 0 {
1284 Divider()
1285 .overlay(T3Colors.separator)
1286 .padding(.vertical, 5)
1287 }
1288 traitSection(section)
1289 }
1290 }
1291 .padding(6)
1292 }
1293 .scrollIndicators(.hidden)
1294 .frame(width: 292)
1295 .frame(maxHeight: 520)
1296 .background(T3Colors.surface)
1297 .accessibilityIdentifier("composer-traits-menu")
1298 }
1299
1300 private func traitSection(_ section: FeatureComposerTraitsControl.Section) -> some View {
1301 VStack(alignment: .leading, spacing: 2) {
1302 Text(section.label)
1303 .font(T3Typography.supportingStrong)
1304 .foregroundStyle(T3Colors.textSecondary)
1305 .padding(.horizontal, 10)
1306 .padding(.top, 5)
1307 .padding(.bottom, 3)
1308
1309 ForEach(section.choices) { choice in
1310 let isCurrent = choice.id == section.currentChoiceID
1311 Button {
1312 onSelect(section.id, choice.id)
1313 } label: {
1314 HStack(alignment: .top, spacing: 10) {
1315 VStack(alignment: .leading, spacing: 2) {
1316 HStack(spacing: 5) {
1317 Text(choice.label)
1318 .font(T3Typography.control)
1319 .foregroundStyle(T3Colors.textPrimary)
1320 .lineLimit(1)
1321 if choice.isDefault {
1322 Text("Default")
1323 .font(.caption2.weight(.semibold))
1324 .foregroundStyle(T3Colors.textSecondary)
1325 .padding(.horizontal, 6)
1326 .padding(.vertical, 2)
1327 .background(T3Colors.subtleStrong, in: Capsule())
1328 }
1329 }
1330 if let detail = choice.detail {
1331 Text(detail)
1332 .font(T3Typography.supporting)
1333 .foregroundStyle(T3Colors.textTertiary)
1334 .fixedSize(horizontal: false, vertical: true)
1335 }
1336 }
1337 Spacer(minLength: 4)
1338 if isCurrent {
1339 Image(systemName: "checkmark")
1340 .font(.system(size: 12, weight: .bold))
1341 .foregroundStyle(T3Colors.accent)
1342 .padding(.top, 3)
1343 }
1344 }
1345 .frame(maxWidth: .infinity, minHeight: 38, alignment: .leading)
1346 .padding(.horizontal, 10)
1347 .padding(.vertical, choice.detail == nil ? 1 : 4)
1348 .background(
1349 isCurrent ? T3Colors.accent.opacity(0.12) : .clear,
1350 in: RoundedRectangle(cornerRadius: 7, style: .continuous)
1351 )
1352 .contentShape(Rectangle())
1353 }
1354 .buttonStyle(.plain)
1355 .accessibilityLabel(choice.label)
1356 .accessibilityValue(
1357 [choice.isDefault ? "Default" : nil, isCurrent ? "Current" : nil]
1358 .compactMap { $0 }
1359 .joined(separator: ", ")
1360 )
1361 .accessibilityIdentifier(
1362 "composer-trait-\(section.id)-choice-\(choice.id)"
1363 )
1364 }
1365 }
1366 .accessibilityElement(children: .contain)
1367 .accessibilityLabel(section.label)
1368 .accessibilityIdentifier("composer-trait-section-\(section.id)")
1369 }
1370}
1371
1372enum FeatureComposerCollapsePolicy {
1373 static func shouldCollapse(
1374 isFocused: Bool,
1375 textIsEmpty: Bool,
1376 attachmentsAreEmpty: Bool,
1377 isAttachmentFlowActive: Bool,
1378 isPreparingAttachments: Bool
1379 ) -> Bool {
1380 !isFocused
1381 && textIsEmpty
1382 && attachmentsAreEmpty
1383 && !isAttachmentFlowActive
1384 && !isPreparingAttachments
1385 }
1386}
1387
1388private struct FeatureComposerPathSearchRequest: Hashable {
1389 let scopeID: String
1390 let query: String
1391}
1392
1393enum FeatureComposerSubmissionEligibility {
1394 static func canSend(
1395 text: String,
1396 attachmentCount: Int,
1397 imagesAllowed: Bool,
1398 filesAllowed: Bool = false,
1399 containsImages: Bool = true,
1400 containsFiles: Bool = false,
1401 isSending: Bool,
1402 preparationState: FeatureAttachmentPreparationState
1403 ) -> Bool {
1404 let hasText = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
1405 let hasAttachments = attachmentCount > 0
1406 return !isSending
1407 && !preparationState.isPreparing
1408 && (hasText || hasAttachments)
1409 && (!hasAttachments || !containsImages || imagesAllowed)
1410 && (!hasAttachments || !containsFiles || filesAllowed)
1411 }
1412}
1413
1414enum FeatureComposerSubmissionIntent: Equatable {
1415 case explicitButton
1416 case returnKey
1417}
1418
1419enum FeatureComposerSubmissionPolicy {
1420 static func allowsSend(for intent: FeatureComposerSubmissionIntent) -> Bool {
1421 intent == .explicitButton
1422 }
1423}
1424
1425private struct FeatureContextMeter: View {
1426 let usage: Double
1427
1428 var body: some View {
1429 ZStack {
1430 Circle()
1431 .stroke(T3Colors.border, lineWidth: 2)
1432 Circle()
1433 .trim(from: 0, to: clampedUsage)
1434 .stroke(
1435 T3Colors.textSecondary,
1436 style: StrokeStyle(lineWidth: 2, lineCap: .round)
1437 )
1438 .rotationEffect(.degrees(-90))
1439 }
1440 .frame(width: 18, height: 18)
1441 .frame(width: 30, height: T3Metrics.minimumTapTarget)
1442 .accessibilityElement()
1443 .accessibilityLabel("Context used")
1444 .accessibilityValue("\(Int((clampedUsage * 100).rounded())) percent")
1445 }
1446
1447 private var clampedUsage: Double {
1448 min(max(usage, 0), 1)
1449 }
1450}