migrate useChatHandler to async thunks
This commit is contained in:
parent
942fd9fa4e
commit
79d9148322
17 changed files with 707 additions and 578 deletions
35
gui/package-lock.json
generated
35
gui/package-lock.json
generated
|
|
@ -47,6 +47,7 @@
|
|||
"react-tooltip": "^5.18.0",
|
||||
"redux-persist": "^6.0.0",
|
||||
"redux-persist-transform-filter": "^0.0.22",
|
||||
"redux-thunk": "^3.1.0",
|
||||
"rehype-highlight": "^7.0.0",
|
||||
"rehype-katex": "^7.0.0",
|
||||
"rehype-wrap-all": "^1.1.0",
|
||||
|
|
@ -1536,6 +1537,22 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@reduxjs/toolkit/node_modules/redux": {
|
||||
"version": "4.2.1",
|
||||
"resolved": "https://registry.npmjs.org/redux/-/redux-4.2.1.tgz",
|
||||
"integrity": "sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.9.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@reduxjs/toolkit/node_modules/redux-thunk": {
|
||||
"version": "2.4.2",
|
||||
"resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-2.4.2.tgz",
|
||||
"integrity": "sha512-+P3TjtnP0k/FEjcBL5FZpoovtvrTNT/UXd4/sluaSyrURlSlhLSzEdfsTBW7WsKB6yPvgd7q/iZPICFjW4o57Q==",
|
||||
"peerDependencies": {
|
||||
"redux": "^4"
|
||||
}
|
||||
},
|
||||
"node_modules/@reduxjs/toolkit/node_modules/reselect": {
|
||||
"version": "4.1.8",
|
||||
"resolved": "https://registry.npmjs.org/reselect/-/reselect-4.1.8.tgz",
|
||||
|
|
@ -8025,12 +8042,10 @@
|
|||
}
|
||||
},
|
||||
"node_modules/redux": {
|
||||
"version": "4.2.1",
|
||||
"resolved": "https://registry.npmjs.org/redux/-/redux-4.2.1.tgz",
|
||||
"integrity": "sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.9.2"
|
||||
}
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
|
||||
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/redux-persist": {
|
||||
"version": "6.0.0",
|
||||
|
|
@ -8053,11 +8068,11 @@
|
|||
}
|
||||
},
|
||||
"node_modules/redux-thunk": {
|
||||
"version": "2.4.2",
|
||||
"resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-2.4.2.tgz",
|
||||
"integrity": "sha512-+P3TjtnP0k/FEjcBL5FZpoovtvrTNT/UXd4/sluaSyrURlSlhLSzEdfsTBW7WsKB6yPvgd7q/iZPICFjW4o57Q==",
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz",
|
||||
"integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==",
|
||||
"peerDependencies": {
|
||||
"redux": "^4"
|
||||
"redux": "^5.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/refractor": {
|
||||
|
|
|
|||
|
|
@ -55,6 +55,7 @@
|
|||
"react-tooltip": "^5.18.0",
|
||||
"redux-persist": "^6.0.0",
|
||||
"redux-persist-transform-filter": "^0.0.22",
|
||||
"redux-thunk": "^3.1.0",
|
||||
"rehype-highlight": "^7.0.0",
|
||||
"rehype-katex": "^7.0.0",
|
||||
"rehype-wrap-all": "^1.1.0",
|
||||
|
|
|
|||
|
|
@ -1,507 +0,0 @@
|
|||
import { Dispatch } from "@reduxjs/toolkit";
|
||||
import { JSONContent } from "@tiptap/react";
|
||||
import {
|
||||
ChatHistory,
|
||||
ChatHistoryItem,
|
||||
ChatMessage,
|
||||
ContextItem,
|
||||
ContextItemWithId,
|
||||
InputModifiers,
|
||||
MessageContent,
|
||||
PromptLog,
|
||||
RangeInFile,
|
||||
SlashCommandDescription,
|
||||
} from "core";
|
||||
import { constructMessages } from "core/llm/constructMessages";
|
||||
import { allTools } from "core/tools";
|
||||
import { getBasename, getRelativePath } from "core/util";
|
||||
import {
|
||||
renderChatMessage,
|
||||
renderContextItems,
|
||||
} from "core/util/messageContent";
|
||||
import { usePostHog } from "posthog-js/react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useSelector } from "react-redux";
|
||||
import resolveEditorContent, {
|
||||
hasSlashCommandOrContextProvider,
|
||||
} from "../components/mainInput/resolveInput";
|
||||
import { IIdeMessenger } from "../context/IdeMessenger";
|
||||
import { defaultModelSelector } from "../redux/selectors/modelSelectors";
|
||||
import { selectCurrentToolCall } from "../redux/selectors/selectCurrentToolCall";
|
||||
import {
|
||||
abortStream,
|
||||
acceptToolCall,
|
||||
addContextItemsAtIndex,
|
||||
addPromptCompletionPair,
|
||||
clearLastEmptyResponse,
|
||||
initNewActiveMessage,
|
||||
resetNextCodeBlockToApplyIndex,
|
||||
resubmitAtIndex,
|
||||
setActive,
|
||||
setCalling,
|
||||
setCurCheckpointIndex,
|
||||
setInactive,
|
||||
setIsGatheringContext,
|
||||
setMessageAtIndex,
|
||||
streamUpdate,
|
||||
} from "../redux/slices/stateSlice";
|
||||
import { RootState } from "../redux/store";
|
||||
import { updateFileSymbolsFromContextItems } from "../util/symbols";
|
||||
import useHistory from "./useHistory";
|
||||
|
||||
function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
|
||||
const posthog = usePostHog();
|
||||
|
||||
const defaultModel = useSelector(defaultModelSelector);
|
||||
const defaultContextProviders = useSelector(
|
||||
(store: RootState) => store.state.config.experimental?.defaultContext ?? [],
|
||||
);
|
||||
|
||||
const slashCommands = useSelector(
|
||||
(store: RootState) => store.state.config.slashCommands || [],
|
||||
);
|
||||
|
||||
const history = useSelector((store: RootState) => store.state.history);
|
||||
const active = useSelector((store: RootState) => store.state.active);
|
||||
const streamAborter = useSelector(
|
||||
(store: RootState) => store.state.streamAborter,
|
||||
);
|
||||
const useTools = useSelector((store: RootState) => store.uiState.useTools);
|
||||
const toolSettings = useSelector(
|
||||
(store: RootState) => store.uiState.toolSettings,
|
||||
);
|
||||
const toolCallState = useSelector(selectCurrentToolCall);
|
||||
|
||||
const activeRef = useRef(active);
|
||||
|
||||
const { saveSession } = useHistory(dispatch);
|
||||
const [save, triggerSave] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
saveSession(false);
|
||||
}, [save]);
|
||||
|
||||
useEffect(() => {
|
||||
activeRef.current = active;
|
||||
}, [active]);
|
||||
|
||||
async function _streamNormalInput(messages: ChatMessage[]) {
|
||||
try {
|
||||
if (!defaultModel) {
|
||||
throw new Error("Default model not defined");
|
||||
}
|
||||
const gen = ideMessenger.llmStreamChat(
|
||||
defaultModel.title,
|
||||
streamAborter.signal,
|
||||
messages,
|
||||
{
|
||||
tools: useTools
|
||||
? Object.keys(toolSettings)
|
||||
.filter((tool) => toolSettings[tool] !== "disabled")
|
||||
.map((toolName) =>
|
||||
allTools.find((tool) => tool.function.name === toolName),
|
||||
)
|
||||
: undefined,
|
||||
},
|
||||
);
|
||||
let next = await gen.next();
|
||||
|
||||
while (!next.done) {
|
||||
if (!activeRef.current) {
|
||||
dispatch(abortStream());
|
||||
break;
|
||||
}
|
||||
dispatch(streamUpdate(next.value as ChatMessage));
|
||||
next = await gen.next();
|
||||
}
|
||||
|
||||
let returnVal = next.value as PromptLog;
|
||||
if (returnVal) {
|
||||
dispatch(addPromptCompletionPair([returnVal]));
|
||||
}
|
||||
|
||||
// If it's a tool call that is automatically accepted, we should call it
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
if (
|
||||
toolCallState &&
|
||||
toolCallState.status === "generated" &&
|
||||
toolSettings[toolCallState.toolCall.function.name] ===
|
||||
"allowedWithoutPermission"
|
||||
) {
|
||||
await callTool();
|
||||
}
|
||||
} catch (e) {
|
||||
// If there's an error, we should clear the response so there aren't two input boxes
|
||||
dispatch(clearLastEmptyResponse());
|
||||
}
|
||||
}
|
||||
|
||||
const getSlashCommandForInput = (
|
||||
input: MessageContent,
|
||||
): [SlashCommandDescription, string] | undefined => {
|
||||
let slashCommand: SlashCommandDescription | undefined;
|
||||
let slashCommandName: string | undefined;
|
||||
|
||||
let lastText =
|
||||
typeof input === "string"
|
||||
? input
|
||||
: input.filter((part) => part.type === "text").slice(-1)[0]?.text || "";
|
||||
|
||||
if (lastText.startsWith("/")) {
|
||||
slashCommandName = lastText.split(" ")[0].substring(1);
|
||||
slashCommand = slashCommands.find(
|
||||
(command) => command.name === slashCommandName,
|
||||
);
|
||||
}
|
||||
if (!slashCommand || !slashCommandName) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Convert to actual slash command object with runnable function
|
||||
return [slashCommand, renderChatMessage({ role: "user", content: input })];
|
||||
};
|
||||
|
||||
async function _streamSlashCommand(
|
||||
messages: ChatMessage[],
|
||||
slashCommand: SlashCommandDescription,
|
||||
input: string,
|
||||
historyIndex: number,
|
||||
selectedCode: RangeInFile[],
|
||||
contextItems: ContextItemWithId[],
|
||||
) {
|
||||
if (!defaultModel) {
|
||||
throw new Error("Default model not defined");
|
||||
}
|
||||
|
||||
const modelTitle = defaultModel.title;
|
||||
|
||||
const checkActiveInterval = setInterval(() => {
|
||||
if (!activeRef.current) {
|
||||
dispatch(abortStream());
|
||||
clearInterval(checkActiveInterval);
|
||||
}
|
||||
}, 100);
|
||||
|
||||
for await (const update of ideMessenger.streamRequest(
|
||||
"command/run",
|
||||
{
|
||||
input,
|
||||
history: messages,
|
||||
modelTitle,
|
||||
slashCommandName: slashCommand.name,
|
||||
contextItems,
|
||||
params: slashCommand.params,
|
||||
historyIndex,
|
||||
selectedCode,
|
||||
},
|
||||
streamAborter.signal,
|
||||
)) {
|
||||
if (!activeRef.current) {
|
||||
dispatch(abortStream());
|
||||
break;
|
||||
}
|
||||
if (typeof update === "string") {
|
||||
dispatch(streamUpdate(update));
|
||||
}
|
||||
}
|
||||
clearInterval(checkActiveInterval);
|
||||
}
|
||||
|
||||
function resetStateForNewMessage() {
|
||||
// Reset current code block index
|
||||
dispatch(resetNextCodeBlockToApplyIndex());
|
||||
}
|
||||
|
||||
async function gatherContext(
|
||||
editorState: JSONContent,
|
||||
modifiers: InputModifiers,
|
||||
ideMessenger: IIdeMessenger,
|
||||
promptPreamble?: string,
|
||||
) {
|
||||
// Resolve context providers and construct new history
|
||||
const shouldGatherContext =
|
||||
modifiers.useCodebase || hasSlashCommandOrContextProvider(editorState);
|
||||
|
||||
if (shouldGatherContext) {
|
||||
dispatch(
|
||||
setIsGatheringContext({
|
||||
isGathering: true,
|
||||
gatheringMessage: "Gathering Context",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
let [selectedContextItems, selectedCode, content] =
|
||||
await resolveEditorContent(
|
||||
editorState,
|
||||
modifiers,
|
||||
ideMessenger,
|
||||
defaultContextProviders,
|
||||
dispatch,
|
||||
);
|
||||
|
||||
// Automatically use currently open file
|
||||
if (!modifiers.noContext) {
|
||||
const usingFreeTrial = defaultModel?.provider === "free-trial";
|
||||
|
||||
const currentFile = await ideMessenger.ide.getCurrentFile();
|
||||
if (currentFile) {
|
||||
let currentFileContents = currentFile.contents;
|
||||
if (usingFreeTrial) {
|
||||
currentFileContents = currentFile.contents
|
||||
.split("\n")
|
||||
.slice(0, 1000)
|
||||
.join("\n");
|
||||
}
|
||||
if (
|
||||
!selectedContextItems.find(
|
||||
(item) => item.uri?.value === currentFile.path,
|
||||
)
|
||||
) {
|
||||
// don't add the file if it's already in the context items
|
||||
selectedContextItems.unshift({
|
||||
content: `The following file is currently open. Don't reference it if it's not relevant to the user's message.\n\n\`\`\`${getRelativePath(
|
||||
currentFile.path,
|
||||
await ideMessenger.ide.getWorkspaceDirs(),
|
||||
)}\n${currentFileContents}\n\`\`\``,
|
||||
name: `Active file: ${getBasename(currentFile.path)}`,
|
||||
description: currentFile.path,
|
||||
id: {
|
||||
itemId: currentFile.path,
|
||||
providerTitle: "file",
|
||||
},
|
||||
uri: {
|
||||
type: "file",
|
||||
value: currentFile.path,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await updateFileSymbolsFromContextItems(
|
||||
selectedContextItems,
|
||||
ideMessenger,
|
||||
dispatch,
|
||||
);
|
||||
|
||||
if (promptPreamble) {
|
||||
typeof content === "string"
|
||||
? (content += promptPreamble)
|
||||
: (content.at(-1).text += promptPreamble);
|
||||
}
|
||||
|
||||
// dispatch(addContextItems(contextItems));
|
||||
return { selectedContextItems, selectedCode, content };
|
||||
}
|
||||
|
||||
async function handleErrors(runStream: () => any): Promise<void> {
|
||||
try {
|
||||
await runStream();
|
||||
} catch (e: any) {
|
||||
console.debug("Error streaming response: ", e);
|
||||
ideMessenger.post("showToast", [
|
||||
"error",
|
||||
`Error streaming response: ${e.message}`,
|
||||
]);
|
||||
} finally {
|
||||
dispatch(setInactive());
|
||||
triggerSave(!save);
|
||||
}
|
||||
}
|
||||
|
||||
async function streamResponseWithoutErrorHandling(
|
||||
editorState: JSONContent,
|
||||
modifiers: InputModifiers,
|
||||
ideMessenger: IIdeMessenger,
|
||||
index?: number,
|
||||
promptPreamble?: string,
|
||||
) {
|
||||
if (typeof index === "number") {
|
||||
dispatch(resubmitAtIndex({ index, editorState }));
|
||||
} else {
|
||||
dispatch(initNewActiveMessage({ editorState }));
|
||||
}
|
||||
|
||||
resetStateForNewMessage();
|
||||
|
||||
if (index) {
|
||||
dispatch(setCurCheckpointIndex(Math.floor(index / 2)));
|
||||
}
|
||||
|
||||
const { selectedContextItems, selectedCode, content } = await gatherContext(
|
||||
editorState,
|
||||
modifiers,
|
||||
ideMessenger,
|
||||
promptPreamble,
|
||||
);
|
||||
|
||||
const message: ChatMessage = {
|
||||
role: "user",
|
||||
content,
|
||||
};
|
||||
|
||||
const historyItem: ChatHistoryItem = {
|
||||
message,
|
||||
contextItems: selectedContextItems,
|
||||
editorState,
|
||||
};
|
||||
|
||||
let newHistory: ChatHistory = [...history.slice(0, index), historyItem];
|
||||
const historyIndex = index || newHistory.length - 1;
|
||||
dispatch(
|
||||
setMessageAtIndex({
|
||||
message,
|
||||
index: historyIndex,
|
||||
contextItems: selectedContextItems,
|
||||
}),
|
||||
);
|
||||
|
||||
// TODO: hacky way to allow rerender
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
posthog.capture("step run", {
|
||||
step_name: "User Input",
|
||||
params: {},
|
||||
});
|
||||
posthog.capture("userInput", {});
|
||||
|
||||
const messages = constructMessages(newHistory, defaultModel.model);
|
||||
|
||||
// Determine if the input is a slash command
|
||||
let commandAndInput = getSlashCommandForInput(content);
|
||||
|
||||
if (!commandAndInput) {
|
||||
await _streamNormalInput(messages);
|
||||
} else {
|
||||
const [slashCommand, commandInput] = commandAndInput;
|
||||
let updatedContextItems = [];
|
||||
posthog.capture("step run", {
|
||||
step_name: slashCommand.name,
|
||||
params: {},
|
||||
});
|
||||
|
||||
// if (slashCommand.name === "multifile-edit") {
|
||||
// dispatch(setIsInMultifileEdit(true));
|
||||
// }
|
||||
|
||||
await _streamSlashCommand(
|
||||
messages,
|
||||
slashCommand,
|
||||
commandInput,
|
||||
historyIndex,
|
||||
selectedCode,
|
||||
updatedContextItems,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function streamResponse(
|
||||
editorState: JSONContent,
|
||||
modifiers: InputModifiers,
|
||||
ideMessenger: IIdeMessenger,
|
||||
index?: number,
|
||||
promptPreamble?: string,
|
||||
) {
|
||||
await handleErrors(() =>
|
||||
streamResponseWithoutErrorHandling(
|
||||
editorState,
|
||||
modifiers,
|
||||
ideMessenger,
|
||||
index,
|
||||
promptPreamble,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function streamResponseAfterToolCall(
|
||||
toolCallId: string,
|
||||
toolOutput: ContextItem[],
|
||||
) {
|
||||
await handleErrors(async () => {
|
||||
resetStateForNewMessage();
|
||||
|
||||
dispatch(acceptToolCall());
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
const newMessage: ChatMessage = {
|
||||
role: "tool",
|
||||
content: renderContextItems(toolOutput),
|
||||
toolCallId,
|
||||
};
|
||||
|
||||
dispatch(streamUpdate(newMessage));
|
||||
dispatch(
|
||||
addContextItemsAtIndex({
|
||||
index: history.length,
|
||||
contextItems: toolOutput.map((contextItem) => ({
|
||||
...contextItem,
|
||||
id: {
|
||||
providerTitle: "toolCall",
|
||||
itemId: toolCallId,
|
||||
},
|
||||
})),
|
||||
}),
|
||||
);
|
||||
activeRef.current = true;
|
||||
dispatch(setActive());
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
const messages = constructMessages(
|
||||
[
|
||||
...history,
|
||||
{
|
||||
message: newMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
],
|
||||
defaultModel.model,
|
||||
);
|
||||
await _streamNormalInput(messages);
|
||||
});
|
||||
}
|
||||
|
||||
async function callTool() {
|
||||
console.log("calling tool", toolCallState.toolCall);
|
||||
if (!toolCallState) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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,
|
||||
};
|
||||
}
|
||||
|
||||
export default useChatHandler;
|
||||
|
|
@ -1,5 +1,4 @@
|
|||
import { Dispatch } from "@reduxjs/toolkit";
|
||||
import { useCallback, useContext, useEffect, useRef, useState } from "react";
|
||||
import { useCallback, useContext, useEffect, useRef } from "react";
|
||||
import { useSelector } from "react-redux";
|
||||
import { VSC_THEME_COLOR_VARS } from "../components";
|
||||
import { IdeMessengerContext } from "../context/IdeMessenger";
|
||||
|
|
@ -13,16 +12,15 @@ import {
|
|||
setTTSActive,
|
||||
updateIndexingStatus,
|
||||
} from "../redux/slices/stateSlice";
|
||||
import { RootState } from "../redux/store";
|
||||
import { AppDispatch, RootState } from "../redux/store";
|
||||
|
||||
import { debounce } from "lodash";
|
||||
import { streamResponseThunk } from "../redux/thunks/streamResponse";
|
||||
import { isJetBrains } from "../util";
|
||||
import { getLocalStorage, setLocalStorage } from "../util/localStorage";
|
||||
import useChatHandler from "./useChatHandler";
|
||||
import { useWebviewListener } from "./useWebviewListener";
|
||||
import { setLocalStorage } from "../util/localStorage";
|
||||
import { updateFileSymbolsFromContextItems } from "../util/symbols";
|
||||
import { useWebviewListener } from "./useWebviewListener";
|
||||
|
||||
function useSetup(dispatch: Dispatch) {
|
||||
function useSetup(dispatch: AppDispatch) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const history = useSelector((store: RootState) => store.state.history);
|
||||
|
||||
|
|
@ -115,8 +113,6 @@ function useSetup(dispatch: Dispatch) {
|
|||
}
|
||||
}, []);
|
||||
|
||||
const { streamResponse } = useChatHandler(dispatch, ideMessenger);
|
||||
|
||||
const defaultModelTitle = useSelector(
|
||||
(store: RootState) => store.state.defaultModelTitle,
|
||||
);
|
||||
|
|
@ -151,10 +147,11 @@ function useSetup(dispatch: Dispatch) {
|
|||
|
||||
// TODO - remove?
|
||||
useWebviewListener("submitMessage", async (data) => {
|
||||
streamResponse(
|
||||
data.message,
|
||||
{ useCodebase: false, noContext: true },
|
||||
ideMessenger,
|
||||
dispatch(
|
||||
streamResponseThunk({
|
||||
editorState: data.message,
|
||||
modifiers: { useCodebase: false, noContext: true },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -178,8 +175,6 @@ function useSetup(dispatch: Dispatch) {
|
|||
},
|
||||
[defaultModelTitle],
|
||||
);
|
||||
|
||||
|
||||
}
|
||||
|
||||
export default useSetup;
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { Editor, JSONContent } from "@tiptap/core";
|
|||
import { InputModifiers, RangeInFileWithContents } from "core";
|
||||
import { stripImages } from "core/util/messageContent";
|
||||
import { useCallback, useContext, useEffect } from "react";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { useSelector } from "react-redux";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import ContinueInputBox from "../../components/mainInput/ContinueInputBox";
|
||||
import { NewSessionButton } from "../../components/mainInput/NewSessionButton";
|
||||
|
|
@ -12,13 +12,13 @@ import TipTapEditor from "../../components/mainInput/TipTapEditor";
|
|||
import StepContainer from "../../components/StepContainer";
|
||||
import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import useChatHandler from "../../hooks/useChatHandler";
|
||||
import {
|
||||
clearCodeToEdit,
|
||||
setEditDone,
|
||||
submitEdit,
|
||||
} from "../../redux/slices/editModeState";
|
||||
import { RootState } from "../../redux/store";
|
||||
import { RootState, useAppDispatch } from "../../redux/store";
|
||||
import { streamResponseThunk } from "../../redux/thunks/streamResponse";
|
||||
import CodeToEdit from "./CodeToEdit";
|
||||
import getMultifileEditPrompt from "./getMultifileEditPrompt";
|
||||
|
||||
|
|
@ -35,10 +35,9 @@ const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [
|
|||
];
|
||||
|
||||
export default function Edit() {
|
||||
const dispatch = useDispatch();
|
||||
const dispatch = useAppDispatch();
|
||||
const navigate = useNavigate();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const { streamResponse } = useChatHandler(dispatch, ideMessenger);
|
||||
const editModeState = useSelector((state: RootState) => state.editModeState);
|
||||
const availableContextProviders = useSelector(
|
||||
(store: RootState) => store.state.config.contextProviders,
|
||||
|
|
@ -138,12 +137,12 @@ export default function Edit() {
|
|||
} else {
|
||||
const promptPreamble = getMultifileEditPrompt(editModeState.codeToEdit);
|
||||
|
||||
streamResponse(
|
||||
editorState,
|
||||
modifiers,
|
||||
ideMessenger,
|
||||
undefined,
|
||||
promptPreamble,
|
||||
dispatch(
|
||||
streamResponseThunk({
|
||||
editorState,
|
||||
modifiers,
|
||||
promptPreamble,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -184,11 +183,12 @@ export default function Edit() {
|
|||
{item.message.role === "user" ? (
|
||||
<ContinueInputBox
|
||||
onEnter={async (editorState, modifiers) => {
|
||||
streamResponse(
|
||||
editorState,
|
||||
modifiers,
|
||||
ideMessenger,
|
||||
index,
|
||||
dispatch(
|
||||
streamResponseThunk({
|
||||
editorState,
|
||||
modifiers,
|
||||
index,
|
||||
}),
|
||||
);
|
||||
}}
|
||||
isLastUserInput={isLastUserInput(index)}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ 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";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { useSelector } from "react-redux";
|
||||
import styled from "styled-components";
|
||||
import {
|
||||
Button,
|
||||
|
|
@ -30,7 +30,6 @@ import {
|
|||
} from "../../components/OnboardingCard";
|
||||
import StepContainer from "../../components/StepContainer";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import useChatHandler from "../../hooks/useChatHandler";
|
||||
import useHistory from "../../hooks/useHistory";
|
||||
import { useTutorialCard } from "../../hooks/useTutorialCard";
|
||||
import { useWebviewListener } from "../../hooks/useWebviewListener";
|
||||
|
|
@ -46,7 +45,8 @@ import {
|
|||
setDialogMessage,
|
||||
setShowDialog,
|
||||
} from "../../redux/slices/uiStateSlice";
|
||||
import { RootState } from "../../redux/store";
|
||||
import { RootState, useAppDispatch } from "../../redux/store";
|
||||
import { streamResponseThunk } from "../../redux/thunks/streamResponse";
|
||||
import {
|
||||
getFontSize,
|
||||
getMetaKeyLabel,
|
||||
|
|
@ -117,9 +117,8 @@ function fallbackRender({ error, resetErrorBoundary }: any) {
|
|||
|
||||
export function Chat() {
|
||||
const posthog = usePostHog();
|
||||
const dispatch = useDispatch();
|
||||
const dispatch = useAppDispatch();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const { streamResponse } = useChatHandler(dispatch, ideMessenger);
|
||||
const onboardingCard = useOnboardingCard();
|
||||
const { showTutorialCard, closeTutorialCard } = useTutorialCard();
|
||||
const defaultModel = useSelector(defaultModelSelector);
|
||||
|
|
@ -219,7 +218,7 @@ export function Chat() {
|
|||
}
|
||||
}
|
||||
|
||||
streamResponse(editorState, modifiers, ideMessenger);
|
||||
dispatch(streamResponseThunk({ editorState, modifiers }));
|
||||
|
||||
// Increment localstorage counter for popup
|
||||
const currentCount = getLocalStorage("mainTextEntryCounter");
|
||||
|
|
@ -291,7 +290,7 @@ export function Chat() {
|
|||
setLocalStorage("mainTextEntryCounter", 1);
|
||||
}
|
||||
},
|
||||
[state.history, defaultModel, state, streamResponse],
|
||||
[state.history, defaultModel, state],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
|
|
@ -340,7 +339,9 @@ export function Chat() {
|
|||
{item.message.role === "user" ? (
|
||||
<ContinueInputBox
|
||||
onEnter={async (editorState, modifiers) => {
|
||||
streamResponse(editorState, modifiers, ideMessenger, index);
|
||||
dispatch(
|
||||
streamResponseThunk({ editorState, modifiers, index }),
|
||||
);
|
||||
}}
|
||||
isLastUserInput={isLastUserInput(index)}
|
||||
isMainInput={false}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { useContext } from "react";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { useSelector } from "react-redux";
|
||||
import styled from "styled-components";
|
||||
import {
|
||||
defaultBorderRadius,
|
||||
|
|
@ -9,9 +9,11 @@ import {
|
|||
} from "../../../components";
|
||||
import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner";
|
||||
import { IdeMessengerContext } from "../../../context/IdeMessenger";
|
||||
import useChatHandler from "../../../hooks/useChatHandler";
|
||||
import { selectCurrentToolCall } from "../../../redux/selectors/selectCurrentToolCall";
|
||||
import { cancelToolCall } from "../../../redux/slices/stateSlice";
|
||||
import { useAppDispatch } from "../../../redux/store";
|
||||
import { callTool } from "../../../redux/thunks/callTool";
|
||||
import { streamResponseAfterToolCall } from "../../../redux/thunks/streamResponseAfterToolCall";
|
||||
|
||||
const ButtonContainer = styled.div`
|
||||
display: flex;
|
||||
|
|
@ -51,26 +53,26 @@ const RejectButton = styled(Button)`
|
|||
interface ToolCallButtonsProps {}
|
||||
|
||||
export function ToolCallButtons(props: ToolCallButtonsProps) {
|
||||
const dispatch = useDispatch();
|
||||
const dispatch = useAppDispatch();
|
||||
const toolCallState = useSelector(selectCurrentToolCall);
|
||||
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
const { streamResponseAfterToolCall, callTool } = useChatHandler(
|
||||
dispatch,
|
||||
ideMessenger,
|
||||
);
|
||||
|
||||
async function cancelTool() {
|
||||
dispatch(cancelToolCall());
|
||||
streamResponseAfterToolCall(toolCallState.toolCallId, [
|
||||
{
|
||||
name: "Cancelled",
|
||||
description: "Cancelled",
|
||||
content:
|
||||
"This tool call was cancelled by the user. You should try something else, likely just chatting instead of using another tool.",
|
||||
},
|
||||
]);
|
||||
dispatch(
|
||||
streamResponseAfterToolCall({
|
||||
toolCallId: toolCallState.toolCallId,
|
||||
toolOutput: [
|
||||
{
|
||||
name: "Cancelled",
|
||||
description: "Cancelled",
|
||||
content:
|
||||
"This tool call was cancelled by the user. You should try something else, likely just chatting instead of using another tool.",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (!toolCallState) {
|
||||
|
|
@ -93,7 +95,9 @@ export function ToolCallButtons(props: ToolCallButtonsProps) {
|
|||
) : toolCallState.status === "generated" ? (
|
||||
<>
|
||||
<RejectButton onClick={cancelTool}>Cancel</RejectButton>
|
||||
<AcceptButton onClick={callTool}>Continue</AcceptButton>
|
||||
<AcceptButton onClick={() => dispatch(callTool())}>
|
||||
Continue
|
||||
</AcceptButton>
|
||||
</>
|
||||
) : toolCallState.status === "calling" ? (
|
||||
<div className="ml-auto flex items-center gap-4">
|
||||
|
|
|
|||
|
|
@ -1,4 +1,9 @@
|
|||
import { PayloadAction, createSlice } from "@reduxjs/toolkit";
|
||||
import {
|
||||
ActionReducerMapBuilder,
|
||||
AsyncThunk,
|
||||
PayloadAction,
|
||||
createSlice,
|
||||
} from "@reduxjs/toolkit";
|
||||
import { JSONContent } from "@tiptap/react";
|
||||
import {
|
||||
ApplyState,
|
||||
|
|
@ -16,6 +21,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 { streamResponseThunk } from "../thunks/streamResponse";
|
||||
import { findCurrentToolCall } from "../util";
|
||||
|
||||
// We need this to handle reorderings (e.g. a mid-array deletion) of the messages array.
|
||||
|
|
@ -518,8 +524,23 @@ export const stateSlice = createSlice({
|
|||
};
|
||||
},
|
||||
},
|
||||
|
||||
extraReducers: (builder) => {
|
||||
addPassthroughCases(builder, [streamResponseThunk]);
|
||||
},
|
||||
});
|
||||
|
||||
function addPassthroughCases(
|
||||
builder: ActionReducerMapBuilder<State>,
|
||||
thunks: AsyncThunk<any, any, any>[],
|
||||
) {
|
||||
thunks.forEach((thunk) => {
|
||||
builder
|
||||
.addCase(thunk.fulfilled, (state, action) => {})
|
||||
.addCase(thunk.rejected, (state, action) => {})
|
||||
.addCase(thunk.pending, (state, action) => {});
|
||||
});
|
||||
}
|
||||
export const {
|
||||
updateFileSymbols,
|
||||
setContextItemsAtIndex,
|
||||
|
|
|
|||
|
|
@ -5,10 +5,12 @@ import serverStateReducer from "./slices/serverStateReducer";
|
|||
import stateReducer from "./slices/stateSlice";
|
||||
import uiStateReducer from "./slices/uiStateSlice";
|
||||
|
||||
import { useDispatch } from "react-redux";
|
||||
import { createTransform, persistReducer, persistStore } from "redux-persist";
|
||||
import { createFilter } from "redux-persist-transform-filter";
|
||||
import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2";
|
||||
import storage from "redux-persist/lib/storage";
|
||||
import { IdeMessenger, IIdeMessenger } from "../context/IdeMessenger";
|
||||
import editModeStateReducer from "./slices/editModeState";
|
||||
export interface ChatMessage {
|
||||
role: "system" | "user" | "assistant";
|
||||
|
|
@ -24,8 +26,6 @@ const rootReducer = combineReducers({
|
|||
editModeState: editModeStateReducer,
|
||||
});
|
||||
|
||||
export type RootState = ReturnType<typeof rootReducer>;
|
||||
|
||||
const windowIDTransform = (windowID: string) =>
|
||||
createTransform(
|
||||
// transform state on its way to being serialized and persisted.
|
||||
|
|
@ -56,15 +56,32 @@ const persistedReducer = persistReducer(persistConfig, rootReducer);
|
|||
|
||||
export function setupStore() {
|
||||
return configureStore({
|
||||
reducer: persistedReducer,
|
||||
// persistedReducer causes type errors with async thunks
|
||||
reducer: persistedReducer as unknown as typeof rootReducer,
|
||||
// reducer: rootReducer,
|
||||
middleware: (getDefaultMiddleware) =>
|
||||
getDefaultMiddleware({
|
||||
serializableCheck: false,
|
||||
thunk: {
|
||||
extraArgument: {
|
||||
ideMessenger: new IdeMessenger(),
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export type ThunkApiType = {
|
||||
state: RootState;
|
||||
extra: { ideMessenger: IIdeMessenger };
|
||||
};
|
||||
|
||||
export const store = setupStore();
|
||||
|
||||
export type RootState = ReturnType<typeof rootReducer>;
|
||||
|
||||
export type AppDispatch = typeof store.dispatch;
|
||||
|
||||
export const useAppDispatch = () => useDispatch<AppDispatch>();
|
||||
|
||||
export const persistor = persistStore(store);
|
||||
|
|
|
|||
50
gui/src/redux/thunks/callTool.ts
Normal file
50
gui/src/redux/thunks/callTool.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import { createAsyncThunk } from "@reduxjs/toolkit";
|
||||
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
|
||||
import { setCalling } from "../slices/stateSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
|
||||
|
||||
export const callTool = createAsyncThunk<void, undefined, ThunkApiType>(
|
||||
"chat/callTool",
|
||||
async (_, { dispatch, extra, getState }) => {
|
||||
const state = getState();
|
||||
const toolCallState = selectCurrentToolCall(state);
|
||||
|
||||
console.log("calling tool", toolCallState.toolCall);
|
||||
if (!toolCallState) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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 extra.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
|
||||
dispatch(
|
||||
streamResponseAfterToolCall({
|
||||
toolCallId: toolCallState.toolCall.id,
|
||||
toolOutput: contextItems,
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
117
gui/src/redux/thunks/gatherContext.ts
Normal file
117
gui/src/redux/thunks/gatherContext.ts
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
import { createAsyncThunk } from "@reduxjs/toolkit";
|
||||
import { JSONContent } from "@tiptap/core";
|
||||
import {
|
||||
ContextItemWithId,
|
||||
InputModifiers,
|
||||
MessageContent,
|
||||
RangeInFile,
|
||||
} from "core";
|
||||
import { getBasename, getRelativePath } from "core/util";
|
||||
import resolveEditorContent, {
|
||||
hasSlashCommandOrContextProvider,
|
||||
} from "../../components/mainInput/resolveInput";
|
||||
import { updateFileSymbolsFromContextItems } from "../../util/symbols";
|
||||
import { defaultModelSelector } from "../selectors/modelSelectors";
|
||||
import { setIsGatheringContext } from "../slices/stateSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
|
||||
export const gatherContext = createAsyncThunk<
|
||||
{
|
||||
selectedContextItems: ContextItemWithId[];
|
||||
selectedCode: RangeInFile[];
|
||||
content: MessageContent;
|
||||
},
|
||||
{
|
||||
editorState: JSONContent;
|
||||
modifiers: InputModifiers;
|
||||
promptPreamble?: string;
|
||||
},
|
||||
ThunkApiType
|
||||
>(
|
||||
"chat/gatherContext",
|
||||
async (
|
||||
{ modifiers, editorState, promptPreamble },
|
||||
{ dispatch, extra, getState },
|
||||
) => {
|
||||
const state = getState();
|
||||
const defaultModel = defaultModelSelector(state);
|
||||
const defaultContextProviders =
|
||||
state.state.config.experimental?.defaultContext ?? [];
|
||||
|
||||
// Resolve context providers and construct new history
|
||||
const shouldGatherContext =
|
||||
modifiers.useCodebase || hasSlashCommandOrContextProvider(editorState);
|
||||
|
||||
if (shouldGatherContext) {
|
||||
dispatch(
|
||||
setIsGatheringContext({
|
||||
isGathering: true,
|
||||
gatheringMessage: "Gathering Context",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
let [selectedContextItems, selectedCode, content] =
|
||||
await resolveEditorContent(
|
||||
editorState,
|
||||
modifiers,
|
||||
extra.ideMessenger,
|
||||
defaultContextProviders,
|
||||
dispatch,
|
||||
);
|
||||
|
||||
// Automatically use currently open file
|
||||
if (!modifiers.noContext) {
|
||||
const usingFreeTrial = defaultModel?.provider === "free-trial";
|
||||
|
||||
const currentFile = await extra.ideMessenger.ide.getCurrentFile();
|
||||
if (currentFile) {
|
||||
let currentFileContents = currentFile.contents;
|
||||
if (usingFreeTrial) {
|
||||
currentFileContents = currentFile.contents
|
||||
.split("\n")
|
||||
.slice(0, 1000)
|
||||
.join("\n");
|
||||
}
|
||||
if (
|
||||
!selectedContextItems.find(
|
||||
(item) => item.uri?.value === currentFile.path,
|
||||
)
|
||||
) {
|
||||
// don't add the file if it's already in the context items
|
||||
selectedContextItems.unshift({
|
||||
content: `The following file is currently open. Don't reference it if it's not relevant to the user's message.\n\n\`\`\`${getRelativePath(
|
||||
currentFile.path,
|
||||
await extra.ideMessenger.ide.getWorkspaceDirs(),
|
||||
)}\n${currentFileContents}\n\`\`\``,
|
||||
name: `Active file: ${getBasename(currentFile.path)}`,
|
||||
description: currentFile.path,
|
||||
id: {
|
||||
itemId: currentFile.path,
|
||||
providerTitle: "file",
|
||||
},
|
||||
uri: {
|
||||
type: "file",
|
||||
value: currentFile.path,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await updateFileSymbolsFromContextItems(
|
||||
selectedContextItems,
|
||||
extra.ideMessenger,
|
||||
dispatch,
|
||||
);
|
||||
|
||||
if (promptPreamble) {
|
||||
typeof content === "string"
|
||||
? (content += promptPreamble)
|
||||
: (content.at(-1).text += promptPreamble);
|
||||
}
|
||||
|
||||
// dispatch(addContextItems(contextItems));
|
||||
return { selectedContextItems, selectedCode, content };
|
||||
},
|
||||
);
|
||||
22
gui/src/redux/thunks/handleErrors.ts
Normal file
22
gui/src/redux/thunks/handleErrors.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import { createAsyncThunk } from "@reduxjs/toolkit";
|
||||
import { setInactive } from "../slices/stateSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
|
||||
export const handleErrors = createAsyncThunk<
|
||||
void,
|
||||
() => Promise<void>,
|
||||
ThunkApiType
|
||||
>("chat/handleErrors", async (runStream, { dispatch, extra }) => {
|
||||
try {
|
||||
await runStream();
|
||||
} catch (e: any) {
|
||||
console.debug("Error streaming response: ", e);
|
||||
extra.ideMessenger.post("showToast", [
|
||||
"error",
|
||||
`Error streaming response: ${e.message}`,
|
||||
]);
|
||||
} finally {
|
||||
dispatch(setInactive());
|
||||
// triggerSave(!save); TODO
|
||||
}
|
||||
});
|
||||
11
gui/src/redux/thunks/resetStateForNewMessage.ts
Normal file
11
gui/src/redux/thunks/resetStateForNewMessage.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import { createAsyncThunk } from "@reduxjs/toolkit";
|
||||
import { resetNextCodeBlockToApplyIndex } from "../slices/stateSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
|
||||
export const resetStateForNewMessage = createAsyncThunk<
|
||||
void,
|
||||
undefined,
|
||||
ThunkApiType
|
||||
>("chat/resetStateForNewMessage", async (_, { dispatch }) => {
|
||||
dispatch(resetNextCodeBlockToApplyIndex());
|
||||
});
|
||||
79
gui/src/redux/thunks/streamNormalInput.ts
Normal file
79
gui/src/redux/thunks/streamNormalInput.ts
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
import { createAsyncThunk } from "@reduxjs/toolkit";
|
||||
import { ChatMessage, PromptLog } from "core";
|
||||
import { allTools } from "core/tools";
|
||||
import { defaultModelSelector } from "../selectors/modelSelectors";
|
||||
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
|
||||
import {
|
||||
abortStream,
|
||||
addPromptCompletionPair,
|
||||
clearLastEmptyResponse,
|
||||
streamUpdate,
|
||||
} from "../slices/stateSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
import { callTool } from "./callTool";
|
||||
|
||||
export const streamNormalInput = createAsyncThunk<
|
||||
void,
|
||||
ChatMessage[],
|
||||
ThunkApiType
|
||||
>("chat/streamNormalInput", async (messages, { dispatch, extra, getState }) => {
|
||||
try {
|
||||
// Gather state
|
||||
const state = getState();
|
||||
const defaultModel = defaultModelSelector(state);
|
||||
const toolSettings = state.uiState.toolSettings;
|
||||
const streamAborter = state.state.streamAborter;
|
||||
const useTools = state.uiState.useTools;
|
||||
|
||||
if (!defaultModel) {
|
||||
throw new Error("Default model not defined");
|
||||
}
|
||||
|
||||
// Send request
|
||||
const gen = extra.ideMessenger.llmStreamChat(
|
||||
defaultModel.title,
|
||||
streamAborter.signal,
|
||||
messages,
|
||||
{
|
||||
tools: useTools
|
||||
? Object.keys(toolSettings)
|
||||
.filter((tool) => toolSettings[tool] !== "disabled")
|
||||
.map((toolName) =>
|
||||
allTools.find((tool) => tool.function.name === toolName),
|
||||
)
|
||||
: undefined,
|
||||
},
|
||||
);
|
||||
|
||||
// Stream response
|
||||
let next = await gen.next();
|
||||
while (!next.done) {
|
||||
if (!getState().state.active) {
|
||||
dispatch(abortStream());
|
||||
break;
|
||||
}
|
||||
dispatch(streamUpdate(next.value as ChatMessage));
|
||||
next = await gen.next();
|
||||
}
|
||||
|
||||
// Attach prompt log
|
||||
let returnVal = next.value as PromptLog;
|
||||
if (returnVal) {
|
||||
dispatch(addPromptCompletionPair([returnVal]));
|
||||
}
|
||||
|
||||
// If it's a tool call that is automatically accepted, we should call it
|
||||
const toolCallState = selectCurrentToolCall(getState());
|
||||
if (
|
||||
toolCallState &&
|
||||
toolCallState.status === "generated" &&
|
||||
toolSettings[toolCallState.toolCall.function.name] ===
|
||||
"allowedWithoutPermission"
|
||||
) {
|
||||
await dispatch(callTool());
|
||||
}
|
||||
} catch (e) {
|
||||
// If there's an error, we should clear the response so there aren't two input boxes
|
||||
dispatch(clearLastEmptyResponse());
|
||||
}
|
||||
});
|
||||
157
gui/src/redux/thunks/streamResponse.ts
Normal file
157
gui/src/redux/thunks/streamResponse.ts
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
|
||||
import { JSONContent } from "@tiptap/core";
|
||||
import {
|
||||
ChatHistoryItem,
|
||||
ChatMessage,
|
||||
InputModifiers,
|
||||
MessageContent,
|
||||
SlashCommandDescription,
|
||||
} from "core";
|
||||
import { constructMessages } from "core/llm/constructMessages";
|
||||
import { renderChatMessage } from "core/util/messageContent";
|
||||
import posthog from "posthog-js";
|
||||
import { defaultModelSelector } from "../selectors/modelSelectors";
|
||||
import {
|
||||
initNewActiveMessage,
|
||||
resubmitAtIndex,
|
||||
setCurCheckpointIndex,
|
||||
setMessageAtIndex,
|
||||
} from "../slices/stateSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
import { gatherContext } from "./gatherContext";
|
||||
import { handleErrors } from "./handleErrors";
|
||||
import { resetStateForNewMessage } from "./resetStateForNewMessage";
|
||||
import { streamNormalInput } from "./streamNormalInput";
|
||||
import { streamSlashCommand } from "./streamSlashCommand";
|
||||
|
||||
const getSlashCommandForInput = (
|
||||
input: MessageContent,
|
||||
slashCommands: SlashCommandDescription[],
|
||||
): [SlashCommandDescription, string] | undefined => {
|
||||
let slashCommand: SlashCommandDescription | undefined;
|
||||
let slashCommandName: string | undefined;
|
||||
|
||||
let lastText =
|
||||
typeof input === "string"
|
||||
? input
|
||||
: input.filter((part) => part.type === "text").slice(-1)[0]?.text || "";
|
||||
|
||||
if (lastText.startsWith("/")) {
|
||||
slashCommandName = lastText.split(" ")[0].substring(1);
|
||||
slashCommand = slashCommands.find(
|
||||
(command) => command.name === slashCommandName,
|
||||
);
|
||||
}
|
||||
if (!slashCommand || !slashCommandName) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Convert to actual slash command object with runnable function
|
||||
return [slashCommand, renderChatMessage({ role: "user", content: input })];
|
||||
};
|
||||
|
||||
export const streamResponseThunk = createAsyncThunk<
|
||||
void,
|
||||
{
|
||||
editorState: JSONContent;
|
||||
modifiers: InputModifiers;
|
||||
index?: number;
|
||||
promptPreamble?: string;
|
||||
},
|
||||
ThunkApiType
|
||||
>(
|
||||
"chat/streamResponse",
|
||||
async (
|
||||
{ editorState, modifiers, index, promptPreamble },
|
||||
{ dispatch, extra, getState },
|
||||
) => {
|
||||
await dispatch(
|
||||
handleErrors(async () => {
|
||||
const state = getState();
|
||||
const defaultModel = defaultModelSelector(state);
|
||||
const slashCommands = state.state.config.slashCommands || [];
|
||||
const inputIndex = index ?? state.state.history.length;
|
||||
|
||||
if (typeof index === "number") {
|
||||
dispatch(resubmitAtIndex({ index, editorState }));
|
||||
} else {
|
||||
dispatch(initNewActiveMessage({ editorState }));
|
||||
}
|
||||
|
||||
resetStateForNewMessage();
|
||||
|
||||
if (index) {
|
||||
dispatch(setCurCheckpointIndex(Math.floor(index / 2)));
|
||||
}
|
||||
|
||||
const result = await dispatch(
|
||||
gatherContext({
|
||||
editorState,
|
||||
modifiers,
|
||||
promptPreamble,
|
||||
}),
|
||||
);
|
||||
const unwrapped = unwrapResult(result);
|
||||
const { selectedContextItems, selectedCode, content } = unwrapped;
|
||||
|
||||
// Add the message to the history
|
||||
const message: ChatMessage = {
|
||||
role: "user",
|
||||
content,
|
||||
};
|
||||
const historyItem: ChatHistoryItem = {
|
||||
message,
|
||||
contextItems: selectedContextItems,
|
||||
editorState,
|
||||
};
|
||||
|
||||
dispatch(
|
||||
setMessageAtIndex({
|
||||
message,
|
||||
index: inputIndex,
|
||||
contextItems: selectedContextItems,
|
||||
}),
|
||||
);
|
||||
|
||||
// Construct messages from updated history
|
||||
const updatedHistory = getState().state.history;
|
||||
const messages = constructMessages(updatedHistory, defaultModel.model);
|
||||
|
||||
posthog.capture("step run", {
|
||||
step_name: "User Input",
|
||||
params: {},
|
||||
});
|
||||
posthog.capture("userInput", {});
|
||||
|
||||
// Determine if the input is a slash command
|
||||
let commandAndInput = getSlashCommandForInput(content, slashCommands);
|
||||
|
||||
if (!commandAndInput) {
|
||||
await dispatch(streamNormalInput(messages));
|
||||
} else {
|
||||
const [slashCommand, commandInput] = commandAndInput;
|
||||
let updatedContextItems = [];
|
||||
posthog.capture("step run", {
|
||||
step_name: slashCommand.name,
|
||||
params: {},
|
||||
});
|
||||
|
||||
// if (slashCommand.name === "multifile-edit") {
|
||||
// dispatch(setIsInMultifileEdit(true));
|
||||
// }
|
||||
|
||||
await dispatch(
|
||||
streamSlashCommand({
|
||||
messages,
|
||||
slashCommand,
|
||||
input: commandInput,
|
||||
historyIndex: inputIndex,
|
||||
selectedCode,
|
||||
contextItems: updatedContextItems,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
75
gui/src/redux/thunks/streamResponseAfterToolCall.ts
Normal file
75
gui/src/redux/thunks/streamResponseAfterToolCall.ts
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
import { createAsyncThunk } from "@reduxjs/toolkit";
|
||||
import { ChatMessage, ContextItem } from "core";
|
||||
import { constructMessages } from "core/llm/constructMessages";
|
||||
import { renderContextItems } from "core/util/messageContent";
|
||||
import { defaultModelSelector } from "../selectors/modelSelectors";
|
||||
import {
|
||||
acceptToolCall,
|
||||
addContextItemsAtIndex,
|
||||
setActive,
|
||||
streamUpdate,
|
||||
} from "../slices/stateSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
import { handleErrors } from "./handleErrors";
|
||||
import { resetStateForNewMessage } from "./resetStateForNewMessage";
|
||||
import { streamNormalInput } from "./streamNormalInput";
|
||||
|
||||
export const streamResponseAfterToolCall = createAsyncThunk<
|
||||
void,
|
||||
{
|
||||
toolCallId: string;
|
||||
toolOutput: ContextItem[];
|
||||
},
|
||||
ThunkApiType
|
||||
>(
|
||||
"chat/streamAfterToolCall",
|
||||
async ({ toolCallId, toolOutput }, { dispatch, getState, extra }) => {
|
||||
await dispatch(
|
||||
handleErrors(async () => {
|
||||
const state = getState();
|
||||
const initialHistory = state.state.history;
|
||||
const defaultModel = defaultModelSelector(state);
|
||||
|
||||
resetStateForNewMessage();
|
||||
|
||||
dispatch(acceptToolCall());
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
const newMessage: ChatMessage = {
|
||||
role: "tool",
|
||||
content: renderContextItems(toolOutput),
|
||||
toolCallId,
|
||||
};
|
||||
|
||||
dispatch(streamUpdate(newMessage));
|
||||
dispatch(
|
||||
addContextItemsAtIndex({
|
||||
index: initialHistory.length,
|
||||
contextItems: toolOutput.map((contextItem) => ({
|
||||
...contextItem,
|
||||
id: {
|
||||
providerTitle: "toolCall",
|
||||
itemId: toolCallId,
|
||||
},
|
||||
})),
|
||||
}),
|
||||
);
|
||||
|
||||
dispatch(setActive());
|
||||
|
||||
const updatedHistory = getState().state.history;
|
||||
const messages = constructMessages(
|
||||
[
|
||||
...updatedHistory,
|
||||
{
|
||||
message: newMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
],
|
||||
defaultModel.model,
|
||||
);
|
||||
await dispatch(streamNormalInput(messages));
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
71
gui/src/redux/thunks/streamSlashCommand.ts
Normal file
71
gui/src/redux/thunks/streamSlashCommand.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import { createAsyncThunk } from "@reduxjs/toolkit";
|
||||
import {
|
||||
ChatMessage,
|
||||
ContextItemWithId,
|
||||
RangeInFile,
|
||||
SlashCommandDescription,
|
||||
} from "core";
|
||||
import { defaultModelSelector } from "../selectors/modelSelectors";
|
||||
import { abortStream, streamUpdate } from "../slices/stateSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
|
||||
export const streamSlashCommand = createAsyncThunk<
|
||||
void,
|
||||
{
|
||||
messages: ChatMessage[];
|
||||
slashCommand: SlashCommandDescription;
|
||||
input: string;
|
||||
historyIndex: number;
|
||||
selectedCode: RangeInFile[];
|
||||
contextItems: ContextItemWithId[];
|
||||
},
|
||||
ThunkApiType
|
||||
>(
|
||||
"chat/streamSlashCommand",
|
||||
async (
|
||||
{ messages, selectedCode, slashCommand, input, historyIndex, contextItems },
|
||||
{ dispatch, getState, extra },
|
||||
) => {
|
||||
const state = getState();
|
||||
const defaultModel = defaultModelSelector(state);
|
||||
const active = state.state.active;
|
||||
const streamAborter = state.state.streamAborter;
|
||||
|
||||
if (!defaultModel) {
|
||||
throw new Error("Default model not defined");
|
||||
}
|
||||
|
||||
const modelTitle = defaultModel.title;
|
||||
|
||||
const checkActiveInterval = setInterval(() => {
|
||||
if (!active) {
|
||||
dispatch(abortStream());
|
||||
clearInterval(checkActiveInterval);
|
||||
}
|
||||
}, 100);
|
||||
|
||||
for await (const update of extra.ideMessenger.streamRequest(
|
||||
"command/run",
|
||||
{
|
||||
input,
|
||||
history: messages,
|
||||
modelTitle,
|
||||
slashCommandName: slashCommand.name,
|
||||
contextItems,
|
||||
params: slashCommand.params,
|
||||
historyIndex,
|
||||
selectedCode,
|
||||
},
|
||||
streamAborter.signal,
|
||||
)) {
|
||||
if (!getState().state.active) {
|
||||
dispatch(abortStream());
|
||||
break;
|
||||
}
|
||||
if (typeof update === "string") {
|
||||
dispatch(streamUpdate(update));
|
||||
}
|
||||
}
|
||||
clearInterval(checkActiveInterval);
|
||||
},
|
||||
);
|
||||
Loading…
Add table
Reference in a new issue