ChatView.tsx 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  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 "task":
  217. case "error":
  218. case "api_req_finished":
  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 (lastApiReqStarted && lastApiReqStarted.text != null && lastApiReqStarted.say === "api_req_started") {
  265. const cost = JSON.parse(lastApiReqStarted.text).cost
  266. if (cost === undefined) {
  267. // api request has not finished yet
  268. return true
  269. }
  270. }
  271. }
  272. return false
  273. }, [modifiedMessages, clineAsk, enableButtons, primaryButtonText])
  274. const handleSendMessage = useCallback(
  275. (text: string, images: string[]) => {
  276. text = text.trim()
  277. if (text || images.length > 0) {
  278. if (messages.length === 0) {
  279. vscode.postMessage({ type: "newTask", text, images })
  280. } else if (clineAsk) {
  281. switch (clineAsk) {
  282. case "followup":
  283. case "tool":
  284. case "browser_action_launch":
  285. case "command": // user can provide feedback to a tool or command use
  286. case "command_output": // user can send input to command stdin
  287. case "use_mcp_server":
  288. case "completion_result": // if this happens then the user has feedback for the completion result
  289. case "resume_task":
  290. case "resume_completed_task":
  291. case "mistake_limit_reached":
  292. vscode.postMessage({
  293. type: "askResponse",
  294. askResponse: "messageResponse",
  295. text,
  296. images,
  297. })
  298. break
  299. // there is no other case that a textfield should be enabled
  300. }
  301. }
  302. // Only reset message-specific state, preserving mode
  303. setInputValue("")
  304. setTextAreaDisabled(true)
  305. setSelectedImages([])
  306. setClineAsk(undefined)
  307. setEnableButtons(false)
  308. // Do not reset mode here as it should persist
  309. // setPrimaryButtonText(undefined)
  310. // setSecondaryButtonText(undefined)
  311. disableAutoScrollRef.current = false
  312. }
  313. },
  314. [messages.length, clineAsk],
  315. )
  316. const startNewTask = useCallback(() => {
  317. vscode.postMessage({ type: "clearTask" })
  318. }, [])
  319. /*
  320. 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.
  321. */
  322. const handlePrimaryButtonClick = useCallback(() => {
  323. switch (clineAsk) {
  324. case "api_req_failed":
  325. case "command":
  326. case "command_output":
  327. case "tool":
  328. case "browser_action_launch":
  329. case "use_mcp_server":
  330. case "resume_task":
  331. case "mistake_limit_reached":
  332. vscode.postMessage({ type: "askResponse", askResponse: "yesButtonClicked" })
  333. break
  334. case "completion_result":
  335. case "resume_completed_task":
  336. // extension waiting for feedback. but we can just present a new task button
  337. startNewTask()
  338. break
  339. }
  340. setTextAreaDisabled(true)
  341. setClineAsk(undefined)
  342. setEnableButtons(false)
  343. disableAutoScrollRef.current = false
  344. }, [clineAsk, startNewTask])
  345. const handleSecondaryButtonClick = useCallback(() => {
  346. if (isStreaming) {
  347. vscode.postMessage({ type: "cancelTask" })
  348. setDidClickCancel(true)
  349. return
  350. }
  351. switch (clineAsk) {
  352. case "api_req_failed":
  353. case "mistake_limit_reached":
  354. case "resume_task":
  355. startNewTask()
  356. break
  357. case "command":
  358. case "tool":
  359. case "browser_action_launch":
  360. case "use_mcp_server":
  361. // responds to the API with a "This operation failed" and lets it try again
  362. vscode.postMessage({ type: "askResponse", askResponse: "noButtonClicked" })
  363. break
  364. }
  365. setTextAreaDisabled(true)
  366. setClineAsk(undefined)
  367. setEnableButtons(false)
  368. disableAutoScrollRef.current = false
  369. }, [clineAsk, startNewTask, isStreaming])
  370. const handleTaskCloseButtonClick = useCallback(() => {
  371. startNewTask()
  372. }, [startNewTask])
  373. const { selectedModelInfo } = useMemo(() => {
  374. return normalizeApiConfiguration(apiConfiguration)
  375. }, [apiConfiguration])
  376. const selectImages = useCallback(() => {
  377. vscode.postMessage({ type: "selectImages" })
  378. }, [])
  379. const shouldDisableImages =
  380. !selectedModelInfo.supportsImages || textAreaDisabled || selectedImages.length >= MAX_IMAGES_PER_MESSAGE
  381. const handleMessage = useCallback(
  382. (e: MessageEvent) => {
  383. const message: ExtensionMessage = e.data
  384. switch (message.type) {
  385. case "action":
  386. switch (message.action!) {
  387. case "didBecomeVisible":
  388. if (!isHidden && !textAreaDisabled && !enableButtons) {
  389. textAreaRef.current?.focus()
  390. }
  391. break
  392. }
  393. break
  394. case "selectedImages":
  395. const newImages = message.images ?? []
  396. if (newImages.length > 0) {
  397. setSelectedImages((prevImages) =>
  398. [...prevImages, ...newImages].slice(0, MAX_IMAGES_PER_MESSAGE),
  399. )
  400. }
  401. break
  402. case "invoke":
  403. switch (message.invoke!) {
  404. case "sendMessage":
  405. handleSendMessage(message.text ?? "", message.images ?? [])
  406. break
  407. case "primaryButtonClick":
  408. handlePrimaryButtonClick()
  409. break
  410. case "secondaryButtonClick":
  411. handleSecondaryButtonClick()
  412. break
  413. }
  414. }
  415. // 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.
  416. },
  417. [
  418. isHidden,
  419. textAreaDisabled,
  420. enableButtons,
  421. handleSendMessage,
  422. handlePrimaryButtonClick,
  423. handleSecondaryButtonClick,
  424. ],
  425. )
  426. useEvent("message", handleMessage)
  427. useMount(() => {
  428. // NOTE: the vscode window needs to be focused for this to work
  429. textAreaRef.current?.focus()
  430. })
  431. useEffect(() => {
  432. const timer = setTimeout(() => {
  433. if (!isHidden && !textAreaDisabled && !enableButtons) {
  434. textAreaRef.current?.focus()
  435. }
  436. }, 50)
  437. return () => {
  438. clearTimeout(timer)
  439. }
  440. }, [isHidden, textAreaDisabled, enableButtons])
  441. const visibleMessages = useMemo(() => {
  442. return modifiedMessages.filter((message) => {
  443. switch (message.ask) {
  444. case "completion_result":
  445. // 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.
  446. if (message.text === "") {
  447. return false
  448. }
  449. break
  450. case "api_req_failed": // this message is used to update the latest api_req_started that the request failed
  451. case "resume_task":
  452. case "resume_completed_task":
  453. return false
  454. }
  455. switch (message.say) {
  456. case "api_req_finished": // combineApiRequests removes this from modifiedMessages anyways
  457. case "api_req_retried": // this message is used to update the latest api_req_started that the request was retried
  458. return false
  459. case "api_req_retry_delayed":
  460. // Only show the retry message if it's the last message
  461. return message === modifiedMessages.at(-1)
  462. case "text":
  463. // 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)
  464. if ((message.text ?? "") === "" && (message.images?.length ?? 0) === 0) {
  465. return false
  466. }
  467. break
  468. case "mcp_server_request_started":
  469. return false
  470. }
  471. return true
  472. })
  473. }, [modifiedMessages])
  474. const isReadOnlyToolAction = useCallback((message: ClineMessage | undefined) => {
  475. if (message?.type === "ask") {
  476. if (!message.text) {
  477. return true
  478. }
  479. const tool = JSON.parse(message.text)
  480. return [
  481. "readFile",
  482. "listFiles",
  483. "listFilesTopLevel",
  484. "listFilesRecursive",
  485. "listCodeDefinitionNames",
  486. "searchFiles",
  487. ].includes(tool.tool)
  488. }
  489. return false
  490. }, [])
  491. const isWriteToolAction = useCallback((message: ClineMessage | undefined) => {
  492. if (message?.type === "ask") {
  493. if (!message.text) {
  494. return true
  495. }
  496. const tool = JSON.parse(message.text)
  497. return ["editedExistingFile", "appliedDiff", "newFileCreated"].includes(tool.tool)
  498. }
  499. return false
  500. }, [])
  501. const isMcpToolAlwaysAllowed = useCallback(
  502. (message: ClineMessage | undefined) => {
  503. if (message?.type === "ask" && message.ask === "use_mcp_server") {
  504. if (!message.text) {
  505. return true
  506. }
  507. const mcpServerUse = JSON.parse(message.text) as { type: string; serverName: string; toolName: string }
  508. if (mcpServerUse.type === "use_mcp_tool") {
  509. const server = mcpServers?.find((s: McpServer) => s.name === mcpServerUse.serverName)
  510. const tool = server?.tools?.find((t: McpTool) => t.name === mcpServerUse.toolName)
  511. return tool?.alwaysAllow || false
  512. }
  513. }
  514. return false
  515. },
  516. [mcpServers],
  517. )
  518. // Check if a command message is allowed
  519. const isAllowedCommand = useCallback(
  520. (message: ClineMessage | undefined): boolean => {
  521. if (message?.type !== "ask") return false
  522. return validateCommand(message.text || "", allowedCommands || [])
  523. },
  524. [allowedCommands],
  525. )
  526. const isAutoApproved = useCallback(
  527. (message: ClineMessage | undefined) => {
  528. if (!autoApprovalEnabled || !message || message.type !== "ask") return false
  529. return (
  530. (alwaysAllowBrowser && message.ask === "browser_action_launch") ||
  531. (alwaysAllowReadOnly && message.ask === "tool" && isReadOnlyToolAction(message)) ||
  532. (alwaysAllowWrite && message.ask === "tool" && isWriteToolAction(message)) ||
  533. (alwaysAllowExecute && message.ask === "command" && isAllowedCommand(message)) ||
  534. (alwaysAllowMcp && message.ask === "use_mcp_server" && isMcpToolAlwaysAllowed(message)) ||
  535. (alwaysAllowModeSwitch &&
  536. message.ask === "tool" &&
  537. JSON.parse(message.text || "{}")?.tool === "switchMode")
  538. )
  539. },
  540. [
  541. autoApprovalEnabled,
  542. alwaysAllowBrowser,
  543. alwaysAllowReadOnly,
  544. isReadOnlyToolAction,
  545. alwaysAllowWrite,
  546. isWriteToolAction,
  547. alwaysAllowExecute,
  548. isAllowedCommand,
  549. alwaysAllowMcp,
  550. isMcpToolAlwaysAllowed,
  551. alwaysAllowModeSwitch,
  552. ],
  553. )
  554. useEffect(() => {
  555. // Only execute when isStreaming changes from true to false
  556. if (wasStreaming && !isStreaming && lastMessage) {
  557. // Play appropriate sound based on lastMessage content
  558. if (lastMessage.type === "ask") {
  559. // Don't play sounds for auto-approved actions
  560. if (!isAutoApproved(lastMessage)) {
  561. switch (lastMessage.ask) {
  562. case "api_req_failed":
  563. case "mistake_limit_reached":
  564. playSound("progress_loop")
  565. break
  566. case "followup":
  567. if (!lastMessage.partial) {
  568. playSound("notification")
  569. }
  570. break
  571. case "tool":
  572. case "browser_action_launch":
  573. case "resume_task":
  574. case "use_mcp_server":
  575. playSound("notification")
  576. break
  577. case "completion_result":
  578. case "resume_completed_task":
  579. playSound("celebration")
  580. break
  581. }
  582. }
  583. }
  584. }
  585. // Update previous value
  586. setWasStreaming(isStreaming)
  587. }, [isStreaming, lastMessage, wasStreaming, isAutoApproved])
  588. const isBrowserSessionMessage = (message: ClineMessage): boolean => {
  589. // which of visible messages are browser session messages, see above
  590. if (message.type === "ask") {
  591. return ["browser_action_launch"].includes(message.ask!)
  592. }
  593. if (message.type === "say") {
  594. return ["api_req_started", "text", "browser_action", "browser_action_result"].includes(message.say!)
  595. }
  596. return false
  597. }
  598. const groupedMessages = useMemo(() => {
  599. const result: (ClineMessage | ClineMessage[])[] = []
  600. let currentGroup: ClineMessage[] = []
  601. let isInBrowserSession = false
  602. const endBrowserSession = () => {
  603. if (currentGroup.length > 0) {
  604. result.push([...currentGroup])
  605. currentGroup = []
  606. isInBrowserSession = false
  607. }
  608. }
  609. visibleMessages.forEach((message) => {
  610. if (message.ask === "browser_action_launch") {
  611. // complete existing browser session if any
  612. endBrowserSession()
  613. // start new
  614. isInBrowserSession = true
  615. currentGroup.push(message)
  616. } else if (isInBrowserSession) {
  617. // end session if api_req_started is cancelled
  618. if (message.say === "api_req_started") {
  619. // 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
  620. const lastApiReqStarted = [...currentGroup].reverse().find((m) => m.say === "api_req_started")
  621. if (lastApiReqStarted?.text != null) {
  622. const info = JSON.parse(lastApiReqStarted.text)
  623. const isCancelled = info.cancelReason != null
  624. if (isCancelled) {
  625. endBrowserSession()
  626. result.push(message)
  627. return
  628. }
  629. }
  630. }
  631. if (isBrowserSessionMessage(message)) {
  632. currentGroup.push(message)
  633. // Check if this is a close action
  634. if (message.say === "browser_action") {
  635. const browserAction = JSON.parse(message.text || "{}") as ClineSayBrowserAction
  636. if (browserAction.action === "close") {
  637. endBrowserSession()
  638. }
  639. }
  640. } else {
  641. // complete existing browser session if any
  642. endBrowserSession()
  643. result.push(message)
  644. }
  645. } else {
  646. result.push(message)
  647. }
  648. })
  649. // Handle case where browser session is the last group
  650. if (currentGroup.length > 0) {
  651. result.push([...currentGroup])
  652. }
  653. return result
  654. }, [visibleMessages])
  655. // scrolling
  656. const scrollToBottomSmooth = useMemo(
  657. () =>
  658. debounce(
  659. () => {
  660. virtuosoRef.current?.scrollTo({
  661. top: Number.MAX_SAFE_INTEGER,
  662. behavior: "smooth",
  663. })
  664. },
  665. 10,
  666. { immediate: true },
  667. ),
  668. [],
  669. )
  670. const scrollToBottomAuto = useCallback(() => {
  671. virtuosoRef.current?.scrollTo({
  672. top: Number.MAX_SAFE_INTEGER,
  673. behavior: "auto", // instant causes crash
  674. })
  675. }, [])
  676. // scroll when user toggles certain rows
  677. const toggleRowExpansion = useCallback(
  678. (ts: number) => {
  679. const isCollapsing = expandedRows[ts] ?? false
  680. const lastGroup = groupedMessages.at(-1)
  681. const isLast = Array.isArray(lastGroup) ? lastGroup[0].ts === ts : lastGroup?.ts === ts
  682. const secondToLastGroup = groupedMessages.at(-2)
  683. const isSecondToLast = Array.isArray(secondToLastGroup)
  684. ? secondToLastGroup[0].ts === ts
  685. : secondToLastGroup?.ts === ts
  686. const isLastCollapsedApiReq =
  687. isLast &&
  688. !Array.isArray(lastGroup) && // Make sure it's not a browser session group
  689. lastGroup?.say === "api_req_started" &&
  690. !expandedRows[lastGroup.ts]
  691. setExpandedRows((prev) => ({
  692. ...prev,
  693. [ts]: !prev[ts],
  694. }))
  695. // disable auto scroll when user expands row
  696. if (!isCollapsing) {
  697. disableAutoScrollRef.current = true
  698. }
  699. if (isCollapsing && isAtBottom) {
  700. const timer = setTimeout(() => {
  701. scrollToBottomAuto()
  702. }, 0)
  703. return () => clearTimeout(timer)
  704. } else if (isLast || isSecondToLast) {
  705. if (isCollapsing) {
  706. if (isSecondToLast && !isLastCollapsedApiReq) {
  707. return
  708. }
  709. const timer = setTimeout(() => {
  710. scrollToBottomAuto()
  711. }, 0)
  712. return () => clearTimeout(timer)
  713. } else {
  714. const timer = setTimeout(() => {
  715. virtuosoRef.current?.scrollToIndex({
  716. index: groupedMessages.length - (isLast ? 1 : 2),
  717. align: "start",
  718. })
  719. }, 0)
  720. return () => clearTimeout(timer)
  721. }
  722. }
  723. },
  724. [groupedMessages, expandedRows, scrollToBottomAuto, isAtBottom],
  725. )
  726. const handleRowHeightChange = useCallback(
  727. (isTaller: boolean) => {
  728. if (!disableAutoScrollRef.current) {
  729. if (isTaller) {
  730. scrollToBottomSmooth()
  731. } else {
  732. setTimeout(() => {
  733. scrollToBottomAuto()
  734. }, 0)
  735. }
  736. }
  737. },
  738. [scrollToBottomSmooth, scrollToBottomAuto],
  739. )
  740. useEffect(() => {
  741. if (!disableAutoScrollRef.current) {
  742. setTimeout(() => {
  743. scrollToBottomSmooth()
  744. }, 50)
  745. // return () => clearTimeout(timer) // dont cleanup since if visibleMessages.length changes it cancels.
  746. }
  747. }, [groupedMessages.length, scrollToBottomSmooth])
  748. const handleWheel = useCallback((event: Event) => {
  749. const wheelEvent = event as WheelEvent
  750. if (wheelEvent.deltaY && wheelEvent.deltaY < 0) {
  751. if (scrollContainerRef.current?.contains(wheelEvent.target as Node)) {
  752. // user scrolled up
  753. disableAutoScrollRef.current = true
  754. }
  755. }
  756. }, [])
  757. useEvent("wheel", handleWheel, window, { passive: true }) // passive improves scrolling performance
  758. const placeholderText = useMemo(() => {
  759. const baseText = task ? "Type a message..." : "Type your task here..."
  760. const contextText = "(@ to add context"
  761. const imageText = shouldDisableImages ? "" : ", hold shift to drag in images"
  762. const helpText = imageText ? `\n${contextText}${imageText})` : `\n${contextText})`
  763. return baseText + helpText
  764. }, [task, shouldDisableImages])
  765. const itemContent = useCallback(
  766. (index: number, messageOrGroup: ClineMessage | ClineMessage[]) => {
  767. // browser session group
  768. if (Array.isArray(messageOrGroup)) {
  769. return (
  770. <BrowserSessionRow
  771. messages={messageOrGroup}
  772. isLast={index === groupedMessages.length - 1}
  773. lastModifiedMessage={modifiedMessages.at(-1)}
  774. onHeightChange={handleRowHeightChange}
  775. isStreaming={isStreaming}
  776. // Pass handlers for each message in the group
  777. isExpanded={(messageTs: number) => expandedRows[messageTs] ?? false}
  778. onToggleExpand={(messageTs: number) => {
  779. setExpandedRows((prev) => ({
  780. ...prev,
  781. [messageTs]: !prev[messageTs],
  782. }))
  783. }}
  784. />
  785. )
  786. }
  787. // regular message
  788. return (
  789. <ChatRow
  790. key={messageOrGroup.ts}
  791. message={messageOrGroup}
  792. isExpanded={expandedRows[messageOrGroup.ts] || false}
  793. onToggleExpand={() => toggleRowExpansion(messageOrGroup.ts)}
  794. lastModifiedMessage={modifiedMessages.at(-1)}
  795. isLast={index === groupedMessages.length - 1}
  796. onHeightChange={handleRowHeightChange}
  797. isStreaming={isStreaming}
  798. />
  799. )
  800. },
  801. [
  802. expandedRows,
  803. modifiedMessages,
  804. groupedMessages.length,
  805. handleRowHeightChange,
  806. isStreaming,
  807. toggleRowExpansion,
  808. ],
  809. )
  810. useEffect(() => {
  811. // Only proceed if we have an ask and buttons are enabled
  812. if (!clineAsk || !enableButtons) return
  813. const autoApprove = async () => {
  814. if (isAutoApproved(lastMessage)) {
  815. // Add delay for write operations
  816. if (lastMessage?.ask === "tool" && isWriteToolAction(lastMessage)) {
  817. await new Promise((resolve) => setTimeout(resolve, writeDelayMs))
  818. }
  819. handlePrimaryButtonClick()
  820. }
  821. }
  822. autoApprove()
  823. }, [
  824. clineAsk,
  825. enableButtons,
  826. handlePrimaryButtonClick,
  827. alwaysAllowBrowser,
  828. alwaysAllowReadOnly,
  829. alwaysAllowWrite,
  830. alwaysAllowExecute,
  831. alwaysAllowMcp,
  832. messages,
  833. allowedCommands,
  834. mcpServers,
  835. isAutoApproved,
  836. lastMessage,
  837. writeDelayMs,
  838. isWriteToolAction,
  839. ])
  840. return (
  841. <div
  842. style={{
  843. position: "fixed",
  844. top: 0,
  845. left: 0,
  846. right: 0,
  847. bottom: 0,
  848. display: isHidden ? "none" : "flex",
  849. flexDirection: "column",
  850. overflow: "hidden",
  851. }}>
  852. {task ? (
  853. <TaskHeader
  854. task={task}
  855. tokensIn={apiMetrics.totalTokensIn}
  856. tokensOut={apiMetrics.totalTokensOut}
  857. doesModelSupportPromptCache={selectedModelInfo.supportsPromptCache}
  858. cacheWrites={apiMetrics.totalCacheWrites}
  859. cacheReads={apiMetrics.totalCacheReads}
  860. totalCost={apiMetrics.totalCost}
  861. contextTokens={apiMetrics.contextTokens}
  862. onClose={handleTaskCloseButtonClick}
  863. />
  864. ) : (
  865. <div
  866. style={{
  867. flex: "1 1 0", // flex-grow: 1, flex-shrink: 1, flex-basis: 0
  868. minHeight: 0,
  869. overflowY: "auto",
  870. display: "flex",
  871. flexDirection: "column",
  872. paddingBottom: "10px",
  873. }}>
  874. {showAnnouncement && <Announcement version={version} hideAnnouncement={hideAnnouncement} />}
  875. <div style={{ padding: "0 20px", flexShrink: 0 }}>
  876. <h2>What can I do for you?</h2>
  877. <p>
  878. Thanks to the latest breakthroughs in agentic coding capabilities, I can handle complex
  879. software development tasks step-by-step. With tools that let me create & edit files, explore
  880. complex projects, use the browser, and execute terminal commands (after you grant
  881. permission), I can assist you in ways that go beyond code completion or tech support. I can
  882. even use MCP to create new tools and extend my own capabilities.
  883. </p>
  884. </div>
  885. {taskHistory.length > 0 && <HistoryPreview showHistoryView={showHistoryView} />}
  886. </div>
  887. )}
  888. {/*
  889. // Flex layout explanation:
  890. // 1. Content div above uses flex: "1 1 0" to:
  891. // - Grow to fill available space (flex-grow: 1)
  892. // - Shrink when AutoApproveMenu needs space (flex-shrink: 1)
  893. // - Start from zero size (flex-basis: 0) to ensure proper distribution
  894. // minHeight: 0 allows it to shrink below its content height
  895. //
  896. // 2. AutoApproveMenu uses flex: "0 1 auto" to:
  897. // - Not grow beyond its content (flex-grow: 0)
  898. // - Shrink when viewport is small (flex-shrink: 1)
  899. // - Use its content size as basis (flex-basis: auto)
  900. // This ensures it takes its natural height when there's space
  901. // but becomes scrollable when the viewport is too small
  902. */}
  903. {!task && (
  904. <AutoApproveMenu
  905. style={{
  906. marginBottom: -2,
  907. flex: "0 1 auto", // flex-grow: 0, flex-shrink: 1, flex-basis: auto
  908. minHeight: 0,
  909. }}
  910. />
  911. )}
  912. {task && (
  913. <>
  914. <div style={{ flexGrow: 1, display: "flex" }} ref={scrollContainerRef}>
  915. <Virtuoso
  916. ref={virtuosoRef}
  917. key={task.ts} // trick to make sure virtuoso re-renders when task changes, and we use initialTopMostItemIndex to start at the bottom
  918. className="scrollable"
  919. style={{
  920. flexGrow: 1,
  921. overflowY: "scroll", // always show scrollbar
  922. }}
  923. components={{
  924. Footer: () => <div style={{ height: 5 }} />, // Add empty padding at the bottom
  925. }}
  926. // increasing top by 3_000 to prevent jumping around when user collapses a row
  927. 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)
  928. 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
  929. itemContent={itemContent}
  930. atBottomStateChange={(isAtBottom) => {
  931. setIsAtBottom(isAtBottom)
  932. if (isAtBottom) {
  933. disableAutoScrollRef.current = false
  934. }
  935. setShowScrollToBottom(disableAutoScrollRef.current && !isAtBottom)
  936. }}
  937. atBottomThreshold={10} // anything lower causes issues with followOutput
  938. initialTopMostItemIndex={groupedMessages.length - 1}
  939. />
  940. </div>
  941. <AutoApproveMenu />
  942. {showScrollToBottom ? (
  943. <div
  944. style={{
  945. display: "flex",
  946. padding: "10px 15px 0px 15px",
  947. }}>
  948. <ScrollToBottomButton
  949. onClick={() => {
  950. scrollToBottomSmooth()
  951. disableAutoScrollRef.current = false
  952. }}>
  953. <span className="codicon codicon-chevron-down" style={{ fontSize: "18px" }}></span>
  954. </ScrollToBottomButton>
  955. </div>
  956. ) : (
  957. <div
  958. style={{
  959. opacity:
  960. primaryButtonText || secondaryButtonText || isStreaming
  961. ? enableButtons || (isStreaming && !didClickCancel)
  962. ? 1
  963. : 0.5
  964. : 0,
  965. display: "flex",
  966. padding: `${primaryButtonText || secondaryButtonText || isStreaming ? "10" : "0"}px 15px 0px 15px`,
  967. }}>
  968. {primaryButtonText && !isStreaming && (
  969. <VSCodeButton
  970. appearance="primary"
  971. disabled={!enableButtons}
  972. style={{
  973. flex: secondaryButtonText ? 1 : 2,
  974. marginRight: secondaryButtonText ? "6px" : "0",
  975. }}
  976. onClick={handlePrimaryButtonClick}>
  977. {primaryButtonText}
  978. </VSCodeButton>
  979. )}
  980. {(secondaryButtonText || isStreaming) && (
  981. <VSCodeButton
  982. appearance="secondary"
  983. disabled={!enableButtons && !(isStreaming && !didClickCancel)}
  984. style={{
  985. flex: isStreaming ? 2 : 1,
  986. marginLeft: isStreaming ? 0 : "6px",
  987. }}
  988. onClick={handleSecondaryButtonClick}>
  989. {isStreaming ? "Cancel" : secondaryButtonText}
  990. </VSCodeButton>
  991. )}
  992. </div>
  993. )}
  994. </>
  995. )}
  996. <ChatTextArea
  997. ref={textAreaRef}
  998. inputValue={inputValue}
  999. setInputValue={setInputValue}
  1000. textAreaDisabled={textAreaDisabled}
  1001. placeholderText={placeholderText}
  1002. selectedImages={selectedImages}
  1003. setSelectedImages={setSelectedImages}
  1004. onSend={() => handleSendMessage(inputValue, selectedImages)}
  1005. onSelectImages={selectImages}
  1006. shouldDisableImages={shouldDisableImages}
  1007. onHeightChange={() => {
  1008. if (isAtBottom) {
  1009. scrollToBottomAuto()
  1010. }
  1011. }}
  1012. mode={mode}
  1013. setMode={setMode}
  1014. />
  1015. </div>
  1016. )
  1017. }
  1018. const ScrollToBottomButton = styled.div`
  1019. background-color: color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 55%, transparent);
  1020. border-radius: 3px;
  1021. overflow: hidden;
  1022. cursor: pointer;
  1023. display: flex;
  1024. justify-content: center;
  1025. align-items: center;
  1026. flex: 1;
  1027. height: 25px;
  1028. &:hover {
  1029. background-color: color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 90%, transparent);
  1030. }
  1031. &:active {
  1032. background-color: color-mix(in srgb, var(--vscode-toolbar-hoverBackground) 70%, transparent);
  1033. }
  1034. `
  1035. export default ChatView