Elffuss BraidHub

kikocis/continue public

fix: Follow JetBrains IDE proxy settings (#6531)

* fix: use HttpRequests in ContinueAuthService

* wip

* fix: Use HttpRequests everywhere in Jetbrains plugin

* build: Remove OkHttp from release (note: it's still used for testing)

* fix time

* remove todo

* remove todo (fixed)
Changesetf8f249972d523d97f6c248cbef9d5798e97a7f0e186235890d74191e07704ca7
AuthorJakub Błach <jakubblach@gmail.com> · 2025-07-21 23:25 +02:00
CommitterGitHub <noreply@github.com> · 2025-07-21 14:25 -07:00
Parents2c1fc907ac7f

Browse the files at this changeset

3 files changed

modified extensions/intellij/build.gradle.kts +0 −3
@@ -32,9 +32,6 @@
3232 }
3333
3434 dependencies {
35- implementation("com.squareup.okhttp3:okhttp:4.12.0") {
36- exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib")
37- }
3835 implementation("org.jetbrains.kotlin:kotlin-stdlib:1.4.32")
3936 implementation("com.posthog.java:posthog:1.+")
4037 implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt +41 −57
@@ -1,5 +1,6 @@
11 package com.github.continuedev.continueintellijextension.auth
22
3+import com.github.continuedev.continueintellijextension.error.ContinueErrorService
34 import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
45 import com.github.continuedev.continueintellijextension.services.ContinuePluginService
56 import com.google.gson.Gson
@@ -10,24 +11,22 @@
1011 import com.intellij.openapi.application.ApplicationManager
1112 import com.intellij.openapi.components.Service
1213 import com.intellij.openapi.components.service
14+import com.intellij.openapi.diagnostic.Logger
1315 import com.intellij.openapi.project.Project
1416 import com.intellij.remoteServer.util.CloudConfigurationUtil.createCredentialAttributes
17+import com.intellij.util.io.HttpRequests
1518 import kotlinx.coroutines.CoroutineScope
1619 import kotlinx.coroutines.Dispatchers
20+import kotlinx.coroutines.delay
1721 import kotlinx.coroutines.launch
18-import kotlinx.coroutines.withContext
19-import okhttp3.MediaType.Companion.toMediaType
20-import okhttp3.OkHttpClient
21-import okhttp3.Request
22-import okhttp3.RequestBody.Companion.toRequestBody
23-import java.net.URL
22+import kotlin.time.Duration.Companion.minutes
2423
2524 @Service
2625 class ContinueAuthService {
2726 private val coroutineScope = CoroutineScope(Dispatchers.IO)
27+ private val log = Logger.getInstance(ContinueAuthService::class.java)
2828
2929 companion object {
30- fun getInstance(): ContinueAuthService = service<ContinueAuthService>()
3130 private const val CREDENTIALS_USER = "ContinueAuthUser"
3231 private const val ACCESS_TOKEN_KEY = "ContinueAccessToken"
3332 private const val REFRESH_TOKEN_KEY = "ContinueRefreshToken"
@@ -77,73 +76,47 @@
7776 }
7877
7978 private fun updateRefreshToken(token: String) {
80- // Launch a coroutine to call the suspend function
81- coroutineScope.launch {
82- try {
83- val response = refreshToken(token)
84- val accessToken = response["accessToken"] as? String
85- val refreshToken = response["refreshToken"] as? String
86- val user = response["user"] as? Map<*, *>
87- val firstName = user?.get("firstName") as? String
88- val lastName = user?.get("lastName") as? String
89- val label = "$firstName $lastName"
90- val id = user?.get("id") as? String
91- val email = user?.get("email") as? String
92-
93- // Persist the session info
94- setRefreshToken(refreshToken!!)
95- val sessionInfo =
96- ControlPlaneSessionInfo(accessToken!!, ControlPlaneSessionInfo.Account(email!!, label))
97- setControlPlaneSessionInfo(sessionInfo)
98-
99- // Notify listeners
100- ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC)
101- .handleUpdatedSessionInfo(sessionInfo)
102-
103- } catch (e: Exception) {
104- // Handle any exceptions
105- println("Exception while refreshing token: ${e.message}")
106- }
79+ try {
80+ val response = refreshToken(token)
81+ val accountLabel = "${response.user.firstName} ${response.user.lastName}"
82+
83+ // Persist the session info
84+ setRefreshToken(response.refreshToken)
85+ val account = ControlPlaneSessionInfo.Account(response.user.email, accountLabel)
86+ val sessionInfo = ControlPlaneSessionInfo(response.accessToken, account)
87+ setControlPlaneSessionInfo(sessionInfo)
88+
89+ // Notify listeners
90+ ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC)
91+ .handleUpdatedSessionInfo(sessionInfo)
92+ } catch (e: Exception) {
93+ service<ContinueErrorService>().report(e, "Exception while refreshing token ${e.message}")
10794 }
10895 }
10996
11097 private fun setupRefreshTokenInterval() {
111- // Launch a coroutine to refresh the token every 30 minutes
11298 coroutineScope.launch {
11399 while (true) {
114100 val refreshToken = getRefreshToken()
115101 if (refreshToken != null) {
116102 updateRefreshToken(refreshToken)
117103 }
118-
119- kotlinx.coroutines.delay(15 * 60 * 1000) // 15 minutes in milliseconds
104+ log.info("Token refreshed, retrying in 15 minutes")
105+ delay(15.minutes)
120106 }
121107 }
122108 }
123109
124- private suspend fun refreshToken(refreshToken: String) = withContext(Dispatchers.IO) {
125- val client = OkHttpClient()
126- val url = URL(getControlPlaneUrl()).toURI().resolve("/auth/refresh").toURL()
127- val jsonBody = mapOf("refreshToken" to refreshToken)
128- val jsonString = Gson().toJson(jsonBody)
129- val requestBody = jsonString.toRequestBody("application/json".toMediaType())
130-
131- val request = Request.Builder()
132- .url(url)
133- .post(requestBody)
134- .header("Content-Type", "application/json")
135- .build()
136-
137- val response = client.newCall(request).execute()
138-
139- val responseBody = response.body?.string()
110+ private fun refreshToken(refreshToken: String): RefreshTokenResponse {
140111 val gson = Gson()
141- val responseMap = gson.fromJson(responseBody, Map::class.java)
142-
143- responseMap
112+ val jsonBody = gson.toJson(mapOf("refreshToken" to refreshToken))
113+ val url = getControlPlaneUrl() + "/auth/refresh"
114+ val response = HttpRequests.post(url, HttpRequests.JSON_CONTENT_TYPE)
115+ .connect { connection -> connection.write(jsonBody.toByteArray()) }
116+ .toString()
117+ return gson.fromJson(response, RefreshTokenResponse::class.java)
144118 }
145119
146-
147120 private fun openSignInPage(project: Project, useOnboarding: Boolean): String? {
148121 var authUrl: String? = null
149122 val coreMessenger = project.service<ContinuePluginService>().coreMessenger
@@ -256,6 +229,17 @@
256229 setAccountLabel(info.account.label)
257230 }
258231
232+ private data class RefreshTokenResponse(
233+ val accessToken: String,
234+ val refreshToken: String,
235+ val user: User,
236+ ) {
237+ data class User(
238+ val firstName: String,
239+ val lastName: String,
240+ val email: String
241+ )
242+ }
259243 }
260244
261245 // Data class to represent the ControlPlaneSessionInfo
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +27 −55
@@ -1,25 +1,25 @@
11 package com.github.continuedev.continueintellijextension.services
22
3-import com.github.continuedev.continueintellijextension.constants.getConfigJsPath
43 import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
5-import com.intellij.execution.target.value.constant
4+import com.github.continuedev.continueintellijextension.error.ContinueErrorService
65 import com.intellij.openapi.application.ApplicationInfo
76 import com.intellij.openapi.application.ApplicationManager
8-import com.intellij.openapi.components.*
7+import com.intellij.openapi.components.PersistentStateComponent
8+import com.intellij.openapi.components.State
9+import com.intellij.openapi.components.Storage
10+import com.intellij.openapi.components.service
911 import com.intellij.openapi.options.Configurable
1012 import com.intellij.openapi.project.DumbAware
11-import com.intellij.openapi.util.SystemInfo
1213 import com.intellij.util.concurrency.AppExecutorUtil
14+import com.intellij.util.io.HttpRequests
1315 import com.intellij.util.messages.Topic
14-import kotlinx.serialization.Serializable
1516 import kotlinx.serialization.decodeFromString
1617 import kotlinx.serialization.json.Json
17-import okhttp3.OkHttpClient
18-import okhttp3.Request
1918 import java.awt.GridBagConstraints
2019 import java.awt.GridBagLayout
2120 import java.io.File
2221 import java.io.IOException
22+import java.net.URL
2323 import java.util.concurrent.ScheduledFuture
2424 import java.util.concurrent.TimeUnit
2525 import javax.swing.*
@@ -72,11 +72,10 @@
7272 }
7373 }
7474
75-@Serializable
76-class ContinueRemoteConfigSyncResponse {
77- var configJson: String? = null
78- var configJs: String? = null
79-}
75+data class ContinueRemoteConfigSyncResponse(
76+ var configJson: String?,
77+ var configJs: String?
78+)
8079
8180 @State(
8281 name = "com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings",
@@ -117,50 +116,23 @@
117116
118117 // Sync remote config from server
119118 private fun syncRemoteConfig() {
120- val state = instance.continueState
121-
122- if (state.remoteConfigServerUrl != null && state.remoteConfigServerUrl!!.isNotEmpty()) {
123- // download remote config as json file
124-
125- val client = OkHttpClient()
126- val baseUrl = state.remoteConfigServerUrl?.removeSuffix("/")
127-
128- val requestBuilder = Request.Builder().url("${baseUrl}/sync")
129-
130- if (state.userToken != null) {
131- requestBuilder.addHeader("Authorization", "Bearer ${state.userToken}")
132- }
133-
134- val request = requestBuilder.build()
135- var configResponse: ContinueRemoteConfigSyncResponse? = null
136-
119+ val remoteServerUrl = state.remoteConfigServerUrl
120+ val token = state.userToken
121+ if (remoteServerUrl != null && remoteServerUrl.isNotEmpty()) {
122+ val baseUrl = remoteServerUrl.removeSuffix("/")
137123 try {
138- client.newCall(request).execute().use { response ->
139- if (!response.isSuccessful) throw IOException("Unexpected code $response")
140-
141- response.body?.string()?.let { responseBody ->
142- try {
143- configResponse =
144- Json.decodeFromString<ContinueRemoteConfigSyncResponse>(responseBody)
145- } catch (e: Exception) {
146- e.printStackTrace()
147- return
148- }
149- }
150- }
124+ val url = "$baseUrl/sync"
125+ val responseBody = HttpRequests.post(url, HttpRequests.JSON_CONTENT_TYPE)
126+ .tuner { connection ->
127+ if (token != null)
128+ connection.addRequestProperty("Authorization", "Bearer $token")
129+ }.readString()
130+ val response = Json.decodeFromString<ContinueRemoteConfigSyncResponse>(responseBody)
131+ val file = File(getConfigJsonPath(URL(url).host))
132+ response.configJs.let { file.writeText(it!!) }
133+ response.configJson.let { file.writeText(it!!) }
151134 } catch (e: IOException) {
152- e.printStackTrace()
153- return
154- }
155-
156- if (configResponse?.configJson?.isNotEmpty()!!) {
157- val file = File(getConfigJsonPath(request.url.host))
158- file.writeText(configResponse!!.configJson!!)
159- }
160-
161- if (configResponse?.configJs?.isNotEmpty()!!) {
162- val file = File(getConfigJsPath(request.url.host))
163- file.writeText(configResponse!!.configJs!!)
135+ service<ContinueErrorService>().report(e, "Unexpected exception during remote config sync")
164136 }
165137 }
166138 }
@@ -174,7 +146,7 @@
174146
175147 instance.remoteSyncFuture = AppExecutorUtil.getAppScheduledExecutorService()
176148 .scheduleWithFixedDelay(
177- { syncRemoteConfig() },
149+ ::syncRemoteConfig,
178150 0,
179151 continueState.remoteConfigSyncPeriod.toLong(),
180152 TimeUnit.MINUTES