All files / src/components/chat/task-header ContextWindow.tsx

0% Statements 0/219
0% Branches 0/1
0% Functions 0/1
0% Lines 0/219

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { cn, Progress, Tooltip } from "@heroui/react"
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import debounce from "debounce"
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"
import { updateSetting } from "@/components/settings/utils/settingsHandlers"
import { formatLargeNumber as formatTokenNumber } from "@/utils/format"
import { AutoCondenseMarker } from "./AutoCondenseMarker"
import CompactTaskButton from "./buttons/CompactTaskButton"
import { ContextWindowSummary } from "./ContextWindowSummary"
 
// Type definitions
interface ContextWindowInfoProps {
	tokensIn?: number
	tokensOut?: number
	cacheWrites?: number
	cacheReads?: number
	size?: number
}
 
interface ContextWindowProgressProps extends ContextWindowInfoProps {
	useAutoCondense: boolean
	lastApiReqTotalTokens?: number
	contextWindow?: number
	autoCondenseThreshold?: number
	onSendMessage?: (command: string, files: string[], images: string[]) => void
}
 
const ConfirmationDialog = memo<{
	onConfirm: (e: React.MouseEvent) => void
	onCancel: (e: React.MouseEvent) => void
}>(({ onConfirm, onCancel }) => (
	<div className="text-xs my-2 flex items-center gap-0 justify-between">
		<span className="font-semibold text-sm">Compact the current task?</span>
		<span className="flex gap-1">
			<VSCodeButton
				appearance="secondary"
				className="text-xs"
				onClick={onCancel}
				title="No, keep the task as is"
				type="button">
				Cancel
			</VSCodeButton>
			<VSCodeButton
				appearance="primary"
				autoFocus={true}
				className="text-xs"
				onClick={onConfirm}
				title="Yes, compact the task"
				type="button">
				Yes
			</VSCodeButton>
		</span>
	</div>
))
ConfirmationDialog.displayName = "ConfirmationDialog"
 
const ContextWindow: React.FC<ContextWindowProgressProps> = ({
	contextWindow = 0,
	lastApiReqTotalTokens = 0,
	autoCondenseThreshold = 0.75,
	onSendMessage,
	useAutoCondense,
	tokensIn,
	tokensOut,
	cacheWrites,
	cacheReads,
}) => {
	const [isOpened, setIsOpened] = useState(false)
	const [threshold, setThreshold] = useState(useAutoCondense ? autoCondenseThreshold : 0)
	const [confirmationNeeded, setConfirmationNeeded] = useState(false)
	const progressBarRef = useRef<HTMLDivElement>(null)
	const [shouldAnimateMarker, setShouldAnimateMarker] = useState(false)
 
	// Trigger marker animation when component first mounts (TaskHeader expands)
	useEffect(() => {
		if (useAutoCondense && threshold > 0) {
			setShouldAnimateMarker(true)
			// Reset animation flag after animation completes
			const timer = setTimeout(() => {
				setShouldAnimateMarker(false)
			}, 1400) // Slightly longer than animation duration (1200ms + buffer)
			return () => clearTimeout(timer)
		}
	}, []) // Empty dependency array means this only runs on mount
 
	const handleContextWindowBarClick = useCallback((event: React.MouseEvent<HTMLDivElement>) => {
		const rect = event.currentTarget.getBoundingClientRect()
		const clickX = event.clientX - rect.left
		const percentage = Math.max(0, Math.min(1, clickX / rect.width))
		const newThreshold = Math.round(percentage * 100) / 100
		setConfirmationNeeded(false)
		setThreshold(newThreshold)
		updateSetting("autoCondenseThreshold", newThreshold)
	}, [])
 
	const handleCompactClick = useCallback(
		(e: React.MouseEvent) => {
			e.preventDefault()
			e.stopPropagation()
			setConfirmationNeeded(!confirmationNeeded)
		},
		[confirmationNeeded],
	)
 
	const handleConfirm = useCallback(
		(e: React.MouseEvent) => {
			e.preventDefault()
			e.stopPropagation()
			onSendMessage?.("/compact", [], [])
			setConfirmationNeeded(false)
		},
		[onSendMessage],
	)
 
	const handleCancel = useCallback((e: React.MouseEvent) => {
		e.preventDefault()
		e.stopPropagation()
		setConfirmationNeeded(false)
	}, [])
 
	const tokenData = useMemo(() => {
		if (!contextWindow) {
			return null
		}
		return {
			percentage: (lastApiReqTotalTokens / contextWindow) * 100,
			max: contextWindow,
			used: lastApiReqTotalTokens,
		}
	}, [contextWindow, lastApiReqTotalTokens])
 
	const debounceCloseHover = useCallback((e: React.MouseEvent) => {
		e.preventDefault()
		e.stopPropagation()
		const showHover = debounce((open: boolean) => setIsOpened(open), 100)
 
		return showHover(false)
	}, [])
 
	// Keyboard event handlers
	const handleKeyDown = useCallback(
		(event: React.KeyboardEvent<HTMLDivElement>) => {
			if (!useAutoCondense) {
				return
			}
 
			const step = event.shiftKey ? 0.1 : 0.05 // Larger step with Shift
			let newThreshold = threshold
 
			switch (event.key) {
				case "ArrowLeft":
				case "ArrowDown":
					event.preventDefault()
					event.stopPropagation()
					setIsOpened(true) // Keep tooltip open on interaction
					newThreshold = Math.max(0, threshold - step)
					break
				case "ArrowRight":
				case "ArrowUp":
					event.preventDefault()
					event.stopPropagation()
					setIsOpened(true) // Keep tooltip open on interaction
					newThreshold = Math.min(1, threshold + step)
					break
				default:
					return
			}
 
			if (newThreshold !== threshold) {
				setThreshold(newThreshold)
				updateSetting("autoCondenseThreshold", newThreshold)
			}
		},
		[threshold, useAutoCondense, setIsOpened],
	)
 
	const handleFocus = useCallback(() => {
		setIsOpened(true)
	}, [])
 
	// Close tooltip when clicking outside
	useEffect(() => {
		const handleClickOutside = (event: MouseEvent) => {
			const target = event.target as Element
			const isInsideProgressBar = progressBarRef.current && progressBarRef.current.contains(target as Node)
 
			// Check if click is inside any tooltip content by looking for our custom class
			const isInsideTooltipContent = target.closest(".context-window-tooltip-content") !== null
 
			if (!isInsideProgressBar && !isInsideTooltipContent) {
				setIsOpened(false)
			}
		}
 
		if (isOpened) {
			document.addEventListener("mousedown", handleClickOutside)
			return () => document.removeEventListener("mousedown", handleClickOutside)
		}
	}, [isOpened])
 
	if (!tokenData) {
		return null
	}
 
	return (
		<div className="flex flex-col my-1.5" onMouseLeave={debounceCloseHover}>
			<div className="flex gap-1 flex-row @max-xs:flex-col @max-xs:items-start items-center text-sm">
				<div className="flex items-center gap-1.5 flex-1 whitespace-nowrap text-xs">
					<span className="cursor-pointer" title="Current tokens used in this request">
						{formatTokenNumber(tokenData.used)}
					</span>
					<div className="flex relative items-center gap-1 flex-1 w-full h-full" onMouseEnter={() => setIsOpened(true)}>
						<Tooltip
							closeDelay={0}
							content={
								<ContextWindowSummary
									autoCompactThreshold={useAutoCondense ? threshold : undefined}
									cacheReads={cacheReads}
									cacheWrites={cacheWrites}
									contextWindow={tokenData.max}
									percentage={tokenData.percentage}
									tokensIn={tokensIn}
									tokensOut={tokensOut}
									tokenUsed={tokenData.used}
								/>
							}
							disableAnimation={true}
							isOpen={isOpened}
							offset={-2}
							placement="bottom"
							shouldCloseOnBlur={false}
							shouldCloseOnInteractOutside={() => false}
							showArrow={true}>
							<div
								aria-label="Auto condense threshold"
								aria-valuemax={100}
								aria-valuemin={0}
								aria-valuenow={Math.round(threshold * 100)}
								aria-valuetext={`${Math.round(threshold * 100)}% threshold`}
								className="relative w-full text-foreground context-window-progress brightness-100"
								onFocus={handleFocus}
								onKeyDown={handleKeyDown}
								ref={progressBarRef}
								role="slider"
								tabIndex={useAutoCondense ? 0 : -1}>
								<Progress
									aria-label="Context window usage progress"
									classNames={{
										base: "drop-shadow-md w-full cursor-pointer",
										track: cn("rounded max-h-2 h-3 bg-foreground/10"),
										indicator: "bg-foreground rounded-r",
										label: "tracking-wider font-medium text-foreground/80",
										value: "text-description",
									}}
									color="success"
									disableAnimation={true}
									onClick={handleContextWindowBarClick}
									size="md"
									value={tokenData.percentage}
								/>
								{useAutoCondense && (
									<AutoCondenseMarker
										isContextWindowHoverOpen={isOpened}
										shouldAnimate={shouldAnimateMarker}
										threshold={threshold}
										usage={tokenData.percentage}
									/>
								)}
								{isOpened}
							</div>
						</Tooltip>
					</div>
					<span className="cursor-pointer" title="Maximum context window size for this model">
						{formatTokenNumber(tokenData.max)}
					</span>
				</div>
				<CompactTaskButton onClick={handleCompactClick} />
			</div>
			{confirmationNeeded && <ConfirmationDialog onCancel={handleCancel} onConfirm={handleConfirm} />}
		</div>
	)
}
 
export default memo(ContextWindow)