Elffuss BraidHub

kikocis/continue public

dd84f7eaed6c · 5.4 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 { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent";
9import { getBaseSystemMessage } from "../../util";
10import { selectSelectedChatModel } from "../slices/configSlice";
11import {
12 setAppliedRulesAtIndex,
13 submitEditorAndInitAtIndex,
14 updateHistoryItemAtIndex,
15} from "../slices/sessionSlice";
16import { ThunkApiType } from "../store";
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 },
29 ThunkApiType
30>(
31 "chat/streamResponse",
32 async ({ editorState, modifiers, index }, { dispatch, extra, getState }) => {
33 await dispatch(
34 streamThunkWrapper(async () => {
35 const state = getState();
36 const selectedChatModel = selectSelectedChatModel(state);
37 const inputIndex = index ?? state.session.history.length; // Either given index or concat to end
38
39 if (!selectedChatModel) {
40 throw new Error("No chat model selected");
41 }
42
43 dispatch(
44 submitEditorAndInitAtIndex({ index: inputIndex, editorState }),
45 );
46 resetStateForNewMessage();
47
48 const defaultContextProviders =
49 state.config.config.experimental?.defaultContext ?? [];
50
51 if (!selectedChatModel) {
52 console.error(
53 "gatherContext thunk: Cannot gather context, no model selected",
54 );
55 throw new Error("No chat model selected");
56 }
57
58 // Resolve context providers and construct new history
59 const {
60 selectedContextItems,
61 selectedCode,
62 content,
63 legacyCommandWithInput,
64 } = await resolveEditorContent({
65 editorState,
66 modifiers,
67 ideMessenger: extra.ideMessenger,
68 defaultContextProviders,
69 availableSlashCommands: state.config.config.slashCommands,
70 dispatch,
71 getState,
72 });
73
74 // symbols for both context items AND selected codeblocks
75 const filesForSymbols = [
76 ...selectedContextItems
77 .filter((item) => item.uri?.type === "file" && item?.uri?.value)
78 .map((item) => item.uri!.value),
79 ...selectedCode.map((rif) => rif.filepath),
80 ];
81 void dispatch(updateFileSymbolsFromFiles(filesForSymbols));
82
83 dispatch(
84 updateHistoryItemAtIndex({
85 index: inputIndex,
86 updates: {
87 message: {
88 role: "user",
89 content,
90 id: uuidv4(),
91 },
92 contextItems: selectedContextItems,
93 },
94 }),
95 );
96
97 // Get updated history after the update
98 const updatedHistory = getState().session.history;
99
100 // Determine which rules apply to this message
101 const userMsg = updatedHistory[inputIndex].message;
102 const rules = getState().config.config.rules;
103 const rulePolicies = getState().ui.ruleSettings;
104
105 // Calculate applicable rules once
106 // We need to check the message type to match what getApplicableRules expects
107 const applicableRules = getApplicableRules(
108 userMsg.role === "user" || userMsg.role === "tool"
109 ? (userMsg as UserChatMessage | ToolResultChatMessage)
110 : undefined,
111 rules,
112 selectedContextItems,
113 rulePolicies,
114 );
115
116 // Store in history for UI display
117 dispatch(
118 setAppliedRulesAtIndex({
119 index: inputIndex,
120 appliedRules: applicableRules,
121 }),
122 );
123
124 const messageMode = getState().session.mode;
125 const baseChatOrAgentSystemMessage = getBaseSystemMessage(
126 selectedChatModel,
127 messageMode,
128 );
129
130 const messages = constructMessages(
131 messageMode,
132 [...updatedHistory],
133 baseChatOrAgentSystemMessage,
134 applicableRules,
135 rulePolicies,
136 );
137
138 posthog.capture("step run", {
139 step_name: "User Input",
140 params: {},
141 });
142 posthog.capture("userInput", {});
143
144 if (legacyCommandWithInput) {
145 posthog.capture("step run", {
146 step_name: legacyCommandWithInput.command.name,
147 params: {},
148 });
149 }
150
151 unwrapResult(
152 await dispatch(
153 streamNormalInput({
154 messages,
155 legacySlashCommandData: legacyCommandWithInput
156 ? {
157 command: legacyCommandWithInput.command,
158 contextItems: selectedContextItems,
159 historyIndex: inputIndex,
160 input: legacyCommandWithInput.input,
161 selectedCode,
162 }
163 : undefined,
164 }),
165 ),
166 );
167 }),
168 );
169 },
170);