Skip to content
Closed
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
20 changes: 20 additions & 0 deletions src/core/webview/webviewMessageHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2190,6 +2190,26 @@ export const webviewMessageHandler = async (
break
}

case "requestEditorContext": {
try {
const { EditorUtils } = await import("../../integrations/editor/EditorUtils")
const editorContext = await EditorUtils.getEditorContext()

await provider.postMessageToWebview({
type: "editorContext",
editorContext: editorContext || undefined,
})
} catch (error) {
provider.log(
`Error getting editor context: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`,
)
await provider.postMessageToWebview({
type: "editorContext",
editorContext: undefined,
})
}
break
}
case "switchTab": {
if (message.tab) {
// Capture tab shown event for all switchTab messages (which are user-initiated)
Expand Down
8 changes: 8 additions & 0 deletions src/shared/ExtensionMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,18 @@ export interface ExtensionMessage {
| "shareTaskSuccess"
| "codeIndexSettingsSaved"
| "codeIndexSecretStatus"
| "editorContext"
| "showDeleteMessageDialog"
| "showEditMessageDialog"
text?: string
payload?: any // Add a generic payload for now, can refine later
editorContext?: {
filePath?: string
selectedText?: string
startLine?: number
endLine?: number
diagnostics?: any[]
}
action?:
| "chatButtonClicked"
| "mcpButtonClicked"
Expand Down
9 changes: 9 additions & 0 deletions src/shared/WebviewMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,8 @@ export interface WebviewMessage {
| "checkRulesDirectoryResult"
| "saveCodeIndexSettingsAtomic"
| "requestCodeIndexSecretStatus"
| "requestEditorContext"
| "editorContext"
text?: string
editedMessageContent?: string
tab?: "settings" | "history" | "mcp" | "modes" | "chat" | "marketplace" | "account"
Expand Down Expand Up @@ -257,6 +259,13 @@ export interface WebviewMessage {
codebaseIndexOpenAiCompatibleApiKey?: string
codebaseIndexGeminiApiKey?: string
}
editorContext?: {
filePath?: string
selectedText?: string
startLine?: number
endLine?: number
diagnostics?: any[]
}
}

export const checkoutDiffPayloadSchema = z.object({
Expand Down
90 changes: 73 additions & 17 deletions webview-ui/src/components/chat/ChatTextArea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,21 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
const [fileSearchResults, setFileSearchResults] = useState<SearchResult[]>([])
const [searchLoading, setSearchLoading] = useState(false)
const [searchRequestId, setSearchRequestId] = useState<string>("")
const [isDraggingOver, setIsDraggingOver] = useState(false)
const [textAreaBaseHeight, setTextAreaBaseHeight] = useState<number | undefined>(undefined)
const [showContextMenu, setShowContextMenu] = useState(false)
const [cursorPosition, setCursorPosition] = useState(0)
const [searchQuery, setSearchQuery] = useState("")
const textAreaRef = useRef<HTMLTextAreaElement | null>(null)
const [isMouseDownOnMenu, setIsMouseDownOnMenu] = useState(false)
const highlightLayerRef = useRef<HTMLDivElement>(null)
const [selectedMenuIndex, setSelectedMenuIndex] = useState(-1)
const [selectedType, setSelectedType] = useState<ContextMenuOptionType | null>(null)
const [justDeletedSpaceAfterMention, setJustDeletedSpaceAfterMention] = useState(false)
const [intendedCursorPosition, setIntendedCursorPosition] = useState<number | null>(null)
const contextMenuContainerRef = useRef<HTMLDivElement>(null)
const [isEnhancingPrompt, setIsEnhancingPrompt] = useState(false)
const [isFocused, setIsFocused] = useState(false)

// Close dropdown when clicking outside.
useEffect(() => {
Expand Down Expand Up @@ -158,28 +173,63 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
if (message.requestId === searchRequestId) {
setFileSearchResults(message.results || [])
}
} else if (message.type === "editorContext") {
// Handle editor context response
if (message.editorContext && textAreaRef.current) {
const editorContext = message.editorContext
let insertValue = ""

if (editorContext.filePath) {
// Format: filename:startLine-endLine (selected text preview)
const fileName = editorContext.filePath.split("/").pop() || editorContext.filePath
let contextText = fileName

if (editorContext.startLine !== undefined) {
if (
editorContext.endLine !== undefined &&
editorContext.endLine !== editorContext.startLine
) {
contextText += `:${editorContext.startLine}-${editorContext.endLine}`
} else {
contextText += `:${editorContext.startLine}`
}
}

if (editorContext.selectedText && editorContext.selectedText.trim()) {
const preview = editorContext.selectedText.trim().substring(0, 50)
contextText += ` (${preview}${editorContext.selectedText.length > 50 ? "..." : ""})`
}

insertValue = contextText
} else {
insertValue = "current-editor"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of using the hardcoded fallback string "current-editor" when editorContext.filePath is missing, consider using a translatable string (e.g. t('chat:currentEditor')) for consistency with i18n practices.

Suggested change
insertValue = "current-editor"
insertValue = t("chat:currentEditor")

This comment was generated because it violated a code review rule: irule_C0ez7Rji6ANcGkkX.

}

const { newValue, mentionIndex } = insertMention(
textAreaRef.current.value,
cursorPosition,
insertValue,
)

setInputValue(newValue)
const newCursorPosition = newValue.indexOf(" ", mentionIndex + insertValue.length) + 1
setCursorPosition(newCursorPosition)
setIntendedCursorPosition(newCursorPosition)

// Scroll to cursor
setTimeout(() => {
if (textAreaRef.current) {
textAreaRef.current.blur()
textAreaRef.current.focus()
}
}, 0)
}
}
}

window.addEventListener("message", messageHandler)
return () => window.removeEventListener("message", messageHandler)
}, [setInputValue, searchRequestId])

const [isDraggingOver, setIsDraggingOver] = useState(false)
const [textAreaBaseHeight, setTextAreaBaseHeight] = useState<number | undefined>(undefined)
const [showContextMenu, setShowContextMenu] = useState(false)
const [cursorPosition, setCursorPosition] = useState(0)
const [searchQuery, setSearchQuery] = useState("")
const textAreaRef = useRef<HTMLTextAreaElement | null>(null)
const [isMouseDownOnMenu, setIsMouseDownOnMenu] = useState(false)
const highlightLayerRef = useRef<HTMLDivElement>(null)
const [selectedMenuIndex, setSelectedMenuIndex] = useState(-1)
const [selectedType, setSelectedType] = useState<ContextMenuOptionType | null>(null)
const [justDeletedSpaceAfterMention, setJustDeletedSpaceAfterMention] = useState(false)
const [intendedCursorPosition, setIntendedCursorPosition] = useState<number | null>(null)
const contextMenuContainerRef = useRef<HTMLDivElement>(null)
const [isEnhancingPrompt, setIsEnhancingPrompt] = useState(false)
const [isFocused, setIsFocused] = useState(false)
}, [setInputValue, searchRequestId, cursorPosition])

// Use custom hook for prompt history navigation
const { handleHistoryNavigation, resetHistoryNavigation, resetOnInputChange } = usePromptHistory({
Expand Down Expand Up @@ -300,6 +350,12 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
insertValue = "problems"
} else if (type === ContextMenuOptionType.Terminal) {
insertValue = "terminal"
} else if (type === ContextMenuOptionType.EditorContext) {
// Request editor context from backend
vscode.postMessage({ type: "requestEditorContext" })
setShowContextMenu(false)
setSelectedType(null)
return
} else if (type === ContextMenuOptionType.Git) {
insertValue = value || ""
}
Expand Down
4 changes: 4 additions & 0 deletions webview-ui/src/components/chat/ContextMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ const ContextMenu: React.FC<ContextMenuProps> = ({
return <span>Problems</span>
case ContextMenuOptionType.Terminal:
return <span>Terminal</span>
case ContextMenuOptionType.EditorContext:
return <span>Current Editor Context</span>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace the hardcoded text 'Current Editor Context' with a call to the translation function (e.g. t('chat:currentEditorContext')) to support i18n.

Suggested change
return <span>Current Editor Context</span>
return <span>{t('chat:currentEditorContext')}</span>

This comment was generated because it violated a code review rule: irule_C0ez7Rji6ANcGkkX.

case ContextMenuOptionType.URL:
return <span>Paste URL to fetch contents</span>
case ContextMenuOptionType.NoResults:
Expand Down Expand Up @@ -173,6 +175,8 @@ const ContextMenu: React.FC<ContextMenuProps> = ({
return "warning"
case ContextMenuOptionType.Terminal:
return "terminal"
case ContextMenuOptionType.EditorContext:
return "edit"
case ContextMenuOptionType.URL:
return "link"
case ContextMenuOptionType.Git:
Expand Down
3 changes: 2 additions & 1 deletion webview-ui/src/utils/__tests__/context-mentions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,9 @@ describe("getContextMenuOptions", () => {

it("should return all option types for empty query", () => {
const result = getContextMenuOptions("", "", null, [])
expect(result).toHaveLength(6)
expect(result).toHaveLength(7)
expect(result.map((item) => item.type)).toEqual([
ContextMenuOptionType.EditorContext,
ContextMenuOptionType.Problems,
ContextMenuOptionType.Terminal,
ContextMenuOptionType.URL,
Expand Down
2 changes: 2 additions & 0 deletions webview-ui/src/utils/context-mentions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ export enum ContextMenuOptionType {
Git = "git",
NoResults = "noResults",
Mode = "mode", // Add mode type
EditorContext = "editorContext", // Add editor context type
}

export interface ContextMenuQueryItem {
Expand Down Expand Up @@ -192,6 +193,7 @@ export function getContextMenuOptions(
}

return [
{ type: ContextMenuOptionType.EditorContext },
{ type: ContextMenuOptionType.Problems },
{ type: ContextMenuOptionType.Terminal },
{ type: ContextMenuOptionType.URL },
Expand Down