-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathAgentMessageBubble.swift
More file actions
1914 lines (1732 loc) · 72.5 KB
/
Copy pathAgentMessageBubble.swift
File metadata and controls
1914 lines (1732 loc) · 72.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import AppKit
import SwiftUI
// swiftformat:disable environmentEntry
private struct AgentWindowIsFocusedKey: EnvironmentKey {
static let defaultValue = true
}
extension EnvironmentValues {
var agentWindowIsFocused: Bool {
get { self[AgentWindowIsFocusedKey.self] }
set { self[AgentWindowIsFocusedKey.self] = newValue }
}
}
// swiftformat:enable environmentEntry
// MARK: - Message Footer Strip
/// An inline footer strip with timestamp and a subtle copy button.
/// Always rendered inside the bubble layout so the copy button is reliably hoverable.
///
/// Performance notes:
/// - Uses the shared message timestamp formatter so timestamp labels stay consistent.
/// - Observes FontScaleManager so footer text follows Agent Mode text size.
private struct MessageFooterStrip: View {
let text: String
let timestamp: Date
let isTrailing: Bool
var handoffConfig: AgentHandoffConfig?
let hasHandoffButton: Bool
/// When non-nil, shows this message's frozen/live runtime marker beside the timestamp.
var runtimeFooter: AgentMessageRuntimeFooter?
@Environment(\.agentWindowIsFocused) private var agentWindowIsFocused
@State private var isHoveringCopy = false
@State private var showCopied = false
@State private var isHoveringHandoff = false
@State private var showHandoffPopover = false
@ObservedObject private var fontScale = FontScaleManager.shared
private var fontPreset: FontScalePreset {
fontScale.preset
}
var body: some View {
HStack(spacing: 6) {
if isTrailing { Spacer(minLength: 0) }
if isTrailing {
elapsedStatusView
timestampText
handoffButton
copyButton
} else {
copyButton
handoffButton
timestampText
elapsedStatusView
}
if !isTrailing { Spacer(minLength: 0) }
}
.padding(.horizontal, 4)
}
private var timestampText: some View {
MessageTimestampText(date: timestamp)
.font(fontPreset.swiftUIFont(sizeAtNormal: 10))
.foregroundColor(.secondary.opacity(0.7))
}
@ViewBuilder
private var elapsedStatusView: some View {
if let runtimeFooter {
if let completedDate = runtimeFooter.completedDate {
#if DEBUG
let _ = AgentModePerfDiagnostics.increment("timeline.messageFooter.completed")
#endif
let elapsed = AgentRuntimeDurationFormatter.string(from: runtimeFooter.anchorDate, to: completedDate)
Text("\(runtimeFooter.statusText) \(elapsed)")
.font(fontPreset.swiftUIFont(sizeAtNormal: 10))
.foregroundColor(.secondary.opacity(0.7))
.monospacedDigit()
} else if agentWindowIsFocused {
TimelineView(.periodic(from: .now, by: 1)) { timeline in
#if DEBUG
let _ = AgentModePerfDiagnostics.increment("timeline.messageFooter.tick")
#endif
runtimeFooterText(runtimeFooter, now: timeline.date)
}
#if DEBUG
.onAppear {
AgentModePerfDiagnostics.increment("timeline.messageFooter.liveMount")
}
#endif
} else {
#if DEBUG
let _ = AgentModePerfDiagnostics.increment("timeline.messageFooter.unfocused")
#endif
runtimeFooterText(runtimeFooter, now: Date())
}
}
}
private func runtimeFooterText(_ runtimeFooter: AgentMessageRuntimeFooter, now: Date) -> some View {
let elapsed = AgentRuntimeDurationFormatter.string(from: runtimeFooter.anchorDate, to: now)
return Text("\(runtimeFooter.statusText) · \(elapsed)")
.font(fontPreset.swiftUIFont(sizeAtNormal: 10))
.foregroundColor(.secondary.opacity(0.7))
.monospacedDigit()
}
private var copyButton: some View {
Button(action: copyToClipboard) {
Image(systemName: showCopied ? "checkmark" : "doc.on.doc")
.font(.system(size: 10, weight: .medium))
.foregroundColor(
showCopied
? .green
: (isHoveringCopy ? BubbleColors.highContrastCopyIconHover : BubbleColors.copyIconNormal)
)
.frame(width: 16, height: 16)
}
.buttonStyle(PlainButtonStyle())
.onHover { hovering in
withAnimation(.easeInOut(duration: 0.15)) {
isHoveringCopy = hovering
}
}
.hoverTooltip("Copy message")
}
@ViewBuilder
private var handoffButton: some View {
if let config = handoffConfig {
Button {
showHandoffPopover = true
} label: {
Image(systemName: "arrow.branch")
.font(.system(size: 10, weight: .medium))
.foregroundColor(
isHoveringHandoff ? BubbleColors.highContrastCopyIconHover : BubbleColors.copyIconNormal
)
.frame(width: 16, height: 16)
}
.buttonStyle(PlainButtonStyle())
.onHover { hovering in
withAnimation(.easeInOut(duration: 0.15)) {
isHoveringHandoff = hovering
}
}
.hoverTooltip("Handoff to new chat")
.popover(isPresented: $showHandoffPopover, arrowEdge: .bottom) {
AgentHandoffPopover(config: config) {
showHandoffPopover = false
}
}
}
}
private func copyToClipboard() {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(text, forType: .string)
withAnimation(.easeInOut(duration: 0.15)) {
showCopied = true
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
withAnimation(.easeInOut(duration: 0.15)) {
showCopied = false
}
}
}
}
// MARK: - Agent Message Bubble
typealias CodexManagedLoginAction = (@MainActor @escaping (URL) -> Void) async throws -> Bool
/// A bubble view for displaying agent chat items (user, assistant, tool calls, etc.)
@MainActor
struct AgentMessageBubble: View {
let item: AgentChatItem
let isMostRecentEditBubble: Bool
let windowID: Int
let currentWorkspaceID: UUID?
let currentTabID: UUID?
let suppressAskUserTranscriptUI: Bool
let contextBuilderContext: ContextBuilderCardContext?
let promptManager: PromptViewModel?
var handoffConfig: AgentHandoffConfig?
let rawToolResultPayload: String?
let rawToolResultPayloadRenderRevision: Int
let showRunScopedToolCancel: Bool
let cancelActiveToolsAction: (() -> Void)?
let codexManagedLoginAction: CodexManagedLoginAction?
@Environment(\.colorScheme) private var colorScheme
@Environment(\.agentRecentAssistantItemIDs) private var recentAssistantItemIDs
@Environment(\.agentMessageRuntimeFooterByItemID) private var runtimeFooterByItemID
@ObservedObject private var fontScale = FontScaleManager.shared
@State private var isStartingCodexManagedLogin = false
@State private var codexManagedLoginFeedback: String?
@State private var codexManagedLoginCompleted = false
private var fontPreset: FontScalePreset {
fontScale.preset
}
init(
item: AgentChatItem,
isMostRecentEditBubble: Bool = false,
windowID: Int,
currentWorkspaceID: UUID? = nil,
currentTabID: UUID? = nil,
suppressAskUserTranscriptUI: Bool = false,
contextBuilderContext: ContextBuilderCardContext? = nil,
promptManager: PromptViewModel? = nil,
handoffConfig: AgentHandoffConfig? = nil,
rawToolResultPayload: String? = nil,
rawToolResultPayloadRenderRevision: Int = 0,
showRunScopedToolCancel: Bool = false,
cancelActiveToolsAction: (() -> Void)? = nil,
codexManagedLoginAction: CodexManagedLoginAction? = nil
) {
self.item = item
self.isMostRecentEditBubble = isMostRecentEditBubble
self.windowID = windowID
self.currentWorkspaceID = currentWorkspaceID
self.currentTabID = currentTabID
self.suppressAskUserTranscriptUI = suppressAskUserTranscriptUI
self.contextBuilderContext = contextBuilderContext
self.promptManager = promptManager
self.handoffConfig = handoffConfig
self.rawToolResultPayload = rawToolResultPayload
self.rawToolResultPayloadRenderRevision = rawToolResultPayloadRenderRevision
self.showRunScopedToolCancel = showRunScopedToolCancel
self.cancelActiveToolsAction = cancelActiveToolsAction
self.codexManagedLoginAction = codexManagedLoginAction
}
private var runtimeFooter: AgentMessageRuntimeFooter? {
runtimeFooterByItemID[item.id]
}
private var normalizedToolName: String? {
normalizedToolCardName(item.toolName)?.lowercased()
}
private var renderingItem: AgentChatItem {
guard item.kind == .toolResult,
let rawToolResultPayload,
!rawToolResultPayload.isEmpty
else {
return item
}
var updated = item
updated.toolResultJSON = rawToolResultPayload
updated.text = rawToolResultPayload
return updated
}
var body: some View {
let renderItem = renderingItem
switch renderItem.kind {
case .user:
userBubble
case .assistant:
assistantBubble
case .assistantInline:
assistantInline
case .toolCall:
if isHiddenAgentTool(item.toolName) {
EmptyView()
} else if isAskUserTool(item.toolName) {
if suppressAskUserTranscriptUI {
EmptyView()
} else {
askUserQuestionPendingView
}
} else if normalizedToolName == "context_builder", let contextBuilderContext {
ContextBuilderCallCard(item: item, context: contextBuilderContext)
} else {
ToolCardRouter.callView(
for: item,
oracleOpenContext: .init(
windowID: windowID,
workspaceID: currentWorkspaceID,
tabID: currentTabID
),
contextBuilder: contextBuilderContext,
showRunScopedToolCancel: showRunScopedToolCancel,
cancelActiveToolsAction: cancelActiveToolsAction
)
}
case .toolResult:
if isHiddenAgentTool(renderItem.toolName) {
EmptyView()
} else if isAskUserTool(renderItem.toolName) {
askUserQuestionExchangeView
} else if normalizedToolName == "context_builder", let contextBuilderContext {
ContextBuilderResultCard(item: renderItem, context: contextBuilderContext)
.id(rawToolResultPayloadRenderRevision)
} else {
ToolCardRouter.resultView(
for: renderItem,
isMostRecentEditBubble: isMostRecentEditBubble,
oracleOpenContext: .init(
windowID: windowID,
workspaceID: currentWorkspaceID,
tabID: currentTabID
),
contextBuilder: contextBuilderContext,
promptManager: promptManager
)
.id(rawToolResultPayloadRenderRevision)
}
case .system:
systemBubble
case .error:
errorBubble
case .thinking:
thinkingBubble
}
}
// MARK: - User Bubble
private var userBubble: some View {
HStack {
Spacer(minLength: 60)
VStack(alignment: .trailing, spacing: 6) {
if !item.attachments.isEmpty {
HStack(spacing: 0) {
Spacer(minLength: 0)
AgentAttachmentsStrip(
imageAttachments: item.attachments,
taggedFileAttachments: item.taggedFileAttachments,
disabled: true,
allowsRemoval: false
)
.fixedSize(horizontal: true, vertical: false)
}
}
VStack(alignment: .leading, spacing: 6) {
if item.codexGoalMode != nil || item.workflow != nil {
HStack(spacing: 6) {
if let codexGoalMode = item.codexGoalMode {
codexGoalModeBadge(codexGoalMode, hasWorkflow: item.workflow != nil)
}
if let workflow = item.workflow {
workflowBadge(workflow)
}
}
}
if !item.taggedFileAttachments.isEmpty {
TaggedFilesBadge(attachments: item.taggedFileAttachments)
}
CollapsibleUserMessage(text: item.text)
}
.padding(12)
.background(BubbleColors.lightBlue)
.cornerRadius(20)
MessageFooterStrip(text: item.text, timestamp: item.timestamp, isTrailing: true, handoffConfig: handoffConfig, hasHandoffButton: handoffConfig != nil)
}
}
}
private func codexGoalModeBadge(_ metadata: AgentCodexGoalModeMetadata, hasWorkflow: Bool) -> some View {
let labelText: String = switch metadata.action {
case .setObjective:
hasWorkflow ? "/goal context" : "/goal"
case .show:
"/goal show"
case .pause:
"/goal pause"
case .resume:
"/goal resume"
case .clear:
"/goal clear"
}
let tooltip = switch metadata.action {
case .setObjective where hasWorkflow:
"This message set a Codex goal. The selected workflow was applied as goal context, not as a separate user turn."
case .setObjective:
"This message set a Codex goal."
case .show, .pause, .resume, .clear:
"Codex goal control command."
}
return HStack(spacing: 4) {
Image(systemName: "target")
.font(fontPreset.swiftUIFont(sizeAtNormal: 10))
Text(labelText)
.font(fontPreset.swiftUIFont(sizeAtNormal: 11, weight: .semibold))
}
.foregroundColor(.green)
.padding(.horizontal, 8)
.padding(.vertical, 3)
.background(Color.green.opacity(0.15))
.clipShape(Capsule())
.hoverTooltip(tooltip)
.accessibilityLabel(Text(labelText))
.accessibilityHint(Text(tooltip))
}
private func workflowBadge(_ workflow: AgentWorkflowDefinition) -> some View {
HStack(spacing: 4) {
Image(systemName: workflow.iconName)
.font(fontPreset.swiftUIFont(sizeAtNormal: 10))
Text(workflow.displayName)
.font(fontPreset.swiftUIFont(sizeAtNormal: 11, weight: .semibold))
}
.foregroundColor(workflow.accentColor)
.padding(.horizontal, 8)
.padding(.vertical, 3)
.background(workflow.accentColor.opacity(0.15))
.clipShape(Capsule())
}
// MARK: - Assistant Bubble (inline style, no bubble)
private var assistantBubble: some View {
HStack(alignment: .top) {
VStack(alignment: .leading, spacing: 4) {
assistantContent
.frame(maxWidth: .infinity, alignment: .leading)
MessageFooterStrip(
text: item.text,
timestamp: item.timestamp,
isTrailing: false,
handoffConfig: handoffConfig,
hasHandoffButton: handoffConfig != nil,
runtimeFooter: runtimeFooter
)
}
Spacer(minLength: 60)
}
}
// MARK: - Assistant Inline
private var assistantInline: some View {
HStack(alignment: .top) {
VStack(alignment: .leading, spacing: 4) {
assistantContent
.frame(maxWidth: .infinity, alignment: .leading)
MessageFooterStrip(
text: item.text,
timestamp: item.timestamp,
isTrailing: false,
handoffConfig: handoffConfig,
hasHandoffButton: handoffConfig != nil,
runtimeFooter: runtimeFooter
)
}
Spacer(minLength: 60)
}
}
@ViewBuilder
private var assistantContent: some View {
if shouldShowCollapsedAssistantView {
CollapsibleAssistantTranscriptContent(text: item.text)
} else {
MarkdownTextView(
text: item.text,
isMarkdown: true,
allowInteraction: true,
renderCadence: item.isStreaming ? .streamingCoalesced : .immediate
)
}
}
private var shouldShowCollapsedAssistantView: Bool {
guard item.kind == .assistant || item.kind == .assistantInline else { return false }
guard !item.isStreaming else { return false }
guard !recentAssistantItemIDs.contains(item.id) else { return false }
guard item.attachments.isEmpty, item.taggedFileAttachments.isEmpty, item.workflow == nil else { return false }
let lineLimit = 10
#if DEBUG
let diagnosticsStartMS = AgentTextDerivationPerfDiagnostics.start()
#endif
let boundedLineCount = AgentAssistantLineDerivation.lineCount(upTo: lineLimit, in: item.text)
let needsCollapse = !boundedLineCount.isExact || boundedLineCount.count > lineLimit
#if DEBUG
AgentTextDerivationPerfDiagnostics.record(
source: .assistantCollapseCheck,
startMS: diagnosticsStartMS,
text: item.text,
lineCount: boundedLineCount.count,
previewLineCount: lineLimit,
needsCollapse: needsCollapse,
expanded: false,
didSplitFullArray: false,
fields: [
"isStreaming": String(item.isStreaming),
"lineCountIsExact": String(boundedLineCount.isExact)
]
)
#endif
return needsCollapse
}
// MARK: - Tool Call Bubble
private var toolCallBubble: some View {
let presentation = toolCallBubblePresentation(toolName: item.toolName, args: item.toolArgsJSON)
return HStack {
VStack(alignment: .leading, spacing: 4) {
VStack(alignment: .leading, spacing: 8) {
// Header with tool icon and name
HStack(spacing: 6) {
Image(systemName: presentation.iconName)
.font(fontPreset.swiftUIFont(sizeAtNormal: 11))
.foregroundColor(.orange)
Text(presentation.title)
.font(fontPreset.swiftUIFont(sizeAtNormal: 12, weight: .semibold))
.foregroundColor(.primary)
// Show key argument inline for common tools
if let summary = presentation.summary {
Text(summary)
.font(fontPreset.swiftUIFont(sizeAtNormal: 11))
.foregroundColor(.secondary)
.lineLimit(1)
.truncationMode(.middle)
}
Spacer()
MessageTimestampText(date: item.timestamp)
.font(fontPreset.swiftUIFont(sizeAtNormal: 10))
.foregroundColor(.secondary)
}
// Arguments (if present and not already summarized inline)
if let args = item.toolArgsJSON, !args.isEmpty, shouldShowFullArgs(toolName: item.toolName) {
CollapsibleCodeBlock(
content: formatJSON(args),
language: "json",
previewLineCount: 5
)
}
}
.padding(10)
.background(BubbleColors.toolCallBackground(colorScheme: colorScheme))
.cornerRadius(12)
}
Spacer(minLength: 40)
}
}
// MARK: - Tool Result Bubble
private var toolResultBubble: some View {
HStack {
VStack(alignment: .leading, spacing: 4) {
VStack(alignment: .leading, spacing: 8) {
// Header with tool-specific icon
HStack(spacing: 6) {
Image(systemName: toolResultIconName(for: item.toolName))
.font(fontPreset.swiftUIFont(sizeAtNormal: 11))
.foregroundColor(.green)
Text(toolResultDisplayName(for: item.toolName))
.font(fontPreset.swiftUIFont(sizeAtNormal: 12, weight: .medium))
.foregroundColor(.secondary)
// Show result summary if available
if let summary = toolResultSummary(toolName: item.toolName, result: item.toolResultJSON) {
Text(summary)
.font(fontPreset.swiftUIFont(sizeAtNormal: 11))
.foregroundColor(.secondary.opacity(0.8))
.lineLimit(1)
}
Spacer()
MessageTimestampText(date: item.timestamp)
.font(fontPreset.swiftUIFont(sizeAtNormal: 10))
.foregroundColor(.secondary)
}
// Result content with appropriate rendering
if let result = item.toolResultJSON, !result.isEmpty {
ToolResultContentView(
content: result,
toolName: item.toolName,
previewLineCount: previewLineCount(for: item.toolName)
)
} else if !item.text.isEmpty {
Text(item.text)
.font(fontPreset.swiftUIFont(sizeAtNormal: 12))
.foregroundColor(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
.padding(10)
.background(BubbleColors.toolResultBackground(colorScheme: colorScheme))
.cornerRadius(12)
}
Spacer(minLength: 40)
}
}
// MARK: - Ask User Question Views
/// Pending question (tool_call state) - shows structured questions while waiting for response
private var askUserQuestionPendingView: some View {
let summary = parseAskUserQuestionSummaryRobust(args: item.toolArgsJSON, result: nil)
return HStack {
VStack(alignment: .leading, spacing: 8) {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "questionmark.circle.fill")
.font(fontPreset.swiftUIFont(sizeAtNormal: 14))
.foregroundColor(.blue)
VStack(alignment: .leading, spacing: 6) {
Text(summary.displayTitle)
.font(fontPreset.standardFont)
.foregroundColor(.primary)
.textSelection(.enabled)
if let context = summary.contextLine {
Text(context)
.font(fontPreset.swiftUIFont(sizeAtNormal: 11))
.foregroundColor(.secondary)
.lineLimit(2)
.textSelection(.enabled)
}
askUserQuestionList(summary.questions)
HStack(spacing: 4) {
ProgressView()
.scaleEffect(0.5)
.frame(width: 12, height: 12)
Text("Waiting for response...")
.font(fontPreset.swiftUIFont(sizeAtNormal: 11))
.foregroundColor(.secondary)
}
}
}
timestampView
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
.background(Color.blue.opacity(0.08))
.cornerRadius(12)
.overlay(
RoundedRectangle(cornerRadius: 12)
.stroke(Color.blue.opacity(0.2), lineWidth: 1)
)
Spacer(minLength: 40)
}
}
/// Completed question exchange (tool_result state) - shows Q&A grouped together
private var askUserQuestionExchangeView: some View {
let summary = parseAskUserQuestionSummaryRobust(args: item.toolArgsJSON, result: item.toolResultJSON)
return HStack {
VStack(alignment: .leading, spacing: 8) {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "questionmark.circle.fill")
.font(fontPreset.swiftUIFont(sizeAtNormal: 14))
.foregroundColor(.blue)
VStack(alignment: .leading, spacing: 10) {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 6) {
Text(summary.displayTitle)
.font(fontPreset.standardFont)
.foregroundColor(.primary)
.textSelection(.enabled)
if let status = summary.statusText {
Text(status)
.font(fontPreset.swiftUIFont(sizeAtNormal: 10, weight: .medium))
.foregroundColor(.secondary)
.padding(.horizontal, 6)
.padding(.vertical, 2)
.background(Color.secondary.opacity(0.12))
.cornerRadius(6)
}
}
if let context = summary.contextLine {
Text(context)
.font(fontPreset.swiftUIFont(sizeAtNormal: 11))
.foregroundColor(.secondary)
.lineLimit(2)
.textSelection(.enabled)
}
}
AskUserQuestionResultView(summary: summary)
}
}
timestampView
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
.background(Color.blue.opacity(0.08))
.cornerRadius(12)
.overlay(
RoundedRectangle(cornerRadius: 12)
.stroke(Color.blue.opacity(0.2), lineWidth: 1)
)
Spacer(minLength: 40)
}
}
private func askUserQuestionList(_ questions: [AskUserQuestionSummary.Question]) -> some View {
VStack(alignment: .leading, spacing: 3) {
ForEach(Array(questions.prefix(3).enumerated()), id: \.element.id) { index, question in
HStack(alignment: .top, spacing: 5) {
Text(questions.count == 1 ? "Q" : "Q\(index + 1)")
.font(fontPreset.swiftUIFont(sizeAtNormal: 10, weight: .bold))
.foregroundColor(.secondary)
.frame(width: questions.count == 1 ? 14 : 22, alignment: .leading)
Text(question.question)
.font(fontPreset.swiftUIFont(sizeAtNormal: 11))
.foregroundColor(.secondary)
.lineLimit(2)
.textSelection(.enabled)
}
}
if questions.count > 3 {
Text("+ \(questions.count - 3) more")
.font(fontPreset.swiftUIFont(sizeAtNormal: 10))
.foregroundColor(.secondary)
}
}
}
// MARK: - System Bubble
private var systemBubble: some View {
HStack {
if let summaryLines = legacyTranscriptSummaryLines {
VStack(alignment: .leading, spacing: 3) {
HStack(spacing: 6) {
Text(summaryLines.primary)
.font(fontPreset.swiftUIFont(sizeAtNormal: 11, weight: .semibold))
.foregroundColor(.primary)
.lineLimit(1)
.truncationMode(.tail)
Spacer(minLength: 0)
}
HStack(spacing: 6) {
Text(summaryLines.secondary)
.font(fontPreset.swiftUIFont(sizeAtNormal: 10.5, weight: .medium))
.foregroundColor(.secondary)
.lineLimit(1)
.truncationMode(.tail)
Spacer(minLength: 0)
}
}
.padding(.horizontal, 10)
.padding(.vertical, 7)
.frame(
minHeight: AgentTranscriptCollapsedCardMetrics.collapsedHeight,
maxHeight: AgentTranscriptCollapsedCardMetrics.collapsedHeight,
alignment: .leading
)
.background(
RoundedRectangle(cornerRadius: 16)
.fill(BubbleColors.toolResultBackground(colorScheme: colorScheme))
)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(Color.secondary.opacity(0.15), lineWidth: 0.5)
)
} else {
HStack(spacing: 6) {
Text(item.text)
.font(fontPreset.swiftUIFont(sizeAtNormal: 12))
.foregroundColor(.secondary)
Spacer()
MessageTimestampText(date: item.timestamp)
.font(fontPreset.swiftUIFont(sizeAtNormal: 10))
.foregroundColor(.secondary.opacity(0.7))
}
.padding(.horizontal, 10)
.padding(.vertical, 7)
.background(
RoundedRectangle(cornerRadius: 16)
.fill(BubbleColors.toolResultBackground(colorScheme: colorScheme))
)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(Color.secondary.opacity(0.15), lineWidth: 0.5)
)
}
}
}
// MARK: - Error Bubble
private var legacyTranscriptSummaryLines: (primary: String, secondary: String)? {
let rawParts = item.text
.components(separatedBy: " • ")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { !$0.isEmpty }
guard rawParts.count >= 2 else { return nil }
let joined = item.text.lowercased()
guard joined.contains("tool called")
|| joined.contains("tools called")
|| joined.contains("hidden tool call")
|| joined.contains("hidden tool calls")
else {
return nil
}
let firstLineCount = rawParts.count >= 4 ? 2 : 1
let primary = rawParts.prefix(firstLineCount).joined(separator: " • ")
let secondary = rawParts.dropFirst(firstLineCount).joined(separator: " • ")
guard !secondary.isEmpty else { return nil }
return (primary, secondary)
}
private var errorBubble: some View {
HStack {
VStack(alignment: .leading, spacing: 4) {
VStack(alignment: .leading, spacing: 10) {
HStack(spacing: 6) {
Image(systemName: "exclamationmark.triangle.fill")
.font(fontPreset.swiftUIFont(sizeAtNormal: 12))
.foregroundColor(BubbleColors.errorRed)
Text(item.text)
.font(fontPreset.swiftUIFont(sizeAtNormal: 13))
.foregroundColor(.primary)
}
if shouldShowCodexManagedLoginAction {
VStack(alignment: .leading, spacing: 6) {
if !codexManagedLoginCompleted {
Button(action: startCodexManagedChatgptLogin) {
HStack(spacing: 6) {
if isStartingCodexManagedLogin {
ProgressView()
.controlSize(.small)
}
Text(isStartingCodexManagedLogin ? "Opening ChatGPT login…" : CodexManagedAuthRecoveryClassifier.loginActionTitle)
}
.font(fontPreset.swiftUIFont(sizeAtNormal: 12))
}
.buttonStyle(.plain)
.foregroundColor(.primary)
.disabled(isStartingCodexManagedLogin)
}
if let feedback = codexManagedLoginFeedback {
Text(feedback)
.font(fontPreset.swiftUIFont(sizeAtNormal: 11))
.foregroundColor(codexManagedLoginCompleted ? .secondary : BubbleColors.errorRed)
.fixedSize(horizontal: false, vertical: true)
}
}
}
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
.background(BubbleColors.errorBackground(colorScheme: colorScheme))
.cornerRadius(12)
MessageFooterStrip(
text: item.text,
timestamp: item.timestamp,
isTrailing: false,
hasHandoffButton: false
)
}
Spacer(minLength: 60)
}
}
// MARK: - Thinking Bubble
private var thinkingBubble: some View {
HStack(spacing: 0) {
// Thin left accent bar
RoundedRectangle(cornerRadius: 1.5)
.fill(Color.secondary.opacity(0.25))
.frame(width: 3)
.padding(.vertical, 4)
MarkdownTextView(
text: item.text,
isMarkdown: true,
allowInteraction: true,
forceTextColor: .secondary.opacity(0.85)
)
.padding(.vertical, 6)
.padding(.leading, 10)
.padding(.trailing, 12)
.frame(maxWidth: .infinity, alignment: .leading)
}
// Prevent the HStack from stretching vertically to fill available space.
// The RoundedRectangle accent bar (a Shape) is vertically greedy and will
// expand when the parent offers more height than the text content needs
// (e.g. when the transcript frame has minHeight: viewportHeight).
.fixedSize(horizontal: false, vertical: true)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(BubbleColors.thinkingBubbleBackground(colorScheme: colorScheme))
)
.padding(.trailing, 60)
}
// MARK: - Tool Name Helpers
/// Check if tool name is a RepoPrompt ask-user variant.
private func isAskUserTool(_ name: String?) -> Bool {
MCPIntegrationHelper.isRepoPromptAskUserToolName(name)
}
/// Hide internal coordination tools from transcript cards.
private func isHiddenAgentTool(_ name: String?) -> Bool {
AgentToolTrackingSupport.shouldHideToolFromTranscript(name)
}
// MARK: - Helper Views
private var timestampView: some View {
MessageTimestampText(date: item.timestamp)
.font(fontPreset.swiftUIFont(sizeAtNormal: 10))
.foregroundColor(.secondary.opacity(0.7))
.padding(.horizontal, 4)
}
private var shouldShowCodexManagedLoginAction: Bool {
item.kind == .error && CodexManagedAuthRecoveryClassifier.preservesAsUserFacingGuidance(item.text)
}
private func startCodexManagedChatgptLogin() {
guard !isStartingCodexManagedLogin else { return }
isStartingCodexManagedLogin = true
codexManagedLoginFeedback = nil
codexManagedLoginCompleted = false
Task { @MainActor in
defer { isStartingCodexManagedLogin = false }
do {
guard let codexManagedLoginAction else {
codexManagedLoginFeedback = "Codex login is unavailable in this view. Open CLI Providers to sign in."
return
}
let authenticated = try await codexManagedLoginAction { url in
NSWorkspace.shared.open(url)
}
guard authenticated else {
codexManagedLoginFeedback = "Codex login did not complete. Retry the login or open CLI Providers."
return
}
codexManagedLoginCompleted = true
codexManagedLoginFeedback = "Login complete. Send your next message to reconnect Codex."
} catch {
codexManagedLoginFeedback = error.localizedDescription
}
}
}
private func formatJSON(_ jsonString: String) -> String {
ToolJSON.prettyPrinted(jsonString)
}
// MARK: - Tool Display Helpers
private struct ToolCallBubblePresentation {
let iconName: String
let title: String
let summary: String?
}
private func toolCallBubblePresentation(toolName: String?, args: String?) -> ToolCallBubblePresentation {
let normalized = normalizedToolCardName(toolName) ?? toolName
let argsObject = parseJSONObject(args)
let webPresentation = AgentWebToolActionPresentation.classify(AgentWebToolActionInput(
rawToolName: toolName,
normalizedToolName: normalized,
argsObject: argsObject,
resultObject: nil
))
return ToolCallBubblePresentation(
iconName: toolIconName(forNormalizedToolName: normalized),
title: webPresentation?.title ?? toolDisplayName(forNormalizedToolName: normalized),
summary: webPresentation?.subtitle ?? toolArgsSummary(normalizedToolName: normalized, argsObject: argsObject)
)