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