Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/jetbrains-auto-editor-context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@kilocode/kilo-jetbrains": minor
---

Include the active editor file, open files, visible files, and selected text in JetBrains chat context by default, with a Context settings toggle to disable it. Files matched by `.kilocodeignore` (or `.gitignore` plus `.env` files) are excluded, and the default shell is reported to the agent.
2 changes: 1 addition & 1 deletion packages/kilo-jetbrains/.run/Run IDE (Backend).run.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/packages/kilo-jetbrains" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="--no-configuration-cache --purge-old-log-directories -Pkilo.dev.log.level=debug -Pkilo.splitModeServerPort=0 -Pkilo.dev.storage.isolated=true" />
<option name="scriptParameters" value="--no-configuration-cache --purge-old-log-directories -Pkilo.dev.log.level=debug -Pkilo.dev.log.chat.content=off -Pkilo.dev.log.chat.preview.max=160 -Pkilo.splitModeServerPort=0 -Pkilo.dev.storage.isolated=true" />
<option name="taskDescriptions">
<list />
</option>
Expand Down
2 changes: 1 addition & 1 deletion packages/kilo-jetbrains/.run/Run IDE (Frontend).run.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/packages/kilo-jetbrains" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="--no-configuration-cache --purge-old-log-directories -Pkilo.dev.log.level=debug -Pkilo.splitModeServerPort=0 -Pkilo.dev.storage.isolated=true" />
<option name="scriptParameters" value="--no-configuration-cache --purge-old-log-directories -Pkilo.dev.log.level=debug -Pkilo.dev.log.chat.content=off -Pkilo.dev.log.chat.preview.max=160 -Pkilo.splitModeServerPort=0 -Pkilo.dev.storage.isolated=true" />
<option name="taskDescriptions">
<list />
</option>
Expand Down
2 changes: 1 addition & 1 deletion packages/kilo-jetbrains/.run/runIdeSplitMode.run.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/packages/kilo-jetbrains" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="--no-configuration-cache --purge-old-log-directories -Pkilo.dev.log.level=debug -Pkilo.splitModeServerPort=0 -Pkilo.dev.storage.isolated=true" />
<option name="scriptParameters" value="--no-configuration-cache --purge-old-log-directories -Pkilo.dev.log.level=debug -Pkilo.dev.log.chat.content=off -Pkilo.dev.log.chat.preview.max=160 -Pkilo.splitModeServerPort=0 -Pkilo.dev.storage.isolated=true" />
<option name="taskDescriptions">
<list />
</option>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import ai.kilocode.rpc.dto.CustomModelDto
import ai.kilocode.rpc.dto.CustomProviderConfigDto
import ai.kilocode.rpc.dto.CustomProviderSaveDto
import ai.kilocode.rpc.dto.DiffFileDto
import ai.kilocode.rpc.dto.EditorContextDto
import ai.kilocode.rpc.dto.MessageDto
import ai.kilocode.rpc.dto.MessageErrorDto
import ai.kilocode.rpc.dto.MessageSummaryDto
Expand Down Expand Up @@ -822,10 +823,27 @@ object KiloCliDataParser {
if (variant != null) {
sb.append(""","variant":${escape(variant)}""")
}
val editor = prompt.editorContext
if (editor != null) {
sb.append(""","editorContext":${editorContextJson(editor)}""")
}
sb.append("}")
return sb.toString()
}

private fun editorContextJson(ctx: EditorContextDto): String {
val fields = mutableListOf<String>()
ctx.directory?.let { fields += "\"directory\":${escape(it)}" }
ctx.worktree?.let { fields += "\"worktree\":${escape(it)}" }
ctx.visibleFiles?.takeIf { it.isNotEmpty() }?.let { fields += "\"visibleFiles\":${array(it)}" }
ctx.openTabs?.takeIf { it.isNotEmpty() }?.let { fields += "\"openTabs\":${array(it)}" }
ctx.activeFile?.let { fields += "\"activeFile\":${escape(it)}" }
ctx.shell?.let { fields += "\"shell\":${escape(it)}" }
return "{${fields.joinToString(",")}}"
}

private fun array(values: List<String>): String = values.joinToString(",", "[", "]") { escape(it) }

private fun buildPromptPartJson(part: PromptPartDto): String {
val fields = mutableListOf("\"type\":${escape(part.type)}")
if (part.type == "file") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ai.kilocode.backend.cli

import ai.kilocode.log.ChatLogSummary
import ai.kilocode.rpc.dto.ChatEventDto
import ai.kilocode.rpc.dto.EditorContextDto
import ai.kilocode.rpc.dto.MessageDto
import ai.kilocode.rpc.dto.MessageErrorDto
import ai.kilocode.rpc.dto.MessageTimeDto
Expand Down Expand Up @@ -156,6 +157,27 @@ class ChatLogSummaryTest {
assertTrue(out.contains("variant=medium"), out)
}

@Test
fun `prompt dto summary includes editor context`() {
System.setProperty("kilo.dev.log.chat.content", "preview")

val out = ChatLogSummary.prompt(
PromptDto(
parts = listOf(PromptPartDto(type = "text", text = "hello")),
editorContext = EditorContextDto(
activeFile = "settings.gradle",
openTabs = listOf("settings.gradle", "src/App.kt"),
visibleFiles = listOf("settings.gradle"),
),
)
)

assertTrue(out.contains("editorContext=true"), out)
assertTrue(out.contains("activeFile=\"settings.gradle\""), out)
assertTrue(out.contains("openTabs=2"), out)
assertTrue(out.contains("visibleFiles=1"), out)
}

@Test
fun `prompt dto summary redacts file attachment urls`() {
System.setProperty("kilo.dev.log.chat.content", "preview")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import ai.kilocode.rpc.dto.CompactionPatchDto
import ai.kilocode.rpc.dto.ConfigDto
import ai.kilocode.rpc.dto.ConfigPatchDto
import ai.kilocode.rpc.dto.ConfigUpdateDto
import ai.kilocode.rpc.dto.EditorContextDto
import ai.kilocode.rpc.dto.McpConfigDto
import ai.kilocode.rpc.dto.PermissionAlwaysRulesDto
import ai.kilocode.rpc.dto.PermissionReplyDto
Expand Down Expand Up @@ -1958,6 +1959,25 @@ class KiloCliDataParserTest {
assertEquals("""{"parts":[{"type":"text","text":"Hi"}],"noReply":true}""", result)
}

@Test
fun `buildPromptJson - with editor context`() {
val prompt = PromptDto(
parts = listOf(PromptPartDto("text", "Hi")),
editorContext = EditorContextDto(
activeFile = "src/App.kt",
visibleFiles = listOf("src/App.kt"),
openTabs = listOf("src/App.kt", "src/Other.kt"),
),
)

val result = KiloCliDataParser.buildPromptJson(prompt)

assertEquals(
"""{"parts":[{"type":"text","text":"Hi"}],"editorContext":{"visibleFiles":["src/App.kt"],"openTabs":["src/App.kt","src/Other.kt"],"activeFile":"src/App.kt"}}""",
result,
)
}

@Test
fun `buildProviderOAuthJson - numeric method index`() {
val result = KiloCliDataParser.buildProviderOAuthJson("0", mapOf("deploymentType" to "github.com"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import com.intellij.ide.util.PropertiesComponent

object KiloPluginSettings {
private const val AUTO_APPROVE_KEY = "kilo.session.autoApprove"
private const val AUTO_EDITOR_CONTEXT_KEY = "kilo.session.autoEditorContext"
private const val PERMISSION_RULES_EXPANDED_KEY = "kilo.session.permissionRulesExpanded"

fun getAutoApprove(): Boolean = PropertiesComponent.getInstance().getBoolean(AUTO_APPROVE_KEY, false)
Expand All @@ -16,6 +17,16 @@ object KiloPluginSettings {
PropertiesComponent.getInstance().unsetValue(AUTO_APPROVE_KEY)
}

fun getAutoEditorContext(): Boolean = PropertiesComponent.getInstance().getBoolean(AUTO_EDITOR_CONTEXT_KEY, true)

fun setAutoEditorContext(value: Boolean) {
PropertiesComponent.getInstance().setValue(AUTO_EDITOR_CONTEXT_KEY, value.toString())
}

internal fun unsetAutoEditorContext() {
PropertiesComponent.getInstance().unsetValue(AUTO_EDITOR_CONTEXT_KEY)
}

fun getPermissionRulesExpanded(): Boolean = PropertiesComponent.getInstance().getBoolean(PERMISSION_RULES_EXPANDED_KEY, false)

fun setPermissionRulesExpanded(value: Boolean) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import ai.kilocode.client.session.ui.style.SessionEditorStyleTarget
import ai.kilocode.client.session.controller.EVENT_FLUSH_MS
import ai.kilocode.client.session.controller.SessionController
import ai.kilocode.client.session.controller.SessionControllerEvent
import ai.kilocode.client.session.context.EditorContextGatherer
import ai.kilocode.client.session.ui.style.SessionUiStyle
import ai.kilocode.client.session.views.LoginRequiredView
import ai.kilocode.client.session.views.permission.PermissionView
Expand Down Expand Up @@ -682,14 +683,16 @@ class SessionUi(

private fun sendPrompt(text: String, files: List<PromptPartDto>) {
if (text.isBlank() && files.isEmpty()) return
val editor = EditorContextGatherer.gather(project, workspace.directory)
Comment thread
kirillk marked this conversation as resolved.
Resolved
val allFiles = files + listOfNotNull(editor.selection)
val parts = buildList {
text.takeIf { it.isNotBlank() }?.let { add(PromptPartDto(type = "text", text = it)) }
addAll(files)
addAll(allFiles)
}
LOG.debug {
val agent = controller.model.agent ?: "none"
val model = controller.model.model ?: "none"
"${ChatLogSummary.prompt(PromptDto(parts = parts))} agent=$agent model=$model ready=${controller.ready}"
"${ChatLogSummary.prompt(PromptDto(parts = parts, editorContext = editor.context))} agent=$agent model=$model ready=${controller.ready}"
}
prompt.clear()
val follow = scroll.atBottom()
Expand All @@ -705,7 +708,7 @@ class SessionUi(
scroll.followBottom(follow)
return
}
controller.prompt(text, files)
controller.prompt(text, allFiles, editor.context)
scroll.followBottom(follow)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package ai.kilocode.client.session.context

import ai.kilocode.client.plugin.KiloPluginSettings
import ai.kilocode.client.vfs.KiloVirtualFileSystem
import ai.kilocode.log.KiloLog
import ai.kilocode.rpc.dto.EditorContextDto
import ai.kilocode.rpc.dto.PromptPartDto
import com.intellij.codeWithMe.ClientId
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.impl.EditorHistoryManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.EnvironmentUtil
import java.nio.file.Path
import kotlin.io.path.name

/**
* Reads the active/open editors and current selection at prompt-send time.
*
* Split mode caveat: the chat UI runs under a non-local [ClientId], so
* [FileEditorManager.getOpenFiles]/[FileEditorManager.getSelectedTextEditor] take
* the per-client branch and return nothing. The `*WithRemotes` variants read the
* local composites directly and are the ones that actually see the user's tabs.
* These APIs are `@ApiStatus.Experimental`.
*/
internal object EditorContextGatherer {
private val LOG = KiloLog.create(EditorContextGatherer::class.java)

// Resolved once per process; the login shell does not change during a session.
private val shell: String? by lazy {
if (SystemInfo.isWindows) EnvironmentUtil.getValue("COMSPEC") else EnvironmentUtil.getValue("SHELL")
}

data class Result(
val context: EditorContextDto?,
val selection: PromptPartDto?,
)

fun gather(project: Project, root: String): Result {
if (!KiloPluginSettings.getAutoEditorContext()) {
LOG.debug { "kind=editor-context enabled=false" }
return Result(null, null)
}
val manager = FileEditorManager.getInstance(project)
val base = Path.of(root).toAbsolutePath().normalize()
val openFiles = manager.openFilesWithRemotes
val editor = manager.selectedTextEditorWithRemotes.firstOrNull()
val activeFile = editor?.let { file(it) } ?: lastOpen(project, openFiles) ?: openFiles.firstOrNull()
val ignore = KiloIgnore.load(rootDir(listOfNotNull(activeFile) + openFiles, base))

fun keep(file: VirtualFile?): String? = rel(file, base)?.takeUnless { ignore.ignored(it) }

val active = keep(activeFile)
val openRel = openFiles.mapNotNull { rel(it, base) }.distinct()
val open = openRel.filterNot { ignore.ignored(it) }.take(20)
val visible = (listOfNotNull(activeFile) + manager.selectedTextEditorWithRemotes.mapNotNull { file(it) })
.mapNotNull { keep(it) }
.distinct()
.take(200)
val ctx = EditorContextDto(
activeFile = active,
openTabs = open.takeIf { it.isNotEmpty() },
visibleFiles = visible.takeIf { it.isNotEmpty() },
shell = shell,
).takeIf { active != null || open.isNotEmpty() || visible.isNotEmpty() || shell != null }
val part = editor?.let { selection(it, base, ignore) }
LOG.debug {
val first = openFiles.firstOrNull()
val filtered = openRel.count { ignore.ignored(it) }
"kind=editor-context enabled=true localId=${ClientId.isCurrentlyUnderLocalId}" +
" rawOpen=${openFiles.size} rawSel=${manager.selectedTextEditorWithRemotes.size}" +
" active=${active ?: "none"} open=${open.size} visible=${visible.size} selection=${part != null}" +
" ignored=$filtered shell=${shell ?: "none"}" +
" firstFs=${first?.fileSystem?.protocol ?: "none"} firstLocal=${first?.isInLocalFileSystem ?: false}" +
" firstPath=${first?.path ?: "none"}"
}
return Result(ctx, part)
}

private fun lastOpen(project: Project, open: List<VirtualFile>): VirtualFile? {
val set = open.toHashSet()
return EditorHistoryManager.getInstance(project).fileList.lastOrNull { it in set }
}

// Walks up from an open editor file to the workspace-root directory so ignore
// files can be read via the same (possibly remote) VFS as the editor files.
private fun rootDir(files: List<VirtualFile>, root: Path): VirtualFile? {
for (file in files) {
var cur: VirtualFile? = file
while (cur != null) {
if (runCatching { Path.of(cur.path).toAbsolutePath().normalize() }.getOrNull() == root) return cur
cur = cur.parent
}
}
return null
}

private fun selection(editor: Editor, root: Path, ignore: KiloIgnore): PromptPartDto? {
val model = editor.selectionModel
if (!model.hasSelection()) return null
val file = file(editor) ?: return null
val path = local(file, root) ?: return null
if (ignore.ignored(root.relativize(path).toString())) return null
val start = model.selectionStart
val end = model.selectionEnd
if (start == end) return null
val doc = editor.document
val last = (end - 1).coerceAtLeast(start)
val first = doc.getLineNumber(start) + 1
val line = doc.getLineNumber(last) + 1
val url = "${path.toUri()}?start=$first&end=$line"
return PromptPartDto(
type = "file",
mime = "text/plain",
url = url,
filename = path.name,
)
}

private fun file(editor: Editor): VirtualFile? = FileDocumentManager.getInstance().getFile(editor.document)

private fun rel(file: VirtualFile?, root: Path): String? {
val path = file?.let { local(it, root) } ?: return null
return root.relativize(path).toString()
}

private fun local(file: VirtualFile, root: Path): Path? {
if (file.fileSystem.protocol == KiloVirtualFileSystem.PROTOCOL) return null
val path = Path.of(file.path).toAbsolutePath().normalize()
Comment thread
kirillk marked this conversation as resolved.
Resolved
if (!path.startsWith(root)) return null
return path
}
}
Loading
Loading