ChatTextArea.tsx 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. import React, { forwardRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"
  2. import { useEvent } from "react-use"
  3. import DynamicTextArea from "react-textarea-autosize"
  4. import { VolumeX, Image, WandSparkles, SendHorizontal } from "lucide-react"
  5. import { mentionRegex, mentionRegexGlobal, commandRegexGlobal, unescapeSpaces } from "@roo/context-mentions"
  6. import { WebviewMessage } from "@roo/WebviewMessage"
  7. import { Mode, getAllModes } from "@roo/modes"
  8. import { ExtensionMessage } from "@roo/ExtensionMessage"
  9. import { vscode } from "@src/utils/vscode"
  10. import { useExtensionState } from "@src/context/ExtensionStateContext"
  11. import { useAppTranslation } from "@src/i18n/TranslationContext"
  12. import {
  13. ContextMenuOptionType,
  14. getContextMenuOptions,
  15. insertMention,
  16. removeMention,
  17. shouldShowContextMenu,
  18. SearchResult,
  19. } from "@src/utils/context-mentions"
  20. import { cn } from "@src/lib/utils"
  21. import { convertToMentionPath } from "@src/utils/path-mentions"
  22. import { StandardTooltip } from "@src/components/ui"
  23. import Thumbnails from "../common/Thumbnails"
  24. import { ModeSelector } from "./ModeSelector"
  25. import { ApiConfigSelector } from "./ApiConfigSelector"
  26. import { MAX_IMAGES_PER_MESSAGE } from "./ChatView"
  27. import ContextMenu from "./ContextMenu"
  28. import { IndexingStatusBadge } from "./IndexingStatusBadge"
  29. import { SlashCommandsPopover } from "./SlashCommandsPopover"
  30. import { usePromptHistory } from "./hooks/usePromptHistory"
  31. interface ChatTextAreaProps {
  32. inputValue: string
  33. setInputValue: (value: string) => void
  34. sendingDisabled: boolean
  35. selectApiConfigDisabled: boolean
  36. placeholderText: string
  37. selectedImages: string[]
  38. setSelectedImages: React.Dispatch<React.SetStateAction<string[]>>
  39. onSend: () => void
  40. onSelectImages: () => void
  41. shouldDisableImages: boolean
  42. onHeightChange?: (height: number) => void
  43. mode: Mode
  44. setMode: (value: Mode) => void
  45. modeShortcutText: string
  46. }
  47. export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
  48. (
  49. {
  50. inputValue,
  51. setInputValue,
  52. selectApiConfigDisabled,
  53. placeholderText,
  54. selectedImages,
  55. setSelectedImages,
  56. onSend,
  57. onSelectImages,
  58. shouldDisableImages,
  59. onHeightChange,
  60. mode,
  61. setMode,
  62. modeShortcutText,
  63. },
  64. ref,
  65. ) => {
  66. const { t } = useAppTranslation()
  67. const {
  68. filePaths,
  69. openedTabs,
  70. currentApiConfigName,
  71. listApiConfigMeta,
  72. customModes,
  73. customModePrompts,
  74. cwd,
  75. pinnedApiConfigs,
  76. togglePinnedApiConfig,
  77. taskHistory,
  78. clineMessages,
  79. commands,
  80. } = useExtensionState()
  81. // Find the ID and display text for the currently selected API configuration.
  82. const { currentConfigId, displayName } = useMemo(() => {
  83. const currentConfig = listApiConfigMeta?.find((config) => config.name === currentApiConfigName)
  84. return {
  85. currentConfigId: currentConfig?.id || "",
  86. displayName: currentApiConfigName || "", // Use the name directly for display.
  87. }
  88. }, [listApiConfigMeta, currentApiConfigName])
  89. const [gitCommits, setGitCommits] = useState<any[]>([])
  90. const [showDropdown, setShowDropdown] = useState(false)
  91. const [fileSearchResults, setFileSearchResults] = useState<SearchResult[]>([])
  92. const [searchLoading, setSearchLoading] = useState(false)
  93. const [searchRequestId, setSearchRequestId] = useState<string>("")
  94. // Close dropdown when clicking outside.
  95. useEffect(() => {
  96. const handleClickOutside = () => {
  97. if (showDropdown) {
  98. setShowDropdown(false)
  99. }
  100. }
  101. document.addEventListener("mousedown", handleClickOutside)
  102. return () => document.removeEventListener("mousedown", handleClickOutside)
  103. }, [showDropdown])
  104. // Handle enhanced prompt response and search results.
  105. useEffect(() => {
  106. const messageHandler = (event: MessageEvent) => {
  107. const message = event.data
  108. if (message.type === "enhancedPrompt") {
  109. if (message.text && textAreaRef.current) {
  110. try {
  111. // Use execCommand to replace text while preserving undo history
  112. if (document.execCommand) {
  113. // Use native browser methods to preserve undo stack
  114. const textarea = textAreaRef.current
  115. // Focus the textarea to ensure it's the active element
  116. textarea.focus()
  117. // Select all text first
  118. textarea.select()
  119. document.execCommand("insertText", false, message.text)
  120. } else {
  121. setInputValue(message.text)
  122. }
  123. } catch {
  124. setInputValue(message.text)
  125. }
  126. }
  127. setIsEnhancingPrompt(false)
  128. } else if (message.type === "insertTextIntoTextarea") {
  129. if (message.text && textAreaRef.current) {
  130. // Insert the command text at the current cursor position
  131. const textarea = textAreaRef.current
  132. const currentValue = inputValue
  133. const cursorPos = textarea.selectionStart || 0
  134. // Check if we need to add a space before the command
  135. const textBefore = currentValue.slice(0, cursorPos)
  136. const needsSpaceBefore = textBefore.length > 0 && !textBefore.endsWith(" ")
  137. const prefix = needsSpaceBefore ? " " : ""
  138. // Insert the text at cursor position
  139. const newValue =
  140. currentValue.slice(0, cursorPos) +
  141. prefix +
  142. message.text +
  143. " " +
  144. currentValue.slice(cursorPos)
  145. setInputValue(newValue)
  146. // Set cursor position after the inserted text
  147. const newCursorPos = cursorPos + prefix.length + message.text.length + 1
  148. setTimeout(() => {
  149. if (textAreaRef.current) {
  150. textAreaRef.current.focus()
  151. textAreaRef.current.setSelectionRange(newCursorPos, newCursorPos)
  152. }
  153. }, 0)
  154. }
  155. } else if (message.type === "commitSearchResults") {
  156. const commits = message.commits.map((commit: any) => ({
  157. type: ContextMenuOptionType.Git,
  158. value: commit.hash,
  159. label: commit.subject,
  160. description: `${commit.shortHash} by ${commit.author} on ${commit.date}`,
  161. icon: "$(git-commit)",
  162. }))
  163. setGitCommits(commits)
  164. } else if (message.type === "fileSearchResults") {
  165. setSearchLoading(false)
  166. if (message.requestId === searchRequestId) {
  167. setFileSearchResults(message.results || [])
  168. }
  169. }
  170. }
  171. window.addEventListener("message", messageHandler)
  172. return () => window.removeEventListener("message", messageHandler)
  173. }, [setInputValue, searchRequestId, inputValue])
  174. const [isDraggingOver, setIsDraggingOver] = useState(false)
  175. const [textAreaBaseHeight, setTextAreaBaseHeight] = useState<number | undefined>(undefined)
  176. const [showContextMenu, setShowContextMenu] = useState(false)
  177. const [cursorPosition, setCursorPosition] = useState(0)
  178. const [searchQuery, setSearchQuery] = useState("")
  179. const textAreaRef = useRef<HTMLTextAreaElement | null>(null)
  180. const [isMouseDownOnMenu, setIsMouseDownOnMenu] = useState(false)
  181. const highlightLayerRef = useRef<HTMLDivElement>(null)
  182. const [selectedMenuIndex, setSelectedMenuIndex] = useState(-1)
  183. const [selectedType, setSelectedType] = useState<ContextMenuOptionType | null>(null)
  184. const [justDeletedSpaceAfterMention, setJustDeletedSpaceAfterMention] = useState(false)
  185. const [intendedCursorPosition, setIntendedCursorPosition] = useState<number | null>(null)
  186. const contextMenuContainerRef = useRef<HTMLDivElement>(null)
  187. const [isEnhancingPrompt, setIsEnhancingPrompt] = useState(false)
  188. const [isFocused, setIsFocused] = useState(false)
  189. // Use custom hook for prompt history navigation
  190. const { handleHistoryNavigation, resetHistoryNavigation, resetOnInputChange } = usePromptHistory({
  191. clineMessages,
  192. taskHistory,
  193. cwd,
  194. inputValue,
  195. setInputValue,
  196. })
  197. // Fetch git commits when Git is selected or when typing a hash.
  198. useEffect(() => {
  199. if (selectedType === ContextMenuOptionType.Git || /^[a-f0-9]+$/i.test(searchQuery)) {
  200. const message: WebviewMessage = {
  201. type: "searchCommits",
  202. query: searchQuery || "",
  203. } as const
  204. vscode.postMessage(message)
  205. }
  206. }, [selectedType, searchQuery])
  207. const handleEnhancePrompt = useCallback(() => {
  208. const trimmedInput = inputValue.trim()
  209. if (trimmedInput) {
  210. setIsEnhancingPrompt(true)
  211. vscode.postMessage({ type: "enhancePrompt" as const, text: trimmedInput })
  212. } else {
  213. setInputValue(t("chat:enhancePromptDescription"))
  214. }
  215. }, [inputValue, setInputValue, t])
  216. const allModes = useMemo(() => getAllModes(customModes), [customModes])
  217. const queryItems = useMemo(() => {
  218. return [
  219. { type: ContextMenuOptionType.Problems, value: "problems" },
  220. { type: ContextMenuOptionType.Terminal, value: "terminal" },
  221. ...gitCommits,
  222. ...openedTabs
  223. .filter((tab) => tab.path)
  224. .map((tab) => ({
  225. type: ContextMenuOptionType.OpenedFile,
  226. value: "/" + tab.path,
  227. })),
  228. ...filePaths
  229. .map((file) => "/" + file)
  230. .filter((path) => !openedTabs.some((tab) => tab.path && "/" + tab.path === path)) // Filter out paths that are already in openedTabs
  231. .map((path) => ({
  232. type: path.endsWith("/") ? ContextMenuOptionType.Folder : ContextMenuOptionType.File,
  233. value: path,
  234. })),
  235. ]
  236. }, [filePaths, gitCommits, openedTabs])
  237. useEffect(() => {
  238. const handleClickOutside = (event: MouseEvent) => {
  239. if (
  240. contextMenuContainerRef.current &&
  241. !contextMenuContainerRef.current.contains(event.target as Node)
  242. ) {
  243. setShowContextMenu(false)
  244. }
  245. }
  246. if (showContextMenu) {
  247. document.addEventListener("mousedown", handleClickOutside)
  248. }
  249. return () => {
  250. document.removeEventListener("mousedown", handleClickOutside)
  251. }
  252. }, [showContextMenu, setShowContextMenu])
  253. const handleMentionSelect = useCallback(
  254. (type: ContextMenuOptionType, value?: string) => {
  255. if (type === ContextMenuOptionType.NoResults) {
  256. return
  257. }
  258. if (type === ContextMenuOptionType.Mode && value) {
  259. // Handle mode selection.
  260. setMode(value)
  261. setInputValue("")
  262. setShowContextMenu(false)
  263. vscode.postMessage({ type: "mode", text: value })
  264. return
  265. }
  266. if (type === ContextMenuOptionType.Command && value) {
  267. // Handle command selection.
  268. setSelectedMenuIndex(-1)
  269. setInputValue("")
  270. setShowContextMenu(false)
  271. // Insert the command mention into the textarea
  272. const commandMention = `/${value}`
  273. setInputValue(commandMention + " ")
  274. setCursorPosition(commandMention.length + 1)
  275. setIntendedCursorPosition(commandMention.length + 1)
  276. // Focus the textarea
  277. setTimeout(() => {
  278. if (textAreaRef.current) {
  279. textAreaRef.current.focus()
  280. }
  281. }, 0)
  282. return
  283. }
  284. if (
  285. type === ContextMenuOptionType.File ||
  286. type === ContextMenuOptionType.Folder ||
  287. type === ContextMenuOptionType.Git
  288. ) {
  289. if (!value) {
  290. setSelectedType(type)
  291. setSearchQuery("")
  292. setSelectedMenuIndex(0)
  293. return
  294. }
  295. }
  296. setShowContextMenu(false)
  297. setSelectedType(null)
  298. if (textAreaRef.current) {
  299. let insertValue = value || ""
  300. if (type === ContextMenuOptionType.URL) {
  301. insertValue = value || ""
  302. } else if (type === ContextMenuOptionType.File || type === ContextMenuOptionType.Folder) {
  303. insertValue = value || ""
  304. } else if (type === ContextMenuOptionType.Problems) {
  305. insertValue = "problems"
  306. } else if (type === ContextMenuOptionType.Terminal) {
  307. insertValue = "terminal"
  308. } else if (type === ContextMenuOptionType.Git) {
  309. insertValue = value || ""
  310. } else if (type === ContextMenuOptionType.Command) {
  311. insertValue = value ? `/${value}` : ""
  312. }
  313. // Determine if this is a slash command selection
  314. const isSlashCommand = type === ContextMenuOptionType.Mode || type === ContextMenuOptionType.Command
  315. const { newValue, mentionIndex } = insertMention(
  316. textAreaRef.current.value,
  317. cursorPosition,
  318. insertValue,
  319. isSlashCommand,
  320. )
  321. setInputValue(newValue)
  322. const newCursorPosition = newValue.indexOf(" ", mentionIndex + insertValue.length) + 1
  323. setCursorPosition(newCursorPosition)
  324. setIntendedCursorPosition(newCursorPosition)
  325. // Scroll to cursor.
  326. setTimeout(() => {
  327. if (textAreaRef.current) {
  328. textAreaRef.current.blur()
  329. textAreaRef.current.focus()
  330. }
  331. }, 0)
  332. }
  333. },
  334. // eslint-disable-next-line react-hooks/exhaustive-deps
  335. [setInputValue, cursorPosition],
  336. )
  337. const handleKeyDown = useCallback(
  338. (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
  339. if (showContextMenu) {
  340. if (event.key === "Escape") {
  341. setSelectedType(null)
  342. setSelectedMenuIndex(3) // File by default
  343. return
  344. }
  345. if (event.key === "ArrowUp" || event.key === "ArrowDown") {
  346. event.preventDefault()
  347. setSelectedMenuIndex((prevIndex) => {
  348. const direction = event.key === "ArrowUp" ? -1 : 1
  349. const options = getContextMenuOptions(
  350. searchQuery,
  351. selectedType,
  352. queryItems,
  353. fileSearchResults,
  354. allModes,
  355. commands,
  356. )
  357. const optionsLength = options.length
  358. if (optionsLength === 0) return prevIndex
  359. // Find selectable options (non-URL types)
  360. const selectableOptions = options.filter(
  361. (option) =>
  362. option.type !== ContextMenuOptionType.URL &&
  363. option.type !== ContextMenuOptionType.NoResults &&
  364. option.type !== ContextMenuOptionType.SectionHeader,
  365. )
  366. if (selectableOptions.length === 0) return -1 // No selectable options
  367. // Find the index of the next selectable option
  368. const currentSelectableIndex = selectableOptions.findIndex(
  369. (option) => option === options[prevIndex],
  370. )
  371. const newSelectableIndex =
  372. (currentSelectableIndex + direction + selectableOptions.length) %
  373. selectableOptions.length
  374. // Find the index of the selected option in the original options array
  375. return options.findIndex((option) => option === selectableOptions[newSelectableIndex])
  376. })
  377. return
  378. }
  379. if ((event.key === "Enter" || event.key === "Tab") && selectedMenuIndex !== -1) {
  380. event.preventDefault()
  381. const selectedOption = getContextMenuOptions(
  382. searchQuery,
  383. selectedType,
  384. queryItems,
  385. fileSearchResults,
  386. allModes,
  387. commands,
  388. )[selectedMenuIndex]
  389. if (
  390. selectedOption &&
  391. selectedOption.type !== ContextMenuOptionType.URL &&
  392. selectedOption.type !== ContextMenuOptionType.NoResults &&
  393. selectedOption.type !== ContextMenuOptionType.SectionHeader
  394. ) {
  395. handleMentionSelect(selectedOption.type, selectedOption.value)
  396. }
  397. return
  398. }
  399. }
  400. const isComposing = event.nativeEvent?.isComposing ?? false
  401. // Handle prompt history navigation using custom hook
  402. if (handleHistoryNavigation(event, showContextMenu, isComposing)) {
  403. return
  404. }
  405. if (event.key === "Enter" && !event.shiftKey && !isComposing) {
  406. event.preventDefault()
  407. // Always call onSend - let ChatView handle queueing when disabled
  408. resetHistoryNavigation()
  409. onSend()
  410. }
  411. if (event.key === "Backspace" && !isComposing) {
  412. const charBeforeCursor = inputValue[cursorPosition - 1]
  413. const charAfterCursor = inputValue[cursorPosition + 1]
  414. const charBeforeIsWhitespace =
  415. charBeforeCursor === " " || charBeforeCursor === "\n" || charBeforeCursor === "\r\n"
  416. const charAfterIsWhitespace =
  417. charAfterCursor === " " || charAfterCursor === "\n" || charAfterCursor === "\r\n"
  418. // Checks if char before cusor is whitespace after a mention.
  419. if (
  420. charBeforeIsWhitespace &&
  421. // "$" is added to ensure the match occurs at the end of the string.
  422. inputValue.slice(0, cursorPosition - 1).match(new RegExp(mentionRegex.source + "$"))
  423. ) {
  424. const newCursorPosition = cursorPosition - 1
  425. // If mention is followed by another word, then instead
  426. // of deleting the space separating them we just move
  427. // the cursor to the end of the mention.
  428. if (!charAfterIsWhitespace) {
  429. event.preventDefault()
  430. textAreaRef.current?.setSelectionRange(newCursorPosition, newCursorPosition)
  431. setCursorPosition(newCursorPosition)
  432. }
  433. setCursorPosition(newCursorPosition)
  434. setJustDeletedSpaceAfterMention(true)
  435. } else if (justDeletedSpaceAfterMention) {
  436. const { newText, newPosition } = removeMention(inputValue, cursorPosition)
  437. if (newText !== inputValue) {
  438. event.preventDefault()
  439. setInputValue(newText)
  440. setIntendedCursorPosition(newPosition) // Store the new cursor position in state
  441. }
  442. setJustDeletedSpaceAfterMention(false)
  443. setShowContextMenu(false)
  444. } else {
  445. setJustDeletedSpaceAfterMention(false)
  446. }
  447. }
  448. },
  449. [
  450. onSend,
  451. showContextMenu,
  452. searchQuery,
  453. selectedMenuIndex,
  454. handleMentionSelect,
  455. selectedType,
  456. inputValue,
  457. cursorPosition,
  458. setInputValue,
  459. justDeletedSpaceAfterMention,
  460. queryItems,
  461. allModes,
  462. fileSearchResults,
  463. handleHistoryNavigation,
  464. resetHistoryNavigation,
  465. commands,
  466. ],
  467. )
  468. useLayoutEffect(() => {
  469. if (intendedCursorPosition !== null && textAreaRef.current) {
  470. textAreaRef.current.setSelectionRange(intendedCursorPosition, intendedCursorPosition)
  471. setIntendedCursorPosition(null) // Reset the state.
  472. }
  473. }, [inputValue, intendedCursorPosition])
  474. // Ref to store the search timeout.
  475. const searchTimeoutRef = useRef<NodeJS.Timeout | null>(null)
  476. const handleInputChange = useCallback(
  477. (e: React.ChangeEvent<HTMLTextAreaElement>) => {
  478. const newValue = e.target.value
  479. setInputValue(newValue)
  480. // Reset history navigation when user types
  481. resetOnInputChange()
  482. const newCursorPosition = e.target.selectionStart
  483. setCursorPosition(newCursorPosition)
  484. const showMenu = shouldShowContextMenu(newValue, newCursorPosition)
  485. setShowContextMenu(showMenu)
  486. if (showMenu) {
  487. if (newValue.startsWith("/") && !newValue.includes(" ")) {
  488. // Handle slash command - request fresh commands
  489. const query = newValue
  490. setSearchQuery(query)
  491. // Set to first selectable item (skip section headers)
  492. setSelectedMenuIndex(1) // Section header is at 0, first command is at 1
  493. // Request commands fresh each time slash menu is shown
  494. vscode.postMessage({ type: "requestCommands" })
  495. } else {
  496. // Existing @ mention handling.
  497. const lastAtIndex = newValue.lastIndexOf("@", newCursorPosition - 1)
  498. const query = newValue.slice(lastAtIndex + 1, newCursorPosition)
  499. setSearchQuery(query)
  500. // Send file search request if query is not empty.
  501. if (query.length > 0) {
  502. setSelectedMenuIndex(0)
  503. // Don't clear results until we have new ones. This
  504. // prevents flickering.
  505. // Clear any existing timeout.
  506. if (searchTimeoutRef.current) {
  507. clearTimeout(searchTimeoutRef.current)
  508. }
  509. // Set a timeout to debounce the search requests.
  510. searchTimeoutRef.current = setTimeout(() => {
  511. // Generate a request ID for this search.
  512. const reqId = Math.random().toString(36).substring(2, 9)
  513. setSearchRequestId(reqId)
  514. setSearchLoading(true)
  515. // Send message to extension to search files.
  516. vscode.postMessage({
  517. type: "searchFiles",
  518. query: unescapeSpaces(query),
  519. requestId: reqId,
  520. })
  521. }, 200) // 200ms debounce.
  522. } else {
  523. setSelectedMenuIndex(3) // Set to "File" option by default.
  524. }
  525. }
  526. } else {
  527. setSearchQuery("")
  528. setSelectedMenuIndex(-1)
  529. setFileSearchResults([]) // Clear file search results.
  530. }
  531. },
  532. [setInputValue, setSearchRequestId, setFileSearchResults, setSearchLoading, resetOnInputChange],
  533. )
  534. useEffect(() => {
  535. if (!showContextMenu) {
  536. setSelectedType(null)
  537. }
  538. }, [showContextMenu])
  539. const handleBlur = useCallback(() => {
  540. // Only hide the context menu if the user didn't click on it.
  541. if (!isMouseDownOnMenu) {
  542. setShowContextMenu(false)
  543. }
  544. setIsFocused(false)
  545. }, [isMouseDownOnMenu])
  546. const handlePaste = useCallback(
  547. async (e: React.ClipboardEvent) => {
  548. const items = e.clipboardData.items
  549. const pastedText = e.clipboardData.getData("text")
  550. // Check if the pasted content is a URL, add space after so user
  551. // can easily delete if they don't want it.
  552. const urlRegex = /^\S+:\/\/\S+$/
  553. if (urlRegex.test(pastedText.trim())) {
  554. e.preventDefault()
  555. const trimmedUrl = pastedText.trim()
  556. const newValue =
  557. inputValue.slice(0, cursorPosition) + trimmedUrl + " " + inputValue.slice(cursorPosition)
  558. setInputValue(newValue)
  559. const newCursorPosition = cursorPosition + trimmedUrl.length + 1
  560. setCursorPosition(newCursorPosition)
  561. setIntendedCursorPosition(newCursorPosition)
  562. setShowContextMenu(false)
  563. // Scroll to new cursor position.
  564. setTimeout(() => {
  565. if (textAreaRef.current) {
  566. textAreaRef.current.blur()
  567. textAreaRef.current.focus()
  568. }
  569. }, 0)
  570. return
  571. }
  572. const acceptedTypes = ["png", "jpeg", "webp"]
  573. const imageItems = Array.from(items).filter((item) => {
  574. const [type, subtype] = item.type.split("/")
  575. return type === "image" && acceptedTypes.includes(subtype)
  576. })
  577. if (!shouldDisableImages && imageItems.length > 0) {
  578. e.preventDefault()
  579. const imagePromises = imageItems.map((item) => {
  580. return new Promise<string | null>((resolve) => {
  581. const blob = item.getAsFile()
  582. if (!blob) {
  583. resolve(null)
  584. return
  585. }
  586. const reader = new FileReader()
  587. reader.onloadend = () => {
  588. if (reader.error) {
  589. console.error(t("chat:errorReadingFile"), reader.error)
  590. resolve(null)
  591. } else {
  592. const result = reader.result
  593. resolve(typeof result === "string" ? result : null)
  594. }
  595. }
  596. reader.readAsDataURL(blob)
  597. })
  598. })
  599. const imageDataArray = await Promise.all(imagePromises)
  600. const dataUrls = imageDataArray.filter((dataUrl): dataUrl is string => dataUrl !== null)
  601. if (dataUrls.length > 0) {
  602. setSelectedImages((prevImages) => [...prevImages, ...dataUrls].slice(0, MAX_IMAGES_PER_MESSAGE))
  603. } else {
  604. console.warn(t("chat:noValidImages"))
  605. }
  606. }
  607. },
  608. [shouldDisableImages, setSelectedImages, cursorPosition, setInputValue, inputValue, t],
  609. )
  610. const handleMenuMouseDown = useCallback(() => {
  611. setIsMouseDownOnMenu(true)
  612. }, [])
  613. const updateHighlights = useCallback(() => {
  614. if (!textAreaRef.current || !highlightLayerRef.current) return
  615. const text = textAreaRef.current.value
  616. // Helper function to check if a command is valid
  617. const isValidCommand = (commandName: string): boolean => {
  618. return commands?.some((cmd) => cmd.name === commandName) || false
  619. }
  620. // Process the text to highlight mentions and valid commands
  621. let processedText = text
  622. .replace(/\n$/, "\n\n")
  623. .replace(/[<>&]/g, (c) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;" })[c] || c)
  624. .replace(mentionRegexGlobal, '<mark class="mention-context-textarea-highlight">$&</mark>')
  625. // Custom replacement for commands - only highlight valid ones
  626. processedText = processedText.replace(commandRegexGlobal, (match, commandName) => {
  627. // Only highlight if the command exists in the valid commands list
  628. if (isValidCommand(commandName)) {
  629. // Check if the match starts with a space
  630. const startsWithSpace = match.startsWith(" ")
  631. const commandPart = `/${commandName}`
  632. if (startsWithSpace) {
  633. // Keep the space but only highlight the command part
  634. return ` <mark class="mention-context-textarea-highlight">${commandPart}</mark>`
  635. } else {
  636. // Highlight the entire command (starts at beginning of line)
  637. return `<mark class="mention-context-textarea-highlight">${commandPart}</mark>`
  638. }
  639. }
  640. return match // Return unhighlighted if command is not valid
  641. })
  642. highlightLayerRef.current.innerHTML = processedText
  643. highlightLayerRef.current.scrollTop = textAreaRef.current.scrollTop
  644. highlightLayerRef.current.scrollLeft = textAreaRef.current.scrollLeft
  645. }, [commands])
  646. useLayoutEffect(() => {
  647. updateHighlights()
  648. }, [inputValue, updateHighlights])
  649. const updateCursorPosition = useCallback(() => {
  650. if (textAreaRef.current) {
  651. setCursorPosition(textAreaRef.current.selectionStart)
  652. }
  653. }, [])
  654. const handleKeyUp = useCallback(
  655. (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  656. if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"].includes(e.key)) {
  657. updateCursorPosition()
  658. }
  659. },
  660. [updateCursorPosition],
  661. )
  662. const handleDrop = useCallback(
  663. async (e: React.DragEvent<HTMLDivElement>) => {
  664. e.preventDefault()
  665. setIsDraggingOver(false)
  666. const textFieldList = e.dataTransfer.getData("text")
  667. const textUriList = e.dataTransfer.getData("application/vnd.code.uri-list")
  668. // When textFieldList is empty, it may attempt to use textUriList obtained from drag-and-drop tabs; if not empty, it will use textFieldList.
  669. const text = textFieldList || textUriList
  670. if (text) {
  671. // Split text on newlines to handle multiple files
  672. const lines = text.split(/\r?\n/).filter((line) => line.trim() !== "")
  673. if (lines.length > 0) {
  674. // Process each line as a separate file path
  675. let newValue = inputValue.slice(0, cursorPosition)
  676. let totalLength = 0
  677. // Using a standard for loop instead of forEach for potential performance gains.
  678. for (let i = 0; i < lines.length; i++) {
  679. const line = lines[i]
  680. // Convert each path to a mention-friendly format
  681. const mentionText = convertToMentionPath(line, cwd)
  682. newValue += mentionText
  683. totalLength += mentionText.length
  684. // Add space after each mention except the last one
  685. if (i < lines.length - 1) {
  686. newValue += " "
  687. totalLength += 1
  688. }
  689. }
  690. // Add space after the last mention and append the rest of the input
  691. newValue += " " + inputValue.slice(cursorPosition)
  692. totalLength += 1
  693. setInputValue(newValue)
  694. const newCursorPosition = cursorPosition + totalLength
  695. setCursorPosition(newCursorPosition)
  696. setIntendedCursorPosition(newCursorPosition)
  697. }
  698. return
  699. }
  700. const files = Array.from(e.dataTransfer.files)
  701. if (files.length > 0) {
  702. const acceptedTypes = ["png", "jpeg", "webp"]
  703. const imageFiles = files.filter((file) => {
  704. const [type, subtype] = file.type.split("/")
  705. return type === "image" && acceptedTypes.includes(subtype)
  706. })
  707. if (!shouldDisableImages && imageFiles.length > 0) {
  708. const imagePromises = imageFiles.map((file) => {
  709. return new Promise<string | null>((resolve) => {
  710. const reader = new FileReader()
  711. reader.onloadend = () => {
  712. if (reader.error) {
  713. console.error(t("chat:errorReadingFile"), reader.error)
  714. resolve(null)
  715. } else {
  716. const result = reader.result
  717. resolve(typeof result === "string" ? result : null)
  718. }
  719. }
  720. reader.readAsDataURL(file)
  721. })
  722. })
  723. const imageDataArray = await Promise.all(imagePromises)
  724. const dataUrls = imageDataArray.filter((dataUrl): dataUrl is string => dataUrl !== null)
  725. if (dataUrls.length > 0) {
  726. setSelectedImages((prevImages) =>
  727. [...prevImages, ...dataUrls].slice(0, MAX_IMAGES_PER_MESSAGE),
  728. )
  729. if (typeof vscode !== "undefined") {
  730. vscode.postMessage({ type: "draggedImages", dataUrls: dataUrls })
  731. }
  732. } else {
  733. console.warn(t("chat:noValidImages"))
  734. }
  735. }
  736. }
  737. },
  738. [
  739. cursorPosition,
  740. cwd,
  741. inputValue,
  742. setInputValue,
  743. setCursorPosition,
  744. setIntendedCursorPosition,
  745. shouldDisableImages,
  746. setSelectedImages,
  747. t,
  748. ],
  749. )
  750. const [isTtsPlaying, setIsTtsPlaying] = useState(false)
  751. useEvent("message", (event: MessageEvent) => {
  752. const message: ExtensionMessage = event.data
  753. if (message.type === "ttsStart") {
  754. setIsTtsPlaying(true)
  755. } else if (message.type === "ttsStop") {
  756. setIsTtsPlaying(false)
  757. }
  758. })
  759. const placeholderBottomText = `\n(${t("chat:addContext")}${shouldDisableImages ? `, ${t("chat:dragFiles")}` : `, ${t("chat:dragFilesImages")}`})`
  760. const handleModeChange = useCallback(
  761. (value: Mode) => {
  762. setMode(value)
  763. vscode.postMessage({ type: "mode", text: value })
  764. },
  765. [setMode],
  766. )
  767. const handleApiConfigChange = useCallback((value: string) => {
  768. vscode.postMessage({ type: "loadApiConfigurationById", text: value })
  769. }, [])
  770. return (
  771. <div
  772. className={cn(
  773. "relative",
  774. "flex",
  775. "flex-col",
  776. "gap-1",
  777. "bg-editor-background",
  778. "px-1.5",
  779. "pb-1",
  780. "outline-none",
  781. "border",
  782. "border-none",
  783. "w-[calc(100%-16px)]",
  784. "ml-auto",
  785. "mr-auto",
  786. "box-border",
  787. )}>
  788. <div className="relative">
  789. <div
  790. className={cn("chat-text-area", "relative", "flex", "flex-col", "outline-none")}
  791. onDrop={handleDrop}
  792. onDragOver={(e) => {
  793. // Only allowed to drop images/files on shift key pressed.
  794. if (!e.shiftKey) {
  795. setIsDraggingOver(false)
  796. return
  797. }
  798. e.preventDefault()
  799. setIsDraggingOver(true)
  800. e.dataTransfer.dropEffect = "copy"
  801. }}
  802. onDragLeave={(e) => {
  803. e.preventDefault()
  804. const rect = e.currentTarget.getBoundingClientRect()
  805. if (
  806. e.clientX <= rect.left ||
  807. e.clientX >= rect.right ||
  808. e.clientY <= rect.top ||
  809. e.clientY >= rect.bottom
  810. ) {
  811. setIsDraggingOver(false)
  812. }
  813. }}>
  814. {showContextMenu && (
  815. <div
  816. ref={contextMenuContainerRef}
  817. className={cn(
  818. "absolute",
  819. "bottom-full",
  820. "left-0",
  821. "right-0",
  822. "z-[1000]",
  823. "mb-2",
  824. "filter",
  825. "drop-shadow-md",
  826. )}>
  827. <ContextMenu
  828. onSelect={handleMentionSelect}
  829. searchQuery={searchQuery}
  830. inputValue={inputValue}
  831. onMouseDown={handleMenuMouseDown}
  832. selectedIndex={selectedMenuIndex}
  833. setSelectedIndex={setSelectedMenuIndex}
  834. selectedType={selectedType}
  835. queryItems={queryItems}
  836. modes={allModes}
  837. loading={searchLoading}
  838. dynamicSearchResults={fileSearchResults}
  839. commands={commands}
  840. />
  841. </div>
  842. )}
  843. <div
  844. className={cn(
  845. "relative",
  846. "flex-1",
  847. "flex",
  848. "flex-col-reverse",
  849. "min-h-0",
  850. "overflow-hidden",
  851. "rounded",
  852. )}>
  853. <div
  854. ref={highlightLayerRef}
  855. data-testid="highlight-layer"
  856. className={cn(
  857. "absolute",
  858. "inset-0",
  859. "pointer-events-none",
  860. "whitespace-pre-wrap",
  861. "break-words",
  862. "text-transparent",
  863. "overflow-hidden",
  864. "font-vscode-font-family",
  865. "text-vscode-editor-font-size",
  866. "leading-vscode-editor-line-height",
  867. isFocused
  868. ? "border border-vscode-focusBorder outline outline-vscode-focusBorder"
  869. : isDraggingOver
  870. ? "border-2 border-dashed border-vscode-focusBorder"
  871. : "border border-transparent",
  872. "px-[8px]",
  873. "py-1.5",
  874. "pr-9",
  875. "z-10",
  876. "forced-color-adjust-none",
  877. )}
  878. style={{
  879. color: "transparent",
  880. }}
  881. />
  882. <DynamicTextArea
  883. ref={(el) => {
  884. if (typeof ref === "function") {
  885. ref(el)
  886. } else if (ref) {
  887. ref.current = el
  888. }
  889. textAreaRef.current = el
  890. }}
  891. value={inputValue}
  892. onChange={(e) => {
  893. handleInputChange(e)
  894. updateHighlights()
  895. }}
  896. onFocus={() => setIsFocused(true)}
  897. onKeyDown={handleKeyDown}
  898. onKeyUp={handleKeyUp}
  899. onBlur={handleBlur}
  900. onPaste={handlePaste}
  901. onSelect={updateCursorPosition}
  902. onMouseUp={updateCursorPosition}
  903. onHeightChange={(height) => {
  904. if (textAreaBaseHeight === undefined || height < textAreaBaseHeight) {
  905. setTextAreaBaseHeight(height)
  906. }
  907. onHeightChange?.(height)
  908. }}
  909. placeholder={placeholderText}
  910. minRows={3}
  911. maxRows={15}
  912. autoFocus={true}
  913. className={cn(
  914. "w-full",
  915. "text-vscode-input-foreground",
  916. "font-vscode-font-family",
  917. "text-vscode-editor-font-size",
  918. "leading-vscode-editor-line-height",
  919. "cursor-text",
  920. "py-1.5 px-2",
  921. isFocused
  922. ? "border border-vscode-focusBorder outline outline-vscode-focusBorder"
  923. : isDraggingOver
  924. ? "border-2 border-dashed border-vscode-focusBorder"
  925. : "border border-transparent",
  926. isDraggingOver
  927. ? "bg-[color-mix(in_srgb,var(--vscode-input-background)_95%,var(--vscode-focusBorder))]"
  928. : "bg-vscode-input-background",
  929. "transition-background-color duration-150 ease-in-out",
  930. "will-change-background-color",
  931. "min-h-[90px]",
  932. "box-border",
  933. "rounded",
  934. "resize-none",
  935. "overflow-x-hidden",
  936. "overflow-y-auto",
  937. "pr-9",
  938. "flex-none flex-grow",
  939. "z-[2]",
  940. "scrollbar-none",
  941. "scrollbar-hide",
  942. )}
  943. onScroll={() => updateHighlights()}
  944. />
  945. <div className="absolute top-1 right-1 z-30">
  946. <StandardTooltip content={t("chat:enhancePrompt")}>
  947. <button
  948. aria-label={t("chat:enhancePrompt")}
  949. disabled={false}
  950. onClick={handleEnhancePrompt}
  951. className={cn(
  952. "relative inline-flex items-center justify-center",
  953. "bg-transparent border-none p-1.5",
  954. "rounded-md min-w-[28px] min-h-[28px]",
  955. "opacity-60 hover:opacity-100 text-vscode-descriptionForeground hover:text-vscode-foreground",
  956. "transition-all duration-150",
  957. "hover:bg-[rgba(255,255,255,0.03)] hover:border-[rgba(255,255,255,0.15)]",
  958. "focus:outline-none focus-visible:ring-1 focus-visible:ring-vscode-focusBorder",
  959. "active:bg-[rgba(255,255,255,0.1)]",
  960. "cursor-pointer",
  961. )}>
  962. <WandSparkles className={cn("w-4 h-4", isEnhancingPrompt && "animate-spin")} />
  963. </button>
  964. </StandardTooltip>
  965. </div>
  966. <div className="absolute bottom-1 right-1 z-30">
  967. <StandardTooltip content={t("chat:sendMessage")}>
  968. <button
  969. aria-label={t("chat:sendMessage")}
  970. disabled={false}
  971. onClick={onSend}
  972. className={cn(
  973. "relative inline-flex items-center justify-center",
  974. "bg-transparent border-none p-1.5",
  975. "rounded-md min-w-[28px] min-h-[28px]",
  976. "opacity-60 hover:opacity-100 text-vscode-descriptionForeground hover:text-vscode-foreground",
  977. "transition-all duration-150",
  978. "hover:bg-[rgba(255,255,255,0.03)] hover:border-[rgba(255,255,255,0.15)]",
  979. "focus:outline-none focus-visible:ring-1 focus-visible:ring-vscode-focusBorder",
  980. "active:bg-[rgba(255,255,255,0.1)]",
  981. "cursor-pointer",
  982. )}>
  983. <SendHorizontal className="w-4 h-4" />
  984. </button>
  985. </StandardTooltip>
  986. </div>
  987. {!inputValue && (
  988. <div
  989. className="absolute left-2 z-30 pr-9 flex items-center h-8 font-vscode-font-family text-vscode-editor-font-size leading-vscode-editor-line-height"
  990. style={{
  991. bottom: "0.25rem",
  992. color: "color-mix(in oklab, var(--vscode-input-foreground) 50%, transparent)",
  993. userSelect: "none",
  994. pointerEvents: "none",
  995. }}>
  996. {placeholderBottomText}
  997. </div>
  998. )}
  999. </div>
  1000. </div>
  1001. </div>
  1002. {selectedImages.length > 0 && (
  1003. <Thumbnails
  1004. images={selectedImages}
  1005. setImages={setSelectedImages}
  1006. style={{
  1007. left: "16px",
  1008. zIndex: 2,
  1009. marginBottom: 0,
  1010. }}
  1011. />
  1012. )}
  1013. <div className="flex justify-between items-center">
  1014. <div className="flex items-center gap-1">
  1015. <div className="max-w-32">
  1016. <ModeSelector
  1017. value={mode}
  1018. title={t("chat:selectMode")}
  1019. onChange={handleModeChange}
  1020. triggerClassName="w-full"
  1021. modeShortcutText={modeShortcutText}
  1022. customModes={customModes}
  1023. customModePrompts={customModePrompts}
  1024. />
  1025. </div>
  1026. <div className="max-w-32">
  1027. <ApiConfigSelector
  1028. value={currentConfigId}
  1029. displayName={displayName}
  1030. disabled={selectApiConfigDisabled}
  1031. title={t("chat:selectApiConfig")}
  1032. onChange={handleApiConfigChange}
  1033. triggerClassName="w-full text-ellipsis overflow-hidden"
  1034. listApiConfigMeta={listApiConfigMeta || []}
  1035. pinnedApiConfigs={pinnedApiConfigs}
  1036. togglePinnedApiConfig={togglePinnedApiConfig}
  1037. />
  1038. </div>
  1039. </div>
  1040. <div className="flex items-center gap-0.5">
  1041. {isTtsPlaying && (
  1042. <StandardTooltip content={t("chat:stopTts")}>
  1043. <button
  1044. aria-label={t("chat:stopTts")}
  1045. onClick={() => vscode.postMessage({ type: "stopTts" })}
  1046. className={cn(
  1047. "relative inline-flex items-center justify-center",
  1048. "bg-transparent border-none p-1.5",
  1049. "rounded-md min-w-[28px] min-h-[28px]",
  1050. "text-vscode-foreground opacity-85",
  1051. "transition-all duration-150",
  1052. "hover:opacity-100 hover:bg-[rgba(255,255,255,0.03)] hover:border-[rgba(255,255,255,0.15)]",
  1053. "focus:outline-none focus-visible:ring-1 focus-visible:ring-vscode-focusBorder",
  1054. "active:bg-[rgba(255,255,255,0.1)]",
  1055. "cursor-pointer",
  1056. )}>
  1057. <VolumeX className="w-4 h-4" />
  1058. </button>
  1059. </StandardTooltip>
  1060. )}
  1061. <SlashCommandsPopover />
  1062. <IndexingStatusBadge />
  1063. <StandardTooltip content={t("chat:addImages")}>
  1064. <button
  1065. aria-label={t("chat:addImages")}
  1066. disabled={shouldDisableImages}
  1067. onClick={!shouldDisableImages ? onSelectImages : undefined}
  1068. className={cn(
  1069. "relative inline-flex items-center justify-center",
  1070. "bg-transparent border-none p-1.5",
  1071. "rounded-md min-w-[28px] min-h-[28px]",
  1072. "text-vscode-foreground opacity-85",
  1073. "transition-all duration-150",
  1074. "hover:opacity-100 hover:bg-[rgba(255,255,255,0.03)] hover:border-[rgba(255,255,255,0.15)]",
  1075. "focus:outline-none focus-visible:ring-1 focus-visible:ring-vscode-focusBorder",
  1076. "active:bg-[rgba(255,255,255,0.1)]",
  1077. !shouldDisableImages && "cursor-pointer",
  1078. shouldDisableImages &&
  1079. "opacity-40 cursor-not-allowed grayscale-[30%] hover:bg-transparent hover:border-[rgba(255,255,255,0.08)] active:bg-transparent",
  1080. "mr-1",
  1081. )}>
  1082. <Image className="w-4 h-4" />
  1083. </button>
  1084. </StandardTooltip>
  1085. </div>
  1086. </div>
  1087. </div>
  1088. )
  1089. },
  1090. )