forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitHubCopilotViewModel.swift
More file actions
365 lines (312 loc) · 13.7 KB
/
GitHubCopilotViewModel.swift
File metadata and controls
365 lines (312 loc) · 13.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
import Foundation
import GitHubCopilotService
import ComposableArchitecture
import Status
import SwiftUI
import Cache
public struct SignInResponse {
public let status: SignInInitiateStatus
public let userCode: String
public let verificationURL: URL
}
@MainActor
public class GitHubCopilotViewModel: ObservableObject {
// Add static shared instance
public static let shared = GitHubCopilotViewModel()
@Dependency(\.toast) var toast
@Dependency(\.openURL) var openURL
@AppStorage("username") var username: String = ""
@Published public var isRunningAction: Bool = false
@Published public var status: GitHubCopilotAccountStatus?
@Published public var version: String?
@Published public var userCode: String?
@Published public var isSignInAlertPresented = false
@Published public var signInResponse: SignInResponse?
@Published public var waitingForSignIn = false
static var copilotAuthService: GitHubCopilotService?
// Make init private to enforce singleton pattern
private init() {}
public func getGitHubCopilotAuthService() throws -> GitHubCopilotService {
if let service = Self.copilotAuthService { return service }
let service = try GitHubCopilotService()
Self.copilotAuthService = service
return service
}
public func preSignIn() async throws -> SignInResponse? {
let service = try getGitHubCopilotAuthService()
let result = try await service.signInInitiate()
if result.status == .alreadySignedIn {
guard let user = result.user else {
toast("Missing user info.", .error)
throw NSError(domain: "Missing user info.", code: 0, userInfo: nil)
}
await Status.shared.updateAuthStatus(.loggedIn, username: user)
self.username = user
broadcastStatusChange()
return nil
}
guard let uri = result.verificationUri,
let userCode = result.userCode,
let url = URL(string: uri) else {
toast("Verification URI is incorrect.", .error)
throw NSError(domain: "Verification URI is incorrect.", code: 0, userInfo: nil)
}
return SignInResponse(
status: SignInInitiateStatus.promptUserDeviceFlow,
userCode: userCode,
verificationURL: url
)
}
public func signIn() {
Task {
isRunningAction = true
defer { isRunningAction = false }
do {
guard let result = try await preSignIn() else { return }
self.signInResponse = result
self.isSignInAlertPresented = true
} catch {
toast(error.localizedDescription, .error)
}
}
}
public func checkStatus() {
Task {
isRunningAction = true
defer { isRunningAction = false }
do {
let service = try getGitHubCopilotAuthService()
status = try await service.checkStatus()
version = try await service.version()
isRunningAction = false
} catch {
toast(error.localizedDescription, .error)
}
}
}
public func signOut() {
Task {
isRunningAction = true
defer { isRunningAction = false }
do {
let service = try getGitHubCopilotAuthService()
status = try await service.signOut()
await Status.shared.updateAuthStatus(.notLoggedIn)
await Status.shared.updateCLSStatus(.unknown, busy: false, message: "")
await Status.shared.updateQuotaInfo(nil)
username = ""
broadcastStatusChange()
} catch {
toast(error.localizedDescription, .error)
}
// Sign out all other CLS instances
do {
try await GitHubCopilotService.signOutAll()
} catch {
// ignore
}
}
}
public func cancelWaiting() {
waitingForSignIn = false
}
public func copyAndOpen() {
waitingForSignIn = true
guard let signInResponse else {
toast("Missing sign in details.", .error)
return
}
let pasteboard = NSPasteboard.general
pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
pasteboard.setString(signInResponse.userCode, forType: NSPasteboard.PasteboardType.string)
toast("Sign-in code \(signInResponse.userCode) copied", .info)
Task {
await openURL(signInResponse.verificationURL)
waitForSignIn()
}
}
public func waitForSignIn() {
Task {
do {
guard waitingForSignIn else { return }
guard let signInResponse else {
waitingForSignIn = false
return
}
let service = try getGitHubCopilotAuthService()
let (username, status) = try await service.signInConfirm(userCode: signInResponse.userCode)
waitingForSignIn = false
self.username = username
self.status = status
await Status.shared.updateAuthStatus(.loggedIn, username: username)
broadcastStatusChange()
let models = try? await service.models()
if let models = models, !models.isEmpty {
CopilotModelManager.updateLLMs(models)
}
} catch let error as GitHubCopilotError {
switch error {
case .languageServerError(.timeout):
waitForSignIn()
return
case .languageServerError(
.serverError(
code: CLSErrorCode.deviceFlowFailed.rawValue,
message: _,
data: _
)
):
await showSignInFailedAlert(error: error)
waitingForSignIn = false
return
default:
throw error
}
} catch {
toast(error.localizedDescription, .error)
}
}
}
private func extractSigninErrorMessage(error: GitHubCopilotError) -> String {
let errorDescription = error.localizedDescription
// Handle specific EACCES permission denied errors
if errorDescription.contains("EACCES") {
// Look for paths wrapped in single quotes
let pattern = "'([^']+)'"
if let regex = try? NSRegularExpression(pattern: pattern, options: []) {
let range = NSRange(location: 0, length: errorDescription.utf16.count)
if let match = regex.firstMatch(in: errorDescription, options: [], range: range) {
let pathRange = Range(match.range(at: 1), in: errorDescription)!
let path = String(errorDescription[pathRange])
return path
}
}
}
return errorDescription
}
private func getSigninErrorTitle(error: GitHubCopilotError) -> String {
let errorDescription = error.localizedDescription
if errorDescription.contains("EACCES") {
return "Can't sign you in. The app couldn't create or access files in"
}
return "Error details:"
}
private var accessPermissionCommands: String {
"""
sudo mkdir -p ~/.config/github-copilot
sudo chown -R $(whoami):staff ~/.config
chmod -N ~/.config ~/.config/github-copilot
"""
}
private var containerBackgroundColor: CGColor {
let isDarkMode = NSApp.effectiveAppearance.name == .darkAqua
return isDarkMode
? NSColor.black.withAlphaComponent(0.85).cgColor
: NSColor.white.withAlphaComponent(0.85).cgColor
}
// MARK: - Alert Building Functions
private func showSignInFailedAlert(error: GitHubCopilotError) async {
let alert = NSAlert()
alert.messageText = "GitHub Copilot Sign-in Failed"
alert.alertStyle = .critical
let accessoryView = createAlertAccessoryView(error: error)
alert.accessoryView = accessoryView
alert.addButton(withTitle: "Copy Commands")
alert.addButton(withTitle: "Cancel")
let response = await MainActor.run {
alert.runModal()
}
if response == .alertFirstButtonReturn {
copyCommandsToClipboard()
}
}
private func createAlertAccessoryView(error: GitHubCopilotError) -> NSView {
let accessoryView = NSView(frame: NSRect(x: 0, y: 0, width: 400, height: 142))
let detailsHeader = createDetailsHeader(error: error)
accessoryView.addSubview(detailsHeader)
let errorContainer = createErrorContainer(error: error)
accessoryView.addSubview(errorContainer)
let terminalHeader = createTerminalHeader()
accessoryView.addSubview(terminalHeader)
let commandsContainer = createCommandsContainer()
accessoryView.addSubview(commandsContainer)
return accessoryView
}
private func createDetailsHeader(error: GitHubCopilotError) -> NSView {
let detailsHeader = NSView(frame: NSRect(x: 16, y: 122, width: 368, height: 20))
let warningIcon = NSImageView(frame: NSRect(x: 0, y: 4, width: 16, height: 16))
warningIcon.image = NSImage(systemSymbolName: "exclamationmark.triangle.fill", accessibilityDescription: "Warning")
warningIcon.contentTintColor = NSColor.systemOrange
detailsHeader.addSubview(warningIcon)
let detailsLabel = NSTextField(wrappingLabelWithString: getSigninErrorTitle(error: error))
detailsLabel.frame = NSRect(x: 20, y: 0, width: 346, height: 20)
detailsLabel.font = NSFont.systemFont(ofSize: 12, weight: .regular)
detailsLabel.textColor = NSColor.labelColor
detailsHeader.addSubview(detailsLabel)
return detailsHeader
}
private func createErrorContainer(error: GitHubCopilotError) -> NSView {
let errorContainer = NSView(frame: NSRect(x: 16, y: 96, width: 368, height: 22))
errorContainer.wantsLayer = true
errorContainer.layer?.backgroundColor = containerBackgroundColor
errorContainer.layer?.borderColor = NSColor.separatorColor.cgColor
errorContainer.layer?.borderWidth = 1
errorContainer.layer?.cornerRadius = 6
let errorMessage = NSTextField(wrappingLabelWithString: extractSigninErrorMessage(error: error))
errorMessage.frame = NSRect(x: 8, y: 4, width: 368, height: 14)
errorMessage.font = NSFont.monospacedSystemFont(ofSize: 11, weight: .regular)
errorMessage.textColor = NSColor.labelColor
errorMessage.backgroundColor = .clear
errorMessage.isBordered = false
errorMessage.isEditable = false
errorMessage.drawsBackground = false
errorMessage.usesSingleLineMode = true
errorContainer.addSubview(errorMessage)
return errorContainer
}
private func createTerminalHeader() -> NSView {
let terminalHeader = NSView(frame: NSRect(x: 16, y: 66, width: 368, height: 20))
let toolIcon = NSImageView(frame: NSRect(x: 0, y: 4, width: 16, height: 16))
toolIcon.image = NSImage(systemSymbolName: "terminal.fill", accessibilityDescription: "Terminal")
toolIcon.contentTintColor = NSColor.secondaryLabelColor
terminalHeader.addSubview(toolIcon)
let terminalLabel = NSTextField(wrappingLabelWithString: "Copy and run the commands below in Terminal, then retry.")
terminalLabel.frame = NSRect(x: 20, y: 0, width: 346, height: 20)
terminalLabel.font = NSFont.systemFont(ofSize: 12, weight: .regular)
terminalLabel.textColor = NSColor.labelColor
terminalHeader.addSubview(terminalLabel)
return terminalHeader
}
private func createCommandsContainer() -> NSView {
let commandsContainer = NSView(frame: NSRect(x: 16, y: 4, width: 368, height: 58))
commandsContainer.wantsLayer = true
commandsContainer.layer?.backgroundColor = containerBackgroundColor
commandsContainer.layer?.borderColor = NSColor.separatorColor.cgColor
commandsContainer.layer?.borderWidth = 1
commandsContainer.layer?.cornerRadius = 6
let commandsText = NSTextField(wrappingLabelWithString: accessPermissionCommands)
commandsText.frame = NSRect(x: 8, y: 8, width: 344, height: 42)
commandsText.font = NSFont.monospacedSystemFont(ofSize: 11, weight: .regular)
commandsText.textColor = NSColor.labelColor
commandsText.backgroundColor = .clear
commandsText.isBordered = false
commandsText.isEditable = false
commandsText.isSelectable = true
commandsText.drawsBackground = false
commandsContainer.addSubview(commandsText)
return commandsContainer
}
private func copyCommandsToClipboard() {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(
self.accessPermissionCommands.replacingOccurrences(of: "\n", with: " && "),
forType: .string
)
}
public func broadcastStatusChange() {
DistributedNotificationCenter.default().post(
name: .authStatusDidChange,
object: nil
)
}
}