diff --git a/core/index.d.ts b/core/index.d.ts index 26421368c..a4f76ead0 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -321,7 +321,7 @@ export interface ToolCallDelta { export interface ToolResultChatMessage { role: "tool"; content: string; - toolCallId?: string; + toolCallId: string; } export interface UserChatMessage { @@ -390,13 +390,28 @@ export interface PromptLog { prompt: string; completion: string; } + +export type ToolStatus = + | "generating" + | "generated" + | "calling" + | "done" + | "canceled"; + +// Will exist only on "assistant" messages with tool calls +interface ToolCallState { + toolCallId: string; + toolCall: ToolCall; + status: ToolStatus; +} + export interface ChatHistoryItem { message: ChatMessage; editorState?: any; modifiers?: InputModifiers; contextItems: ContextItemWithId[]; promptLogs?: PromptLog[]; - acceptedToolCall?: boolean; + toolCallState?: ToolCallState; } export type ChatHistory = ChatHistoryItem[]; diff --git a/core/llm/index.ts b/core/llm/index.ts index fd3e9b7ac..144df72d2 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -4,7 +4,6 @@ import Handlebars from "handlebars"; import { CacheBehavior, ChatMessage, - ChatMessageRole, CompletionOptions, ILLM, LLMFullCompletionOptions, @@ -582,7 +581,7 @@ export abstract class BaseLLM implements ILLM { for await (const chunk of this.streamChat(messages, signal, options)) { completion += chunk.content; } - return { role: "assistant" as ChatMessageRole, content: completion }; + return { role: "assistant" as const, content: completion }; } async *streamChat( diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 6cd262a4a..2d0281bd4 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -27,6 +27,7 @@ import resolveEditorContent, { } from "../components/mainInput/resolveInput"; import { IIdeMessenger } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; +import { selectLastToolCall } from "../redux/selectors/selectLastToolCall"; import { abortStream, acceptToolCall, @@ -37,6 +38,7 @@ import { resetNextCodeBlockToApplyIndex, resubmitAtIndex, setActive, + setCalling, setCurCheckpointIndex, setInactive, setIsGatheringContext, @@ -68,6 +70,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const toolSettings = useSelector( (store: RootState) => store.uiState.toolSettings, ); + const toolCallState = useSelector(selectLastToolCall); const activeRef = useRef(active); @@ -116,7 +119,16 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { if (returnVal) { dispatch(addPromptCompletionPair([returnVal])); } + + // If it's a tool call that is automatically accepted, we should call it + if ( + toolSettings[toolCallState?.toolCall.function.name] === + "allowedWithoutPermission" + ) { + await callTool(); + } } catch (e) { + debugger; // If there's an error, we should clear the response so there aren't two input boxes dispatch(clearLastEmptyResponse()); } @@ -446,9 +458,40 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { }); } + async function callTool() { + console.log("calling tool", toolCallState.toolCall); + // If it goes "generated" -> "calling" -> "done" really quickly + // we don't want an abrupt flash so just skip "calling" + let setCallingState = true; + + const timer = setTimeout(() => { + if (setCallingState) { + dispatch(setCalling()); + } + }, 800); + + if (toolCallState.status !== "generated") { + return; + } + + const result = await ideMessenger.request("tools/call", { + toolCall: toolCallState.toolCall, + }); + + setCallingState = false; + clearTimeout(timer); + + if (result.status === "success") { + const contextItems = result.content.contextItems; + // Send to the LLM to continue the conversation + streamResponseAfterToolCall(toolCallState.toolCall.id, contextItems); + } + } + return { streamResponse, streamResponseAfterToolCall, + callTool, }; } diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index a858c09a8..26c68f04d 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -5,7 +5,7 @@ import { ExclamationTriangleIcon, } from "@heroicons/react/24/outline"; import { JSONContent } from "@tiptap/react"; -import { InputModifiers } from "core"; +import { InputModifiers, ToolCallState } from "core"; import { usePostHog } from "posthog-js/react"; import { useCallback, useContext, useEffect, useRef, useState } from "react"; import { ErrorBoundary } from "react-error-boundary"; @@ -35,6 +35,7 @@ import useHistory from "../../hooks/useHistory"; import { useTutorialCard } from "../../hooks/useTutorialCard"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; +import { selectLastToolCall } from "../../redux/selectors/selectLastToolCall"; import { clearLastEmptyResponse, newSession, @@ -132,8 +133,8 @@ export function Chat() { const { saveSession, getLastSessionId, loadLastSession } = useHistory(dispatch); - const toolCallState = useSelector( - (store: RootState) => store.state.currentToolCallState, + const toolCallState = useSelector( + selectLastToolCall, ); const snapToBottom = useCallback(() => { @@ -352,13 +353,14 @@ export function Chat() { toolCallId={item.message.toolCallId} /> ) : item.message.role === "assistant" && - item.message.toolCalls ? ( + item.message.toolCalls && + item.toolCallState ? (
{item.message.toolCalls?.map((toolCall) => { return ( ); })} @@ -431,9 +433,7 @@ export function Chat() { )}
- {toolCallState.currentToolCallState === "generated" && ( - - )} + {toolCallState?.status === "generated" && } - + /> */} ); } diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 27bd820a8..db72817c9 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -2,28 +2,17 @@ import { ToolCall } from "core"; import { incrementalParseJson } from "core/util/incrementalParseJson"; import { CreateFile } from "./CreateFile"; import { RunTerminalCommand } from "./RunTerminalCommand"; -import { ToolState } from "./types"; -function FunctionSpecificToolCallDiv({ - toolCall, - state, -}: { - toolCall: ToolCall; - state: ToolState; -}) { +function FunctionSpecificToolCallDiv({ toolCall }: { toolCall: ToolCall }) { const [_, args] = incrementalParseJson(toolCall.function.arguments); switch (toolCall.function.name) { case "create_new_file": return ( - + ); case "run_terminal_command": - return ; + return ; default: return null; } diff --git a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx index c217bd07b..08c00c0bd 100644 --- a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +++ b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx @@ -1,9 +1,7 @@ import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; -import { ToolState } from "./types"; interface RunTerminalCommandToolCallProps { command: string; - state: ToolState; } export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx index 42f9d9204..068394086 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx @@ -1,4 +1,4 @@ -import { useContext, useEffect } from "react"; +import { useContext } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; import { @@ -10,8 +10,8 @@ import { import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import useChatHandler from "../../../hooks/useChatHandler"; -import { cancelToolCall, setCalling } from "../../../redux/slices/stateSlice"; -import { RootState } from "../../../redux/store"; +import { selectLastToolCall } from "../../../redux/selectors/selectLastToolCall"; +import { cancelToolCall } from "../../../redux/slices/stateSlice"; const ButtonContainer = styled.div` display: flex; @@ -52,62 +52,18 @@ interface ToolCallButtonsProps {} export function ToolCallButtons(props: ToolCallButtonsProps) { const dispatch = useDispatch(); - const toolCallState = useSelector( - (store: RootState) => store.state.currentToolCallState, - ); - const toolSetting = useSelector( - (store: RootState) => - store.uiState.toolSettings[toolCallState.toolCall.function.name], - ); + const toolCallState = useSelector(selectLastToolCall); const ideMessenger = useContext(IdeMessengerContext); - useEffect(() => { - if ( - toolCallState.currentToolCallState === "generated" && - toolSetting === "allowedWithoutPermission" - ) { - callTool(); - } - }, [toolCallState.currentToolCallState, toolSetting]); - - const { streamResponseAfterToolCall } = useChatHandler( + const { streamResponseAfterToolCall, callTool } = useChatHandler( dispatch, ideMessenger, ); - async function callTool() { - // If it goes "generated" -> "calling" -> "done" really quickly - // we don't want an abrupt flash so just skip "calling" - let setCallingState = true; - - const timer = setTimeout(() => { - if (setCallingState) { - dispatch(setCalling()); - } - }, 800); - - if (toolCallState.currentToolCallState !== "generated") { - return; - } - - const result = await ideMessenger.request("tools/call", { - toolCall: toolCallState.toolCall, - }); - - setCallingState = false; - clearTimeout(timer); - - if (result.status === "success") { - const contextItems = result.content.contextItems; - // Send to the LLM to continue the conversation - streamResponseAfterToolCall(toolCallState.toolCall.id, contextItems); - } - } - async function cancelTool() { dispatch(cancelToolCall()); - streamResponseAfterToolCall(toolCallState.toolCall.id, [ + streamResponseAfterToolCall(toolCallState.toolCallId, [ { name: "Cancelled", description: "Cancelled", @@ -120,7 +76,7 @@ export function ToolCallButtons(props: ToolCallButtonsProps) { return ( <> - {toolCallState.currentToolCallState === "generating" ? ( + {toolCallState.status === "generating" ? (
Thinking...
- ) : toolCallState.currentToolCallState === "generated" ? ( + ) : toolCallState.status === "generated" ? ( <> Cancel Continue - ) : toolCallState.currentToolCallState === "calling" ? ( + ) : toolCallState.status === "calling" ? (
Loading... diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index fa0a96a6a..656d2b248 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -1,33 +1,21 @@ import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { ToolCall } from "core"; +import { ToolCall, ToolStatus } from "core"; import { incrementalParseJson } from "core/util/incrementalParseJson"; import { useEffect } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { lightGray } from "../../../components"; import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner"; -import { - registerCurrentToolCall, - setGeneratedOutput, -} from "../../../redux/slices/stateSlice"; -import { RootState } from "../../../redux/store"; +import { setGeneratedOutput } from "../../../redux/slices/stateSlice"; import FunctionSpecificToolCallDiv from "./FunctionSpecificToolCallDiv"; import { ThreadDiv } from "./ThreadDiv"; -import { ToolState } from "./types"; interface ToolCallDivProps { toolCall: ToolCall; - acceptedToolCall?: boolean; + status: ToolStatus; } export function ToolCallDiv(props: ToolCallDivProps) { const dispatch = useDispatch(); - const toolCallState = useSelector( - (store: RootState) => store.state.currentToolCallState, - ); - - useEffect(() => { - dispatch(registerCurrentToolCall()); - }, []); useEffect(() => { // Once the JSON can successfully parse, then set state to "generated" @@ -42,13 +30,8 @@ export function ToolCallDiv(props: ToolCallDivProps) { } }, [props.toolCall.function.arguments]); - function getIcon(state: ToolState) { + function getIcon(state: ToolStatus) { console.log("State: ", state); - if (props.acceptedToolCall === true) { - return ; - } else if (props.acceptedToolCall === false) { - return ; - } switch (state) { case "generating": @@ -65,15 +48,9 @@ export function ToolCallDiv(props: ToolCallDivProps) { } return ( - - {toolCallState.currentToolCallState} - + + {props.status} + ); } diff --git a/gui/src/pages/gui/ToolCallDiv/types.ts b/gui/src/pages/gui/ToolCallDiv/types.ts deleted file mode 100644 index 2a21a7bb9..000000000 --- a/gui/src/pages/gui/ToolCallDiv/types.ts +++ /dev/null @@ -1,6 +0,0 @@ -export type ToolState = - | "generating" - | "generated" - | "calling" - | "done" - | "canceled"; diff --git a/gui/src/redux/selectors/selectLastToolCall.ts b/gui/src/redux/selectors/selectLastToolCall.ts new file mode 100644 index 000000000..3625cf8de --- /dev/null +++ b/gui/src/redux/selectors/selectLastToolCall.ts @@ -0,0 +1,10 @@ +import { createSelector } from "@reduxjs/toolkit"; +import { RootState } from "../store"; +import { findLastToolCall } from "../util"; + +export const selectLastToolCall = createSelector( + (store: RootState) => store.state.history, + (history) => { + return findLastToolCall(history); + }, +); diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index fecd98176..cbed186c8 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -16,13 +16,7 @@ import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { renderChatMessage } from "core/util/messageContent"; import { v4 as uuidv4, v4 } from "uuid"; -import { ToolState } from "../../pages/gui/ToolCallDiv/types"; - -interface CurrentToolCallState { - currentToolCallId?: string; - currentToolCallState?: ToolState; - toolCall?: ToolCall; -} +import { findLastToolCall } from "../util"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -31,7 +25,6 @@ type ChatHistoryItemWithMessageId = ChatHistoryItem & { }; type State = { - currentToolCallState: CurrentToolCallState; history: ChatHistoryItemWithMessageId[]; symbols: FileSymbolMap; context: { @@ -59,10 +52,6 @@ type State = { }; const initialState: State = { - currentToolCallState: { - currentToolCallId: undefined, - currentToolCallState: undefined, - }, history: [], symbols: {}, context: { @@ -215,8 +204,6 @@ export const stateSlice = createSlice({ contextItems: [], }); - state.currentToolCallState = {}; - // https://github.com/continuedev/continue/pull/1021 state.active = true; }, @@ -320,10 +307,20 @@ export const stateSlice = createSlice({ action.payload.toolCalls?.length)) ) { // Create a new message - state.history.push({ + const historyItem: ChatHistoryItemWithMessageId = { contextItems: [], - message: { id: "NONE", ...action.payload }, - }); + message: { id: uuidv4(), ...action.payload }, + }; + + if (action.payload.role === "assistant" && action.payload.toolCalls) { + historyItem.toolCallState = { + status: "generating", + toolCall: action.payload.toolCalls[0] as ToolCall, + toolCallId: action.payload.toolCalls[0].id, + }; + } + + state.history.push(historyItem); } else { // Add to the existing message const msg = state.history[state.history.length - 1].message; @@ -359,7 +356,6 @@ export const stateSlice = createSlice({ state.active = false; state.context.isGathering = false; state.symbols = {}; - state.currentToolCallState = {}; if (payload) { state.history = payload.history as any; @@ -460,26 +456,30 @@ export const stateSlice = createSlice({ }, // Related to currentToolCallState - registerCurrentToolCall: (state, { payload }: PayloadAction) => { - state.currentToolCallState.currentToolCallId = payload; - state.currentToolCallState.currentToolCallState = "generating"; - }, cancelToolCall: (state) => { - state.currentToolCallState.currentToolCallId = undefined; - state.currentToolCallState.currentToolCallState = undefined; - state.history[state.history.length - 1].acceptedToolCall = false; + const toolCallState = findLastToolCall(state.history); + if (!toolCallState) return; + + toolCallState.status = "canceled"; }, acceptToolCall: (state) => { - state.currentToolCallState.currentToolCallId = undefined; - state.currentToolCallState.currentToolCallState = undefined; - state.history[state.history.length - 1].acceptedToolCall = true; + const toolCallState = findLastToolCall(state.history); + if (!toolCallState) return; + + toolCallState.status = "done"; }, setGeneratedOutput: (state, { payload }: PayloadAction) => { - state.currentToolCallState.currentToolCallState = "generated"; - state.currentToolCallState.toolCall = payload; + const toolCallState = findLastToolCall(state.history); + if (!toolCallState) return; + + toolCallState.toolCall = payload; + toolCallState.status = "generated"; }, setCalling: (state) => { - state.currentToolCallState.currentToolCallState = "calling"; + const toolCallState = findLastToolCall(state.history); + if (!toolCallState) return; + + toolCallState.status = "calling"; }, updateIndexingStatus: ( state, @@ -551,7 +551,6 @@ export const { setIndexingChatPeekHidden, setCalling, cancelToolCall, - registerCurrentToolCall, setGeneratedOutput, acceptToolCall, } = stateSlice.actions; diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts new file mode 100644 index 000000000..debf6b329 --- /dev/null +++ b/gui/src/redux/util/index.ts @@ -0,0 +1,20 @@ +import { ToolCallState } from "core"; +import { RootState } from "../store"; + +function findLast( + array: T[], + predicate: (value: T, index: number, array: T[]) => boolean, +): T | undefined { + for (let i = array.length - 1; i >= 0; i--) { + if (predicate(array[i], i, array)) { + return array[i]; + } + } + return undefined; +} + +export function findLastToolCall( + state: RootState["state"]["history"], +): ToolCallState | undefined { + return findLast(state, (item) => !!item.toolCallState)?.toolCallState; +}