Merge pull request #5347 from continuedev/dallin/apply-state

Edit tool fixes
This commit is contained in:
Dallin Romney 2025-04-25 17:04:34 -07:00 • committed by GitHub
commit 72f71339bf
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 170 additions and 135 deletions

1
core/index.d.ts vendored
View file

@ -1216,6 +1216,7 @@ export type EditStatus =
| "done";
export type ApplyStateStatus =
| "not-started" // Apply state created but not necessarily streaming
| "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"

View file

@ -48,6 +48,14 @@ export function ApplyActions(props: ApplyActionsProps) {
);
switch (props.applyState ? props.applyState.status : null) {
case "not-started":
return (
<div className="flex select-none items-center rounded bg-zinc-700 pl-2 pr-1">
<span className="text-lightgray inline-flex w-min items-center gap-2 text-center text-xs">
Pending
</span>
</div>
);
case "streaming":
return (
<div className="flex select-none items-center rounded bg-zinc-700 pl-2 pr-1">
@ -84,8 +92,8 @@ export function ApplyActions(props: ApplyActionsProps) {
</div>
);
case "closed":
if (!hasRejected && props.applyState?.numDiffs === 0) {
if (showApplied) {
if (isSuccessful) {
if (showApplied || props.disableManualApply) {
return (
<span className="flex select-none items-center rounded bg-zinc-700 text-slate-400 max-sm:px-0.5 sm:pl-2">
<span className="max-sm:hidden">Applied</span>
@ -93,9 +101,6 @@ export function ApplyActions(props: ApplyActionsProps) {
</span>
);
}
if (props.disableManualApply) {
return null;
}
return applyButton("Reapply");
}
default:

View file

@ -3,22 +3,24 @@ import Spinner from "../../gui/Spinner";
export interface GeneratingCodeLoaderProps {
showLineCount: boolean;
codeBlockContent: string;
isPending: boolean;
}
export function GeneratingCodeLoader({
showLineCount,
codeBlockContent,
isPending,
}: GeneratingCodeLoaderProps) {
const numLinesCodeBlock = codeBlockContent.split("\n").length;
const linesGeneratedText =
numLinesCodeBlock === 1
? `1 line generated`
: `${numLinesCodeBlock} lines generated`;
: `${numLinesCodeBlock} lines ${isPending ? "pending" : "generated"}`;
return (
<span className="text-lightgray inline-flex items-center gap-2">
{showLineCount ? linesGeneratedText : "Generating"}
<Spinner />
{!isPending && <Spinner />}
</span>
);
}

View file

@ -52,7 +52,7 @@ export interface StepContainerPreToolbarProps {
codeBlockContent: string;
language: string | null;
relativeFilepath?: string;
isGeneratingCodeBlock: boolean;
isFinalCodeblock: boolean;
codeBlockIndex: number; // To track which codeblock we are applying
codeBlockStreamId: string;
range?: string;
@ -65,7 +65,7 @@ export function StepContainerPreToolbar({
codeBlockContent,
language,
relativeFilepath,
isGeneratingCodeBlock,
isFinalCodeblock,
codeBlockIndex,
codeBlockStreamId,
range,
@ -115,6 +115,9 @@ export function StepContainerPreToolbar({
const hasFileExtension =
relativeFilepath && /\.[0-9a-z]+$/i.test(relativeFilepath);
const isStreaming = useAppSelector((store) => store.session.isStreaming);
const isGeneratingCodeBlock = isFinalCodeblock && isStreaming;
// If we are creating a file, we already render that in the button
// so we don't want to dispaly it twice here
const displayFilepath = relativeFilepath ?? appliedFileUri;
@ -272,20 +275,23 @@ export function StepContainerPreToolbar({
</div>
<div className="flex items-center gap-2.5">
{isGeneratingCodeBlock ? (
{!isGeneratingCodeBlock && (
<div className="xs:flex hidden items-center gap-2.5">
<InsertButton onInsert={onClickInsertAtCursor} />
<CopyButton text={codeBlockContent} />
</div>
)}
{isGeneratingCodeBlock || applyState?.status === "not-started" ? (
<GeneratingCodeLoader
showLineCount={!isExpanded}
codeBlockContent={codeBlockContent}
isPending={
applyState?.status === "not-started" && !isGeneratingCodeBlock
}
/>
) : (
<>
<div className="xs:flex hidden items-center gap-2.5">
<InsertButton onInsert={onClickInsertAtCursor} />
<CopyButton text={codeBlockContent} />
</div>
{renderActionButtons()}
</>
renderActionButtons()
)}
</div>
</ToolbarDiv>

View file

@ -126,7 +126,7 @@ interface StyledMarkdownPreviewProps {
itemIndex?: number;
useParentBackgroundColor?: boolean;
disableManualApply?: boolean;
singleCodeblockStreamId?: string;
forceStreamId?: string;
expandCodeblocks?: boolean;
}
@ -195,27 +195,16 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
const pastFileInfoRef = useUpdatingRef(pastFileInfo);
const isLastItem = useMemo(() => {
return props.itemIndex && props.itemIndex === history.length - 1;
return 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 }[]>(
[],
);
const codeblockStreamIds = useRef<string[]>([]);
useEffect(() => {
if (props.singleCodeblockStreamId) {
codeblockState.current = [
{
streamId: props.singleCodeblockStreamId,
isGenerating: false,
},
];
if (props.forceStreamId) {
codeblockStreamIds.current = [props.forceStreamId];
}
}, [props.singleCodeblockStreamId]);
}, [props.forceStreamId, codeblockStreamIds]);
const [reactContent, setMarkdownSource] = useRemark({
remarkPlugins: [
@ -310,19 +299,12 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
const language = getLanguageFromClassName(className);
const isGeneratingCodeBlock =
preChildProps["data-islastcodeblock"] &&
isLastItemRef.current &&
isStreamingRef.current;
const isFinalCodeblock =
preChildProps["data-islastcodeblock"] && isLastItemRef.current;
if (codeblockState.current[codeBlockIndex] === undefined) {
codeblockState.current[codeBlockIndex] = {
streamId: uuidv4(),
isGenerating: isGeneratingCodeBlock,
};
} else {
codeblockState.current[codeBlockIndex].isGenerating =
isGeneratingCodeBlock;
if (codeblockStreamIds.current[codeBlockIndex] === undefined) {
codeblockStreamIds.current[codeBlockIndex] =
props.forceStreamId ?? uuidv4();
}
return (
@ -331,11 +313,9 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
codeBlockIndex={codeBlockIndex}
language={language}
relativeFilepath={relativeFilePath}
isGeneratingCodeBlock={isGeneratingCodeBlock}
isFinalCodeblock={isFinalCodeblock}
range={range}
codeBlockStreamId={
codeblockState.current[codeBlockIndex].streamId
}
codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]}
expanded={props.expandCodeblocks}
disableManualApply={props.disableManualApply}
>
@ -381,7 +361,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
const codeWrapState = uiConfig?.codeWrap ? "pre-wrap" : "pre";
return (
<StyledMarkdown
contentEditable='false'
contentEditable="false"
fontSize={getFontSize()}
whiteSpace={codeWrapState}
bgColor={props.useParentBackgroundColor ? "" : vscBackground}

View file

@ -4,7 +4,10 @@ import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect";
import { useRef } from "react";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectUseActiveFile } from "../../redux/selectors";
import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall";
import {
selectCurrentToolCall,
selectCurrentToolCallApplyState,
} from "../../redux/selectors/selectCurrentToolCall";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import {
selectHasCodeToEdit,
@ -53,15 +56,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 currentToolCallApplyState = useAppSelector(
selectCurrentToolCallApplyState,
);
const isEnterDisabled =
props.disabled ||
isEditModeAndNoCodeToEdit ||
toolCallState?.status === "generated" ||
!!activeToolCallStreamId;
(currentToolCallApplyState &&
currentToolCallApplyState.status !== "closed");
const toolsSupported = defaultModel && modelSupportsTools(defaultModel);

View file

@ -109,7 +109,9 @@ export function LumpToolbar() {
if (toolCallState?.status === "generated") {
return (
<Container>
<GeneratingIndicator />
<div className="flex flex-row items-center pb-0.5 pr-1 text-xs text-gray-400">
<span className="hidden sm:flex">Pending tool call</span>
</div>
<div className="flex gap-2 pb-0.5">
<StopButton

View file

@ -10,6 +10,7 @@ import {
setSelectedProfile,
} from "../redux";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall";
import {
selectSelectedChatModel,
setConfigResult,
@ -252,41 +253,39 @@ function useSetup() {
dispatch(updateIndexingStatus(data));
});
const activeToolStreamId = useAppSelector(
(store) => store.session.activeToolStreamId,
const currentToolCallApplyState = useAppSelector(
selectCurrentToolCallApplyState,
);
useWebviewListener(
"updateApplyState",
async (state) => {
dispatch(updateApplyState(state));
const lastHistoryMsg = history.at(-1);
const [streamId, toolCallId] = activeToolStreamId ?? [];
// Handle apply status updates that are associated with current tool call
if (
toolCallId &&
state.status === "closed" &&
lastHistoryMsg?.toolCallState?.toolCallId === toolCallId
currentToolCallApplyState &&
currentToolCallApplyState.streamId === state.streamId
) {
if (state.streamId === streamId) {
// const output: ContextItem = {
// name: "Edit tool output",
// content: "Completed edit",
// description: "",
// };
dispatch(
acceptToolCall({
toolCallId,
}),
);
// dispatch(setToolCallOutput([]));
dispatch(
streamResponseAfterToolCall({
toolCallId,
}),
);
}
// const output: ContextItem = {
// name: "Edit tool output",
// content: "Completed edit",
// description: "",
// };
dispatch(
acceptToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
// dispatch(setToolCallOutput([]));
dispatch(
streamResponseAfterToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
}
},
[activeToolStreamId, history],
[currentToolCallApplyState, history],
);
}

View file

@ -30,7 +30,10 @@ import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectUseHub } from "../../redux/selectors";
import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall";
import {
selectCurrentToolCall,
selectCurrentToolCallApplyState,
} from "../../redux/selectors/selectCurrentToolCall";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { submitEdit } from "../../redux/slices/editModeState";
import {
@ -152,6 +155,10 @@ export function Chat() {
const { widget, highlights } = useFindWidget(stepsDivRef);
const currentToolCallApplyState = useAppSelector(
selectCurrentToolCallApplyState,
);
const sendInput = useCallback(
(
editorState: JSONContent,
@ -164,6 +171,14 @@ export function Chat() {
"Cannot submit message while awaiting tool confirmation",
);
}
if (
currentToolCallApplyState &&
currentToolCallApplyState.status !== "closed"
) {
return console.error(
"Cannot submit message while awaiting tool call apply",
);
}
if (selectedChatModel?.provider === "free-trial") {
const newCount = incrementFreeTrialCount();
@ -352,6 +367,7 @@ export function Chat() {
toolCallState={item.toolCallState!}
toolCall={toolCall}
output={history[index + 1]?.contextItems}
historyIndex={index}
/>
</div>
);

View file

@ -4,6 +4,7 @@ import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview";
interface CreateFileToolCallProps {
relativeFilepath: string;
fileContents: string;
historyIndex: number;
}
export function CreateFile(props: CreateFileToolCallProps) {
@ -14,6 +15,7 @@ export function CreateFile(props: CreateFileToolCallProps) {
isRenderingInStepContainer
disableManualApply
source={src}
itemIndex={props.historyIndex}
/>
) : null;
}

View file

@ -1,26 +1,40 @@
import { getMarkdownLanguageTagForFile } from "core/util";
import { useMemo } from "react";
import { useEffect } from "react";
import { v4 as uuidv4 } from "uuid";
import AcceptRejectAllButtons from "../../../components/AcceptRejectAllButtons";
import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview";
import { useAppSelector } from "../../../redux/hooks";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import {
selectApplyStateByToolCallId,
updateApplyState,
} from "../../../redux/slices/sessionSlice";
type EditToolCallProps = {
relativeFilePath: string;
changes: string;
toolCallId?: string;
historyIndex: number;
};
export function EditFile(props: EditToolCallProps) {
const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.changes ?? ""}\n\`\`\``;
const dispatch = useAppDispatch();
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]);
const applyState = useAppSelector((state) =>
selectApplyStateByToolCallId(state, props.toolCallId),
);
useEffect(() => {
if (!applyState) {
dispatch(
updateApplyState({
streamId: uuidv4(),
toolCallId: props.toolCallId,
status: "not-started",
}),
);
}
}, [applyState, props.toolCallId]);
if (!props.relativeFilePath) {
return null;
@ -32,8 +46,9 @@ export function EditFile(props: EditToolCallProps) {
isRenderingInStepContainer
disableManualApply
source={src}
singleCodeblockStreamId={applyState?.streamId}
forceStreamId={applyState?.streamId}
expandCodeblocks={false}
itemIndex={props.historyIndex}
/>
{/* TODO better indicator of generation at bottom */}
{/* {isStreaming && applyState?.status === "streaming" && (

View file

@ -7,9 +7,11 @@ import { RunTerminalCommand } from "./RunTerminalCommand";
function FunctionSpecificToolCallDiv({
toolCall,
toolCallState,
historyIndex,
}: {
toolCall: ToolCallDelta;
toolCallState: ToolCallState;
historyIndex: number;
}) {
const args = toolCallState.parsedArgs;
@ -19,6 +21,7 @@ function FunctionSpecificToolCallDiv({
<CreateFile
relativeFilepath={args.filepath}
fileContents={args.contents}
historyIndex={historyIndex}
/>
);
case BuiltInToolNames.EditExistingFile:
@ -27,6 +30,7 @@ function FunctionSpecificToolCallDiv({
relativeFilePath={args.filepath}
changes={args.changes}
toolCallId={toolCall.id}
historyIndex={historyIndex}
/>
);
case BuiltInToolNames.RunTerminalCommand:

View file

@ -31,6 +31,7 @@ interface ToolCallDivProps {
toolCall: ToolCallDelta;
toolCallState: ToolCallState;
output?: ContextItemWithId[];
historyIndex: number;
}
const toolCallIcons: Record<string, ComponentType> = {
@ -100,6 +101,7 @@ export function ToolCallDiv(props: ToolCallDivProps) {
<FunctionSpecificToolCallDiv
toolCall={props.toolCall}
toolCallState={props.toolCallState}
historyIndex={props.historyIndex}
/>
</ToolCallDisplay>
);

View file

@ -8,3 +8,20 @@ export const selectCurrentToolCall = createSelector(
return findCurrentToolCall(history);
},
);
export const selectCurrentToolCallApplyState = createSelector(
[
(store: RootState) => store.session.history,
(store: RootState) => store.session.codeBlockApplyStates,
],
(history, applyStates) => {
const currentToolCall = findCurrentToolCall(history);
if (!currentToolCall) {
return undefined;
}
return applyStates.states.find(
(state) =>
state.toolCallId && state.toolCallId === currentToolCall.toolCallId,
);
},
);

View file

@ -21,7 +21,6 @@ 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";
@ -54,7 +53,6 @@ type SessionState = {
states: ApplyState[];
curIndex: number;
};
activeToolStreamId?: [string, string];
newestToolbarPreviewForInput: Record<string, string>;
};
@ -357,7 +355,7 @@ export const sessionSlice = createSlice({
if (
!(
toolCallDelta.id &&
toolCallDelta.function?.arguments &&
toolCallDelta.function?.arguments !== undefined &&
toolCallDelta.function?.name &&
toolCallDelta.type
)
@ -368,19 +366,6 @@ export const sessionSlice = createSlice({
);
}
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);
@ -660,9 +645,6 @@ export const sessionSlice = createSlice({
toolCallId: string;
}>,
) => {
if (action.payload.toolCallId === state.activeToolStreamId?.[1]) {
state.activeToolStreamId = undefined;
}
const toolCallState = findToolCall(
state.history,
action.payload.toolCallId,
@ -677,9 +659,6 @@ export const sessionSlice = createSlice({
toolCallId: string;
}>,
) => {
if (action.payload.toolCallId === state.activeToolStreamId?.[1]) {
state.activeToolStreamId = undefined;
}
const toolCallState = findToolCall(
state.history,
action.payload.toolCallId,
@ -694,9 +673,6 @@ export const sessionSlice = createSlice({
toolCallId: string;
}>,
) => {
if (action.payload.toolCallId === state.activeToolStreamId?.[1]) {
state.activeToolStreamId = undefined;
}
const toolCallState = findToolCall(
state.history,
action.payload.toolCallId,
@ -803,6 +779,16 @@ export const selectApplyStateByStreamId = createSelector(
},
);
export const selectApplyStateByToolCallId = createSelector(
[
(state: RootState) => state.session.codeBlockApplyStates.states,
(state: RootState, toolCallId?: string) => toolCallId,
],
(states, toolCallId) => {
return states.find((state) => state.toolCallId === toolCallId);
},
);
export const {
updateFileSymbols,
setContextItemsAtIndex,

View file

@ -63,7 +63,11 @@ export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>(
} = await callClientTool(toolCallState.toolCall, {
dispatch,
ideMessenger: extra.ideMessenger,
activeToolStreamId: state.session.activeToolStreamId?.[0],
streamId: state.session.codeBlockApplyStates.states.find(
(state) =>
state.toolCallId && state.toolCallId === toolCallState.toolCallId,
)?.streamId,
getState,
});
output = clientToolOuput;
errorMessage = clientToolError;

View file

@ -1,13 +1,14 @@
import { ContextItem, ToolCall } from "core";
import { BuiltInToolNames } from "core/tools/builtIn";
import { IIdeMessenger } from "../../context/IdeMessenger";
import { AppThunkDispatch } from "../../redux/store";
import { AppThunkDispatch, RootState } from "../../redux/store";
import { editToolImpl } from "./editImpl";
export interface ClientToolExtras {
getState: () => RootState;
dispatch: AppThunkDispatch;
ideMessenger: IIdeMessenger;
activeToolStreamId?: string;
streamId?: string;
}
export interface ClientToolOutput {

View file

@ -1,5 +1,4 @@
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { updateApplyState } from "../../redux/slices/sessionSlice";
import { ClientToolImpl } from "./callClientTool";
export const editToolImpl: ClientToolImpl = async (
@ -7,7 +6,7 @@ export const editToolImpl: ClientToolImpl = async (
toolCallId,
extras,
) => {
if (!extras.activeToolStreamId) {
if (!extras.streamId) {
throw new Error("Invalid apply state");
}
const firstUriMatch = await resolveRelativePathInDir(
@ -18,7 +17,7 @@ export const editToolImpl: ClientToolImpl = async (
throw new Error(`${args.filepath} does not exist`);
}
const apply = await extras.ideMessenger.request("applyToFile", {
streamId: extras.activeToolStreamId,
streamId: extras.streamId,
text: args.changes,
toolCallId,
filepath: firstUriMatch,
@ -26,17 +25,7 @@ export const editToolImpl: ClientToolImpl = async (
if (apply.status === "error") {
throw new Error(apply.error);
}
if (extras.activeToolStreamId) {
extras.dispatch(
updateApplyState({
streamId: extras.activeToolStreamId,
status: "closed",
toolCallId,
numDiffs: 0,
filepath: args.filepath,
}),
);
}
return {
respondImmediately: false,
output: undefined, // No immediate output.