| 1 | import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; |
| 2 | import { ChatMessage } from "core"; |
| 3 | import { renderContextItems } from "core/util/messageContent"; |
| 4 | import { streamUpdate } from "../slices/sessionSlice"; |
| 5 | import { ThunkApiType } from "../store"; |
| 6 | import { findToolCall } from "../util"; |
| 7 | import { resetStateForNewMessage } from "./resetStateForNewMessage"; |
| 8 | import { streamNormalInput } from "./streamNormalInput"; |
| 9 | import { streamThunkWrapper } from "./streamThunkWrapper"; |
| 10 | |
| 11 | export const streamResponseAfterToolCall = createAsyncThunk< |
| 12 | void, |
| 13 | { toolCallId: string }, |
| 14 | ThunkApiType |
| 15 | >( |
| 16 | "chat/streamAfterToolCall", |
| 17 | async ({ toolCallId }, { dispatch, getState }) => { |
| 18 | await dispatch( |
| 19 | streamThunkWrapper(async () => { |
| 20 | const state = getState(); |
| 21 | |
| 22 | const toolCallState = findToolCall(state.session.history, toolCallId); |
| 23 | if (!toolCallState) { |
| 24 | return; // in cases where edit tool is cancelled mid apply, this will be triggered |
| 25 | } |
| 26 | |
| 27 | const toolOutput = toolCallState.output ?? []; |
| 28 | |
| 29 | resetStateForNewMessage(); |
| 30 | |
| 31 | await new Promise((resolve) => setTimeout(resolve, 0)); |
| 32 | |
| 33 | // TODO parallel tool calls - dispatch one tool message per tool call |
| 34 | const newMessage: ChatMessage = { |
| 35 | role: "tool", |
| 36 | content: renderContextItems(toolOutput), |
| 37 | toolCallId, |
| 38 | }; |
| 39 | dispatch(streamUpdate([newMessage])); |
| 40 | |
| 41 | unwrapResult(await dispatch(streamNormalInput({}))); |
| 42 | }), |
| 43 | ); |
| 44 | }, |
| 45 | ); |