| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987 |
- import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"
- import { useDeepCompareEffect, useEvent, useMount } from "react-use"
- import debounce from "debounce"
- import { Virtuoso, type VirtuosoHandle } from "react-virtuoso"
- import removeMd from "remove-markdown"
- import { VSCodeButton, VSCodeLink } from "@vscode/webview-ui-toolkit/react"
- import useSound from "use-sound"
- import { LRUCache } from "lru-cache"
- import { Trans, useTranslation } from "react-i18next"
- import { useDebounceEffect } from "@src/utils/useDebounceEffect"
- import { appendImages } from "@src/utils/imageUtils"
- import type { ClineAsk, ClineMessage, McpServerUse } from "@roo-code/types"
- import { ClineSayBrowserAction, ClineSayTool, ExtensionMessage } from "@roo/ExtensionMessage"
- import { McpServer, McpTool } from "@roo/mcp"
- import { findLast } from "@roo/array"
- import { FollowUpData, SuggestionItem } from "@roo-code/types"
- import { combineApiRequests } from "@roo/combineApiRequests"
- import { combineCommandSequences } from "@roo/combineCommandSequences"
- import { getApiMetrics } from "@roo/getApiMetrics"
- import { AudioType } from "@roo/WebviewMessage"
- import { getAllModes } from "@roo/modes"
- import { ProfileValidator } from "@roo/ProfileValidator"
- import { getLatestTodo } from "@roo/todo"
- import { vscode } from "@src/utils/vscode"
- import {
- getCommandDecision,
- CommandDecision,
- findLongestPrefixMatch,
- parseCommand,
- } from "@src/utils/command-validation"
- import { useAppTranslation } from "@src/i18n/TranslationContext"
- import { useExtensionState } from "@src/context/ExtensionStateContext"
- import { useSelectedModel } from "@src/components/ui/hooks/useSelectedModel"
- import RooHero from "@src/components/welcome/RooHero"
- import RooTips from "@src/components/welcome/RooTips"
- import { StandardTooltip } from "@src/components/ui"
- import { useAutoApprovalState } from "@src/hooks/useAutoApprovalState"
- import { useAutoApprovalToggles } from "@src/hooks/useAutoApprovalToggles"
- import { CloudUpsellDialog } from "@src/components/cloud/CloudUpsellDialog"
- import TelemetryBanner from "../common/TelemetryBanner"
- import VersionIndicator from "../common/VersionIndicator"
- import HistoryPreview from "../history/HistoryPreview"
- import Announcement from "./Announcement"
- import BrowserSessionRow from "./BrowserSessionRow"
- import ChatRow from "./ChatRow"
- import { ChatTextArea } from "./ChatTextArea"
- import TaskHeader from "./TaskHeader"
- import SystemPromptWarning from "./SystemPromptWarning"
- import ProfileViolationWarning from "./ProfileViolationWarning"
- import { CheckpointWarning } from "./CheckpointWarning"
- import { QueuedMessages } from "./QueuedMessages"
- import DismissibleUpsell from "../common/DismissibleUpsell"
- import { useCloudUpsell } from "@src/hooks/useCloudUpsell"
- import { Cloud } from "lucide-react"
- export interface ChatViewProps {
- isHidden: boolean
- showAnnouncement: boolean
- hideAnnouncement: () => void
- }
- export interface ChatViewRef {
- acceptInput: () => void
- }
- export const MAX_IMAGES_PER_MESSAGE = 20 // This is the Anthropic limit.
- const isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0
- const ChatViewComponent: React.ForwardRefRenderFunction<ChatViewRef, ChatViewProps> = (
- { isHidden, showAnnouncement, hideAnnouncement },
- ref,
- ) => {
- const isMountedRef = useRef(true)
- const [audioBaseUri] = useState(() => {
- const w = window as any
- return w.AUDIO_BASE_URI || ""
- })
- const { t } = useAppTranslation()
- const { t: tSettings } = useTranslation("settings")
- const modeShortcutText = `${isMac ? "⌘" : "Ctrl"} + . ${t("chat:forNextMode")}, ${isMac ? "⌘" : "Ctrl"} + Shift + . ${t("chat:forPreviousMode")}`
- const {
- clineMessages: messages,
- currentTaskItem,
- currentTaskTodos,
- taskHistory,
- apiConfiguration,
- organizationAllowList,
- mcpServers,
- alwaysAllowBrowser,
- alwaysAllowReadOnly,
- alwaysAllowReadOnlyOutsideWorkspace,
- alwaysAllowWrite,
- alwaysAllowWriteOutsideWorkspace,
- alwaysAllowWriteProtected,
- alwaysAllowExecute,
- alwaysAllowMcp,
- allowedCommands,
- deniedCommands,
- writeDelayMs,
- followupAutoApproveTimeoutMs,
- mode,
- setMode,
- autoApprovalEnabled,
- alwaysAllowModeSwitch,
- alwaysAllowSubtasks,
- alwaysAllowFollowupQuestions,
- alwaysAllowUpdateTodoList,
- customModes,
- telemetrySetting,
- hasSystemPromptOverride,
- soundEnabled,
- soundVolume,
- cloudIsAuthenticated,
- messageQueue = [],
- } = useExtensionState()
- const messagesRef = useRef(messages)
- useEffect(() => {
- messagesRef.current = messages
- }, [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).
- const task = useMemo(() => messages.at(0), [messages])
- const latestTodos = useMemo(() => {
- // First check if we have initial todos from the state (for new subtasks)
- if (currentTaskTodos && currentTaskTodos.length > 0) {
- // Check if there are any todo updates in messages
- const messageBasedTodos = getLatestTodo(messages)
- // If there are message-based todos, they take precedence (user has updated them)
- if (messageBasedTodos && messageBasedTodos.length > 0) {
- return messageBasedTodos
- }
- // Otherwise use the initial todos from state
- return currentTaskTodos
- }
- // Fall back to extracting from messages
- return getLatestTodo(messages)
- }, [messages, currentTaskTodos])
- const modifiedMessages = useMemo(() => combineApiRequests(combineCommandSequences(messages.slice(1))), [messages])
- // Has to be after api_req_finished are all reduced into api_req_started messages.
- const apiMetrics = useMemo(() => getApiMetrics(modifiedMessages), [modifiedMessages])
- const [inputValue, setInputValue] = useState("")
- const inputValueRef = useRef(inputValue)
- const textAreaRef = useRef<HTMLTextAreaElement>(null)
- const [sendingDisabled, setSendingDisabled] = useState(false)
- const [selectedImages, setSelectedImages] = useState<string[]>([])
- // 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)
- const [clineAsk, setClineAsk] = useState<ClineAsk | undefined>(undefined)
- const [enableButtons, setEnableButtons] = useState<boolean>(false)
- const [primaryButtonText, setPrimaryButtonText] = useState<string | undefined>(undefined)
- const [secondaryButtonText, setSecondaryButtonText] = useState<string | undefined>(undefined)
- const [didClickCancel, setDidClickCancel] = useState(false)
- const virtuosoRef = useRef<VirtuosoHandle>(null)
- const [expandedRows, setExpandedRows] = useState<Record<number, boolean>>({})
- const prevExpandedRowsRef = useRef<Record<number, boolean>>()
- const scrollContainerRef = useRef<HTMLDivElement>(null)
- const disableAutoScrollRef = useRef(false)
- const [showScrollToBottom, setShowScrollToBottom] = useState(false)
- const [isAtBottom, setIsAtBottom] = useState(false)
- const lastTtsRef = useRef<string>("")
- const [wasStreaming, setWasStreaming] = useState<boolean>(false)
- const [checkpointWarning, setCheckpointWarning] = useState<
- { type: "WAIT_TIMEOUT" | "INIT_TIMEOUT"; timeout: number } | undefined
- >(undefined)
- const [isCondensing, setIsCondensing] = useState<boolean>(false)
- const [showAnnouncementModal, setShowAnnouncementModal] = useState(false)
- const everVisibleMessagesTsRef = useRef<LRUCache<number, boolean>>(
- new LRUCache({
- max: 100,
- ttl: 1000 * 60 * 5,
- }),
- )
- const autoApproveTimeoutRef = useRef<NodeJS.Timeout | null>(null)
- const userRespondedRef = useRef<boolean>(false)
- const [currentFollowUpTs, setCurrentFollowUpTs] = useState<number | null>(null)
- const clineAskRef = useRef(clineAsk)
- useEffect(() => {
- clineAskRef.current = clineAsk
- }, [clineAsk])
- const {
- isOpen: isUpsellOpen,
- openUpsell,
- closeUpsell,
- handleConnect,
- } = useCloudUpsell({
- autoOpenOnAuth: false,
- })
- // Keep inputValueRef in sync with inputValue state
- useEffect(() => {
- inputValueRef.current = inputValue
- }, [inputValue])
- useEffect(() => {
- isMountedRef.current = true
- return () => {
- isMountedRef.current = false
- }
- }, [])
- const isProfileDisabled = useMemo(
- () => !!apiConfiguration && !ProfileValidator.isProfileAllowed(apiConfiguration, organizationAllowList),
- [apiConfiguration, organizationAllowList],
- )
- // UI layout depends on the last 2 messages
- // (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
- const lastMessage = useMemo(() => messages.at(-1), [messages])
- const secondLastMessage = useMemo(() => messages.at(-2), [messages])
- // Setup sound hooks with use-sound
- const volume = typeof soundVolume === "number" ? soundVolume : 0.5
- const soundConfig = {
- volume,
- // useSound expects 'disabled' property, not 'soundEnabled'
- soundEnabled,
- }
- const getAudioUrl = (path: string) => `${audioBaseUri}/${path}`
- // Use the getAudioUrl helper function
- const [playNotification] = useSound(getAudioUrl("notification.wav"), soundConfig)
- const [playCelebration] = useSound(getAudioUrl("celebration.wav"), soundConfig)
- const [playProgressLoop] = useSound(getAudioUrl("progress_loop.wav"), soundConfig)
- function playSound(audioType: AudioType) {
- // Play the appropriate sound based on type
- // The disabled state is handled by the useSound hook configuration
- switch (audioType) {
- case "notification":
- playNotification()
- break
- case "celebration":
- playCelebration()
- break
- case "progress_loop":
- playProgressLoop()
- break
- default:
- console.warn(`Unknown audio type: ${audioType}`)
- }
- }
- function playTts(text: string) {
- vscode.postMessage({ type: "playTts", text })
- }
- useDeepCompareEffect(() => {
- // if last message is an ask, show user ask UI
- // 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.
- // basically as long as a task is active, the conversation history will be persisted
- if (lastMessage) {
- switch (lastMessage.type) {
- case "ask":
- // Reset user response flag when a new ask arrives to allow auto-approval
- userRespondedRef.current = false
- const isPartial = lastMessage.partial === true
- switch (lastMessage.ask) {
- case "api_req_failed":
- playSound("progress_loop")
- setSendingDisabled(true)
- setClineAsk("api_req_failed")
- setEnableButtons(true)
- setPrimaryButtonText(t("chat:retry.title"))
- setSecondaryButtonText(t("chat:startNewTask.title"))
- break
- case "mistake_limit_reached":
- playSound("progress_loop")
- setSendingDisabled(false)
- setClineAsk("mistake_limit_reached")
- setEnableButtons(true)
- setPrimaryButtonText(t("chat:proceedAnyways.title"))
- setSecondaryButtonText(t("chat:startNewTask.title"))
- break
- case "followup":
- if (!isPartial) {
- playSound("notification")
- }
- setSendingDisabled(isPartial)
- setClineAsk("followup")
- // setting enable buttons to `false` would trigger a focus grab when
- // the text area is enabled which is undesirable.
- // We have no buttons for this tool, so no problem having them "enabled"
- // to workaround this issue. See #1358.
- setEnableButtons(true)
- setPrimaryButtonText(undefined)
- setSecondaryButtonText(undefined)
- break
- case "tool":
- if (!isAutoApproved(lastMessage) && !isPartial) {
- playSound("notification")
- }
- setSendingDisabled(isPartial)
- setClineAsk("tool")
- setEnableButtons(!isPartial)
- const tool = JSON.parse(lastMessage.text || "{}") as ClineSayTool
- switch (tool.tool) {
- case "editedExistingFile":
- case "appliedDiff":
- case "newFileCreated":
- case "insertContent":
- case "generateImage":
- setPrimaryButtonText(t("chat:save.title"))
- setSecondaryButtonText(t("chat:reject.title"))
- break
- case "finishTask":
- setPrimaryButtonText(t("chat:completeSubtaskAndReturn"))
- setSecondaryButtonText(undefined)
- break
- case "readFile":
- if (tool.batchFiles && Array.isArray(tool.batchFiles)) {
- setPrimaryButtonText(t("chat:read-batch.approve.title"))
- setSecondaryButtonText(t("chat:read-batch.deny.title"))
- } else {
- setPrimaryButtonText(t("chat:approve.title"))
- setSecondaryButtonText(t("chat:reject.title"))
- }
- break
- default:
- setPrimaryButtonText(t("chat:approve.title"))
- setSecondaryButtonText(t("chat:reject.title"))
- break
- }
- break
- case "browser_action_launch":
- if (!isAutoApproved(lastMessage) && !isPartial) {
- playSound("notification")
- }
- setSendingDisabled(isPartial)
- setClineAsk("browser_action_launch")
- setEnableButtons(!isPartial)
- setPrimaryButtonText(t("chat:approve.title"))
- setSecondaryButtonText(t("chat:reject.title"))
- break
- case "command":
- if (!isAutoApproved(lastMessage) && !isPartial) {
- playSound("notification")
- }
- setSendingDisabled(isPartial)
- setClineAsk("command")
- setEnableButtons(!isPartial)
- setPrimaryButtonText(t("chat:runCommand.title"))
- setSecondaryButtonText(t("chat:reject.title"))
- break
- case "command_output":
- setSendingDisabled(false)
- setClineAsk("command_output")
- setEnableButtons(true)
- setPrimaryButtonText(t("chat:proceedWhileRunning.title"))
- setSecondaryButtonText(t("chat:killCommand.title"))
- break
- case "use_mcp_server":
- if (!isAutoApproved(lastMessage) && !isPartial) {
- playSound("notification")
- }
- setSendingDisabled(isPartial)
- setClineAsk("use_mcp_server")
- setEnableButtons(!isPartial)
- setPrimaryButtonText(t("chat:approve.title"))
- setSecondaryButtonText(t("chat:reject.title"))
- break
- case "completion_result":
- // extension waiting for feedback. but we can just present a new task button
- if (!isPartial) {
- playSound("celebration")
- }
- setSendingDisabled(isPartial)
- setClineAsk("completion_result")
- setEnableButtons(!isPartial)
- setPrimaryButtonText(t("chat:startNewTask.title"))
- setSecondaryButtonText(undefined)
- break
- case "resume_task":
- setSendingDisabled(false)
- setClineAsk("resume_task")
- setEnableButtons(true)
- setPrimaryButtonText(t("chat:resumeTask.title"))
- setSecondaryButtonText(t("chat:terminate.title"))
- setDidClickCancel(false) // special case where we reset the cancel button state
- break
- case "resume_completed_task":
- setSendingDisabled(false)
- setClineAsk("resume_completed_task")
- setEnableButtons(true)
- setPrimaryButtonText(t("chat:startNewTask.title"))
- setSecondaryButtonText(undefined)
- setDidClickCancel(false)
- break
- }
- break
- case "say":
- // Don't want to reset since there could be a "say" after
- // an "ask" while ask is waiting for response.
- switch (lastMessage.say) {
- case "api_req_retry_delayed":
- setSendingDisabled(true)
- break
- case "api_req_started":
- if (secondLastMessage?.ask === "command_output") {
- setSendingDisabled(true)
- setSelectedImages([])
- setClineAsk(undefined)
- setEnableButtons(false)
- }
- break
- case "api_req_finished":
- case "error":
- case "text":
- case "browser_action":
- case "browser_action_result":
- case "command_output":
- case "mcp_server_request_started":
- case "mcp_server_response":
- case "completion_result":
- break
- }
- break
- }
- }
- }, [lastMessage, secondLastMessage])
- useEffect(() => {
- if (messages.length === 0) {
- setSendingDisabled(false)
- setClineAsk(undefined)
- setEnableButtons(false)
- setPrimaryButtonText(undefined)
- setSecondaryButtonText(undefined)
- }
- }, [messages.length])
- useEffect(() => {
- // Reset UI states
- setExpandedRows({})
- everVisibleMessagesTsRef.current.clear() // Clear for new task
- setCurrentFollowUpTs(null) // Clear follow-up answered state for new task
- setIsCondensing(false) // Reset condensing state when switching tasks
- // Note: sendingDisabled is not reset here as it's managed by message effects
- // Clear any pending auto-approval timeout from previous task
- if (autoApproveTimeoutRef.current) {
- clearTimeout(autoApproveTimeoutRef.current)
- autoApproveTimeoutRef.current = null
- }
- // Reset user response flag for new task
- userRespondedRef.current = false
- }, [task?.ts])
- useEffect(() => {
- if (isHidden) {
- everVisibleMessagesTsRef.current.clear()
- }
- }, [isHidden])
- useEffect(() => {
- const cache = everVisibleMessagesTsRef.current
- return () => {
- cache.clear()
- }
- }, [])
- useEffect(() => {
- const prev = prevExpandedRowsRef.current
- let wasAnyRowExpandedByUser = false
- if (prev) {
- // Check if any row transitioned from false/undefined to true
- for (const [tsKey, isExpanded] of Object.entries(expandedRows)) {
- const ts = Number(tsKey)
- if (isExpanded && !(prev[ts] ?? false)) {
- wasAnyRowExpandedByUser = true
- break
- }
- }
- }
- if (wasAnyRowExpandedByUser) {
- disableAutoScrollRef.current = true
- }
- prevExpandedRowsRef.current = expandedRows // Store current state for next comparison
- }, [expandedRows])
- const isStreaming = useMemo(() => {
- // 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.
- const isLastAsk = !!modifiedMessages.at(-1)?.ask
- const isToolCurrentlyAsking =
- isLastAsk && clineAsk !== undefined && enableButtons && primaryButtonText !== undefined
- if (isToolCurrentlyAsking) {
- return false
- }
- const isLastMessagePartial = modifiedMessages.at(-1)?.partial === true
- if (isLastMessagePartial) {
- return true
- } else {
- const lastApiReqStarted = findLast(
- modifiedMessages,
- (message: ClineMessage) => message.say === "api_req_started",
- )
- if (
- lastApiReqStarted &&
- lastApiReqStarted.text !== null &&
- lastApiReqStarted.text !== undefined &&
- lastApiReqStarted.say === "api_req_started"
- ) {
- const cost = JSON.parse(lastApiReqStarted.text).cost
- if (cost === undefined) {
- return true // API request has not finished yet.
- }
- }
- }
- return false
- }, [modifiedMessages, clineAsk, enableButtons, primaryButtonText])
- const markFollowUpAsAnswered = useCallback(() => {
- const lastFollowUpMessage = messagesRef.current.findLast((msg: ClineMessage) => msg.ask === "followup")
- if (lastFollowUpMessage) {
- setCurrentFollowUpTs(lastFollowUpMessage.ts)
- }
- }, [])
- const handleChatReset = useCallback(() => {
- // Clear any pending auto-approval timeout
- if (autoApproveTimeoutRef.current) {
- clearTimeout(autoApproveTimeoutRef.current)
- autoApproveTimeoutRef.current = null
- }
- // Reset user response flag for new message
- userRespondedRef.current = false
- // Only reset message-specific state, preserving mode.
- setInputValue("")
- setSendingDisabled(true)
- setSelectedImages([])
- setClineAsk(undefined)
- setEnableButtons(false)
- // Do not reset mode here as it should persist.
- // setPrimaryButtonText(undefined)
- // setSecondaryButtonText(undefined)
- disableAutoScrollRef.current = false
- }, [])
- /**
- * Handles sending messages to the extension
- * @param text - The message text to send
- * @param images - Array of image data URLs to send with the message
- */
- const handleSendMessage = useCallback(
- (text: string, images: string[]) => {
- text = text.trim()
- if (text || images.length > 0) {
- // Queue message if:
- // - Task is busy (sendingDisabled)
- // - API request in progress (isStreaming)
- // - Queue has items (preserve message order during drain)
- if (sendingDisabled || isStreaming || messageQueue.length > 0) {
- try {
- console.log("queueMessage", text, images)
- vscode.postMessage({ type: "queueMessage", text, images })
- setInputValue("")
- setSelectedImages([])
- } catch (error) {
- console.error(
- `Failed to queue message: ${error instanceof Error ? error.message : String(error)}`,
- )
- }
- return
- }
- // Mark that user has responded - this prevents any pending auto-approvals.
- userRespondedRef.current = true
- if (messagesRef.current.length === 0) {
- vscode.postMessage({ type: "newTask", text, images })
- } else if (clineAskRef.current) {
- if (clineAskRef.current === "followup") {
- markFollowUpAsAnswered()
- }
- // Use clineAskRef.current
- switch (
- clineAskRef.current // Use clineAskRef.current
- ) {
- case "followup":
- case "tool":
- case "browser_action_launch":
- case "command": // User can provide feedback to a tool or command use.
- case "command_output": // User can send input to command stdin.
- case "use_mcp_server":
- case "completion_result": // If this happens then the user has feedback for the completion result.
- case "resume_task":
- case "resume_completed_task":
- case "mistake_limit_reached":
- vscode.postMessage({
- type: "askResponse",
- askResponse: "messageResponse",
- text,
- images,
- })
- break
- // There is no other case that a textfield should be enabled.
- }
- } else {
- // This is a new message in an ongoing task.
- vscode.postMessage({ type: "askResponse", askResponse: "messageResponse", text, images })
- }
- handleChatReset()
- }
- },
- [handleChatReset, markFollowUpAsAnswered, sendingDisabled, isStreaming, messageQueue.length], // messagesRef and clineAskRef are stable
- )
- const handleSetChatBoxMessage = useCallback(
- (text: string, images: string[]) => {
- // Avoid nested template literals by breaking down the logic
- let newValue = text
- if (inputValue !== "") {
- newValue = inputValue + " " + text
- }
- setInputValue(newValue)
- setSelectedImages([...selectedImages, ...images])
- },
- [inputValue, selectedImages],
- )
- const startNewTask = useCallback(() => vscode.postMessage({ type: "clearTask" }), [])
- // 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.
- const handlePrimaryButtonClick = useCallback(
- (text?: string, images?: string[]) => {
- // Mark that user has responded
- userRespondedRef.current = true
- const trimmedInput = text?.trim()
- switch (clineAsk) {
- case "api_req_failed":
- case "command":
- case "tool":
- case "browser_action_launch":
- case "use_mcp_server":
- case "resume_task":
- case "mistake_limit_reached":
- // Only send text/images if they exist
- if (trimmedInput || (images && images.length > 0)) {
- vscode.postMessage({
- type: "askResponse",
- askResponse: "yesButtonClicked",
- text: trimmedInput,
- images: images,
- })
- // Clear input state after sending
- setInputValue("")
- setSelectedImages([])
- } else {
- vscode.postMessage({ type: "askResponse", askResponse: "yesButtonClicked" })
- }
- break
- case "completion_result":
- case "resume_completed_task":
- // Waiting for feedback, but we can just present a new task button
- startNewTask()
- break
- case "command_output":
- vscode.postMessage({ type: "terminalOperation", terminalOperation: "continue" })
- break
- }
- setSendingDisabled(true)
- setClineAsk(undefined)
- setEnableButtons(false)
- },
- [clineAsk, startNewTask],
- )
- const handleSecondaryButtonClick = useCallback(
- (text?: string, images?: string[]) => {
- // Mark that user has responded
- userRespondedRef.current = true
- const trimmedInput = text?.trim()
- if (isStreaming) {
- vscode.postMessage({ type: "cancelTask" })
- setDidClickCancel(true)
- return
- }
- switch (clineAsk) {
- case "api_req_failed":
- case "mistake_limit_reached":
- case "resume_task":
- startNewTask()
- break
- case "command":
- case "tool":
- case "browser_action_launch":
- case "use_mcp_server":
- // Only send text/images if they exist
- if (trimmedInput || (images && images.length > 0)) {
- vscode.postMessage({
- type: "askResponse",
- askResponse: "noButtonClicked",
- text: trimmedInput,
- images: images,
- })
- // Clear input state after sending
- setInputValue("")
- setSelectedImages([])
- } else {
- // Responds to the API with a "This operation failed" and lets it try again
- vscode.postMessage({ type: "askResponse", askResponse: "noButtonClicked" })
- }
- break
- case "command_output":
- vscode.postMessage({ type: "terminalOperation", terminalOperation: "abort" })
- break
- }
- setSendingDisabled(true)
- setClineAsk(undefined)
- setEnableButtons(false)
- },
- [clineAsk, startNewTask, isStreaming],
- )
- const { info: model } = useSelectedModel(apiConfiguration)
- const selectImages = useCallback(() => vscode.postMessage({ type: "selectImages" }), [])
- const shouldDisableImages = !model?.supportsImages || selectedImages.length >= MAX_IMAGES_PER_MESSAGE
- const handleMessage = useCallback(
- (e: MessageEvent) => {
- const message: ExtensionMessage = e.data
- switch (message.type) {
- case "action":
- switch (message.action!) {
- case "didBecomeVisible":
- if (!isHidden && !sendingDisabled && !enableButtons) {
- textAreaRef.current?.focus()
- }
- break
- case "focusInput":
- textAreaRef.current?.focus()
- break
- }
- break
- case "selectedImages":
- // Only handle selectedImages if it's not for editing context
- // When context is "edit", ChatRow will handle the images
- if (message.context !== "edit") {
- setSelectedImages((prevImages: string[]) =>
- appendImages(prevImages, message.images, MAX_IMAGES_PER_MESSAGE),
- )
- }
- break
- case "invoke":
- switch (message.invoke!) {
- case "newChat":
- handleChatReset()
- break
- case "sendMessage":
- handleSendMessage(message.text ?? "", message.images ?? [])
- break
- case "setChatBoxMessage":
- handleSetChatBoxMessage(message.text ?? "", message.images ?? [])
- break
- case "primaryButtonClick":
- handlePrimaryButtonClick(message.text ?? "", message.images ?? [])
- break
- case "secondaryButtonClick":
- handleSecondaryButtonClick(message.text ?? "", message.images ?? [])
- break
- }
- break
- case "condenseTaskContextResponse":
- if (message.text && message.text === currentTaskItem?.id) {
- if (isCondensing && sendingDisabled) {
- setSendingDisabled(false)
- }
- setIsCondensing(false)
- }
- break
- case "checkpointInitWarning":
- setCheckpointWarning(message.checkpointWarning)
- break
- }
- // textAreaRef.current is not explicitly required here since React
- // guarantees that ref will be stable across re-renders, and we're
- // not using its value but its reference.
- },
- [
- isCondensing,
- isHidden,
- sendingDisabled,
- enableButtons,
- currentTaskItem,
- handleChatReset,
- handleSendMessage,
- handleSetChatBoxMessage,
- handlePrimaryButtonClick,
- handleSecondaryButtonClick,
- setCheckpointWarning,
- ],
- )
- useEvent("message", handleMessage)
- // NOTE: the VSCode window needs to be focused for this to work.
- useMount(() => textAreaRef.current?.focus())
- const visibleMessages = useMemo(() => {
- // Pre-compute checkpoint hashes that have associated user messages for O(1) lookup
- const userMessageCheckpointHashes = new Set<string>()
- modifiedMessages.forEach((msg) => {
- if (
- msg.say === "user_feedback" &&
- msg.checkpoint &&
- (msg.checkpoint as any).type === "user_message" &&
- (msg.checkpoint as any).hash
- ) {
- userMessageCheckpointHashes.add((msg.checkpoint as any).hash)
- }
- })
- // Remove the 500-message limit to prevent array index shifting
- // Virtuoso is designed to efficiently handle large lists through virtualization
- const newVisibleMessages = modifiedMessages.filter((message) => {
- // Filter out checkpoint_saved messages that should be suppressed
- if (message.say === "checkpoint_saved") {
- // Check if this checkpoint has the suppressMessage flag set
- if (
- message.checkpoint &&
- typeof message.checkpoint === "object" &&
- "suppressMessage" in message.checkpoint &&
- message.checkpoint.suppressMessage
- ) {
- return false
- }
- // Also filter out checkpoint messages associated with user messages (legacy behavior)
- if (message.text && userMessageCheckpointHashes.has(message.text)) {
- return false
- }
- }
- if (everVisibleMessagesTsRef.current.has(message.ts)) {
- const alwaysHiddenOnceProcessedAsk: ClineAsk[] = [
- "api_req_failed",
- "resume_task",
- "resume_completed_task",
- ]
- const alwaysHiddenOnceProcessedSay = [
- "api_req_finished",
- "api_req_retried",
- "api_req_deleted",
- "mcp_server_request_started",
- ]
- if (message.ask && alwaysHiddenOnceProcessedAsk.includes(message.ask)) return false
- if (message.say && alwaysHiddenOnceProcessedSay.includes(message.say)) return false
- if (message.say === "text" && (message.text ?? "") === "" && (message.images?.length ?? 0) === 0) {
- return false
- }
- return true
- }
- switch (message.ask) {
- case "completion_result":
- if (message.text === "") return false
- break
- case "api_req_failed":
- case "resume_task":
- case "resume_completed_task":
- return false
- }
- switch (message.say) {
- case "api_req_finished":
- case "api_req_retried":
- case "api_req_deleted":
- return false
- case "api_req_retry_delayed":
- const last1 = modifiedMessages.at(-1)
- const last2 = modifiedMessages.at(-2)
- if (last1?.ask === "resume_task" && last2 === message) {
- return true
- } else if (message !== last1) {
- return false
- }
- break
- case "text":
- if ((message.text ?? "") === "" && (message.images?.length ?? 0) === 0) return false
- break
- case "mcp_server_request_started":
- return false
- }
- return true
- })
- const viewportStart = Math.max(0, newVisibleMessages.length - 100)
- newVisibleMessages
- .slice(viewportStart)
- .forEach((msg: ClineMessage) => everVisibleMessagesTsRef.current.set(msg.ts, true))
- return newVisibleMessages
- }, [modifiedMessages])
- useEffect(() => {
- const cleanupInterval = setInterval(() => {
- const cache = everVisibleMessagesTsRef.current
- const currentMessageIds = new Set(modifiedMessages.map((m: ClineMessage) => m.ts))
- const viewportMessages = visibleMessages.slice(Math.max(0, visibleMessages.length - 100))
- const viewportMessageIds = new Set(viewportMessages.map((m: ClineMessage) => m.ts))
- cache.forEach((_value: boolean, key: number) => {
- if (!currentMessageIds.has(key) && !viewportMessageIds.has(key)) {
- cache.delete(key)
- }
- })
- }, 60000)
- return () => clearInterval(cleanupInterval)
- }, [modifiedMessages, visibleMessages])
- useDebounceEffect(
- () => {
- if (!isHidden && !sendingDisabled && !enableButtons) {
- textAreaRef.current?.focus()
- }
- },
- 50,
- [isHidden, sendingDisabled, enableButtons],
- )
- const isReadOnlyToolAction = useCallback((message: ClineMessage | undefined) => {
- if (message?.type === "ask") {
- if (!message.text) {
- return true
- }
- const tool = JSON.parse(message.text)
- return [
- "readFile",
- "listFiles",
- "listFilesTopLevel",
- "listFilesRecursive",
- "listCodeDefinitionNames",
- "searchFiles",
- "codebaseSearch",
- "runSlashCommand",
- ].includes(tool.tool)
- }
- return false
- }, [])
- const isWriteToolAction = useCallback((message: ClineMessage | undefined) => {
- if (message?.type === "ask") {
- if (!message.text) {
- return true
- }
- const tool = JSON.parse(message.text)
- return ["editedExistingFile", "appliedDiff", "newFileCreated", "insertContent", "generateImage"].includes(
- tool.tool,
- )
- }
- return false
- }, [])
- const isMcpToolAlwaysAllowed = useCallback(
- (message: ClineMessage | undefined) => {
- if (message?.type === "ask" && message.ask === "use_mcp_server") {
- if (!message.text) {
- return true
- }
- const mcpServerUse = JSON.parse(message.text) as McpServerUse
- if (mcpServerUse.type === "use_mcp_tool" && mcpServerUse.toolName) {
- const server = mcpServers?.find((s: McpServer) => s.name === mcpServerUse.serverName)
- const tool = server?.tools?.find((t: McpTool) => t.name === mcpServerUse.toolName)
- return tool?.alwaysAllow || false
- }
- }
- return false
- },
- [mcpServers],
- )
- // Get the command decision using unified validation logic
- const getCommandDecisionForMessage = useCallback(
- (message: ClineMessage | undefined): CommandDecision => {
- if (message?.type !== "ask") return "ask_user"
- return getCommandDecision(message.text || "", allowedCommands || [], deniedCommands || [])
- },
- [allowedCommands, deniedCommands],
- )
- // Check if a command message should be auto-approved.
- const isAllowedCommand = useCallback(
- (message: ClineMessage | undefined): boolean => {
- return getCommandDecisionForMessage(message) === "auto_approve"
- },
- [getCommandDecisionForMessage],
- )
- // Check if a command message should be auto-denied.
- const isDeniedCommand = useCallback(
- (message: ClineMessage | undefined): boolean => {
- return getCommandDecisionForMessage(message) === "auto_deny"
- },
- [getCommandDecisionForMessage],
- )
- // Helper function to get the denied prefix for a command
- const getDeniedPrefix = useCallback(
- (command: string): string | null => {
- if (!command || !deniedCommands?.length) return null
- // Parse the command into sub-commands and check each one
- const subCommands = parseCommand(command)
- for (const cmd of subCommands) {
- const deniedMatch = findLongestPrefixMatch(cmd, deniedCommands)
- if (deniedMatch) {
- return deniedMatch
- }
- }
- return null
- },
- [deniedCommands],
- )
- // Create toggles object for useAutoApprovalState hook
- const autoApprovalToggles = useAutoApprovalToggles()
- const { hasEnabledOptions } = useAutoApprovalState(autoApprovalToggles, autoApprovalEnabled)
- const isAutoApproved = useCallback(
- (message: ClineMessage | undefined) => {
- // First check if auto-approval is enabled AND we have at least one permission
- if (!autoApprovalEnabled || !message || message.type !== "ask") {
- return false
- }
- // Use the hook's result instead of duplicating the logic
- if (!hasEnabledOptions) {
- return false
- }
- if (message.ask === "followup") {
- return alwaysAllowFollowupQuestions
- }
- if (message.ask === "browser_action_launch") {
- return alwaysAllowBrowser
- }
- if (message.ask === "use_mcp_server") {
- // Check if it's a tool or resource access
- if (!message.text) {
- return false
- }
- try {
- const mcpServerUse = JSON.parse(message.text) as McpServerUse
- if (mcpServerUse.type === "use_mcp_tool") {
- // For tools, check if the specific tool is always allowed
- return alwaysAllowMcp && isMcpToolAlwaysAllowed(message)
- } else if (mcpServerUse.type === "access_mcp_resource") {
- // For resources, auto-approve if MCP is always allowed
- // Resources don't have individual alwaysAllow settings like tools do
- return alwaysAllowMcp
- }
- } catch (error) {
- console.error("Failed to parse MCP server use message:", error)
- return false
- }
- return false
- }
- if (message.ask === "command") {
- return alwaysAllowExecute && isAllowedCommand(message)
- }
- // For read/write operations, check if it's outside workspace and if
- // we have permission for that.
- if (message.ask === "tool") {
- let tool: any = {}
- try {
- tool = JSON.parse(message.text || "{}")
- } catch (error) {
- console.error("Failed to parse tool:", error)
- }
- if (!tool) {
- return false
- }
- if (tool?.tool === "updateTodoList") {
- return alwaysAllowUpdateTodoList
- }
- if (tool?.tool === "fetchInstructions") {
- if (tool.content === "create_mode") {
- return alwaysAllowModeSwitch
- }
- if (tool.content === "create_mcp_server") {
- return alwaysAllowMcp
- }
- }
- if (tool?.tool === "switchMode") {
- return alwaysAllowModeSwitch
- }
- if (["newTask", "finishTask"].includes(tool?.tool)) {
- return alwaysAllowSubtasks
- }
- const isOutsideWorkspace = !!tool.isOutsideWorkspace
- const isProtected = message.isProtected
- if (isReadOnlyToolAction(message)) {
- return alwaysAllowReadOnly && (!isOutsideWorkspace || alwaysAllowReadOnlyOutsideWorkspace)
- }
- if (isWriteToolAction(message)) {
- return (
- alwaysAllowWrite &&
- (!isOutsideWorkspace || alwaysAllowWriteOutsideWorkspace) &&
- (!isProtected || alwaysAllowWriteProtected)
- )
- }
- }
- return false
- },
- [
- autoApprovalEnabled,
- hasEnabledOptions,
- alwaysAllowBrowser,
- alwaysAllowReadOnly,
- alwaysAllowReadOnlyOutsideWorkspace,
- isReadOnlyToolAction,
- alwaysAllowWrite,
- alwaysAllowWriteOutsideWorkspace,
- alwaysAllowWriteProtected,
- isWriteToolAction,
- alwaysAllowExecute,
- isAllowedCommand,
- alwaysAllowMcp,
- isMcpToolAlwaysAllowed,
- alwaysAllowModeSwitch,
- alwaysAllowFollowupQuestions,
- alwaysAllowSubtasks,
- alwaysAllowUpdateTodoList,
- ],
- )
- useEffect(() => {
- // This ensures the first message is not read, future user messages are
- // labeled as `user_feedback`.
- if (lastMessage && messages.length > 1) {
- if (
- lastMessage.text && // has text
- (lastMessage.say === "text" || lastMessage.say === "completion_result") && // is a text message
- !lastMessage.partial && // not a partial message
- !lastMessage.text.startsWith("{") // not a json object
- ) {
- let text = lastMessage?.text || ""
- const mermaidRegex = /```mermaid[\s\S]*?```/g
- // remove mermaid diagrams from text
- text = text.replace(mermaidRegex, "")
- // remove markdown from text
- text = removeMd(text)
- // ensure message is not a duplicate of last read message
- if (text !== lastTtsRef.current) {
- try {
- playTts(text)
- lastTtsRef.current = text
- } catch (error) {
- console.error("Failed to execute text-to-speech:", error)
- }
- }
- }
- }
- // Update previous value.
- setWasStreaming(isStreaming)
- }, [isStreaming, lastMessage, wasStreaming, isAutoApproved, messages.length])
- const isBrowserSessionMessage = (message: ClineMessage): boolean => {
- // Which of visible messages are browser session messages, see above.
- if (message.type === "ask") {
- return ["browser_action_launch"].includes(message.ask!)
- }
- if (message.type === "say") {
- return ["api_req_started", "text", "browser_action", "browser_action_result"].includes(message.say!)
- }
- return false
- }
- const groupedMessages = useMemo(() => {
- const result: (ClineMessage | ClineMessage[])[] = []
- let currentGroup: ClineMessage[] = []
- let isInBrowserSession = false
- const endBrowserSession = () => {
- if (currentGroup.length > 0) {
- result.push([...currentGroup])
- currentGroup = []
- isInBrowserSession = false
- }
- }
- visibleMessages.forEach((message: ClineMessage) => {
- if (message.ask === "browser_action_launch") {
- // Complete existing browser session if any.
- endBrowserSession()
- // Start new.
- isInBrowserSession = true
- currentGroup.push(message)
- } else if (isInBrowserSession) {
- // End session if `api_req_started` is cancelled.
- if (message.say === "api_req_started") {
- // 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.
- const lastApiReqStarted = [...currentGroup].reverse().find((m) => m.say === "api_req_started")
- if (lastApiReqStarted?.text !== null && lastApiReqStarted?.text !== undefined) {
- const info = JSON.parse(lastApiReqStarted.text)
- const isCancelled = info.cancelReason !== null && info.cancelReason !== undefined
- if (isCancelled) {
- endBrowserSession()
- result.push(message)
- return
- }
- }
- }
- if (isBrowserSessionMessage(message)) {
- currentGroup.push(message)
- // Check if this is a close action
- if (message.say === "browser_action") {
- const browserAction = JSON.parse(message.text || "{}") as ClineSayBrowserAction
- if (browserAction.action === "close") {
- endBrowserSession()
- }
- }
- } else {
- // complete existing browser session if any
- endBrowserSession()
- result.push(message)
- }
- } else {
- result.push(message)
- }
- })
- // Handle case where browser session is the last group
- if (currentGroup.length > 0) {
- result.push([...currentGroup])
- }
- if (isCondensing) {
- // Show indicator after clicking condense button
- result.push({
- type: "say",
- say: "condense_context",
- ts: Date.now(),
- partial: true,
- })
- }
- return result
- }, [isCondensing, visibleMessages])
- // scrolling
- const scrollToBottomSmooth = useMemo(
- () =>
- debounce(() => virtuosoRef.current?.scrollTo({ top: Number.MAX_SAFE_INTEGER, behavior: "smooth" }), 10, {
- immediate: true,
- }),
- [],
- )
- useEffect(() => {
- return () => {
- if (scrollToBottomSmooth && typeof (scrollToBottomSmooth as any).cancel === "function") {
- ;(scrollToBottomSmooth as any).cancel()
- }
- }
- }, [scrollToBottomSmooth])
- const scrollToBottomAuto = useCallback(() => {
- virtuosoRef.current?.scrollTo({
- top: Number.MAX_SAFE_INTEGER,
- behavior: "auto", // Instant causes crash.
- })
- }, [])
- const handleSetExpandedRow = useCallback(
- (ts: number, expand?: boolean) => {
- setExpandedRows((prev: Record<number, boolean>) => ({
- ...prev,
- [ts]: expand === undefined ? !prev[ts] : expand,
- }))
- },
- [setExpandedRows], // setExpandedRows is stable
- )
- // Scroll when user toggles certain rows.
- const toggleRowExpansion = useCallback(
- (ts: number) => {
- handleSetExpandedRow(ts)
- // The logic to set disableAutoScrollRef.current = true on expansion
- // is now handled by the useEffect hook that observes expandedRows.
- },
- [handleSetExpandedRow],
- )
- const handleRowHeightChange = useCallback(
- (isTaller: boolean) => {
- if (!disableAutoScrollRef.current) {
- if (isTaller) {
- scrollToBottomSmooth()
- } else {
- setTimeout(() => scrollToBottomAuto(), 0)
- }
- }
- },
- [scrollToBottomSmooth, scrollToBottomAuto],
- )
- useEffect(() => {
- let timer: ReturnType<typeof setTimeout> | undefined
- if (!disableAutoScrollRef.current) {
- timer = setTimeout(() => scrollToBottomSmooth(), 50)
- }
- return () => {
- if (timer) {
- clearTimeout(timer)
- }
- }
- }, [groupedMessages.length, scrollToBottomSmooth])
- const handleWheel = useCallback((event: Event) => {
- const wheelEvent = event as WheelEvent
- if (wheelEvent.deltaY && wheelEvent.deltaY < 0) {
- if (scrollContainerRef.current?.contains(wheelEvent.target as Node)) {
- // User scrolled up
- disableAutoScrollRef.current = true
- }
- }
- }, [])
- useEvent("wheel", handleWheel, window, { passive: true }) // passive improves scrolling performance
- // Effect to clear checkpoint warning when messages appear or task changes
- useEffect(() => {
- if (isHidden || !task) {
- setCheckpointWarning(undefined)
- }
- }, [modifiedMessages.length, isStreaming, isHidden, task])
- const placeholderText = task ? t("chat:typeMessage") : t("chat:typeTask")
- const switchToMode = useCallback(
- (modeSlug: string): void => {
- // Update local state and notify extension to sync mode change.
- setMode(modeSlug)
- // Send the mode switch message.
- vscode.postMessage({ type: "mode", text: modeSlug })
- },
- [setMode],
- )
- const handleSuggestionClickInRow = useCallback(
- (suggestion: SuggestionItem, event?: React.MouseEvent) => {
- // Mark that user has responded if this is a manual click (not auto-approval)
- if (event) {
- userRespondedRef.current = true
- }
- // Mark the current follow-up question as answered when a suggestion is clicked
- if (clineAsk === "followup" && !event?.shiftKey) {
- markFollowUpAsAnswered()
- }
- // Check if we need to switch modes
- if (suggestion.mode) {
- // Only switch modes if it's a manual click (event exists) or auto-approval is allowed
- const isManualClick = !!event
- if (isManualClick || alwaysAllowModeSwitch) {
- // Switch mode without waiting
- switchToMode(suggestion.mode)
- }
- }
- if (event?.shiftKey) {
- // Always append to existing text, don't overwrite
- setInputValue((currentValue: string) => {
- return currentValue !== "" ? `${currentValue} \n${suggestion.answer}` : suggestion.answer
- })
- } else {
- // Don't clear the input value when sending a follow-up choice
- // The message should be sent but the text area should preserve what the user typed
- const preservedInput = inputValueRef.current
- handleSendMessage(suggestion.answer, [])
- // Restore the input value after sending
- setInputValue(preservedInput)
- }
- },
- [handleSendMessage, setInputValue, switchToMode, alwaysAllowModeSwitch, clineAsk, markFollowUpAsAnswered],
- )
- const handleBatchFileResponse = useCallback((response: { [key: string]: boolean }) => {
- // Handle batch file response, e.g., for file uploads
- vscode.postMessage({ type: "askResponse", askResponse: "objectResponse", text: JSON.stringify(response) })
- }, [])
- // Handler for when FollowUpSuggest component unmounts
- const handleFollowUpUnmount = useCallback(() => {
- // Mark that user has responded
- userRespondedRef.current = true
- }, [])
- const itemContent = useCallback(
- (index: number, messageOrGroup: ClineMessage | ClineMessage[]) => {
- // browser session group
- if (Array.isArray(messageOrGroup)) {
- return (
- <BrowserSessionRow
- messages={messageOrGroup}
- isLast={index === groupedMessages.length - 1}
- lastModifiedMessage={modifiedMessages.at(-1)}
- onHeightChange={handleRowHeightChange}
- isStreaming={isStreaming}
- isExpanded={(messageTs: number) => expandedRows[messageTs] ?? false}
- onToggleExpand={(messageTs: number) => {
- setExpandedRows((prev: Record<number, boolean>) => ({
- ...prev,
- [messageTs]: !prev[messageTs],
- }))
- }}
- />
- )
- }
- const hasCheckpoint = modifiedMessages.some((message) => message.say === "checkpoint_saved")
- // regular message
- return (
- <ChatRow
- key={messageOrGroup.ts}
- message={messageOrGroup}
- isExpanded={expandedRows[messageOrGroup.ts] || false}
- onToggleExpand={toggleRowExpansion} // This was already stabilized
- lastModifiedMessage={modifiedMessages.at(-1)} // Original direct access
- isLast={index === groupedMessages.length - 1} // Original direct access
- onHeightChange={handleRowHeightChange}
- isStreaming={isStreaming}
- onSuggestionClick={handleSuggestionClickInRow} // This was already stabilized
- onBatchFileResponse={handleBatchFileResponse}
- onFollowUpUnmount={handleFollowUpUnmount}
- isFollowUpAnswered={messageOrGroup.isAnswered === true || messageOrGroup.ts === currentFollowUpTs}
- editable={
- messageOrGroup.type === "ask" &&
- messageOrGroup.ask === "tool" &&
- (() => {
- let tool: any = {}
- try {
- tool = JSON.parse(messageOrGroup.text || "{}")
- } catch (_) {
- if (messageOrGroup.text?.includes("updateTodoList")) {
- tool = { tool: "updateTodoList" }
- }
- }
- if (tool.tool === "updateTodoList" && alwaysAllowUpdateTodoList) {
- return false
- }
- return tool.tool === "updateTodoList" && enableButtons && !!primaryButtonText
- })()
- }
- hasCheckpoint={hasCheckpoint}
- />
- )
- },
- [
- expandedRows,
- toggleRowExpansion,
- modifiedMessages,
- groupedMessages.length,
- handleRowHeightChange,
- isStreaming,
- handleSuggestionClickInRow,
- handleBatchFileResponse,
- handleFollowUpUnmount,
- currentFollowUpTs,
- alwaysAllowUpdateTodoList,
- enableButtons,
- primaryButtonText,
- ],
- )
- useEffect(() => {
- if (autoApproveTimeoutRef.current) {
- clearTimeout(autoApproveTimeoutRef.current)
- autoApproveTimeoutRef.current = null
- }
- if (!clineAsk || !enableButtons) {
- return
- }
- // Exit early if user has already responded
- if (userRespondedRef.current) {
- return
- }
- const autoApproveOrReject = async () => {
- // Check for auto-reject first (commands that should be denied)
- if (lastMessage?.ask === "command" && isDeniedCommand(lastMessage)) {
- // Get the denied prefix for the localized message
- const deniedPrefix = getDeniedPrefix(lastMessage.text || "")
- if (deniedPrefix) {
- // Create the localized auto-deny message and send it with the rejection
- const autoDenyMessage = tSettings("autoApprove.execute.autoDenied", { prefix: deniedPrefix })
- vscode.postMessage({
- type: "askResponse",
- askResponse: "noButtonClicked",
- text: autoDenyMessage,
- })
- } else {
- // Auto-reject denied commands immediately if no prefix found
- vscode.postMessage({ type: "askResponse", askResponse: "noButtonClicked" })
- }
- setSendingDisabled(true)
- setClineAsk(undefined)
- setEnableButtons(false)
- return
- }
- // Then check for auto-approve
- if (lastMessage?.ask && isAutoApproved(lastMessage)) {
- // Special handling for follow-up questions
- if (lastMessage.ask === "followup") {
- // Handle invalid JSON
- let followUpData: FollowUpData = {}
- try {
- followUpData = JSON.parse(lastMessage.text || "{}") as FollowUpData
- } catch (error) {
- console.error("Failed to parse follow-up data:", error)
- return
- }
- if (followUpData && followUpData.suggest && followUpData.suggest.length > 0) {
- // Wait for the configured timeout before auto-selecting the first suggestion
- await new Promise<void>((resolve) => {
- autoApproveTimeoutRef.current = setTimeout(() => {
- autoApproveTimeoutRef.current = null
- resolve()
- }, followupAutoApproveTimeoutMs)
- })
- // Check if user responded manually
- if (userRespondedRef.current) {
- return
- }
- // Get the first suggestion
- const firstSuggestion = followUpData.suggest[0]
- // Handle the suggestion click
- handleSuggestionClickInRow(firstSuggestion)
- return
- }
- } else if (lastMessage.ask === "tool" && isWriteToolAction(lastMessage)) {
- await new Promise<void>((resolve) => {
- autoApproveTimeoutRef.current = setTimeout(() => {
- autoApproveTimeoutRef.current = null
- resolve()
- }, writeDelayMs)
- })
- }
- vscode.postMessage({ type: "askResponse", askResponse: "yesButtonClicked" })
- setSendingDisabled(true)
- setClineAsk(undefined)
- setEnableButtons(false)
- }
- }
- autoApproveOrReject()
- return () => {
- if (autoApproveTimeoutRef.current) {
- clearTimeout(autoApproveTimeoutRef.current)
- autoApproveTimeoutRef.current = null
- }
- }
- }, [
- clineAsk,
- enableButtons,
- handlePrimaryButtonClick,
- alwaysAllowBrowser,
- alwaysAllowReadOnly,
- alwaysAllowReadOnlyOutsideWorkspace,
- alwaysAllowWrite,
- alwaysAllowWriteOutsideWorkspace,
- alwaysAllowExecute,
- followupAutoApproveTimeoutMs,
- alwaysAllowMcp,
- messages,
- allowedCommands,
- deniedCommands,
- mcpServers,
- isAutoApproved,
- lastMessage,
- writeDelayMs,
- isWriteToolAction,
- alwaysAllowFollowupQuestions,
- handleSuggestionClickInRow,
- isAllowedCommand,
- isDeniedCommand,
- getDeniedPrefix,
- tSettings,
- ])
- // Function to handle mode switching
- const switchToNextMode = useCallback(() => {
- const allModes = getAllModes(customModes)
- const currentModeIndex = allModes.findIndex((m) => m.slug === mode)
- const nextModeIndex = (currentModeIndex + 1) % allModes.length
- // Update local state and notify extension to sync mode change
- switchToMode(allModes[nextModeIndex].slug)
- }, [mode, customModes, switchToMode])
- // Function to handle switching to previous mode
- const switchToPreviousMode = useCallback(() => {
- const allModes = getAllModes(customModes)
- const currentModeIndex = allModes.findIndex((m) => m.slug === mode)
- const previousModeIndex = (currentModeIndex - 1 + allModes.length) % allModes.length
- // Update local state and notify extension to sync mode change
- switchToMode(allModes[previousModeIndex].slug)
- }, [mode, customModes, switchToMode])
- // Add keyboard event handler
- const handleKeyDown = useCallback(
- (event: KeyboardEvent) => {
- // Check for Command/Ctrl + Period (with or without Shift)
- // Using event.key to respect keyboard layouts (e.g., Dvorak)
- if ((event.metaKey || event.ctrlKey) && event.key === ".") {
- event.preventDefault() // Prevent default browser behavior
- if (event.shiftKey) {
- // Shift + Period = Previous mode
- switchToPreviousMode()
- } else {
- // Just Period = Next mode
- switchToNextMode()
- }
- }
- },
- [switchToNextMode, switchToPreviousMode],
- )
- useEffect(() => {
- window.addEventListener("keydown", handleKeyDown)
- return () => {
- window.removeEventListener("keydown", handleKeyDown)
- }
- }, [handleKeyDown])
- useImperativeHandle(ref, () => ({
- acceptInput: () => {
- if (enableButtons && primaryButtonText) {
- handlePrimaryButtonClick(inputValue, selectedImages)
- } else if (!sendingDisabled && !isProfileDisabled && (inputValue.trim() || selectedImages.length > 0)) {
- handleSendMessage(inputValue, selectedImages)
- }
- },
- }))
- const handleCondenseContext = (taskId: string) => {
- if (isCondensing || sendingDisabled) {
- return
- }
- setIsCondensing(true)
- setSendingDisabled(true)
- vscode.postMessage({ type: "condenseTaskContextRequest", text: taskId })
- }
- const areButtonsVisible = showScrollToBottom || primaryButtonText || secondaryButtonText || isStreaming
- return (
- <div
- data-testid="chat-view"
- className={isHidden ? "hidden" : "fixed top-0 left-0 right-0 bottom-0 flex flex-col overflow-hidden"}>
- {telemetrySetting === "unset" && <TelemetryBanner />}
- {(showAnnouncement || showAnnouncementModal) && (
- <Announcement
- hideAnnouncement={() => {
- if (showAnnouncementModal) {
- setShowAnnouncementModal(false)
- }
- if (showAnnouncement) {
- hideAnnouncement()
- }
- }}
- />
- )}
- {task ? (
- <>
- <TaskHeader
- task={task}
- tokensIn={apiMetrics.totalTokensIn}
- tokensOut={apiMetrics.totalTokensOut}
- cacheWrites={apiMetrics.totalCacheWrites}
- cacheReads={apiMetrics.totalCacheReads}
- totalCost={apiMetrics.totalCost}
- contextTokens={apiMetrics.contextTokens}
- buttonsDisabled={sendingDisabled}
- handleCondenseContext={handleCondenseContext}
- todos={latestTodos}
- />
- {hasSystemPromptOverride && (
- <div className="px-3">
- <SystemPromptWarning />
- </div>
- )}
- {checkpointWarning && (
- <div className="px-3">
- <CheckpointWarning warning={checkpointWarning} />
- </div>
- )}
- </>
- ) : (
- <div className="flex flex-col h-full justify-center p-6 min-h-0 overflow-y-auto gap-4 relative">
- <div className="flex flex-col items-start gap-2 justify-center h-full min-[400px]:px-6">
- <VersionIndicator
- onClick={() => setShowAnnouncementModal(true)}
- className="absolute top-2 right-3 z-10"
- />
- <div className="flex flex-col gap-4 w-full">
- <RooHero />
- {/* Show RooTips when authenticated or when user is new */}
- {taskHistory.length < 6 && <RooTips />}
- {/* Everyone should see their task history if any */}
- {taskHistory.length > 0 && <HistoryPreview />}
- </div>
- {/* Logged out users should see a one-time upsell, but not for brand new users */}
- {!cloudIsAuthenticated && taskHistory.length >= 6 && (
- <DismissibleUpsell
- upsellId="taskList2"
- icon={<Cloud className="size-5 mt-0.5 shrink-0" />}
- onClick={() => openUpsell()}
- dismissOnClick={false}
- className="!bg-vscode-editor-background mt-6 border-border rounded-xl pl-4 pr-3 py-3 !text-base">
- <Trans
- i18nKey="cloud:upsell.taskList"
- components={{
- learnMoreLink: <VSCodeLink href="#" />,
- }}
- />
- </DismissibleUpsell>
- )}
- </div>
- </div>
- )}
- {task && (
- <>
- <div className="grow flex" ref={scrollContainerRef}>
- <Virtuoso
- ref={virtuosoRef}
- key={task.ts}
- className="scrollable grow overflow-y-scroll mb-1"
- increaseViewportBy={{ top: 3_000, bottom: 1000 }}
- data={groupedMessages}
- itemContent={itemContent}
- atBottomStateChange={(isAtBottom: boolean) => {
- setIsAtBottom(isAtBottom)
- if (isAtBottom) {
- disableAutoScrollRef.current = false
- }
- setShowScrollToBottom(disableAutoScrollRef.current && !isAtBottom)
- }}
- atBottomThreshold={10}
- initialTopMostItemIndex={groupedMessages.length - 1}
- />
- </div>
- {areButtonsVisible && (
- <div
- className={`flex h-9 items-center mb-1 px-[15px] ${
- showScrollToBottom
- ? "opacity-100"
- : enableButtons || (isStreaming && !didClickCancel)
- ? "opacity-100"
- : "opacity-50"
- }`}>
- {showScrollToBottom ? (
- <StandardTooltip content={t("chat:scrollToBottom")}>
- <VSCodeButton
- appearance="secondary"
- className="flex-[2]"
- onClick={() => {
- scrollToBottomSmooth()
- disableAutoScrollRef.current = false
- }}>
- <span className="codicon codicon-chevron-down"></span>
- </VSCodeButton>
- </StandardTooltip>
- ) : (
- <>
- {primaryButtonText && !isStreaming && (
- <StandardTooltip
- content={
- primaryButtonText === t("chat:retry.title")
- ? t("chat:retry.tooltip")
- : primaryButtonText === t("chat:save.title")
- ? t("chat:save.tooltip")
- : primaryButtonText === t("chat:approve.title")
- ? t("chat:approve.tooltip")
- : primaryButtonText === t("chat:runCommand.title")
- ? t("chat:runCommand.tooltip")
- : primaryButtonText === t("chat:startNewTask.title")
- ? t("chat:startNewTask.tooltip")
- : primaryButtonText === t("chat:resumeTask.title")
- ? t("chat:resumeTask.tooltip")
- : primaryButtonText ===
- t("chat:proceedAnyways.title")
- ? t("chat:proceedAnyways.tooltip")
- : primaryButtonText ===
- t("chat:proceedWhileRunning.title")
- ? t("chat:proceedWhileRunning.tooltip")
- : undefined
- }>
- <VSCodeButton
- appearance="primary"
- disabled={!enableButtons}
- className={secondaryButtonText ? "flex-1 mr-[6px]" : "flex-[2] mr-0"}
- onClick={() => handlePrimaryButtonClick(inputValue, selectedImages)}>
- {primaryButtonText}
- </VSCodeButton>
- </StandardTooltip>
- )}
- {(secondaryButtonText || isStreaming) && (
- <StandardTooltip
- content={
- isStreaming
- ? t("chat:cancel.tooltip")
- : secondaryButtonText === t("chat:startNewTask.title")
- ? t("chat:startNewTask.tooltip")
- : secondaryButtonText === t("chat:reject.title")
- ? t("chat:reject.tooltip")
- : secondaryButtonText === t("chat:terminate.title")
- ? t("chat:terminate.tooltip")
- : undefined
- }>
- <VSCodeButton
- appearance="secondary"
- disabled={!enableButtons && !(isStreaming && !didClickCancel)}
- className={isStreaming ? "flex-[2] ml-0" : "flex-1 ml-[6px]"}
- onClick={() => handleSecondaryButtonClick(inputValue, selectedImages)}>
- {isStreaming ? t("chat:cancel.title") : secondaryButtonText}
- </VSCodeButton>
- </StandardTooltip>
- )}
- </>
- )}
- </div>
- )}
- </>
- )}
- <QueuedMessages
- queue={messageQueue}
- onRemove={(index) => {
- if (messageQueue[index]) {
- vscode.postMessage({ type: "removeQueuedMessage", text: messageQueue[index].id })
- }
- }}
- onUpdate={(index, newText) => {
- if (messageQueue[index]) {
- vscode.postMessage({
- type: "editQueuedMessage",
- payload: { id: messageQueue[index].id, text: newText, images: messageQueue[index].images },
- })
- }
- }}
- />
- <ChatTextArea
- ref={textAreaRef}
- inputValue={inputValue}
- setInputValue={setInputValue}
- sendingDisabled={sendingDisabled || isProfileDisabled}
- selectApiConfigDisabled={sendingDisabled && clineAsk !== "api_req_failed"}
- placeholderText={placeholderText}
- selectedImages={selectedImages}
- setSelectedImages={setSelectedImages}
- onSend={() => handleSendMessage(inputValue, selectedImages)}
- onSelectImages={selectImages}
- shouldDisableImages={shouldDisableImages}
- onHeightChange={() => {
- if (isAtBottom) {
- scrollToBottomAuto()
- }
- }}
- mode={mode}
- setMode={setMode}
- modeShortcutText={modeShortcutText}
- />
- {isProfileDisabled && (
- <div className="px-3">
- <ProfileViolationWarning />
- </div>
- )}
- <div id="roo-portal" />
- <CloudUpsellDialog open={isUpsellOpen} onOpenChange={closeUpsell} onConnect={handleConnect} />
- </div>
- )
- }
- const ChatView = forwardRef(ChatViewComponent)
- export default ChatView
|