Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,10 @@ public void addSelection(VirtualFile editorFile, SelectionModel selectionModel)
userInputPanel.addSelection(editorFile, selectionModel);
}

public void addContextTag(TagDetails tag) {
userInputPanel.addTag(tag);
}

public void addCommitReferences(List<GitCommitTagDetails> gitCommits) {
userInputPanel.addCommitReferences(gitCommits);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ class PsiStructureRepository(
is ImageTagDetails -> null
is CodeAnalyzeTagDetails -> null
is DiagnosticsTagDetails -> null
is SingleDiagnosticTagDetails -> null
}

virtualFile?.takeIf { it.isValid && it.exists() }
Expand Down Expand Up @@ -268,6 +269,7 @@ class PsiStructureRepository(
is ImageTagDetails -> false
is CodeAnalyzeTagDetails -> false
is DiagnosticsTagDetails -> false
is SingleDiagnosticTagDetails -> false
}
}
.toSet()
Expand Down Expand Up @@ -296,6 +298,7 @@ class PsiStructureRepository(
is ImageTagDetails -> null
is CodeAnalyzeTagDetails -> null
is DiagnosticsTagDetails -> null
is SingleDiagnosticTagDetails -> null
}

virtualFile?.takeIf { it.isValid && it.exists() }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
package ee.carlrobert.codegpt.actions

import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerEx
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.Navigatable
import ee.carlrobert.codegpt.toolwindow.chat.ChatToolWindowContentManager
import ee.carlrobert.codegpt.ui.OverlayUtil
import ee.carlrobert.codegpt.ui.textarea.header.tag.SingleDiagnosticTagDetails

class AddProblemToContextAction : AnAction() {

override fun update(e: AnActionEvent) {
e.presentation.isEnabled = e.project != null
}

override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT

override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val context = extractProblemContext(project, e) ?: run {
OverlayUtil.showNotification(
"No problem selected. Open the Problems tool window, select a row, then press the shortcut.",
NotificationType.INFORMATION
)
return
}

val tag = SingleDiagnosticTagDetails(
virtualFile = context.virtualFile,
line = context.line,
column = context.column,
severityName = context.severityName,
description = context.description
)

val contentManager = project.service<ChatToolWindowContentManager>()
contentManager.displayChatTab()
val chatTabPanel = contentManager.tryFindActiveChatTabPanel()
.orElseGet { contentManager.createNewTabPanel() }
chatTabPanel.addContextTag(tag)
}

private data class ProblemContext(
val virtualFile: VirtualFile,
val line: Int,
val column: Int,
val severityName: String,
val description: String,
)

private fun extractProblemContext(project: Project, e: AnActionEvent): ProblemContext? {
val problemContext = readFromProblemNavigatable(project, e)
if (problemContext != null) return problemContext

val descriptor = e.getData(CommonDataKeys.NAVIGATABLE) as? OpenFileDescriptor
if (descriptor != null) {
return readFromOpenFileDescriptor(project, descriptor)
}

val virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE) ?: return null
return readFirstHighlight(project, virtualFile, offsetHint = -1, lineHint = -1)
}

private fun readFromProblemNavigatable(project: Project, e: AnActionEvent): ProblemContext? {
val problemClass = try {
Class.forName("com.intellij.analysis.problemsView.Problem")
} catch (_: ClassNotFoundException) {
return null
}

val navigatable: Navigatable = e.getData(CommonDataKeys.NAVIGATABLE) ?: return null
if (!problemClass.isInstance(navigatable)) return null

val virtualFile = problemClass.invokeNullable<VirtualFile>(navigatable, "getFile") ?: return null
val rawLine = problemClass.invokeNullable<Int>(navigatable, "getLine") ?: -1
val rawColumn = problemClass.invokeNullable<Int>(navigatable, "getColumn") ?: -1
val rawOffset = problemClass.invokeNullable<Int>(navigatable, "getOffset") ?: -1
val description = problemClass.invokeNullable<String>(navigatable, "getDescription")
val text = problemClass.invokeNullable<String>(navigatable, "getText").orEmpty()

val displayDescription = StringUtil.removeHtmlTags(
(description?.takeIf { it.isNotBlank() } ?: text).trim(),
false
)

val line = if (rawLine >= 0) rawLine + 1 else -1
val column = if (rawColumn >= 0) rawColumn + 1 else -1

val severityName = resolveSeverityName(project, virtualFile, rawOffset, rawLine)

return ProblemContext(
virtualFile = virtualFile,
line = line,
column = column,
severityName = severityName,
description = displayDescription
)
}

private fun readFromOpenFileDescriptor(
project: Project,
descriptor: OpenFileDescriptor
): ProblemContext? {
return readFirstHighlight(
project,
descriptor.file,
offsetHint = descriptor.offset,
lineHint = descriptor.line
)
}

private fun readFirstHighlight(
project: Project,
virtualFile: VirtualFile,
offsetHint: Int,
lineHint: Int
): ProblemContext? {
val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: return null
val info = findBestHighlight(project, virtualFile, document, offsetHint, lineHint)
?: return null

val startOffset = info.startOffset.coerceIn(0, document.textLength)
val line = if (document.textLength > 0) document.getLineNumber(startOffset) + 1 else -1
val column = if (line > 0) {
startOffset - document.getLineStartOffset(line - 1) + 1
} else {
-1
}
val rawMessage = info.description ?: info.toolTip ?: ""
val description = StringUtil.removeHtmlTags(rawMessage, false).trim()

return ProblemContext(
virtualFile = virtualFile,
line = line,
column = column,
severityName = severityNameOf(info.severity),
description = description.ifBlank { "(no description)" }
)
}

private fun resolveSeverityName(
project: Project,
virtualFile: VirtualFile,
offsetHint: Int,
lineHint: Int
): String {
val document = FileDocumentManager.getInstance().getDocument(virtualFile)
?: return "ERROR"
val info = findBestHighlight(project, virtualFile, document, offsetHint, lineHint)
?: return "ERROR"
return severityNameOf(info.severity)
}

private fun findBestHighlight(
project: Project,
virtualFile: VirtualFile,
document: com.intellij.openapi.editor.Document,
offsetHint: Int,
lineHint: Int
): HighlightInfo? {
var best: HighlightInfo? = null
runReadAction {
DaemonCodeAnalyzerEx.processHighlights(
document,
project,
HighlightSeverity.INFORMATION,
0,
document.textLength
) { info ->
val matches = when {
offsetHint >= 0 && offsetHint in info.startOffset..info.endOffset -> true
lineHint >= 0 && document.textLength > 0 && info.startOffset >= 0 -> {
val lineOfInfo = document.getLineNumber(
info.startOffset.coerceIn(0, document.textLength)
)
lineOfInfo == lineHint
}
else -> false
}
if (matches) {
val current = best
if (current == null || info.severity.compareTo(current.severity) > 0) {
best = info
}
}
true
}
}
return best
}

private fun severityNameOf(severity: HighlightSeverity): String {
return when (severity) {
HighlightSeverity.ERROR -> "ERROR"
HighlightSeverity.WARNING -> "WARNING"
HighlightSeverity.WEAK_WARNING -> "WEAK_WARNING"
HighlightSeverity.INFORMATION -> "INFO"
else -> severity.toString()
}
}

private inline fun <reified T> Class<*>.invokeNullable(target: Any, methodName: String): T? {
return try {
val value = getMethod(methodName).invoke(target)
value as? T
} catch (_: NoSuchMethodException) {
null
} catch (_: Exception) {
null
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ object TagProcessorFactory {
is EmptyTagDetails -> TagProcessor { _, _ -> }
is CodeAnalyzeTagDetails -> TagProcessor { _, _ -> }
is DiagnosticsTagDetails -> DiagnosticsTagProcessor(project, tagDetails)
is SingleDiagnosticTagDetails -> SingleDiagnosticTagProcessor(project, tagDetails)
}
}

Expand Down Expand Up @@ -258,3 +259,30 @@ class DiagnosticsTagProcessor(
.append("\n")
}
}

class SingleDiagnosticTagProcessor(
private val project: Project,
private val tagDetails: SingleDiagnosticTagDetails,
) : TagProcessor {

override fun process(message: Message, promptBuilder: StringBuilder) {
TagProcessorFactory.appendReferencedFilePaths(
project,
message,
listOf(tagDetails.virtualFile)
)

val locationSuffix = if (tagDetails.column > 0) {
"${tagDetails.line}:${tagDetails.column}"
} else {
tagDetails.line.toString()
}

promptBuilder
.append("\n## Problem in ${tagDetails.virtualFile.name}\n")
.append("- Path: ${tagDetails.virtualFile.path}\n")
.append("- Location: line $locationSuffix\n")
.append("- Severity: ${tagDetails.severityName}\n")
.append("- Message: ${tagDetails.description}\n")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -311,3 +311,42 @@ data class DiagnosticsTagDetails(
) : TagDetails("${virtualFile.name} Problems (${filter.displayName})", AllIcons.General.InspectionsEye) {
override fun getTooltipText(): String = "${virtualFile.path} (${filter.displayName})"
}

data class SingleDiagnosticTagDetails(
val virtualFile: VirtualFile,
val line: Int,
val column: Int,
val severityName: String,
val description: String
) : TagDetails(
buildSingleDiagnosticTagName(virtualFile, line, description),
iconForDiagnosticSeverity(severityName)
) {
override fun getTooltipText(): String {
val location = if (column > 0) "$line:$column" else line.toString()
return "${virtualFile.path}:$location\n[$severityName] $description"
}
}

private fun buildSingleDiagnosticTagName(
virtualFile: VirtualFile,
line: Int,
description: String
): String {
val prefix = "${virtualFile.name}:$line"
val shortDesc = description.lineSequence().firstOrNull().orEmpty().trim()
return if (shortDesc.isEmpty()) {
prefix
} else {
"$prefix ${shortDesc.take(48)}".trimEnd()
}
}

private fun iconForDiagnosticSeverity(severityName: String): Icon {
return when (severityName.uppercase()) {
"ERROR" -> AllIcons.General.Error
"WARNING" -> AllIcons.General.Warning
"WEAK_WARNING" -> AllIcons.General.Warning
else -> AllIcons.General.Information
}
}
5 changes: 5 additions & 0 deletions src/main/resources/META-INF/plugin.xml
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,11 @@
<override-text place="MainMenu" text="Open Settings"/>
<override-text place="popup" use-text-of-place="MainMenu"/>
</action>
<action
id="ProxyAI.AddProblemToContext"
text="ProxyAI: Add Selected Problem to Chat Context"
description="Add the problem currently selected in the Problems tool window to the ProxyAI Chat context"
class="ee.carlrobert.codegpt.actions.AddProblemToContextAction"/>
<action
id="statusbar.enableCompletions"
class="ee.carlrobert.codegpt.actions.EnableCompletionsAction">
Expand Down