Elffuss BraidHub

kikocis/continue public

b4db4cbf8943 · 2.5 KiBRawPermalink
1import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
2import { ChatMessage } from "core";
3import { renderContextItems } from "core/util/messageContent";
4import {
5 ChatHistoryItemWithMessageId,
6 resetNextCodeBlockToApplyIndex,
7 streamUpdate,
8} from "../slices/sessionSlice";
9import { ThunkApiType } from "../store";
10import { findToolCallById } from "../util";
11import { streamNormalInput } from "./streamNormalInput";
12import { streamThunkWrapper } from "./streamThunkWrapper";
13
14/**
15 * Determines if we should continue streaming based on tool call completion status.
16 */
17function areAllToolsDoneStreaming(
18 assistantMessage: ChatHistoryItemWithMessageId | undefined,
19): boolean {
20 // This might occur because of race conditions, if so, the tools are completed
21 if (!assistantMessage?.toolCallStates) {
22 return true;
23 }
24
25 // Only continue if all tool calls are complete
26 const completedToolCalls = assistantMessage.toolCallStates.filter(
27 (tc) => tc.status === "done" || tc.status === "errored",
28 );
29
30 return completedToolCalls.length === assistantMessage.toolCallStates.length;
31}
32
33export const streamResponseAfterToolCall = createAsyncThunk<
34 void,
35 { toolCallId: string },
36 ThunkApiType
37>(
38 "chat/streamAfterToolCall",
39 async ({ toolCallId }, { dispatch, getState }) => {
40 await dispatch(
41 streamThunkWrapper(async () => {
42 const state = getState();
43
44 const toolCallState = findToolCallById(
45 state.session.history,
46 toolCallId,
47 );
48
49 if (!toolCallState) {
50 return; // in cases where edit tool is cancelled mid apply, this will be triggered
51 }
52
53 const toolOutput = toolCallState.output ?? [];
54
55 dispatch(resetNextCodeBlockToApplyIndex());
56 // await new Promise((resolve) => setTimeout(resolve, 0));
57
58 // Create and dispatch the tool message
59 const newMessage: ChatMessage = {
60 role: "tool",
61 content: renderContextItems(toolOutput),
62 toolCallId,
63 };
64 dispatch(streamUpdate([newMessage]));
65
66 // Check if we should continue streaming based on tool call completion
67 const history = getState().session.history;
68 const assistantMessage = history.find(
69 (item) =>
70 item.message.role === "assistant" &&
71 item.toolCallStates?.some((tc) => tc.toolCallId === toolCallId),
72 );
73
74 if (areAllToolsDoneStreaming(assistantMessage)) {
75 unwrapResult(await dispatch(streamNormalInput({})));
76 }
77 }),
78 );
79 },
80);