| 1 | import { createAsyncThunk } from "@reduxjs/toolkit"; |
| 2 | import posthog from "posthog-js"; |
| 3 | import { selectSelectedChatModel } from "../slices/configSlice"; |
| 4 | import { |
| 5 | cancelToolCall as cancelToolCallAction, |
| 6 | updateToolCallOutput, |
| 7 | } from "../slices/sessionSlice"; |
| 8 | import { ThunkApiType } from "../store"; |
| 9 | import { findToolCallById } from "../util"; |
| 10 | import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; |
| 11 | |
| 12 | const DEFAULT_USER_REJECTION_MESSAGE = `The user skipped the tool call. |
| 13 | If the tool call is optional or non-critical to the main goal, skip it and continue with the next step. |
| 14 | If the tool call is essential, try an alternative approach. |
| 15 | If no alternatives exist, offer to pause here.`; |
| 16 | |
| 17 | export const cancelToolCallThunk = createAsyncThunk< |
| 18 | void, |
| 19 | { toolCallId: string }, |
| 20 | ThunkApiType |
| 21 | >("chat/cancelToolCall", async ({ toolCallId }, { dispatch, getState }) => { |
| 22 | const state = getState(); |
| 23 | const selectedChatModel = selectSelectedChatModel(state); |
| 24 | const continueAfterToolRejection = |
| 25 | state.config.config.ui?.continueAfterToolRejection; |
| 26 | const toolCallState = findToolCallById(state.session.history, toolCallId); |
| 27 | |
| 28 | if (toolCallState) { |
| 29 | // Track tool call rejection |
| 30 | posthog.capture("tool_call_decision", { |
| 31 | model: selectedChatModel, |
| 32 | decision: "reject", |
| 33 | toolName: toolCallState.toolCall.function.name, |
| 34 | toolCallId: toolCallId, |
| 35 | }); |
| 36 | } |
| 37 | |
| 38 | if (continueAfterToolRejection) { |
| 39 | // Update tool call output with rejection message |
| 40 | dispatch( |
| 41 | updateToolCallOutput({ |
| 42 | toolCallId, |
| 43 | contextItems: [ |
| 44 | { |
| 45 | icon: "problems", |
| 46 | name: "Tool Call Rejected", |
| 47 | description: "User skipped the tool call", |
| 48 | content: DEFAULT_USER_REJECTION_MESSAGE, |
| 49 | hidden: true, |
| 50 | }, |
| 51 | ], |
| 52 | }), |
| 53 | ); |
| 54 | } |
| 55 | |
| 56 | // Dispatch the actual cancel action |
| 57 | dispatch(cancelToolCallAction({ toolCallId })); |
| 58 | |
| 59 | void dispatch(streamResponseAfterToolCall({ toolCallId })); |
| 60 | }); |