-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathChat.swift
More file actions
1583 lines (1354 loc) · 59.7 KB
/
Chat.swift
File metadata and controls
1583 lines (1354 loc) · 59.7 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 ChatService
import ComposableArchitecture
import Foundation
import ChatAPIService
import Preferences
import Terminal
import ConversationServiceProvider
import Persist
import GitHubCopilotService
import Logger
import OrderedCollections
import SwiftUI
import GitHelper
import SuggestionBasic
import HostAppActivator
public struct DisplayedChatMessage: Equatable {
public enum Role: Equatable {
case user
case assistant
case ignored
}
public var id: String
public var role: Role
public var text: String
public var imageReferences: [ImageReference] = []
public var references: [ConversationReference] = []
public var followUp: ConversationFollowUp? = nil
public var suggestedTitle: String? = nil
public var errorMessages: [String] = []
public var steps: [ConversationProgressStep] = []
public var editAgentRounds: [AgentRound] = []
public var parentTurnId: String? = nil
public var panelMessages: [CopilotShowMessageParams] = []
public var codeReviewRound: CodeReviewRound? = nil
public var fileEdits: [FileEdit] = []
public var turnStatus: ChatMessage.TurnStatus? = nil
public let requestType: RequestType
public var modelName: String? = nil
public var billingMultiplier: Float? = nil
public init(
id: String,
role: Role,
text: String,
imageReferences: [ImageReference] = [],
references: [ConversationReference] = [],
followUp: ConversationFollowUp? = nil,
suggestedTitle: String? = nil,
errorMessages: [String] = [],
steps: [ConversationProgressStep] = [],
editAgentRounds: [AgentRound] = [],
parentTurnId: String? = nil,
panelMessages: [CopilotShowMessageParams] = [],
codeReviewRound: CodeReviewRound? = nil,
fileEdits: [FileEdit] = [],
turnStatus: ChatMessage.TurnStatus? = nil,
requestType: RequestType,
modelName: String? = nil,
billingMultiplier: Float? = nil
) {
self.id = id
self.role = role
self.text = text
self.imageReferences = imageReferences
self.references = references
self.followUp = followUp
self.suggestedTitle = suggestedTitle
self.errorMessages = errorMessages
self.steps = steps
self.editAgentRounds = editAgentRounds
self.parentTurnId = parentTurnId
self.panelMessages = panelMessages
self.codeReviewRound = codeReviewRound
self.fileEdits = fileEdits
self.turnStatus = turnStatus
self.requestType = requestType
self.modelName = modelName
self.billingMultiplier = billingMultiplier
}
}
private var isPreview: Bool {
ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"
}
struct ChatContext: Equatable {
var typedMessage: String
var attachedReferences: [ConversationAttachedReference]
var attachedImages: [ImageReference]
init(typedMessage: String, attachedReferences: [ConversationAttachedReference] = [], attachedImages: [ImageReference] = []) {
self.typedMessage = typedMessage
self.attachedReferences = attachedReferences
self.attachedImages = attachedImages
}
static func empty() -> ChatContext {
.init(typedMessage: "", attachedReferences: [], attachedImages: [])
}
static func from(_ message: DisplayedChatMessage, projectURL: URL) -> ChatContext {
.init(
typedMessage: message.text,
attachedReferences: message.references.compactMap {
guard let url = $0.url else { return nil }
if $0.isDirectory {
return .directory(.init(url: url))
} else {
let relativePath = url.path.replacingOccurrences(of: projectURL.path, with: "")
let fileName = url.lastPathComponent
return .file(.init(url: url, relativePath: relativePath, fileName: fileName))
}
},
attachedImages: message.imageReferences)
}
}
struct ChatContextProvider: Equatable {
var contextStack: [ChatContext]
init(contextStack: [ChatContext] = []) {
self.contextStack = contextStack
}
mutating func reset() {
contextStack = []
}
mutating func getNextContext() -> ChatContext? {
guard !contextStack.isEmpty else {
return nil
}
return contextStack.removeLast()
}
func getPreviousContext(from history: [DisplayedChatMessage], projectURL: URL) -> ChatContext? {
let previousUserMessage: DisplayedChatMessage? = {
let userMessages = history.filter { $0.role == .user }
guard !userMessages.isEmpty else {
return nil
}
let stackCount = contextStack.count
guard userMessages.count > stackCount else {
return nil
}
let index = userMessages.count - stackCount - 1
guard index >= 0 else { return nil }
return userMessages[index]
}()
var context: ChatContext?
if let previousUserMessage {
context = .from(previousUserMessage, projectURL: projectURL)
}
return context
}
mutating func pushContext(_ context: ChatContext) {
contextStack.append(context)
}
}
@Reducer
struct Chat {
public typealias MessageID = String
public enum EditorMode: Hashable {
case input // Default input mode
case editUserMessage(MessageID)
var isDefault: Bool { self == .input }
var isEditingUserMessage: Bool {
switch self {
case .input: false
case .editUserMessage: true
}
}
var editingUserMessageId: String? {
switch self {
case .input: nil
case .editUserMessage(let messageID): messageID
}
}
}
@ObservableState
struct EditorState: Equatable {
enum Field: String, Hashable {
case textField
case fileSearchBar
}
var codeReviewState = ConversationCodeReviewFeature.State()
var mode: EditorMode
var contexts: [EditorMode: ChatContext]
var contextProvider: ChatContextProvider
var focusedField: Field?
var currentEditor: ConversationFileReference?
var handOffClicked: Bool = false
init(
mode: EditorMode = .input,
contexts: [EditorMode: ChatContext] = [.input: .empty()],
contextProvider: ChatContextProvider = .init(),
focusedField: Field? = nil,
currentEditor: ConversationFileReference? = nil,
handOffClicked: Bool = false
) {
self.mode = mode
self.contexts = contexts
self.contextProvider = contextProvider
self.focusedField = focusedField
self.currentEditor = currentEditor
self.handOffClicked = handOffClicked
}
func context(for mode: EditorMode) -> ChatContext {
contexts[mode] ?? .empty()
}
mutating func setContext(_ context: ChatContext, for mode: EditorMode) {
contexts[mode] = context
}
mutating func updateCurrentContext(_ update: (inout ChatContext) -> Void) {
var context = self.context(for: mode)
update(&context)
setContext(context, for: mode)
}
mutating func keepOnlyInputContext() {
let inputContext = context(for: .input)
contexts = [.input: inputContext]
}
mutating func clearAttachedImages() {
updateCurrentContext { $0.attachedImages.removeAll() }
}
mutating func addReference(_ reference: ConversationAttachedReference) {
updateCurrentContext { context in
guard !context.attachedReferences.contains(reference) else { return }
context.attachedReferences.append(reference)
}
}
mutating func removeReference(_ reference: ConversationAttachedReference) {
updateCurrentContext { context in
guard let index = context.attachedReferences.firstIndex(of: reference) else { return }
context.attachedReferences.remove(at: index)
}
}
mutating func addImage(_ image: ImageReference) {
updateCurrentContext { context in
guard !context.attachedImages.contains(image) else { return }
context.attachedImages.append(image)
}
}
mutating func removeImage(_ image: ImageReference) {
updateCurrentContext { context in
guard let index = context.attachedImages.firstIndex(of: image) else { return }
context.attachedImages.remove(at: index)
}
}
mutating func pushContext(_ context: ChatContext) {
contextProvider.pushContext(context)
}
mutating func resetContextProvider() {
contextProvider.reset()
}
mutating func popNextContext() -> ChatContext? {
contextProvider.getNextContext()
}
func previousContext(from history: [DisplayedChatMessage], projectURL: URL) -> ChatContext? {
contextProvider.getPreviousContext(from: history, projectURL: projectURL)
}
}
@ObservableState
struct ConversationState: Equatable {
var history: [DisplayedChatMessage]
var isReceivingMessage: Bool
var isSummarizingConversation: Bool
var requestType: RequestType?
var contextSizeInfo: ContextSizeInfo?
init(
history: [DisplayedChatMessage] = [],
isReceivingMessage: Bool = false,
isSummarizingConversation: Bool = false,
requestType: RequestType? = nil,
contextSizeInfo: ContextSizeInfo? = nil
) {
self.history = history
self.isReceivingMessage = isReceivingMessage
self.isSummarizingConversation = isSummarizingConversation
self.requestType = requestType
self.contextSizeInfo = contextSizeInfo
}
func subsequentMessages(after messageId: MessageID) -> [DisplayedChatMessage] {
guard let index = history.firstIndex(where: { $0.id == messageId }) else {
return []
}
return Array(history[(index + 1)...])
}
func editUserMessageEffectedMessages(for mode: EditorMode) -> [DisplayedChatMessage] {
guard case .editUserMessage(let messageId) = mode else {
return []
}
return subsequentMessages(after: messageId)
}
}
struct AgentEditingState: Equatable {
var fileEditMap: OrderedDictionary<URL, FileEdit>
var diffViewerController: DiffViewWindowController?
init(
fileEditMap: OrderedDictionary<URL, FileEdit> = [:],
diffViewerController: DiffViewWindowController? = nil
) {
self.fileEditMap = fileEditMap
self.diffViewerController = diffViewerController
}
static func == (lhs: AgentEditingState, rhs: AgentEditingState) -> Bool {
lhs.fileEditMap == rhs.fileEditMap && lhs.diffViewerController === rhs.diffViewerController
}
}
struct EnvironmentState: Equatable {
var isAgentMode: Bool
var workspaceURL: URL?
var selectedAgent: ConversationMode
init(
isAgentMode: Bool = AppState.shared.isAgentModeEnabled(),
workspaceURL: URL? = nil,
selectedAgent: ConversationMode = .defaultAgent
) {
self.isAgentMode = isAgentMode
self.workspaceURL = workspaceURL
self.selectedAgent = selectedAgent
}
}
@ObservableState
struct State: Equatable {
typealias Field = EditorState.Field
// Not use anymore. the title of history tab will get from chat tab info
// Keep this var as `ChatTabItemView` reference this
var title: String
var editor: EditorState
var conversation: ConversationState
var agentEditing: AgentEditingState
var environment: EnvironmentState
var chatMenu: ChatMenu.State
var codeReviewState: ConversationCodeReviewFeature.State
init(
title: String = "New Chat",
editor: EditorState = .init(),
conversation: ConversationState = .init(),
agentEditing: AgentEditingState = .init(),
environment: EnvironmentState = .init(),
chatMenu: ChatMenu.State = .init(),
codeReviewState: ConversationCodeReviewFeature.State = .init()
) {
self.title = title
self.editor = editor
self.conversation = conversation
self.agentEditing = agentEditing
self.environment = environment
self.chatMenu = chatMenu
self.codeReviewState = codeReviewState
}
init(
title: String = "New Chat",
editorMode: EditorMode = .input,
editorModeContexts: [EditorMode: ChatContext] = [.input: .empty()],
focusedField: Field? = nil,
history: [DisplayedChatMessage] = [],
isReceivingMessage: Bool = false,
requestType: RequestType? = nil,
fileEditMap: OrderedDictionary<URL, FileEdit> = [:],
diffViewerController: DiffViewWindowController? = nil,
isAgentMode: Bool = AppState.shared.isAgentModeEnabled(),
workspaceURL: URL? = nil,
selectedAgent: ConversationMode = .defaultAgent,
chatMenu: ChatMenu.State = .init(),
codeReviewState: ConversationCodeReviewFeature.State = .init()
) {
self.init(
title: title,
editor: EditorState(
mode: editorMode,
contexts: editorModeContexts,
focusedField: focusedField
),
conversation: ConversationState(
history: history,
isReceivingMessage: isReceivingMessage,
requestType: requestType
),
agentEditing: AgentEditingState(
fileEditMap: fileEditMap,
diffViewerController: diffViewerController
),
environment: EnvironmentState(
isAgentMode: isAgentMode,
workspaceURL: workspaceURL,
selectedAgent: selectedAgent
),
chatMenu: chatMenu,
codeReviewState: codeReviewState
)
}
var editorMode: EditorMode {
get { editor.mode }
set {
editor.mode = newValue
if editor.contexts[newValue] == nil {
editor.contexts[newValue] = .empty()
}
}
}
var chatContext: ChatContext {
get { editor.context(for: editor.mode) }
set { editor.setContext(newValue, for: editor.mode) }
}
var history: [DisplayedChatMessage] {
get { conversation.history }
set { conversation.history = newValue }
}
var isReceivingMessage: Bool {
get { conversation.isReceivingMessage }
set { conversation.isReceivingMessage = newValue }
}
var isSummarizingConversation: Bool {
get { conversation.isSummarizingConversation }
set { conversation.isSummarizingConversation = newValue }
}
var requestType: RequestType? {
get { conversation.requestType }
set { conversation.requestType = newValue }
}
var contextSizeInfo: ContextSizeInfo? {
get { conversation.contextSizeInfo }
set { conversation.contextSizeInfo = newValue }
}
var handOffClicked: Bool {
get { editor.handOffClicked }
set { editor.handOffClicked = newValue }
}
var focusedField: Field? {
get { editor.focusedField }
set { editor.focusedField = newValue }
}
var currentEditor: ConversationFileReference? {
get { editor.currentEditor }
set { editor.currentEditor = newValue }
}
var attachedReferences: [ConversationAttachedReference] {
chatContext.attachedReferences
}
var attachedImages: [ImageReference] {
chatContext.attachedImages
}
var typedMessage: String {
get { chatContext.typedMessage }
set {
editor.updateCurrentContext { $0.typedMessage = newValue }
editor.resetContextProvider()
}
}
var fileEditMap: OrderedDictionary<URL, FileEdit> {
get { agentEditing.fileEditMap }
set { agentEditing.fileEditMap = newValue }
}
var diffViewerController: DiffViewWindowController? {
get { agentEditing.diffViewerController }
set { agentEditing.diffViewerController = newValue }
}
var isAgentMode: Bool {
get { environment.isAgentMode }
set { environment.isAgentMode = newValue }
}
var workspaceURL: URL? {
get { environment.workspaceURL }
set { environment.workspaceURL = newValue }
}
var selectedAgent: ConversationMode {
get { environment.selectedAgent }
set { environment.selectedAgent = newValue }
}
/// Not including the one being edited
var editUserMessageEffectedMessages: [DisplayedChatMessage] {
conversation.editUserMessageEffectedMessages(for: editor.mode)
}
// The following messages after check point message will hide on ChatPanel
var pendingCheckpointMessageId: String? = nil
// The chat context before the first restoring
var pendingCheckpointContext: ChatContext? = nil
var messagesAfterCheckpoint: [DisplayedChatMessage] {
guard let pendingCheckpointMessageId, let index = history.firstIndex(where: { $0.id == pendingCheckpointMessageId }) else {
return []
}
let nextIndex = index + 1
guard nextIndex < history.count else {
return []
}
// The order matters for restoring / redoing file edits
return Array(history[nextIndex...])
}
func getMessages(after afterMessageId: String, through throughMessageId: String?) -> [DisplayedChatMessage] {
guard let afterMessageIdIndex = history.firstIndex(where: { $0.id == afterMessageId }) else {
return []
}
let startIndex = afterMessageIdIndex + 1
let endIndex: Int
if let throughMessageId = throughMessageId,
let throughMessageIdIndex = history.firstIndex(where: { $0.id == throughMessageId }) {
endIndex = throughMessageIdIndex + 1
} else {
endIndex = history.count
}
guard startIndex < endIndex, startIndex < history.count else {
return []
}
return Array(history[startIndex..<endIndex])
}
}
enum Action: Equatable, BindableAction {
case binding(BindingAction<State>)
case appear
case refresh
case sendButtonTapped(String)
case returnButtonTapped
case updateTypedMessage(String)
case setEditorMode(EditorMode)
case stopRespondingButtonTapped
case clearButtonTap
case deleteMessageButtonTapped(MessageID)
case resendMessageButtonTapped(MessageID)
case setAsExtraPromptButtonTapped(MessageID)
case focusOnTextField
case referenceClicked(ConversationReference)
case upvote(MessageID, ConversationRating)
case downvote(MessageID, ConversationRating)
case copyCode(MessageID)
case insertCode(String)
case toolCallAccepted(String)
case toolCallAcceptedWithApproval(String, ToolAutoApprovalManager.AutoApproval?)
case toolCallCompleted(String, String)
case toolCallCancelled(String)
case observeChatService
case observeHistoryChange
case observeIsReceivingMessageChange
case observeFileEditChange
case observeContextSizeInfoChange
case historyChanged
case isReceivingMessageChanged
case fileEditChanged
case contextSizeInfoChanged
case chatMenu(ChatMenu.Action)
// File context
case resetCurrentEditor
case setCurrentEditor(ConversationFileReference)
case addReference(ConversationAttachedReference)
case removeReference(ConversationAttachedReference)
// Image context
case addSelectedImage(ImageReference)
case removeSelectedImage(ImageReference)
case followUpButtonClicked(String, String)
case handOffButtonClicked(HandOff)
// Agent File Edit
case undoEdits(fileURLs: [URL])
case keepEdits(fileURLs: [URL])
case resetEdits
case discardFileEdits(fileURLs: [URL])
case openDiffViewWindow(fileURL: URL)
case setDiffViewerController(chat: StoreOf<Chat>)
case agentModeChanged(Bool)
case selectedAgentChanged(ConversationMode)
// Code Review
case codeReview(ConversationCodeReviewFeature.Action)
// Chat Context
case reloadNextContext
case reloadPreviousContext
case resetContextProvider
// External Action
case observeFixErrorNotification
case fixEditorErrorIssue(EditorErrorIssue)
// Check Point
case restoreCheckPoint(String)
case restoreFileEdits
case undoCheckPoint // Revert the restore
case discardCheckPoint
case reloadWorkingset(DisplayedChatMessage)
case openAutoApproveSettings
}
let service: ChatService
let id = UUID()
enum CancelID: Hashable {
case observeHistoryChange(UUID)
case observeIsReceivingMessageChange(UUID)
case sendMessage(UUID)
case observeFileEditChange(UUID)
case observeContextSizeInfoChange(UUID)
case observeFixErrorNotification(UUID)
}
@Dependency(\.openURL) var openURL
@AppStorage(\.enableCurrentEditorContext) var enableCurrentEditorContext: Bool
@AppStorage(\.chatResponseLocale) var chatResponseLocale
var body: some ReducerOf<Self> {
BindingReducer()
Scope(state: \.chatMenu, action: /Action.chatMenu) {
ChatMenu(service: service)
}
Scope(state: \.codeReviewState, action: /Action.codeReview) {
ConversationCodeReviewFeature(service: service)
}
Reduce { state, action in
switch action {
case .appear:
return .run { send in
if isPreview { return }
await send(.observeChatService)
await send(.historyChanged)
await send(.isReceivingMessageChanged)
await send(.focusOnTextField)
await send(.refresh)
await send(.observeFixErrorNotification)
let selectedAgentSubModeId = AppState.shared.getSelectedAgentSubMode()
if let modes = await SharedChatService.shared.loadConversationModes(),
let currentMode = modes.first(where: { $0.id == selectedAgentSubModeId }) {
await send(.selectedAgentChanged(currentMode))
}
let publisher = NotificationCenter.default.publisher(for: .gitHubCopilotChatModeDidChange)
for await _ in publisher.values {
let isAgentMode = AppState.shared.isAgentModeEnabled()
await send(.agentModeChanged(isAgentMode))
let selectedAgentSubModeId = AppState.shared.getSelectedAgentSubMode()
if let modes = await SharedChatService.shared.loadConversationModes(),
let currentMode = modes.first(where: { $0.id == selectedAgentSubModeId }) {
await send(.selectedAgentChanged(currentMode))
}
}
}
case .refresh:
return .run { send in
await send(.chatMenu(.refresh))
}
case let .sendButtonTapped(id):
guard !state.typedMessage.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return .none }
let message = state.typedMessage
let skillSet = state.buildSkillSet(
isCurrentEditorContextEnabled: enableCurrentEditorContext
)
state.typedMessage = ""
let selectedModel = AppState.shared.getSelectedModel()
let selectedModelFamily = selectedModel?.modelFamily ?? CopilotModelManager.getDefaultChatModel(
scope: AppState.shared.modelScope()
)?.modelFamily
let agentMode = AppState.shared.isAgentModeEnabled()
let selectedAgentSubMode = AppState.shared.getSelectedAgentSubMode()
let shouldAttachImages = selectedModel?.supportVision ?? CopilotModelManager.getDefaultChatModel(
scope: AppState.shared.modelScope()
)?.supportVision ?? false
let attachedImages: [ImageReference] = shouldAttachImages ? state.attachedImages : []
let references = state.attachedReferences
state.editor.clearAttachedImages()
let toDeleteMessageIds: [String] = {
var messageIds: [String] = []
if state.editorMode.isEditingUserMessage {
messageIds.append(contentsOf: state.editUserMessageEffectedMessages.map { $0.id })
if let editingUserMessageId = state.editorMode.editingUserMessageId {
messageIds.append(editingUserMessageId)
}
}
return messageIds
}()
return .run { send in
await send(.resetContextProvider)
await send(.discardCheckPoint)
await service.deleteMessages(ids: toDeleteMessageIds)
await send(.setEditorMode(.input))
try await service
.send(
id,
content: message,
contentImageReferences: attachedImages,
skillSet: skillSet,
references: references,
model: selectedModelFamily,
modelProviderName: selectedModel?.providerName,
agentMode: agentMode,
customChatModeId: selectedAgentSubMode,
userLanguage: chatResponseLocale
)
}.cancellable(id: CancelID.sendMessage(self.id))
case let .toolCallAccepted(toolCallId):
guard !toolCallId.isEmpty else { return .none }
return .run { _ in
service.updateToolCallStatus(toolCallId: toolCallId, status: .accepted)
}.cancellable(id: CancelID.sendMessage(self.id))
case let .toolCallAcceptedWithApproval(toolCallId, approval):
guard !toolCallId.isEmpty else { return .none }
return .run { send in
if let approval {
await ToolAutoApprovalManager.shared.approve(approval)
}
await send(.toolCallAccepted(toolCallId))
}.cancellable(id: CancelID.sendMessage(self.id))
case let .toolCallCancelled(toolCallId):
guard !toolCallId.isEmpty else { return .none }
return .run { _ in
service.updateToolCallStatus(toolCallId: toolCallId, status: .cancelled)
}.cancellable(id: CancelID.sendMessage(self.id))
case let .toolCallCompleted(toolCallId, result):
guard !toolCallId.isEmpty else { return .none }
return .run { _ in
service.updateToolCallStatus(toolCallId: toolCallId, status: .completed, payload: result)
}.cancellable(id: CancelID.sendMessage(self.id))
case let .followUpButtonClicked(id, message):
guard !message.isEmpty else { return .none }
let skillSet = state.buildSkillSet(
isCurrentEditorContextEnabled: enableCurrentEditorContext
)
let selectedModel = AppState.shared.getSelectedModel()
let selectedModelFamily = selectedModel?.modelFamily ?? CopilotModelManager.getDefaultChatModel(
scope: AppState.shared.modelScope()
)?.modelFamily
let references = state.attachedReferences
let agentMode = AppState.shared.isAgentModeEnabled()
let selectedAgentSubMode = AppState.shared.getSelectedAgentSubMode()
return .run { send in
await send(.resetContextProvider)
await send(.discardCheckPoint)
try await service
.send(
id,
content: message,
skillSet: skillSet,
references: references,
model: selectedModelFamily,
modelProviderName: selectedModel?.providerName,
agentMode: agentMode,
customChatModeId: selectedAgentSubMode,
userLanguage: chatResponseLocale
)
}.cancellable(id: CancelID.sendMessage(self.id))
case let .handOffButtonClicked(handOff):
state.handOffClicked = true
let agent = handOff.agent
let prompt = handOff.prompt
let shouldSend = handOff.send ?? false
return .run { send in
// Find and switch to the target agent
let modes = await SharedChatService.shared.loadConversationModes() ?? []
if let targetAgent = modes.first(where: { $0.name.lowercased() == agent.lowercased() }) {
await send(.selectedAgentChanged(targetAgent))
}
// If send is true, send the prompt message
if shouldSend && !prompt.isEmpty {
await send(.updateTypedMessage(prompt))
let id = UUID().uuidString
await send(.sendButtonTapped(id))
} else if !prompt.isEmpty {
// Just populate the message field
await send(.updateTypedMessage(prompt))
}
}
case .returnButtonTapped:
state.typedMessage += "\n"
return .none
case let .updateTypedMessage(message):
state.typedMessage = message
return .none
case let .setEditorMode(mode):
switch mode {
case .input:
state.editorMode = mode
// remove all edit contexts except input mode
state.editor.keepOnlyInputContext()
case .editUserMessage(let messageID):
guard let message = state.history.first(where: { $0.id == messageID }),
message.role == .user,
let projectURL = service.getProjectRootURL()
else {
return .none
}
let chatContext: ChatContext = .from(message, projectURL: projectURL)
state.editor.setContext(chatContext, for: mode)
state.editorMode = mode
let isReceivingMessage = service.isReceivingMessage
return .run { send in
if isReceivingMessage {
await send(.stopRespondingButtonTapped)
}
}
}
return .none
case .stopRespondingButtonTapped:
return .merge(
.run { _ in
await service.stopReceivingMessage()
},
.cancel(id: CancelID.sendMessage(id))
)
case .clearButtonTap:
return .run { _ in
await service.clearHistory()
}
case let .deleteMessageButtonTapped(id):
return .run { _ in
await service.deleteMessages(ids: [id])
}
case let .resendMessageButtonTapped(id):
return .run { _ in
try await service.resendMessage(id: id)
}
case let .setAsExtraPromptButtonTapped(id):
return .run { _ in
await service.setMessageAsExtraPrompt(id: id)
}
case let .referenceClicked(reference):
guard let fileURL = reference.url else {
return .none
}
return .run { _ in
if FileManager.default.fileExists(atPath: fileURL.path) {
let terminal = Terminal()
do {
_ = try await terminal.runCommand(
"/bin/bash",
arguments: [
"-c",
"xed -l 0 \"${TARGET_CHAT_FILE}\"",
],
environment: [
"TARGET_CHAT_FILE": reference.filePath
]
)
} catch {
print(error)
}
} else if let url = URL(string: reference.uri), url.scheme != nil {
await openURL(url)
}
}
case .focusOnTextField:
state.focusedField = .textField
return .none
case .observeChatService:
return .run { send in
await send(.observeHistoryChange)
await send(.observeIsReceivingMessageChange)
await send(.observeFileEditChange)
await send(.observeContextSizeInfoChange)
}
case .observeHistoryChange:
return .run { send in
let stream = AsyncStream<Void> { continuation in
let cancellable = service.$chatHistory.sink { _ in
continuation.yield()
}
continuation.onTermination = { _ in
cancellable.cancel()
}
}
let debouncedHistoryChange = TimedDebounceFunction(duration: 0.2) {
await send(.historyChanged)
}
for await _ in stream {
await debouncedHistoryChange()
}
}.cancellable(id: CancelID.observeHistoryChange(id), cancelInFlight: true)
case .observeIsReceivingMessageChange:
return .run { send in
let stream = AsyncStream<Void> { continuation in
let cancellable = service.$isReceivingMessage
.merge(with: service.$isSummarizingConversation)
.sink { _ in
continuation.yield()
}
continuation.onTermination = { _ in
cancellable.cancel()
}
}
for await _ in stream {
await send(.isReceivingMessageChanged)
}