import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import React, { memo, useEffect, useMemo, useRef, useState } from "react" import { useWindowSize } from "react-use" import { mentionRegexGlobal } from "@shared/context-mentions" import { ClineMessage } from "@shared/ExtensionMessage" import { useExtensionState } from "@/context/ExtensionStateContext" import { formatLargeNumber } from "@/utils/format" import { formatSize } from "@/utils/format" import { vscode } from "@/utils/vscode" import Thumbnails from "@/components/common/Thumbnails" import { normalizeApiConfiguration } from "@/components/settings/ApiOptions" import { validateSlashCommand } from "@/utils/slash-commands" import TaskTimeline from "./TaskTimeline" import { TaskServiceClient, FileServiceClient, UiServiceClient } from "@/services/grpc-client" import HeroTooltip from "@/components/common/HeroTooltip" interface TaskHeaderProps { task: ClineMessage tokensIn: number tokensOut: number doesModelSupportPromptCache: boolean cacheWrites?: number cacheReads?: number totalCost: number lastApiReqTotalTokens?: number onClose: () => void } const TaskHeader: React.FC = ({ task, tokensIn, tokensOut, doesModelSupportPromptCache, cacheWrites, cacheReads, totalCost, lastApiReqTotalTokens, onClose, }) => { const { apiConfiguration, currentTaskItem, checkpointTrackerErrorMessage, clineMessages, navigateToSettings } = useExtensionState() const [isTaskExpanded, setIsTaskExpanded] = useState(true) const [isTextExpanded, setIsTextExpanded] = useState(false) const [showSeeMore, setShowSeeMore] = useState(false) const textContainerRef = useRef(null) const textRef = useRef(null) const { selectedModelInfo } = useMemo(() => normalizeApiConfiguration(apiConfiguration), [apiConfiguration]) const contextWindow = selectedModelInfo?.contextWindow // Open task header when checkpoint tracker error message is set const prevErrorMessageRef = useRef(checkpointTrackerErrorMessage) useEffect(() => { if (checkpointTrackerErrorMessage !== prevErrorMessageRef.current) { setIsTaskExpanded(true) prevErrorMessageRef.current = checkpointTrackerErrorMessage } }, [checkpointTrackerErrorMessage]) // Reset isTextExpanded when task is collapsed useEffect(() => { if (!isTaskExpanded) { setIsTextExpanded(false) } }, [isTaskExpanded]) /* When dealing with event listeners in React components that depend on state variables, we face a challenge. We want our listener to always use the most up-to-date version of a callback function that relies on current state, but we don't want to constantly add and remove event listeners as that function updates. This scenario often arises with resize listeners or other window events. Simply adding the listener in a useEffect with an empty dependency array risks using stale state, while including the callback in the dependencies can lead to unnecessary re-registrations of the listener. There are react hook libraries that provide a elegant solution to this problem by utilizing the useRef hook to maintain a reference to the latest callback function without triggering re-renders or effect re-runs. This approach ensures that our event listener always has access to the most current state while minimizing performance overhead and potential memory leaks from multiple listener registrations. Sources - https://usehooks-ts.com/react-hook/use-event-listener - https://streamich.github.io/react-use/?path=/story/sensors-useevent--docs - https://github.com/streamich/react-use/blob/master/src/useEvent.ts - https://stackoverflow.com/questions/55565444/how-to-register-event-with-useeffect-hooks Before: const updateMaxHeight = useCallback(() => { if (isExpanded && textContainerRef.current) { const maxHeight = window.innerHeight * (3 / 5) textContainerRef.current.style.maxHeight = `${maxHeight}px` } }, [isExpanded]) useEffect(() => { updateMaxHeight() }, [isExpanded, updateMaxHeight]) useEffect(() => { window.removeEventListener("resize", updateMaxHeight) window.addEventListener("resize", updateMaxHeight) return () => { window.removeEventListener("resize", updateMaxHeight) } }, [updateMaxHeight]) After: */ const { height: windowHeight, width: windowWidth } = useWindowSize() useEffect(() => { if (isTextExpanded && textContainerRef.current) { const maxHeight = windowHeight * (1 / 2) textContainerRef.current.style.maxHeight = `${maxHeight}px` } }, [isTextExpanded, windowHeight]) useEffect(() => { if (isTaskExpanded && textRef.current && textContainerRef.current) { // Use requestAnimationFrame to ensure DOM is fully updated requestAnimationFrame(() => { // Check if refs are still valid if (textRef.current && textContainerRef.current) { let textContainerHeight = textContainerRef.current.clientHeight if (!textContainerHeight) { textContainerHeight = textContainerRef.current.getBoundingClientRect().height } const isOverflowing = textRef.current.scrollHeight > textContainerHeight setShowSeeMore(isOverflowing) } }) } }, [task.text, windowWidth, isTaskExpanded]) const isCostAvailable = useMemo(() => { const openAiCompatHasPricing = apiConfiguration?.apiProvider === "openai" && apiConfiguration?.openAiModelInfo?.inputPrice && apiConfiguration?.openAiModelInfo?.outputPrice if (openAiCompatHasPricing) { return true } return ( apiConfiguration?.apiProvider !== "vscode-lm" && apiConfiguration?.apiProvider !== "ollama" && apiConfiguration?.apiProvider !== "lmstudio" ) }, [apiConfiguration?.apiProvider, apiConfiguration?.openAiModelInfo]) const shouldShowPromptCacheInfo = () => { return ( doesModelSupportPromptCache && ((cacheReads !== undefined && cacheReads > 0) || (cacheWrites !== undefined && cacheWrites > 0)) ) } const ContextWindowComponent = ( <> {isTaskExpanded && contextWindow && (
{formatLargeNumber(lastApiReqTotalTokens || 0)}
{formatLargeNumber(contextWindow)}
)} ) return (
setIsTaskExpanded(!isTaskExpanded)}>
Task {!isTaskExpanded && ":"} {!isTaskExpanded && ( {highlightText(task.text, false)} )}
{isCostAvailable && (
${totalCost?.toFixed(4)}
)}
{isTaskExpanded && ( <>
{highlightText(task.text, false)}
{!isTextExpanded && showSeeMore && (
setIsTextExpanded(!isTextExpanded)}> See more
)}
{isTextExpanded && showSeeMore && (
setIsTextExpanded(!isTextExpanded)}> See less
)} {task.images && task.images.length > 0 && }
Tokens:
{formatLargeNumber(tokensIn || 0)} {formatLargeNumber(tokensOut || 0)}
{!shouldShowPromptCacheInfo() && (
)}
{shouldShowPromptCacheInfo() && (
Cache:
{cacheWrites !== undefined && cacheWrites > 0 && ( +{formatLargeNumber(cacheWrites || 0)} )} {cacheReads !== undefined && cacheReads > 0 && ( {formatLargeNumber(cacheReads || 0)} )}
)}
{ContextWindowComponent}
{checkpointTrackerErrorMessage && (
{checkpointTrackerErrorMessage.replace(/disabling checkpoints\.$/, "")} {checkpointTrackerErrorMessage.endsWith("disabling checkpoints.") && ( <> )} {checkpointTrackerErrorMessage.includes("Git must be installed to use checkpoints.") && ( <> {" "} See here for instructions. )}
)}
)}
{/* {apiProvider === "" && (
Credits Remaining:
{formatPrice(Credits || 0)} {(Credits || 0) < 1 && ( <> {" "} (get more?) )}
)} */}
) } /** * Highlights slash-command in this text if it exists */ const highlightSlashCommands = (text: string, withShadow = true) => { const match = text.match(/^\s*\/([a-zA-Z0-9_-]+)(\s*|$)/) if (!match) { return text } const commandName = match[1] const validationResult = validateSlashCommand(commandName) if (!validationResult || validationResult !== "full") { return text } const commandEndIndex = match[0].length const beforeCommand = text.substring(0, text.indexOf("/")) const afterCommand = match[2] + text.substring(commandEndIndex) return [ beforeCommand, /{commandName} , afterCommand, ] } /** * Highlights & formats all mentions inside this text */ export const highlightMentions = (text: string, withShadow = true) => { const parts = text.split(mentionRegexGlobal) return parts.map((part, index) => { if (index % 2 === 0) { // This is regular text return part } else { // This is a mention return ( FileServiceClient.openMention({ value: part })}> @{part} ) } }) } /** * Handles parsing both mentions and slash-commands */ export const highlightText = (text?: string, withShadow = true) => { if (!text) { return text } const resultWithSlashHighlighting = highlightSlashCommands(text, withShadow) if (resultWithSlashHighlighting === text) { // no highlighting done return highlightMentions(resultWithSlashHighlighting, withShadow) } if (Array.isArray(resultWithSlashHighlighting) && resultWithSlashHighlighting.length === 3) { const [beforeCommand, commandElement, afterCommand] = resultWithSlashHighlighting as [string, JSX.Element, string] return [beforeCommand, commandElement, ...highlightMentions(afterCommand, withShadow)] } return [text] } const CopyButton: React.FC<{ taskText?: string }> = ({ taskText }) => { const [copied, setCopied] = useState(false) const handleCopy = () => { if (!taskText) return navigator.clipboard.writeText(taskText).then(() => { setCopied(true) setTimeout(() => setCopied(false), 1500) }) } return (
) } const DeleteButton: React.FC<{ taskSize: string taskId?: string }> = ({ taskSize, taskId }) => ( taskId && TaskServiceClient.deleteTasksWithIds({ value: [taskId] })} style={{ padding: "0px 0px" }}>
{taskSize}
) // const ExportButton = () => ( // vscode.postMessage({ type: "exportCurrentTask" })} // style={ // { // // marginBottom: "-2px", // // marginRight: "-2.5px", // } // }> //
EXPORT
//
// ) export default memo(TaskHeader)