fix: reject logic

This commit is contained in:
Patrick Erichsen 2025-05-16 10:38:47 -07:00
parent 5f6cda7374
commit 5944fca737
10 changed files with 95 additions and 81 deletions

5
core/index.d.ts vendored
View file

@ -1245,6 +1245,11 @@ export interface HighlightedCodePayload {
shouldRun?: boolean;
}
export interface AcceptOrRejectDiffPayload {
filepath: string;
streamId?: string;
}
export interface RangeInFileWithContents {
filepath: string;
range: {

View file

@ -7,6 +7,7 @@ import {
HighlightedCodePayload,
MessageContent,
RangeInFileWithContents,
AcceptOrRejectDiffPayload,
} from "../";
export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
@ -43,8 +44,8 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
"jetbrains/getColors": [undefined, Record<string, string>];
"vscode/openMoveRightMarkdown": [undefined, void];
setGitHubAuthToken: [{ token: string }, void];
acceptDiff: [{ filepath: string; streamId?: string }, void];
rejectDiff: [{ filepath: string; streamId?: string }, void];
acceptDiff: [AcceptOrRejectDiffPayload, void];
rejectDiff: [AcceptOrRejectDiffPayload, void];
"edit/sendPrompt": [
{
prompt: MessageContent;

View file

@ -33,6 +33,8 @@ class IdeProtocolClient(
private val project: Project
) : DumbAware {
private val ide: IDE = IntelliJIDE(project, continuePluginService)
private val diffStreamService = project.service<DiffStreamService>()
/**
* Create a dispatcher with limited parallelism to prevent UI freezing.
@ -441,7 +443,13 @@ class IdeProtocolClient(
)
val filepath = params.filepath;
acceptOrRejectDiff(filepath, true)
val editor = EditorUtils.getOrOpenEditor(project, filepath)?.editor
if (editor != null) {
diffStreamService.accept(editor)
}
respond(null)
}
"rejectDiff" -> {
@ -450,7 +458,13 @@ class IdeProtocolClient(
RejectDiffParams::class.java
)
val filepath = params.filepath;
acceptOrRejectDiff(filepath, false)
val editor = EditorUtils.getOrOpenEditor(project, filepath)?.editor
if (editor != null) {
diffStreamService.reject(editor)
}
respond(null)
}
"applyToFile" -> {
@ -496,28 +510,6 @@ class IdeProtocolClient(
continuePluginService.sendToWebview("acceptRejectDiff", AcceptRejectDiff(accepted, stepIndex), uuid())
}
fun acceptOrRejectDiff(filepath: String, accepted: Boolean) {
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
if (virtualFile != null) {
ApplicationManager.getApplication().invokeAndWait {
val openedEditor =
FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first()
if (openedEditor != null) {
val editor: Editor? = FileEditorManager.getInstance(project).selectedTextEditor
if (editor != null) {
val diffStreamService = project.service<DiffStreamService>()
if (accepted) {
diffStreamService.accept(editor)
} else {
diffStreamService.reject(editor)
}
}
}
}
}
}
fun deleteAtIndex(index: Int) {
continuePluginService.sendToWebview("deleteAtIndex", DeleteAtIndex(index), uuid())

View file

@ -69,9 +69,9 @@ class DiffStreamHandler(
}
fun acceptAll() {
editor.markupModel.removeAllHighlighters();
sendUpdate(ApplyStateStatus.CLOSED)
resetState()
ApplicationManager.getApplication().invokeLater {
diffBlocks.toList().forEach { it.handleAccept() }
}
}
fun rejectAll() {
@ -79,12 +79,16 @@ class DiffStreamHandler(
// to our changes. However, if the user has accepted or rejected one or more diff blocks, there isn't a simple
// way to undo our changes without also undoing the diff that the user accepted or rejected.
if (hasAcceptedOrRejectedBlock) {
diffBlocks.forEach { it.handleReject() }
ApplicationManager.getApplication().invokeLater {
val blocksToReject = diffBlocks.toList()
blocksToReject.toList().forEach { it.handleReject() }
}
} else {
undoChanges()
// We have to manually call `handleClosedState`, but above,
// this is done by invoking the button handlers
setClosed()
}
sendUpdate(ApplyStateStatus.CLOSED)
resetState()
}
fun streamDiffLinesToEditor(
@ -170,11 +174,10 @@ class DiffStreamHandler(
}
if (diffBlocks.isEmpty()) {
sendUpdate(ApplyStateStatus.CLOSED)
onClose()
setClosed()
} else {
// TODO: It's confusing that we pass `DONE` here. What we're doing is updating the UI with the latest
// diff count. We should have a dedicated status for
// diff count. We should have a dedicated status for this.
sendUpdate(ApplyStateStatus.DONE)
}
}
@ -268,11 +271,11 @@ class DiffStreamHandler(
private fun undoChanges() {
WriteCommandAction.runWriteCommandAction(project) {
if (virtualFile == null) {
return@runWriteCommandAction
}
if (virtualFile == null) {
return
}
WriteCommandAction.runWriteCommandAction(project) {
val undoManager = UndoManager.getInstance(project)
val fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(virtualFile) as TextEditor
@ -296,7 +299,11 @@ class DiffStreamHandler(
onFinish()
cleanupProgressHighlighters()
sendUpdate(if (diffBlocks.isEmpty()) ApplyStateStatus.CLOSED else ApplyStateStatus.DONE)
if (diffBlocks.isEmpty()) {
setClosed()
} else {
sendUpdate(ApplyStateStatus.DONE)
}
}
}
@ -326,4 +333,10 @@ class DiffStreamHandler(
else -> throw Exception("Unknown diff line type: $type")
}
}
private fun setClosed() {
sendUpdate(ApplyStateStatus.CLOSED)
resetState()
onClose()
}
}

View file

@ -27,14 +27,11 @@ class VerticalDiffBlock(
) {
val deletedLines: MutableList<String> = mutableListOf()
val addedLines: MutableList<String> = mutableListOf()
private var editorUtils = EditorUtils(editor)
private val acceptButton: JButton
private val rejectButton: JButton
private var deletionInlay: Disposable? = null
private var textArea: JTextArea? = null // Used for calculation of the text area height when rendering buttons
private var hasRenderedDiffBlock: Boolean = false
private val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false)
private val greenKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00)
init {
val (acceptBtn, rejectBtn) = createButtons()
@ -79,6 +76,8 @@ class VerticalDiffBlock(
fun addNewLine(text: String, line: Int) {
val greenKey = EditorUtils(editor).createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00)
if (line == editor.document.lineCount) {
editor.document.insertString(editor.document.textLength, "\n")
}
@ -108,20 +107,32 @@ class VerticalDiffBlock(
}
fun handleReject() {
revertDiff()
// Note that the logic for clearing editor UI state assumes that we do it
// prior to undoing the diff changes, changing this order will break things
clearEditorUI()
revertDiff()
onAcceptReject(this@VerticalDiffBlock, false)
}
fun handleAccept() {
clearEditorUI()
onAcceptReject(this@VerticalDiffBlock, true)
}
private fun refreshEditor() {
editor.contentComponent.revalidate()
editor.contentComponent.repaint()
}
private fun renderDeletedLinesInlay() {
val textArea = createDeletionTextArea(deletedLines.joinToString("\n"))
this.textArea = textArea
val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false)
val newTextArea = createDeletionTextArea(deletedLines.joinToString("\n"))
val disposable = editorComponentInlaysManager.insert(startLine, textArea, true)
textArea = newTextArea
val disposable = editorComponentInlaysManager.insert(startLine, newTextArea, true)
deletionInlay = disposable
}
@ -159,7 +170,6 @@ class VerticalDiffBlock(
).apply {
addActionListener {
handleReject()
onAcceptReject(this@VerticalDiffBlock, false)
}
}
@ -172,7 +182,6 @@ class VerticalDiffBlock(
).apply {
addActionListener {
handleAccept()
onAcceptReject(this@VerticalDiffBlock, true)
}
}
@ -186,9 +195,6 @@ class VerticalDiffBlock(
refreshEditor()
}
private fun handleAccept() {
clearEditorUI()
}
private fun revertDiff() {
WriteCommandAction.runWriteCommandAction(project) {

View file

@ -239,4 +239,9 @@ data class StreamDiffLinesPayload(
val language: String?,
val modelTitle: String?,
val includeRulesInSystemMessage: Boolean
)
)
data class AcceptOrRejectDiffPayload(
val filepath: String,
val streamId: String? = null
)

View file

@ -1,5 +1,6 @@
import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { UpdateApplyStatePayload } from "core";
import { ToIdeFromWebviewProtocol } from "core/protocol/ideWebview";
import { useContext } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { getMetaKeyLabel } from "../util";
@ -10,9 +11,12 @@ export interface AcceptRejectAllButtonsProps {
onAcceptOrReject?: (outcome: AcceptOrRejectOutcome) => void;
}
export type AcceptOrRejectOutcome = "acceptDiff" | "rejectDiff";
export type AcceptOrRejectOutcome = keyof Pick<
ToIdeFromWebviewProtocol,
"acceptDiff" | "rejectDiff"
>;
export default function AcceptRejectAllButtons({
export default function AcceptRejectDiffButtons({
applyStates,
onAcceptOrReject,
}: AcceptRejectAllButtonsProps) {
@ -24,6 +28,7 @@ export default function AcceptRejectAllButtons({
const tinyFont = useFontSize(-3);
async function handleAcceptOrReject(status: AcceptOrRejectOutcome) {
debugger;
for (const { filepath = "", streamId } of pendingApplyStates) {
ideMessenger.post(status, {
filepath,
@ -53,7 +58,6 @@ export default function AcceptRejectAllButtons({
<div className="flex flex-row items-center gap-1">
<XMarkIcon className="h-4 w-4 text-red-600" />
<span>Reject</span>
<span className="xs:inline-block hidden">All</span>
</div>
<span
@ -73,7 +77,6 @@ export default function AcceptRejectAllButtons({
<div className="flex flex-row items-center gap-1">
<CheckIcon className="h-4 w-4 text-green-600" />
<span>Accept</span>
<span className="xs:inline-block hidden">All</span>
</div>
<span
className="xs:inline-block hidden text-gray-400"

View file

@ -2,7 +2,7 @@ import { useContext } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { exitEditMode } from "../../redux/thunks/editMode";
import AcceptRejectAllButtons from "../AcceptRejectAllButtons";
import AcceptRejectDiffButtons from "../AcceptRejectDiffButtons";
import { useMainEditor } from "./TipTapEditor";
const EditModeDetails = () => {
@ -28,7 +28,7 @@ const EditModeDetails = () => {
<div className="flex flex-col items-center justify-center pb-1 pt-3 text-xs italic text-gray-400">
<span className="">{`${editApplyState.numDiffs} diff${plural} remaining`}</span>
</div>
<AcceptRejectAllButtons
<AcceptRejectDiffButtons
applyStates={[editApplyState]}
onAcceptOrReject={async (outcome) => {
if (outcome === "acceptDiff") {

View file

@ -1,8 +1,6 @@
import {
ArrowLeftIcon,
ChatBubbleOvalLeftIcon,
CodeBracketSquareIcon,
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { Editor, JSONContent } from "@tiptap/react";
import { InputModifiers } from "core";
@ -20,7 +18,6 @@ import {
import { ErrorBoundary } from "react-error-boundary";
import styled from "styled-components";
import { Button, lightGray, vscBackground } from "../../components";
import AcceptRejectAllButtons from "../../components/AcceptRejectAllButtons";
import FeedbackDialog from "../../components/dialogs/FeedbackDialog";
import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog";
import { useFindWidget } from "../../components/find/FindWidget";
@ -50,7 +47,7 @@ import {
import { cancelStream } from "../../redux/thunks/cancelStream";
import { streamEditThunk } from "../../redux/thunks/editMode";
import { loadLastSession } from "../../redux/thunks/session";
import { streamResponseThunk } from "../../redux/thunks/streamResponse";
import { streamResponseThunk } from "../../redux/thunks";
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
import {
FREE_TRIAL_LIMIT_REQUESTS,
@ -64,6 +61,7 @@ import { EmptyChatBody } from "./EmptyChatBody";
import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
import { ToolCallDiv } from "./ToolCallDiv";
import { useAutoScroll } from "./useAutoScroll";
import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons";
const StepsDiv = styled.div`
position: relative;
@ -74,7 +72,7 @@ const StepsDiv = styled.div`
}
.thread-message {
margin: 0px 0px 0px 1px;
margin: 0 0 0 1px;
}
`;
@ -112,7 +110,7 @@ export function Chat() {
(store) => store.config?.config.selectedModelByRole,
);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]);
const [stepsOpen] = useState<(boolean | undefined)[]>([]);
const mainTextInputRef = useRef<HTMLInputElement>(null);
const stepsDivRef = useRef<HTMLDivElement>(null);
const history = useAppSelector((state) => state.session.history);
@ -200,7 +198,7 @@ export function Chat() {
if (newCount >= FREE_TRIAL_LIMIT_REQUESTS) {
// Show this message whether using platform or not
// So that something happens if in new chat
ideMessenger.ide.showToast(
void ideMessenger.ide.showToast(
"error",
"You've reached the free trial limit. Please configure a model to continue.",
);
@ -355,23 +353,11 @@ export function Chat() {
<TimelineItem
item={item}
iconElement={
false ? (
<CodeBracketSquareIcon width="16px" height="16px" />
) : false ? (
<ExclamationTriangleIcon
width="16px"
height="16px"
color="red"
/>
) : (
<ChatBubbleOvalLeftIcon width="16px" height="16px" />
)
<ChatBubbleOvalLeftIcon width="16px" height="16px" />
}
open={
typeof stepsOpen[index] === "undefined"
? false
? false
: true
? true
: stepsOpen[index]!
}
onToggle={() => {}}
@ -391,7 +377,7 @@ export function Chat() {
<div className={"relative"}>
<>
{!isStreaming && mode !== "edit" && (
<AcceptRejectAllButtons
<AcceptRejectDiffButtons
applyStates={applyStates}
onAcceptOrReject={async () => {}}
/>

View file

@ -31,3 +31,6 @@ class Test {
}
}