From ad5cf21c0c21a413808fae1524c5c9256bbfe1b2 Mon Sep 17 00:00:00 2001 From: kirillk Date: Sun, 30 Aug 2026 14:12:45 -0400 Subject: [PATCH 1/5] fix(jetbrains): resolve api key env var when selecting custom provider models The custom OpenAI-compatible provider dialog's "Select models" action only read the API key text field, ignoring the "API key environment variable" field entirely. Providers configured with an env var worked for chatting (the CLI resolves it at runtime) but failed to list models unless the key was retyped into the dialog. Resolve credentials backend-side, where the env that matters actually lives (the CLI process), with precedence: typed key -> env var value via EnvironmentUtil -> the provider's already-stored key from provider state. This also removes the retyping requirement for providers authenticated with a stored API key, not just an env var. An unresolvable env var no longer blocks the fetch, since local providers (Ollama, LM Studio, etc.) need no credential; instead the result carries an envMissing flag so the dialog can append a hint naming the variable. While tracing this, three related defects surfaced from the same root cause (env-configured custom providers being second-class in this UI): - saved custom headers were never sent when fetching models - deleting a custom provider whose env var resolved was blocked, because the disconnect guard checked provider source before the config-backed delete branch - clearing the env var field left the old value in kilo.json, since the config patch omitted the key instead of nulling it Fixes all four. The API key field still shows blank on edit (secrets are never prefilled or logged); a hint now explains that a saved key is kept when the field is left blank. --- ...etbrains-custom-provider-env-var-models.md | 5 + .../kilocode/backend/cli/KiloCliDataParser.kt | 2 +- .../KiloBackendProviderSettingsManager.kt | 26 ++- .../KiloBackendProviderSettingsManagerTest.kt | 193 +++++++++++++++++ .../settings/providers/ProvidersSettingsUi.kt | 32 ++- .../resources/messages/KiloBundle.properties | 2 + .../providers/ProvidersSettingsUiTest.kt | 197 ++++++++++++++++++ .../client/testing/FakeProviderRpcApi.kt | 5 +- .../kilocode/rpc/dto/ProviderSettingsDto.kt | 4 + 9 files changed, 453 insertions(+), 13 deletions(-) create mode 100644 .changeset/jetbrains-custom-provider-env-var-models.md diff --git a/.changeset/jetbrains-custom-provider-env-var-models.md b/.changeset/jetbrains-custom-provider-env-var-models.md new file mode 100644 index 000000000000..ee29cc313979 --- /dev/null +++ b/.changeset/jetbrains-custom-provider-env-var-models.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Use the configured API key environment variable (or an already-saved key) when selecting models for a custom OpenAI-compatible provider, instead of requiring the key to be retyped every time. Also allow removing custom providers that authenticate through an environment variable, and stop a cleared environment variable from lingering in the saved configuration. diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/cli/KiloCliDataParser.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/cli/KiloCliDataParser.kt index 1e401e45b5cd..eb250dfd8467 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/cli/KiloCliDataParser.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/cli/KiloCliDataParser.kt @@ -1087,7 +1087,7 @@ object KiloCliDataParser { put("name", input.name.trim().ifBlank { id }) put("npm", "@ai-sdk/openai-compatible") put("options", buildJsonObject { put("baseURL", input.baseUrl.trim()) }) - if (env != null) put("env", buildJsonArray { add(JsonPrimitive(env)) }) + if (env != null) put("env", buildJsonArray { add(JsonPrimitive(env)) }) else put("env", JsonNull) if (input.headers.isNotEmpty()) put("headers", buildJsonObject { input.headers.forEach { (k, v) -> put(k, v) } }) if (models.isNotEmpty()) put("models", JsonObject(models)) } diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt index a046fc4d3427..0db3d3012bb4 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt @@ -19,6 +19,7 @@ import ai.kilocode.rpc.dto.ProviderOAuthAuthorizeDto import ai.kilocode.rpc.dto.ProviderOAuthCallbackDto import ai.kilocode.rpc.dto.ProviderOAuthReadyDto import ai.kilocode.rpc.dto.ProviderSettingsDto +import com.intellij.util.EnvironmentUtil import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.MediaType.Companion.toMediaType @@ -111,7 +112,7 @@ internal class KiloBackendProviderSettingsManager( if (input.providerId == "kilo") { return ProviderActionResultDto(current, error = "Kilo Gateway cannot be disconnected from provider settings.") } - if (provider?.source == "env") { + if (provider?.source == "env" && cfg == null) { return ProviderActionResultDto(current, error = "Provider is configured by environment variables.") } val configured = input.providerId in current.connected || provider?.key != null || provider?.source == "config" || cfg != null @@ -124,7 +125,7 @@ internal class KiloBackendProviderSettingsManager( dispose() return ProviderActionResultDto(state(input.directory)) } - if (provider?.source == "config") { + if (cfg != null || provider?.source == "config") { val scope = cfg?.scope ?: "global" val ids = disabledFor(current, scope) + input.providerId patch(input.directory, scope, KiloCliDataParser.buildDisabledProviderPatch(ids)) @@ -160,12 +161,18 @@ internal class KiloBackendProviderSettingsManager( return ProviderActionResultDto(state(input.directory)) } - suspend fun fetch(input: CustomModelFetchDto): CustomModelFetchResultDto { + suspend fun fetch(input: CustomModelFetchDto, env: Map = EnvironmentUtil.getEnvironmentMap()): CustomModelFetchResultDto { + val name = input.env?.trim()?.takeIf { it.isNotBlank() } + val resolved = name?.let { env[it]?.takeIf(String::isNotBlank) } + val stored = if (input.apiKey.isNullOrBlank() && resolved == null) storedKey(input) else null + val key = input.apiKey?.takeIf { it.isNotBlank() } ?: resolved ?: stored + val envMissing = name != null && resolved == null val url = input.baseUrl.trim().trimEnd('/') + "/models" + LOG.debug { "custom provider model fetch: env=$name resolved=${resolved != null} stored=${stored != null}" } return try { val request = Request.Builder().url(url).get().apply { - input.apiKey?.takeIf { it.isNotBlank() }?.let { header("Authorization", "Bearer $it") } - input.headers.forEach { (key, value) -> header(key, value) } + key?.let { header("Authorization", "Bearer $it") } + input.headers.forEach { (headerKey, value) -> header(headerKey, value) } }.build() val raw = withContext(Dispatchers.IO) { FETCH.newCall(request).execute().use { response -> @@ -174,13 +181,18 @@ internal class KiloBackendProviderSettingsManager( body } } - CustomModelFetchResultDto(KiloCliDataParser.parseModelIds(raw)) + CustomModelFetchResultDto(KiloCliDataParser.parseModelIds(raw), envMissing = envMissing) } catch (e: Exception) { LOG.warn("Custom provider model fetch failed: ${e.message}", e) - CustomModelFetchResultDto(error = e.message) + CustomModelFetchResultDto(error = e.message, envMissing = envMissing) } } + private suspend fun storedKey(input: CustomModelFetchDto): String? { + val id = input.providerId?.trim()?.takeIf { it.isNotBlank() } ?: return null + return state(input.directory).providers.firstOrNull { it.id == id }?.key?.takeIf(String::isNotBlank) + } + private suspend fun load(resource: String, errors: MutableList, block: suspend () -> T): T? { val start = System.currentTimeMillis() LOG.debug { "provider settings $resource: start" } diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt index 10a2ea8e61ea..39b6d21a8701 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt @@ -6,11 +6,14 @@ import ai.kilocode.backend.testing.FakeCliServer import ai.kilocode.backend.testing.MockCliServer import ai.kilocode.backend.testing.TestLog import ai.kilocode.rpc.dto.CustomModelDto +import ai.kilocode.rpc.dto.CustomModelFetchDto import ai.kilocode.rpc.dto.CustomProviderSaveDto import ai.kilocode.rpc.dto.ProviderConnectDto import ai.kilocode.rpc.dto.ProviderDisconnectDto import ai.kilocode.rpc.dto.ProviderEnableDto import kotlinx.coroutines.async +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob @@ -265,6 +268,196 @@ class KiloBackendProviderSettingsManagerTest { assertEquals(1, mock.requestCount("/global/dispose")) } + @Test + fun `saving custom provider with blank env var clears env in config patch`() = runBlocking { + mock.providers = """{ + "all":[{"id":"my-openai","name":"My OpenAI","source":"config","models":{"gpt-4o":{"id":"gpt-4o","name":"gpt-4o"}}}], + "default":{}, + "connected":[], + "failed":[] + }""".trimIndent() + val manager = manager() + + mock.resetCounts() + val result = manager.saveCustom( + CustomProviderSaveDto( + "/test", + "my-openai", + "My OpenAI", + "https://api.example.com/v1", + apiKey = "sk-test", + envVar = null, + models = listOf(CustomModelDto("gpt-4o", "gpt-4o")), + ), + ) + + assertNull(result.error) + assertContains(mock.lastConfigPatchBody.orEmpty(), "\"env\":null") + } + + @Test + fun `disconnecting env backed openai compatible custom provider deletes config and auth`() = runBlocking { + mock.config = """{ + "provider":{ + "local-openai":{"name":"Local OpenAI","npm":"@ai-sdk/openai-compatible","options":{"baseURL":"http://localhost:11434"},"env":["API_KEY"]} + } + }""".trimIndent() + mock.providers = """{ + "all":[{"id":"local-openai","name":"Local OpenAI","source":"env","key":"sk-env","models":{}}], + "default":{}, + "connected":["local-openai"], + "failed":[] + }""".trimIndent() + val manager = manager() + + mock.resetCounts() + val result = manager.disconnect(ProviderDisconnectDto("/test", "local-openai")) + + assertNull(result.error) + assertContains(mock.lastConfigPatchBody.orEmpty(), "\"local-openai\":null") + assertEquals("/auth/local-openai", mock.lastAuthDeletePath) + } + + @Test + fun `disconnecting env only catalog provider still returns configured by environment error`() = runBlocking { + mock.providers = """{ + "all":[{"id":"anthropic","name":"Anthropic","source":"env","key":"sk-env","models":{}}], + "default":{}, + "connected":["anthropic"], + "failed":[] + }""".trimIndent() + val manager = manager() + + mock.resetCounts() + val result = manager.disconnect(ProviderDisconnectDto("/test", "anthropic")) + + assertEquals("Provider is configured by environment variables.", result.error) + assertNull(mock.lastConfigPatchBody) + } + + @Test + fun `fetch uses env var value for authorization when no key is typed`() = runBlocking { + val server = MockWebServer() + server.enqueue(MockResponse().setBody("""{"data":[{"id":"gpt-4o"}]}""")) + server.start() + val manager = manager() + + try { + val result = manager.fetch( + CustomModelFetchDto(baseUrl = server.url("/v1").toString(), directory = "/test", env = "API_KEY"), + env = mapOf("API_KEY" to "sk-env"), + ) + + assertEquals(listOf("gpt-4o"), result.models) + assertNull(result.error) + assertFalse(result.envMissing) + assertEquals("Bearer sk-env", server.takeRequest().getHeader("Authorization")) + } finally { + server.shutdown() + } + } + + @Test + fun `fetch falls back to stored provider key when key and env are absent`() = runBlocking { + mock.providers = """{ + "all":[{"id":"my-openai","name":"My OpenAI","source":"api","key":"sk-stored","models":{}}], + "default":{}, + "connected":["my-openai"], + "failed":[] + }""".trimIndent() + val server = MockWebServer() + server.enqueue(MockResponse().setBody("""{"data":[{"id":"gpt-4o"}]}""")) + server.start() + val manager = manager() + + try { + val result = manager.fetch( + CustomModelFetchDto(baseUrl = server.url("/v1").toString(), directory = "/test", providerId = "my-openai"), + env = emptyMap(), + ) + + assertEquals(listOf("gpt-4o"), result.models) + assertEquals("Bearer sk-stored", server.takeRequest().getHeader("Authorization")) + } finally { + server.shutdown() + } + } + + @Test + fun `fetch marks env missing and sends request without authorization when env var is unset`() = runBlocking { + val server = MockWebServer() + server.enqueue(MockResponse().setBody("""{"data":[{"id":"local-model"}]}""")) + server.start() + val manager = manager() + + try { + val result = manager.fetch( + CustomModelFetchDto(baseUrl = server.url("/v1").toString(), directory = "/test", env = "MISSING_KEY"), + env = emptyMap(), + ) + + assertEquals(listOf("local-model"), result.models) + assertTrue(result.envMissing) + assertNull(server.takeRequest().getHeader("Authorization")) + } finally { + server.shutdown() + } + } + + @Test + fun `fetch forwards custom headers to the models request`() = runBlocking { + val server = MockWebServer() + server.enqueue(MockResponse().setBody("""{"data":[]}""")) + server.start() + val manager = manager() + + try { + manager.fetch( + CustomModelFetchDto( + baseUrl = server.url("/v1").toString(), + directory = "/test", + headers = mapOf("X-Custom" to "abc-123"), + ), + env = emptyMap(), + ) + + assertEquals("abc-123", server.takeRequest().getHeader("X-Custom")) + } finally { + server.shutdown() + } + } + + @Test + fun `fetch prefers typed api key over env var and stored key`() = runBlocking { + mock.providers = """{ + "all":[{"id":"my-openai","name":"My OpenAI","source":"api","key":"sk-stored","models":{}}], + "default":{}, + "connected":["my-openai"], + "failed":[] + }""".trimIndent() + val server = MockWebServer() + server.enqueue(MockResponse().setBody("""{"data":[]}""")) + server.start() + val manager = manager() + + try { + manager.fetch( + CustomModelFetchDto( + baseUrl = server.url("/v1").toString(), + directory = "/test", + providerId = "my-openai", + apiKey = "sk-typed", + env = "API_KEY", + ), + env = mapOf("API_KEY" to "sk-env"), + ) + + assertEquals("Bearer sk-typed", server.takeRequest().getHeader("Authorization")) + } finally { + server.shutdown() + } + } + @Test fun `disconnecting kilo gateway returns error without logout`() = runBlocking { mock.providers = """{ diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/providers/ProvidersSettingsUi.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/providers/ProvidersSettingsUi.kt index 22e134b49d5c..0e4731dcc728 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/providers/ProvidersSettingsUi.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/providers/ProvidersSettingsUi.kt @@ -55,6 +55,7 @@ import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBPasswordField import com.intellij.ui.components.JBTextField import com.intellij.util.concurrency.annotations.RequiresEdt +import com.intellij.util.ui.UIUtil import java.awt.BorderLayout import java.awt.Component import java.awt.event.KeyEvent @@ -272,6 +273,7 @@ internal class ProvidersSettingsUi( baseUrl = cfg.options["baseURL"].orEmpty(), envVar = cfg.env.firstOrNull(), models = cfg.models.values.map { it.id }, + headers = cfg.headers, ), ) } @@ -617,6 +619,7 @@ internal data class CustomProviderEdit( val baseUrl: String, val envVar: String?, val models: List, + val headers: Map = emptyMap(), ) internal class CustomProviderDialog( @@ -703,12 +706,21 @@ internal class CustomProviderDialog( KiloBundle.message("settings.providers.customId") to id, KiloBundle.message("settings.providers.customName") to name, KiloBundle.message("settings.providers.customUrl") to url, - KiloBundle.message("settings.providers.apiKey") to key, - KiloBundle.message("settings.providers.customEnv") to env, ).forEach { (label, field) -> panel.next(JBLabel(label)) panel.next(field) } + panel.next(JBLabel(KiloBundle.message("settings.providers.apiKey"))) + panel.next(key) + if (existing != null) { + panel.next( + JBLabel(KiloBundle.message("settings.providers.customKeyStored")).apply { + foreground = UIUtil.getContextHelpForeground() + }, + ) + } + panel.next(JBLabel(KiloBundle.message("settings.providers.customEnv"))) + panel.next(env) panel.next(JBLabel(KiloBundle.message("settings.providers.customModels"))) panel.next(JPanel(BorderLayout(UiStyle.Gap.sm(), 0)).apply { add(models, BorderLayout.CENTER) @@ -797,9 +809,14 @@ internal class CustomProviderDialog( return } startFetch() + val envName = env.text.trim().takeIf { it.isNotBlank() } val input = CustomModelFetchDto( baseUrl = url.text.trim(), + directory = directory, + providerId = id.text.trim().takeIf { it.isNotBlank() }, apiKey = String(key.password).takeIf { it.isNotBlank() }, + env = envName, + headers = existing?.headers ?: emptyMap(), ) val current = token job = cs.launch { @@ -819,12 +836,12 @@ internal class CustomProviderDialog( finishFetch() val error = result.error if (error != null) { - fail(error) + fail(envHint(error, envName, result.envMissing)) return@withContext } val ids = result.models.mapNotNull { it.trim().takeIf(String::isNotBlank) }.distinct() if (ids.isEmpty()) { - fail(KiloBundle.message("settings.providers.customModelsEmpty")) + fail(envHint(KiloBundle.message("settings.providers.customModelsEmpty"), envName, result.envMissing)) return@withContext } showModelPopup(ids) @@ -832,6 +849,13 @@ internal class CustomProviderDialog( } } + // Local-only providers (e.g. Ollama, LM Studio) need no credential, so a missing env var must + // not block the fetch — only annotate the resulting error with which variable was unresolved. + private fun envHint(message: String, envName: String?, envMissing: Boolean): String { + if (!envMissing || envName == null) return message + return "$message ${KiloBundle.message("settings.providers.customEnvMissing", envName)}" + } + @RequiresEdt private fun startFetch() { draft = models.text diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties index 41c5ac8b65fb..e8069f300413 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties @@ -834,6 +834,8 @@ settings.providers.customModels=Model IDs (comma-separated) settings.providers.customModelsSelectAll=All settings.providers.customModelsUnselectAll=None settings.providers.customModelsEmpty=No models found at this Base URL. +settings.providers.customEnvMissing=Environment variable {0} is not set for the Kilo backend process. +settings.providers.customKeyStored=Leave blank to keep the saved API key. settings.providers.customIdRequired=Provider ID is required. settings.providers.customUrlRequired=Base URL is required. settings.providers.customUrlInvalid=Base URL must start with http:// or https://. diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/providers/ProvidersSettingsUiTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/providers/ProvidersSettingsUiTest.kt index aed6ce37bcac..157cdd820dc8 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/providers/ProvidersSettingsUiTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/providers/ProvidersSettingsUiTest.kt @@ -14,6 +14,7 @@ import ai.kilocode.client.ui.list.activeListCellAt import ai.kilocode.client.ui.list.activeListCellBounds import ai.kilocode.client.ui.list.activeListSectionTitle import ai.kilocode.client.ui.list.activeListVisibleCells +import ai.kilocode.rpc.dto.CustomModelFetchDto import ai.kilocode.rpc.dto.CustomModelFetchResultDto import ai.kilocode.rpc.dto.CustomProviderConfigDto import ai.kilocode.rpc.dto.ModelDto @@ -302,6 +303,202 @@ class ProvidersSettingsUiTest : BasePlatformTestCase() { } } + fun `test custom dialog shows stored key hint only when editing`() { + val cs = CoroutineScope(SupervisorJob()) + scope = cs + val addDialog = edt { + CustomProviderDialog(cs, "/tmp", { CustomModelFetchResultDto() }, { ProviderActionResultDto(ProviderSettingsDto()) }) + } + val editDialog = edt { + CustomProviderDialog( + cs, + "/tmp", + { CustomModelFetchResultDto() }, + { ProviderActionResultDto(ProviderSettingsDto()) }, + CustomProviderEdit("my-openai", "My OpenAI", "https://example.com/v1", null, listOf("gpt-4o")), + ) + } + + edt { + val hint = KiloBundle.message("settings.providers.customKeyStored") + assertTrue(components(center(addDialog)).filterIsInstance().none { it.text == hint }) + assertTrue(components(center(editDialog)).filterIsInstance().any { it.text == hint }) + dispose(addDialog) + dispose(editDialog) + } + } + + fun `test custom dialog select models sends directory provider id and env var name`() { + val cs = CoroutineScope(SupervisorJob()) + scope = cs + val captured = mutableListOf() + val dialog = edt { + val dialog = CustomProviderDialog( + cs, + "/tmp", + { input -> captured.add(input); CustomModelFetchResultDto(error = "boom") }, + { ProviderActionResultDto(providerState(provider("my-openai", "My OpenAI"))) }, + ) + val fields = components(center(dialog)).filterIsInstance() + fields[0].text = "my-openai" + fields[2].text = "https://example.com/v1" + fields[4].text = "API_KEY" + components(center(dialog)).filterIsInstance().first().doClick() + dialog + } + + flushUntil { captured.isNotEmpty() } + + edt { + assertEquals(1, captured.size) + assertEquals("/tmp", captured[0].directory) + assertEquals("my-openai", captured[0].providerId) + assertEquals("API_KEY", captured[0].env) + assertNull(captured[0].apiKey) + assertEquals(emptyMap(), captured[0].headers) + dispose(dialog) + } + } + + fun `test custom dialog select models sends typed api key`() { + val cs = CoroutineScope(SupervisorJob()) + scope = cs + val captured = mutableListOf() + val dialog = edt { + val dialog = CustomProviderDialog( + cs, + "/tmp", + { input -> captured.add(input); CustomModelFetchResultDto(error = "boom") }, + { ProviderActionResultDto(providerState(provider("my-openai", "My OpenAI"))) }, + ) + val fields = components(center(dialog)).filterIsInstance() + fields[0].text = "my-openai" + fields[2].text = "https://example.com/v1" + fields[3].text = "sk-test" + components(center(dialog)).filterIsInstance().first().doClick() + dialog + } + + flushUntil { captured.isNotEmpty() } + + edt { + assertEquals("sk-test", captured[0].apiKey) + assertNull(captured[0].env) + dispose(dialog) + } + } + + fun `test custom dialog select models forwards saved headers when editing`() { + val cs = CoroutineScope(SupervisorJob()) + scope = cs + val captured = mutableListOf() + val dialog = edt { + val dialog = CustomProviderDialog( + cs, + "/tmp", + { input -> captured.add(input); CustomModelFetchResultDto(error = "boom") }, + { ProviderActionResultDto(providerState(provider("my-openai", "My OpenAI"))) }, + CustomProviderEdit( + "my-openai", + "My OpenAI", + "https://example.com/v1", + "API_KEY", + listOf("gpt-4o"), + headers = mapOf("X-Custom" to "abc-123"), + ), + ) + components(center(dialog)).filterIsInstance().first().doClick() + dialog + } + + flushUntil { captured.isNotEmpty() } + + edt { + assertEquals(mapOf("X-Custom" to "abc-123"), captured[0].headers) + dispose(dialog) + } + } + + fun `test custom dialog select models appends env hint on unresolved env var error`() { + val cs = CoroutineScope(SupervisorJob()) + scope = cs + val dialog = edt { + val dialog = CustomProviderDialog( + cs, + "/tmp", + { CustomModelFetchResultDto(error = "HTTP 401: unauthorized", envMissing = true) }, + { ProviderActionResultDto(providerState(provider("my-openai", "My OpenAI"))) }, + ) + val fields = components(center(dialog)).filterIsInstance() + fields[0].text = "my-openai" + fields[2].text = "https://example.com/v1" + fields[4].text = "API_KEY" + components(center(dialog)).filterIsInstance().first().doClick() + dialog + } + + flushUntil { edt { validation(dialog) != null } } + + edt { + val expected = "HTTP 401: unauthorized ${KiloBundle.message("settings.providers.customEnvMissing", "API_KEY")}" + assertEquals(expected, validation(dialog)) + dispose(dialog) + } + } + + fun `test custom dialog select models appends env hint when no models found`() { + val cs = CoroutineScope(SupervisorJob()) + scope = cs + val dialog = edt { + val dialog = CustomProviderDialog( + cs, + "/tmp", + { CustomModelFetchResultDto(models = emptyList(), envMissing = true) }, + { ProviderActionResultDto(providerState(provider("my-openai", "My OpenAI"))) }, + ) + val fields = components(center(dialog)).filterIsInstance() + fields[0].text = "my-openai" + fields[2].text = "https://example.com/v1" + fields[4].text = "API_KEY" + components(center(dialog)).filterIsInstance().first().doClick() + dialog + } + + flushUntil { edt { validation(dialog) != null } } + + edt { + val expected = "${KiloBundle.message("settings.providers.customModelsEmpty")} " + + KiloBundle.message("settings.providers.customEnvMissing", "API_KEY") + assertEquals(expected, validation(dialog)) + dispose(dialog) + } + } + + fun `test custom dialog select models does not append hint when env is not missing`() { + val cs = CoroutineScope(SupervisorJob()) + scope = cs + val dialog = edt { + val dialog = CustomProviderDialog( + cs, + "/tmp", + { CustomModelFetchResultDto(error = "boom") }, + { ProviderActionResultDto(providerState(provider("my-openai", "My OpenAI"))) }, + ) + val fields = components(center(dialog)).filterIsInstance() + fields[0].text = "my-openai" + fields[2].text = "https://example.com/v1" + components(center(dialog)).filterIsInstance().first().doClick() + dialog + } + + flushUntil { edt { validation(dialog) != null } } + + edt { + assertEquals("boom", validation(dialog)) + dispose(dialog) + } + } + fun `test catalog provider without auth methods is connectable`() { val content = content() diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeProviderRpcApi.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeProviderRpcApi.kt index 0b0d0ba66c37..508a6ef7b81f 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeProviderRpcApi.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeProviderRpcApi.kt @@ -26,8 +26,10 @@ class FakeProviderRpcApi : KiloProviderRpcApi { val callbacks = mutableListOf() val authorizesReady = ArrayDeque>() val callbacksReady = ArrayDeque>() + val fetches = mutableListOf() var ready = ProviderOAuthReadyDto() var disconnectError: Exception? = null + var fetchResult = CustomModelFetchResultDto() override suspend fun state(directory: String): ProviderSettingsDto { assertNotEdt("provider.state") @@ -77,6 +79,7 @@ class FakeProviderRpcApi : KiloProviderRpcApi { override suspend fun fetchCustomModels(input: CustomModelFetchDto): CustomModelFetchResultDto { assertNotEdt("provider.fetchCustomModels") - return CustomModelFetchResultDto() + fetches.add(input) + return fetchResult } } diff --git a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/ProviderSettingsDto.kt b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/ProviderSettingsDto.kt index e45eb8d4f7d4..44a37c279ccd 100644 --- a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/ProviderSettingsDto.kt +++ b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/ProviderSettingsDto.kt @@ -133,7 +133,10 @@ data class CustomModelDto( @Serializable data class CustomModelFetchDto( val baseUrl: String, + val directory: String, + val providerId: String? = null, val apiKey: String? = null, + val env: String? = null, val headers: Map = emptyMap(), ) @@ -141,6 +144,7 @@ data class CustomModelFetchDto( data class CustomModelFetchResultDto( val models: List = emptyList(), val error: String? = null, + val envMissing: Boolean = false, ) @Serializable From a4956d3f7010bb1d9286fe1a8cdc3816f164882b Mon Sep 17 00:00:00 2001 From: kirillk Date: Sun, 30 Aug 2026 14:35:22 -0400 Subject: [PATCH 2/5] fix(jetbrains): clear provider env var without violating config schema ConfigProviderV1.Info.env is Schema.optional(Array), not NullOr, so a "env": null patch field is rejected by the real CLI's schema-validated PATCH /global/config payload (unlike the whole provider entry, which is Schema.NullOr and does support null for deletion). The previous commit's fix for defect D sent that unsupported field-level null unconditionally, which would 400 every custom-provider save that has no env var configured -- the common case. MockCliServer's merge simulation doesn't enforce the schema, so the added test passed locally without catching this; the automated PR review caught it. Clear the env var by deleting the provider entry first (schema-supported, and a no-op when nothing exists yet) and recreating it right after without an "env" key, instead of trying to null the field directly. --- .../kilocode/backend/cli/KiloCliDataParser.kt | 2 +- .../KiloBackendProviderSettingsManager.kt | 5 +++++ .../KiloBackendProviderSettingsManagerTest.kt | 17 +++++++++++++++-- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/cli/KiloCliDataParser.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/cli/KiloCliDataParser.kt index eb250dfd8467..1e401e45b5cd 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/cli/KiloCliDataParser.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/cli/KiloCliDataParser.kt @@ -1087,7 +1087,7 @@ object KiloCliDataParser { put("name", input.name.trim().ifBlank { id }) put("npm", "@ai-sdk/openai-compatible") put("options", buildJsonObject { put("baseURL", input.baseUrl.trim()) }) - if (env != null) put("env", buildJsonArray { add(JsonPrimitive(env)) }) else put("env", JsonNull) + if (env != null) put("env", buildJsonArray { add(JsonPrimitive(env)) }) if (input.headers.isNotEmpty()) put("headers", buildJsonObject { input.headers.forEach { (k, v) -> put(k, v) } }) if (models.isNotEmpty()) put("models", JsonObject(models)) } diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt index 0db3d3012bb4..a1599c6ecab3 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt @@ -150,6 +150,11 @@ internal class KiloBackendProviderSettingsManager( suspend fun saveCustom(input: CustomProviderSaveDto): ProviderActionResultDto { val err = validate(input) if (err != null) return ProviderActionResultDto(state(input.directory), error = err) + // The config schema only allows nulling a whole provider entry (to delete it), not an + // individual field inside one, so a blank env var must be cleared by deleting the entry + // before the patch below recreates it without that key. Deleting an entry that has no + // existing "env" (or doesn't exist yet) is a no-op, so this is safe to always do. + if (input.envVar.isNullOrBlank()) patch(KiloCliDataParser.buildCustomProviderDeletePatch(input.id)) patch(KiloCliDataParser.buildCustomProviderPatch(input)) if (input.envVar.isNullOrBlank()) { val key = input.apiKey?.takeIf { it.isNotBlank() } diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt index 39b6d21a8701..789f7e0afda1 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt @@ -269,7 +269,16 @@ class KiloBackendProviderSettingsManagerTest { } @Test - fun `saving custom provider with blank env var clears env in config patch`() = runBlocking { + fun `saving custom provider with blank env var clears existing env from config`() = runBlocking { + // The config schema only allows nulling a whole provider entry, not a single field inside + // one, so clearing "env" requires deleting and recreating the entry. This exercises that + // two-step flow through MockCliServer's own JSON-merge-patch simulation of the real config + // endpoint, rather than asserting on a single "env":null patch body the real CLI would 400 on. + mock.config = """{ + "provider":{ + "my-openai":{"name":"My OpenAI","npm":"@ai-sdk/openai-compatible","options":{"baseURL":"http://localhost:11434"},"env":["OLD_VAR"]} + } + }""".trimIndent() mock.providers = """{ "all":[{"id":"my-openai","name":"My OpenAI","source":"config","models":{"gpt-4o":{"id":"gpt-4o","name":"gpt-4o"}}}], "default":{}, @@ -292,7 +301,11 @@ class KiloBackendProviderSettingsManagerTest { ) assertNull(result.error) - assertContains(mock.lastConfigPatchBody.orEmpty(), "\"env\":null") + assertContains(mock.lastConfigPatchBody.orEmpty(), "\"my-openai\"") + assertFalse(mock.lastConfigPatchBody.orEmpty().contains("\"env\"")) + assertContains(mock.lastAuthPutBody.orEmpty(), "\"key\":\"sk-test\"") + val state = manager.state("/test") + assertEquals(emptyList(), state.config["my-openai"]?.env.orEmpty()) } @Test From bc07f1e665160504f03388eb27a03e2a34bba1a6 Mon Sep 17 00:00:00 2001 From: kirillk Date: Sun, 30 Aug 2026 14:48:58 -0400 Subject: [PATCH 3/5] fix(jetbrains): only delete-recreate provider entry when clearing env The unconditional delete-then-recreate on every save (added in the previous commit) wiped the whole provider entry on every save that has no env var, which is the common case. That drops any field the recreate patch doesn't set -- e.g. a hand-authored whitelist/blacklist -- and leaves the entry missing if the recreate patch fails partway through. Only take the delete-first path when the provider actually has an existing env var to clear, narrowing both risks to that specific, deliberate action instead of every ordinary save. --- .../KiloBackendProviderSettingsManager.kt | 11 ++++-- .../KiloBackendProviderSettingsManagerTest.kt | 39 +++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt index a1599c6ecab3..6a16e7534714 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt @@ -151,10 +151,13 @@ internal class KiloBackendProviderSettingsManager( val err = validate(input) if (err != null) return ProviderActionResultDto(state(input.directory), error = err) // The config schema only allows nulling a whole provider entry (to delete it), not an - // individual field inside one, so a blank env var must be cleared by deleting the entry - // before the patch below recreates it without that key. Deleting an entry that has no - // existing "env" (or doesn't exist yet) is a no-op, so this is safe to always do. - if (input.envVar.isNullOrBlank()) patch(KiloCliDataParser.buildCustomProviderDeletePatch(input.id)) + // individual field inside one, so a previously-set env var can only be cleared by deleting + // the entry before the patch below recreates it. Only do this when there is an existing env + // var to clear: deleting drops any fields the recreate patch doesn't set (e.g. a + // hand-authored whitelist/blacklist), and a failure between the two patches would otherwise + // leave the entry missing until the next successful save. + val hadEnv = input.envVar.isNullOrBlank() && state(input.directory).config[input.id]?.env?.isNotEmpty() == true + if (hadEnv) patch(KiloCliDataParser.buildCustomProviderDeletePatch(input.id)) patch(KiloCliDataParser.buildCustomProviderPatch(input)) if (input.envVar.isNullOrBlank()) { val key = input.apiKey?.takeIf { it.isNotBlank() } diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt index 789f7e0afda1..05a9c9530e73 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt @@ -308,6 +308,45 @@ class KiloBackendProviderSettingsManagerTest { assertEquals(emptyList(), state.config["my-openai"]?.env.orEmpty()) } + @Test + fun `saving custom provider without an existing env var does not delete the entry first`() = runBlocking { + // Deleting first is only needed to clear a previously-set env var. Doing it unconditionally + // would risk wiping fields the save patch doesn't set (e.g. a hand-authored + // whitelist/blacklist) on every ordinary save, and would leave the provider entry missing + // if the recreate patch failed, so this must stay a no-op when there is nothing to clear. + mock.config = """{ + "provider":{ + "my-openai":{"name":"My OpenAI","npm":"@ai-sdk/openai-compatible","options":{"baseURL":"http://localhost:11434"}} + } + }""".trimIndent() + mock.providers = """{ + "all":[{"id":"my-openai","name":"My OpenAI","source":"config","models":{"gpt-4o":{"id":"gpt-4o","name":"gpt-4o"}}}], + "default":{}, + "connected":[], + "failed":[] + }""".trimIndent() + val manager = manager() + + mock.resetCounts() + val result = manager.saveCustom( + CustomProviderSaveDto( + "/test", + "my-openai", + "My OpenAI", + "https://api.example.com/v1", + apiKey = "sk-test", + envVar = null, + models = listOf(CustomModelDto("gpt-4o", "gpt-4o")), + ), + ) + + assertNull(result.error) + assertContains(mock.lastAuthPutBody.orEmpty(), "\"key\":\"sk-test\"") + // Exactly one GET (the pre-check) + one PATCH (the recreate) + one GET (the trailing + // reload) hit /global/config; a fourth request would mean a delete patch also fired. + assertEquals(3, mock.requestCount("/global/config")) + } + @Test fun `disconnecting env backed openai compatible custom provider deletes config and auth`() = runBlocking { mock.config = """{ From df4ac54d6f0ba02d670e5c710875d5a9dbac63c3 Mon Sep 17 00:00:00 2001 From: kirillk Date: Sun, 30 Aug 2026 15:10:47 -0400 Subject: [PATCH 4/5] i18n(jetbrains): translate new provider settings keys Add translations for settings.providers.customEnvMissing and settings.providers.customKeyStored (introduced in this PR) across all 18 existing locale bundles. These files had fallen out of sync with the newer provider-settings section of the base bundle, so this only adds the two keys this PR introduces rather than backfilling the whole section. --- .../src/main/resources/messages/KiloBundle_ar.properties | 2 ++ .../src/main/resources/messages/KiloBundle_bs.properties | 2 ++ .../src/main/resources/messages/KiloBundle_da.properties | 2 ++ .../src/main/resources/messages/KiloBundle_de.properties | 2 ++ .../src/main/resources/messages/KiloBundle_es.properties | 2 ++ .../src/main/resources/messages/KiloBundle_fr.properties | 2 ++ .../src/main/resources/messages/KiloBundle_ja.properties | 2 ++ .../src/main/resources/messages/KiloBundle_ko.properties | 2 ++ .../src/main/resources/messages/KiloBundle_nl.properties | 2 ++ .../src/main/resources/messages/KiloBundle_no.properties | 2 ++ .../src/main/resources/messages/KiloBundle_pl.properties | 2 ++ .../src/main/resources/messages/KiloBundle_pt_BR.properties | 2 ++ .../src/main/resources/messages/KiloBundle_ru.properties | 2 ++ .../src/main/resources/messages/KiloBundle_th.properties | 2 ++ .../src/main/resources/messages/KiloBundle_tr.properties | 2 ++ .../src/main/resources/messages/KiloBundle_uk.properties | 2 ++ .../src/main/resources/messages/KiloBundle_zh_CN.properties | 2 ++ .../src/main/resources/messages/KiloBundle_zh_TW.properties | 2 ++ 18 files changed, 36 insertions(+) diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ar.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ar.properties index 2e3d77562adb..79182397f64e 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ar.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ar.properties @@ -509,3 +509,5 @@ worktree.menu.configure=تكوين Worktree جديد... session.part.tool.openSubagent=فتح الوكيل الفرعي في المحرر session.subagent.title=جلسة الوكيل الفرعي session.subagent.path=Kilo / الوكلاء الفرعيون / {0} +settings.providers.customEnvMissing=متغير البيئة {0} غير معيَّن لعملية الخلفية في Kilo. +settings.providers.customKeyStored=اتركه فارغًا للاحتفاظ بمفتاح API المحفوظ. diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_bs.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_bs.properties index e9940e90b36b..b5790ae731c7 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_bs.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_bs.properties @@ -509,3 +509,5 @@ worktree.menu.configure=Konfiguriši novi worktree... session.part.tool.openSubagent=Otvori pod-agenta u uređivaču session.subagent.title=Sesija pod-agenta session.subagent.path=Kilo / Pod-agenti / {0} +settings.providers.customEnvMissing=Varijabla okruženja {0} nije postavljena za backend proces Kilo. +settings.providers.customKeyStored=Ostavite prazno da sačuvate spremljeni API ključ. diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_da.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_da.properties index ef51518f8186..68929733467d 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_da.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_da.properties @@ -509,3 +509,5 @@ worktree.menu.configure=Konfigurer nyt worktree... session.part.tool.openSubagent=Åbn underagent i editor session.subagent.title=Underagent-session session.subagent.path=Kilo / Underagenter / {0} +settings.providers.customEnvMissing=Miljøvariablen {0} er ikke angivet for Kilo-backendprocessen. +settings.providers.customKeyStored=Lad stå tomt for at bevare den gemte API-nøgle. diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_de.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_de.properties index c3b3aba3a0f9..bc085c9e56e1 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_de.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_de.properties @@ -509,3 +509,5 @@ worktree.menu.configure=Neuen Worktree konfigurieren... session.part.tool.openSubagent=Unter-Agent im Editor öffnen session.subagent.title=Unter-Agent-Sitzung session.subagent.path=Kilo / Unter-Agenten / {0} +settings.providers.customEnvMissing=Die Umgebungsvariable {0} ist für den Kilo-Backend-Prozess nicht gesetzt. +settings.providers.customKeyStored=Leer lassen, um den gespeicherten API-Schlüssel zu behalten. diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_es.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_es.properties index e9b9fc43d7d6..c1ab2bf2344f 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_es.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_es.properties @@ -509,3 +509,5 @@ worktree.menu.configure=Configurar nuevo worktree... session.part.tool.openSubagent=Abrir subagente en el editor session.subagent.title=Sesión de subagente session.subagent.path=Kilo / Subagentes / {0} +settings.providers.customEnvMissing=La variable de entorno {0} no está configurada para el proceso backend de Kilo. +settings.providers.customKeyStored=Déjelo en blanco para conservar la clave de API guardada. diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_fr.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_fr.properties index e2563922f50d..789d7cf55352 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_fr.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_fr.properties @@ -509,3 +509,5 @@ worktree.menu.configure=Configurer un nouveau worktree... session.part.tool.openSubagent=Ouvrir le sous-agent dans l'éditeur session.subagent.title=Session du sous-agent session.subagent.path=Kilo / Sous-agents / {0} +settings.providers.customEnvMissing=La variable d'environnement {0} n'est pas définie pour le processus backend de Kilo. +settings.providers.customKeyStored=Laissez vide pour conserver la clé API enregistrée. diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ja.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ja.properties index 2581eb65953f..2f994d84e048 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ja.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ja.properties @@ -509,3 +509,5 @@ worktree.menu.configure=新しいワークツリーを設定... session.part.tool.openSubagent=サブエージェントをエディタで開く session.subagent.title=サブエージェントセッション session.subagent.path=Kilo / サブエージェント / {0} +settings.providers.customEnvMissing=環境変数 {0} が Kilo バックエンドプロセスに設定されていません。 +settings.providers.customKeyStored=空欄のままにすると、保存済みの API キーが保持されます。 diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ko.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ko.properties index 34a4381cd97d..cf46454e7695 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ko.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ko.properties @@ -509,3 +509,5 @@ worktree.menu.configure=새 워크트리 구성... session.part.tool.openSubagent=하위 에이전트를 편집기에서 열기 session.subagent.title=하위 에이전트 세션 session.subagent.path=Kilo / 하위 에이전트 / {0} +settings.providers.customEnvMissing=Kilo 백엔드 프로세스에 환경 변수 {0}이(가) 설정되어 있지 않습니다. +settings.providers.customKeyStored=저장된 API 키를 유지하려면 비워 두세요. diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_nl.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_nl.properties index 14897927377c..ba8fe355dc62 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_nl.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_nl.properties @@ -509,3 +509,5 @@ worktree.menu.configure=Nieuwe worktree configureren... session.part.tool.openSubagent=Subagent openen in editor session.subagent.title=Subagent-sessie session.subagent.path=Kilo / Subagents / {0} +settings.providers.customEnvMissing=Omgevingsvariabele {0} is niet ingesteld voor het Kilo-backendproces. +settings.providers.customKeyStored=Laat leeg om de opgeslagen API-sleutel te behouden. diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_no.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_no.properties index 81db0a5fc939..94c9e2bc1180 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_no.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_no.properties @@ -509,3 +509,5 @@ worktree.menu.configure=Konfigurer nytt worktree... session.part.tool.openSubagent=Åpne underagent i editor session.subagent.title=Underagent-økt session.subagent.path=Kilo / Underagenter / {0} +settings.providers.customEnvMissing=Miljøvariabelen {0} er ikke satt for Kilo-backendprosessen. +settings.providers.customKeyStored=La stå tomt for å beholde den lagrede API-nøkkelen. diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_pl.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_pl.properties index 3cc0b8fa6d9c..db6c2efc597f 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_pl.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_pl.properties @@ -509,3 +509,5 @@ worktree.menu.configure=Skonfiguruj nowy worktree... session.part.tool.openSubagent=Otwórz podagenta w edytorze session.subagent.title=Sesja podagenta session.subagent.path=Kilo / Podagenci / {0} +settings.providers.customEnvMissing=Zmienna środowiskowa {0} nie jest ustawiona dla procesu backendu Kilo. +settings.providers.customKeyStored=Pozostaw puste, aby zachować zapisany klucz API. diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_pt_BR.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_pt_BR.properties index b2483f331119..ab3fb3309d92 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_pt_BR.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_pt_BR.properties @@ -509,3 +509,5 @@ worktree.menu.configure=Configurar novo worktree... session.part.tool.openSubagent=Abrir subagente no editor session.subagent.title=Sessão do subagente session.subagent.path=Kilo / Subagentes / {0} +settings.providers.customEnvMissing=A variável de ambiente {0} não está definida para o processo de backend do Kilo. +settings.providers.customKeyStored=Deixe em branco para manter a chave de API salva. diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ru.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ru.properties index 70be07d5ec12..20746d92cb5d 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ru.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_ru.properties @@ -509,3 +509,5 @@ worktree.menu.configure=Настроить новое рабочее дерев session.part.tool.openSubagent=Открыть субагента в редакторе session.subagent.title=Сессия субагента session.subagent.path=Kilo / Субагенты / {0} +settings.providers.customEnvMissing=Переменная среды {0} не задана для фонового процесса Kilo. +settings.providers.customKeyStored=Оставьте поле пустым, чтобы сохранить сохранённый ключ API. diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_th.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_th.properties index 8e69b8e58b49..b7d6ac5ad2fc 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_th.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_th.properties @@ -509,3 +509,5 @@ worktree.menu.configure=กำหนดค่า worktree ใหม่... session.part.tool.openSubagent=เปิดซับเอเจนต์ในตัวแก้ไข session.subagent.title=เซสชันซับเอเจนต์ session.subagent.path=Kilo / ซับเอเจนต์ / {0} +settings.providers.customEnvMissing=ไม่ได้ตั้งค่าตัวแปรสภาพแวดล้อม {0} สำหรับโปรเซสแบ็กเอนด์ของ Kilo +settings.providers.customKeyStored=เว้นว่างไว้เพื่อเก็บคีย์ API ที่บันทึกไว้ diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_tr.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_tr.properties index 83bb12f626c2..419ce5bb03fc 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_tr.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_tr.properties @@ -509,3 +509,5 @@ worktree.menu.configure=Yeni worktree yapılandır... session.part.tool.openSubagent=Alt aracıyı düzenleyicide aç session.subagent.title=Alt aracı oturumu session.subagent.path=Kilo / Alt aracılar / {0} +settings.providers.customEnvMissing={0} ortam değişkeni Kilo arka uç işlemi için ayarlanmamış. +settings.providers.customKeyStored=Kaydedilen API anahtarını korumak için boş bırakın. diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_uk.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_uk.properties index 22a55616bb33..fed70f8484f3 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_uk.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_uk.properties @@ -509,3 +509,5 @@ worktree.menu.configure=Налаштувати нове робоче дерев session.part.tool.openSubagent=Відкрити субагента в редакторі session.subagent.title=Сесія субагента session.subagent.path=Kilo / Субагенти / {0} +settings.providers.customEnvMissing=Змінна середовища {0} не встановлена для фонового процесу Kilo. +settings.providers.customKeyStored=Залишіть поле порожнім, щоб зберегти збережений ключ API. diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_zh_CN.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_zh_CN.properties index de299037c5c7..d80db22bf45e 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_zh_CN.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_zh_CN.properties @@ -509,3 +509,5 @@ worktree.menu.configure=配置新工作树... session.part.tool.openSubagent=在编辑器中打开子代理 session.subagent.title=子代理会话 session.subagent.path=Kilo / 子代理 / {0} +settings.providers.customEnvMissing=Kilo 后端进程未设置环境变量 {0}。 +settings.providers.customKeyStored=留空以保留已保存的 API 密钥。 diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_zh_TW.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_zh_TW.properties index 0205ff09f9cc..d3b9c171cbc1 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_zh_TW.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle_zh_TW.properties @@ -509,3 +509,5 @@ worktree.menu.configure=設定新工作樹... session.part.tool.openSubagent=在編輯器中開啟子代理 session.subagent.title=子代理工作階段 session.subagent.path=Kilo / 子代理 / {0} +settings.providers.customEnvMissing=Kilo 後端處理程序未設定環境變數 {0}。 +settings.providers.customKeyStored=留空以保留已儲存的 API 金鑰。 From 077a481b92b758ecd146ec248fa57cff294afe08 Mon Sep 17 00:00:00 2001 From: kirillk Date: Mon, 31 Aug 2026 11:01:58 -0400 Subject: [PATCH 5/5] fix(jetbrains): preserve custom provider headers when clearing env var Clearing a provider's env var deletes and recreates the whole config entry, because the CLI config schema only accepts null for an entire provider value. The recreate patch is built from the save DTO, and the provider dialog has no headers field, so any headers hand-authored in kilo.json were silently dropped by an unrelated env var change. Carry the existing headers into the recreate patch when the save itself sets none. --- .../KiloBackendProviderSettingsManager.kt | 10 +++-- .../KiloBackendProviderSettingsManagerTest.kt | 37 +++++++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt index 6a16e7534714..0172e2985d43 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManager.kt @@ -156,9 +156,13 @@ internal class KiloBackendProviderSettingsManager( // var to clear: deleting drops any fields the recreate patch doesn't set (e.g. a // hand-authored whitelist/blacklist), and a failure between the two patches would otherwise // leave the entry missing until the next successful save. - val hadEnv = input.envVar.isNullOrBlank() && state(input.directory).config[input.id]?.env?.isNotEmpty() == true - if (hadEnv) patch(KiloCliDataParser.buildCustomProviderDeletePatch(input.id)) - patch(KiloCliDataParser.buildCustomProviderPatch(input)) + val cfg = if (input.envVar.isNullOrBlank()) state(input.directory).config[input.id] else null + val stale = cfg?.takeIf { it.env.isNotEmpty() } + if (stale != null) patch(KiloCliDataParser.buildCustomProviderDeletePatch(input.id)) + // The dialog never edits headers, so the delete above would otherwise drop hand-authored + // ones: carry them into the recreate patch when the save itself doesn't set any. + val save = if (stale != null && input.headers.isEmpty()) input.copy(headers = stale.headers) else input + patch(KiloCliDataParser.buildCustomProviderPatch(save)) if (input.envVar.isNullOrBlank()) { val key = input.apiKey?.takeIf { it.isNotBlank() } if (key != null) put("/auth/${enc(input.id)}", KiloCliDataParser.buildProviderAuthJson(key, emptyMap())) diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt index 05a9c9530e73..14204c9ca139 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/provider/KiloBackendProviderSettingsManagerTest.kt @@ -308,6 +308,43 @@ class KiloBackendProviderSettingsManagerTest { assertEquals(emptyList(), state.config["my-openai"]?.env.orEmpty()) } + @Test + fun `clearing an env var keeps hand-authored headers on the provider entry`() = runBlocking { + // Deleting the entry to clear "env" also drops every other key on it. The dialog has no + // headers field, so headers only ever come from a hand-edited kilo.json and must survive + // the recreate patch instead of being silently wiped by an unrelated env var change. + mock.config = """{ + "provider":{ + "my-openai":{"name":"My OpenAI","npm":"@ai-sdk/openai-compatible","options":{"baseURL":"http://localhost:11434"},"env":["OLD_VAR"],"headers":{"X-Custom":"abc-123"}} + } + }""".trimIndent() + mock.providers = """{ + "all":[{"id":"my-openai","name":"My OpenAI","source":"config","models":{"gpt-4o":{"id":"gpt-4o","name":"gpt-4o"}}}], + "default":{}, + "connected":[], + "failed":[] + }""".trimIndent() + val manager = manager() + + mock.resetCounts() + val result = manager.saveCustom( + CustomProviderSaveDto( + "/test", + "my-openai", + "My OpenAI", + "https://api.example.com/v1", + apiKey = "sk-test", + envVar = null, + models = listOf(CustomModelDto("gpt-4o", "gpt-4o")), + ), + ) + + assertNull(result.error) + val state = manager.state("/test") + assertEquals(emptyList(), state.config["my-openai"]?.env.orEmpty()) + assertEquals(mapOf("X-Custom" to "abc-123"), state.config["my-openai"]?.headers) + } + @Test fun `saving custom provider without an existing env var does not delete the entry first`() = runBlocking { // Deleting first is only needed to clear a previously-set env var. Doing it unconditionally