Merge pull request #4978 from continuedev/dallin/create-edit

Edit tool + Create tool tweaks
This commit is contained in:
Dallin Romney 2025-04-04 18:33:09 -07:00 • committed by GitHub
commit 3939b5bb85
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
29 changed files with 497 additions and 133 deletions

1
core/index.d.ts vendored
View file

@ -1143,6 +1143,7 @@ export interface ApplyState {
numDiffs?: number;
filepath?: string;
fileContent?: string;
toolCallId?: string;
}
export interface RangeInFileWithContents {

View file

@ -4,7 +4,6 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
import type {
ApplyState,
CodeToEdit,
ContextSubmenuItem,
EditStatus,
MessageContent,
RangeInFileWithContents,
@ -20,6 +19,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
streamId: string;
curSelectedModelTitle: string;
filepath?: string;
toolCallId?: string;
},
void,
];

View file

@ -1,5 +1,6 @@
export enum BuiltInToolNames {
ReadFile = "builtin_read_file",
EditExistingFile = "builtin_edit_existing_file",
ReadCurrentlyOpenFile = "builtin_read_currently_open_file",
CreateNewFile = "builtin_create_new_file",
RunTerminalCommand = "builtin_run_terminal_command",

View file

@ -138,6 +138,7 @@ export async function callTool(
switch (uri) {
case BuiltInToolNames.ReadFile:
return await readFileImpl(args, extras);
// Note: Custom GUI handling for edit
case BuiltInToolNames.CreateNewFile:
return await createNewFileImpl(args, extras);
case BuiltInToolNames.ExactSearch:

View file

@ -0,0 +1,37 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export interface EditToolArgs {
filepath: string;
new_contents: string;
}
export const editFileTool: Tool = {
type: "function",
displayTitle: "Edit File",
wouldLikeTo: "edit {{{ filepath }}}",
isCurrently: "editing {{{ filepath }}}",
hasAlready: "edited {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
function: {
name: BuiltInToolNames.EditExistingFile,
description:
"Use this tool to edit an existing file. If you don't know the contents of the file, read it first.",
parameters: {
type: "object",
required: ["filepath", "new_contents"],
properties: {
filepath: {
type: "string",
description:
"The path of the file to edit, relative to the root of the workspace.",
},
new_contents: {
type: "string",
description: "The new file contents",
},
},
},
},
};

View file

@ -6,7 +6,7 @@ export const exactSearchTool: Tool = {
displayTitle: "Exact Search",
wouldLikeTo: 'search for "{{{ query }}}" in the repository',
isCurrently: 'getting search results for "{{{ query }}}"',
hasAlready: 'retreived search results for "{{{ query }}}"',
hasAlready: 'retrieved search results for "{{{ query }}}"',
readonly: true,
group: BUILT_IN_GROUP_NAME,
function: {

View file

@ -1,6 +1,7 @@
import { inferResolvedUriFromRelativePath } from "../../util/ideUtils";
import { ToolImpl } from ".";
import { getCleanUriPath, getUriPathBasename } from "../../util/uri";
export const createNewFileImpl: ToolImpl = async (args, extras) => {
const resolvedFileUri = await inferResolvedUriFromRelativePath(
@ -8,8 +9,26 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => {
extras.ide,
);
if (resolvedFileUri) {
const exists = await extras.ide.fileExists(resolvedFileUri);
if (exists) {
throw new Error(
`File ${args.filepath} already exists. Use the edit tool to edit this file`,
);
}
await extras.ide.writeFile(resolvedFileUri, args.contents);
await extras.ide.openFile(resolvedFileUri);
return [
{
name: getUriPathBasename(resolvedFileUri),
description: getCleanUriPath(resolvedFileUri),
content: "File created successfuly",
uri: {
type: "file",
value: resolvedFileUri,
},
},
];
} else {
throw new Error("Failed to resolve path");
}
return [];
};

View file

@ -1,4 +1,5 @@
import { createNewFileTool } from "./definitions/createNewFile";
import { editFileTool } from "./definitions/editFile";
import { exactSearchTool } from "./definitions/exactSearch";
import { lsTool } from "./definitions/lsTool";
import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile";
@ -9,6 +10,7 @@ import { viewDiffTool } from "./definitions/viewDiff";
export const allTools = [
readFileTool,
editFileTool,
createNewFileTool,
runTerminalCommandTool,

View file

@ -16,6 +16,7 @@ import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.SelectionModel
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
@ -423,11 +424,43 @@ class IdeProtocolClient(
dataElement.toString(),
ApplyToFileParams::class.java
)
val filepath = params.filepath
val editor = FileEditorManager.getInstance(project).selectedTextEditor
continuePluginService.sendToWebview("updateApplyState", mapOf(
"streamId" to params.streamId,
"status" to "streaming",
"fileContent" to params.text,
"toolCallId" to params.toolCallId,
"filepath" to filepath
))
fun closeStream () {
continuePluginService.sendToWebview("updateApplyState", mapOf(
"numDiffs" to 0,
"streamId" to params.streamId,
"status" to "closed",
"fileContent" to params.text,
"toolCallId" to params.toolCallId,
"filepath" to filepath
))
}
var editor: Editor? = null;
if (!filepath.isNullOrEmpty()) {
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
if (virtualFile != null) {
ApplicationManager.getApplication().invokeAndWait {
FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first()
}
}
}
editor = FileEditorManager.getInstance(project).selectedTextEditor
if (editor == null) {
ide.showToast(ToastType.ERROR, "No active editor to apply edits to")
closeStream()
respond(null)
return@launch
}
@ -436,6 +469,7 @@ class IdeProtocolClient(
WriteCommandAction.runWriteCommandAction(project) {
editor.document.insertString(0, params.text)
}
closeStream()
respond(null)
return@launch
}
@ -481,6 +515,7 @@ class IdeProtocolClient(
ToastType.ERROR, "Failed to fetch model configuration"
)
}
closeStream()
respond(null)
return@launch
}
@ -519,7 +554,11 @@ class IdeProtocolClient(
editor,
rif?.range?.start?.line ?: 0,
rif?.range?.end?.line ?: (editor.document.lineCount - 1),
{}, {})
{},
{},
params.streamId,
params.toolCallId
)
diffStreamService.register(diffStreamHandler, editor)

View file

@ -27,14 +27,15 @@ class DiffStreamHandler(
private val startLine: Int,
private val endLine: Int,
private val onClose: () -> Unit,
private val onFinish: () -> Unit
private val onFinish: () -> Unit,
private val streamId: String?,
private val toolCallId: String?
) {
private data class CurLineState(
var index: Int, var highlighter: RangeHighlighter? = null, var diffBlock: VerticalDiffBlock? = null
)
private var curLine = CurLineState(startLine)
private var isRunning: Boolean = false
private var hasAcceptedOrRejectedBlock: Boolean = false
@ -48,8 +49,26 @@ class DiffStreamHandler(
initUnfinishedRangeHighlights()
}
private fun sendUpdate(status: String) {
if(this.streamId == null) {
return
}
val virtualFile = getVirtualFile()
val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
continuePluginService.sendToWebview("updateApplyState", mapOf(
"numDiffs" to this.diffBlocks.size,
"streamId" to this.streamId,
"status" to status,
"fileContent" to "not implemented",
"toolCallId" to this.toolCallId,
"filepath" to virtualFile?.url
))
}
fun acceptAll() {
editor.markupModel.removeAllHighlighters()
editor.markupModel.removeAllHighlighters();
sendUpdate("closed")
resetState()
}
@ -62,6 +81,7 @@ class DiffStreamHandler(
} else {
undoChanges()
}
sendUpdate("closed")
resetState()
}
@ -70,6 +90,7 @@ class DiffStreamHandler(
input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String
) {
isRunning = true
this.sendUpdate("streaming")
val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
val virtualFile = getVirtualFile()
@ -83,6 +104,7 @@ class DiffStreamHandler(
if (response["done"] as? Boolean == true) {
handleFinishedResponse()
sendUpdate(if (diffBlocks.isEmpty()) "closed" else "done")
return@request
}
@ -133,7 +155,10 @@ class DiffStreamHandler(
}
if (diffBlocks.isEmpty()) {
sendUpdate("closed")
onClose()
} else {
sendUpdate("done")
}
}
@ -144,6 +169,7 @@ class DiffStreamHandler(
)
diffBlocks.add(diffBlock)
sendUpdate("streaming")
return diffBlock
}
@ -234,6 +260,7 @@ class DiffStreamHandler(
undoManager.undo(fileEditor)
}
}
sendUpdate("done")
}
}

View file

@ -207,7 +207,10 @@ fun openInlineEdit(project: Project?, editor: Editor) {
textArea.document.insertString(textArea.caretPosition, ", ", null)
textArea.requestFocus()
customPanelRef.get().finish()
})
},
null,
null
)
val diffStreamService = project.service<DiffStreamService>()
diffStreamService.register(diffStreamHandler, editor)

View file

@ -12,7 +12,8 @@ data class ApplyToFileParams(
val text: String,
val streamId: String,
val curSelectedModelTitle: String,
val filepath: String?
val filepath: String?,
val toolCallId: String?
)
data class InsertAtCursorParams(

View file

@ -247,6 +247,7 @@ async function processDiff(
verticalDiffManager: VerticalDiffManager,
newFileUri?: string,
streamId?: string,
toolCallId?: string,
) {
captureCommandTelemetry(`${action}Diff`);
@ -280,6 +281,7 @@ async function processDiff(
streamId,
status: "closed",
numDiffs: 0,
toolCallId,
});
}

View file

@ -190,6 +190,7 @@ export class VerticalDiffManager {
diffStream: AsyncGenerator<DiffLine>,
instant: boolean,
streamId: string,
toolCallId?: string,
) {
vscode.commands.executeCommand("setContext", "continue.diffVisible", true);
@ -226,6 +227,7 @@ export class VerticalDiffManager {
numDiffs,
fileContent,
filepath: fileUri,
toolCallId,
}),
},
);
@ -276,6 +278,7 @@ export class VerticalDiffManager {
quickEdit?: string,
range?: vscode.Range,
newCode?: string,
toolCallId?: string,
): Promise<string | undefined> {
vscode.commands.executeCommand("setContext", "continue.diffVisible", true);
@ -351,6 +354,7 @@ export class VerticalDiffManager {
numDiffs,
fileContent,
filepath: fileUri,
toolCallId,
}),
},
);

View file

@ -18,6 +18,7 @@ import { stripImages } from "core/util/messageContent";
import { getUriPathBasename } from "core/util/uri";
import * as vscode from "vscode";
import { ILLM } from "core";
import { VerticalDiffManager } from "../diff/vertical/manager";
import EditDecorationManager from "../quickEdit/EditDecorationManager";
import {
@ -28,7 +29,6 @@ import { showTutorial } from "../util/tutorial";
import { getExtensionUri } from "../util/vscode";
import { VsCodeIde } from "../VsCodeIde";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
import { ILLM } from "core";
/**
* A shared messenger class between Core and Webview
@ -133,6 +133,7 @@ export class VsCodeMessenger {
streamId: data.streamId,
status: "streaming",
fileContent: data.text,
toolCallId: data.toolCallId,
});
if (data.filepath) {
@ -164,6 +165,7 @@ export class VsCodeMessenger {
status: "closed",
numDiffs: 0,
fileContent: data.text,
toolCallId: data.toolCallId,
});
return;
@ -211,6 +213,7 @@ export class VsCodeMessenger {
diffLines,
instant,
data.streamId,
data.toolCallId,
);
} else {
const prompt = `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`;
@ -232,6 +235,7 @@ export class VsCodeMessenger {
undefined,
rangeToApplyTo,
data.text,
data.toolCallId,
);
}
});

View file

@ -46,7 +46,7 @@ export default function FileIcon({ filename, height, width }: FileIconProps) {
height: height,
fill: color,
flexShrink: 0,
display: "block",
display: "flex",
}}
/>
);

View file

@ -12,7 +12,6 @@ import {
newSession,
selectIsInEditMode,
setMode,
updateApplyState,
} from "../redux/slices/sessionSlice";
import { setShowDialog } from "../redux/slices/uiSlice";
import { exitEditMode } from "../redux/thunks";
@ -125,20 +124,6 @@ const Layout = () => {
[],
);
useWebviewListener(
"updateApplyState",
async (state) => {
// dispatch(
// updateCurCheckpoint({
// filepath: state.filepath,
// content: state.fileContent,
// }),
// );
dispatch(updateApplyState(state));
},
[],
);
useWebviewListener(
"openOnboardingCard",
async () => {

View file

@ -98,11 +98,16 @@ function InputToolbar(props: InputToolbarProps) {
const hasCodeToEdit = useAppSelector(selectHasCodeToEdit);
const toolCallState = useAppSelector(selectCurrentToolCall);
const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit;
const activeToolCallStreamId = useAppSelector(
(store) => store.session.activeToolStreamId,
);
const isEnterDisabled =
props.disabled ||
isEditModeAndNoCodeToEdit ||
toolCallState?.status === "generated";
toolCallState?.status === "generated" ||
!!activeToolCallStreamId;
const toolsSupported = defaultModel && modelSupportsTools(defaultModel);
const supportsImages =

View file

@ -7,6 +7,7 @@ import Spinner from "../../gui/Spinner";
import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
interface ApplyActionsProps {
disableManualApply?: boolean;
applyState?: ApplyState;
onClickAccept: () => void;
onClickReject: () => void;
@ -59,8 +60,8 @@ export default function ApplyActions(props: ApplyActionsProps) {
);
case "done":
return (
<div className="xs:pl-2 xs:pr-1 flex items-center rounded bg-zinc-700">
<span className="max-xs:hidden xs:mr-1 text-xs text-gray-400">
<div className="flex items-center sm:gap-1">
<span className="max-xs:hidden text-center text-xs text-gray-400">
{`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`}
<span className="max-md:hidden">{` remaining`}</span>
</span>
@ -90,10 +91,15 @@ export default function ApplyActions(props: ApplyActionsProps) {
</span>
);
}
if (props.disableManualApply) {
return null;
}
return applyButton("Reapply");
}
default:
if (props.disableManualApply) {
return null;
}
return applyButton("Apply");
}
}

View file

@ -1,8 +1,8 @@
import FileIcon from "../../FileIcon";
import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
import { getLastNPathParts } from "core/util/uri";
import { useContext } from "react";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { getLastNPathParts, getUriPathBasename } from "core/util/uri";
import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
import FileIcon from "../../FileIcon";
export interface FileInfoProps {
relativeFilepath: string;
@ -23,17 +23,17 @@ const FileInfo = ({ relativeFilepath, range }: FileInfoProps) => {
}
return (
<div className="flex w-full min-w-0 items-center">
<div
className="mr-0.5 flex w-full min-w-0 cursor-pointer items-center gap-0.5"
onClick={onClickFileName}
>
<div
className="flex cursor-pointer flex-row items-center gap-0.5"
onClick={onClickFileName}
>
<div>
<FileIcon height="20px" width="20px" filename={relativeFilepath} />
<span className="w-full truncate hover:underline">
{getLastNPathParts(relativeFilepath, 1)}
{range && ` ${range}`}
</span>
</div>
<span className="line-clamp-1 break-all hover:underline">
{getLastNPathParts(relativeFilepath, 1)}
{range && ` ${range}`}
</span>
</div>
);
};

View file

@ -3,7 +3,6 @@ import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
import { debounce } from "lodash";
import { useContext, useEffect, useRef, useState } from "react";
import styled from "styled-components";
import { v4 as uuidv4 } from "uuid";
import {
defaultBorderRadius,
vscCommandCenterInactiveBorder,
@ -26,6 +25,8 @@ import GeneratingCodeLoader from "./GeneratingCodeLoader";
import RunInTerminalButton from "./RunInTerminalButton";
const TopDiv = styled.div`
display: flex;
flex-direction: column;
outline: 1px solid ${vscCommandCenterInactiveBorder};
outline-offset: -0.5px;
border-radius: ${defaultBorderRadius};
@ -38,7 +39,6 @@ const ToolbarDiv = styled.div<{ isExpanded: boolean }>`
display: flex;
justify-content: space-between;
align-items: center;
background: inherit;
font-size: ${getFontSize() - 2}px;
padding: 4px 6px;
margin: 0;
@ -52,42 +52,32 @@ export interface StepContainerPreToolbarProps {
relativeFilepath: string;
isGeneratingCodeBlock: boolean;
codeBlockIndex: number; // To track which codeblock we are applying
codeBlockStreamId: string;
range?: string;
children: any;
expanded?: boolean;
hideApply?: boolean;
disableManualApply?: boolean;
}
export default function StepContainerPreToolbar(
props: StepContainerPreToolbarProps,
) {
const ideMessenger = useContext(IdeMessengerContext);
const streamIdRef = useRef<string>(uuidv4());
const wasGeneratingRef = useRef(props.isGeneratingCodeBlock);
const isInEditMode = useAppSelector(selectIsInEditMode);
const [isExpanded, setIsExpanded] = useState(
props.expanded ?? (isInEditMode ? false : true),
);
const [codeBlockContent, setCodeBlockContent] = useState("");
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const nextCodeBlockIndex = useAppSelector(
(state) => state.session.codeBlockApplyStates.curIndex,
);
const applyState = useAppSelector((state) =>
selectApplyStateByStreamId(state, streamIdRef.current),
selectApplyStateByStreamId(state, props.codeBlockStreamId),
);
// This handles an edge case when the last node in the markdown syntax tree is a codeblock.
// In this scenario, `isGeneratingCodeBlock` is never set to false since we determine if
// we are done generating based on whether the next node in the tree is not a codeblock.
// The tree parsing logic for Remark is defined on page load, so we can't access state
// during the actual tree parsing.
const isGeneratingCodeBlock = !isStreaming
? false
: props.isGeneratingCodeBlock;
const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex;
const hasFileExtension = /\.[0-9a-z]+$/i.test(props.relativeFilepath);
@ -104,7 +94,7 @@ export default function StepContainerPreToolbar(
);
ideMessenger.post("applyToFile", {
streamId: streamIdRef.current,
streamId: props.codeBlockStreamId,
filepath: fileUri,
text: codeBlockContent,
curSelectedModelTitle: defaultModel.title,
@ -135,19 +125,17 @@ export default function StepContainerPreToolbar(
}
}, [props.children, codeBlockContent]);
// Temporarily disabling auto apply for Edit mode
// useEffect(() => {
// const hasCompletedGenerating =
// wasGeneratingRef.current && !isGeneratingCodeBlock;
// const shouldAutoApply = hasCompletedGenerating && isInEditMode;
// if (shouldAutoApply) {
// onClickApply();
// }
// wasGeneratingRef.current = isGeneratingCodeBlock;
// }, [isGeneratingCodeBlock]);
// if (hasCompletedGenerating) {
// if (props.autoApply) {
// onClickApply();
// }
// }
// }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]);
async function onClickAcceptApply() {
const fileUri = await inferResolvedUriFromRelativePath(
@ -156,7 +144,7 @@ export default function StepContainerPreToolbar(
);
ideMessenger.post("acceptDiff", {
filepath: fileUri,
streamId: streamIdRef.current,
streamId: props.codeBlockStreamId,
});
}
@ -167,7 +155,7 @@ export default function StepContainerPreToolbar(
);
ideMessenger.post("rejectDiff", {
filepath: fileUri,
streamId: streamIdRef.current,
streamId: props.codeBlockStreamId,
});
}
@ -183,44 +171,40 @@ export default function StepContainerPreToolbar(
return (
<TopDiv>
<ToolbarDiv isExpanded={isExpanded} className="find-widget-skip">
<div className="flex min-w-0 max-w-[45%] items-center">
<ToolbarDiv isExpanded={isExpanded} className="find-widget-skip gap-3">
<div className="flex max-w-72 flex-row items-center">
<ChevronDownIcon
onClick={onClickExpand}
className={`h-3.5 w-3.5 shrink-0 cursor-pointer text-gray-400 hover:brightness-125 ${
className={`h-3.5 w-3.5 flex-shrink-0 cursor-pointer text-gray-400 hover:brightness-125 ${
isExpanded ? "rotate-0" : "-rotate-90"
}`}
/>
<div className="w-full min-w-0">
<FileInfo
relativeFilepath={props.relativeFilepath}
range={props.range}
/>
</div>
<FileInfo
relativeFilepath={props.relativeFilepath}
range={props.range}
/>
</div>
<div className="flex items-center gap-3 max-sm:gap-1.5">
{isGeneratingCodeBlock && (
{props.isGeneratingCodeBlock ? (
<GeneratingCodeLoader
showLineCount={!isExpanded}
codeBlockContent={codeBlockContent}
/>
)}
{!isGeneratingCodeBlock && (
) : (
<>
<CopyButton text={props.codeBlockContent} />
{props.hideApply ||
(isTerminalCodeBlock(props.language, props.codeBlockContent) ? (
<RunInTerminalButton command={props.codeBlockContent} />
) : (
<ApplyActions
applyState={applyState}
onClickApply={onClickApply}
onClickAccept={onClickAcceptApply}
onClickReject={onClickRejectApply}
/>
))}
{isTerminalCodeBlock(props.language, props.codeBlockContent) ? (
<RunInTerminalButton command={props.codeBlockContent} />
) : (
<ApplyActions
disableManualApply={props.disableManualApply}
applyState={applyState}
onClickApply={onClickApply}
onClickAccept={onClickAcceptApply}
onClickReject={onClickRejectApply}
/>
)}
</>
)}
</div>

View file

@ -1,5 +1,5 @@
import { ctxItemToRifWithContents } from "core/commands/util";
import { memo, useEffect, useMemo } from "react";
import { memo, useEffect, useMemo, useRef } from "react";
import { useRemark } from "react-remark";
import rehypeHighlight, { Options } from "rehype-highlight";
import rehypeKatex from "rehype-katex";
@ -17,7 +17,7 @@ import useUpdatingRef from "../../hooks/useUpdatingRef";
import { useAppSelector } from "../../redux/hooks";
import { selectUIConfig } from "../../redux/slices/configSlice";
import { getContextItemsFromHistory } from "../../redux/thunks/updateFileSymbols";
import { getFontSize, isJetBrains } from "../../util";
import { getFontSize } from "../../util";
import { ToolTip } from "../gui/Tooltip";
import FilenameLink from "./FilenameLink";
import "./katex.css";
@ -126,6 +126,9 @@ interface StyledMarkdownPreviewProps {
scrollLocked?: boolean;
itemIndex?: number;
useParentBackgroundColor?: boolean;
disableManualApply?: boolean;
singleCodeblockStreamId?: string;
expandCodeblocks?: boolean;
}
const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-";
@ -192,6 +195,29 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
}, [props.itemIndex, history, allSymbols]);
const pastFileInfoRef = useUpdatingRef(pastFileInfo);
const isLastItem = useMemo(() => {
return props.itemIndex && props.itemIndex === history.length - 1;
}, [history.length, props.itemIndex]);
const isLastItemRef = useUpdatingRef(isLastItem);
const isStreaming = useAppSelector((store) => store.session.isStreaming);
const isStreamingRef = useUpdatingRef(isStreaming);
const codeblockState = useRef<{ streamId: string; isGenerating: boolean }[]>(
[],
);
useEffect(() => {
if (props.singleCodeblockStreamId) {
codeblockState.current = [
{
streamId: props.singleCodeblockStreamId,
isGenerating: false,
},
];
}
}, [props.singleCodeblockStreamId]);
const [reactContent, setMarkdownSource] = useRemark({
remarkPlugins: [
remarkTables,
@ -215,8 +241,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
node.data = node.data || {};
node.data.hProperties = node.data.hProperties || {};
node.data.hProperties["data-isgeneratingcodeblock"] =
lastCodeNode === node;
node.data.hProperties["data-islastcodeblock"] = lastCodeNode === node;
node.data.hProperties["data-codeblockcontent"] = node.value;
if (node.meta) {
@ -278,8 +303,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
const { className, range } = preChildProps;
const relativeFilePath = preChildProps["data-relativefilepath"];
const codeBlockContent = preChildProps["data-codeblockcontent"];
const isGeneratingCodeBlock =
preChildProps["data-isgeneratingcodeblock"];
if (!props.isRenderingInStepContainer) {
return <SyntaxHighlightedPre {...preProps} />;
@ -287,11 +310,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
const language = getLanguageFromClassName(className);
// If we don't have a filepath show the more basic toolbar
// that is just action buttons on hover.
// We also use this in JB since we haven't yet implemented
// the logic forfileUri lazy apply.
if (!relativeFilePath || isJetBrains()) {
if (!relativeFilePath) {
return (
<StepContainerPreActionButtons
language={language}
@ -303,6 +322,21 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
);
}
const isGeneratingCodeBlock =
preChildProps["data-islastcodeblock"] &&
isLastItemRef.current &&
!isStreamingRef.current;
if (codeblockState.current[codeBlockIndex] === undefined) {
codeblockState.current[codeBlockIndex] = {
streamId: uuidv4(),
isGenerating: isGeneratingCodeBlock,
};
} else {
codeblockState.current[codeBlockIndex].isGenerating =
isGeneratingCodeBlock;
}
// We use a custom toolbar for codeblocks in the step container
return (
<StepContainerPreToolbar
@ -312,6 +346,11 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
relativeFilepath={relativeFilePath}
isGeneratingCodeBlock={isGeneratingCodeBlock}
range={range}
codeBlockStreamId={
codeblockState.current[codeBlockIndex].streamId
}
expanded={props.expandCodeblocks}
disableManualApply={props.disableManualApply}
>
<SyntaxHighlightedPre {...preProps} />
</StepContainerPreToolbar>

View file

@ -16,10 +16,14 @@ import {
} from "../redux/slices/configSlice";
import { updateIndexingStatus } from "../redux/slices/indexingSlice";
import {
acceptToolCall,
addContextItemsAtIndex,
setInactive,
setToolCallOutput,
updateApplyState,
} from "../redux/slices/sessionSlice";
import { setTTSActive } from "../redux/slices/uiSlice";
import { streamResponseAfterToolCall } from "../redux/thunks";
import { refreshSessionMetadata } from "../redux/thunks/session";
import { streamResponseThunk } from "../redux/thunks/streamResponse";
import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";
@ -245,6 +249,42 @@ function useSetup() {
},
[defaultModel],
);
const activeToolStreamId = useAppSelector(
(store) => store.session.activeToolStreamId,
);
useWebviewListener(
"updateApplyState",
async (state) => {
// dispatch(
// updateCurCheckpoint({
// filepath: state.filepath,
// content: state.fileContent,
// }),
// );
dispatch(updateApplyState(state));
if (
activeToolStreamId &&
state.streamId === activeToolStreamId[0] &&
state.status === "closed"
) {
// const output: ContextItem = {
// name: "Edit tool output",
// content: "Completed edit",
// description: "",
// };
dispatch(acceptToolCall());
dispatch(setToolCallOutput([]));
dispatch(
streamResponseAfterToolCall({
toolCallId: activeToolStreamId[1],
toolOutput: [],
}),
);
}
},
[activeToolStreamId],
);
}
export default useSetup;

View file

@ -7,9 +7,13 @@ interface CreateFileToolCallProps {
}
export function CreateFile(props: CreateFileToolCallProps) {
const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilepath ?? "test.txt")} ${props.relativeFilepath}\n${props.fileContents ?? ""}\n\`\`\``;
const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilepath ?? "output.txt")} ${props.relativeFilepath}\n${props.fileContents ?? ""}\n\`\`\``;
return props.relativeFilepath ? (
<StyledMarkdownPreview isRenderingInStepContainer={true} source={src} />
<StyledMarkdownPreview
isRenderingInStepContainer={true}
source={src}
disableManualApply={true}
/>
) : null;
}

View file

@ -0,0 +1,54 @@
import { getMarkdownLanguageTagForFile } from "core/util";
import { useMemo } from "react";
import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview";
import AcceptRejectAllButtons from "../../../components/StepContainer/AcceptRejectAllButtons";
import { useAppSelector } from "../../../redux/hooks";
type EditToolCallProps = {
relativeFilePath: string;
newContents: string;
toolCallId?: string;
};
export function EditFile(props: EditToolCallProps) {
const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.newContents ?? ""}\n\`\`\``;
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const states = useAppSelector((store) => store.session.codeBlockApplyStates);
const applyState = useMemo(() => {
return states.states.find(
(state) => state.toolCallId && state.toolCallId === props.toolCallId,
);
}, [states, props.toolCallId]);
if (!props.relativeFilePath) {
return null;
}
return (
<>
<StyledMarkdownPreview
isRenderingInStepContainer={true}
source={src}
disableManualApply={true}
singleCodeblockStreamId={applyState?.streamId}
expandCodeblocks={false}
/>
{/* TODO better indicator of generation at bottom */}
{/* {isStreaming && applyState?.status === "streaming" && (
<div className={`m-2 flex items-center justify-center`}>
Generating...
</div>
)} */}
{!isStreaming && applyState?.status === "done" && (
<div className={`m-2 flex items-center justify-center`}>
<AcceptRejectAllButtons
pendingApplyStates={[applyState]}
onAcceptOrReject={async (outcome) => {}}
/>
</div>
)}
</>
);
}

View file

@ -1,5 +1,7 @@
import { ToolCall, ToolCallDelta, ToolCallState } from "core";
import { ToolCallDelta, ToolCallState } from "core";
import { BuiltInToolNames } from "core/tools/builtIn";
import { CreateFile } from "./CreateFile";
import { EditFile } from "./EditFile";
import { RunTerminalCommand } from "./RunTerminalCommand";
function FunctionSpecificToolCallDiv({
@ -12,14 +14,22 @@ function FunctionSpecificToolCallDiv({
const args = toolCallState.parsedArgs;
switch (toolCall.function?.name) {
case "builtin_create_new_file":
case BuiltInToolNames.CreateNewFile:
return (
<CreateFile
relativeFilepath={args.filepath}
fileContents={args.contents}
/>
);
case "builtin_run_terminal_command":
case BuiltInToolNames.EditExistingFile:
return (
<EditFile
relativeFilePath={args.filepath}
newContents={args.new_contents}
toolCallId={toolCall.id}
/>
);
case BuiltInToolNames.RunTerminalCommand:
return (
<RunTerminalCommand
command={args.command}

View file

@ -21,6 +21,7 @@ import {
ToolCallDelta,
ToolCallState,
} from "core";
import { BuiltInToolNames } from "core/tools/builtIn";
import { NEW_SESSION_TITLE } from "core/util/constants";
import { incrementalParseJson } from "core/util/incrementalParseJson";
import { renderChatMessage } from "core/util/messageContent";
@ -53,6 +54,7 @@ type SessionState = {
states: ApplyState[];
curIndex: number;
};
activeToolStreamId?: [string, string];
newestToolbarPreviewForInput: Record<string, string>;
};
@ -353,16 +355,32 @@ export const sessionSlice = createSlice({
if (message.role === "assistant" && message.toolCalls?.[0]) {
const toolCallDelta = message.toolCalls[0];
if (
toolCallDelta.id &&
toolCallDelta.function?.arguments &&
toolCallDelta.function?.name &&
toolCallDelta.type
!(
toolCallDelta.id &&
toolCallDelta.function?.arguments &&
toolCallDelta.function?.name &&
toolCallDelta.type
)
) {
console.warn(
"Received streamed tool call without required fields",
toolCallDelta,
);
}
if (
toolCallDelta.id &&
toolCallDelta.function?.name ===
BuiltInToolNames.EditExistingFile
) {
const streamId = uuidv4();
state.codeBlockApplyStates.states.push({
streamId,
toolCallId: toolCallDelta.id,
status: "streaming",
});
state.activeToolStreamId = [streamId, toolCallDelta.id];
}
historyItem.toolCallState = toolCallDeltaToState(toolCallDelta);
}
state.history.push(historyItem);
@ -626,6 +644,7 @@ export const sessionSlice = createSlice({
toolCallState.status = "canceled";
},
acceptToolCall: (state) => {
state.activeToolStreamId = undefined;
const toolCallState = findCurrentToolCall(state.history);
if (!toolCallState) return;
@ -717,7 +736,7 @@ export const selectCurrentToolCall = createSelector(
export const selectApplyStateByStreamId = createSelector(
[
(state: RootState) => state.session.codeBlockApplyStates.states,
(state: RootState, streamId: string) => streamId,
(state: RootState, streamId?: string) => streamId,
],
(states, streamId) => {
return states.find((state) => state.streamId === streamId);

View file

@ -44,6 +44,7 @@ export const uiSlice = createSlice({
ttsActive: false,
toolSettings: {
[BuiltInToolNames.ReadFile]: "allowedWithoutPermission",
[BuiltInToolNames.EditExistingFile]: "allowedWithPermission",
[BuiltInToolNames.CreateNewFile]: "allowedWithPermission",
[BuiltInToolNames.RunTerminalCommand]: "allowedWithPermission",
[BuiltInToolNames.ViewSubdirectory]: "allowedWithoutPermission",

View file

@ -1,4 +1,9 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ContextItem } from "core";
import { BuiltInToolNames } from "core/tools/builtIn";
import { EditToolArgs } from "core/tools/definitions/editFile";
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { IIdeMessenger } from "../../context/IdeMessenger";
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
import { selectDefaultModel } from "../slices/configSlice";
import {
@ -6,6 +11,7 @@ import {
cancelToolCall,
setCalling,
setToolCallOutput,
updateApplyState,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
@ -31,28 +37,59 @@ export const callTool = createAsyncThunk<void, undefined, ThunkApiType>(
dispatch(setCalling());
const result = await extra.ideMessenger.request("tools/call", {
toolCall: toolCallState.toolCall,
selectedModelTitle: defaultModel.title,
});
let errorMessage = "";
let output: ContextItem[] | undefined = undefined;
if (result.status === "success") {
const contextItems = result.content.contextItems;
dispatch(setToolCallOutput(contextItems));
dispatch(acceptToolCall());
// Send to the LLM to continue the conversation
const response = await dispatch(
streamResponseAfterToolCall({
toolCallId: toolCallState.toolCall.id,
toolOutput: contextItems,
}),
if (
toolCallState.toolCall.function.name === BuiltInToolNames.EditExistingFile
) {
const args = JSON.parse(
toolCallState.toolCall.function.arguments || "{}",
);
unwrapResult(response);
try {
if (!state.session.activeToolStreamId) {
throw new Error("Invalid apply state");
}
await customGuiEditImpl(
args,
extra.ideMessenger,
state.session.activeToolStreamId[0],
defaultModel.title,
toolCallState.toolCallId,
);
} catch (e) {
errorMessage = "Failed to call edit tool";
if (e instanceof Error) {
errorMessage = e.message;
}
if (state.session.activeToolStreamId?.[0]) {
dispatch(
updateApplyState({
streamId: state.session.activeToolStreamId[0],
status: "closed",
toolCallId: toolCallState.toolCallId,
numDiffs: 0,
filepath: args.filepath,
}),
);
}
}
} else {
const result = await extra.ideMessenger.request("tools/call", {
toolCall: toolCallState.toolCall,
selectedModelTitle: defaultModel.title,
});
if (result.status === "error") {
errorMessage = result.error;
} else {
output = result.content.contextItems;
}
}
if (errorMessage) {
dispatch(cancelToolCall());
const output = await dispatch(
const wrapped = await dispatch(
streamResponseAfterToolCall({
toolCallId: toolCallState.toolCallId,
toolOutput: [
@ -60,13 +97,52 @@ export const callTool = createAsyncThunk<void, undefined, ThunkApiType>(
icon: "problems",
name: "Tool Call Error",
description: "Tool Call Failed",
content: `The tool call failed with the message:\n\n${result.error}\n\nPlease try something else or request further instructions.`,
content: `${toolCallState.toolCall.function.name} failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`,
hidden: false,
},
],
}),
);
unwrapResult(output);
unwrapResult(wrapped);
} else if (output) {
dispatch(setToolCallOutput(output));
dispatch(acceptToolCall());
// Send to the LLM to continue the conversation
const wrapped = await dispatch(
streamResponseAfterToolCall({
toolCallId: toolCallState.toolCall.id,
toolOutput: output,
}),
);
unwrapResult(wrapped);
}
// okay for a tool to have no output and need some GUI trigger or other to trigger response e.g. edit tool
},
);
async function customGuiEditImpl(
args: EditToolArgs,
ideMessenger: IIdeMessenger,
streamId: string,
modelTitle: string,
toolCallId: string,
) {
const firstUriMatch = await resolveRelativePathInDir(
args.filepath,
ideMessenger.ide,
);
if (!firstUriMatch) {
throw new Error(`${args.filepath} does not exist`);
}
const apply = await ideMessenger.request("applyToFile", {
streamId,
text: args.new_contents,
curSelectedModelTitle: modelTitle,
toolCallId,
filepath: firstUriMatch,
});
if (apply.status === "error") {
throw new Error(apply.error);
}
}