From 001966ac29527ce5f84e5c9f7a696353a92b62c8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 11 Nov 2024 17:02:06 -0800 Subject: [PATCH 01/82] exclude lazy edit tests from search --- .vscode/settings.json | 1 + gui/src/components/find/FindWidget.tsx | 767 +++++++++++++----------- gui/src/components/gui/TimelineItem.tsx | 2 +- 3 files changed, 417 insertions(+), 353 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index b77c6d9b0..0979d760e 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -19,6 +19,7 @@ "binary/build/**": true, "binary/out/**": true, "binary/tmp/**": true, + "core/edit/lazy/test-examples/**": true, "core/llm/llamaTokenizer.js": true, "core/llm/llamaTokenizer.mjs": true, "core/vendor/**": true, diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx index c3fb37ef9..3089803da 100644 --- a/gui/src/components/find/FindWidget.tsx +++ b/gui/src/components/find/FindWidget.tsx @@ -1,50 +1,61 @@ -import { useRef, useEffect, useState, RefObject, useCallback, useMemo } from "react"; +import { + useRef, + useEffect, + useState, + RefObject, + useCallback, + useMemo, +} from "react"; import { RootState } from "../../redux/store"; import { useSelector } from "react-redux"; import { HeaderButton, Input } from ".."; -import ButtonWithTooltip from "../ButtonWithTooltip"; -import { ArrowDownIcon, ArrowUpIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import { + ArrowDownIcon, + ArrowUpIcon, + XMarkIcon, +} from "@heroicons/react/24/outline"; +import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; interface SearchMatch { - index: number; - textNode: Text; - overlayRectangle: Rectangle; + index: number; + textNode: Text; + overlayRectangle: Rectangle; } -type ScrollToMatchOption = "closest" | "first" | "none" +type ScrollToMatchOption = "closest" | "first" | "none"; -const SEARCH_DEBOUNCE = 300 -const RESIZE_DEBOUNCE = 200 +const SEARCH_DEBOUNCE = 300; +const RESIZE_DEBOUNCE = 200; interface Rectangle { - top: number; - left: number; - width: number; - height: number; + top: number; + left: number; + width: number; + height: number; } interface HighlightOverlayProps extends Rectangle { - isCurrent: boolean; + isCurrent: boolean; } const HighlightOverlay = (props: HighlightOverlayProps) => { - const { isCurrent, top, left, width, height } = props; - return ( -
- ) -} + const { isCurrent, top, left, width, height } = props; + return ( +
+ ); +}; /* useFindWidget takes a container ref and returns @@ -55,351 +66,403 @@ const HighlightOverlay = (props: HighlightOverlayProps) => { Container must have relative positioning */ export const useFindWidget = (searchRef: RefObject) => { - // Search input, debounced - const [input, setInput] = useState(""); - const debouncedInput = useRef("") - const inputRef = useRef(null) + // Search input, debounced + const [input, setInput] = useState(""); + const debouncedInput = useRef(""); + const inputRef = useRef(null); - // Widget open/closed state - const [open, setOpen] = useState(false); - const openWidget = useCallback(() => { - setOpen(true); - inputRef?.current.select() - }, [setOpen, inputRef]) + // Widget open/closed state + const [open, setOpen] = useState(false); + const openWidget = useCallback(() => { + setOpen(true); + inputRef?.current.select(); + }, [setOpen, inputRef]); - // Search settings and results - const [caseSensitive, setCaseSensitive] = useState(false); - const [useRegex, setUseRegex] = useState(false); + // Search settings and results + const [caseSensitive, setCaseSensitive] = useState(false); + const [useRegex, setUseRegex] = useState(false); - const [matches, setMatches] = useState([]); - const [currentMatch, setCurrentMatch] = useState(undefined); + const [matches, setMatches] = useState([]); + const [currentMatch, setCurrentMatch] = useState( + undefined, + ); - // Navigating between search results - // The "current" search result is highlighted a different color - const scrollToMatch = useCallback((match: SearchMatch) => { - setCurrentMatch(match) - searchRef.current.scrollTo({ - top: match.overlayRectangle.top - searchRef.current.clientHeight / 2, - left: match.overlayRectangle.left - searchRef.current.clientWidth / 2, - behavior: "smooth" - }) - }, [searchRef.current]) + // Navigating between search results + // The "current" search result is highlighted a different color + const scrollToMatch = useCallback( + (match: SearchMatch) => { + setCurrentMatch(match); + searchRef.current.scrollTo({ + top: match.overlayRectangle.top - searchRef.current.clientHeight / 2, + left: match.overlayRectangle.left - searchRef.current.clientWidth / 2, + behavior: "smooth", + }); + }, + [searchRef.current], + ); - const nextMatch = useCallback(() => { - if (!currentMatch || (matches.length === 0)) return - const newIndex = (currentMatch.index + 1) % matches.length; - const newMatch = matches[newIndex] - scrollToMatch(newMatch) - }, [scrollToMatch, currentMatch, matches]) + const nextMatch = useCallback(() => { + if (!currentMatch || matches.length === 0) return; + const newIndex = (currentMatch.index + 1) % matches.length; + const newMatch = matches[newIndex]; + scrollToMatch(newMatch); + }, [scrollToMatch, currentMatch, matches]); - const previousMatch = useCallback(() => { - if (!currentMatch || (matches.length === 0)) return - const newIndex = currentMatch.index === 0 ? matches.length - 1 : currentMatch.index - 1 - const newMatch = matches[newIndex] - scrollToMatch(newMatch) - }, [scrollToMatch, currentMatch, matches]) + const previousMatch = useCallback(() => { + if (!currentMatch || matches.length === 0) return; + const newIndex = + currentMatch.index === 0 ? matches.length - 1 : currentMatch.index - 1; + const newMatch = matches[newIndex]; + scrollToMatch(newMatch); + }, [scrollToMatch, currentMatch, matches]); - // Handle keyboard shortcuts for navigation - useEffect(() => { - const handleKeyDown = (event: KeyboardEvent) => { - if (event.metaKey && event.key.toLowerCase() === "f") { - event.preventDefault(); - event.stopPropagation(); - openWidget(); - } else if (document.activeElement === inputRef.current) { - if (event.key === "Escape") { - event.preventDefault(); - event.stopPropagation(); - setOpen(false); - } else if (event.key === "Enter") { - event.preventDefault(); - event.stopPropagation(); - if (event.shiftKey) previousMatch() - else nextMatch() - } - } + // Handle keyboard shortcuts for navigation + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + if (event.metaKey && event.key.toLowerCase() === "f") { + event.preventDefault(); + event.stopPropagation(); + openWidget(); + } else if (document.activeElement === inputRef.current) { + if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + setOpen(false); + } else if (event.key === "Enter") { + event.preventDefault(); + event.stopPropagation(); + if (event.shiftKey) previousMatch(); + else nextMatch(); } + } + }; - document.addEventListener("keydown", handleKeyDown); - return () => { - document.removeEventListener("keydown", handleKeyDown); - }; - }, [inputRef, matches, nextMatch]); + document.addEventListener("keydown", handleKeyDown); + return () => { + document.removeEventListener("keydown", handleKeyDown); + }; + }, [inputRef, matches, nextMatch]); - // Handle container resize changes - highlight positions must adjust - const [isResizing, setIsResizing] = useState(false); - useEffect(() => { - let timeoutId: NodeJS.Timeout | null = null; - if (!searchRef?.current) return; + // Handle container resize changes - highlight positions must adjust + const [isResizing, setIsResizing] = useState(false); + useEffect(() => { + let timeoutId: NodeJS.Timeout | null = null; + if (!searchRef?.current) return; - const resizeObserver = new ResizeObserver(entries => { - if (timeoutId) { - clearTimeout(timeoutId); + const resizeObserver = new ResizeObserver((entries) => { + if (timeoutId) { + clearTimeout(timeoutId); + } + setIsResizing(true); + timeoutId = setTimeout(() => { + setIsResizing(false); + }, RESIZE_DEBOUNCE); + }); + + resizeObserver.observe(searchRef.current); + return () => { + if (timeoutId) { + clearTimeout(timeoutId); + } + if (searchRef.current) resizeObserver.unobserve(searchRef.current); + }; + }, [searchRef.current]); + + // Main function for finding matches and generating highlight overlays + const refreshSearch = useCallback( + (scrollTo: ScrollToMatchOption = "none", clearFirst = false) => { + if (clearFirst) setMatches([]); + + const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable + if (!searchRef.current || !_query) { + setMatches([]); + return; + } + const query = caseSensitive ? _query : _query.toLowerCase(); + + // First grab all text nodes + // Skips any elements with the "find-widget-skip" class + const textNodes: Text[] = []; + const walker = document.createTreeWalker( + searchRef.current, + NodeFilter.SHOW_ALL, + { + acceptNode: (node) => { + if (node.nodeType === Node.ELEMENT_NODE) { + if ((node as Element).classList.contains("find-widget-skip")) + return NodeFilter.FILTER_REJECT; + return NodeFilter.FILTER_ACCEPT; + } else if (node.nodeType === Node.TEXT_NODE) { + if (!node.nodeValue) return NodeFilter.FILTER_REJECT; + const nodeValue = caseSensitive + ? node.nodeValue + : node.nodeValue.toLowerCase(); + if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT; } - setIsResizing(true); - timeoutId = setTimeout(() => { - setIsResizing(false) - }, RESIZE_DEBOUNCE); - }); + return NodeFilter.FILTER_REJECT; + }, + }, + ); - resizeObserver.observe(searchRef.current); - return () => { - if (timeoutId) { - clearTimeout(timeoutId); - } - if (searchRef.current) resizeObserver.unobserve(searchRef.current); - }; - }, [searchRef.current]); + while (walker.nextNode()) { + if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue; + textNodes.push(walker.currentNode as Text); + } - // Main function for finding matches and generating highlight overlays - const refreshSearch = useCallback((scrollTo: ScrollToMatchOption = "none", clearFirst = false) => { - if (clearFirst) setMatches([]) + // Now walk through each node match and extract search results + // One node can have several matches + const newMatches: SearchMatch[] = []; + textNodes.forEach((textNode, idx) => { + // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail + const highlightFullLine = + textNode.parentElement.className.includes("hljs"); - const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable - if (!searchRef.current || !_query) { - setMatches([]); - return; - }; - const query = caseSensitive ? _query : _query.toLowerCase() + let nodeTextValue = caseSensitive + ? textNode.nodeValue + : textNode.nodeValue.toLowerCase(); + let startIndex = 0; + while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) { + // Create a range to measure the size and position of the match + const range = document.createRange(); + range.setStart(textNode, startIndex); + const endIndex = startIndex + query.length; + range.setEnd(textNode, endIndex); + const rect = range.getBoundingClientRect(); + range.detach(); + startIndex = endIndex; - // First grab all text nodes - // Skips any elements with the "find-widget-skip" class - const textNodes: Text[] = []; - const walker = document.createTreeWalker( - searchRef.current, - NodeFilter.SHOW_ALL, - { - acceptNode: (node) => { - if (node.nodeType === Node.ELEMENT_NODE) { - if ((node as Element).classList.contains("find-widget-skip")) return NodeFilter.FILTER_REJECT; - return NodeFilter.FILTER_ACCEPT; - } else if (node.nodeType === Node.TEXT_NODE) { - if (!node.nodeValue) return NodeFilter.FILTER_REJECT; - const nodeValue = caseSensitive ? node.nodeValue : node.nodeValue.toLowerCase() - if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT; - } - return NodeFilter.FILTER_REJECT - } - } - ); + const top = + rect.top + + searchRef.current.clientTop + + searchRef.current.scrollTop; + const left = + rect.left + + searchRef.current.clientLeft + + searchRef.current.scrollLeft; - while (walker.nextNode()) { - if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue - textNodes.push(walker.currentNode as Text); + // Build a match result and push to matches + const newMatch: SearchMatch = { + index: 0, // will set later + textNode, + overlayRectangle: { + top, + left: highlightFullLine ? 2 : left, + width: highlightFullLine + ? searchRef.current.clientWidth - 4 + : rect.width, // equivalent of adding 2 px x padding + height: rect.height, + }, + }; + newMatches.push(newMatch); + + if (highlightFullLine) { + break; // Since highlighting full line no need for multiple overlays, will cause darker highlight + } } + }); - // Now walk through each node match and extract search results - // One node can have several matches - const newMatches: SearchMatch[] = []; - textNodes.forEach((textNode, idx) => { - // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail - const highlightFullLine = textNode.parentElement.className.includes("hljs") + // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights) + // Filter them out by using the overlay rectangle as a hash key + const matchHash = Object.fromEntries( + newMatches.map((match) => [ + JSON.stringify(match.overlayRectangle), + match, + ]), + ); + const filteredMatches = Object.values(matchHash).map((match, index) => ({ + ...match, + index, + })); - let nodeTextValue = caseSensitive ? textNode.nodeValue : textNode.nodeValue.toLowerCase(); - let startIndex = 0; - while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) { - // Create a range to measure the size and position of the match - const range = document.createRange(); - range.setStart(textNode, startIndex); - const endIndex = startIndex + query.length - range.setEnd(textNode, endIndex); - const rect = range.getBoundingClientRect(); - range.detach(); - startIndex = endIndex; - - const top = rect.top + searchRef.current.clientTop + searchRef.current.scrollTop - const left = rect.left + searchRef.current.clientLeft + searchRef.current.scrollLeft; - - // Build a match result and push to matches - const newMatch: SearchMatch = { - index: 0, // will set later - textNode, - overlayRectangle: { - top, - left: highlightFullLine ? 2 : left, - width: highlightFullLine ? (searchRef.current.clientWidth - 4) : rect.width, // equivalent of adding 2 px x padding - height: rect.height, - }, - } - newMatches.push(newMatch); - - if (highlightFullLine) { - break; // Since highlighting full line no need for multiple overlays, will cause darker highlight - } - } - }); - - // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights) - // Filter them out by using the overlay rectangle as a hash key - const matchHash = Object.fromEntries(newMatches.map(match => [JSON.stringify(match.overlayRectangle), match])) - const filteredMatches = Object.values(matchHash).map((match, index) => ({ ...match, index })); - - // Find match closest to the middle of the view - const verticalMiddle = searchRef.current.scrollTop + searchRef.current.clientHeight / 2 - let closestDist = Infinity - let closestMatchToMiddle: SearchMatch | null = null - filteredMatches.forEach((match) => { - const dist = Math.abs(verticalMiddle - match.overlayRectangle.top); - if (dist < closestDist) { - closestDist = dist; - closestMatchToMiddle = match; - } - }) - - // Update matches and scroll to the closest or first match - setMatches(filteredMatches); - if (query.length > 1 && filteredMatches.length) { - if (scrollTo === "first") { - scrollToMatch(filteredMatches[0]); - } - if (scrollTo === "closest") { - scrollToMatch(closestMatchToMiddle) - } - if (scrollTo === "none") { - if (closestMatchToMiddle) { - setCurrentMatch(closestMatchToMiddle) - } else { - setCurrentMatch(filteredMatches[0]) - } - } + // Find match closest to the middle of the view + const verticalMiddle = + searchRef.current.scrollTop + searchRef.current.clientHeight / 2; + let closestDist = Infinity; + let closestMatchToMiddle: SearchMatch | null = null; + filteredMatches.forEach((match) => { + const dist = Math.abs(verticalMiddle - match.overlayRectangle.top); + if (dist < closestDist) { + closestDist = dist; + closestMatchToMiddle = match; } - }, [searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex]) + }); - // Triggers that should cause immediate refresh of results to closest search value: - // Input change (debounced) and window click - const lastUpdateRef = useRef(0); - useEffect(() => { - const debounce = () => { - debouncedInput.current = input - lastUpdateRef.current = Date.now(); - refreshSearch("closest"); + // Update matches and scroll to the closest or first match + setMatches(filteredMatches); + if (query.length > 1 && filteredMatches.length) { + if (scrollTo === "first") { + scrollToMatch(filteredMatches[0]); } - const timeSinceLastUpdate = Date.now() - lastUpdateRef.current; - if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) { - debounce() - } else { - const handler = setTimeout(() => { - debounce() - }, SEARCH_DEBOUNCE - timeSinceLastUpdate); - return () => { - clearTimeout(handler); - }; + if (scrollTo === "closest") { + scrollToMatch(closestMatchToMiddle); } - }, [refreshSearch, input]); - - // Could consider doing any window click but I only handled search div here - // Since usually only clicks in search div will cause content changes in search div - useEffect(() => { - if (!open || !searchRef.current) return - const handleSearchRefClick = () => { - refreshSearch("none"); + if (scrollTo === "none") { + if (closestMatchToMiddle) { + setCurrentMatch(closestMatchToMiddle); + } else { + setCurrentMatch(filteredMatches[0]); + } } - searchRef.current.addEventListener("click", handleSearchRefClick) - return () => { - searchRef.current.removeEventListener("click", handleSearchRefClick); - }; - }, [searchRef.current, refreshSearch, open]); + } + }, + [searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex], + ); - // Triggers that should cause results to temporarily disappear and then reload - // Active = LLM is generating, etc. - const active = useSelector((state: RootState) => state.state.active); - useEffect(() => { - if (active || isResizing) setMatches([]) - else refreshSearch("none") - }, [refreshSearch, active]); - - useEffect(() => { - if (!open) setMatches([]) - else refreshSearch("closest") - }, [refreshSearch, open]); - - useEffect(() => { - refreshSearch("closest") - }, [refreshSearch, caseSensitive, useRegex]) - - // Find widget component - const widget = useMemo(() => { - return ( -
- { - setInput(e.target.value); - }} - placeholder="Search..." - /> -

- {matches.length === 0 ? "No results" : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`} -

-
- { - e.stopPropagation() - previousMatch() - }} - className="h-4 w-4 focus:ring focus:ring-1" - disabled={matches.length < 2 || active} - > - - - { - e.stopPropagation() - nextMatch() - }} - className="h-4 w-4 focus:ring focus:ring-1" - disabled={matches.length < 2 || active} - > - - -
- { - e.stopPropagation() - setCaseSensitive(curr => !curr) - }} - className="h-5 w-6 text-xs focus:ring focus:ring-1 rounded-full border focus:outline-none" - > - Aa - - {/* TODO - add useRegex functionality */} - setOpen(false)} - className="focus:ring focus:ring-1" - > - - -
- ) - }, [open, input, inputRef, caseSensitive, matches, currentMatch, previousMatch, nextMatch]) - - // Generate the highlight overlay elements - const highlights = useMemo(() => { - return matches.map(match => ) - }, [matches, currentMatch]) - - return { - matches, - highlights, - inputRef, - input: debouncedInput, - setInput, - open, - setOpen, - widget + // Triggers that should cause immediate refresh of results to closest search value: + // Input change (debounced) and window click + const lastUpdateRef = useRef(0); + useEffect(() => { + const debounce = () => { + debouncedInput.current = input; + lastUpdateRef.current = Date.now(); + refreshSearch("closest"); + }; + const timeSinceLastUpdate = Date.now() - lastUpdateRef.current; + if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) { + debounce(); + } else { + const handler = setTimeout(() => { + debounce(); + }, SEARCH_DEBOUNCE - timeSinceLastUpdate); + return () => { + clearTimeout(handler); + }; } -} \ No newline at end of file + }, [refreshSearch, input]); + + // Could consider doing any window click but I only handled search div here + // Since usually only clicks in search div will cause content changes in search div + useEffect(() => { + if (!open || !searchRef.current) return; + const handleSearchRefClick = () => { + refreshSearch("none"); + }; + searchRef.current.addEventListener("click", handleSearchRefClick); + return () => { + searchRef.current.removeEventListener("click", handleSearchRefClick); + }; + }, [searchRef.current, refreshSearch, open]); + + // Triggers that should cause results to temporarily disappear and then reload + // Active = LLM is generating, etc. + const active = useSelector((state: RootState) => state.state.active); + useEffect(() => { + if (active || isResizing) setMatches([]); + else refreshSearch("none"); + }, [refreshSearch, active]); + + useEffect(() => { + if (!open) setMatches([]); + else refreshSearch("closest"); + }, [refreshSearch, open]); + + useEffect(() => { + refreshSearch("closest"); + }, [refreshSearch, caseSensitive, useRegex]); + + // Find widget component + const widget = useMemo(() => { + return ( +
+ { + setInput(e.target.value); + }} + placeholder="Search..." + /> +

+ {matches.length === 0 + ? "No results" + : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`} +

+
+ { + e.stopPropagation(); + previousMatch(); + }} + className="h-4 w-4 focus:ring focus:ring-1" + disabled={matches.length < 2 || active} + > + + + { + e.stopPropagation(); + nextMatch(); + }} + className="h-4 w-4 focus:ring focus:ring-1" + disabled={matches.length < 2 || active} + > + + +
+ { + e.stopPropagation(); + setCaseSensitive((curr) => !curr); + }} + className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring focus:ring-1" + > + Aa + + {/* TODO - add useRegex functionality */} + setOpen(false)} + className="focus:ring focus:ring-1" + > + + +
+ ); + }, [ + open, + input, + inputRef, + caseSensitive, + matches, + currentMatch, + previousMatch, + nextMatch, + ]); + + // Generate the highlight overlay elements + const highlights = useMemo(() => { + return matches.map((match) => ( + + )); + }, [matches, currentMatch]); + + return { + matches, + highlights, + inputRef, + input: debouncedInput, + setInput, + open, + setOpen, + widget, + }; +}; diff --git a/gui/src/components/gui/TimelineItem.tsx b/gui/src/components/gui/TimelineItem.tsx index 3796a4cd9..28222abcb 100644 --- a/gui/src/components/gui/TimelineItem.tsx +++ b/gui/src/components/gui/TimelineItem.tsx @@ -30,7 +30,7 @@ interface TimelineItemProps { item: ChatHistoryItem; open: boolean; onToggle: () => void; - children: any; + children: React.ReactNode; iconElement?: any; } From 099a7a601e7e6ad9b46cfaa1b683c8efba2b7af8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 11 Nov 2024 17:25:37 -0800 Subject: [PATCH 02/82] start nested markdown patch --- gui/src/components/markdown/StyledMarkdownPreview.tsx | 3 ++- gui/src/components/markdown/utils/patchNestedMarkdown.ts | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 gui/src/components/markdown/utils/patchNestedMarkdown.ts diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 77158e96a..792763823 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -21,6 +21,7 @@ import FilenameLink from "./FilenameLink"; import StepContainerPreToolbar from "./StepContainerPreToolbar"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; +import { patchNestedMarkdown } from "./utils/patchNestedMarkdown"; const StyledMarkdown = styled.div<{ fontSize?: number; @@ -253,7 +254,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( }); useEffect(() => { - setMarkdownSource(props.source || ""); + setMarkdownSource(patchNestedMarkdown(props.source ?? "")); }, [props.source]); return ( diff --git a/gui/src/components/markdown/utils/patchNestedMarkdown.ts b/gui/src/components/markdown/utils/patchNestedMarkdown.ts new file mode 100644 index 000000000..dc4690424 --- /dev/null +++ b/gui/src/components/markdown/utils/patchNestedMarkdown.ts @@ -0,0 +1,5 @@ +export const patchNestedMarkdown = (source: string): string => { + const firstCode = source.indexOf("```"); + + return source; +}; From 992bb38d8ad208f13572983a1ef513307c87f98f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 11 Nov 2024 18:46:26 -0800 Subject: [PATCH 03/82] patch working --- .../markdown/utils/patchNestedMarkdown.ts | 90 ++++++++++++++++++- 1 file changed, 87 insertions(+), 3 deletions(-) diff --git a/gui/src/components/markdown/utils/patchNestedMarkdown.ts b/gui/src/components/markdown/utils/patchNestedMarkdown.ts index dc4690424..e385711b2 100644 --- a/gui/src/components/markdown/utils/patchNestedMarkdown.ts +++ b/gui/src/components/markdown/utils/patchNestedMarkdown.ts @@ -1,5 +1,89 @@ -export const patchNestedMarkdown = (source: string): string => { - const firstCode = source.indexOf("```"); +/* + This is a patch for outputing markdown code that contains codeblocks - return source; + It notices markdown blocks, keeps track of when that specific block is closed, + and uses ~~~ instead of ``` for that block + + Note, this was benchmarked at sub-millisecond + + // TODO support github-specific markdown as well, edge case +*/ + +export const patchNestedMarkdown = (source: string): string => { + // const start = Date.now(); + let nestCount = 0; + const lines = source.split("\n"); + const trimmedLines = lines.map((l) => l.trim()); + for (let i = 0; i < trimmedLines.length; i++) { + const line = trimmedLines[i]; + if (nestCount) { + if (line.match(/^`+$/)) { + // Ending a block + if (nestCount === 1) lines[i] = "~~~"; // End of markdown block + nestCount--; + } else if (line.startsWith("```")) { + // Going into a nested codeblock + nestCount++; + } + } else { + // Enter the markdown block, start tracking nesting + if (line.startsWith("```md") || line.startsWith("```markdown")) { + nestCount = 1; + lines[i] = lines[i].replace(/^```(md|markdown)/, "~~~"); // Replace backticks with tildes + } + } + } + const out = lines.join("\n"); + // console.log(`patched in ${Date.now() - start}ms`); + return out; }; + +// This version tries to detect if a codeblock without a language specified is a starter codeblock +// It tries again if didn't come back to root nesting, without checking for that ^ +// I didn't use for performance and also because the root nest check doesn't make sense mid-generation + +// export const patchNestedMarkdown = (source: string): string => { +// const start = Date.now(); + +// let attempts = 0; + +// while (attempts <= 2) { +// let nestCount = 0; +// const lines = source.split("\n"); +// const trimmedLines = lines.map((l) => l.trim()); +// for (let i = 0; i < trimmedLines.length; i++) { +// const line = trimmedLines[i]; +// if (nestCount) { +// if (line.match(/^`+$/)) { +// if (attempts === 0 && i !== lines.length && lines[i + 1] !== "") { +// nestCount++; +// continue; +// } +// if (nestCount === 1) lines[i] = "~~~"; +// nestCount--; +// } else if (line.startsWith("```")) { +// // Going into a nested codeblock +// nestCount++; +// } +// } else { +// // Enter the markdown block, start tracking nesting +// if (line.startsWith("```md") || line.startsWith("```markdown")) { +// nestCount = 1; +// lines[i] = lines[i].replace(/^```(md|markdown)/, "~~~"); // Replace backticks with tildes +// } +// } +// } +// if (nestCount === 0) { +// console.log( +// `patch successful in ${Date.now() - start} ms with ${attempts} attempts`, +// ); +// return lines.join("\n"); +// } +// attempts++; +// } + +// console.log( +// `patch failed in ${Date.now() - start} ms with ${attempts} attempts`, +// ); +// return source; +// }; From 1f6ac6b61d5a5144666f3e5aa30fe3779f4acda1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 11 Nov 2024 18:49:10 -0800 Subject: [PATCH 04/82] skip patch if no --- gui/src/components/markdown/utils/patchNestedMarkdown.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/gui/src/components/markdown/utils/patchNestedMarkdown.ts b/gui/src/components/markdown/utils/patchNestedMarkdown.ts index e385711b2..b349939f4 100644 --- a/gui/src/components/markdown/utils/patchNestedMarkdown.ts +++ b/gui/src/components/markdown/utils/patchNestedMarkdown.ts @@ -10,6 +10,7 @@ */ export const patchNestedMarkdown = (source: string): string => { + if (!source.includes("```m")) return source; // For performance // const start = Date.now(); let nestCount = 0; const lines = source.split("\n"); From 1589c208dd030a1db7f23842745922d71443fee0 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 11 Nov 2024 18:53:05 -0800 Subject: [PATCH 05/82] markdown patch performance p2 --- gui/src/components/markdown/utils/patchNestedMarkdown.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/components/markdown/utils/patchNestedMarkdown.ts b/gui/src/components/markdown/utils/patchNestedMarkdown.ts index b349939f4..29b305b26 100644 --- a/gui/src/components/markdown/utils/patchNestedMarkdown.ts +++ b/gui/src/components/markdown/utils/patchNestedMarkdown.ts @@ -10,7 +10,7 @@ */ export const patchNestedMarkdown = (source: string): string => { - if (!source.includes("```m")) return source; // For performance + if (!source.match(/```(md|markdown)/)) return source; // For performance // const start = Date.now(); let nestCount = 0; const lines = source.split("\n"); @@ -30,7 +30,7 @@ export const patchNestedMarkdown = (source: string): string => { // Enter the markdown block, start tracking nesting if (line.startsWith("```md") || line.startsWith("```markdown")) { nestCount = 1; - lines[i] = lines[i].replace(/^```(md|markdown)/, "~~~"); // Replace backticks with tildes + lines[i] = lines[i].replace(/```(md|markdown)/, "~~~"); // Replace backticks with tildes } } } From c419d15116804cadff974d5b71466625049383d0 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 11 Nov 2024 19:10:38 -0800 Subject: [PATCH 06/82] timeline item build fix --- gui/src/components/gui/TimelineItem.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/components/gui/TimelineItem.tsx b/gui/src/components/gui/TimelineItem.tsx index 28222abcb..c3edc4c76 100644 --- a/gui/src/components/gui/TimelineItem.tsx +++ b/gui/src/components/gui/TimelineItem.tsx @@ -30,8 +30,8 @@ interface TimelineItemProps { item: ChatHistoryItem; open: boolean; onToggle: () => void; - children: React.ReactNode; - iconElement?: any; + children: JSX.Element; + iconElement?: JSX.Element; } function TimelineItem(props: TimelineItemProps) { From 5a320626107441ff72f7d75a8e66dd36b80e43f6 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 13 Nov 2024 09:20:59 -0800 Subject: [PATCH 07/82] checkpoints working with undo --- core/index.d.ts | 30 ++-- core/protocol/ideWebview.ts | 4 + extensions/vscode/package-lock.json | 4 +- extensions/vscode/package.json | 2 +- .../vscode/src/diff/vertical/handler.ts | 19 +- .../vscode/src/diff/vertical/manager.ts | 8 +- .../vscode/src/extension/VsCodeMessenger.ts | 42 +++-- gui/src/components/Layout.tsx | 16 +- .../AcceptRejectAllButtons.tsx | 23 ++- .../StepContainer/FeedbackButtons.tsx | 55 ++++++ .../StepContainer/ResponseActions.tsx | 101 +++++++++++ .../StepContainer/StepContainer.tsx | 102 +++++++++++ .../StepContainer/UndoOrRedoAction.tsx | 54 ++++++ gui/src/components/StepContainer/index.ts | 1 + gui/src/components/gui/StepContainer.tsx | 169 ------------------ .../components/mainInput/ContinueInputBox.tsx | 6 +- .../StepContainerPreActionButtons.tsx | 16 +- .../StepContainerPreToolbar.tsx | 28 +-- .../markdown/{utils/index.ts => utils.ts} | 0 .../markdown/utils/useApplyCodeBlock.ts | 45 ----- gui/src/hooks/useApplyCodeBlock.ts | 51 ++++++ gui/src/hooks/useChatHandler.ts | 2 +- gui/src/hooks/useHistory.tsx | 58 +++--- gui/src/pages/edit.tsx | 2 +- gui/src/pages/gui/Chat.tsx | 63 ++----- gui/src/redux/slices/stateSlice.ts | 85 ++++++++- gui/src/redux/slices/uiStateSlice.ts | 34 ---- gui/src/redux/store.ts | 1 - 28 files changed, 612 insertions(+), 409 deletions(-) rename gui/src/components/{mainInput => StepContainer}/AcceptRejectAllButtons.tsx (79%) create mode 100644 gui/src/components/StepContainer/FeedbackButtons.tsx create mode 100644 gui/src/components/StepContainer/ResponseActions.tsx create mode 100644 gui/src/components/StepContainer/StepContainer.tsx create mode 100644 gui/src/components/StepContainer/UndoOrRedoAction.tsx create mode 100644 gui/src/components/StepContainer/index.ts delete mode 100644 gui/src/components/gui/StepContainer.tsx rename gui/src/components/markdown/{utils/index.ts => utils.ts} (100%) delete mode 100644 gui/src/components/markdown/utils/useApplyCodeBlock.ts create mode 100644 gui/src/hooks/useApplyCodeBlock.ts diff --git a/core/index.d.ts b/core/index.d.ts index ac8ea5376..f501ac5d0 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -200,11 +200,16 @@ export interface IContextProvider { loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise; } +export interface Checkpoint { + [filepath: string]: string; +} + export interface PersistedSessionInfo { history: ChatHistory; title: string; workspaceDirectory: string; sessionId: string; + checkpoints?: Checkpoint[]; } export interface SessionInfo { @@ -494,11 +499,14 @@ export interface IDE { stepIndex: number, ): Promise; getOpenFiles(): Promise; - getCurrentFile(): Promise; + getCurrentFile(): Promise< + | undefined + | { + isUntitled: boolean; + path: string; + contents: string; + } + >; getPinnedFiles(): Promise; getSearchResults(query: string): Promise; subprocess(command: string, cwd?: string): Promise<[string, string]>; @@ -785,11 +793,13 @@ export interface CustomCommand { } interface Prediction { - type: "content" - content: string | { - type: "text" - text: string - }[] + type: "content"; + content: + | string + | { + type: "text"; + text: string; + }[]; } interface BaseCompletionOptions { diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 55cb3a9b9..22b1ab530 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -24,6 +24,9 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { streamId: string; curSelectedModelTitle: string; filepath?: string; + // Overwrites the contents of the file with the value of "text" + // This is used in multifile edits when reverting to a given checkpoint + overwriteFileContents?: boolean; }, void, ]; @@ -63,6 +66,7 @@ export interface ApplyState { status?: "streaming" | "done" | "closed"; numDiffs?: number; filepath?: string; + fileContent?: string; } export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 3f6ace66f..3f4123969 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.226", + "version": "0.9.228", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.226", + "version": "0.9.228", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index a3f246a73..76b93351e 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.227", + "version": "0.9.228", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 4583aa62a..fe643b1bb 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -16,6 +16,7 @@ export interface VerticalDiffHandlerOptions { onStatusUpdate: ( status?: ApplyState["status"], numDiffs?: ApplyState["numDiffs"], + fileContent?: ApplyState["fileContent"], ) => void; } @@ -269,7 +270,11 @@ export class VerticalDiffHandler implements vscode.Disposable { }, ); - this.options.onStatusUpdate("closed", this.diffBlocks.length); + this.options.onStatusUpdate( + "closed", + this.diffBlocks.length, + this.editor.document.getText(), + ); this.cancelled = true; this.refreshCodeLens(); @@ -357,7 +362,11 @@ export class VerticalDiffHandler implements vscode.Disposable { this.refreshCodeLens(); - this.options.onStatusUpdate("done", this.diffBlocks.length); + this.options.onStatusUpdate( + "done", + this.diffBlocks.length, + this.editor.document.getText(), + ); // Reject on user typing // const listener = vscode.workspace.onDidChangeTextDocument((e) => { @@ -408,7 +417,11 @@ export class VerticalDiffHandler implements vscode.Disposable { this.shiftCodeLensObjects(startLine, offset); const status = this.diffBlocks.length === 0 ? "closed" : undefined; - this.options.onStatusUpdate(status, this.diffBlocks.length); + this.options.onStatusUpdate( + status, + this.diffBlocks.length, + this.editor.document.getText(), + ); } private shiftCodeLensObjects(startLine: number, offset: number) { diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 2461d9762..80aa54be1 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -213,11 +213,13 @@ export class VerticalDiffManager { endLine, { instant, - onStatusUpdate: (status, numDiffs) => + onStatusUpdate: (status, numDiffs, fileContent) => this.webviewProtocol.request("updateApplyState", { streamId, status, numDiffs, + fileContent, + filepath, }), }, ); @@ -332,12 +334,14 @@ export class VerticalDiffManager { endLine, { input, - onStatusUpdate: (status, numDiffs) => + onStatusUpdate: (status, numDiffs, fileContent) => streamId && this.webviewProtocol.request("updateApplyState", { streamId, status, numDiffs, + fileContent, + filepath, }), }, ); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 4b95e923a..e1356a9c1 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -163,29 +163,13 @@ export class VsCodeMessenger { // If there is a filepath, verify it exists and then open the file if (filepath) { - const fullPath = getFullyQualifiedPath(ide, filepath); + filepath = getFullyQualifiedPath(ide, filepath); - if (!fullPath) { + if (!filepath) { return; } - const fileExists = await this.ide.fileExists(fullPath); - - // If it's a new file, no need to apply, just write directly - if (!fileExists) { - await this.ide.writeFile(fullPath, data.text); - await this.ide.openFile(fullPath); - - await webviewProtocol.request("updateApplyState", { - streamId: data.streamId, - status: "done", - numDiffs: 0, - }); - - return; - } - - await this.ide.openFile(fullPath); + await this.ide.openFile(filepath); } // Get active text editor @@ -196,6 +180,24 @@ export class VsCodeMessenger { return; } + if (data.overwriteFileContents) { + debugger; + // TODO: Delete all contents and write new contents + editor.edit((builder) => + builder.insert(new vscode.Position(0, 0), data.text), + ); + + await webviewProtocol.request("updateApplyState", { + filepath, + streamId: data.streamId, + status: "done", + numDiffs: 0, + fileContent: data.text, + }); + + return; + } + // If document is empty, insert at 0,0 and finish if (!editor.document.getText().trim()) { editor.edit((builder) => @@ -205,6 +207,8 @@ export class VsCodeMessenger { streamId: data.streamId, status: "done", numDiffs: 0, + fileContent: data.text, + filepath, }); return; } diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 0ab40cb03..5974c00cd 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -12,7 +12,11 @@ import { setEditStatus, startEditMode, } from "../redux/slices/editModeState"; -import { setShowDialog, updateApplyState } from "../redux/slices/uiStateSlice"; +import { setShowDialog } from "../redux/slices/uiStateSlice"; +import { + updateApplyState, + updateCurCheckpoint, +} from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getFontSize, isMetaEquivalentKeyPressed } from "../util"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; @@ -158,6 +162,16 @@ const Layout = () => { useWebviewListener( "updateApplyState", async (state) => { + // console.log({ + // filepath: state.filepath, + // content: state.fileContent, + // }); + dispatch( + updateCurCheckpoint({ + filepath: state.filepath, + content: state.fileContent, + }), + ); dispatch(updateApplyState(state)); }, [], diff --git a/gui/src/components/mainInput/AcceptRejectAllButtons.tsx b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx similarity index 79% rename from gui/src/components/mainInput/AcceptRejectAllButtons.tsx rename to gui/src/components/StepContainer/AcceptRejectAllButtons.tsx index aff8355e0..69f044d31 100644 --- a/gui/src/components/mainInput/AcceptRejectAllButtons.tsx +++ b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx @@ -1,21 +1,20 @@ import { useContext } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { RootState } from "../../redux/store"; +import { useDispatch } from "react-redux"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { updateApplyState } from "../../redux/slices/uiStateSlice"; +import { updateApplyState } from "../../redux/slices/stateSlice"; import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; -export default function AcceptRejectAllButtons() { +import { ApplyState } from "core/protocol/ideWebview"; + +export interface AcceptRejectAllButtonsProps { + pendingApplyStates: ApplyState[]; +} + +export default function AcceptRejectAllButtons({ + pendingApplyStates, +}: AcceptRejectAllButtonsProps) { const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); - const applyStates = useSelector( - (state: RootState) => state.uiState.applyStates, - ); - - const pendingApplyStates = applyStates.filter( - (state) => state.status === "done", - ); - const handleAcceptAll = async () => { for (const applyState of pendingApplyStates) { ideMessenger.post("acceptDiff", { filepath: applyState.filepath }); diff --git a/gui/src/components/StepContainer/FeedbackButtons.tsx b/gui/src/components/StepContainer/FeedbackButtons.tsx new file mode 100644 index 000000000..55e870991 --- /dev/null +++ b/gui/src/components/StepContainer/FeedbackButtons.tsx @@ -0,0 +1,55 @@ +import { + HandThumbUpIcon, + HandThumbDownIcon, +} from "@heroicons/react/24/outline"; +import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { ChatHistoryItem } from "core"; +import { useState, useContext } from "react"; +import { useSelector } from "react-redux"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { RootState } from "../../redux/store"; + +export interface FeedbackButtonsProps { + item: ChatHistoryItem; +} + +export default function FeedbackButtons({ item }: FeedbackButtonsProps) { + const [feedback, setFeedback] = useState(undefined); + const ideMessenger = useContext(IdeMessengerContext); + const sessionId = useSelector((store: RootState) => store.state.sessionId); + + const sendFeedback = (feedback: boolean) => { + setFeedback(feedback); + if (item.promptLogs?.length) { + for (const promptLog of item.promptLogs) { + ideMessenger.post("devdata/log", { + tableName: "chat", + data: { ...promptLog, feedback, sessionId }, + }); + } + } + }; + + return ( + <> + sendFeedback(true)} + > + + + sendFeedback(false)} + > + + {" "} + + ); +} diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx new file mode 100644 index 000000000..39b64d69b --- /dev/null +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -0,0 +1,101 @@ +import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline"; +import { stripImages } from "core/llm/images"; +import { CopyIconButton } from "../gui/CopyIconButton"; +import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; +import { ChatHistoryItem } from "core"; +import UndoOrRedoAction from "./UndoOrRedoAction"; +import AcceptRejectAllButtons from "./AcceptRejectAllButtons"; +import FeedbackButtons from "./FeedbackButtons"; + +export interface ResponseActionsProps { + isTruncated: boolean; + onContinueGeneration: () => void; + index: number; + onDelete: () => void; + item: ChatHistoryItem; + isLast: boolean; +} + +export default function ResponseActions({ + onContinueGeneration, + index, + item, + isTruncated, + onDelete, + isLast, +}: ResponseActionsProps) { + const isInMultifileEdit = useSelector( + (store: RootState) => store.state.isMultifileEdit, + ); + + const applyStates = useSelector( + (state: RootState) => state.state.applyStates, + ); + + const pendingApplyStates = applyStates.filter( + (state) => state.status === "done", + ); + + const isStreaming = applyStates.some((state) => state.status === "streaming"); + console.log({ + applyStates, + }); + + // Only render delete button if there is more than one message + const shouldRenderDelete = index !== 1; + + if (isInMultifileEdit) { + return ( +
+
+ + {isLast && !isStreaming && ( +
+ {pendingApplyStates.length > 0 ? ( + + ) : ( + + )} +
+ )} + +
+ +
+
+ ); + } + + return ( +
+ {isTruncated && ( + + + + )} + + {shouldRenderDelete && ( + + + + )} + + + + +
+ ); +} diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx new file mode 100644 index 000000000..40afe5f32 --- /dev/null +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -0,0 +1,102 @@ +import { ChatHistoryItem } from "core"; +import { stripImages } from "core/llm/images"; +import { useEffect, useState } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import styled from "styled-components"; +import { vscBackground } from ".."; +import useUIConfig from "../../hooks/useUIConfig"; +import { RootState } from "../../redux/store"; +import { getFontSize } from "../../util"; +import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; +import ResponseActions from "./ResponseActions"; +import { deleteMessage } from "../../redux/slices/stateSlice"; + +interface StepContainerProps { + item: ChatHistoryItem; + onContinueGeneration: () => void; + index: number; + isLast: boolean; +} + +const ContentDiv = styled.div<{ fontSize?: number }>` + padding-top: 4px; + background-color: ${vscBackground}; + font-size: ${getFontSize()}px; + overflow: hidden; +`; + +export default function StepContainer(props: StepContainerProps) { + const dispatch = useDispatch(); + const [isTruncated, setIsTruncated] = useState(false); + const active = useSelector((store: RootState) => store.state.active); + const curCheckpointIndex = useSelector( + (store: RootState) => store.state.curCheckpointIndex, + ); + const uiConfig = useUIConfig(); + const shouldRenderActions = !active || !props.isLast; + const shouldHideStep = props.index > curCheckpointIndex * 2 + 1; + console.log({ index: props.index, curCheckpointIndex }); + + useEffect(() => { + if (!active) { + const content = stripImages(props.item.message.content).trim(); + const endingPunctuation = [".", "?", "!", "```"]; + + // If not ending in punctuation or emoji, we assume the response got truncated + if ( + !( + endingPunctuation.some((p) => content.endsWith(p)) || + /\p{Emoji}/u.test(content.slice(-2)) + ) + ) { + setIsTruncated(true); + } else { + setIsTruncated(false); + } + } + }, [props.item.message.content, active]); + + function onDelete() { + dispatch(deleteMessage(props.index)); + } + + return ( +
+ + {uiConfig?.displayRawMarkdown ? ( +
+            {stripImages(props.item.message.content)}
+          
+ ) : ( + + )} +
+ {/* We want to occupy space in the DOM regardless of whether the actions are visible to avoid jank on */} +
+ {shouldRenderActions && ( + + )} +
+
+ ); +} diff --git a/gui/src/components/StepContainer/UndoOrRedoAction.tsx b/gui/src/components/StepContainer/UndoOrRedoAction.tsx new file mode 100644 index 000000000..4290126f0 --- /dev/null +++ b/gui/src/components/StepContainer/UndoOrRedoAction.tsx @@ -0,0 +1,54 @@ +import { useDispatch, useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; +import { ArrowUturnLeftIcon } from "@heroicons/react/24/outline"; +import { useApplyCodeBlock } from "../../hooks/useApplyCodeBlock"; +import { setCurCheckpointIndex } from "../../redux/slices/stateSlice"; + +export interface UndoOrRedoActionProps { + index: number; +} + +export default function UndoOrRedoAction({ index }: UndoOrRedoActionProps) { + const dispatch = useDispatch(); + const applyCodeBlock = useApplyCodeBlock(); + + const checkpoints = useSelector( + (store: RootState) => store.state.checkpoints, + ); + + const prevCheckpointIndex = useSelector( + (store: RootState) => store.state.curCheckpointIndex - 1, + ); + + const prevCheckpoint = checkpoints[prevCheckpointIndex]; + + // // `index` is the 0-based index of history items we map over in the step container. + // // This converts that index our checkpoint indices, e.g. first chat message becomes zeroth checkpoint + // const checkpointsIndex = Math.floor(index / 2); + // const checkpoint = checkpoints[checkpointsIndex]; + + async function handleUndo() { + console.log({ prevCheckpointIndex, checkpoints, prevCheckpoint }); + + for (const [filepath, codeBlockContent] of Object.entries(prevCheckpoint)) { + debugger; + await applyCodeBlock({ + filepath, + codeBlockContent, + overwriteFileContents: true, + }); + } + + dispatch(setCurCheckpointIndex(prevCheckpointIndex)); + } + + return ( + + ); +} diff --git a/gui/src/components/StepContainer/index.ts b/gui/src/components/StepContainer/index.ts new file mode 100644 index 000000000..41d4fa945 --- /dev/null +++ b/gui/src/components/StepContainer/index.ts @@ -0,0 +1 @@ +export { default } from "./StepContainer"; diff --git a/gui/src/components/gui/StepContainer.tsx b/gui/src/components/gui/StepContainer.tsx deleted file mode 100644 index b156f6c1f..000000000 --- a/gui/src/components/gui/StepContainer.tsx +++ /dev/null @@ -1,169 +0,0 @@ -import { - BarsArrowDownIcon, - HandThumbDownIcon, - HandThumbUpIcon, - TrashIcon, -} from "@heroicons/react/24/outline"; -import { ChatHistoryItem } from "core"; -import { stripImages } from "core/llm/images"; -import { useContext, useEffect, useState } from "react"; -import { useSelector } from "react-redux"; -import styled from "styled-components"; -import { vscBackground, vscInputBackground } from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import useUIConfig from "../../hooks/useUIConfig"; -import { RootState } from "../../redux/store"; -import { getFontSize } from "../../util"; -import HeaderButtonWithToolTip from "./HeaderButtonWithToolTip"; -import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; -import { CopyIconButton } from "./CopyIconButton"; - -interface StepContainerProps { - item: ChatHistoryItem; - onReverse: () => void; - onUserInput: (input: string) => void; - onRetry: () => void; - onContinueGeneration: () => void; - onDelete: () => void; - open: boolean; - isFirst: boolean; - isLast: boolean; - index: number; - modelTitle?: string; -} - -const ContentDiv = styled.div<{ isUserInput: boolean; fontSize?: number }>` - padding-top: 4px; - background-color: ${(props) => - props.isUserInput ? vscInputBackground : vscBackground}; - font-size: ${(props) => props.fontSize || getFontSize()}px; - overflow: hidden; -`; - -function StepContainer(props: StepContainerProps) { - const active = useSelector((store: RootState) => store.state.active); - const [truncatedEarly, setTruncatedEarly] = useState(false); - const ideMessenger = useContext(IdeMessengerContext); - const [feedback, setFeedback] = useState(undefined); - const sessionId = useSelector((store: RootState) => store.state.sessionId); - - const isUserInput = props.item.message.role === "user"; - const uiConfig = useUIConfig(); - const shouldRenderActions = !active || !props.isLast; - - useEffect(() => { - if (!active) { - const content = stripImages(props.item.message.content).trim(); - const endingPunctuation = [".", "?", "!", "```"]; - - // If not ending in punctuation or emoji, we assume the response got truncated - if ( - !( - endingPunctuation.some((p) => content.endsWith(p)) || - /\p{Emoji}/u.test(content.slice(-2)) - ) - ) { - setTruncatedEarly(true); - } else { - setTruncatedEarly(false); - } - } - }, [props.item.message.content, active]); - - const sendFeedback = (feedback: boolean) => { - setFeedback(feedback); - if (props.item.promptLogs?.length) { - for (const promptLog of props.item.promptLogs) { - ideMessenger.post("devdata/log", { - tableName: "chat", - data: { ...promptLog, feedback, sessionId }, - }); - } - } - }; - - return ( -
- -
- {truncatedEarly && ( - - - - )} - - {props.index !== 1 && ( - - - - )} - - - - sendFeedback(true)} - > - - - - sendFeedback(false)} - > - - -
-
- ); -} - -export default StepContainer; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index c98a69403..2cb0a085c 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -10,7 +10,7 @@ import { newSession, setMessageAtIndex } from "../../redux/slices/stateSlice"; import { RootState } from "../../redux/store"; import ContextItemsPeek from "./ContextItemsPeek"; import TipTapEditor from "./TipTapEditor"; -import AcceptRejectAllButtons from "./AcceptRejectAllButtons"; +import AcceptRejectAllButtons from "../StepContainer/AcceptRejectAllButtons"; interface ContinueInputBoxProps { isLastUserInput: boolean; @@ -78,7 +78,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) { const timeoutRef = useRef(null); const isInMultifileEdit = useSelector( - (state: RootState) => state.state.isInMultifileEdit, + (state: RootState) => state.state.isMultifileEdit, ); const shouldShowAcceptRejectButtons = @@ -118,8 +118,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { return (
- {shouldShowAcceptRejectButtons && } -
state.uiState.nextCodeBlockToApplyIndex, ); - const onClickApply = useApplyCodeBlock({ - codeBlockContent, - streamId: streamIdRef.current, - }); + const applyCodeBlock = useApplyCodeBlock(); const isBottomToolbarPosition = uiConfig?.codeBlockToolbarPosition == "bottom"; @@ -83,10 +80,17 @@ export default function StepContainerPreActionButtons({ streamIdRef.current = uuidv4(); } + function onClickApply() { + applyCodeBlock({ + streamId: streamIdRef.current, + codeBlockContent: codeBlockContent, + }); + } + // Handle apply keyboard shortcut useWebviewListener( "applyCodeFromChat", - onClickApply, + async () => onClickApply(), [isNextCodeBlock, codeBlockContent], !isNextCodeBlock, ); diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index ac13c6d54..1933e93c0 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -7,11 +7,11 @@ import { v4 as uuidv4 } from "uuid"; import { defaultBorderRadius, lightGray, vscEditorBackground } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; -import { updateApplyState } from "../../../redux/slices/uiStateSlice"; +import { updateApplyState } from "../../../redux/slices/stateSlice"; import { RootState } from "../../../redux/store"; import { getFontSize } from "../../../util"; import { childrenToText } from "../utils"; -import { useApplyCodeBlock } from "../utils/useApplyCodeBlock"; +import { useApplyCodeBlock } from "../../../hooks/useApplyCodeBlock"; import ApplyActions from "./ApplyActions"; import CopyButton from "./CopyButton"; import FileInfo from "./FileInfo"; @@ -62,25 +62,21 @@ export default function StepContainerPreToolbar( ) { const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); - const streamIdRef = useRef(null); + const streamIdRef = useRef(uuidv4()); const wasGeneratingRef = useRef(props.isGeneratingCodeBlock); const isMultifileEdit = useSelector( - (state: RootState) => state.state.isInMultifileEdit, + (state: RootState) => state.state.isMultifileEdit, ); const [isExpanded, setIsExpanded] = useState(isMultifileEdit ? false : true); const [codeBlockContent, setCodeBlockContent] = useState(""); const isChatActive = useSelector((state: RootState) => state.state.active); - const onClickApply = useApplyCodeBlock({ - streamId: streamIdRef.current, - filepath: props.filepath, - codeBlockContent: props.codeBlockContent, - }); + const applyCodeBlock = useApplyCodeBlock(); const nextCodeBlockIndex = useSelector( - (state: RootState) => state.uiState.nextCodeBlockToApplyIndex, + (state: RootState) => state.state.nextCodeBlockToApplyIndex, ); const applyState = useSelector((store: RootState) => - store.uiState.applyStates.find( + store.state.applyStates.find( (state) => state.streamId === streamIdRef.current, ), ); @@ -97,14 +93,18 @@ export default function StepContainerPreToolbar( const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex; const hasFileExtension = /\.[0-9a-z]+$/i.test(props.filepath); - if (streamIdRef.current === null) { - streamIdRef.current = uuidv4(); + function onClickApply() { + applyCodeBlock({ + streamId: streamIdRef.current, + filepath: props.filepath, + codeBlockContent: props.codeBlockContent, + }); } // Handle apply keyboard shortcut useWebviewListener( "applyCodeFromChat", - onClickApply, + async () => onClickApply(), [isNextCodeBlock, codeBlockContent], !isNextCodeBlock, ); diff --git a/gui/src/components/markdown/utils/index.ts b/gui/src/components/markdown/utils.ts similarity index 100% rename from gui/src/components/markdown/utils/index.ts rename to gui/src/components/markdown/utils.ts diff --git a/gui/src/components/markdown/utils/useApplyCodeBlock.ts b/gui/src/components/markdown/utils/useApplyCodeBlock.ts deleted file mode 100644 index cb016e1d8..000000000 --- a/gui/src/components/markdown/utils/useApplyCodeBlock.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { useContext } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { - incrementNextCodeBlockToApplyIndex, - updateApplyState, -} from "../../../redux/slices/uiStateSlice"; -import { defaultModelSelector } from "../../../redux/selectors/modelSelectors"; - -export interface useApplyCodeBlock { - streamId: string; - filepath?: string; - codeBlockContent: string; -} - -export function useApplyCodeBlock({ - streamId, - filepath, - codeBlockContent, -}: useApplyCodeBlock) { - const dispatch = useDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - const defaultModel = useSelector(defaultModelSelector); - - const applyCodeBlock = async () => { - dispatch( - updateApplyState({ - streamId, - filepath, - status: "streaming", - }), - ); - - await ideMessenger.request("applyToFile", { - text: codeBlockContent, - streamId, - curSelectedModelTitle: defaultModel.title, - filepath, - }); - - dispatch(incrementNextCodeBlockToApplyIndex({})); - }; - - return applyCodeBlock; -} diff --git a/gui/src/hooks/useApplyCodeBlock.ts b/gui/src/hooks/useApplyCodeBlock.ts new file mode 100644 index 000000000..679ec7d0e --- /dev/null +++ b/gui/src/hooks/useApplyCodeBlock.ts @@ -0,0 +1,51 @@ +import { useContext, useRef } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { + incrementNextCodeBlockToApplyIndex, + updateApplyState, +} from "../redux/slices/stateSlice"; +import { defaultModelSelector } from "../redux/selectors/modelSelectors"; +import { v4 as uuidv4 } from "uuid"; + +export interface useApplyCodeBlockParams { + codeBlockContent: string; + streamId?: string; + filepath?: string; + overwriteFileContents?: boolean; +} + +export function useApplyCodeBlock() { + const dispatch = useDispatch(); + const streamIdRef = useRef(uuidv4()); + const ideMessenger = useContext(IdeMessengerContext); + const defaultModel = useSelector(defaultModelSelector); + + const applyCodeBlock = async ({ + streamId, + filepath, + codeBlockContent, + overwriteFileContents, + }: useApplyCodeBlockParams) => { + dispatch( + updateApplyState({ + filepath, + // When reverting to a checkpoint, we don't have a pre-existing streamId + streamId: streamId ?? streamIdRef.current, + status: "streaming", + }), + ); + + await ideMessenger.request("applyToFile", { + streamId, + filepath, + overwriteFileContents, + text: codeBlockContent, + curSelectedModelTitle: defaultModel.title, + }); + + dispatch(incrementNextCodeBlockToApplyIndex({})); + }; + + return applyCodeBlock; +} diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 2e35acc53..4cd8fba00 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -34,7 +34,7 @@ import { setMessageAtIndex, streamUpdate, } from "../redux/slices/stateSlice"; -import { resetNextCodeBlockToApplyIndex } from "../redux/slices/uiStateSlice"; +import { resetNextCodeBlockToApplyIndex } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import useHistory from "./useHistory"; diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 8ebcd4581..0390f1110 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -2,10 +2,9 @@ import { Dispatch } from "@reduxjs/toolkit"; import { PersistedSessionInfo, SessionInfo } from "core"; import { stripImages } from "core/llm/images"; -import { useCallback, useContext, useEffect } from "react"; +import { useCallback, useContext } from "react"; import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; -import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { newSession } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; @@ -22,7 +21,6 @@ function truncateText(text: string, maxLength: number) { function useHistory(dispatch: Dispatch) { const state = useSelector((state: RootState) => state.state); - const defaultModel = useSelector(defaultModelSelector); const ideMessenger = useContext(IdeMessengerContext); const { lastSessionId, setLastSessionId } = useLastSessionContext(); @@ -50,16 +48,7 @@ function useHistory(dispatch: Dispatch) { return result.status === "success" ? result.content : undefined; } - async function saveSession(open_new_session = true) { - if (state.history.length === 0) return; - - const stateCopy = { ...state }; - if (open_new_session) { - dispatch(newSession()); - updateLastSessionId(stateCopy.sessionId); - } - await new Promise((resolve) => setTimeout(resolve, 10)); - + async function getSessionTitle(stateCopy: typeof state): Promise { if ( state.config?.experimental?.getChatTitles && stateCopy.title === "New Session" @@ -71,32 +60,47 @@ function useHistory(dispatch: Dispatch) { ?.message?.content?.toString(); if (assistantResponse) { - stateCopy.title = await getChatTitle(assistantResponse); + return await getChatTitle(assistantResponse); } } catch (e) { - throw new Error("Unable to get chat title"); + console.error("Unable to get chat title:", e); } } // Fallback if we get an error above or if the user has not set getChatTitles - let title = - stateCopy.title === "New Session" - ? truncateText( - stripImages(stateCopy.history[0].message.content) - .split("\n") - .filter((l) => l.trim() !== "") - .slice(-1)[0] || "", - MAX_TITLE_LENGTH, - ) - : stateCopy.title?.length > 0 - ? stateCopy.title - : (await getSession(stateCopy.sessionId)).title; // to ensure titles are synced with updates from history page. + return stateCopy.title === "New Session" + ? truncateText( + stripImages(stateCopy.history[0].message.content) + .split("\n") + .filter((l) => l.trim() !== "") + .slice(-1)[0] || "", + MAX_TITLE_LENGTH, + ) + : stateCopy.title?.length > 0 + ? stateCopy.title + : (await getSession(stateCopy.sessionId)).title; // to ensure titles are synced with updates from history page. + } + + async function saveSession(openNewSession = true) { + if (state.history.length === 0) return; + + const stateCopy = { ...state }; + + if (openNewSession) { + dispatch(newSession()); + updateLastSessionId(stateCopy.sessionId); + } + + await new Promise((resolve) => setTimeout(resolve, 10)); + + const title = await getSessionTitle(stateCopy); const sessionInfo: PersistedSessionInfo = { history: stateCopy.history, title: title, sessionId: stateCopy.sessionId, workspaceDirectory: window.workspacePaths?.[0] || "", + checkpoints: stateCopy.checkpoints, }; return await ideMessenger.request("history/save", sessionInfo); diff --git a/gui/src/pages/edit.tsx b/gui/src/pages/edit.tsx index b2a7e4e77..e608c8d73 100644 --- a/gui/src/pages/edit.tsx +++ b/gui/src/pages/edit.tsx @@ -96,7 +96,7 @@ function Edit() { const applyState = useSelector( (store: RootState) => - store.uiState.applyStates.find((state) => state.streamId === "edit") + store.state.applyStates.find((state) => state.streamId === "edit") ?.status ?? "closed", ); diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index d68879881..3701b753e 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -25,10 +25,9 @@ import { vscBackground, } from "../../components"; import { ChatScrollAnchor } from "../../components/ChatScrollAnchor"; -import StepContainer from "../../components/gui/StepContainer"; +import StepContainer from "../../components/StepContainer"; import TimelineItem from "../../components/gui/TimelineItem"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; -import { defaultInputModifiers } from "../../components/mainInput/inputModifiers"; import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; import { TutorialCard } from "../../components/mainInput/TutorialCard"; import { @@ -43,7 +42,6 @@ import { useWebviewListener } from "../../hooks/useWebviewListener"; import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; import { clearLastResponse, - deleteMessage, newSession, setInactive, } from "../../redux/slices/stateSlice"; @@ -63,7 +61,6 @@ import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import { useFindWidget } from "../../components/find/FindWidget"; - const StopButton = styled.div` background-color: ${vscBackground}; width: fit-content; @@ -147,11 +144,11 @@ export function Chat() { const smoothScrollToBottom = useCallback(async () => { if (!stepsDivRef.current) return; - const elem = stepsDivRef.current + const elem = stepsDivRef.current; elem.scrollTo({ top: elem.scrollHeight - elem.clientHeight, - behavior: 'smooth' - }) + behavior: "smooth", + }); setIsAtBottom(true); }, [stepsDivRef, setIsAtBottom]); @@ -163,7 +160,7 @@ export function Chat() { useEffect(() => { setTimeout(() => { smoothScrollToBottom(); - }, 400) + }, 400); }, [smoothScrollToBottom, state.sessionId]); useEffect(() => { @@ -196,7 +193,7 @@ export function Chat() { setIsAtBottom(atBottom); }; - const { widget, highlights } = useFindWidget(stepsDivRef) + const { widget, highlights } = useFindWidget(stepsDivRef); const sendInput = useCallback( (editorState: JSONContent, modifiers: InputModifiers) => { @@ -291,13 +288,7 @@ export function Chat() { setLocalStorage("mainTextEntryCounter", 1); } }, - [ - state.history, - state.contextItems, - defaultModel, - state, - streamResponse, - ], + [state.history, state.contextItems, defaultModel, state, streamResponse], ); useWebviewListener( @@ -318,14 +309,14 @@ export function Chat() { [state.history], ); - const showScrollbar = state.config.ui?.showChatScrollbar || false + const showScrollbar = state.config.ui?.showChatScrollbar || false; return ( <> {widget} 0 ? "h-full" : ""}`} + className={`overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${state.history.length > 0 ? "h-full" : ""}`} onScroll={handleScroll} > {highlights} @@ -340,12 +331,7 @@ export function Chat() { {item.message.role === "user" ? ( { - streamResponse( - editorState, - modifiers, - ideMessenger, - index, - ); + streamResponse(editorState, modifiers, ideMessenger, index); }} isLastUserInput={isLastUserInput(index)} isMainInput={false} @@ -366,10 +352,7 @@ export function Chat() { color="red" /> ) : ( - + ) } open={ @@ -379,30 +362,12 @@ export function Chat() { : true : stepsOpen[index]! } - onToggle={() => { }} + onToggle={() => {}} > { }} item={item} - onReverse={() => { }} - onRetry={() => { - streamResponse( - state.history[index - 1].editorState, - state.history[index - 1].modifiers ?? - defaultInputModifiers, - ideMessenger, - index - 1, - ); - }} onContinueGeneration={() => { window.postMessage( { @@ -415,10 +380,6 @@ export function Chat() { "*", ); }} - onDelete={() => { - dispatch(deleteMessage(index)); - }} - modelTitle={item.promptLogs?.[0]?.modelTitle ?? ""} />
diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index e3ce22eb6..6c45a0b63 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -3,6 +3,7 @@ import { JSONContent } from "@tiptap/react"; import { ChatHistoryItem, ChatMessage, + Checkpoint, ContextItemId, ContextItemWithId, PersistedSessionInfo, @@ -14,6 +15,7 @@ import { stripImages } from "core/llm/images"; import { createSelector } from "reselect"; import { v4 as uuidv4, v4 } from "uuid"; import { RootState } from "../store"; +import { ApplyState } from "core/protocol/ideWebview"; export const memoizedContextItemsSelector = createSelector( [(state: RootState) => state.state.history], @@ -30,7 +32,6 @@ export const memoizedContextItemsSelector = createSelector( type ChatHistoryItemWithMessageId = ChatHistoryItem & { message: ChatMessage & { id: string }; }; - type State = { history: ChatHistoryItemWithMessageId[]; contextItems: ContextItemWithId[]; @@ -44,7 +45,11 @@ type State = { mainEditorContent?: JSONContent; selectedProfileId: string; configError: ConfigValidationError[] | undefined; - isInMultifileEdit: boolean; + checkpoints: Checkpoint[]; + curCheckpointIndex: number; + isMultifileEdit: boolean; + applyStates: ApplyState[]; + nextCodeBlockToApplyIndex: number; }; const initialState: State = { @@ -72,7 +77,11 @@ const initialState: State = { sessionId: v4(), defaultModelTitle: "GPT-4", selectedProfileId: "local", - isInMultifileEdit: false, + checkpoints: [], + isMultifileEdit: false, + curCheckpointIndex: 0, + nextCodeBlockToApplyIndex: 0, + applyStates: [], }; export const stateSlice = createSlice({ @@ -204,6 +213,13 @@ export const stateSlice = createSlice({ // https://github.com/continuedev/continue/pull/1021 // state.contextItems = []; state.active = true; + console.log( + "incrementing state.curCheckpointIndex from ", + state.curCheckpointIndex, + " to ", + state.curCheckpointIndex + 1, + ); + state.curCheckpointIndex = state.curCheckpointIndex + 1; }, setMessageAtIndex: ( state, @@ -270,13 +286,16 @@ export const stateSlice = createSlice({ state.history = payload.history as any; state.title = payload.title; state.sessionId = payload.sessionId; + state.checkpoints = payload.checkpoints; + // state.applyStates = []; } else { state.history = []; state.contextItems = []; state.active = false; state.title = "New Session"; state.sessionId = v4(); - state.isInMultifileEdit = false; + state.checkpoints = []; + // state.applyStates = []; } }, deleteContextWithIds: ( @@ -418,8 +437,57 @@ export const stateSlice = createSlice({ selectedProfileId: payload, }; }, - setIsInMultifileEdit: (state, action: PayloadAction) => { - state.isInMultifileEdit = action.payload; + + setIsInMultifileEdit: (state, { payload }: PayloadAction) => { + state.isMultifileEdit = payload; + }, + setCurCheckpointIndex: (state, { payload }: PayloadAction) => { + state.curCheckpointIndex = payload; + }, + updateCurCheckpoint: ( + state, + { payload }: PayloadAction<{ filepath: string; content: string }>, + ) => { + // If the user has explicitly checked out a given checkpoint, `curCheckpointIndex` will be set to that index. + // Else, we assume the current checkpoint index is the end of the checkpoints array. + // const index = + // state.curCheckpointIndex === -1 + // ? state.history.length / 2 - 1 + // : state.curCheckpointIndex; + + console.log("updating checkpoint"); + console.log({ + index: state.curCheckpointIndex, + historyLength: state.history.length, + filepath: payload.filepath, + content: payload.content, + }); + + state.checkpoints[state.curCheckpointIndex] = { + ...state.checkpoints[state.curCheckpointIndex], + [payload.filepath]: payload.content, + }; + }, + incrementNextCodeBlockToApplyIndex: (state, action) => { + state.nextCodeBlockToApplyIndex++; + }, + updateApplyState: (state, { payload }: PayloadAction) => { + const index = state.applyStates.findIndex( + (applyState) => applyState.streamId === payload.streamId, + ); + + const curApplyState = state.applyStates[index]; + + if (index === -1) { + state.applyStates.push(payload); + } else { + curApplyState.status = payload.status ?? curApplyState.status; + curApplyState.numDiffs = payload.numDiffs ?? curApplyState.numDiffs; + curApplyState.filepath = payload.filepath ?? curApplyState.filepath; + } + }, + resetNextCodeBlockToApplyIndex: (state) => { + state.nextCodeBlockToApplyIndex = 0; }, }, }); @@ -449,6 +517,11 @@ export const { deleteMessage, setIsGatheringContext, setIsInMultifileEdit, + updateCurCheckpoint, + setCurCheckpointIndex, + resetNextCodeBlockToApplyIndex, + incrementNextCodeBlockToApplyIndex, + updateApplyState, } = stateSlice.actions; export default stateSlice.reducer; diff --git a/gui/src/redux/slices/uiStateSlice.ts b/gui/src/redux/slices/uiStateSlice.ts index 24c4fc194..f4b531c39 100644 --- a/gui/src/redux/slices/uiStateSlice.ts +++ b/gui/src/redux/slices/uiStateSlice.ts @@ -1,5 +1,4 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; -import { ApplyState } from "core/protocol/ideWebview"; import { defaultOnboardingCardState, OnboardingCardState, @@ -9,13 +8,7 @@ type UiState = { showDialog: boolean; dialogMessage: string | JSX.Element | undefined; dialogEntryOn: boolean; - nextCodeBlockToApplyIndex: number; onboardingCard: OnboardingCardState; - - /** - * Syncs the sidebar with the accepted/rejected blocks in the editor. Reused for Edit as well. - */ - applyStates: ApplyState[]; }; export const uiStateSlice = createSlice({ @@ -24,9 +17,7 @@ export const uiStateSlice = createSlice({ showDialog: false, dialogMessage: "", dialogEntryOn: false, - nextCodeBlockToApplyIndex: 0, onboardingCard: defaultOnboardingCardState, - applyStates: [], } as UiState, reducers: { setOnboardingCard: ( @@ -50,28 +41,6 @@ export const uiStateSlice = createSlice({ setShowDialog: (state, action: PayloadAction) => { state.showDialog = action.payload; }, - - resetNextCodeBlockToApplyIndex: (state) => { - state.nextCodeBlockToApplyIndex = 0; - }, - incrementNextCodeBlockToApplyIndex: (state, action) => { - state.nextCodeBlockToApplyIndex++; - }, - updateApplyState: (state, { payload }: PayloadAction) => { - const index = state.applyStates.findIndex( - (applyState) => applyState.streamId === payload.streamId, - ); - - const curApplyState = state.applyStates[index]; - - if (index === -1) { - state.applyStates.push(payload); - } else { - curApplyState.status = payload.status ?? curApplyState.status; - curApplyState.numDiffs = payload.numDiffs ?? curApplyState.numDiffs; - curApplyState.filepath = payload.filepath ?? curApplyState.filepath; - } - }, }, }); @@ -80,9 +49,6 @@ export const { setDialogMessage, setDialogEntryOn, setShowDialog, - resetNextCodeBlockToApplyIndex, - incrementNextCodeBlockToApplyIndex, - updateApplyState, } = uiStateSlice.actions; export default uiStateSlice.reducer; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index a5d0313f4..5a6bc51f5 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -10,7 +10,6 @@ import { createFilter } from "redux-persist-transform-filter"; import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2"; import storage from "redux-persist/lib/storage"; import editModeStateReducer from "./slices/editModeState"; - export interface ChatMessage { role: "system" | "user" | "assistant"; content: string; From 121be85a69837a1d31dde31f7fca7098458ed38d Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 13 Nov 2024 17:22:21 -0800 Subject: [PATCH 08/82] feat: redo action --- core/protocol/ideWebview.ts | 5 +- extensions/vscode/src/commands.ts | 34 ++++++- .../vscode/src/extension/VsCodeMessenger.ts | 94 +++++++++++++------ .../StepContainer/AcceptRejectAllButtons.tsx | 36 ++----- .../StepContainer/ResponseActions.tsx | 44 ++++++--- .../StepContainer/StepContainer.tsx | 33 +++++-- .../StepContainer/UndoOrRedoAction.tsx | 67 ++++++++----- .../StepContainerPreActionButtons.tsx | 4 +- .../StepContainerPreToolbar.tsx | 23 ++--- .../markdown/StyledMarkdownPreview.tsx | 12 +-- gui/src/hooks/useApplyCodeBlock.ts | 10 +- gui/src/pages/edit/EditInputHeader.tsx | 4 +- gui/src/redux/slices/stateSlice.ts | 10 +- 13 files changed, 230 insertions(+), 146 deletions(-) diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 77f958b92..75a4667a9 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -30,6 +30,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { }, void, ]; + overwriteFile: [{ filepath: string; prevFileContent: string | null }, void]; showTutorial: [undefined, void]; showFile: [{ filepath: string }, void]; openConfigJson: [undefined, void]; @@ -42,8 +43,8 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { "jetbrains/editorInsetHeight": [{ height: number }, void]; "vscode/openMoveRightMarkdown": [undefined, void]; setGitHubAuthToken: [{ token: string }, void]; - acceptDiff: [{ filepath: string }, void]; - rejectDiff: [{ filepath: string }, void]; + acceptDiff: [{ filepath: string; streamId?: string }, void]; + rejectDiff: [{ filepath: string; streamId?: string }, void]; "edit/sendPrompt": [ { prompt: MessageContent; range: RangeInFileWithContents }, void, diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 4733dee6f..0a5943551 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -271,7 +271,10 @@ const commandsMap: ( } return { - "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { + "continue.acceptDiff": async ( + newFilepath?: string | vscode.Uri, + streamId?: string, + ) => { captureCommandTelemetry("acceptDiff"); let fullPath = newFilepath; @@ -290,8 +293,23 @@ const commandsMap: ( await sidebar.webviewProtocol.request("setEditStatus", { status: "done", }); + + if (streamId && fullPath) { + const fileContent = await ide.readFile(fullPath); + + await sidebar.webviewProtocol.request("updateApplyState", { + fileContent, + filepath: fullPath, + streamId: streamId, + status: "closed", + numDiffs: 0, + }); + } }, - "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { + "continue.rejectDiff": async ( + newFilepath?: string | vscode.Uri, + streamId?: string, + ) => { captureCommandTelemetry("rejectDiff"); let fullPath = newFilepath; @@ -309,6 +327,18 @@ const commandsMap: ( await sidebar.webviewProtocol.request("setEditStatus", { status: "done", }); + + if (streamId && fullPath) { + const fileContent = await ide.readFile(fullPath); + + await sidebar.webviewProtocol.request("updateApplyState", { + fileContent, + filepath: fullPath, + streamId: streamId, + status: "closed", + numDiffs: 0, + }); + } }, "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { captureCommandTelemetry("acceptVerticalDiffBlock"); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index ff60b13c8..6bb250041 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -152,26 +152,48 @@ export class VsCodeMessenger { ); }); - webviewProtocol.on("acceptDiff", async ({ data: { filepath } }) => { - await vscode.commands.executeCommand("continue.acceptDiff", filepath); - }); + webviewProtocol.on( + "acceptDiff", + async ({ data: { filepath, streamId } }) => { + await vscode.commands.executeCommand( + "continue.acceptDiff", + filepath, + streamId, + ); + }, + ); - webviewProtocol.on("rejectDiff", async ({ data: { filepath } }) => { - await vscode.commands.executeCommand("continue.rejectDiff", filepath); - }); + webviewProtocol.on( + "rejectDiff", + async ({ data: { filepath, streamId } }) => { + await vscode.commands.executeCommand( + "continue.rejectDiff", + filepath, + streamId, + ); + }, + ); this.onWebview("applyToFile", async ({ data }) => { let filepath = data.filepath; // If there is a filepath, verify it exists and then open the file if (filepath) { - filepath = getFullyQualifiedPath(ide, filepath); + const fullPath = getFullyQualifiedPath(ide, filepath); - if (!filepath) { + if (!fullPath) { return; } - await this.ide.openFile(filepath); + const fileExists = await this.ide.fileExists(fullPath); + + // If there is no existing file at the path, create it + if (!fileExists) { + await this.ide.writeFile(fullPath, ""); + await this.ide.openFile(fullPath); + } + + await this.ide.openFile(fullPath); } // Get active text editor @@ -182,36 +204,19 @@ export class VsCodeMessenger { return; } - if (data.overwriteFileContents) { - debugger; - // TODO: Delete all contents and write new contents - editor.edit((builder) => - builder.insert(new vscode.Position(0, 0), data.text), - ); - - await webviewProtocol.request("updateApplyState", { - filepath, - streamId: data.streamId, - status: "done", - numDiffs: 0, - fileContent: data.text, - }); - - return; - } - // If document is empty, insert at 0,0 and finish if (!editor.document.getText().trim()) { editor.edit((builder) => builder.insert(new vscode.Position(0, 0), data.text), ); + await webviewProtocol.request("updateApplyState", { streamId: data.streamId, - status: "done", + status: "closed", numDiffs: 0, fileContent: data.text, - filepath, }); + return; } @@ -299,6 +304,37 @@ export class VsCodeMessenger { this.onWebview("openUrl", (msg) => { vscode.env.openExternal(vscode.Uri.parse(msg.data)); }); + + this.onWebview( + "overwriteFile", + async ({ data: { prevFileContent, filepath } }) => { + if (prevFileContent === null) { + // TODO: Delete the file + return; + } + + await this.ide.openFile(filepath); + + // Get active text editor + const editor = vscode.window.activeTextEditor; + + if (!editor) { + vscode.window.showErrorMessage("No active editor to apply edits to"); + return; + } + + editor.edit((builder) => + builder.replace( + new vscode.Range( + editor.document.positionAt(0), + editor.document.positionAt(editor.document.getText().length), + ), + prevFileContent, + ), + ); + }, + ); + this.onWebview("insertAtCursor", async (msg) => { const editor = vscode.window.activeTextEditor; if (editor === undefined || !editor.selection) { diff --git a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx index 69f044d31..9e9afe23f 100644 --- a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx +++ b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx @@ -1,7 +1,5 @@ import { useContext } from "react"; -import { useDispatch } from "react-redux"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { updateApplyState } from "../../redux/slices/stateSlice"; import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core/protocol/ideWebview"; @@ -12,45 +10,29 @@ export interface AcceptRejectAllButtonsProps { export default function AcceptRejectAllButtons({ pendingApplyStates, }: AcceptRejectAllButtonsProps) { - const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); - const handleAcceptAll = async () => { - for (const applyState of pendingApplyStates) { - ideMessenger.post("acceptDiff", { filepath: applyState.filepath }); - dispatch( - updateApplyState({ - streamId: applyState.streamId, - status: "closed", - }), - ); + async function handleAcceptOrReject(status: "acceptDiff" | "rejectDiff") { + for (const { filepath, streamId } of pendingApplyStates) { + ideMessenger.post(status, { + filepath, + streamId, + }); } - }; - - const handleRejectAll = async () => { - for (const applyState of pendingApplyStates) { - ideMessenger.post("rejectDiff", { filepath: applyState.filepath }); - dispatch( - updateApplyState({ - streamId: applyState.streamId, - status: "closed", - }), - ); - } - }; + } return (
+
+ + + {shouldRenderRedo && ( + + )} +
); } diff --git a/gui/src/components/markdown/StepContainerPreActionButtons.tsx b/gui/src/components/markdown/StepContainerPreActionButtons.tsx index bed618a99..669479fa3 100644 --- a/gui/src/components/markdown/StepContainerPreActionButtons.tsx +++ b/gui/src/components/markdown/StepContainerPreActionButtons.tsx @@ -66,7 +66,7 @@ export default function StepContainerPreActionButtons({ const uiConfig = useUIConfig(); const streamIdRef = useRef(null); const nextCodeBlockIndex = useSelector( - (state: RootState) => state.uiState.nextCodeBlockToApplyIndex, + (state: RootState) => state.state.nextCodeBlockToApplyIndex, ); const applyCodeBlock = useApplyCodeBlock(); @@ -82,8 +82,8 @@ export default function StepContainerPreActionButtons({ function onClickApply() { applyCodeBlock({ + codeBlockContent, streamId: streamIdRef.current, - codeBlockContent: codeBlockContent, }); } diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 1933e93c0..39272df92 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -60,7 +60,6 @@ export interface StepContainerPreToolbarProps { export default function StepContainerPreToolbar( props: StepContainerPreToolbarProps, ) { - const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); const streamIdRef = useRef(uuidv4()); const wasGeneratingRef = useRef(props.isGeneratingCodeBlock); @@ -138,23 +137,17 @@ export default function StepContainerPreToolbar( }, [isGeneratingCodeBlock]); function onClickAcceptApply() { - ideMessenger.post("acceptDiff", { filepath: props.filepath }); - dispatch( - updateApplyState({ - streamId: streamIdRef.current, - status: "closed", - }), - ); + ideMessenger.post("acceptDiff", { + filepath: props.filepath, + streamId: streamIdRef.current, + }); } function onClickRejectApply() { - ideMessenger.post("rejectDiff", { filepath: props.filepath }); - dispatch( - updateApplyState({ - streamId: streamIdRef.current, - status: "closed", - }), - ); + ideMessenger.post("rejectDiff", { + filepath: props.filepath, + streamId: streamIdRef.current, + }); } function onClickExpand() { diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 77158e96a..8def16617 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -136,13 +136,13 @@ function processCodeBlocks(tree: any) { node.lang = node.lang.split(".").slice(-1)[0]; } + node.data = node.data || {}; + node.data.hProperties = node.data.hProperties || {}; + + node.data.hProperties.isGeneratingCodeBlock = lastCodeNode === node; + node.data.hProperties.codeBlockContent = node.value; + if (node.meta) { - node.data = node.data || {}; - node.data.hProperties = node.data.hProperties || {}; - - node.data.hProperties.isGeneratingCodeBlock = lastCodeNode === node; - node.data.hProperties.codeBlockContent = node.value; - let meta = node.meta.split(" "); node.data.hProperties.filepath = meta[0]; node.data.hProperties.range = meta[1]; diff --git a/gui/src/hooks/useApplyCodeBlock.ts b/gui/src/hooks/useApplyCodeBlock.ts index 679ec7d0e..9ac1888f5 100644 --- a/gui/src/hooks/useApplyCodeBlock.ts +++ b/gui/src/hooks/useApplyCodeBlock.ts @@ -1,4 +1,4 @@ -import { useContext, useRef } from "react"; +import { useContext } from "react"; import { useDispatch, useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { @@ -6,18 +6,15 @@ import { updateApplyState, } from "../redux/slices/stateSlice"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { v4 as uuidv4 } from "uuid"; export interface useApplyCodeBlockParams { codeBlockContent: string; streamId?: string; filepath?: string; - overwriteFileContents?: boolean; } export function useApplyCodeBlock() { const dispatch = useDispatch(); - const streamIdRef = useRef(uuidv4()); const ideMessenger = useContext(IdeMessengerContext); const defaultModel = useSelector(defaultModelSelector); @@ -25,13 +22,11 @@ export function useApplyCodeBlock() { streamId, filepath, codeBlockContent, - overwriteFileContents, }: useApplyCodeBlockParams) => { dispatch( updateApplyState({ filepath, - // When reverting to a checkpoint, we don't have a pre-existing streamId - streamId: streamId ?? streamIdRef.current, + streamId, status: "streaming", }), ); @@ -39,7 +34,6 @@ export function useApplyCodeBlock() { await ideMessenger.request("applyToFile", { streamId, filepath, - overwriteFileContents, text: codeBlockContent, curSelectedModelTitle: defaultModel.title, }); diff --git a/gui/src/pages/edit/EditInputHeader.tsx b/gui/src/pages/edit/EditInputHeader.tsx index b7b66de8c..e0f819c87 100644 --- a/gui/src/pages/edit/EditInputHeader.tsx +++ b/gui/src/pages/edit/EditInputHeader.tsx @@ -77,7 +77,7 @@ export function EditInputHeader(editInputHeaderParams: EditInputHeaderParams) { )} */}
- + - + { diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 6c45a0b63..8c95599a6 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -213,12 +213,6 @@ export const stateSlice = createSlice({ // https://github.com/continuedev/continue/pull/1021 // state.contextItems = []; state.active = true; - console.log( - "incrementing state.curCheckpointIndex from ", - state.curCheckpointIndex, - " to ", - state.curCheckpointIndex + 1, - ); state.curCheckpointIndex = state.curCheckpointIndex + 1; }, setMessageAtIndex: ( @@ -287,7 +281,7 @@ export const stateSlice = createSlice({ state.title = payload.title; state.sessionId = payload.sessionId; state.checkpoints = payload.checkpoints; - // state.applyStates = []; + state.curCheckpointIndex = 0; } else { state.history = []; state.contextItems = []; @@ -295,7 +289,7 @@ export const stateSlice = createSlice({ state.title = "New Session"; state.sessionId = v4(); state.checkpoints = []; - // state.applyStates = []; + state.curCheckpointIndex = 0; } }, deleteContextWithIds: ( From 2119391b1592b34ed2bd917b39de771752274fcc Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 13 Nov 2024 18:19:20 -0800 Subject: [PATCH 09/82] handle redo bug --- core/protocol/ideWebview.ts | 3 - .../StepContainer/MultifileEditActions.tsx | 57 +++++++++++++++++ .../StepContainer/ResponseActions.tsx | 62 +------------------ ...rRedoAction.tsx => UndoAndRedoButtons.tsx} | 6 +- .../components/mainInput/ContinueInputBox.tsx | 8 --- gui/src/components/mainInput/InputToolbar.tsx | 4 +- gui/src/hooks/useChatHandler.ts | 5 ++ 7 files changed, 67 insertions(+), 78 deletions(-) create mode 100644 gui/src/components/StepContainer/MultifileEditActions.tsx rename gui/src/components/StepContainer/{UndoOrRedoAction.tsx => UndoAndRedoButtons.tsx} (93%) diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 75a4667a9..1fa5e84a5 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -24,9 +24,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { streamId: string; curSelectedModelTitle: string; filepath?: string; - // Overwrites the contents of the file with the value of "text" - // This is used in multifile edits when reverting to a given checkpoint - overwriteFileContents?: boolean; }, void, ]; diff --git a/gui/src/components/StepContainer/MultifileEditActions.tsx b/gui/src/components/StepContainer/MultifileEditActions.tsx new file mode 100644 index 000000000..db6b0d871 --- /dev/null +++ b/gui/src/components/StepContainer/MultifileEditActions.tsx @@ -0,0 +1,57 @@ +import { useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; +import AcceptRejectAllButtons from "./AcceptRejectAllButtons"; +import FeedbackButtons from "./FeedbackButtons"; +import UndoAndRedoButtons from "./UndoAndRedoButtons"; +import { ChatHistoryItem } from "core"; + +export interface MultifileEditActionsProps { + index: number; + item: ChatHistoryItem; +} + +export default function MultifileEditActions({ + index, + item, +}: MultifileEditActionsProps) { + const curCheckpointIndex = useSelector( + (store: RootState) => store.state.curCheckpointIndex, + ); + + const applyStates = useSelector( + (state: RootState) => state.state.applyStates, + ); + + const pendingApplyStates = applyStates.filter( + (state) => state.status === "done", + ); + + const hasClosedAllStreams = applyStates.every( + (state) => state.status === "closed", + ); + + const isStreaming = applyStates.some((state) => state.status === "streaming"); + const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex; + const hasPendingApplies = pendingApplyStates.length > 0; + + return ( +
+
+ + {isCurCheckpoint && ( +
+ {hasPendingApplies && ( + + )} + {hasClosedAllStreams && } +
+ )} + +
+ +
+
+ ); +} diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index 55f6f9ddf..66d62575c 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -5,9 +5,8 @@ import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import { useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import { ChatHistoryItem } from "core"; -import UndoOrRedoAction from "./UndoOrRedoAction"; -import AcceptRejectAllButtons from "./AcceptRejectAllButtons"; import FeedbackButtons from "./FeedbackButtons"; +import MultifileEditActions from "./MultifileEditActions"; export interface ResponseActionsProps { isTruncated: boolean; @@ -28,68 +27,11 @@ export default function ResponseActions({ (store: RootState) => store.state.isMultifileEdit, ); - const curCheckpointIndex = useSelector( - (store: RootState) => store.state.curCheckpointIndex, - ); - - const applyStates = useSelector( - (state: RootState) => state.state.applyStates, - ); - - const pendingApplyStates = applyStates.filter( - (state) => state.status === "done", - ); - - const isStreaming = applyStates.some((state) => state.status === "streaming"); - // Only render delete button if there is more than one message const shouldRenderDelete = index !== 1; - const hasPendingApplies = pendingApplyStates.length > 0; - const shouldRenderAcceptRejectAll = - isInMultifileEdit && - hasPendingApplies && - Math.floor(index / 2) === curCheckpointIndex; - const shouldRenderUndoRedo = - isInMultifileEdit && - !isStreaming && - !hasPendingApplies && - Math.floor(index / 2) === curCheckpointIndex; - - console.log({ - applyStates, - pendingApplyStates, - shouldRenderMultifileEditActions: shouldRenderUndoRedo, - curCheckpointIndex, - index, - isInMultifileEdit, - isStreaming, - floored: Math.floor(index / 2), - }); if (isInMultifileEdit) { - return ( -
-
- - {shouldRenderAcceptRejectAll && ( -
- -
- )} - - {shouldRenderUndoRedo && ( -
- -
- )} - -
- -
-
- ); + return ; } return ( diff --git a/gui/src/components/StepContainer/UndoOrRedoAction.tsx b/gui/src/components/StepContainer/UndoAndRedoButtons.tsx similarity index 93% rename from gui/src/components/StepContainer/UndoOrRedoAction.tsx rename to gui/src/components/StepContainer/UndoAndRedoButtons.tsx index fae917a4a..769669797 100644 --- a/gui/src/components/StepContainer/UndoOrRedoAction.tsx +++ b/gui/src/components/StepContainer/UndoAndRedoButtons.tsx @@ -8,11 +8,7 @@ import { setCurCheckpointIndex } from "../../redux/slices/stateSlice"; import { useContext } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -export interface UndoOrRedoActionProps { - index: number; -} - -export default function UndoOrRedoAction({ index }: UndoOrRedoActionProps) { +export default function UndoAndRedoButtons() { const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 2cb0a085c..4a9ea0dfd 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -10,7 +10,6 @@ import { newSession, setMessageAtIndex } from "../../redux/slices/stateSlice"; import { RootState } from "../../redux/store"; import ContextItemsPeek from "./ContextItemsPeek"; import TipTapEditor from "./TipTapEditor"; -import AcceptRejectAllButtons from "../StepContainer/AcceptRejectAllButtons"; interface ContinueInputBoxProps { isLastUserInput: boolean; @@ -77,13 +76,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { const [isGatheringContext, setIsGatheringContext] = useState(false); const timeoutRef = useRef(null); - const isInMultifileEdit = useSelector( - (state: RootState) => state.state.isMultifileEdit, - ); - - const shouldShowAcceptRejectButtons = - props.isMainInput && isInMultifileEdit && !active; - useWebviewListener( "newSessionWithPrompt", async (data) => { diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 643753b50..c335ce978 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -22,7 +22,7 @@ import { ToolTip } from "../gui/Tooltip"; import ModelSelect from "../modelSelection/ModelSelect"; const StyledDiv = styled.div<{ isHidden: boolean }>` - padding: 4px 0; + padding-top: 4px; justify-content: space-between; gap: 1px; background-color: ${vscInputBackground}; @@ -103,7 +103,7 @@ function InputToolbar(props: InputToolbarProps) { isHidden={props.hidden} onClick={props.onClick} id="input-toolbar" - className="flex find-widget-skip" + className="find-widget-skip flex" >
diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 4cd8fba00..c805c94db 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -28,6 +28,7 @@ import { clearLastResponse, initNewActiveMessage, resubmitAtIndex, + setCurCheckpointIndex, setInactive, setIsGatheringContext, setIsInMultifileEdit, @@ -195,6 +196,10 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { // Reset current code block index dispatch(resetNextCodeBlockToApplyIndex()); + if (index) { + dispatch(setCurCheckpointIndex(Math.floor(index / 2))); + } + const shouldGatherContext = modifiers.useCodebase || hasSlashCommandOrContextProvider(editorState); From cd0e1b3b48f1445cd7eeb08dbf889b2c817b3bcc Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 13 Nov 2024 18:26:54 -0800 Subject: [PATCH 10/82] remove console logs --- core/protocol/ideWebview.ts | 7 ++++++- gui/src/components/Layout.tsx | 4 ---- gui/src/redux/slices/stateSlice.ts | 15 --------------- 3 files changed, 6 insertions(+), 20 deletions(-) diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 1fa5e84a5..8a07e257c 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -64,9 +64,14 @@ export type EditStatus = | "accepting:full-diff" | "done"; +export type ApplyStateStatus = + | "streaming" // Changes are being applied to the file + | "done" // All changes have been applied, awaiting user to accept/reject + | "closed"; // All changes have been applied. Note that for new files, we immediately set the status to "closed" + export interface ApplyState { streamId: string; - status?: "streaming" | "done" | "closed"; + status?: ApplyStateStatus; numDiffs?: number; filepath?: string; fileContent?: string; diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index cc09881a3..5879bd2e0 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -162,10 +162,6 @@ const Layout = () => { useWebviewListener( "updateApplyState", async (state) => { - // console.log({ - // filepath: state.filepath, - // content: state.fileContent, - // }); dispatch( updateCurCheckpoint({ filepath: state.filepath, diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 8c95599a6..17be955b8 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -442,21 +442,6 @@ export const stateSlice = createSlice({ state, { payload }: PayloadAction<{ filepath: string; content: string }>, ) => { - // If the user has explicitly checked out a given checkpoint, `curCheckpointIndex` will be set to that index. - // Else, we assume the current checkpoint index is the end of the checkpoints array. - // const index = - // state.curCheckpointIndex === -1 - // ? state.history.length / 2 - 1 - // : state.curCheckpointIndex; - - console.log("updating checkpoint"); - console.log({ - index: state.curCheckpointIndex, - historyLength: state.history.length, - filepath: payload.filepath, - content: payload.content, - }); - state.checkpoints[state.curCheckpointIndex] = { ...state.checkpoints[state.curCheckpointIndex], [payload.filepath]: payload.content, From bb7b9781fa71f5d0fae6e6206978d73cd6138996 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 13 Nov 2024 19:22:44 -0800 Subject: [PATCH 11/82] symbols in chat p1 --- core/core.ts | 19 +++- core/index.d.ts | 11 ++- core/protocol/core.ts | 5 ++ core/protocol/passThrough.ts | 3 +- core/util/treeSitter.ts | 70 +++++++++++++++ .../mainInput/CodeBlockComponent.tsx | 2 +- .../components/mainInput/ContextItemsPeek.tsx | 19 +++- .../components/mainInput/ContinueInputBox.tsx | 25 +----- gui/src/components/mainInput/TipTapEditor.tsx | 2 +- gui/src/components/mainInput/resolveInput.ts | 86 +++++++++++++------ gui/src/components/markdown/FilenameLink.tsx | 4 +- .../markdown/StyledMarkdownPreview.tsx | 2 + gui/src/hooks/useChatHandler.ts | 16 +--- gui/src/hooks/useSetup.ts | 2 +- gui/src/pages/edit/index.tsx | 1 + gui/src/pages/gui/Chat.tsx | 2 +- gui/src/redux/slices/stateSlice.ts | 61 ++++++++----- 17 files changed, 228 insertions(+), 102 deletions(-) diff --git a/core/core.ts b/core/core.ts index 6df1482ef..dfe3a4f4a 100644 --- a/core/core.ts +++ b/core/core.ts @@ -32,9 +32,15 @@ import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { TTS } from "./util/tts"; -import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; +import type { + ContextItemId, + IDE, + IndexingProgressUpdate, + SymbolWithLocation, +} from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./util/messenger"; +import { getFileSymbols, getSymbolsForFiles } from "./util/treeSitter"; export class Core { // implements IMessenger @@ -83,7 +89,7 @@ export class Core { constructor( private readonly messenger: IMessenger, private readonly ide: IDE, - private readonly onWrite: (text: string) => Promise = async () => { }, + private readonly onWrite: (text: string) => Promise = async () => {}, ) { // Ensure .continue directory is created setupInitialDotContinueDirectory(); @@ -174,7 +180,7 @@ export class Core { this.configHandler, ide, getLlm, - (e) => { }, + (e) => {}, (..._) => Promise.resolve([]), ); @@ -365,6 +371,11 @@ export class Core { } }); + on("context/getSymbolsForFiles", async (msg) => { + const { uris } = msg.data; + return await getSymbolsForFiles(uris, this.ide); + }); + on("config/getSerializedProfileInfo", async (msg) => { return { config: await this.configHandler.getSerializedConfig(), @@ -684,7 +695,7 @@ export class Core { await codebaseIndexer.clearIndexes(); } - const dirs = data?.dirs ?? await this.ide.getWorkspaceDirs(); + const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs()); await this.refreshCodebaseIndex(dirs); }); on("index/setPaused", (msg) => { diff --git a/core/index.d.ts b/core/index.d.ts index 1bad9fd74..2e6d79318 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,3 +1,4 @@ +import Parser from "web-tree-sitter"; import { GetGhTokenArgs } from "./protocol/ide"; declare global { @@ -298,18 +299,26 @@ export interface InputModifiers { noContext: boolean; } +export interface SymbolWithLocation { + name: string; + type: Parser.SyntaxNode["type"]; + location: Location; +} + +export type FileSymbolMap = Record; + export interface PromptLog { modelTitle: string; completionOptions: CompletionOptions; prompt: string; completion: string; } - export interface ChatHistoryItem { message: ChatMessage; editorState?: any; modifiers?: InputModifiers; contextItems: ContextItemWithId[]; + contextSymbols?: SymbolWithLocation[]; promptLogs?: PromptLog[]; } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 2c9af1433..3f02c3fc0 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -17,6 +17,7 @@ import type { SerializedContinueConfig, SessionInfo, SiteIndexingConfig, + SymbolWithLocation, } from "../"; export type ProtocolGeneratorType = AsyncGenerator<{ @@ -76,6 +77,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ContextItemWithId[], ]; + "context/getSymbolsForFiles": [ + { uris: string[] }, + Record, + ]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; "context/addDocs": [SiteIndexingConfig, void]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 1c0f5e962..d05d773c4 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -22,6 +22,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/deleteModel", "config/reload", "context/getContextItems", + "context/getSymbolsForFiles", "context/loadSubmenuItems", "context/addDocs", "context/removeDocs", @@ -60,5 +61,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "isContinueInputFocused", "didChangeAvailableProfiles", "setTTSActive", - "getWebviewHistoryLength" + "getWebviewHistoryLength", ]; diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index b877a251b..566917ecc 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -2,6 +2,7 @@ import fs from "node:fs"; import * as path from "node:path"; import Parser, { Language } from "web-tree-sitter"; +import { FileSymbolMap, IDE, SymbolWithLocation } from ".."; export const supportedLanguages: { [key: string]: string } = { cpp: "cpp", @@ -178,3 +179,72 @@ async function loadLanguageForFileExt( ); return await Parser.Language.load(wasmPath); } + +const GET_SYMBOLS_FOR_NODE_TYPES: Parser.SyntaxNode["type"][] = [ + "class_declaration", + "function_item", // function name = first "identifier" child + "method_declaration", // method name = first "identifier" child + // "arrow_function", +]; + +export async function getSymbolsForFile( + filepath: string, + contents: string, +): Promise { + const parser = await getParserForFile(filepath); + + if (!parser) { + return; + } + + const tree = parser.parse(contents); + console.log(`file: ${filepath}`); + + // Function to recursively find all named nodes (classes and functions) + const symbols: SymbolWithLocation[] = []; + function findNamedNodesRecursive(node: Parser.SyntaxNode) { + if (GET_SYMBOLS_FOR_NODE_TYPES.includes(node.type)) { + console.log(`parent: ${node.type}, ${node.text.substring(0, 200)}`); + node.children.forEach((child) => { + console.log(`child: ${child.type}, ${child.text}`); + }); + + // Empirically, the actualy name is the last identifier in the node + // Especially with languages where return type is declared before the name + const identifier = node.children.findLast( + (child) => child.type === "identifier", + )?.text; + if (identifier) { + symbols.push({ + type: node.type, + name: identifier, + location: { + filepath, + position: { + character: node.startPosition.column, + line: node.startPosition.row + 1, + }, + }, + }); + } + } + node.children.forEach(findNamedNodesRecursive); + } + findNamedNodesRecursive(tree.rootNode); + + return symbols; +} + +export async function getSymbolsForFiles( + uris: string[], + ide: IDE, +): Promise { + const filesAndSymbols = await Promise.all( + uris.map(async (uri): Promise<[string, SymbolWithLocation[]]> => { + const contents = await ide.readFile(uri); + const symbols = await getSymbolsForFile(uri, contents); + return [uri, symbols ?? []]; + }), + ); + return Object.fromEntries(filesAndSymbols); +} diff --git a/gui/src/components/mainInput/CodeBlockComponent.tsx b/gui/src/components/mainInput/CodeBlockComponent.tsx index 217fcc293..4266db4f5 100644 --- a/gui/src/components/mainInput/CodeBlockComponent.tsx +++ b/gui/src/components/mainInput/CodeBlockComponent.tsx @@ -16,7 +16,7 @@ export const CodeBlockComponent = ({ const item: ContextItemWithId = node.attrs.item; const contextItems = useSelector( - (state: RootState) => state.state.contextItems, + (state: RootState) => state.state.context.items, ); return ( diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 3ae178abf..33bdbff6d 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -10,10 +10,12 @@ import { INSTRUCTIONS_BASE_ITEM } from "core/context/providers/utils"; import { getIconFromDropdownItem } from "./MentionList"; import styled from "styled-components"; import { getBasename } from "core/util"; +import { RootState } from "../../redux/store"; +import { useSelector } from "react-redux"; interface ContextItemsPeekProps { contextItems?: ContextItemWithId[]; - isGatheringContext: boolean; + isCurrentContextPeek: boolean; } interface ContextItemsPeekItemProps { @@ -119,7 +121,7 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) { function ContextItemsPeek({ contextItems, - isGatheringContext, + isCurrentContextPeek, }: ContextItemsPeekProps) { const [open, setOpen] = useState(false); @@ -127,7 +129,16 @@ function ContextItemsPeek({ (ctxItem) => !ctxItem.name.includes(INSTRUCTIONS_BASE_ITEM.name), ); - if ((!ctxItems || ctxItems.length === 0) && !isGatheringContext) { + const isGatheringContext = useSelector( + (store: RootState) => store.state.context.isGathering, + ); + const gatheringMessage = useSelector( + (store: RootState) => store.state.context.gatheringMessage, + ); + + const indicateIsGathering = isCurrentContextPeek && isGatheringContext; + + if ((!ctxItems || ctxItems.length === 0) && !indicateIsGathering) { return null; } @@ -152,7 +163,7 @@ function ContextItemsPeek({ {isGatheringContext ? ( <> - Gathering context + {gatheringMessage} ) : ( diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index c98a69403..544eb8f63 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -1,6 +1,5 @@ import { Editor, JSONContent } from "@tiptap/react"; import { ContextItemWithId, InputModifiers } from "core"; -import { useEffect, useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled, { keyframes } from "styled-components"; import { defaultBorderRadius, vscBackground } from ".."; @@ -70,12 +69,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { const availableContextProviders = useSelector( (store: RootState) => store.state.config.contextProviders, ); - const isGatheringContextStore = useSelector( - (store: RootState) => store.state.isGatheringContext, - ); - - const [isGatheringContext, setIsGatheringContext] = useState(false); - const timeoutRef = useRef(null); const isInMultifileEdit = useSelector( (state: RootState) => state.state.isInMultifileEdit, @@ -100,22 +93,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { [props.isMainInput], ); - useEffect(() => { - if (isGatheringContextStore && !isGatheringContext) { - // 500ms delay when going from false -> true to prevent flashing loading indicator - timeoutRef.current = setTimeout(() => setIsGatheringContext(true), 500); - } else { - // Update immediately otherwise (i.e. true -> false) - setIsGatheringContext(isGatheringContextStore); - } - - return () => { - if (timeoutRef.current) { - clearTimeout(timeoutRef.current); - } - }; - }, [isGatheringContextStore]); - return (
{shouldShowAcceptRejectButtons && } @@ -145,7 +122,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
); diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index c2646415e..cb57681ea 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -223,7 +223,7 @@ function TipTapEditor(props: TipTapEditorProps) { }; const contextItems = useSelector( - (store: RootState) => store.state.contextItems, + (store: RootState) => store.state.context.items, ); const defaultModel = useSelector(defaultModelSelector); diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 64acba85a..85ac9e398 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -9,6 +9,8 @@ import { } from "core"; import { stripImages } from "core/llm/images"; import { IIdeMessenger } from "../../context/IdeMessenger"; +import { Dispatch } from "@reduxjs/toolkit"; +import { setIsGatheringContext } from "../../redux/slices/stateSlice"; interface MentionAttrs { label: string; @@ -29,6 +31,7 @@ async function resolveEditorContent( modifiers: InputModifiers, ideMessenger: IIdeMessenger, defaultContextProviders: DefaultContextProvider[], + dispatch: Dispatch, ): Promise<[ContextItemWithId[], RangeInFile[], MessageContent]> { let parts: MessagePart[] = []; let contextItemAttrs: MentionAttrs[] = []; @@ -38,8 +41,7 @@ async function resolveEditorContent( if (p.type === "paragraph") { const [text, ctxItems, foundSlashCommand] = resolveParagraph(p); - // Only take the first slash command - + // Only take the first slash command\ if (foundSlashCommand && typeof slashCommand === "undefined") { slashCommand = foundSlashCommand; } @@ -103,6 +105,17 @@ async function resolveEditorContent( } } + const shouldGatherContext = modifiers.useCodebase || slashCommand; + + if (shouldGatherContext) { + dispatch( + setIsGatheringContext({ + isGathering: true, + gatheringMessage: "Gathering context", + }), + ); + } + let contextItemsText = ""; let contextItems: ContextItemWithId[] = []; for (const item of contextItemAttrs) { @@ -158,6 +171,18 @@ async function resolveEditorContent( ); contextItems.push(...defaultContextItems.flat()); + const contextItemFileUris = Array.from( + new Set( + contextItems + .filter((item) => item.uri?.type === "file" && item?.uri?.value) + .map((item) => item.uri.value), + ), + ); + + const symbols = await ideMessenger.request("context/getSymbolsForFiles", { + uris: contextItemFileUris, + }); + if (contextItemsText !== "") { contextItemsText += "\n"; } @@ -172,7 +197,16 @@ async function resolveEditorContent( } } - return [contextItems, selectedCode, parts]; + if (shouldGatherContext) { + dispatch( + setIsGatheringContext({ + isGathering: false, + gatheringMessage: "Gathering context", + }), + ); + } + + return [contextItems, selectedCode, parts, symbols]; } function findLastIndex( @@ -213,30 +247,30 @@ function resolveParagraph(p: JSONContent): [string, MentionAttrs[], string] { return [text, contextItems, slashCommand]; } -export function hasSlashCommandOrContextProvider( - editorState: JSONContent, -): boolean { - if (!editorState.content) { - return false; - } +// export function hasSlashCommandOrContextProvider( +// editorState: JSONContent, +// ): boolean { +// if (!editorState.content) { +// return false; +// } - for (const p of editorState.content) { - if (p.type === "paragraph" && p.content) { - for (const child of p.content) { - if (child.type === "slashcommand") { - return true; - } - if ( - child.type === "mention" && - child.attrs?.itemType === "contextProvider" - ) { - return true; - } - } - } - } +// for (const p of editorState.content) { +// if (p.type === "paragraph" && p.content) { +// for (const child of p.content) { +// if (child.type === "slashcommand") { +// return true; +// } +// if ( +// child.type === "mention" && +// child.attrs?.itemType === "contextProvider" +// ) { +// return true; +// } +// } +// } +// } - return false; -} +// return false; +// } export default resolveEditorContent; diff --git a/gui/src/components/markdown/FilenameLink.tsx b/gui/src/components/markdown/FilenameLink.tsx index 3674fc418..0d1166a00 100644 --- a/gui/src/components/markdown/FilenameLink.tsx +++ b/gui/src/components/markdown/FilenameLink.tsx @@ -20,7 +20,7 @@ function FilenameLink({ rif }: FilenameLinkProps) { } return ( -
@@ -28,7 +28,7 @@ function FilenameLink({ rif }: FilenameLinkProps) { {getBasename(rif.filepath)} -
+ ); } diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 77158e96a..c5190d8e8 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -246,6 +246,8 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( return ; } + // const symbole = symboles + return {codeProps.children}; }, }, diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 2e35acc53..8517ea5d9 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -17,9 +17,7 @@ import { getBasename, getRelativePath } from "core/util"; import { usePostHog } from "posthog-js/react"; import { useEffect, useRef, useState } from "react"; import { useSelector } from "react-redux"; -import resolveEditorContent, { - hasSlashCommandOrContextProvider, -} from "../components/mainInput/resolveInput"; +import resolveEditorContent from "../components/mainInput/resolveInput"; import { IIdeMessenger } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { @@ -51,7 +49,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { ); const contextItems = useSelector( - (state: RootState) => state.state.contextItems, + (store: RootState) => store.state.context.items, ); const history = useSelector((store: RootState) => store.state.history); @@ -195,13 +193,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { // Reset current code block index dispatch(resetNextCodeBlockToApplyIndex()); - const shouldGatherContext = - modifiers.useCodebase || hasSlashCommandOrContextProvider(editorState); - - if (shouldGatherContext) { - dispatch(setIsGatheringContext(true)); - } - // Resolve context providers and construct new history const [selectedContextItems, selectedCode, content] = await resolveEditorContent( @@ -209,10 +200,9 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { modifiers, ideMessenger, defaultContextProviders, + dispatch, ); - dispatch(setIsGatheringContext(false)); - // Automatically use currently open file if (!modifiers.noContext) { const usingFreeTrial = defaultModel?.provider === "free-trial"; diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 2fed805da..4378059e0 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -20,7 +20,7 @@ import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import useChatHandler from "./useChatHandler"; import { useWebviewListener } from "./useWebviewListener"; -function useSetup(dispatch: Dispatch) { +function useSetup(dispatch: Dispatch) { const [configLoaded, setConfigLoaded] = useState(false); const ideMessenger = useContext(IdeMessengerContext); diff --git a/gui/src/pages/edit/index.tsx b/gui/src/pages/edit/index.tsx index 5b1b71e66..af33ee99d 100644 --- a/gui/src/pages/edit/index.tsx +++ b/gui/src/pages/edit/index.tsx @@ -174,6 +174,7 @@ function Edit() { }, ideMessenger, [], + dispatch, ); const prompt = [ diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 78bbcd262..85f4eb416 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -290,7 +290,7 @@ export function Chat() { setLocalStorage("mainTextEntryCounter", 1); } }, - [state.history, state.contextItems, defaultModel, state, streamResponse], + [state.history, state.context.items, defaultModel, state, streamResponse], ); useWebviewListener( diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index e3ce22eb6..cd1e4a8bc 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -15,16 +15,6 @@ import { createSelector } from "reselect"; import { v4 as uuidv4, v4 } from "uuid"; import { RootState } from "../store"; -export const memoizedContextItemsSelector = createSelector( - [(state: RootState) => state.state.history], - (history) => { - return history.reduce((acc, item) => { - acc.push(...item.contextItems); - return acc; - }, []); - }, -); - // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. type ChatHistoryItemWithMessageId = ChatHistoryItem & { @@ -33,10 +23,13 @@ type ChatHistoryItemWithMessageId = ChatHistoryItem & { type State = { history: ChatHistoryItemWithMessageId[]; - contextItems: ContextItemWithId[]; + context: { + items: ContextItemWithId[]; + isGathering: boolean; + gatheringMessage: string; + }; ttsActive: boolean; active: boolean; - isGatheringContext: boolean; config: BrowserSerializedContinueConfig; title: string; sessionId: string; @@ -49,10 +42,13 @@ type State = { const initialState: State = { history: [], - contextItems: [], + context: { + items: [], + isGathering: false, + gatheringMessage: "Gathering Context", + }, ttsActive: false, active: false, - isGatheringContext: false, configError: undefined, config: { slashCommands: [ @@ -116,8 +112,17 @@ export const stateSlice = createSlice({ setActive: (state) => { state.active = true; }, - setIsGatheringContext: (state, { payload }: PayloadAction) => { - state.isGatheringContext = payload; + setIsGatheringContext: ( + state, + { + payload, + }: PayloadAction<{ + isGathering: boolean; + gatheringMessage: string; + }>, + ) => { + state.context.isGathering = payload.isGathering; + state.context.gatheringMessage = payload.gatheringMessage; }, clearLastResponse: (state) => { if (state.history.length < 2) { @@ -144,7 +149,7 @@ export const stateSlice = createSlice({ } }, addContextItems: (state, action: PayloadAction) => { - state.contextItems = state.contextItems.concat(action.payload); + state.context.items = state.context.items.concat(action.payload); }, resubmitAtIndex: ( state, @@ -190,7 +195,7 @@ export const stateSlice = createSlice({ ) => { state.history.push({ message: { role: "user", content: "", id: uuidv4() }, - contextItems: state.contextItems, + contextItems: state.context.items, editorState: payload.editorState, }); state.history.push({ @@ -253,7 +258,7 @@ export const stateSlice = createSlice({ historyItem.contextItems.push(...payload.contextItems); }, setInactive: (state) => { - state.isGatheringContext = false; + state.context.isGathering = false; state.active = false; }, streamUpdate: (state, action: PayloadAction) => { @@ -272,7 +277,7 @@ export const stateSlice = createSlice({ state.sessionId = payload.sessionId; } else { state.history = []; - state.contextItems = []; + state.context.items = []; state.active = false; state.title = "New Session"; state.sessionId = v4(); @@ -289,7 +294,7 @@ export const stateSlice = createSlice({ const ids = new Set(payload.ids.map(getKey)); if (payload.index === undefined) { - state.contextItems = state.contextItems.filter( + state.context.items = state.context.items.filter( (item) => !ids.has(getKey(item.id)), ); } else { @@ -304,7 +309,7 @@ export const stateSlice = createSlice({ payload, }: PayloadAction<{ rangeInFileWithContents: any; edit: boolean }>, ) => { - let contextItems = [...state.contextItems].map((item) => { + let contextItems = [...state.context.items].map((item) => { return { ...item, editing: false }; }); const base = payload.rangeInFileWithContents.filepath @@ -372,7 +377,7 @@ export const stateSlice = createSlice({ if (typeof payload.index === "undefined") { return { ...state, - contextItems: state.contextItems.map((item) => { + contextItems: state.context.items.map((item) => { return { ...item, editing: ids.includes(item.id.itemId), @@ -424,6 +429,16 @@ export const stateSlice = createSlice({ }, }); +export const memoizedContextItemsSelector = createSelector( + [(state: RootState) => state.state.history], + (history) => { + return history.reduce((acc, item) => { + acc.push(...item.contextItems); + return acc; + }, []); + }, +); + export const { setContextItemsAtIndex, addContextItems, From faf45035f9f214ad231a89a2f0d2220bd3d5e4b3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 14 Nov 2024 09:37:20 -0800 Subject: [PATCH 12/82] symbol links p3 --- core/core.ts | 9 +--- core/index.d.ts | 7 ++- core/protocol/core.ts | 7 +-- core/util/treeSitter.ts | 53 +++++++++++++------ .../mainInput/CodeBlockComponent.tsx | 1 - gui/src/components/mainInput/resolveInput.ts | 19 +++++-- .../markdown/StyledMarkdownPreview.tsx | 47 +++++++++++++--- gui/src/components/markdown/SymbolLink.tsx | 33 ++++++++++++ gui/src/redux/slices/stateSlice.ts | 10 ++++ 9 files changed, 141 insertions(+), 45 deletions(-) create mode 100644 gui/src/components/markdown/SymbolLink.tsx diff --git a/core/core.ts b/core/core.ts index dfe3a4f4a..727e5f200 100644 --- a/core/core.ts +++ b/core/core.ts @@ -30,17 +30,12 @@ import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; +import { getSymbolsForFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; -import type { - ContextItemId, - IDE, - IndexingProgressUpdate, - SymbolWithLocation, -} from "."; +import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./util/messenger"; -import { getFileSymbols, getSymbolsForFiles } from "./util/treeSitter"; export class Core { // implements IMessenger diff --git a/core/index.d.ts b/core/index.d.ts index 2e6d79318..25d5c346d 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -299,13 +299,12 @@ export interface InputModifiers { noContext: boolean; } -export interface SymbolWithLocation { +export interface SymbolWithRange extends RangeInFile { name: string; type: Parser.SyntaxNode["type"]; - location: Location; } -export type FileSymbolMap = Record; +export type FileSymbolMap = Record; export interface PromptLog { modelTitle: string; @@ -318,7 +317,7 @@ export interface ChatHistoryItem { editorState?: any; modifiers?: InputModifiers; contextItems: ContextItemWithId[]; - contextSymbols?: SymbolWithLocation[]; + contextSymbols?: SymbolWithRange[]; promptLogs?: PromptLog[]; } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 3f02c3fc0..cef8c38c9 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -7,6 +7,7 @@ import type { ContextItemWithId, ContextSubmenuItem, DiffLine, + FileSymbolMap, IdeSettings, LLMFullCompletionOptions, MessageContent, @@ -17,7 +18,6 @@ import type { SerializedContinueConfig, SessionInfo, SiteIndexingConfig, - SymbolWithLocation, } from "../"; export type ProtocolGeneratorType = AsyncGenerator<{ @@ -77,10 +77,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ContextItemWithId[], ]; - "context/getSymbolsForFiles": [ - { uris: string[] }, - Record, - ]; + "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; "context/addDocs": [SiteIndexingConfig, void]; diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 566917ecc..18ac14d16 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -2,7 +2,8 @@ import fs from "node:fs"; import * as path from "node:path"; import Parser, { Language } from "web-tree-sitter"; -import { FileSymbolMap, IDE, SymbolWithLocation } from ".."; + +import { FileSymbolMap, IDE, SymbolWithRange } from ".."; export const supportedLanguages: { [key: string]: string } = { cpp: "cpp", @@ -180,17 +181,24 @@ async function loadLanguageForFileExt( return await Parser.Language.load(wasmPath); } +// See https://tree-sitter.github.io/tree-sitter/using-parsers const GET_SYMBOLS_FOR_NODE_TYPES: Parser.SyntaxNode["type"][] = [ "class_declaration", + "class_definition", "function_item", // function name = first "identifier" child + "function_definition", "method_declaration", // method name = first "identifier" child + "method_definition", + "generator_function_declaration", + // property_identifier + // field_declaration // "arrow_function", ]; export async function getSymbolsForFile( filepath: string, contents: string, -): Promise { +): Promise { const parser = await getParserForFile(filepath); if (!parser) { @@ -201,28 +209,39 @@ export async function getSymbolsForFile( console.log(`file: ${filepath}`); // Function to recursively find all named nodes (classes and functions) - const symbols: SymbolWithLocation[] = []; + const symbols: SymbolWithRange[] = []; function findNamedNodesRecursive(node: Parser.SyntaxNode) { + // console.log(`node: ${node.type}, ${node.text}`); if (GET_SYMBOLS_FOR_NODE_TYPES.includes(node.type)) { - console.log(`parent: ${node.type}, ${node.text.substring(0, 200)}`); - node.children.forEach((child) => { - console.log(`child: ${child.type}, ${child.text}`); - }); + // console.log(`parent: ${node.type}, ${node.text.substring(0, 200)}`); + // node.children.forEach((child) => { + // console.log(`child: ${child.type}, ${child.text}`); + // }); // Empirically, the actualy name is the last identifier in the node // Especially with languages where return type is declared before the name - const identifier = node.children.findLast( - (child) => child.type === "identifier", - )?.text; - if (identifier) { + // TODO use findLast in newer version of node target + let identifier: Parser.SyntaxNode | undefined = undefined; + for (let i = node.children.length - 1; i >= 0; i--) { + if (node.children[i].type === "identifier") { + identifier = node.children[i]; + break; + } + } + + if (identifier?.text) { symbols.push({ + filepath, type: node.type, - name: identifier, - location: { - filepath, - position: { + name: identifier.text, + range: { + start: { character: node.startPosition.column, - line: node.startPosition.row + 1, + line: node.startPosition.row, + }, + end: { + character: node.endPosition.column + 1, + line: node.endPosition.row + 1, }, }, }); @@ -240,7 +259,7 @@ export async function getSymbolsForFiles( ide: IDE, ): Promise { const filesAndSymbols = await Promise.all( - uris.map(async (uri): Promise<[string, SymbolWithLocation[]]> => { + uris.map(async (uri): Promise<[string, SymbolWithRange[]]> => { const contents = await ide.readFile(uri); const symbols = await getSymbolsForFile(uri, contents); return [uri, symbols ?? []]; diff --git a/gui/src/components/mainInput/CodeBlockComponent.tsx b/gui/src/components/mainInput/CodeBlockComponent.tsx index 4266db4f5..2a63d889e 100644 --- a/gui/src/components/mainInput/CodeBlockComponent.tsx +++ b/gui/src/components/mainInput/CodeBlockComponent.tsx @@ -12,7 +12,6 @@ export const CodeBlockComponent = ({ editor, updateAttributes, }: any) => { - const dispatch = useDispatch(); const item: ContextItemWithId = node.attrs.item; const contextItems = useSelector( diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 85ac9e398..a4598ae93 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -10,7 +10,10 @@ import { import { stripImages } from "core/llm/images"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { Dispatch } from "@reduxjs/toolkit"; -import { setIsGatheringContext } from "../../redux/slices/stateSlice"; +import { + setIsGatheringContext, + updateFileSymbols, +} from "../../redux/slices/stateSlice"; interface MentionAttrs { label: string; @@ -179,9 +182,15 @@ async function resolveEditorContent( ), ); - const symbols = await ideMessenger.request("context/getSymbolsForFiles", { - uris: contextItemFileUris, - }); + const symbolsResult = await ideMessenger.request( + "context/getSymbolsForFiles", + { + uris: contextItemFileUris, + }, + ); + if (symbolsResult.status === "success") { + dispatch(updateFileSymbols(symbolsResult.content)); + } if (contextItemsText !== "") { contextItemsText += "\n"; @@ -206,7 +215,7 @@ async function resolveEditorContent( ); } - return [contextItems, selectedCode, parts, symbols]; + return [contextItems, selectedCode, parts]; } function findLastIndex( diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index c5190d8e8..70af5b6b4 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,4 +1,4 @@ -import { memo, useEffect } from "react"; +import { memo, useEffect, useMemo } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -21,6 +21,9 @@ import FilenameLink from "./FilenameLink"; import StepContainerPreToolbar from "./StepContainerPreToolbar"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; +import { RootState } from "../../redux/store"; +import { SymbolWithRange } from "core"; +import SymbolLink from "./SymbolLink"; const StyledMarkdown = styled.div<{ fontSize?: number; @@ -112,16 +115,16 @@ function getLanuageFromClassName(className: any): string | null { function getCodeChildrenContent(children: any) { if (typeof children === "string") { + console.log(children); return children; } else if ( Array.isArray(children) && children.length > 0 && - typeof children[0] === "string" && - children[0] !== "" + typeof children[0] === "string" ) { + console.log(children[0]); return children[0]; } - return undefined; } @@ -154,6 +157,25 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( props: StyledMarkdownPreviewProps, ) { const contextItems = useSelector(memoizedContextItemsSelector); + const symbols = useSelector( + (state: RootState) => state.state.context.symbols, + ); + const symbolsForContextItems: SymbolWithRange[] = useMemo(() => { + const contextUris = Array.from( + new Set( + contextItems.filter((item) => item?.uri).map((item) => item.uri!.value), + ), + ); + const contextSymbols: SymbolWithRange[] = []; + contextUris.forEach((uri) => { + const fileSymbols = symbols[uri]; + if (fileSymbols) { + contextSymbols.push(...fileSymbols); + } + }); + console.log(contextSymbols.map((s) => s.name)); + return contextSymbols; + }, [contextItems, symbols]); const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [remarkMath, () => processCodeBlocks], @@ -245,9 +267,22 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const rif = ctxItemToRifWithContents(ctxItem); return ; } + // console.log("content", content); + const exactSymbol = symbolsForContextItems.find( + (s) => s.name === content, + ); + if (exactSymbol) { + return ; + } - // const symbole = symboles - + // PARTIAL - PARENTHESES + const partialSymbol = symbolsForContextItems.find( + (s) => false, + // content.startsWith(s.name), + ); + if (partialSymbol) { + return ; + } return {codeProps.children}; }, }, diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx new file mode 100644 index 000000000..84c1e8984 --- /dev/null +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -0,0 +1,33 @@ +import { SymbolWithRange } from "core"; +import { useContext } from "react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; + +interface SymbolLinkProps { + symbol: SymbolWithRange; + content: string; +} + +function SymbolLink({ symbol, content }: SymbolLinkProps) { + const ideMessenger = useContext(IdeMessengerContext); + + function onClick() { + ideMessenger.post("showLines", { + filepath: symbol.filepath, + startLine: symbol.range.start.line, + endLine: symbol.range.end.line, + }); + } + + return ( + + + {content} + + + ); +} + +export default SymbolLink; diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index cd1e4a8bc..22c76e9ee 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -5,6 +5,7 @@ import { ChatMessage, ContextItemId, ContextItemWithId, + FileSymbolMap, PersistedSessionInfo, PromptLog, } from "core"; @@ -25,6 +26,7 @@ type State = { history: ChatHistoryItemWithMessageId[]; context: { items: ContextItemWithId[]; + symbols: FileSymbolMap; isGathering: boolean; gatheringMessage: string; }; @@ -44,6 +46,7 @@ const initialState: State = { history: [], context: { items: [], + symbols: {}, isGathering: false, gatheringMessage: "Gathering Context", }, @@ -135,6 +138,12 @@ export const stateSlice = createSlice({ consumeMainEditorContent: (state) => { state.mainEditorContent = undefined; }, + updateFileSymbols: (state, action: PayloadAction) => { + state.context.symbols = Object.assign( + state.context.symbols, + action.payload, + ); + }, setContextItemsAtIndex: ( state, { @@ -440,6 +449,7 @@ export const memoizedContextItemsSelector = createSelector( ); export const { + updateFileSymbols, setContextItemsAtIndex, addContextItems, addContextItemsAtIndex, From 9d2fad9ad0ce5d43a6b69c7da9aea0d54c79ad81 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 14 Nov 2024 16:30:40 -0800 Subject: [PATCH 13/82] docs UI start with indexing per file --- core/core.ts | 80 +++++++++--- core/indexing/CodebaseIndexer.ts | 77 ++++++++--- core/protocol/core.ts | 1 + core/protocol/passThrough.ts | 3 +- .../ContinuePluginStartupActivity.kt | 4 +- .../toolWindow/ContinueBrowser.kt | 1 + extensions/vscode/package-lock.json | 4 +- .../vscode/src/extension/VsCodeExtension.ts | 10 +- gui/src/pages/More/IndexingProgress/index.ts | 1 - gui/src/pages/More/More.tsx | 2 +- .../IndexingProgressBar.tsx | 2 +- .../IndexingProgressIndicator.tsx | 2 +- .../IndexingProgressSubtext.tsx | 0 .../IndexingProgressTitleText.tsx | 10 +- .../codebase}/IndexingProgressErrorText.tsx | 4 +- .../codebase/index.tsx} | 34 ++--- gui/src/pages/More/progress/docs/index.tsx | 121 ++++++++++++++++++ gui/src/pages/More/progress/index.ts | 17 +++ 18 files changed, 290 insertions(+), 83 deletions(-) delete mode 100644 gui/src/pages/More/IndexingProgress/index.ts rename gui/src/pages/More/{IndexingProgress => progress}/IndexingProgressBar.tsx (91%) rename gui/src/pages/More/{IndexingProgress => progress}/IndexingProgressIndicator.tsx (95%) rename gui/src/pages/More/{IndexingProgress => progress}/IndexingProgressSubtext.tsx (100%) rename gui/src/pages/More/{IndexingProgress => progress}/IndexingProgressTitleText.tsx (65%) rename gui/src/pages/More/{IndexingProgress => progress/codebase}/IndexingProgressErrorText.tsx (94%) rename gui/src/pages/More/{IndexingProgress/IndexingProgress.tsx => progress/codebase/index.tsx} (75%) create mode 100644 gui/src/pages/More/progress/docs/index.tsx create mode 100644 gui/src/pages/More/progress/index.ts diff --git a/core/core.ts b/core/core.ts index 6df1482ef..a5514490a 100644 --- a/core/core.ts +++ b/core/core.ts @@ -83,7 +83,7 @@ export class Core { constructor( private readonly messenger: IMessenger, private readonly ide: IDE, - private readonly onWrite: (text: string) => Promise = async () => { }, + private readonly onWrite: (text: string) => Promise = async () => {}, ) { // Ensure .continue directory is created setupInitialDotContinueDirectory(); @@ -174,7 +174,7 @@ export class Core { this.configHandler, ide, getLlm, - (e) => { }, + (e) => {}, (..._) => Promise.resolve([]), ); @@ -684,9 +684,14 @@ export class Core { await codebaseIndexer.clearIndexes(); } - const dirs = data?.dirs ?? await this.ide.getWorkspaceDirs(); + const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs()); await this.refreshCodebaseIndex(dirs); }); + on("index/forceReIndexFiles", async ({ data }) => { + if (data?.files?.length) { + await this.refreshCodebaseIndexFiles(data.files); + } + }); on("index/setPaused", (msg) => { new GlobalContext().update("indexingPaused", msg.data); this.indexingPauseToken.paused = msg.data; @@ -722,14 +727,29 @@ export class Core { } private indexingCancellationController: AbortController | undefined; + private async sendIndexingTelemetry(update: IndexingProgressUpdate) { + console.debug( + "Indexing failed with error: ", + update.desc, + update.debugInfo, + ); + void Telemetry.capture( + "indexing_error", + { + error: update.desc, + stack: update.debugInfo, + }, + false, + ); + } - private async refreshCodebaseIndex(dirs: string[]) { + private async refreshCodebaseIndex(paths: string[]) { if (this.indexingCancellationController) { this.indexingCancellationController.abort(); } this.indexingCancellationController = new AbortController(); - for await (const update of (await this.codebaseIndexerPromise).refresh( - dirs, + for await (const update of (await this.codebaseIndexerPromise).refreshDirs( + paths, this.indexingCancellationController.signal, )) { let updateToSend = { ...update }; @@ -743,19 +763,41 @@ export class Core { this.indexingState = updateToSend; if (update.status === "failed") { - console.debug( - "Indexing failed with error: ", - update.desc, - update.debugInfo, - ); - void Telemetry.capture( - "indexing_error", - { - error: update.desc, - stack: update.debugInfo, - }, - false, - ); + void this.sendIndexingTelemetry(update); + } + } + + this.messenger.send("refreshSubmenuItems", undefined); + } + + private async refreshCodebaseIndexFiles(files: string[]) { + // Can be cancelled by codebase index but not vice versa + if ( + this.indexingCancellationController && + !this.indexingCancellationController.signal.aborted + ) { + return console.debug( + "Codebase indexing already in progress, skipping indexing of files\n" + + files.join("\n"), + ); + } + this.indexingCancellationController = new AbortController(); + for await (const update of (await this.codebaseIndexerPromise).refreshFiles( + files, + this.indexingCancellationController.signal, + )) { + let updateToSend = { ...update }; + if (update.status === "failed") { + updateToSend.status = "done"; + updateToSend.desc = "Indexing complete"; + updateToSend.progress = 1.0; + } + + void this.messenger.request("indexProgress", updateToSend); + this.indexingState = updateToSend; + + if (update.status === "failed") { + void this.sendIndexingTelemetry(update); } } diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index b4962d182..175e1a062 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -17,6 +17,7 @@ import { RefreshIndexResults, } from "./types.js"; import { walkDirAsync } from "./walkDir.js"; +import { getBasename } from "../util/index.js"; export class PauseToken { constructor(private _paused: boolean) {} @@ -144,13 +145,61 @@ export class CodebaseIndexer { } } - async *refresh( - workspaceDirs: string[], + async *refreshFiles( + files: string[], + abortSignal: AbortSignal, + ): AsyncGenerator { + let progress = 0; + if (files.length === 0) { + yield { + progress: 1, + desc: "Indexing Complete", + status: "done", + }; + } + + const progressPer = 1 / files.length; + try { + for (const file of files) { + yield { + progress, + desc: `Indexing file ${file}...`, + status: "indexing", + }; + await this.refreshFile(file); + + progress += progressPer; + + if (this.pauseToken.paused) { + yield* this.yieldUpdateAndPause(); + } + if (abortSignal.aborted) { + yield { + progress: 1, + desc: "Indexing cancelled", + status: "disabled", + }; + return; + } + } + + yield { + progress: 1, + desc: "Indexing Complete", + status: "done", + }; + } catch (err) { + yield this.handleErrorAndGetProgressUpdate(err); + } + } + + async *refreshDirs( + dirs: string[], abortSignal: AbortSignal, ): AsyncGenerator { let progress = 0; - if (workspaceDirs.length === 0) { + if (dirs.length === 0) { yield { progress, desc: "Nothing to index", @@ -175,11 +224,9 @@ export class CodebaseIndexer { }; } - let completedDirs = 0; - // Wait until Git Extension has loaded to report progress // so we don't appear stuck at 0% while waiting - await this.ide.getRepoName(workspaceDirs[0]); + await this.ide.getRepoName(dirs[0]); yield { progress, @@ -188,16 +235,16 @@ export class CodebaseIndexer { }; const beginTime = Date.now(); - for (const directory of workspaceDirs) { + for (const directory of dirs) { const dirBasename = await this.basename(directory); yield { progress, desc: `Discovering files in ${dirBasename}...`, status: "indexing", }; - const workspaceFiles = []; + const directoryFiles = []; for await (const p of walkDirAsync(directory, this.ide)) { - workspaceFiles.push(p); + directoryFiles.push(p); if (abortSignal.aborted) { yield { progress: 1, @@ -218,7 +265,7 @@ export class CodebaseIndexer { try { for await (const updateDesc of this.indexFiles( directory, - workspaceFiles, + directoryFiles, branch, repoName, )) { @@ -240,7 +287,7 @@ export class CodebaseIndexer { nextLogThreshold += 0.025; this.logProgress( beginTime, - Math.floor(workspaceFiles.length * updateDesc.progress), + Math.floor(directoryFiles.length * updateDesc.progress), updateDesc.progress, ); } @@ -347,18 +394,18 @@ export class CodebaseIndexer { } private async *indexFiles( - workspaceDir: string, - workspaceFiles: string[], + directory: string, + files: string[], branch: string, repoName: string | undefined, ): AsyncGenerator { - const stats = await this.ide.getLastModified(workspaceFiles); + const stats = await this.ide.getLastModified(files); const indexesToBuild = await this.getIndexesToBuild(); let completedIndexCount = 0; let progress = 0; for (const codebaseIndex of indexesToBuild) { const tag: IndexTag = { - directory: workspaceDir, + directory, branch, artifactId: codebaseIndex.artifactId, }; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 2c9af1433..e30de4673 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -147,6 +147,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { undefined | { dirs?: string[]; shouldClearIndexes?: boolean }, void, ]; + "index/forceReIndexFiles": [undefined | { files?: string[] }, void]; "index/indexingProgressBarInitialized": [undefined, void]; completeOnboarding: [ { diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 1c0f5e962..21ac52c8d 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -41,6 +41,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "stats/getTokensPerModel", "index/setPaused", "index/forceReIndex", + "index/forceReIndexFiles", "index/indexingProgressBarInitialized", "completeOnboarding", "addAutocompleteModel", @@ -60,5 +61,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "isContinueInputFocused", "didChangeAvailableProfiles", "setTTSActive", - "getWebviewHistoryLength" + "getWebviewHistoryLength", ]; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index fa39729fa..451baae68 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -169,8 +169,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { // Create a data map if there are any paths to re-index if (allPaths.isNotEmpty()) { - val data = mapOf("dirs" to allPaths) - continuePluginService.coreMessenger?.request("index/forceReIndex", data, null) { _ -> } + val data = mapOf("files" to allPaths) + continuePluginService.coreMessenger?.request("index/forceReIndexFiles", data, null) { _ -> } } } }) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 26896906b..147f153e3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -58,6 +58,7 @@ class ContinueBrowser(val project: Project, url: String) { "stats/getTokensPerModel", "index/setPaused", "index/forceReIndex", + "index/forceReIndexFiles", "index/indexingProgressBarInitialized", "completeOnboarding", "addAutocompleteModel", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 24930d980..29ac4731f 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.229", + "version": "0.9.230", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.229", + "version": "0.9.230", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 06263e356..bb46e7466 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -297,17 +297,15 @@ export class VsCodeExtension { this.core.invoke("index/forceReIndex", undefined); } else { // Reindex the file - this.core.invoke("index/forceReIndex", { - dirs: [filepath], + this.core.invoke("index/forceReIndexFiles", { + files: [filepath], }); } }); vscode.workspace.onDidDeleteFiles(async (event) => { - this.core.invoke("index/forceReIndex", { - dirs: event.files.map((file) => - file.fsPath.split("/").slice(0, -1).join("/"), - ), + this.core.invoke("index/forceReIndexFiles", { + files: event.files.map((file) => file.fsPath), }); }); diff --git a/gui/src/pages/More/IndexingProgress/index.ts b/gui/src/pages/More/IndexingProgress/index.ts deleted file mode 100644 index 7f51ae6ad..000000000 --- a/gui/src/pages/More/IndexingProgress/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { default } from "./IndexingProgress"; diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index 4824c9535..14d0eadee 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -14,7 +14,7 @@ import { useDispatch } from "react-redux"; import { setOnboardingCard } from "../../redux/slices/uiStateSlice"; import useHistory from "../../hooks/useHistory"; import MoreHelpRow from "./MoreHelpRow"; -import IndexingProgress from "./IndexingProgress"; +import IndexingProgress from "./progress/codebase"; function MorePage() { useNavigationListener(); diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx b/gui/src/pages/More/progress/IndexingProgressBar.tsx similarity index 91% rename from gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx rename to gui/src/pages/More/progress/IndexingProgressBar.tsx index 5de74fb3f..6d0f7f104 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx +++ b/gui/src/pages/More/progress/IndexingProgressBar.tsx @@ -1,5 +1,5 @@ import { IndexingProgressUpdate } from "core"; -import { getProgressPercentage } from "./IndexingProgress"; +import { getProgressPercentage } from "."; export interface IndexingProgressBarProps { update: IndexingProgressUpdate; diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx b/gui/src/pages/More/progress/IndexingProgressIndicator.tsx similarity index 95% rename from gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx rename to gui/src/pages/More/progress/IndexingProgressIndicator.tsx index 944fdc917..f337a1d0a 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx +++ b/gui/src/pages/More/progress/IndexingProgressIndicator.tsx @@ -1,10 +1,10 @@ import { IndexingProgressUpdate } from "core"; -import { getProgressPercentage } from "./IndexingProgress"; import { ArrowPathIcon, PauseCircleIcon, CheckCircleIcon, } from "@heroicons/react/24/outline"; +import { getProgressPercentage } from "."; export interface IndexingProgressIndicatorProps { update: IndexingProgressUpdate; diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx b/gui/src/pages/More/progress/IndexingProgressSubtext.tsx similarity index 100% rename from gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx rename to gui/src/pages/More/progress/IndexingProgressSubtext.tsx diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx b/gui/src/pages/More/progress/IndexingProgressTitleText.tsx similarity index 65% rename from gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx rename to gui/src/pages/More/progress/IndexingProgressTitleText.tsx index 61d4bbba6..9cf014e10 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx +++ b/gui/src/pages/More/progress/IndexingProgressTitleText.tsx @@ -1,19 +1,11 @@ import { IndexingProgressUpdate } from "core"; import { AnimatedEllipsis } from "../../../components"; +import { STATUS_TO_TEXT } from "."; export interface IndexingProgressTitleTextProps { update: IndexingProgressUpdate; } -const STATUS_TO_TEXT: Record = { - done: "Indexing complete", - loading: "Initializing", - indexing: "Indexing in-progress", - paused: "Indexing paused", - failed: "Indexing failed", - disabled: "Indexing disabled", -}; - function IndexingProgressTitleText({ update }: IndexingProgressTitleTextProps) { const showEllipsis = update.status === "loading"; diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx b/gui/src/pages/More/progress/codebase/IndexingProgressErrorText.tsx similarity index 94% rename from gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx rename to gui/src/pages/More/progress/codebase/IndexingProgressErrorText.tsx index fff7ab9a8..c8ec68937 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx +++ b/gui/src/pages/More/progress/codebase/IndexingProgressErrorText.tsx @@ -1,8 +1,8 @@ import { IndexingProgressUpdate } from "core"; import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider"; import { useSelector } from "react-redux"; -import { RootState } from "../../../redux/store"; -import { isJetBrains } from "../../../util"; +import { RootState } from "../../../../redux/store"; +import { isJetBrains } from "../../../../util"; import { XCircleIcon } from "@heroicons/react/24/outline"; export interface IndexingProgressErrorTextProps { diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx b/gui/src/pages/More/progress/codebase/index.tsx similarity index 75% rename from gui/src/pages/More/IndexingProgress/IndexingProgress.tsx rename to gui/src/pages/More/progress/codebase/index.tsx index f3d4fea55..a0388b785 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx +++ b/gui/src/pages/More/progress/codebase/index.tsx @@ -1,26 +1,20 @@ import { IndexingProgressUpdate } from "core"; import { useContext, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { isJetBrains } from "../../../util"; -import { useWebviewListener } from "../../../hooks/useWebviewListener"; -import IndexingProgressBar from "./IndexingProgressBar"; -import IndexingProgressIndicator from "./IndexingProgressIndicator"; -import IndexingProgressTitleText from "./IndexingProgressTitleText"; -import IndexingProgressSubtext from "./IndexingProgressSubtext"; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { isJetBrains } from "../../../../util"; +import { useWebviewListener } from "../../../../hooks/useWebviewListener"; +import IndexingProgressBar from "../IndexingProgressBar"; +import IndexingProgressIndicator from "../IndexingProgressIndicator"; +import IndexingProgressSubtext from "../IndexingProgressSubtext"; import { usePostHog } from "posthog-js/react"; -import ConfirmationDialog from "../../../components/dialogs/ConfirmationDialog"; +import ConfirmationDialog from "../../../../components/dialogs/ConfirmationDialog"; import { setShowDialog, setDialogMessage, -} from "../../../redux/slices/uiStateSlice"; +} from "../../../../redux/slices/uiStateSlice"; import IndexingProgressErrorText from "./IndexingProgressErrorText"; - -export function getProgressPercentage( - progress: IndexingProgressUpdate["progress"], -) { - return Math.min(100, Math.max(0, progress * 100)); -} +import IndexingProgressTitleText from "../IndexingProgressTitleText"; function IndexingProgress() { const ideMessenger = useContext(IdeMessengerContext); @@ -33,19 +27,13 @@ function IndexingProgress() { status: "loading", }); - // If sidebar is opened after extension initializes, retrieve saved states. - let initialized = false; - useWebviewListener("indexProgress", async (data) => { setUpdate(data); }); useEffect(() => { - if (!initialized) { - // Triggers retrieval for possible non-default states set prior to IndexingProgressBar initialization - ideMessenger.post("index/indexingProgressBarInitialized", undefined); - initialized = true; - } + // Triggers retrieval for possible non-default states set prior to IndexingProgressBar initialization + ideMessenger.post("index/indexingProgressBarInitialized", undefined); }, []); useEffect(() => { diff --git a/gui/src/pages/More/progress/docs/index.tsx b/gui/src/pages/More/progress/docs/index.tsx new file mode 100644 index 000000000..b2590adbe --- /dev/null +++ b/gui/src/pages/More/progress/docs/index.tsx @@ -0,0 +1,121 @@ +import { IndexingProgressUpdate } from "core"; +import { useContext, useEffect, useState } from "react"; +import { useDispatch } from "react-redux"; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { isJetBrains } from "../../../../util"; +import { useWebviewListener } from "../../../../hooks/useWebviewListener"; +import IndexingProgressBar from "../IndexingProgressBar"; +import IndexingProgressIndicator from "../IndexingProgressIndicator"; +import IndexingProgressSubtext from "../IndexingProgressSubtext"; +import { usePostHog } from "posthog-js/react"; +import ConfirmationDialog from "../../../../components/dialogs/ConfirmationDialog"; +import { + setShowDialog, + setDialogMessage, +} from "../../../../redux/slices/uiStateSlice"; +import IndexingProgressTitleText from "../IndexingProgressTitleText"; +import IndexingProgressErrorText from "../codebase/IndexingProgressErrorText"; + +function DocsIndexingProgressItem() { + const ideMessenger = useContext(IdeMessengerContext); + const posthog = usePostHog(); + const dispatch = useDispatch(); + const [paused, setPaused] = useState(undefined); + const [update, setUpdate] = useState({ + desc: "Loading indexing config", + progress: 0.0, + status: "loading", + }); + + useWebviewListener("indexProgress", async (data) => { + setUpdate(data); + }); + + useEffect(() => { + // Triggers retrieval for possible non-default states set prior to IndexingProgressBar initialization + ideMessenger.post("index/indexingProgressBarInitialized", undefined); + }, []); + + useEffect(() => { + if (paused === undefined) return; + ideMessenger.post("index/setPaused", paused); + }, [paused]); + + function onClickRetry() { + // For now, we don't show in JetBrains since the re-index command + // is not yet implemented + if (update.shouldClearIndexes && !isJetBrains()) { + dispatch(setShowDialog(true)); + dispatch( + setDialogMessage( + { + posthog.capture("rebuild_index_clicked"); + ideMessenger.post("index/forceReIndex", { + shouldClearIndexes: true, + }); + }} + />, + ), + ); + } else { + ideMessenger.post("index/forceReIndex", undefined); + } + } + + function onClick() { + switch (update.status) { + case "failed": + onClickRetry(); + break; + case "indexing": + case "loading": + case "paused": + if (update.progress < 1 && update.progress >= 0) { + setPaused((prev) => !prev); + } else { + ideMessenger.post("index/forceReIndex", undefined); + } + break; + case "disabled": + ideMessenger.post("openConfigJson", undefined); + break; + case "done": + ideMessenger.post("index/forceReIndex", undefined); + default: + break; + } + } + + return ( +
+
+ + {update.status !== "loading" && ( + + )} +
+ + + + + + {update.status === "failed" && ( +
+ +
+ )} +
+ ); +} + +function AllDocsIndexingProgress() {} +export default AllDocsIndexingProgress; diff --git a/gui/src/pages/More/progress/index.ts b/gui/src/pages/More/progress/index.ts new file mode 100644 index 000000000..44c3d50e3 --- /dev/null +++ b/gui/src/pages/More/progress/index.ts @@ -0,0 +1,17 @@ +import { IndexingProgressUpdate } from "core"; + +export function getProgressPercentage( + progress: IndexingProgressUpdate["progress"], +) { + return Math.min(100, Math.max(0, progress * 100)); +} + +export const STATUS_TO_TEXT: Record = + { + done: "Indexing complete", + loading: "Initializing", + indexing: "Indexing in-progress", + paused: "Indexing paused", + failed: "Indexing failed", + disabled: "Indexing disabled", + }; From 44c7b7fff39fdb947e9015aaf361356bc47f389c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 14 Nov 2024 16:35:08 -0800 Subject: [PATCH 14/82] revert files per index changes - moved to different branch --- core/core.ts | 80 +++++-------------- core/indexing/CodebaseIndexer.ts | 77 ++++-------------- core/protocol/core.ts | 1 - core/protocol/passThrough.ts | 3 +- .../ContinuePluginStartupActivity.kt | 4 +- .../toolWindow/ContinueBrowser.kt | 1 - extensions/vscode/package-lock.json | 4 +- .../vscode/src/extension/VsCodeExtension.ts | 10 ++- 8 files changed, 45 insertions(+), 135 deletions(-) diff --git a/core/core.ts b/core/core.ts index a5514490a..6df1482ef 100644 --- a/core/core.ts +++ b/core/core.ts @@ -83,7 +83,7 @@ export class Core { constructor( private readonly messenger: IMessenger, private readonly ide: IDE, - private readonly onWrite: (text: string) => Promise = async () => {}, + private readonly onWrite: (text: string) => Promise = async () => { }, ) { // Ensure .continue directory is created setupInitialDotContinueDirectory(); @@ -174,7 +174,7 @@ export class Core { this.configHandler, ide, getLlm, - (e) => {}, + (e) => { }, (..._) => Promise.resolve([]), ); @@ -684,14 +684,9 @@ export class Core { await codebaseIndexer.clearIndexes(); } - const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs()); + const dirs = data?.dirs ?? await this.ide.getWorkspaceDirs(); await this.refreshCodebaseIndex(dirs); }); - on("index/forceReIndexFiles", async ({ data }) => { - if (data?.files?.length) { - await this.refreshCodebaseIndexFiles(data.files); - } - }); on("index/setPaused", (msg) => { new GlobalContext().update("indexingPaused", msg.data); this.indexingPauseToken.paused = msg.data; @@ -727,29 +722,14 @@ export class Core { } private indexingCancellationController: AbortController | undefined; - private async sendIndexingTelemetry(update: IndexingProgressUpdate) { - console.debug( - "Indexing failed with error: ", - update.desc, - update.debugInfo, - ); - void Telemetry.capture( - "indexing_error", - { - error: update.desc, - stack: update.debugInfo, - }, - false, - ); - } - private async refreshCodebaseIndex(paths: string[]) { + private async refreshCodebaseIndex(dirs: string[]) { if (this.indexingCancellationController) { this.indexingCancellationController.abort(); } this.indexingCancellationController = new AbortController(); - for await (const update of (await this.codebaseIndexerPromise).refreshDirs( - paths, + for await (const update of (await this.codebaseIndexerPromise).refresh( + dirs, this.indexingCancellationController.signal, )) { let updateToSend = { ...update }; @@ -763,41 +743,19 @@ export class Core { this.indexingState = updateToSend; if (update.status === "failed") { - void this.sendIndexingTelemetry(update); - } - } - - this.messenger.send("refreshSubmenuItems", undefined); - } - - private async refreshCodebaseIndexFiles(files: string[]) { - // Can be cancelled by codebase index but not vice versa - if ( - this.indexingCancellationController && - !this.indexingCancellationController.signal.aborted - ) { - return console.debug( - "Codebase indexing already in progress, skipping indexing of files\n" + - files.join("\n"), - ); - } - this.indexingCancellationController = new AbortController(); - for await (const update of (await this.codebaseIndexerPromise).refreshFiles( - files, - this.indexingCancellationController.signal, - )) { - let updateToSend = { ...update }; - if (update.status === "failed") { - updateToSend.status = "done"; - updateToSend.desc = "Indexing complete"; - updateToSend.progress = 1.0; - } - - void this.messenger.request("indexProgress", updateToSend); - this.indexingState = updateToSend; - - if (update.status === "failed") { - void this.sendIndexingTelemetry(update); + console.debug( + "Indexing failed with error: ", + update.desc, + update.debugInfo, + ); + void Telemetry.capture( + "indexing_error", + { + error: update.desc, + stack: update.debugInfo, + }, + false, + ); } } diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 175e1a062..b4962d182 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -17,7 +17,6 @@ import { RefreshIndexResults, } from "./types.js"; import { walkDirAsync } from "./walkDir.js"; -import { getBasename } from "../util/index.js"; export class PauseToken { constructor(private _paused: boolean) {} @@ -145,61 +144,13 @@ export class CodebaseIndexer { } } - async *refreshFiles( - files: string[], - abortSignal: AbortSignal, - ): AsyncGenerator { - let progress = 0; - if (files.length === 0) { - yield { - progress: 1, - desc: "Indexing Complete", - status: "done", - }; - } - - const progressPer = 1 / files.length; - try { - for (const file of files) { - yield { - progress, - desc: `Indexing file ${file}...`, - status: "indexing", - }; - await this.refreshFile(file); - - progress += progressPer; - - if (this.pauseToken.paused) { - yield* this.yieldUpdateAndPause(); - } - if (abortSignal.aborted) { - yield { - progress: 1, - desc: "Indexing cancelled", - status: "disabled", - }; - return; - } - } - - yield { - progress: 1, - desc: "Indexing Complete", - status: "done", - }; - } catch (err) { - yield this.handleErrorAndGetProgressUpdate(err); - } - } - - async *refreshDirs( - dirs: string[], + async *refresh( + workspaceDirs: string[], abortSignal: AbortSignal, ): AsyncGenerator { let progress = 0; - if (dirs.length === 0) { + if (workspaceDirs.length === 0) { yield { progress, desc: "Nothing to index", @@ -224,9 +175,11 @@ export class CodebaseIndexer { }; } + let completedDirs = 0; + // Wait until Git Extension has loaded to report progress // so we don't appear stuck at 0% while waiting - await this.ide.getRepoName(dirs[0]); + await this.ide.getRepoName(workspaceDirs[0]); yield { progress, @@ -235,16 +188,16 @@ export class CodebaseIndexer { }; const beginTime = Date.now(); - for (const directory of dirs) { + for (const directory of workspaceDirs) { const dirBasename = await this.basename(directory); yield { progress, desc: `Discovering files in ${dirBasename}...`, status: "indexing", }; - const directoryFiles = []; + const workspaceFiles = []; for await (const p of walkDirAsync(directory, this.ide)) { - directoryFiles.push(p); + workspaceFiles.push(p); if (abortSignal.aborted) { yield { progress: 1, @@ -265,7 +218,7 @@ export class CodebaseIndexer { try { for await (const updateDesc of this.indexFiles( directory, - directoryFiles, + workspaceFiles, branch, repoName, )) { @@ -287,7 +240,7 @@ export class CodebaseIndexer { nextLogThreshold += 0.025; this.logProgress( beginTime, - Math.floor(directoryFiles.length * updateDesc.progress), + Math.floor(workspaceFiles.length * updateDesc.progress), updateDesc.progress, ); } @@ -394,18 +347,18 @@ export class CodebaseIndexer { } private async *indexFiles( - directory: string, - files: string[], + workspaceDir: string, + workspaceFiles: string[], branch: string, repoName: string | undefined, ): AsyncGenerator { - const stats = await this.ide.getLastModified(files); + const stats = await this.ide.getLastModified(workspaceFiles); const indexesToBuild = await this.getIndexesToBuild(); let completedIndexCount = 0; let progress = 0; for (const codebaseIndex of indexesToBuild) { const tag: IndexTag = { - directory, + directory: workspaceDir, branch, artifactId: codebaseIndex.artifactId, }; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index e30de4673..2c9af1433 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -147,7 +147,6 @@ export type ToCoreFromIdeOrWebviewProtocol = { undefined | { dirs?: string[]; shouldClearIndexes?: boolean }, void, ]; - "index/forceReIndexFiles": [undefined | { files?: string[] }, void]; "index/indexingProgressBarInitialized": [undefined, void]; completeOnboarding: [ { diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 21ac52c8d..1c0f5e962 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -41,7 +41,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "stats/getTokensPerModel", "index/setPaused", "index/forceReIndex", - "index/forceReIndexFiles", "index/indexingProgressBarInitialized", "completeOnboarding", "addAutocompleteModel", @@ -61,5 +60,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "isContinueInputFocused", "didChangeAvailableProfiles", "setTTSActive", - "getWebviewHistoryLength", + "getWebviewHistoryLength" ]; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 451baae68..fa39729fa 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -169,8 +169,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { // Create a data map if there are any paths to re-index if (allPaths.isNotEmpty()) { - val data = mapOf("files" to allPaths) - continuePluginService.coreMessenger?.request("index/forceReIndexFiles", data, null) { _ -> } + val data = mapOf("dirs" to allPaths) + continuePluginService.coreMessenger?.request("index/forceReIndex", data, null) { _ -> } } } }) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 147f153e3..26896906b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -58,7 +58,6 @@ class ContinueBrowser(val project: Project, url: String) { "stats/getTokensPerModel", "index/setPaused", "index/forceReIndex", - "index/forceReIndexFiles", "index/indexingProgressBarInitialized", "completeOnboarding", "addAutocompleteModel", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 29ac4731f..24930d980 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.230", + "version": "0.9.229", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.230", + "version": "0.9.229", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index bb46e7466..06263e356 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -297,15 +297,17 @@ export class VsCodeExtension { this.core.invoke("index/forceReIndex", undefined); } else { // Reindex the file - this.core.invoke("index/forceReIndexFiles", { - files: [filepath], + this.core.invoke("index/forceReIndex", { + dirs: [filepath], }); } }); vscode.workspace.onDidDeleteFiles(async (event) => { - this.core.invoke("index/forceReIndexFiles", { - files: event.files.map((file) => file.fsPath), + this.core.invoke("index/forceReIndex", { + dirs: event.files.map((file) => + file.fsPath.split("/").slice(0, -1).join("/"), + ), }); }); From 067da11573d17049b39749fe53086efc832bd56d Mon Sep 17 00:00:00 2001 From: Test Date: Fri, 15 Nov 2024 14:32:13 -0800 Subject: [PATCH 15/82] adjust styling on small breakpoints --- extensions/vscode/package-lock.json | 4 ++-- .../StepContainer/MultifileEditActions.tsx | 10 +++++++++- gui/src/components/StepContainer/StepContainer.tsx | 12 +++++------- .../StepContainerPreToolbar/ApplyActions.tsx | 13 +++++++------ .../markdown/StepContainerPreToolbar/CopyButton.tsx | 6 +++--- .../markdown/StepContainerPreToolbar/FileInfo.tsx | 7 +++---- .../StepContainerPreToolbar.tsx | 11 +++++++---- manual-testing-sandbox/helloNested.py | 0 8 files changed, 36 insertions(+), 27 deletions(-) create mode 100644 manual-testing-sandbox/helloNested.py diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 24930d980..29ac4731f 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.229", + "version": "0.9.230", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.229", + "version": "0.9.230", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/gui/src/components/StepContainer/MultifileEditActions.tsx b/gui/src/components/StepContainer/MultifileEditActions.tsx index db6b0d871..5fb7122df 100644 --- a/gui/src/components/StepContainer/MultifileEditActions.tsx +++ b/gui/src/components/StepContainer/MultifileEditActions.tsx @@ -4,6 +4,8 @@ import AcceptRejectAllButtons from "./AcceptRejectAllButtons"; import FeedbackButtons from "./FeedbackButtons"; import UndoAndRedoButtons from "./UndoAndRedoButtons"; import { ChatHistoryItem } from "core"; +import { stripImages } from "core/llm/images"; +import { CopyIconButton } from "../gui/CopyIconButton"; export interface MultifileEditActionsProps { index: number; @@ -30,7 +32,6 @@ export default function MultifileEditActions({ (state) => state.status === "closed", ); - const isStreaming = applyStates.some((state) => state.status === "streaming"); const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex; const hasPendingApplies = pendingApplyStates.length > 0; @@ -50,6 +51,13 @@ export default function MultifileEditActions({ )}
+ +
diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index 844252a8b..f5673e4e8 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -31,15 +31,13 @@ export default function StepContainer(props: StepContainerProps) { const curCheckpointIndex = useSelector( (store: RootState) => store.state.curCheckpointIndex, ); + const isMultifileEdit = useSelector( + (store: RootState) => store.state.isMultifileEdit, + ); const uiConfig = useUIConfig(); const shouldHideActions = active && props.isLast; const isStepAheadOfCurCheckpoint = - Math.floor(props.index / 2) > curCheckpointIndex; - console.log({ - index: props.index, - curCheckpointIndex, - isStepAheadOfCurCheckpoint, - }); + isMultifileEdit && Math.floor(props.index / 2) > curCheckpointIndex; useEffect(() => { if (!active) { @@ -78,7 +76,7 @@ export default function StepContainer(props: StepContainerProps) { return (
- - {`${props.applyState.numDiffs === 1 ? "1 diff" : `${props.applyState.numDiffs} diffs`} remaining`} +
+ + {`${props.applyState.numDiffs === 1 ? "1 diff" : `${props.applyState.numDiffs} diffs`}`} + {` remaining`} - Applied - + + Applied + ); } diff --git a/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx b/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx index 99dfddfaa..195615380 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx @@ -15,18 +15,18 @@ export default function CopyButton({ text }: CopyButtonProps) { onClick={copyText} >
{copied ? ( <> - Copied + Copied ) : ( <> - Copy + Copy )}
diff --git a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx index c95e7962d..6d8fc8d74 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx @@ -12,7 +12,6 @@ export interface FileInfoProps { const FileInfo = ({ filepath, range }: FileInfoProps) => { const ideMessenger = useContext(IdeMessengerContext); - // TODO: Need to turn into relative or fq path function onClickFileName() { ideMessenger.post("showFile", { filepath, @@ -20,13 +19,13 @@ const FileInfo = ({ filepath, range }: FileInfoProps) => { } return ( -
+
- + {getBasename(filepath)} {range && ` ${range}`} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 39272df92..9acff543d 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -32,6 +32,7 @@ const TopDiv = styled.div` border-radius: ${defaultBorderRadius}; margin-bottom: 8px !important; background-color: ${vscEditorBackground}; + min-width: 0; animation: ${fadeInAnimation} 300ms ease-out forwards; `; @@ -163,17 +164,19 @@ export default function StepContainerPreToolbar( return ( -
+
- +
+ +
-
+
{isGeneratingCodeBlock && ( Date: Fri, 15 Nov 2024 14:32:55 -0800 Subject: [PATCH 16/82] Update UndoAndRedoButtons.tsx --- gui/src/components/StepContainer/UndoAndRedoButtons.tsx | 6 ------ 1 file changed, 6 deletions(-) diff --git a/gui/src/components/StepContainer/UndoAndRedoButtons.tsx b/gui/src/components/StepContainer/UndoAndRedoButtons.tsx index 769669797..2ee69a11a 100644 --- a/gui/src/components/StepContainer/UndoAndRedoButtons.tsx +++ b/gui/src/components/StepContainer/UndoAndRedoButtons.tsx @@ -31,12 +31,6 @@ export default function UndoAndRedoButtons() { const checkpoint = checkpoints[checkpointIndex]; for (const [filepath, prevFileContent] of Object.entries(checkpoint)) { - console.log({ - filepath, - prevFileContent, - checkpointIndex, - curCheckpointIndex, - }); ideMessenger.post("overwriteFile", { filepath, prevFileContent }); } From d2decdb80e7ca2e3876b9541f91ee48c94c0586b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 15 Nov 2024 14:34:03 -0800 Subject: [PATCH 17/82] docs servie updates --- core/core.ts | 2 +- core/indexing/docs/DocsCrawler.ts | 2 +- core/indexing/docs/DocsService.ts | 93 +++++++++++--------- gui/src/hooks/useSetup.ts | 16 +--- gui/src/hooks/useSubmenuContextProviders.tsx | 7 +- 5 files changed, 56 insertions(+), 64 deletions(-) diff --git a/core/core.ts b/core/core.ts index 6df1482ef..dc140cf3d 100644 --- a/core/core.ts +++ b/core/core.ts @@ -688,7 +688,7 @@ export class Core { await this.refreshCodebaseIndex(dirs); }); on("index/setPaused", (msg) => { - new GlobalContext().update("indexingPaused", msg.data); + this.globalContext.update("indexingPaused", msg.data); this.indexingPauseToken.paused = msg.data; }); on("index/indexingProgressBarInitialized", async (msg) => { diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index cb9146ab5..01f0efab1 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -95,6 +95,6 @@ export default DocsCrawler; export { CheerioCrawler, ChromiumCrawler, - ChromiumInstaller as ChromiumInstaller, + ChromiumInstaller, GitHubCrawler, }; diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index d97b92974..2c9a01e1e 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -103,26 +103,6 @@ export default class DocsService { return docsService; } - async isJetBrainsAndPreIndexedDocsProvider(): Promise { - const isJetBrains = await this.isJetBrains(); - - const isPreIndexedDocsProvider = - this.config.embeddingsProvider.id === - DocsService.preIndexedDocsEmbeddingsProvider.id; - - return isJetBrains && isPreIndexedDocsProvider; - } - - /* - * Currently, we generate and host embeddings for pre-indexed docs using transformers. - * However, we don't ship transformers with the JetBrains extension. - * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. - */ - async canUsePreindexedDocs() { - const isJetBrains = await this.isJetBrains(); - return !isJetBrains; - } - async delete(startUrl: string) { await this.deleteFromLance(startUrl); await this.deleteFromSqlite(startUrl); @@ -426,36 +406,41 @@ export default class DocsService { private async init(configHandler: ConfigHandler) { this.config = await configHandler.loadConfig(); - this.docsCrawler = new DocsCrawler(this.ide, this.config); + await this.handleConfigUpdate({config: this.config}); + configHandler.onConfigUpdate(this.handleConfigUpdate); + } - const embeddingsProvider = await this.getEmbeddingsProvider(); + private async handleConfigUpdate({config: newConfig}: {config: ContinueConfig | undefined}) { + if(newConfig){ + this.config = newConfig; + this.docsCrawler = new DocsCrawler(this.ide, this.config); - this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); + const embeddingsProvider = await this.getEmbeddingsProvider(); + + this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); - configHandler.onConfigUpdate(async ({ config: newConfig }) => { - if (newConfig) { - const oldConfig = this.config; + const oldConfig = this.config; - // Need to update class property for config at the beginning of this callback - // to ensure downstream methods have access to the latest config. - this.config = newConfig; + // Need to update class property for config at the beginning of this callback + // to ensure downstream methods have access to the latest config. + this.config = newConfig; - if (oldConfig.docs !== newConfig.docs) { - await this.syncConfigAndSqlite(); - } - - const shouldReindex = - await this.shouldReindexDocsOnNewEmbeddingsProvider( - newConfig.embeddingsProvider.id, - ); - - if (shouldReindex) { - await this.reindexDocsOnNewEmbeddingsProvider( - newConfig.embeddingsProvider, - ); - } + if (oldConfig.docs !== newConfig.docs) { + await this.syncConfigAndSqlite(); } - }); + + const shouldReindex = + await this.shouldReindexDocsOnNewEmbeddingsProvider( + newConfig.embeddingsProvider.id, + ); + + if (shouldReindex) { + await this.reindexDocsOnNewEmbeddingsProvider( + newConfig.embeddingsProvider, + ); + } + } + } private async syncConfigAndSqlite() { @@ -609,6 +594,26 @@ export default class DocsService { return ideInfo.ideType === "jetbrains"; } + async isJetBrainsAndPreIndexedDocsProvider(): Promise { + const isJetBrains = await this.isJetBrains(); + + const isPreIndexedDocsProvider = + this.config.embeddingsProvider.id === + DocsService.preIndexedDocsEmbeddingsProvider.id; + + return isJetBrains && isPreIndexedDocsProvider; + } + + /* + * Currently, we generate and host embeddings for pre-indexed docs using transformers. + * However, we don't ship transformers with the JetBrains extension. + * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. + */ + async canUsePreindexedDocs() { + const isJetBrains = await this.isJetBrains(); + return !isJetBrains; + } + private async hasIndexedDoc(startUrl: string) { const db = await this.getOrCreateSqliteDb(); const docs = await db.all( diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 2fed805da..8ece44bec 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -37,7 +37,6 @@ function useSetup(dispatch: Dispatch) { dispatch(setConfig(config)); dispatch(setSelectedProfileId(profileId)); setConfigLoaded(true); - setLocalStorage("disableIndexing", config.disableIndexing || false); // Perform any actions needed with the config if (config.ui?.fontSize) { @@ -46,20 +45,7 @@ function useSetup(dispatch: Dispatch) { } }; - // Load config from the IDE - useEffect(() => { - loadConfig(); - const interval = setInterval(() => { - if (configLoaded) { - clearInterval(interval); - return; - } - loadConfig(); - }, 2_000); - - return () => clearInterval(interval); - }, [configLoaded]); - + // ON LOAD useEffect(() => { // Override persisted state dispatch(setInactive()); diff --git a/gui/src/hooks/useSubmenuContextProviders.tsx b/gui/src/hooks/useSubmenuContextProviders.tsx index fc0b0c71a..7f9e65f73 100644 --- a/gui/src/hooks/useSubmenuContextProviders.tsx +++ b/gui/src/hooks/useSubmenuContextProviders.tsx @@ -13,6 +13,7 @@ import { IdeMessengerContext } from "../context/IdeMessenger"; import { selectContextProviderDescriptions } from "../redux/selectors"; import { getLocalStorage } from "../util/localStorage"; import { useWebviewListener } from "./useWebviewListener"; +import { RootState } from "../redux/store"; const MINISEARCH_OPTIONS = { prefix: true, @@ -38,6 +39,8 @@ function useSubmenuContextProviders() { const [isLoading, setIsLoading] = useState(false); const [autoLoadTriggered, setAutoLoadTriggered] = useState(false); + const config = useSelector((store: RootState) => store.state.config); + const ideMessenger = useContext(IdeMessengerContext); const memoizedGetOpenFileItems = useMemo(() => { @@ -213,12 +216,10 @@ function useSubmenuContextProviders() { const loadSubmenuItems = async () => { try { - const disableIndexing = getLocalStorage("disableIndexing") ?? false; - await Promise.all( contextProviderDescriptions.map(async (description) => { const shouldSkipProvider = - description.dependsOnIndexing && disableIndexing; + description.dependsOnIndexing && config.disableIndexing; if (shouldSkipProvider) { console.debug( From fc934933c570c9c97150732b85e0426b94143ae1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 15 Nov 2024 15:23:31 -0800 Subject: [PATCH 18/82] applytofile refactor --- extensions/vscode/package-lock.json | 4 +- .../vscode/src/extension/VsCodeMessenger.ts | 6 +++ .../StepContainerPreActionButtons.tsx | 9 ++-- .../StepContainerPreToolbar.tsx | 9 ++-- gui/src/hooks/useApplyCodeBlock.ts | 45 ------------------- gui/src/redux/slices/stateSlice.ts | 7 ++- 6 files changed, 22 insertions(+), 58 deletions(-) delete mode 100644 gui/src/hooks/useApplyCodeBlock.ts diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 3f4123969..24930d980 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.228", + "version": "0.9.229", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.228", + "version": "0.9.229", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 6bb250041..d5e1d38a8 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -175,6 +175,12 @@ export class VsCodeMessenger { ); this.onWebview("applyToFile", async ({ data }) => { + webviewProtocol.request("updateApplyState", { + streamId: data.streamId, + status: "streaming", + fileContent: data.text, + }); + let filepath = data.filepath; // If there is a filepath, verify it exists and then open the file diff --git a/gui/src/components/markdown/StepContainerPreActionButtons.tsx b/gui/src/components/markdown/StepContainerPreActionButtons.tsx index 669479fa3..21fafc2f5 100644 --- a/gui/src/components/markdown/StepContainerPreActionButtons.tsx +++ b/gui/src/components/markdown/StepContainerPreActionButtons.tsx @@ -13,10 +13,10 @@ import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import { CopyIconButton } from "../gui/CopyIconButton"; import useUIConfig from "../../hooks/useUIConfig"; import { v4 as uuidv4 } from "uuid"; -import { useApplyCodeBlock } from "../../hooks/useApplyCodeBlock"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useSelector } from "react-redux"; import { RootState } from "../../redux/store"; +import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; const TopDiv = styled.div` outline: 0.5px solid rgba(153, 153, 152); @@ -68,7 +68,6 @@ export default function StepContainerPreActionButtons({ const nextCodeBlockIndex = useSelector( (state: RootState) => state.state.nextCodeBlockToApplyIndex, ); - const applyCodeBlock = useApplyCodeBlock(); const isBottomToolbarPosition = uiConfig?.codeBlockToolbarPosition == "bottom"; @@ -80,10 +79,12 @@ export default function StepContainerPreActionButtons({ streamIdRef.current = uuidv4(); } + const defaultModel = useSelector(defaultModelSelector); function onClickApply() { - applyCodeBlock({ - codeBlockContent, + ideMessenger.post("applyToFile", { streamId: streamIdRef.current, + text: codeBlockContent, + curSelectedModelTitle: defaultModel.title, }); } diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 39272df92..f2f460b18 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -16,6 +16,7 @@ import ApplyActions from "./ApplyActions"; import CopyButton from "./CopyButton"; import FileInfo from "./FileInfo"; import GeneratingCodeLoader from "./GeneratingCodeLoader"; +import { defaultModelSelector } from "../../../redux/selectors/modelSelectors"; const fadeInAnimation = keyframes` from { @@ -69,7 +70,7 @@ export default function StepContainerPreToolbar( const [isExpanded, setIsExpanded] = useState(isMultifileEdit ? false : true); const [codeBlockContent, setCodeBlockContent] = useState(""); const isChatActive = useSelector((state: RootState) => state.state.active); - const applyCodeBlock = useApplyCodeBlock(); + const nextCodeBlockIndex = useSelector( (state: RootState) => state.state.nextCodeBlockToApplyIndex, ); @@ -92,11 +93,13 @@ export default function StepContainerPreToolbar( const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex; const hasFileExtension = /\.[0-9a-z]+$/i.test(props.filepath); + const defaultModel = useSelector(defaultModelSelector); function onClickApply() { - applyCodeBlock({ + ideMessenger.post("applyToFile", { streamId: streamIdRef.current, filepath: props.filepath, - codeBlockContent: props.codeBlockContent, + text: codeBlockContent, + curSelectedModelTitle: defaultModel.title, }); } diff --git a/gui/src/hooks/useApplyCodeBlock.ts b/gui/src/hooks/useApplyCodeBlock.ts deleted file mode 100644 index 9ac1888f5..000000000 --- a/gui/src/hooks/useApplyCodeBlock.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { useContext } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { IdeMessengerContext } from "../context/IdeMessenger"; -import { - incrementNextCodeBlockToApplyIndex, - updateApplyState, -} from "../redux/slices/stateSlice"; -import { defaultModelSelector } from "../redux/selectors/modelSelectors"; - -export interface useApplyCodeBlockParams { - codeBlockContent: string; - streamId?: string; - filepath?: string; -} - -export function useApplyCodeBlock() { - const dispatch = useDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - const defaultModel = useSelector(defaultModelSelector); - - const applyCodeBlock = async ({ - streamId, - filepath, - codeBlockContent, - }: useApplyCodeBlockParams) => { - dispatch( - updateApplyState({ - filepath, - streamId, - status: "streaming", - }), - ); - - await ideMessenger.request("applyToFile", { - streamId, - filepath, - text: codeBlockContent, - curSelectedModelTitle: defaultModel.title, - }); - - dispatch(incrementNextCodeBlockToApplyIndex({})); - }; - - return applyCodeBlock; -} diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 17be955b8..34f844908 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -447,9 +447,6 @@ export const stateSlice = createSlice({ [payload.filepath]: payload.content, }; }, - incrementNextCodeBlockToApplyIndex: (state, action) => { - state.nextCodeBlockToApplyIndex++; - }, updateApplyState: (state, { payload }: PayloadAction) => { const index = state.applyStates.findIndex( (applyState) => applyState.streamId === payload.streamId, @@ -464,6 +461,9 @@ export const stateSlice = createSlice({ curApplyState.numDiffs = payload.numDiffs ?? curApplyState.numDiffs; curApplyState.filepath = payload.filepath ?? curApplyState.filepath; } + if(payload.status === "done"){ + state.nextCodeBlockToApplyIndex++; + } }, resetNextCodeBlockToApplyIndex: (state) => { state.nextCodeBlockToApplyIndex = 0; @@ -499,7 +499,6 @@ export const { updateCurCheckpoint, setCurCheckpointIndex, resetNextCodeBlockToApplyIndex, - incrementNextCodeBlockToApplyIndex, updateApplyState, } = stateSlice.actions; From dfe11d357a41c43bfe08d9a456b0bcfc6343c15b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 15 Nov 2024 15:39:49 -0800 Subject: [PATCH 19/82] indexing progress status type --- core/index.d.ts | 12 ++++++++++++ core/indexing/docs/DocsService.ts | 13 ++++++------- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 1bad9fd74..6b275d7e2 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -45,6 +45,18 @@ export interface IndexingProgressUpdate { debugInfo?: string; } +// This is more or less a V2 of IndexingProgressUpdate +export interface IndexingStatusUpdate { + type: "docs"; + id: string; // Unique identifier, e.g. docs start url + progress: number; + description: string; + status: "initializing" | "indexing" | "complete" | "paused" | "failed" | "disabled"; + embeddingsModel: string; + isReindexing: boolean; + debugInfo: string; +} + export type PromptTemplateFunction = ( history: ChatMessage[], otherData: Record, diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 2c9a01e1e..1bf358e8f 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -407,6 +407,11 @@ export default class DocsService { private async init(configHandler: ConfigHandler) { this.config = await configHandler.loadConfig(); await this.handleConfigUpdate({config: this.config}); + + // only update on init because should only update on reindexDocsOnNewEmbeddingsProvider + const embeddingsProvider = await this.getEmbeddingsProvider(); + this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); + configHandler.onConfigUpdate(this.handleConfigUpdate); } @@ -415,10 +420,6 @@ export default class DocsService { this.config = newConfig; this.docsCrawler = new DocsCrawler(this.ide, this.config); - const embeddingsProvider = await this.getEmbeddingsProvider(); - - this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); - const oldConfig = this.config; // Need to update class property for config at the beginning of this callback @@ -817,6 +818,4 @@ export default class DocsService { console.log("Completed reindexing of all docs"); } -} - -export const docsServiceSingleton = DocsService.getSingleton(); +} \ No newline at end of file From 23bde0305495d9ce0ac8da99d3d2cde63f5a2210 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 15 Nov 2024 15:42:05 -0800 Subject: [PATCH 20/82] revert to old indexing progress folder structure --- .../IndexingProgress.tsx} | 34 +++-- .../IndexingProgressBar.tsx | 2 +- .../IndexingProgressErrorText.tsx | 4 +- .../IndexingProgressIndicator.tsx | 2 +- .../IndexingProgressSubtext.tsx | 0 .../IndexingProgressTitleText.tsx | 10 +- gui/src/pages/More/IndexingProgress/index.ts | 1 + gui/src/pages/More/More.tsx | 2 +- gui/src/pages/More/progress/docs/index.tsx | 121 ------------------ gui/src/pages/More/progress/index.ts | 17 --- 10 files changed, 38 insertions(+), 155 deletions(-) rename gui/src/pages/More/{progress/codebase/index.tsx => IndexingProgress/IndexingProgress.tsx} (75%) rename gui/src/pages/More/{progress => IndexingProgress}/IndexingProgressBar.tsx (91%) rename gui/src/pages/More/{progress/codebase => IndexingProgress}/IndexingProgressErrorText.tsx (94%) rename gui/src/pages/More/{progress => IndexingProgress}/IndexingProgressIndicator.tsx (95%) rename gui/src/pages/More/{progress => IndexingProgress}/IndexingProgressSubtext.tsx (100%) rename gui/src/pages/More/{progress => IndexingProgress}/IndexingProgressTitleText.tsx (65%) create mode 100644 gui/src/pages/More/IndexingProgress/index.ts delete mode 100644 gui/src/pages/More/progress/docs/index.tsx delete mode 100644 gui/src/pages/More/progress/index.ts diff --git a/gui/src/pages/More/progress/codebase/index.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx similarity index 75% rename from gui/src/pages/More/progress/codebase/index.tsx rename to gui/src/pages/More/IndexingProgress/IndexingProgress.tsx index a0388b785..f3d4fea55 100644 --- a/gui/src/pages/More/progress/codebase/index.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx @@ -1,20 +1,26 @@ import { IndexingProgressUpdate } from "core"; import { useContext, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; -import { IdeMessengerContext } from "../../../../context/IdeMessenger"; -import { isJetBrains } from "../../../../util"; -import { useWebviewListener } from "../../../../hooks/useWebviewListener"; -import IndexingProgressBar from "../IndexingProgressBar"; -import IndexingProgressIndicator from "../IndexingProgressIndicator"; -import IndexingProgressSubtext from "../IndexingProgressSubtext"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { isJetBrains } from "../../../util"; +import { useWebviewListener } from "../../../hooks/useWebviewListener"; +import IndexingProgressBar from "./IndexingProgressBar"; +import IndexingProgressIndicator from "./IndexingProgressIndicator"; +import IndexingProgressTitleText from "./IndexingProgressTitleText"; +import IndexingProgressSubtext from "./IndexingProgressSubtext"; import { usePostHog } from "posthog-js/react"; -import ConfirmationDialog from "../../../../components/dialogs/ConfirmationDialog"; +import ConfirmationDialog from "../../../components/dialogs/ConfirmationDialog"; import { setShowDialog, setDialogMessage, -} from "../../../../redux/slices/uiStateSlice"; +} from "../../../redux/slices/uiStateSlice"; import IndexingProgressErrorText from "./IndexingProgressErrorText"; -import IndexingProgressTitleText from "../IndexingProgressTitleText"; + +export function getProgressPercentage( + progress: IndexingProgressUpdate["progress"], +) { + return Math.min(100, Math.max(0, progress * 100)); +} function IndexingProgress() { const ideMessenger = useContext(IdeMessengerContext); @@ -27,13 +33,19 @@ function IndexingProgress() { status: "loading", }); + // If sidebar is opened after extension initializes, retrieve saved states. + let initialized = false; + useWebviewListener("indexProgress", async (data) => { setUpdate(data); }); useEffect(() => { - // Triggers retrieval for possible non-default states set prior to IndexingProgressBar initialization - ideMessenger.post("index/indexingProgressBarInitialized", undefined); + if (!initialized) { + // Triggers retrieval for possible non-default states set prior to IndexingProgressBar initialization + ideMessenger.post("index/indexingProgressBarInitialized", undefined); + initialized = true; + } }, []); useEffect(() => { diff --git a/gui/src/pages/More/progress/IndexingProgressBar.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx similarity index 91% rename from gui/src/pages/More/progress/IndexingProgressBar.tsx rename to gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx index 6d0f7f104..5de74fb3f 100644 --- a/gui/src/pages/More/progress/IndexingProgressBar.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx @@ -1,5 +1,5 @@ import { IndexingProgressUpdate } from "core"; -import { getProgressPercentage } from "."; +import { getProgressPercentage } from "./IndexingProgress"; export interface IndexingProgressBarProps { update: IndexingProgressUpdate; diff --git a/gui/src/pages/More/progress/codebase/IndexingProgressErrorText.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx similarity index 94% rename from gui/src/pages/More/progress/codebase/IndexingProgressErrorText.tsx rename to gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx index c8ec68937..fff7ab9a8 100644 --- a/gui/src/pages/More/progress/codebase/IndexingProgressErrorText.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx @@ -1,8 +1,8 @@ import { IndexingProgressUpdate } from "core"; import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider"; import { useSelector } from "react-redux"; -import { RootState } from "../../../../redux/store"; -import { isJetBrains } from "../../../../util"; +import { RootState } from "../../../redux/store"; +import { isJetBrains } from "../../../util"; import { XCircleIcon } from "@heroicons/react/24/outline"; export interface IndexingProgressErrorTextProps { diff --git a/gui/src/pages/More/progress/IndexingProgressIndicator.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx similarity index 95% rename from gui/src/pages/More/progress/IndexingProgressIndicator.tsx rename to gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx index f337a1d0a..944fdc917 100644 --- a/gui/src/pages/More/progress/IndexingProgressIndicator.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx @@ -1,10 +1,10 @@ import { IndexingProgressUpdate } from "core"; +import { getProgressPercentage } from "./IndexingProgress"; import { ArrowPathIcon, PauseCircleIcon, CheckCircleIcon, } from "@heroicons/react/24/outline"; -import { getProgressPercentage } from "."; export interface IndexingProgressIndicatorProps { update: IndexingProgressUpdate; diff --git a/gui/src/pages/More/progress/IndexingProgressSubtext.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx similarity index 100% rename from gui/src/pages/More/progress/IndexingProgressSubtext.tsx rename to gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx diff --git a/gui/src/pages/More/progress/IndexingProgressTitleText.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx similarity index 65% rename from gui/src/pages/More/progress/IndexingProgressTitleText.tsx rename to gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx index 9cf014e10..61d4bbba6 100644 --- a/gui/src/pages/More/progress/IndexingProgressTitleText.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx @@ -1,11 +1,19 @@ import { IndexingProgressUpdate } from "core"; import { AnimatedEllipsis } from "../../../components"; -import { STATUS_TO_TEXT } from "."; export interface IndexingProgressTitleTextProps { update: IndexingProgressUpdate; } +const STATUS_TO_TEXT: Record = { + done: "Indexing complete", + loading: "Initializing", + indexing: "Indexing in-progress", + paused: "Indexing paused", + failed: "Indexing failed", + disabled: "Indexing disabled", +}; + function IndexingProgressTitleText({ update }: IndexingProgressTitleTextProps) { const showEllipsis = update.status === "loading"; diff --git a/gui/src/pages/More/IndexingProgress/index.ts b/gui/src/pages/More/IndexingProgress/index.ts new file mode 100644 index 000000000..7f51ae6ad --- /dev/null +++ b/gui/src/pages/More/IndexingProgress/index.ts @@ -0,0 +1 @@ +export { default } from "./IndexingProgress"; diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index 14d0eadee..4824c9535 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -14,7 +14,7 @@ import { useDispatch } from "react-redux"; import { setOnboardingCard } from "../../redux/slices/uiStateSlice"; import useHistory from "../../hooks/useHistory"; import MoreHelpRow from "./MoreHelpRow"; -import IndexingProgress from "./progress/codebase"; +import IndexingProgress from "./IndexingProgress"; function MorePage() { useNavigationListener(); diff --git a/gui/src/pages/More/progress/docs/index.tsx b/gui/src/pages/More/progress/docs/index.tsx deleted file mode 100644 index b2590adbe..000000000 --- a/gui/src/pages/More/progress/docs/index.tsx +++ /dev/null @@ -1,121 +0,0 @@ -import { IndexingProgressUpdate } from "core"; -import { useContext, useEffect, useState } from "react"; -import { useDispatch } from "react-redux"; -import { IdeMessengerContext } from "../../../../context/IdeMessenger"; -import { isJetBrains } from "../../../../util"; -import { useWebviewListener } from "../../../../hooks/useWebviewListener"; -import IndexingProgressBar from "../IndexingProgressBar"; -import IndexingProgressIndicator from "../IndexingProgressIndicator"; -import IndexingProgressSubtext from "../IndexingProgressSubtext"; -import { usePostHog } from "posthog-js/react"; -import ConfirmationDialog from "../../../../components/dialogs/ConfirmationDialog"; -import { - setShowDialog, - setDialogMessage, -} from "../../../../redux/slices/uiStateSlice"; -import IndexingProgressTitleText from "../IndexingProgressTitleText"; -import IndexingProgressErrorText from "../codebase/IndexingProgressErrorText"; - -function DocsIndexingProgressItem() { - const ideMessenger = useContext(IdeMessengerContext); - const posthog = usePostHog(); - const dispatch = useDispatch(); - const [paused, setPaused] = useState(undefined); - const [update, setUpdate] = useState({ - desc: "Loading indexing config", - progress: 0.0, - status: "loading", - }); - - useWebviewListener("indexProgress", async (data) => { - setUpdate(data); - }); - - useEffect(() => { - // Triggers retrieval for possible non-default states set prior to IndexingProgressBar initialization - ideMessenger.post("index/indexingProgressBarInitialized", undefined); - }, []); - - useEffect(() => { - if (paused === undefined) return; - ideMessenger.post("index/setPaused", paused); - }, [paused]); - - function onClickRetry() { - // For now, we don't show in JetBrains since the re-index command - // is not yet implemented - if (update.shouldClearIndexes && !isJetBrains()) { - dispatch(setShowDialog(true)); - dispatch( - setDialogMessage( - { - posthog.capture("rebuild_index_clicked"); - ideMessenger.post("index/forceReIndex", { - shouldClearIndexes: true, - }); - }} - />, - ), - ); - } else { - ideMessenger.post("index/forceReIndex", undefined); - } - } - - function onClick() { - switch (update.status) { - case "failed": - onClickRetry(); - break; - case "indexing": - case "loading": - case "paused": - if (update.progress < 1 && update.progress >= 0) { - setPaused((prev) => !prev); - } else { - ideMessenger.post("index/forceReIndex", undefined); - } - break; - case "disabled": - ideMessenger.post("openConfigJson", undefined); - break; - case "done": - ideMessenger.post("index/forceReIndex", undefined); - default: - break; - } - } - - return ( -
-
- - {update.status !== "loading" && ( - - )} -
- - - - - - {update.status === "failed" && ( -
- -
- )} -
- ); -} - -function AllDocsIndexingProgress() {} -export default AllDocsIndexingProgress; diff --git a/gui/src/pages/More/progress/index.ts b/gui/src/pages/More/progress/index.ts deleted file mode 100644 index 44c3d50e3..000000000 --- a/gui/src/pages/More/progress/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { IndexingProgressUpdate } from "core"; - -export function getProgressPercentage( - progress: IndexingProgressUpdate["progress"], -) { - return Math.min(100, Math.max(0, progress * 100)); -} - -export const STATUS_TO_TEXT: Record = - { - done: "Indexing complete", - loading: "Initializing", - indexing: "Indexing in-progress", - paused: "Indexing paused", - failed: "Indexing failed", - disabled: "Indexing disabled", - }; From bcd82c901117c69680e4ec64185d26d494575c70 Mon Sep 17 00:00:00 2001 From: Test Date: Fri, 15 Nov 2024 15:59:49 -0800 Subject: [PATCH 21/82] more styling updates --- .../StepContainer/AcceptRejectAllButtons.tsx | 12 ++++++++---- .../StepContainerPreToolbar/ApplyActions.tsx | 4 ++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx index 9e9afe23f..a1e7b28f6 100644 --- a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx +++ b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx @@ -27,15 +27,19 @@ export default function AcceptRejectAllButtons({ className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125" onClick={() => handleAcceptOrReject("rejectDiff")} > - - Reject all changes + + Reject + Reject all + Reject all changes
); diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx index 5a2cc6462..286277d4f 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx @@ -43,7 +43,7 @@ export default function ApplyActions(props: ApplyActionsProps) { onClick={onClickReject} tooltipContent={`Reject all (${getMetaKeyLabel()}⇧⌫)`} > - + Applied - + ); } From a9169c373875ffc1d01869509246bad7ab7aae20 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 15 Nov 2024 16:39:42 -0800 Subject: [PATCH 22/82] indexing progress start --- core/core.ts | 25 +++++++++++++------- core/indexing/docs/DocsService.ts | 38 +++++++++++++++++++------------ gui/src/hooks/useSetup.ts | 17 ++++++++++++-- 3 files changed, 56 insertions(+), 24 deletions(-) diff --git a/core/core.ts b/core/core.ts index dc140cf3d..dd7b2c3e6 100644 --- a/core/core.ts +++ b/core/core.ts @@ -42,7 +42,8 @@ export class Core { codebaseIndexerPromise: Promise; completionProvider: CompletionProvider; continueServerClientPromise: Promise; - indexingState: IndexingProgressUpdate; + codebaseIndexingState: IndexingProgressUpdate; + docsIndexingStates: Map = new Map(); controlPlaneClient: ControlPlaneClient; private docsService: DocsService; private globalContext = new GlobalContext(); @@ -83,12 +84,16 @@ export class Core { constructor( private readonly messenger: IMessenger, private readonly ide: IDE, - private readonly onWrite: (text: string) => Promise = async () => { }, + private readonly onWrite: (text: string) => Promise = async () => {}, ) { // Ensure .continue directory is created setupInitialDotContinueDirectory(); - this.indexingState = { status: "loading", desc: "loading", progress: 0 }; + this.codebaseIndexingState = { + status: "loading", + desc: "loading", + progress: 0, + }; const ideSettingsPromise = messenger.request("getIdeSettings", undefined); const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", { @@ -148,6 +153,7 @@ export class Core { // Index on initialization void this.ide.getWorkspaceDirs().then(async (dirs) => { // Respect pauseCodebaseIndexOnStart user settings + this.indexingPauseToken.paused = true; if (ideSettings.pauseCodebaseIndexOnStart) { await this.messenger.request("indexProgress", { progress: 1, @@ -174,7 +180,7 @@ export class Core { this.configHandler, ide, getLlm, - (e) => { }, + (e) => {}, (..._) => Promise.resolve([]), ); @@ -684,7 +690,7 @@ export class Core { await codebaseIndexer.clearIndexes(); } - const dirs = data?.dirs ?? await this.ide.getWorkspaceDirs(); + const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs()); await this.refreshCodebaseIndex(dirs); }); on("index/setPaused", (msg) => { @@ -694,8 +700,11 @@ export class Core { on("index/indexingProgressBarInitialized", async (msg) => { // Triggered when progress bar is initialized. // If a non-default state has been stored, update the indexing display to that state - if (this.indexingState.status !== "loading") { - void this.messenger.request("indexProgress", this.indexingState); + if (this.codebaseIndexingState.status !== "loading") { + void this.messenger.request( + "indexProgress", + this.codebaseIndexingState, + ); } }); @@ -740,7 +749,7 @@ export class Core { } void this.messenger.request("indexProgress", updateToSend); - this.indexingState = updateToSend; + this.codebaseIndexingState = updateToSend; if (update.status === "failed") { console.debug( diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 1bf358e8f..f75412917 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -7,7 +7,7 @@ import { ContinueConfig, EmbeddingsProvider, IDE, - IndexingProgressUpdate, + IndexingStatusUpdate, SiteIndexingConfig, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; @@ -178,7 +178,7 @@ export default class DocsService { async *indexAndAdd( siteIndexingConfig: SiteIndexingConfig, reIndex: boolean = false, - ): AsyncGenerator { + ): AsyncGenerator { const { startUrl } = siteIndexingConfig; const embeddingsProvider = await this.getEmbeddingsProvider(); @@ -406,17 +406,29 @@ export default class DocsService { private async init(configHandler: ConfigHandler) { this.config = await configHandler.loadConfig(); - await this.handleConfigUpdate({config: this.config}); + await this.handleConfigUpdate({ config: this.config }); // only update on init because should only update on reindexDocsOnNewEmbeddingsProvider - const embeddingsProvider = await this.getEmbeddingsProvider(); - this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); + const currentEmbeddingsProvider = this.globalContext.get( + "curEmbeddingsProviderId", + ); + if (!currentEmbeddingsProvider) { + const embeddingsProvider = await this.getEmbeddingsProvider(); + this.globalContext.update( + "curEmbeddingsProviderId", + embeddingsProvider.id, + ); + } configHandler.onConfigUpdate(this.handleConfigUpdate); } - private async handleConfigUpdate({config: newConfig}: {config: ContinueConfig | undefined}) { - if(newConfig){ + private async handleConfigUpdate({ + config: newConfig, + }: { + config: ContinueConfig | undefined; + }) { + if (newConfig) { this.config = newConfig; this.docsCrawler = new DocsCrawler(this.ide, this.config); @@ -430,10 +442,9 @@ export default class DocsService { await this.syncConfigAndSqlite(); } - const shouldReindex = - await this.shouldReindexDocsOnNewEmbeddingsProvider( - newConfig.embeddingsProvider.id, - ); + const shouldReindex = await this.shouldReindexDocsOnNewEmbeddingsProvider( + newConfig.embeddingsProvider.id, + ); if (shouldReindex) { await this.reindexDocsOnNewEmbeddingsProvider( @@ -441,7 +452,6 @@ export default class DocsService { ); } } - } private async syncConfigAndSqlite() { @@ -595,7 +605,7 @@ export default class DocsService { return ideInfo.ideType === "jetbrains"; } - async isJetBrainsAndPreIndexedDocsProvider(): Promise { + async isJetBrainsAndPreIndexedDocsProvider(): Promise { const isJetBrains = await this.isJetBrains(); const isPreIndexedDocsProvider = @@ -818,4 +828,4 @@ export default class DocsService { console.log("Completed reindexing of all docs"); } -} \ No newline at end of file +} diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 8ece44bec..58feba2a5 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -45,7 +45,20 @@ function useSetup(dispatch: Dispatch) { } }; - // ON LOAD + // Load config from the IDE + useEffect(() => { + loadConfig(); + const interval = setInterval(() => { + if (configLoaded) { + clearInterval(interval); + return; + } + loadConfig(); + }, 2_000); + + return () => clearInterval(interval); + }, [configLoaded]); + useEffect(() => { // Override persisted state dispatch(setInactive()); @@ -104,7 +117,7 @@ function useSetup(dispatch: Dispatch) { useWebviewListener("configUpdate", async () => { await loadConfig(); - if (!isJetBrains && !getLocalStorage("disableIndexing")) { + if (!isJetBrains) { debouncedIndexDocs(); } }); From 0af5dc4411d791d8afcb3693eb86e8482444338d Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 16 Nov 2024 14:13:46 -0800 Subject: [PATCH 23/82] ListenableGenerator.test.ts --- .../generation/ListenableGenerator.test.ts | 149 ++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 core/autocomplete/generation/ListenableGenerator.test.ts diff --git a/core/autocomplete/generation/ListenableGenerator.test.ts b/core/autocomplete/generation/ListenableGenerator.test.ts new file mode 100644 index 000000000..69797959e --- /dev/null +++ b/core/autocomplete/generation/ListenableGenerator.test.ts @@ -0,0 +1,149 @@ +import { jest } from "@jest/globals"; +import { ListenableGenerator } from "./ListenableGenerator"; + +describe("ListenableGenerator", () => { + // Helper function to create an async generator + async function* asyncGenerator(values: T[], delay = 0) { + for (const value of values) { + if (delay > 0) { + await new Promise((resolve) => setTimeout(resolve, delay)); + } + yield value; + } + } + + it("should yield values from the source generator via tee()", async () => { + const values = [1, 2, 3]; + const source = asyncGenerator(values); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const result: number[] = []; + for await (const value of lg.tee()) { + result.push(value); + } + + expect(result).toEqual(values); + expect(onError).not.toHaveBeenCalled(); + }); + + it("should allow listeners to receive values", async () => { + const values = [1, 2, 3]; + const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const listener = jest.fn(); + + // Add listener after some delay to simulate late subscription + setTimeout(() => { + lg.listen(listener); + }, 15); + + // Wait for generator to finish + await new Promise((resolve) => setTimeout(resolve, 50)); + + expect(listener).toHaveBeenCalledWith(1); + expect(listener).toHaveBeenCalledWith(2); + expect(listener).toHaveBeenCalledWith(3); + // Listener should receive null at the end + expect(listener).toHaveBeenCalledWith(null); + }); + + it("should buffer values for listeners added after some values have been yielded", async () => { + const values = [1, 2, 3]; + const source = asyncGenerator(values, 10); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const initialListener = jest.fn(); + + lg.listen(initialListener); + + // Wait for the first value to be yielded + await new Promise((resolve) => setTimeout(resolve, 15)); + + // Add a second listener + const newListener = jest.fn(); + lg.listen(newListener); + + // Wait for generator to finish + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Both listeners should have received all values + [initialListener, newListener].forEach((listener) => { + expect(listener).toHaveBeenCalledWith(1); + expect(listener).toHaveBeenCalledWith(2); + expect(listener).toHaveBeenCalledWith(3); + expect(listener).toHaveBeenCalledWith(null); + }); + }); + + it("should handle cancellation", async () => { + const values = [1, 2, 3, 4, 5]; + const source = asyncGenerator(values, 10); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const result: number[] = []; + const teeIterator = lg.tee(); + + const consume = async () => { + for await (const value of teeIterator) { + result.push(value); + if (value === 3) { + lg.cancel(); + } + } + }; + + await consume(); + + expect(result).toEqual([1, 2, 3]); + expect(lg["_isEnded"]).toBe(true); + }); + + it("should call onError when the source generator throws an error", async () => { + async function* errorGenerator() { + yield 1; + throw new Error("Test error"); + } + + const source = errorGenerator(); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const result: number[] = []; + for await (const value of lg.tee()) { + result.push(value); + } + + expect(result).toEqual([1]); + expect(onError).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledWith(new Error("Test error")); + }); + + it("should notify listeners when the generator ends", async () => { + const values = [1, 2, 3]; + const source = asyncGenerator(values); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const listener = jest.fn(); + lg.listen(listener); + + // Wait for the generator to finish + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(listener).toHaveBeenCalledWith(1); + expect(listener).toHaveBeenCalledWith(2); + expect(listener).toHaveBeenCalledWith(3); + expect(listener).toHaveBeenCalledWith(null); + }); +}); From 2d281cd4cf12c94939661fd26f047e22f6b997e7 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 16 Nov 2024 16:25:43 -0800 Subject: [PATCH 24/82] tests for GeneratorReuseManager.ts --- .../generation/GeneratorReuseManager.test.ts | 272 ++++++++++++++++++ .../generation/GeneratorReuseManager.ts | 45 +-- 2 files changed, 298 insertions(+), 19 deletions(-) create mode 100644 core/autocomplete/generation/GeneratorReuseManager.test.ts diff --git a/core/autocomplete/generation/GeneratorReuseManager.test.ts b/core/autocomplete/generation/GeneratorReuseManager.test.ts new file mode 100644 index 000000000..acf81b73e --- /dev/null +++ b/core/autocomplete/generation/GeneratorReuseManager.test.ts @@ -0,0 +1,272 @@ +import { jest } from "@jest/globals"; +import { GeneratorReuseManager } from "./GeneratorReuseManager"; + +// Mock implementation of ListenableGenerator +class MockListenableGenerator { + private generator: AsyncGenerator; + private listeners: Array<(chunk: T | undefined) => void> = []; + private canceled = false; + private chunks: T[] = []; + private teeIndex = 0; + + constructor( + generator: AsyncGenerator, + private onError: (err: any) => void, + ) { + this.generator = this._wrapGenerator(generator); + } + + private async *_wrapGenerator(gen: AsyncGenerator): AsyncGenerator { + try { + for await (const chunk of gen) { + if (this.canceled) break; + this.chunks.push(chunk); + this.listeners.forEach((listener) => listener(chunk)); + yield chunk; + } + } catch (err) { + this.onError(err); + } finally { + this.listeners.forEach((listener) => listener(undefined)); + } + } + + cancel() { + this.canceled = true; + } + + listen(callback: (chunk: T | undefined) => void) { + this.listeners.push(callback); + // Send already received chunks + this.chunks.forEach((chunk) => callback(chunk)); + } + + async *tee(): AsyncGenerator { + while (this.teeIndex < this.chunks.length) { + yield this.chunks[this.teeIndex++]; + } + const iterator = this.generator[Symbol.asyncIterator](); + while (true) { + const { value, done } = await iterator.next(); + if (done) break; + yield value; + this.teeIndex++; + } + } +} + +function createMockGenerator( + data: string[], + delay: number = 0, +): () => AsyncGenerator { + const mockGenerator = async function* () { + for (const chunk of data) { + yield chunk; + + if (delay > 0) { + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + }; + const newGenerator = jest + .fn<() => AsyncGenerator>() + .mockReturnValue(mockGenerator()); + + return newGenerator; +} + +describe("GeneratorReuseManager", () => { + let reuseManager: GeneratorReuseManager; + let onErrorMock: jest.Mock; + + beforeEach(() => { + onErrorMock = jest.fn(); + reuseManager = new GeneratorReuseManager( + onErrorMock, + // MockListenableGenerator as any, + ); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + test("creates new generator when there is no current generator", async () => { + const data = ["hello ", "world"]; + const newGenerator = createMockGenerator(data); + + const prefix = ""; + + const generator = reuseManager.getGenerator(prefix, newGenerator, true); + + const output: string[] = []; + for await (const chunk of generator) { + output.push(chunk); + } + + expect(output).toEqual(data); + expect(newGenerator).toHaveBeenCalledTimes(1); + }); + + test("reuses generator when prefix matches pending completion", async () => { + const newGenerator = createMockGenerator(["llo ", "world"]); + + // First call with initial prefix + const prefix1 = "he"; + const generator1 = reuseManager.getGenerator(prefix1, newGenerator, true); + + const output1: string[] = []; + for await (const chunk of generator1) { + output1.push(chunk); + } + + expect(output1).toEqual(["llo ", "world"]); + + // Second call with extended prefix that matches pending completion + const prefix2 = "hello "; + const generator2 = reuseManager.getGenerator(prefix2, newGenerator, true); + + const output2: string[] = []; + for await (const chunk of generator2) { + output2.push(chunk); + } + + expect(output2).toEqual(["world"]); + + // Ensure generator was reused (newGenerator should be called only once) + expect(newGenerator).toHaveBeenCalledTimes(1); + }); + + test("creates new generator when prefix does not match pending completion", async () => { + const data = ["goodbye ", "world"]; + const newGenerator = createMockGenerator(data); + + // Initial generator with different prefix + reuseManager.pendingGeneratorPrefix = "hello "; + reuseManager.pendingCompletion = "world"; + + const prefix = "good"; + const generator = reuseManager.getGenerator(prefix, newGenerator, true); + + const output: string[] = []; + for await (const chunk of generator) { + output.push(chunk); + } + + expect(output).toEqual(data); + // Ensure a new generator was created + expect(newGenerator).toHaveBeenCalledTimes(1); + }); + + test("handles multiline=false by stopping at newline", async () => { + const data = ["first line\n", "second line"]; + const newGenerator = createMockGenerator(data); + + const prefix = ""; + const generator = reuseManager.getGenerator(prefix, newGenerator, false); + + const output: string[] = []; + for await (const chunk of generator) { + output.push(chunk); + } + + expect(output).toEqual(["first line"]); + // Ensure it stops after the first newline + }); + + test("handles multiline=true by not stopping at newline", async () => { + const data = ["first line\n", "second line"]; + const newGenerator = createMockGenerator(data); + + const prefix = ""; + const generator = reuseManager.getGenerator(prefix, newGenerator, true); + + const output: string[] = []; + for await (const chunk of generator) { + output.push(chunk); + } + + expect(output).toEqual(data); + }); + + test("cancels previous generator when creating a new one", async () => { + const data1 = ["data from generator 1", "not generated"]; + const data2 = ["data from generator 2"]; + + const newGenerator1 = createMockGenerator(data1, 1000); // Delay so we have the chance to cancel it + const newGenerator2 = createMockGenerator(data2); + + const prefix1 = "prefix1"; + const prefix2 = "prefix2"; + + // First generator + const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true); + const output1: string[] = []; + for await (const chunk of generator1) { + output1.push(chunk); + // Simulate the generator being canceled before completing + reuseManager.currentGenerator?.cancel(); + } + + expect(output1.length).toEqual(1); + expect(output1[0]).toEqual(data1[0]); + + // Second generator + const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true); + const output2: string[] = []; + for await (const chunk of generator2) { + output2.push(chunk); + } + + expect(output2).toEqual(data2); + }); + + test("calls onError when generator throws an error", async () => { + const error = new Error("Generator error"); + const mockGenerator = async function* () { + throw error; + }; + const newGenerator = jest + .fn<() => AsyncGenerator>() + .mockReturnValue(mockGenerator()); + + const prefix = ""; + const generator = reuseManager.getGenerator(prefix, newGenerator, true); + + const output: string[] = []; + await expect(async () => { + for await (const chunk of generator) { + output.push(chunk); + } + }).not.toThrow(); // getGenerator handles errors internally + + expect(onErrorMock).toHaveBeenCalledWith(error); + expect(output).toEqual([]); + }); + + test("handles backspacing by creating new generator when prefix is shorter", async () => { + const data = ["hello world"]; + const newGenerator1 = createMockGenerator(data); + const newGenerator2 = createMockGenerator(data); + + // First prefix + const prefix1 = "hello world"; + const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true); + const output1: string[] = []; + for await (const chunk of generator1) { + output1.push(chunk); + } + + // Simulate backspace (prefix is shorter) + const prefix2 = "hello worl"; + const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true); + const output2: string[] = []; + for await (const chunk of generator2) { + output2.push(chunk); + } + + // Ensure a new generator was created + expect(newGenerator1).toHaveBeenCalledTimes(1); + expect(newGenerator2).toHaveBeenCalledTimes(1); + }); +}); diff --git a/core/autocomplete/generation/GeneratorReuseManager.ts b/core/autocomplete/generation/GeneratorReuseManager.ts index 7a67e686f..0b19183ce 100644 --- a/core/autocomplete/generation/GeneratorReuseManager.ts +++ b/core/autocomplete/generation/GeneratorReuseManager.ts @@ -21,47 +21,54 @@ export class GeneratorReuseManager { this.currentGenerator = listenableGen; } + private shouldReuseExistingGenerator(prefix: string): boolean { + return ( + !!this.currentGenerator && + !!this.pendingGeneratorPrefix && + (this.pendingGeneratorPrefix + this.pendingCompletion).startsWith( + prefix, + ) && + // for e.g. backspace + this.pendingGeneratorPrefix?.length <= prefix?.length + ); + } + async *getGenerator( prefix: string, newGenerator: () => AsyncGenerator, multiline: boolean, ): AsyncGenerator { - // Check if current can be reused - if ( - !( - this.currentGenerator && - this.pendingGeneratorPrefix && - (this.pendingGeneratorPrefix + this.pendingCompletion).startsWith( - prefix, - ) && - // for e.g. backspace - this.pendingGeneratorPrefix?.length <= prefix?.length - ) - ) { + // If we can't reuse, then create a new generator + if (!this.shouldReuseExistingGenerator(prefix)) { // Create a wrapper over the current generator to fix the prompt this._createListenableGenerator(newGenerator(), prefix); } - let alreadyTyped = prefix.slice(this.pendingGeneratorPrefix?.length) || ""; + // Already typed characters are those that are new in the prefix from the old generator + let typedSinceLastGenerator = + prefix.slice(this.pendingGeneratorPrefix?.length) || ""; for await (let chunk of this.currentGenerator?.tee() ?? []) { if (!chunk) { continue; } - while (chunk.length && alreadyTyped.length) { - if (chunk[0] === alreadyTyped[0]) { - alreadyTyped = alreadyTyped.slice(1); + + // Ignore already typed characters in the completion + while (chunk.length && typedSinceLastGenerator.length) { + if (chunk[0] === typedSinceLastGenerator[0]) { + typedSinceLastGenerator = typedSinceLastGenerator.slice(1); chunk = chunk.slice(1); } else { break; } } + // Break at newline unless we are in multiline mode const newLineIndex = chunk.indexOf("\n"); - if (multiline || newLineIndex === -1) { - yield chunk; - } else { + if (newLineIndex >= 0 && !multiline) { yield chunk.slice(0, newLineIndex); break; + } else if (chunk !== "") { + yield chunk; } } } From 49a9fcd1e609d72d8196129c2090c978fd021e72 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 16 Nov 2024 16:28:15 -0800 Subject: [PATCH 25/82] clean up test --- .../generation/GeneratorReuseManager.test.ts | 59 +------------------ 1 file changed, 1 insertion(+), 58 deletions(-) diff --git a/core/autocomplete/generation/GeneratorReuseManager.test.ts b/core/autocomplete/generation/GeneratorReuseManager.test.ts index acf81b73e..2454377d3 100644 --- a/core/autocomplete/generation/GeneratorReuseManager.test.ts +++ b/core/autocomplete/generation/GeneratorReuseManager.test.ts @@ -1,60 +1,6 @@ import { jest } from "@jest/globals"; import { GeneratorReuseManager } from "./GeneratorReuseManager"; -// Mock implementation of ListenableGenerator -class MockListenableGenerator { - private generator: AsyncGenerator; - private listeners: Array<(chunk: T | undefined) => void> = []; - private canceled = false; - private chunks: T[] = []; - private teeIndex = 0; - - constructor( - generator: AsyncGenerator, - private onError: (err: any) => void, - ) { - this.generator = this._wrapGenerator(generator); - } - - private async *_wrapGenerator(gen: AsyncGenerator): AsyncGenerator { - try { - for await (const chunk of gen) { - if (this.canceled) break; - this.chunks.push(chunk); - this.listeners.forEach((listener) => listener(chunk)); - yield chunk; - } - } catch (err) { - this.onError(err); - } finally { - this.listeners.forEach((listener) => listener(undefined)); - } - } - - cancel() { - this.canceled = true; - } - - listen(callback: (chunk: T | undefined) => void) { - this.listeners.push(callback); - // Send already received chunks - this.chunks.forEach((chunk) => callback(chunk)); - } - - async *tee(): AsyncGenerator { - while (this.teeIndex < this.chunks.length) { - yield this.chunks[this.teeIndex++]; - } - const iterator = this.generator[Symbol.asyncIterator](); - while (true) { - const { value, done } = await iterator.next(); - if (done) break; - yield value; - this.teeIndex++; - } - } -} - function createMockGenerator( data: string[], delay: number = 0, @@ -81,10 +27,7 @@ describe("GeneratorReuseManager", () => { beforeEach(() => { onErrorMock = jest.fn(); - reuseManager = new GeneratorReuseManager( - onErrorMock, - // MockListenableGenerator as any, - ); + reuseManager = new GeneratorReuseManager(onErrorMock); }); afterEach(() => { From e037246324a6f9c80b20519a6a9626f051a2f484 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 16 Nov 2024 17:52:56 -0800 Subject: [PATCH 26/82] don't autocomplete past double new line AND closed bracket --- .../filtering/BracketMatchingService.ts | 52 +++--- .../StreamTransformPipeline.ts | 2 + .../filtering/streamTransforms/lineStream.ts | 41 +++++ ...noDoubleNewlineAfterClosingBracket.test.ts | 166 ++++++++++++++++++ 4 files changed, 229 insertions(+), 32 deletions(-) create mode 100644 core/autocomplete/filtering/streamTransforms/noDoubleNewlineAfterClosingBracket.test.ts diff --git a/core/autocomplete/filtering/BracketMatchingService.ts b/core/autocomplete/filtering/BracketMatchingService.ts index d4415259e..da7d38e61 100644 --- a/core/autocomplete/filtering/BracketMatchingService.ts +++ b/core/autocomplete/filtering/BracketMatchingService.ts @@ -1,3 +1,13 @@ +export const BRACKETS: { [key: string]: string } = { + "(": ")", + "{": "}", + "[": "]", +}; +export const BRACKETS_REVERSE: { [key: string]: string } = { + ")": "(", + "}": "{", + "]": "[", +}; /** * We follow the policy of only completing bracket pairs that we started * But sometimes we started the pair in a previous autocomplete suggestion @@ -6,30 +16,18 @@ export class BracketMatchingService { private openingBracketsFromLastCompletion: string[] = []; private lastCompletionFile: string | undefined = undefined; - static BRACKETS: { [key: string]: string } = { "(": ")", "{": "}", "[": "]" }; - static BRACKETS_REVERSE: { [key: string]: string } = { - ")": "(", - "}": "{", - "]": "[", - }; - handleAcceptedCompletion(completion: string, filepath: string) { this.openingBracketsFromLastCompletion = []; const stack: string[] = []; for (let i = 0; i < completion.length; i++) { const char = completion[i]; - if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) { + if (Object.keys(BRACKETS).includes(char)) { // It's an opening bracket stack.push(char); - } else if ( - Object.values(BracketMatchingService.BRACKETS).includes(char) - ) { + } else if (Object.values(BRACKETS).includes(char)) { // It's a closing bracket - if ( - stack.length === 0 || - BracketMatchingService.BRACKETS[stack.pop()!] !== char - ) { + if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) { break; } } @@ -63,17 +61,12 @@ export class BracketMatchingService { (prefix.split("\n").pop() ?? "") + (suffix.split("\n")[0] ?? ""); for (let i = 0; i < currentLine.length; i++) { const char = currentLine[i]; - if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) { + if (Object.keys(BRACKETS).includes(char)) { // It's an opening bracket stack.push(char); - } else if ( - Object.values(BracketMatchingService.BRACKETS).includes(char) - ) { + } else if (Object.values(BRACKETS).includes(char)) { // It's a closing bracket - if ( - stack.length === 0 || - BracketMatchingService.BRACKETS[stack.pop()!] !== char - ) { + if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) { break; } } @@ -87,7 +80,7 @@ export class BracketMatchingService { if (suffix[i] === " ") { continue; } - const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]]; + const openBracket = BRACKETS_REVERSE[suffix[i]]; if (!openBracket) { break; } @@ -115,19 +108,14 @@ export class BracketMatchingService { const allLines = all.split("\n"); for (let i = 0; i < chunk.length; i++) { const char = chunk[i]; - if (Object.values(BracketMatchingService.BRACKETS).includes(char)) { + if (Object.values(BRACKETS).includes(char)) { // It's a closing bracket - if ( - stack.length === 0 || - BracketMatchingService.BRACKETS[stack.pop()!] !== char - ) { + if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) { // If the stack is empty or the top of the stack doesn't match the current closing bracket yield chunk.slice(0, i); return; // Stop the generator if the closing bracket doesn't have a matching opening bracket in the stream } - } else if ( - Object.keys(BracketMatchingService.BRACKETS).includes(char) - ) { + } else if (Object.keys(BRACKETS).includes(char)) { // It's an opening bracket stack.push(char); } diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 5576ee26b..6097ff797 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -6,6 +6,7 @@ import { stopAtStopTokens } from "./charStream"; import { avoidEmptyComments, avoidPathLine, + noDoubleNewlineAfterClosingBracket, showWhateverWeHaveAtXMs, skipPrefixes, stopAtLines, @@ -47,6 +48,7 @@ export class StreamTransformPipeline { ); lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment); lineGenerator = skipPrefixes(lineGenerator); + lineGenerator = noDoubleNewlineAfterClosingBracket(lineGenerator); for (const lineFilter of helper.lang.lineFilters ?? []) { lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index 8c7936e2d..160fc9d85 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -2,6 +2,7 @@ import { distance } from "fastest-levenshtein"; import { DiffLine } from "../../.."; import { LineStream } from "../../../diff/util"; +import { BRACKETS, BRACKETS_REVERSE } from "../BracketMatchingService"; export type LineFilter = (args: { lines: LineStream; @@ -545,3 +546,43 @@ export async function* showWhateverWeHaveAtXMs( } } } + +export async function* noDoubleNewlineAfterClosingBracket( + lines: LineStream, +): LineStream { + const bracketTypeCounts = new Map(); + + for await (const line of lines) { + if (line.trim() === "") { + // Double newline detected + // Check if any bracket counts are negative + let hasNegativeCount = false; + for (const count of bracketTypeCounts.values()) { + if (count < 0) { + hasNegativeCount = true; + break; + } + } + if (hasNegativeCount) { + // Stop the generator if we've closed brackets we didn't open + return; + } + } + + yield line; + + // Update bracket counts + for (const char of line) { + if (BRACKETS[char]) { + // It's an opening bracket + const count = bracketTypeCounts.get(char) || 0; + bracketTypeCounts.set(char, count + 1); + } else if (BRACKETS_REVERSE[char]) { + // It's a closing bracket + const openingBracket = BRACKETS_REVERSE[char]; + const count = bracketTypeCounts.get(openingBracket) || 0; + bracketTypeCounts.set(openingBracket, count - 1); + } + } + } +} diff --git a/core/autocomplete/filtering/streamTransforms/noDoubleNewlineAfterClosingBracket.test.ts b/core/autocomplete/filtering/streamTransforms/noDoubleNewlineAfterClosingBracket.test.ts new file mode 100644 index 000000000..a25b5d4bf --- /dev/null +++ b/core/autocomplete/filtering/streamTransforms/noDoubleNewlineAfterClosingBracket.test.ts @@ -0,0 +1,166 @@ +import { noDoubleNewlineAfterClosingBracket } from "./lineStream"; + +describe("noDoubleNewlineAfterClosingBracket", () => { + // Helper function to convert an array to an async generator + async function* arrayToAsyncGenerator(array: T[]): AsyncGenerator { + for (const item of array) { + yield item; + } + } + + // Helper function to collect lines from the async generator + async function collectLines(lines: AsyncIterable): Promise { + const result: string[] = []; + for await (const line of lines) { + result.push(line); + } + return result; + } + + test("should yield all lines when no double newline and no unmatched brackets", async () => { + const inputLines = [ + "function test() {", + ' console.log("Hello World");', + "}", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should yield all lines when double newline but brackets are matched", async () => { + const inputLines = [ + "function test() {", + ' console.log("Hello World");', + "}", + "", + "", + "// End of function", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should stop yielding after double newline when unmatched closing bracket is found before double newline", async () => { + const inputLines = [ + // "function test() {", + ' console.log("Hello World");', + // Unmatched closing bracket + "}", + "", + "", + "// This should not be yielded", + 'console.log("End");', + ]; + const expectedOutputLines = [' console.log("Hello World");', "}"]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(expectedOutputLines); + }); + + test("should yield all lines when unmatched brackets but no double newline", async () => { + const inputLines = [ + "function test() {", + ' console.log("Hello World");', + "}", + // Unmatched closing bracket + ")", + "// Continue code", + 'console.log("End");', + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should continue yielding if unmatched closing bracket occurs after double newline", async () => { + const inputLines = [ + "function test() {", + ' console.log("Hello World");', + "}", + "", + "", + // Unmatched closing bracket after double newline + ")", + 'console.log("End");', + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should yield all lines when brackets are matched even with double newline", async () => { + const inputLines = [ + "const arr = [", + " 1, 2, 3,", + "];", + "", + "", + "console.log(arr);", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should stop yielding when unmatched closing bracket occurs before double newline", async () => { + const inputLines = [ + "if (condition) {", + " doSomething();", + "}", + // Unmatched closing bracket + "}", + "", + "", + "doSomethingElse();", + ]; + const expectedOutputLines = [ + "if (condition) {", + " doSomething();", + "}", + "}", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(expectedOutputLines); + }); + + test("should yield all lines when no unmatched closing brackets and double newline", async () => { + const inputLines = [ + "while (true) {", + " // Infinite loop", + "}", + "", + "", + "// Loop exited", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); +}); From 9390157830c9a650bc8fefa5587abdd358d4e42b Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 16 Nov 2024 21:51:19 -0800 Subject: [PATCH 27/82] remove cmd+shift+I (old Edit) --- extensions/vscode/package.json | 8 -------- 1 file changed, 8 deletions(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 186d18219..697bf61c1 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -368,11 +368,6 @@ "mac": "alt+cmd+n", "key": "alt+ctrl+n" }, - { - "command": "continue.quickEdit", - "mac": "cmd+shift+i", - "key": "ctrl+shift+i" - }, { "command": "continue.edit", "mac": "cmd+i", @@ -415,9 +410,6 @@ ], "menus": { "commandPalette": [ - { - "command": "continue.quickEdit" - }, { "command": "continue.focusContinueInput" }, From 5b85cad7a9e292ca4060d8188ec60f7d4060de40 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 16 Nov 2024 22:02:48 -0800 Subject: [PATCH 28/82] unable to click status bar button if not autocomplete model configured --- extensions/vscode/src/commands.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 42c10c3c9..f9e436f40 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -387,7 +387,10 @@ const commandsMap: ( if (historyLength === 0) { hideGUI(); } else { - void sidebar.webviewProtocol?.request("focusContinueInput", undefined); + void sidebar.webviewProtocol?.request( + "focusContinueInput", + undefined, + ); } } else { focusGUI(); @@ -596,7 +599,9 @@ const commandsMap: ( prompt: "Enter the Session ID", }); } - void sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); + void sidebar.webviewProtocol?.request("focusContinueSessionId", { + sessionId, + }); }, "continue.applyCodeFromChat": () => { void sidebar.webviewProtocol.request("applyCodeFromChat", undefined); @@ -734,7 +739,7 @@ const commandsMap: ( !selected || !autocompleteModels.some((model) => model.title === selected) ) { - selected = autocompleteModels[0].title; + selected = autocompleteModels[0]?.title; } // Toggle between Disabled, Paused, and Enabled From ecb97f23f636b761d9565100318d07eddd3429b3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sat, 16 Nov 2024 22:24:10 -0800 Subject: [PATCH 29/82] docs service p23232 --- core/context/providers/DocsContextProvider.ts | 36 +- core/core.ts | 34 +- core/index.d.ts | 10 +- core/indexing/docs/DocsService.test.ts | 8 +- core/indexing/docs/DocsService.ts | 539 ++++++++++-------- core/protocol/passThrough.ts | 7 +- 6 files changed, 331 insertions(+), 303 deletions(-) diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index a290589e4..f3a1e5d77 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -88,38 +88,10 @@ class DocsContextProvider extends BaseContextProvider { return []; } - const isJetBrainsAndPreIndexedDocsProvider = - await docsService.isJetBrainsAndPreIndexedDocsProvider(); - - if (isJetBrainsAndPreIndexedDocsProvider) { - await extras.ide.showToast( - "error", - `${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` + - "the embeddings provider, but it cannot be used with JetBrains. " + - "Please select a different embeddings provider to use the '@docs' " + - "context provider.", - ); - - return []; - } - - const preIndexedDoc = preIndexedDocs[query]; - - if (!!preIndexedDoc) { - void Telemetry.capture("docs_pre_indexed_doc_used", { - doc: preIndexedDoc["title"], - }); - } - - const embeddingsProvider = await docsService.getEmbeddingsProvider( - !!preIndexedDoc, - ); - - const [vector] = await embeddingsProvider.embed([extras.fullInput]); - - let chunks = await docsService.retrieveChunks( + await docsService.isInitialized; + let chunks = await docsService.retrieveChunksFromQuery( + extras.fullInput, query, - vector, this.options?.nRetrieve ?? DocsContextProvider.nRetrieve, ); @@ -175,7 +147,7 @@ class DocsContextProvider extends BaseContextProvider { return []; } - const docs = (await docsService.list()) ?? []; + const docs = (await docsService.listMetadata()) ?? []; const canUsePreindexedDocs = await docsService.canUsePreindexedDocs(); const submenuItemsMap = new Map(); diff --git a/core/core.ts b/core/core.ts index dd7b2c3e6..c1075dfd6 100644 --- a/core/core.ts +++ b/core/core.ts @@ -278,24 +278,22 @@ export class Core { // Context providers on("context/addDocs", async (msg) => { - let hasFailed = false; - - for await (const result of this.docsService.indexAndAdd(msg.data)) { - if (result.status === "failed") { - hasFailed = true; - break; - } - } - - if (hasFailed) { - void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`); - } else { - void this.ide.showToast( - "info", - `Successfully indexed ${msg.data.startUrl}`, - ); - this.messenger.send("refreshSubmenuItems", undefined); - } + // let hasFailed = false; + // for await (const result of this.docsService.indexAndAdd(msg.data)) { + // if (result.status === "failed") { + // hasFailed = true; + // break; + // } + // } + // if (hasFailed) { + // void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`); + // } else { + // void this.ide.showToast( + // "info", + // `Successfully indexed ${msg.data.startUrl}`, + // ); + // this.messenger.send("refreshSubmenuItems", undefined); + // } }); on("context/removeDocs", async (msg) => { diff --git a/core/index.d.ts b/core/index.d.ts index 6b275d7e2..b6b4c7f0c 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -51,10 +51,16 @@ export interface IndexingStatusUpdate { id: string; // Unique identifier, e.g. docs start url progress: number; description: string; - status: "initializing" | "indexing" | "complete" | "paused" | "failed" | "disabled"; + status: + | "initializing" + | "indexing" + | "complete" + | "paused" + | "failed" + | "disabled"; embeddingsModel: string; isReindexing: boolean; - debugInfo: string; + debugInfo?: string; } export type PromptTemplateFunction = ( diff --git a/core/indexing/docs/DocsService.test.ts b/core/indexing/docs/DocsService.test.ts index 9bac503c9..11fed29e5 100644 --- a/core/indexing/docs/DocsService.test.ts +++ b/core/indexing/docs/DocsService.test.ts @@ -72,7 +72,7 @@ describe.skip("DocsService Integration Tests", () => { let latestConfig = await getReloadedConfig(); // Sqlite check - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true); // config.json check expect(latestConfig.docs).toContainEqual(mockSiteConfig); @@ -91,7 +91,7 @@ describe.skip("DocsService Integration Tests", () => { await docsService.delete(mockSiteConfig.startUrl); // Sqlite check - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false); // config.json check latestConfig = await getReloadedConfig(); @@ -143,7 +143,7 @@ describe.skip("DocsService Integration Tests", () => { await getReloadedConfig(); - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true); editConfigJson((config) => { const { docs, ...restConfig } = config; @@ -164,6 +164,6 @@ describe.skip("DocsService Integration Tests", () => { await new Promise((resolve) => setTimeout(resolve, 100)); } - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false); }); }); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index f75412917..79dea28e6 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -62,13 +62,25 @@ export type AddParams = { favicon?: string; }; +/* + General process: + - On config update: + - Reindex ALL docs if embeddings provider has changed + - Otherwise, reindex docs with CHANGED URL/DEPTH + - And update docs with CHANGED TITLE/FAVICON + - Also, messages to core can trigger: + - delete + - reindex all + - add/index one + - Currently a full reindex deletes all docs rather than storing PER embeddings provider + - The last successful embeddings provider is stored in global context and updated AFTER an indexing process is successful +*/ export default class DocsService { static lanceTableName = "docs"; static sqlitebTableName = "docs"; static preIndexedDocsEmbeddingsProvider = new TransformersJsEmbeddingsProvider(); - private static instance?: DocsService; public isInitialized: Promise; public isSyncing: boolean = false; @@ -89,10 +101,8 @@ export default class DocsService { this.isInitialized = this.init(configHandler); } - static getSingleton() { - return DocsService.instance; - } - + // Singleton pattern: only one service globally + private static instance?: DocsService; static createSingleton( configHandler: ConfigHandler, ide: IDE, @@ -103,17 +113,102 @@ export default class DocsService { return docsService; } - async delete(startUrl: string) { - await this.deleteFromLance(startUrl); - await this.deleteFromSqlite(startUrl); - this.deleteFromConfig(startUrl); + static getSingleton() { + return DocsService.instance; + } - if (this.messenger) { - this.messenger.send("refreshSubmenuItems", undefined); + // Initialization - load config and attach config listener + private async init(configHandler: ConfigHandler) { + this.config = await configHandler.loadConfig(); + await this.handleConfigUpdate({ config: this.config }); + + configHandler.onConfigUpdate(this.handleConfigUpdate); + } + + // Config + + /* + * Currently, we generate and host embeddings for pre-indexed docs using transformers. + * However, we don't ship transformers with the JetBrains extension. + * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. + */ + async canUsePreindexedDocs() { + const ideInfo = await this.ide.getIdeInfo(); + if (ideInfo.ideType === "jetbrains") { + return false; + } + return true; + } + + async isUsingUnsupportedPreIndexedEmbeddingsProvider() { + const isPreIndexedDocsProvider = + this.config.embeddingsProvider.id === + DocsService.preIndexedDocsEmbeddingsProvider.id; + const canUsePreindexedDocs = await this.canUsePreindexedDocs(); + return isPreIndexedDocsProvider && !canUsePreindexedDocs; + } + + async getEmbeddingsProvider( + isPreIndexedDoc: boolean = false, + ): Promise { + const canUsePreindexedDocs = await this.canUsePreindexedDocs(); + + if (canUsePreindexedDocs && isPreIndexedDoc) { + return DocsService.preIndexedDocsEmbeddingsProvider; + } + + return this.config.embeddingsProvider; + } + + // Expose this so that docs provider can check it + + private async handleConfigUpdate({ + config: newConfig, + }: { + config: ContinueConfig | undefined; + }) { + if (newConfig) { + const oldConfig = this.config; + this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in + + this.docsCrawler = new DocsCrawler(this.ide, newConfig); + + // Skip docs indexing if not supported + const unsupported = + await this.isUsingUnsupportedPreIndexedEmbeddingsProvider(); + if (unsupported) { + return; + } + + const newConfigDocs = newConfig.docs || []; + const oldConfigDocs = oldConfig.docs || []; + + const newPreindexed = newConfigDocs.filter( + (doc) => !!preIndexedDocs[doc.startUrl], + ); + + // On embeddings provider change, reindex all docs + // change = doesn't match last successful embeddings provider + const curEmbeddingsProviderId = this.globalContext.get( + "curEmbeddingsProviderId", + ); + if ( + curEmbeddingsProviderId && + curEmbeddingsProviderId !== curEmbeddingsProviderId + ) { + // If not set, we're initializing + const currentDocs = await this.listMetadata(); + if (currentDocs.length > 0) { + await this.reindexDocsOnNewEmbeddingsProvider(); + return; + } + } + + await this.syncConfigAndSqlite(); } } - async has(startUrl: string): Promise> { + async hasMetadata(startUrl: string): Promise> { const db = await this.getOrCreateSqliteDb(); const title = await db.get( `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, @@ -123,6 +218,16 @@ export default class DocsService { return !!title; } + // private async hasIndexedDoc(startUrl: string) { + // const db = await this.getOrCreateSqliteDb(); + // const docs = await db.all( + // `SELECT startUrl FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, + // startUrl, + // ); + + // return docs.length > 0; + // } + async showAddDocsContextProviderToast() { const actionMsg = "Add 'docs' context provider"; const res = await this.ide.showToast( @@ -156,17 +261,17 @@ export default class DocsService { } } - const docs = await this.list(); + const docs = await this.listMetadata(); for (const doc of docs) { const generator = this.indexAndAdd(doc, reIndex); while (!(await generator.next()).done) {} } - await this.ide.showToast("info", "Docs indexing completed"); + void this.ide.showToast("info", "Docs indexing completed"); } - async list() { + async listMetadata() { const db = await this.getOrCreateSqliteDb(); const docs = await db.all( `SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName}`, @@ -180,18 +285,36 @@ export default class DocsService { reIndex: boolean = false, ): AsyncGenerator { const { startUrl } = siteIndexingConfig; - const embeddingsProvider = await this.getEmbeddingsProvider(); if (this.docsIndexingQueue.has(startUrl)) { - console.log("Already in queue"); + console.debug("Already in queue"); return; } + const embeddingsProvider = await this.getEmbeddingsProvider(); - if (!reIndex && (await this.has(startUrl))) { + const indexExists = await this.hasMetadata(startUrl); + + const fixedStatus: Pick< + IndexingStatusUpdate, + "type" | "id" | "embeddingsModel" | "isReindexing" + > = { + type: "docs", + id: siteIndexingConfig.startUrl, + embeddingsModel: embeddingsProvider.id, + isReindexing: reIndex && indexExists, + }; + + const completeStatus: IndexingStatusUpdate = { + ...fixedStatus, + progress: 1, + description: "Complete", + status: "complete", + }; + + if (indexExists && !reIndex) { yield { - progress: 1, - desc: "Already indexed", - status: "done", + ...completeStatus, + debugInfo: "Already indexed", }; return; } @@ -200,9 +323,10 @@ export default class DocsService { this.docsIndexingQueue.add(startUrl); yield { - progress: 0, - desc: "Finding subpages", + ...fixedStatus, status: "indexing", + description: "Finding subpages", + progress: 0, }; const articles: Article[] = []; @@ -225,9 +349,10 @@ export default class DocsService { const progress = Math.min(processedPages / maxKnownPages, 1); yield { - progress, // Yield the heuristic progress - desc: `Finding subpages (${page.path})`, + ...fixedStatus, + description: `Finding subpages (${page.path})`, status: "indexing", + progress, // Yield the heuristic progress }; // Increase maxKnownPages to delay progress reaching 100% too soon @@ -246,14 +371,15 @@ export default class DocsService { const embeddings: number[][] = []; // Create embeddings of retrieved articles - console.log(`Creating embeddings for ${articles.length} articles`); + console.debug(`Creating embeddings for ${articles.length} articles`); for (let i = 0; i < articles.length; i++) { const article = articles[i]; yield { - progress: i / articles.length, - desc: `Creating Embeddings: ${article.subpath}`, + ...fixedStatus, status: "indexing", + description: `Creating Embeddings: ${article.subpath}`, + progress: i / articles.length, }; try { @@ -284,9 +410,10 @@ export default class DocsService { ); yield { - progress: 1, - desc: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, + ...fixedStatus, + description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, status: "failed", + progress: 1, }; this.docsIndexingQueue.delete(startUrl); @@ -298,13 +425,14 @@ export default class DocsService { console.log(`Adding ${embeddings.length} embeddings to db`); yield { - progress: 0.5, - desc: `Adding ${embeddings.length} embeddings to db`, + ...fixedStatus, + description: `Adding ${embeddings.length} embeddings to db`, status: "indexing", + progress: 0.5, }; // Delete indexed docs if re-indexing - if (reIndex && (await this.has(startUrl.toString()))) { + if (reIndex && (await this.hasMetadata(startUrl.toString()))) { console.log("Deleting old embeddings"); await this.delete(startUrl); } @@ -321,9 +449,10 @@ export default class DocsService { this.docsIndexingQueue.delete(startUrl); yield { + ...fixedStatus, + description: "Complete", + status: "complete", progress: 1, - desc: "Done", - status: "done", }; console.log(`Successfully indexed: ${siteIndexingConfig.startUrl}`); @@ -333,15 +462,50 @@ export default class DocsService { } } + // Retrieve docs embeds based on user input + async retrieveChunksFromQuery( + query: string, + startUrl: string, + nRetrieve: number, + ) { + if (await this.isUsingUnsupportedPreIndexedEmbeddingsProvider()) { + await this.ide.showToast( + "error", + `${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` + + "the embeddings provider, but it cannot be used with JetBrains. " + // TODO "with this IDE" + "Please select a different embeddings provider to use the '@docs' " + + "context provider.", + ); + + return []; + } + + const preIndexedDoc = preIndexedDocs[query]; + + if (!!preIndexedDoc) { + void Telemetry.capture("docs_pre_indexed_doc_used", { + doc: preIndexedDoc["title"], + }); + } + + const embeddingsProvider = + await this.getEmbeddingsProvider(!!preIndexedDoc); + + const [vector] = await embeddingsProvider.embed([query]); + + return await this.retrieveChunks(query, vector, nRetrieve); + } + async retrieveChunks( startUrl: string, vector: number[], nRetrieve: number, isRetry: boolean = false, ): Promise { + const embeddingsProvider = await this.getEmbeddingsProvider(); const table = await this.getOrCreateLanceTable({ initializationVector: vector, - isPreIndexedDoc: !!preIndexedDocs[startUrl], + embeddingsProvider, }); let docs: LanceDbDocsRow[] = []; @@ -355,7 +519,7 @@ export default class DocsService { console.error("Error retrieving chunks from LanceDB", e); } - const hasIndexedDoc = await this.hasIndexedDoc(startUrl); + const hasIndexedDoc = await this.hasMetadata(startUrl); if (!hasIndexedDoc && docs.length === 0) { const preIndexedDoc = preIndexedDocs[startUrl]; @@ -381,121 +545,7 @@ export default class DocsService { })); } - async getEmbeddingsProvider(isPreIndexedDoc: boolean = false) { - const canUsePreindexedDocs = await this.canUsePreindexedDocs(); - - if (isPreIndexedDoc && canUsePreindexedDocs) { - return DocsService.preIndexedDocsEmbeddingsProvider; - } - - return this.config.embeddingsProvider; - } - - async getFavicon(startUrl: string) { - const db = await this.getOrCreateSqliteDb(); - const result = await db.get( - `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, - startUrl, - ); - - if (!result) { - return; - } - return result.favicon; - } - - private async init(configHandler: ConfigHandler) { - this.config = await configHandler.loadConfig(); - await this.handleConfigUpdate({ config: this.config }); - - // only update on init because should only update on reindexDocsOnNewEmbeddingsProvider - const currentEmbeddingsProvider = this.globalContext.get( - "curEmbeddingsProviderId", - ); - if (!currentEmbeddingsProvider) { - const embeddingsProvider = await this.getEmbeddingsProvider(); - this.globalContext.update( - "curEmbeddingsProviderId", - embeddingsProvider.id, - ); - } - - configHandler.onConfigUpdate(this.handleConfigUpdate); - } - - private async handleConfigUpdate({ - config: newConfig, - }: { - config: ContinueConfig | undefined; - }) { - if (newConfig) { - this.config = newConfig; - this.docsCrawler = new DocsCrawler(this.ide, this.config); - - const oldConfig = this.config; - - // Need to update class property for config at the beginning of this callback - // to ensure downstream methods have access to the latest config. - this.config = newConfig; - - if (oldConfig.docs !== newConfig.docs) { - await this.syncConfigAndSqlite(); - } - - const shouldReindex = await this.shouldReindexDocsOnNewEmbeddingsProvider( - newConfig.embeddingsProvider.id, - ); - - if (shouldReindex) { - await this.reindexDocsOnNewEmbeddingsProvider( - newConfig.embeddingsProvider, - ); - } - } - } - - private async syncConfigAndSqlite() { - this.isSyncing = true; - - const sqliteDocs = await this.list(); - const sqliteDocStartUrls = sqliteDocs.map((doc) => doc.startUrl) || []; - - const configDocs = this.config.docs || []; - const configDocStartUrls = - this.config.docs?.map((doc) => doc.startUrl) || []; - - const newDocs = configDocs.filter( - (doc) => !sqliteDocStartUrls.includes(doc.startUrl), - ); - const deletedDocs = sqliteDocs.filter( - (doc) => - !configDocStartUrls.includes(doc.startUrl) && - !preIndexedDocs[doc.startUrl], - ); - - for (const doc of newDocs) { - console.log(`Indexing new doc: ${doc.startUrl}`); - void Telemetry.capture("add_docs_config", { url: doc.startUrl }); - - const generator = this.indexAndAdd(doc); - while (!(await generator.next()).done) {} - } - - for (const doc of deletedDocs) { - // console.debug(`Deleting doc: ${doc.startUrl}`); - await this.delete(doc.startUrl); - } - - this.isSyncing = false; - } - - private hasDocsContextProvider() { - return !!this.config.contextProviders?.some( - (provider) => - provider.description.title === DocsContextProvider.description.title, - ); - } - + // SQLITE DB private async getOrCreateSqliteDb() { if (!this.sqliteDb) { const db = await open({ @@ -520,6 +570,65 @@ export default class DocsService { return this.sqliteDb; } + async getFavicon(startUrl: string) { + const db = await this.getOrCreateSqliteDb(); + const result = await db.get( + `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, + startUrl, + ); + + if (!result) { + return; + } + return result.favicon; + } + + private async syncConfigAndSqlite() { + try { + this.isSyncing = true; + + const sqliteDocs = await this.listMetadata(); + const sqliteDocStartUrls = sqliteDocs.map((doc) => doc.startUrl) || []; + + const configDocs = this.config.docs || []; + const configDocStartUrls = + this.config.docs?.map((doc) => doc.startUrl) || []; + + const newDocs = configDocs.filter( + (doc) => !sqliteDocStartUrls.includes(doc.startUrl), + ); + const deletedDocs = sqliteDocs.filter( + (doc) => + !configDocStartUrls.includes(doc.startUrl) && + !preIndexedDocs[doc.startUrl], + ); + + for (const doc of newDocs) { + console.log(`Indexing new doc: ${doc.startUrl}`); + void Telemetry.capture("add_docs_config", { url: doc.startUrl }); + + const generator = this.indexAndAdd(doc); + while (!(await generator.next()).done) {} + } + + for (const doc of deletedDocs) { + await this.delete(doc.startUrl); + } + } catch (e) { + console.error("Error syncing config and sqlite", e); + } finally { + this.isSyncing = false; + } + } + + private hasDocsContextProvider() { + return !!this.config.contextProviders?.some( + (provider) => + provider.description.title === DocsContextProvider.description.title, + ); + } + + // Lance DB Initialization private async createLanceDocsTable( connection: Connection, initializationVector: number[], @@ -554,11 +663,8 @@ export default class DocsService { } private async getLanceTableNameFromEmbeddingsProvider( - isPreIndexedDoc: boolean, + embeddingsProvider: EmbeddingsProvider, ) { - const embeddingsProvider = - await this.getEmbeddingsProvider(isPreIndexedDoc); - const tableName = this.sanitizeLanceTableName( `${DocsService.lanceTableName}${embeddingsProvider.id}`, ); @@ -568,15 +674,15 @@ export default class DocsService { private async getOrCreateLanceTable({ initializationVector, - isPreIndexedDoc, + embeddingsProvider, }: { initializationVector: number[]; - isPreIndexedDoc?: boolean; + embeddingsProvider: EmbeddingsProvider; }) { const conn = await lancedb.connect(getLanceDbPath()); const tableNames = await conn.tableNames(); const tableNameFromEmbeddingsProvider = - await this.getLanceTableNameFromEmbeddingsProvider(!!isPreIndexedDoc); + await this.getLanceTableNameFromEmbeddingsProvider(embeddingsProvider); if (!tableNames.includes(tableNameFromEmbeddingsProvider)) { if (initializationVector) { @@ -600,40 +706,7 @@ export default class DocsService { return table; } - private async isJetBrains() { - const ideInfo = await this.ide.getIdeInfo(); - return ideInfo.ideType === "jetbrains"; - } - - async isJetBrainsAndPreIndexedDocsProvider(): Promise { - const isJetBrains = await this.isJetBrains(); - - const isPreIndexedDocsProvider = - this.config.embeddingsProvider.id === - DocsService.preIndexedDocsEmbeddingsProvider.id; - - return isJetBrains && isPreIndexedDocsProvider; - } - - /* - * Currently, we generate and host embeddings for pre-indexed docs using transformers. - * However, we don't ship transformers with the JetBrains extension. - * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. - */ - async canUsePreindexedDocs() { - const isJetBrains = await this.isJetBrains(); - return !isJetBrains; - } - - private async hasIndexedDoc(startUrl: string) { - const db = await this.getOrCreateSqliteDb(); - const docs = await db.all( - `SELECT startUrl FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, - startUrl, - ); - - return docs.length > 0; - } + // Add methods for Individual docs private async addToLance({ chunks, @@ -642,8 +715,11 @@ export default class DocsService { }: AddParams) { const sampleVector = embeddings[0]; const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl]; + const embeddingsProvider = + await this.getEmbeddingsProvider(isPreIndexedDoc); + const table = await this.getOrCreateLanceTable({ - isPreIndexedDoc, + embeddingsProvider, initializationVector: sampleVector, }); @@ -660,7 +736,7 @@ export default class DocsService { await table.add(rows); } - private async addToSqlite({ + private async addMetadataToSqlite({ siteIndexingConfig: { title, startUrl }, favicon, }: AddParams) { @@ -690,7 +766,7 @@ export default class DocsService { private async add(params: AddParams) { await this.addToLance(params); - await this.addToSqlite(params); + await this.addMetadataToSqlite(params); const isPreIndexedDoc = !!preIndexedDocs[params.siteIndexingConfig.startUrl]; @@ -700,7 +776,8 @@ export default class DocsService { } } - private async deleteFromLance(startUrl: string) { + // Delete methods for individual docs + private async deleteEmbeddingsFromLance(startUrl: string) { for (const tableName of this.lanceTableNamesSet) { const conn = await lancedb.connect(getLanceDbPath()); const table = await conn.openTable(tableName); @@ -708,7 +785,7 @@ export default class DocsService { } } - private async deleteFromSqlite(startUrl: string) { + private async deleteMetadataFromSqlite(startUrl: string) { const db = await this.getOrCreateSqliteDb(); await db.run( `DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, @@ -716,13 +793,26 @@ export default class DocsService { ); } - deleteFromConfig(startUrl: string) { + private deleteFromConfig(startUrl: string) { editConfigJson((config) => ({ ...config, docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [], })); } + async delete(startUrl: string) { + await this.deleteEmbeddingsFromLance(startUrl); + await this.deleteMetadataFromSqlite(startUrl); + this.deleteFromConfig(startUrl); + + if (this.messenger) { + this.messenger.send("refreshSubmenuItems", undefined); + } + } + + // When user requests a pre-indexed doc for the first time + // And pre-indexed embeddings are supported + // Fetch pre-indexed embeddings from S3, add to Lance, and then search those private async fetchAndAddPreIndexedDocEmbeddings(title: string) { const embeddingsProvider = await this.getEmbeddingsProvider(true); @@ -751,59 +841,17 @@ export default class DocsService { }); } - private async shouldReindexDocsOnNewEmbeddingsProvider( - curEmbeddingsProviderId: EmbeddingsProvider["id"], - ): Promise { - const isJetBrainsAndPreIndexedDocsProvider = - await this.isJetBrainsAndPreIndexedDocsProvider(); - - if (isJetBrainsAndPreIndexedDocsProvider) { - // A bit noisy for teams users whom have no choice if their admin is the one who didn't setup an embeddingsProvider - // this.ide.showToast( - // "error", - // "The 'transformers.js' embeddings provider currently cannot be used to index " + - // "documentation in JetBrains. To enable documentation indexing, you can use " + - // "any of the other providers described in the docs: " + - // "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers", - // ); - - this.globalContext.update( - "curEmbeddingsProviderId", - curEmbeddingsProviderId, - ); - - return false; - } - - const lastEmbeddingsProviderId = this.globalContext.get( - "curEmbeddingsProviderId", - ); - - if (!lastEmbeddingsProviderId) { - // If it's the first time we're setting the `curEmbeddingsProviderId` - // global state, we don't need to reindex docs - this.globalContext.update( - "curEmbeddingsProviderId", - curEmbeddingsProviderId, - ); - - return false; - } - - return lastEmbeddingsProviderId !== curEmbeddingsProviderId; - } + // METHODS FOR MASS REINDEXING /** * Currently this deletes re-crawls + re-indexes all docs. * A more optimal solution in the future will be to create * a per-embeddings-provider table for docs. */ - private async reindexDocsOnNewEmbeddingsProvider( - embeddingsProvider: EmbeddingsProvider, - ) { + private async reindexDocsOnNewEmbeddingsProvider() { // We use config as our source of truth here since it contains additional information // needed for re-crawling such as `faviconUrl` and `maxDepth`. - const { docs } = this.config; + const { docs, embeddingsProvider } = this.config; if (!docs || docs.length === 0) { return; @@ -815,9 +863,10 @@ export default class DocsService { for (const doc of docs) { await this.delete(doc.startUrl); + } + for (const doc of docs) { const generator = this.indexAndAdd(doc); - while (!(await generator.next()).done) {} } diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 1c0f5e962..077fa4315 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -41,7 +41,9 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "stats/getTokensPerModel", "index/setPaused", "index/forceReIndex", - "index/indexingProgressBarInitialized", + "index/indexingProgressBarInitialized", // Deprecated + "index/getStatuses", + "completeOnboarding", "addAutocompleteModel", "config/listProfiles", @@ -55,10 +57,11 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "configUpdate", "getDefaultModelTitle", "indexProgress", + "index/statusUpdate", // "addContextItem", "refreshSubmenuItems", "isContinueInputFocused", "didChangeAvailableProfiles", "setTTSActive", - "getWebviewHistoryLength" + "getWebviewHistoryLength", ]; From af4e5ee4400f65843319ce4f50e487e80344605d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 01:22:57 -0800 Subject: [PATCH 30/82] indexing manager --- core/context/providers/DocsContextProvider.ts | 1 - core/core.ts | 41 +++-- core/index.d.ts | 19 +- core/indexing/IndexingStatusManager.ts | 104 +++++++++++ core/indexing/docs/DocsService.test.ts | 9 +- core/indexing/docs/DocsService.ts | 171 +++++++++++------- core/protocol/core.ts | 12 ++ core/protocol/passThrough.ts | 15 +- core/protocol/webview.ts | 7 +- gui/src/hooks/useSetup.ts | 8 - 10 files changed, 274 insertions(+), 113 deletions(-) create mode 100644 core/indexing/IndexingStatusManager.ts diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index f3a1e5d77..2f2ca9002 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -9,7 +9,6 @@ import { } from "../.."; import DocsService from "../../indexing/docs/DocsService"; import preIndexedDocs from "../../indexing/docs/preIndexedDocs"; -import { Telemetry } from "../../util/posthog"; import { INSTRUCTIONS_BASE_ITEM } from "./utils"; diff --git a/core/core.ts b/core/core.ts index c1075dfd6..fe07ecbce 100644 --- a/core/core.ts +++ b/core/core.ts @@ -35,6 +35,7 @@ import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./util/messenger"; +import { IndexingStatusManager } from "./indexing/IndexingStatusManager"; export class Core { // implements IMessenger @@ -43,8 +44,8 @@ export class Core { completionProvider: CompletionProvider; continueServerClientPromise: Promise; codebaseIndexingState: IndexingProgressUpdate; - docsIndexingStates: Map = new Map(); controlPlaneClient: ControlPlaneClient; + private indexingManager: IndexingStatusManager; private docsService: DocsService; private globalContext = new GlobalContext(); @@ -109,6 +110,8 @@ export class Core { this.controlPlaneClient, ); + this.indexingManager = new IndexingStatusManager(this.messenger); + this.docsService = DocsService.createSingleton( this.configHandler, this.ide, @@ -278,32 +281,15 @@ export class Core { // Context providers on("context/addDocs", async (msg) => { - // let hasFailed = false; - // for await (const result of this.docsService.indexAndAdd(msg.data)) { - // if (result.status === "failed") { - // hasFailed = true; - // break; - // } - // } - // if (hasFailed) { - // void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`); - // } else { - // void this.ide.showToast( - // "info", - // `Successfully indexed ${msg.data.startUrl}`, - // ); - // this.messenger.send("refreshSubmenuItems", undefined); - // } + void this.docsService.indexAndAdd(msg.data); }); on("context/removeDocs", async (msg) => { await this.docsService.delete(msg.data.startUrl); - this.messenger.send("refreshSubmenuItems", undefined); }); on("context/indexDocs", async (msg) => { - await this.docsService.indexAllDocs(msg.data.reIndex); - this.messenger.send("refreshSubmenuItems", undefined); + await this.docsService.indexAllDocsWithPrompt(msg.data.reIndex); }); on("context/loadSubmenuItems", async (msg) => { @@ -726,6 +712,19 @@ export class Core { recentlyEditedFilesCache.set(filepath, filepath); } }); + + on("indexing/reindex", async (msg) => { + this.indexingManager.reindex(msg.data.id); + }); + on("indexing/abort", async (msg) => { + this.indexingManager.abort(msg.data.id); + }); + on("indexing/setPaused", async (msg) => { + this.indexingManager.setPaused(msg.data.id, msg.data.pause); + }); + on("indexing/getStatuses", async (msg) => { + return this.indexingManager.statuses; + }); } private indexingCancellationController: AbortController | undefined; @@ -768,4 +767,6 @@ export class Core { this.messenger.send("refreshSubmenuItems", undefined); } + + // private } diff --git a/core/index.d.ts b/core/index.d.ts index b6b4c7f0c..f1c7263eb 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -47,22 +47,21 @@ export interface IndexingProgressUpdate { // This is more or less a V2 of IndexingProgressUpdate export interface IndexingStatusUpdate { + id: string; type: "docs"; - id: string; // Unique identifier, e.g. docs start url progress: number; description: string; - status: - | "initializing" - | "indexing" - | "complete" - | "paused" - | "failed" - | "disabled"; - embeddingsModel: string; - isReindexing: boolean; + status: "indexing" | "complete" | "paused" | "failed" | "aborted" | "deleted"; + embeddingsProviderId: string; + isReindexing?: boolean; debugInfo?: string; } +export type IndexingStatusMap = Map< + string, + Map +>; + export type PromptTemplateFunction = ( history: ChatMessage[], otherData: Record, diff --git a/core/indexing/IndexingStatusManager.ts b/core/indexing/IndexingStatusManager.ts new file mode 100644 index 000000000..1ba177493 --- /dev/null +++ b/core/indexing/IndexingStatusManager.ts @@ -0,0 +1,104 @@ +import { IndexingStatusMap, IndexingStatusUpdate } from ".."; +import { FromCoreProtocol, ToCoreProtocol } from "../protocol"; +import { IMessenger } from "../util/messenger"; + +/* + Any service that sends indexing updates can use an instance of this class + 1. Pass indexingManager to the service + 2. Register the service with the manager using `registerService` + E.g. docs uses startUrl as id + 3. +*/ +export class IndexingStatusManager { + private readonly messenger: IMessenger; + readonly statuses: IndexingStatusMap = new Map(); + private readonly reindexTypeFunctions: Map< + string, + (id: string) => Promise + > = new Map(); + + constructor(messenger: IMessenger) { + this.messenger = messenger; + } + + // Services that use an instance of this class should add their reindex functions here + registerService(type: string, fn: (id: string) => Promise) { + this.reindexTypeFunctions.set(type, fn); + this.statuses.set(type, new Map()); + } + + reindex(type: string, id: string) { + const byType = this.statuses.get(type); + const reindexFn = this.reindexTypeFunctions.get(type); + + if (byType && reindexFn) { + const status = byType.get(id); + if (status) { + if (status.status === "deleted") { + throw new Error( + "Cannot reindex a deleted item, shouldn't ever happen", + ); + } + void reindexFn(id); + } + } + } + + handleUpdate(status: IndexingStatusUpdate) { + const byType = this.statuses.get(status.type); + if (byType) { + byType.set(status.id, status); + this.messenger.send("indexing/statusUpdate", status); + } + } + + delete(type: string, id: string) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + this.handleUpdate({ ...status, status: "deleted" }); + } + } + } + + abort(type: string, id: string) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + this.handleUpdate({ ...status, status: "aborted" }); + } + } + } + + isAborted(type: string, id: string) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + return status.status === "aborted"; + } + } + } + + setPaused(type: string, id: string, pause: boolean) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + this.handleUpdate({ ...status, status: pause ? "paused" : "indexing" }); + } + } + } + + isPaused(type: string, id: string) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + return status.status === "paused"; + } + } + } +} diff --git a/core/indexing/docs/DocsService.test.ts b/core/indexing/docs/DocsService.test.ts index 11fed29e5..4a911b38a 100644 --- a/core/indexing/docs/DocsService.test.ts +++ b/core/indexing/docs/DocsService.test.ts @@ -66,8 +66,7 @@ describe.skip("DocsService Integration Tests", () => { }); test("Indexing, retrieval, and deletion of a new documentation site", async () => { - const generator = docsService.indexAndAdd(mockSiteConfig); - while (!(await generator.next()).done) {} + await docsService.indexAndAdd(mockSiteConfig); let latestConfig = await getReloadedConfig(); @@ -133,13 +132,11 @@ describe.skip("DocsService Integration Tests", () => { test("Handles pulling down and adding pre-indexed docs", async () => { const preIndexedDoc = Object.values(preIndexedDocs)[0]; - const generator = docsService.indexAndAdd(preIndexedDoc); - while (!(await generator.next()).done) {} + await docsService.indexAndAdd(preIndexedDoc); }); test("Config synchronization with SQLite", async () => { - const generator = docsService.indexAndAdd(mockSiteConfig); - while (!(await generator.next()).done) {} + await docsService.indexAndAdd(mockSiteConfig); await getReloadedConfig(); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 79dea28e6..9450cca6b 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -24,6 +24,7 @@ import { } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider"; +import { IndexingStatusManager } from "../IndexingStatusManager"; import { Article, chunkArticle, pageToArticle } from "./article"; import DocsCrawler from "./DocsCrawler"; @@ -78,6 +79,8 @@ export type AddParams = { export default class DocsService { static lanceTableName = "docs"; static sqlitebTableName = "docs"; + static indexingType = "docs"; + static preIndexedDocsEmbeddingsProvider = new TransformersJsEmbeddingsProvider(); @@ -97,6 +100,7 @@ export default class DocsService { configHandler: ConfigHandler, private readonly ide: IDE, private readonly messenger?: IMessenger, + private readonly indexingManager?: IndexingStatusManager, ) { this.isInitialized = this.init(configHandler); } @@ -119,9 +123,12 @@ export default class DocsService { // Initialization - load config and attach config listener private async init(configHandler: ConfigHandler) { + this.indexingManager?.registerService( + DocsService.indexingType, + this.reindexDoc, + ); this.config = await configHandler.loadConfig(); await this.handleConfigUpdate({ config: this.config }); - configHandler.onConfigUpdate(this.handleConfigUpdate); } @@ -180,14 +187,7 @@ export default class DocsService { return; } - const newConfigDocs = newConfig.docs || []; - const oldConfigDocs = oldConfig.docs || []; - - const newPreindexed = newConfigDocs.filter( - (doc) => !!preIndexedDocs[doc.startUrl], - ); - - // On embeddings provider change, reindex all docs + // On embeddings provider change, reindex all non-preindexed docs // change = doesn't match last successful embeddings provider const curEmbeddingsProviderId = this.globalContext.get( "curEmbeddingsProviderId", @@ -204,7 +204,7 @@ export default class DocsService { } } - await this.syncConfigAndSqlite(); + await this.syncDocsOnConfigUpdate(oldConfig, newConfig); } } @@ -251,7 +251,7 @@ export default class DocsService { return res === actionMsg; } - async indexAllDocs(reIndex: boolean = false) { + async indexAllDocsWithPrompt(reIndex: boolean = false) { if (!this.hasDocsContextProvider()) { const didAddDocsContextProvider = await this.showAddDocsContextProviderToast(); @@ -264,8 +264,7 @@ export default class DocsService { const docs = await this.listMetadata(); for (const doc of docs) { - const generator = this.indexAndAdd(doc, reIndex); - while (!(await generator.next()).done) {} + await this.indexAndAdd(doc, reIndex); } void this.ide.showToast("info", "Docs indexing completed"); @@ -280,10 +279,23 @@ export default class DocsService { return docs; } - async *indexAndAdd( + updateIndexingStatus(update: IndexingStatusUpdate) { + this.indexingManager?.handleUpdate(update); + } + + async reindexDoc(startUrl: string) { + const docConfig = this.config.docs?.find( + (doc) => doc.startUrl === startUrl, + ); + if (docConfig) { + await this.indexAndAdd(docConfig, true); + } + } + + async indexAndAdd( siteIndexingConfig: SiteIndexingConfig, reIndex: boolean = false, - ): AsyncGenerator { + ): Promise { const { startUrl } = siteIndexingConfig; if (this.docsIndexingQueue.has(startUrl)) { @@ -296,38 +308,34 @@ export default class DocsService { const fixedStatus: Pick< IndexingStatusUpdate, - "type" | "id" | "embeddingsModel" | "isReindexing" + "type" | "id" | "embeddingsProviderId" | "isReindexing" > = { type: "docs", id: siteIndexingConfig.startUrl, - embeddingsModel: embeddingsProvider.id, + embeddingsProviderId: embeddingsProvider.id, isReindexing: reIndex && indexExists, }; - const completeStatus: IndexingStatusUpdate = { - ...fixedStatus, - progress: 1, - description: "Complete", - status: "complete", - }; - if (indexExists && !reIndex) { - yield { - ...completeStatus, + this.updateIndexingStatus({ + ...fixedStatus, + progress: 1, + description: "Complete", + status: "complete", debugInfo: "Already indexed", - }; + }); return; } // Mark the site as currently being indexed this.docsIndexingQueue.add(startUrl); - yield { + this.updateIndexingStatus({ ...fixedStatus, status: "indexing", description: "Finding subpages", progress: 0, - }; + }); const articles: Article[] = []; let processedPages = 0; @@ -348,12 +356,12 @@ export default class DocsService { // Use a heuristic approach for progress calculation const progress = Math.min(processedPages / maxKnownPages, 1); - yield { + this.updateIndexingStatus({ ...fixedStatus, description: `Finding subpages (${page.path})`, status: "indexing", progress, // Yield the heuristic progress - }; + }); // Increase maxKnownPages to delay progress reaching 100% too soon if (processedPages === maxKnownPages) { @@ -375,12 +383,12 @@ export default class DocsService { for (let i = 0; i < articles.length; i++) { const article = articles[i]; - yield { + this.updateIndexingStatus({ ...fixedStatus, status: "indexing", description: `Creating Embeddings: ${article.subpath}`, progress: i / articles.length, - }; + }); try { const chunkedArticle = chunkArticle( @@ -409,12 +417,14 @@ export default class DocsService { `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, ); - yield { + this.updateIndexingStatus({ ...fixedStatus, description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, status: "failed", progress: 1, - }; + }); + + void this.ide.showToast("info", `Failed to index ${startUrl}`); this.docsIndexingQueue.delete(startUrl); @@ -424,12 +434,12 @@ export default class DocsService { // Add docs to databases console.log(`Adding ${embeddings.length} embeddings to db`); - yield { + this.updateIndexingStatus({ ...fixedStatus, description: `Adding ${embeddings.length} embeddings to db`, status: "indexing", progress: 0.5, - }; + }); // Delete indexed docs if re-indexing if (reIndex && (await this.hasMetadata(startUrl.toString()))) { @@ -448,14 +458,14 @@ export default class DocsService { this.docsIndexingQueue.delete(startUrl); - yield { + this.updateIndexingStatus({ ...fixedStatus, description: "Complete", status: "complete", progress: 1, - }; + }); - console.log(`Successfully indexed: ${siteIndexingConfig.startUrl}`); + void this.ide.showToast("info", `Successfully indexed ${startUrl}`); if (this.messenger) { this.messenger.send("refreshSubmenuItems", undefined); @@ -480,8 +490,7 @@ export default class DocsService { return []; } - const preIndexedDoc = preIndexedDocs[query]; - + const preIndexedDoc = preIndexedDocs[startUrl]; if (!!preIndexedDoc) { void Telemetry.capture("docs_pre_indexed_doc_used", { doc: preIndexedDoc["title"], @@ -583,32 +592,72 @@ export default class DocsService { return result.favicon; } - private async syncConfigAndSqlite() { + /* + Sync with no embeddings provider change + Ignores pre-indexed docs + */ + private async syncDocsOnConfigUpdate( + oldConfig: ContinueConfig, + newConfig: ContinueConfig, + ) { try { this.isSyncing = true; - const sqliteDocs = await this.listMetadata(); - const sqliteDocStartUrls = sqliteDocs.map((doc) => doc.startUrl) || []; + // Otherwise sync the index based on config changes + const oldConfigDocs = oldConfig.docs || []; + const newConfigDocs = newConfig.docs || []; + const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl); - const configDocs = this.config.docs || []; - const configDocStartUrls = - this.config.docs?.map((doc) => doc.startUrl) || []; + const currentlyIndexedDocs = await this.listMetadata(); + const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); - const newDocs = configDocs.filter( - (doc) => !sqliteDocStartUrls.includes(doc.startUrl), - ); - const deletedDocs = sqliteDocs.filter( + // const newDocs = newConfigDocs.filter( + // (doc) => !currentStartUrls.includes(doc.startUrl), + // ); + + // Anything found in sqlite but not in new config should be deleted + const deletedDocs = currentlyIndexedDocs.filter( (doc) => - !configDocStartUrls.includes(doc.startUrl) && - !preIndexedDocs[doc.startUrl], + !preIndexedDocs[doc.startUrl] && + !newConfigStartUrls.includes(doc.startUrl), ); + // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed + // TODO if only favicon and title change, only update, don't embed + // Otherwise anything found in new config that isn't in sqlite should be added/indexed + const newDocs: SiteIndexingConfig[] = []; + const changedDocs: SiteIndexingConfig[] = []; + for (const doc of newConfigDocs) { + const oldConfigDoc = oldConfigDocs.find( + (d) => d.startUrl === doc.startUrl, + ); + const currentIndexedDoc = currentStartUrls.includes(doc.startUrl); + + if (currentIndexedDoc) { + if ( + oldConfigDoc && + (oldConfigDoc.maxDepth !== doc.maxDepth || + oldConfigDoc.title !== doc.title || + oldConfigDoc.faviconUrl !== doc.faviconUrl) + ) { + changedDocs.push(doc); + } + // if get's here, not changed, no update needed + } else { + newDocs.push(doc); + } + } + + for (const doc of changedDocs) { + console.log(`Updating indexed doc: ${doc.startUrl}`); + await this.indexAndAdd(doc, true); + } + for (const doc of newDocs) { console.log(`Indexing new doc: ${doc.startUrl}`); void Telemetry.capture("add_docs_config", { url: doc.startUrl }); - const generator = this.indexAndAdd(doc); - while (!(await generator.next()).done) {} + await this.indexAndAdd(doc); } for (const doc of deletedDocs) { @@ -706,8 +755,7 @@ export default class DocsService { return table; } - // Add methods for Individual docs - + // Methods for adding individual docs private async addToLance({ chunks, siteIndexingConfig, @@ -858,7 +906,7 @@ export default class DocsService { } console.log( - `Reindexing docs with new embeddings provider: ${embeddingsProvider.id}`, + `Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.id}`, ); for (const doc of docs) { @@ -866,8 +914,7 @@ export default class DocsService { } for (const doc of docs) { - const generator = this.indexAndAdd(doc); - while (!(await generator.next()).done) {} + await this.indexAndAdd(doc); } // Important that this only is invoked after we have successfully @@ -875,6 +922,6 @@ export default class DocsService { // invalid state. this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); - console.log("Completed reindexing of all docs"); + console.log("Completed reindexing of all non-preindexed docs"); } } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 2c9af1433..fec158eac 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -8,6 +8,7 @@ import type { ContextSubmenuItem, DiffLine, IdeSettings, + IndexingStatusMap, LLMFullCompletionOptions, MessageContent, ModelDescription, @@ -142,6 +143,8 @@ export type ToCoreFromIdeOrWebviewProtocol = { { model: string; promptTokens: number; generatedTokens: number }[], ]; "tts/kill": [undefined, void]; + + // Codebase indexing "index/setPaused": [boolean, void]; "index/forceReIndex": [ undefined | { dirs?: string[]; shouldClearIndexes?: boolean }, @@ -154,6 +157,15 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, void, ]; + + // Docs Indexing. TODO move codebase to this + "indexing/reindex": [ + { id: string; shouldClearAllOfIndexType?: boolean }, + void, + ]; + "indexing/abort": [{ id: string }, void]; + "indexing/setPaused": [{ id: string; pause: boolean }, void]; + "indexing/getStatuses": [undefined, IndexingStatusMap]; addAutocompleteModel: [{ model: ModelDescription }, void]; "profiles/switch": [{ id: string }, undefined]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 077fa4315..b2d18c533 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -39,11 +39,16 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "chatDescriber/describe", "stats/getTokensPerDay", "stats/getTokensPerModel", + // Codebase "index/setPaused", "index/forceReIndex", - "index/indexingProgressBarInitialized", // Deprecated - "index/getStatuses", - + "index/indexingProgressBarInitialized", + // Docs, etc. + "indexing/getStatuses", + "indexing/reindex", + "indexing/abort", + "indexing/setPaused", + // "completeOnboarding", "addAutocompleteModel", "config/listProfiles", @@ -56,8 +61,8 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = [ "configUpdate", "getDefaultModelTitle", - "indexProgress", - "index/statusUpdate", // + "indexProgress", // Codebase + "indexing/statusUpdate", // Docs, etc. "addContextItem", "refreshSubmenuItems", "isContinueInputFocused", diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index d974c1516..4fd2f7094 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,12 +1,17 @@ import { ConfigValidationError } from "../config/validation.js"; -import type { ContextItemWithId, IndexingProgressUpdate } from "../index.js"; +import type { + ContextItemWithId, + IndexingProgressUpdate, + IndexingStatusUpdate, +} from "../index.js"; export type ToWebviewFromIdeOrCoreProtocol = { configUpdate: [undefined, void]; configError: [ConfigValidationError[] | undefined, void]; getDefaultModelTitle: [undefined, string]; indexProgress: [IndexingProgressUpdate, void]; + "indexing/statusUpdate": [IndexingStatusUpdate, void]; refreshSubmenuItems: [undefined, void]; isContinueInputFocused: [undefined, boolean]; addContextItem: [ diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 58feba2a5..5329abdda 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -110,16 +110,8 @@ function useSetup(dispatch: Dispatch) { }); }); - const debouncedIndexDocs = debounce(() => { - ideMessenger.request("context/indexDocs", { reIndex: false }); - }, 1000); - useWebviewListener("configUpdate", async () => { await loadConfig(); - - if (!isJetBrains) { - debouncedIndexDocs(); - } }); useWebviewListener("configError", async (error) => { From 34627a94d473a16ffdc6c185ac695bd1ebfc7043 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 02:25:32 -0800 Subject: [PATCH 31/82] indexing manager p2 --- core/core.ts | 11 ++-- core/index.d.ts | 5 ++ core/indexing/IndexingStatusManager.ts | 89 +++++++++++--------------- core/indexing/docs/DocsService.ts | 24 ++++--- core/protocol/core.ts | 11 ++-- core/protocol/webview.ts | 4 +- extensions/vscode/package-lock.json | 4 +- gui/src/hooks/useSetup.ts | 10 +++ 8 files changed, 85 insertions(+), 73 deletions(-) diff --git a/core/core.ts b/core/core.ts index fe07ecbce..8a27fedc3 100644 --- a/core/core.ts +++ b/core/core.ts @@ -110,12 +110,15 @@ export class Core { this.controlPlaneClient, ); - this.indexingManager = new IndexingStatusManager(this.messenger); + this.indexingManager = IndexingStatusManager.createSingleton( + this.messenger, + ); this.docsService = DocsService.createSingleton( this.configHandler, this.ide, this.messenger, + this.indexingManager, ); this.configHandler.onConfigUpdate( @@ -714,13 +717,13 @@ export class Core { }); on("indexing/reindex", async (msg) => { - this.indexingManager.reindex(msg.data.id); + this.indexingManager.reindex(msg.data.identifier); }); on("indexing/abort", async (msg) => { - this.indexingManager.abort(msg.data.id); + this.indexingManager.abort(msg.data.identifier); }); on("indexing/setPaused", async (msg) => { - this.indexingManager.setPaused(msg.data.id, msg.data.pause); + this.indexingManager.setPaused(msg.data.identifier, msg.data.pause); }); on("indexing/getStatuses", async (msg) => { return this.indexingManager.statuses; diff --git a/core/index.d.ts b/core/index.d.ts index f1c7263eb..53ca6ae42 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -57,6 +57,11 @@ export interface IndexingStatusUpdate { debugInfo?: string; } +interface IndexIdentifier { + type: string; + id: string; +} + export type IndexingStatusMap = Map< string, Map diff --git a/core/indexing/IndexingStatusManager.ts b/core/indexing/IndexingStatusManager.ts index 1ba177493..785f14b95 100644 --- a/core/indexing/IndexingStatusManager.ts +++ b/core/indexing/IndexingStatusManager.ts @@ -1,4 +1,4 @@ -import { IndexingStatusMap, IndexingStatusUpdate } from ".."; +import { IndexIdentifier, IndexingStatusMap, IndexingStatusUpdate } from ".."; import { FromCoreProtocol, ToCoreProtocol } from "../protocol"; import { IMessenger } from "../util/messenger"; @@ -7,7 +7,8 @@ import { IMessenger } from "../util/messenger"; 1. Pass indexingManager to the service 2. Register the service with the manager using `registerService` E.g. docs uses startUrl as id - 3. + 3. Rules of engagement: + - service is responsible for checking corrupted indexes - don't check paused or deleted */ export class IndexingStatusManager { private readonly messenger: IMessenger; @@ -21,26 +22,29 @@ export class IndexingStatusManager { this.messenger = messenger; } + private static instance?: IndexingStatusManager; + static createSingleton( + messenger: IMessenger, + ) { + const instance = new IndexingStatusManager(messenger); + IndexingStatusManager.instance = instance; + return instance; + } + + static getSingleton() { + return IndexingStatusManager.instance; + } + // Services that use an instance of this class should add their reindex functions here registerService(type: string, fn: (id: string) => Promise) { this.reindexTypeFunctions.set(type, fn); this.statuses.set(type, new Map()); } - reindex(type: string, id: string) { - const byType = this.statuses.get(type); + reindex({ type, id }: IndexIdentifier) { const reindexFn = this.reindexTypeFunctions.get(type); - - if (byType && reindexFn) { - const status = byType.get(id); - if (status) { - if (status.status === "deleted") { - throw new Error( - "Cannot reindex a deleted item, shouldn't ever happen", - ); - } - void reindexFn(id); - } + if (reindexFn) { + void reindexFn(id); } } @@ -52,53 +56,38 @@ export class IndexingStatusManager { } } - delete(type: string, id: string) { - const byType = this.statuses.get(type); - if (byType) { - const status = byType.get(id); - if (status) { - this.handleUpdate({ ...status, status: "deleted" }); - } + delete({ type, id }: IndexIdentifier) { + const status = this.statuses.get(type)?.get(id); + if (status) { + this.handleUpdate({ ...status, status: "deleted" }); } } - abort(type: string, id: string) { - const byType = this.statuses.get(type); - if (byType) { - const status = byType.get(id); - if (status) { - this.handleUpdate({ ...status, status: "aborted" }); - } + abort({ type, id }: IndexIdentifier) { + const status = this.statuses.get(type)?.get(id); + if (status) { + this.handleUpdate({ ...status, status: "aborted" }); } } - isAborted(type: string, id: string) { - const byType = this.statuses.get(type); - if (byType) { - const status = byType.get(id); - if (status) { - return status.status === "aborted"; - } + isAborted({ type, id }: IndexIdentifier) { + const status = this.statuses.get(type)?.get(id); + if (status) { + return status.status === "aborted"; } } - setPaused(type: string, id: string, pause: boolean) { - const byType = this.statuses.get(type); - if (byType) { - const status = byType.get(id); - if (status) { - this.handleUpdate({ ...status, status: pause ? "paused" : "indexing" }); - } + setPaused({ type, id }: IndexIdentifier, pause: boolean) { + const status = this.statuses.get(type)?.get(id); + if (status) { + this.handleUpdate({ ...status, status: pause ? "paused" : "indexing" }); } } - isPaused(type: string, id: string) { - const byType = this.statuses.get(type); - if (byType) { - const status = byType.get(id); - if (status) { - return status.status === "paused"; - } + isPaused({ type, id }: IndexIdentifier) { + const status = this.statuses.get(type)?.get(id); + if (status) { + return status.status === "paused"; } } } diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 9450cca6b..cb6e12bee 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -111,8 +111,14 @@ export default class DocsService { configHandler: ConfigHandler, ide: IDE, messenger?: IMessenger, + indexingManager?: IndexingStatusManager, ) { - const docsService = new DocsService(configHandler, ide, messenger); + const docsService = new DocsService( + configHandler, + ide, + messenger, + indexingManager, + ); DocsService.instance = docsService; return docsService; } @@ -127,9 +133,9 @@ export default class DocsService { DocsService.indexingType, this.reindexDoc, ); - this.config = await configHandler.loadConfig(); - await this.handleConfigUpdate({ config: this.config }); - configHandler.onConfigUpdate(this.handleConfigUpdate); + const config = await configHandler.loadConfig(); + await this.handleConfigUpdate({ config }); + configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this)); } // Config @@ -502,7 +508,7 @@ export default class DocsService { const [vector] = await embeddingsProvider.embed([query]); - return await this.retrieveChunks(query, vector, nRetrieve); + return await this.retrieveChunks(startUrl, vector, nRetrieve); } async retrieveChunks( @@ -525,7 +531,7 @@ export default class DocsService { .where(`starturl = '${startUrl}'`) .execute(); } catch (e: any) { - console.error("Error retrieving chunks from LanceDB", e); + console.warn("Error retrieving chunks from LanceDB", e); } const hasIndexedDoc = await this.hasMetadata(startUrl); @@ -597,14 +603,14 @@ export default class DocsService { Ignores pre-indexed docs */ private async syncDocsOnConfigUpdate( - oldConfig: ContinueConfig, + oldConfig: ContinueConfig | undefined, newConfig: ContinueConfig, ) { try { this.isSyncing = true; // Otherwise sync the index based on config changes - const oldConfigDocs = oldConfig.docs || []; + const oldConfigDocs = oldConfig?.docs || []; const newConfigDocs = newConfig.docs || []; const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl); @@ -664,7 +670,7 @@ export default class DocsService { await this.delete(doc.startUrl); } } catch (e) { - console.error("Error syncing config and sqlite", e); + console.error("Error syncing docs index on config update", e); } finally { this.isSyncing = false; } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index fec158eac..2e5a660d4 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -8,6 +8,7 @@ import type { ContextSubmenuItem, DiffLine, IdeSettings, + IndexIdentifier, IndexingStatusMap, LLMFullCompletionOptions, MessageContent, @@ -159,13 +160,11 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; // Docs Indexing. TODO move codebase to this - "indexing/reindex": [ - { id: string; shouldClearAllOfIndexType?: boolean }, - void, - ]; - "indexing/abort": [{ id: string }, void]; - "indexing/setPaused": [{ id: string; pause: boolean }, void]; + "indexing/reindex": [{ identifier: IndexIdentifier }, void]; + "indexing/abort": [{ identifier: IndexIdentifier }, void]; + "indexing/setPaused": [{ identifier: IndexIdentifier; pause: boolean }, void]; "indexing/getStatuses": [undefined, IndexingStatusMap]; + addAutocompleteModel: [{ model: ModelDescription }, void]; "profiles/switch": [{ id: string }, undefined]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 4fd2f7094..e5330d81f 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -10,8 +10,8 @@ export type ToWebviewFromIdeOrCoreProtocol = { configUpdate: [undefined, void]; configError: [ConfigValidationError[] | undefined, void]; getDefaultModelTitle: [undefined, string]; - indexProgress: [IndexingProgressUpdate, void]; - "indexing/statusUpdate": [IndexingStatusUpdate, void]; + indexProgress: [IndexingProgressUpdate, void]; // Codebase + "indexing/statusUpdate": [IndexingStatusUpdate, void]; // Docs, etc. refreshSubmenuItems: [undefined, void]; isContinueInputFocused: [undefined, boolean]; addContextItem: [ diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 24930d980..29ac4731f 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.229", + "version": "0.9.230", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.229", + "version": "0.9.230", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 5329abdda..07bcec0eb 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -135,6 +135,16 @@ function useSetup(dispatch: Dispatch) { ); }); + useWebviewListener("indexing/statusUpdate", async (data) => { + console.log("Indexing status update", data); + // dispatch( + // addContextItemsAtIndex({ + // index: data.historyIndex, + // contextItems: [data.item], + // }), + // ); + }); + useWebviewListener( "getDefaultModelTitle", async () => { From b14aca3b996afd6bdfbe3b89544de84a01516545 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 02:47:13 -0800 Subject: [PATCH 32/82] docs service debugging --- core/context/providers/DocsContextProvider.ts | 2 +- core/indexing/docs/DocsService.test.ts | 10 ++++------ core/indexing/docs/DocsService.ts | 9 ++++----- 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 2f2ca9002..6eab55fa4 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -89,7 +89,7 @@ class DocsContextProvider extends BaseContextProvider { await docsService.isInitialized; let chunks = await docsService.retrieveChunksFromQuery( - extras.fullInput, + extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case query, this.options?.nRetrieve ?? DocsContextProvider.nRetrieve, ); diff --git a/core/indexing/docs/DocsService.test.ts b/core/indexing/docs/DocsService.test.ts index 4a911b38a..67d33020d 100644 --- a/core/indexing/docs/DocsService.test.ts +++ b/core/indexing/docs/DocsService.test.ts @@ -77,11 +77,9 @@ describe.skip("DocsService Integration Tests", () => { expect(latestConfig.docs).toContainEqual(mockSiteConfig); // Lance DB check - const embeddingsProvider = await docsService.getEmbeddingsProvider(); - const [mockVector] = await embeddingsProvider.embed(["test"]); - let retrievedChunks = await docsService.retrieveChunks( + let retrievedChunks = await docsService.retrieveChunksFromQuery( + "test", mockSiteConfig.startUrl, - mockVector, 5, ); @@ -99,9 +97,9 @@ describe.skip("DocsService Integration Tests", () => { ); // LanceDB check - retrievedChunks = await docsService.retrieveChunks( + retrievedChunks = await docsService.retrieveChunksFromQuery( + "test", mockSiteConfig.startUrl, - mockVector, 5, ); expect(retrievedChunks.length).toBe(0); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index cb6e12bee..c37b68553 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -199,8 +199,8 @@ export default class DocsService { "curEmbeddingsProviderId", ); if ( - curEmbeddingsProviderId && - curEmbeddingsProviderId !== curEmbeddingsProviderId + !curEmbeddingsProviderId || + curEmbeddingsProviderId !== newConfig.embeddingsProvider.id ) { // If not set, we're initializing const currentDocs = await this.listMetadata(); @@ -517,7 +517,8 @@ export default class DocsService { nRetrieve: number, isRetry: boolean = false, ): Promise { - const embeddingsProvider = await this.getEmbeddingsProvider(); + const isPreindexed = !!preIndexedDocs[startUrl]; + const embeddingsProvider = await this.getEmbeddingsProvider(isPreindexed); const table = await this.getOrCreateLanceTable({ initializationVector: vector, embeddingsProvider, @@ -895,8 +896,6 @@ export default class DocsService { }); } - // METHODS FOR MASS REINDEXING - /** * Currently this deletes re-crawls + re-indexes all docs. * A more optimal solution in the future will be to create From 08d8f3781be54f191bd426cc9a4058f2960890c4 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 02:55:31 -0800 Subject: [PATCH 33/82] docs working --- core/indexing/docs/DocsService.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index c37b68553..ee7520eb5 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -517,11 +517,10 @@ export default class DocsService { nRetrieve: number, isRetry: boolean = false, ): Promise { - const isPreindexed = !!preIndexedDocs[startUrl]; - const embeddingsProvider = await this.getEmbeddingsProvider(isPreindexed); + const isPreIndexedDoc = !!preIndexedDocs[startUrl]; const table = await this.getOrCreateLanceTable({ initializationVector: vector, - embeddingsProvider, + isPreIndexedDoc, }); let docs: LanceDbDocsRow[] = []; @@ -719,8 +718,11 @@ export default class DocsService { } private async getLanceTableNameFromEmbeddingsProvider( - embeddingsProvider: EmbeddingsProvider, + isPreIndexedDoc: boolean, ) { + const embeddingsProvider = + await this.getEmbeddingsProvider(isPreIndexedDoc); + const tableName = this.sanitizeLanceTableName( `${DocsService.lanceTableName}${embeddingsProvider.id}`, ); @@ -730,15 +732,15 @@ export default class DocsService { private async getOrCreateLanceTable({ initializationVector, - embeddingsProvider, + isPreIndexedDoc, }: { initializationVector: number[]; - embeddingsProvider: EmbeddingsProvider; + isPreIndexedDoc?: boolean; }) { const conn = await lancedb.connect(getLanceDbPath()); const tableNames = await conn.tableNames(); const tableNameFromEmbeddingsProvider = - await this.getLanceTableNameFromEmbeddingsProvider(embeddingsProvider); + await this.getLanceTableNameFromEmbeddingsProvider(!!isPreIndexedDoc); if (!tableNames.includes(tableNameFromEmbeddingsProvider)) { if (initializationVector) { @@ -770,11 +772,9 @@ export default class DocsService { }: AddParams) { const sampleVector = embeddings[0]; const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl]; - const embeddingsProvider = - await this.getEmbeddingsProvider(isPreIndexedDoc); const table = await this.getOrCreateLanceTable({ - embeddingsProvider, + isPreIndexedDoc, initializationVector: sampleVector, }); From 441b489fcbcee0c5d81db0393d7ebb242f413e7f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 03:11:16 -0800 Subject: [PATCH 34/82] init with status updates --- core/indexing/docs/DocsService.ts | 263 ++++++++++++++++-------------- 1 file changed, 142 insertions(+), 121 deletions(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index ee7520eb5..801796363 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -134,6 +134,16 @@ export default class DocsService { this.reindexDoc, ); const config = await configHandler.loadConfig(); + this.config = config; + + // On first go we want to have an indexing status for all docs + // Since config handler will only trigger indexing status updates on changes + if (config.docs?.length) { + for (const doc of config.docs) { + await this.indexAndAdd(doc); + } + } + await this.handleConfigUpdate({ config }); configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this)); } @@ -335,146 +345,157 @@ export default class DocsService { // Mark the site as currently being indexed this.docsIndexingQueue.add(startUrl); - - this.updateIndexingStatus({ - ...fixedStatus, - status: "indexing", - description: "Finding subpages", - progress: 0, - }); - - const articles: Article[] = []; - let processedPages = 0; - let maxKnownPages = 1; - - // Crawl pages and retrieve info as articles - for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { - processedPages++; - - const article = pageToArticle(page); - - if (!article) { - continue; - } - - articles.push(article); - - // Use a heuristic approach for progress calculation - const progress = Math.min(processedPages / maxKnownPages, 1); - - this.updateIndexingStatus({ - ...fixedStatus, - description: `Finding subpages (${page.path})`, - status: "indexing", - progress, // Yield the heuristic progress - }); - - // Increase maxKnownPages to delay progress reaching 100% too soon - if (processedPages === maxKnownPages) { - maxKnownPages *= 2; - } - - await new Promise((resolve) => setTimeout(resolve, 50)); - } - - void Telemetry.capture("docs_pages_crawled", { - count: processedPages, - }); - - const chunks: Chunk[] = []; - const embeddings: number[][] = []; - - // Create embeddings of retrieved articles - console.debug(`Creating embeddings for ${articles.length} articles`); - - for (let i = 0; i < articles.length; i++) { - const article = articles[i]; + try { this.updateIndexingStatus({ ...fixedStatus, status: "indexing", - description: `Creating Embeddings: ${article.subpath}`, - progress: i / articles.length, + description: "Finding subpages", + progress: 0, }); - try { - const chunkedArticle = chunkArticle( - article, - embeddingsProvider.maxChunkSize, - ); + const articles: Article[] = []; + let processedPages = 0; + let maxKnownPages = 1; - const chunkedArticleContents = chunkedArticle.map( - (chunk) => chunk.content, - ); + // Crawl pages and retrieve info as articles + for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { + processedPages++; - chunks.push(...chunkedArticle); + const article = pageToArticle(page); - const subpathEmbeddings = await embeddingsProvider.embed( - chunkedArticleContents, - ); + if (!article) { + continue; + } - embeddings.push(...subpathEmbeddings); - } catch (e) { - console.warn("Error chunking article: ", e); + articles.push(article); + + // Use a heuristic approach for progress calculation + const progress = Math.min(processedPages / maxKnownPages, 1); + + this.updateIndexingStatus({ + ...fixedStatus, + description: `Finding subpages (${page.path})`, + status: "indexing", + progress, // Yield the heuristic progress + }); + + // Increase maxKnownPages to delay progress reaching 100% too soon + if (processedPages === maxKnownPages) { + maxKnownPages *= 2; + } + + await new Promise((resolve) => setTimeout(resolve, 50)); } - } - if (embeddings.length === 0) { - console.error( - `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, - ); + void Telemetry.capture("docs_pages_crawled", { + count: processedPages, + }); + const chunks: Chunk[] = []; + const embeddings: number[][] = []; + + // Create embeddings of retrieved articles + console.debug(`Creating embeddings for ${articles.length} articles`); + + for (let i = 0; i < articles.length; i++) { + const article = articles[i]; + this.updateIndexingStatus({ + ...fixedStatus, + status: "indexing", + description: `Creating Embeddings: ${article.subpath}`, + progress: i / articles.length, + }); + + try { + const chunkedArticle = chunkArticle( + article, + embeddingsProvider.maxChunkSize, + ); + + const chunkedArticleContents = chunkedArticle.map( + (chunk) => chunk.content, + ); + + chunks.push(...chunkedArticle); + + const subpathEmbeddings = await embeddingsProvider.embed( + chunkedArticleContents, + ); + + embeddings.push(...subpathEmbeddings); + } catch (e) { + console.warn("Error chunking article: ", e); + } + } + + if (embeddings.length === 0) { + console.error( + `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, + ); + + this.updateIndexingStatus({ + ...fixedStatus, + description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, + status: "failed", + progress: 1, + }); + + void this.ide.showToast("info", `Failed to index ${startUrl}`); + + this.docsIndexingQueue.delete(startUrl); + + return; + } + + // Add docs to databases + console.log(`Adding ${embeddings.length} embeddings to db`); + + this.updateIndexingStatus({ + ...fixedStatus, + description: `Adding ${embeddings.length} embeddings to db`, + status: "indexing", + progress: 0.5, + }); + + // Delete indexed docs if re-indexing + if (reIndex && (await this.hasMetadata(startUrl.toString()))) { + console.log("Deleting old embeddings"); + await this.delete(startUrl); + } + + const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); + + await this.add({ + siteIndexingConfig, + chunks, + embeddings, + favicon, + }); + + this.docsIndexingQueue.delete(startUrl); + + this.updateIndexingStatus({ + ...fixedStatus, + description: "Complete", + status: "complete", + progress: 1, + }); + + void this.ide.showToast("info", `Successfully indexed ${startUrl}`); + + if (this.messenger) { + this.messenger.send("refreshSubmenuItems", undefined); + } + } catch (e) { + console.error("Error indexing docs", e); this.updateIndexingStatus({ ...fixedStatus, description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, status: "failed", progress: 1, }); - - void this.ide.showToast("info", `Failed to index ${startUrl}`); - + } finally { this.docsIndexingQueue.delete(startUrl); - - return; - } - - // Add docs to databases - console.log(`Adding ${embeddings.length} embeddings to db`); - - this.updateIndexingStatus({ - ...fixedStatus, - description: `Adding ${embeddings.length} embeddings to db`, - status: "indexing", - progress: 0.5, - }); - - // Delete indexed docs if re-indexing - if (reIndex && (await this.hasMetadata(startUrl.toString()))) { - console.log("Deleting old embeddings"); - await this.delete(startUrl); - } - - const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); - - await this.add({ - siteIndexingConfig, - chunks, - embeddings, - favicon, - }); - - this.docsIndexingQueue.delete(startUrl); - - this.updateIndexingStatus({ - ...fixedStatus, - description: "Complete", - status: "complete", - progress: 1, - }); - - void this.ide.showToast("info", `Successfully indexed ${startUrl}`); - - if (this.messenger) { - this.messenger.send("refreshSubmenuItems", undefined); } } From b8a278d216db9851aa2b0772e0313ff4bc12c7cc Mon Sep 17 00:00:00 2001 From: burlinchen Date: Mon, 18 Nov 2024 09:34:17 +0800 Subject: [PATCH 35/82] feat: add Moonshot AI model provider support --- core/index.d.ts | 9 +- core/llm/autodetect.ts | 6 +- core/llm/llms/Moonshot.ts | 59 +++++++ core/llm/llms/index.ts | 2 + .../customize/model-providers/moonshot.md | 60 +++++++ extensions/vscode/config_schema.json | 161 ++++-------------- gui/src/pages/AddNewModel/configs/models.ts | 69 ++++++++ .../pages/AddNewModel/configs/providers.ts | 23 +++ packages/openai-adapters/src/apis/Moonshot.ts | 63 +++++++ packages/openai-adapters/src/index.ts | 3 + 10 files changed, 323 insertions(+), 132 deletions(-) create mode 100644 core/llm/llms/Moonshot.ts create mode 100644 docs/docs/customize/model-providers/moonshot.md create mode 100644 packages/openai-adapters/src/apis/Moonshot.ts diff --git a/core/index.d.ts b/core/index.d.ts index 1bad9fd74..1fddaa173 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -654,7 +654,8 @@ type ModelProvider = | "askSage" | "vertexai" | "nebius" - | "xAI"; + | "xAI" + | "moonshot"; export type ModelName = | "AUTODETECT" @@ -749,7 +750,11 @@ export type ModelName = | "starcoder-1b" | "starcoder-3b" | "starcoder2-3b" - | "stable-code-3b"; + | "stable-code-3b" + // Moonshot + | "moonshot-v1-8k" + | "moonshot-v1-32k" + | "moonshot-v1-128k"; export interface RequestOptions { timeout?: number; diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index bebb8ead1..8e475d01e 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -117,6 +117,7 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [ "huggingface-inference-api", "huggingface-tgi", "mistral", + "moonshot", "free-trial", "replicate", "together", @@ -149,9 +150,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined { lower.includes("chat-bison") || lower.includes("pplx") || lower.includes("gemini") || - lower.includes("grok") + lower.includes("grok")|| + lower.includes("moonshot") ) { - return undefined; + return undefined; } if (lower.includes("llama3")) { diff --git a/core/llm/llms/Moonshot.ts b/core/llm/llms/Moonshot.ts new file mode 100644 index 000000000..022fa8af2 --- /dev/null +++ b/core/llm/llms/Moonshot.ts @@ -0,0 +1,59 @@ +import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js"; +import { streamSse } from "../stream.js"; +import { osModelsEditPrompt } from "../templates/edit.js"; + +import OpenAI from "./OpenAI.js"; + +class Moonshot extends OpenAI { + static providerName: ModelProvider = "moonshot"; + static defaultOptions: Partial = { + apiBase: "https://api.moonshot.cn/v1/", + model: "moonshot-v1-8k", + promptTemplates: { + edit: osModelsEditPrompt, + }, + useLegacyCompletionsEndpoint: false, + }; + maxStopWords: number | undefined = 16; + + supportsFim(): boolean { + return true; + } + + async *_streamFim( + prefix: string, + suffix: string, + options: CompletionOptions, + ): AsyncGenerator { + const endpoint = new URL("v1/chat/completions", this.apiBase); + const resp = await this.fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + model: options.model, + messages: [ + { + role: "user", + content: prefix + "[fill]" + suffix, + }, + ], + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stop: options.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + }); + for await (const chunk of streamSse(resp)) { + yield chunk.choices[0].delta.content; + } + } +} + +export default Moonshot; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 48088dc34..121f0f46d 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -31,6 +31,7 @@ import Llamafile from "./Llamafile"; import LMStudio from "./LMStudio"; import Mistral from "./Mistral"; import Mock from "./Mock"; +import Moonshot from "./Moonshot"; import Msty from "./Msty"; import Nebius from "./Nebius"; import Nvidia from "./Nvidia"; @@ -54,6 +55,7 @@ const LLMs = [ FreeTrial, Gemini, Llamafile, + Moonshot, Ollama, Replicate, TextGenWebUI, diff --git a/docs/docs/customize/model-providers/moonshot.md b/docs/docs/customize/model-providers/moonshot.md new file mode 100644 index 000000000..64017d1bd --- /dev/null +++ b/docs/docs/customize/model-providers/moonshot.md @@ -0,0 +1,60 @@ +# Moonshot + +[Moonshot AI](https://platform.moonshot.cn/) provides high-quality large language model services with competitive pricing and excellent performance. + +## Configuration + +To use Moonshot AI models, you need to: + +1. Get an API key from [Moonshot AI Platform](https://platform.moonshot.cn/) +2. Add the following configuration to your `config.json`: + +```json +{ + "models": [ + { + "title": "Moonshot", + "provider": "moonshot", + "model": "moonshot-v1-8k", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +## Available Models + +Moonshot AI currently provides the following models: + +- `moonshot-v1-8k`: Base model with 8K context window +- `moonshot-v1-32k`: Base model with 32K context window +- `moonshot-v1-128k`: Base model with 128K context window + +## Configuration Options + +| Option | Description | Default | +|--------|-------------|---------| +| `apiKey` | Moonshot API key | Required | +| `apiBase` | API base URL | `https://api.moonshot.cn/v1/` | +| `model` | Model name to use | `moonshot-v1-8k` | + +## Example + +Here's a complete configuration example: + +```json +{ + "models": [ + { + "title": "Moonshot-8K", + "provider": "moonshot", + "model": "moonshot-v1-8k", + "apiKey": "YOUR_API_KEY", + "completionOptions": { + "temperature": 0.7, + "topP": 0.95, + "maxTokens": 2048 + } + } + ] +} diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index eb75d1f90..88f3626d5 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -205,7 +205,8 @@ "nebius", "vertexai", "xAI", - "kindo" + "kindo", + "moonshot" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -242,7 +243,8 @@ "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).", "### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)", "### xAI offers a world class developer tool set to build scalable applications powered by Grok. To get started, obtain an API key from [the x Console](https://console.x.ai/), and see the [docs](https://docs.x.ai/docs/)", - "### Secure AI management software that helps enterprises adopt and manage AI across their workforce. To get started, obtain an API key from [the Kindo console](https://app.kindo.ai/settings/api), and see the [website](https://app.kindo.ai//)" + "### Secure AI management software that helps enterprises adopt and manage AI across their workforce. To get started, obtain an API key from [the Kindo console](https://app.kindo.ai/settings/api), and see the [website](https://app.kindo.ai//)", + "### Moonshot\nTo get started with Moonshot AI, obtain your API key from [Moonshot AI](https://platform.moonshot.cn/). Moonshot AI provides high-quality large language models with competitive pricing.\n> [Reference](https://platform.moonshot.cn/docs/api)" ], "type": "string" }, @@ -590,129 +592,6 @@ } } }, - { - "if": { - "properties": { - "provider": { - "enum": ["openai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4o", - "gpt-4o-mini", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-0125-preview", - "gpt-4-turbo", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["xAI"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": ["grok-beta", "AUTODETECT"] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["replicate"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "llama3-8b", - "llama3-70b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "llama2-7b", - "llama2-13b" - ] - }, - { - "type": "string" - } - ] - }, - "markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models).", - "x-intellij-html-description": "Select a pre-defined option, or find an exact model ID from Replicate here." - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["free-trial"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": [ - "gpt-4o", - "codestral-latest", - "llama3.1-70b", - "llama3.1-405b", - "gpt-3.5-turbo", - "gemini-pro", - "claude-3-5-sonnet-latest", - "claude-3-haiku-20240307", - "AUTODETECT" - ] - } - } - } - }, { "if": { "properties": { @@ -769,9 +648,6 @@ "starcoder-1b", "starcoder-3b", "starcoder2-3b", - "mistral-tiny", - "mistral-small", - "mistral-medium", "qwen2.5-coder:1.5b", "qwen2.5-coder:3b", "qwen2.5-coder:7b", @@ -1147,6 +1023,35 @@ "required": ["projectId", "region"] } }, + { + "if": { + "properties": { + "provider": { + "enum": ["moonshot"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "moonshot-v1-8k", + "moonshot-v1-32k", + "moonshot-v1-128k", + "AUTODETECT" + ] + }, + { + "type": "string" + } + ] + } + } + } + }, { "if": { "properties": { diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index 01293f87a..6a0a4da73 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -31,6 +31,42 @@ export interface ModelPackage { } export const models: { [key: string]: ModelPackage } = { + moonshotChat: { + title: "Moonshot Chat", + description: "Moonshot AI provides high-performance large language models", + refUrl: "https://platform.moonshot.cn/", + params: { + title: "Moonshot-v1-8k", + model: "moonshot-v1-8k", + contextLength: 8192, + }, + icon: "moonshot.png", + dimensions: [ + { + name: "Context Window", + description: "The size of the model's context window", + options: { + "8K": { + model: "moonshot-v1-8k", + title: "Moonshot-v1-8k", + contextLength: 8192, + }, + "32K": { + model: "moonshot-v1-32k", + title: "Moonshot-v1-32k", + contextLength: 32768, + }, + "128K": { + model: "moonshot-v1-128k", + title: "Moonshot-v1-128k", + contextLength: 131072, + }, + }, + }, + ], + providerOptions: ["moonshot"], + isOpenSource: false, + }, llama31Chat: { title: "Llama3.1 Chat", description: "A model from Meta, fine-tuned for chat", @@ -111,6 +147,39 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["ollama", "groq", "llama.cpp"], isOpenSource: true, }, + moonshotChat: { + title: "Moonshot Chat", + description: "The latest model from Moonshot, fine-tuned for chat", + refUrl: "", + params: { + title: "Moonshot-8b", + model: "moonshot-8b", + contextLength: 8192, + }, + icon: "moonshot.png", + dimensions: [ + { + name: "Parameter Count", + description: "The number of parameters in the model", + options: { + "1b": { + model: "moonshot-1b", + title: "Moonshot-1b", + }, + "8b": { + model: "moonshot-8b", + title: "Moonshot-8b", + }, + "65b": { + model: "moonshot-65b", + title: "Moonshot-65b", + }, + }, + }, + ], + providerOptions: ["ollama", "lmstudio", "llama.cpp"], + isOpenSource: true, + }, deepseek: { title: "DeepSeek Coder", description: diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 5047fbad0..9c3ef2224 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -116,6 +116,29 @@ export const providers: Partial> = { ], apiKeyUrl: "https://console.anthropic.com/account/keys", }, + moonshot: { + title: "Moonshot", + provider: "moonshot", + description: "Use the Moonshot API for LLMs", + longDescription: `[Visit our documentation](https://docs.continue.dev/reference/Model%20Providers/moonshot) for information on obtaining an API key.`, + icon: "moonshot.png", + tags: [ModelProviderTags.RequiresApiKey], + refPage: "moonshot", + apiKeyUrl: "https://docs.moonshot.cn/docs/getting-started", + packages: [ + models.moonshotLlama7bChat, + ], + collectInputFor: [ + { + inputType: "text", + key: "apiKey", + label: "API Key", + placeholder: "Enter your Moonshot API key", + required: true, + }, + ...completionParamsInputsConfigs, + ], + }, azure: { title: "Azure OpenAI", provider: "azure", diff --git a/packages/openai-adapters/src/apis/Moonshot.ts b/packages/openai-adapters/src/apis/Moonshot.ts new file mode 100644 index 000000000..eb11124f0 --- /dev/null +++ b/packages/openai-adapters/src/apis/Moonshot.ts @@ -0,0 +1,63 @@ +import { streamSse } from "@continuedev/fetch"; +import fetch from "node-fetch"; +import { ChatCompletionChunk } from "openai/resources/index.mjs"; +import { LlmApiConfig } from "../index.js"; +import { OpenAIApi } from "./OpenAI.js"; +import { FimCreateParamsStreaming } from "./base.js"; + +export class MoonshotApi extends OpenAIApi { + constructor(config: LlmApiConfig) { + super(config); + this.apiBase = "https://api.moonshot.cn/"; + } + + async *fimStream( + body: FimCreateParamsStreaming, + ): AsyncGenerator { + const endpoint = new URL("v1/chat/completions", this.apiBase); + const resp = await fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + model: body.model, + messages: [ + { + role: "user", + content: body.prompt + "[fill]" + body.suffix, + }, + ], + max_tokens: body.max_tokens, + temperature: body.temperature, + top_p: body.top_p, + frequency_penalty: body.frequency_penalty, + presence_penalty: body.presence_penalty, + stop: body.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.config.apiKey}`, + }, + }); + + for await (const chunk of streamSse(resp as any)) { + yield { + choices: [ + { + delta: { + content: chunk.choices[0].delta.content, + role: "assistant", + }, + finish_reason: chunk.finish_reason, + index: 0, + logprobs: null, + }, + ], + created: Date.now(), + id: "", + model: body.model, + object: "chat.completion.chunk", + }; + } + } +} diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index f782f1c78..4856a7b11 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -6,6 +6,7 @@ import { CohereApi } from "./apis/Cohere.js"; import { DeepSeekApi } from "./apis/DeepSeek.js"; import { GeminiApi } from "./apis/Gemini.js"; import { JinaApi } from "./apis/Jina.js"; +import { MoonshotApi } from "./apis/Moonshot.js"; import { OpenAIApi } from "./apis/OpenAI.js"; dotenv.config(); @@ -48,6 +49,8 @@ export function constructLlmApi(config: LlmApiConfig): BaseLlmApi { }); case "deepseek": return new DeepSeekApi(config); + case "moonshot": + return new MoonshotApi(config); case "groq": return new OpenAIApi({ ...config, From f52fbca1d5e09982db1a5040ebd928af7730a92c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 20:29:19 -0800 Subject: [PATCH 36/82] docs indexing on more --- core/core.ts | 47 +-- core/index.d.ts | 24 +- core/indexing/IndexingStatusManager.ts | 93 ----- core/indexing/docs/DocsService.ts | 328 +++++++++++------- core/protocol/core.ts | 11 +- core/protocol/passThrough.ts | 2 +- core/protocol/webview.ts | 4 +- extensions/vscode/config_schema.json | 2 +- gui/src/components/Footer.tsx | 71 ++-- .../indexing/FooterIndexingPeeks.tsx | 80 +++++ .../components/indexing/IndexingStatus.tsx | 135 +++++++ .../components/indexing/IndexingStatuses.tsx | 50 +++ gui/src/components/indexing/utils.ts | 17 + gui/src/hooks/useSetup.ts | 21 +- gui/src/index.css | 19 + gui/src/pages/More/More.tsx | 4 + gui/src/redux/slices/stateSlice.ts | 16 +- 17 files changed, 620 insertions(+), 304 deletions(-) delete mode 100644 core/indexing/IndexingStatusManager.ts create mode 100644 gui/src/components/indexing/FooterIndexingPeeks.tsx create mode 100644 gui/src/components/indexing/IndexingStatus.tsx create mode 100644 gui/src/components/indexing/IndexingStatuses.tsx create mode 100644 gui/src/components/indexing/utils.ts diff --git a/core/core.ts b/core/core.ts index ab71ab4d7..823607814 100644 --- a/core/core.ts +++ b/core/core.ts @@ -35,7 +35,6 @@ import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./util/messenger"; -import { IndexingStatusManager } from "./indexing/IndexingStatusManager"; export class Core { // implements IMessenger @@ -45,7 +44,6 @@ export class Core { continueServerClientPromise: Promise; codebaseIndexingState: IndexingProgressUpdate; controlPlaneClient: ControlPlaneClient; - private indexingManager: IndexingStatusManager; private docsService: DocsService; private globalContext = new GlobalContext(); @@ -110,15 +108,10 @@ export class Core { this.controlPlaneClient, ); - this.indexingManager = IndexingStatusManager.createSingleton( - this.messenger, - ); - this.docsService = DocsService.createSingleton( this.configHandler, this.ide, this.messenger, - this.indexingManager, ); this.configHandler.onConfigUpdate( @@ -292,7 +285,7 @@ export class Core { }); on("context/indexDocs", async (msg) => { - await this.docsService.indexAllDocsWithPrompt(msg.data.reIndex); + await this.docsService.syncOrReindexAllDocsWithPrompt(msg.data.reIndex); }); on("context/loadSubmenuItems", async (msg) => { @@ -671,6 +664,8 @@ export class Core { const rows = await DevDataSqliteDb.getTokensPerModel(); return rows; }); + + // Codebase indexing on("index/forceReIndex", async ({ data }) => { if (data?.shouldClearIndexes) { const codebaseIndexer = await this.codebaseIndexerPromise; @@ -700,6 +695,27 @@ export class Core { } }); + // Docs, etc. indexing + on("indexing/reindex", async (msg) => { + if (msg.data.type === "docs") { + void this.docsService.reindexDoc(msg.data.id); + } + }); + on("indexing/abort", async (msg) => { + if (msg.data.type === "docs") { + this.docsService.abort(msg.data.id); + } + }); + on("indexing/setPaused", async (msg) => { + if (msg.data.type === "docs") { + this.docsService.setPaused(msg.data.id, msg.data.paused); + } + }); + on("indexing/initStatuses", async (msg) => { + return this.docsService.initStatuses(); + }); + // + on("didChangeSelectedProfile", (msg) => { void this.configHandler.setSelectedProfile(msg.data.id); void this.configHandler.reloadConfig(); @@ -720,19 +736,6 @@ export class Core { recentlyEditedFilesCache.set(filepath, filepath); } }); - - on("indexing/reindex", async (msg) => { - this.indexingManager.reindex(msg.data.identifier); - }); - on("indexing/abort", async (msg) => { - this.indexingManager.abort(msg.data.identifier); - }); - on("indexing/setPaused", async (msg) => { - this.indexingManager.setPaused(msg.data.identifier, msg.data.pause); - }); - on("indexing/getStatuses", async (msg) => { - return this.indexingManager.statuses; - }); } private indexingCancellationController: AbortController | undefined; @@ -803,7 +806,7 @@ export class Core { } void this.messenger.request("indexProgress", updateToSend); - this.indexingState = updateToSend; + this.codebaseIndexingState = updateToSend; if (update.status === "failed") { void this.sendIndexingErrorTelemetry(update); diff --git a/core/index.d.ts b/core/index.d.ts index 53ca6ae42..32685b79a 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -46,26 +46,28 @@ export interface IndexingProgressUpdate { } // This is more or less a V2 of IndexingProgressUpdate -export interface IndexingStatusUpdate { +export interface IndexingStatus { id: string; type: "docs"; progress: number; description: string; - status: "indexing" | "complete" | "paused" | "failed" | "aborted" | "deleted"; + status: + | "indexing" + | "complete" + | "paused" + | "failed" + | "aborted" + | "deleted" + | "pending"; embeddingsProviderId: string; isReindexing?: boolean; debugInfo?: string; + title: string; + icon?: string; + url?: string; } -interface IndexIdentifier { - type: string; - id: string; -} - -export type IndexingStatusMap = Map< - string, - Map ->; +export type IndexingStatusMap = Map; export type PromptTemplateFunction = ( history: ChatMessage[], diff --git a/core/indexing/IndexingStatusManager.ts b/core/indexing/IndexingStatusManager.ts deleted file mode 100644 index 785f14b95..000000000 --- a/core/indexing/IndexingStatusManager.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { IndexIdentifier, IndexingStatusMap, IndexingStatusUpdate } from ".."; -import { FromCoreProtocol, ToCoreProtocol } from "../protocol"; -import { IMessenger } from "../util/messenger"; - -/* - Any service that sends indexing updates can use an instance of this class - 1. Pass indexingManager to the service - 2. Register the service with the manager using `registerService` - E.g. docs uses startUrl as id - 3. Rules of engagement: - - service is responsible for checking corrupted indexes - don't check paused or deleted -*/ -export class IndexingStatusManager { - private readonly messenger: IMessenger; - readonly statuses: IndexingStatusMap = new Map(); - private readonly reindexTypeFunctions: Map< - string, - (id: string) => Promise - > = new Map(); - - constructor(messenger: IMessenger) { - this.messenger = messenger; - } - - private static instance?: IndexingStatusManager; - static createSingleton( - messenger: IMessenger, - ) { - const instance = new IndexingStatusManager(messenger); - IndexingStatusManager.instance = instance; - return instance; - } - - static getSingleton() { - return IndexingStatusManager.instance; - } - - // Services that use an instance of this class should add their reindex functions here - registerService(type: string, fn: (id: string) => Promise) { - this.reindexTypeFunctions.set(type, fn); - this.statuses.set(type, new Map()); - } - - reindex({ type, id }: IndexIdentifier) { - const reindexFn = this.reindexTypeFunctions.get(type); - if (reindexFn) { - void reindexFn(id); - } - } - - handleUpdate(status: IndexingStatusUpdate) { - const byType = this.statuses.get(status.type); - if (byType) { - byType.set(status.id, status); - this.messenger.send("indexing/statusUpdate", status); - } - } - - delete({ type, id }: IndexIdentifier) { - const status = this.statuses.get(type)?.get(id); - if (status) { - this.handleUpdate({ ...status, status: "deleted" }); - } - } - - abort({ type, id }: IndexIdentifier) { - const status = this.statuses.get(type)?.get(id); - if (status) { - this.handleUpdate({ ...status, status: "aborted" }); - } - } - - isAborted({ type, id }: IndexIdentifier) { - const status = this.statuses.get(type)?.get(id); - if (status) { - return status.status === "aborted"; - } - } - - setPaused({ type, id }: IndexIdentifier, pause: boolean) { - const status = this.statuses.get(type)?.get(id); - if (status) { - this.handleUpdate({ ...status, status: pause ? "paused" : "indexing" }); - } - } - - isPaused({ type, id }: IndexIdentifier) { - const status = this.statuses.get(type)?.get(id); - if (status) { - return status.status === "paused"; - } - } -} diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 25f465be4..7c163667b 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -7,7 +7,8 @@ import { ContinueConfig, EmbeddingsProvider, IDE, - IndexingStatusUpdate, + IndexingStatusMap, + IndexingStatus, SiteIndexingConfig, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; @@ -24,7 +25,6 @@ import { } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider"; -import { IndexingStatusManager } from "../IndexingStatusManager"; import { Article, chunkArticle, pageToArticle } from "./article"; import DocsCrawler from "./DocsCrawler"; @@ -100,7 +100,6 @@ export default class DocsService { configHandler: ConfigHandler, private readonly ide: IDE, private readonly messenger?: IMessenger, - private readonly indexingManager?: IndexingStatusManager, ) { this.isInitialized = this.init(configHandler); } @@ -111,14 +110,8 @@ export default class DocsService { configHandler: ConfigHandler, ide: IDE, messenger?: IMessenger, - indexingManager?: IndexingStatusManager, ) { - const docsService = new DocsService( - configHandler, - ide, - messenger, - indexingManager, - ); + const docsService = new DocsService(configHandler, ide, messenger); DocsService.instance = docsService; return docsService; } @@ -129,26 +122,46 @@ export default class DocsService { // Initialization - load config and attach config listener private async init(configHandler: ConfigHandler) { - this.indexingManager?.registerService( - DocsService.indexingType, - this.reindexDoc, - ); const config = await configHandler.loadConfig(); - this.config = config; - - // On first go we want to have an indexing status for all docs - // Since config handler will only trigger indexing status updates on changes - if (config.docs?.length) { - for (const doc of config.docs) { - await this.indexAndAdd(doc); - } - } - await this.handleConfigUpdate({ config }); configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this)); } - // Config + readonly statuses: IndexingStatusMap = new Map(); + + handleStatusUpdate(update: IndexingStatus) { + this.statuses.set(update.id, update); + this.messenger?.send("indexing/statusUpdate", update); + } + + abort(startUrl: string) { + const status = this.statuses.get(startUrl); + if (status) { + this.handleStatusUpdate({ + ...status, + status: "aborted", + }); + } + } + + isAborted(startUrl: string) { + return this.statuses.get(startUrl)?.status === "aborted"; + } + + // Pausing not supported for docs yet + // setPaused(startUrl: string, pause: boolean) { + // const status = this.statuses.get(startUrl); + // if (status) { + // this.handleStatusUpdate({ + // ...status, + // status: pause ? "paused" : "indexing", + // }); + // } + // } + + // isPaused(startUrl: string) { + // return this.statuses.get(startUrl)?.status === "paused"; + // } /* * Currently, we generate and host embeddings for pre-indexed docs using transformers. @@ -183,8 +196,6 @@ export default class DocsService { return this.config.embeddingsProvider; } - // Expose this so that docs provider can check it - private async handleConfigUpdate({ config: newConfig, }: { @@ -203,27 +214,49 @@ export default class DocsService { return; } - // On embeddings provider change, reindex all non-preindexed docs - // change = doesn't match last successful embeddings provider - const curEmbeddingsProviderId = this.globalContext.get( - "curEmbeddingsProviderId", - ); - if ( - !curEmbeddingsProviderId || - curEmbeddingsProviderId !== newConfig.embeddingsProvider.id - ) { - // If not set, we're initializing - const currentDocs = await this.listMetadata(); - if (currentDocs.length > 0) { - await this.reindexDocsOnNewEmbeddingsProvider(); - return; - } - } - - await this.syncDocsOnConfigUpdate(oldConfig, newConfig); + await this.syncOrReindexAllDocs(newConfig, oldConfig); } } + private async syncOrReindexAllDocs( + newConfig: ContinueConfig, + oldConfig?: ContinueConfig, + ) { + // On embeddings provider change, reindex all non-preindexed docs + // change = doesn't match last successful embeddings provider + const curEmbeddingsProviderId = this.globalContext.get( + "curEmbeddingsProviderId", + ); + if ( + !curEmbeddingsProviderId || + curEmbeddingsProviderId !== newConfig.embeddingsProvider.id + ) { + // If not set, we're initializing + const currentDocs = await this.listMetadata(); + if (currentDocs.length > 0) { + await this.reindexDocsOnNewEmbeddingsProvider(); + return; + } + } + + await this.syncDocsOnConfigUpdate(oldConfig, newConfig); + } + + async syncOrReindexAllDocsWithPrompt(reIndex: boolean = false) { + if (!this.hasDocsContextProvider()) { + const didAddDocsContextProvider = + await this.showAddDocsContextProviderToast(); + + if (!didAddDocsContextProvider) { + return; + } + } + + await this.syncOrReindexAllDocs(this.config); + + void this.ide.showToast("info", "Docs indexing completed"); + } + async hasMetadata(startUrl: string): Promise> { const db = await this.getOrCreateSqliteDb(); const title = await db.get( @@ -234,16 +267,6 @@ export default class DocsService { return !!title; } - // private async hasIndexedDoc(startUrl: string) { - // const db = await this.getOrCreateSqliteDb(); - // const docs = await db.all( - // `SELECT startUrl FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, - // startUrl, - // ); - - // return docs.length > 0; - // } - async showAddDocsContextProviderToast() { const actionMsg = "Add 'docs' context provider"; const res = await this.ide.showToast( @@ -267,25 +290,6 @@ export default class DocsService { return res === actionMsg; } - async indexAllDocsWithPrompt(reIndex: boolean = false) { - if (!this.hasDocsContextProvider()) { - const didAddDocsContextProvider = - await this.showAddDocsContextProviderToast(); - - if (!didAddDocsContextProvider) { - return; - } - } - - const docs = await this.listMetadata(); - - for (const doc of docs) { - await this.indexAndAdd(doc, reIndex); - } - - void this.ide.showToast("info", "Docs indexing completed"); - } - async listMetadata() { const db = await this.getOrCreateSqliteDb(); const docs = await db.all( @@ -295,10 +299,6 @@ export default class DocsService { return docs; } - updateIndexingStatus(update: IndexingStatusUpdate) { - this.indexingManager?.handleUpdate(update); - } - async reindexDoc(startUrl: string) { const docConfig = this.config.docs?.find( (doc) => doc.startUrl === startUrl, @@ -323,36 +323,53 @@ export default class DocsService { const indexExists = await this.hasMetadata(startUrl); const fixedStatus: Pick< - IndexingStatusUpdate, - "type" | "id" | "embeddingsProviderId" | "isReindexing" + IndexingStatus, + | "type" + | "id" + | "embeddingsProviderId" + | "isReindexing" + | "debugInfo" + | "icon" + | "url" + | "title" > = { type: "docs", id: siteIndexingConfig.startUrl, embeddingsProviderId: embeddingsProvider.id, isReindexing: reIndex && indexExists, + title: siteIndexingConfig.title, + debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`, + icon: siteIndexingConfig.faviconUrl, + url: siteIndexingConfig.startUrl, }; - if (indexExists && !reIndex) { - this.updateIndexingStatus({ - ...fixedStatus, - progress: 1, - description: "Complete", - status: "complete", - debugInfo: "Already indexed", - }); - return; + if (indexExists) { + if (reIndex) { + await this.deleteIndexes(startUrl); + } else { + this.handleStatusUpdate({ + ...fixedStatus, + progress: 1, + description: "Complete", + status: "complete", + debugInfo: "Already indexed", + }); + return; + } } // Mark the site as currently being indexed this.docsIndexingQueue.add(startUrl); try { - this.updateIndexingStatus({ + this.handleStatusUpdate({ ...fixedStatus, status: "indexing", description: "Finding subpages", progress: 0, }); + // NOTE - during "indexing" phase, check if aborted before each status update + const articles: Article[] = []; let processedPages = 0; let maxKnownPages = 1; @@ -372,7 +389,10 @@ export default class DocsService { // Use a heuristic approach for progress calculation const progress = Math.min(processedPages / maxKnownPages, 1); - this.updateIndexingStatus({ + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ ...fixedStatus, description: `Finding subpages (${page.path})`, status: "indexing", @@ -399,7 +419,11 @@ export default class DocsService { for (let i = 0; i < articles.length; i++) { const article = articles[i]; - this.updateIndexingStatus({ + + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ ...fixedStatus, status: "indexing", description: `Creating Embeddings: ${article.subpath}`, @@ -433,7 +457,10 @@ export default class DocsService { `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, ); - this.updateIndexingStatus({ + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ ...fixedStatus, description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, status: "failed", @@ -450,21 +477,34 @@ export default class DocsService { // Add docs to databases console.log(`Adding ${embeddings.length} embeddings to db`); - this.updateIndexingStatus({ + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ ...fixedStatus, - description: `Adding ${embeddings.length} embeddings to db`, + description: "Deleting old embeddings from the db", status: "indexing", progress: 0.5, }); // Delete indexed docs if re-indexing - if (reIndex && (await this.hasMetadata(startUrl.toString()))) { + if (reIndex && indexExists) { console.log("Deleting old embeddings"); - await this.delete(startUrl); + await this.deleteIndexes(startUrl); } const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ + ...fixedStatus, + description: `Adding ${embeddings.length} embeddings to db`, + status: "indexing", + progress: 0.5, + }); + await this.add({ siteIndexingConfig, chunks, @@ -474,7 +514,10 @@ export default class DocsService { this.docsIndexingQueue.delete(startUrl); - this.updateIndexingStatus({ + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ ...fixedStatus, description: "Complete", status: "complete", @@ -488,7 +531,7 @@ export default class DocsService { } } catch (e) { console.error("Error indexing docs", e); - this.updateIndexingStatus({ + this.handleStatusUpdate({ ...fixedStatus, description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, status: "failed", @@ -499,6 +542,31 @@ export default class DocsService { } } + // Function for GUI to retrieve initial pending statuses + // And kickoff indexing where needed + async initStatuses() { + this.config?.docs?.forEach(async (doc) => { + const currentStatus = this.statuses.get(doc.startUrl); + if (currentStatus) { + this.handleStatusUpdate(currentStatus); + } else { + this.handleStatusUpdate({ + type: "docs", + id: doc.startUrl, + embeddingsProviderId: this.config.embeddingsProvider.id, + isReindexing: false, + progress: 0, + description: "Pending", + status: "pending", + title: doc.title, + debugInfo: `max depth: ${doc.maxDepth}`, + icon: doc.faviconUrl, + url: doc.startUrl, + }); + } + }); + } + // Retrieve docs embeds based on user input async retrieveChunksFromQuery( query: string, @@ -638,10 +706,6 @@ export default class DocsService { const currentlyIndexedDocs = await this.listMetadata(); const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); - // const newDocs = newConfigDocs.filter( - // (doc) => !currentStartUrls.includes(doc.startUrl), - // ); - // Anything found in sqlite but not in new config should be deleted const deletedDocs = currentlyIndexedDocs.filter( (doc) => @@ -668,13 +732,30 @@ export default class DocsService { oldConfigDoc.faviconUrl !== doc.faviconUrl) ) { changedDocs.push(doc); + } else { + // if get's here, not changed, no update needed, mark as complete + this.handleStatusUpdate({ + type: "docs", + id: doc.startUrl, + embeddingsProviderId: this.config.embeddingsProvider.id, + isReindexing: false, + title: doc.title, + debugInfo: "Config sync: not changed", + icon: doc.faviconUrl, + url: doc.startUrl, + progress: 1, + description: "Complete", + status: "complete", + }); } - // if get's here, not changed, no update needed } else { newDocs.push(doc); } } + // Sends "Pending" or current status for each + await this.initStatuses(); + for (const doc of changedDocs) { console.log(`Updating indexed doc: ${doc.startUrl}`); await this.indexAndAdd(doc, true); @@ -688,7 +769,7 @@ export default class DocsService { } for (const doc of deletedDocs) { - await this.delete(doc.startUrl); + await this.deleteIndexes(doc.startUrl); } } catch (e) { console.error("Error syncing docs index on config update", e); @@ -852,7 +933,7 @@ export default class DocsService { } } - // Delete methods for individual docs + // Delete methods private async deleteEmbeddingsFromLance(startUrl: string) { for (const tableName of this.lanceTableNamesSet) { const conn = await lancedb.connect(getLanceDbPath()); @@ -870,20 +951,31 @@ export default class DocsService { } private deleteFromConfig(startUrl: string) { - editConfigJson((config) => ({ - ...config, - docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [], - })); + const doesDocExist = this.config.docs?.some( + (doc) => doc.startUrl === startUrl, + ); + if (doesDocExist) { + editConfigJson((config) => ({ + ...config, + docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [], + })); + } + } + + async deleteIndexes(startUrl: string) { + await this.deleteEmbeddingsFromLance(startUrl); + await this.deleteMetadataFromSqlite(startUrl); } async delete(startUrl: string) { - await this.deleteEmbeddingsFromLance(startUrl); - await this.deleteMetadataFromSqlite(startUrl); + await this.deleteIndexes(startUrl); this.deleteFromConfig(startUrl); - if (this.messenger) { - this.messenger.send("refreshSubmenuItems", undefined); + const status = this.statuses.get(startUrl); + if (status) { + this.handleStatusUpdate({ ...status, status: "deleted" }); } + this.messenger?.send("refreshSubmenuItems", undefined); } // When user requests a pre-indexed doc for the first time @@ -934,13 +1026,9 @@ export default class DocsService { console.log( `Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.id}`, ); - + await this.initStatuses(); for (const doc of docs) { - await this.delete(doc.startUrl); - } - - for (const doc of docs) { - await this.indexAndAdd(doc); + await this.indexAndAdd(doc, true); } // Important that this only is invoked after we have successfully diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 65a798c55..f6c849963 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -8,7 +8,6 @@ import type { ContextSubmenuItem, DiffLine, IdeSettings, - IndexIdentifier, IndexingStatusMap, LLMFullCompletionOptions, MessageContent, @@ -160,11 +159,11 @@ export type ToCoreFromIdeOrWebviewProtocol = { void, ]; - // Docs Indexing. TODO move codebase to this - "indexing/reindex": [{ identifier: IndexIdentifier }, void]; - "indexing/abort": [{ identifier: IndexIdentifier }, void]; - "indexing/setPaused": [{ identifier: IndexIdentifier; pause: boolean }, void]; - "indexing/getStatuses": [undefined, IndexingStatusMap]; + // Docs etc. Indexing. TODO move codebase to this + "indexing/reindex": [{ type: string; id: string }, void]; + "indexing/abort": [{ type: string; id: string }, void]; + "indexing/setPaused": [{ type: string; id: string; paused: boolean }, void]; + "indexing/initStatuses": [undefined, void]; addAutocompleteModel: [{ model: ModelDescription }, void]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 1997b8700..71e35fe65 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -45,7 +45,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "index/forceReIndexFiles", "index/indexingProgressBarInitialized", // Docs, etc. - "indexing/getStatuses", + "indexing/initStatuses", "indexing/reindex", "indexing/abort", "indexing/setPaused", diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index e5330d81f..d259fde9e 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -3,7 +3,7 @@ import { ConfigValidationError } from "../config/validation.js"; import type { ContextItemWithId, IndexingProgressUpdate, - IndexingStatusUpdate, + IndexingStatus, } from "../index.js"; export type ToWebviewFromIdeOrCoreProtocol = { @@ -11,7 +11,7 @@ export type ToWebviewFromIdeOrCoreProtocol = { configError: [ConfigValidationError[] | undefined, void]; getDefaultModelTitle: [undefined, string]; indexProgress: [IndexingProgressUpdate, void]; // Codebase - "indexing/statusUpdate": [IndexingStatusUpdate, void]; // Docs, etc. + "indexing/statusUpdate": [IndexingStatus, void]; // Docs, etc. refreshSubmenuItems: [undefined, void]; isContinueInputFocused: [undefined, boolean]; addContextItem: [ diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index eb75d1f90..76d27bec2 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2325,7 +2325,7 @@ "type": "integer", "description": "The maximum depth to crawl the documentation site" }, - "favicon": { + "faviconUrl": { "type": "string", "description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL" } diff --git a/gui/src/components/Footer.tsx b/gui/src/components/Footer.tsx index 0c094155c..bf51abc0f 100644 --- a/gui/src/components/Footer.tsx +++ b/gui/src/components/Footer.tsx @@ -14,6 +14,7 @@ import { ROUTES } from "../util/navigation"; import HeaderButtonWithToolTip from "./gui/HeaderButtonWithToolTip"; import FreeTrialProgressBar from "./loaders/FreeTrialProgressBar"; import ProfileSwitcher from "./ProfileSwitcher"; +import FooterIndexingPeeks from "./indexing/FooterIndexingPeeks"; function Footer() { const navigate = useNavigate(); @@ -47,45 +48,49 @@ function Footer() { } return ( -
-
- - {defaultModel?.provider === "free-trial" && ( - - )} -
+ <> + + +
+
+ + {defaultModel?.provider === "free-trial" && ( + + )} +
+ +
+ {configError && ( + + + + )} -
- {configError && ( - + - )} - - - - - - - -
-
+ + + +
+ + ); } diff --git a/gui/src/components/indexing/FooterIndexingPeeks.tsx b/gui/src/components/indexing/FooterIndexingPeeks.tsx new file mode 100644 index 000000000..c95e8db7d --- /dev/null +++ b/gui/src/components/indexing/FooterIndexingPeeks.tsx @@ -0,0 +1,80 @@ +import { useDispatch, useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; + +import { IndexingStatus } from "core"; +import { useContext, useMemo } from "react"; +import { STATUS_TO_ICON } from "./utils"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; + +interface IndexingStatusViewerProps { + status: IndexingStatus; +} + +function FooterIndexingPeek({ status }: IndexingStatusViewerProps) { + const ideMessenger = useContext(IdeMessengerContext); + + const progressPercentage = useMemo(() => { + return Math.min(100, Math.max(0, status.progress * 100)); + }, [status.progress]); + + const Icon = STATUS_TO_ICON[status.status]; + + return ( +
+
{ + if (status.url) { + ideMessenger.post("openUrl", status.url); + } + }} + > + {status.icon ? ( + doc icon + ) : null} +

+ {status.title ?? status.id} +

+
+
+
+
+
+ {progressPercentage.toFixed(0)}% + {Icon ? ( + + ) : null} +
+
+ ); +} + +function FooterIndexingPeeks() { + const indexingStatuses = useSelector( + (store: RootState) => store.state.indexingStatuses, + ); + const currentlyIndexingDocs = useMemo(() => { + return Object.values(indexingStatuses).filter( + (status) => status.status === "indexing", + ); + }, [indexingStatuses]); + + return ( + <> + {currentlyIndexingDocs.map((status) => { + return ; + })} + + ); +} + +export default FooterIndexingPeeks; diff --git a/gui/src/components/indexing/IndexingStatus.tsx b/gui/src/components/indexing/IndexingStatus.tsx new file mode 100644 index 000000000..eb53fd794 --- /dev/null +++ b/gui/src/components/indexing/IndexingStatus.tsx @@ -0,0 +1,135 @@ +import { IndexingStatus } from "core"; +import { PropsWithChildren, useContext, useMemo } from "react"; +import { useDispatch } from "react-redux"; +import { usePostHog } from "posthog-js/react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { + ArrowPathIcon, + CheckCircleIcon, + PauseCircleIcon, + XMarkIcon, +} from "@heroicons/react/24/outline"; + +interface IndexingStatusViewerProps { + status: IndexingStatus; +} + +const STATUS_TO_ICON: Record = { + indexing: ArrowPathIcon, + paused: PauseCircleIcon, + complete: CheckCircleIcon, + aborted: null, + deleted: null, + pending: null, + failed: XMarkIcon, // Since we show an erorr message below +}; + +function IndexingStatusViewer({ status }: IndexingStatusViewerProps) { + const ideMessenger = useContext(IdeMessengerContext); + const posthog = usePostHog(); + + const reIndex = () => + ideMessenger.post("indexing/reindex", { + type: status.type, + id: status.id, + }); + + const abort = () => + ideMessenger.post("indexing/abort", { + type: status.type, + id: status.id, + }); + + const progressPercentage = useMemo(() => { + return Math.min(100, Math.max(0, status.progress * 100)); + }, [status.progress]); + + const Icon = STATUS_TO_ICON[status.status]; + + return ( +
+ {/* {`${status.type} - ${status.id} - ${status.status} - ${status.progress} - ${status.description} - ${status.icon}`} */} +
+
{ + if (status.url) { + ideMessenger.post("openUrl", status.url); + } + }} + > + {status.icon ? ( + doc icon + ) : null} +

+ {status.title ?? status.id} +

+
+ {status.status === "pending" ? ( +
Pending...
+ ) : ( +
+ {progressPercentage.toFixed(0)}% + {Icon ? ( + + ) : null} +
+ )} +
+ +
+
+
+ +
+ {}, + deleted: () => {}, + pending: () => {}, + }[status.status] + } + > + { + { + complete: "Click to re-index", + indexing: "Cancel indexing", + failed: "Click to retry", + aborted: "Click to index", + paused: "", + deleted: "", + pending: "", + }[status.status] + } + + + {status.status === "indexing" && ( + + {status.description} + + )} +
+
+ ); +} + +export default IndexingStatusViewer; diff --git a/gui/src/components/indexing/IndexingStatuses.tsx b/gui/src/components/indexing/IndexingStatuses.tsx new file mode 100644 index 000000000..bd7a61f44 --- /dev/null +++ b/gui/src/components/indexing/IndexingStatuses.tsx @@ -0,0 +1,50 @@ +import { useMemo } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; +import IndexingStatusViewer from "./IndexingStatus"; +import { Button } from ".."; +import { + setDialogMessage, + setShowDialog, +} from "../../redux/slices/uiStateSlice"; +import AddDocsDialog from "../dialogs/AddDocsDialog"; + +function IndexingStatuses() { + const indexingStatuses = useSelector( + (store: RootState) => store.state.indexingStatuses, + ); + const docsStatuses = useMemo(() => { + const docs = Object.values(indexingStatuses).filter( + (status) => status.type === "docs" && status.status !== "deleted", + ); + + return []; + return docs; + }, [indexingStatuses]); + const dispatch = useDispatch(); + + return ( +
+

@docs indexes

+ + Manage your documentation sources + + {docsStatuses.length ? ( + docsStatuses.map((status) => { + return ; + }) + ) : ( + + )} +
+ ); +} + +export default IndexingStatuses; diff --git a/gui/src/components/indexing/utils.ts b/gui/src/components/indexing/utils.ts new file mode 100644 index 000000000..350f5008e --- /dev/null +++ b/gui/src/components/indexing/utils.ts @@ -0,0 +1,17 @@ +import { + ArrowPathIcon, + CheckCircleIcon, + PauseCircleIcon, + XMarkIcon, +} from "@heroicons/react/24/outline"; +import { IndexingStatus } from "core"; + +export const STATUS_TO_ICON: Record = { + indexing: ArrowPathIcon, + paused: PauseCircleIcon, + complete: CheckCircleIcon, + aborted: null, + deleted: null, + pending: null, + failed: null, // XMarkIcon, // Since we show an error message below +}; diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 49a6d429f..4bdfdd8bf 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -11,6 +11,7 @@ import { setInactive, setSelectedProfileId, setTTSActive, + updateIndexingStatus, } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; @@ -50,14 +51,20 @@ function useSetup(dispatch: Dispatch) { loadConfig(); const interval = setInterval(() => { if (initialConfigLoad.current) { + // This triggers sending pending status to the GUI for relevant docs indexes clearInterval(interval); + ideMessenger.post("indexing/initStatuses", undefined); return; } loadConfig(); }, 2_000); return () => clearInterval(interval); - }, [initialConfigLoad, loadConfig]); + }, [initialConfigLoad, loadConfig, ideMessenger]); + + useWebviewListener("configUpdate", async () => { + await loadConfig(); + }); useEffect(() => { // Override persisted state @@ -110,10 +117,6 @@ function useSetup(dispatch: Dispatch) { }); }); - useWebviewListener("configUpdate", async () => { - await loadConfig(); - }); - useWebviewListener("configError", async (error) => { dispatch(setConfigError(error)); }); @@ -136,13 +139,7 @@ function useSetup(dispatch: Dispatch) { }); useWebviewListener("indexing/statusUpdate", async (data) => { - console.log("Indexing status update", data); - // dispatch( - // addContextItemsAtIndex({ - // index: data.historyIndex, - // contextItems: [data.item], - // }), - // ); + dispatch(updateIndexingStatus(data)); }); useWebviewListener( diff --git a/gui/src/index.css b/gui/src/index.css index b1cde096f..554ce2faa 100644 --- a/gui/src/index.css +++ b/gui/src/index.css @@ -72,3 +72,22 @@ a:focus { -ms-overflow-style: none; /* IE and Edge */ scrollbar-width: none; /* Firefox */ } + +.lines { + /* white-space: pre-wrap; */ + word-break: break-word; + overflow: hidden; + line-height: 1.375; +} + +.lines-3 { + display: -webkit-box; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; +} + +.lines-1 { + display: -webkit-box; + -webkit-line-clamp: 1; + -webkit-box-orient: vertical; +} diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index 4824c9535..e743a3834 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -15,6 +15,7 @@ import { setOnboardingCard } from "../../redux/slices/uiStateSlice"; import useHistory from "../../hooks/useHistory"; import MoreHelpRow from "./MoreHelpRow"; import IndexingProgress from "./IndexingProgress"; +import IndexingStatuses from "../../components/indexing/IndexingStatuses"; function MorePage() { useNavigationListener(); @@ -50,6 +51,9 @@ function MorePage() {
+
+ +

Help center

diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 4222b4693..fa85427e5 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -3,17 +3,15 @@ import { JSONContent } from "@tiptap/react"; import { ChatHistoryItem, ChatMessage, - ContextItemId, ContextItemWithId, + IndexingStatus, PersistedSessionInfo, PromptLog, } from "core"; import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { stripImages } from "core/llm/images"; -import { createSelector } from "reselect"; import { v4 as uuidv4, v4 } from "uuid"; -import { RootState } from "../store"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -34,6 +32,7 @@ type State = { selectedProfileId: string; configError: ConfigValidationError[] | undefined; isInMultifileEdit: boolean; + indexingStatuses: { [id: string]: IndexingStatus }; }; const initialState: State = { @@ -61,6 +60,7 @@ const initialState: State = { defaultModelTitle: "GPT-4", selectedProfileId: "local", isInMultifileEdit: false, + indexingStatuses: {}, }; export const stateSlice = createSlice({ @@ -314,6 +314,15 @@ export const stateSlice = createSlice({ setIsInMultifileEdit: (state, action: PayloadAction) => { state.isInMultifileEdit = action.payload; }, + updateIndexingStatus: (state, action: PayloadAction) => { + console.log("update indexing status"); + state.indexingStatuses = { + ...state.indexingStatuses, + [action.payload.id]: action.payload, + }; + // consider only overwriting the one that changed + // depends on how watching + }, }, }); @@ -339,6 +348,7 @@ export const { deleteMessage, setIsGatheringContext, setIsInMultifileEdit, + updateIndexingStatus, } = stateSlice.actions; export default stateSlice.reducer; From 8e4c56ebea9e45a24ae3dcd85cfc0561289fadc6 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 21:52:02 -0800 Subject: [PATCH 37/82] chat peeks --- core/indexing/docs/DocsService.ts | 57 +++++++-------- gui/src/components/Footer.tsx | 71 +++++++++---------- ...ndexingPeeks.tsx => ChatIndexingPeeks.tsx} | 49 +++++++++---- .../components/indexing/IndexingStatus.tsx | 9 ++- .../components/indexing/IndexingStatuses.tsx | 1 - gui/src/pages/gui/Chat.tsx | 2 + 6 files changed, 107 insertions(+), 82 deletions(-) rename gui/src/components/indexing/{FooterIndexingPeeks.tsx => ChatIndexingPeeks.tsx} (58%) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 7c163667b..cc75c3835 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -37,6 +37,12 @@ import { } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; +// Progress heuristic values +// subpages -> embeddings -> delete from db -> add to db +const PROGRESS_AT_EMBEDDING = 0.5; +const PROGRESS_AT_DELETE_OPERATIONS = 0.7; +const PROGRESS_AT_ADD_OPERATIONS = 0.8; + // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { title: string; @@ -140,6 +146,8 @@ export default class DocsService { this.handleStatusUpdate({ ...status, status: "aborted", + progress: 0, + description: "Canceled", }); } } @@ -148,20 +156,20 @@ export default class DocsService { return this.statuses.get(startUrl)?.status === "aborted"; } - // Pausing not supported for docs yet - // setPaused(startUrl: string, pause: boolean) { - // const status = this.statuses.get(startUrl); - // if (status) { - // this.handleStatusUpdate({ - // ...status, - // status: pause ? "paused" : "indexing", - // }); - // } - // } + // NOTE Pausing not supported for docs yet + setPaused(startUrl: string, pause: boolean) { + const status = this.statuses.get(startUrl); + if (status) { + this.handleStatusUpdate({ + ...status, + status: pause ? "paused" : "indexing", + }); + } + } - // isPaused(startUrl: string) { - // return this.statuses.get(startUrl)?.status === "paused"; - // } + isPaused(startUrl: string) { + return this.statuses.get(startUrl)?.status === "paused"; + } /* * Currently, we generate and host embeddings for pre-indexed docs using transformers. @@ -372,11 +380,11 @@ export default class DocsService { const articles: Article[] = []; let processedPages = 0; - let maxKnownPages = 1; + let estimatedProgress = 0; // progress heuristic = sum series 1/(3*2^n) from n=0 to pages. Alternative e.g. sum 1/(2^n) // Crawl pages and retrieve info as articles for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { - processedPages++; + estimatedProgress += 1 / (3 * 2 ** processedPages); const article = pageToArticle(page); @@ -386,9 +394,6 @@ export default class DocsService { articles.push(article); - // Use a heuristic approach for progress calculation - const progress = Math.min(processedPages / maxKnownPages, 1); - if (this.isAborted(startUrl)) { return; } @@ -396,15 +401,11 @@ export default class DocsService { ...fixedStatus, description: `Finding subpages (${page.path})`, status: "indexing", - progress, // Yield the heuristic progress + progress: 0.4 * estimatedProgress, // 0% -> 40%, a heuristic approach for progress calculation }); - // Increase maxKnownPages to delay progress reaching 100% too soon - if (processedPages === maxKnownPages) { - maxKnownPages *= 2; - } - - await new Promise((resolve) => setTimeout(resolve, 50)); + processedPages++; + await new Promise((resolve) => setTimeout(resolve, 50)); // Locks down GUI if no sleeping } void Telemetry.capture("docs_pages_crawled", { @@ -427,7 +428,7 @@ export default class DocsService { ...fixedStatus, status: "indexing", description: `Creating Embeddings: ${article.subpath}`, - progress: i / articles.length, + progress: 0.4 + 0.4 * (i / articles.length), // 40% -> 80% }); try { @@ -484,7 +485,7 @@ export default class DocsService { ...fixedStatus, description: "Deleting old embeddings from the db", status: "indexing", - progress: 0.5, + progress: 0.8, }); // Delete indexed docs if re-indexing @@ -502,7 +503,7 @@ export default class DocsService { ...fixedStatus, description: `Adding ${embeddings.length} embeddings to db`, status: "indexing", - progress: 0.5, + progress: 0.85, }); await this.add({ diff --git a/gui/src/components/Footer.tsx b/gui/src/components/Footer.tsx index bf51abc0f..0c094155c 100644 --- a/gui/src/components/Footer.tsx +++ b/gui/src/components/Footer.tsx @@ -14,7 +14,6 @@ import { ROUTES } from "../util/navigation"; import HeaderButtonWithToolTip from "./gui/HeaderButtonWithToolTip"; import FreeTrialProgressBar from "./loaders/FreeTrialProgressBar"; import ProfileSwitcher from "./ProfileSwitcher"; -import FooterIndexingPeeks from "./indexing/FooterIndexingPeeks"; function Footer() { const navigate = useNavigate(); @@ -48,49 +47,45 @@ function Footer() { } return ( - <> - - -
-
- - {defaultModel?.provider === "free-trial" && ( - - )} -
- -
- {configError && ( - - - - )} +
+
+ + {defaultModel?.provider === "free-trial" && ( + + )} +
+
+ {configError && ( - + + )} - - - -
-
- + + + + + + + +
+
); } diff --git a/gui/src/components/indexing/FooterIndexingPeeks.tsx b/gui/src/components/indexing/ChatIndexingPeeks.tsx similarity index 58% rename from gui/src/components/indexing/FooterIndexingPeeks.tsx rename to gui/src/components/indexing/ChatIndexingPeeks.tsx index c95e8db7d..d5fffd138 100644 --- a/gui/src/components/indexing/FooterIndexingPeeks.tsx +++ b/gui/src/components/indexing/ChatIndexingPeeks.tsx @@ -2,9 +2,12 @@ import { useDispatch, useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import { IndexingStatus } from "core"; -import { useContext, useMemo } from "react"; +import { useContext, useMemo, useState } from "react"; import { STATUS_TO_ICON } from "./utils"; import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useNavigate } from "react-router-dom"; +import { XMarkIcon } from "@heroicons/react/24/outline"; +import { current } from "@reduxjs/toolkit"; interface IndexingStatusViewerProps { status: IndexingStatus; @@ -12,6 +15,7 @@ interface IndexingStatusViewerProps { function FooterIndexingPeek({ status }: IndexingStatusViewerProps) { const ideMessenger = useContext(IdeMessengerContext); + const navigate = useNavigate(); const progressPercentage = useMemo(() => { return Math.min(100, Math.max(0, status.progress * 100)); @@ -20,23 +24,33 @@ function FooterIndexingPeek({ status }: IndexingStatusViewerProps) { const Icon = STATUS_TO_ICON[status.status]; return ( -
+
{ + navigate("/more"); + }} + >
{ + onClick={(e) => { if (status.url) { ideMessenger.post("openUrl", status.url); + e.stopPropagation(); } }} > {status.icon ? ( - doc icon + icon ) : null} -

+

{status.title ?? status.id}

-
+
-
+
{progressPercentage.toFixed(0)}% {Icon ? ( ) : null}
+ {/* */}
); } -function FooterIndexingPeeks() { +function ChatIndexingPeeks() { const indexingStatuses = useSelector( (store: RootState) => store.state.indexingStatuses, ); + const [hidden, setHidden] = useState(false); const currentlyIndexingDocs = useMemo(() => { return Object.values(indexingStatuses).filter( (status) => status.status === "indexing", ); }, [indexingStatuses]); + if (!currentlyIndexingDocs.length) return null; + return ( - <> - {currentlyIndexingDocs.map((status) => { - return ; - })} - +
+

Indexing in progress

+ {hidden + ? null + : currentlyIndexingDocs.map((status) => { + return ; + })} +
); } -export default FooterIndexingPeeks; +export default ChatIndexingPeeks; diff --git a/gui/src/components/indexing/IndexingStatus.tsx b/gui/src/components/indexing/IndexingStatus.tsx index eb53fd794..bb4f1d546 100644 --- a/gui/src/components/indexing/IndexingStatus.tsx +++ b/gui/src/components/indexing/IndexingStatus.tsx @@ -9,6 +9,7 @@ import { PauseCircleIcon, XMarkIcon, } from "@heroicons/react/24/outline"; +import { updateIndexingStatus } from "../../redux/slices/stateSlice"; interface IndexingStatusViewerProps { status: IndexingStatus; @@ -27,6 +28,7 @@ const STATUS_TO_ICON: Record = { function IndexingStatusViewer({ status }: IndexingStatusViewerProps) { const ideMessenger = useContext(IdeMessengerContext); const posthog = usePostHog(); + const dispatch = useDispatch(); const reIndex = () => ideMessenger.post("indexing/reindex", { @@ -34,11 +36,16 @@ function IndexingStatusViewer({ status }: IndexingStatusViewerProps) { id: status.id, }); - const abort = () => + const abort = () => { ideMessenger.post("indexing/abort", { type: status.type, id: status.id, }); + // Optimistic abort status + dispatch( + updateIndexingStatus({ ...status, status: "aborted", progress: 0 }), + ); + }; const progressPercentage = useMemo(() => { return Math.min(100, Math.max(0, status.progress * 100)); diff --git a/gui/src/components/indexing/IndexingStatuses.tsx b/gui/src/components/indexing/IndexingStatuses.tsx index bd7a61f44..51f28ba9f 100644 --- a/gui/src/components/indexing/IndexingStatuses.tsx +++ b/gui/src/components/indexing/IndexingStatuses.tsx @@ -18,7 +18,6 @@ function IndexingStatuses() { (status) => status.type === "docs" && status.status !== "deleted", ); - return []; return docs; }, [indexingStatuses]); const dispatch = useDispatch(); diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 1cb6d66d6..366834ec6 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -62,6 +62,7 @@ import { } from "../../util"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; +import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks"; const StopButton = styled.div` background-color: ${vscBackground}; @@ -505,6 +506,7 @@ export function Chat() { )}
+ ); } From 93eddae58aea25283e24da6774caacf515788df1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 23:10:01 -0800 Subject: [PATCH 38/82] docs UI working --- core/indexing/docs/DocsService.ts | 21 +++--- gui/src/components/dialogs/AddDocsDialog.tsx | 69 ++++++++++++++++++- gui/src/components/dialogs/index.tsx | 2 +- .../components/indexing/ChatIndexingPeeks.tsx | 10 +-- .../components/indexing/IndexingStatus.tsx | 10 +-- .../components/indexing/IndexingStatuses.tsx | 11 ++- gui/src/pages/gui/Chat.tsx | 8 ++- 7 files changed, 101 insertions(+), 30 deletions(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index cc75c3835..ffb251c64 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -376,24 +376,15 @@ export default class DocsService { progress: 0, }); - // NOTE - during "indexing" phase, check if aborted before each status update - const articles: Article[] = []; let processedPages = 0; - let estimatedProgress = 0; // progress heuristic = sum series 1/(3*2^n) from n=0 to pages. Alternative e.g. sum 1/(2^n) + let estimatedProgress = 0; // progress heuristic = sum series 1/(2^n) from n=1 to pages + 1. Alternative e.g. sum 1/(2^n) // Crawl pages and retrieve info as articles for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { - estimatedProgress += 1 / (3 * 2 ** processedPages); - - const article = pageToArticle(page); - - if (!article) { - continue; - } - - articles.push(article); + estimatedProgress += 1 / 2 ** (processedPages + 1); + // NOTE - during "indexing" phase, check if aborted before each status update if (this.isAborted(startUrl)) { return; } @@ -404,6 +395,12 @@ export default class DocsService { progress: 0.4 * estimatedProgress, // 0% -> 40%, a heuristic approach for progress calculation }); + const article = pageToArticle(page); + if (!article) { + continue; + } + articles.push(article); + processedPages++; await new Promise((resolve) => setTimeout(resolve, 50)); // Locks down GUI if no sleeping } diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 3c97e09e6..f373f4bc0 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -1,11 +1,17 @@ -import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline"; +import { + CheckCircleIcon, + ChevronDownIcon, + ChevronUpIcon, +} from "@heroicons/react/24/outline"; import { SiteIndexingConfig } from "core"; import { usePostHog } from "posthog-js/react"; import { useContext, useLayoutEffect, useRef, useState } from "react"; -import { useDispatch } from "react-redux"; +import { useDispatch, useSelector } from "react-redux"; import { Button, HelperText, Input, lightGray } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { setShowDialog } from "../../redux/slices/uiStateSlice"; +import { RootState } from "../../redux/store"; +import IndexingStatusViewer from "../indexing/IndexingStatus"; function AddDocsDialog() { const posthog = usePostHog(); @@ -18,7 +24,12 @@ function AddDocsDialog() { const [faviconUrl, setFaviconUrl] = useState(""); const [isOpen, setIsOpen] = useState(false); + const [submittedConfig, setSubmittedConfig] = useState(); + const ideMessenger = useContext(IdeMessengerContext); + const indexingStatuses = useSelector( + (store: RootState) => store.state.indexingStatuses, + ); const isFormValid = startUrl && title; @@ -41,15 +52,67 @@ function AddDocsDialog() { ideMessenger.post("context/addDocs", siteIndexingConfig); + setSubmittedConfig(siteIndexingConfig); setTitle(""); setStartUrl(""); setFaviconUrl(""); - dispatch(setShowDialog(false)); + // dispatch(setShowDialog(false)); posthog.capture("add_docs_gui", { url: startUrl }); } + if (submittedConfig) { + const status = indexingStatuses[submittedConfig.startUrl]; + return ( +
+
+ +

{`Docs added`}

+
+
+

Title: {submittedConfig.title}

+

Start URL: {submittedConfig.startUrl}

+ {submittedConfig.rootUrl && ( +

Root URL: {submittedConfig.rootUrl}

+ )} + {submittedConfig.maxDepth && ( +

Max depth: {submittedConfig.maxDepth}

+ )} + {submittedConfig.faviconUrl && ( +

Favicon URL: {submittedConfig.faviconUrl}

+ )} +
+ {!!status && ( +
+

{`Type "@docs" and select ${submittedConfig.title} to reference these docs once indexing is complete. Check indexing status from the "More" page.`}

+
+ +
+
+ )} +
+ + +
+
+ ); + } + return (
diff --git a/gui/src/components/dialogs/index.tsx b/gui/src/components/dialogs/index.tsx index 33214fdfb..7685109ba 100644 --- a/gui/src/components/dialogs/index.tsx +++ b/gui/src/components/dialogs/index.tsx @@ -34,7 +34,6 @@ const DialogContainer = styled.div` top: 50%; left: 50%; transform: translate(-50%, -50%); - width: 75%; `; const Dialog = styled.div` @@ -72,6 +71,7 @@ const TextDialog = (props: TextDialogProps) => { return (
- +
+ +
); } From 356a4b67c0fc4988851fa2706571c8dfc59ca988 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 01:09:50 -0800 Subject: [PATCH 39/82] stream aborter --- gui/src/components/Layout.tsx | 1 + gui/src/hooks/useChatHandler.ts | 17 ++++++++++------- gui/src/hooks/useHistory.tsx | 2 +- gui/src/hooks/useSetup.ts | 1 + gui/src/redux/slices/stateSlice.ts | 12 ++++++++++-- 5 files changed, 23 insertions(+), 10 deletions(-) diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 42a1182e6..92dbdb4a6 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -21,6 +21,7 @@ import TextDialog from "./dialogs"; import Footer from "./Footer"; import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard"; import PostHogPageView from "./PosthogPageView"; +import { setInactive } from "../redux/slices/stateSlice"; const LayoutTopDiv = styled(CustomScrollbarDiv)` height: 100%; diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 229c03ebc..bf6836107 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -23,6 +23,7 @@ import resolveEditorContent, { import { IIdeMessenger } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { + abortStream, addPromptCompletionPair, clearLastResponse, initNewActiveMessage, @@ -51,6 +52,9 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const history = useSelector((store: RootState) => store.state.history); const active = useSelector((store: RootState) => store.state.active); + const streamAborter = useSelector( + (store: RootState) => store.state.streamAborter, + ); const activeRef = useRef(active); const { saveSession } = useHistory(dispatch); @@ -65,7 +69,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { }, [active]); async function _streamNormalInput(messages: ChatMessage[]) { - const abortController = new AbortController(); + const abortController = streamAborter ?? new AbortController(); const cancelToken = abortController.signal; try { @@ -133,9 +137,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { selectedCode: RangeInFile[], contextItems: ContextItemWithId[], ) { - const abortController = new AbortController(); - const cancelToken = abortController.signal; - if (!defaultModel) { throw new Error("Default model not defined"); } @@ -144,7 +145,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const checkActiveInterval = setInterval(() => { if (!activeRef.current) { - abortController.abort(); + dispatch(abortStream()); clearInterval(checkActiveInterval); } }, 100); @@ -164,7 +165,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { cancelToken, )) { if (!activeRef.current) { - abortController.abort(); + dispatch(abortStream()); break; } if (typeof update === "string") { @@ -319,7 +320,9 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } } - return { streamResponse }; + return { + streamResponse, + }; } export default useChatHandler; diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 911a2a014..e57253924 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -7,7 +7,7 @@ import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { newSession } from "../redux/slices/stateSlice"; +import { newSession, setInactive } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 2d98b1011..eae4b0acc 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -126,6 +126,7 @@ function useSetup(dispatch: Dispatch) { dispatch(setConfigError(error)); }); + // TODO - remove? useWebviewListener("submitMessage", async (data) => { streamResponse( data.message, diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 4222b4693..469ef3ead 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -34,6 +34,7 @@ type State = { selectedProfileId: string; configError: ConfigValidationError[] | undefined; isInMultifileEdit: boolean; + streamAborter: AbortController; }; const initialState: State = { @@ -61,6 +62,7 @@ const initialState: State = { defaultModelTitle: "GPT-4", selectedProfileId: "local", isInMultifileEdit: false, + streamAborter: new AbortController(), }; export const stateSlice = createSlice({ @@ -239,6 +241,10 @@ export const stateSlice = createSlice({ state.isGatheringContext = false; state.active = false; }, + abortStream: (state) => { + state.streamAborter.abort(); + state.streamAborter = new AbortController(); + }, streamUpdate: (state, action: PayloadAction) => { if (state.history.length) { state.history[state.history.length - 1].message.content += @@ -249,16 +255,17 @@ export const stateSlice = createSlice({ state, { payload }: PayloadAction, ) => { + state.active = false; + state.isGatheringContext = false; + state.isInMultifileEdit = false; if (payload) { state.history = payload.history as any; state.title = payload.title; state.sessionId = payload.sessionId; } else { state.history = []; - state.active = false; state.title = "New Session"; state.sessionId = v4(); - state.isInMultifileEdit = false; } }, addHighlightedCode: ( @@ -339,6 +346,7 @@ export const { deleteMessage, setIsGatheringContext, setIsInMultifileEdit, + abortStream, } = stateSlice.actions; export default stateSlice.reducer; From 022b7a7d7d90e58f467d057b506e79ebcbe6b0e1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 01:10:03 -0800 Subject: [PATCH 40/82] stream aborter p2 --- gui/src/hooks/useChatHandler.ts | 7 +++---- gui/src/hooks/useHistory.tsx | 12 ++++++++---- gui/src/redux/slices/stateSlice.ts | 3 +++ 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index bf6836107..75e9e428e 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -69,8 +69,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { }, [active]); async function _streamNormalInput(messages: ChatMessage[]) { - const abortController = streamAborter ?? new AbortController(); - const cancelToken = abortController.signal; + const cancelToken = streamAborter.signal; try { if (!defaultModel) { @@ -85,7 +84,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { while (!next.done) { if (!activeRef.current) { - abortController.abort(); + dispatch(abortStream()); break; } dispatch( @@ -162,7 +161,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { historyIndex, selectedCode, }, - cancelToken, + streamAborter.signal, )) { if (!activeRef.current) { dispatch(abortStream()); diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index e57253924..03657d74d 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -7,7 +7,11 @@ import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { newSession, setInactive } from "../redux/slices/stateSlice"; +import { + abortStream, + newSession, + setInactive, +} from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; @@ -121,9 +125,9 @@ function useHistory(dispatch: Dispatch) { if (result.status === "error") { throw new Error(result.error); } - const persistedSessionInfo = result.content; - dispatch(newSession(persistedSessionInfo)); - return persistedSessionInfo; + const sessionContent = result.content; + dispatch(newSession(sessionContent)); + return sessionContent; } async function loadLastSession(): Promise { diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 469ef3ead..3caa424b8 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -255,6 +255,9 @@ export const stateSlice = createSlice({ state, { payload }: PayloadAction, ) => { + state.streamAborter.abort(); + state.streamAborter = new AbortController(); + state.active = false; state.isGatheringContext = false; state.isInMultifileEdit = false; From 32ee22bf700ec4d3b63a4b687418bb8595944342 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 01:14:08 -0800 Subject: [PATCH 41/82] stream aborter cleanup --- gui/src/components/Layout.tsx | 1 - gui/src/hooks/useChatHandler.ts | 4 +--- gui/src/hooks/useHistory.tsx | 6 +----- 3 files changed, 2 insertions(+), 9 deletions(-) diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 92dbdb4a6..42a1182e6 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -21,7 +21,6 @@ import TextDialog from "./dialogs"; import Footer from "./Footer"; import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard"; import PostHogPageView from "./PosthogPageView"; -import { setInactive } from "../redux/slices/stateSlice"; const LayoutTopDiv = styled(CustomScrollbarDiv)` height: 100%; diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 75e9e428e..760948134 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -69,15 +69,13 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { }, [active]); async function _streamNormalInput(messages: ChatMessage[]) { - const cancelToken = streamAborter.signal; - try { if (!defaultModel) { throw new Error("Default model not defined"); } const gen = ideMessenger.llmStreamChat( defaultModel.title, - cancelToken, + streamAborter.signal, messages, ); let next = await gen.next(); diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 03657d74d..8b9a93531 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -7,11 +7,7 @@ import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { - abortStream, - newSession, - setInactive, -} from "../redux/slices/stateSlice"; +import { newSession } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; From 0ba023cd91858f7fd8b84e1143146d5ebe837fe9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 02:26:46 -0800 Subject: [PATCH 42/82] clickable symbols to code + working for js --- core/core.ts | 4 +- core/util/treeSitter.ts | 9 ++- gui/src/components/gui/StepContainer.tsx | 2 +- .../markdown/CodeSnippetPreview.tsx | 1 - .../markdown/StyledMarkdownPreview.tsx | 58 ++++++++++--------- gui/src/components/markdown/SymbolLink.tsx | 6 +- gui/src/redux/slices/stateSlice.ts | 6 +- gui/src/redux/store.ts | 7 ++- 8 files changed, 54 insertions(+), 39 deletions(-) diff --git a/core/core.ts b/core/core.ts index 53a2a068d..8825f235c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -30,7 +30,7 @@ import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; -import { getSymbolsForFiles } from "./util/treeSitter"; +import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; @@ -368,7 +368,7 @@ export class Core { on("context/getSymbolsForFiles", async (msg) => { const { uris } = msg.data; - return await getSymbolsForFiles(uris, this.ide); + return await getSymbolsForManyFiles(uris, this.ide); }); on("config/getSerializedProfileInfo", async (msg) => { diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 3b7a34c29..22a59e85c 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -232,7 +232,7 @@ export async function getSymbolsForFile( } const tree = parser.parse(contents); - console.log(`file: ${filepath}`); + // console.log(`file: ${filepath}`); // Function to recursively find all named nodes (classes and functions) const symbols: SymbolWithRange[] = []; @@ -249,7 +249,10 @@ export async function getSymbolsForFile( // TODO use findLast in newer version of node target let identifier: Parser.SyntaxNode | undefined = undefined; for (let i = node.children.length - 1; i >= 0; i--) { - if (node.children[i].type === "identifier") { + if ( + node.children[i].type === "identifier" || + node.children[i].type === "property_identifier" + ) { identifier = node.children[i]; break; } @@ -280,7 +283,7 @@ export async function getSymbolsForFile( return symbols; } -export async function getSymbolsForFiles( +export async function getSymbolsForManyFiles( uris: string[], ide: IDE, ): Promise { diff --git a/gui/src/components/gui/StepContainer.tsx b/gui/src/components/gui/StepContainer.tsx index 22523cfb2..613b98b5b 100644 --- a/gui/src/components/gui/StepContainer.tsx +++ b/gui/src/components/gui/StepContainer.tsx @@ -105,7 +105,7 @@ function StepContainer(props: StepContainerProps) { )} diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index 39c09cfb6..639e14cc8 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -124,7 +124,6 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { source={`${fence}${getMarkdownLanguageTagForFile( props.item.description.split(" ")[0], )} ${props.item.description}\n${content}\n${fence}`} - contextItems={[props.item]} />
diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index aca1cca2b..a2b55ba26 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,4 +1,4 @@ -import { memo, useEffect, useMemo } from "react"; +import { memo, useCallback, useEffect, useMemo } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -22,7 +22,6 @@ import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; import { RootState } from "../../redux/store"; import { SymbolWithRange } from "core"; import SymbolLink from "./SymbolLink"; -import { ContextItemWithId } from "core"; import { useSelector } from "react-redux"; const StyledMarkdown = styled.div<{ @@ -96,7 +95,7 @@ interface StyledMarkdownPreviewProps { className?: string; isRenderingInStepContainer?: boolean; // Currently only used to control the rendering of codeblocks scrollLocked?: boolean; - contextItems?: ContextItemWithId[]; + itemIndex?: number; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -116,14 +115,12 @@ function getLanuageFromClassName(className: any): string | null { function getCodeChildrenContent(children: any) { if (typeof children === "string") { - console.log(children); return children; } else if ( Array.isArray(children) && children.length > 0 && typeof children[0] === "string" ) { - console.log(children[0]); return children[0]; } return undefined; @@ -156,13 +153,20 @@ function processCodeBlocks(tree: any) { const StyledMarkdownPreview = memo(function StyledMarkdownPreview( props: StyledMarkdownPreviewProps, ) { + // Grab context items from the user history item before it + const contextItems = useSelector( + (state: RootState) => + state.state.history[props.itemIndex - 1]?.contextItems, + ); const symbols = useSelector((state: RootState) => state.state.symbols); + const symbolsForContextItems: SymbolWithRange[] = useMemo(() => { + if (!contextItems) { + return []; + } const contextUris = Array.from( new Set( - props.contextItems - .filter((item) => item?.uri) - .map((item) => item.uri!.value), + contextItems.filter((item) => item?.uri).map((item) => item.uri!.value), ), ); const contextSymbols: SymbolWithRange[] = []; @@ -172,9 +176,9 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( contextSymbols.push(...fileSymbols); } }); - console.log(contextSymbols.map((s) => s.name)); + console.log(contextSymbols); return contextSymbols; - }, [props.contextItems, symbols]); + }, [contextItems, symbols]); const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [remarkMath, () => processCodeBlocks], @@ -258,30 +262,30 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( code: ({ node, ...codeProps }) => { const content = getCodeChildrenContent(codeProps.children); - if (props.contextItems) { - const ctxItem = props.contextItems.find((ctxItem) => + if (content && contextItems) { + const ctxItem = contextItems.find((ctxItem) => ctxItem.uri?.value.includes(content), ); + console.log("CTX item", ctxItem); if (ctxItem) { const rif = ctxItemToRifWithContents(ctxItem); return ; } - } - // console.log("content", content); - const exactSymbol = symbolsForContextItems.find( - (s) => s.name === content, - ); - if (exactSymbol) { - return ; - } - // PARTIAL - PARENTHESES - const partialSymbol = symbolsForContextItems.find( - (s) => false, - // content.startsWith(s.name), - ); - if (partialSymbol) { - return ; + const exactSymbol = symbolsForContextItems.find( + (s) => s.name === content, + ); + if (exactSymbol) { + return ; + } + + // PARTIAL - this is the case where the llm returns e.g. `subtract(number)` instead of `subtract` + const partialSymbol = symbolsForContextItems.find((s) => + content.startsWith(s.name), + ); + if (partialSymbol) { + return ; + } } return {codeProps.children}; }, diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx index 84c1e8984..b18d302df 100644 --- a/gui/src/components/markdown/SymbolLink.tsx +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -20,12 +20,12 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) { return ( - + {content} - + ); } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 8f46f50ec..460b55af8 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -137,6 +137,7 @@ export const stateSlice = createSlice({ state.mainEditorContent = undefined; }, updateFileSymbols: (state, action: PayloadAction) => { + console.log("UPDATE SYMBOLS", action.payload); state.symbols = Object.assign(state.symbols, action.payload); }, setContextItemsAtIndex: ( @@ -254,7 +255,10 @@ export const stateSlice = createSlice({ if (!historyItem) { return; } - historyItem.contextItems.push(...payload.contextItems); + historyItem.contextItems = [ + ...historyItem.contextItems, + ...payload.contextItems, + ]; }, setInactive: (state) => { state.context.isGathering = false; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 221d275c9..0c92e7f26 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -40,7 +40,12 @@ const windowIDTransform = (windowID: string) => ); const saveSubsetFilters = [ - createFilter("state", ["history", "sessionId", "defaultModelTitle"]), + createFilter("state", [ + "history", + "sessionId", + "defaultModelTitle", + "symbols", + ]), ]; const persistConfig = { From 1ef7087a8923a8c6cf7628b4fbf7d7ec1e2d20e8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 02:41:59 -0800 Subject: [PATCH 43/82] chat symbols cleanup --- core/index.d.ts | 1 - gui/src/components/mainInput/resolveInput.ts | 26 ------------------- .../markdown/StyledMarkdownPreview.tsx | 2 -- 3 files changed, 29 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 25d5c346d..c22a66aff 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -317,7 +317,6 @@ export interface ChatHistoryItem { editorState?: any; modifiers?: InputModifiers; contextItems: ContextItemWithId[]; - contextSymbols?: SymbolWithRange[]; promptLogs?: PromptLog[]; } diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index a4598ae93..e8502d89c 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -256,30 +256,4 @@ function resolveParagraph(p: JSONContent): [string, MentionAttrs[], string] { return [text, contextItems, slashCommand]; } -// export function hasSlashCommandOrContextProvider( -// editorState: JSONContent, -// ): boolean { -// if (!editorState.content) { -// return false; -// } - -// for (const p of editorState.content) { -// if (p.type === "paragraph" && p.content) { -// for (const child of p.content) { -// if (child.type === "slashcommand") { -// return true; -// } -// if ( -// child.type === "mention" && -// child.attrs?.itemType === "contextProvider" -// ) { -// return true; -// } -// } -// } -// } - -// return false; -// } - export default resolveEditorContent; diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index a2b55ba26..29bef8c91 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -176,7 +176,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( contextSymbols.push(...fileSymbols); } }); - console.log(contextSymbols); return contextSymbols; }, [contextItems, symbols]); @@ -266,7 +265,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const ctxItem = contextItems.find((ctxItem) => ctxItem.uri?.value.includes(content), ); - console.log("CTX item", ctxItem); if (ctxItem) { const rif = ctxItemToRifWithContents(ctxItem); return ; From 7ffb95e9d0fc964b55b3f92149515fa79fc3aa0d Mon Sep 17 00:00:00 2001 From: burlinchen Date: Mon, 18 Nov 2024 19:05:07 +0800 Subject: [PATCH 44/82] feat: integrate Moonshot AI model provider and update UI translations --- gui/public/logos/moonshot.png | Bin 0 -> 27733 bytes gui/src/pages/AddNewModel/configs/models.ts | 105 ++++++------------ .../pages/AddNewModel/configs/providers.ts | 2 +- 3 files changed, 37 insertions(+), 70 deletions(-) create mode 100644 gui/public/logos/moonshot.png diff --git a/gui/public/logos/moonshot.png b/gui/public/logos/moonshot.png new file mode 100644 index 0000000000000000000000000000000000000000..f51df62eb4bd5949e861849e1f59dca511513946 GIT binary patch literal 27733 zcmW(+cRbYpA3xX8*=O&4xFjQckId{)WM=OuGxLx=BAFqSmF(uReK6VMYtAP{18HKj-3=Pvd?91pz98g3+mA253bEd>aq zDv|K=87}x8=j9_+MM(J|;|BNz&q_m8337w|_o21uEd=7^p{}H0;QMR4)hB>)GLZi~ zyPAqH1UV&jC+4Gkei9{473AX-az@XJyV@)8Dj@p@zqbELmzeg7>Dn*tc8}iy48mdFa)ACkQ20VuO2E#o)5yK#?KaQbP9sSZda``lqwA%{<>+j7PHD7v*N` zTn<(cGSqMX!$ZgqBJOE~vKps)u_JGklNk_w)#VJE_-qqbo^#dnBu(YEvqNqfw|$=W z?LC^b437JGHJy!lbyG5ufAYK)Lfo`5wXw!M`xUOVe7xp{a&0-hoOszob2b-!bi40p z6L}z5^FA>+C!>z@`?YWAfPc#7S@iZrXT0;i%mjXW>)4gY8pkX1nIen!KTV4FL;O%5 zLZF50G0KpR=(ZRr0m{+{9>XE0fva(?9b(eFbXu08>O$T+_O|dX@2Hr ziC{zfCI1Szg~}*NKuw)(mbK}q%F&)se`*xmAa!J+u&QYvyfO(NA5Zm$ZeA~5ruQ!6 z_b!NNf7Lng&rB?;iGQ>olRzjn_~SAsG;AT+EO_7k`W#=5xp1>ewzHq*AmB15{H&`6 z9ucq%iC|ED698%IJWc$$lXYY+wLOr`cAYJCW9(xs69`~RANvA#x%}_dDu3&d{T#W!YcY$Y4>7xxe&KSV zAFf|^MEgHpNd%ju5^dYjPglgjw5!+SnZ1WIISf?){H871ZQtB?tDsjV|!B@w)YS>_cCNf(W-&7t)pV5zED#1NGQ2l$^ zjGSAzEuD&iM8DOipI&q7AE*UzDhU|f{=h!(;@&-^j4)!ouqHJ|XiBmkg*}xO5+zTw zIlgUjng2cs^+YC3ilTn&u(u}mE7$Cc7lE0B?8u>{pE7>!UmSh(ZVMMLl2~3Uf01|s% zsjvNe+YTK;DsEl29Wsr3F(IPtC|Yf=4{T0 zUXJ5*zT#t&JggP0PT<>lV*j6Hi06ZhH}!)VGNMzL-c{$1?V`EedqySX0_P_?Z>(;v zZA*LK?OY}N9Ln^V&toaJ*nhn1y^u|pCGE2u`_P?_iR3GSBKQB0IrkUdb?jzzBX}fmWv5iQmU{0?MTqLHYU7@-Z=zaB)#bR? z(rhk<`RNZB_G@0a84s8Bc&zvwXBup?j_|xP~X)|?sHVDxj&Xc;B(1% zpq|~a(f_KBUhCEUroNo-8$o8;Vmb>QudaUR*lT=V?vH={fx)^ow%hy8O^p_#LMAbL zbGTQzRF0d+AorozLcp`4z5l!e?e}7c zl7QB1C0D!H#M-AMIXUxuKj^8O&o74P&t~sR_;tI-q&5T`B`ZWo#0L^H3g2>ip;nWB z3bD{k9F^DxwVJtjuO4al*kAuy*ftWQjUzEF691nnNl#>o}Qv3^k(0 z{Y>t%La`~?Ou}{2l_ED2Aonfms%*NZ^E7Zj&|EvneQmR^?Yb%%gG;$v{LGZ%oRC%~ zD%9*xQb}}ZhpR72Z4pXKz~A{ZOw-d@_HM3R*3*ujU9Mm|G?i$RW99`XO`n6PILuqT zTjk}6^Rmjg*5i}1C#Ci$`ch`?5-d_;HbEpM%jt>STsOIr_OA@pwTrC!pg!Vv{Enu* z)JA%_FhM#)S%o4UtTx3sh4_eM8tcK3iPu}LG5aHaLeGcfIEsc$k58Vic(XWq>n{~- zhJhxEol(M94g1=Q)A1`(d4F@ES+!d-jTbG-M5b%SKhyI-zQC zOR;z5Z)KA-Orihm^eypOie>d(g{;pE+-ud{)>|t7(a@C*YrpOO$dcaoa)8F$uVv%b zkJb?HAPu9d7MB`fxr(eT=DL7=MXlZ+K=!v4WdGYXbo7k*lm!dcB!(u^_R{h=N~>R*kGMnSihkRIH9^4iq8 zFCKlQVXEaq?XIk}t6d&u%3a$e=x7AGM=gtb_gT-G_B#ghsZ=Mi2FvXlolG)u3~!}+ zE}z2|5MYl{$CsDS`;)%Fi>)x3xO z&JNVyFNla!hW2rGZXSL6^MZpqQC{BZFGFI_;>iULBuR}jAEh`6H&8~GepW-0tD*3b z`GO%12wR_DQ$`2&#P`Pj>~(B=cm7FcQ@?M@M`L5Gh$N3#ut<@%p#Ah|?1LkZ!T6L8 z0tpX==pjCkS!woay?V~0k|QTZlcsg6m-zrnym7YfIZgXqw3=5bdkoEej>l~8P>Pq< z=L?Hgf`V6gaq4I*UmAmqj0{|r{f!ct6E8ur_7UCM_#mDe~%;^i9V4|p!#1wYnw#=P}MG)opf zt}MrNQ+;3d2v-bim>dhs+G$S&OFTS0{yo|iEAIb~@%-OH&vw>MO%g%m1NX+3h}zV+ z8bP^Qv$lpmfxW{)qFT54!?|o=W9XtvSdLTBd>kK6x#r)n+oX9Yp5J@ol$>Zz4eDn{ ze~YTB>Zm_IF8_Xhv?*xaO+<+sBQFe1Ln@{ysWFnlF(31fF7uTKSVQ3oh{b~j@Dlif z40(M(^P#X1Pl*HUG=h^X$sKk@dOq@^nu=Q|=lds(ou&Q^ZE0TtIA>A_O5MHL)V+C5 z0xwxy!)bXrGuQCcBT~23aSah-bsp9lELKx6+snUgT0hNKC+SBwOJl4yrq_7=-Ly<- zyz#|5ObdzTds({g=C>!jn3Tp@qwyRm4V9-4A05tacC**L%jqnA zcekqQ*s(uTgmCO36aslyddT}zBBLk^=`QML`%{mam&G;5xdpTA6?C2lkKkDU*A|w?{=H-g3hp>}r)=oEX~96F z+^$1&yh^j%%XwuE2_|t7db%EVBUXXnGzrAi){OQhLT&U@d7)#JQbCjoJDm8KRrfvx z@e#3ug9GNASY)csl~9S+=G~d4k9$p_AeR8?!QY1bPy~)_V)%8WLhaYO-@XTeTMPB1 zU%t5N8sdhs<~N8#a)$_&4Ieos(&gamScYkyDJM|DrSV{c6EcI2@}o7e;)(~{E6rW; zY-k~>%a`nxCdnQr|I84I0{+J?Etk%@ird{!w`QweyHX_Zp!OR-IBdYI*Q(eu-*&GH z-|}Lw%(;Z9C&Sbsib=2lSurHeu;+s!?PB@_7P*-E;Om!{m)rGw^MCqutvq;5Ti|=X z(%Z(gsm@aDGUhPtJ|64X-f2Snt~G&2&{#T)zaAX!c zQ+D&9GuxjNj}@RFoI-eUVhBVB;(C@*Jo{mY@fW6SB{kZVXk}WMp&@Zl1;ZW;-Q&9T zaU-O(6rqftjFg8BpL}51X}jQSyO<09R%NZa^n$_do;i8ZKb;@$Dq}}faLvT`8=eY| zgWouV;p@!wI5sxzc1>yp&-wDaVv|i6o`+No!ja@tFY4sFy)shOUs&XKdP0q8JmJIf z&6@Kig%sM>3+pW01s_P{DV2Xz!Zsez*P`lh< z_&6(a!5K$bX=3F`nAEa7NS9ckG zbrSje_iv@s_(PXce>}+Ifeoo2qq?BM!96&g=T;KN_XgCC3O2yqime~o&tgJ&-A z_k3iHG4z+8r6XXXPc($%;r|xe6V;H=`k8pYnl+;dYTOt^yb4)jkD%)>;lsn(*ZH($ z2APHVg{AafUS3mQooPV74UG}`{6<$~y@@1EgZZW0(K^}GN-2AHipiuGf*5{!6~*;? z{omhjEH`_(zb|g~WgxKRzOZC@NIvVT)^F9<7}klC>5YK*1GX>7j6!P0U)@JcwG7NP z`|R!|-q`a#ZGqcMN_w2`KI^+yRt}=P9h0{y8QQ_xA}eMv{^nO^p_PLr;-NI2{DbK- zzp0i+l0Sd`Of|lw;kkQP;Ij)}H@UTfB@XmEZ*Go$kIs%GeSeb9l>RHHR_fGo=;Gft0*r2C(J zs@nSc<-g;f#REMt*C71tG; zjEccGx7H;)`ZI*897fnv($cICR__&8EW~uhrm-%bDC&E4KFXGs86ld>LO_j^*?Nyx z%SVs`kc5_1Zq3}6|5egd6Kh;!r=Ukp4W-EM+&N)mPAsUXU{TV7KMxBo(xi)8cjhWvzN5xuFb0lFC-+BaPnM^w>tuC>ub_mqy6R$q9iN{=t_p#Mhjw zoUWN1?RIK`yNJE^DD&&02uLPNN6|MmH3>L-(*^DL$i-rhe*`i%N}0mF*(@UA6WI^G zq((9&y-FnUsdR+xD^|+x+Lc3z(&F{aoz9J8eR02PT>q1QUD;AT?mP2l>+}kG9)fm* z@9`B7h}f-re>?*xi|$>IJNLx*%vl_$~rA#1sM zU8OWh?DM1!gJ8P|aWGCG{n!;PuhSH!n5O^_jr!N@qpPnURuR0tqgS6t?-a2lc*0Gt z++js$y{0oL?EwEcJy}8?_6C5|ot6WV%*;&p6*Y=~vyEXLk)#lac`#X_meA-0L_XE* z4U+7kbVu1NDC!3f9-v4ltv9Ma6_*t&*&1?+y3Iy;ZBFDN=`03vf&}0d3#5knY|-pC z)3{_D9A67|CzCuO2VO;QRaCW7DMBPXr%@l8!B<;5w#&H2v(6mz;# zbj^QxwQwZ^L#QDZz55EA3u!p3otJJ)(?D-^Z)(6lpd!9A(-JJTp77ZzJ*T!`-mdxuNp686y87KqyGM-ks1yivk$Kagq<+X*_!Ws70A8^{cE zN4@uMs3mnrV<@y1QyvY$%Qj0&lJ#YG-0|OEBBCUR$H$2k5WC|Q*CN+DIyXGzr3AUW z4-BawAsWeJgZ9#_-wNLxq6P649^8Iw++2cUcWM+tM02vjq0-E0f9C%k&-VE5n0-Uv zy6y4jKPpBkZ%Q*Wvtf~UjaHs!s!8o|`jHPjJT0>Ppq1v2pzxSUSSgu9C!H_rytkj0 zS+p~oFwkSm#8xBKs0X+6f%e~e5*xmo2aq38Dq*|lEv%Ud!Pjd$%R;$lM8aCC>gxDW zs{&z}Ww64$mdm}bTYH{wV=$rHVM1oR;uKT0P>B20C@1eLE8Mp0qxR0!FD9&g?3c`> zzxQZkq|F~Z%DDYbxBcb)Z~8y7F{Rq9e zT_pB@CdZQX9kHN^Z6l!HfI|#>IU7Re}2W|R*hyR+r z-LS%k-ThYy6Z@^~zoLW^zdXC+G0x7LLfk^)MDq0LZT4rQ@U@j5tuK=Uu+_mKHvw0b zY%^|lM-@IQKK0O^<&M`v+f$>JgbO#9jKz|ygxW0lS&LyS4F~+`nDK#OEpl;v z-1x)2dcHpP4<(X(7L9Q=_Jh9%>gT^_3<@>uT@w=#6GI@geEb?Mxia=#=jZ1iHYK5G zh)q4=ty{Nf>1o5|5b}!ZmK~S4#b4&4h;`)RznJ{3a+{M}o{lCbkA_{Ei%||#o<=A> z>rb~ciYxHIHBY;%dbeRtYu}b34yWbSA4%CW3)yH2?u2LOhxbwV95A7K$)Y{-BvR~a zT9#61PTCzoD%LoR<3{zgYKgq%ZK(g;eI>o`V6yD~j^+Q|d~=$(`${>yK(N7vPL}3L zZTMgJ5)M1&B1U{(JMl-dd#A~e@5=d-nHVV2g5dvZCkTTyvFG*NfuP zRNhdUu*uEWthA1ip$Uv(YA>4AwK#{PQiX?K@8-%~=kBeVRCF!_Cja8WfKaOMM{@$S zP4EpD6Z$|4lj{VVNP%HNSz^En&0hTTfLok6EdNeOKYT=nfJ&g_?3$q1y;W}Cmb-_n z%%@dgsB$3sG!~P=pFV#c7D+ntYcz&KHSt410TT_MDP|x`j5wFa^E4KU%6?3sE}TDT zleTpHhzhrQt0SzZlpSWaCK#7Q+B)0KG-Ui7k0rBLO+_@~N1B zKzM#WyVAGrRve6~+&OvB@mMZhDLM?MEwzuLn3{kavhLE7PkjuYYq^#+_xnS-yU@NH ziP~>M#2^=6^zJrRw*;>0YYL$AHh4!L>IpZPl81H(#KguT;=eB)_zQ?5Y`$|Tb^50* zbb=ipo}P~OIc|%+IN7mY?067WP4>;m)TM<4^tqR-{XO6`=ozet{kYd`v@z}Oju`8+ z%PTJ@8Irq^o+vX8ixF|wefl)>fp}5Q@=oupwP9pw$*!;I`lf%#P|$JB>16N~bAa;W z$ti2qMG>9n19vmnTnWCI#2W?t7Ttl8=NW%wy}=b>c)c!bM?jK=Q6HtI!9@^}C?a5{ z{yR|fvu`weG{MI`QFmeHG&g=D8HN&Ti(Ic>weg_`R^R5~EpLn!c`RaZ-pdBk_arcN z#xsaLn&ggA@hvFKD=vobHH3mE8I=#$8h5WKnt4%X+n1VGT1qe^d%;^;T3YF`tkPgQ zL8&2o11G0IJ=*jmF2O&qVDPK{rl=-T`QDY>T(w7 z&Y%$YN-VA@gU-iTtS8DO;I9=EP8_eZu4FZ#MauM}+b$C`3YB*xY;ydJ2Cd@`*2%@k z0_FvCed6%TievP`-=FynEmP#aqFcBrdLoD*C=k{SZz%1&O9=1&z3Zp{McqN2<{-@D zJ0(YD`DUF(pdy?DsjQ*FP;Swj;4>e1yGTlVdG<^wb=%7<5~+^j;R%&8Ce_fRL{*7X z8lv+*rKA|!3RQh=V|Jb>?|3=1-L0=9^LljjQQuiVfVVH2=e9T=RQXT7oC>y-BmDYt z^WY2o08TDmqhxz~;>(4);=^RRP5mB@a0s;bm41Mv1jz zR~g1=%dtW&asN6B^9q(dU&f~Lj?JT)`TDAgqd@O}iSGjmTzzsVPw7;=+eJv-h*Wbi zj$cMp(ubrTLAl8ZkjC=QpYz-Gqq?H4djx?p(}0v`d-W9db6I6^B(%^;*8mq3hl7*T zw~nye9-9;QR?A0)i9db%q`8Lo$ko`>EV9tCx5N_~jyMgF#o{HSdN(Ff*I(fg5qP}D zE#X>w(b}UwX6FJ)0qJcBybzt`6Kj#J_*8aJhFh1_eIBNLwDu=q=M9Ot3zR$Yb16M& z{&6GZR~&n)v%i5(h0U zE#~^_f{dhyoE)hh+V>~4v=p2XT|+9s1@ci`8YG{7$bzrNYu-ZJ?7jUhQ^dJ4@WQ)4 zS1z~l2WtN8%v|~gEdvy`L0LRI&BxFg&7|q0gPOFJ<3wh(mzEHbWACzxwcz3Ld}sUB z=E-gnX)x`QE-fdT{ktKDqx`C885DhROXM+~GEwq98_F(sibhk-Z{D7si(NDpO5pL% zOkR#UJuUT2;4QMM@3JwW=irt+svgRfV|n-P-6`gP<(trublAJkkH764JkXSm%;Pi4$E|EWQFEOsE>+o+Bi8|#Y76?OPlUcF?PKJWlUrT|g-@mO; zF`;rd2XZ|Ymt7VR`KPka3$KLG^gsH8A)VyJ5JDQh?mE|*O6N7cmfdfJr~g?5;|8Cl z1?MQ-uH&NG4W@|nE;+N~m!K+N8_4q0$zu_LHY39tIu=>o=3AoI8}3l$B@B zM*nVyZ!KKfZCe?CdumW{kgZwZ=D-1V@^3yYzgy4D4E;P{nPC{G7=jmpC(!yaWhN{l zU{5gdtW^z{_QQ%y@U^t}))X3a*AKO|DI0wpUtb*zM-L(ch3Q|*8N;80iRYH)zrsz+ zP4to=JJ(7q!h9gJ(oYvIUS{>#2|CK+ z+IeT;)@UE!F*x_&c^@+*J2Pq{z9a6cT1Q>jM(jnjWYy!kpHX^n`6oDN%k$ce^ma>} zoN3d@rY1=PLjz0iY2NQC;+K4hpFC*pIdjl#8A_m=ULw^MQIv|T2n;x)drP1=^K{{| zxun%Dn)?wPej-|7d{NUU1N+yAc=?nvkr~gqr}mj|wsvR|lOk2@d^n=>(}(undoA{A zTI%V%ThC*A?0cvKAv3klyPAa81yhxf{QeGQ9ym}%x<7tF| zsaOhe#lq^wJeU%s6rmV#<^z%( zE1U_td@MM-3c^kf1~E6RWr7_N@9sXyFDoMoVe^96Bn&XwYHZp7YYW}8{fsSMrd0;e z*#|m0iO-OlPct2Pg_%g1>y*?AiwX(qxQVr`UhoXip!;+m8*#sS3h06KEvi%~0fFLu;J_cWL%YbZ#Wu4*rTI>B3F< z3gqTDYO;NIM*SUJT$BL+=gV#fxZ5h_$`D zPReJ|6h2WWT3c7U2%cVp?;bgOl7LMbp{q?PGjj3iI{-BMtAfOpkMWNakNY#_4s*&ov!lOhNnCO+*f&G}b zqNz5HoC*}YO9}aR%0m!Lipd`wRrt%f)3S-}tI4LSJ`Vo%%8F373<~5C{Y8KA-g$tn z`Bj@8R9{1A#7nLBKVniAB1H}ufBWT~%k3xEx6E=(iQ&qi-qu=MZqVGO-bp=dG_-SM6$RYZt*pZwR`Q1P}<2 z8$k5GJuBe-JhN>_CuCKf$#E1|S{l>%axEVKez5Xqtx-}L*J`3HXSJUh+EEDTz%1wNy zO?XF$Z0b!56sZ@gLJ54*+4jk>C$cww0ZW9rktV4hN+vcf^^166g_G*SP-R1-!(m{) zj{N!+L&2@RxUN_54u9JLsIUk)4Es)m$EHr6<+Rz9Fh6g8{NiD9IN-)V$HxT=rT}u` z4Hr?Rk$H$$DdqF;0|1b6H)lg56B7}GgW9RjV6^%_Mm2WCqApV*Oj6z-nwscisqX=N+3QTh$aMae z?$Fwyjg+1+aJ8Q-qHNjlVo+6!7a7K%euEZL5p2}kNx z&$&v9*))swZ4kl+6EV>r8BmNQzgOcKPRA{-L|V@Oijl?AZHpKmzuD-($-pmjq~FxC zVb;|ef1^vp5jUAt`ghU0dD#IKHYdW8Y4$El7NYR(Z-?MMqS0tTOgC=jPsv=`zV)EVmQty6! z=@+g@21ah!5>VPDx*N%jCd-oi5}D9vo-#ogU+4k;Rex#EoO`K)k2iFtaECK-)5{-0 ztSTQB)6t>8DDeWOQ*MN#@RJRmPj+5xa#zES0sgBj4#XOvxG&NN$ras?w~XJ5dxUCH z@S8SZcqa@b2}2>keF6s?10VkwQRyo^X!@weZr~fRK`Mb>gk3Kc6;+vapa88BE247U zGn5suzaQ)Ksy|ZRN9Z#s>FZM*?<^#~TpP^$`jsjyEGz`2K*_l-iDr$8a8@6KtOK_% z{ks@9|HnuaS1#3a-tjL=|GmT1=V{>`da&nyP;;=QiJfr{|s3trfr6!tkP$zy@<^Sh%nsO9>66L?X#zuSCM;DQ#(;aoQq8g`~&w6W9I+4=6%r%&BM zy$Xwo6@302OXm)RR!|&M!Y0Yc)P=u$zQdD~JqZBZU{zKyJo4Jwn8D*um+`Mtwir4j z*H(e*_o{nZ;WzgyCF>$X!GT_!^I1^#_h&f%Hy4}Zf5IwXP5BO?EYVnD_#rBEm+vKB>KYh?E3xA!>!o|95C*yYaoYLl5rD|@{sJ<>=HoyAyVs*KSVKq*70)_`o?28A$>i4@R z<{i0Ly)=0g@{=8E(xX27Pv$b(Pm)>=f%qnGZOt*5BNJP{5QL4>MD;Ak4cF#(9d3+~ z5#a$6kzUo$n~h_6w*RNNxEOQ1J)>u6_!^14I8ersI}_vukHbf+$dt6b(?N|4E7vurGQyvPMDs?CVTp^(__2y{UxX*VSBH zB_S(w;>vJ{ZfaQJQOfzWjEvvsTX!t`3Y*jw7DtqLsjb~g?>;HVZXwnf;+-Ui!*m}# z3I(Z+R6g|)Pz%4SIn}=%^13xjdMve0J+`xoK}sSVjxPsP?D9NM5{CI`q3u zgTxH3r8dIQU>42Q>nPA1Sp&^y`zgcX5lRjH{TecE!EUAMFwP%!r!XB`tqzvb1fjH6d z#C*in#c=^>cxywssy-*JwSl-~roM?X1hCbF9=uQv0X-45e0Y2@aFBK^T0`Z|YT7Y3 zr{C`C3NyXbGV*Ex{3Bxj$ZE#z!-lE0?HWq`d^-+-a{)P$;M=qXd0Z z)BZvXNOPsy7BXaR@{T>`CMG5>E-&wnls#lCGiy#Y{#itTevk);;yCyF@n(h~341Yg zbjd5B(^Dgp3$XxBfD^i`Hbyqv;Bl+|xetzedDJs8W(w8C7-Bm7{__KJXV&mmhCBZE zL+9?3n%{oBEZAVm2bggr=|!G146Ds)X%Wv>r(_a%pcy1cFe$34s<(g5%b5+6)IV3|RPHn#SBS^MsL@65*oO$5MI%j?TC-kWJt zzSQTu-JO?QajLWg*GBQ49jH)3$orT$i6@C!}Kwo+XvNz zO>Q~#JENbKTReh9(u|mHVuoGdE`#_Kdw7Az=`3^KG0^`?NZ(xxJ`Krvrc#AH^Dt

rZt z?T)V*c(yt5r4#6|V899&d-qBELb>zFe5ILH7Kd&+?w%IhT>C+Mx9~L?VsIt|bV{Xq zmOU7!f+4QkuD&O8K3Ku1F5%zu$psx6r{D{IyhfqE4+NV|!Db)M&tLtVn6LuUZn|us zq`_PN+iK4XB8R*mkzadI~dd^ltq^Qbq{LJ8NS^)2TEk%e-V5 ziI`Q zKj!feF=syz6N!OMcx7`4ppkHd^5W`1mQjlhn>M4A8)eB`B{+ijDl$??K9OPl@R7bq zZEYR4MzH21=tv%5UOeu}_?EnqbjX>N%l2+oBlX?`LqksQ?fLj4V5XKf(FY~c;2WZO zo9~NKvVHe$E4Ye_*nARny32;eBbfB;bU7nw-{0D^luZF<<}mNSS}BeKHTR0XXiNy- zNAf)L%GmLo`vzp2-HFZT_xJw}GYwg=x)TVycQ76)!O^Ig(_fQq5ervy3tFGqlLvS- zEGZ2kMC?8JdK{x#kjH6h%NwAqE)Q5Rg#%fYHcRZw^dBDRkH>vvz88lS_y~|2K+^pP zhbIqSRU?d6uO=q)zfj!jpd@wF_FSl3awPO4{6U(`s}L$E@^K?BAN3pbTU*YT^%-XRZ(mnR+q5M}v21;jGWBW0AD$-9$5nv9HbtFYu(q1B zIBovrdeu@W+^?^pH4ebyZu|A*&9|k_NMi}s#|j*ci5U$|Z~l4ddNJwhUq$5i+CUE^ zl=YzTK0m!e(UGKk-3-qc2I3>O~De(_4SR74(tStR!R@*r$`U_;RnqMtmr1$c*lL@;#HQ6yN^@3 zI}GH6-?vy!A@ub0xq&~(tr;;`hJo9YJ z%kp2EaI_Rojp1@WE;UUCJQ8bG0s^17g~2s~^0!_7;V&pEifk>GR`=b{ycsZ$<=wfR z9h!MJG_#jCN@etQp<~&15{PMA09_itMYmY{nU+IlL{V-KeU_*z7WLJ+OheU^!Gk8s z{VLG(`k?Q>|FDY#YQV8V-ig&jAa|@KZ9U#Xqx_^7$JZZ5P*0{LcUpv!fq_AYgH5v8 z-cLXSLuR(S+X63kpWhrmPnUSf1)Nlaag+lKN#wm5lOKKRb1UB}D_%R$zn%K|S7W)| zv4I;>TUVD4f&{@A^}(^qvDA6h)#NjEt`9(&fQc#b*ShxAkrT)dy&td7>3_pCC;gso zu6M_YH1+q;Rn9f8$gG+qWNv+@baQ=kQx(OinAAh4EX4i>s3022_ui3mUxergI|Ll& zUT@^GQ^y*6wpa?JmoJap5xN`w(L}xP-ABPEJDf_9tnSJynhfwaqYoEsc!ZSt4xpIr znR<_lW7n3W2@?oW^@vr-`1m+L$Pb%u&wsHwwzYp{@wm(g4K$P7p`QGa{+UnHu8iIO z$W5l1cs>*Tw;~L^B@yo^`g>0^j%hUYS)Wq>Tn{KluhSpe6n|j-3%Hx_tGQP$^VPT@ zzf$GfYjrAPZfAH8L)TQk{B_d2vq8K9{?$(NlBR zdw2UddT_k1=LQ9BV+usRb_@IpBmd6+tUp8Qc9I&rRi-tH2p0!Zvo_fAyGx_;EW;j4 z%FLR*pN-@zmyJj3Tm0&w0wWl!i~%_WqzJ~$-)Mri4K)+M{bj@Ep2_gw$MtpPp+T|< zZ|fg}%PoPDqH2LhW~ydp|MxE}&fZxl`1wg}CL|5WfQA3R{ve~U2W@#x0Cu@u^eS7@ zzqUQJxF0j+*TM%x!vJ$J#ST`a#`Amu_B;fD1Hiz+x~O2hy3DuG&D1})cNHL1TWVgo z;=_iO9&73d8l%x4In!giv&vwi&#iOF4<2QBYrU89;j4STkbtF_zrGSWPnK&*QM187 zx}!{Q?k7j(t!HEZ{rJUxkRp-A5Z%VQdiBni5@h)-ciC14vI!IWQ1q%^?1?>L?&5I( zeA@LQ!~YMBL68OObP+R%Vvj#|Gh=SXy{sGqt!e2bqFvAHmqI_5)3g~7Sop^@Wvfu% zw>b&go3Lto5WcX}Gx|xR%C?W%Wg1k@(UDQ@5BLd4*BUi>-T|RaSA6M*_-Bqk#)cT* zABxV&e}Lzso*i#xfYb3{a$5?}K(ssrP`yr&69-d!wLhaXGtn_K0z8kU|K8m#YqbU2 z1A1W<$g^N8tGaqr%}R`}gIQ!Bs`8q|Y!Ynx-to-yE=mopHwOxuH)()i52)wf@{ro4Oi3_zo)8hcW#hiuhFaCm&IefURG(dg3P zlQQ%GP1g8u(KGtJN&C34J9)#!;Jtvu0+z1!>&+AQeH)?qfGc8b;{r3X;pH01=WIVheSkPY2Lqc=5=p|OsG&h9 zDJh8{h=eGFAV0PJsl5e-$WyXLadpOrfimu3M^6Wlkoz{U#hyL1EWJ-V5@?>vpruey z>2RX{YvWss?3hz$~0cKBp~l%>NGE z9m%sHTQ5H5hu4$9@&LeaKnwfS{vMneJ!e1P71j#NN0r4#=A$(Eg-^Ij z0doa=FZgm*vrl5+{Qkhdyw^XAl5wTWk&7OUdE}u&_L5c47i8Z{Plv9)9cb`5;hWKZ zI1yV&_0%Zk9jh^Y#ilyB{z+1}O}%_p`jh*LOzDwt<2f1f*4u=Oku!TLu^2z{;}N7g zu#+Y?ZJ9t!suLS}nVpThb(;jc&<4K)E?^MA*|1kN93AhpnDc`(M@aw1mM%%{`)HOL zrSktLeyt+~s5YZ9x8~bIvkCCGI4S**;V~Z;tP};fFF;U{$H(5qF;=xVnh~_*A~^El ztpB}v%W^LV6RMr8|Kgv_eY$rl6ldO~D<@Pi^uVv`uf=x|QzV_N?(9hrHrR+m%D8&r zgi2c9YfFJ24|^FUJ>l5T_VE$>?7eYvfsH6nyc(U&0{j^c81|Ma&|a{u6X<+;ps#{N zF}P>Lu1i^I;QF5Di-KclE3%KSM=X!Wy^qhd&6|o_`@Ot#>FeC)h!P8fPMQQ2Ub{BBhNEPqsAZh5dWPT(jD9hV3c`9i4Ay^=oevs zoox%uGIKUIrUT6hOl1y<_(goYu+;a{)z$X_-oO%u;u0Iq{|*FJmeizK%ZXYJ)y zgna)k2)Ie=w>y36B?JZd8TmZB{w>3vzz@|BAN?6FHt$P8!*BlmVzL4XL8c`#Nf@#_ z{zash8XtfC%Ef?w^4NxW1>wSY@H56iXK|~2CR9duc}Hr;qUYvf`X-|NEUO|;{V2j$ zIssei0M$P!H|p3AajA{daaAFcIkde$mM~jIyt45s(&+E2I;n36xesq zh1OdIr4Jugq#*H~*ps}qoByM+#;uuoGa37m$s*^+nW)%HNwb6}c5QnL;qM&1%CMa@y>zj(gh0~Yy~HXe<>hu&jezAn0I37s zzTH=?D$>=cs+PyHF%D&)T~;+LnX6HXoFTl>kp?Ikrt>!G2;lw`sgJkhDrvAaB+U%2 z6{%u&R8bOPdyO(6vA%4c-<^OtGkt)@c+;vvvo6Md8NLEC6%gTAuwhed3dYmZ=$Dap zmT0`IvuF^K9Djm2<(%5qSOqX`9v+@b`ypl^KNX$j3U!^>nK0i`3B!zp>*davF2^K* zn@`w04QMmNKtj*GI_1V*N(wKWlro#uGN;} zPUi>%>BfldnL2CdtH%aUo>&7^s!RFW_`i~lgw(f5Hql=n=Lz^U4dH561hwJ9#)#q_ zp_nFFMxx)IYmQjDUZj)TJwnlQZ(!>FncZ39vb#X?$M678yPkmgOSse-T=PvF(L-5> zHuWA5bqm-HWBGP-Q@|pxMGYOYUyKY3D7-qn9C4rocxC?3qitpISFXYG7GUJAW!ZvJp_sfdEBsITdnhfUXB!yO5oMUY>{ z+SIKV^XS4-clC+O*l4awKmT*f0rI*}pK!tAe6NlsJ+^;|ge$W3?KuXst0yC(m8K45 zm=lHWD5)Dic@haCP5@2(o(5OON1pwJsCu0Rn6GQXnANA}Tj0FEh!VlT6+C zjg9^TBIWX{7Jo?kfC!MFWI=@m{O_IvydlrtgLJXVfoo@A>g8@!$*#dmC5CODk@@*S zIFR`qL2)}9O`iQg_)f=sr7Ie)3;%=UVo6Vu{i-eY$XMNVfaxnN8IE*Rd$Htc&%HXB zNlg4WTlL$@!zrIf_pGXDK_dp2ZX~6oJT6Z?CS1%zZd>qS_erV zQCKQI`!lNatD$}ZM!KJrl{vBV&kF@g<=MuUw}B$rv$x!X^|HXt5pahhcOweqA(#^* z-w{DEaZiLF5kWTZpZ?U>0oj81|I=;Iasbq`Tl^hH({KFnC%260%EO={-u!^UA`}6L z7=v%G{azehSje?CQ%^csZlW$Xt_r&h?qZMou)_{T{512%$YA>l8UnkkO}srkT8me0PhY+lqN{-FYNcl z#eY;6JA9@zuLk|ZWvUVfyVp6v*M3+z9;Cm3_p0J*t5>~pxyqijB>)7VUv8kA19E`9 z9s{;$WNIp^8ALZ|iJsOK9DTAiuA}WaJs_HN5K-iKHx{TP3q7bBM!=h%FLczm9RMi! zCoRuoMn?pi#Uc-Y%+Oj*z}bMld8RE@V$a_7#ZCcmf}XcuiGn`qe)QMy^eSk*Y4CoL zLoqj7xFOfx#TE4(q&j(_PHqA?IavJ$d#euco=)BwZ8TDwRtMi@J{4~eB!5LY@@g1Z z-@P~wW4VN2?`HPC<;J0Pdfk{qy+fFD2s1zbp83DJt~;E{`0XQGWlPyxHrX>HyCf+q zj*gj`En6fzds7iIvXiWX?Cc6<%L>^u^xjX``}teliKQ zQ}E{Ua>vL;T#GMsQ~kW<*J9Nuc_kV(qo{DUtY!8orRk7E>w!7e`^%cKIK$tQnZM@N z=H{M52(}7zC!+Quiw8J6!QMY88m-~Yd_!|5amcrULo0a(p6VMnZr~xP0Uo7%nc)?& z(%W&}p<)!_S)O@QLi-Z+em3!1kR%c?`4H$iwJMc+ZPeXz%I&U;BGlgbV zIOm1*jg-kA5oSi)y}+4A=1Xo5$(mg_bky^%wb-TFky*BTXEwl8c%Ew+85iSgWn zQEuA!K~L&Ikf2nu69i8WjKII9+KL~6G>r8ttA1E^*- zn?GbJN*lT{lOm|9G-q-krV~mTj(cr+Yqa?7l_I;Mttp=k^Ny&?wxw1sasxK}JG6R; z#_akW?^eMA!9+NwB2~BgmM*2F`!6aQ4w=R(^-S5<4;d|&KgPho0?OvY$Yu!d@~um* z=Y>k`bkm0@?Ja{)$=bY3@NlZZ8yZlQ-ftvUQc_~C(oWKmfU%mcY(L04IYf{V*u&LW z<4_A>J1t(6lBFdjSzDT4uE`u-(=c%jGt4UH{aha>;zt^lArz$tDIl;)%6V?gEytm~ zR^FsA69wjzJj-56lin-nzyWgpS@V51uRrUx*my!L;%BU)Ks zPX|wx*HV@z7FO}SQYAzfS^pjis2rNmMTQH>-N#uQO>NkXsyk7Oo3m|viALrR z)@M2`FBETkj`c}4m3&JZaiqD0;AwT40q8=RV4T(p( zwXy1CE3W9hwV!~RKe(+>_#d`0;b0+(IXqa&4{BT%G&|8zcS-vR(g<0@-;z#(AKG9@ z8G3pzS$W4%ar!Q4!N+?QPiE>oxkQ!qlYVM(&wxp{``wEFb5`cagx*k5@|S`?zZTzr z43&n{y)(Dmlyfdi+MRfPecfyC>wRpje|5!iGQ#X^!K?#H7P!A3T@6MF{E|%8y2yRso8?hR%17*`~Vxd;L_j@ePqeT2WOu^W9j`O$r>0!;vD z=-JJwS))ep+mZ4^L{MNNbx3h>2*cVgPg*4qiI`Q#6w4*QKmVYdV(iZ0$VR zs7twB5_QcnXuNB-Hq$?#q}-d99`RUwVthnvC8Dt!7iii!I7kKuhb%$&&HSjLb^+e7 zitYd}6k^fMf0~|KWW(}w=tb+6SLQf*45M7nuctd`DMJ=Mg9?#cx^Vu21rcZeYk5ZQ zSozEsii}+y^W2E+8S<(HrCDBB0Bx6BTYJg4*0FV}@y|>=ZV0O|?#cK$YQ`IzpBf&| z<7a!#5y2wQ*O|tCvkABVXYGIo|H+XEKeT2zs>^OUMm~Mte#4bTE%YQIObH?)?X8Yh zsX8p8m;OBN7QLoRg_oW`+s&1u5)hye8JQnve?;#T@+$7g=vApB`{PvUUj|Q`yaWtY z=UbF*oSc9{O+qIQ&0{GM#?VUvODVC!pN~Z=EXzn5Ido4y$q;c7Z*HAEd~&+TeeHMy$h~<$>4?*fH4X!7xh{0K z@Yo{EmyX4w62j9X{64eUn%e@GU9$c~@G7-zXO=l1Qw2oxJ;41LoBQ6#~<`oqe z8}|GJz%C4)u5W)Y3-MS#nP4P~F8`vzQgBr;4oiEw1?xWpOFdDSJI`zBFIX zE~e?r#iWxezo4k!xa{-tyAt|(U_k;e-{~cwE%AIjeg}`P-q3wXD3Bt&{+O7>HxXt@ z062$A_NFh&d+l=^b$VH>(q5&os|aK`IAtWh1pdLldeV#$JLF%c2O&=h3jC2qE# zef9_hx6q6-(=nNAw`F~@Z*R}V0&Pde`OBX*QJSX7f^Q3&u~bG&&SqqZ?9<+nXYep{ z9!C0t)NY|qtBHe+K%1qQtiqyqt&4pFsPEObmkVrSSs}`~nKs~ykB9}JS1{V*jI1x8 z@7*|n@(T1`viF-J9$s#p4Kx5bul;fB3hx~&Xz`J917-|ynZ>fd$7S@*YURVxm(c!NN4F`W z({aKQ>!Oz};{0DkFF-5Xwh}WU`DBe7!EE4KLf2c!aUXAi8^k7@sp;7lo0b?1 zT7RqU;v%U;Up1Kj<#S@cW_n0F$qO%nFYe1U?(6I+$HdM;N(1#~Mv|bty9{iG$+I5y zP$Gc)qPn5TP4#fez0L$N7a#`%H53l!bB08$#!KzTbqQIRh9XP~`VCU^5PAR_CL|;S zRj@>p?JI{ZR-1vk`OX(_b`2Uf7TKhUYAt*R!kp+2Cy$qFmeLi)7I96>*E9&&Xzu6o zglYa6PafY0`B}}dzUzq3QXT*DnF?PIevT@~P=BDC^Id(*$*s>LR!}tI6a!`aPr!kW zu&1YI`^sQ=i1!n94V!lkmJ%ay*QxmU$RK_wbZ5*gVh{yFm#(b>tLzUjtBbV-?o~FT z22dU*93>!TMw&BVZ5O&&<~gj6%Eo+B8PnEV77g$5yj3yeFup&5x9Xv*h~soy`0Ha< zT%%!w3cJo*C%?+hc>GW1nR0(-^XkG0FV@l99VXY$F@3DBM-WR} z7%3QC@J7qb1`dZuB2wyJj0spc=e-K6v$qx>#vZ4XTw{N&*M)xP{yOWo^%tVgS{Tt{ z(Hv40)eMYLk*oQ(ogz^QdGO|K+MKi9f~~%QL(by2=L7dRA0g&rV>*OF1>y50c(gyh ztNIlKD4@j6PKY*SUO|VB=0oG5 zm(zok^X4c?qLf>*W5q62}{kQ6B_Eo}#)XLD`enk%F$mm|oQOgW#F;^uU2IOY8^)Am=&VS~Uu z&v(Wyi6*^g3*?UQPI|*nmddty(yn8{QJ!y{;vF1;b1)neh@mO2y-xD;jWI#EYAVwh zM>km7I?GPKm(9Yc38wM0FO4{uJ6hjO2v%A{Nua91oyFxm_lXF^5F;gW+v|i`;$ccG zs=vTc0%T{@L!dxZL6}7(6QJ%uX9Ymcl^|q7b0_Ma$g#ygffA4zy(DV)Kn}c?*9y}% z5{#bMzR@z;59<#ZtGdD&RCP0Lr`xnA`9@OjhU_-Kg3JO@$?8Y_IV)$j6_v1ebb{(} z1F_)7VUAOO2`Vf|oL33_w~ZjQrAmt_?>P3A|1jwYT-(grcomYeg0?6EI!ySVax2v0 z6}`n3&aZxu3FGU%O_hs#8NxU#)k{vz#AmO87+Xc8gwmHk$B&5ZHWw2*h0ed$#en-?!y1vEK0Q zZZMVdA62C1D^jUMCelOka!f`Xm34J#d;72s@)d_N##)Wrq<65s{5-M)jT0JHVT3P1 z)Itb(fodJnW)2=CkDDi{+ITn_okoczG>agE%|So!H6JZ8I6MsQBqpQ%H$fbAQ)QGv zefXO7c6}ZVzTskbB!&`mlw$FNI5d>N=LxMY*el;VPNoazr)b`Gm5?WPCC+%wO{2s` zLG;hu9mAjuTRny%pD*5Fm!kA`|0nQXaxZUh%E|FA&3 z%RiX@oak7jVE(RYtEKc~g7;)83~D1R;i@($Zu(ZZy`4X7390B}u}DkQ;NT8*FbmuTmf7yBCu^V|CI-3Y9|Rtb%MVyQ&&Ifa_8rGLo(bF)5a?`H8n5? zh8pOSr${Ii!arFFq&=x?EAe%onE}J-IFTZE2lU>e;^K24B$Vg~V=cNCP_x?dQav%L z`W084l+paozNXT}@cj>k(Vd-MFzy-#(z4(OSzJ0>4mcr)Xzl@dEU$C-c*36@4xt)* z;QJTPUBG{e0N;ecjm87W7v9WmE&M4#ImYL=d>*s3V-6Z7a-ILJGQgBT1lPRL*M|3V zH(%O1p*Eog%>(tm??5*J-v(Ap=hI{N$lhO&h)X6@1Lgk7S1-zdx|pc3h2=+mb|T@zRH7*!mmJn zvX~g+?ghp3Vb;cH-J6LMqMV~AA~xyxH*|$SE8{b)#6=j1WPamv_tkqq+<3`mN6E!= z$`mH$2##td=q#UtvN6BC&})A_BRyRRC@c9VrezZ79pSUdS!*6PjuOg_#>PU1And1~ z^ujTs+=}{lWgEA^hF?3q9bB->v4a8i>(RQ0Yu~5|or2!at zqO9?3Y?vLdfI|7`*5maTc355NM48{RHg(xHp>u?;1bT5r(cs7wfrm%iZ=QEjd&Nf& zehy=@!`YefYl34!IBlRXhG0bisYvTvA`~=#t189|d3iD3Yrr0$?sAXUQR?gK8#F$t z5$@?GRTKsDn~%Cn`VVU!Ov%T=KT-fA0ColEs>RGr9JzY^Jw4DhGCGD+cGe23E3FvL z&bsC`c8w_fAlqbZU0rgRC4q8iH=baTvm3ii=lbC_Kt8pM0XS8V#@8 z2k|}w$t0N_hMFOHVc~$Ylklc?ayFVs%Mz4EaRTTii1sJgxO*qPey~4URM+vfhB8X# zG%2N8R>YV*ObrDxKFkZb7z&bNPD4O5LC)bPuC2)p{}k%R4DP`|g4dMKgS(2JV|6@z z)r|c%-wd3tAD-;-0HnJKr5cSwF}rVY{^d&gyx5Gb96Vy$46ag(+3f1E9~K^JmN*-^ z1n22Oir$t8+!KNp;Pk86Y_Zwtqx6ckIJV7(8~1SZ*r<8$s+FknJ<99pluUA$aU2hC zu)U|M_tbeGC!;^@HpTPK+{69arl&f-bCjD$a)Wo-(tM7i?nH4N&O9~Q7>erXP(=n9 zZJhnya0ZjkkM&9oI}G!FFdhlaCc@Z;o>7efE#~HklZe00$ zxD|jJeaCQ{>iaPIA^WyE;dxrptxNv1mo^tOoUBYzRu8>p8EKZ}p#MM?OW@S38^d8~ zLi|9R%PPZ&@x``B)IjT0f4!r1f;fTnWOQ5Rsw4ZZ-*fgkMYt$8 z{~(Qxj{Ffjq%>R9Zx$zD1*(dwzZQKPg@Wt>+^=HD_=dD=)|GS5(mDi3->#~UV0Wft zl5wu9s7nwVUX1A;m$^!3Qb}@UNXYIR{rQU*=O}Xyai{za9wa8>zECfGp_(hzjtiCs zBjSsaL8D2NjuIq>d6r>?#1yfeLqL&&vjKT1EBVmi%0(J1XcYgcEMOLX4YQ=c3vUoz z47G0tNH2qO6gEBqf#Jrq+U3@XP_2?6`po_w0;@n0&pbVc`2D>B6SBat->CLm(^IB6 zBYWdG-v|hp=0Y#|6Dj-|*NH#S8haYk{?Jx6wwv|Ap%3EneeOB!CxLc(^4@Oo9KFb! z@0MC#1#xH)ea1ez^Y--if?OO85c(c116G1>_0CJf`;6hF(p1DPFdu4utNbPDgV8PU zN>h|I?q7*?%$<}H(U|ZZzND6ZF}3VdpTrCFqlg??3~ATexa-#OszSS#pdbBTm>Ph6 z#wysm{zkCvuF^YP+EP+-{@(8(WmQ=Z1d|0rK`$!eK}<^sAqd{K?k@UhRl{nkulM_s zn0ELbuXh6(92t4mr6wPobGl{?F<11+qBcix=R;Y}D|*?OTS07T?sF6kU~Po(&tbo3 zQy#~`#g%+)aq2UNTl110YqVIo;|4&lBBm!&|IMe64if;*4U3t2 zCo`5xw9RBcj4b%?vDshVDX;kp+8N>(00`M~gkH;Pqkq&rAg)@E+i##uoT&Xr8OwgE zi-eiQA*Od)cQI!q;4)pec;;+^#XNRxwJ00y`MIN|9BU%{HouAvI;3esl>9|`Fw+WV zP>YZ7eQLfjvh7jxd4y{@%@9yl$P;GQlQX)uY*DZ zIst0Lr3@)ZWw3k!=B1-K?kk$Im0zoImtU$6w198J@?L zeZ4kvR<}EVCvw24$xZ=)8cFQkhFfGQ+vg(CO8z-Hb-ACh1>xj^f$$>wK06xX8TDj+QDQ&Hybpf%K5#?%n<} zs6XuoVmI3gzXfkLL_k}{a~O`|d-KHm0lMJFH_j1#$D>ouddrAsC2 z9Jk|At^^|nqmw#xxJmv*of6FGQ;ABRT!FBStLruJ+p|QdhR*b6Z|UTzF?6*ORk;ON{POmRb>2E%N`&9~>uA9L}%4wSFT^A+%qVpUZpS zs;9c&<)(_YD!IOHMTG|&LbO+28F8%beyG`@;1f>ZFn9X&?*_qPO-ewY@Q-Jm&IN9{ ziWc&Xahe8?(r9plsO4Xd>;gxOI8hKn7;&gVWYOS!w8zNNEdHaY8W>uxXJg(!5o(xl zxg#ATOAoWwtE3B<6spWJSQ%pxA@49H;OLV5bW;`wtu~EcD!#zK*grf`t-*pe`lQSX zE(>!@KMPuOuexW(wAae?-CwFP?iV{1oSu)V%o(-yyPYa$t#}WIQY~2Wa@I4QnY*Z< z?8l8GXKAC>T+Xbou8&YXe;v|%oD&c_aC#PSO?(7Hd`_F)h8t}bz_i$()$3nyZ`PN; zJ|PKn;vW4z&-X52W@pHYu@moVm@`92Mg5eFy7@0bb6AS$v80=bR2K>DxPCmJd4Hx9 z!kY0W_p8Z7(;VIrW0UjGAC_2DSX?j6=IgC&Z_Zemf9M%a8OJY{{UQQ~gGND!RIaUg zyRGZAIhT%pVP+Knx*JYeCqeCxr!g@eq6|_IHFi8g0cQeIaL;VJfFK(vaI zb2sD3EYleaVxU$e=$2fbzZ%!aL}nBhGBDBzk;#ip@=*v#1XnlG0=db3jm!Qu1ZLHb z*$VF%g1m`VRc20I}q`yv@Rd>bM{B5Pha zC`=+*4y<p;*^R| zwqahTgp|0-YM}P&T6W#*XTJw$WbWhqNY3b+5vkNft!`yKe4Evu@wUkFee3p#Gz8Yb zC+oYw`_FXyC+pdnuC2`u7AGF?Lyv)YK&;mgHnQ%|thjrO6{XG%#*K?%&>9*vo5{G0 z-%QKuz`Wgj(iB2Bzn|?*xgW<-{=kf#i^1nLLL%t4dZ4g!PJVK2g$nv&LrSYUuVF>S zn*SD;9yg;7&G#1#a3=tuR)sqOD9FJdKYB&{Y*KDO`m=d@!07EZH<@JZdRELvxjc7b zU%EAAR}1+pIfqbY{@O(z+|uuaw4?(Y{|1ZIZf^Gq&WA7PTu)T7qNP+Zze7$d6lEGw zG)5B`sltjRni0hxVH80!gwZ&BNkG4hW-5{TW|oKd{5uyDl*U>jo1@qFS1EQg~Om%OKD(_uq zw(J(W-?{sw(Q7fy8YYMa&MO6*F6KY&cKoq$R8Ms*6or6^-3;bmTmW#4%*67@ob` zg7PxgtMkcFt*um}arpe$OkU)9(+LDVd18x-UL)7zB17vz(*crIR7|!kF{nVMYQy9i zzWQgs6TD42nQ)@6HnZoKjPGW@q!UE^g2@68h=JLK859WF66g6LdDZ?$^!u-=fBh0U zei~3pvV2aJk}1Yr+$z+VslHm>mMCT1uF5EyoU*?yd{8+Fc|3$FM_l9pfRmp+pd8v_ zPQVpUNVZ{5GqqKp1DeC+gEKbr6A?RB0+$X9F)NQ9wV~wwLA&HSF~qrSW2Q5uw;V?y z>37 zRDM-lOcA@O3`{m+DMq@ti4O?r2%TBgmj~h!)CD6(kY&<}vmZr!_U+~>5+dVLfn*q* znsQu8R*&o+Ika^xCw$Ov=}U~un6yeKg$z;CQJ7lpxCiDC)nS7G>GV;r5Mbc0xm!m~o#E21~izcb*jLi`+o?wS{|09Pmj z-wwkSk$Fw9AX&?)u~PtMCqr-oTpal5UZvZyoo#$8i7)({nP45agV6TZxt_#aW6U8? zvl_T?7Wyn*%UH2!=3nI7f-MnD0&uR&O9mvEQsZO4>0QLd;gbyQxXT+6408_BIO|Q` zMHw3Wdn3!0@ac5>Vv-A3($&>we1ArERws^j*H)aUe7k0xO}Dk5iSQ&{weg{t zI-UJ;E5U5>f~D_y(dKNUo@)%QvT=4AnM2u1v7WU`1v{76H_`Y7YuUcHUtlO>;jIC* zYs06UB$@0zckLJ@#)Vt-V@TkQE^(+a@Oj7G)nhu55cJIQQn6m(5sy)+rPBzQGKtC2 z3J!QTs_^a9+f~l&-JjUIOMM3?p;vdQIxTWE6`n9{cH^nx#ERZV7cozhbq^`MH0eR==@m__cFX?K`4}kw3cwv8J(6T^!-(u$Lfmv_|iFR)uxpM zw)N@N>ga@|Q4Lnu#7z8wfbmmjE~agpOF^!!w3o8z9^=udWqGT3nq9}n)8^j(7PJ#x zoz9b5_=k2C^(RiVup*h8tuaPz;gn8*nBoJx0Y~U(T!(n9rCpLqzu+%hg7V*jo5gA# zezC;Qj87b@Bl^b8Kb%dPlsRQa_D9!clrjH%GfeLF8F+n1D>vD{Pslgne$z#rIXZI1 zgG*~RPh99svxwE!f0*2Kz?mfSM=8_#y4v@9t{{U^OiImyO8K^Jr=-mu@_w{I=gC)vQ`pMEzAW2GP-z zZ$raDYQGK`927PUMhAJ|B@}Q#sm{E+xmS!&KRnE%=HG62W^3Z4bSbrpC(_$+go}uU z?_J_PWqyBchAx8ZFY9f+jOD<0*58Oye-|4c=nO3O@dt?4WJk6$E{uJzC^D8c3D`6E z`r^v^lkU3g0FlGEouLhe&VbiWR_udZXNFX_F(D6I-BHFwrh}mc>>V=3T+>~(-Gp2^ z*T4PAS&kHh7Ysck?ev|A`_&L5mTzCH^9zIXW6)snhmT8VZ|(b^>gY(dA7zrJ($?>m zdOhh?SN&aU1Y$k^48}DvdCZHgEeVx0A}C!HVf59Y?qc3?*t4U~j4!mC!eQHOAA#S#)rZ_bBn za0K;Lt!TKL!>y*l5?eDZ;c$8Xs6qOUzd0+d{M4?m=@hAK<@3_5{%QK+o!DAj#&@^m zCYmt0NoBI%{HKPR7`do$A0XH4IaUPMF)MP6=C2I!oiANSy)Mgxuj`_F_4nL4Vs`O} ziT+7=9TkV$4Ffj|b2m$Aw2LMDg(V^+BFZl;%r7i?S6E0|OakO8ULhg)lQvwt^#APO z;ACNI<^BKfVEbj49CqOT?>D&FI#{~8nL9ZD|NF?deC>yQB$0h=(P(M3le4#rt+kCC zmhyl8#mtSq$}B7;CCRLA>1l82=Ei^99BpUrV!^EJLSV~-+UqnFoe(85L*qHM_8#|agx?7o}-P~O)U9ez7W*av* zXK6t}Pft$)TT8S6+J-&=OB?o(`0pN07MAw^HvR91GOJixnY-J&F(coGcCvSJcVTvQ bHb+}B^D`qyprWV#7Cr)Yx~1|?2^IW5S&Uj| literal 0 HcmV?d00001 diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index 6a0a4da73..5e55c5c64 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -31,42 +31,6 @@ export interface ModelPackage { } export const models: { [key: string]: ModelPackage } = { - moonshotChat: { - title: "Moonshot Chat", - description: "Moonshot AI provides high-performance large language models", - refUrl: "https://platform.moonshot.cn/", - params: { - title: "Moonshot-v1-8k", - model: "moonshot-v1-8k", - contextLength: 8192, - }, - icon: "moonshot.png", - dimensions: [ - { - name: "Context Window", - description: "The size of the model's context window", - options: { - "8K": { - model: "moonshot-v1-8k", - title: "Moonshot-v1-8k", - contextLength: 8192, - }, - "32K": { - model: "moonshot-v1-32k", - title: "Moonshot-v1-32k", - contextLength: 32768, - }, - "128K": { - model: "moonshot-v1-128k", - title: "Moonshot-v1-128k", - contextLength: 131072, - }, - }, - }, - ], - providerOptions: ["moonshot"], - isOpenSource: false, - }, llama31Chat: { title: "Llama3.1 Chat", description: "A model from Meta, fine-tuned for chat", @@ -147,39 +111,6 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["ollama", "groq", "llama.cpp"], isOpenSource: true, }, - moonshotChat: { - title: "Moonshot Chat", - description: "The latest model from Moonshot, fine-tuned for chat", - refUrl: "", - params: { - title: "Moonshot-8b", - model: "moonshot-8b", - contextLength: 8192, - }, - icon: "moonshot.png", - dimensions: [ - { - name: "Parameter Count", - description: "The number of parameters in the model", - options: { - "1b": { - model: "moonshot-1b", - title: "Moonshot-1b", - }, - "8b": { - model: "moonshot-8b", - title: "Moonshot-8b", - }, - "65b": { - model: "moonshot-65b", - title: "Moonshot-65b", - }, - }, - }, - ], - providerOptions: ["ollama", "lmstudio", "llama.cpp"], - isOpenSource: true, - }, deepseek: { title: "DeepSeek Coder", description: @@ -251,6 +182,42 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["nebius"], isOpenSource: true, }, + moonshotChat: { + title: "Moonshot Chat", + description: "Moonshot AI provides high-performance large language models", + refUrl: "https://platform.moonshot.cn/", + params: { + title: "Moonshot-v1-8k", + model: "moonshot-v1-8k", + contextLength: 8192, + }, + icon: "moonshot.png", + dimensions: [ + { + name: "Context Window", + description: "The size of the model's context window", + options: { + "8K": { + model: "moonshot-v1-8k", + title: "Moonshot-v1-8k", + contextLength: 8192, + }, + "32K": { + model: "moonshot-v1-32k", + title: "Moonshot-v1-32k", + contextLength: 32768, + }, + "128K": { + model: "moonshot-v1-128k", + title: "Moonshot-v1-128k", + contextLength: 131072, + }, + }, + }, + ], + providerOptions: ["moonshot"], + isOpenSource: false, + }, mistralOs: { title: "Mistral", description: diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 9c3ef2224..3100f1ddc 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -126,7 +126,7 @@ export const providers: Partial> = { refPage: "moonshot", apiKeyUrl: "https://docs.moonshot.cn/docs/getting-started", packages: [ - models.moonshotLlama7bChat, + models.moonshotChat, ], collectInputFor: [ { From 7a3f297b20cd1abe32dcd60b7bf5d6590f94eaff Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 18 Nov 2024 03:10:39 -0800 Subject: [PATCH 45/82] fix symbols not rendering bug --- .../markdown/StyledMarkdownPreview.tsx | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 29bef8c91..be438e408 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,4 +1,4 @@ -import { memo, useCallback, useEffect, useMemo } from "react"; +import { memo, useCallback, useEffect, useMemo, useRef } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -20,7 +20,7 @@ import StepContainerPreToolbar from "./StepContainerPreToolbar"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; import { RootState } from "../../redux/store"; -import { SymbolWithRange } from "core"; +import { ContextItemWithId, SymbolWithRange } from "core"; import SymbolLink from "./SymbolLink"; import { useSelector } from "react-redux"; @@ -153,17 +153,23 @@ function processCodeBlocks(tree: any) { const StyledMarkdownPreview = memo(function StyledMarkdownPreview( props: StyledMarkdownPreviewProps, ) { - // Grab context items from the user history item before it const contextItems = useSelector( (state: RootState) => state.state.history[props.itemIndex - 1]?.contextItems, ); const symbols = useSelector((state: RootState) => state.state.symbols); - const symbolsForContextItems: SymbolWithRange[] = useMemo(() => { + // The refs are a workaround because rehype options are stored on initiation + // So they won't use the most up-to-date state values + // So in this case we just put them in refs + const symbolsForContextItems = useRef([]); + const contextItemsRef = useRef([]); + useEffect(() => { + contextItemsRef.current = contextItems || []; if (!contextItems) { - return []; + symbolsForContextItems.current = []; } + // Get unique URIs and then find relevant symbols const contextUris = Array.from( new Set( contextItems.filter((item) => item?.uri).map((item) => item.uri!.value), @@ -176,7 +182,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( contextSymbols.push(...fileSymbols); } }); - return contextSymbols; + symbolsForContextItems.current = contextSymbols; }, [contextItems, symbols]); const [reactContent, setMarkdownSource] = useRemark({ @@ -261,8 +267,8 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( code: ({ node, ...codeProps }) => { const content = getCodeChildrenContent(codeProps.children); - if (content && contextItems) { - const ctxItem = contextItems.find((ctxItem) => + if (content && contextItemsRef.current) { + const ctxItem = contextItemsRef.current.find((ctxItem) => ctxItem.uri?.value.includes(content), ); if (ctxItem) { @@ -270,7 +276,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( return ; } - const exactSymbol = symbolsForContextItems.find( + const exactSymbol = symbolsForContextItems.current.find( (s) => s.name === content, ); if (exactSymbol) { @@ -278,7 +284,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( } // PARTIAL - this is the case where the llm returns e.g. `subtract(number)` instead of `subtract` - const partialSymbol = symbolsForContextItems.find((s) => + const partialSymbol = symbolsForContextItems.current.find((s) => content.startsWith(s.name), ); if (partialSymbol) { From 89a90f99baaf493f184a09aa6083a606076f9771 Mon Sep 17 00:00:00 2001 From: burlinchen Date: Mon, 18 Nov 2024 19:12:39 +0800 Subject: [PATCH 46/82] feat: add OpenAI, xAI, Replicate and free-trial model options to config schema --- extensions/vscode/config_schema.json | 123 +++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 88f3626d5..21fe76ccf 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -592,6 +592,129 @@ } } }, + { + "if": { + "properties": { + "provider": { + "enum": ["openai"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-4o", + "gpt-4o-mini", + "gpt-4", + "gpt-3.5-turbo-0613", + "gpt-4-32k", + "gpt-4-0125-preview", + "gpt-4-turbo", + "AUTODETECT" + ] + }, + { + "type": "string" + } + ] + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["xAI"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": ["grok-beta", "AUTODETECT"] + }, + { + "type": "string" + } + ] + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["replicate"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "llama3.1-8b", + "llama3.1-70b", + "llama3.1-405b", + "llama3-8b", + "llama3-70b", + "codellama-7b", + "codellama-13b", + "codellama-34b", + "llama2-7b", + "llama2-13b" + ] + }, + { + "type": "string" + } + ] + }, + "markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models).", + "x-intellij-html-description": "Select a pre-defined option, or find an exact model ID from Replicate here." + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["free-trial"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "enum": [ + "gpt-4o", + "codestral-latest", + "llama3.1-70b", + "llama3.1-405b", + "gpt-3.5-turbo", + "gemini-pro", + "claude-3-5-sonnet-latest", + "claude-3-haiku-20240307", + "AUTODETECT" + ] + } + } + } + }, { "if": { "properties": { From 2b828b0e7b455bf6b0f9ae5a6f6a705ab4cefe6a Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 18 Nov 2024 11:07:12 -0800 Subject: [PATCH 47/82] fix: failing tests --- core/autocomplete/filtering/test/testCases.ts | 44 +++++++++---------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts index 406faf66f..f0584ab48 100644 --- a/core/autocomplete/filtering/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -63,7 +63,7 @@ function sayHello() { `, llmOutput: `world!"); `, - expectedCompletion: "world!\");", + expectedCompletion: 'world!");', }, { description: "Should autocomplete Java when inside a block", @@ -131,10 +131,6 @@ public class Calculator { } `, expectedCompletion: ` - } - - public void subtract(double number) { - result -= number; }`, }, { @@ -489,8 +485,8 @@ echo calculateArea(5, 3);`, $colors = array("Red", "Green", <|fim|>); echo "First color is: " . $colors[0];`, - llmOutput: "\"Blue\"", - expectedCompletion: "\"Blue\"", + llmOutput: '"Blue"', + expectedCompletion: '"Blue"', filename: "colors.php", }, { @@ -775,8 +771,10 @@ func main() { FROM users u WHERE u.active = 1 <|fim|>`, - llmOutput: " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", - expectedCompletion: " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", + llmOutput: + " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", + expectedCompletion: + " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", }, { description: @@ -817,8 +815,8 @@ func main() {

Description text.

`, - llmOutput: "alt=\"Description of image\"", - expectedCompletion: "alt=\"Description of image\"", + llmOutput: 'alt="Description of image"', + expectedCompletion: 'alt="Description of image"', filename: "test.html", }, { @@ -930,8 +928,8 @@ public class App { <|fim|> ] }`, - llmOutput: ", { \"id\": 3, \"name\": \"Charlie\" }", - expectedCompletion: ", { \"id\": 3, \"name\": \"Charlie\" }", + llmOutput: ', { "id": 3, "name": "Charlie" }', + expectedCompletion: ', { "id": 3, "name": "Charlie" }', }, { description: "Should autocomplete within a CSV record", @@ -1237,8 +1235,8 @@ class Counter { :age 30 <|fim|> (println "User information loaded"))`, - llmOutput: ":location \"Unknown\"}", - expectedCompletion: ":location \"Unknown\"}", + llmOutput: ':location "Unknown"}', + expectedCompletion: ':location "Unknown"}', filename: "test.clj", }, { @@ -1301,8 +1299,8 @@ if (grade >= 90) { } else { print("C") }`, - llmOutput: "print(\"B\")", - expectedCompletion: "print(\"B\")", + llmOutput: 'print("B")', + expectedCompletion: 'print("B")', }, { description: "Should autocomplete R ggplot2 plot structure", @@ -1324,8 +1322,8 @@ ggplot(data=mtcars, aes(x=wt, y=mpg)) + <|fim|> } }`, - llmOutput: "s\"Hello, my name is $name and I am $age years old.\"", - expectedCompletion: "s\"Hello, my name is $name and I am $age years old.\"", + llmOutput: 's"Hello, my name is $name and I am $age years old."', + expectedCompletion: 's"Hello, my name is $name and I am $age years old."', }, { @@ -1335,8 +1333,8 @@ ggplot(data=mtcars, aes(x=wt, y=mpg)) + case class Person(name: String, age: Int, address: Address) val alice = Person("Alice", 30, Address("Wonderland", <|fim|>))`, - llmOutput: "\"12345\")", - expectedCompletion: "\"12345\")", + llmOutput: '"12345")', + expectedCompletion: '"12345")', }, { @@ -2066,8 +2064,8 @@ export default { /> `, - llmOutput: "name=\"World\"", - expectedCompletion: "name=\"World\"", + llmOutput: 'name="World"', + expectedCompletion: 'name="World"', }, { From 0a85f9be041f743ffdd9927a5822594455eeed1c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Nov 2024 20:19:02 +0000 Subject: [PATCH 48/82] build(deps): bump cross-spawn from 7.0.3 to 7.0.6 in /core Bumps [cross-spawn](https://github.com/moxystudio/node-cross-spawn) from 7.0.3 to 7.0.6. - [Changelog](https://github.com/moxystudio/node-cross-spawn/blob/master/CHANGELOG.md) - [Commits](https://github.com/moxystudio/node-cross-spawn/compare/v7.0.3...v7.0.6) --- updated-dependencies: - dependency-name: cross-spawn dependency-type: indirect ... Signed-off-by: dependabot[bot] --- core/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/package-lock.json b/core/package-lock.json index e817a7c6f..09e22ce96 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -6827,9 +6827,9 @@ } }, "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", From f76c69dfda0ae439f16a5e28db48328dfabb9309 Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 18 Nov 2024 12:23:43 -0800 Subject: [PATCH 49/82] chore: merge main --- core/llm/llms/Bedrock.ts | 11 ++++++-- .../StepContainer/StepContainer.tsx | 1 + gui/src/components/mainInput/resolveInput.ts | 26 +++++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 67d8a4167..9d9f3af87 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -14,6 +14,11 @@ import { import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; +/** + * Bedrock class implements AWS Bedrock LLM integration. + * It handles streaming completions and chat messages using AWS Bedrock runtime. + * Supports both text and image inputs through Claude 3 models. + */ class Bedrock extends BaseLLM { static providerName: ModelProvider = "bedrock"; static defaultOptions: Partial = { @@ -120,7 +125,9 @@ class Bedrock extends BaseLLM { // TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback. // For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes), // providing meaningful error messages to improve the user experience. - stopSequences: options.stop?.filter((stop) => stop.trim() !== "").slice(0, 4), + stopSequences: options.stop + ?.filter((stop) => stop.trim() !== "") + .slice(0, 4), }, }; } @@ -162,7 +169,7 @@ class Bedrock extends BaseLLM { try { return await fromIni({ profile: this.profile, - ignoreCache: true + ignoreCache: true, })(); } catch (e) { console.warn( diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index f5673e4e8..4fdd6eda2 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -93,6 +93,7 @@ export default function StepContainer(props: StepContainerProps) { )} diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index e8502d89c..4c7f4c640 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -256,4 +256,30 @@ function resolveParagraph(p: JSONContent): [string, MentionAttrs[], string] { return [text, contextItems, slashCommand]; } +export function hasSlashCommandOrContextProvider( + editorState: JSONContent, +): boolean { + if (!editorState.content) { + return false; + } + + for (const p of editorState.content) { + if (p.type === "paragraph" && p.content) { + for (const child of p.content) { + if (child.type === "slashcommand") { + return true; + } + if ( + child.type === "mention" && + child.attrs?.itemType === "contextProvider" + ) { + return true; + } + } + } + } + + return false; +} + export default resolveEditorContent; From 5fc0db9f54675d30eb1242b1966f1d17cdb2c71a Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 18 Nov 2024 12:45:24 -0800 Subject: [PATCH 50/82] Update stateSlice.ts --- gui/src/redux/slices/stateSlice.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 2cdd4e72e..8c0a8e759 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -4,7 +4,6 @@ import { ChatHistoryItem, ChatMessage, Checkpoint, - ContextItemId, ContextItemWithId, PersistedSessionInfo, PromptLog, @@ -12,9 +11,7 @@ import { import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { stripImages } from "core/llm/images"; -import { createSelector } from "reselect"; import { v4 as uuidv4, v4 } from "uuid"; -import { RootState } from "../store"; import { ApplyState } from "core/protocol/ideWebview"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. @@ -36,10 +33,10 @@ type State = { configError: ConfigValidationError[] | undefined; checkpoints: Checkpoint[]; curCheckpointIndex: number; - isMultifileEdit: boolean; applyStates: ApplyState[]; nextCodeBlockToApplyIndex: number; streamAborter: AbortController; + isMultifileEdit: boolean; }; const initialState: State = { @@ -270,7 +267,7 @@ export const stateSlice = createSlice({ state.active = false; state.isGatheringContext = false; - state.isInMultifileEdit = false; + state.isMultifileEdit = false; if (payload) { state.history = payload.history as any; state.title = payload.title; @@ -365,7 +362,7 @@ export const stateSlice = createSlice({ curApplyState.numDiffs = payload.numDiffs ?? curApplyState.numDiffs; curApplyState.filepath = payload.filepath ?? curApplyState.filepath; } - if(payload.status === "done"){ + if (payload.status === "done") { state.nextCodeBlockToApplyIndex++; } }, From 51e1c4216baa38d73141aca1d1e681eabf044b4b Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 18 Nov 2024 12:01:50 -0800 Subject: [PATCH 51/82] fix: snippets in fim prefix --- core/autocomplete/CompletionProvider.ts | 5 +- ...onstructPrompt.ts => aggregateSnippets.ts} | 2 +- core/autocomplete/templating/index.ts | 107 ++++++++++-------- 3 files changed, 66 insertions(+), 48 deletions(-) rename core/autocomplete/{constructPrompt.ts => aggregateSnippets.ts} (97%) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 9667352fd..bbb02c254 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -6,7 +6,7 @@ import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; -import { constructAutocompletePrompt } from "./constructPrompt.js"; +import { aggregateSnippets } from "./aggregateSnippets"; // @prettier-ignore import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; @@ -176,12 +176,13 @@ export class CompletionProvider { // or they might separately track recently edited ranges) const extraSnippets = await this._getExtraSnippets(helper); - let snippets = await constructAutocompletePrompt( + let snippets = await aggregateSnippets( helper, extraSnippets, this.contextRetrievalService, ); + debugger; const { prompt, prefix, suffix, completionOptions } = renderPrompt( snippets, await this.ide.getWorkspaceDirs(), diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/aggregateSnippets.ts similarity index 97% rename from core/autocomplete/constructPrompt.ts rename to core/autocomplete/aggregateSnippets.ts index f15b1c4e1..90196de87 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/aggregateSnippets.ts @@ -44,7 +44,7 @@ function getRangeOfPrefixAndSuffixWithBuffer( return prefixSuffixRangeWithBuffer; } -export async function constructAutocompletePrompt( +export async function aggregateSnippets( helper: HelperVars, extraSnippets: AutocompleteSnippet[], contextRetrievalService: ContextRetrievalService, diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 87bc7cfd9..51a4d857b 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -28,42 +28,30 @@ export function formatExternalSnippet( ]; return lines.join("\n"); } -function renderStringTemplate( - template: string, - prefix: string, - suffix: string, + +function getContextComments( snippets: AutocompleteSnippet[], lang: AutocompleteLanguageInfo, filepath: string, - reponame: string, + prefix: string, + suffix: string, ) { - const filename = getBasename(filepath); - const compiledTemplate = Handlebars.compile(template); - - // Format snippets as comments and prepend to prefix const formattedSnippets = snippets .map((snippet) => formatExternalSnippet(snippet.filepath, snippet.contents, lang), ) .join("\n"); if (formattedSnippets.length > 0) { - prefix = `${formattedSnippets}\n\n${prefix}`; - } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { - // If it's an empty file, include the file name as a comment - prefix = `${lang.singleLineComment} ${getLastNPathParts( - filepath, - 2, - )}\n${prefix}`; + return `${formattedSnippets}\n\n`; } - const prompt = compiledTemplate({ - prefix, - suffix, - filename, - reponame, - language: lang.name, - }); - return prompt; + const isEmptyFile = prefix.trim().length === 0 && suffix.trim().length === 0; + if (isEmptyFile) { + // Include the file name as a comment + prefix = `${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n`; + } + + return ""; } function getTemplate(helper: HelperVars): AutocompleteTemplate { @@ -77,6 +65,26 @@ function getTemplate(helper: HelperVars): AutocompleteTemplate { return getTemplateForModel(helper.modelName); } +function renderStringTemplate( + template: string, + prefix: string, + suffix: string, + lang: AutocompleteLanguageInfo, + filepath: string, + reponame: string, +) { + const filename = getBasename(filepath); + const compiledTemplate = Handlebars.compile(template); + + return compiledTemplate({ + prefix, + suffix, + filename, + reponame, + language: lang.name, + }); +} + export function renderPrompt( snippets: AutocompleteSnippet[], workspaceDirs: string[], @@ -87,6 +95,7 @@ export function renderPrompt( suffix: string; completionOptions: Partial | undefined; } { + debugger; // If prefix is manually passed let prefix = helper.prunedPrefix; let suffix = helper.prunedSuffix; @@ -102,6 +111,14 @@ export function renderPrompt( let { template, compilePrefixSuffix, completionOptions } = getTemplate(helper); + const contextComments = getContextComments( + snippets, + helper.lang, + helper.filepath, + prefix, + suffix, + ); + // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix // into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint if (compilePrefixSuffix) { @@ -112,29 +129,29 @@ export function renderPrompt( reponame, snippets, ); + } else { + prefix = `${contextComments}${prefix}`; } - // Templates can be passed as a Handlebars template string or a function - if (typeof template === "string") { - prompt = renderStringTemplate( - template, - prefix, - suffix, - snippets, - helper.lang, - helper.filepath, - reponame, - ); - } else { - prompt = template( - prefix, - suffix, - helper.filepath, - reponame, - helper.lang.name, - snippets, - ); - } + prompt = + // Templates can be passed as a Handlebars template string or a function + typeof template === "string" + ? renderStringTemplate( + template, + `${contextComments}${prefix}`, + suffix, + helper.lang, + helper.filepath, + reponame, + ) + : template( + prefix, + suffix, + helper.filepath, + reponame, + helper.lang.name, + snippets, + ); const stopTokens = getStopTokens( completionOptions, From f5293bc02e9326ada10933b1db0089c2c83043e3 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 18 Nov 2024 13:12:50 -0800 Subject: [PATCH 52/82] refactor: clean up code --- core/autocomplete/CompletionProvider.ts | 1 - core/autocomplete/templating/index.ts | 28 +++++++++++-------------- 2 files changed, 12 insertions(+), 17 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index bbb02c254..381dc63b7 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -182,7 +182,6 @@ export class CompletionProvider { this.contextRetrievalService, ); - debugger; const { prompt, prefix, suffix, completionOptions } = renderPrompt( snippets, await this.ide.getWorkspaceDirs(), diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 51a4d857b..8faf6bf6d 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -95,20 +95,13 @@ export function renderPrompt( suffix: string; completionOptions: Partial | undefined; } { - debugger; // If prefix is manually passed - let prefix = helper.prunedPrefix; - let suffix = helper.prunedSuffix; + let prefix = helper.input.manuallyPassPrefix || helper.prunedPrefix; + let suffix = helper.input.manuallyPassPrefix ? "" : helper.prunedSuffix; - if (helper.input.manuallyPassPrefix) { - prefix = helper.input.manuallyPassPrefix; - suffix = ""; - } - - let prompt: string; const reponame = getBasename(workspaceDirs[0] ?? "myproject"); - let { template, compilePrefixSuffix, completionOptions } = + const { template, compilePrefixSuffix, completionOptions } = getTemplate(helper); const contextComments = getContextComments( @@ -133,7 +126,7 @@ export function renderPrompt( prefix = `${contextComments}${prefix}`; } - prompt = + const prompt = // Templates can be passed as a Handlebars template string or a function typeof template === "string" ? renderStringTemplate( @@ -159,10 +152,13 @@ export function renderPrompt( helper.modelName, ); - completionOptions = { - ...completionOptions, - stop: stopTokens, + return { + prompt, + prefix, + suffix, + completionOptions: { + ...completionOptions, + stop: stopTokens, + }, }; - - return { prompt, prefix, suffix, completionOptions }; } From 0c217a40082c2c244de4f4f8c955d96314f130da Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 18 Nov 2024 13:27:13 -0800 Subject: [PATCH 53/82] fix: remove duplicated context comments --- core/autocomplete/templating/index.ts | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 8faf6bf6d..d0d67db85 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -104,14 +104,6 @@ export function renderPrompt( const { template, compilePrefixSuffix, completionOptions } = getTemplate(helper); - const contextComments = getContextComments( - snippets, - helper.lang, - helper.filepath, - prefix, - suffix, - ); - // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix // into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint if (compilePrefixSuffix) { @@ -123,6 +115,13 @@ export function renderPrompt( snippets, ); } else { + const contextComments = getContextComments( + snippets, + helper.lang, + helper.filepath, + prefix, + suffix, + ); prefix = `${contextComments}${prefix}`; } @@ -131,7 +130,7 @@ export function renderPrompt( typeof template === "string" ? renderStringTemplate( template, - `${contextComments}${prefix}`, + prefix, suffix, helper.lang, helper.filepath, From d56b48cad2fcb0bb8e4a3e0dd3e32ab7f704d762 Mon Sep 17 00:00:00 2001 From: burlinchen Date: Tue, 19 Nov 2024 07:51:56 +0800 Subject: [PATCH 54/82] fix: add mistral model options to config schema --- extensions/vscode/config_schema.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 21fe76ccf..7761b605f 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -771,6 +771,9 @@ "starcoder-1b", "starcoder-3b", "starcoder2-3b", + "mistral-tiny", + "mistral-small", + "mistral-medium", "qwen2.5-coder:1.5b", "qwen2.5-coder:3b", "qwen2.5-coder:7b", From 0d0c6de7124a30f2edc088f0f92b747452c8060f Mon Sep 17 00:00:00 2001 From: Rahi Dehzani Date: Tue, 19 Nov 2024 17:20:55 +0100 Subject: [PATCH 55/82] Adding Go doc to Pre-Indexed Documentations --- core/indexing/docs/preIndexedDocs.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 01935af9e..99a8ddc8a 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -330,6 +330,12 @@ const preIndexedDocs: Record< startUrl: "https://llama-stack.readthedocs.io/", rootUrl: "https://llama-stack.readthedocs.io/", }, + "https://go.dev/doc": { + title: "Go", + startUrl: "https://go.dev/doc", + rootUrl: "https://go.dev", + faviconUrl: "https://go.dev/favicon.ico", + }, }; export default preIndexedDocs; From 416fdbb69ff17f3ab02f6d2b7dce0ea5a7db058c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 09:50:10 -0800 Subject: [PATCH 56/82] unified indexing peeks --- core/indexing/docs/DocsService.ts | 138 ++++++++------- gui/src/components/dialogs/AddDocsDialog.tsx | 8 +- .../components/indexing/ChatIndexingPeeks.tsx | 161 +++++++++++------- .../components/indexing/IndexingStatuses.tsx | 1 - gui/src/components/indexing/utils.ts | 1 - gui/src/pages/gui/Chat.tsx | 1 - gui/src/redux/slices/stateSlice.ts | 65 +------ 7 files changed, 178 insertions(+), 197 deletions(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index ffb251c64..838e8fb54 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -10,6 +10,7 @@ import { IndexingStatusMap, IndexingStatus, SiteIndexingConfig, + IdeInfo, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; import { addContextProvider } from "../../config/util"; @@ -101,12 +102,14 @@ export default class DocsService { private sqliteDb?: Database; private docsCrawler!: DocsCrawler; + private ideInfoPromise: Promise; constructor( configHandler: ConfigHandler, private readonly ide: IDE, private readonly messenger?: IMessenger, ) { + this.ideInfoPromise = this.ide.getIdeInfo(); this.isInitialized = this.init(configHandler); } @@ -135,6 +138,31 @@ export default class DocsService { readonly statuses: IndexingStatusMap = new Map(); + // Function for GUI to retrieve initial pending statuses + // And kickoff indexing where needed + async initStatuses() { + this.config?.docs?.forEach(async (doc) => { + const currentStatus = this.statuses.get(doc.startUrl); + if (currentStatus) { + this.handleStatusUpdate(currentStatus); + } else { + this.handleStatusUpdate({ + type: "docs", + id: doc.startUrl, + embeddingsProviderId: this.config.embeddingsProvider.id, + isReindexing: false, + progress: 0, + description: "Pending", + status: "pending", + title: doc.title, + debugInfo: `max depth: ${doc.maxDepth}`, + icon: doc.faviconUrl, + url: doc.startUrl, + }); + } + }); + } + handleStatusUpdate(update: IndexingStatus) { this.statuses.set(update.id, update); this.messenger?.send("indexing/statusUpdate", update); @@ -143,6 +171,7 @@ export default class DocsService { abort(startUrl: string) { const status = this.statuses.get(startUrl); if (status) { + this.docsIndexingQueue.delete(startUrl); this.handleStatusUpdate({ ...status, status: "aborted", @@ -177,7 +206,7 @@ export default class DocsService { * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. */ async canUsePreindexedDocs() { - const ideInfo = await this.ide.getIdeInfo(); + const ideInfo = await this.ideInfoPromise; if (ideInfo.ideType === "jetbrains") { return false; } @@ -322,12 +351,15 @@ export default class DocsService { ): Promise { const { startUrl } = siteIndexingConfig; + // Queue - indexAndAdd is invoked circularly by config edits. This prevents duplicate runs if (this.docsIndexingQueue.has(startUrl)) { - console.debug("Already in queue"); return; } + const embeddingsProvider = await this.getEmbeddingsProvider(); + this.docsIndexingQueue.add(startUrl); + const indexExists = await this.hasMetadata(startUrl); const fixedStatus: Pick< @@ -366,8 +398,6 @@ export default class DocsService { } } - // Mark the site as currently being indexed - this.docsIndexingQueue.add(startUrl); try { this.handleStatusUpdate({ ...fixedStatus, @@ -378,7 +408,7 @@ export default class DocsService { const articles: Article[] = []; let processedPages = 0; - let estimatedProgress = 0; // progress heuristic = sum series 1/(2^n) from n=1 to pages + 1. Alternative e.g. sum 1/(2^n) + let estimatedProgress = 0; // Crawl pages and retrieve info as articles for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { @@ -392,7 +422,10 @@ export default class DocsService { ...fixedStatus, description: `Finding subpages (${page.path})`, status: "indexing", - progress: 0.4 * estimatedProgress, // 0% -> 40%, a heuristic approach for progress calculation + progress: + 0.3 * estimatedProgress + + Math.min(0.2, (0.2 * processedPages) / 500), + // For the first 50%, 30% is sum of series 1/(2^n) and the other 20% is based on number of files/ 500 max }); const article = pageToArticle(page); @@ -425,7 +458,7 @@ export default class DocsService { ...fixedStatus, status: "indexing", description: `Creating Embeddings: ${article.subpath}`, - progress: 0.4 + 0.4 * (i / articles.length), // 40% -> 80% + progress: 0.5 + 0.3 * (i / articles.length), // 50% -> 80% }); try { @@ -466,9 +499,7 @@ export default class DocsService { }); void this.ide.showToast("info", `Failed to index ${startUrl}`); - this.docsIndexingQueue.delete(startUrl); - return; } @@ -540,28 +571,34 @@ export default class DocsService { } } - // Function for GUI to retrieve initial pending statuses - // And kickoff indexing where needed - async initStatuses() { - this.config?.docs?.forEach(async (doc) => { - const currentStatus = this.statuses.get(doc.startUrl); - if (currentStatus) { - this.handleStatusUpdate(currentStatus); - } else { - this.handleStatusUpdate({ - type: "docs", - id: doc.startUrl, - embeddingsProviderId: this.config.embeddingsProvider.id, - isReindexing: false, - progress: 0, - description: "Pending", - status: "pending", - title: doc.title, - debugInfo: `max depth: ${doc.maxDepth}`, - icon: doc.faviconUrl, - url: doc.startUrl, - }); - } + // When user requests a pre-indexed doc for the first time + // And pre-indexed embeddings are supported + // Fetch pre-indexed embeddings from S3, add to Lance, and then search those + private async fetchAndAddPreIndexedDocEmbeddings(title: string) { + const embeddingsProvider = await this.getEmbeddingsProvider(true); + + const data = await downloadFromS3( + S3Buckets.continueIndexedDocs, + getS3Filename(embeddingsProvider.id, title), + ); + + const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; + const startUrl = new URL(siteEmbeddings.url).toString(); + + const faviconUrl = preIndexedDocs[startUrl].faviconUrl; + const favicon = + typeof faviconUrl === "string" + ? await getFaviconBase64(faviconUrl) + : undefined; + + await this.add({ + favicon, + siteIndexingConfig: { + startUrl, + title: siteEmbeddings.title, + }, + chunks: siteEmbeddings.chunks, + embeddings: siteEmbeddings.chunks.map((c) => c.embedding), }); } @@ -704,7 +741,7 @@ export default class DocsService { const currentlyIndexedDocs = await this.listMetadata(); const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); - // Anything found in sqlite but not in new config should be deleted + // Anything found in sqlite but not in new config should be deleted if not preindexed const deletedDocs = currentlyIndexedDocs.filter( (doc) => !preIndexedDocs[doc.startUrl] && @@ -717,12 +754,12 @@ export default class DocsService { const newDocs: SiteIndexingConfig[] = []; const changedDocs: SiteIndexingConfig[] = []; for (const doc of newConfigDocs) { - const oldConfigDoc = oldConfigDocs.find( - (d) => d.startUrl === doc.startUrl, - ); const currentIndexedDoc = currentStartUrls.includes(doc.startUrl); if (currentIndexedDoc) { + const oldConfigDoc = oldConfigDocs.find( + (d) => d.startUrl === doc.startUrl, + ); if ( oldConfigDoc && (oldConfigDoc.maxDepth !== doc.maxDepth || @@ -976,37 +1013,6 @@ export default class DocsService { this.messenger?.send("refreshSubmenuItems", undefined); } - // When user requests a pre-indexed doc for the first time - // And pre-indexed embeddings are supported - // Fetch pre-indexed embeddings from S3, add to Lance, and then search those - private async fetchAndAddPreIndexedDocEmbeddings(title: string) { - const embeddingsProvider = await this.getEmbeddingsProvider(true); - - const data = await downloadFromS3( - S3Buckets.continueIndexedDocs, - getS3Filename(embeddingsProvider.id, title), - ); - - const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; - const startUrl = new URL(siteEmbeddings.url).toString(); - - const faviconUrl = preIndexedDocs[startUrl].faviconUrl; - const favicon = - typeof faviconUrl === "string" - ? await getFaviconBase64(faviconUrl) - : undefined; - - await this.add({ - favicon, - siteIndexingConfig: { - startUrl, - title: siteEmbeddings.title, - }, - chunks: siteEmbeddings.chunks, - embeddings: siteEmbeddings.chunks.map((c) => c.embedding), - }); - } - /** * Currently this deletes re-crawls + re-indexes all docs. * A more optimal solution in the future will be to create diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index f373f4bc0..1a8682150 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -9,7 +9,10 @@ import { useContext, useLayoutEffect, useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Button, HelperText, Input, lightGray } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { setShowDialog } from "../../redux/slices/uiStateSlice"; +import { + setDialogMessage, + setShowDialog, +} from "../../redux/slices/uiStateSlice"; import { RootState } from "../../redux/store"; import IndexingStatusViewer from "../indexing/IndexingStatus"; @@ -57,8 +60,6 @@ function AddDocsDialog() { setStartUrl(""); setFaviconUrl(""); - // dispatch(setShowDialog(false)); - posthog.capture("add_docs_gui", { url: startUrl }); } @@ -103,6 +104,7 @@ function AddDocsDialog() { +
diff --git a/gui/src/components/indexing/ChatIndexingPeeks.tsx b/gui/src/components/indexing/ChatIndexingPeeks.tsx index f3a609c68..c77bdc323 100644 --- a/gui/src/components/indexing/ChatIndexingPeeks.tsx +++ b/gui/src/components/indexing/ChatIndexingPeeks.tsx @@ -1,14 +1,15 @@ -import { useSelector } from "react-redux"; +import { useDispatch, useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import { IndexingStatus } from "core"; import { useMemo, useState } from "react"; import { useNavigate } from "react-router-dom"; import { ArrowPathIcon, EyeSlashIcon } from "@heroicons/react/24/outline"; +import { setIndexingChatPeekHidden } from "../../redux/slices/stateSlice"; interface MergedIndexingState { displayName: string; - type: string; + type: IndexingStatus["type"]; titles: IndexingStatus["title"][]; progressPercentage: number; } @@ -21,14 +22,16 @@ const mergeProgress = (states: IndexingStatus[]): number => { export interface ChatIndexingPeekProps { state: MergedIndexingState; - hidden: boolean; - setHidden: (hidden: boolean) => void; } -function ChatIndexingPeek({ state, hidden, setHidden }: ChatIndexingPeekProps) { +function ChatIndexingPeek({ state }: ChatIndexingPeekProps) { const navigate = useNavigate(); + const dispatch = useDispatch(); + const hiddenPeeks = useSelector( + (store: RootState) => store.state.indexing.hiddenChatPeekTypes, + ); - if (hidden) return null; + if (hiddenPeeks[state.type]) return null; return (
{ - setHidden(true); + dispatch( + setIndexingChatPeekHidden({ type: state.type, hidden: true }), + ); e.stopPropagation(); }} /> @@ -75,13 +80,8 @@ function ChatIndexingPeek({ state, hidden, setHidden }: ChatIndexingPeekProps) { function ChatIndexingPeeks() { const indexingStatuses = useSelector( - (store: RootState) => store.state.indexingStatuses, + (store: RootState) => store.state.indexing.statuses, ); - - const [hidden, setHidden] = useState<{ - [key: string]: boolean; - }>({}); - const mergedIndexingStates: MergedIndexingState[] = useMemo(() => { const mergedStates: MergedIndexingState[] = []; @@ -95,12 +95,6 @@ function ChatIndexingPeeks() { titles: docsStates.map((state) => state.title), progressPercentage: mergeProgress(docsStates), }); - } else { - // So that next indexing will show again if hidden - setHidden({ - ...hidden, - docs: false, - }); } return mergedStates; }, [indexingStatuses]); @@ -110,18 +104,7 @@ function ChatIndexingPeeks() { return (
{mergedIndexingStates.map((state) => { - return ( -
); diff --git a/gui/src/components/indexing/IndexingStatuses.tsx b/gui/src/components/indexing/IndexingStatuses.tsx index da10dde90..ecc35189d 100644 --- a/gui/src/components/indexing/IndexingStatuses.tsx +++ b/gui/src/components/indexing/IndexingStatuses.tsx @@ -11,7 +11,7 @@ import AddDocsDialog from "../dialogs/AddDocsDialog"; function IndexingStatuses() { const indexingStatuses = useSelector( - (store: RootState) => store.state.indexingStatuses, + (store: RootState) => store.state.indexing.statuses, ); const docsStatuses = useMemo(() => { const docs = Object.values(indexingStatuses).filter( @@ -28,6 +28,7 @@ function IndexingStatuses() { {/*
*/} + {/* TODO add some way to hide, scroll, etc. */}
Manage your documentation sources diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 7027ac54c..b31e4b01e 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -38,7 +38,10 @@ type State = { isMultifileEdit: boolean; applyStates: ApplyState[]; nextCodeBlockToApplyIndex: number; - indexingStatuses: Record; + indexing: { + hiddenChatPeekTypes: Record; + statuses: Record; + }; }; const initialState: State = { @@ -70,7 +73,12 @@ const initialState: State = { curCheckpointIndex: 0, nextCodeBlockToApplyIndex: 0, applyStates: [], - indexingStatuses: {}, + indexing: { + statuses: {}, + hiddenChatPeekTypes: { + docs: false, + }, + }, }; export const stateSlice = createSlice({ @@ -366,10 +374,37 @@ export const stateSlice = createSlice({ state, { payload }: PayloadAction, ) => { - state.indexingStatuses = { - ...state.indexingStatuses, + state.indexing.statuses = { + ...state.indexing.statuses, [payload.id]: payload, }; + + // This check is so that if all indexing is stopped for e.g. docs + // The next time docs indexing starts the peek will show again + const indexingThisType = Object.values(state.indexing.statuses).filter( + (status) => + status.type === payload.type && status.status === "indexing", + ); + if (indexingThisType.length === 0) { + state.indexing.hiddenChatPeekTypes = { + ...state.indexing.hiddenChatPeekTypes, + [payload.type]: false, + }; + } + }, + setIndexingChatPeekHidden: ( + state, + { + payload, + }: PayloadAction<{ + type: IndexingStatus["type"]; + hidden: boolean; + }>, + ) => { + state.indexing.hiddenChatPeekTypes = { + ...state.indexing.hiddenChatPeekTypes, + [payload.type]: payload.hidden, + }; }, }, }); @@ -401,6 +436,7 @@ export const { resetNextCodeBlockToApplyIndex, updateApplyState, updateIndexingStatus, + setIndexingChatPeekHidden, } = stateSlice.actions; export default stateSlice.reducer; From 499b1223b7728e3766f41bc6fdf7cceb80215d37 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 13:09:47 -0800 Subject: [PATCH 60/82] docs UI tweaks --- gui/src/components/dialogs/AddDocsDialog.tsx | 1 - gui/src/components/indexing/IndexingStatus.tsx | 7 ++++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index d66c315fe..098194886 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -15,7 +15,6 @@ import { } from "../../redux/slices/uiStateSlice"; import { RootState } from "../../redux/store"; import IndexingStatusViewer from "../indexing/IndexingStatus"; -import { NewSessionButton } from "../mainInput/NewSessionButton"; function AddDocsDialog() { const posthog = usePostHog(); diff --git a/gui/src/components/indexing/IndexingStatus.tsx b/gui/src/components/indexing/IndexingStatus.tsx index 98014c27b..6fe72c741 100644 --- a/gui/src/components/indexing/IndexingStatus.tsx +++ b/gui/src/components/indexing/IndexingStatus.tsx @@ -5,6 +5,8 @@ import { usePostHog } from "posthog-js/react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { ArrowPathIcon, + ArrowRightStartOnRectangleIcon, + ArrowTopRightOnSquareIcon, CheckCircleIcon, PauseCircleIcon, XMarkIcon, @@ -60,7 +62,7 @@ function IndexingStatusViewer({ status }: IndexingStatusViewerProps) { className={`flex flex-row items-center justify-between gap-2 text-sm`} >
{ if (status.url) { ideMessenger.post("openUrl", status.url); @@ -73,6 +75,9 @@ function IndexingStatusViewer({ status }: IndexingStatusViewerProps) {

{status.title ?? status.id}

+ {!!status.url && ( + + )}
{status.status === "pending" ? (
Pending...
From 29fb0cdb802411df16ad694ed1ffebe03a38b83f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 13:11:43 -0800 Subject: [PATCH 61/82] docs ui tweaks --- gui/src/components/indexing/IndexingStatuses.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gui/src/components/indexing/IndexingStatuses.tsx b/gui/src/components/indexing/IndexingStatuses.tsx index ecc35189d..7441212f9 100644 --- a/gui/src/components/indexing/IndexingStatuses.tsx +++ b/gui/src/components/indexing/IndexingStatuses.tsx @@ -2,7 +2,7 @@ import { useMemo } from "react"; import { useDispatch, useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import IndexingStatusViewer from "./IndexingStatus"; -import { Button } from ".."; +import { Button, SecondaryButton } from ".."; import { setDialogMessage, setShowDialog, @@ -39,14 +39,14 @@ function IndexingStatuses() { return ; }) ) : ( - + )}
//
From c06c31edb31f6c1837ef9758f6e7161e75b34961 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 15:00:40 -0800 Subject: [PATCH 62/82] dont clear non-empty messages on error --- core/core.ts | 56 +++++++++-------- core/llm/llms/Anthropic.ts | 8 ++- gui/src/hooks/useChatHandler.ts | 99 +++++++++++++++--------------- gui/src/pages/gui/Chat.tsx | 9 +-- gui/src/redux/slices/stateSlice.ts | 15 +++-- 5 files changed, 96 insertions(+), 91 deletions(-) diff --git a/core/core.ts b/core/core.ts index 853666174..14db3517d 100644 --- a/core/core.ts +++ b/core/core.ts @@ -540,33 +540,39 @@ export class Core { } }, 100); - for await (const content of slashCommand.run({ - input, - history, - llm, - contextItems, - params, - ide, - addContextItem: (item) => { - void messenger.request("addContextItem", { - item, - historyIndex, - }); - }, - selectedCode, - config, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - })) { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - break; - } - if (content) { - yield { content }; + try { + for await (const content of slashCommand.run({ + input, + history, + llm, + contextItems, + params, + ide, + addContextItem: (item) => { + void messenger.request("addContextItem", { + item, + historyIndex, + }); + }, + selectedCode, + config, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), + })) { + if (abortedMessageIds.has(msg.messageId)) { + abortedMessageIds.delete(msg.messageId); + clearInterval(checkActiveInterval); + break; + } + if (content) { + yield { content }; + } } + } catch (e) { + throw e; + } finally { + clearInterval(checkActiveInterval); } - clearInterval(checkActiveInterval); yield { done: true, content: "" }; } on("command/run", (msg) => diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 8db42eefa..dfb3065cd 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -37,7 +37,9 @@ class Anthropic extends BaseLLM { public convertMessages(msgs: ChatMessage[]): any[] { // should be public for use within VertexAI - const filteredmessages = msgs.filter((m) => m.role !== "system"); + const filteredmessages = msgs.filter( + (m) => m.role !== "system" && !!m.content, + ); const lastTwoUserMsgIndices = filteredmessages .map((msg, index) => (msg.role === "user" ? index : -1)) .filter((index) => index !== -1) @@ -146,7 +148,9 @@ class Anthropic extends BaseLLM { } for await (const value of streamSse(response)) { - if (value.type == "message_start") {console.log(value);} + if (value.type == "message_start") { + console.log(value); + } if (value.delta?.text) { yield { role: "assistant", content: value.delta.text }; } diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index ce599454d..02f44e1be 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -24,7 +24,7 @@ import { IIdeMessenger } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { addPromptCompletionPair, - clearLastResponse, + clearLastEmptyResponse, initNewActiveMessage, resubmitAtIndex, setCurCheckpointIndex, @@ -69,35 +69,27 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const abortController = new AbortController(); const cancelToken = abortController.signal; - try { - if (!defaultModel) { - throw new Error("Default model not defined"); + if (!defaultModel) { + throw new Error("Default model not defined"); + } + const gen = ideMessenger.llmStreamChat( + defaultModel.title, + cancelToken, + messages, + ); + let next = await gen.next(); + while (!next.done) { + if (!activeRef.current) { + abortController.abort(); + break; } - const gen = ideMessenger.llmStreamChat( - defaultModel.title, - cancelToken, - messages, - ); - let next = await gen.next(); + dispatch(streamUpdate(stripImages((next.value as ChatMessage).content))); + next = await gen.next(); + } - while (!next.done) { - if (!activeRef.current) { - abortController.abort(); - break; - } - dispatch( - streamUpdate(stripImages((next.value as ChatMessage).content)), - ); - next = await gen.next(); - } - - let returnVal = next.value as PromptLog; - if (returnVal) { - dispatch(addPromptCompletionPair([returnVal])); - } - } catch (e) { - // If there's an error, we should clear the response so there aren't two input boxes - dispatch(clearLastResponse()); + let returnVal = next.value as PromptLog; + if (returnVal) { + dispatch(addPromptCompletionPair([returnVal])); } } @@ -150,29 +142,35 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } }, 100); - for await (const update of ideMessenger.streamRequest( - "command/run", - { - input, - history: messages, - modelTitle, - slashCommandName: slashCommand.name, - contextItems, - params: slashCommand.params, - historyIndex, - selectedCode, - }, - cancelToken, - )) { - if (!activeRef.current) { - abortController.abort(); - break; - } - if (typeof update === "string") { - dispatch(streamUpdate(update)); + try { + for await (const update of ideMessenger.streamRequest( + "command/run", + { + input, + history: messages, + modelTitle, + slashCommandName: slashCommand.name, + contextItems, + params: slashCommand.params, + historyIndex, + selectedCode, + }, + cancelToken, + )) { + if (!activeRef.current) { + abortController.abort(); + clearInterval(checkActiveInterval); + break; + } + if (typeof update === "string") { + dispatch(streamUpdate(update)); + } } + } catch (e) { + throw e; + } finally { + clearInterval(checkActiveInterval); } - clearInterval(checkActiveInterval); } async function streamResponse( @@ -252,8 +250,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } } - // dispatch(addContextItems(contextItems)); - const message: ChatMessage = { role: "user", content, @@ -313,6 +309,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { ); } } catch (e: any) { + dispatch(clearLastEmptyResponse()); console.debug("Error streaming response: ", e); ideMessenger.post("showToast", [ "error", diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 345fe6f37..aee6d9416 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -41,7 +41,7 @@ import { useTutorialCard } from "../../hooks/useTutorialCard"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; import { - clearLastResponse, + clearLastEmptyResponse, newSession, setInactive, } from "../../redux/slices/stateSlice"; @@ -399,12 +399,7 @@ export function Chat() { { dispatch(setInactive()); - if ( - state.history[state.history.length - 1]?.message.content - .length === 0 - ) { - dispatch(clearLastResponse()); - } + dispatch(clearLastEmptyResponse()); }} > {getMetaKeyLabel()} ⌫ Cancel diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 2d5cb1267..9c3292c1a 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -116,13 +116,16 @@ export const stateSlice = createSlice({ setIsGatheringContext: (state, { payload }: PayloadAction) => { state.isGatheringContext = payload; }, - clearLastResponse: (state) => { + clearLastEmptyResponse: (state) => { if (state.history.length < 2) { return; } - state.mainEditorContent = - state.history[state.history.length - 2].editorState; - state.history = state.history.slice(0, -2); + // Only clear in the case of an empty message + if (!state.history[state.history.length - 1]?.message.content.length) { + state.mainEditorContent = + state.history[state.history.length - 2].editorState; + state.history = state.history.slice(0, -2); + } }, consumeMainEditorContent: (state) => { state.mainEditorContent = undefined; @@ -354,7 +357,7 @@ export const stateSlice = createSlice({ curApplyState.numDiffs = payload.numDiffs ?? curApplyState.numDiffs; curApplyState.filepath = payload.filepath ?? curApplyState.filepath; } - if(payload.status === "done"){ + if (payload.status === "done") { state.nextCodeBlockToApplyIndex++; } }, @@ -380,7 +383,7 @@ export const { setActive, initNewActiveMessage, setMessageAtIndex, - clearLastResponse, + clearLastEmptyResponse, consumeMainEditorContent, setSelectedProfileId, deleteMessage, From 1adbd9a456f6c4c2f56b78d6bd5e3b8737f60ec5 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 19 Nov 2024 15:21:55 -0800 Subject: [PATCH 63/82] feat: use git diff, improve comment formatting --- core/autocomplete/CompletionProvider.ts | 23 +++++---- core/autocomplete/aggregateSnippets.ts | 45 +---------------- core/autocomplete/context/ranking/index.ts | 46 ----------------- core/autocomplete/templating/index.ts | 59 +++++++++++++--------- core/autocomplete/util/HelperVars.ts | 9 +++- core/config/types.ts | 2 +- core/index.d.ts | 2 +- core/util/parameters.ts | 4 +- extensions/vscode/src/util/ideUtils.ts | 19 +++---- packages/config-types/src/index.ts | 2 +- 10 files changed, 70 insertions(+), 141 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 381dc63b7..9fe11df79 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -176,17 +176,22 @@ export class CompletionProvider { // or they might separately track recently edited ranges) const extraSnippets = await this._getExtraSnippets(helper); - let snippets = await aggregateSnippets( - helper, - extraSnippets, - this.contextRetrievalService, - ); - - const { prompt, prefix, suffix, completionOptions } = renderPrompt( - snippets, + const [snippets, diff, workspaceDirs] = await Promise.all([ + await aggregateSnippets( + helper, + extraSnippets, + this.contextRetrievalService, + ), + await this.ide.getDiff(true), await this.ide.getWorkspaceDirs(), + ]); + + const { prompt, prefix, suffix, completionOptions } = renderPrompt({ + snippets, + diff, + workspaceDirs, helper, - ); + }); // Completion let completion: string | undefined = ""; diff --git a/core/autocomplete/aggregateSnippets.ts b/core/autocomplete/aggregateSnippets.ts index 90196de87..f47b9021f 100644 --- a/core/autocomplete/aggregateSnippets.ts +++ b/core/autocomplete/aggregateSnippets.ts @@ -1,10 +1,7 @@ -import { Position, Range } from "../index.js"; - import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, rankAndOrderSnippets, - removeRangeFromSnippets, type AutocompleteSnippet, } from "./context/ranking/index.js"; import { HelperVars } from "./util/HelperVars.js"; @@ -21,29 +18,6 @@ function filterSnippetsAlreadyInCaretWindow( ); } -function getRangeOfPrefixAndSuffixWithBuffer( - prefix: string, - suffix: string, - caretPos: Position, -): Range { - // Remove prefix range from snippets - const prefixLines = prefix.split("\n").length; - const suffixLines = suffix.split("\n").length; - const buffer = 8; - const prefixSuffixRangeWithBuffer = { - start: { - line: caretPos.line - prefixLines - buffer, - character: 0, - }, - end: { - line: caretPos.line + suffixLines + buffer, - character: 0, - }, - }; - - return prefixSuffixRangeWithBuffer; -} - export async function aggregateSnippets( helper: HelperVars, extraSnippets: AutocompleteSnippet[], @@ -61,24 +35,7 @@ export async function aggregateSnippets( const scoredSnippets = rankAndOrderSnippets(snippets, helper); - // This might be redundant with filterSnippetsAlreadyInCaretWindow - let finalSnippets = removeRangeFromSnippets( - scoredSnippets, - helper.filepath.split("://").slice(-1)[0], - getRangeOfPrefixAndSuffixWithBuffer( - helper.prunedPrefix, - helper.prunedSuffix, - helper.pos, - ), - ); - - // Filter snippets below similarity threshold - finalSnippets = finalSnippets.filter( - (snippet) => - snippet.score >= helper.options.recentlyEditedSimilarityThreshold, - ); - - finalSnippets = fillPromptWithSnippets( + const finalSnippets = fillPromptWithSnippets( scoredSnippets, helper.maxSnippetTokens, helper.modelName, diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index e761d994e..3e83afca5 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -153,24 +153,6 @@ export function fillPromptWithSnippets( return keptSnippets; } -function rangeIntersectionByLines(a: Range, b: Range): Range | null { - const startLine = Math.max(a.start.line, b.start.line); - const endLine = Math.min(a.end.line, b.end.line); - if (startLine >= endLine) { - return null; - } - return { - start: { - line: startLine, - character: 0, - }, - end: { - line: endLine, - character: 0, - }, - }; -} - /** * Remove one range from another range, which may lead to returning two disjoint ranges */ @@ -225,31 +207,3 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { } return [orig]; } - -export function removeRangeFromSnippets( - snippets: Required[], - filepath: string, - range: Range, -): Required[] { - const finalSnippets: Required[] = []; - for (const snippet of snippets) { - if (snippet.filepath !== filepath) { - finalSnippets.push(snippet); - continue; - } - - const intersection = rangeIntersectionByLines(range, snippet.range); - if (!intersection) { - finalSnippets.push(snippet); - } else { - finalSnippets.push( - ...rangeDifferenceByLines(snippet.range, intersection).map((range) => ({ - ...snippet, - range, - })), - ); - } - } - - return finalSnippets; -} diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index d0d67db85..f847e3b2a 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -11,6 +11,7 @@ import { getTemplateForModel, } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; +import { countTokens } from "../../llm/countTokens"; export function formatExternalSnippet( filepath: string, @@ -33,25 +34,17 @@ function getContextComments( snippets: AutocompleteSnippet[], lang: AutocompleteLanguageInfo, filepath: string, - prefix: string, - suffix: string, ) { - const formattedSnippets = snippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), - ) - .join("\n"); - if (formattedSnippets.length > 0) { - return `${formattedSnippets}\n\n`; - } + const fileNameSnippet = `\n\n${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n\n`; - const isEmptyFile = prefix.trim().length === 0 && suffix.trim().length === 0; - if (isEmptyFile) { - // Include the file name as a comment - prefix = `${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n`; - } + const formattedSnippets = + snippets + .map((snippet) => + formatExternalSnippet(snippet.filepath, snippet.contents, lang), + ) + .join("\n") + fileNameSnippet; - return ""; + return formattedSnippets; } function getTemplate(helper: HelperVars): AutocompleteTemplate { @@ -85,11 +78,29 @@ function renderStringTemplate( }); } -export function renderPrompt( - snippets: AutocompleteSnippet[], - workspaceDirs: string[], - helper: HelperVars, -): { +const formatDiff = (helper: HelperVars, diff?: string) => { + if (!diff) return ""; + + const tokenCount = countTokens(diff, helper.modelName); + + if (tokenCount > helper.maxDiffTokens) { + return ""; + } + + return `${diff}\n\n`; +}; + +export function renderPrompt({ + snippets, + workspaceDirs, + helper, + diff, +}: { + snippets: AutocompleteSnippet[]; + workspaceDirs: string[]; + helper: HelperVars; + diff?: string; +}): { prompt: string; prefix: string; suffix: string; @@ -119,10 +130,10 @@ export function renderPrompt( snippets, helper.lang, helper.filepath, - prefix, - suffix, ); - prefix = `${contextComments}${prefix}`; + const formattedDiff = formatDiff(helper, diff); + + prefix = `${formattedDiff}${contextComments}${prefix}`; } const prompt = diff --git a/core/autocomplete/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts index 2d9f74ab5..190e9b8ec 100644 --- a/core/autocomplete/util/HelperVars.ts +++ b/core/autocomplete/util/HelperVars.ts @@ -39,7 +39,9 @@ export class HelperVars { private async init() { // Don't do anything if already initialized - if (this._fileContents !== undefined) {return;} + if (this._fileContents !== undefined) { + return; + } this._fileContents = this.input.manuallyPassFileContents ?? @@ -115,6 +117,11 @@ export class HelperVars { get maxSnippetTokens() { return this.options.maxPromptTokens * this.options.maxSnippetPercentage; } + + get maxDiffTokens() { + return this.options.maxPromptTokens * this.options.maxDiffPercentage; + } + get prunedCaretWindow() { return this.prunedPrefix + this.prunedSuffix; } diff --git a/core/config/types.ts b/core/config/types.ts index ad80cdeab..370689dde 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -836,7 +836,7 @@ declare global { slidingWindowPrefixPercentage: number; slidingWindowSize: number; maxSnippetPercentage: number; - recentlyEditedSimilarityThreshold: number; + maxDiffPercentage: number; useCache: boolean; onlyMyCode: boolean; useOtherFiles: boolean; diff --git a/core/index.d.ts b/core/index.d.ts index c30119968..ca6c8482d 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -937,7 +937,7 @@ export interface TabAutocompleteOptions { slidingWindowPrefixPercentage: number; slidingWindowSize: number; maxSnippetPercentage: number; - recentlyEditedSimilarityThreshold: number; + maxDiffPercentage: number; useCache: boolean; onlyMyCode: boolean; useOtherFiles: boolean; diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 7a94abc03..269f3489e 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -11,8 +11,8 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { multilineCompletions: "auto", slidingWindowPrefixPercentage: 0.75, slidingWindowSize: 500, - maxSnippetPercentage: 0.6, - recentlyEditedSimilarityThreshold: 0.0, // Effectively no threshold. + maxSnippetPercentage: 0.5, + maxDiffPercentage: 0.5, useCache: true, onlyMyCode: true, useOtherFiles: true, diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 60fc6b72d..2ce332f02 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -21,7 +21,6 @@ import { uriFromFilePath, } from "./vscode"; - import type { FileEdit, RangeInFile, Thread } from "core"; const util = require("node:util"); @@ -181,7 +180,8 @@ export class VsCodeIdeUtils { vscode.workspace .openTextDocument( vscode.Uri.parse( - `${VsCodeExtension.continueVirtualDocumentScheme + `${ + VsCodeExtension.continueVirtualDocumentScheme }:${encodeURIComponent(name)}?${encodeURIComponent(contents)}`, ), ) @@ -305,8 +305,8 @@ export class VsCodeIdeUtils { return `${lines .slice(range.start.line, range.end.line) .join("\n")}\n${lines[ - range.end.line < lines.length - 1 ? range.end.line : lines.length - 1 - ].slice(0, range.end.character)}`; + range.end.line < lines.length - 1 ? range.end.line : lines.length - 1 + ].slice(0, range.end.character)}`; } async getTerminalContents(commands = -1): Promise { @@ -572,7 +572,6 @@ export class VsCodeIdeUtils { async getDiff(includeUnstaged: boolean): Promise { let diffs: string[] = []; - let repos = []; for (const dir of this.getWorkspaceDirectories()) { const repo = await this.getRepo(vscode.Uri.file(dir)); @@ -580,20 +579,16 @@ export class VsCodeIdeUtils { continue; } - repos.push(repo.state.HEAD?.name); - const staged = await repo.diff(true); - diffs.push(`${staged}`); + diffs.push(staged); if (includeUnstaged) { const unstaged = await repo.diff(false); - diffs.push(`\n${unstaged}`); + diffs.push(unstaged); } } const fullDiff = diffs.join("\n\n"); - if (fullDiff.trim() === "") { - console.log(`Diff empty for repos: ${repos}`); - } + return fullDiff; } diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index 4d989c127..a4ba53b8e 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -142,7 +142,7 @@ export const tabAutocompleteOptionsSchema = z.object({ slidingWindowPrefixPercentage: z.number(), slidingWindowSize: z.number(), maxSnippetPercentage: z.number(), - recentlyEditedSimilarityThreshold: z.number(), + maxDiffPercentage: z.number(), useCache: z.boolean(), onlyMyCode: z.boolean(), useOtherFiles: z.boolean(), From a830dca11d50596d9cd5f29df99c91b9fb630e45 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 19 Nov 2024 16:26:31 -0800 Subject: [PATCH 64/82] refactor: clean up code --- core/autocomplete/CompletionProvider.ts | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 9fe11df79..f6b783be0 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -177,13 +177,9 @@ export class CompletionProvider { const extraSnippets = await this._getExtraSnippets(helper); const [snippets, diff, workspaceDirs] = await Promise.all([ - await aggregateSnippets( - helper, - extraSnippets, - this.contextRetrievalService, - ), - await this.ide.getDiff(true), - await this.ide.getWorkspaceDirs(), + aggregateSnippets(helper, extraSnippets, this.contextRetrievalService), + this.ide.getDiff(true), + this.ide.getWorkspaceDirs(), ]); const { prompt, prefix, suffix, completionOptions } = renderPrompt({ From 389b2c94c2f6ed178c109bb3872fd368c24155b5 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 16:39:28 -0800 Subject: [PATCH 65/82] symbols bug fixes --- .../components/History/HistoryTableRow.tsx | 13 +++++-- gui/src/components/mainInput/resolveInput.ts | 19 ++--------- gui/src/components/markdown/FilenameLink.tsx | 4 +-- .../markdown/StyledMarkdownPreview.tsx | 32 ++++++----------- gui/src/components/markdown/SymbolLink.tsx | 4 +-- gui/src/hooks/useHistory.tsx | 15 ++++++-- gui/src/redux/slices/stateSlice.ts | 4 +-- gui/src/redux/store.ts | 7 +--- gui/src/util/symbols.ts | 34 +++++++++++++++++++ 9 files changed, 76 insertions(+), 56 deletions(-) create mode 100644 gui/src/util/symbols.ts diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 26107c199..695389c29 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -1,11 +1,12 @@ import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline"; import { SessionInfo } from "core"; import React, { useState } from "react"; -import { useDispatch } from "react-redux"; +import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import { Input } from ".."; import useHistory from "../../hooks/useHistory"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { RootState } from "../../redux/store"; function lastPartOfPath(path: string): string { const sep = path.includes("/") ? "/" : "\\"; @@ -29,6 +30,9 @@ export function HistoryTableRow({ const [sessionTitleEditValue, setSessionTitleEditValue] = useState( session.title, ); + const currentSessionId = useSelector( + (state: RootState) => state.state.sessionId, + ); const { saveSession, deleteSession, loadSession, getSession, updateSession } = useHistory(dispatch); @@ -59,8 +63,11 @@ export function HistoryTableRow({ className="hover:bg-vsc-editor-background relative box-border flex max-w-full cursor-pointer overflow-hidden rounded-lg p-3" onClick={async () => { // Save current session - await saveSession(); - await loadSession(session.sessionId); + if (session.sessionId !== currentSessionId) { + await saveSession(); + await loadSession(session.sessionId); + } + navigate("/"); }} > diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 4c7f4c640..a933bd1a3 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -14,6 +14,7 @@ import { setIsGatheringContext, updateFileSymbols, } from "../../redux/slices/stateSlice"; +import { updateFileSymbolsFromContextItems } from "../../util/symbols"; interface MentionAttrs { label: string; @@ -174,23 +175,7 @@ async function resolveEditorContent( ); contextItems.push(...defaultContextItems.flat()); - const contextItemFileUris = Array.from( - new Set( - contextItems - .filter((item) => item.uri?.type === "file" && item?.uri?.value) - .map((item) => item.uri.value), - ), - ); - - const symbolsResult = await ideMessenger.request( - "context/getSymbolsForFiles", - { - uris: contextItemFileUris, - }, - ); - if (symbolsResult.status === "success") { - dispatch(updateFileSymbols(symbolsResult.content)); - } + await updateFileSymbolsFromContextItems(contextItems, ideMessenger, dispatch); if (contextItemsText !== "") { contextItemsText += "\n"; diff --git a/gui/src/components/markdown/FilenameLink.tsx b/gui/src/components/markdown/FilenameLink.tsx index 0d1166a00..d63bf8309 100644 --- a/gui/src/components/markdown/FilenameLink.tsx +++ b/gui/src/components/markdown/FilenameLink.tsx @@ -21,11 +21,11 @@ function FilenameLink({ rif }: FilenameLinkProps) { return ( - + {getBasename(rif.filepath)} diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 9ded0464f..ca1ea2afd 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -164,28 +164,18 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( // The refs are a workaround because rehype options are stored on initiation // So they won't use the most up-to-date state values // So in this case we just put them in refs - const symbolsForContextItems = useRef([]); + const symbolsRef = useRef([]); const contextItemsRef = useRef([]); + useEffect(() => { contextItemsRef.current = contextItems || []; - if (!contextItems) { - symbolsForContextItems.current = []; - } - // Get unique URIs and then find relevant symbols - const contextUris = Array.from( - new Set( - contextItems.filter((item) => item?.uri).map((item) => item.uri!.value), - ), - ); - const contextSymbols: SymbolWithRange[] = []; - contextUris.forEach((uri) => { - const fileSymbols = symbols[uri]; - if (fileSymbols) { - contextSymbols.push(...fileSymbols); - } - }); - symbolsForContextItems.current = contextSymbols; - }, [contextItems, symbols]); + }, [contextItems]); + useEffect(() => { + // Note, before I was only looking for symbols that matched + // Context item files on current history item + // but in practice global symbols for session makes way more sense + symbolsRef.current = Object.values(symbols).flat(); + }, [symbols]); const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [remarkMath, () => processCodeBlocks], @@ -278,7 +268,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( return ; } - const exactSymbol = symbolsForContextItems.current.find( + const exactSymbol = symbolsRef.current.find( (s) => s.name === content, ); if (exactSymbol) { @@ -286,7 +276,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( } // PARTIAL - this is the case where the llm returns e.g. `subtract(number)` instead of `subtract` - const partialSymbol = symbolsForContextItems.current.find((s) => + const partialSymbol = symbolsRef.current.find((s) => content.startsWith(s.name), ); if (partialSymbol) { diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx index b18d302df..569a493e5 100644 --- a/gui/src/components/markdown/SymbolLink.tsx +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -20,10 +20,10 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) { return ( - + {content} diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index f159ffea3..b52271ab4 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -7,9 +7,10 @@ import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { newSession } from "../redux/slices/stateSlice"; +import { newSession, updateFileSymbols } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +import { updateFileSymbolsFromContextItems } from "../util/symbols"; const MAX_TITLE_LENGTH = 100; @@ -22,7 +23,6 @@ function truncateText(text: string, maxLength: number) { function useHistory(dispatch: Dispatch) { const state = useSelector((state: RootState) => state.state); - const defaultModel = useSelector(defaultModelSelector); const ideMessenger = useContext(IdeMessengerContext); const { lastSessionId, setLastSessionId } = useLastSessionContext(); @@ -122,7 +122,18 @@ function useHistory(dispatch: Dispatch) { if (result.status === "error") { throw new Error(result.error); } + const persistedSessionInfo = result.content; + + // Update file symbols on session load for all context items + await updateFileSymbolsFromContextItems( + persistedSessionInfo.history + .map((item) => item.contextItems ?? []) + .flat(), + ideMessenger, + dispatch, + ); + dispatch(newSession(persistedSessionInfo)); return persistedSessionInfo; } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index c8abe266e..09735499f 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -4,7 +4,6 @@ import { ChatHistoryItem, ChatMessage, Checkpoint, - ContextItemId, ContextItemWithId, FileSymbolMap, PersistedSessionInfo, @@ -146,7 +145,6 @@ export const stateSlice = createSlice({ state.mainEditorContent = undefined; }, updateFileSymbols: (state, action: PayloadAction) => { - console.log("UPDATE SYMBOLS", action.payload); state.symbols = Object.assign(state.symbols, action.payload); }, setContextItemsAtIndex: ( @@ -379,7 +377,7 @@ export const stateSlice = createSlice({ curApplyState.numDiffs = payload.numDiffs ?? curApplyState.numDiffs; curApplyState.filepath = payload.filepath ?? curApplyState.filepath; } - if(payload.status === "done"){ + if (payload.status === "done") { state.nextCodeBlockToApplyIndex++; } }, diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 986075a84..725d88c01 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -39,12 +39,7 @@ const windowIDTransform = (windowID: string) => ); const saveSubsetFilters = [ - createFilter("state", [ - "history", - "sessionId", - "defaultModelTitle", - "symbols", - ]), + createFilter("state", ["history", "sessionId", "defaultModelTitle"]), ]; const persistConfig = { diff --git a/gui/src/util/symbols.ts b/gui/src/util/symbols.ts new file mode 100644 index 000000000..98848053a --- /dev/null +++ b/gui/src/util/symbols.ts @@ -0,0 +1,34 @@ +import { ContextItemWithId } from "core"; +import { IIdeMessenger } from "../context/IdeMessenger"; +import { updateFileSymbols } from "../redux/slices/stateSlice"; +import { Dispatch } from "@reduxjs/toolkit"; + +export async function updateFileSymbolsFromContextItems( + contextItems: ContextItemWithId[], + ideMessenger: IIdeMessenger, + dispatch: Dispatch, +) { + // Given a list of context items, + // Get unique file uris + try { + const contextUris = Array.from( + new Set( + contextItems + .filter((item) => item.uri?.type === "file" && item?.uri?.value) + .map((item) => item.uri.value), + ), + ); + // And then update symbols for those files + if (contextUris.length > 0) { + const symbolsResult = await ideMessenger.request( + "context/getSymbolsForFiles", + { uris: contextUris }, + ); + if (symbolsResult.status === "success") { + dispatch(updateFileSymbols(symbolsResult.content)); + } + } + } catch (e) { + console.error("Error updating file symbols from context items", e); + } +} From 3f7daee8f30ee241cdf19cb16589865509c2e424 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 21:56:53 -0800 Subject: [PATCH 66/82] restore domain --- core/context/providers/GitHubIssuesContextProvider.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/context/providers/GitHubIssuesContextProvider.ts b/core/context/providers/GitHubIssuesContextProvider.ts index c0f25c12b..7bd64d860 100644 --- a/core/context/providers/GitHubIssuesContextProvider.ts +++ b/core/context/providers/GitHubIssuesContextProvider.ts @@ -24,6 +24,9 @@ class GitHubIssuesContextProvider extends BaseContextProvider { const octokit = new Octokit({ auth: this.options?.githubToken, + baseUrl: this.options?.domain + ? `https://${this.options.domain}/api/v3` + : undefined, request: { fetch: extras.fetch, }, From a9845386f054179651bd1e71e768175a3b873c2e Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 22:11:20 -0800 Subject: [PATCH 67/82] add pre-commit hook with husky --- .husky/pre-commit | 1 + .prettierignore | 13 +++++++++++++ package-lock.json | 16 ++++++++++++++++ package.json | 10 +++++++--- 4 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 .husky/pre-commit diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 000000000..d59df2ef6 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1 @@ +npx prettier --write . \ No newline at end of file diff --git a/.prettierignore b/.prettierignore index db326191f..15619929d 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,4 +1,17 @@ +binary/bin +binary/build +binary/out +binary/tmp +core/.continue-test +docs/.docusaurus +extensions/.continue-debug extensions/vscode/continue_rc_schema.json +extensions/vscode/.vscode-test +extensions/vscode/bin +extensions/vscode/build +extensions/vscode/out +gui/dist **/.continueignore CHANGELOG.md **/continue_tutorial.py +**/node_modules \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index c147efa72..42ecd2cd8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,6 +7,7 @@ "devDependencies": { "@typescript-eslint/parser": "^7.8.0", "eslint-plugin-import": "^2.29.1", + "husky": "^9.1.7", "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8" } @@ -1645,6 +1646,21 @@ "node": ">= 0.4" } }, + "node_modules/husky": { + "version": "9.1.7", + "resolved": "https://registry.npmjs.org/husky/-/husky-9.1.7.tgz", + "integrity": "sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA==", + "dev": true, + "bin": { + "husky": "bin.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/typicode" + } + }, "node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", diff --git a/package.json b/package.json index 6d93be403..e5dbe76f2 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,12 @@ { "devDependencies": { - "prettier": "^3.3.3", - "prettier-plugin-tailwindcss": "^0.6.8", "@typescript-eslint/parser": "^7.8.0", - "eslint-plugin-import": "^2.29.1" + "eslint-plugin-import": "^2.29.1", + "husky": "^9.1.7", + "prettier": "^3.3.3", + "prettier-plugin-tailwindcss": "^0.6.8" + }, + "scripts": { + "prepare": "husky" } } From f9883fbf095f398118ce06bae28672b83f06f00e Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 22:57:50 -0800 Subject: [PATCH 68/82] fix zh-CN links --- .../model-providers/top-level/vertexai.md | 2 +- .../current/actions/how-to-customize.md | 2 +- .../current/autocomplete/how-to-customize.md | 2 +- .../current/chat/model-setup.mdx | 2 +- .../customize/deep-dives/autocomplete.md | 2 +- .../customize/model-providers/more/nvidia.md | 52 ++ .../model-providers/top-level/vertexai.md | 65 +++ .../model-providers/top-level/xai.md | 53 +++ .../current/customize/overview.md | 4 +- .../current/edit/model-setup.md | 4 +- .../current/reference.md | 446 ++++++++++++++++++ 11 files changed, 625 insertions(+), 9 deletions(-) create mode 100644 docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md create mode 100644 docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md create mode 100644 docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md create mode 100644 docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md diff --git a/docs/docs/customize/model-providers/top-level/vertexai.md b/docs/docs/customize/model-providers/top-level/vertexai.md index 1778ce3c6..50958cae0 100644 --- a/docs/docs/customize/model-providers/top-level/vertexai.md +++ b/docs/docs/customize/model-providers/top-level/vertexai.md @@ -27,7 +27,6 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. } ``` - ## Autocomplete model We recommend configuring **Codestral** or **code-gecko** as your autocomplete model. @@ -43,6 +42,7 @@ We recommend configuring **Codestral** or **code-gecko** as your autocomplete mo } } ``` + ## Embeddings model We recommend configuring **text-embedding-004** as your embeddings model. diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md index 940fedc65..095d75918 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md @@ -7,7 +7,7 @@ sidebar_position: 5 ## 内置的斜杠命令 -Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../customize/config.mdx) 并添加它们到 `slashCommands` 列表中。 +Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../reference.md) 并添加它们到 `slashCommands` 列表中。 ## 定制斜杠命令 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md index 5e7b8fad2..aa2a04d5f 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md @@ -5,7 +5,7 @@ keywords: [定制] sidebar_position: 5 --- -Continue 在 [`config.json`](../customize/config.mdx) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡: +Continue 在 [`config.json`](../reference.md) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡: ```json title="config.json" "tabAutocompleteOptions": { diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx index fe24f18fb..b95d976f1 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx @@ -9,7 +9,7 @@ import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; :::info -这个页面推荐聊天的模型和提供者。在 [这里](../customize/config.mdx) 了解更多关于如何设置你的 `config.json` 。 +这个页面推荐聊天的模型和提供者。在 [这里](../reference.md) 了解更多关于如何设置你的 `config.json` 。 ::: ## 最好的总体体验 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md index ea07525ee..b85cfe323 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md @@ -44,7 +44,7 @@ ollama run starcoder2:3b } ``` -如果你对可用选项不熟悉,你可以在 [这里](../config.mdx) 查找完整的参考。 +如果你对可用选项不熟悉,你可以在 [这里](../../reference.md) 查找完整的参考。 ## 配置选项 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md new file mode 100644 index 000000000..049ff7754 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md @@ -0,0 +1,52 @@ +--- +title: NVIDIA +--- + +:::info + +[View the docs](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog) to learn how to get an API key. + +::: + +## Chat model + +We recommend configuring **Nemotron-4-340B-Instruct** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Nemotron-4-340B-Instruct", + "provider": "nvidia", + "model": "nvidia-nemotron-4-340b-instruct", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## Autocomplete model + +NVIDIA currently does not offer any autocomplete models. + +[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. + +## Embeddings model + +We recommend configuring **NVIDIA Retrieval QA Mistral 7B** as your embeddings model. + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "nvidia", + "model": "nvidia/nv-embedqa-mistral-7b-v2", + "apiKey": "[API_KEY]" + } +} +``` + +## Reranking model + +NVIDIA currently does not offer any reranking models. + +[Click here](../../model-types/reranking.md) to see a list of reranking model providers. diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md new file mode 100644 index 000000000..daf966d9e --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md @@ -0,0 +1,65 @@ +--- +title: Vertex AI +slug: ../vertexai +--- + +:::info + +You need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc). + +::: + +## Chat model + +We recommend configuring **Claude 3.5 Sonnet** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "vertexai", + "model": "claude-3-5-sonnet-20240620", + "projectId": "[PROJECT_ID]", + "region": "us-east5" + } + ] +} +``` + +## Autocomplete model + +We recommend configuring **Codestral** or **code-gecko** as your autocomplete model. + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "Codestral (Vertex AI)", + "provider": "vertexai", + "model": "codestral", + "projectId": "[PROJECT_ID]", + "region": "us-central1" + } +} +``` + +## Embeddings model + +We recommend configuring **text-embedding-004** as your embeddings model. + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "vertexai", + "model": "text-embedding-004", + "projectId": "[PROJECT_ID]", + "region": "us-central1" + } +} +``` + +## Reranking model + + diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md new file mode 100644 index 000000000..fbdfa83ad --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md @@ -0,0 +1,53 @@ +--- +title: xAI +slug: ../xai +--- + +:::info + +You can get an API key from the [xAI console](https://console.x.ai/) + +::: + +## Chat model + +We recommend configuring **grok-beta** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Grok Beta", + "provider": "xAI", + "model": "grok-beta", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## Autocomplete model + +xAI currently does not offer any autocomplete models. + +[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. + +## Embeddings model + +xAI currently does not offer any embeddings models. + +[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers. + +## Reranking model + +xAI currently does not offer any reranking models. + +[Click here](../../model-types/reranking.md) to see a list of reranking model providers. + +## Legacy Completions + +To force usage of `chat/completions` instead of `completions` endpoint you can set + +```json +"useLegacyCompletionsEndpoint": false +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md index 784c0bd59..f95574dae 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md @@ -8,13 +8,13 @@ Continue 可以深度定制。这个主要通过编辑位于 `~/.continue/config ## 开始 -要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](./config.mdx) 。 +要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](../reference.md) 。 当你保存 `config.json` 时, Continue 会自动地刷新,应用你的变更。 ## 每个工作区的配置 -如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](./config.mdx) ,会自动地应用到本地 `config.json` 之上。 +如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](../reference.md) ,会自动地应用到本地 `config.json` 之上。 ## 可编程的配置 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md index f96a8fe6d..07a0a6c65 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md @@ -5,6 +5,6 @@ description: 如何设置一个编辑模型 keywords: [编辑, cmd l, 模型] --- -默认情况下,编辑使用 [与聊天相同的模型](chat/model-setup.mdx) ,所以对于代码编辑,我们推荐相同的 400B+ 参数模型或者领先的模型之一。 +默认情况下,编辑使用 [与聊天相同的模型](../chat/model-setup.mdx) ,所以对于代码编辑,我们推荐相同的 400B+ 参数模型或者领先的模型之一。 -你可以通过更新你的 [`config.json`](../customize/config.mdx) 为编辑配置一个不同的模型。 +你可以通过更新你的 [`config.json`](../reference.md) 为编辑配置一个不同的模型。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md new file mode 100644 index 000000000..09dd150a6 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md @@ -0,0 +1,446 @@ +--- +title: Reference +description: Reference for the Continue _config.json_ configuration file +keywords: [config, config_schema.json, json] +--- + +Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json). + +**All properties at all levels are optional unless explicitly marked required** + +### `models` + +Your **chat** models are defined here, which are used for [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Actions](./actions/how-to-use-it.md). +Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json. + +**Properties:** + +- `title` (**required**): The title to assign to your model, shown in dropdowns, etc. +- `provider` (**required**): The provider of the model, which determines the type and interaction method. Options inclued `openai`, `ollama`, etc., see intelliJ suggestions. +- `model` (**required**): The name of the model, used for prompt template auto-detection. +- `apiKey`: API key required by providers like OpenAI, Anthropic, and Cohere. +- `apiBase`: The base URL of the LLM API. +- `contextLength`: Maximum context length of the model, typically in tokens (default: 2048). +- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists. +- `template`: Chat template to format messages. Auto-detected for most models but can be overridden. See intelliJ suggestions. +- `promptTemplates`: A mapping of prompt template names (e.g., `edit`) to template strings. [Customization Guide](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt). +- `completionOptions`: Model-specific completion options, same format as top-level [`completionOptions`](#completionoptions), which they override. +- `systemMessage`: A system message that will precede responses from the LLM. +- `requestOptions`: Model-specific HTTP request options, same format as top-level [`requestOptions`](#requestoptions), which they override. +- `apiType`: Specifies the type of API (`openai` or `azure`). +- `apiVersion`: Azure API version (e.g., `2023-07-01-preview`). +- `engine`: Engine for Azure OpenAI requests. +- `capabilities`: Override auto-detected capabilities: + - `uploadImage`: Boolean indicating if the model supports image uploads. + +_(AWS Only)_ + +- `profile`: AWS security profile for authorization. +- `modelArn`: AWS ARN for imported models (e.g., for `bedrockimport` provider). +- `region`: Region where the model is hosted (e.g., `us-east-1`, `eu-central-1`). + +Example: + +```json title="config.json" +{ + "models": [ + { + "title": "Ollama", + "provider": "ollama", + "model": "AUTODETECT" + }, + { + "model": "gpt-4o", + "contextLength": 128000, + "title": "GPT-4o", + "provider": "openai", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +### `tabAutocompleteModel` + +Specifies the model or models for tab autocompletion, defaulting to an Ollama instance. This property uses the same format as `models`. Can be an array of models or an object for one model. + +Example + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "My Starcoder", + "provider": "ollama", + "model": "starcoder2:3b" + } +} +``` + +### `tabAutocompleteOptions` + +Specifies options for tab autocompletion behavior. + +**Properties:** + +- `disable`: If `true`, disables tab autocomplete (default: `false`). +- `useCopyBuffer`: If `true`, includes the copy buffer in the prompt. +- `useFileSuffix`: If `true`, includes file suffix in the prompt. +- `maxPromptTokens`: Maximum number of tokens for the prompt. +- `debounceDelay`: Delay (in ms) before triggering autocomplete. +- `maxSuffixPercentage`: Maximum percentage of prompt for suffix. +- `prefixPercentage`: Percentage of input for prefix. +- `template`: Template string for autocomplete, using Mustache templating. +- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). +- `useCache`: If `true`, caches completions. +- `onlyMyCode`: If `true`, only includes code within the repository. +- `useOtherFiles`: If `true`, includes snippets from other files (default: `true`). +- `disableInFiles`: Array of glob patterns for files where autocomplete is disabled. + +Example + +```json title="config.json" +{ + "tabAutocompleteOptions": { + "debounceDelay": 500, + "maxPromptTokens": 1500, + "disableInFiles": ["*.md"] + } +} +``` + +### `embeddingsProvider` + +Embeddings model settings - the model used for @Codebase and @docs. + +**Properties:** + +- `provider` (**required**): Specifies the embeddings provider, with options including `transformers.js`, `ollama`, `openai`, `cohere`, `free-trial`, `gemini`, etc +- `model`: Model name for embeddings. +- `apiKey`: API key for the provider. +- `apiBase`: Base URL for API requests. +- `requestOptions`: Additional HTTP request settings specific to the embeddings provider. +- `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. +- `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. + +(AWS ONLY) + +- `region`: Specifies the region hosting the model. +- `profile`: AWS security profile. + +Example: + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "openai", + "model": "text-embedding-ada-002", + "apiKey": "", + "maxChunkSize": 256, + "maxBatchSize": 5 + } +} +``` + +### `completionOptions` + +Parameters that control the behavior of text generation and completion settings. Top-level `completionOptions` apply to all models, _unless overridden at the model level_. + +**Properties:** + +- `stream`: Whether to stream the LLM response. Currently only respected by the `anthropic` and `ollama` providers; other providers will always stream (default: `true`). +- `temperature`: Controls the randomness of the completion. Higher values result in more diverse outputs. +- `topP`: The cumulative probability for nucleus sampling. Lower values limit responses to tokens within the top probability mass. +- `topK`: The maximum number of tokens considered at each step. Limits the generated text to tokens within this probability. +- `presencePenalty`: Discourages the model from generating tokens that have already appeared in the output. +- `frequencePenalty`: Penalizes tokens based on their frequency in the text, reducing repetition. +- `mirostat`: Enables Mirostat sampling, which controls the perplexity during text generation. Supported by Ollama, LM Studio, and llama.cpp providers (default: `0`, where `0` = disabled, `1` = Mirostat, and `2` = Mirostat 2.0). +- `stop`: An array of stop tokens that, when encountered, will terminate the completion. Allows specifying multiple end conditions. +- `maxTokens`: The maximum number of tokens to generate in a completion (default: `2048`). +- `numThreads`: The number of threads used during the generation process. Available only for Ollama as `num_thread`. +- `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes). +- `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream. + +Example + +```json title="config.json" +{ + "completionOptions": { + "stream": false, + "temperature": 0.5 + } +} +``` + +### `requestOptions` + +Default HTTP request options that apply to all models and context providers, unless overridden at the model level. + +**Properties:** + +- `timeout`: Timeout for each request to the LLM (default: 7200 seconds). +- `verifySsl`: Whether to verify SSL certificates for requests. +- `caBundlePath`: Path to a custom CA bundle for HTTP requests - path to `.pem` file (or array of paths) +- `proxy`: Proxy URL to use for HTTP requests. +- `headers`: Custom headers for HTTP requests. +- `extraBodyProperties`: Additional properties to merge with the HTTP request body. +- `noProxy`: List of hostnames that should bypass the specified proxy. +- `clientCertificate`: Client certificate for HTTP requests. + + - `cert`: Path to the client certificate file. + - `key`: Path to the client certificate key file. + - `passphrase`: Optional passphrase for the client certificate key file. + +Example + +```json title="config.json" +{ + "requestOptions": { + "headers": { + "X-Auth-Token": "xxx" + } + } +} +``` + +### `reranker` + +Configuration for the reranker model used in response ranking. + +**Properties:** + +- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei` +- `params`: + - `model`: Model name + - `apiKey`: Api key + +Example + +```json title="config.json" +{ + "reranker": { + "name": "voyage", + "params": { + "model": "rerank-2", + "apiKey": "" + } + } +} +``` + +### `docs` + +List of documentation sites to index. + +**Properties:** + +- `title` (**required**): Title of the documentation site, displayed in dropdowns, etc. +- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs +- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL +- `maxDepth`: Maximum depth for crawling. Default `3` +- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). + +Example + +```json title="config.json" +"docs": [ + { + "title": "Continue", + "startUrl": "https://docs.continue.dev/intro", + "rootUrl": "https://docs.continue.dev", + "faviconUrl": "https://docs.continue.dev/favicon.ico", + } +] +``` + +### `analytics` + +Configuration for analytics tracking. + +**Properties:** + +- `provider`: Analytics provider (`"posthog"` or `"logstash"`). +- `url`: URL for analytics data. +- `clientKey`: Client key for analytics. + +### `slashCommands` + +Custom commands initiated by typing "/" in the sidebar. Commands include predefined functionality or may be user-defined. + +**Properties:** + +- `name`: The command name. Options include "issue", "share", "cmd", "http", "commit", and "review". +- `description`: Brief description of the command. +- `step`: (Deprecated) Used for built-in commands; set the name for pre-configured options. +- `params`: Additional parameters to configure command behavior (command-specific - see code for command) + +Example: + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "commit", + "description": "Generate a commit message" + }, + { + "name": "share", + "description": "Export this session as markdown" + }, + { + "name": "cmd", + "description": "Generate a shell command" + } + ] +} +``` + +### `customCommands` + +User-defined commands for prompt shortcuts in the sidebar, allowing quick access to common actions. + +**Properties:** + +- `name`: The name of the custom command. +- `prompt`: Text prompt for the command. +- `description`: Brief description explaining the command's function. + +Example: + +```json title="config.json" +{ + "customCommands": [ + { + "name": "test", + "prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", + "description": "Write unit tests for highlighted code" + } + ] +} +``` + +### `contextProviders` + +List of the pre-defined context providers that will show up as options while typing in the chat, and their customization with `params`. + +**Properties:** + +- `name`: Name of the context provider, e.g. `docs` or `web` +- `params`: A context-provider-specific record of params to configure the context behavior + +Example + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "code", + "params": {} + }, + { + "name": "docs", + "params": {} + }, + { + "name": "diff", + "params": {} + }, + { + "name": "open", + "params": {} + } + ] +} +``` + +### `disableSessionTitles` + +Prevents generating summary titles for each chat session when set to `true`. + +### `ui` + +Customizable UI settings to control interface appearance and behavior. + +**Properties:** + +- `codeBlockToolbarPosition`: Sets the toolbar position within code blocks, either `top` (default) or `bottom`. +- `fontSize`: Specifies font size for UI elements. +- `displayRawMarkdown`: If `true`, shows raw markdown in responses. +- `showChatScrollbar`: If `true`, enables a scrollbar in the chat window. + +Example: + +```json title="config.json" +{ + "ui": { + "codeBlockToolbarPosition": "bottom", + "fontSize": 14, + "displayRawMarkdown": false + } +} +``` + +### `allowAnonymousTelemetry` + +When `true`, anonymous usage data is collected using Posthog, to improve features. Default is `true`. + +### `userToken` + +An optional token that identifies the user, primarily for authenticated services. + +### `systemMessage` + +Defines a system message that appears before every response from the language model, providing guidance or context. + +### `disableIndexing` + +Prevents indexing of the codebase, useful primarily for debugging purposes. + +### `experimental` + +Several experimental config parameters are available, as described below: + +`experimental`: + +- `defaultContext`: Defines the default context for the LLM. Uses the same format as `contextProviders` but includes an additional `query` property to specify custom query parameters.= +- `modelRoles`: + - `inlineEdit`: Model title for inline edits. + - `applyCodeBlock`: Model title for applying code blocks. + - `repoMapFileSelection`: Model title for repo map selections. +- `readResponseTTS`: If `true`, reads LLM responses aloud with TTS. Default is `true`. +- `promptPath`: Change the path to custom prompt files from the default ".prompts" +- `quickActions`: Array of custom quick actions + - `title` (**required**): Display title for the quick action. + - `prompt` (**required**): Prompt for quick action. + - `sendToChat`: If `true`, sends result to chat; else inserts in document. Default is `false`. +- `contextMenuPrompts`: + - `comment`: Prompt for commenting code. + - `docstring`: Prompt for adding docstrings. + - `fix`: Prompt for fixing code. + - `optimize`: Prompt for optimizing code. + - `fixGrammar`: Prompt for fixing grammar or spelling. +- `useChromiumForDocsCrawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`.. + +Example + +```json title="config.json" +{ + "experimental": { + "modelRoles": { + "inlineEdit": "Edit Model" + }, + "promptPath": "custom/.prompts", + "quickActions": [ + { + "title": "Tags", + "prompt": "Return a list of any function and class names from the included code block", + "sendToChat": true + } + ], + "contextMenuPrompts": { + "fixGrammar": "Fix grammar in the above but allow for typos." + }, + "readResponseTTS": false, + "useChromiumForDocsCrawling": true + } +} +``` From 6013e6e0d551c14dbbe28fa1f11bcadc684e39a5 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 23:03:36 -0800 Subject: [PATCH 69/82] fix "ignore not defined" --- core/autocomplete/prefiltering/index.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts index bc3b3bcaa..40ffa5384 100644 --- a/core/autocomplete/prefiltering/index.ts +++ b/core/autocomplete/prefiltering/index.ts @@ -1,5 +1,7 @@ import path from "node:path"; +import ignore from "ignore"; + import { IDE } from "../.."; import { getBasename } from "../../util"; import { getConfigJsonPath } from "../../util/paths"; @@ -31,7 +33,7 @@ async function isDisabledForFile( } // @ts-ignore - const pattern = ignore.default().add(options.disableInFiles); + const pattern = ignore.default().add(disableInFiles); if (pattern.ignores(filepath)) { return true; } From ce7866b23823159d486ccc98628aa2249755f626 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 23:07:49 -0800 Subject: [PATCH 70/82] no predicted outputs for azure openai --- core/llm/llms/Azure.ts | 4 ++++ core/llm/llms/OpenAI.ts | 19 +++++++++---------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/core/llm/llms/Azure.ts b/core/llm/llms/Azure.ts index 0daec0850..d563ca78e 100644 --- a/core/llm/llms/Azure.ts +++ b/core/llm/llms/Azure.ts @@ -5,6 +5,10 @@ import OpenAI from "./OpenAI.js"; class Azure extends OpenAI { static providerName: ModelProvider = "azure"; + protected supportsPrediction(model: string): boolean { + return false; + } + static defaultOptions: Partial = { apiVersion: "2024-02-15-preview", apiType: "azure", diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 168e0afff..8498cd8cb 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -95,11 +95,8 @@ class OpenAI extends BaseLLM { ); } - private supportsPrediction(model: string): boolean { - return [ - "gpt-4o-mini", - "gpt-4o" - ].includes(model); + protected supportsPrediction(model: string): boolean { + return ["gpt-4o-mini", "gpt-4o"].includes(model); } protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) { @@ -120,9 +117,9 @@ class OpenAI extends BaseLLM { : url.host === "api.deepseek.com" ? options.stop?.slice(0, 16) : url.port === "1337" || - url.host === "api.openai.com" || - url.host === "api.groq.com" || - this.apiType === "azure" + url.host === "api.openai.com" || + url.host === "api.groq.com" || + this.apiType === "azure" ? options.stop?.slice(0, 4) : options.stop, }; @@ -143,10 +140,12 @@ class OpenAI extends BaseLLM { } if (options.prediction && this.supportsPrediction(options.model)) { - if (finalOptions.presence_penalty) { // prediction doesn't support > 0 + if (finalOptions.presence_penalty) { + // prediction doesn't support > 0 finalOptions.presence_penalty = undefined; } - if (finalOptions.frequency_penalty) { // prediction doesn't support > 0 + if (finalOptions.frequency_penalty) { + // prediction doesn't support > 0 finalOptions.frequency_penalty = undefined; } finalOptions.max_completion_tokens = undefined; From 867d509263063bb7d29e0e9ffb8ae9a936ca897d Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 23:15:28 -0800 Subject: [PATCH 71/82] config.json reference --- docs/docs/reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 09dd150a6..7fefa4347 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -1,5 +1,5 @@ --- -title: Reference +title: `config.json` Reference description: Reference for the Continue _config.json_ configuration file keywords: [config, config_schema.json, json] --- From ca78284986571717cb5af8746139d20b31e01680 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 19 Nov 2024 23:17:43 -0800 Subject: [PATCH 72/82] oops --- docs/docs/reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 7fefa4347..f39e68998 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -1,5 +1,5 @@ --- -title: `config.json` Reference +title: config.json Reference description: Reference for the Continue _config.json_ configuration file keywords: [config, config_schema.json, json] --- From 3b292cf732b73e9d4bd57354042ab165f1321a86 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 23:40:47 -0800 Subject: [PATCH 73/82] update symbols on load --- gui/src/hooks/useSetup.ts | 14 +++++++++++++- gui/src/redux/slices/stateSlice.ts | 10 ---------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 593283849..6aeaae25c 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -19,9 +19,11 @@ import { isJetBrains } from "../util"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import useChatHandler from "./useChatHandler"; import { useWebviewListener } from "./useWebviewListener"; +import { updateFileSymbolsFromContextItems } from "../util/symbols"; function useSetup(dispatch: Dispatch) { const ideMessenger = useContext(IdeMessengerContext); + const history = useSelector((store: RootState) => store.state.history); const initialConfigLoad = useRef(false); const loadConfig = useCallback(async () => { @@ -59,6 +61,17 @@ function useSetup(dispatch: Dispatch) { return () => clearInterval(interval); }, [initialConfigLoad, loadConfig]); + useEffect(() => { + // currently persist gate ensures that + // State.history is loaded before this is called + // Load symbols for chat on startup + updateFileSymbolsFromContextItems( + history.flatMap((item) => item.contextItems), + ideMessenger, + dispatch, + ); + }, []); + useEffect(() => { // Override persisted state dispatch(setInactive()); @@ -86,7 +99,6 @@ function useSetup(dispatch: Dispatch) { ); // IDE event listeners - const history = useSelector((store: RootState) => store.state.history); useWebviewListener( "getWebviewHistoryLength", async () => { diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 09735499f..56bc9d7b5 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -387,16 +387,6 @@ export const stateSlice = createSlice({ }, }); -export const memoizedContextItemsSelector = createSelector( - [(state: RootState) => state.state.history], - (history) => { - return history.reduce((acc, item) => { - acc.push(...item.contextItems); - return acc; - }, []); - }, -); - export const { updateFileSymbols, setContextItemsAtIndex, From b80833158b430779dbc4141cc6dac68ab3b7b447 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 23:47:43 -0800 Subject: [PATCH 74/82] better styling on file and symbol links --- gui/src/components/markdown/FilenameLink.tsx | 2 +- gui/src/components/markdown/SymbolLink.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/components/markdown/FilenameLink.tsx b/gui/src/components/markdown/FilenameLink.tsx index d63bf8309..20b7c0343 100644 --- a/gui/src/components/markdown/FilenameLink.tsx +++ b/gui/src/components/markdown/FilenameLink.tsx @@ -21,7 +21,7 @@ function FilenameLink({ rif }: FilenameLinkProps) { return ( diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx index 569a493e5..0dea98a28 100644 --- a/gui/src/components/markdown/SymbolLink.tsx +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -20,7 +20,7 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) { return ( From f210faf09d36805f58ff3a843383d665027c036f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Nov 2024 23:57:11 -0800 Subject: [PATCH 75/82] chat symbols - active file working --- gui/src/components/mainInput/resolveInput.ts | 8 +------- gui/src/hooks/useChatHandler.ts | 7 ++++++- gui/src/hooks/useHistory.tsx | 3 +-- gui/src/pages/edit/index.tsx | 2 ++ gui/src/util/symbols.ts | 1 + 5 files changed, 11 insertions(+), 10 deletions(-) diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index a933bd1a3..b12804d72 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -10,11 +10,7 @@ import { import { stripImages } from "core/llm/images"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { Dispatch } from "@reduxjs/toolkit"; -import { - setIsGatheringContext, - updateFileSymbols, -} from "../../redux/slices/stateSlice"; -import { updateFileSymbolsFromContextItems } from "../../util/symbols"; +import { setIsGatheringContext } from "../../redux/slices/stateSlice"; interface MentionAttrs { label: string; @@ -175,8 +171,6 @@ async function resolveEditorContent( ); contextItems.push(...defaultContextItems.flat()); - await updateFileSymbolsFromContextItems(contextItems, ideMessenger, dispatch); - if (contextItemsText !== "") { contextItemsText += "\n"; } diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index b9342d4e9..a4aeb799e 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -37,6 +37,7 @@ import { import { resetNextCodeBlockToApplyIndex } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import useHistory from "./useHistory"; +import { updateFileSymbolsFromContextItems } from "../util/symbols"; function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const posthog = usePostHog(); @@ -256,7 +257,11 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } } - // dispatch(addContextItems(contextItems)); + await updateFileSymbolsFromContextItems( + selectedContextItems, + ideMessenger, + dispatch, + ); const message: ChatMessage = { role: "user", diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index b52271ab4..4bdd1e2c1 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -6,8 +6,7 @@ import { useCallback, useContext } from "react"; import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; -import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { newSession, updateFileSymbols } from "../redux/slices/stateSlice"; +import { newSession } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import { updateFileSymbolsFromContextItems } from "../util/symbols"; diff --git a/gui/src/pages/edit/index.tsx b/gui/src/pages/edit/index.tsx index 2e93a16aa..26fbacbb1 100644 --- a/gui/src/pages/edit/index.tsx +++ b/gui/src/pages/edit/index.tsx @@ -177,6 +177,8 @@ function Edit() { dispatch, ); + // Note, not currently updating file symbols in edit mode + const prompt = [ ...contextItems.map((item) => item.content), stripImages(userInstructions), diff --git a/gui/src/util/symbols.ts b/gui/src/util/symbols.ts index 98848053a..5c4e1be12 100644 --- a/gui/src/util/symbols.ts +++ b/gui/src/util/symbols.ts @@ -29,6 +29,7 @@ export async function updateFileSymbolsFromContextItems( } } } catch (e) { + // Catch all - don't want file symbols to break the chat experience for now console.error("Error updating file symbols from context items", e); } } From f5ab00d3ae0da78318af4e1463756a5d3be1f20c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 20 Nov 2024 00:02:50 -0800 Subject: [PATCH 76/82] chat symbols style tweaks --- gui/src/components/markdown/FilenameLink.tsx | 2 +- gui/src/components/markdown/SymbolLink.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/components/markdown/FilenameLink.tsx b/gui/src/components/markdown/FilenameLink.tsx index 20b7c0343..161bd0b0a 100644 --- a/gui/src/components/markdown/FilenameLink.tsx +++ b/gui/src/components/markdown/FilenameLink.tsx @@ -21,7 +21,7 @@ function FilenameLink({ rif }: FilenameLinkProps) { return ( diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/markdown/SymbolLink.tsx index 0dea98a28..45d54ba8f 100644 --- a/gui/src/components/markdown/SymbolLink.tsx +++ b/gui/src/components/markdown/SymbolLink.tsx @@ -20,7 +20,7 @@ function SymbolLink({ symbol, content }: SymbolLinkProps) { return ( From f9c1b37c80b35aec65f4eb376ea4b965f098f37b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 20 Nov 2024 01:15:59 -0800 Subject: [PATCH 77/82] move update file symbols on load to use setup --- gui/src/hooks/useHistory.tsx | 9 --------- gui/src/hooks/useSetup.ts | 21 ++++++++++++--------- gui/src/redux/slices/stateSlice.ts | 7 +++++-- 3 files changed, 17 insertions(+), 20 deletions(-) diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 38aa5ec2b..e6feec628 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -9,7 +9,6 @@ import { useLastSessionContext } from "../context/LastSessionContext"; import { newSession } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; -import { updateFileSymbolsFromContextItems } from "../util/symbols"; const MAX_TITLE_LENGTH = 100; @@ -123,14 +122,6 @@ function useHistory(dispatch: Dispatch) { } const sessionContent = result.content; - - // Update file symbols on session load for all context items - await updateFileSymbolsFromContextItems( - sessionContent.history.map((item) => item.contextItems ?? []).flat(), - ideMessenger, - dispatch, - ); - dispatch(newSession(sessionContent)); return sessionContent; } diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index e95db68b3..ee80c36c3 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -61,16 +61,19 @@ function useSetup(dispatch: Dispatch) { return () => clearInterval(interval); }, [initialConfigLoad, loadConfig]); + // Load symbols for chat on any session change + const sessionId = useSelector((store: RootState) => store.state.sessionId); + const sessionIdRef = useRef(""); useEffect(() => { - // currently persist gate ensures that - // State.history is loaded before this is called - // Load symbols for chat on startup - updateFileSymbolsFromContextItems( - history.flatMap((item) => item.contextItems), - ideMessenger, - dispatch, - ); - }, []); + if (sessionIdRef.current !== sessionId) { + updateFileSymbolsFromContextItems( + history.flatMap((item) => item.contextItems), + ideMessenger, + dispatch, + ); + } + sessionIdRef.current = sessionId; + }, [sessionId, history, ideMessenger, dispatch]); useEffect(() => { // Override persisted state diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 8f1906409..c0132cf41 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -145,7 +145,10 @@ export const stateSlice = createSlice({ state.mainEditorContent = undefined; }, updateFileSymbols: (state, action: PayloadAction) => { - state.symbols = Object.assign(state.symbols, action.payload); + state.symbols = { + ...state.symbols, + ...action.payload, + }; }, setContextItemsAtIndex: ( state, @@ -290,7 +293,7 @@ export const stateSlice = createSlice({ state.streamAborter = new AbortController(); state.active = false; - state.isGatheringContext = false; + state.context.isGathering = false; state.isMultifileEdit = false; if (payload) { state.history = payload.history as any; From 57b18d73d67bccbb0726b9170b3d1620c8402dcd Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Wed, 13 Nov 2024 16:20:57 +0100 Subject: [PATCH 78/82] Cancel stale completion requests as you type Signed-off-by: Fred Bricon --- .gitignore | 6 ++-- core/autocomplete/CompletionProvider.ts | 1 + .../generation/CompletionStreamer.ts | 6 ++-- .../generation/GeneratorReuseManager.test.ts | 2 +- .../generation/GeneratorReuseManager.ts | 8 +++-- .../generation/ListenableGenerator.ts | 4 +++ core/commands/index.ts | 2 +- core/commands/slash/cmd.ts | 4 ++- core/commands/slash/commit.ts | 2 +- core/commands/slash/draftIssue.ts | 4 +-- core/commands/slash/edit.ts | 6 ++-- core/commands/slash/multifileEdit.ts | 2 +- core/commands/slash/onboard.ts | 4 +-- core/commands/slash/review.ts | 2 +- core/config/promptFile.ts | 2 +- core/context/rerankers/llm.ts | 9 +++--- core/context/retrieval/repoMapRequest.ts | 2 +- core/core.ts | 3 ++ core/edit/lazy/replace.ts | 2 +- core/edit/lazy/streamLazyApply.ts | 2 +- core/edit/streamDiffLines.ts | 4 +-- core/index.d.ts | 12 ++++++- core/llm/index.ts | 32 +++++++++++++------ core/llm/llms/Anthropic.ts | 5 ++- core/llm/llms/Asksage.ts | 6 +++- core/llm/llms/Bedrock.ts | 6 ++-- core/llm/llms/BedrockImport.ts | 3 +- core/llm/llms/Cloudflare.ts | 4 +++ core/llm/llms/Cohere.ts | 5 ++- core/llm/llms/CustomLLM.ts | 9 +++++- core/llm/llms/Deepseek.ts | 2 ++ core/llm/llms/Flowise.ts | 5 ++- core/llm/llms/FreeTrial.ts | 6 ++++ core/llm/llms/Gemini.ts | 9 ++++++ core/llm/llms/HuggingFaceInferenceAPI.ts | 2 ++ core/llm/llms/HuggingFaceTGI.ts | 2 ++ core/llm/llms/LlamaCpp.ts | 2 ++ core/llm/llms/Mock.ts | 2 ++ core/llm/llms/Moonshot.ts | 2 ++ core/llm/llms/Ollama.ts | 10 ++++-- core/llm/llms/OpenAI.ts | 11 +++++++ core/llm/llms/Replicate.ts | 10 ++++-- core/llm/llms/SageMaker.ts | 6 ++-- core/llm/llms/Together.ts | 3 +- core/llm/llms/VertexAI.ts | 14 ++++++-- core/llm/llms/WatsonX.ts | 6 ++++ .../v1/slashCommandFromPromptFile.ts | 2 +- core/util/chatDescriber.ts | 1 + 48 files changed, 192 insertions(+), 62 deletions(-) diff --git a/.gitignore b/.gitignore index 106cef892..9621811de 100644 --- a/.gitignore +++ b/.gitignore @@ -142,7 +142,7 @@ codeql .tiktoken_cache -# IntelliJ Plugin +# IntelliJ Plugin **/**/.gradle **/**/.qodana **/**/build @@ -168,4 +168,6 @@ extensions/intellij/.idea/** **/.idea/shelf/ extensions/intellij/bin -extensions/.continue-debug/ \ No newline at end of file +extensions/.continue-debug/ + +*.vsix \ No newline at end of file diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index f6b783be0..3cc1ce65c 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -29,6 +29,7 @@ const autocompleteCache = AutocompleteLruCache.get(); const ERRORS_TO_IGNORE = [ // From Ollama "unexpected server status", + "operation was aborted" ]; export type GetLspDefinitionsFunction = ( diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts index f516ad04b..d44957d15 100644 --- a/core/autocomplete/generation/CompletionStreamer.ts +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -25,10 +25,10 @@ export class CompletionStreamer { // Try to reuse pending requests if what the user typed matches start of completion const generator = this.generatorReuseManager.getGenerator( prefix, - () => + (abortSignal: AbortSignal) => llm.supportsFim() - ? llm.streamFim(prefix, suffix, completionOptions) - : llm.streamComplete(prompt, { + ? llm.streamFim(prefix, suffix, abortSignal, completionOptions) + : llm.streamComplete(prompt, abortSignal, { ...completionOptions, raw: true, }), diff --git a/core/autocomplete/generation/GeneratorReuseManager.test.ts b/core/autocomplete/generation/GeneratorReuseManager.test.ts index 2454377d3..039059903 100644 --- a/core/autocomplete/generation/GeneratorReuseManager.test.ts +++ b/core/autocomplete/generation/GeneratorReuseManager.test.ts @@ -4,7 +4,7 @@ import { GeneratorReuseManager } from "./GeneratorReuseManager"; function createMockGenerator( data: string[], delay: number = 0, -): () => AsyncGenerator { +): (abortSignal: AbortSignal) => AsyncGenerator { const mockGenerator = async function* () { for (const chunk of data) { yield chunk; diff --git a/core/autocomplete/generation/GeneratorReuseManager.ts b/core/autocomplete/generation/GeneratorReuseManager.ts index 0b19183ce..e099b92f4 100644 --- a/core/autocomplete/generation/GeneratorReuseManager.ts +++ b/core/autocomplete/generation/GeneratorReuseManager.ts @@ -8,12 +8,13 @@ export class GeneratorReuseManager { constructor(private readonly onError: (err: any) => void) {} private _createListenableGenerator( + abortController: AbortController, gen: AsyncGenerator, prefix: string, ) { this.currentGenerator?.cancel(); - const listenableGen = new ListenableGenerator(gen, this.onError); + const listenableGen = new ListenableGenerator(gen, this.onError, abortController); listenableGen.listen((chunk) => (this.pendingCompletion += chunk ?? "")); this.pendingGeneratorPrefix = prefix; @@ -35,13 +36,14 @@ export class GeneratorReuseManager { async *getGenerator( prefix: string, - newGenerator: () => AsyncGenerator, + newGenerator: (abortSignal: AbortSignal) => AsyncGenerator, multiline: boolean, ): AsyncGenerator { // If we can't reuse, then create a new generator if (!this.shouldReuseExistingGenerator(prefix)) { // Create a wrapper over the current generator to fix the prompt - this._createListenableGenerator(newGenerator(), prefix); + const abortController = new AbortController(); + this._createListenableGenerator(abortController, newGenerator(abortController.signal), prefix); } // Already typed characters are those that are new in the prefix from the old generator diff --git a/core/autocomplete/generation/ListenableGenerator.ts b/core/autocomplete/generation/ListenableGenerator.ts index 0cc9f664e..e6b36019b 100644 --- a/core/autocomplete/generation/ListenableGenerator.ts +++ b/core/autocomplete/generation/ListenableGenerator.ts @@ -3,16 +3,20 @@ export class ListenableGenerator { private _buffer: T[] = []; private _listeners: Set<(value: T) => void> = new Set(); private _isEnded = false; + private _abortController: AbortController constructor( source: AsyncGenerator, private readonly onError: (e: any) => void, + abortController: AbortController ) { this._source = source; + this._abortController = abortController; this._start(); } public cancel() { + this._abortController.abort(); this._isEnded = true; } diff --git a/core/commands/index.ts b/core/commands/index.ts index 806e918db..cb5e162f7 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -58,7 +58,7 @@ export function slashFromCustomCommand( } } - for await (const chunk of llm.streamChat(messages)) { + for await (const chunk of llm.streamChat(messages, new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/commands/slash/cmd.ts b/core/commands/slash/cmd.ts index 00ba5b0de..1c3968172 100644 --- a/core/commands/slash/cmd.ts +++ b/core/commands/slash/cmd.ts @@ -24,7 +24,9 @@ const GenerateTerminalCommand: SlashCommand = { "${input}" -Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`); +Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`, + new AbortController().signal + ); const lines = streamLines(gen); let cmd = ""; diff --git a/core/commands/slash/commit.ts b/core/commands/slash/commit.ts index 034e07e5e..7d5f22a90 100644 --- a/core/commands/slash/commit.ts +++ b/core/commands/slash/commit.ts @@ -16,7 +16,7 @@ const CommitMessageCommand: SlashCommand = { const prompt = `${diff}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`; for await (const chunk of llm.streamChat([ { role: "user", content: prompt }, - ])) { + ], new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/draftIssue.ts index 25da6b559..268c68384 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/draftIssue.ts @@ -30,7 +30,7 @@ const DraftIssueCommand: SlashCommand = { return; } let title = await llm.complete( - `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, + `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, new AbortController().signal, { maxTokens: 20 }, ); @@ -43,7 +43,7 @@ const DraftIssueCommand: SlashCommand = { { role: "user", content: PROMPT(input, title) }, ]; - for await (const chunk of llm.streamChat(messages)) { + for await (const chunk of llm.streamChat(messages, new AbortController().signal)) { body += chunk.content; yield stripImages(chunk.content); } diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index fc71838df..78d86beee 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -478,7 +478,7 @@ const EditSlashCommand: SlashCommand = { messages = rendered; } - const completion = llm.streamComplete(rendered as string, { + const completion = llm.streamComplete(rendered as string, new AbortController().signal, { maxTokens: Math.min(maxTokens, Math.floor(llm.contextLength / 2), 4096), raw: true, }); @@ -494,7 +494,7 @@ const EditSlashCommand: SlashCommand = { ); } else { async function* gen() { - for await (const chunk of llm.streamChat(messages, { + for await (const chunk of llm.streamChat(messages, new AbortController().signal,{ temperature: 0.5, // TODO maxTokens: Math.min( maxTokens, @@ -609,7 +609,7 @@ ${lines.join("\n")} Please briefly explain the changes made to the code above. Give no more than 2-3 sentences, and use markdown bullet points:`; - for await (const update of llm.streamComplete(prompt)) { + for await (const update of llm.streamComplete(prompt, new AbortController().signal)) { yield update; } } diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts index 740243a5a..c8cf64679 100644 --- a/core/commands/slash/multifileEdit.ts +++ b/core/commands/slash/multifileEdit.ts @@ -39,7 +39,7 @@ const MultiFileEditSlashCommand: SlashCommand = { const content = createPrompt(filesToEditStr, additionalContextStr, input); - for await (const chunk of llm.streamChat([{ role: "user", content }])) { + for await (const chunk of llm.streamChat([{ role: "user", content }], new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index 8d3433c25..4d8aa3a38 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -47,7 +47,7 @@ const OnboardSlashCommand: SlashCommand = { for await (const chunk of llm.streamChat([ { role: "user", content: prompt }, - ])) { + ], new AbortController().signal)) { yield stripImages(chunk.content); } }, @@ -134,7 +134,7 @@ function createOnboardingPrompt(context: string): string { Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole. Here is an example of a valid response: - + ## Important folders ### /folder1 diff --git a/core/commands/slash/review.ts b/core/commands/slash/review.ts index 34859d94c..77357647a 100644 --- a/core/commands/slash/review.ts +++ b/core/commands/slash/review.ts @@ -45,7 +45,7 @@ const ReviewMessageCommand: SlashCommand = { for await (const chunk of llm.streamChat([ { role: "user", content: content }, - ])) { + ], new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index aa19f3b0c..1ec963513 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -125,7 +125,7 @@ export function slashCommandFromPromptFile( systemMessage, ); - for await (const chunk of context.llm.streamChat(messages)) { + for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) { yield stripImages(chunk.content); } diff --git a/core/context/rerankers/llm.ts b/core/context/rerankers/llm.ts index 5396c8d9b..a673f5dc4 100644 --- a/core/context/rerankers/llm.ts +++ b/core/context/rerankers/llm.ts @@ -6,7 +6,7 @@ const RERANK_PROMPT = ( documentId: string, document: string, ) => `You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: "Yes" or "No" indicating the retrieved snippet is relevant to the query. - + Query: Where is the FastAPI server? Snippet: \`\`\`/Users/andrew/Desktop/server/main.py @@ -17,7 +17,7 @@ const RERANK_PROMPT = ( return {{"Hello": "World"}} \`\`\` Relevant: Yes - + Query: Where in the documentation does it talk about the UI? Snippet: \`\`\`/Users/andrew/Projects/bubble_sort/src/lib.rs @@ -32,13 +32,13 @@ const RERANK_PROMPT = ( }} \`\`\` Relevant: No - + Query: ${query} Snippet: \`\`\`${documentId} ${document} \`\`\` - Relevant: + Relevant: `; export class LLMReranker implements Reranker { @@ -49,6 +49,7 @@ export class LLMReranker implements Reranker { async scoreChunk(chunk: Chunk, query: string): Promise { const completion = await this.llm.complete( RERANK_PROMPT(query, getBasename(chunk.filepath), chunk.content), + new AbortController().signal, { maxTokens: 1, model: diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index e4b3e072e..8dc55df9d 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -61,7 +61,7 @@ This is the question that you should select relevant files for: "${input}"`; const response = await llm.chat([ { role: "user", content: prompt }, { role: "assistant", content: "" }, - ]); + ], new AbortController().signal); const content = stripImages(response.content); console.debug("Repo map retrieval response: ", content); diff --git a/core/core.ts b/core/core.ts index 853666174..b40eb8208 100644 --- a/core/core.ts +++ b/core/core.ts @@ -387,6 +387,7 @@ export class Core { const model = await configHandler.llmFromTitle(msg.data.title); const gen = model.streamChat( msg.data.messages, + new AbortController().signal, msg.data.completionOptions, ); let next = await gen.next(); @@ -428,6 +429,7 @@ export class Core { const model = await configHandler.llmFromTitle(msg.data.title); const gen = model.streamComplete( msg.data.prompt, + new AbortController().signal, msg.data.completionOptions, ); let next = await gen.next(); @@ -460,6 +462,7 @@ export class Core { const model = await this.configHandler.llmFromTitle(msg.data.title); const completion = await model.complete( msg.data.prompt, + new AbortController().signal, msg.data.completionOptions, ); return completion; diff --git a/core/edit/lazy/replace.ts b/core/edit/lazy/replace.ts index e6c3183f0..26e174c17 100644 --- a/core/edit/lazy/replace.ts +++ b/core/edit/lazy/replace.ts @@ -86,7 +86,7 @@ export async function* getReplacementWithLlm( const completion = await llm.streamChat([ { role: "user", content: userPrompt }, { role: "assistant", content: assistantPrompt }, - ]); + ], new AbortController().signal); let lines = streamLines(completion); lines = filterLeadingNewline(lines); diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 135aa3170..a5c85ee4d 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -23,7 +23,7 @@ export async function* streamLazyApply( } const promptMessages = promptFactory(oldCode, filename, newCode); - const lazyCompletion = llm.streamChat(promptMessages); + const lazyCompletion = llm.streamChat(promptMessages, new AbortController().signal); // Do find and replace over the lazy edit response async function* replacementFunction( diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index ca47f010d..5ecf273c5 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -96,8 +96,8 @@ export async function* streamDiffLines( const completion = typeof prompt === "string" - ? llm.streamComplete(prompt, { raw: true, prediction }) - : llm.streamChat(prompt, { + ? llm.streamComplete(prompt, new AbortController().signal, { raw: true, prediction }) + : llm.streamChat(prompt, new AbortController().signal, { prediction, }); diff --git a/core/index.d.ts b/core/index.d.ts index ca6c8482d..392a9e11c 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -78,26 +78,34 @@ export interface ILLM extends LLMOptions { region?: string; projectId?: string; - complete(prompt: string, options?: LLMFullCompletionOptions): Promise; + complete( + prompt: string, + signal: AbortSignal, + options?: LLMFullCompletionOptions + ): Promise; streamComplete( prompt: string, + signal: AbortSignal, options?: LLMFullCompletionOptions, ): AsyncGenerator; streamFim( prefix: string, suffix: string, + signal: AbortSignal, options?: LLMFullCompletionOptions, ): AsyncGenerator; streamChat( messages: ChatMessage[], + signal: AbortSignal, options?: LLMFullCompletionOptions, ): AsyncGenerator; chat( messages: ChatMessage[], + signal: AbortSignal, options?: LLMFullCompletionOptions, ): Promise; @@ -388,11 +396,13 @@ export interface CustomLLMWithOptionals { options: LLMOptions; streamCompletion?: ( prompt: string, + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; streamChat?: ( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; diff --git a/core/llm/index.ts b/core/llm/index.ts index d3148f833..1156120a6 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -372,10 +372,11 @@ export abstract class BaseLLM implements ILLM { `HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`, ); } else { - console.debug( - `${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`, - ); - + if (e.name !== "AbortError") { // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here + console.debug( + `${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`, + ); + } if ( e.code === "ECONNREFUSED" && e.message.includes("http://127.0.0.1:11434") @@ -424,6 +425,7 @@ export abstract class BaseLLM implements ILLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { throw new Error("Not implemented"); @@ -432,6 +434,7 @@ export abstract class BaseLLM implements ILLM { async *streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { const { completionOptions, log } = this._parseCompletionOptions(options); @@ -452,6 +455,7 @@ export abstract class BaseLLM implements ILLM { for await (const chunk of this._streamFim( prefix, suffix, + signal, completionOptions, )) { completion += chunk; @@ -477,6 +481,7 @@ export abstract class BaseLLM implements ILLM { async *streamComplete( _prompt: string, + signal: AbortSignal, options: LLMFullCompletionOptions = {}, ) { const { completionOptions, log, raw } = @@ -506,6 +511,7 @@ export abstract class BaseLLM implements ILLM { try { for await (const chunk of this._streamComplete( prompt, + signal, completionOptions, )) { completion += chunk; @@ -527,7 +533,7 @@ export abstract class BaseLLM implements ILLM { }; } - async complete(_prompt: string, options: LLMFullCompletionOptions = {}) { + async complete(_prompt: string, signal: AbortSignal, options: LLMFullCompletionOptions = {}) { const { completionOptions, log, raw } = this._parseCompletionOptions(options); @@ -551,7 +557,7 @@ export abstract class BaseLLM implements ILLM { } } - const completion = await this._complete(prompt, completionOptions); + const completion = await this._complete(prompt, signal, completionOptions); this._logTokensGenerated(completionOptions.model, prompt, completion); @@ -562,9 +568,9 @@ export abstract class BaseLLM implements ILLM { return completion; } - async chat(messages: ChatMessage[], options: LLMFullCompletionOptions = {}) { + async chat(messages: ChatMessage[], signal: AbortSignal, options: LLMFullCompletionOptions = {}) { let completion = ""; - for await (const chunk of this.streamChat(messages, options)) { + for await (const chunk of this.streamChat(messages, signal, options)) { completion += chunk.content; } return { role: "assistant" as ChatMessageRole, content: completion }; @@ -572,6 +578,7 @@ export abstract class BaseLLM implements ILLM { async *streamChat( _messages: ChatMessage[], + signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { const { completionOptions, log, raw } = @@ -597,6 +604,7 @@ export abstract class BaseLLM implements ILLM { if (this.templateMessages) { for await (const chunk of this._streamComplete( prompt, + signal, completionOptions, )) { completion += chunk; @@ -605,6 +613,7 @@ export abstract class BaseLLM implements ILLM { } else { for await (const chunk of this._streamChat( messages, + signal, completionOptions, )) { completion += chunk.content; @@ -633,6 +642,7 @@ export abstract class BaseLLM implements ILLM { // biome-ignore lint/correctness/useYield: Purposefully not implemented protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { throw new Error("Not implemented"); @@ -640,6 +650,7 @@ export abstract class BaseLLM implements ILLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (!this.templateMessages) { @@ -650,15 +661,16 @@ export abstract class BaseLLM implements ILLM { for await (const chunk of this._streamComplete( this.templateMessages(messages), + signal, options, )) { yield { role: "assistant", content: chunk }; } } - protected async _complete(prompt: string, options: CompletionOptions) { + protected async _complete(prompt: string, signal: AbortSignal, options: CompletionOptions) { let completion = ""; - for await (const chunk of this._streamComplete(prompt, options)) { + for await (const chunk of this._streamComplete(prompt, signal, options)) { completion += chunk; } return completion; diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 8db42eefa..3f860511b 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -95,16 +95,18 @@ class Anthropic extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; - for await (const update of this._streamChat(messages, options)) { + for await (const update of this._streamChat(messages, signal, options)) { yield stripImages(update.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const shouldCacheSystemMessage = @@ -137,6 +139,7 @@ class Anthropic extends BaseLLM { ] : systemMessage, }), + signal }); if (options.stream === false) { diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts index 85fb19184..74b1ddc27 100644 --- a/core/llm/llms/Asksage.ts +++ b/core/llm/llms/Asksage.ts @@ -98,6 +98,7 @@ class Asksage extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions ): Promise { if (typeof prompt !== "string" || prompt.trim() === "") { @@ -126,14 +127,16 @@ class Asksage extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions ): AsyncGenerator { - const completion = await this._complete(prompt, options); + const completion = await this._complete(prompt, signal, options); yield completion; } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions ): AsyncGenerator { const args = this._convertArgs(options, messages); @@ -142,6 +145,7 @@ class Asksage extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify(args), + signal }); if (!response.ok) { diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 67d8a4167..01a0201eb 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -37,16 +37,18 @@ class Bedrock extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; - for await (const update of this._streamChat(messages, options)) { + for await (const update of this._streamChat(messages, signal, options)) { yield stripImages(update.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -84,7 +86,7 @@ class Bedrock extends BaseLLM { const input = this._generateConverseInput(messages, options); const command = new ConverseStreamCommand(input); - const response = await client.send(command); + const response = await client.send(command, { abortSignal: signal}); if (response.stream) { for await (const chunk of response.stream) { diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts index 44a57205e..5726cd91e 100644 --- a/core/llm/llms/BedrockImport.ts +++ b/core/llm/llms/BedrockImport.ts @@ -37,6 +37,7 @@ class BedrockImport extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -51,7 +52,7 @@ class BedrockImport extends BaseLLM { const input = this._generateInvokeModelCommandInput(prompt, options); const command = new InvokeModelWithResponseStreamCommand(input); - const response = await client.send(command); + const response = await client.send(command, {abortSignal: signal}); if (response.body) { for await (const item of response.body) { diff --git a/core/llm/llms/Cloudflare.ts b/core/llm/llms/Cloudflare.ts index 93b9c4433..07e2e427c 100644 --- a/core/llm/llms/Cloudflare.ts +++ b/core/llm/llms/Cloudflare.ts @@ -16,6 +16,7 @@ export default class Cloudflare extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const headers = { @@ -35,6 +36,7 @@ export default class Cloudflare extends BaseLLM { model: this.model, ...this._convertArgs(options), }), + signal }); for await (const value of streamSse(resp)) { @@ -46,10 +48,12 @@ export default class Cloudflare extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { yield stripImages(chunk.content); diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index 83f255904..98135c7cc 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -46,16 +46,18 @@ class Cohere extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; - for await (const update of this._streamChat(messages, options)) { + for await (const update of this._streamChat(messages, signal, options)) { yield stripImages(update.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const headers = { @@ -73,6 +75,7 @@ class Cohere extends BaseLLM { chat_history: this._convertMessages(messages), preamble: this.systemMessage, }), + signal }); if (options.stream === false) { diff --git a/core/llm/llms/CustomLLM.ts b/core/llm/llms/CustomLLM.ts index d35dfabde..81d038f9d 100644 --- a/core/llm/llms/CustomLLM.ts +++ b/core/llm/llms/CustomLLM.ts @@ -13,12 +13,14 @@ class CustomLLMClass extends BaseLLM { private customStreamCompletion?: ( prompt: string, + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; private customStreamChat?: ( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; @@ -31,18 +33,20 @@ class CustomLLMClass extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (this.customStreamChat) { for await (const content of this.customStreamChat( messages, + signal, options, (...args) => this.fetch(...args), )) { yield { role: "assistant", content }; } } else { - for await (const update of super._streamChat(messages, options)) { + for await (const update of super._streamChat(messages, signal, options)) { yield update; } } @@ -50,11 +54,13 @@ class CustomLLMClass extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (this.customStreamCompletion) { for await (const content of this.customStreamCompletion( prompt, + signal, options, (...args) => this.fetch(...args), )) { @@ -63,6 +69,7 @@ class CustomLLMClass extends BaseLLM { } else if (this.customStreamChat) { for await (const content of this.customStreamChat( [{ role: "user", content: prompt }], + signal, options, (...args) => this.fetch(...args), )) { diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts index cfba34e85..177ac7efa 100644 --- a/core/llm/llms/Deepseek.ts +++ b/core/llm/llms/Deepseek.ts @@ -23,6 +23,7 @@ class Deepseek extends OpenAI { async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("beta/completions", this.apiBase); @@ -45,6 +46,7 @@ class Deepseek extends OpenAI { Accept: "application/json", Authorization: `Bearer ${this.apiKey}`, }, + signal }); for await (const chunk of streamSse(resp)) { yield chunk.choices[0].text; diff --git a/core/llm/llms/Flowise.ts b/core/llm/llms/Flowise.ts index 0d9e617a0..ecca89d16 100644 --- a/core/llm/llms/Flowise.ts +++ b/core/llm/llms/Flowise.ts @@ -121,16 +121,18 @@ class Flowise extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const message: ChatMessage = { role: "user", content: prompt }; - for await (const chunk of this._streamChat([message], options)) { + for await (const chunk of this._streamChat([message], signal, options)) { yield stripImages(chunk.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const requestBody = this._getRequestBody(messages, options); @@ -139,6 +141,7 @@ class Flowise extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }), + signal }).then((res) => res.json()); while (await socketInfo.hasNextToken()) { diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 9f307d125..8f80c7418 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -60,6 +60,7 @@ class FreeTrial extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(this.collectArgs(options)); @@ -73,6 +74,7 @@ class FreeTrial extends BaseLLM { prompt, ...args, }), + signal }); let completion = ""; @@ -103,6 +105,7 @@ class FreeTrial extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(this.collectArgs(options)); @@ -120,6 +123,7 @@ class FreeTrial extends BaseLLM { messages: messages.map(this._convertMessage), ...args, }), + signal }); let completion = ""; @@ -140,6 +144,7 @@ class FreeTrial extends BaseLLM { async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(this.collectArgs(options)); @@ -153,6 +158,7 @@ class FreeTrial extends BaseLLM { suffix, ...args, }), + signal }); let completion = ""; diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 2e33968d5..ada603240 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -46,10 +46,12 @@ class Gemini extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const message of this._streamChat( [{ content: prompt, role: "user" }], + signal, options, )) { yield stripImages(message.content); @@ -72,6 +74,7 @@ class Gemini extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { // Ensure this.apiBase is used if available, otherwise use default @@ -89,6 +92,7 @@ class Gemini extends BaseLLM { if (options.model.includes("gemini")) { for await (const message of this.streamChatGemini( convertedMsgs, + signal, options, )) { yield message; @@ -96,6 +100,7 @@ class Gemini extends BaseLLM { } else { for await (const message of this.streamChatBison( convertedMsgs, + signal, options, )) { yield message; @@ -118,6 +123,7 @@ class Gemini extends BaseLLM { private async *streamChatGemini( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const apiURL = new URL( @@ -159,6 +165,7 @@ class Gemini extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal }); let buffer = ""; @@ -211,6 +218,7 @@ class Gemini extends BaseLLM { } private async *streamChatBison( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const msgList = []; @@ -226,6 +234,7 @@ class Gemini extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal }); const data = await response.json(); yield { role: "assistant", content: data.candidates[0].content }; diff --git a/core/llm/llms/HuggingFaceInferenceAPI.ts b/core/llm/llms/HuggingFaceInferenceAPI.ts index 21b607163..7e8d11c56 100644 --- a/core/llm/llms/HuggingFaceInferenceAPI.ts +++ b/core/llm/llms/HuggingFaceInferenceAPI.ts @@ -16,6 +16,7 @@ class HuggingFaceInferenceAPI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (!this.apiBase) { @@ -36,6 +37,7 @@ class HuggingFaceInferenceAPI extends BaseLLM { stream: true, parameters: this._convertArgs(options), }), + signal }); async function* stream() { diff --git a/core/llm/llms/HuggingFaceTGI.ts b/core/llm/llms/HuggingFaceTGI.ts index 9636dbc63..df84083dc 100644 --- a/core/llm/llms/HuggingFaceTGI.ts +++ b/core/llm/llms/HuggingFaceTGI.ts @@ -48,6 +48,7 @@ class HuggingFaceTGI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(options, prompt); @@ -60,6 +61,7 @@ class HuggingFaceTGI extends BaseLLM { "Content-Type": "application/json", }, body: JSON.stringify({ inputs: prompt, parameters: args }), + signal }, ); diff --git a/core/llm/llms/LlamaCpp.ts b/core/llm/llms/LlamaCpp.ts index e37b445e6..80ada3fdf 100644 --- a/core/llm/llms/LlamaCpp.ts +++ b/core/llm/llms/LlamaCpp.ts @@ -26,6 +26,7 @@ class LlamaCpp extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const headers = { @@ -42,6 +43,7 @@ class LlamaCpp extends BaseLLM { stream: true, ...this._convertArgs(options, prompt), }), + signal }); for await (const value of streamSse(resp)) { diff --git a/core/llm/llms/Mock.ts b/core/llm/llms/Mock.ts index e6097a60d..5f3880e3c 100644 --- a/core/llm/llms/Mock.ts +++ b/core/llm/llms/Mock.ts @@ -7,6 +7,7 @@ class Mock extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { yield this.completion; @@ -14,6 +15,7 @@ class Mock extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for (const char of this.completion) { diff --git a/core/llm/llms/Moonshot.ts b/core/llm/llms/Moonshot.ts index 022fa8af2..5a015dcca 100644 --- a/core/llm/llms/Moonshot.ts +++ b/core/llm/llms/Moonshot.ts @@ -23,6 +23,7 @@ class Moonshot extends OpenAI { async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("v1/chat/completions", this.apiBase); @@ -49,6 +50,7 @@ class Moonshot extends OpenAI { Accept: "application/json", Authorization: `Bearer ${this.apiKey}`, }, + signal }); for await (const chunk of streamSse(resp)) { yield chunk.choices[0].delta.content; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index a9ac7ab75..dcaa078ba 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -30,7 +30,7 @@ interface ModelFileParams { min_p?: number; // deprecated? num_thread?: number; - use_mmap?: boolean; + use_mmap?: boolean; num_gqa?: number; num_gpu?: number; } @@ -77,7 +77,6 @@ class Ollama extends BaseLLM { if (options.model === "AUTODETECT") { return; } - this.fetch(this.getEndpoint("api/show"), { method: "POST", headers: { @@ -262,6 +261,7 @@ class Ollama extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const response = await this.fetch(this.getEndpoint("api/generate"), { @@ -271,6 +271,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getGenerateOptions(options, prompt)), + signal }); let buffer = ""; @@ -301,6 +302,7 @@ class Ollama extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const response = await this.fetch(this.getEndpoint("api/chat"), { @@ -310,6 +312,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getChatOptions(options, messages)), + signal }); let buffer = ""; @@ -348,8 +351,10 @@ class Ollama extends BaseLLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { + const response = await this.fetch(this.getEndpoint("api/generate"), { method: "POST", headers: { @@ -357,6 +362,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)), + signal }); let buffer = ""; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 8498cd8cb..36abb746d 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -166,11 +166,13 @@ class OpenAI extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): Promise { let completion = ""; for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { completion += chunk.content; @@ -199,10 +201,12 @@ class OpenAI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { yield stripImages(chunk.content); @@ -211,6 +215,7 @@ class OpenAI extends BaseLLM { protected async *_legacystreamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args: any = this._convertArgs(options, []); @@ -224,6 +229,7 @@ class OpenAI extends BaseLLM { ...args, stream: true, }), + signal }); for await (const value of streamSse(response)) { @@ -235,6 +241,7 @@ class OpenAI extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if ( @@ -246,6 +253,7 @@ class OpenAI extends BaseLLM { ) { for await (const content of this._legacystreamComplete( stripImages(messages[messages.length - 1]?.content || ""), + signal, options, )) { yield { @@ -266,6 +274,7 @@ class OpenAI extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify(body), + signal }); // Handle non-streaming response @@ -285,6 +294,7 @@ class OpenAI extends BaseLLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("fim/completions", this.apiBase); @@ -308,6 +318,7 @@ class OpenAI extends BaseLLM { "x-api-key": this.apiKey ?? "", Authorization: `Bearer ${this.apiKey}`, }, + signal }); for await (const chunk of streamSse(resp)) { yield chunk.choices[0].delta.content; diff --git a/core/llm/llms/Replicate.ts b/core/llm/llms/Replicate.ts index 414975ac4..59994cec1 100644 --- a/core/llm/llms/Replicate.ts +++ b/core/llm/llms/Replicate.ts @@ -41,11 +41,13 @@ class Replicate extends BaseLLM { private _convertArgs( options: CompletionOptions, prompt: string, - ): [`${string}/${string}:${string}`, { input: any }] { + signal: AbortSignal + ): [`${string}/${string}:${string}`, { input: any, signal: AbortSignal }] { return [ Replicate.MODEL_IDS[options.model] || (options.model as any), { input: { prompt, message: prompt }, + signal }, ]; } @@ -57,9 +59,10 @@ class Replicate extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): Promise { - const [model, args] = this._convertArgs(options, prompt); + const [model, args] = this._convertArgs(options, prompt, signal); const response = await this._replicate.run(model, args); return (response as any)[0]; @@ -67,9 +70,10 @@ class Replicate extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - const [model, args] = this._convertArgs(options, prompt); + const [model, args] = this._convertArgs(options, prompt, signal); for await (const event of this._replicate.stream(model, args)) { if (event.event === "output") { yield event.data; diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts index c88261941..edbda4d34 100644 --- a/core/llm/llms/SageMaker.ts +++ b/core/llm/llms/SageMaker.ts @@ -32,6 +32,7 @@ class SageMaker extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -45,7 +46,7 @@ class SageMaker extends BaseLLM { }); const toolkit = new CompletionAPIToolkit(this); const command = toolkit.generateCommand([], prompt, options); - const response = await client.send(command); + const response = await client.send(command, { abortSignal: signal }); if (response.Body) { let buffer = ""; for await (const rawValue of response.Body) { @@ -82,6 +83,7 @@ class SageMaker extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -96,7 +98,7 @@ class SageMaker extends BaseLLM { const toolkit = new MessageAPIToolkit(this); const command = toolkit.generateCommand(messages, "", options); - const response = await client.send(command); + const response = await client.send(command, { abortSignal: signal }); if (response.Body) { let buffer = ""; for await (const rawValue of response.Body) { diff --git a/core/llm/llms/Together.ts b/core/llm/llms/Together.ts index f5b5f0bac..b0044c4a8 100644 --- a/core/llm/llms/Together.ts +++ b/core/llm/llms/Together.ts @@ -41,9 +41,10 @@ class Together extends OpenAI { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - for await (const chunk of this._legacystreamComplete(prompt, options)) { + for await (const chunk of this._legacystreamComplete(prompt,signal, options)) { yield chunk; } } diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index e945831e6..c17aac90d 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -49,7 +49,7 @@ class VertexAI extends BaseLLM { "unknown"; this.anthropicInstance = new Anthropic(_options); this.geminiInstance = new Gemini(_options); - + } async fetch(url: RequestInfo | URL, init?: RequestInit) { @@ -307,6 +307,7 @@ class VertexAI extends BaseLLM { protected async *StreamFimMistral( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const apiBase = this.apiBase!; @@ -329,6 +330,7 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal }); for await (const chunk of streamSse(response)) { @@ -342,6 +344,7 @@ class VertexAI extends BaseLLM { protected async *streamFimGecko( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("publishers/google/models/code-gecko:predict", this.apiBase); @@ -363,6 +366,7 @@ class VertexAI extends BaseLLM { } }), + signal }); // Streaming is not supported by code-gecko // TODO: convert to non-streaming fim method when one exist in continue. @@ -373,6 +377,7 @@ class VertexAI extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const isV1API = this.apiBase.includes("/v1/"); @@ -396,10 +401,12 @@ class VertexAI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const message of this._streamChat( [{ content: prompt, role: "user" }], + signal, options, )) { yield stripImages(message.content); @@ -409,15 +416,16 @@ class VertexAI extends BaseLLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (this.model === "code-gecko") { - yield* this.streamFimGecko(prefix, suffix, options); + yield* this.streamFimGecko(prefix, suffix, signal, options); } else if (this.model.includes("codestral")) { - yield* this.StreamFimMistral(prefix, suffix, options); + yield* this.StreamFimMistral(prefix, suffix, signal, options); } else { throw new Error(`Unsupported model: ${this.model}`); } diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 89a2d13dc..808557692 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -140,11 +140,13 @@ class WatsonX extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): Promise { let completion = ""; for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { completion += chunk.content; @@ -155,10 +157,12 @@ class WatsonX extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { yield stripImages(chunk.content); @@ -167,6 +171,7 @@ class WatsonX extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { var now = new Date().getTime() / 1000; @@ -219,6 +224,7 @@ class WatsonX extends BaseLLM { method: "POST", headers: headers, body: JSON.stringify(payload), + signal }); if (!response.ok || response.body === null) { diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index 4b77360fe..9e4f0c194 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -90,7 +90,7 @@ export function slashCommandFromPromptFile( systemMessage, ); - for await (const chunk of context.llm.streamChat(messages)) { + for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index 5f3d1bdc1..b8ca609a2 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -52,6 +52,7 @@ export class ChatDescriber { content: ChatDescriber.prompt + message, }, ], + new AbortController().signal, completionOptions, ); From e60341647fcf9834844ad7ef4d5aa44fe1edf801 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 20 Nov 2024 08:50:24 -0800 Subject: [PATCH 79/82] bump version --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 697bf61c1..ef2d12c82 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.231", + "version": "0.9.232", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From a20374299ac6f70f5cc26bdf16690f8681e78757 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 20 Nov 2024 10:25:25 -0800 Subject: [PATCH 80/82] change button height --- gui/src/components/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/gui/src/components/index.ts b/gui/src/components/index.ts index 3a384c995..e380f3ef6 100644 --- a/gui/src/components/index.ts +++ b/gui/src/components/index.ts @@ -154,7 +154,6 @@ export const Button = styled.button` export const SecondaryButton = styled.button` padding: 10px 12px; margin: 8px 0; - height: 2.5rem; border-radius: ${defaultBorderRadius}; border: 1px solid ${vscForeground}; From eb4030207f41ee68f3e6de433b1d0023d2b030b8 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 20 Nov 2024 10:31:49 -0800 Subject: [PATCH 81/82] clear symbols on new session --- gui/src/redux/slices/stateSlice.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index c0132cf41..29fee95d3 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -12,8 +12,8 @@ import { import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { stripImages } from "core/llm/images"; -import { v4 as uuidv4, v4 } from "uuid"; import { ApplyState } from "core/protocol/ideWebview"; +import { v4 as uuidv4, v4 } from "uuid"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -295,6 +295,7 @@ export const stateSlice = createSlice({ state.active = false; state.context.isGathering = false; state.isMultifileEdit = false; + state.symbols = {}; if (payload) { state.history = payload.history as any; state.title = payload.title; From d909621a9337ffd6eae5970c64c33b32c1e0b91a Mon Sep 17 00:00:00 2001 From: Ari Roffe Date: Wed, 20 Nov 2024 15:23:25 -0600 Subject: [PATCH 82/82] Update context-providers.md --- docs/docs/customize/context-providers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index e582beb1b..a423ff4dc 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -291,7 +291,7 @@ Reference the conversation in a Jira issue. "name": "jira", "params": { "domain": "company.atlassian.net", - "token ": "ATATT..." + "token": "ATATT..." } } ]