ChatView.tsx 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  1. import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
  2. import debounce from "debounce"
  3. import { useCallback, useEffect, useMemo, useRef, useState } from "react"
  4. import { useDeepCompareEffect, useEvent, useMount } from "react-use"
  5. import { Virtuoso, type VirtuosoHandle } from "react-virtuoso"
  6. import styled from "styled-components"
  7. import {
  8. ClineAsk,
  9. ClineMessage,
  10. ClineSayBrowserAction,
  11. ClineSayTool,
  12. ExtensionMessage,
  13. } from "../../../../src/shared/ExtensionMessage"
  14. import { McpServer, McpTool } from "../../../../src/shared/mcp"
  15. import { findLast } from "../../../../src/shared/array"
  16. import { combineApiRequests } from "../../../../src/shared/combineApiRequests"
  17. import { combineCommandSequences } from "../../../../src/shared/combineCommandSequences"
  18. import { getApiMetrics } from "../../../../src/shared/getApiMetrics"
  19. import { useExtensionState } from "../../context/ExtensionStateContext"
  20. import { vscode } from "../../utils/vscode"
  21. import HistoryPreview from "../history/HistoryPreview"
  22. import { normalizeApiConfiguration } from "../settings/ApiOptions"
  23. import Announcement from "./Announcement"
  24. import BrowserSessionRow from "./BrowserSessionRow"
  25. import ChatRow from "./ChatRow"
  26. import ChatTextArea from "./ChatTextArea"
  27. import TaskHeader from "./TaskHeader"
  28. import AutoApproveMenu from "./AutoApproveMenu"
  29. import { AudioType } from "../../../../src/shared/WebviewMessage"
  30. import { validateCommand } from "../../utils/command-validation"
  31. interface ChatViewProps {
  32. isHidden: boolean
  33. showAnnouncement: boolean
  34. hideAnnouncement: () => void
  35. showHistoryView: () => void
  36. }
  37. export const MAX_IMAGES_PER_MESSAGE = 20 // Anthropic limits to 20 images
  38. const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryView }: ChatViewProps) => {
  39. const {
  40. version,
  41. clineMessages: messages,
  42. taskHistory,
  43. apiConfiguration,
  44. mcpServers,
  45. alwaysAllowBrowser,
  46. alwaysAllowReadOnly,
  47. alwaysAllowWrite,
  48. alwaysAllowExecute,
  49. alwaysAllowMcp,
  50. allowedCommands,
  51. writeDelayMs,
  52. mode,
  53. setMode,
  54. autoApprovalEnabled,
  55. alwaysAllowModeSwitch,
  56. } = useExtensionState()
  57. //const task = messages.length > 0 ? (messages[0].say === "task" ? messages[0] : undefined) : undefined) : undefined
  58. const task = useMemo(() => messages.at(0), [messages]) // leaving this less safe version here since if the first message is not a task, then the extension is in a bad state and needs to be debugged (see Cline.abort)
  59. const modifiedMessages = useMemo(() => combineApiRequests(combineCommandSequences(messages.slice(1))), [messages])
  60. // has to be after api_req_finished are all reduced into api_req_started messages
  61. const apiMetrics = useMemo(() => getApiMetrics(modifiedMessages), [modifiedMessages])
  62. const [inputValue, setInputValue] = useState("")
  63. const textAreaRef = useRef<HTMLTextAreaElement>(null)
  64. const [textAreaDisabled, setTextAreaDisabled] = useState(false)
  65. const [selectedImages, setSelectedImages] = useState<string[]>([])
  66. // we need to hold on to the ask because useEffect > lastMessage will always let us know when an ask comes in and handle it, but by the time handleMessage is called, the last message might not be the ask anymore (it could be a say that followed)
  67. const [clineAsk, setClineAsk] = useState<ClineAsk | undefined>(undefined)
  68. const [enableButtons, setEnableButtons] = useState<boolean>(false)
  69. const [primaryButtonText, setPrimaryButtonText] = useState<string | undefined>(undefined)
  70. const [secondaryButtonText, setSecondaryButtonText] = useState<string | undefined>(undefined)
  71. const [didClickCancel, setDidClickCancel] = useState(false)
  72. const virtuosoRef = useRef<VirtuosoHandle>(null)
  73. const [expandedRows, setExpandedRows] = useState<Record<number, boolean>>({})
  74. const scrollContainerRef = useRef<HTMLDivElement>(null)
  75. const disableAutoScrollRef = useRef(false)
  76. const [showScrollToBottom, setShowScrollToBottom] = useState(false)
  77. const [isAtBottom, setIsAtBottom] = useState(false)
  78. const [wasStreaming, setWasStreaming] = useState<boolean>(false)
  79. // UI layout depends on the last 2 messages
  80. // (since it relies on the content of these messages, we are deep comparing. i.e. the button state after hitting button sets enableButtons to false, and this effect otherwise would have to true again even if messages didn't change
  81. const lastMessage = useMemo(() => messages.at(-1), [messages])
  82. const secondLastMessage = useMemo(() => messages.at(-2), [messages])
  83. function playSound(audioType: AudioType) {
  84. vscode.postMessage({ type: "playSound", audioType })
  85. }
  86. useDeepCompareEffect(() => {
  87. // if last message is an ask, show user ask UI
  88. // if user finished a task, then start a new task with a new conversation history since in this moment that the extension is waiting for user response, the user could close the extension and the conversation history would be lost.
  89. // basically as long as a task is active, the conversation history will be persisted
  90. if (lastMessage) {
  91. switch (lastMessage.type) {
  92. case "ask":
  93. const isPartial = lastMessage.partial === true
  94. switch (lastMessage.ask) {
  95. case "api_req_failed":
  96. playSound("progress_loop")
  97. setTextAreaDisabled(true)
  98. setClineAsk("api_req_failed")
  99. setEnableButtons(true)
  100. setPrimaryButtonText("Retry")
  101. setSecondaryButtonText("Start New Task")
  102. break
  103. case "mistake_limit_reached":
  104. playSound("progress_loop")
  105. setTextAreaDisabled(false)
  106. setClineAsk("mistake_limit_reached")
  107. setEnableButtons(true)
  108. setPrimaryButtonText("Proceed Anyways")
  109. setSecondaryButtonText("Start New Task")
  110. break
  111. case "followup":
  112. setTextAreaDisabled(isPartial)
  113. setClineAsk("followup")
  114. setEnableButtons(isPartial)
  115. // setPrimaryButtonText(undefined)
  116. // setSecondaryButtonText(undefined)
  117. break
  118. case "tool":
  119. if (!isAutoApproved(lastMessage)) {
  120. playSound("notification")
  121. }
  122. setTextAreaDisabled(isPartial)
  123. setClineAsk("tool")
  124. setEnableButtons(!isPartial)
  125. const tool = JSON.parse(lastMessage.text || "{}") as ClineSayTool
  126. switch (tool.tool) {
  127. case "editedExistingFile":
  128. case "appliedDiff":
  129. case "newFileCreated":
  130. setPrimaryButtonText("Save")
  131. setSecondaryButtonText("Reject")
  132. break
  133. default:
  134. setPrimaryButtonText("Approve")
  135. setSecondaryButtonText("Reject")
  136. break
  137. }
  138. break
  139. case "browser_action_launch":
  140. if (!isAutoApproved(lastMessage)) {
  141. playSound("notification")
  142. }
  143. setTextAreaDisabled(isPartial)
  144. setClineAsk("browser_action_launch")
  145. setEnableButtons(!isPartial)
  146. setPrimaryButtonText("Approve")
  147. setSecondaryButtonText("Reject")
  148. break
  149. case "command":
  150. if (!isAutoApproved(lastMessage)) {
  151. playSound("notification")
  152. }
  153. setTextAreaDisabled(isPartial)
  154. setClineAsk("command")
  155. setEnableButtons(!isPartial)
  156. setPrimaryButtonText("Run Command")
  157. setSecondaryButtonText("Reject")
  158. break
  159. case "command_output":
  160. setTextAreaDisabled(false)
  161. setClineAsk("command_output")
  162. setEnableButtons(true)
  163. setPrimaryButtonText("Proceed While Running")
  164. setSecondaryButtonText(undefined)
  165. break
  166. case "use_mcp_server":
  167. setTextAreaDisabled(isPartial)
  168. setClineAsk("use_mcp_server")
  169. setEnableButtons(!isPartial)
  170. setPrimaryButtonText("Approve")
  171. setSecondaryButtonText("Reject")
  172. break
  173. case "completion_result":
  174. // extension waiting for feedback. but we can just present a new task button
  175. playSound("celebration")
  176. setTextAreaDisabled(isPartial)
  177. setClineAsk("completion_result")
  178. setEnableButtons(!isPartial)
  179. setPrimaryButtonText("Start New Task")
  180. setSecondaryButtonText(undefined)
  181. break
  182. case "resume_task":
  183. setTextAreaDisabled(false)
  184. setClineAsk("resume_task")
  185. setEnableButtons(true)
  186. setPrimaryButtonText("Resume Task")
  187. setSecondaryButtonText("Terminate")
  188. setDidClickCancel(false) // special case where we reset the cancel button state
  189. break
  190. case "resume_completed_task":
  191. setTextAreaDisabled(false)
  192. setClineAsk("resume_completed_task")
  193. setEnableButtons(true)
  194. setPrimaryButtonText("Start New Task")
  195. setSecondaryButtonText(undefined)
  196. setDidClickCancel(false)
  197. break
  198. }
  199. break
  200. case "say":
  201. // don't want to reset since there could be a "say" after an "ask" while ask is waiting for response
  202. switch (lastMessage.say) {
  203. case "api_req_retry_delayed":
  204. setTextAreaDisabled(true)
  205. break
  206. case "api_req_started":
  207. if (secondLastMessage?.ask === "command_output") {
  208. // if the last ask is a command_output, and we receive an api_req_started, then that means the command has finished and we don't need input from the user anymore (in every other case, the user has to interact with input field or buttons to continue, which does the following automatically)
  209. setInputValue("")
  210. setTextAreaDisabled(true)
  211. setSelectedImages([])
  212. setClineAsk(undefined)
  213. setEnableButtons(false)
  214. }
  215. break
  216. case "api_req_finished":
  217. case "task":
  218. case "error":
  219. case "text":
  220. case "browser_action":
  221. case "browser_action_result":
  222. case "command_output":
  223. case "mcp_server_request_started":
  224. case "mcp_server_response":
  225. case "completion_result":
  226. case "tool":
  227. break
  228. }
  229. break
  230. }
  231. } else {
  232. // this would get called after sending the first message, so we have to watch messages.length instead
  233. // No messages, so user has to submit a task
  234. // setTextAreaDisabled(false)
  235. // setClineAsk(undefined)
  236. // setPrimaryButtonText(undefined)
  237. // setSecondaryButtonText(undefined)
  238. }
  239. }, [lastMessage, secondLastMessage])
  240. useEffect(() => {
  241. if (messages.length === 0) {
  242. setTextAreaDisabled(false)
  243. setClineAsk(undefined)
  244. setEnableButtons(false)
  245. setPrimaryButtonText(undefined)
  246. setSecondaryButtonText(undefined)
  247. }
  248. }, [messages.length])
  249. useEffect(() => {
  250. setExpandedRows({})
  251. }, [task?.ts])
  252. const isStreaming = useMemo(() => {
  253. const isLastAsk = !!modifiedMessages.at(-1)?.ask // checking clineAsk isn't enough since messages effect may be called again for a tool for example, set clineAsk to its value, and if the next message is not an ask then it doesn't reset. This is likely due to how much more often we're updating messages as compared to before, and should be resolved with optimizations as it's likely a rendering bug. but as a final guard for now, the cancel button will show if the last message is not an ask
  254. const isToolCurrentlyAsking =
  255. isLastAsk && clineAsk !== undefined && enableButtons && primaryButtonText !== undefined
  256. if (isToolCurrentlyAsking) {
  257. return false
  258. }
  259. const isLastMessagePartial = modifiedMessages.at(-1)?.partial === true
  260. if (isLastMessagePartial) {
  261. return true
  262. } else {
  263. const lastApiReqStarted = findLast(modifiedMessages, (message) => message.say === "api_req_started")
  264. if (
  265. lastApiReqStarted &&
  266. lastApiReqStarted.text !== null &&
  267. lastApiReqStarted.text !== undefined &&
  268. lastApiReqStarted.say === "api_req_started"
  269. ) {
  270. const cost = JSON.parse(lastApiReqStarted.text).cost
  271. if (cost === undefined) {
  272. // api request has not finished yet
  273. return true
  274. }
  275. }
  276. }
  277. return false
  278. }, [modifiedMessages, clineAsk, enableButtons, primaryButtonText])
  279. const handleSendMessage = useCallback(
  280. (text: string, images: string[]) => {
  281. text = text.trim()
  282. if (text || images.length > 0) {
  283. if (messages.length === 0) {
  284. vscode.postMessage({ type: "newTask", text, images })
  285. } else if (clineAsk) {
  286. switch (clineAsk) {
  287. case "followup":
  288. case "tool":
  289. case "browser_action_launch":
  290. case "command": // user can provide feedback to a tool or command use
  291. case "command_output": // user can send input to command stdin
  292. case "use_mcp_server":
  293. case "completion_result": // if this happens then the user has feedback for the completion result
  294. case "resume_task":
  295. case "resume_completed_task":
  296. case "mistake_limit_reached":
  297. vscode.postMessage({
  298. type: "askResponse",
  299. askResponse: "messageResponse",
  300. text,
  301. images,
  302. })
  303. break
  304. // there is no other case that a textfield should be enabled
  305. }
  306. }
  307. // Only reset message-specific state, preserving mode
  308. setInputValue("")
  309. setTextAreaDisabled(true)
  310. setSelectedImages([])
  311. setClineAsk(undefined)
  312. setEnableButtons(false)
  313. // Do not reset mode here as it should persist
  314. // setPrimaryButtonText(undefined)
  315. // setSecondaryButtonText(undefined)
  316. disableAutoScrollRef.current = false
  317. }
  318. },
  319. [messages.length, clineAsk],
  320. )
  321. const handleSetChatBoxMessage = useCallback(
  322. (text: string, images: string[]) => {
  323. // Avoid nested template literals by breaking down the logic
  324. let newValue = text
  325. if (inputValue !== "") {
  326. newValue = inputValue + " " + text
  327. }
  328. setInputValue(newValue)
  329. setSelectedImages([...selectedImages, ...images])
  330. },
  331. [inputValue, selectedImages],
  332. )
  333. const startNewTask = useCallback(() => {
  334. vscode.postMessage({ type: "clearTask" })
  335. }, [])
  336. /*
  337. This logic depends on the useEffect[messages] above to set clineAsk, after which buttons are shown and we then send an askResponse to the extension.
  338. */
  339. const handlePrimaryButtonClick = useCallback(
  340. (text?: string, images?: string[]) => {
  341. const trimmedInput = text?.trim()
  342. switch (clineAsk) {
  343. case "api_req_failed":
  344. case "command":
  345. case "command_output":
  346. case "tool":
  347. case "browser_action_launch":
  348. case "use_mcp_server":
  349. case "resume_task":
  350. case "mistake_limit_reached":
  351. // Only send text/images if they exist
  352. if (trimmedInput || (images && images.length > 0)) {
  353. vscode.postMessage({
  354. type: "askResponse",
  355. askResponse: "yesButtonClicked",
  356. text: trimmedInput,
  357. images: images,
  358. })
  359. } else {
  360. vscode.postMessage({
  361. type: "askResponse",
  362. askResponse: "yesButtonClicked",
  363. })
  364. }
  365. // Clear input state after sending
  366. setInputValue("")
  367. setSelectedImages([])
  368. break
  369. case "completion_result":
  370. case "resume_completed_task":
  371. // extension waiting for feedback. but we can just present a new task button
  372. startNewTask()
  373. break
  374. }
  375. setTextAreaDisabled(true)
  376. setClineAsk(undefined)
  377. setEnableButtons(false)
  378. disableAutoScrollRef.current = false
  379. },
  380. [clineAsk, startNewTask],
  381. )
  382. const handleSecondaryButtonClick = useCallback(
  383. (text?: string, images?: string[]) => {
  384. const trimmedInput = text?.trim()
  385. if (isStreaming) {
  386. vscode.postMessage({ type: "cancelTask" })
  387. setDidClickCancel(true)
  388. return
  389. }
  390. switch (clineAsk) {
  391. case "api_req_failed":
  392. case "mistake_limit_reached":
  393. case "resume_task":
  394. startNewTask()
  395. break
  396. case "command":
  397. case "tool":
  398. case "browser_action_launch":
  399. case "use_mcp_server":
  400. // Only send text/images if they exist
  401. if (trimmedInput || (images && images.length > 0)) {
  402. vscode.postMessage({
  403. type: "askResponse",
  404. askResponse: "noButtonClicked",
  405. text: trimmedInput,
  406. images: images,
  407. })
  408. } else {
  409. // responds to the API with a "This operation failed" and lets it try again
  410. vscode.postMessage({
  411. type: "askResponse",
  412. askResponse: "noButtonClicked",
  413. })
  414. }
  415. // Clear input state after sending
  416. setInputValue("")
  417. setSelectedImages([])
  418. break
  419. }
  420. setTextAreaDisabled(true)
  421. setClineAsk(undefined)
  422. setEnableButtons(false)
  423. disableAutoScrollRef.current = false
  424. },
  425. [clineAsk, startNewTask, isStreaming],
  426. )
  427. const handleTaskCloseButtonClick = useCallback(() => {
  428. startNewTask()
  429. }, [startNewTask])
  430. const { selectedModelInfo } = useMemo(() => {
  431. return normalizeApiConfiguration(apiConfiguration)
  432. }, [apiConfiguration])
  433. const selectImages = useCallback(() => {
  434. vscode.postMessage({ type: "selectImages" })
  435. }, [])
  436. const shouldDisableImages =
  437. !selectedModelInfo.supportsImages || textAreaDisabled || selectedImages.length >= MAX_IMAGES_PER_MESSAGE
  438. const handleMessage = useCallback(
  439. (e: MessageEvent) => {
  440. const message: ExtensionMessage = e.data
  441. switch (message.type) {
  442. case "action":
  443. switch (message.action!) {
  444. case "didBecomeVisible":
  445. if (!isHidden && !textAreaDisabled && !enableButtons) {
  446. textAreaRef.current?.focus()
  447. }
  448. break
  449. }
  450. break
  451. case "selectedImages":
  452. const newImages = message.images ?? []
  453. if (newImages.length > 0) {
  454. setSelectedImages((prevImages) =>
  455. [...prevImages, ...newImages].slice(0, MAX_IMAGES_PER_MESSAGE),
  456. )
  457. }
  458. break
  459. case "invoke":
  460. switch (message.invoke!) {
  461. case "sendMessage":
  462. handleSendMessage(message.text ?? "", message.images ?? [])
  463. break
  464. case "setChatBoxMessage":
  465. handleSetChatBoxMessage(message.text ?? "", message.images ?? [])
  466. break
  467. case "primaryButtonClick":
  468. handlePrimaryButtonClick(message.text ?? "", message.images ?? [])
  469. break
  470. case "secondaryButtonClick":
  471. handleSecondaryButtonClick(message.text ?? "", message.images ?? [])
  472. break
  473. }
  474. }
  475. // textAreaRef.current is not explicitly required here since react gaurantees that ref will be stable across re-renders, and we're not using its value but its reference.
  476. },
  477. [
  478. isHidden,
  479. textAreaDisabled,
  480. enableButtons,
  481. handleSendMessage,
  482. handleSetChatBoxMessage,
  483. handlePrimaryButtonClick,
  484. handleSecondaryButtonClick,
  485. ],
  486. )
  487. useEvent("message", handleMessage)
  488. useMount(() => {
  489. // NOTE: the vscode window needs to be focused for this to work
  490. textAreaRef.current?.focus()
  491. })
  492. useEffect(() => {
  493. const timer = setTimeout(() => {
  494. if (!isHidden && !textAreaDisabled && !enableButtons) {
  495. textAreaRef.current?.focus()
  496. }
  497. }, 50)
  498. return () => {
  499. clearTimeout(timer)
  500. }
  501. }, [isHidden, textAreaDisabled, enableButtons])
  502. const visibleMessages = useMemo(() => {
  503. return modifiedMessages.filter((message) => {
  504. switch (message.ask) {
  505. case "completion_result":
  506. // don't show a chat row for a completion_result ask without text. This specific type of message only occurs if cline wants to execute a command as part of its completion result, in which case we interject the completion_result tool with the execute_command tool.
  507. if (message.text === "") {
  508. return false
  509. }
  510. break
  511. case "api_req_failed": // this message is used to update the latest api_req_started that the request failed
  512. case "resume_task":
  513. case "resume_completed_task":
  514. return false
  515. }
  516. switch (message.say) {
  517. case "api_req_finished": // combineApiRequests removes this from modifiedMessages anyways
  518. case "api_req_retried": // this message is used to update the latest api_req_started that the request was retried
  519. case "api_req_deleted": // aggregated api_req metrics from deleted messages
  520. return false
  521. case "api_req_retry_delayed":
  522. // Only show the retry message if it's the last message
  523. return message === modifiedMessages.at(-1)
  524. case "text":
  525. // Sometimes cline returns an empty text message, we don't want to render these. (We also use a say text for user messages, so in case they just sent images we still render that)
  526. if ((message.text ?? "") === "" && (message.images?.length ?? 0) === 0) {
  527. return false
  528. }
  529. break
  530. case "mcp_server_request_started":
  531. return false
  532. }
  533. return true
  534. })
  535. }, [modifiedMessages])
  536. const isReadOnlyToolAction = useCallback((message: ClineMessage | undefined) => {
  537. if (message?.type === "ask") {
  538. if (!message.text) {
  539. return true
  540. }
  541. const tool = JSON.parse(message.text)
  542. return [
  543. "readFile",
  544. "listFiles",
  545. "listFilesTopLevel",
  546. "listFilesRecursive",
  547. "listCodeDefinitionNames",
  548. "searchFiles",
  549. ].includes(tool.tool)
  550. }
  551. return false
  552. }, [])
  553. const isWriteToolAction = useCallback((message: ClineMessage | undefined) => {
  554. if (message?.type === "ask") {
  555. if (!message.text) {
  556. return true
  557. }
  558. const tool = JSON.parse(message.text)
  559. return ["editedExistingFile", "appliedDiff", "newFileCreated"].includes(tool.tool)
  560. }
  561. return false
  562. }, [])
  563. const isMcpToolAlwaysAllowed = useCallback(
  564. (message: ClineMessage | undefined) => {
  565. if (message?.type === "ask" && message.ask === "use_mcp_server") {
  566. if (!message.text) {
  567. return true
  568. }
  569. const mcpServerUse = JSON.parse(message.text) as { type: string; serverName: string; toolName: string }
  570. if (mcpServerUse.type === "use_mcp_tool") {
  571. const server = mcpServers?.find((s: McpServer) => s.name === mcpServerUse.serverName)
  572. const tool = server?.tools?.find((t: McpTool) => t.name === mcpServerUse.toolName)
  573. return tool?.alwaysAllow || false
  574. }
  575. }
  576. return false
  577. },
  578. [mcpServers],
  579. )
  580. // Check if a command message is allowed
  581. const isAllowedCommand = useCallback(
  582. (message: ClineMessage | undefined): boolean => {
  583. if (message?.type !== "ask") return false
  584. return validateCommand(message.text || "", allowedCommands || [])
  585. },
  586. [allowedCommands],
  587. )
  588. const isAutoApproved = useCallback(
  589. (message: ClineMessage | undefined) => {
  590. if (!autoApprovalEnabled || !message || message.type !== "ask") return false
  591. return (
  592. (alwaysAllowBrowser && message.ask === "browser_action_launch") ||
  593. (alwaysAllowReadOnly && message.ask === "tool" && isReadOnlyToolAction(message)) ||
  594. (alwaysAllowWrite && message.ask === "tool" && isWriteToolAction(message)) ||
  595. (alwaysAllowExecute && message.ask === "command" && isAllowedCommand(message)) ||
  596. (alwaysAllowMcp && message.ask === "use_mcp_server" && isMcpToolAlwaysAllowed(message)) ||
  597. (alwaysAllowModeSwitch &&
  598. message.ask === "tool" &&
  599. (JSON.parse(message.text || "{}")?.tool === "switchMode" ||
  600. JSON.parse(message.text || "{}")?.tool === "newTask"))
  601. )
  602. },
  603. [
  604. autoApprovalEnabled,
  605. alwaysAllowBrowser,
  606. alwaysAllowReadOnly,
  607. isReadOnlyToolAction,
  608. alwaysAllowWrite,
  609. isWriteToolAction,
  610. alwaysAllowExecute,
  611. isAllowedCommand,
  612. alwaysAllowMcp,
  613. isMcpToolAlwaysAllowed,
  614. alwaysAllowModeSwitch,
  615. ],
  616. )
  617. useEffect(() => {
  618. // Only execute when isStreaming changes from true to false
  619. if (wasStreaming && !isStreaming && lastMessage) {
  620. // Play appropriate sound based on lastMessage content
  621. if (lastMessage.type === "ask") {
  622. // Don't play sounds for auto-approved actions
  623. if (!isAutoApproved(lastMessage)) {
  624. switch (lastMessage.ask) {
  625. case "api_req_failed":
  626. case "mistake_limit_reached":
  627. playSound("progress_loop")
  628. break
  629. case "followup":
  630. if (!lastMessage.partial) {
  631. playSound("notification")
  632. }
  633. break
  634. case "tool":
  635. case "browser_action_launch":
  636. case "resume_task":
  637. case "use_mcp_server":
  638. playSound("notification")
  639. break
  640. case "completion_result":
  641. case "resume_completed_task":
  642. playSound("celebration")
  643. break
  644. }
  645. }
  646. }
  647. }
  648. // Update previous value
  649. setWasStreaming(isStreaming)
  650. }, [isStreaming, lastMessage, wasStreaming, isAutoApproved])
  651. const isBrowserSessionMessage = (message: ClineMessage): boolean => {
  652. // which of visible messages are browser session messages, see above
  653. if (message.type === "ask") {
  654. return ["browser_action_launch"].includes(message.ask!)
  655. }
  656. if (message.type === "say") {
  657. return ["api_req_started", "text", "browser_action", "browser_action_result"].includes(message.say!)
  658. }
  659. return false
  660. }
  661. const groupedMessages = useMemo(() => {
  662. const result: (ClineMessage | ClineMessage[])[] = []
  663. let currentGroup: ClineMessage[] = []
  664. let isInBrowserSession = false
  665. const endBrowserSession = () => {
  666. if (currentGroup.length > 0) {
  667. result.push([...currentGroup])
  668. currentGroup = []
  669. isInBrowserSession = false
  670. }
  671. }
  672. visibleMessages.forEach((message) => {
  673. if (message.ask === "browser_action_launch") {
  674. // complete existing browser session if any
  675. endBrowserSession()
  676. // start new
  677. isInBrowserSession = true
  678. currentGroup.push(message)
  679. } else if (isInBrowserSession) {
  680. // end session if api_req_started is cancelled
  681. if (message.say === "api_req_started") {
  682. // get last api_req_started in currentGroup to check if it's cancelled. If it is then this api req is not part of the current browser session
  683. const lastApiReqStarted = [...currentGroup].reverse().find((m) => m.say === "api_req_started")
  684. if (lastApiReqStarted?.text !== null && lastApiReqStarted?.text !== undefined) {
  685. const info = JSON.parse(lastApiReqStarted.text)
  686. const isCancelled = info.cancelReason !== null && info.cancelReason !== undefined
  687. if (isCancelled) {
  688. endBrowserSession()
  689. result.push(message)
  690. return
  691. }
  692. }
  693. }
  694. if (isBrowserSessionMessage(message)) {
  695. currentGroup.push(message)
  696. // Check if this is a close action
  697. if (message.say === "browser_action") {
  698. const browserAction = JSON.parse(message.text || "{}") as ClineSayBrowserAction
  699. if (browserAction.action === "close") {
  700. endBrowserSession()
  701. }
  702. }
  703. } else {
  704. // complete existing browser session if any
  705. endBrowserSession()
  706. result.push(message)
  707. }
  708. } else {
  709. result.push(message)
  710. }
  711. })
  712. // Handle case where browser session is the last group
  713. if (currentGroup.length > 0) {
  714. result.push([...currentGroup])
  715. }
  716. return result
  717. }, [visibleMessages])
  718. // scrolling
  719. const scrollToBottomSmooth = useMemo(
  720. () =>
  721. debounce(
  722. () => {
  723. virtuosoRef.current?.scrollTo({
  724. top: Number.MAX_SAFE_INTEGER,
  725. behavior: "smooth",
  726. })
  727. },
  728. 10,
  729. { immediate: true },
  730. ),
  731. [],
  732. )
  733. const scrollToBottomAuto = useCallback(() => {
  734. virtuosoRef.current?.scrollTo({
  735. top: Number.MAX_SAFE_INTEGER,
  736. behavior: "auto", // instant causes crash
  737. })
  738. }, [])
  739. // scroll when user toggles certain rows
  740. const toggleRowExpansion = useCallback(
  741. (ts: number) => {
  742. const isCollapsing = expandedRows[ts] ?? false
  743. const lastGroup = groupedMessages.at(-1)
  744. const isLast = Array.isArray(lastGroup) ? lastGroup[0].ts === ts : lastGroup?.ts === ts
  745. const secondToLastGroup = groupedMessages.at(-2)
  746. const isSecondToLast = Array.isArray(secondToLastGroup)
  747. ? secondToLastGroup[0].ts === ts
  748. : secondToLastGroup?.ts === ts
  749. const isLastCollapsedApiReq =
  750. isLast &&
  751. !Array.isArray(lastGroup) && // Make sure it's not a browser session group
  752. lastGroup?.say === "api_req_started" &&
  753. !expandedRows[lastGroup.ts]
  754. setExpandedRows((prev) => ({
  755. ...prev,
  756. [ts]: !prev[ts],
  757. }))
  758. // disable auto scroll when user expands row
  759. if (!isCollapsing) {
  760. disableAutoScrollRef.current = true
  761. }
  762. if (isCollapsing && isAtBottom) {
  763. const timer = setTimeout(() => {
  764. scrollToBottomAuto()
  765. }, 0)
  766. return () => clearTimeout(timer)
  767. } else if (isLast || isSecondToLast) {
  768. if (isCollapsing) {
  769. if (isSecondToLast && !isLastCollapsedApiReq) {
  770. return
  771. }
  772. const timer = setTimeout(() => {
  773. scrollToBottomAuto()
  774. }, 0)
  775. return () => clearTimeout(timer)
  776. } else {
  777. const timer = setTimeout(() => {
  778. virtuosoRef.current?.scrollToIndex({
  779. index: groupedMessages.length - (isLast ? 1 : 2),
  780. align: "start",
  781. })
  782. }, 0)
  783. return () => clearTimeout(timer)
  784. }
  785. }
  786. },
  787. [groupedMessages, expandedRows, scrollToBottomAuto, isAtBottom],
  788. )
  789. const handleRowHeightChange = useCallback(
  790. (isTaller: boolean) => {
  791. if (!disableAutoScrollRef.current) {
  792. if (isTaller) {
  793. scrollToBottomSmooth()
  794. } else {
  795. setTimeout(() => {
  796. scrollToBottomAuto()
  797. }, 0)
  798. }
  799. }
  800. },
  801. [scrollToBottomSmooth, scrollToBottomAuto],
  802. )
  803. useEffect(() => {
  804. if (!disableAutoScrollRef.current) {
  805. setTimeout(() => {
  806. scrollToBottomSmooth()
  807. }, 50)
  808. // return () => clearTimeout(timer) // dont cleanup since if visibleMessages.length changes it cancels.
  809. }
  810. }, [groupedMessages.length, scrollToBottomSmooth])
  811. const handleWheel = useCallback((event: Event) => {
  812. const wheelEvent = event as WheelEvent
  813. if (wheelEvent.deltaY && wheelEvent.deltaY < 0) {
  814. if (scrollContainerRef.current?.contains(wheelEvent.target as Node)) {
  815. // user scrolled up
  816. disableAutoScrollRef.current = true
  817. }
  818. }
  819. }, [])
  820. useEvent("wheel", handleWheel, window, { passive: true }) // passive improves scrolling performance
  821. const placeholderText = useMemo(() => {
  822. const baseText = task ? "Type a message..." : "Type your task here..."
  823. const contextText = "(@ to add context, / to switch modes"
  824. const imageText = shouldDisableImages ? ", hold shift to drag in files" : ", hold shift to drag in files/images"
  825. return baseText + `\n${contextText}${imageText})`
  826. }, [task, shouldDisableImages])
  827. const itemContent = useCallback(
  828. (index: number, messageOrGroup: ClineMessage | ClineMessage[]) => {
  829. // browser session group
  830. if (Array.isArray(messageOrGroup)) {
  831. return (
  832. <BrowserSessionRow
  833. messages={messageOrGroup}
  834. isLast={index === groupedMessages.length - 1}
  835. lastModifiedMessage={modifiedMessages.at(-1)}
  836. onHeightChange={handleRowHeightChange}
  837. isStreaming={isStreaming}
  838. // Pass handlers for each message in the group
  839. isExpanded={(messageTs: number) => expandedRows[messageTs] ?? false}
  840. onToggleExpand={(messageTs: number) => {
  841. setExpandedRows((prev) => ({
  842. ...prev,
  843. [messageTs]: !prev[messageTs],
  844. }))
  845. }}
  846. />
  847. )
  848. }
  849. // regular message
  850. return (
  851. <ChatRow
  852. key={messageOrGroup.ts}
  853. message={messageOrGroup}
  854. isExpanded={expandedRows[messageOrGroup.ts] || false}
  855. onToggleExpand={() => toggleRowExpansion(messageOrGroup.ts)}
  856. lastModifiedMessage={modifiedMessages.at(-1)}
  857. isLast={index === groupedMessages.length - 1}
  858. onHeightChange={handleRowHeightChange}
  859. isStreaming={isStreaming}
  860. />
  861. )
  862. },
  863. [
  864. expandedRows,
  865. modifiedMessages,
  866. groupedMessages.length,
  867. handleRowHeightChange,
  868. isStreaming,
  869. toggleRowExpansion,
  870. ],
  871. )
  872. useEffect(() => {
  873. // Only proceed if we have an ask and buttons are enabled
  874. if (!clineAsk || !enableButtons) return
  875. const autoApprove = async () => {
  876. if (isAutoApproved(lastMessage)) {
  877. // Add delay for write operations
  878. if (lastMessage?.ask === "tool" && isWriteToolAction(lastMessage)) {
  879. await new Promise((resolve) => setTimeout(resolve, writeDelayMs))
  880. }
  881. handlePrimaryButtonClick()
  882. }
  883. }
  884. autoApprove()
  885. }, [
  886. clineAsk,
  887. enableButtons,
  888. handlePrimaryButtonClick,
  889. alwaysAllowBrowser,
  890. alwaysAllowReadOnly,
  891. alwaysAllowWrite,
  892. alwaysAllowExecute,
  893. alwaysAllowMcp,
  894. messages,
  895. allowedCommands,
  896. mcpServers,
  897. isAutoApproved,
  898. lastMessage,
  899. writeDelayMs,
  900. isWriteToolAction,
  901. ])
  902. return (
  903. <div
  904. style={{
  905. position: "fixed",
  906. top: 0,
  907. left: 0,
  908. right: 0,
  909. bottom: 0,
  910. display: isHidden ? "none" : "flex",
  911. flexDirection: "column",
  912. overflow: "hidden",
  913. }}>
  914. {task ? (
  915. <TaskHeader
  916. task={task}
  917. tokensIn={apiMetrics.totalTokensIn}
  918. tokensOut={apiMetrics.totalTokensOut}
  919. doesModelSupportPromptCache={selectedModelInfo.supportsPromptCache}
  920. cacheWrites={apiMetrics.totalCacheWrites}
  921. cacheReads={apiMetrics.totalCacheReads}
  922. totalCost={apiMetrics.totalCost}
  923. contextTokens={apiMetrics.contextTokens}
  924. onClose={handleTaskCloseButtonClick}
  925. />
  926. ) : (
  927. <div
  928. style={{
  929. flex: "1 1 0", // flex-grow: 1, flex-shrink: 1, flex-basis: 0
  930. minHeight: 0,
  931. overflowY: "auto",
  932. display: "flex",
  933. flexDirection: "column",
  934. paddingBottom: "10px",
  935. }}>
  936. {showAnnouncement && <Announcement version={version} hideAnnouncement={hideAnnouncement} />}
  937. <div style={{ padding: "0 20px", flexShrink: 0 }}>
  938. <h2>What can Roo do for you?</h2>
  939. <p>
  940. Thanks to the latest breakthroughs in agentic coding capabilities, I can handle complex
  941. software development tasks step-by-step. With tools that let me create & edit files, explore
  942. complex projects, use the browser, and execute terminal commands (after you grant
  943. permission), I can assist you in ways that go beyond code completion or tech support. I can
  944. even use MCP to create new tools and extend my own capabilities.
  945. </p>
  946. </div>
  947. {taskHistory.length > 0 && <HistoryPreview showHistoryView={showHistoryView} />}
  948. </div>
  949. )}
  950. {/*
  951. // Flex layout explanation:
  952. // 1. Content div above uses flex: "1 1 0" to:
  953. // - Grow to fill available space (flex-grow: 1)
  954. // - Shrink when AutoApproveMenu needs space (flex-shrink: 1)
  955. // - Start from zero size (flex-basis: 0) to ensure proper distribution
  956. // minHeight: 0 allows it to shrink below its content height
  957. //
  958. // 2. AutoApproveMenu uses flex: "0 1 auto" to:
  959. // - Not grow beyond its content (flex-grow: 0)
  960. // - Shrink when viewport is small (flex-shrink: 1)
  961. // - Use its content size as basis (flex-basis: auto)
  962. // This ensures it takes its natural height when there's space
  963. // but becomes scrollable when the viewport is too small
  964. */}
  965. {!task && (
  966. <AutoApproveMenu
  967. style={{
  968. marginBottom: -2,
  969. flex: "0 1 auto", // flex-grow: 0, flex-shrink: 1, flex-basis: auto
  970. minHeight: 0,
  971. }}
  972. />
  973. )}
  974. {task && (
  975. <>
  976. <div style={{ flexGrow: 1, display: "flex" }} ref={scrollContainerRef}>
  977. <Virtuoso
  978. ref={virtuosoRef}
  979. key={task.ts} // trick to make sure virtuoso re-renders when task changes, and we use initialTopMostItemIndex to start at the bottom
  980. className="scrollable"
  981. style={{
  982. flexGrow: 1,
  983. overflowY: "scroll", // always show scrollbar
  984. }}
  985. components={{
  986. Footer: () => <div style={{ height: 5 }} />, // Add empty padding at the bottom
  987. }}
  988. // increasing top by 3_000 to prevent jumping around when user collapses a row
  989. increaseViewportBy={{ top: 3_000, bottom: Number.MAX_SAFE_INTEGER }} // hack to make sure the last message is always rendered to get truly perfect scroll to bottom animation when new messages are added (Number.MAX_SAFE_INTEGER is safe for arithmetic operations, which is all virtuoso uses this value for in src/sizeRangeSystem.ts)
  990. data={groupedMessages} // messages is the raw format returned by extension, modifiedMessages is the manipulated structure that combines certain messages of related type, and visibleMessages is the filtered structure that removes messages that should not be rendered
  991. itemContent={itemContent}
  992. atBottomStateChange={(isAtBottom) => {
  993. setIsAtBottom(isAtBottom)
  994. if (isAtBottom) {
  995. disableAutoScrollRef.current = false
  996. }
  997. setShowScrollToBottom(disableAutoScrollRef.current && !isAtBottom)
  998. }}
  999. atBottomThreshold={10} // anything lower causes issues with followOutput
  1000. initialTopMostItemIndex={groupedMessages.length - 1}
  1001. />
  1002. </div>
  1003. <AutoApproveMenu />
  1004. {showScrollToBottom ? (
  1005. <div
  1006. style={{
  1007. display: "flex",
  1008. padding: "10px 15px 0px 15px",
  1009. }}>
  1010. <ScrollToBottomButton
  1011. onClick={() => {
  1012. scrollToBottomSmooth()
  1013. disableAutoScrollRef.current = false
  1014. }}
  1015. title="Scroll to bottom of chat">
  1016. <span className="codicon codicon-chevron-down" style={{ fontSize: "18px" }}></span>
  1017. </ScrollToBottomButton>
  1018. </div>
  1019. ) : (
  1020. <div
  1021. style={{
  1022. opacity:
  1023. primaryButtonText || secondaryButtonText || isStreaming
  1024. ? enableButtons || (isStreaming && !didClickCancel)
  1025. ? 1
  1026. : 0.5
  1027. : 0,
  1028. display: "flex",
  1029. padding: `${primaryButtonText || secondaryButtonText || isStreaming ? "10" : "0"}px 15px 0px 15px`,
  1030. }}>
  1031. {primaryButtonText && !isStreaming && (
  1032. <VSCodeButton
  1033. appearance="primary"
  1034. disabled={!enableButtons}
  1035. style={{
  1036. flex: secondaryButtonText ? 1 : 2,
  1037. marginRight: secondaryButtonText ? "6px" : "0",
  1038. }}
  1039. title={
  1040. primaryButtonText === "Retry"
  1041. ? "Try the operation again"
  1042. : primaryButtonText === "Save"
  1043. ? "Save the file changes"
  1044. : primaryButtonText === "Approve"
  1045. ? "Approve this action"
  1046. : primaryButtonText === "Run Command"
  1047. ? "Execute this command"
  1048. : primaryButtonText === "Start New Task"
  1049. ? "Begin a new task"
  1050. : primaryButtonText === "Resume Task"
  1051. ? "Continue the current task"
  1052. : primaryButtonText === "Proceed Anyways"
  1053. ? "Continue despite warnings"
  1054. : primaryButtonText === "Proceed While Running"
  1055. ? "Continue while command executes"
  1056. : undefined
  1057. }
  1058. onClick={(e) => handlePrimaryButtonClick(inputValue, selectedImages)}>
  1059. {primaryButtonText}
  1060. </VSCodeButton>
  1061. )}
  1062. {(secondaryButtonText || isStreaming) && (
  1063. <VSCodeButton
  1064. appearance="secondary"
  1065. disabled={!enableButtons && !(isStreaming && !didClickCancel)}
  1066. style={{
  1067. flex: isStreaming ? 2 : 1,
  1068. marginLeft: isStreaming ? 0 : "6px",
  1069. }}
  1070. title={
  1071. isStreaming
  1072. ? "Cancel the current operation"
  1073. : secondaryButtonText === "Start New Task"
  1074. ? "Begin a new task"
  1075. : secondaryButtonText === "Reject"
  1076. ? "Reject this action"
  1077. : secondaryButtonText === "Terminate"
  1078. ? "End the current task"
  1079. : undefined
  1080. }
  1081. onClick={(e) => handleSecondaryButtonClick(inputValue, selectedImages)}>
  1082. {isStreaming ? "Cancel" : secondaryButtonText}
  1083. </VSCodeButton>
  1084. )}
  1085. </div>
  1086. )}
  1087. </>
  1088. )}
  1089. <ChatTextArea
  1090. ref={textAreaRef}
  1091. inputValue={inputValue}
  1092. setInputValue={setInputValue}
  1093. textAreaDisabled={textAreaDisabled}
  1094. placeholderText={placeholderText}
  1095. selectedImages={selectedImages}
  1096. setSelectedImages={setSelectedImages}
  1097. onSend={() => handleSendMessage(inputValue, selectedImages)}
  1098. onSelectImages={selectImages}
  1099. shouldDisableImages={shouldDisableImages}
  1100. onHeightChange={() => {
  1101. if (isAtBottom) {
  1102. scrollToBottomAuto()
  1103. }
  1104. }}
  1105. mode={mode}
  1106. setMode={setMode}
  1107. />
  1108. <div id="chat-view-portal" />
  1109. </div>
  1110. )
  1111. }
  1112. const ScrollToBottomButton = styled.div`
  1113. background-color: color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 55%, transparent);
  1114. border-radius: 3px;
  1115. overflow: hidden;
  1116. cursor: pointer;
  1117. display: flex;
  1118. justify-content: center;
  1119. align-items: center;
  1120. flex: 1;
  1121. height: 25px;
  1122. &:hover {
  1123. background-color: color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 90%, transparent);
  1124. }
  1125. &:active {
  1126. background-color: color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 70%, transparent);
  1127. }
  1128. `
  1129. export default ChatView