-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathModelPicker.swift
More file actions
460 lines (394 loc) · 16.5 KB
/
ModelPicker.swift
File metadata and controls
460 lines (394 loc) · 16.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
import SwiftUI
import ChatService
import Persist
import ComposableArchitecture
import GitHubCopilotService
import Combine
import ConversationServiceProvider
public let SELECTED_LLM_KEY = "selectedLLM"
public let SELECTED_CHATMODE_KEY = "selectedChatMode"
extension Notification.Name {
static let gitHubCopilotSelectedModelDidChange = Notification.Name("com.github.CopilotForXcode.SelectedModelDidChange")
}
extension AppState {
func getSelectedModelFamily() -> String? {
if let savedModel = get(key: SELECTED_LLM_KEY),
let modelFamily = savedModel["modelFamily"]?.stringValue {
return modelFamily
}
return nil
}
func getSelectedModelName() -> String? {
if let savedModel = get(key: SELECTED_LLM_KEY),
let modelName = savedModel["modelName"]?.stringValue {
return modelName
}
return nil
}
func setSelectedModel(_ model: LLMModel) {
update(key: SELECTED_LLM_KEY, value: model)
NotificationCenter.default.post(name: .gitHubCopilotSelectedModelDidChange, object: nil)
}
func modelScope() -> PromptTemplateScope {
return isAgentModeEnabled() ? .agentPanel : .chatPanel
}
func getSelectedChatMode() -> String {
if let savedMode = get(key: SELECTED_CHATMODE_KEY),
let modeName = savedMode.stringValue {
return convertChatMode(modeName)
}
return "Ask"
}
func setSelectedChatMode(_ mode: String) {
update(key: SELECTED_CHATMODE_KEY, value: mode)
}
func isAgentModeEnabled() -> Bool {
return getSelectedChatMode() == "Agent"
}
private func convertChatMode(_ mode: String) -> String {
switch mode {
case "Agent":
return "Agent"
default:
return "Ask"
}
}
}
class CopilotModelManagerObservable: ObservableObject {
static let shared = CopilotModelManagerObservable()
@Published var availableChatModels: [LLMModel] = []
@Published var availableAgentModels: [LLMModel] = []
@Published var defaultChatModel: LLMModel?
@Published var defaultAgentModel: LLMModel?
private var cancellables = Set<AnyCancellable>()
private init() {
// Initial load
availableChatModels = CopilotModelManager.getAvailableChatLLMs(scope: .chatPanel)
availableAgentModels = CopilotModelManager.getAvailableChatLLMs(scope: .agentPanel)
defaultChatModel = CopilotModelManager.getDefaultChatModel(scope: .chatPanel)
defaultAgentModel = CopilotModelManager.getDefaultChatModel(scope: .agentPanel)
// Setup notification to update when models change
NotificationCenter.default.publisher(for: .gitHubCopilotModelsDidChange)
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.availableChatModels = CopilotModelManager.getAvailableChatLLMs(scope: .chatPanel)
self?.availableAgentModels = CopilotModelManager.getAvailableChatLLMs(scope: .agentPanel)
self?.defaultChatModel = CopilotModelManager.getDefaultChatModel(scope: .chatPanel)
self?.defaultAgentModel = CopilotModelManager.getDefaultChatModel(scope: .agentPanel)
}
.store(in: &cancellables)
NotificationCenter.default.publisher(for: .gitHubCopilotShouldSwitchFallbackModel)
.receive(on: DispatchQueue.main)
.sink { _ in
if let fallbackModel = CopilotModelManager.getFallbackLLM(
scope: AppState.shared
.isAgentModeEnabled() ? .agentPanel : .chatPanel
) {
AppState.shared.setSelectedModel(
.init(
modelName: fallbackModel.modelName,
modelFamily: fallbackModel.id,
billing: fallbackModel.billing
)
)
}
}
.store(in: &cancellables)
}
}
extension CopilotModelManager {
static func getAvailableChatLLMs(scope: PromptTemplateScope = .chatPanel) -> [LLMModel] {
let LLMs = CopilotModelManager.getAvailableLLMs()
return LLMs.filter(
{ $0.scopes.contains(scope) }
).map {
return LLMModel(
modelName: $0.modelName,
modelFamily: $0.isChatFallback ? $0.id : $0.modelFamily,
billing: $0.billing
)
}
}
static func getDefaultChatModel(scope: PromptTemplateScope = .chatPanel) -> LLMModel? {
let LLMs = CopilotModelManager.getAvailableLLMs()
let LLMsInScope = LLMs.filter({ $0.scopes.contains(scope) })
let defaultModel = LLMsInScope.first(where: { $0.isChatDefault })
// If a default model is found, return it
if let defaultModel = defaultModel {
return LLMModel(
modelName: defaultModel.modelName,
modelFamily: defaultModel.modelFamily,
billing: defaultModel.billing
)
}
// Fallback to gpt-4.1 if available
let gpt4_1 = LLMsInScope.first(where: { $0.modelFamily == "gpt-4.1" })
if let gpt4_1 = gpt4_1 {
return LLMModel(
modelName: gpt4_1.modelName,
modelFamily: gpt4_1.modelFamily,
billing: gpt4_1.billing
)
}
// If no default model is found, fallback to the first available model
if let firstModel = LLMsInScope.first {
return LLMModel(
modelName: firstModel.modelName,
modelFamily: firstModel.modelFamily,
billing: firstModel.billing
)
}
return nil
}
}
struct LLMModel: Codable, Hashable {
let modelName: String
let modelFamily: String
let billing: CopilotModelBilling?
}
struct ScopeCache {
var modelMultiplierCache: [String: String] = [:]
var cachedMaxWidth: CGFloat = 0
var lastModelsHash: Int = 0
}
struct ModelPicker: View {
@State private var selectedModel = ""
@State private var isHovered = false
@State private var isPressed = false
@ObservedObject private var modelManager = CopilotModelManagerObservable.shared
static var lastRefreshModelsTime: Date = .init(timeIntervalSince1970: 0)
@State private var chatMode = "Ask"
@State private var isAgentPickerHovered = false
// Separate caches for both scopes
@State private var askScopeCache: ScopeCache = ScopeCache()
@State private var agentScopeCache: ScopeCache = ScopeCache()
let minimumPadding: Int = 48
let attributes: [NSAttributedString.Key: NSFont] = [.font: NSFont.systemFont(ofSize: NSFont.systemFontSize)]
var spaceWidth: CGFloat {
"\u{200A}".size(withAttributes: attributes).width
}
var minimumPaddingWidth: CGFloat {
spaceWidth * CGFloat(minimumPadding)
}
init() {
let initialModel = AppState.shared.getSelectedModelName() ?? CopilotModelManager.getDefaultChatModel()?.modelName ?? ""
self._selectedModel = State(initialValue: initialModel)
updateAgentPicker()
}
var models: [LLMModel] {
AppState.shared.isAgentModeEnabled() ? modelManager.availableAgentModels : modelManager.availableChatModels
}
var defaultModel: LLMModel? {
AppState.shared.isAgentModeEnabled() ? modelManager.defaultAgentModel : modelManager.defaultChatModel
}
// Get the current cache based on scope
var currentCache: ScopeCache {
AppState.shared.isAgentModeEnabled() ? agentScopeCache : askScopeCache
}
// Helper method to format multiplier text
func formatMultiplierText(for billing: CopilotModelBilling?) -> String {
guard let billingInfo = billing else { return "" }
let multiplier = billingInfo.multiplier
if multiplier == 0 {
return "Included"
} else {
let numberPart = multiplier.truncatingRemainder(dividingBy: 1) == 0
? String(format: "%.0f", multiplier)
: String(format: "%.2f", multiplier)
return "\(numberPart)x"
}
}
// Update cache for specific scope only if models changed
func updateModelCacheIfNeeded(for scope: PromptTemplateScope) {
let currentModels = scope == .agentPanel ? modelManager.availableAgentModels : modelManager.availableChatModels
let modelsHash = currentModels.hashValue
if scope == .agentPanel {
guard agentScopeCache.lastModelsHash != modelsHash else { return }
agentScopeCache = buildCache(for: currentModels, currentHash: modelsHash)
} else {
guard askScopeCache.lastModelsHash != modelsHash else { return }
askScopeCache = buildCache(for: currentModels, currentHash: modelsHash)
}
}
// Build cache for given models
private func buildCache(for models: [LLMModel], currentHash: Int) -> ScopeCache {
var newCache: [String: String] = [:]
var maxWidth: CGFloat = 0
for model in models {
let multiplierText = formatMultiplierText(for: model.billing)
newCache[model.modelName] = multiplierText
let displayName = "✓ \(model.modelName)"
let displayNameWidth = displayName.size(withAttributes: attributes).width
let multiplierWidth = multiplierText.isEmpty ? 0 : multiplierText.size(withAttributes: attributes).width
let totalWidth = displayNameWidth + minimumPaddingWidth + multiplierWidth
maxWidth = max(maxWidth, totalWidth)
}
if maxWidth == 0 {
maxWidth = selectedModel.size(withAttributes: attributes).width
}
return ScopeCache(
modelMultiplierCache: newCache,
cachedMaxWidth: maxWidth,
lastModelsHash: currentHash
)
}
func updateCurrentModel() {
selectedModel = AppState.shared.getSelectedModelName() ?? defaultModel?.modelName ?? ""
}
func updateAgentPicker() {
self.chatMode = AppState.shared.getSelectedChatMode()
}
func switchModelsForScope(_ scope: PromptTemplateScope) {
let newModeModels = CopilotModelManager.getAvailableChatLLMs(scope: scope)
if let currentModel = AppState.shared.getSelectedModelName() {
if !newModeModels.isEmpty && !newModeModels.contains(where: { $0.modelName == currentModel }) {
let defaultModel = CopilotModelManager.getDefaultChatModel(scope: scope)
if let defaultModel = defaultModel {
AppState.shared.setSelectedModel(defaultModel)
} else {
AppState.shared.setSelectedModel(newModeModels[0])
}
}
}
self.updateCurrentModel()
updateModelCacheIfNeeded(for: scope)
}
// Model picker menu component
private var modelPickerMenu: some View {
Menu(selectedModel) {
// Group models by premium status
let premiumModels = models.filter { $0.billing?.isPremium == true }
let standardModels = models.filter { $0.billing?.isPremium == false || $0.billing == nil }
// Display standard models section if available
modelSection(title: "Standard Models", models: standardModels)
// Display premium models section if available
modelSection(title: "Premium Models", models: premiumModels)
if standardModels.isEmpty {
Link("Add Premium Models", destination: URL(string: "https://aka.ms/github-copilot-upgrade-plan")!)
}
}
.menuStyle(BorderlessButtonMenuStyle())
.frame(maxWidth: labelWidth())
.padding(4)
.background(
RoundedRectangle(cornerRadius: 5)
.fill(isHovered ? Color.gray.opacity(0.1) : Color.clear)
)
.onHover { hovering in
isHovered = hovering
}
}
// Helper function to create a section of model options
@ViewBuilder
private func modelSection(title: String, models: [LLMModel]) -> some View {
if !models.isEmpty {
Section(title) {
ForEach(models, id: \.self) { model in
modelButton(for: model)
}
}
}
}
// Helper function to create a model selection button
private func modelButton(for model: LLMModel) -> some View {
Button {
AppState.shared.setSelectedModel(model)
} label: {
Text(createModelMenuItemAttributedString(
modelName: model.modelName,
isSelected: selectedModel == model.modelName,
cachedMultiplierText: currentCache.modelMultiplierCache[model.modelName] ?? ""
))
}
}
// Main view body
var body: some View {
WithPerceptionTracking {
HStack(spacing: 0) {
// Custom segmented control with color change
ChatModePicker(chatMode: $chatMode, onScopeChange: switchModelsForScope)
.onAppear() {
updateAgentPicker()
}
// Model Picker
Group {
if !models.isEmpty && !selectedModel.isEmpty {
modelPickerMenu
} else {
EmptyView()
}
}
}
.onAppear() {
updateCurrentModel()
// Initialize both caches
updateModelCacheIfNeeded(for: .chatPanel)
updateModelCacheIfNeeded(for: .agentPanel)
Task {
await refreshModels()
}
}
.onChange(of: defaultModel) { _ in
updateCurrentModel()
}
.onChange(of: modelManager.availableChatModels) { _ in
updateCurrentModel()
updateModelCacheIfNeeded(for: .chatPanel)
}
.onChange(of: modelManager.availableAgentModels) { _ in
updateCurrentModel()
updateModelCacheIfNeeded(for: .agentPanel)
}
.onChange(of: chatMode) { _ in
updateCurrentModel()
}
.onReceive(NotificationCenter.default.publisher(for: .gitHubCopilotSelectedModelDidChange)) { _ in
updateCurrentModel()
}
}
}
func labelWidth() -> CGFloat {
let width = selectedModel.size(withAttributes: attributes).width
return CGFloat(width + 20)
}
@MainActor
func refreshModels() async {
let now = Date()
if now.timeIntervalSince(Self.lastRefreshModelsTime) < 60 {
return
}
Self.lastRefreshModelsTime = now
let copilotModels = await SharedChatService.shared.copilotModels()
if !copilotModels.isEmpty {
CopilotModelManager.updateLLMs(copilotModels)
}
}
private func createModelMenuItemAttributedString(
modelName: String,
isSelected: Bool,
cachedMultiplierText: String
) -> AttributedString {
let displayName = isSelected ? "✓ \(modelName)" : " \(modelName)"
var fullString = displayName
var attributedString = AttributedString(fullString)
if !cachedMultiplierText.isEmpty {
let displayNameWidth = displayName.size(withAttributes: attributes).width
let multiplierTextWidth = cachedMultiplierText.size(withAttributes: attributes).width
let neededPaddingWidth = currentCache.cachedMaxWidth - displayNameWidth - multiplierTextWidth
let finalPaddingWidth = max(neededPaddingWidth, minimumPaddingWidth)
let numberOfSpaces = Int(round(finalPaddingWidth / spaceWidth))
let padding = String(repeating: "\u{200A}", count: max(minimumPadding, numberOfSpaces))
fullString = "\(displayName)\(padding)\(cachedMultiplierText)"
attributedString = AttributedString(fullString)
if let range = attributedString.range(of: cachedMultiplierText) {
attributedString[range].foregroundColor = .secondary
}
}
return attributedString
}
}
struct ModelPicker_Previews: PreviewProvider {
static var previews: some View {
ModelPicker()
}
}