-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathAppDelegate.swift
More file actions
589 lines (532 loc) · 20.8 KB
/
AppDelegate.swift
File metadata and controls
589 lines (532 loc) · 20.8 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
import Combine
import FileChangeChecker
import GitHubCopilotService
import LaunchAgentManager
import Logger
import Preferences
import Service
import ServiceManagement
import Status
import SwiftUI
import UpdateChecker
import UserDefaultsObserver
import UserNotifications
import XcodeInspector
import XPCShared
import GitHubCopilotViewModel
import StatusBarItemView
import HostAppActivator
let bundleIdentifierBase = Bundle.main
.object(forInfoDictionaryKey: "BUNDLE_IDENTIFIER_BASE") as! String
let serviceIdentifier = bundleIdentifierBase + ".ExtensionService"
class ExtensionUpdateCheckerDelegate: UpdateCheckerDelegate {
func prepareForRelaunch(finish: @escaping () -> Void) {
Task {
await Service.shared.prepareForExit()
finish()
}
}
}
@main
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
let service = Service.shared
var statusBarItem: NSStatusItem!
var axStatusItem: NSMenuItem!
var extensionStatusItem: NSMenuItem!
var openCopilotForXcodeItem: NSMenuItem!
var accountItem: NSMenuItem!
var authStatusItem: NSMenuItem!
var quotaItem: NSMenuItem!
var toggleCompletions: NSMenuItem!
var toggleIgnoreLanguage: NSMenuItem!
var toggleNES: NSMenuItem!
var openChat: NSMenuItem!
var signOutItem: NSMenuItem!
var xpcController: XPCController?
let updateChecker =
UpdateChecker(
hostBundle: Bundle(url: HostAppURL!),
checkerDelegate: ExtensionUpdateCheckerDelegate()
)
var xpcExtensionService: XPCExtensionService?
private var cancellables = Set<AnyCancellable>()
private var progressView: NSProgressIndicator?
func applicationDidFinishLaunching(_: Notification) {
if ProcessInfo.processInfo.environment["IS_UNIT_TEST"] == "YES" { return }
_ = XcodeInspector.shared
service.start()
AXIsProcessTrustedWithOptions([
kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true,
] as CFDictionary)
setupQuitOnUpdate()
setupQuitOnUserTerminated()
xpcController = .init()
Logger.service.info("XPC Service started.")
NSApp.setActivationPolicy(.accessory)
buildStatusBarMenu()
_ = FeatureFlagNotifierImpl.shared
observeFeatureFlags()
watchServiceStatus()
watchAXStatus()
watchAuthStatus()
setInitialStatusBarStatus()
UserDefaults.shared.set(false, for: \.clsWarningDismissedUntilRelaunch)
}
@objc func quit() {
if let hostApp = getRunningHostApp() {
hostApp.terminate()
}
// Start shutdown process in a task
Task { @MainActor in
await service.prepareForExit()
await xpcController?.quit()
NSApp.terminate(self)
}
}
@objc func openCopilotForXcodeSettings() {
try? launchHostAppSettings()
}
@objc func signIntoGitHub() {
Task { @MainActor in
let viewModel = GitHubCopilotViewModel.shared
// Don't trigger the shared viewModel's alert
do {
guard let signInResponse = try await viewModel.preSignIn() else {
return
}
NSApp.activate(ignoringOtherApps: true)
let alert = NSAlert()
alert.messageText = signInResponse.userCode
alert.informativeText = """
Please enter the above code in the GitHub website to authorize your \
GitHub account with Copilot for Xcode.
\(signInResponse.verificationURL.absoluteString)
"""
alert.addButton(withTitle: "Copy Code and Open")
alert.addButton(withTitle: "Cancel")
let response = alert.runModal()
if response == .alertFirstButtonReturn {
viewModel.signInResponse = signInResponse
viewModel.copyAndOpen()
}
} catch {
Logger.service.error("GitHub copilot view model Sign in fails: \(error)")
}
}
}
@objc func signOutGitHub() {
Task { @MainActor in
let viewModel = GitHubCopilotViewModel.shared
viewModel.signOut()
}
}
@objc func openGlobalChat() {
Task { @MainActor in
let serviceGUI = Service.shared.guiController
serviceGUI.openGlobalChat()
}
}
func setupQuitOnUpdate() {
Task {
guard let url = Bundle.main.executableURL else { return }
let checker = await FileChangeChecker(fileURL: url)
// If Xcode or Copilot for Xcode is made active, check if the executable of this program
// is changed. If changed, quit this program.
let sequence = NSWorkspace.shared.notificationCenter
.notifications(named: NSWorkspace.didActivateApplicationNotification)
for await notification in sequence {
try Task.checkCancellation()
guard let app = notification
.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
app.isUserOfService
else { continue }
guard await checker.checkIfChanged() else {
Logger.service.info("Extension Service is not updated, no need to quit.")
continue
}
Logger.service.info("Extension Service will quit.")
#if DEBUG
#else
quit()
#endif
}
}
}
func setupQuitOnUserTerminated() {
Task {
// Whenever Xcode or the host application quits, check if any of the two is running.
// If none, quit the XPC service.
let sequence = NSWorkspace.shared.notificationCenter
.notifications(named: NSWorkspace.didTerminateApplicationNotification)
for await notification in sequence {
try Task.checkCancellation()
guard UserDefaults.shared.value(for: \.quitXPCServiceOnXcodeAndAppQuit)
else { continue }
guard let app = notification
.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
app.isUserOfService
else { continue }
// Check if Xcode is running
let isXcodeRunning = NSWorkspace.shared.runningApplications.contains {
$0.bundleIdentifier == "com.apple.dt.Xcode"
}
if !isXcodeRunning {
Logger.client.info("No Xcode instances running, preparing to quit")
quit()
}
}
}
}
func requestAccessoryAPIPermission() {
AXIsProcessTrustedWithOptions([
kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true,
] as NSDictionary)
}
@objc func checkForUpdate() {
guard let updateChecker = updateChecker else {
Logger.service.error("Unable to check for updates: updateChecker is nil.")
return
}
updateChecker.checkForUpdates()
}
func getXPCExtensionService() -> XPCExtensionService {
if let service = xpcExtensionService { return service }
let service = XPCExtensionService(logger: .service)
xpcExtensionService = service
return service
}
func watchServiceStatus() {
let notifications = NotificationCenter.default.notifications(named: .serviceStatusDidChange)
Task { [weak self] in
for await _ in notifications {
guard let self else { return }
self.updateStatusBarItem()
}
}
}
func watchAXStatus() {
let osNotifications = DistributedNotificationCenter.default().notifications(named: NSNotification.Name("com.apple.accessibility.api"))
Task { [weak self] in
for await _ in osNotifications {
guard let self else { return }
self.updateStatusBarItem()
}
}
}
func observeFeatureFlags() {
Task { @MainActor in
FeatureFlagNotifierImpl.shared.featureFlagsDidChange
.sink(receiveValue: { [weak self] featureFlags in
self?.toggleNES.isHidden = !featureFlags.editorPreviewFeatures
})
}
}
func watchAuthStatus() {
let notifications = DistributedNotificationCenter.default().notifications(named: .authStatusDidChange)
Task { [weak self] in
for await _ in notifications {
guard self != nil else { return }
do {
let service = try await GitHubCopilotViewModel.shared.getGitHubCopilotAuthService()
let accountStatus = try await service.checkStatus()
if accountStatus == .notSignedIn {
try await GitHubCopilotService.signOutAll()
}
} catch {
Logger.service.error("Failed to watch auth status: \(error)")
}
}
}
}
func setInitialStatusBarStatus() {
Task {
let authStatus = await Status.shared.getAuthStatus()
if authStatus.status == .unknown {
// temporarily kick off a language server instance to prime the initial auth status
await forceAuthStatusCheck()
}
updateStatusBarItem()
}
}
func forceAuthStatusCheck() async {
do {
let service = try await GitHubCopilotViewModel.shared.getGitHubCopilotAuthService()
let accountStatus = try await service.checkStatus()
if accountStatus == .ok || accountStatus == .maybeOk {
let quota = try await service.checkQuota()
Logger.service.info("User quota checked successfully: \(quota)")
}
} catch {
Logger.service.error("Failed to read auth status: \(error)")
}
}
private func configureNotLoggedIn() {
self.accountItem.view = AccountItemView(
target: self,
action: #selector(signIntoGitHub)
)
self.authStatusItem.isHidden = true
self.quotaItem.isHidden = true
self.toggleCompletions.isHidden = true
self.toggleIgnoreLanguage.isHidden = true
self.toggleNES.isHidden = true
self.signOutItem.isHidden = true
}
private func configureLoggedIn(status: StatusResponse) {
self.accountItem.view = AccountItemView(
target: self,
action: nil,
userName: status.userName ?? ""
)
if !status.clsMessage.isEmpty {
let CLSMessageSummary = getCLSMessageSummary(status.clsMessage)
// If the quota is nil, keep the original auth status item
// Else only log the CLS error other than quota limit reached error
if CLSMessageSummary.summary == CLSMessageType.other.summary || status.quotaInfo == nil {
configureCLSAuthStatusItem(
summary: CLSMessageSummary,
actionTitle: "View Details on GitHub",
action: #selector(openGitHubDetailsLink)
)
} else if CLSMessageSummary.summary == CLSMessageType.byokLimitedReached.summary {
configureCLSAuthStatusItem(
summary: CLSMessageSummary,
actionTitle: "Dismiss",
action: #selector(dismissBYOKMessage)
)
} else {
// Explicitly hide to avoid leaving stale content if another CLS state was previously shown.
self.authStatusItem.isHidden = true
}
} else {
self.authStatusItem.isHidden = true
}
if let quotaInfo = status.quotaInfo, !quotaInfo.resetDate.isEmpty {
self.quotaItem.isHidden = false
self.quotaItem.view = QuotaView(
chat: .init(
percentRemaining: quotaInfo.chat.percentRemaining,
unlimited: quotaInfo.chat.unlimited,
overagePermitted: quotaInfo.chat.overagePermitted
),
completions: .init(
percentRemaining: quotaInfo.completions.percentRemaining,
unlimited: quotaInfo.completions.unlimited,
overagePermitted: quotaInfo.completions.overagePermitted
),
premiumInteractions: .init(
percentRemaining: quotaInfo.premiumInteractions.percentRemaining,
unlimited: quotaInfo.premiumInteractions.unlimited,
overagePermitted: quotaInfo.premiumInteractions.overagePermitted
),
resetDate: quotaInfo.resetDate,
copilotPlan: quotaInfo.copilotPlan
)
} else {
self.quotaItem.isHidden = true
}
self.toggleCompletions.isHidden = false
self.toggleIgnoreLanguage.isHidden = false
self.toggleNES.isHidden = false
self.signOutItem.isHidden = false
}
func configureCLSAuthStatusItem(
summary: CLSMessage,
actionTitle: String,
action: Selector
) {
self.authStatusItem.isHidden = false
self.authStatusItem.title = summary.summary
let submenu = NSMenu()
let attributedCLSErrorItem = NSMenuItem()
attributedCLSErrorItem.view = ErrorMessageView(
errorMessage: summary.detail
)
submenu.addItem(attributedCLSErrorItem)
submenu.addItem(.separator())
submenu.addItem(
NSMenuItem(
title: actionTitle,
action: action,
keyEquivalent: ""
)
)
self.authStatusItem.submenu = submenu
self.authStatusItem.isEnabled = true
}
private func configureNotAuthorized(status: StatusResponse) {
self.accountItem.view = AccountItemView(
target: self,
action: nil,
userName: status.userName ?? ""
)
self.authStatusItem.isHidden = false
self.authStatusItem.title = "No Subscription"
let submenu = NSMenu()
let attributedNotAuthorizedItem = NSMenuItem()
attributedNotAuthorizedItem.view = ErrorMessageView(
errorMessage: "GitHub Copilot features are disabled. Check your subscription to enable them."
)
attributedNotAuthorizedItem.isEnabled = true
submenu.addItem(attributedNotAuthorizedItem)
self.authStatusItem.submenu = submenu
self.authStatusItem.isEnabled = true
self.quotaItem.isHidden = true
self.toggleCompletions.isHidden = true
self.toggleIgnoreLanguage.isHidden = true
self.toggleNES.isHidden = true
self.signOutItem.isHidden = false
}
private func configureUnknown() {
self.accountItem.view = AccountItemView(
target: self,
action: nil,
userName: "Unknown User"
)
self.authStatusItem.isHidden = true
self.quotaItem.isHidden = true
self.toggleCompletions.isHidden = false
self.toggleIgnoreLanguage.isHidden = false
self.toggleNES.isHidden = false
self.signOutItem.isHidden = false
}
func updateStatusBarItem() {
Task { @MainActor in
let status = await Status.shared.getStatus()
/// Update status bar icon
self.statusBarItem.button?.image = status.icon.nsImage
/// Update auth status related status bar items
switch status.authStatus {
case .notLoggedIn: configureNotLoggedIn()
case .loggedIn: configureLoggedIn(status: status)
case .notAuthorized: configureNotAuthorized(status: status)
case .unknown: configureUnknown()
}
/// Update accessibility permission status bar item
let exclamationmarkImage = NSImage(
systemSymbolName: "exclamationmark.circle.fill",
accessibilityDescription: "Permission not granted"
)
exclamationmarkImage?.isTemplate = false
exclamationmarkImage?.withSymbolConfiguration(.init(paletteColors: [.red]))
if let message = status.message {
self.axStatusItem.title = message
if let image = exclamationmarkImage {
self.axStatusItem.image = image
}
self.axStatusItem.isHidden = false
self.axStatusItem.isEnabled = status.url != nil
} else {
self.axStatusItem.isHidden = true
}
/// Update settings status bar item
if status.extensionStatus == .disabled || status.extensionStatus == .notGranted {
if let image = exclamationmarkImage{
if #available(macOS 15.0, *){
self.extensionStatusItem.image = image
self.extensionStatusItem.title = status.extensionStatus == .notGranted ? "Enable extension for full-featured completion" : "Quit and restart Xcode to enable extension"
self.extensionStatusItem.isHidden = false
self.extensionStatusItem.isEnabled = status.extensionStatus == .notGranted
} else {
self.extensionStatusItem.isHidden = true
self.openCopilotForXcodeItem.image = image
}
}
} else {
self.openCopilotForXcodeItem.image = nil
self.extensionStatusItem.isHidden = true
}
self.markAsProcessing(status.inProgress)
}
}
func markAsProcessing(_ isProcessing: Bool) {
if !isProcessing {
// No longer in progress
progressView?.removeFromSuperview()
progressView = nil
return
}
if progressView != nil {
// Already in progress
return
}
let progress = NSProgressIndicator()
progress.style = .spinning
progress.sizeToFit()
progress.frame = statusBarItem.button?.bounds ?? .zero
progress.isIndeterminate = true
progress.startAnimation(nil)
statusBarItem.button?.addSubview(progress)
statusBarItem.button?.image = nil
progressView = progress
}
@objc func openGitHubDetailsLink() {
Task {
if let url = URL(string: "https://github.com/copilot") {
NSWorkspace.shared.open(url)
}
}
}
@objc func dismissBYOKMessage() {
Task {
await Status.shared.updateCLSStatus(.normal, busy: false, message: "")
}
}
}
extension NSRunningApplication {
var isUserOfService: Bool {
[
"com.apple.dt.Xcode",
bundleIdentifierBase,
].contains(bundleIdentifier)
}
}
enum CLSMessageType {
case chatLimitReached
case completionLimitReached
case byokLimitedReached
case other
var summary: String {
switch self {
case .chatLimitReached:
return "Monthly Chat Limit Reached"
case .completionLimitReached:
return "Monthly Completion Limit Reached"
case .byokLimitedReached:
return "BYOK Limit Reached"
case .other:
return "CLS Error"
}
}
}
struct CLSMessage {
let summary: String
let detail: String
}
func extractDateFromCLSMessage(_ message: String) -> String? {
let pattern = #"until (\d{1,2}/\d{1,2}/\d{4}, \d{1,2}:\d{2}:\d{2} [AP]M)"#
if let range = message.range(of: pattern, options: .regularExpression) {
return String(message[range].dropFirst(6))
}
return nil
}
func getCLSMessageSummary(_ message: String) -> CLSMessage {
let messageType: CLSMessageType
if message.contains("You've reached your monthly chat messages limit") ||
message.contains("You've reached your monthly chat messages quota") {
messageType = .chatLimitReached
} else if message.contains("Completions limit reached") {
messageType = .completionLimitReached
} else if message.contains("BYOK") {
messageType = .byokLimitedReached
} else {
messageType = .other
}
let detail: String
if let date = extractDateFromCLSMessage(message) {
detail = "Visit GitHub to check your usage and upgrade to Copilot Pro or wait until \(date) for your limit to reset."
} else {
detail = message
}
return CLSMessage(summary: messageType.summary, detail: detail)
}