update state

This commit is contained in:
Nate 2024-11-23 21:13:47 -08:00
parent 5004123054
commit 4916cdda2e
13 changed files with 153 additions and 157 deletions

19
core/index.d.ts vendored
View file

@ -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[];

View file

@ -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(

View file

@ -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,
};
}

View file

@ -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<RootState, ToolCallState | undefined>(
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 ? (
<div>
{item.message.toolCalls?.map((toolCall) => {
return (
<ToolCallDiv
toolCall={toolCall as any}
acceptedToolCall={item.acceptedToolCall}
status={item.toolCallState!.status}
/>
);
})}
@ -431,9 +433,7 @@ export function Chat() {
)}
</div>
{toolCallState.currentToolCallState === "generated" && (
<ToolCallButtons />
)}
{toolCallState?.status === "generated" && <ToolCallButtons />}
<ContinueInputBox
isMainInput
isLastUserInput={false}

View file

@ -1,20 +1,16 @@
import { getMarkdownLanguageTagForFile } from "core/util";
import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview";
import { ToolState } from "./types";
interface CreateFileToolCallProps {
filepath: string;
fileContents: string;
state: ToolState;
}
export function CreateFile(props: CreateFileToolCallProps) {
return (
<>
<StyledMarkdownPreview
{props.fileContents}
{/* <StyledMarkdownPreview
isRenderingInStepContainer={true}
source={`\`\`\`${getMarkdownLanguageTagForFile(props.filepath ?? ".txt")} ${props.filepath}\n${props.fileContents ?? ""}\n\`\`\``}
/>
/> */}
</>
);
}

View file

@ -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 (
<CreateFile
filepath={args.filepath}
fileContents={args.contents}
state={state}
/>
<CreateFile filepath={args.filepath} fileContents={args.contents} />
);
case "run_terminal_command":
return <RunTerminalCommand command={args.command} state={state} />;
return <RunTerminalCommand command={args.command} />;
default:
return null;
}

View file

@ -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) {

View file

@ -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 (
<>
<ButtonContainer>
{toolCallState.currentToolCallState === "generating" ? (
{toolCallState.status === "generating" ? (
<div
className="flex w-full items-center justify-center gap-4"
style={{
@ -130,12 +86,12 @@ export function ToolCallButtons(props: ToolCallButtonsProps) {
>
Thinking...
</div>
) : toolCallState.currentToolCallState === "generated" ? (
) : toolCallState.status === "generated" ? (
<>
<RejectButton onClick={cancelTool}>Cancel</RejectButton>
<AcceptButton onClick={callTool}>Continue</AcceptButton>
</>
) : toolCallState.currentToolCallState === "calling" ? (
) : toolCallState.status === "calling" ? (
<div className="ml-auto flex items-center gap-4">
Loading...
<Spinner />

View file

@ -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 <CheckIcon className="text-green-500" color={lightGray} />;
} else if (props.acceptedToolCall === false) {
return <XMarkIcon className="text-red-500" />;
}
switch (state) {
case "generating":
@ -65,15 +48,9 @@ export function ToolCallDiv(props: ToolCallDivProps) {
}
return (
<ThreadDiv
icon={getIcon(toolCallState.currentToolCallState)}
toolCall={props.toolCall}
>
{toolCallState.currentToolCallState}
<FunctionSpecificToolCallDiv
toolCall={props.toolCall}
state={toolCallState.currentToolCallState}
/>
<ThreadDiv icon={getIcon(props.status)} toolCall={props.toolCall}>
{props.status}
<FunctionSpecificToolCallDiv toolCall={props.toolCall} />
</ThreadDiv>
);
}

View file

@ -1,6 +0,0 @@
export type ToolState =
| "generating"
| "generated"
| "calling"
| "done"
| "canceled";

View file

@ -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);
},
);

View file

@ -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<string>) => {
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<ToolCall>) => {
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;

View file

@ -0,0 +1,20 @@
import { ToolCallState } from "core";
import { RootState } from "../store";
function findLast<T>(
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;
}