-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathChatModePicker.swift
More file actions
304 lines (276 loc) · 11.3 KB
/
ChatModePicker.swift
File metadata and controls
304 lines (276 loc) · 11.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
import AppKit
import AppKitExtension
import ChatService
import Combine
import ConversationServiceProvider
import GitHubCopilotService
import Persist
import SharedUIComponents
import SwiftUI
import SystemUtils
import Workspace
import XcodeInspector
public extension Notification.Name {
static let gitHubCopilotChatModeDidChange = Notification
.Name("com.github.CopilotForXcode.ChatModeDidChange")
}
public struct ChatModePicker: View {
@Binding var chatMode: String
@Binding var selectedAgent: ConversationMode
let projectRootURL: URL?
@Environment(\.colorScheme) var colorScheme
@State var isAgentModeFFEnabled: Bool
@State var isEditorPreviewFFEnabled: Bool
@State var isCustomAgentPolicyEnabled: Bool
@State private var cancellables = Set<AnyCancellable>()
@State private var builtInAgents: [ConversationMode] = []
@State private var customAgents: [ConversationMode] = []
@State private var isCreateSheetPresented = false
@State private var agentToDelete: ConversationMode?
@State private var showDeleteConfirmation = false
var onScopeChange: (PromptTemplateScope, String?) -> Void
public init(
projectRootURL: URL?,
chatMode: Binding<String>,
selectedAgent: Binding<ConversationMode>,
onScopeChange: @escaping (PromptTemplateScope, String?) -> Void = { _, _ in }
) {
_chatMode = chatMode
_selectedAgent = selectedAgent
self.projectRootURL = projectRootURL
self.onScopeChange = onScopeChange
isAgentModeFFEnabled = FeatureFlagNotifierImpl.shared.featureFlags.agentMode
isEditorPreviewFFEnabled = FeatureFlagNotifierImpl.shared.featureFlags.editorPreviewFeatures
isCustomAgentPolicyEnabled = CopilotPolicyNotifierImpl.shared.copilotPolicy.customAgentEnabled
}
private func setAskMode() {
chatMode = ChatMode.Ask.rawValue
AppState.shared.setSelectedChatMode(ChatMode.Ask.rawValue)
onScopeChange(.chatPanel, nil)
NotificationCenter.default.post(
name: .gitHubCopilotChatModeDidChange,
object: nil
)
}
private func setAgentMode(_ agent: ConversationMode) {
chatMode = ChatMode.Agent.rawValue
selectedAgent = agent
AppState.shared.setSelectedChatMode(ChatMode.Agent.rawValue)
AppState.shared.setSelectedAgentSubMode(agent.id)
// Load agents if switching from Ask mode
Task {
await loadCustomAgentsAsync()
}
onScopeChange(.agentPanel, agent.model)
NotificationCenter.default.post(
name: .gitHubCopilotChatModeDidChange,
object: nil
)
}
private func subscribeToFeatureFlagsDidChangeEvent() {
FeatureFlagNotifierImpl.shared.featureFlagsDidChange.sink(receiveValue: { featureFlags in
isAgentModeFFEnabled = featureFlags.agentMode
isEditorPreviewFFEnabled = featureFlags.editorPreviewFeatures
})
.store(in: &cancellables)
}
private func subscribeToPolicyDidChangeEvent() {
CopilotPolicyNotifierImpl.shared.policyDidChange.sink(receiveValue: { policy in
isCustomAgentPolicyEnabled = policy.customAgentEnabled
})
.store(in: &cancellables)
}
private func loadCustomAgents() {
Task {
await loadCustomAgentsAsync()
// Only restore if we're in Agent mode
if chatMode == ChatMode.Agent.rawValue {
loadSelectedAgentSubMode()
}
}
}
private func loadCustomAgentsAsync() async {
guard let modes = await SharedChatService.shared.loadConversationModes() else {
// Fallback: create default built-in modes when server returns nil
builtInAgents = [.defaultAgent]
customAgents = []
return
}
// Filter built-in modes (exclude Edit)
builtInAgents = modes.filter { $0.isBuiltIn && $0.kind == .Agent }
// Filter for custom agent modes (non-built-in)
customAgents = modes.filter { !$0.isBuiltIn && $0.kind == .Agent }
}
private func deleteCustomAgent(_ agent: ConversationMode) {
agentToDelete = agent
showDeleteConfirmation = true
}
private func performDelete() {
guard let agent = agentToDelete,
let uriString = agent.uri,
let fileURL = URL(string: uriString) else {
return
}
do {
try FileManager.default.removeItem(at: fileURL)
loadCustomAgents()
} catch {
// Error handling
}
agentToDelete = nil
}
private func openAgentFileInXcode(_ agent: ConversationMode) {
guard let uriString = agent.uri, let fileURL = URL(string: uriString) else {
return
}
NSWorkspace.openFileInXcode(fileURL: fileURL)
}
private func createNewAgent() {
isCreateSheetPresented = true
}
private var displayName: String {
return selectedAgent.name
}
private var displayIconName: String? {
// Custom agents don't have icons
if !selectedAgent.isBuiltIn {
return nil
}
// Use checklist icon for Plan, Agent icon for others
return AgentModeIcon.icon(for: selectedAgent.name)
}
public var body: some View {
VStack {
if isAgentModeFFEnabled {
HStack(spacing: -1) {
ModeButton(
title: "Ask",
isSelected: chatMode == ChatMode.Ask.rawValue,
activeBackground: colorScheme == .dark ? Color.white.opacity(0.25) : Color.white,
activeTextColor: Color.primary,
inactiveTextColor: Color.primary.opacity(0.5),
action: {
setAskMode()
}
)
AgentModeButton(
title: displayName,
isSelected: chatMode == ChatMode.Agent.rawValue,
activeBackground: Color.accentColor,
activeTextColor: Color.white,
inactiveTextColor: Color.primary.opacity(0.5),
chatMode: chatMode,
builtInAgentModes: builtInAgents,
customAgents: customAgents,
selectedAgent: selectedAgent,
selectedIconName: displayIconName,
isCustomAgentEnabled: isEditorPreviewFFEnabled && isCustomAgentPolicyEnabled,
onSelectAgent: { setAgentMode($0) },
onEditAgent: { openAgentFileInXcode($0) },
onDeleteAgent: { deleteCustomAgent($0) },
onCreateAgent: { createNewAgent() }
)
}
.scaledPadding(1)
.scaledFrame(height: 22, alignment: .topLeading)
.background(.primary.opacity(0.1))
.cornerRadius(16)
.padding(4)
.help("Set Agent")
} else {
EmptyView()
}
}
.task {
subscribeToFeatureFlagsDidChangeEvent()
subscribeToPolicyDidChangeEvent()
await loadCustomAgentsAsync()
loadSelectedAgentSubMode()
if !isAgentModeFFEnabled {
setAskMode()
}
}
.onChange(of: isAgentModeFFEnabled) { newAgentModeFFEnabled in
if !newAgentModeFFEnabled {
setAskMode()
}
}
.onChange(of: isEditorPreviewFFEnabled) { newValue in
// If editor preview is disabled and current agent is not the default agent, reset to default
if !newValue && chatMode == ChatMode.Agent.rawValue && !selectedAgent.isDefaultAgent {
let defaultAgent = builtInAgents.first(where: { $0.isDefaultAgent }) ?? .defaultAgent
setAgentMode(defaultAgent)
}
}
.onChange(of: isCustomAgentPolicyEnabled) { newValue in
// If custom agent policy is disabled and current agent is not the default agent, reset to default
if !newValue && chatMode == ChatMode.Agent.rawValue && !selectedAgent.isDefaultAgent {
let defaultAgent = builtInAgents.first(where: { $0.isDefaultAgent }) ?? .defaultAgent
setAgentMode(defaultAgent)
}
}
// Minimal refresh: when app becomes active (e.g. user returns from editing an agent file in Xcode)
// Reload custom agents to pick up external changes without adding complex file monitoring.
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
loadCustomAgents()
}
.onChange(of: selectedAgent) { newAgent in
// When selectedAgent changes externally (e.g., from handoff),
// call setAgentMode to trigger all side effects
// Guard: only trigger if we're not already in the correct state to avoid redundant work
guard chatMode != ChatMode.Agent.rawValue ||
AppState.shared.getSelectedAgentSubMode() != newAgent.id else {
return
}
setAgentMode(newAgent)
}
.sheet(isPresented: $isCreateSheetPresented) {
CreateCustomCopilotFileView(
promptType: .agent,
editorPluginVersion: SystemUtils.editorPluginVersionString,
getCurrentProjectURL: { projectRootURL },
onSuccess: { _ in
loadCustomAgents()
},
onError: { _ in
// Handle error silently or log it
}
)
}
.confirmationDialog(
// `agentToDelete` should always be non-nil, adding fallback for compilation safety
"Are you sure you want to delete '\(agentToDelete?.name ?? "Agent")'?",
isPresented: $showDeleteConfirmation
) {
Button("Cancel", role: .cancel) { }
Button("Delete", role: .destructive) { performDelete() }
}
}
private func loadSelectedAgentSubMode() {
let subMode = AppState.shared.getSelectedAgentSubMode()
// Try to find the agent
if let agent = findAgent(byId: subMode) {
// If it's not the default agent and custom agents are disabled, reset to default
if !agent.isDefaultAgent && (!isEditorPreviewFFEnabled || !isCustomAgentPolicyEnabled) {
selectedAgent = builtInAgents.first(where: { $0.isDefaultAgent }) ?? .defaultAgent
AppState.shared.setSelectedAgentSubMode("Agent")
return
}
selectedAgent = agent
return
}
// Default to Agent mode if nothing matches
selectedAgent = builtInAgents.first(where: { $0.isDefaultAgent }) ?? .defaultAgent
}
private func findAgent(byId id: String) -> ConversationMode? {
// Check built-in agents first
if let builtIn = builtInAgents.first(where: { $0.id == id }) {
return builtIn
}
// Check custom agents
if let custom = customAgents.first(where: { $0.id == id }) {
return custom
}
return nil
}
}