From 001966ac29527ce5f84e5c9f7a696353a92b62c8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 11 Nov 2024 17:02:06 -0800 Subject: [PATCH 01/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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 067da11573d17049b39749fe53086efc832bd56d Mon Sep 17 00:00:00 2001 From: Test Date: Fri, 15 Nov 2024 14:32:13 -0800 Subject: [PATCH 11/28] 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 12/28] 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 fc934933c570c9c97150732b85e0426b94143ae1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 15 Nov 2024 15:23:31 -0800 Subject: [PATCH 13/28] 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 bcd82c901117c69680e4ec64185d26d494575c70 Mon Sep 17 00:00:00 2001 From: Test Date: Fri, 15 Nov 2024 15:59:49 -0800 Subject: [PATCH 14/28] 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 0af5dc4411d791d8afcb3693eb86e8482444338d Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 16 Nov 2024 14:13:46 -0800 Subject: [PATCH 15/28] 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 16/28] 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 17/28] 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 18/28] 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 19/28] 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 20/28] 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 b8a278d216db9851aa2b0772e0313ff4bc12c7cc Mon Sep 17 00:00:00 2001 From: burlinchen Date: Mon, 18 Nov 2024 09:34:17 +0800 Subject: [PATCH 21/28] 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 2f84ef0ab9a87aa6300415d30db02e3460a07195 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Fri, 15 Nov 2024 15:29:54 -0800 Subject: [PATCH 22/28] feat: capture python definitions --- .../RootPathContextService.ts | 7 +- .../test/RootPathContextService.test.ts | 25 +-- .../root-path-context/test/files/file1.py | 13 -- .../test/files/python/classes.py | 11 ++ .../test/files/python/functions.py | 42 +++++ .../files/{ => typescript}/arrowFunctions.ts | 0 .../files/{ => typescript}/classMethods.ts | 0 .../test/files/{ => typescript}/classes.ts | 0 .../test/files/{ => typescript}/functions.ts | 0 .../test/files/{ => typescript}/generators.ts | 0 .../root-path-context/test/testCases/index.ts | 2 + .../test/testCases/python.ts | 145 ++++++++++++++++++ .../test/testCases/typescript.ts | 72 ++++----- .../python/class_definition.scm | 27 +++- .../python/function_definition.scm | 71 +++++++-- 15 files changed, 322 insertions(+), 93 deletions(-) delete mode 100644 core/autocomplete/context/root-path-context/test/files/file1.py create mode 100644 core/autocomplete/context/root-path-context/test/files/python/classes.py create mode 100644 core/autocomplete/context/root-path-context/test/files/python/functions.py rename core/autocomplete/context/root-path-context/test/files/{ => typescript}/arrowFunctions.ts (100%) rename core/autocomplete/context/root-path-context/test/files/{ => typescript}/classMethods.ts (100%) rename core/autocomplete/context/root-path-context/test/files/{ => typescript}/classes.ts (100%) rename core/autocomplete/context/root-path-context/test/files/{ => typescript}/functions.ts (100%) rename core/autocomplete/context/root-path-context/test/files/{ => typescript}/generators.ts (100%) create mode 100644 core/autocomplete/context/root-path-context/test/testCases/index.ts create mode 100644 core/autocomplete/context/root-path-context/test/testCases/python.ts diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index 0147df151..8571acd0a 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -82,9 +82,9 @@ export class RootPathContextService { this.importDefinitionsService.get(filepath); break; default: - // const type = node.type; - // console.log(getSyntaxTreeString(node)); - // debugger; + const type = node.type; + console.log(getSyntaxTreeString(node)); + debugger; query = await getQueryForFile( filepath, @@ -176,6 +176,7 @@ export class RootPathContextService { parentKey = key; } + debugger; return snippets; } } diff --git a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts index 78aed69a7..a954dda84 100644 --- a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts +++ b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts @@ -1,30 +1,9 @@ -import { TYPESCRIPT_TEST_CASES } from "./testCases/typescript"; +import { PYTHON_TEST_CASES, TYPESCRIPT_TEST_CASES } from "./testCases"; import { testRootPathContext } from "./testUtils"; const TEST_CASES = [ + ...PYTHON_TEST_CASES, ...TYPESCRIPT_TEST_CASES, - { - nodeType: "function_definition", - fileName: "file1.py", - language: "Python", - cursorPosition: { line: 4, character: 25 }, - definitionPositions: [ - { row: 3, column: 30 }, // Person - { row: 3, column: 42 }, // Address - ], - }, - { - nodeType: "function_definition (inside a class)", - fileName: "file1.py", - language: "Python", - cursorPosition: { line: 12, character: 33 }, - definitionPositions: [ - { row: 6, column: 21 }, // BaseClass - { row: 6, column: 33 }, // Collection - { row: 11, column: 47 }, // Person - { row: 11, column: 59 }, // Address - ], - }, { nodeType: "function_definition", fileName: "file1.php", diff --git a/core/autocomplete/context/root-path-context/test/files/file1.py b/core/autocomplete/context/root-path-context/test/files/file1.py deleted file mode 100644 index 55c3d9c25..000000000 --- a/core/autocomplete/context/root-path-context/test/files/file1.py +++ /dev/null @@ -1,13 +0,0 @@ -from .base_module import BaseClass, Collection, Person, Address -from typing import List - -def get_address(person: Person) -> Address: - return person.address - -class Group(BaseClass, Collection): - def __init__(self, people: List[Person]) -> None: - super().__init__() - self.people = people - - def get_person_address(self, person: Person) -> Address: - return get_address(person) diff --git a/core/autocomplete/context/root-path-context/test/files/python/classes.py b/core/autocomplete/context/root-path-context/test/files/python/classes.py new file mode 100644 index 000000000..d752d8433 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/files/python/classes.py @@ -0,0 +1,11 @@ +class Group(BaseClass, Person): + pass + +class Group(metaclass=MetaGroup): + pass + +class Group(BaseClass[Address], Gathering[Person]): + pass + +class Group(List[Address], Person[str]): + pass \ No newline at end of file diff --git a/core/autocomplete/context/root-path-context/test/files/python/functions.py b/core/autocomplete/context/root-path-context/test/files/python/functions.py new file mode 100644 index 000000000..74a9d8b58 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/files/python/functions.py @@ -0,0 +1,42 @@ +from typing import List, Union, TypeVar, Generic + +T = TypeVar('T') + +class Address: + pass + +class Person: + pass + +class PersonWithGeneric(Generic[T]): + pass + + +def get_address(person: Person) -> Address: + pass + +def get_group_address(people: Group[Person]) -> Group[Address]: + pass + +def log_person(person: Person) -> None: + pass + +def get_hardcoded_address() -> Address: + pass + +def log_person_or_address(value: Union[Person, Address]) -> Union[Person, Address]: + pass + +def log_person_and_address(person: Person, address: Address) -> None: + pass + +def get_address_generator(person: Person) -> Generator[Address, None, None]: + yield + + +class Group: + def log_person_and_address(self, person: Person, address: Address) -> None: + pass + +async def get_person(address: Address) -> Person: + pass \ No newline at end of file diff --git a/core/autocomplete/context/root-path-context/test/files/arrowFunctions.ts b/core/autocomplete/context/root-path-context/test/files/typescript/arrowFunctions.ts similarity index 100% rename from core/autocomplete/context/root-path-context/test/files/arrowFunctions.ts rename to core/autocomplete/context/root-path-context/test/files/typescript/arrowFunctions.ts diff --git a/core/autocomplete/context/root-path-context/test/files/classMethods.ts b/core/autocomplete/context/root-path-context/test/files/typescript/classMethods.ts similarity index 100% rename from core/autocomplete/context/root-path-context/test/files/classMethods.ts rename to core/autocomplete/context/root-path-context/test/files/typescript/classMethods.ts diff --git a/core/autocomplete/context/root-path-context/test/files/classes.ts b/core/autocomplete/context/root-path-context/test/files/typescript/classes.ts similarity index 100% rename from core/autocomplete/context/root-path-context/test/files/classes.ts rename to core/autocomplete/context/root-path-context/test/files/typescript/classes.ts diff --git a/core/autocomplete/context/root-path-context/test/files/functions.ts b/core/autocomplete/context/root-path-context/test/files/typescript/functions.ts similarity index 100% rename from core/autocomplete/context/root-path-context/test/files/functions.ts rename to core/autocomplete/context/root-path-context/test/files/typescript/functions.ts diff --git a/core/autocomplete/context/root-path-context/test/files/generators.ts b/core/autocomplete/context/root-path-context/test/files/typescript/generators.ts similarity index 100% rename from core/autocomplete/context/root-path-context/test/files/generators.ts rename to core/autocomplete/context/root-path-context/test/files/typescript/generators.ts diff --git a/core/autocomplete/context/root-path-context/test/testCases/index.ts b/core/autocomplete/context/root-path-context/test/testCases/index.ts new file mode 100644 index 000000000..7859fc23d --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/testCases/index.ts @@ -0,0 +1,2 @@ +export * from "./python"; +export * from "./typescript"; diff --git a/core/autocomplete/context/root-path-context/test/testCases/python.ts b/core/autocomplete/context/root-path-context/test/testCases/python.ts new file mode 100644 index 000000000..9c8d46e43 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/testCases/python.ts @@ -0,0 +1,145 @@ +export const FUNCTIONS = [ + { + nodeType: "function_definition with argument and return type", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 15, character: 8 }, + definitionPositions: [ + { row: 14, column: 30 }, // Person + { row: 14, column: 42 }, // Address + ], + }, + { + nodeType: + "function_definition with generic argument and generic return type", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 18, character: 8 }, + definitionPositions: [ + { row: 17, column: 35 }, // Group + { row: 17, column: 42 }, // Person + { row: 17, column: 53 }, // Group + { row: 17, column: 61 }, // Address + ], + }, + { + nodeType: "function_definition with single argument and None return type", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 21, character: 8 }, + definitionPositions: [ + { row: 20, column: 29 }, // Person + ], + }, + { + nodeType: "function_definition with no arguments and single return type", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 24, character: 8 }, + definitionPositions: [ + { row: 23, column: 38 }, // Address + ], + }, + { + nodeType: "function_definition with Union arguments and Union return type", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 27, character: 8 }, + definitionPositions: [ + { row: 26, column: 45 }, // Person + { row: 26, column: 54 }, // Address + { row: 26, column: 72 }, // Person + { row: 26, column: 81 }, // Address + ], + }, + { + nodeType: + "function_definition with multiple arguments and None return type", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 30, character: 8 }, + definitionPositions: [ + { row: 29, column: 41 }, // Person + { row: 29, column: 59 }, // Address + ], + }, + { + nodeType: "function_definition with one argument and Generator return type", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 33, character: 9 }, + definitionPositions: [ + { row: 32, column: 40 }, // Person + { row: 32, column: 62 }, // Address + ], + }, + { + nodeType: "function_definition inside a class", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 38, character: 12 }, + definitionPositions: [ + { row: 37, column: 51 }, // Person + { row: 37, column: 69 }, // Address + ], + }, + { + nodeType: "function_definition of an async function", + fileName: "python/functions.py", + language: "Python", + cursorPosition: { line: 41, character: 8 }, + definitionPositions: [ + { row: 40, column: 37 }, // Address + { row: 40, column: 48 }, // Person + ], + }, +]; + +export const CLASSES = [ + { + nodeType: "class_definition with multiple superclasses", + fileName: "python/classes.py", + language: "Python", + cursorPosition: { line: 1, character: 8 }, + definitionPositions: [ + { row: 0, column: 21 }, // BaseClass + { row: 0, column: 29 }, // Person + ], + }, + { + nodeType: "class_definition with multiple superclasses", + fileName: "python/classes.py", + language: "Python", + cursorPosition: { line: 4, character: 8 }, + definitionPositions: [ + { row: 3, column: 31 }, // MetaGroup + ], + }, + { + nodeType: "class_definition with generic superclasses", + fileName: "python/classes.py", + language: "Python", + cursorPosition: { line: 7, character: 8 }, + definitionPositions: [ + { row: 6, column: 21 }, // BaseClass + { row: 6, column: 29 }, // Address + { row: 6, column: 41 }, // Gathering + { row: 6, column: 48 }, // Person + ], + }, + { + nodeType: "class_definition with generic superclasses (built in types)", + fileName: "python/classes.py", + language: "Python", + cursorPosition: { line: 10, character: 8 }, + definitionPositions: [ + { row: 9, column: 24 }, // Address + { row: 9, column: 33 }, // Person + ], + }, +]; + +export const PYTHON_TEST_CASES = [ + // ...FUNCTIONS, + ...CLASSES, +]; diff --git a/core/autocomplete/context/root-path-context/test/testCases/typescript.ts b/core/autocomplete/context/root-path-context/test/testCases/typescript.ts index f945a02a9..ddda2bfde 100644 --- a/core/autocomplete/context/root-path-context/test/testCases/typescript.ts +++ b/core/autocomplete/context/root-path-context/test/testCases/typescript.ts @@ -1,7 +1,7 @@ const FUNCTIONS = [ { nodeType: "function_declaration with a param and a return type", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 3, character: 9 }, definitionPositions: [ @@ -11,7 +11,7 @@ const FUNCTIONS = [ }, { nodeType: "function_declaration with array param", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 7, character: 9 }, definitionPositions: [ @@ -21,7 +21,7 @@ const FUNCTIONS = [ }, { nodeType: "function_declaration without return type", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 11, character: 9 }, definitionPositions: [ @@ -30,7 +30,7 @@ const FUNCTIONS = [ }, { nodeType: "function_declaration without params", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 15, character: 9 }, definitionPositions: [ @@ -39,7 +39,7 @@ const FUNCTIONS = [ }, { nodeType: "function_declaration with array params and array return type", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 19, character: 9 }, definitionPositions: [ @@ -50,7 +50,7 @@ const FUNCTIONS = [ { nodeType: "function_declaration with generic params and generic return type", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 23, character: 9 }, definitionPositions: [ @@ -63,7 +63,7 @@ const FUNCTIONS = [ { nodeType: "function_declaration with union type params and union return type", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 27, character: 9 }, definitionPositions: [ @@ -75,7 +75,7 @@ const FUNCTIONS = [ }, { nodeType: "function_declaration with two arguments", - fileName: "functions.ts", + fileName: "typescript/functions.ts", language: "TypeScript", cursorPosition: { line: 31, character: 9 }, definitionPositions: [ @@ -88,7 +88,7 @@ const FUNCTIONS = [ const GENERATORS = [ { nodeType: "function_declaration with a param and a return type", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 3, character: 9 }, definitionPositions: [ @@ -98,7 +98,7 @@ const GENERATORS = [ }, { nodeType: "function_declaration with array param", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 7, character: 9 }, definitionPositions: [ @@ -108,7 +108,7 @@ const GENERATORS = [ }, { nodeType: "function_declaration without return type", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 11, character: 9 }, definitionPositions: [ @@ -117,7 +117,7 @@ const GENERATORS = [ }, { nodeType: "function_declaration without params", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 15, character: 9 }, definitionPositions: [ @@ -126,7 +126,7 @@ const GENERATORS = [ }, { nodeType: "function_declaration with array params and array return type", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 19, character: 9 }, definitionPositions: [ @@ -137,7 +137,7 @@ const GENERATORS = [ { nodeType: "function_declaration with generic params and generic return type", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 23, character: 9 }, definitionPositions: [ @@ -150,7 +150,7 @@ const GENERATORS = [ { nodeType: "function_declaration with union type params and union return type", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 27, character: 9 }, definitionPositions: [ @@ -162,7 +162,7 @@ const GENERATORS = [ }, { nodeType: "function_declaration with two arguments", - fileName: "generators.ts", + fileName: "typescript/generators.ts", language: "TypeScript", cursorPosition: { line: 31, character: 9 }, definitionPositions: [ @@ -175,7 +175,7 @@ const GENERATORS = [ const ARROW_FUNCTIONS = [ { nodeType: "arrow_function with a param and a return type", - fileName: "arrowFunctions.ts", + fileName: "typescript/arrowFunctions.ts", language: "TypeScript", cursorPosition: { line: 3, character: 9 }, definitionPositions: [ @@ -185,7 +185,7 @@ const ARROW_FUNCTIONS = [ }, { nodeType: "arrow_function without return type", - fileName: "arrowFunctions.ts", + fileName: "typescript/arrowFunctions.ts", language: "TypeScript", cursorPosition: { line: 7, character: 9 }, definitionPositions: [ @@ -194,7 +194,7 @@ const ARROW_FUNCTIONS = [ }, { nodeType: "arrow_function without params", - fileName: "arrowFunctions.ts", + fileName: "typescript/arrowFunctions.ts", language: "TypeScript", cursorPosition: { line: 11, character: 9 }, definitionPositions: [ @@ -203,7 +203,7 @@ const ARROW_FUNCTIONS = [ }, { nodeType: "arrow_function with array params and array return type", - fileName: "arrowFunctions.ts", + fileName: "typescript/arrowFunctions.ts", language: "TypeScript", cursorPosition: { line: 15, character: 9 }, definitionPositions: [ @@ -213,7 +213,7 @@ const ARROW_FUNCTIONS = [ }, { nodeType: "arrow_function with generic params and generic return type", - fileName: "arrowFunctions.ts", + fileName: "typescript/arrowFunctions.ts", language: "TypeScript", cursorPosition: { line: 19, character: 9 }, definitionPositions: [ @@ -225,7 +225,7 @@ const ARROW_FUNCTIONS = [ }, { nodeType: "arrow_function with union type params and union return type", - fileName: "arrowFunctions.ts", + fileName: "typescript/arrowFunctions.ts", language: "TypeScript", cursorPosition: { line: 23, character: 9 }, definitionPositions: [ @@ -237,7 +237,7 @@ const ARROW_FUNCTIONS = [ }, { nodeType: "arrow_function with two arguments", - fileName: "arrowFunctions.ts", + fileName: "typescript/arrowFunctions.ts", language: "TypeScript", cursorPosition: { line: 27, character: 11 }, definitionPositions: [ @@ -250,7 +250,7 @@ const ARROW_FUNCTIONS = [ const CLASS_METHODS = [ { nodeType: "method_declaration with a param and a return type", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 4, character: 11 }, definitionPositions: [ @@ -260,7 +260,7 @@ const CLASS_METHODS = [ }, { nodeType: "method_declaration without arguments", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 8, character: 11 }, definitionPositions: [ @@ -269,7 +269,7 @@ const CLASS_METHODS = [ }, { nodeType: "method_declaration without return type", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 12, character: 11 }, definitionPositions: [ @@ -278,7 +278,7 @@ const CLASS_METHODS = [ }, { nodeType: "method_declaration with array type arguments", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 16, character: 11 }, definitionPositions: [ @@ -288,7 +288,7 @@ const CLASS_METHODS = [ { nodeType: "method_declaration with array type arguments and array type return", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 20, character: 11 }, definitionPositions: [ @@ -299,7 +299,7 @@ const CLASS_METHODS = [ { nodeType: "method_declaration with with generic params and generic return type", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 24, character: 11 }, definitionPositions: [ @@ -311,7 +311,7 @@ const CLASS_METHODS = [ }, { nodeType: "method_declaration with union type params and union return type", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 28, character: 11 }, definitionPositions: [ @@ -323,7 +323,7 @@ const CLASS_METHODS = [ }, { nodeType: "method_declaration with two arguments", - fileName: "classMethods.ts", + fileName: "typescript/classMethods.ts", language: "TypeScript", cursorPosition: { line: 32, character: 11 }, definitionPositions: [ @@ -336,7 +336,7 @@ const CLASS_METHODS = [ const CLASS_DEFINITIONS = [ { nodeType: "class_declaration with base class", - fileName: "classes.ts", + fileName: "typescript/classes.ts", language: "TypeScript", cursorPosition: { line: 2, character: 31 }, definitionPositions: [ @@ -345,7 +345,7 @@ const CLASS_DEFINITIONS = [ }, { nodeType: "class_declaration with interface", - fileName: "classes.ts", + fileName: "typescript/classes.ts", language: "TypeScript", cursorPosition: { line: 4, character: 39 }, definitionPositions: [ @@ -354,7 +354,7 @@ const CLASS_DEFINITIONS = [ }, { nodeType: "class_declaration with base class and multiple interfaces", - fileName: "classes.ts", + fileName: "typescript/classes.ts", language: "TypeScript", cursorPosition: { line: 6, character: 74 }, definitionPositions: [ @@ -365,7 +365,7 @@ const CLASS_DEFINITIONS = [ }, { nodeType: "class_declaration with base class and multiple interfaces", - fileName: "classes.ts", + fileName: "typescript/classes.ts", language: "TypeScript", cursorPosition: { line: 6, character: 74 }, definitionPositions: [ @@ -376,7 +376,7 @@ const CLASS_DEFINITIONS = [ }, { nodeType: "class_declaration with generic base class and generic interface", - fileName: "classes.ts", + fileName: "typescript/classes.ts", language: "TypeScript", cursorPosition: { line: 8, character: 69 }, definitionPositions: [ diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/python/class_definition.scm b/extensions/vscode/tree-sitter/root-path-context-queries/python/class_definition.scm index 5a9e34b86..61fdb29ec 100644 --- a/extensions/vscode/tree-sitter/root-path-context-queries/python/class_definition.scm +++ b/extensions/vscode/tree-sitter/root-path-context-queries/python/class_definition.scm @@ -1,5 +1,24 @@ -( - (class_definition - superclasses: (argument_list - (identifier) @superclass)) +; Match superclass identifiers in a simple inheritance +(class_definition + superclasses: (argument_list + (identifier) @catch) + (#not-match? @catch "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") +) + +; Match the value of a keyword argument in class inheritance +(class_definition + superclasses: (argument_list + (keyword_argument + (_) + (identifier) @catch)) + (#not-match? @catch "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") +) + +; Match identifiers within subscripts in class inheritance +(class_definition + superclasses: (argument_list + (subscript + (identifier) @catch + )) + (#not-match? @catch "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") ) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/python/function_definition.scm b/extensions/vscode/tree-sitter/root-path-context-queries/python/function_definition.scm index 864666a4a..535882bfa 100644 --- a/extensions/vscode/tree-sitter/root-path-context-queries/python/function_definition.scm +++ b/extensions/vscode/tree-sitter/root-path-context-queries/python/function_definition.scm @@ -1,17 +1,60 @@ -( - (function_definition - (parameters - (_ - (type) @a - (#not-match? @a "^(str|int|float|bool|list|dict|tuple)$") - ) - ) - ) +; When the type is a simple identifier: +(function_definition + parameters: (parameters + (typed_parameter + type: (type + (identifier) @type_identifier))) + + (#not-match? @type_identifier "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") ) -( - (function_definition - (type) @b - (#not-match? @b "^(str|int|float|bool|list|dict|tuple)$") - ) +; When the type is a generic type with one identifier +(function_definition + parameters: (parameters + (typed_parameter + type: (type + (generic_type + (identifier) @type_identifier)))) + + (#not-match? @type_identifier "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") +) + +; When the generic type has type parameters with one identifier +(function_definition + parameters: (parameters + (typed_parameter + type: (type + (generic_type + (identifier) + (type_parameter + (type + (identifier) @type_identifier)))))) + + (#not-match? @type_identifier "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") +) + +; When the return type is a simple identifier +(function_definition + return_type: (type + (identifier) @type_identifier) + (#not-match? @type_identifier "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") +) + +; When the return type is a generic type with one identifier +(function_definition + return_type: (type + (generic_type + (identifier) @type_identifier)) + (#not-match? @type_identifier "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") +) + +; When the generic type has type parameters with one identifier +(function_definition + return_type: (type + (generic_type + (identifier) + (type_parameter + (type + (identifier) @type_identifier)))) + (#not-match? @type_identifier "^(str|int|float|bool|list|dict|tuple|set|frozenset|complex|bytes|bytearray|memoryview|range|slice|object|type|NoneType|List|Dict|Tuple|Set|FrozenSet|Union|Optional|Any|Callable|Iterable|Iterator|Generator|Coroutine|AsyncIterable|AsyncIterator|Awaitable|ContextManager|Pattern|Match|TypeVar|Generic|Sequence|Mapping|MutableMapping|MutableSequence|ByteString|Reversible|Sized|Container|Collection|AbstractSet|MutableSet|KeysView|ItemsView|ValuesView|Hashable|Sized|SupportsInt|SupportsFloat|SupportsComplex|SupportsBytes|SupportsAbs|SupportsRound|ChainMap|Counter|OrderedDict|defaultdict|deque|namedtuple|TypedDict)$") ) \ No newline at end of file From 5a5903f178283fdcd2de4f41349c7e56909f80b9 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Sun, 17 Nov 2024 18:24:12 -0800 Subject: [PATCH 23/28] refactor: cleanup --- .../context/root-path-context/RootPathContextService.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index 8571acd0a..5e37f9143 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -82,9 +82,9 @@ export class RootPathContextService { this.importDefinitionsService.get(filepath); break; default: - const type = node.type; - console.log(getSyntaxTreeString(node)); - debugger; + // const type = node.type; + // console.log(getSyntaxTreeString(node)); + // debugger; query = await getQueryForFile( filepath, From 3a64c61207dfcccd88440ac6e90f7c2c0318247f Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Sun, 17 Nov 2024 18:24:44 -0800 Subject: [PATCH 24/28] refactor: cleanup --- .../context/root-path-context/RootPathContextService.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index 5e37f9143..0147df151 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -176,7 +176,6 @@ export class RootPathContextService { parentKey = key; } - debugger; return snippets; } } From aaebd85c323cc31e8372f2f935412d11bffae01c Mon Sep 17 00:00:00 2001 From: markMe1024 Date: Mon, 18 Nov 2024 10:56:20 +0800 Subject: [PATCH 25/28] fix issue: every accepted attribute in the file ~/.continue/dev_data/autocomplete.jsonl is true --- core/autocomplete/util/AutocompleteLoggingService.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/autocomplete/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts index ff0c5d493..96261e646 100644 --- a/core/autocomplete/util/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -37,6 +37,7 @@ export class AutocompleteLoggingService { if (this._outcomes.has(completionId)) { const outcome = this._outcomes.get(completionId)!; + outcome.accepted = true; this.logAutocompleteOutcome(outcome); this._outcomes.delete(completionId); return outcome; @@ -94,7 +95,6 @@ export class AutocompleteLoggingService { } private logAutocompleteOutcome(outcome: AutocompleteOutcome) { - outcome.accepted = true; logDevData("autocomplete", outcome); const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; void Telemetry.capture( From 7ffb95e9d0fc964b55b3f92149515fa79fc3aa0d Mon Sep 17 00:00:00 2001 From: burlinchen Date: Mon, 18 Nov 2024 19:05:07 +0800 Subject: [PATCH 26/28] 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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 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 89a90f99baaf493f184a09aa6083a606076f9771 Mon Sep 17 00:00:00 2001 From: burlinchen Date: Mon, 18 Nov 2024 19:12:39 +0800 Subject: [PATCH 27/28] 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 28/28] 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"', }, {