From e8cbbc8f42ef8bd8fdf909a7d1989ae74bfc506d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kukie=C5=82ka?= Date: Mon, 2 Sep 2024 15:13:29 +0200 Subject: [PATCH] Change CodyAuthenticationManager from project to application level service (#2190) ## Changes After discussion with @danielmarquespt we decided account settings should be global, shared across all IntelliJ projects. To reflect that fact I'm changing `CodyAuthenticationManager` to be APP level service instead of project level. Notifications about account state change are pushed to all open projects. All projects use shared storage, so changes done when project is closed are also properly loaded upon opening that project. All relevant changes are in the `CodyAuthenticationManager`, all the rest is removal of unneeded `project` parameter. ## Test plan **Scenario 1** 1. Sign-in with any account 2. Restart the IntelliJ 3. Make sure you are still logged in **Scenario 2** 1. Sign-in with any account, add a few more 2. Restart the IntelliJ 3. Make sure you are still logged in, with the same account **Scenario 3** 1. Sign-in with any account, add a few more 2. Switch account 3. Restart the IntelliJ 4. Make sure you are still logged in, with the same account you switched to **Scenario 4** 1. Sign-in with any account, add a few more 2. Sign-out 3. Restart the IntelliJ 4. Make sure you are not logged in **Scenario 5** 1. Sign-in with any account, add a few more 2. Switch account 3. Open a second IntelliJ project 4. Make sure in the second IntelliJ window you are logged in, with the same account you switched to **Scenario 6** 1. Open two IntelliJ projects side by side 2. Open `Account` panel in both of them 3. Make sure that switching account in one of them causes switch to the same account on the second **Scenario 7** 1. Open two IntelliJ projects side by side 2. Open `Account` panel in both of them and make sure they have active the same account 3. Close one of the instances 4. Switch account in the remaining instance 5. Close the second instance and open back the first one 6. Make sure account is properly switched --- .../config/CodyAuthNotificationActivity.java | 2 +- .../browser/JSToJavaBridgeRequestHandler.java | 2 +- .../sourcegraph/telemetry/GraphQlLogger.java | 22 ++-- .../sourcegraph/website/FileActionBase.java | 3 - .../website/OpenRevisionAction.java | 4 +- .../sourcegraph/website/SearchActionBase.java | 6 +- .../com/sourcegraph/website/URLBuilder.java | 14 +-- .../sourcegraph/cody/CodyToolWindowContent.kt | 2 +- .../ui/SignInWithEnterpriseInstanceAction.kt | 2 +- .../autocomplete/CodyAutocompleteManager.kt | 3 +- .../cody/chat/actions/NewChatAction.kt | 3 +- .../sourcegraph/cody/chat/ui/LlmDropdown.kt | 4 +- .../cody/config/CodyAccountListModel.kt | 5 +- .../cody/config/CodyAuthenticationManager.kt | 111 ++++++++++++------ .../cody/config/CodyPersistentAccountsHost.kt | 2 +- .../com/sourcegraph/cody/config/ServerAuth.kt | 5 +- .../config/migration/ChatHistoryMigration.kt | 2 +- .../config/migration/SettingsMigration.kt | 29 ++--- .../AccountSettingChangeListener.kt | 2 +- .../notification/CodySettingChangeListener.kt | 2 +- .../cody/config/ui/AccountConfigurable.kt | 4 +- .../cody/edit/actions/BaseEditCodeAction.kt | 2 +- .../edit/actions/lenses/LensEditAction.kt | 3 +- .../cody/history/HistoryService.kt | 6 +- .../ignore/ActionInIgnoredFileNotification.kt | 2 +- .../EndOfTrialNotificationScheduler.kt | 2 +- .../initialization/PostStartupActivity.kt | 2 + .../listeners/CodySelectionInlayManager.kt | 2 +- .../CodyDisableAutocompleteAction.kt | 3 +- ...odyDisableLanguageForAutocompleteAction.kt | 3 +- .../cody/statusbar/CodyStatusService.kt | 5 +- .../cody/ui/CodyToolWindowFactory.kt | 2 +- .../com/sourcegraph/common/BrowserOpener.kt | 2 +- .../com/sourcegraph/config/ConfigUtil.kt | 10 +- .../cody/config/SettingsMigrationTest.kt | 2 +- 35 files changed, 145 insertions(+), 130 deletions(-) diff --git a/src/main/java/com/sourcegraph/config/CodyAuthNotificationActivity.java b/src/main/java/com/sourcegraph/config/CodyAuthNotificationActivity.java index 33fdf4d8f5..9cd0ed8e23 100644 --- a/src/main/java/com/sourcegraph/config/CodyAuthNotificationActivity.java +++ b/src/main/java/com/sourcegraph/config/CodyAuthNotificationActivity.java @@ -25,7 +25,7 @@ public class CodyAuthNotificationActivity implements Activity { @Override public void runActivity(@NotNull Project project) { - CodyAccount activeAccount = CodyAuthenticationManager.getInstance(project).getAccount(); + CodyAccount activeAccount = CodyAuthenticationManager.getInstance().getAccount(); CodyAccountManager service = ApplicationManager.getApplication().getService(CodyAccountManager.class); diff --git a/src/main/java/com/sourcegraph/find/browser/JSToJavaBridgeRequestHandler.java b/src/main/java/com/sourcegraph/find/browser/JSToJavaBridgeRequestHandler.java index 0983b93436..a0c9e16afc 100644 --- a/src/main/java/com/sourcegraph/find/browser/JSToJavaBridgeRequestHandler.java +++ b/src/main/java/com/sourcegraph/find/browser/JSToJavaBridgeRequestHandler.java @@ -42,7 +42,7 @@ public JBCefJSQuery.Response handle(@NotNull JsonObject request) { try { switch (action) { case "getConfig": - return createSuccessResponse(ConfigUtil.getConfigAsJson(project)); + return createSuccessResponse(ConfigUtil.getConfigAsJson()); case "getTheme": JsonObject currentThemeAsJson = ThemeUtil.getCurrentThemeAsJson(); return createSuccessResponse(currentThemeAsJson); diff --git a/src/main/java/com/sourcegraph/telemetry/GraphQlLogger.java b/src/main/java/com/sourcegraph/telemetry/GraphQlLogger.java index 1e61f9cac6..c60830923d 100644 --- a/src/main/java/com/sourcegraph/telemetry/GraphQlLogger.java +++ b/src/main/java/com/sourcegraph/telemetry/GraphQlLogger.java @@ -16,8 +16,7 @@ public static CompletableFuture logInstallEvent(@NotNull Project projec CodyApplicationSettings codyApplicationSettings = CodyApplicationSettings.getInstance(); if (codyApplicationSettings.getAnonymousUserId() != null && !project.isDisposed()) { var event = - createEvent( - project, ConfigUtil.getServerPath(project), "CodyInstalled", new JsonObject()); + createEvent(project, ConfigUtil.getServerPath(), "CodyInstalled", new JsonObject()); return logEvent(project, event); } return CompletableFuture.completedFuture(false); @@ -27,8 +26,7 @@ public static void logUninstallEvent(@NotNull Project project) { CodyApplicationSettings codyApplicationSettings = CodyApplicationSettings.getInstance(); if (codyApplicationSettings.getAnonymousUserId() != null) { Event event = - createEvent( - project, ConfigUtil.getServerPath(project), "CodyUninstalled", new JsonObject()); + createEvent(project, ConfigUtil.getServerPath(), "CodyUninstalled", new JsonObject()); logEvent(project, event); } } @@ -37,8 +35,7 @@ public static void logCodyEvent( @NotNull Project project, @NotNull String componentName, @NotNull String action) { var eventName = "CodyJetBrainsPlugin:" + componentName + ":" + action; logEvent( - project, - createEvent(project, ConfigUtil.getServerPath(project), eventName, new JsonObject())); + project, createEvent(project, ConfigUtil.getServerPath(), eventName, new JsonObject())); } public static void logCodeGenerationEvent( @@ -54,9 +51,7 @@ public static void logCodeGenerationEvent( eventParameters.addProperty("source", "chat"); var eventName = "CodyJetBrainsPlugin:" + componentName + ":" + action; - logEvent( - project, - createEvent(project, ConfigUtil.getServerPath(project), eventName, eventParameters)); + logEvent(project, createEvent(project, ConfigUtil.getServerPath(), eventName, eventParameters)); } @NotNull @@ -65,8 +60,7 @@ private static Event createEvent( @NotNull SourcegraphServerPath sourcegraphServerPath, @NotNull String eventName, @NotNull JsonObject eventParameters) { - var updatedEventParameters = - addGlobalEventParameters(project, eventParameters, sourcegraphServerPath); + var updatedEventParameters = addGlobalEventParameters(eventParameters, sourcegraphServerPath); CodyApplicationSettings codyApplicationSettings = CodyApplicationSettings.getInstance(); String anonymousUserId = codyApplicationSettings.getAnonymousUserId(); return new Event( @@ -75,13 +69,11 @@ private static Event createEvent( @NotNull private static JsonObject addGlobalEventParameters( - @NotNull Project project, - @NotNull JsonObject eventParameters, - @NotNull SourcegraphServerPath sourcegraphServerPath) { + @NotNull JsonObject eventParameters, @NotNull SourcegraphServerPath sourcegraphServerPath) { // project specific properties var updatedEventParameters = eventParameters.deepCopy(); var activeAccountTier = - CodyAuthenticationManager.getInstance(project).getActiveAccountTier().getNow(null); + CodyAuthenticationManager.getInstance().getActiveAccountTier().getNow(null); if (activeAccountTier != null) { updatedEventParameters.addProperty("tier", activeAccountTier.getValue()); } diff --git a/src/main/java/com/sourcegraph/website/FileActionBase.java b/src/main/java/com/sourcegraph/website/FileActionBase.java index 51ab7d7c62..60c593229d 100644 --- a/src/main/java/com/sourcegraph/website/FileActionBase.java +++ b/src/main/java/com/sourcegraph/website/FileActionBase.java @@ -45,7 +45,6 @@ public void actionPerformed(@NotNull AnActionEvent event) { handleFileUri( project, URLBuilder.buildSourcegraphBlobUrl( - project, sourcegraphFile.getRepoUrl(), sourcegraphFile.getCommit(), sourcegraphFile.getRelativePath(), @@ -70,7 +69,6 @@ public void actionPerformed(@NotNull AnActionEvent event) { // need, so we'll go to the final URL directly. url = URLBuilder.buildSourcegraphBlobUrl( - project, repoInfo.getCodeHostUrl() + "/" + repoInfo.getRepoName(), null, repoInfo.relativePath, @@ -106,7 +104,6 @@ public void actionPerformedFromPreviewContent( handleFileUri( project, URLBuilder.buildSourcegraphBlobUrl( - project, previewContent.getRepoUrl(), previewContent.getCommit(), previewContent.getPath(), diff --git a/src/main/java/com/sourcegraph/website/OpenRevisionAction.java b/src/main/java/com/sourcegraph/website/OpenRevisionAction.java index 5561192eef..c6907cdfcd 100644 --- a/src/main/java/com/sourcegraph/website/OpenRevisionAction.java +++ b/src/main/java/com/sourcegraph/website/OpenRevisionAction.java @@ -84,7 +84,7 @@ public void actionPerformed(@NotNull AnActionEvent event) { try { url = URLBuilder.buildCommitUrl( - ConfigUtil.getServerPath(project).getUrl(), + ConfigUtil.getServerPath().getUrl(), context.getRevisionNumber(), remoteUrl, productName, @@ -92,7 +92,7 @@ public void actionPerformed(@NotNull AnActionEvent event) { } catch (IllegalArgumentException e) { logger.warn( "Unable to build commit view URI for url " - + ConfigUtil.getServerPath(project).getUrl() + + ConfigUtil.getServerPath().getUrl() + ", revision " + context.getRevisionNumber() + ", product " diff --git a/src/main/java/com/sourcegraph/website/SearchActionBase.java b/src/main/java/com/sourcegraph/website/SearchActionBase.java index 23381112c6..654da181d1 100644 --- a/src/main/java/com/sourcegraph/website/SearchActionBase.java +++ b/src/main/java/com/sourcegraph/website/SearchActionBase.java @@ -41,7 +41,7 @@ public void actionPerformedMode(@NotNull AnActionEvent event, @NotNull Scope sco String url; SourcegraphVirtualFile sourcegraphFile = (SourcegraphVirtualFile) currentFile; String repoUrl = (scope == Scope.REPOSITORY) ? sourcegraphFile.getRepoUrl() : null; - url = URLBuilder.buildEditorSearchUrl(project, selectedText, repoUrl, null); + url = URLBuilder.buildEditorSearchUrl(selectedText, repoUrl, null); BrowserOpener.INSTANCE.openInBrowser(project, url); } else { // This cannot run on EDT (Event Dispatch Thread) because it may block for a long time. @@ -62,9 +62,7 @@ public void actionPerformedMode(@NotNull AnActionEvent event, @NotNull Scope sco url = URLBuilder.buildDirectSearchUrl(project, selectedText, codeHostUrl, repoName); } else { - url = - URLBuilder.buildEditorSearchUrl( - project, selectedText, remoteUrl, remoteBranchName); + url = URLBuilder.buildEditorSearchUrl(selectedText, remoteUrl, remoteBranchName); } BrowserOpener.INSTANCE.openInBrowser(project, url); }); diff --git a/src/main/java/com/sourcegraph/website/URLBuilder.java b/src/main/java/com/sourcegraph/website/URLBuilder.java index 49e1e9a87d..bea385fc54 100644 --- a/src/main/java/com/sourcegraph/website/URLBuilder.java +++ b/src/main/java/com/sourcegraph/website/URLBuilder.java @@ -19,7 +19,7 @@ public static String buildEditorFileUrl( @NotNull String relativePath, @Nullable LogicalPosition start, @Nullable LogicalPosition end) { - return ConfigUtil.getServerPath(project).getUrl() + return ConfigUtil.getServerPath().getUrl() + "-/editor" + "?remote_url=" + URLEncoder.encode(remoteUrl, StandardCharsets.UTF_8) @@ -45,12 +45,9 @@ public static String buildEditorFileUrl( @NotNull public static String buildEditorSearchUrl( - @NotNull Project project, - @NotNull String search, - @Nullable String remoteUrl, - @Nullable String remoteBranchName) { + @NotNull String search, @Nullable String remoteUrl, @Nullable String remoteBranchName) { String url = - ConfigUtil.getServerPath(project).getUrl() + ConfigUtil.getServerPath().getUrl() + "-/editor" + "?" + buildVersionParams() @@ -77,7 +74,7 @@ public static String buildDirectSearchUrl( (codeHost != null && repoName != null) ? "repo:^" + RegexEscaper.INSTANCE.escapeRegexChars(codeHost + "/" + repoName) + "$" : null; - return ConfigUtil.getServerPath(project).getUrl() + return ConfigUtil.getServerPath().getUrl() + "/search" + "?patternType=literal" + "&q=" @@ -124,13 +121,12 @@ public static String buildCommitUrl( @NotNull // repoUrl should be like "github.com/sourcegraph/sourcegraph" public static String buildSourcegraphBlobUrl( - @NotNull Project project, @NotNull String repoUrl, @Nullable String commit, @NotNull String path, @Nullable LogicalPosition start, @Nullable LogicalPosition end) { - return ConfigUtil.getServerPath(project).getUrl() + return ConfigUtil.getServerPath().getUrl() + repoUrl + (commit != null ? "@" + commit : "") + "/-/blob/" diff --git a/src/main/kotlin/com/sourcegraph/cody/CodyToolWindowContent.kt b/src/main/kotlin/com/sourcegraph/cody/CodyToolWindowContent.kt index 3185224a34..c5f721c560 100644 --- a/src/main/kotlin/com/sourcegraph/cody/CodyToolWindowContent.kt +++ b/src/main/kotlin/com/sourcegraph/cody/CodyToolWindowContent.kt @@ -37,7 +37,7 @@ class CodyToolWindowContent(private val project: Project) { @RequiresEdt fun refreshPanelsVisibility() { - val codyAuthenticationManager = CodyAuthenticationManager.getInstance(project) + val codyAuthenticationManager = CodyAuthenticationManager.getInstance() if (codyAuthenticationManager.hasNoActiveAccount() || codyAuthenticationManager.showInvalidAccessTokenError()) { allContentLayout.show(allContentPanel, SIGN_IN_PANEL) diff --git a/src/main/kotlin/com/sourcegraph/cody/auth/ui/SignInWithEnterpriseInstanceAction.kt b/src/main/kotlin/com/sourcegraph/cody/auth/ui/SignInWithEnterpriseInstanceAction.kt index 65629ec989..790672b80d 100644 --- a/src/main/kotlin/com/sourcegraph/cody/auth/ui/SignInWithEnterpriseInstanceAction.kt +++ b/src/main/kotlin/com/sourcegraph/cody/auth/ui/SignInWithEnterpriseInstanceAction.kt @@ -16,7 +16,7 @@ class SignInWithEnterpriseInstanceAction( override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val accountsHost = CodyPersistentAccountsHost(project) - val authManager = CodyAuthenticationManager.getInstance(project) + val authManager = CodyAuthenticationManager.getInstance() val serverUrl = authManager.account?.server?.url ?: defaultServer val dialog = SourcegraphInstanceLoginDialog( diff --git a/src/main/kotlin/com/sourcegraph/cody/autocomplete/CodyAutocompleteManager.kt b/src/main/kotlin/com/sourcegraph/cody/autocomplete/CodyAutocompleteManager.kt index f02a1fa822..0e40bb1d6f 100644 --- a/src/main/kotlin/com/sourcegraph/cody/autocomplete/CodyAutocompleteManager.kt +++ b/src/main/kotlin/com/sourcegraph/cody/autocomplete/CodyAutocompleteManager.kt @@ -172,8 +172,7 @@ class CodyAutocompleteManager { val textDocument: TextDocument = IntelliJTextDocument(editor, project) - if (isTriggeredExplicitly && - CodyAuthenticationManager.getInstance(project).hasNoActiveAccount()) { + if (isTriggeredExplicitly && CodyAuthenticationManager.getInstance().hasNoActiveAccount()) { HintManager.getInstance().showErrorHint(editor, "Cody: Sign in to use autocomplete") return } diff --git a/src/main/kotlin/com/sourcegraph/cody/chat/actions/NewChatAction.kt b/src/main/kotlin/com/sourcegraph/cody/chat/actions/NewChatAction.kt index 4b818a466c..6a79c278f7 100644 --- a/src/main/kotlin/com/sourcegraph/cody/chat/actions/NewChatAction.kt +++ b/src/main/kotlin/com/sourcegraph/cody/chat/actions/NewChatAction.kt @@ -12,8 +12,7 @@ class NewChatAction : DumbAwareEDTAction() { } override fun update(event: AnActionEvent) { - val project = event.project ?: return - val hasActiveAccount = CodyAuthenticationManager.getInstance(project).hasActiveAccount() + val hasActiveAccount = CodyAuthenticationManager.getInstance().hasActiveAccount() event.presentation.isEnabled = hasActiveAccount if (!event.presentation.isEnabled) { event.presentation.description = diff --git a/src/main/kotlin/com/sourcegraph/cody/chat/ui/LlmDropdown.kt b/src/main/kotlin/com/sourcegraph/cody/chat/ui/LlmDropdown.kt index cfd21decc5..b35fde4378 100644 --- a/src/main/kotlin/com/sourcegraph/cody/chat/ui/LlmDropdown.kt +++ b/src/main/kotlin/com/sourcegraph/cody/chat/ui/LlmDropdown.kt @@ -85,7 +85,7 @@ class LlmDropdown( } ?: models.firstOrNull() val isEnterpriseAccount = - CodyAuthenticationManager.getInstance(project).account?.isEnterpriseAccount() ?: false + CodyAuthenticationManager.getInstance().account?.isEnterpriseAccount() ?: false // If the dropdown is already disabled, don't change it. It can happen // in the case of the legacy commands (updateAfterFirstMessage happens before this call). @@ -119,7 +119,7 @@ class LlmDropdown( } fun isCurrentUserFree(): Boolean = - CodyAuthenticationManager.getInstance(project) + CodyAuthenticationManager.getInstance() .getActiveAccountTier() .getNow(AccountTier.DOTCOM_FREE) == AccountTier.DOTCOM_FREE } diff --git a/src/main/kotlin/com/sourcegraph/cody/config/CodyAccountListModel.kt b/src/main/kotlin/com/sourcegraph/cody/config/CodyAccountListModel.kt index 32b843228f..e5620ec41d 100644 --- a/src/main/kotlin/com/sourcegraph/cody/config/CodyAccountListModel.kt +++ b/src/main/kotlin/com/sourcegraph/cody/config/CodyAccountListModel.kt @@ -31,8 +31,9 @@ class CodyAccountListModel(private val project: Project) : override fun editAccount(parentComponent: JComponent, account: CodyAccount) { val token = newCredentials[account] ?: getOldToken(account) val authData = - CodyAuthenticationManager.getInstance(project) + CodyAuthenticationManager.getInstance() .login( + project, parentComponent, CodyLoginRequest( title = "Edit Sourcegraph Account", @@ -53,7 +54,7 @@ class CodyAccountListModel(private val project: Project) : } private fun getOldToken(account: CodyAccount) = - CodyAuthenticationManager.getInstance(project).getTokenForAccount(account) + CodyAuthenticationManager.getInstance().getTokenForAccount(account) override fun addAccount( server: SourcegraphServerPath, diff --git a/src/main/kotlin/com/sourcegraph/cody/config/CodyAuthenticationManager.kt b/src/main/kotlin/com/sourcegraph/cody/config/CodyAuthenticationManager.kt index f629091f93..5e6df79b6d 100644 --- a/src/main/kotlin/com/sourcegraph/cody/config/CodyAuthenticationManager.kt +++ b/src/main/kotlin/com/sourcegraph/cody/config/CodyAuthenticationManager.kt @@ -13,6 +13,7 @@ import com.intellij.openapi.components.service import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project +import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.WindowManager import com.intellij.util.AuthData @@ -52,13 +53,35 @@ data class AuthenticationState( val isTokenInvalid: CompletableFuture ) -/** Entry point for interactions with Sourcegraph authentication subsystem */ +// That class is keep only for a compatibility purposes, so we can load old per-project account +// settings, and use them as the new default when `CodyAccountsSettings` state is loaded for a very +// first time in the `noStateLoaded` method +@Deprecated("Use only for backward compatibility purposes") @State( name = "CodyActiveAccount", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)], reportStatistic = false) @Service(Service.Level.PROJECT) -class CodyAuthenticationManager(val project: Project) : +class DeprecatedCodyActiveAccount(val project: Project) : + PersistentStateComponent { + private var accountState: CodyAuthenticationManager.AccountState? = null + + override fun getState(): CodyAuthenticationManager.AccountState? { + return accountState + } + + override fun loadState(state: CodyAuthenticationManager.AccountState) { + accountState = state + } +} + +/** Entry point for interactions with Sourcegraph authentication subsystem */ +@State( + name = "CodyAccountsSettings", + storages = [Storage("cody_accounts_settings.xml")], + reportStatistic = false) +@Service(Service.Level.APP) +class CodyAuthenticationManager : PersistentStateComponent, Disposable { var account: CodyAccount? = null @@ -66,7 +89,8 @@ class CodyAuthenticationManager(val project: Project) : private val scheduler = Executors.newScheduledThreadPool(1) - private val publisher = project.messageBus.syncPublisher(AccountSettingChangeActionNotifier.TOPIC) + private fun publisher(project: Project) = + project.messageBus.syncPublisher(AccountSettingChangeActionNotifier.TOPIC) @Volatile private var tier: CompletableFuture? = null @@ -78,7 +102,12 @@ class CodyAuthenticationManager(val project: Project) : /* initialDelay = */ 2, /* period = */ 2, /* unit = */ TimeUnit.HOURS) + } + + private val accountManager: CodyAccountManager + get() = service() + fun addAuthChangeListener(project: Project) { val frame = WindowManager.getInstance().getFrame(project) val listener = object : WindowAdapter() { @@ -91,9 +120,6 @@ class CodyAuthenticationManager(val project: Project) : Disposer.register(this) { frame?.removeWindowListener(listener) } } - private val accountManager: CodyAccountManager - get() = service() - @CalledInAny fun getAccounts(): Set = accountManager.accounts @CalledInAny @@ -111,18 +137,18 @@ class CodyAuthenticationManager(val project: Project) : tierFuture.thenApply { currentAccountTier -> if (previousTier != currentAccountTier) { - if (!project.isDisposed) { - tier = tierFuture - publisher.afterAction(AccountSettingChangeContext(accountTierChanged = true)) + tier = tierFuture + ProjectManager.getInstance().openProjects.forEach { project -> + publisher(project).afterAction(AccountSettingChangeContext(accountTierChanged = true)) } } } isTokenInvalidFuture.thenApply { isInvalid -> if (previousIsTokenInvalid != isInvalid) { - if (!project.isDisposed) { - isTokenInvalid = isTokenInvalidFuture - publisher.afterAction(AccountSettingChangeContext(isTokenInvalidChanged = true)) + isTokenInvalid = isTokenInvalidFuture + ProjectManager.getInstance().openProjects.forEach { project -> + publisher(project).afterAction(AccountSettingChangeContext(isTokenInvalidChanged = true)) } } } @@ -188,46 +214,53 @@ class CodyAuthenticationManager(val project: Project) : accountManager.accounts.none { it.name == name && it.server.url == server.url } @RequiresEdt - internal fun login(parentComponent: Component?, request: CodyLoginRequest): CodyAuthData? = - request.loginWithToken(project, parentComponent) + internal fun login( + project: Project, + parentComponent: Component?, + request: CodyLoginRequest + ): CodyAuthData? = request.loginWithToken(project, parentComponent) @RequiresEdt internal fun updateAccountToken(newAccount: CodyAccount, newToken: String) { val oldToken = getTokenForAccount(newAccount) accountManager.updateAccount(newAccount, newToken) if (oldToken != newToken && newAccount == account) { - CodyAgentService.withAgentRestartIfNeeded(project) { agent -> - if (!project.isDisposed) { - agent.server.extensionConfiguration_didChange(ConfigUtil.getAgentConfiguration(project)) - publisher.afterAction(AccountSettingChangeContext(accessTokenChanged = true)) + + ProjectManager.getInstance().openProjects.forEach { project -> + CodyAgentService.withAgentRestartIfNeeded(project) { agent -> + if (!project.isDisposed) { + agent.server.extensionConfiguration_didChange(ConfigUtil.getAgentConfiguration(project)) + publisher(project).afterAction(AccountSettingChangeContext(accessTokenChanged = true)) + } } } } } fun setActiveAccount(newAccount: CodyAccount?) { - if (!project.isDisposed) { - val previousAccount = account - val previousUrl = previousAccount?.server?.url - val previousTier = previousAccount?.isDotcomAccount() + val previousAccount = account + val previousUrl = previousAccount?.server?.url + val previousTier = previousAccount?.isDotcomAccount() - account = newAccount - tier = null - isTokenInvalid = null + account = newAccount + tier = null + isTokenInvalid = null - val serverUrlChanged = previousUrl != newAccount?.server?.url - val tierChanged = previousTier != newAccount?.isDotcomAccount() - val accountChanged = previousAccount != newAccount + val serverUrlChanged = previousUrl != newAccount?.server?.url + val tierChanged = previousTier != newAccount?.isDotcomAccount() + val accountChanged = previousAccount != newAccount + ProjectManager.getInstance().openProjects.forEach { project -> CodyAgentService.withAgentRestartIfNeeded(project) { agent -> if (!project.isDisposed) { agent.server.extensionConfiguration_didChange(ConfigUtil.getAgentConfiguration(project)) if (serverUrlChanged || tierChanged || accountChanged) { - publisher.afterAction( - AccountSettingChangeContext( - serverUrlChanged = serverUrlChanged, - accountTierChanged = tierChanged, - accessTokenChanged = accountChanged)) + publisher(project) + .afterAction( + AccountSettingChangeContext( + serverUrlChanged = serverUrlChanged, + accountTierChanged = tierChanged, + accessTokenChanged = accountChanged)) } } } @@ -251,6 +284,7 @@ class CodyAuthenticationManager(val project: Project) : override fun loadState(state: AccountState) { val initialAccount = state.activeAccountId?.let { id -> accountManager.accounts.find { it.id == id } } + if (initialAccount != null) { setActiveAccount(initialAccount) } @@ -258,14 +292,19 @@ class CodyAuthenticationManager(val project: Project) : override fun noStateLoaded() { super.noStateLoaded() - loadState(AccountState()) + val initialAccountId = + ProjectManager.getInstance().openProjects.firstNotNullOfOrNull { + it.service().state?.activeAccountId + } ?: getAccounts().firstOrNull()?.id + + loadState(AccountState().apply { activeAccountId = initialAccountId }) } companion object { @JvmStatic - fun getInstance(project: Project): CodyAuthenticationManager { - return project.service() + fun getInstance(): CodyAuthenticationManager { + return ApplicationManager.getApplication().getService(CodyAuthenticationManager::class.java) } } diff --git a/src/main/kotlin/com/sourcegraph/cody/config/CodyPersistentAccountsHost.kt b/src/main/kotlin/com/sourcegraph/cody/config/CodyPersistentAccountsHost.kt index c3a8a4d585..1c00f0ca4c 100644 --- a/src/main/kotlin/com/sourcegraph/cody/config/CodyPersistentAccountsHost.kt +++ b/src/main/kotlin/com/sourcegraph/cody/config/CodyPersistentAccountsHost.kt @@ -14,7 +14,7 @@ class CodyPersistentAccountsHost(private val project: Project) : CodyAccountsHos TelemetryV2.sendTelemetryEvent(project, "auth.signin.token", "clicked") val codyAccount = CodyAccount(login, displayName, server, id) - val authManager = CodyAuthenticationManager.getInstance(project) + val authManager = CodyAuthenticationManager.getInstance() authManager.updateAccountToken(codyAccount, token) authManager.setActiveAccount(codyAccount) } diff --git a/src/main/kotlin/com/sourcegraph/cody/config/ServerAuth.kt b/src/main/kotlin/com/sourcegraph/cody/config/ServerAuth.kt index 5bc68dcfed..d51e8aec7f 100644 --- a/src/main/kotlin/com/sourcegraph/cody/config/ServerAuth.kt +++ b/src/main/kotlin/com/sourcegraph/cody/config/ServerAuth.kt @@ -1,6 +1,5 @@ package com.sourcegraph.cody.config -import com.intellij.openapi.project.Project import com.sourcegraph.config.ConfigUtil data class ServerAuth( @@ -12,8 +11,8 @@ data class ServerAuth( object ServerAuthLoader { @JvmStatic - fun loadServerAuth(project: Project): ServerAuth { - val codyAuthenticationManager = CodyAuthenticationManager.getInstance(project) + fun loadServerAuth(): ServerAuth { + val codyAuthenticationManager = CodyAuthenticationManager.getInstance() val defaultAccount = codyAuthenticationManager.account if (defaultAccount != null) { val accessToken = codyAuthenticationManager.getTokenForAccount(defaultAccount) ?: "" diff --git a/src/main/kotlin/com/sourcegraph/cody/config/migration/ChatHistoryMigration.kt b/src/main/kotlin/com/sourcegraph/cody/config/migration/ChatHistoryMigration.kt index ace597e0e3..9c84ca30e0 100644 --- a/src/main/kotlin/com/sourcegraph/cody/config/migration/ChatHistoryMigration.kt +++ b/src/main/kotlin/com/sourcegraph/cody/config/migration/ChatHistoryMigration.kt @@ -18,7 +18,7 @@ object ChatHistoryMigration { fun migrate(project: Project) { CodyAgentService.withAgent(project) { agent -> val chats = - CodyAuthenticationManager.getInstance(project).getAccounts().associateWith { account -> + CodyAuthenticationManager.getInstance().getAccounts().associateWith { account -> (HistoryService.getInstance(project).getChatHistoryFor(account.id) ?: listOf()) } val history = toChatInput(chats) diff --git a/src/main/kotlin/com/sourcegraph/cody/config/migration/SettingsMigration.kt b/src/main/kotlin/com/sourcegraph/cody/config/migration/SettingsMigration.kt index abb1122ede..0659b7a401 100644 --- a/src/main/kotlin/com/sourcegraph/cody/config/migration/SettingsMigration.kt +++ b/src/main/kotlin/com/sourcegraph/cody/config/migration/SettingsMigration.kt @@ -70,7 +70,7 @@ class SettingsMigration : Activity { } private fun migrateOrphanedChatsToActiveAccount(project: Project) { - val activeAccountId = CodyAuthenticationManager.getInstance(project).account?.id + val activeAccountId = CodyAuthenticationManager.getInstance().account?.id HistoryService.getInstance(project) .state .chats @@ -80,9 +80,9 @@ class SettingsMigration : Activity { private fun refreshAccountsIds(project: Project) { val customRequestHeaders = extractCustomRequestHeaders(project) - CodyAuthenticationManager.getInstance(project).getAccounts().forEach { codyAccount -> + CodyAuthenticationManager.getInstance().getAccounts().forEach { codyAccount -> val server = SourcegraphServerPath.from(codyAccount.server.url, customRequestHeaders) - val token = CodyAuthenticationManager.getInstance(project).getTokenForAccount(codyAccount) + val token = CodyAuthenticationManager.getInstance().getTokenForAccount(codyAccount) if (token != null) { loadUserDetails( SourcegraphApiRequestExecutor.Factory.instance, @@ -90,7 +90,7 @@ class SettingsMigration : Activity { EmptyProgressIndicator(ModalityState.NON_MODAL), server) { codyAccount.id = it.id - CodyAuthenticationManager.getInstance(project).updateAccountToken(codyAccount, token) + CodyAuthenticationManager.getInstance().updateAccountToken(codyAccount, token) } } } @@ -172,7 +172,6 @@ class SettingsMigration : Activity { val shouldSetAccountAsDefault = extractedAccountType == AccountType.DOTCOM if (shouldSetAccountAsDefault) { addAsDefaultAccountIfUnique( - project, dotcomAccessToken, server, requestExecutorFactory, @@ -201,7 +200,6 @@ class SettingsMigration : Activity { val shouldSetAccountAsDefault = extractAccountType(project) == AccountType.ENTERPRISE if (shouldSetAccountAsDefault) { addAsDefaultAccountIfUnique( - project, enterpriseAccessToken, it, requestExecutorFactory, @@ -228,12 +226,11 @@ class SettingsMigration : Activity { progressIndicator: EmptyProgressIndicator, ) { loadUserDetails(requestExecutorFactory, accessToken, progressIndicator, server) { - addAccount(project, CodyAccount(it.name, it.displayName, server, it.id), accessToken) + addAccount(CodyAccount(it.name, it.displayName, server, it.id), accessToken) } } private fun addAsDefaultAccountIfUnique( - project: Project, accessToken: String, server: SourcegraphServerPath, requestExecutorFactory: SourcegraphApiRequestExecutor.Factory, @@ -241,9 +238,9 @@ class SettingsMigration : Activity { ) { loadUserDetails(requestExecutorFactory, accessToken, progressIndicator, server) { val codyAccount = CodyAccount(it.name, it.displayName, server, it.id) - addAccount(project, codyAccount, accessToken) - if (CodyAuthenticationManager.getInstance(project).hasNoActiveAccount()) - CodyAuthenticationManager.getInstance(project).setActiveAccount(codyAccount) + addAccount(codyAccount, accessToken) + if (CodyAuthenticationManager.getInstance().hasNoActiveAccount()) + CodyAuthenticationManager.getInstance().setActiveAccount(codyAccount) } } @@ -268,14 +265,14 @@ class SettingsMigration : Activity { } } - private fun addAccount(project: Project, codyAccount: CodyAccount, token: String) { - if (isAccountUnique(project, codyAccount)) { - CodyAuthenticationManager.getInstance(project).updateAccountToken(codyAccount, token) + private fun addAccount(codyAccount: CodyAccount, token: String) { + if (isAccountUnique(codyAccount)) { + CodyAuthenticationManager.getInstance().updateAccountToken(codyAccount, token) } } - private fun isAccountUnique(project: Project, codyAccount: CodyAccount): Boolean { - return CodyAuthenticationManager.getInstance(project) + private fun isAccountUnique(codyAccount: CodyAccount): Boolean { + return CodyAuthenticationManager.getInstance() .isAccountUnique(codyAccount.name, codyAccount.server) } diff --git a/src/main/kotlin/com/sourcegraph/cody/config/notification/AccountSettingChangeListener.kt b/src/main/kotlin/com/sourcegraph/cody/config/notification/AccountSettingChangeListener.kt index a92088cd4a..a116c33108 100644 --- a/src/main/kotlin/com/sourcegraph/cody/config/notification/AccountSettingChangeListener.kt +++ b/src/main/kotlin/com/sourcegraph/cody/config/notification/AccountSettingChangeListener.kt @@ -18,7 +18,7 @@ class AccountSettingChangeListener(project: Project) : ChangeListener(project) { override fun afterAction(context: AccountSettingChangeContext) { // Notify JCEF about the config changes - javaToJSBridge?.callJS("pluginSettingsChanged", ConfigUtil.getConfigAsJson(project)) + javaToJSBridge?.callJS("pluginSettingsChanged", ConfigUtil.getConfigAsJson()) UpgradeToCodyProNotification.autocompleteRateLimitError.set(null) UpgradeToCodyProNotification.chatRateLimitError.set(null) diff --git a/src/main/kotlin/com/sourcegraph/cody/config/notification/CodySettingChangeListener.kt b/src/main/kotlin/com/sourcegraph/cody/config/notification/CodySettingChangeListener.kt index 8ea402b242..d58819d6f5 100644 --- a/src/main/kotlin/com/sourcegraph/cody/config/notification/CodySettingChangeListener.kt +++ b/src/main/kotlin/com/sourcegraph/cody/config/notification/CodySettingChangeListener.kt @@ -20,7 +20,7 @@ class CodySettingChangeListener(project: Project) : ChangeListener(project) { object : CodySettingChangeActionNotifier { override fun afterAction(context: CodySettingChangeContext) { // Notify JCEF about the config changes - javaToJSBridge?.callJS("pluginSettingsChanged", ConfigUtil.getConfigAsJson(project)) + javaToJSBridge?.callJS("pluginSettingsChanged", ConfigUtil.getConfigAsJson()) if (context.oldCodyEnabled != context.newCodyEnabled) { if (context.newCodyEnabled) { diff --git a/src/main/kotlin/com/sourcegraph/cody/config/ui/AccountConfigurable.kt b/src/main/kotlin/com/sourcegraph/cody/config/ui/AccountConfigurable.kt index 0c03d96c82..dc8a2608ed 100644 --- a/src/main/kotlin/com/sourcegraph/cody/config/ui/AccountConfigurable.kt +++ b/src/main/kotlin/com/sourcegraph/cody/config/ui/AccountConfigurable.kt @@ -37,7 +37,7 @@ class AccountConfigurable(val project: Project) : private val codyApplicationSettings = service() private val settingsModel = SettingsModel(shouldCheckForUpdates = codyApplicationSettings.shouldCheckForUpdates) - private val authManager = CodyAuthenticationManager.getInstance(project) + private val authManager = CodyAuthenticationManager.getInstance() private val initialActiveAccount: Account? private val initialToken: String? @@ -107,7 +107,7 @@ class AccountConfigurable(val project: Project) : activeAccount = accountsModel.accounts.getFirstAccountOrNull() } - CodyAuthenticationManager.getInstance(project).setActiveAccount(activeAccount) + CodyAuthenticationManager.getInstance().setActiveAccount(activeAccount) accountsModel.activeAccount = activeAccount codyApplicationSettings.shouldCheckForUpdates = settingsModel.shouldCheckForUpdates diff --git a/src/main/kotlin/com/sourcegraph/cody/edit/actions/BaseEditCodeAction.kt b/src/main/kotlin/com/sourcegraph/cody/edit/actions/BaseEditCodeAction.kt index b0c9fdcc08..76a81b2e16 100644 --- a/src/main/kotlin/com/sourcegraph/cody/edit/actions/BaseEditCodeAction.kt +++ b/src/main/kotlin/com/sourcegraph/cody/edit/actions/BaseEditCodeAction.kt @@ -35,7 +35,7 @@ open class BaseEditCodeAction(runAction: (Editor) -> Unit) : CodyBundle.getString("action.cody.not-working") } else if (isBlockedByPolicy(project, event)) { CodyBundle.getString("filter.action-in-ignored-file.detail") - } else if (CodyAuthenticationManager.getInstance(project).hasNoActiveAccount()) { + } else if (CodyAuthenticationManager.getInstance().hasNoActiveAccount()) { CodyBundle.getString("action.sourcegraph.disabled.description") } else { "" diff --git a/src/main/kotlin/com/sourcegraph/cody/edit/actions/lenses/LensEditAction.kt b/src/main/kotlin/com/sourcegraph/cody/edit/actions/lenses/LensEditAction.kt index 22e0412a2f..7e5b5d5b02 100644 --- a/src/main/kotlin/com/sourcegraph/cody/edit/actions/lenses/LensEditAction.kt +++ b/src/main/kotlin/com/sourcegraph/cody/edit/actions/lenses/LensEditAction.kt @@ -22,8 +22,7 @@ abstract class LensEditAction(val editAction: (Project, AnActionEvent, Editor, S } override fun update(event: AnActionEvent) { - val project = event.project ?: return - val hasActiveAccount = CodyAuthenticationManager.getInstance(project).hasActiveAccount() + val hasActiveAccount = CodyAuthenticationManager.getInstance().hasActiveAccount() event.presentation.isEnabled = hasActiveAccount if (!event.presentation.isEnabled) { event.presentation.description = diff --git a/src/main/kotlin/com/sourcegraph/cody/history/HistoryService.kt b/src/main/kotlin/com/sourcegraph/cody/history/HistoryService.kt index f49ebf1a07..48fb6d06db 100644 --- a/src/main/kotlin/com/sourcegraph/cody/history/HistoryService.kt +++ b/src/main/kotlin/com/sourcegraph/cody/history/HistoryService.kt @@ -19,7 +19,7 @@ class HistoryService(private val project: Project) : @Synchronized fun getDefaultLlm(): LLMState? { - val account = CodyAuthenticationManager.getInstance(project).account + val account = CodyAuthenticationManager.getInstance().account val llm = account?.let { findEntry(it.id) }?.defaultLlm if (llm == null) return null return LLMState().also { it.copyFrom(llm) } @@ -49,11 +49,11 @@ class HistoryService(private val project: Project) : @Synchronized fun getActiveAccountHistory(): AccountData? = - CodyAuthenticationManager.getInstance(project).account?.let { findEntry(it.id) } + CodyAuthenticationManager.getInstance().account?.let { findEntry(it.id) } private fun getOrCreateActiveAccountEntry(): AccountData { val activeAccount = - CodyAuthenticationManager.getInstance(project).account + CodyAuthenticationManager.getInstance().account ?: throw IllegalStateException("No active account") val existingEntry = findEntry(activeAccount.id) diff --git a/src/main/kotlin/com/sourcegraph/cody/ignore/ActionInIgnoredFileNotification.kt b/src/main/kotlin/com/sourcegraph/cody/ignore/ActionInIgnoredFileNotification.kt index cc2644df00..6e1d8afc21 100644 --- a/src/main/kotlin/com/sourcegraph/cody/ignore/ActionInIgnoredFileNotification.kt +++ b/src/main/kotlin/com/sourcegraph/cody/ignore/ActionInIgnoredFileNotification.kt @@ -31,7 +31,7 @@ class ActionInIgnoredFileNotification : fun maybeNotify(project: Project) { val status = CodyStatusService.getCurrentStatus(project) - val account = CodyAuthenticationManager.getInstance(project).account + val account = CodyAuthenticationManager.getInstance().account when { status == CodyStatus.CodyUninit || status == CodyStatus.CodyDisabled || diff --git a/src/main/kotlin/com/sourcegraph/cody/initialization/EndOfTrialNotificationScheduler.kt b/src/main/kotlin/com/sourcegraph/cody/initialization/EndOfTrialNotificationScheduler.kt index c28efff4b0..cb0f061edc 100644 --- a/src/main/kotlin/com/sourcegraph/cody/initialization/EndOfTrialNotificationScheduler.kt +++ b/src/main/kotlin/com/sourcegraph/cody/initialization/EndOfTrialNotificationScheduler.kt @@ -31,7 +31,7 @@ class EndOfTrialNotificationScheduler private constructor(val project: Project) this.dispose() } - if (CodyAuthenticationManager.getInstance(project).account?.isDotcomAccount() != true) { + if (CodyAuthenticationManager.getInstance().account?.isDotcomAccount() != true) { return@scheduleAtFixedRate } diff --git a/src/main/kotlin/com/sourcegraph/cody/initialization/PostStartupActivity.kt b/src/main/kotlin/com/sourcegraph/cody/initialization/PostStartupActivity.kt index c62d4743ac..9b823566b9 100644 --- a/src/main/kotlin/com/sourcegraph/cody/initialization/PostStartupActivity.kt +++ b/src/main/kotlin/com/sourcegraph/cody/initialization/PostStartupActivity.kt @@ -7,6 +7,7 @@ import com.intellij.openapi.editor.ex.EditorEventMulticasterEx import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.sourcegraph.cody.agent.CodyAgentService +import com.sourcegraph.cody.config.CodyAuthenticationManager import com.sourcegraph.cody.config.CodySettingsChangeListener import com.sourcegraph.cody.config.migration.SettingsMigration import com.sourcegraph.cody.config.ui.CheckUpdatesTask @@ -35,6 +36,7 @@ class PostStartupActivity : StartupActivity.DumbAware { TelemetryInitializerActivity().runActivity(project) SettingsMigration().runActivity(project) CodyAuthNotificationActivity().runActivity(project) + CodyAuthenticationManager.getInstance().addAuthChangeListener(project) ApplicationManager.getApplication().executeOnPooledThread { // Scheduling because this task takes ~2s to run CheckUpdatesTask(project).queue() diff --git a/src/main/kotlin/com/sourcegraph/cody/listeners/CodySelectionInlayManager.kt b/src/main/kotlin/com/sourcegraph/cody/listeners/CodySelectionInlayManager.kt index 2d7c5581c8..c80617425f 100644 --- a/src/main/kotlin/com/sourcegraph/cody/listeners/CodySelectionInlayManager.kt +++ b/src/main/kotlin/com/sourcegraph/cody/listeners/CodySelectionInlayManager.kt @@ -37,7 +37,7 @@ class CodySelectionInlayManager(val project: Project) { !CodyAgentService.isConnected(project) || !ConfigUtil.isCodyUIHintsEnabled() || !CodyEditorUtil.isEditorValidForAutocomplete(editor) || - CodyAuthenticationManager.getInstance(project).hasNoActiveAccount() || + CodyAuthenticationManager.getInstance().hasNoActiveAccount() || IgnoreOracle.getInstance(project).policyForEditor(editor) != IgnorePolicy.USE) { return } diff --git a/src/main/kotlin/com/sourcegraph/cody/statusbar/CodyDisableAutocompleteAction.kt b/src/main/kotlin/com/sourcegraph/cody/statusbar/CodyDisableAutocompleteAction.kt index 0eb9ff3270..e367bde271 100644 --- a/src/main/kotlin/com/sourcegraph/cody/statusbar/CodyDisableAutocompleteAction.kt +++ b/src/main/kotlin/com/sourcegraph/cody/statusbar/CodyDisableAutocompleteAction.kt @@ -15,8 +15,7 @@ class CodyDisableAutocompleteAction : DumbAwareEDTAction("Disable Cody Autocompl override fun update(e: AnActionEvent) { super.update(e) - val hasActiveAccount = - e.project?.let { CodyAuthenticationManager.getInstance(it).hasActiveAccount() } ?: false + val hasActiveAccount = CodyAuthenticationManager.getInstance().hasActiveAccount() e.presentation.isEnabledAndVisible = ConfigUtil.isCodyEnabled() && ConfigUtil.isCodyAutocompleteEnabled() && hasActiveAccount } diff --git a/src/main/kotlin/com/sourcegraph/cody/statusbar/CodyDisableLanguageForAutocompleteAction.kt b/src/main/kotlin/com/sourcegraph/cody/statusbar/CodyDisableLanguageForAutocompleteAction.kt index 88cbc4c584..bdc217d9db 100644 --- a/src/main/kotlin/com/sourcegraph/cody/statusbar/CodyDisableLanguageForAutocompleteAction.kt +++ b/src/main/kotlin/com/sourcegraph/cody/statusbar/CodyDisableLanguageForAutocompleteAction.kt @@ -25,8 +25,7 @@ class CodyDisableLanguageForAutocompleteAction : DumbAwareEDTAction() { val isLanguageBlacklisted = languageForFocusedEditor?.let { CodyLanguageUtil.isLanguageBlacklisted(it) } ?: false val languageName = languageForFocusedEditor?.displayName ?: "" - val hasActiveAccount = - e.project?.let { CodyAuthenticationManager.getInstance(it).hasActiveAccount() } ?: false + val hasActiveAccount = CodyAuthenticationManager.getInstance().hasActiveAccount() e.presentation.isEnabledAndVisible = languageForFocusedEditor != null && ConfigUtil.isCodyEnabled() && diff --git a/src/main/kotlin/com/sourcegraph/cody/statusbar/CodyStatusService.kt b/src/main/kotlin/com/sourcegraph/cody/statusbar/CodyStatusService.kt index 6ce04ec126..d5df509833 100644 --- a/src/main/kotlin/com/sourcegraph/cody/statusbar/CodyStatusService.kt +++ b/src/main/kotlin/com/sourcegraph/cody/statusbar/CodyStatusService.kt @@ -46,11 +46,10 @@ class CodyStatusService(val project: Project) : Disposable { synchronized(this) { val oldStatus = status val service = ApplicationManager.getApplication().getService(CodyAccountManager::class.java) - val authManager = CodyAuthenticationManager.getInstance(project) + val authManager = CodyAuthenticationManager.getInstance() val isTokenInvalid = authManager.getIsTokenInvalid().getNow(null) == true - val token = - CodyAuthenticationManager.getInstance(project).account?.let(service::findCredentials) + val token = CodyAuthenticationManager.getInstance().account?.let(service::findCredentials) // Note, the order of these clauses is important because earlier clauses take precedence over // later ones. // Fundamental issues are tested first. diff --git a/src/main/kotlin/com/sourcegraph/cody/ui/CodyToolWindowFactory.kt b/src/main/kotlin/com/sourcegraph/cody/ui/CodyToolWindowFactory.kt index c2fe369797..36ddc37261 100644 --- a/src/main/kotlin/com/sourcegraph/cody/ui/CodyToolWindowFactory.kt +++ b/src/main/kotlin/com/sourcegraph/cody/ui/CodyToolWindowFactory.kt @@ -301,7 +301,7 @@ class WebUIHostImpl( if ((command == "auth" && decodedJson.get("authKind")?.asString == "signout") || (isCommand && id == "cody.auth.signout")) { - CodyAuthenticationManager.getInstance(project).setActiveAccount(null) + CodyAuthenticationManager.getInstance().setActiveAccount(null) } else if (isCommand && id == "cody.auth.switchAccount") { runInEdt { ShowSettingsUtil.getInstance().showSettingsDialog(project, AccountConfigurable::class.java) diff --git a/src/main/kotlin/com/sourcegraph/common/BrowserOpener.kt b/src/main/kotlin/com/sourcegraph/common/BrowserOpener.kt index bbd5d143b9..1ddb7c4c8e 100644 --- a/src/main/kotlin/com/sourcegraph/common/BrowserOpener.kt +++ b/src/main/kotlin/com/sourcegraph/common/BrowserOpener.kt @@ -12,7 +12,7 @@ import java.net.URISyntaxException object BrowserOpener { fun openRelativeUrlInBrowser(project: Project, relativeUrl: String) { - openInBrowser(project, getServerPath(project).url + "/" + relativeUrl) + openInBrowser(project, getServerPath().url + "/" + relativeUrl) } fun openInBrowser(project: Project?, absoluteUrl: String) { diff --git a/src/main/kotlin/com/sourcegraph/config/ConfigUtil.kt b/src/main/kotlin/com/sourcegraph/config/ConfigUtil.kt index 58fd0c0b8b..79c746874b 100644 --- a/src/main/kotlin/com/sourcegraph/config/ConfigUtil.kt +++ b/src/main/kotlin/com/sourcegraph/config/ConfigUtil.kt @@ -69,7 +69,7 @@ object ConfigUtil { project: Project, customConfigContent: String? = null ): ExtensionConfiguration { - val serverAuth = ServerAuthLoader.loadServerAuth(project) + val serverAuth = ServerAuthLoader.loadServerAuth() return ExtensionConfiguration( anonymousUserID = CodyApplicationSettings.instance.anonymousUserId, @@ -87,8 +87,8 @@ object ConfigUtil { } @JvmStatic - fun getConfigAsJson(project: Project): JsonObject { - val (instanceUrl, accessToken, customRequestHeaders) = ServerAuthLoader.loadServerAuth(project) + fun getConfigAsJson(): JsonObject { + val (instanceUrl, accessToken, customRequestHeaders) = ServerAuthLoader.loadServerAuth() return JsonObject().apply { addProperty("instanceURL", instanceUrl) addProperty("accessToken", accessToken) @@ -99,8 +99,8 @@ object ConfigUtil { } @JvmStatic - fun getServerPath(project: Project): SourcegraphServerPath { - val activeAccount = CodyAuthenticationManager.getInstance(project).account + fun getServerPath(): SourcegraphServerPath { + val activeAccount = CodyAuthenticationManager.getInstance().account return activeAccount?.server ?: from(DOTCOM_URL, "") } diff --git a/src/test/kotlin/com/sourcegraph/cody/config/SettingsMigrationTest.kt b/src/test/kotlin/com/sourcegraph/cody/config/SettingsMigrationTest.kt index fc9a7d1f66..bbbe825b61 100644 --- a/src/test/kotlin/com/sourcegraph/cody/config/SettingsMigrationTest.kt +++ b/src/test/kotlin/com/sourcegraph/cody/config/SettingsMigrationTest.kt @@ -181,7 +181,7 @@ class SettingsMigrationTest : BasePlatformTestCase() { } val project = myFixture.project project.registerServiceInstance( - CodyAuthenticationManager::class.java, CodyAuthenticationManager(project)) + CodyAuthenticationManager::class.java, CodyAuthenticationManager()) project.registerServiceInstance(HistoryService::class.java, HistoryService(project)) HistoryService.getInstance(project) .loadState(HistoryState().also { it.copyFrom(originalHistory) })