forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgentConfigurationWidgetView.swift
More file actions
1186 lines (1054 loc) · 49.3 KB
/
AgentConfigurationWidgetView.swift
File metadata and controls
1186 lines (1054 loc) · 49.3 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 ChatService
import ComposableArchitecture
import ConversationServiceProvider
import ConversationTab
import GitHubCopilotService
import LanguageServerProtocol
import Logger
import SharedUIComponents
import SuggestionBasic
import SwiftUI
import XcodeInspector
struct SelectedAgentModel: Equatable {
let displayName: String
let modelName: String
let source: ModelSource
enum ModelSource: Equatable {
case copilot
case byok(provider: String)
}
}
struct AgentConfigurationWidgetView: View {
let store: StoreOf<AgentConfigurationWidgetFeature>
@State private var showPopover = false
@State private var isHovered = false
@State private var selectedToolStates: [String: [String: Bool]] = [:]
@State private var selectedModel: SelectedAgentModel? = nil
@State private var searchText = ""
@State private var isSearchFieldExpanded = false
@State private var generateHandoffExample: Bool = true
@Environment(\.colorScheme) var colorScheme
var body: some View {
WithPerceptionTracking {
if store.isPanelDisplayed {
VStack {
buildAgentConfigurationButton()
.popover(isPresented: $showPopover) {
buildConfigView(currentMode: store.currentMode).padding(.horizontal, 4)
}
}
.animation(.easeInOut(duration: 0.2), value: store.isPanelDisplayed)
.onChange(of: showPopover) { newValue in
if newValue {
// Load state from agent file when popover is opened
loadToolStatesFromAgentFile(currentMode: store.currentMode)
// Refresh client tools to get any late-arriving server tools
Task {
await GitHubCopilotService.refreshClientTools()
}
}
}
}
}
}
@ViewBuilder
private func buildAgentConfigurationButton() -> some View {
let fontSize = store.lineHeight * 0.7
let lineHeight = store.lineHeight
ZStack {
Button(action: { showPopover.toggle() }) {
HStack(spacing: 4) {
Image(systemName: "square.and.pencil")
.resizable()
.scaledToFit()
.frame(width: fontSize, height: fontSize)
Text("Customize Agent")
.font(.system(size: fontSize))
.fixedSize()
}
.frame(height: lineHeight)
.foregroundColor(isHovered ? Color("ItemSelectedColor") : .secondary)
}
.buttonStyle(.plain)
.contentShape(Capsule())
.help("Configure tools and model for custom agent")
.onHover { isHovered = $0 }
}
}
@ViewBuilder
private func buildConfigView(currentMode: ConversationMode?) -> some View {
if let currentMode = currentMode {
VStack(spacing: 0) {
ScrollView {
VStack(alignment: .leading, spacing: 8) {
Text("Configure Model")
.font(.system(size: 15, weight: .bold))
Text("The AI model to use when running the prompt. If not specified, the currently selected model in model picker is used.")
.font(.system(size: 11))
.foregroundColor(.secondary)
.padding(.bottom, 8)
AgentModelPickerSection(
selectedModel: $selectedModel
)
Divider()
if currentMode.handOffs?.isEmpty ?? true {
Text("Configure Handoffs")
.font(.system(size: 15, weight: .bold))
Text("Suggested next actions or prompts to transition between custom agents. Handoff buttons appear as interactive suggestions after a chat response completes.")
.font(.system(size: 11))
.foregroundColor(.secondary)
Toggle(isOn: $generateHandoffExample) {
Text("Generate Handoff Example")
.font(.system(size: 11, weight: .regular))
}
.toggleStyle(.checkbox)
.help("Adds a starter handoff example to the agent file YAML frontmatter.")
Divider()
}
// Title with Search
HStack {
Text("Configure Tools")
.font(.system(size: 15, weight: .bold))
Spacer()
CollapsibleSearchField(
searchText: $searchText,
isExpanded: $isSearchFieldExpanded,
placeholderString: "Search tools..."
)
}
Text("A list of built-in tools and MCP tools that are available for this agent. If a given tool is not available when running the agent, it is ignored.")
.font(.system(size: 11))
.foregroundColor(.secondary)
.padding(.bottom, 8)
// MCP Tools Section
AgentToolsSection(
title: "MCP Tools",
currentMode: currentMode,
selectedToolStates: $selectedToolStates,
searchText: searchText
)
// Built-In Tools Section
AgentBuiltInToolsSection(
title: "Built-In Tools",
currentMode: currentMode,
selectedToolStates: $selectedToolStates,
searchText: searchText
)
}
.padding(12)
}
.frame(width: 500, height: 600)
Divider()
// Buttons
HStack(spacing: 12) {
Button(action: { showPopover = false }) {
Text("Cancel")
.font(.system(size: 13, weight: .medium))
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
Button(action: {
updateAgentTools(selectedToolStates: selectedToolStates, currentMode: currentMode)
applyAgentFileChanges(
selectedModel: selectedModel,
generateHandoffExample: generateHandoffExample,
currentMode: currentMode
)
showPopover = false
}) {
Text("Apply")
.font(.system(size: 13, weight: .medium))
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
.keyboardShortcut(.defaultAction)
}
.padding(12)
}
.transition(.opacity.combined(with: .scale(scale: 0.95)))
} else {
// Should never be shown since widget only displays when mode exists
VStack {
Text("No agent mode available")
.foregroundColor(.secondary)
}
.frame(width: 500, height: 600)
}
}
// MARK: - Helper functions
// MARK: - Agent File Utilities
private struct AgentFileAccess {
let documentURL: URL
let content: String
}
private func validateAndReadAgentFile() -> AgentFileAccess? {
guard let documentURL = store.withState({ $0.focusedEditor?.realtimeDocumentURL }) else {
Logger.extension.error("Could not access agent file - documentURL is nil")
return nil
}
guard documentURL.pathExtension == "md" else {
Logger.extension.error("Could not access agent file - invalid extension")
return nil
}
guard documentURL.lastPathComponent.hasSuffix(".agent.md") else {
Logger.extension.error("Could not access agent file - filename does not end with .agent.md")
return nil
}
guard let content = try? String(contentsOf: documentURL) else {
Logger.extension.error("Could not access agent file - unable to read file")
return nil
}
return AgentFileAccess(documentURL: documentURL, content: content)
}
private struct YAMLFrontmatterInfo {
var lines: [String]
let frontmatterEndIndex: Int?
let modelLineIndex: Int?
let toolsLineIndex: Int?
let handoffsLineIndex: Int?
}
private func parseYAMLFrontmatter(content: String) -> YAMLFrontmatterInfo {
var lines = content.components(separatedBy: .newlines)
var inFrontmatter = false
var frontmatterEndIndex: Int?
var modelLineIndex: Int?
var toolsLineIndex: Int?
var handoffsLineIndex: Int?
for (idx, line) in lines.enumerated() {
let trimmed = line.trimmingCharacters(in: .whitespaces)
if trimmed == "---" {
if !inFrontmatter {
inFrontmatter = true
} else {
inFrontmatter = false
frontmatterEndIndex = idx
break
}
} else if inFrontmatter {
if trimmed.hasPrefix("model:") {
modelLineIndex = idx
} else if trimmed.hasPrefix("tools:") {
toolsLineIndex = idx
} else if trimmed.hasPrefix("handoffs:") || trimmed.hasPrefix("handOffs:") {
handoffsLineIndex = idx
}
}
}
return YAMLFrontmatterInfo(
lines: lines,
frontmatterEndIndex: frontmatterEndIndex,
modelLineIndex: modelLineIndex,
toolsLineIndex: toolsLineIndex,
handoffsLineIndex: handoffsLineIndex
)
}
private func writeToAgentFile(url: URL, content: String, successMessage: String) {
do {
try content.write(to: url, atomically: true, encoding: .utf8)
Logger.extension.info(successMessage)
} catch {
Logger.extension.error("Error writing agent file: \(error)")
}
}
private func formatModelLine(_ selectedModel: SelectedAgentModel?) -> String? {
guard let model = selectedModel else { return nil }
let sourceLabel: String
switch model.source {
case .copilot:
sourceLabel = "copilot"
case let .byok(provider):
sourceLabel = provider
}
return "model: '\(model.displayName) (\(sourceLabel))'"
}
private func loadMCPToolStates(enabledTools: Set<String>) {
guard let mcpServerTools = CopilotMCPToolManager.getAvailableMCPServerToolsCollections() else { return }
for server in mcpServerTools {
for tool in server.tools {
let configurationKey = AgentModeToolHelpers.makeConfigurationKey(
serverName: server.name,
toolName: tool.name
)
selectedToolStates["mcp"]?[configurationKey] = enabledTools.contains(configurationKey)
}
}
}
private func loadBuiltInToolStates(enabledTools: Set<String>) {
guard let builtInTools = CopilotLanguageModelToolManager.getAvailableLanguageModelTools() else { return }
for tool in builtInTools {
selectedToolStates["builtin"]?[tool.name] = enabledTools.contains(tool.name)
}
}
private func collectMCPToolUpdates(selectedToolStates: [String: [String: Bool]]) -> [UpdateMCPToolsStatusServerCollection] {
guard let mcpStates = selectedToolStates["mcp"],
let mcpServerTools = CopilotMCPToolManager.getAvailableMCPServerToolsCollections() else {
return []
}
return mcpServerTools.map { server in
let toolUpdates = server.tools.map { tool in
let configurationKey = AgentModeToolHelpers.makeConfigurationKey(
serverName: server.name,
toolName: tool.name
)
let isEnabled = mcpStates[configurationKey] ?? false
return UpdatedMCPToolsStatus(
name: tool.name,
status: isEnabled ? .enabled : .disabled
)
}
return UpdateMCPToolsStatusServerCollection(
name: server.name,
tools: toolUpdates
)
}
}
private func collectBuiltInToolUpdates(selectedToolStates: [String: [String: Bool]]) -> [ToolStatusUpdate] {
guard let builtInStates = selectedToolStates["builtin"],
let builtInTools = CopilotLanguageModelToolManager.getAvailableLanguageModelTools() else {
return []
}
return builtInTools.map { tool in
let isEnabled = builtInStates[tool.name] ?? false
return ToolStatusUpdate(
name: tool.name,
status: isEnabled ? .enabled : .disabled
)
}
}
private func updateMCPToolsViaAPI(
service: GitHubCopilotService,
mcpCollections: [UpdateMCPToolsStatusServerCollection],
chatModeKind: ChatMode?,
customChatModeId: String?,
workspaceFolders: [WorkspaceFolder]
) async {
guard !mcpCollections.isEmpty else { return }
do {
let _ = try await service.updateMCPToolsStatus(
params: UpdateMCPToolsStatusParams(
chatModeKind: chatModeKind,
customChatModeId: customChatModeId,
workspaceFolders: workspaceFolders,
servers: mcpCollections
)
)
Logger.extension.info("MCP tools updated via API")
// Notify Settings app about custom agent tool changes
DistributedNotificationCenter.default().postNotificationName(
.gitHubCopilotCustomAgentToolsDidChange,
object: nil,
userInfo: nil,
deliverImmediately: true
)
} catch {
Logger.extension.error("Error updating MCP tools via API: \(error)")
}
}
private func updateBuiltInToolsViaAPI(
service: GitHubCopilotService,
builtInToolUpdates: [ToolStatusUpdate],
chatModeKind: ChatMode?,
customChatModeId: String?,
workspaceFolders: [WorkspaceFolder]
) async {
guard !builtInToolUpdates.isEmpty else { return }
do {
let _ = try await service.updateToolsStatus(
params: UpdateToolsStatusParams(
chatmodeKind: chatModeKind,
customChatModeId: customChatModeId,
workspaceFolders: workspaceFolders,
tools: builtInToolUpdates
)
)
Logger.extension.info("Built-in tools updated via API")
// Notify Settings app about custom agent tool changes
DistributedNotificationCenter.default().postNotificationName(
.gitHubCopilotCustomAgentToolsDidChange,
object: nil,
userInfo: nil,
deliverImmediately: true
)
} catch {
Logger.extension.error("Error updating built-in tools via API: \(error)")
}
}
private func parseModelFromMode(_ mode: ConversationMode?) -> SelectedAgentModel? {
guard let mode = mode,
let modelString = mode.model else {
return nil
}
// Parse format: "displayName (copilot)" or "displayName (providerName)"
if let openParen = modelString.lastIndex(of: "("),
let closeParen = modelString.lastIndex(of: ")") {
let displayName = String(modelString[..<openParen]).trimmingCharacters(in: .whitespaces)
let sourceString = String(modelString[modelString.index(after: openParen) ..< closeParen])
.trimmingCharacters(in: .whitespaces)
.lowercased()
let source: SelectedAgentModel.ModelSource
if sourceString == "copilot" {
source = .copilot
} else {
source = .byok(provider: sourceString)
}
return SelectedAgentModel(
displayName: displayName,
modelName: displayName,
source: source
)
}
return nil
}
private func loadToolStatesFromAgentFile(currentMode: ConversationMode?) {
Task {
await MainActor.run {
// Load model
if let parsedModel = parseModelFromMode(currentMode) {
let copilotModels = CopilotModelManager.getAvailableChatLLMs(scope: .agentPanel)
let byokModels = BYOKModelManager.getAvailableChatLLMs(scope: .agentPanel)
let allModels = copilotModels + byokModels
// Find matching model by display name and source
let matchingModel = allModels.first { model in
let modelDisplayName = model.displayName ?? model.modelName
let matchesName = modelDisplayName == parsedModel.displayName
switch parsedModel.source {
case .copilot:
return matchesName && model.providerName == nil
case let .byok(provider):
return matchesName && model.providerName?.lowercased() == provider.lowercased()
}
}
if let model = matchingModel {
selectedModel = SelectedAgentModel(
displayName: model.displayName ?? model.modelName,
modelName: model.modelName,
source: model.providerName == nil ? .copilot : .byok(provider: model.providerName!)
)
} else {
selectedModel = nil
}
} else {
selectedModel = nil
}
// Reset states
selectedToolStates = ["mcp": [:], "builtin": [:]]
// Load tool states from customTools in current mode
guard let customTools = currentMode?.customTools else {
return
}
let enabledTools = Set(customTools)
loadMCPToolStates(enabledTools: enabledTools)
loadBuiltInToolStates(enabledTools: enabledTools)
}
}
}
private func updateAgentTools(selectedToolStates: [String: [String: Bool]], currentMode: ConversationMode?) {
Task {
// Get the workspace URL and extract project root URL
guard let projectRootURL = await XcodeInspector.shared.safe.realtimeActiveProjectURL,
let service = GitHubCopilotService.getProjectGithubCopilotService(for: projectRootURL) else {
Logger.extension.error("Could not get GitHubCopilotService for project")
return
}
// Get workspace folders
let workspaceFolders = [WorkspaceFolder(
uri: projectRootURL.absoluteString,
name: projectRootURL.lastPathComponent
)]
let chatModeKind: ChatMode? = currentMode?.kind
let customChatModeId: String? = currentMode?.id
let mcpCollections = collectMCPToolUpdates(selectedToolStates: selectedToolStates)
let builtInToolUpdates = collectBuiltInToolUpdates(selectedToolStates: selectedToolStates)
await updateMCPToolsViaAPI(
service: service,
mcpCollections: mcpCollections,
chatModeKind: chatModeKind,
customChatModeId: customChatModeId,
workspaceFolders: workspaceFolders
)
await updateBuiltInToolsViaAPI(
service: service,
builtInToolUpdates: builtInToolUpdates,
chatModeKind: chatModeKind,
customChatModeId: customChatModeId,
workspaceFolders: workspaceFolders
)
}
}
private func applyAgentFileChanges(
selectedModel: SelectedAgentModel?,
generateHandoffExample: Bool,
currentMode: ConversationMode
) {
guard let fileAccess = validateAndReadAgentFile() else { return }
var yamlInfo = parseYAMLFrontmatter(content: fileAccess.content)
// Apply model update and get the index where model was placed
let modelIndex = applyModelUpdate(to: &yamlInfo, selectedModel: selectedModel)
// Apply handoffs update after model
if generateHandoffExample && (currentMode.handOffs?.isEmpty ?? true) {
applyHandoffsUpdate(to: &yamlInfo, afterModelIndex: modelIndex)
}
let updatedContent = yamlInfo.lines.joined(separator: "\n")
writeToAgentFile(url: fileAccess.documentURL, content: updatedContent, successMessage: "Agent file updated")
}
private func applyModelUpdate(to yamlInfo: inout YAMLFrontmatterInfo, selectedModel: SelectedAgentModel?) -> Int? {
let modelLine = formatModelLine(selectedModel)
if let modelLine = modelLine {
if let modelIdx = yamlInfo.modelLineIndex {
yamlInfo.lines[modelIdx] = modelLine
return modelIdx
} else if let endIdx = yamlInfo.frontmatterEndIndex {
yamlInfo.lines.insert(modelLine, at: endIdx)
return endIdx
}
} else if let modelIdx = yamlInfo.modelLineIndex {
yamlInfo.lines.remove(at: modelIdx)
return nil
}
return yamlInfo.modelLineIndex
}
private func applyHandoffsUpdate(to yamlInfo: inout YAMLFrontmatterInfo, afterModelIndex modelIndex: Int?) {
guard yamlInfo.handoffsLineIndex == nil else { return }
let snippet = [
"handoffs:",
" - label: Start Implementation",
" agent: implementation",
" prompt: Now implement the plan outlined above.",
" send: true",
]
if let mIdx = modelIndex {
yamlInfo.lines.insert(contentsOf: snippet, at: mIdx + 1)
} else if let endIdx = yamlInfo.frontmatterEndIndex {
yamlInfo.lines.insert(contentsOf: snippet, at: endIdx)
}
}
// MARK: - MCP Tools Section
private struct AgentToolsSection: View {
let title: String
let currentMode: ConversationMode
@Binding var selectedToolStates: [String: [String: Bool]]
let searchText: String
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Text(title)
.font(.system(size: 14, weight: .semibold))
let mcpServerTools = CopilotMCPToolManager.getAvailableMCPServerToolsCollections() ?? []
if mcpServerTools.isEmpty {
Text("No MCP tools available.")
.foregroundColor(.secondary)
.font(.system(size: 13))
.padding(.vertical, 8)
} else {
ForEach(mcpServerTools, id: \.name) { server in
AgentMCPServerSection(
serverTools: server,
currentMode: currentMode,
selectedToolStates: $selectedToolStates,
searchText: searchText
)
}
}
}
}
}
// MARK: - MCP Server Section
private struct AgentMCPServerSection: View {
let serverTools: MCPServerToolsCollection
let currentMode: ConversationMode
@Binding var selectedToolStates: [String: [String: Bool]]
let searchText: String
@State private var isExpanded: Bool = false
@State private var checkboxState: CheckboxMixedState = .off
private func matchesSearch(_ text: String, _ description: String?) -> Bool {
guard !searchText.isEmpty else { return true }
let lowercasedSearch = searchText.lowercased()
return text.lowercased().contains(lowercasedSearch) ||
(description?.lowercased().contains(lowercasedSearch) ?? false)
}
private var serverNameMatches: Bool {
matchesSearch(serverTools.name, nil)
}
private var hasMatchingTools: Bool {
guard !searchText.isEmpty else { return false }
if serverNameMatches { return true }
return serverTools.tools.contains { tool in
matchesSearch(tool.name, tool.description)
}
}
private var filteredTools: [MCPTool] {
guard !searchText.isEmpty else { return serverTools.tools }
if serverNameMatches { return serverTools.tools }
return serverTools.tools.filter { tool in
matchesSearch(tool.name, tool.description)
}
}
var body: some View {
// Don't show this server if search is active and there are no matches
if searchText.isEmpty || hasMatchingTools {
VStack(alignment: .leading, spacing: 0) {
DisclosureGroup(isExpanded: $isExpanded) {
VStack(alignment: .leading, spacing: 0) {
Divider()
.padding(.vertical, 4)
ForEach(filteredTools, id: \.name) { tool in
let configurationKey = AgentModeToolHelpers.makeConfigurationKey(
serverName: serverTools.name,
toolName: tool.name
)
let isSelected = selectedToolStates["mcp"]?[configurationKey] ?? AgentModeToolHelpers.isToolEnabledInMode(
configurationKey: configurationKey,
currentStatus: .enabled,
selectedMode: currentMode
)
AgentToolRow(
toolName: tool.name,
toolDescription: tool.description,
isSelected: isSelected,
isBlocked: serverTools.status == .blocked || serverTools.status == .error,
onToggle: { isSelected in
if selectedToolStates["mcp"] == nil {
selectedToolStates["mcp"] = [:]
}
selectedToolStates["mcp"]?[configurationKey] = isSelected
updateServerSelectionState()
}
)
.padding(.leading, 20)
}
}
} label: {
HStack(spacing: 8) {
MixedStateCheckbox(
title: "",
font: .systemFont(ofSize: 13),
state: $checkboxState,
action: {
// Toggle based on current state
switch checkboxState {
case .off, .mixed:
toggleAllTools(selected: true)
case .on:
toggleAllTools(selected: false)
}
}
)
.disabled(serverTools.status == .blocked || serverTools.status == .error)
HStack(spacing: 8) {
if serverTools.status == .blocked || serverTools.status == .error {
Text("MCP Server: \(serverTools.name)")
.font(.system(size: 13, weight: .medium))
} else {
let selectedCount = serverTools.tools.filter { tool in
let configurationKey = AgentModeToolHelpers.makeConfigurationKey(
serverName: serverTools.name,
toolName: tool.name
)
if let state = selectedToolStates["mcp"]?[configurationKey] {
return state
}
return AgentModeToolHelpers.isToolEnabledInMode(
configurationKey: configurationKey,
currentStatus: .enabled,
selectedMode: currentMode
)
}.count
Text("MCP Server: \(serverTools.name) ")
.font(.system(size: 13, weight: .medium))
+ Text("(\(selectedCount) of \(serverTools.tools.count) Selected)")
.font(.system(size: 13, weight: .regular))
}
if serverTools.status == .error {
Image(systemName: "xmark.circle.fill")
.foregroundColor(.red)
.font(.system(size: 11))
} else if serverTools.status == .blocked {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundColor(.orange)
.font(.system(size: 11))
}
}
.contentShape(Rectangle())
.onTapGesture {
withAnimation {
isExpanded.toggle()
}
}
Spacer()
}
}
.padding(.vertical, 4)
}
.disabled(serverTools.status != .running)
.onAppear {
updateServerSelectionState()
}
.onChange(of: selectedToolStates) { _ in
updateServerSelectionState()
}
.onChange(of: searchText) { _ in
if hasMatchingTools && !isExpanded && serverTools.status == .running {
isExpanded = true
}
}
}
}
private func toggleAllTools(selected: Bool) {
if selectedToolStates["mcp"] == nil {
selectedToolStates["mcp"] = [:]
}
for tool in serverTools.tools {
let configurationKey = AgentModeToolHelpers.makeConfigurationKey(
serverName: serverTools.name,
toolName: tool.name
)
selectedToolStates["mcp"]?[configurationKey] = selected
}
updateServerSelectionState()
}
private func isToolSelected(_ tool: MCPTool) -> Bool {
let configurationKey = AgentModeToolHelpers.makeConfigurationKey(
serverName: serverTools.name,
toolName: tool.name
)
if let state = selectedToolStates["mcp"]?[configurationKey] {
return state
}
return AgentModeToolHelpers.isToolEnabledInMode(
configurationKey: configurationKey,
currentStatus: .enabled,
selectedMode: currentMode
)
}
private func updateServerSelectionState() {
guard serverTools.status != .blocked && serverTools.status != .error && !serverTools.tools.isEmpty else {
checkboxState = .off
return
}
let selectedCount = serverTools.tools.filter { isToolSelected($0) }.count
checkboxState = selectedCount == 0 ? .off : (selectedCount == serverTools.tools.count ? .on : .mixed)
}
}
// MARK: - Built-In Tools Section
private struct AgentBuiltInToolsSection: View {
let title: String
let currentMode: ConversationMode
@Binding var selectedToolStates: [String: [String: Bool]]
let searchText: String
@State private var isExpanded: Bool = false
@State private var checkboxState: CheckboxMixedState = .off
private func matchesBuiltInSearch(_ tool: LanguageModelTool) -> Bool {
guard !searchText.isEmpty else { return true }
let lowercasedSearch = searchText.lowercased()
return tool.name.lowercased().contains(lowercasedSearch) ||
(tool.displayName?.lowercased().contains(lowercasedSearch) ?? false) ||
(tool.description?.lowercased().contains(lowercasedSearch) ?? false)
}
private var builtInNameMatches: Bool {
guard !searchText.isEmpty else { return false }
let lowercasedSearch = searchText.lowercased()
return "built-in".contains(lowercasedSearch) || "builtin".contains(lowercasedSearch)
}
private func hasMatchingTools(builtInTools: [LanguageModelTool]) -> Bool {
guard !searchText.isEmpty else { return false }
if builtInNameMatches { return true }
return builtInTools.contains { matchesBuiltInSearch($0) }
}
private func filteredTools(builtInTools: [LanguageModelTool]) -> [LanguageModelTool] {
guard !searchText.isEmpty else { return builtInTools }
if builtInNameMatches { return builtInTools }
return builtInTools.filter { matchesBuiltInSearch($0) }
}
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Text(title)
.font(.system(size: 14, weight: .semibold))
let builtInTools = CopilotLanguageModelToolManager.getAvailableLanguageModelTools() ?? []
if builtInTools.isEmpty {
Text("No built-in tools available.")
.foregroundColor(.secondary)
.font(.system(size: 13))
.padding(.vertical, 8)
} else if searchText.isEmpty || hasMatchingTools(builtInTools: builtInTools) {
VStack(alignment: .leading, spacing: 0) {
DisclosureGroup(isExpanded: $isExpanded) {
VStack(alignment: .leading, spacing: 0) {
Divider()
.padding(.vertical, 4)
ForEach(filteredTools(builtInTools: builtInTools), id: \.name) { tool in
let isSelected = selectedToolStates["builtin"]?[tool.name] ?? AgentModeToolHelpers.isToolEnabledInMode(
configurationKey: tool.name,
currentStatus: tool.status,
selectedMode: currentMode
)
AgentToolRow(
toolName: tool.displayName ?? tool.name,
toolDescription: tool.description,
isSelected: isSelected,
isBlocked: false,
onToggle: { isSelected in
if selectedToolStates["builtin"] == nil {
selectedToolStates["builtin"] = [:]
}
selectedToolStates["builtin"]?[tool.name] = isSelected
updateBuiltInSelectionState(builtInTools: builtInTools)
}
)
.padding(.leading, 20)
}
}
} label: {
HStack(spacing: 8) {
MixedStateCheckbox(
title: "",
font: .systemFont(ofSize: 13),
state: $checkboxState,
action: {
// Toggle based on current state
switch checkboxState {
case .off, .mixed:
toggleAllBuiltInTools(selected: true, builtInTools: builtInTools)
case .on:
toggleAllBuiltInTools(selected: false, builtInTools: builtInTools)
}
}
)
let selectedCount = builtInTools.filter { tool in
if let state = selectedToolStates["builtin"]?[tool.name] {
return state
}
return AgentModeToolHelpers.isToolEnabledInMode(
configurationKey: tool.name,
currentStatus: tool.status,
selectedMode: currentMode
)
}.count
(Text("Built-In ")
.font(.system(size: 13, weight: .medium))
+ Text("(\(selectedCount) of \(builtInTools.count) Selected)")
.font(.system(size: 13, weight: .regular))
.foregroundColor(.secondary))
.contentShape(Rectangle())
.onTapGesture {
withAnimation {
isExpanded.toggle()
}
}
Spacer()
}
}
.padding(.vertical, 4)
}
.onAppear {
updateBuiltInSelectionState(builtInTools: builtInTools)
}
.onChange(of: selectedToolStates) { _ in
updateBuiltInSelectionState(builtInTools: builtInTools)
}
.onChange(of: searchText) { _ in
if hasMatchingTools(builtInTools: builtInTools) && !isExpanded {
isExpanded = true
}
}
}
}
}
private func toggleAllBuiltInTools(selected: Bool, builtInTools: [LanguageModelTool]) {
if selectedToolStates["builtin"] == nil {
selectedToolStates["builtin"] = [:]
}
for tool in builtInTools {
selectedToolStates["builtin"]?[tool.name] = selected
}
updateBuiltInSelectionState(builtInTools: builtInTools)
}
private func isBuiltInToolSelected(_ tool: LanguageModelTool) -> Bool {
if let state = selectedToolStates["builtin"]?[tool.name] {
return state
}
return AgentModeToolHelpers.isToolEnabledInMode(
configurationKey: tool.name,
currentStatus: tool.status,
selectedMode: currentMode
)
}
private func updateBuiltInSelectionState(builtInTools: [LanguageModelTool]) {
guard !builtInTools.isEmpty else {
checkboxState = .off
return
}
let selectedCount = builtInTools.filter { isBuiltInToolSelected($0) }.count
checkboxState = selectedCount == 0 ? .off : (selectedCount == builtInTools.count ? .on : .mixed)
}
}
// MARK: - Agent Tool Row
private struct AgentToolRow: View {
let toolName: String
let toolDescription: String?
let isSelected: Bool