| 1 | import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; |
| 2 | import { ChatMessage } from "core"; |
| 3 | import { constructMessages } from "core/llm/constructMessages"; |
| 4 | import { renderContextItems } from "core/util/messageContent"; |
| 5 | import { getBaseSystemMessage } from "../../util"; |
| 6 | import { selectSelectedChatModel } from "../slices/configSlice"; |
| 7 | import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice"; |
| 8 | import { ThunkApiType } from "../store"; |
| 9 | import { findToolCall } from "../util"; |
| 10 | import { resetStateForNewMessage } from "./resetStateForNewMessage"; |
| 11 | import { streamNormalInput } from "./streamNormalInput"; |
| 12 | import { streamThunkWrapper } from "./streamThunkWrapper"; |
| 13 | |
| 14 | export const streamResponseAfterToolCall = createAsyncThunk< |
| 15 | void, |
| 16 | { toolCallId: string }, |
| 17 | ThunkApiType |
| 18 | >( |
| 19 | "chat/streamAfterToolCall", |
| 20 | async ({ toolCallId }, { dispatch, getState }) => { |
| 21 | await dispatch( |
| 22 | streamThunkWrapper(async () => { |
| 23 | const state = getState(); |
| 24 | const initialHistory = state.session.history; |
| 25 | const selectedChatModel = selectSelectedChatModel(state); |
| 26 | |
| 27 | if (!selectedChatModel) { |
| 28 | throw new Error("No model selected"); |
| 29 | } |
| 30 | |
| 31 | const toolCallState = findToolCall(state.session.history, toolCallId); |
| 32 | |
| 33 | if (!toolCallState) { |
| 34 | return; // in cases where edit tool is cancelled mid apply, this will be triggered |
| 35 | } |
| 36 | |
| 37 | const toolOutput = toolCallState.output ?? []; |
| 38 | |
| 39 | resetStateForNewMessage(); |
| 40 | |
| 41 | await new Promise((resolve) => setTimeout(resolve, 0)); |
| 42 | |
| 43 | const newMessage: ChatMessage = { |
| 44 | role: "tool", |
| 45 | content: renderContextItems(toolOutput), |
| 46 | toolCallId, |
| 47 | }; |
| 48 | dispatch(streamUpdate([newMessage])); |
| 49 | dispatch( |
| 50 | addContextItemsAtIndex({ |
| 51 | index: initialHistory.length, |
| 52 | contextItems: toolOutput.map((contextItem) => ({ |
| 53 | ...contextItem, |
| 54 | id: { |
| 55 | providerTitle: "toolCall", |
| 56 | itemId: toolCallId, |
| 57 | }, |
| 58 | })), |
| 59 | }), |
| 60 | ); |
| 61 | |
| 62 | const updatedHistory = getState().session.history; |
| 63 | const messageMode = getState().session.mode; |
| 64 | |
| 65 | const baseChatOrAgentSystemMessage = getBaseSystemMessage( |
| 66 | selectedChatModel, |
| 67 | messageMode, |
| 68 | ); |
| 69 | |
| 70 | const messages = constructMessages( |
| 71 | messageMode, |
| 72 | [...updatedHistory], |
| 73 | baseChatOrAgentSystemMessage, |
| 74 | state.config.config.rules, |
| 75 | ); |
| 76 | |
| 77 | unwrapResult(await dispatch(streamNormalInput({ messages }))); |
| 78 | }), |
| 79 | ); |
| 80 | }, |
| 81 | ); |