From b6b39dbf0abfca128cb0a7199a153cb78c710c77 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 9 Oct 2024 14:22:17 -0700 Subject: [PATCH] update diff accept/reject logi --- .../editor/DiffStreamHandler.kt | 149 ++- .../editor/DiffStreamService.kt | 6 +- .../editor/EditorComponentInlaysManager.kt | 2 - .../editor/VerticalDiffActionButtons.kt | 95 ++ .../vscode/src/diff/vertical/handler.ts | 7 +- gui/src/components/mainInput/InputToolbar.tsx | 2 +- gui/src/pages/gui.tsx | 940 +++++++++--------- 7 files changed, 707 insertions(+), 494 deletions(-) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffActionButtons.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index f26a80f5f..15ff0689d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -26,6 +26,13 @@ enum class DiffLineType { SAME, NEW, OLD } +data class VerticalDiffBlock( + val start: Int, + val numRed: Int, + val numGreen: Int, + val buttons: VerticalDiffActionButtons +) + class DiffStreamHandler( private val project: Project, private val editor: Editor, @@ -70,11 +77,13 @@ class DiffStreamHandler( private var currentLineHighlighter: RangeHighlighter? = null private val unfinishedHighlighters: MutableList = mutableListOf() private var changeCount: Int = 0 // Kept track of so we can count steps to undo when cancelling + private var insertedInCurrentBlock: Int = 0; private var running: Boolean = false - private var deletionBufferStartLine: Int = -1 private val deletionsBuffer: MutableList = mutableListOf() private val deletionInlays: MutableList = mutableListOf() + private val verticalDiffBlocks: MutableList = mutableListOf() + private fun removeDeletionInlays() { deletionInlays.forEach { @@ -102,8 +111,45 @@ class DiffStreamHandler( } private fun insertDeletionBuffer() { + if (deletionsBuffer.isNotEmpty() || insertedInCurrentBlock > 0) { + val start = currentLine - insertedInCurrentBlock + val numGreen = insertedInCurrentBlock + val numRed = deletionsBuffer.size + val buttons = VerticalDiffActionButtons( + editor, + start, + onClickAccept = { + acceptRejectBlock(true, start, numGreen, numRed) + }, + onClickReject = { + acceptRejectBlock(false, start, numGreen, numRed) + } + ) + + verticalDiffBlocks.add( + VerticalDiffBlock( + start = start, + numRed = deletionsBuffer.size, + numGreen = insertedInCurrentBlock, + buttons = buttons + ) + ) + + editor.contentComponent.add(buttons.acceptButton) + editor.contentComponent.add(buttons.rejectButton) + editor.contentComponent.revalidate() + editor.contentComponent.repaint() + } + + if (deletionsBuffer.isEmpty()) { + insertedInCurrentBlock = 0; + return; + } + + // TODO: Handle decoration updates according to insertedInCurrentBlock + // Insert red highlighted code between the real lines in the editor - if (deletionBufferStartLine != -1 && deletionsBuffer.isNotEmpty()) { + if (deletionBufferStartLine != -1) { val component = JTextArea().apply { text = deletionsBuffer.joinToString("\n") isEditable = false @@ -125,6 +171,8 @@ class DiffStreamHandler( deletionsBuffer.clear() deletionBufferStartLine = -1 } + + insertedInCurrentBlock = 0; } private fun handleDiffLine(type: DiffLineType, line: String) { @@ -137,28 +185,25 @@ class DiffStreamHandler( } DiffLineType.NEW -> { - // Insert new line if (currentLine == editor.document.lineCount) { editor.document.insertString(editor.document.textLength, "\n") } + val offset = editor.document.getLineStartOffset(currentLine) editor.document.insertString(offset, line + "\n") - - // Highlight the new line green editor.markupModel.addLineHighlighter(greenKey, currentLine, HighlighterLayer.LAST) insertDeletionBuffer() currentLine++ changeCount++ + insertedInCurrentBlock++; } DiffLineType.OLD -> { - // Remove old line deleteLineAt(currentLine) - - // Add to deletions buffer deletionsBuffer.add(line) + if (deletionBufferStartLine == -1) { deletionBufferStartLine = currentLine } @@ -171,6 +216,7 @@ class DiffStreamHandler( if (currentLineHighlighter != null) { editor.markupModel.removeHighlighter(currentLineHighlighter!!) } + currentLineHighlighter = editor.markupModel.addLineHighlighter( currentLineKey, min(currentLine, editor.document.lineCount - 1), @@ -188,6 +234,64 @@ class DiffStreamHandler( } } + private fun acceptRejectBlock( + accept: Boolean, + startLine: Int, + numGreen: Int, + numRed: Int + ) { + // TODO: We use virtual lines for red so we should shouldnt be doing numRed addition + if (numGreen > 0) { + val highlightersToRemove = editor.markupModel.allHighlighters.filter { highlighter -> + val highlighterLine = editor.document.getLineNumber(highlighter.startOffset) + highlighterLine in startLine until (startLine + numRed) + } + + if (highlightersToRemove.isNotEmpty()) { + editor.markupModel.removeHighlighter(highlightersToRemove.first()) + } + + if (!accept) { + // Delete the actual lines + WriteCommandAction.runWriteCommandAction(project) { + for (i in 0 until numGreen) { + deleteLineAt(startLine + numRed) + } + } + } + } + + if (numRed > 0 && accept) { + // Delete the actual lines + WriteCommandAction.runWriteCommandAction(project) { + for (i in 0 until numRed) { + deleteLineAt(startLine) + } + } + } + + // Shift everything below upward + val offset = -(if (accept) numRed else numGreen) + + // Update the positions of the vertical diff blocks + verticalDiffBlocks.forEach { block -> + if (block.start > startLine) { + block.buttons.updatePosition(block.start + offset) + } + } + + // Remove the processed block + verticalDiffBlocks.removeAll { it.start == startLine } + + if (verticalDiffBlocks.isEmpty()) { + onClose() + } + + // Refresh the editor + editor.contentComponent.revalidate() + editor.contentComponent.repaint() + } + private fun resetState() { // Remove all highlighters editor.markupModel.removeAllHighlighters() @@ -212,29 +316,36 @@ class DiffStreamHandler( } } - fun accept() { + private fun removeDiffBlock(block: VerticalDiffBlock) { + editor.contentComponent.remove(block.buttons.acceptButton) + editor.contentComponent.remove(block.buttons.rejectButton) + + verticalDiffBlocks.remove(block) + + editor.contentComponent.revalidate() + editor.contentComponent.repaint() + } + + private fun removeAllDiffBlocks() { + verticalDiffBlocks.forEach(::removeDiffBlock) + } + + fun acceptAll() { // Accept the changes editor.markupModel.removeAllHighlighters() removeDeletionInlays() onClose() running = false + removeAllDiffBlocks() } - fun reject() { + fun rejectAll() { // Reject the changes resetState() removeDeletionInlays() onClose() running = false - } - - fun toggleFocus() { - if (textArea.hasFocus()) { - textArea.transferFocus() - editor.contentComponent.requestFocus() - } else { - textArea.requestFocus() - } + removeAllDiffBlocks() } fun run(input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamService.kt index 48aba76b8..222e6a71c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamService.kt @@ -9,19 +9,19 @@ class DiffStreamService { fun register(handler: DiffStreamHandler, editor: Editor) { if (handlers.containsKey(editor)) { - handlers[editor]?.reject() + handlers[editor]?.rejectAll() } handlers[editor] = handler println("Registered handler for editor") } fun reject(editor: Editor) { - handlers[editor]?.reject() + handlers[editor]?.rejectAll() handlers.remove(editor) } fun accept(editor: Editor) { - handlers[editor]?.accept() + handlers[editor]?.acceptAll() handlers.remove(editor) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorComponentInlaysManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorComponentInlaysManager.kt index 20d31a519..e8f24f972 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorComponentInlaysManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorComponentInlaysManager.kt @@ -14,10 +14,8 @@ import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.JBUI import java.awt.Dimension import java.awt.Font -import java.awt.Insets import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent -import javax.swing.BorderFactory import javax.swing.JComponent import javax.swing.ScrollPaneConstants import kotlin.math.ceil diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffActionButtons.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffActionButtons.kt new file mode 100644 index 000000000..101799549 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffActionButtons.kt @@ -0,0 +1,95 @@ +package com.github.continuedev.continueintellijextension.editor + +import com.github.continuedev.continueintellijextension.utils.getAltKeyLabel +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.LogicalPosition +import com.intellij.ui.JBColor +import java.awt.* +import javax.swing.JButton + +class VerticalDiffActionButtons( + private val editor: Editor, + private var lineNumber: Int, + private val onClickAccept: () -> Unit, + private val onClickReject: () -> Unit +) { + val acceptButton: JButton + val rejectButton: JButton + + private fun removeButtons() { + editor.contentComponent.remove(acceptButton) + editor.contentComponent.remove(rejectButton) + } + + init { + acceptButton = createButton("${getAltKeyLabel()}⇧Y", JBColor(0x9900FF00.toInt(), 0x9900FF00.toInt())) + rejectButton = createButton("${getAltKeyLabel()}⇧N", JBColor(0x99FF0000.toInt(), 0x99FF0000.toInt())) + + acceptButton.addActionListener { + removeButtons() + onClickAccept() + } + + rejectButton.addActionListener { + removeButtons() + onClickReject() + } + + // Position the buttons + val visibleArea = editor.scrollingModel.visibleArea + val lineStartPosition = editor.logicalPositionToXY(LogicalPosition(lineNumber, 0)) + val xPosition = + visibleArea.x + visibleArea.width - acceptButton.preferredSize.width - rejectButton.preferredSize.width - 20 + val yPosition = lineStartPosition.y + + acceptButton.setBounds( + xPosition, + yPosition, + acceptButton.preferredSize.width, + acceptButton.preferredSize.height + ) + rejectButton.setBounds( + xPosition + acceptButton.preferredSize.width + 5, + yPosition, + rejectButton.preferredSize.width, + rejectButton.preferredSize.height + ) + } + + private fun createButton(text: String, backgroundColor: JBColor): JButton { + return object : JButton(text) { + override fun paintComponent(g: Graphics) { + val g2 = g.create() as Graphics2D + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + g2.color = backgroundColor + g2.fillRoundRect(0, 0, width - 1, height - 1, 8, 8) + super.paintComponent(g2) + g2.dispose() + } + }.apply { + // This isn't working currently, font color is transparent + foreground = JBColor.WHITE + font = Font("Arial", Font.BOLD, 9) + isContentAreaFilled = false + isOpaque = false + border = null + preferredSize = Dimension(preferredSize.width, 16) + cursor = Cursor(Cursor.HAND_CURSOR) + } + } + + fun updatePosition(newLineNumber: Int) { + this.lineNumber = newLineNumber + val visibleArea = editor.scrollingModel.visibleArea + val lineStartPosition = editor.logicalPositionToXY(LogicalPosition(lineNumber, 0)) + val xPosition = + visibleArea.x + visibleArea.width - acceptButton.width - rejectButton.width - 40 + val yPosition = lineStartPosition.y + + acceptButton.location = Point(xPosition, yPosition) + rejectButton.location = Point(xPosition + acceptButton.width + 5, yPosition) + + // Refresh the editor to reflect the changes + editor.component.repaint() + } +} diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index a1efbd1df..37cb1badf 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -90,6 +90,7 @@ export class VerticalDiffHandler implements vscode.Disposable { private async insertDeletionBuffer() { // Don't remove trailing whitespace line const totalDeletedContent = this.deletionBuffer.join("\n"); + if ( totalDeletedContent === "" && this.currentLineIndex >= this.endLine + this.newLinesAdded && @@ -100,11 +101,13 @@ export class VerticalDiffHandler implements vscode.Disposable { if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) { const blocks = this.editorToVerticalDiffCodeLens.get(this.filepath) || []; + blocks.push({ start: this.currentLineIndex - this.insertedInCurrentBlock, numRed: this.deletionBuffer.length, numGreen: this.insertedInCurrentBlock, }); + this.editorToVerticalDiffCodeLens.set(this.filepath, blocks); } @@ -118,10 +121,12 @@ export class VerticalDiffHandler implements vscode.Disposable { this.currentLineIndex - this.insertedInCurrentBlock, totalDeletedContent, ); + this.redDecorationManager.addLines( this.currentLineIndex - this.insertedInCurrentBlock, this.deletionBuffer.length, ); + // Shift green decorations downward this.greenDecorationManager.shiftDownAfterLine( this.currentLineIndex - this.insertedInCurrentBlock, @@ -132,9 +137,9 @@ export class VerticalDiffHandler implements vscode.Disposable { for (let i = 0; i < this.deletionBuffer.length; i++) { this.incrementCurrentLineIndex(); } + this.deletionBuffer = []; this.insertedInCurrentBlock = 0; - this.refreshCodeLens(); } diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index da255e86d..544ccfa23 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -152,7 +152,7 @@ function InputToolbar(props: InputToolbarProps) { } > - @codebase + {getMetaKeyLabel()}⏎ @codebase Submit with the codebase as context ({getMetaKeyLabel()}⏎) diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx index 156c0b3b2..02c7d2ec4 100644 --- a/gui/src/pages/gui.tsx +++ b/gui/src/pages/gui.tsx @@ -1,532 +1,536 @@ import { - ArrowLeftIcon, - ChatBubbleOvalLeftIcon, - CodeBracketSquareIcon, - ExclamationTriangleIcon, + ArrowLeftIcon, + ChatBubbleOvalLeftIcon, + CodeBracketSquareIcon, + ExclamationTriangleIcon, } from "@heroicons/react/24/outline"; -import { JSONContent } from "@tiptap/react"; -import { InputModifiers } from "core"; -import { usePostHog } from "posthog-js/react"; +import {JSONContent} from "@tiptap/react"; +import {InputModifiers} from "core"; +import {usePostHog} from "posthog-js/react"; import { - Fragment, - useCallback, - useContext, - useEffect, - useRef, - useState, + Fragment, + useCallback, + useContext, + useEffect, + useRef, + useState, } from "react"; -import { ErrorBoundary } from "react-error-boundary"; -import { useDispatch, useSelector } from "react-redux"; +import {ErrorBoundary} from "react-error-boundary"; +import {useDispatch, useSelector} from "react-redux"; import styled from "styled-components"; import { - Button, - defaultBorderRadius, - lightGray, - vscBackground, - vscForeground, + Button, + defaultBorderRadius, + lightGray, + vscBackground, + vscForeground, } from "../components"; -import { ChatScrollAnchor } from "../components/ChatScrollAnchor"; +import {ChatScrollAnchor} from "../components/ChatScrollAnchor"; import StepContainer from "../components/gui/StepContainer"; import TimelineItem from "../components/gui/TimelineItem"; import ContinueInputBox from "../components/mainInput/ContinueInputBox"; -import { defaultInputModifiers } from "../components/mainInput/inputModifiers"; -import { TutorialCard } from "../components/mainInput/TutorialCard"; +import {defaultInputModifiers} from "../components/mainInput/inputModifiers"; +import {TutorialCard} from "../components/mainInput/TutorialCard"; import { - OnboardingCard, - useOnboardingCard, + OnboardingCard, + useOnboardingCard, } from "../components/OnboardingCard"; -import { IdeMessengerContext } from "../context/IdeMessenger"; +import {IdeMessengerContext} from "../context/IdeMessenger"; import useChatHandler from "../hooks/useChatHandler"; import useHistory from "../hooks/useHistory"; -import { useTutorialCard } from "../hooks/useTutorialCard"; -import { useWebviewListener } from "../hooks/useWebviewListener"; -import { defaultModelSelector } from "../redux/selectors/modelSelectors"; +import {useTutorialCard} from "../hooks/useTutorialCard"; +import {useWebviewListener} from "../hooks/useWebviewListener"; +import {defaultModelSelector} from "../redux/selectors/modelSelectors"; import { - clearLastResponse, - deleteMessage, - newSession, - setInactive, + clearLastResponse, + deleteMessage, + newSession, + setInactive, } from "../redux/slices/stateSlice"; import { - setDialogEntryOn, - setDialogMessage, - setShowDialog, + setDialogEntryOn, + setDialogMessage, + setShowDialog, } from "../redux/slices/uiStateSlice"; -import { RootState } from "../redux/store"; +import {RootState} from "../redux/store"; import { - getFontSize, - getMetaKeyLabel, - isJetBrains, - isMetaEquivalentKeyPressed, + getFontSize, + getMetaKeyLabel, + isJetBrains, + isMetaEquivalentKeyPressed, } from "../util"; -import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial"; -import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +import {FREE_TRIAL_LIMIT_REQUESTS} from "../util/freeTrial"; +import {getLocalStorage, setLocalStorage} from "../util/localStorage"; const TopGuiDiv = styled.div<{ - showScrollbar?: boolean; + showScrollbar?: boolean; }>` - overflow-y: auto; - height: 100%; - scrollbar-width: ${(props) => (props.showScrollbar ? "thin" : "none")}; + overflow-y: auto; + height: 100%; + scrollbar-width: ${(props) => (props.showScrollbar ? "thin" : "none")}; - &::-webkit-scrollbar { - display: ${(props) => (props.showScrollbar ? "block" : "none")}; - } + &::-webkit-scrollbar { + display: ${(props) => (props.showScrollbar ? "block" : "none")}; + } `; const StopButton = styled.div` - width: fit-content; - margin-right: auto; - margin-left: auto; - font-size: ${getFontSize() - 2}px; - border: 0.5px solid ${lightGray}; - border-radius: ${defaultBorderRadius}; - padding: 4px 8px; - color: ${lightGray}; - cursor: pointer; - box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08); - transition: box-shadow 0.3s ease; + width: fit-content; + margin-right: auto; + margin-left: auto; + font-size: ${getFontSize() - 2}px; + border: 0.5px solid ${lightGray}; + border-radius: ${defaultBorderRadius}; + padding: 4px 8px; + color: ${lightGray}; + cursor: pointer; + box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08); + transition: box-shadow 0.3s ease; - &:hover { - box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15), 0 3px 6px rgba(0, 0, 0, 0.1); - } + &:hover { + box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15), 0 3px 6px rgba(0, 0, 0, 0.1); + } `; const StepsDiv = styled.div` - position: relative; - background-color: transparent; - - & > * { position: relative; - } + background-color: transparent; - .thread-message { - margin: 8px 4px 0 4px; - } + & > * { + position: relative; + } + + .thread-message { + margin: 8px 4px 0 4px; + } `; const NewSessionButton = styled.div` - width: fit-content; - margin-right: auto; - margin-left: 6px; - margin-top: 2px; - margin-bottom: 8px; - font-size: ${getFontSize() - 2}px; + width: fit-content; + margin-right: auto; + margin-left: 6px; + margin-top: 2px; + margin-bottom: 8px; + font-size: ${getFontSize() - 2}px; - border-radius: ${defaultBorderRadius}; - padding: 2px 6px; - color: ${lightGray}; + border-radius: ${defaultBorderRadius}; + padding: 2px 6px; + color: ${lightGray}; - &:hover { - background-color: ${lightGray}33; - color: ${vscForeground}; - } + &:hover { + background-color: ${lightGray}33; + color: ${vscForeground}; + } - cursor: pointer; + cursor: pointer; `; -function fallbackRender({ error, resetErrorBoundary }: any) { - // Call resetErrorBoundary() to reset the error boundary and retry the render. +function fallbackRender({error, resetErrorBoundary}: any) { + // Call resetErrorBoundary() to reset the error boundary and retry the render. - return ( -
-

Something went wrong:

-
{error.message}
-
- -
-
- ); + return ( +
+

Something went wrong:

+
{error.message}
+ +
+ +
+
+ ); } function GUI() { - const posthog = usePostHog(); - const dispatch = useDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - const { streamResponse } = useChatHandler(dispatch, ideMessenger); - const onboardingCard = useOnboardingCard(); - const { showTutorialCard, closeTutorialCard } = useTutorialCard(); - const sessionState = useSelector((state: RootState) => state.state); - const defaultModel = useSelector(defaultModelSelector); - const ttsActive = useSelector((state: RootState) => state.state.ttsActive); - const active = useSelector((state: RootState) => state.state.active); - const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); - const mainTextInputRef = useRef(null); - const topGuiDivRef = useRef(null); - const [isAtBottom, setIsAtBottom] = useState(false); - const state = useSelector((state: RootState) => state.state); - const { saveSession, getLastSessionId, loadLastSession } = - useHistory(dispatch); + const posthog = usePostHog(); + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + const {streamResponse} = useChatHandler(dispatch, ideMessenger); + const onboardingCard = useOnboardingCard(); + const {showTutorialCard, closeTutorialCard} = useTutorialCard(); + const sessionState = useSelector((state: RootState) => state.state); + const defaultModel = useSelector(defaultModelSelector); + const ttsActive = useSelector((state: RootState) => state.state.ttsActive); + const active = useSelector((state: RootState) => state.state.active); + const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); + const mainTextInputRef = useRef(null); + const topGuiDivRef = useRef(null); + const [isAtBottom, setIsAtBottom] = useState(false); + const state = useSelector((state: RootState) => state.state); + const {saveSession, getLastSessionId, loadLastSession} = + useHistory(dispatch); - useEffect(() => { - if (!active || !topGuiDivRef.current) return; + useEffect(() => { + if (!active || !topGuiDivRef.current) return; - const scrollAreaElement = topGuiDivRef.current; + const scrollAreaElement = topGuiDivRef.current; - scrollAreaElement.scrollTop = - scrollAreaElement.scrollHeight - scrollAreaElement.clientHeight; + scrollAreaElement.scrollTop = + scrollAreaElement.scrollHeight - scrollAreaElement.clientHeight; - setIsAtBottom(true); - }, [active]); + setIsAtBottom(true); + }, [active]); - useEffect(() => { - // Cmd + Backspace to delete current step - const listener = (e: any) => { - if ( - e.key === "Backspace" && - isMetaEquivalentKeyPressed(e) && - !e.shiftKey - ) { - dispatch(setInactive()); - } + useEffect(() => { + // Cmd + Backspace to delete current step + const listener = (e: any) => { + if ( + e.key === "Backspace" && + isMetaEquivalentKeyPressed(e) && + !e.shiftKey + ) { + dispatch(setInactive()); + } + }; + window.addEventListener("keydown", listener); + + return () => { + window.removeEventListener("keydown", listener); + }; + }, [active]); + + const handleScroll = () => { + // Temporary fix to account for additional height when code blocks are added + const OFFSET_HERUISTIC = 300; + if (!topGuiDivRef.current) return; + + const {scrollTop, scrollHeight, clientHeight} = topGuiDivRef.current; + const atBottom = + scrollHeight - clientHeight <= scrollTop + OFFSET_HERUISTIC; + + setIsAtBottom(atBottom); }; - window.addEventListener("keydown", listener); - return () => { - window.removeEventListener("keydown", listener); - }; - }, [active]); + const sendInput = useCallback( + (editorState: JSONContent, modifiers: InputModifiers) => { + if (defaultModel?.provider === "free-trial") { + const u = getLocalStorage("ftc"); + if (u) { + setLocalStorage("ftc", u + 1); - const handleScroll = () => { - // Temporary fix to account for additional height when code blocks are added - const OFFSET_HERUISTIC = 300; - if (!topGuiDivRef.current) return; - - const { scrollTop, scrollHeight, clientHeight } = topGuiDivRef.current; - const atBottom = - scrollHeight - clientHeight <= scrollTop + OFFSET_HERUISTIC; - - setIsAtBottom(atBottom); - }; - - const sendInput = useCallback( - (editorState: JSONContent, modifiers: InputModifiers) => { - if (defaultModel?.provider === "free-trial") { - const u = getLocalStorage("ftc"); - if (u) { - setLocalStorage("ftc", u + 1); - - if (u >= FREE_TRIAL_LIMIT_REQUESTS) { - onboardingCard.open("Best"); - posthog?.capture("ftc_reached"); - ideMessenger.ide.showToast( - "info", - "You've reached the free trial limit. Please configure a model to continue.", - ); - return; - } - } else { - setLocalStorage("ftc", 1); - } - } - - streamResponse(editorState, modifiers, ideMessenger); - - // Increment localstorage counter for popup - const currentCount = getLocalStorage("mainTextEntryCounter"); - if (currentCount) { - setLocalStorage("mainTextEntryCounter", currentCount + 1); - if (currentCount === 300) { - dispatch( - setDialogMessage( -
- 👋 Thanks for using Continue. We are always trying to improve - and love hearing from users. If you're interested in speaking, - enter your name and email. We won't use this information for - anything other than reaching out. -
-
-
{ - e.preventDefault(); - posthog?.capture("user_interest_form", { - name: e.target.elements[0].value, - email: e.target.elements[1].value, - }); - dispatch( - setDialogMessage( -
- Thanks! We'll be in touch soon. -
, - ), - ); - }} - style={{ - display: "flex", - flexDirection: "column", - gap: "10px", - }} - > - - - -
-
, - ), - ); - dispatch(setDialogEntryOn(false)); - dispatch(setShowDialog(true)); - } - } else { - setLocalStorage("mainTextEntryCounter", 1); - } - }, - [ - sessionState.history, - sessionState.contextItems, - defaultModel, - state, - streamResponse, - ], - ); - - useWebviewListener( - "newSession", - async () => { - saveSession(); - mainTextInputRef.current?.focus?.(); - }, - [saveSession], - ); - - const isLastUserInput = useCallback( - (index: number): boolean => { - return !state.history - .slice(index + 1) - .some((entry) => entry.message.role === "user"); - }, - [state.history], - ); - - return ( - <> - -
- - {state.history.map((item, index: number) => ( - - { - dispatch(newSession()); - }} - > - {item.message.role === "user" ? ( - { - streamResponse( - editorState, - modifiers, - ideMessenger, - index, + if (u >= FREE_TRIAL_LIMIT_REQUESTS) { + onboardingCard.open("Best"); + posthog?.capture("ftc_reached"); + ideMessenger.ide.showToast( + "info", + "You've reached the free trial limit. Please configure a model to continue.", ); - }} - isLastUserInput={isLastUserInput(index)} - isMainInput={false} - editorState={item.editorState} - contextItems={item.contextItems} + return; + } + } else { + setLocalStorage("ftc", 1); + } + } + + streamResponse(editorState, modifiers, ideMessenger); + + // Increment localstorage counter for popup + const currentCount = getLocalStorage("mainTextEntryCounter"); + if (currentCount) { + setLocalStorage("mainTextEntryCounter", currentCount + 1); + if (currentCount === 300) { + dispatch( + setDialogMessage( +
+ 👋 Thanks for using Continue. We are always trying to improve + and love hearing from users. If you're interested in speaking, + enter your name and email. We won't use this information for + anything other than reaching out. +
+
+
{ + e.preventDefault(); + posthog?.capture("user_interest_form", { + name: e.target.elements[0].value, + email: e.target.elements[1].value, + }); + dispatch( + setDialogMessage( +
+ Thanks! We'll be in touch soon. +
, + ), + ); + }} + style={{ + display: "flex", + flexDirection: "column", + gap: "10px", + }} + > + + + +
+
, + ), + ); + dispatch(setDialogEntryOn(false)); + dispatch(setShowDialog(true)); + } + } else { + setLocalStorage("mainTextEntryCounter", 1); + } + }, + [ + sessionState.history, + sessionState.contextItems, + defaultModel, + state, + streamResponse, + ], + ); + + useWebviewListener( + "newSession", + async () => { + saveSession(); + mainTextInputRef.current?.focus?.(); + }, + [saveSession], + ); + + const isLastUserInput = useCallback( + (index: number): boolean => { + return !state.history + .slice(index + 1) + .some((entry) => entry.message.role === "user"); + }, + [state.history], + ); + + return ( + <> + +
+ + {state.history.map((item, index: number) => ( + + { + dispatch(newSession()); + }} + > + {item.message.role === "user" ? ( + { + streamResponse( + editorState, + modifiers, + ideMessenger, + index, + ); + }} + isLastUserInput={isLastUserInput(index)} + isMainInput={false} + editorState={item.editorState} + contextItems={item.contextItems} + /> + ) : ( +
+ + ) : false ? ( + + ) : ( + + ) + } + open={ + typeof stepsOpen[index] === "undefined" + ? false + ? false + : true + : stepsOpen[index]! + } + onToggle={() => { + }} + > + { + }} + item={item} + onReverse={() => { + }} + onRetry={() => { + streamResponse( + state.history[index - 1].editorState, + state.history[index - 1].modifiers ?? + defaultInputModifiers, + ideMessenger, + index - 1, + ); + }} + onContinueGeneration={() => { + window.postMessage( + { + messageType: "userInput", + data: { + input: + "Continue your response exactly where you left off:", + }, + }, + "*", + ); + }} + onDelete={() => { + dispatch(deleteMessage(index)); + }} + modelTitle={item.promptLogs?.[0]?.modelTitle ?? ""} + /> + +
+ )} +
+
+ ))} +
+ +
- ) : null} - - {onboardingCard.show && ( -
- -
- )} - - {showTutorialCard !== false && !onboardingCard.open && ( -
- -
- )} - - )} -
- - -
- - {ttsActive && ( - { - ideMessenger.post("tts/kill", undefined); - }} - > - ■ Stop TTS - - )} - {active && ( - { - dispatch(setInactive()); - if ( - state.history[state.history.length - 1]?.message.content - .length === 0 - ) { - dispatch(clearLastResponse()); - } - }} - > - {getMetaKeyLabel()} ⌫ Cancel - - )} - - ); + > + ■ Stop TTS + + )} + {active && ( + { + dispatch(setInactive()); + if ( + state.history[state.history.length - 1]?.message.content + .length === 0 + ) { + dispatch(clearLastResponse()); + } + }} + > + {getMetaKeyLabel()} ⌫ Cancel + + )} + + ); } export default GUI;