import { VSCodeButton, VSCodeTextField, VSCodeRadioGroup, VSCodeRadio } from "@vscode/webview-ui-toolkit/react" import { useExtensionState } from "../../context/ExtensionStateContext" import { vscode } from "../../utils/vscode" import { Virtuoso } from "react-virtuoso" import React, { memo, useMemo, useState, useEffect } from "react" import Fuse, { FuseResult } from "fuse.js" import { formatLargeNumber } from "../../utils/format" type HistoryViewProps = { onDone: () => void } type SortOption = "newest" | "oldest" | "mostExpensive" | "mostTokens" | "mostRelevant" const HistoryView = ({ onDone }: HistoryViewProps) => { const { taskHistory } = useExtensionState() const [searchQuery, setSearchQuery] = useState("") const [sortOption, setSortOption] = useState("newest") const [lastNonRelevantSort, setLastNonRelevantSort] = useState("newest") const [showCopyModal, setShowCopyModal] = useState(false) useEffect(() => { if (searchQuery && sortOption !== "mostRelevant" && !lastNonRelevantSort) { setLastNonRelevantSort(sortOption) setSortOption("mostRelevant") } else if (!searchQuery && sortOption === "mostRelevant" && lastNonRelevantSort) { setSortOption(lastNonRelevantSort) setLastNonRelevantSort(null) } }, [searchQuery, sortOption, lastNonRelevantSort]) const handleHistorySelect = (id: string) => { vscode.postMessage({ type: "showTaskWithId", text: id }) } const handleDeleteHistoryItem = (id: string) => { vscode.postMessage({ type: "deleteTaskWithId", text: id }) } const handleCopyTask = async (e: React.MouseEvent, task: string) => { e.stopPropagation() try { await navigator.clipboard.writeText(task) setShowCopyModal(true) setTimeout(() => setShowCopyModal(false), 2000) } catch (error) { console.error('Failed to copy to clipboard:', error) } } const formatDate = (timestamp: number) => { const date = new Date(timestamp) return date ?.toLocaleString("en-US", { month: "long", day: "numeric", hour: "numeric", minute: "2-digit", hour12: true, }) .replace(", ", " ") .replace(" at", ",") .toUpperCase() } const presentableTasks = useMemo(() => { return taskHistory.filter((item) => item.ts && item.task) }, [taskHistory]) const fuse = useMemo(() => { return new Fuse(presentableTasks, { keys: ["task"], threshold: 0.6, shouldSort: true, isCaseSensitive: false, ignoreLocation: false, includeMatches: true, minMatchCharLength: 1, }) }, [presentableTasks]) const taskHistorySearchResults = useMemo(() => { let results = searchQuery ? highlight(fuse.search(searchQuery)) : presentableTasks // First apply search if needed const searchResults = searchQuery ? results : presentableTasks; // Then sort the results return [...searchResults].sort((a, b) => { switch (sortOption) { case "oldest": return (a.ts || 0) - (b.ts || 0); case "mostExpensive": return (b.totalCost || 0) - (a.totalCost || 0); case "mostTokens": const aTokens = (a.tokensIn || 0) + (a.tokensOut || 0) + (a.cacheWrites || 0) + (a.cacheReads || 0); const bTokens = (b.tokensIn || 0) + (b.tokensOut || 0) + (b.cacheWrites || 0) + (b.cacheReads || 0); return bTokens - aTokens; case "mostRelevant": // Keep fuse order if searching, otherwise sort by newest return searchQuery ? 0 : (b.ts || 0) - (a.ts || 0); case "newest": default: return (b.ts || 0) - (a.ts || 0); } }); }, [presentableTasks, searchQuery, fuse, sortOption]) return ( <> {showCopyModal && (
Prompt Copied to Clipboard
)}

History

Done
{ const newValue = (e.target as HTMLInputElement)?.value setSearchQuery(newValue) if (newValue && !searchQuery && sortOption !== "mostRelevant") { setLastNonRelevantSort(sortOption) setSortOption("mostRelevant") } }}>
{searchQuery && (
setSearchQuery("")} slot="end" style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "100%", }} /> )} setSortOption((e.target as HTMLInputElement).value as SortOption)}> Newest Oldest Most Expensive Most Tokens Most Relevant
(
)) }} itemContent={(index, item) => (
handleHistorySelect(item.id)}>
{formatDate(item.ts)}
Tokens: {formatLargeNumber(item.tokensIn || 0)} {formatLargeNumber(item.tokensOut || 0)}
{!item.totalCost && }
{!!item.cacheWrites && (
Cache: +{formatLargeNumber(item.cacheWrites || 0)} {formatLargeNumber(item.cacheReads || 0)}
)} {!!item.totalCost && (
API Cost: ${item.totalCost?.toFixed(4)}
)}
)} />
) } const ExportButton = ({ itemId }: { itemId: string }) => ( { e.stopPropagation() vscode.postMessage({ type: "exportTaskWithId", text: itemId }) }}>
EXPORT
) // https://gist.github.com/evenfrost/1ba123656ded32fb7a0cd4651efd4db0 export const highlight = ( fuseSearchResult: FuseResult[], highlightClassName: string = "history-item-highlight", ) => { const set = (obj: Record, path: string, value: any) => { const pathValue = path.split(".") let i: number for (i = 0; i < pathValue.length - 1; i++) { if (pathValue[i] === "__proto__" || pathValue[i] === "constructor") return obj = obj[pathValue[i]] as Record } if (pathValue[i] !== "__proto__" && pathValue[i] !== "constructor") { obj[pathValue[i]] = value } } // Function to merge overlapping regions const mergeRegions = (regions: [number, number][]): [number, number][] => { if (regions.length === 0) return regions // Sort regions by start index regions.sort((a, b) => a[0] - b[0]) const merged: [number, number][] = [regions[0]] for (let i = 1; i < regions.length; i++) { const last = merged[merged.length - 1] const current = regions[i] if (current[0] <= last[1] + 1) { // Overlapping or adjacent regions last[1] = Math.max(last[1], current[1]) } else { merged.push(current) } } return merged } const generateHighlightedText = (inputText: string, regions: [number, number][] = []) => { if (regions.length === 0) { return inputText } // Sort and merge overlapping regions const mergedRegions = mergeRegions(regions) // Convert regions to a list of parts with their highlight status const parts: { text: string; highlight: boolean }[] = [] let lastIndex = 0 mergedRegions.forEach(([start, end]) => { // Add non-highlighted text before this region if (start > lastIndex) { parts.push({ text: inputText.substring(lastIndex, start), highlight: false }) } // Add highlighted text parts.push({ text: inputText.substring(start, end + 1), highlight: true }) lastIndex = end + 1 }) // Add any remaining text if (lastIndex < inputText.length) { parts.push({ text: inputText.substring(lastIndex), highlight: false }) } // Build final string return parts .map(part => part.highlight ? `${part.text}` : part.text ) .join('') } return fuseSearchResult .filter(({ matches }) => matches && matches.length) .map(({ item, matches }) => { const highlightedItem = { ...item } matches?.forEach((match) => { if (match.key && typeof match.value === "string" && match.indices) { // Merge overlapping regions before generating highlighted text const mergedIndices = mergeRegions([...match.indices]) set(highlightedItem, match.key, generateHighlightedText(match.value, mergedIndices)) } }) return highlightedItem }) } export default memo(HistoryView)