Elffuss BraidHub

kikocis/continue public

451a09bc4725 · 5.0 KiBRawPermalink
1import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
2import { JSONContent } from "@tiptap/core";
3import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core";
4import { constructMessages } from "core/llm/constructMessages";
5import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules";
6import posthog from "posthog-js";
7import { v4 as uuidv4 } from "uuid";
8import { getBaseSystemMessage } from "../../util";
9import { selectSelectedChatModel } from "../slices/configSlice";
10import {
11 setAppliedRulesAtIndex,
12 submitEditorAndInitAtIndex,
13 updateHistoryItemAtIndex,
14} from "../slices/sessionSlice";
15import { ThunkApiType } from "../store";
16import { gatherContext } from "./gatherContext";
17import { resetStateForNewMessage } from "./resetStateForNewMessage";
18import { streamNormalInput } from "./streamNormalInput";
19import { streamThunkWrapper } from "./streamThunkWrapper";
20import { updateFileSymbolsFromFiles } from "./updateFileSymbols";
21
22export const streamResponseThunk = createAsyncThunk<
23 void,
24 {
25 editorState: JSONContent;
26 modifiers: InputModifiers;
27 index?: number;
28 promptPreamble?: string;
29 },
30 ThunkApiType
31>(
32 "chat/streamResponse",
33 async (
34 { editorState, modifiers, index, promptPreamble },
35 { dispatch, extra, getState },
36 ) => {
37 await dispatch(
38 streamThunkWrapper(async () => {
39 const state = getState();
40 const selectedChatModel = selectSelectedChatModel(state);
41 const inputIndex = index ?? state.session.history.length; // Either given index or concat to end
42
43 if (!selectedChatModel) {
44 throw new Error("No chat model selected");
45 }
46
47 dispatch(
48 submitEditorAndInitAtIndex({ index: inputIndex, editorState }),
49 );
50 resetStateForNewMessage();
51
52 const result = await dispatch(
53 gatherContext({
54 editorState,
55 modifiers,
56 promptPreamble,
57 }),
58 );
59 const {
60 selectedContextItems,
61 selectedCode,
62 content,
63 slashCommandWithInput,
64 } = unwrapResult(result);
65
66 // symbols for both context items AND selected codeblocks
67 const filesForSymbols = [
68 ...selectedContextItems
69 .filter((item) => item.uri?.type === "file" && item?.uri?.value)
70 .map((item) => item.uri!.value),
71 ...selectedCode.map((rif) => rif.filepath),
72 ];
73 dispatch(updateFileSymbolsFromFiles(filesForSymbols));
74
75 dispatch(
76 updateHistoryItemAtIndex({
77 index: inputIndex,
78 updates: {
79 message: {
80 role: "user",
81 content,
82 id: uuidv4(),
83 },
84 contextItems: selectedContextItems,
85 },
86 }),
87 );
88
89 // Get updated history after the update
90 const updatedHistory = getState().session.history;
91
92 // Determine which rules apply to this message
93 const userMsg = updatedHistory[inputIndex].message;
94 const rules = getState().config.config.rules;
95 const rulePolicies = getState().ui.ruleSettings;
96
97 // Calculate applicable rules once
98 // We need to check the message type to match what getApplicableRules expects
99 const applicableRules = getApplicableRules(
100 userMsg.role === "user" || userMsg.role === "tool"
101 ? (userMsg as UserChatMessage | ToolResultChatMessage)
102 : undefined,
103 rules,
104 selectedContextItems,
105 rulePolicies,
106 );
107
108 // Store in history for UI display
109 dispatch(
110 setAppliedRulesAtIndex({
111 index: inputIndex,
112 appliedRules: applicableRules,
113 }),
114 );
115
116 const messageMode = getState().session.mode;
117 const baseChatOrAgentSystemMessage = getBaseSystemMessage(
118 selectedChatModel,
119 messageMode,
120 );
121
122 const messages = constructMessages(
123 messageMode,
124 [...updatedHistory],
125 baseChatOrAgentSystemMessage,
126 applicableRules,
127 rulePolicies,
128 );
129
130 posthog.capture("step run", {
131 step_name: "User Input",
132 params: {},
133 });
134 posthog.capture("userInput", {});
135
136 if (slashCommandWithInput) {
137 posthog.capture("step run", {
138 step_name: slashCommandWithInput.command.name,
139 params: {},
140 });
141 }
142
143 unwrapResult(
144 await dispatch(
145 streamNormalInput({
146 messages,
147 legacySlashCommandData: slashCommandWithInput
148 ? {
149 command: slashCommandWithInput.command,
150 contextItems: selectedContextItems,
151 historyIndex: inputIndex,
152 input: slashCommandWithInput.input,
153 selectedCode,
154 }
155 : undefined,
156 }),
157 ),
158 );
159 }),
160 );
161 },
162);